compiler.umd.js 1.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764
  1. /**
  2. * @license Angular v12.0.5
  3. * (c) 2010-2021 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  8. typeof define === 'function' && define.amd ? define('@angular/compiler', ['exports'], factory) :
  9. (global = global || self, factory((global.ng = global.ng || {}, global.ng.compiler = {})));
  10. }(this, (function (exports) { 'use strict';
  11. /*! *****************************************************************************
  12. Copyright (c) Microsoft Corporation.
  13. Permission to use, copy, modify, and/or distribute this software for any
  14. purpose with or without fee is hereby granted.
  15. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  16. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  17. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  18. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  19. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  20. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  21. PERFORMANCE OF THIS SOFTWARE.
  22. ***************************************************************************** */
  23. /* global Reflect, Promise */
  24. var extendStatics = function (d, b) {
  25. extendStatics = Object.setPrototypeOf ||
  26. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  27. function (d, b) { for (var p in b)
  28. if (Object.prototype.hasOwnProperty.call(b, p))
  29. d[p] = b[p]; };
  30. return extendStatics(d, b);
  31. };
  32. function __extends(d, b) {
  33. if (typeof b !== "function" && b !== null)
  34. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  35. extendStatics(d, b);
  36. function __() { this.constructor = d; }
  37. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  38. }
  39. var __assign = function () {
  40. __assign = Object.assign || function __assign(t) {
  41. for (var s, i = 1, n = arguments.length; i < n; i++) {
  42. s = arguments[i];
  43. for (var p in s)
  44. if (Object.prototype.hasOwnProperty.call(s, p))
  45. t[p] = s[p];
  46. }
  47. return t;
  48. };
  49. return __assign.apply(this, arguments);
  50. };
  51. function __rest(s, e) {
  52. var t = {};
  53. for (var p in s)
  54. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  55. t[p] = s[p];
  56. if (s != null && typeof Object.getOwnPropertySymbols === "function")
  57. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  58. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  59. t[p[i]] = s[p[i]];
  60. }
  61. return t;
  62. }
  63. function __decorate(decorators, target, key, desc) {
  64. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  65. if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
  66. r = Reflect.decorate(decorators, target, key, desc);
  67. else
  68. for (var i = decorators.length - 1; i >= 0; i--)
  69. if (d = decorators[i])
  70. r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  71. return c > 3 && r && Object.defineProperty(target, key, r), r;
  72. }
  73. function __param(paramIndex, decorator) {
  74. return function (target, key) { decorator(target, key, paramIndex); };
  75. }
  76. function __metadata(metadataKey, metadataValue) {
  77. if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
  78. return Reflect.metadata(metadataKey, metadataValue);
  79. }
  80. function __awaiter(thisArg, _arguments, P, generator) {
  81. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  82. return new (P || (P = Promise))(function (resolve, reject) {
  83. function fulfilled(value) { try {
  84. step(generator.next(value));
  85. }
  86. catch (e) {
  87. reject(e);
  88. } }
  89. function rejected(value) { try {
  90. step(generator["throw"](value));
  91. }
  92. catch (e) {
  93. reject(e);
  94. } }
  95. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  96. step((generator = generator.apply(thisArg, _arguments || [])).next());
  97. });
  98. }
  99. function __generator(thisArg, body) {
  100. var _ = { label: 0, sent: function () { if (t[0] & 1)
  101. throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  102. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
  103. function verb(n) { return function (v) { return step([n, v]); }; }
  104. function step(op) {
  105. if (f)
  106. throw new TypeError("Generator is already executing.");
  107. while (_)
  108. try {
  109. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
  110. return t;
  111. if (y = 0, t)
  112. op = [op[0] & 2, t.value];
  113. switch (op[0]) {
  114. case 0:
  115. case 1:
  116. t = op;
  117. break;
  118. case 4:
  119. _.label++;
  120. return { value: op[1], done: false };
  121. case 5:
  122. _.label++;
  123. y = op[1];
  124. op = [0];
  125. continue;
  126. case 7:
  127. op = _.ops.pop();
  128. _.trys.pop();
  129. continue;
  130. default:
  131. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
  132. _ = 0;
  133. continue;
  134. }
  135. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
  136. _.label = op[1];
  137. break;
  138. }
  139. if (op[0] === 6 && _.label < t[1]) {
  140. _.label = t[1];
  141. t = op;
  142. break;
  143. }
  144. if (t && _.label < t[2]) {
  145. _.label = t[2];
  146. _.ops.push(op);
  147. break;
  148. }
  149. if (t[2])
  150. _.ops.pop();
  151. _.trys.pop();
  152. continue;
  153. }
  154. op = body.call(thisArg, _);
  155. }
  156. catch (e) {
  157. op = [6, e];
  158. y = 0;
  159. }
  160. finally {
  161. f = t = 0;
  162. }
  163. if (op[0] & 5)
  164. throw op[1];
  165. return { value: op[0] ? op[1] : void 0, done: true };
  166. }
  167. }
  168. var __createBinding = Object.create ? (function (o, m, k, k2) {
  169. if (k2 === undefined)
  170. k2 = k;
  171. Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
  172. }) : (function (o, m, k, k2) {
  173. if (k2 === undefined)
  174. k2 = k;
  175. o[k2] = m[k];
  176. });
  177. function __exportStar(m, o) {
  178. for (var p in m)
  179. if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
  180. __createBinding(o, m, p);
  181. }
  182. function __values(o) {
  183. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  184. if (m)
  185. return m.call(o);
  186. if (o && typeof o.length === "number")
  187. return {
  188. next: function () {
  189. if (o && i >= o.length)
  190. o = void 0;
  191. return { value: o && o[i++], done: !o };
  192. }
  193. };
  194. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  195. }
  196. function __read(o, n) {
  197. var m = typeof Symbol === "function" && o[Symbol.iterator];
  198. if (!m)
  199. return o;
  200. var i = m.call(o), r, ar = [], e;
  201. try {
  202. while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
  203. ar.push(r.value);
  204. }
  205. catch (error) {
  206. e = { error: error };
  207. }
  208. finally {
  209. try {
  210. if (r && !r.done && (m = i["return"]))
  211. m.call(i);
  212. }
  213. finally {
  214. if (e)
  215. throw e.error;
  216. }
  217. }
  218. return ar;
  219. }
  220. /** @deprecated */
  221. function __spread() {
  222. for (var ar = [], i = 0; i < arguments.length; i++)
  223. ar = ar.concat(__read(arguments[i]));
  224. return ar;
  225. }
  226. /** @deprecated */
  227. function __spreadArrays() {
  228. for (var s = 0, i = 0, il = arguments.length; i < il; i++)
  229. s += arguments[i].length;
  230. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  231. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  232. r[k] = a[j];
  233. return r;
  234. }
  235. function __spreadArray(to, from) {
  236. for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
  237. to[j] = from[i];
  238. return to;
  239. }
  240. function __await(v) {
  241. return this instanceof __await ? (this.v = v, this) : new __await(v);
  242. }
  243. function __asyncGenerator(thisArg, _arguments, generator) {
  244. if (!Symbol.asyncIterator)
  245. throw new TypeError("Symbol.asyncIterator is not defined.");
  246. var g = generator.apply(thisArg, _arguments || []), i, q = [];
  247. return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
  248. function verb(n) { if (g[n])
  249. i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
  250. function resume(n, v) { try {
  251. step(g[n](v));
  252. }
  253. catch (e) {
  254. settle(q[0][3], e);
  255. } }
  256. function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
  257. function fulfill(value) { resume("next", value); }
  258. function reject(value) { resume("throw", value); }
  259. function settle(f, v) { if (f(v), q.shift(), q.length)
  260. resume(q[0][0], q[0][1]); }
  261. }
  262. function __asyncDelegator(o) {
  263. var i, p;
  264. return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
  265. function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
  266. }
  267. function __asyncValues(o) {
  268. if (!Symbol.asyncIterator)
  269. throw new TypeError("Symbol.asyncIterator is not defined.");
  270. var m = o[Symbol.asyncIterator], i;
  271. return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
  272. function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
  273. function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
  274. }
  275. function __makeTemplateObject(cooked, raw) {
  276. if (Object.defineProperty) {
  277. Object.defineProperty(cooked, "raw", { value: raw });
  278. }
  279. else {
  280. cooked.raw = raw;
  281. }
  282. return cooked;
  283. }
  284. ;
  285. var __setModuleDefault = Object.create ? (function (o, v) {
  286. Object.defineProperty(o, "default", { enumerable: true, value: v });
  287. }) : function (o, v) {
  288. o["default"] = v;
  289. };
  290. function __importStar(mod) {
  291. if (mod && mod.__esModule)
  292. return mod;
  293. var result = {};
  294. if (mod != null)
  295. for (var k in mod)
  296. if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
  297. __createBinding(result, mod, k);
  298. __setModuleDefault(result, mod);
  299. return result;
  300. }
  301. function __importDefault(mod) {
  302. return (mod && mod.__esModule) ? mod : { default: mod };
  303. }
  304. function __classPrivateFieldGet(receiver, state, kind, f) {
  305. if (kind === "a" && !f)
  306. throw new TypeError("Private accessor was defined without a getter");
  307. if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
  308. throw new TypeError("Cannot read private member from an object whose class did not declare it");
  309. return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
  310. }
  311. function __classPrivateFieldSet(receiver, state, value, kind, f) {
  312. if (kind === "m")
  313. throw new TypeError("Private method is not writable");
  314. if (kind === "a" && !f)
  315. throw new TypeError("Private accessor was defined without a setter");
  316. if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
  317. throw new TypeError("Cannot write private member to an object whose class did not declare it");
  318. return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
  319. }
  320. /**
  321. * @license
  322. * Copyright Google LLC All Rights Reserved.
  323. *
  324. * Use of this source code is governed by an MIT-style license that can be
  325. * found in the LICENSE file at https://angular.io/license
  326. */
  327. (function (TagContentType) {
  328. TagContentType[TagContentType["RAW_TEXT"] = 0] = "RAW_TEXT";
  329. TagContentType[TagContentType["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT";
  330. TagContentType[TagContentType["PARSABLE_DATA"] = 2] = "PARSABLE_DATA";
  331. })(exports.TagContentType || (exports.TagContentType = {}));
  332. function splitNsName(elementName) {
  333. if (elementName[0] != ':') {
  334. return [null, elementName];
  335. }
  336. var colonIndex = elementName.indexOf(':', 1);
  337. if (colonIndex == -1) {
  338. throw new Error("Unsupported format \"" + elementName + "\" expecting \":namespace:name\"");
  339. }
  340. return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)];
  341. }
  342. // `<ng-container>` tags work the same regardless the namespace
  343. function isNgContainer(tagName) {
  344. return splitNsName(tagName)[1] === 'ng-container';
  345. }
  346. // `<ng-content>` tags work the same regardless the namespace
  347. function isNgContent(tagName) {
  348. return splitNsName(tagName)[1] === 'ng-content';
  349. }
  350. // `<ng-template>` tags work the same regardless the namespace
  351. function isNgTemplate(tagName) {
  352. return splitNsName(tagName)[1] === 'ng-template';
  353. }
  354. function getNsPrefix(fullName) {
  355. return fullName === null ? null : splitNsName(fullName)[0];
  356. }
  357. function mergeNsAndName(prefix, localName) {
  358. return prefix ? ":" + prefix + ":" + localName : localName;
  359. }
  360. // see https://www.w3.org/TR/html51/syntax.html#named-character-references
  361. // see https://html.spec.whatwg.org/multipage/entities.json
  362. // This list is not exhaustive to keep the compiler footprint low.
  363. // The `&#123;` / `&#x1ab;` syntax should be used when the named character reference does not
  364. // exist.
  365. var NAMED_ENTITIES = {
  366. 'Aacute': '\u00C1',
  367. 'aacute': '\u00E1',
  368. 'Acirc': '\u00C2',
  369. 'acirc': '\u00E2',
  370. 'acute': '\u00B4',
  371. 'AElig': '\u00C6',
  372. 'aelig': '\u00E6',
  373. 'Agrave': '\u00C0',
  374. 'agrave': '\u00E0',
  375. 'alefsym': '\u2135',
  376. 'Alpha': '\u0391',
  377. 'alpha': '\u03B1',
  378. 'amp': '&',
  379. 'and': '\u2227',
  380. 'ang': '\u2220',
  381. 'apos': '\u0027',
  382. 'Aring': '\u00C5',
  383. 'aring': '\u00E5',
  384. 'asymp': '\u2248',
  385. 'Atilde': '\u00C3',
  386. 'atilde': '\u00E3',
  387. 'Auml': '\u00C4',
  388. 'auml': '\u00E4',
  389. 'bdquo': '\u201E',
  390. 'Beta': '\u0392',
  391. 'beta': '\u03B2',
  392. 'brvbar': '\u00A6',
  393. 'bull': '\u2022',
  394. 'cap': '\u2229',
  395. 'Ccedil': '\u00C7',
  396. 'ccedil': '\u00E7',
  397. 'cedil': '\u00B8',
  398. 'cent': '\u00A2',
  399. 'Chi': '\u03A7',
  400. 'chi': '\u03C7',
  401. 'circ': '\u02C6',
  402. 'clubs': '\u2663',
  403. 'cong': '\u2245',
  404. 'copy': '\u00A9',
  405. 'crarr': '\u21B5',
  406. 'cup': '\u222A',
  407. 'curren': '\u00A4',
  408. 'dagger': '\u2020',
  409. 'Dagger': '\u2021',
  410. 'darr': '\u2193',
  411. 'dArr': '\u21D3',
  412. 'deg': '\u00B0',
  413. 'Delta': '\u0394',
  414. 'delta': '\u03B4',
  415. 'diams': '\u2666',
  416. 'divide': '\u00F7',
  417. 'Eacute': '\u00C9',
  418. 'eacute': '\u00E9',
  419. 'Ecirc': '\u00CA',
  420. 'ecirc': '\u00EA',
  421. 'Egrave': '\u00C8',
  422. 'egrave': '\u00E8',
  423. 'empty': '\u2205',
  424. 'emsp': '\u2003',
  425. 'ensp': '\u2002',
  426. 'Epsilon': '\u0395',
  427. 'epsilon': '\u03B5',
  428. 'equiv': '\u2261',
  429. 'Eta': '\u0397',
  430. 'eta': '\u03B7',
  431. 'ETH': '\u00D0',
  432. 'eth': '\u00F0',
  433. 'Euml': '\u00CB',
  434. 'euml': '\u00EB',
  435. 'euro': '\u20AC',
  436. 'exist': '\u2203',
  437. 'fnof': '\u0192',
  438. 'forall': '\u2200',
  439. 'frac12': '\u00BD',
  440. 'frac14': '\u00BC',
  441. 'frac34': '\u00BE',
  442. 'frasl': '\u2044',
  443. 'Gamma': '\u0393',
  444. 'gamma': '\u03B3',
  445. 'ge': '\u2265',
  446. 'gt': '>',
  447. 'harr': '\u2194',
  448. 'hArr': '\u21D4',
  449. 'hearts': '\u2665',
  450. 'hellip': '\u2026',
  451. 'Iacute': '\u00CD',
  452. 'iacute': '\u00ED',
  453. 'Icirc': '\u00CE',
  454. 'icirc': '\u00EE',
  455. 'iexcl': '\u00A1',
  456. 'Igrave': '\u00CC',
  457. 'igrave': '\u00EC',
  458. 'image': '\u2111',
  459. 'infin': '\u221E',
  460. 'int': '\u222B',
  461. 'Iota': '\u0399',
  462. 'iota': '\u03B9',
  463. 'iquest': '\u00BF',
  464. 'isin': '\u2208',
  465. 'Iuml': '\u00CF',
  466. 'iuml': '\u00EF',
  467. 'Kappa': '\u039A',
  468. 'kappa': '\u03BA',
  469. 'Lambda': '\u039B',
  470. 'lambda': '\u03BB',
  471. 'lang': '\u27E8',
  472. 'laquo': '\u00AB',
  473. 'larr': '\u2190',
  474. 'lArr': '\u21D0',
  475. 'lceil': '\u2308',
  476. 'ldquo': '\u201C',
  477. 'le': '\u2264',
  478. 'lfloor': '\u230A',
  479. 'lowast': '\u2217',
  480. 'loz': '\u25CA',
  481. 'lrm': '\u200E',
  482. 'lsaquo': '\u2039',
  483. 'lsquo': '\u2018',
  484. 'lt': '<',
  485. 'macr': '\u00AF',
  486. 'mdash': '\u2014',
  487. 'micro': '\u00B5',
  488. 'middot': '\u00B7',
  489. 'minus': '\u2212',
  490. 'Mu': '\u039C',
  491. 'mu': '\u03BC',
  492. 'nabla': '\u2207',
  493. 'nbsp': '\u00A0',
  494. 'ndash': '\u2013',
  495. 'ne': '\u2260',
  496. 'ni': '\u220B',
  497. 'not': '\u00AC',
  498. 'notin': '\u2209',
  499. 'nsub': '\u2284',
  500. 'Ntilde': '\u00D1',
  501. 'ntilde': '\u00F1',
  502. 'Nu': '\u039D',
  503. 'nu': '\u03BD',
  504. 'Oacute': '\u00D3',
  505. 'oacute': '\u00F3',
  506. 'Ocirc': '\u00D4',
  507. 'ocirc': '\u00F4',
  508. 'OElig': '\u0152',
  509. 'oelig': '\u0153',
  510. 'Ograve': '\u00D2',
  511. 'ograve': '\u00F2',
  512. 'oline': '\u203E',
  513. 'Omega': '\u03A9',
  514. 'omega': '\u03C9',
  515. 'Omicron': '\u039F',
  516. 'omicron': '\u03BF',
  517. 'oplus': '\u2295',
  518. 'or': '\u2228',
  519. 'ordf': '\u00AA',
  520. 'ordm': '\u00BA',
  521. 'Oslash': '\u00D8',
  522. 'oslash': '\u00F8',
  523. 'Otilde': '\u00D5',
  524. 'otilde': '\u00F5',
  525. 'otimes': '\u2297',
  526. 'Ouml': '\u00D6',
  527. 'ouml': '\u00F6',
  528. 'para': '\u00B6',
  529. 'permil': '\u2030',
  530. 'perp': '\u22A5',
  531. 'Phi': '\u03A6',
  532. 'phi': '\u03C6',
  533. 'Pi': '\u03A0',
  534. 'pi': '\u03C0',
  535. 'piv': '\u03D6',
  536. 'plusmn': '\u00B1',
  537. 'pound': '\u00A3',
  538. 'prime': '\u2032',
  539. 'Prime': '\u2033',
  540. 'prod': '\u220F',
  541. 'prop': '\u221D',
  542. 'Psi': '\u03A8',
  543. 'psi': '\u03C8',
  544. 'quot': '\u0022',
  545. 'radic': '\u221A',
  546. 'rang': '\u27E9',
  547. 'raquo': '\u00BB',
  548. 'rarr': '\u2192',
  549. 'rArr': '\u21D2',
  550. 'rceil': '\u2309',
  551. 'rdquo': '\u201D',
  552. 'real': '\u211C',
  553. 'reg': '\u00AE',
  554. 'rfloor': '\u230B',
  555. 'Rho': '\u03A1',
  556. 'rho': '\u03C1',
  557. 'rlm': '\u200F',
  558. 'rsaquo': '\u203A',
  559. 'rsquo': '\u2019',
  560. 'sbquo': '\u201A',
  561. 'Scaron': '\u0160',
  562. 'scaron': '\u0161',
  563. 'sdot': '\u22C5',
  564. 'sect': '\u00A7',
  565. 'shy': '\u00AD',
  566. 'Sigma': '\u03A3',
  567. 'sigma': '\u03C3',
  568. 'sigmaf': '\u03C2',
  569. 'sim': '\u223C',
  570. 'spades': '\u2660',
  571. 'sub': '\u2282',
  572. 'sube': '\u2286',
  573. 'sum': '\u2211',
  574. 'sup': '\u2283',
  575. 'sup1': '\u00B9',
  576. 'sup2': '\u00B2',
  577. 'sup3': '\u00B3',
  578. 'supe': '\u2287',
  579. 'szlig': '\u00DF',
  580. 'Tau': '\u03A4',
  581. 'tau': '\u03C4',
  582. 'there4': '\u2234',
  583. 'Theta': '\u0398',
  584. 'theta': '\u03B8',
  585. 'thetasym': '\u03D1',
  586. 'thinsp': '\u2009',
  587. 'THORN': '\u00DE',
  588. 'thorn': '\u00FE',
  589. 'tilde': '\u02DC',
  590. 'times': '\u00D7',
  591. 'trade': '\u2122',
  592. 'Uacute': '\u00DA',
  593. 'uacute': '\u00FA',
  594. 'uarr': '\u2191',
  595. 'uArr': '\u21D1',
  596. 'Ucirc': '\u00DB',
  597. 'ucirc': '\u00FB',
  598. 'Ugrave': '\u00D9',
  599. 'ugrave': '\u00F9',
  600. 'uml': '\u00A8',
  601. 'upsih': '\u03D2',
  602. 'Upsilon': '\u03A5',
  603. 'upsilon': '\u03C5',
  604. 'Uuml': '\u00DC',
  605. 'uuml': '\u00FC',
  606. 'weierp': '\u2118',
  607. 'Xi': '\u039E',
  608. 'xi': '\u03BE',
  609. 'Yacute': '\u00DD',
  610. 'yacute': '\u00FD',
  611. 'yen': '\u00A5',
  612. 'yuml': '\u00FF',
  613. 'Yuml': '\u0178',
  614. 'Zeta': '\u0396',
  615. 'zeta': '\u03B6',
  616. 'zwj': '\u200D',
  617. 'zwnj': '\u200C',
  618. };
  619. // The &ngsp; pseudo-entity is denoting a space. see:
  620. // https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart
  621. var NGSP_UNICODE = '\uE500';
  622. NAMED_ENTITIES['ngsp'] = NGSP_UNICODE;
  623. /**
  624. * @license
  625. * Copyright Google LLC All Rights Reserved.
  626. *
  627. * Use of this source code is governed by an MIT-style license that can be
  628. * found in the LICENSE file at https://angular.io/license
  629. */
  630. var HtmlTagDefinition = /** @class */ (function () {
  631. function HtmlTagDefinition(_c) {
  632. var _this = this;
  633. var _d = _c === void 0 ? {} : _c, closedByChildren = _d.closedByChildren, implicitNamespacePrefix = _d.implicitNamespacePrefix, _e = _d.contentType, contentType = _e === void 0 ? exports.TagContentType.PARSABLE_DATA : _e, _f = _d.closedByParent, closedByParent = _f === void 0 ? false : _f, _g = _d.isVoid, isVoid = _g === void 0 ? false : _g, _h = _d.ignoreFirstLf, ignoreFirstLf = _h === void 0 ? false : _h, _j = _d.preventNamespaceInheritance, preventNamespaceInheritance = _j === void 0 ? false : _j;
  634. this.closedByChildren = {};
  635. this.closedByParent = false;
  636. this.canSelfClose = false;
  637. if (closedByChildren && closedByChildren.length > 0) {
  638. closedByChildren.forEach(function (tagName) { return _this.closedByChildren[tagName] = true; });
  639. }
  640. this.isVoid = isVoid;
  641. this.closedByParent = closedByParent || isVoid;
  642. this.implicitNamespacePrefix = implicitNamespacePrefix || null;
  643. this.contentType = contentType;
  644. this.ignoreFirstLf = ignoreFirstLf;
  645. this.preventNamespaceInheritance = preventNamespaceInheritance;
  646. }
  647. HtmlTagDefinition.prototype.isClosedByChild = function (name) {
  648. return this.isVoid || name.toLowerCase() in this.closedByChildren;
  649. };
  650. HtmlTagDefinition.prototype.getContentType = function (prefix) {
  651. if (typeof this.contentType === 'object') {
  652. var overrideType = prefix == null ? undefined : this.contentType[prefix];
  653. return overrideType !== null && overrideType !== void 0 ? overrideType : this.contentType.default;
  654. }
  655. return this.contentType;
  656. };
  657. return HtmlTagDefinition;
  658. }());
  659. var _DEFAULT_TAG_DEFINITION;
  660. // see https://www.w3.org/TR/html51/syntax.html#optional-tags
  661. // This implementation does not fully conform to the HTML5 spec.
  662. var TAG_DEFINITIONS;
  663. function getHtmlTagDefinition(tagName) {
  664. var _a, _b;
  665. if (!TAG_DEFINITIONS) {
  666. _DEFAULT_TAG_DEFINITION = new HtmlTagDefinition();
  667. TAG_DEFINITIONS = {
  668. 'base': new HtmlTagDefinition({ isVoid: true }),
  669. 'meta': new HtmlTagDefinition({ isVoid: true }),
  670. 'area': new HtmlTagDefinition({ isVoid: true }),
  671. 'embed': new HtmlTagDefinition({ isVoid: true }),
  672. 'link': new HtmlTagDefinition({ isVoid: true }),
  673. 'img': new HtmlTagDefinition({ isVoid: true }),
  674. 'input': new HtmlTagDefinition({ isVoid: true }),
  675. 'param': new HtmlTagDefinition({ isVoid: true }),
  676. 'hr': new HtmlTagDefinition({ isVoid: true }),
  677. 'br': new HtmlTagDefinition({ isVoid: true }),
  678. 'source': new HtmlTagDefinition({ isVoid: true }),
  679. 'track': new HtmlTagDefinition({ isVoid: true }),
  680. 'wbr': new HtmlTagDefinition({ isVoid: true }),
  681. 'p': new HtmlTagDefinition({
  682. closedByChildren: [
  683. 'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset',
  684. 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5',
  685. 'h6', 'header', 'hgroup', 'hr', 'main', 'nav', 'ol',
  686. 'p', 'pre', 'section', 'table', 'ul'
  687. ],
  688. closedByParent: true
  689. }),
  690. 'thead': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'] }),
  691. 'tbody': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'], closedByParent: true }),
  692. 'tfoot': new HtmlTagDefinition({ closedByChildren: ['tbody'], closedByParent: true }),
  693. 'tr': new HtmlTagDefinition({ closedByChildren: ['tr'], closedByParent: true }),
  694. 'td': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
  695. 'th': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
  696. 'col': new HtmlTagDefinition({ isVoid: true }),
  697. 'svg': new HtmlTagDefinition({ implicitNamespacePrefix: 'svg' }),
  698. 'foreignObject': new HtmlTagDefinition({
  699. // Usually the implicit namespace here would be redundant since it will be inherited from
  700. // the parent `svg`, but we have to do it for `foreignObject`, because the way the parser
  701. // works is that the parent node of an end tag is its own start tag which means that
  702. // the `preventNamespaceInheritance` on `foreignObject` would have it default to the
  703. // implicit namespace which is `html`, unless specified otherwise.
  704. implicitNamespacePrefix: 'svg',
  705. // We want to prevent children of foreignObject from inheriting its namespace, because
  706. // the point of the element is to allow nodes from other namespaces to be inserted.
  707. preventNamespaceInheritance: true,
  708. }),
  709. 'math': new HtmlTagDefinition({ implicitNamespacePrefix: 'math' }),
  710. 'li': new HtmlTagDefinition({ closedByChildren: ['li'], closedByParent: true }),
  711. 'dt': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'] }),
  712. 'dd': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'], closedByParent: true }),
  713. 'rb': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  714. 'rt': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  715. 'rtc': new HtmlTagDefinition({ closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true }),
  716. 'rp': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
  717. 'optgroup': new HtmlTagDefinition({ closedByChildren: ['optgroup'], closedByParent: true }),
  718. 'option': new HtmlTagDefinition({ closedByChildren: ['option', 'optgroup'], closedByParent: true }),
  719. 'pre': new HtmlTagDefinition({ ignoreFirstLf: true }),
  720. 'listing': new HtmlTagDefinition({ ignoreFirstLf: true }),
  721. 'style': new HtmlTagDefinition({ contentType: exports.TagContentType.RAW_TEXT }),
  722. 'script': new HtmlTagDefinition({ contentType: exports.TagContentType.RAW_TEXT }),
  723. 'title': new HtmlTagDefinition({
  724. // The browser supports two separate `title` tags which have to use
  725. // a different content type: `HTMLTitleElement` and `SVGTitleElement`
  726. contentType: { default: exports.TagContentType.ESCAPABLE_RAW_TEXT, svg: exports.TagContentType.PARSABLE_DATA }
  727. }),
  728. 'textarea': new HtmlTagDefinition({ contentType: exports.TagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true }),
  729. };
  730. }
  731. // We have to make both a case-sensitive and a case-insesitive lookup, because
  732. // HTML tag names are case insensitive, whereas some SVG tags are case sensitive.
  733. return (_b = (_a = TAG_DEFINITIONS[tagName]) !== null && _a !== void 0 ? _a : TAG_DEFINITIONS[tagName.toLowerCase()]) !== null && _b !== void 0 ? _b : _DEFAULT_TAG_DEFINITION;
  734. }
  735. /**
  736. * @license
  737. * Copyright Google LLC All Rights Reserved.
  738. *
  739. * Use of this source code is governed by an MIT-style license that can be
  740. * found in the LICENSE file at https://angular.io/license
  741. */
  742. var _SELECTOR_REGEXP = new RegExp('(\\:not\\()|' + // 1: ":not("
  743. '(([\\.\\#]?)[-\\w]+)|' + // 2: "tag"; 3: "."/"#";
  744. // "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range
  745. // 4: attribute; 5: attribute_string; 6: attribute_value
  746. '(?:\\[([-.\\w*]+)(?:=([\"\']?)([^\\]\"\']*)\\5)?\\])|' + // "[name]", "[name=value]",
  747. // "[name="value"]",
  748. // "[name='value']"
  749. '(\\))|' + // 7: ")"
  750. '(\\s*,\\s*)', // 8: ","
  751. 'g');
  752. /**
  753. * A css selector contains an element name,
  754. * css classes and attribute/value pairs with the purpose
  755. * of selecting subsets out of them.
  756. */
  757. var CssSelector = /** @class */ (function () {
  758. function CssSelector() {
  759. this.element = null;
  760. this.classNames = [];
  761. /**
  762. * The selectors are encoded in pairs where:
  763. * - even locations are attribute names
  764. * - odd locations are attribute values.
  765. *
  766. * Example:
  767. * Selector: `[key1=value1][key2]` would parse to:
  768. * ```
  769. * ['key1', 'value1', 'key2', '']
  770. * ```
  771. */
  772. this.attrs = [];
  773. this.notSelectors = [];
  774. }
  775. CssSelector.parse = function (selector) {
  776. var results = [];
  777. var _addResult = function (res, cssSel) {
  778. if (cssSel.notSelectors.length > 0 && !cssSel.element && cssSel.classNames.length == 0 &&
  779. cssSel.attrs.length == 0) {
  780. cssSel.element = '*';
  781. }
  782. res.push(cssSel);
  783. };
  784. var cssSelector = new CssSelector();
  785. var match;
  786. var current = cssSelector;
  787. var inNot = false;
  788. _SELECTOR_REGEXP.lastIndex = 0;
  789. while (match = _SELECTOR_REGEXP.exec(selector)) {
  790. if (match[1 /* NOT */]) {
  791. if (inNot) {
  792. throw new Error('Nesting :not in a selector is not allowed');
  793. }
  794. inNot = true;
  795. current = new CssSelector();
  796. cssSelector.notSelectors.push(current);
  797. }
  798. var tag = match[2 /* TAG */];
  799. if (tag) {
  800. var prefix = match[3 /* PREFIX */];
  801. if (prefix === '#') {
  802. // #hash
  803. current.addAttribute('id', tag.substr(1));
  804. }
  805. else if (prefix === '.') {
  806. // Class
  807. current.addClassName(tag.substr(1));
  808. }
  809. else {
  810. // Element
  811. current.setElement(tag);
  812. }
  813. }
  814. var attribute = match[4 /* ATTRIBUTE */];
  815. if (attribute) {
  816. current.addAttribute(attribute, match[6 /* ATTRIBUTE_VALUE */]);
  817. }
  818. if (match[7 /* NOT_END */]) {
  819. inNot = false;
  820. current = cssSelector;
  821. }
  822. if (match[8 /* SEPARATOR */]) {
  823. if (inNot) {
  824. throw new Error('Multiple selectors in :not are not supported');
  825. }
  826. _addResult(results, cssSelector);
  827. cssSelector = current = new CssSelector();
  828. }
  829. }
  830. _addResult(results, cssSelector);
  831. return results;
  832. };
  833. CssSelector.prototype.isElementSelector = function () {
  834. return this.hasElementSelector() && this.classNames.length == 0 && this.attrs.length == 0 &&
  835. this.notSelectors.length === 0;
  836. };
  837. CssSelector.prototype.hasElementSelector = function () {
  838. return !!this.element;
  839. };
  840. CssSelector.prototype.setElement = function (element) {
  841. if (element === void 0) { element = null; }
  842. this.element = element;
  843. };
  844. /** Gets a template string for an element that matches the selector. */
  845. CssSelector.prototype.getMatchingElementTemplate = function () {
  846. var tagName = this.element || 'div';
  847. var classAttr = this.classNames.length > 0 ? " class=\"" + this.classNames.join(' ') + "\"" : '';
  848. var attrs = '';
  849. for (var i = 0; i < this.attrs.length; i += 2) {
  850. var attrName = this.attrs[i];
  851. var attrValue = this.attrs[i + 1] !== '' ? "=\"" + this.attrs[i + 1] + "\"" : '';
  852. attrs += " " + attrName + attrValue;
  853. }
  854. return getHtmlTagDefinition(tagName).isVoid ? "<" + tagName + classAttr + attrs + "/>" :
  855. "<" + tagName + classAttr + attrs + "></" + tagName + ">";
  856. };
  857. CssSelector.prototype.getAttrs = function () {
  858. var result = [];
  859. if (this.classNames.length > 0) {
  860. result.push('class', this.classNames.join(' '));
  861. }
  862. return result.concat(this.attrs);
  863. };
  864. CssSelector.prototype.addAttribute = function (name, value) {
  865. if (value === void 0) { value = ''; }
  866. this.attrs.push(name, value && value.toLowerCase() || '');
  867. };
  868. CssSelector.prototype.addClassName = function (name) {
  869. this.classNames.push(name.toLowerCase());
  870. };
  871. CssSelector.prototype.toString = function () {
  872. var res = this.element || '';
  873. if (this.classNames) {
  874. this.classNames.forEach(function (klass) { return res += "." + klass; });
  875. }
  876. if (this.attrs) {
  877. for (var i = 0; i < this.attrs.length; i += 2) {
  878. var name = this.attrs[i];
  879. var value = this.attrs[i + 1];
  880. res += "[" + name + (value ? '=' + value : '') + "]";
  881. }
  882. }
  883. this.notSelectors.forEach(function (notSelector) { return res += ":not(" + notSelector + ")"; });
  884. return res;
  885. };
  886. return CssSelector;
  887. }());
  888. /**
  889. * Reads a list of CssSelectors and allows to calculate which ones
  890. * are contained in a given CssSelector.
  891. */
  892. var SelectorMatcher = /** @class */ (function () {
  893. function SelectorMatcher() {
  894. this._elementMap = new Map();
  895. this._elementPartialMap = new Map();
  896. this._classMap = new Map();
  897. this._classPartialMap = new Map();
  898. this._attrValueMap = new Map();
  899. this._attrValuePartialMap = new Map();
  900. this._listContexts = [];
  901. }
  902. SelectorMatcher.createNotMatcher = function (notSelectors) {
  903. var notMatcher = new SelectorMatcher();
  904. notMatcher.addSelectables(notSelectors, null);
  905. return notMatcher;
  906. };
  907. SelectorMatcher.prototype.addSelectables = function (cssSelectors, callbackCtxt) {
  908. var listContext = null;
  909. if (cssSelectors.length > 1) {
  910. listContext = new SelectorListContext(cssSelectors);
  911. this._listContexts.push(listContext);
  912. }
  913. for (var i = 0; i < cssSelectors.length; i++) {
  914. this._addSelectable(cssSelectors[i], callbackCtxt, listContext);
  915. }
  916. };
  917. /**
  918. * Add an object that can be found later on by calling `match`.
  919. * @param cssSelector A css selector
  920. * @param callbackCtxt An opaque object that will be given to the callback of the `match` function
  921. */
  922. SelectorMatcher.prototype._addSelectable = function (cssSelector, callbackCtxt, listContext) {
  923. var matcher = this;
  924. var element = cssSelector.element;
  925. var classNames = cssSelector.classNames;
  926. var attrs = cssSelector.attrs;
  927. var selectable = new SelectorContext(cssSelector, callbackCtxt, listContext);
  928. if (element) {
  929. var isTerminal = attrs.length === 0 && classNames.length === 0;
  930. if (isTerminal) {
  931. this._addTerminal(matcher._elementMap, element, selectable);
  932. }
  933. else {
  934. matcher = this._addPartial(matcher._elementPartialMap, element);
  935. }
  936. }
  937. if (classNames) {
  938. for (var i = 0; i < classNames.length; i++) {
  939. var isTerminal = attrs.length === 0 && i === classNames.length - 1;
  940. var className = classNames[i];
  941. if (isTerminal) {
  942. this._addTerminal(matcher._classMap, className, selectable);
  943. }
  944. else {
  945. matcher = this._addPartial(matcher._classPartialMap, className);
  946. }
  947. }
  948. }
  949. if (attrs) {
  950. for (var i = 0; i < attrs.length; i += 2) {
  951. var isTerminal = i === attrs.length - 2;
  952. var name = attrs[i];
  953. var value = attrs[i + 1];
  954. if (isTerminal) {
  955. var terminalMap = matcher._attrValueMap;
  956. var terminalValuesMap = terminalMap.get(name);
  957. if (!terminalValuesMap) {
  958. terminalValuesMap = new Map();
  959. terminalMap.set(name, terminalValuesMap);
  960. }
  961. this._addTerminal(terminalValuesMap, value, selectable);
  962. }
  963. else {
  964. var partialMap = matcher._attrValuePartialMap;
  965. var partialValuesMap = partialMap.get(name);
  966. if (!partialValuesMap) {
  967. partialValuesMap = new Map();
  968. partialMap.set(name, partialValuesMap);
  969. }
  970. matcher = this._addPartial(partialValuesMap, value);
  971. }
  972. }
  973. }
  974. };
  975. SelectorMatcher.prototype._addTerminal = function (map, name, selectable) {
  976. var terminalList = map.get(name);
  977. if (!terminalList) {
  978. terminalList = [];
  979. map.set(name, terminalList);
  980. }
  981. terminalList.push(selectable);
  982. };
  983. SelectorMatcher.prototype._addPartial = function (map, name) {
  984. var matcher = map.get(name);
  985. if (!matcher) {
  986. matcher = new SelectorMatcher();
  987. map.set(name, matcher);
  988. }
  989. return matcher;
  990. };
  991. /**
  992. * Find the objects that have been added via `addSelectable`
  993. * whose css selector is contained in the given css selector.
  994. * @param cssSelector A css selector
  995. * @param matchedCallback This callback will be called with the object handed into `addSelectable`
  996. * @return boolean true if a match was found
  997. */
  998. SelectorMatcher.prototype.match = function (cssSelector, matchedCallback) {
  999. var result = false;
  1000. var element = cssSelector.element;
  1001. var classNames = cssSelector.classNames;
  1002. var attrs = cssSelector.attrs;
  1003. for (var i = 0; i < this._listContexts.length; i++) {
  1004. this._listContexts[i].alreadyMatched = false;
  1005. }
  1006. result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result;
  1007. result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) ||
  1008. result;
  1009. if (classNames) {
  1010. for (var i = 0; i < classNames.length; i++) {
  1011. var className = classNames[i];
  1012. result =
  1013. this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result;
  1014. result =
  1015. this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) ||
  1016. result;
  1017. }
  1018. }
  1019. if (attrs) {
  1020. for (var i = 0; i < attrs.length; i += 2) {
  1021. var name = attrs[i];
  1022. var value = attrs[i + 1];
  1023. var terminalValuesMap = this._attrValueMap.get(name);
  1024. if (value) {
  1025. result =
  1026. this._matchTerminal(terminalValuesMap, '', cssSelector, matchedCallback) || result;
  1027. }
  1028. result =
  1029. this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result;
  1030. var partialValuesMap = this._attrValuePartialMap.get(name);
  1031. if (value) {
  1032. result = this._matchPartial(partialValuesMap, '', cssSelector, matchedCallback) || result;
  1033. }
  1034. result =
  1035. this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result;
  1036. }
  1037. }
  1038. return result;
  1039. };
  1040. /** @internal */
  1041. SelectorMatcher.prototype._matchTerminal = function (map, name, cssSelector, matchedCallback) {
  1042. if (!map || typeof name !== 'string') {
  1043. return false;
  1044. }
  1045. var selectables = map.get(name) || [];
  1046. var starSelectables = map.get('*');
  1047. if (starSelectables) {
  1048. selectables = selectables.concat(starSelectables);
  1049. }
  1050. if (selectables.length === 0) {
  1051. return false;
  1052. }
  1053. var selectable;
  1054. var result = false;
  1055. for (var i = 0; i < selectables.length; i++) {
  1056. selectable = selectables[i];
  1057. result = selectable.finalize(cssSelector, matchedCallback) || result;
  1058. }
  1059. return result;
  1060. };
  1061. /** @internal */
  1062. SelectorMatcher.prototype._matchPartial = function (map, name, cssSelector, matchedCallback) {
  1063. if (!map || typeof name !== 'string') {
  1064. return false;
  1065. }
  1066. var nestedSelector = map.get(name);
  1067. if (!nestedSelector) {
  1068. return false;
  1069. }
  1070. // TODO(perf): get rid of recursion and measure again
  1071. // TODO(perf): don't pass the whole selector into the recursion,
  1072. // but only the not processed parts
  1073. return nestedSelector.match(cssSelector, matchedCallback);
  1074. };
  1075. return SelectorMatcher;
  1076. }());
  1077. var SelectorListContext = /** @class */ (function () {
  1078. function SelectorListContext(selectors) {
  1079. this.selectors = selectors;
  1080. this.alreadyMatched = false;
  1081. }
  1082. return SelectorListContext;
  1083. }());
  1084. // Store context to pass back selector and context when a selector is matched
  1085. var SelectorContext = /** @class */ (function () {
  1086. function SelectorContext(selector, cbContext, listContext) {
  1087. this.selector = selector;
  1088. this.cbContext = cbContext;
  1089. this.listContext = listContext;
  1090. this.notSelectors = selector.notSelectors;
  1091. }
  1092. SelectorContext.prototype.finalize = function (cssSelector, callback) {
  1093. var result = true;
  1094. if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) {
  1095. var notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors);
  1096. result = !notMatcher.match(cssSelector, null);
  1097. }
  1098. if (result && callback && (!this.listContext || !this.listContext.alreadyMatched)) {
  1099. if (this.listContext) {
  1100. this.listContext.alreadyMatched = true;
  1101. }
  1102. callback(this.selector, this.cbContext);
  1103. }
  1104. return result;
  1105. };
  1106. return SelectorContext;
  1107. }());
  1108. var createInject = makeMetadataFactory('Inject', function (token) { return ({ token: token }); });
  1109. var createInjectionToken = makeMetadataFactory('InjectionToken', function (desc) { return ({ _desc: desc, ɵprov: undefined }); });
  1110. var createAttribute = makeMetadataFactory('Attribute', function (attributeName) { return ({ attributeName: attributeName }); });
  1111. // Stores the default value of `emitDistinctChangesOnly` when the `emitDistinctChangesOnly` is not
  1112. // explicitly set.
  1113. var emitDistinctChangesOnlyDefaultValue = true;
  1114. var createContentChildren = makeMetadataFactory('ContentChildren', function (selector, data) {
  1115. if (data === void 0) { data = {}; }
  1116. return (Object.assign({ selector: selector, first: false, isViewQuery: false, descendants: false, emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue }, data));
  1117. });
  1118. var createContentChild = makeMetadataFactory('ContentChild', function (selector, data) {
  1119. if (data === void 0) { data = {}; }
  1120. return (Object.assign({ selector: selector, first: true, isViewQuery: false, descendants: true }, data));
  1121. });
  1122. var createViewChildren = makeMetadataFactory('ViewChildren', function (selector, data) {
  1123. if (data === void 0) { data = {}; }
  1124. return (Object.assign({ selector: selector, first: false, isViewQuery: true, descendants: true, emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue }, data));
  1125. });
  1126. var createViewChild = makeMetadataFactory('ViewChild', function (selector, data) { return (Object.assign({ selector: selector, first: true, isViewQuery: true, descendants: true }, data)); });
  1127. var createDirective = makeMetadataFactory('Directive', function (dir) {
  1128. if (dir === void 0) { dir = {}; }
  1129. return dir;
  1130. });
  1131. var ViewEncapsulation;
  1132. (function (ViewEncapsulation) {
  1133. ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
  1134. // Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
  1135. ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
  1136. ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
  1137. })(ViewEncapsulation || (ViewEncapsulation = {}));
  1138. var ChangeDetectionStrategy;
  1139. (function (ChangeDetectionStrategy) {
  1140. ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
  1141. ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
  1142. })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}));
  1143. var createComponent = makeMetadataFactory('Component', function (c) {
  1144. if (c === void 0) { c = {}; }
  1145. return (Object.assign({ changeDetection: ChangeDetectionStrategy.Default }, c));
  1146. });
  1147. var createPipe = makeMetadataFactory('Pipe', function (p) { return (Object.assign({ pure: true }, p)); });
  1148. var createInput = makeMetadataFactory('Input', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); });
  1149. var createOutput = makeMetadataFactory('Output', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); });
  1150. var createHostBinding = makeMetadataFactory('HostBinding', function (hostPropertyName) { return ({ hostPropertyName: hostPropertyName }); });
  1151. var createHostListener = makeMetadataFactory('HostListener', function (eventName, args) { return ({ eventName: eventName, args: args }); });
  1152. var createNgModule = makeMetadataFactory('NgModule', function (ngModule) { return ngModule; });
  1153. var createInjectable = makeMetadataFactory('Injectable', function (injectable) {
  1154. if (injectable === void 0) { injectable = {}; }
  1155. return injectable;
  1156. });
  1157. var CUSTOM_ELEMENTS_SCHEMA = {
  1158. name: 'custom-elements'
  1159. };
  1160. var NO_ERRORS_SCHEMA = {
  1161. name: 'no-errors-schema'
  1162. };
  1163. var createOptional = makeMetadataFactory('Optional');
  1164. var createSelf = makeMetadataFactory('Self');
  1165. var createSkipSelf = makeMetadataFactory('SkipSelf');
  1166. var createHost = makeMetadataFactory('Host');
  1167. var Type = Function;
  1168. var SecurityContext;
  1169. (function (SecurityContext) {
  1170. SecurityContext[SecurityContext["NONE"] = 0] = "NONE";
  1171. SecurityContext[SecurityContext["HTML"] = 1] = "HTML";
  1172. SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE";
  1173. SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT";
  1174. SecurityContext[SecurityContext["URL"] = 4] = "URL";
  1175. SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL";
  1176. })(SecurityContext || (SecurityContext = {}));
  1177. var MissingTranslationStrategy;
  1178. (function (MissingTranslationStrategy) {
  1179. MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error";
  1180. MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning";
  1181. MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore";
  1182. })(MissingTranslationStrategy || (MissingTranslationStrategy = {}));
  1183. function makeMetadataFactory(name, props) {
  1184. // This must be declared as a function, not a fat arrow, so that ES2015 devmode produces code
  1185. // that works with the static_reflector.ts in the ViewEngine compiler.
  1186. // In particular, `_registerDecoratorOrConstructor` assumes that the value returned here can be
  1187. // new'ed.
  1188. function factory() {
  1189. var args = [];
  1190. for (var _i = 0; _i < arguments.length; _i++) {
  1191. args[_i] = arguments[_i];
  1192. }
  1193. var values = props ? props.apply(void 0, __spreadArray([], __read(args))) : {};
  1194. return Object.assign({ ngMetadataName: name }, values);
  1195. }
  1196. factory.isTypeOf = function (obj) { return obj && obj.ngMetadataName === name; };
  1197. factory.ngMetadataName = name;
  1198. return factory;
  1199. }
  1200. function parserSelectorToSimpleSelector(selector) {
  1201. var classes = selector.classNames && selector.classNames.length ? __spreadArray([8 /* CLASS */], __read(selector.classNames)) :
  1202. [];
  1203. var elementName = selector.element && selector.element !== '*' ? selector.element : '';
  1204. return __spreadArray(__spreadArray([elementName], __read(selector.attrs)), __read(classes));
  1205. }
  1206. function parserSelectorToNegativeSelector(selector) {
  1207. var classes = selector.classNames && selector.classNames.length ? __spreadArray([8 /* CLASS */], __read(selector.classNames)) :
  1208. [];
  1209. if (selector.element) {
  1210. return __spreadArray(__spreadArray([
  1211. 1 /* NOT */ | 4 /* ELEMENT */, selector.element
  1212. ], __read(selector.attrs)), __read(classes));
  1213. }
  1214. else if (selector.attrs.length) {
  1215. return __spreadArray(__spreadArray([1 /* NOT */ | 2 /* ATTRIBUTE */], __read(selector.attrs)), __read(classes));
  1216. }
  1217. else {
  1218. return selector.classNames && selector.classNames.length ? __spreadArray([1 /* NOT */ | 8 /* CLASS */], __read(selector.classNames)) :
  1219. [];
  1220. }
  1221. }
  1222. function parserSelectorToR3Selector(selector) {
  1223. var positive = parserSelectorToSimpleSelector(selector);
  1224. var negative = selector.notSelectors && selector.notSelectors.length ?
  1225. selector.notSelectors.map(function (notSelector) { return parserSelectorToNegativeSelector(notSelector); }) :
  1226. [];
  1227. return positive.concat.apply(positive, __spreadArray([], __read(negative)));
  1228. }
  1229. function parseSelectorToR3Selector(selector) {
  1230. return selector ? CssSelector.parse(selector).map(parserSelectorToR3Selector) : [];
  1231. }
  1232. var core = /*#__PURE__*/Object.freeze({
  1233. __proto__: null,
  1234. createInject: createInject,
  1235. createInjectionToken: createInjectionToken,
  1236. createAttribute: createAttribute,
  1237. emitDistinctChangesOnlyDefaultValue: emitDistinctChangesOnlyDefaultValue,
  1238. createContentChildren: createContentChildren,
  1239. createContentChild: createContentChild,
  1240. createViewChildren: createViewChildren,
  1241. createViewChild: createViewChild,
  1242. createDirective: createDirective,
  1243. get ViewEncapsulation () { return ViewEncapsulation; },
  1244. get ChangeDetectionStrategy () { return ChangeDetectionStrategy; },
  1245. createComponent: createComponent,
  1246. createPipe: createPipe,
  1247. createInput: createInput,
  1248. createOutput: createOutput,
  1249. createHostBinding: createHostBinding,
  1250. createHostListener: createHostListener,
  1251. createNgModule: createNgModule,
  1252. createInjectable: createInjectable,
  1253. CUSTOM_ELEMENTS_SCHEMA: CUSTOM_ELEMENTS_SCHEMA,
  1254. NO_ERRORS_SCHEMA: NO_ERRORS_SCHEMA,
  1255. createOptional: createOptional,
  1256. createSelf: createSelf,
  1257. createSkipSelf: createSkipSelf,
  1258. createHost: createHost,
  1259. Type: Type,
  1260. get SecurityContext () { return SecurityContext; },
  1261. get MissingTranslationStrategy () { return MissingTranslationStrategy; },
  1262. parseSelectorToR3Selector: parseSelectorToR3Selector
  1263. });
  1264. /**
  1265. * @license
  1266. * Copyright Google LLC All Rights Reserved.
  1267. *
  1268. * Use of this source code is governed by an MIT-style license that can be
  1269. * found in the LICENSE file at https://angular.io/license
  1270. */
  1271. //// Types
  1272. var TypeModifier;
  1273. (function (TypeModifier) {
  1274. TypeModifier[TypeModifier["Const"] = 0] = "Const";
  1275. })(TypeModifier || (TypeModifier = {}));
  1276. var Type$1 = /** @class */ (function () {
  1277. function Type(modifiers) {
  1278. if (modifiers === void 0) { modifiers = []; }
  1279. this.modifiers = modifiers;
  1280. }
  1281. Type.prototype.hasModifier = function (modifier) {
  1282. return this.modifiers.indexOf(modifier) !== -1;
  1283. };
  1284. return Type;
  1285. }());
  1286. (function (BuiltinTypeName) {
  1287. BuiltinTypeName[BuiltinTypeName["Dynamic"] = 0] = "Dynamic";
  1288. BuiltinTypeName[BuiltinTypeName["Bool"] = 1] = "Bool";
  1289. BuiltinTypeName[BuiltinTypeName["String"] = 2] = "String";
  1290. BuiltinTypeName[BuiltinTypeName["Int"] = 3] = "Int";
  1291. BuiltinTypeName[BuiltinTypeName["Number"] = 4] = "Number";
  1292. BuiltinTypeName[BuiltinTypeName["Function"] = 5] = "Function";
  1293. BuiltinTypeName[BuiltinTypeName["Inferred"] = 6] = "Inferred";
  1294. BuiltinTypeName[BuiltinTypeName["None"] = 7] = "None";
  1295. })(exports.BuiltinTypeName || (exports.BuiltinTypeName = {}));
  1296. var BuiltinType = /** @class */ (function (_super) {
  1297. __extends(BuiltinType, _super);
  1298. function BuiltinType(name, modifiers) {
  1299. var _this = _super.call(this, modifiers) || this;
  1300. _this.name = name;
  1301. return _this;
  1302. }
  1303. BuiltinType.prototype.visitType = function (visitor, context) {
  1304. return visitor.visitBuiltinType(this, context);
  1305. };
  1306. return BuiltinType;
  1307. }(Type$1));
  1308. var ExpressionType = /** @class */ (function (_super) {
  1309. __extends(ExpressionType, _super);
  1310. function ExpressionType(value, modifiers, typeParams) {
  1311. if (typeParams === void 0) { typeParams = null; }
  1312. var _this = _super.call(this, modifiers) || this;
  1313. _this.value = value;
  1314. _this.typeParams = typeParams;
  1315. return _this;
  1316. }
  1317. ExpressionType.prototype.visitType = function (visitor, context) {
  1318. return visitor.visitExpressionType(this, context);
  1319. };
  1320. return ExpressionType;
  1321. }(Type$1));
  1322. var ArrayType = /** @class */ (function (_super) {
  1323. __extends(ArrayType, _super);
  1324. function ArrayType(of, modifiers) {
  1325. var _this = _super.call(this, modifiers) || this;
  1326. _this.of = of;
  1327. return _this;
  1328. }
  1329. ArrayType.prototype.visitType = function (visitor, context) {
  1330. return visitor.visitArrayType(this, context);
  1331. };
  1332. return ArrayType;
  1333. }(Type$1));
  1334. var MapType = /** @class */ (function (_super) {
  1335. __extends(MapType, _super);
  1336. function MapType(valueType, modifiers) {
  1337. var _this = _super.call(this, modifiers) || this;
  1338. _this.valueType = valueType || null;
  1339. return _this;
  1340. }
  1341. MapType.prototype.visitType = function (visitor, context) {
  1342. return visitor.visitMapType(this, context);
  1343. };
  1344. return MapType;
  1345. }(Type$1));
  1346. var DYNAMIC_TYPE = new BuiltinType(exports.BuiltinTypeName.Dynamic);
  1347. var INFERRED_TYPE = new BuiltinType(exports.BuiltinTypeName.Inferred);
  1348. var BOOL_TYPE = new BuiltinType(exports.BuiltinTypeName.Bool);
  1349. var INT_TYPE = new BuiltinType(exports.BuiltinTypeName.Int);
  1350. var NUMBER_TYPE = new BuiltinType(exports.BuiltinTypeName.Number);
  1351. var STRING_TYPE = new BuiltinType(exports.BuiltinTypeName.String);
  1352. var FUNCTION_TYPE = new BuiltinType(exports.BuiltinTypeName.Function);
  1353. var NONE_TYPE = new BuiltinType(exports.BuiltinTypeName.None);
  1354. (function (UnaryOperator) {
  1355. UnaryOperator[UnaryOperator["Minus"] = 0] = "Minus";
  1356. UnaryOperator[UnaryOperator["Plus"] = 1] = "Plus";
  1357. })(exports.UnaryOperator || (exports.UnaryOperator = {}));
  1358. (function (BinaryOperator) {
  1359. BinaryOperator[BinaryOperator["Equals"] = 0] = "Equals";
  1360. BinaryOperator[BinaryOperator["NotEquals"] = 1] = "NotEquals";
  1361. BinaryOperator[BinaryOperator["Identical"] = 2] = "Identical";
  1362. BinaryOperator[BinaryOperator["NotIdentical"] = 3] = "NotIdentical";
  1363. BinaryOperator[BinaryOperator["Minus"] = 4] = "Minus";
  1364. BinaryOperator[BinaryOperator["Plus"] = 5] = "Plus";
  1365. BinaryOperator[BinaryOperator["Divide"] = 6] = "Divide";
  1366. BinaryOperator[BinaryOperator["Multiply"] = 7] = "Multiply";
  1367. BinaryOperator[BinaryOperator["Modulo"] = 8] = "Modulo";
  1368. BinaryOperator[BinaryOperator["And"] = 9] = "And";
  1369. BinaryOperator[BinaryOperator["Or"] = 10] = "Or";
  1370. BinaryOperator[BinaryOperator["BitwiseAnd"] = 11] = "BitwiseAnd";
  1371. BinaryOperator[BinaryOperator["Lower"] = 12] = "Lower";
  1372. BinaryOperator[BinaryOperator["LowerEquals"] = 13] = "LowerEquals";
  1373. BinaryOperator[BinaryOperator["Bigger"] = 14] = "Bigger";
  1374. BinaryOperator[BinaryOperator["BiggerEquals"] = 15] = "BiggerEquals";
  1375. BinaryOperator[BinaryOperator["NullishCoalesce"] = 16] = "NullishCoalesce";
  1376. })(exports.BinaryOperator || (exports.BinaryOperator = {}));
  1377. function nullSafeIsEquivalent(base, other) {
  1378. if (base == null || other == null) {
  1379. return base == other;
  1380. }
  1381. return base.isEquivalent(other);
  1382. }
  1383. function areAllEquivalentPredicate(base, other, equivalentPredicate) {
  1384. var len = base.length;
  1385. if (len !== other.length) {
  1386. return false;
  1387. }
  1388. for (var i = 0; i < len; i++) {
  1389. if (!equivalentPredicate(base[i], other[i])) {
  1390. return false;
  1391. }
  1392. }
  1393. return true;
  1394. }
  1395. function areAllEquivalent(base, other) {
  1396. return areAllEquivalentPredicate(base, other, function (baseElement, otherElement) { return baseElement.isEquivalent(otherElement); });
  1397. }
  1398. var Expression = /** @class */ (function () {
  1399. function Expression(type, sourceSpan) {
  1400. this.type = type || null;
  1401. this.sourceSpan = sourceSpan || null;
  1402. }
  1403. Expression.prototype.prop = function (name, sourceSpan) {
  1404. return new ReadPropExpr(this, name, null, sourceSpan);
  1405. };
  1406. Expression.prototype.key = function (index, type, sourceSpan) {
  1407. return new ReadKeyExpr(this, index, type, sourceSpan);
  1408. };
  1409. Expression.prototype.callMethod = function (name, params, sourceSpan) {
  1410. return new InvokeMethodExpr(this, name, params, null, sourceSpan);
  1411. };
  1412. Expression.prototype.callFn = function (params, sourceSpan, pure) {
  1413. return new InvokeFunctionExpr(this, params, null, sourceSpan, pure);
  1414. };
  1415. Expression.prototype.instantiate = function (params, type, sourceSpan) {
  1416. return new InstantiateExpr(this, params, type, sourceSpan);
  1417. };
  1418. Expression.prototype.conditional = function (trueCase, falseCase, sourceSpan) {
  1419. if (falseCase === void 0) { falseCase = null; }
  1420. return new ConditionalExpr(this, trueCase, falseCase, null, sourceSpan);
  1421. };
  1422. Expression.prototype.equals = function (rhs, sourceSpan) {
  1423. return new BinaryOperatorExpr(exports.BinaryOperator.Equals, this, rhs, null, sourceSpan);
  1424. };
  1425. Expression.prototype.notEquals = function (rhs, sourceSpan) {
  1426. return new BinaryOperatorExpr(exports.BinaryOperator.NotEquals, this, rhs, null, sourceSpan);
  1427. };
  1428. Expression.prototype.identical = function (rhs, sourceSpan) {
  1429. return new BinaryOperatorExpr(exports.BinaryOperator.Identical, this, rhs, null, sourceSpan);
  1430. };
  1431. Expression.prototype.notIdentical = function (rhs, sourceSpan) {
  1432. return new BinaryOperatorExpr(exports.BinaryOperator.NotIdentical, this, rhs, null, sourceSpan);
  1433. };
  1434. Expression.prototype.minus = function (rhs, sourceSpan) {
  1435. return new BinaryOperatorExpr(exports.BinaryOperator.Minus, this, rhs, null, sourceSpan);
  1436. };
  1437. Expression.prototype.plus = function (rhs, sourceSpan) {
  1438. return new BinaryOperatorExpr(exports.BinaryOperator.Plus, this, rhs, null, sourceSpan);
  1439. };
  1440. Expression.prototype.divide = function (rhs, sourceSpan) {
  1441. return new BinaryOperatorExpr(exports.BinaryOperator.Divide, this, rhs, null, sourceSpan);
  1442. };
  1443. Expression.prototype.multiply = function (rhs, sourceSpan) {
  1444. return new BinaryOperatorExpr(exports.BinaryOperator.Multiply, this, rhs, null, sourceSpan);
  1445. };
  1446. Expression.prototype.modulo = function (rhs, sourceSpan) {
  1447. return new BinaryOperatorExpr(exports.BinaryOperator.Modulo, this, rhs, null, sourceSpan);
  1448. };
  1449. Expression.prototype.and = function (rhs, sourceSpan) {
  1450. return new BinaryOperatorExpr(exports.BinaryOperator.And, this, rhs, null, sourceSpan);
  1451. };
  1452. Expression.prototype.bitwiseAnd = function (rhs, sourceSpan, parens) {
  1453. if (parens === void 0) { parens = true; }
  1454. return new BinaryOperatorExpr(exports.BinaryOperator.BitwiseAnd, this, rhs, null, sourceSpan, parens);
  1455. };
  1456. Expression.prototype.or = function (rhs, sourceSpan) {
  1457. return new BinaryOperatorExpr(exports.BinaryOperator.Or, this, rhs, null, sourceSpan);
  1458. };
  1459. Expression.prototype.lower = function (rhs, sourceSpan) {
  1460. return new BinaryOperatorExpr(exports.BinaryOperator.Lower, this, rhs, null, sourceSpan);
  1461. };
  1462. Expression.prototype.lowerEquals = function (rhs, sourceSpan) {
  1463. return new BinaryOperatorExpr(exports.BinaryOperator.LowerEquals, this, rhs, null, sourceSpan);
  1464. };
  1465. Expression.prototype.bigger = function (rhs, sourceSpan) {
  1466. return new BinaryOperatorExpr(exports.BinaryOperator.Bigger, this, rhs, null, sourceSpan);
  1467. };
  1468. Expression.prototype.biggerEquals = function (rhs, sourceSpan) {
  1469. return new BinaryOperatorExpr(exports.BinaryOperator.BiggerEquals, this, rhs, null, sourceSpan);
  1470. };
  1471. Expression.prototype.isBlank = function (sourceSpan) {
  1472. // Note: We use equals by purpose here to compare to null and undefined in JS.
  1473. // We use the typed null to allow strictNullChecks to narrow types.
  1474. return this.equals(TYPED_NULL_EXPR, sourceSpan);
  1475. };
  1476. Expression.prototype.cast = function (type, sourceSpan) {
  1477. return new CastExpr(this, type, sourceSpan);
  1478. };
  1479. Expression.prototype.nullishCoalesce = function (rhs, sourceSpan) {
  1480. return new BinaryOperatorExpr(exports.BinaryOperator.NullishCoalesce, this, rhs, null, sourceSpan);
  1481. };
  1482. Expression.prototype.toStmt = function () {
  1483. return new ExpressionStatement(this, null);
  1484. };
  1485. return Expression;
  1486. }());
  1487. (function (BuiltinVar) {
  1488. BuiltinVar[BuiltinVar["This"] = 0] = "This";
  1489. BuiltinVar[BuiltinVar["Super"] = 1] = "Super";
  1490. BuiltinVar[BuiltinVar["CatchError"] = 2] = "CatchError";
  1491. BuiltinVar[BuiltinVar["CatchStack"] = 3] = "CatchStack";
  1492. })(exports.BuiltinVar || (exports.BuiltinVar = {}));
  1493. var ReadVarExpr = /** @class */ (function (_super) {
  1494. __extends(ReadVarExpr, _super);
  1495. function ReadVarExpr(name, type, sourceSpan) {
  1496. var _this = _super.call(this, type, sourceSpan) || this;
  1497. if (typeof name === 'string') {
  1498. _this.name = name;
  1499. _this.builtin = null;
  1500. }
  1501. else {
  1502. _this.name = null;
  1503. _this.builtin = name;
  1504. }
  1505. return _this;
  1506. }
  1507. ReadVarExpr.prototype.isEquivalent = function (e) {
  1508. return e instanceof ReadVarExpr && this.name === e.name && this.builtin === e.builtin;
  1509. };
  1510. ReadVarExpr.prototype.isConstant = function () {
  1511. return false;
  1512. };
  1513. ReadVarExpr.prototype.visitExpression = function (visitor, context) {
  1514. return visitor.visitReadVarExpr(this, context);
  1515. };
  1516. ReadVarExpr.prototype.set = function (value) {
  1517. if (!this.name) {
  1518. throw new Error("Built in variable " + this.builtin + " can not be assigned to.");
  1519. }
  1520. return new WriteVarExpr(this.name, value, null, this.sourceSpan);
  1521. };
  1522. return ReadVarExpr;
  1523. }(Expression));
  1524. var TypeofExpr = /** @class */ (function (_super) {
  1525. __extends(TypeofExpr, _super);
  1526. function TypeofExpr(expr, type, sourceSpan) {
  1527. var _this = _super.call(this, type, sourceSpan) || this;
  1528. _this.expr = expr;
  1529. return _this;
  1530. }
  1531. TypeofExpr.prototype.visitExpression = function (visitor, context) {
  1532. return visitor.visitTypeofExpr(this, context);
  1533. };
  1534. TypeofExpr.prototype.isEquivalent = function (e) {
  1535. return e instanceof TypeofExpr && e.expr.isEquivalent(this.expr);
  1536. };
  1537. TypeofExpr.prototype.isConstant = function () {
  1538. return this.expr.isConstant();
  1539. };
  1540. return TypeofExpr;
  1541. }(Expression));
  1542. var WrappedNodeExpr = /** @class */ (function (_super) {
  1543. __extends(WrappedNodeExpr, _super);
  1544. function WrappedNodeExpr(node, type, sourceSpan) {
  1545. var _this = _super.call(this, type, sourceSpan) || this;
  1546. _this.node = node;
  1547. return _this;
  1548. }
  1549. WrappedNodeExpr.prototype.isEquivalent = function (e) {
  1550. return e instanceof WrappedNodeExpr && this.node === e.node;
  1551. };
  1552. WrappedNodeExpr.prototype.isConstant = function () {
  1553. return false;
  1554. };
  1555. WrappedNodeExpr.prototype.visitExpression = function (visitor, context) {
  1556. return visitor.visitWrappedNodeExpr(this, context);
  1557. };
  1558. return WrappedNodeExpr;
  1559. }(Expression));
  1560. var WriteVarExpr = /** @class */ (function (_super) {
  1561. __extends(WriteVarExpr, _super);
  1562. function WriteVarExpr(name, value, type, sourceSpan) {
  1563. var _this = _super.call(this, type || value.type, sourceSpan) || this;
  1564. _this.name = name;
  1565. _this.value = value;
  1566. return _this;
  1567. }
  1568. WriteVarExpr.prototype.isEquivalent = function (e) {
  1569. return e instanceof WriteVarExpr && this.name === e.name && this.value.isEquivalent(e.value);
  1570. };
  1571. WriteVarExpr.prototype.isConstant = function () {
  1572. return false;
  1573. };
  1574. WriteVarExpr.prototype.visitExpression = function (visitor, context) {
  1575. return visitor.visitWriteVarExpr(this, context);
  1576. };
  1577. WriteVarExpr.prototype.toDeclStmt = function (type, modifiers) {
  1578. return new DeclareVarStmt(this.name, this.value, type, modifiers, this.sourceSpan);
  1579. };
  1580. WriteVarExpr.prototype.toConstDecl = function () {
  1581. return this.toDeclStmt(INFERRED_TYPE, [exports.StmtModifier.Final]);
  1582. };
  1583. return WriteVarExpr;
  1584. }(Expression));
  1585. var WriteKeyExpr = /** @class */ (function (_super) {
  1586. __extends(WriteKeyExpr, _super);
  1587. function WriteKeyExpr(receiver, index, value, type, sourceSpan) {
  1588. var _this = _super.call(this, type || value.type, sourceSpan) || this;
  1589. _this.receiver = receiver;
  1590. _this.index = index;
  1591. _this.value = value;
  1592. return _this;
  1593. }
  1594. WriteKeyExpr.prototype.isEquivalent = function (e) {
  1595. return e instanceof WriteKeyExpr && this.receiver.isEquivalent(e.receiver) &&
  1596. this.index.isEquivalent(e.index) && this.value.isEquivalent(e.value);
  1597. };
  1598. WriteKeyExpr.prototype.isConstant = function () {
  1599. return false;
  1600. };
  1601. WriteKeyExpr.prototype.visitExpression = function (visitor, context) {
  1602. return visitor.visitWriteKeyExpr(this, context);
  1603. };
  1604. return WriteKeyExpr;
  1605. }(Expression));
  1606. var WritePropExpr = /** @class */ (function (_super) {
  1607. __extends(WritePropExpr, _super);
  1608. function WritePropExpr(receiver, name, value, type, sourceSpan) {
  1609. var _this = _super.call(this, type || value.type, sourceSpan) || this;
  1610. _this.receiver = receiver;
  1611. _this.name = name;
  1612. _this.value = value;
  1613. return _this;
  1614. }
  1615. WritePropExpr.prototype.isEquivalent = function (e) {
  1616. return e instanceof WritePropExpr && this.receiver.isEquivalent(e.receiver) &&
  1617. this.name === e.name && this.value.isEquivalent(e.value);
  1618. };
  1619. WritePropExpr.prototype.isConstant = function () {
  1620. return false;
  1621. };
  1622. WritePropExpr.prototype.visitExpression = function (visitor, context) {
  1623. return visitor.visitWritePropExpr(this, context);
  1624. };
  1625. return WritePropExpr;
  1626. }(Expression));
  1627. (function (BuiltinMethod) {
  1628. BuiltinMethod[BuiltinMethod["ConcatArray"] = 0] = "ConcatArray";
  1629. BuiltinMethod[BuiltinMethod["SubscribeObservable"] = 1] = "SubscribeObservable";
  1630. BuiltinMethod[BuiltinMethod["Bind"] = 2] = "Bind";
  1631. })(exports.BuiltinMethod || (exports.BuiltinMethod = {}));
  1632. var InvokeMethodExpr = /** @class */ (function (_super) {
  1633. __extends(InvokeMethodExpr, _super);
  1634. function InvokeMethodExpr(receiver, method, args, type, sourceSpan) {
  1635. var _this = _super.call(this, type, sourceSpan) || this;
  1636. _this.receiver = receiver;
  1637. _this.args = args;
  1638. if (typeof method === 'string') {
  1639. _this.name = method;
  1640. _this.builtin = null;
  1641. }
  1642. else {
  1643. _this.name = null;
  1644. _this.builtin = method;
  1645. }
  1646. return _this;
  1647. }
  1648. InvokeMethodExpr.prototype.isEquivalent = function (e) {
  1649. return e instanceof InvokeMethodExpr && this.receiver.isEquivalent(e.receiver) &&
  1650. this.name === e.name && this.builtin === e.builtin && areAllEquivalent(this.args, e.args);
  1651. };
  1652. InvokeMethodExpr.prototype.isConstant = function () {
  1653. return false;
  1654. };
  1655. InvokeMethodExpr.prototype.visitExpression = function (visitor, context) {
  1656. return visitor.visitInvokeMethodExpr(this, context);
  1657. };
  1658. return InvokeMethodExpr;
  1659. }(Expression));
  1660. var InvokeFunctionExpr = /** @class */ (function (_super) {
  1661. __extends(InvokeFunctionExpr, _super);
  1662. function InvokeFunctionExpr(fn, args, type, sourceSpan, pure) {
  1663. if (pure === void 0) { pure = false; }
  1664. var _this = _super.call(this, type, sourceSpan) || this;
  1665. _this.fn = fn;
  1666. _this.args = args;
  1667. _this.pure = pure;
  1668. return _this;
  1669. }
  1670. InvokeFunctionExpr.prototype.isEquivalent = function (e) {
  1671. return e instanceof InvokeFunctionExpr && this.fn.isEquivalent(e.fn) &&
  1672. areAllEquivalent(this.args, e.args) && this.pure === e.pure;
  1673. };
  1674. InvokeFunctionExpr.prototype.isConstant = function () {
  1675. return false;
  1676. };
  1677. InvokeFunctionExpr.prototype.visitExpression = function (visitor, context) {
  1678. return visitor.visitInvokeFunctionExpr(this, context);
  1679. };
  1680. return InvokeFunctionExpr;
  1681. }(Expression));
  1682. var TaggedTemplateExpr = /** @class */ (function (_super) {
  1683. __extends(TaggedTemplateExpr, _super);
  1684. function TaggedTemplateExpr(tag, template, type, sourceSpan) {
  1685. var _this = _super.call(this, type, sourceSpan) || this;
  1686. _this.tag = tag;
  1687. _this.template = template;
  1688. return _this;
  1689. }
  1690. TaggedTemplateExpr.prototype.isEquivalent = function (e) {
  1691. return e instanceof TaggedTemplateExpr && this.tag.isEquivalent(e.tag) &&
  1692. areAllEquivalentPredicate(this.template.elements, e.template.elements, function (a, b) { return a.text === b.text; }) &&
  1693. areAllEquivalent(this.template.expressions, e.template.expressions);
  1694. };
  1695. TaggedTemplateExpr.prototype.isConstant = function () {
  1696. return false;
  1697. };
  1698. TaggedTemplateExpr.prototype.visitExpression = function (visitor, context) {
  1699. return visitor.visitTaggedTemplateExpr(this, context);
  1700. };
  1701. return TaggedTemplateExpr;
  1702. }(Expression));
  1703. var InstantiateExpr = /** @class */ (function (_super) {
  1704. __extends(InstantiateExpr, _super);
  1705. function InstantiateExpr(classExpr, args, type, sourceSpan) {
  1706. var _this = _super.call(this, type, sourceSpan) || this;
  1707. _this.classExpr = classExpr;
  1708. _this.args = args;
  1709. return _this;
  1710. }
  1711. InstantiateExpr.prototype.isEquivalent = function (e) {
  1712. return e instanceof InstantiateExpr && this.classExpr.isEquivalent(e.classExpr) &&
  1713. areAllEquivalent(this.args, e.args);
  1714. };
  1715. InstantiateExpr.prototype.isConstant = function () {
  1716. return false;
  1717. };
  1718. InstantiateExpr.prototype.visitExpression = function (visitor, context) {
  1719. return visitor.visitInstantiateExpr(this, context);
  1720. };
  1721. return InstantiateExpr;
  1722. }(Expression));
  1723. var LiteralExpr = /** @class */ (function (_super) {
  1724. __extends(LiteralExpr, _super);
  1725. function LiteralExpr(value, type, sourceSpan) {
  1726. var _this = _super.call(this, type, sourceSpan) || this;
  1727. _this.value = value;
  1728. return _this;
  1729. }
  1730. LiteralExpr.prototype.isEquivalent = function (e) {
  1731. return e instanceof LiteralExpr && this.value === e.value;
  1732. };
  1733. LiteralExpr.prototype.isConstant = function () {
  1734. return true;
  1735. };
  1736. LiteralExpr.prototype.visitExpression = function (visitor, context) {
  1737. return visitor.visitLiteralExpr(this, context);
  1738. };
  1739. return LiteralExpr;
  1740. }(Expression));
  1741. var TemplateLiteral = /** @class */ (function () {
  1742. function TemplateLiteral(elements, expressions) {
  1743. this.elements = elements;
  1744. this.expressions = expressions;
  1745. }
  1746. return TemplateLiteral;
  1747. }());
  1748. var TemplateLiteralElement = /** @class */ (function () {
  1749. function TemplateLiteralElement(text, sourceSpan, rawText) {
  1750. var _a;
  1751. this.text = text;
  1752. this.sourceSpan = sourceSpan;
  1753. // If `rawText` is not provided, try to extract the raw string from its
  1754. // associated `sourceSpan`. If that is also not available, "fake" the raw
  1755. // string instead by escaping the following control sequences:
  1756. // - "\" would otherwise indicate that the next character is a control character.
  1757. // - "`" and "${" are template string control sequences that would otherwise prematurely
  1758. // indicate the end of the template literal element.
  1759. this.rawText =
  1760. (_a = rawText !== null && rawText !== void 0 ? rawText : sourceSpan === null || sourceSpan === void 0 ? void 0 : sourceSpan.toString()) !== null && _a !== void 0 ? _a : escapeForTemplateLiteral(escapeSlashes(text));
  1761. }
  1762. return TemplateLiteralElement;
  1763. }());
  1764. var MessagePiece = /** @class */ (function () {
  1765. function MessagePiece(text, sourceSpan) {
  1766. this.text = text;
  1767. this.sourceSpan = sourceSpan;
  1768. }
  1769. return MessagePiece;
  1770. }());
  1771. var LiteralPiece = /** @class */ (function (_super) {
  1772. __extends(LiteralPiece, _super);
  1773. function LiteralPiece() {
  1774. return _super !== null && _super.apply(this, arguments) || this;
  1775. }
  1776. return LiteralPiece;
  1777. }(MessagePiece));
  1778. var PlaceholderPiece = /** @class */ (function (_super) {
  1779. __extends(PlaceholderPiece, _super);
  1780. function PlaceholderPiece() {
  1781. return _super !== null && _super.apply(this, arguments) || this;
  1782. }
  1783. return PlaceholderPiece;
  1784. }(MessagePiece));
  1785. var LocalizedString = /** @class */ (function (_super) {
  1786. __extends(LocalizedString, _super);
  1787. function LocalizedString(metaBlock, messageParts, placeHolderNames, expressions, sourceSpan) {
  1788. var _this = _super.call(this, STRING_TYPE, sourceSpan) || this;
  1789. _this.metaBlock = metaBlock;
  1790. _this.messageParts = messageParts;
  1791. _this.placeHolderNames = placeHolderNames;
  1792. _this.expressions = expressions;
  1793. return _this;
  1794. }
  1795. LocalizedString.prototype.isEquivalent = function (e) {
  1796. // return e instanceof LocalizedString && this.message === e.message;
  1797. return false;
  1798. };
  1799. LocalizedString.prototype.isConstant = function () {
  1800. return false;
  1801. };
  1802. LocalizedString.prototype.visitExpression = function (visitor, context) {
  1803. return visitor.visitLocalizedString(this, context);
  1804. };
  1805. /**
  1806. * Serialize the given `meta` and `messagePart` into "cooked" and "raw" strings that can be used
  1807. * in a `$localize` tagged string. The format of the metadata is the same as that parsed by
  1808. * `parseI18nMeta()`.
  1809. *
  1810. * @param meta The metadata to serialize
  1811. * @param messagePart The first part of the tagged string
  1812. */
  1813. LocalizedString.prototype.serializeI18nHead = function () {
  1814. var MEANING_SEPARATOR = '|';
  1815. var ID_SEPARATOR = '@@';
  1816. var LEGACY_ID_INDICATOR = '␟';
  1817. var metaBlock = this.metaBlock.description || '';
  1818. if (this.metaBlock.meaning) {
  1819. metaBlock = "" + this.metaBlock.meaning + MEANING_SEPARATOR + metaBlock;
  1820. }
  1821. if (this.metaBlock.customId) {
  1822. metaBlock = "" + metaBlock + ID_SEPARATOR + this.metaBlock.customId;
  1823. }
  1824. if (this.metaBlock.legacyIds) {
  1825. this.metaBlock.legacyIds.forEach(function (legacyId) {
  1826. metaBlock = "" + metaBlock + LEGACY_ID_INDICATOR + legacyId;
  1827. });
  1828. }
  1829. return createCookedRawString(metaBlock, this.messageParts[0].text, this.getMessagePartSourceSpan(0));
  1830. };
  1831. LocalizedString.prototype.getMessagePartSourceSpan = function (i) {
  1832. var _a, _b;
  1833. return (_b = (_a = this.messageParts[i]) === null || _a === void 0 ? void 0 : _a.sourceSpan) !== null && _b !== void 0 ? _b : this.sourceSpan;
  1834. };
  1835. LocalizedString.prototype.getPlaceholderSourceSpan = function (i) {
  1836. var _a, _b, _c, _d;
  1837. return (_d = (_b = (_a = this.placeHolderNames[i]) === null || _a === void 0 ? void 0 : _a.sourceSpan) !== null && _b !== void 0 ? _b : (_c = this.expressions[i]) === null || _c === void 0 ? void 0 : _c.sourceSpan) !== null && _d !== void 0 ? _d : this.sourceSpan;
  1838. };
  1839. /**
  1840. * Serialize the given `placeholderName` and `messagePart` into "cooked" and "raw" strings that
  1841. * can be used in a `$localize` tagged string.
  1842. *
  1843. * @param placeholderName The placeholder name to serialize
  1844. * @param messagePart The following message string after this placeholder
  1845. */
  1846. LocalizedString.prototype.serializeI18nTemplatePart = function (partIndex) {
  1847. var placeholderName = this.placeHolderNames[partIndex - 1].text;
  1848. var messagePart = this.messageParts[partIndex];
  1849. return createCookedRawString(placeholderName, messagePart.text, this.getMessagePartSourceSpan(partIndex));
  1850. };
  1851. return LocalizedString;
  1852. }(Expression));
  1853. var escapeSlashes = function (str) { return str.replace(/\\/g, '\\\\'); };
  1854. var escapeStartingColon = function (str) { return str.replace(/^:/, '\\:'); };
  1855. var escapeColons = function (str) { return str.replace(/:/g, '\\:'); };
  1856. var escapeForTemplateLiteral = function (str) { return str.replace(/`/g, '\\`').replace(/\${/g, '$\\{'); };
  1857. /**
  1858. * Creates a `{cooked, raw}` object from the `metaBlock` and `messagePart`.
  1859. *
  1860. * The `raw` text must have various character sequences escaped:
  1861. * * "\" would otherwise indicate that the next character is a control character.
  1862. * * "`" and "${" are template string control sequences that would otherwise prematurely indicate
  1863. * the end of a message part.
  1864. * * ":" inside a metablock would prematurely indicate the end of the metablock.
  1865. * * ":" at the start of a messagePart with no metablock would erroneously indicate the start of a
  1866. * metablock.
  1867. *
  1868. * @param metaBlock Any metadata that should be prepended to the string
  1869. * @param messagePart The message part of the string
  1870. */
  1871. function createCookedRawString(metaBlock, messagePart, range) {
  1872. if (metaBlock === '') {
  1873. return {
  1874. cooked: messagePart,
  1875. raw: escapeForTemplateLiteral(escapeStartingColon(escapeSlashes(messagePart))),
  1876. range: range,
  1877. };
  1878. }
  1879. else {
  1880. return {
  1881. cooked: ":" + metaBlock + ":" + messagePart,
  1882. raw: escapeForTemplateLiteral(":" + escapeColons(escapeSlashes(metaBlock)) + ":" + escapeSlashes(messagePart)),
  1883. range: range,
  1884. };
  1885. }
  1886. }
  1887. var ExternalExpr = /** @class */ (function (_super) {
  1888. __extends(ExternalExpr, _super);
  1889. function ExternalExpr(value, type, typeParams, sourceSpan) {
  1890. if (typeParams === void 0) { typeParams = null; }
  1891. var _this = _super.call(this, type, sourceSpan) || this;
  1892. _this.value = value;
  1893. _this.typeParams = typeParams;
  1894. return _this;
  1895. }
  1896. ExternalExpr.prototype.isEquivalent = function (e) {
  1897. return e instanceof ExternalExpr && this.value.name === e.value.name &&
  1898. this.value.moduleName === e.value.moduleName && this.value.runtime === e.value.runtime;
  1899. };
  1900. ExternalExpr.prototype.isConstant = function () {
  1901. return false;
  1902. };
  1903. ExternalExpr.prototype.visitExpression = function (visitor, context) {
  1904. return visitor.visitExternalExpr(this, context);
  1905. };
  1906. return ExternalExpr;
  1907. }(Expression));
  1908. var ExternalReference = /** @class */ (function () {
  1909. function ExternalReference(moduleName, name, runtime) {
  1910. this.moduleName = moduleName;
  1911. this.name = name;
  1912. this.runtime = runtime;
  1913. }
  1914. return ExternalReference;
  1915. }());
  1916. var ConditionalExpr = /** @class */ (function (_super) {
  1917. __extends(ConditionalExpr, _super);
  1918. function ConditionalExpr(condition, trueCase, falseCase, type, sourceSpan) {
  1919. if (falseCase === void 0) { falseCase = null; }
  1920. var _this = _super.call(this, type || trueCase.type, sourceSpan) || this;
  1921. _this.condition = condition;
  1922. _this.falseCase = falseCase;
  1923. _this.trueCase = trueCase;
  1924. return _this;
  1925. }
  1926. ConditionalExpr.prototype.isEquivalent = function (e) {
  1927. return e instanceof ConditionalExpr && this.condition.isEquivalent(e.condition) &&
  1928. this.trueCase.isEquivalent(e.trueCase) && nullSafeIsEquivalent(this.falseCase, e.falseCase);
  1929. };
  1930. ConditionalExpr.prototype.isConstant = function () {
  1931. return false;
  1932. };
  1933. ConditionalExpr.prototype.visitExpression = function (visitor, context) {
  1934. return visitor.visitConditionalExpr(this, context);
  1935. };
  1936. return ConditionalExpr;
  1937. }(Expression));
  1938. var NotExpr = /** @class */ (function (_super) {
  1939. __extends(NotExpr, _super);
  1940. function NotExpr(condition, sourceSpan) {
  1941. var _this = _super.call(this, BOOL_TYPE, sourceSpan) || this;
  1942. _this.condition = condition;
  1943. return _this;
  1944. }
  1945. NotExpr.prototype.isEquivalent = function (e) {
  1946. return e instanceof NotExpr && this.condition.isEquivalent(e.condition);
  1947. };
  1948. NotExpr.prototype.isConstant = function () {
  1949. return false;
  1950. };
  1951. NotExpr.prototype.visitExpression = function (visitor, context) {
  1952. return visitor.visitNotExpr(this, context);
  1953. };
  1954. return NotExpr;
  1955. }(Expression));
  1956. var AssertNotNull = /** @class */ (function (_super) {
  1957. __extends(AssertNotNull, _super);
  1958. function AssertNotNull(condition, sourceSpan) {
  1959. var _this = _super.call(this, condition.type, sourceSpan) || this;
  1960. _this.condition = condition;
  1961. return _this;
  1962. }
  1963. AssertNotNull.prototype.isEquivalent = function (e) {
  1964. return e instanceof AssertNotNull && this.condition.isEquivalent(e.condition);
  1965. };
  1966. AssertNotNull.prototype.isConstant = function () {
  1967. return false;
  1968. };
  1969. AssertNotNull.prototype.visitExpression = function (visitor, context) {
  1970. return visitor.visitAssertNotNullExpr(this, context);
  1971. };
  1972. return AssertNotNull;
  1973. }(Expression));
  1974. var CastExpr = /** @class */ (function (_super) {
  1975. __extends(CastExpr, _super);
  1976. function CastExpr(value, type, sourceSpan) {
  1977. var _this = _super.call(this, type, sourceSpan) || this;
  1978. _this.value = value;
  1979. return _this;
  1980. }
  1981. CastExpr.prototype.isEquivalent = function (e) {
  1982. return e instanceof CastExpr && this.value.isEquivalent(e.value);
  1983. };
  1984. CastExpr.prototype.isConstant = function () {
  1985. return false;
  1986. };
  1987. CastExpr.prototype.visitExpression = function (visitor, context) {
  1988. return visitor.visitCastExpr(this, context);
  1989. };
  1990. return CastExpr;
  1991. }(Expression));
  1992. var FnParam = /** @class */ (function () {
  1993. function FnParam(name, type) {
  1994. if (type === void 0) { type = null; }
  1995. this.name = name;
  1996. this.type = type;
  1997. }
  1998. FnParam.prototype.isEquivalent = function (param) {
  1999. return this.name === param.name;
  2000. };
  2001. return FnParam;
  2002. }());
  2003. var FunctionExpr = /** @class */ (function (_super) {
  2004. __extends(FunctionExpr, _super);
  2005. function FunctionExpr(params, statements, type, sourceSpan, name) {
  2006. var _this = _super.call(this, type, sourceSpan) || this;
  2007. _this.params = params;
  2008. _this.statements = statements;
  2009. _this.name = name;
  2010. return _this;
  2011. }
  2012. FunctionExpr.prototype.isEquivalent = function (e) {
  2013. return e instanceof FunctionExpr && areAllEquivalent(this.params, e.params) &&
  2014. areAllEquivalent(this.statements, e.statements);
  2015. };
  2016. FunctionExpr.prototype.isConstant = function () {
  2017. return false;
  2018. };
  2019. FunctionExpr.prototype.visitExpression = function (visitor, context) {
  2020. return visitor.visitFunctionExpr(this, context);
  2021. };
  2022. FunctionExpr.prototype.toDeclStmt = function (name, modifiers) {
  2023. return new DeclareFunctionStmt(name, this.params, this.statements, this.type, modifiers, this.sourceSpan);
  2024. };
  2025. return FunctionExpr;
  2026. }(Expression));
  2027. var UnaryOperatorExpr = /** @class */ (function (_super) {
  2028. __extends(UnaryOperatorExpr, _super);
  2029. function UnaryOperatorExpr(operator, expr, type, sourceSpan, parens) {
  2030. if (parens === void 0) { parens = true; }
  2031. var _this = _super.call(this, type || NUMBER_TYPE, sourceSpan) || this;
  2032. _this.operator = operator;
  2033. _this.expr = expr;
  2034. _this.parens = parens;
  2035. return _this;
  2036. }
  2037. UnaryOperatorExpr.prototype.isEquivalent = function (e) {
  2038. return e instanceof UnaryOperatorExpr && this.operator === e.operator &&
  2039. this.expr.isEquivalent(e.expr);
  2040. };
  2041. UnaryOperatorExpr.prototype.isConstant = function () {
  2042. return false;
  2043. };
  2044. UnaryOperatorExpr.prototype.visitExpression = function (visitor, context) {
  2045. return visitor.visitUnaryOperatorExpr(this, context);
  2046. };
  2047. return UnaryOperatorExpr;
  2048. }(Expression));
  2049. var BinaryOperatorExpr = /** @class */ (function (_super) {
  2050. __extends(BinaryOperatorExpr, _super);
  2051. function BinaryOperatorExpr(operator, lhs, rhs, type, sourceSpan, parens) {
  2052. if (parens === void 0) { parens = true; }
  2053. var _this = _super.call(this, type || lhs.type, sourceSpan) || this;
  2054. _this.operator = operator;
  2055. _this.rhs = rhs;
  2056. _this.parens = parens;
  2057. _this.lhs = lhs;
  2058. return _this;
  2059. }
  2060. BinaryOperatorExpr.prototype.isEquivalent = function (e) {
  2061. return e instanceof BinaryOperatorExpr && this.operator === e.operator &&
  2062. this.lhs.isEquivalent(e.lhs) && this.rhs.isEquivalent(e.rhs);
  2063. };
  2064. BinaryOperatorExpr.prototype.isConstant = function () {
  2065. return false;
  2066. };
  2067. BinaryOperatorExpr.prototype.visitExpression = function (visitor, context) {
  2068. return visitor.visitBinaryOperatorExpr(this, context);
  2069. };
  2070. return BinaryOperatorExpr;
  2071. }(Expression));
  2072. var ReadPropExpr = /** @class */ (function (_super) {
  2073. __extends(ReadPropExpr, _super);
  2074. function ReadPropExpr(receiver, name, type, sourceSpan) {
  2075. var _this = _super.call(this, type, sourceSpan) || this;
  2076. _this.receiver = receiver;
  2077. _this.name = name;
  2078. return _this;
  2079. }
  2080. ReadPropExpr.prototype.isEquivalent = function (e) {
  2081. return e instanceof ReadPropExpr && this.receiver.isEquivalent(e.receiver) &&
  2082. this.name === e.name;
  2083. };
  2084. ReadPropExpr.prototype.isConstant = function () {
  2085. return false;
  2086. };
  2087. ReadPropExpr.prototype.visitExpression = function (visitor, context) {
  2088. return visitor.visitReadPropExpr(this, context);
  2089. };
  2090. ReadPropExpr.prototype.set = function (value) {
  2091. return new WritePropExpr(this.receiver, this.name, value, null, this.sourceSpan);
  2092. };
  2093. return ReadPropExpr;
  2094. }(Expression));
  2095. var ReadKeyExpr = /** @class */ (function (_super) {
  2096. __extends(ReadKeyExpr, _super);
  2097. function ReadKeyExpr(receiver, index, type, sourceSpan) {
  2098. var _this = _super.call(this, type, sourceSpan) || this;
  2099. _this.receiver = receiver;
  2100. _this.index = index;
  2101. return _this;
  2102. }
  2103. ReadKeyExpr.prototype.isEquivalent = function (e) {
  2104. return e instanceof ReadKeyExpr && this.receiver.isEquivalent(e.receiver) &&
  2105. this.index.isEquivalent(e.index);
  2106. };
  2107. ReadKeyExpr.prototype.isConstant = function () {
  2108. return false;
  2109. };
  2110. ReadKeyExpr.prototype.visitExpression = function (visitor, context) {
  2111. return visitor.visitReadKeyExpr(this, context);
  2112. };
  2113. ReadKeyExpr.prototype.set = function (value) {
  2114. return new WriteKeyExpr(this.receiver, this.index, value, null, this.sourceSpan);
  2115. };
  2116. return ReadKeyExpr;
  2117. }(Expression));
  2118. var LiteralArrayExpr = /** @class */ (function (_super) {
  2119. __extends(LiteralArrayExpr, _super);
  2120. function LiteralArrayExpr(entries, type, sourceSpan) {
  2121. var _this = _super.call(this, type, sourceSpan) || this;
  2122. _this.entries = entries;
  2123. return _this;
  2124. }
  2125. LiteralArrayExpr.prototype.isConstant = function () {
  2126. return this.entries.every(function (e) { return e.isConstant(); });
  2127. };
  2128. LiteralArrayExpr.prototype.isEquivalent = function (e) {
  2129. return e instanceof LiteralArrayExpr && areAllEquivalent(this.entries, e.entries);
  2130. };
  2131. LiteralArrayExpr.prototype.visitExpression = function (visitor, context) {
  2132. return visitor.visitLiteralArrayExpr(this, context);
  2133. };
  2134. return LiteralArrayExpr;
  2135. }(Expression));
  2136. var LiteralMapEntry = /** @class */ (function () {
  2137. function LiteralMapEntry(key, value, quoted) {
  2138. this.key = key;
  2139. this.value = value;
  2140. this.quoted = quoted;
  2141. }
  2142. LiteralMapEntry.prototype.isEquivalent = function (e) {
  2143. return this.key === e.key && this.value.isEquivalent(e.value);
  2144. };
  2145. return LiteralMapEntry;
  2146. }());
  2147. var LiteralMapExpr = /** @class */ (function (_super) {
  2148. __extends(LiteralMapExpr, _super);
  2149. function LiteralMapExpr(entries, type, sourceSpan) {
  2150. var _this = _super.call(this, type, sourceSpan) || this;
  2151. _this.entries = entries;
  2152. _this.valueType = null;
  2153. if (type) {
  2154. _this.valueType = type.valueType;
  2155. }
  2156. return _this;
  2157. }
  2158. LiteralMapExpr.prototype.isEquivalent = function (e) {
  2159. return e instanceof LiteralMapExpr && areAllEquivalent(this.entries, e.entries);
  2160. };
  2161. LiteralMapExpr.prototype.isConstant = function () {
  2162. return this.entries.every(function (e) { return e.value.isConstant(); });
  2163. };
  2164. LiteralMapExpr.prototype.visitExpression = function (visitor, context) {
  2165. return visitor.visitLiteralMapExpr(this, context);
  2166. };
  2167. return LiteralMapExpr;
  2168. }(Expression));
  2169. var CommaExpr = /** @class */ (function (_super) {
  2170. __extends(CommaExpr, _super);
  2171. function CommaExpr(parts, sourceSpan) {
  2172. var _this = _super.call(this, parts[parts.length - 1].type, sourceSpan) || this;
  2173. _this.parts = parts;
  2174. return _this;
  2175. }
  2176. CommaExpr.prototype.isEquivalent = function (e) {
  2177. return e instanceof CommaExpr && areAllEquivalent(this.parts, e.parts);
  2178. };
  2179. CommaExpr.prototype.isConstant = function () {
  2180. return false;
  2181. };
  2182. CommaExpr.prototype.visitExpression = function (visitor, context) {
  2183. return visitor.visitCommaExpr(this, context);
  2184. };
  2185. return CommaExpr;
  2186. }(Expression));
  2187. var THIS_EXPR = new ReadVarExpr(exports.BuiltinVar.This, null, null);
  2188. var SUPER_EXPR = new ReadVarExpr(exports.BuiltinVar.Super, null, null);
  2189. var CATCH_ERROR_VAR = new ReadVarExpr(exports.BuiltinVar.CatchError, null, null);
  2190. var CATCH_STACK_VAR = new ReadVarExpr(exports.BuiltinVar.CatchStack, null, null);
  2191. var NULL_EXPR = new LiteralExpr(null, null, null);
  2192. var TYPED_NULL_EXPR = new LiteralExpr(null, INFERRED_TYPE, null);
  2193. (function (StmtModifier) {
  2194. StmtModifier[StmtModifier["Final"] = 0] = "Final";
  2195. StmtModifier[StmtModifier["Private"] = 1] = "Private";
  2196. StmtModifier[StmtModifier["Exported"] = 2] = "Exported";
  2197. StmtModifier[StmtModifier["Static"] = 3] = "Static";
  2198. })(exports.StmtModifier || (exports.StmtModifier = {}));
  2199. var LeadingComment = /** @class */ (function () {
  2200. function LeadingComment(text, multiline, trailingNewline) {
  2201. this.text = text;
  2202. this.multiline = multiline;
  2203. this.trailingNewline = trailingNewline;
  2204. }
  2205. LeadingComment.prototype.toString = function () {
  2206. return this.multiline ? " " + this.text + " " : this.text;
  2207. };
  2208. return LeadingComment;
  2209. }());
  2210. var JSDocComment = /** @class */ (function (_super) {
  2211. __extends(JSDocComment, _super);
  2212. function JSDocComment(tags) {
  2213. var _this = _super.call(this, '', /* multiline */ true, /* trailingNewline */ true) || this;
  2214. _this.tags = tags;
  2215. return _this;
  2216. }
  2217. JSDocComment.prototype.toString = function () {
  2218. return serializeTags(this.tags);
  2219. };
  2220. return JSDocComment;
  2221. }(LeadingComment));
  2222. var Statement = /** @class */ (function () {
  2223. function Statement(modifiers, sourceSpan, leadingComments) {
  2224. if (modifiers === void 0) { modifiers = []; }
  2225. if (sourceSpan === void 0) { sourceSpan = null; }
  2226. this.modifiers = modifiers;
  2227. this.sourceSpan = sourceSpan;
  2228. this.leadingComments = leadingComments;
  2229. }
  2230. Statement.prototype.hasModifier = function (modifier) {
  2231. return this.modifiers.indexOf(modifier) !== -1;
  2232. };
  2233. Statement.prototype.addLeadingComment = function (leadingComment) {
  2234. var _a;
  2235. this.leadingComments = (_a = this.leadingComments) !== null && _a !== void 0 ? _a : [];
  2236. this.leadingComments.push(leadingComment);
  2237. };
  2238. return Statement;
  2239. }());
  2240. var DeclareVarStmt = /** @class */ (function (_super) {
  2241. __extends(DeclareVarStmt, _super);
  2242. function DeclareVarStmt(name, value, type, modifiers, sourceSpan, leadingComments) {
  2243. var _this = _super.call(this, modifiers, sourceSpan, leadingComments) || this;
  2244. _this.name = name;
  2245. _this.value = value;
  2246. _this.type = type || (value && value.type) || null;
  2247. return _this;
  2248. }
  2249. DeclareVarStmt.prototype.isEquivalent = function (stmt) {
  2250. return stmt instanceof DeclareVarStmt && this.name === stmt.name &&
  2251. (this.value ? !!stmt.value && this.value.isEquivalent(stmt.value) : !stmt.value);
  2252. };
  2253. DeclareVarStmt.prototype.visitStatement = function (visitor, context) {
  2254. return visitor.visitDeclareVarStmt(this, context);
  2255. };
  2256. return DeclareVarStmt;
  2257. }(Statement));
  2258. var DeclareFunctionStmt = /** @class */ (function (_super) {
  2259. __extends(DeclareFunctionStmt, _super);
  2260. function DeclareFunctionStmt(name, params, statements, type, modifiers, sourceSpan, leadingComments) {
  2261. var _this = _super.call(this, modifiers, sourceSpan, leadingComments) || this;
  2262. _this.name = name;
  2263. _this.params = params;
  2264. _this.statements = statements;
  2265. _this.type = type || null;
  2266. return _this;
  2267. }
  2268. DeclareFunctionStmt.prototype.isEquivalent = function (stmt) {
  2269. return stmt instanceof DeclareFunctionStmt && areAllEquivalent(this.params, stmt.params) &&
  2270. areAllEquivalent(this.statements, stmt.statements);
  2271. };
  2272. DeclareFunctionStmt.prototype.visitStatement = function (visitor, context) {
  2273. return visitor.visitDeclareFunctionStmt(this, context);
  2274. };
  2275. return DeclareFunctionStmt;
  2276. }(Statement));
  2277. var ExpressionStatement = /** @class */ (function (_super) {
  2278. __extends(ExpressionStatement, _super);
  2279. function ExpressionStatement(expr, sourceSpan, leadingComments) {
  2280. var _this = _super.call(this, [], sourceSpan, leadingComments) || this;
  2281. _this.expr = expr;
  2282. return _this;
  2283. }
  2284. ExpressionStatement.prototype.isEquivalent = function (stmt) {
  2285. return stmt instanceof ExpressionStatement && this.expr.isEquivalent(stmt.expr);
  2286. };
  2287. ExpressionStatement.prototype.visitStatement = function (visitor, context) {
  2288. return visitor.visitExpressionStmt(this, context);
  2289. };
  2290. return ExpressionStatement;
  2291. }(Statement));
  2292. var ReturnStatement = /** @class */ (function (_super) {
  2293. __extends(ReturnStatement, _super);
  2294. function ReturnStatement(value, sourceSpan, leadingComments) {
  2295. if (sourceSpan === void 0) { sourceSpan = null; }
  2296. var _this = _super.call(this, [], sourceSpan, leadingComments) || this;
  2297. _this.value = value;
  2298. return _this;
  2299. }
  2300. ReturnStatement.prototype.isEquivalent = function (stmt) {
  2301. return stmt instanceof ReturnStatement && this.value.isEquivalent(stmt.value);
  2302. };
  2303. ReturnStatement.prototype.visitStatement = function (visitor, context) {
  2304. return visitor.visitReturnStmt(this, context);
  2305. };
  2306. return ReturnStatement;
  2307. }(Statement));
  2308. var AbstractClassPart = /** @class */ (function () {
  2309. function AbstractClassPart(type, modifiers) {
  2310. if (type === void 0) { type = null; }
  2311. if (modifiers === void 0) { modifiers = []; }
  2312. this.type = type;
  2313. this.modifiers = modifiers;
  2314. }
  2315. AbstractClassPart.prototype.hasModifier = function (modifier) {
  2316. return this.modifiers.indexOf(modifier) !== -1;
  2317. };
  2318. return AbstractClassPart;
  2319. }());
  2320. var ClassField = /** @class */ (function (_super) {
  2321. __extends(ClassField, _super);
  2322. function ClassField(name, type, modifiers, initializer) {
  2323. var _this = _super.call(this, type, modifiers) || this;
  2324. _this.name = name;
  2325. _this.initializer = initializer;
  2326. return _this;
  2327. }
  2328. ClassField.prototype.isEquivalent = function (f) {
  2329. return this.name === f.name;
  2330. };
  2331. return ClassField;
  2332. }(AbstractClassPart));
  2333. var ClassMethod = /** @class */ (function (_super) {
  2334. __extends(ClassMethod, _super);
  2335. function ClassMethod(name, params, body, type, modifiers) {
  2336. var _this = _super.call(this, type, modifiers) || this;
  2337. _this.name = name;
  2338. _this.params = params;
  2339. _this.body = body;
  2340. return _this;
  2341. }
  2342. ClassMethod.prototype.isEquivalent = function (m) {
  2343. return this.name === m.name && areAllEquivalent(this.body, m.body);
  2344. };
  2345. return ClassMethod;
  2346. }(AbstractClassPart));
  2347. var ClassGetter = /** @class */ (function (_super) {
  2348. __extends(ClassGetter, _super);
  2349. function ClassGetter(name, body, type, modifiers) {
  2350. var _this = _super.call(this, type, modifiers) || this;
  2351. _this.name = name;
  2352. _this.body = body;
  2353. return _this;
  2354. }
  2355. ClassGetter.prototype.isEquivalent = function (m) {
  2356. return this.name === m.name && areAllEquivalent(this.body, m.body);
  2357. };
  2358. return ClassGetter;
  2359. }(AbstractClassPart));
  2360. var ClassStmt = /** @class */ (function (_super) {
  2361. __extends(ClassStmt, _super);
  2362. function ClassStmt(name, parent, fields, getters, constructorMethod, methods, modifiers, sourceSpan, leadingComments) {
  2363. var _this = _super.call(this, modifiers, sourceSpan, leadingComments) || this;
  2364. _this.name = name;
  2365. _this.parent = parent;
  2366. _this.fields = fields;
  2367. _this.getters = getters;
  2368. _this.constructorMethod = constructorMethod;
  2369. _this.methods = methods;
  2370. return _this;
  2371. }
  2372. ClassStmt.prototype.isEquivalent = function (stmt) {
  2373. return stmt instanceof ClassStmt && this.name === stmt.name &&
  2374. nullSafeIsEquivalent(this.parent, stmt.parent) &&
  2375. areAllEquivalent(this.fields, stmt.fields) &&
  2376. areAllEquivalent(this.getters, stmt.getters) &&
  2377. this.constructorMethod.isEquivalent(stmt.constructorMethod) &&
  2378. areAllEquivalent(this.methods, stmt.methods);
  2379. };
  2380. ClassStmt.prototype.visitStatement = function (visitor, context) {
  2381. return visitor.visitDeclareClassStmt(this, context);
  2382. };
  2383. return ClassStmt;
  2384. }(Statement));
  2385. var IfStmt = /** @class */ (function (_super) {
  2386. __extends(IfStmt, _super);
  2387. function IfStmt(condition, trueCase, falseCase, sourceSpan, leadingComments) {
  2388. if (falseCase === void 0) { falseCase = []; }
  2389. var _this = _super.call(this, [], sourceSpan, leadingComments) || this;
  2390. _this.condition = condition;
  2391. _this.trueCase = trueCase;
  2392. _this.falseCase = falseCase;
  2393. return _this;
  2394. }
  2395. IfStmt.prototype.isEquivalent = function (stmt) {
  2396. return stmt instanceof IfStmt && this.condition.isEquivalent(stmt.condition) &&
  2397. areAllEquivalent(this.trueCase, stmt.trueCase) &&
  2398. areAllEquivalent(this.falseCase, stmt.falseCase);
  2399. };
  2400. IfStmt.prototype.visitStatement = function (visitor, context) {
  2401. return visitor.visitIfStmt(this, context);
  2402. };
  2403. return IfStmt;
  2404. }(Statement));
  2405. var TryCatchStmt = /** @class */ (function (_super) {
  2406. __extends(TryCatchStmt, _super);
  2407. function TryCatchStmt(bodyStmts, catchStmts, sourceSpan, leadingComments) {
  2408. if (sourceSpan === void 0) { sourceSpan = null; }
  2409. var _this = _super.call(this, [], sourceSpan, leadingComments) || this;
  2410. _this.bodyStmts = bodyStmts;
  2411. _this.catchStmts = catchStmts;
  2412. return _this;
  2413. }
  2414. TryCatchStmt.prototype.isEquivalent = function (stmt) {
  2415. return stmt instanceof TryCatchStmt && areAllEquivalent(this.bodyStmts, stmt.bodyStmts) &&
  2416. areAllEquivalent(this.catchStmts, stmt.catchStmts);
  2417. };
  2418. TryCatchStmt.prototype.visitStatement = function (visitor, context) {
  2419. return visitor.visitTryCatchStmt(this, context);
  2420. };
  2421. return TryCatchStmt;
  2422. }(Statement));
  2423. var ThrowStmt = /** @class */ (function (_super) {
  2424. __extends(ThrowStmt, _super);
  2425. function ThrowStmt(error, sourceSpan, leadingComments) {
  2426. if (sourceSpan === void 0) { sourceSpan = null; }
  2427. var _this = _super.call(this, [], sourceSpan, leadingComments) || this;
  2428. _this.error = error;
  2429. return _this;
  2430. }
  2431. ThrowStmt.prototype.isEquivalent = function (stmt) {
  2432. return stmt instanceof TryCatchStmt && this.error.isEquivalent(stmt.error);
  2433. };
  2434. ThrowStmt.prototype.visitStatement = function (visitor, context) {
  2435. return visitor.visitThrowStmt(this, context);
  2436. };
  2437. return ThrowStmt;
  2438. }(Statement));
  2439. var AstTransformer = /** @class */ (function () {
  2440. function AstTransformer() {
  2441. }
  2442. AstTransformer.prototype.transformExpr = function (expr, context) {
  2443. return expr;
  2444. };
  2445. AstTransformer.prototype.transformStmt = function (stmt, context) {
  2446. return stmt;
  2447. };
  2448. AstTransformer.prototype.visitReadVarExpr = function (ast, context) {
  2449. return this.transformExpr(ast, context);
  2450. };
  2451. AstTransformer.prototype.visitWrappedNodeExpr = function (ast, context) {
  2452. return this.transformExpr(ast, context);
  2453. };
  2454. AstTransformer.prototype.visitTypeofExpr = function (expr, context) {
  2455. return this.transformExpr(new TypeofExpr(expr.expr.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  2456. };
  2457. AstTransformer.prototype.visitWriteVarExpr = function (expr, context) {
  2458. return this.transformExpr(new WriteVarExpr(expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  2459. };
  2460. AstTransformer.prototype.visitWriteKeyExpr = function (expr, context) {
  2461. return this.transformExpr(new WriteKeyExpr(expr.receiver.visitExpression(this, context), expr.index.visitExpression(this, context), expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  2462. };
  2463. AstTransformer.prototype.visitWritePropExpr = function (expr, context) {
  2464. return this.transformExpr(new WritePropExpr(expr.receiver.visitExpression(this, context), expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
  2465. };
  2466. AstTransformer.prototype.visitInvokeMethodExpr = function (ast, context) {
  2467. var method = ast.builtin || ast.name;
  2468. return this.transformExpr(new InvokeMethodExpr(ast.receiver.visitExpression(this, context), method, this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  2469. };
  2470. AstTransformer.prototype.visitInvokeFunctionExpr = function (ast, context) {
  2471. return this.transformExpr(new InvokeFunctionExpr(ast.fn.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  2472. };
  2473. AstTransformer.prototype.visitTaggedTemplateExpr = function (ast, context) {
  2474. var _this = this;
  2475. return this.transformExpr(new TaggedTemplateExpr(ast.tag.visitExpression(this, context), new TemplateLiteral(ast.template.elements, ast.template.expressions.map(function (e) { return e.visitExpression(_this, context); })), ast.type, ast.sourceSpan), context);
  2476. };
  2477. AstTransformer.prototype.visitInstantiateExpr = function (ast, context) {
  2478. return this.transformExpr(new InstantiateExpr(ast.classExpr.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
  2479. };
  2480. AstTransformer.prototype.visitLiteralExpr = function (ast, context) {
  2481. return this.transformExpr(ast, context);
  2482. };
  2483. AstTransformer.prototype.visitLocalizedString = function (ast, context) {
  2484. return this.transformExpr(new LocalizedString(ast.metaBlock, ast.messageParts, ast.placeHolderNames, this.visitAllExpressions(ast.expressions, context), ast.sourceSpan), context);
  2485. };
  2486. AstTransformer.prototype.visitExternalExpr = function (ast, context) {
  2487. return this.transformExpr(ast, context);
  2488. };
  2489. AstTransformer.prototype.visitConditionalExpr = function (ast, context) {
  2490. return this.transformExpr(new ConditionalExpr(ast.condition.visitExpression(this, context), ast.trueCase.visitExpression(this, context), ast.falseCase.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  2491. };
  2492. AstTransformer.prototype.visitNotExpr = function (ast, context) {
  2493. return this.transformExpr(new NotExpr(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
  2494. };
  2495. AstTransformer.prototype.visitAssertNotNullExpr = function (ast, context) {
  2496. return this.transformExpr(new AssertNotNull(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
  2497. };
  2498. AstTransformer.prototype.visitCastExpr = function (ast, context) {
  2499. return this.transformExpr(new CastExpr(ast.value.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  2500. };
  2501. AstTransformer.prototype.visitFunctionExpr = function (ast, context) {
  2502. return this.transformExpr(new FunctionExpr(ast.params, this.visitAllStatements(ast.statements, context), ast.type, ast.sourceSpan), context);
  2503. };
  2504. AstTransformer.prototype.visitUnaryOperatorExpr = function (ast, context) {
  2505. return this.transformExpr(new UnaryOperatorExpr(ast.operator, ast.expr.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  2506. };
  2507. AstTransformer.prototype.visitBinaryOperatorExpr = function (ast, context) {
  2508. return this.transformExpr(new BinaryOperatorExpr(ast.operator, ast.lhs.visitExpression(this, context), ast.rhs.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  2509. };
  2510. AstTransformer.prototype.visitReadPropExpr = function (ast, context) {
  2511. return this.transformExpr(new ReadPropExpr(ast.receiver.visitExpression(this, context), ast.name, ast.type, ast.sourceSpan), context);
  2512. };
  2513. AstTransformer.prototype.visitReadKeyExpr = function (ast, context) {
  2514. return this.transformExpr(new ReadKeyExpr(ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context), ast.type, ast.sourceSpan), context);
  2515. };
  2516. AstTransformer.prototype.visitLiteralArrayExpr = function (ast, context) {
  2517. return this.transformExpr(new LiteralArrayExpr(this.visitAllExpressions(ast.entries, context), ast.type, ast.sourceSpan), context);
  2518. };
  2519. AstTransformer.prototype.visitLiteralMapExpr = function (ast, context) {
  2520. var _this = this;
  2521. var entries = ast.entries.map(function (entry) { return new LiteralMapEntry(entry.key, entry.value.visitExpression(_this, context), entry.quoted); });
  2522. var mapType = new MapType(ast.valueType);
  2523. return this.transformExpr(new LiteralMapExpr(entries, mapType, ast.sourceSpan), context);
  2524. };
  2525. AstTransformer.prototype.visitCommaExpr = function (ast, context) {
  2526. return this.transformExpr(new CommaExpr(this.visitAllExpressions(ast.parts, context), ast.sourceSpan), context);
  2527. };
  2528. AstTransformer.prototype.visitAllExpressions = function (exprs, context) {
  2529. var _this = this;
  2530. return exprs.map(function (expr) { return expr.visitExpression(_this, context); });
  2531. };
  2532. AstTransformer.prototype.visitDeclareVarStmt = function (stmt, context) {
  2533. var value = stmt.value && stmt.value.visitExpression(this, context);
  2534. return this.transformStmt(new DeclareVarStmt(stmt.name, value, stmt.type, stmt.modifiers, stmt.sourceSpan, stmt.leadingComments), context);
  2535. };
  2536. AstTransformer.prototype.visitDeclareFunctionStmt = function (stmt, context) {
  2537. return this.transformStmt(new DeclareFunctionStmt(stmt.name, stmt.params, this.visitAllStatements(stmt.statements, context), stmt.type, stmt.modifiers, stmt.sourceSpan, stmt.leadingComments), context);
  2538. };
  2539. AstTransformer.prototype.visitExpressionStmt = function (stmt, context) {
  2540. return this.transformStmt(new ExpressionStatement(stmt.expr.visitExpression(this, context), stmt.sourceSpan, stmt.leadingComments), context);
  2541. };
  2542. AstTransformer.prototype.visitReturnStmt = function (stmt, context) {
  2543. return this.transformStmt(new ReturnStatement(stmt.value.visitExpression(this, context), stmt.sourceSpan, stmt.leadingComments), context);
  2544. };
  2545. AstTransformer.prototype.visitDeclareClassStmt = function (stmt, context) {
  2546. var _this = this;
  2547. var parent = stmt.parent.visitExpression(this, context);
  2548. var getters = stmt.getters.map(function (getter) { return new ClassGetter(getter.name, _this.visitAllStatements(getter.body, context), getter.type, getter.modifiers); });
  2549. var ctorMethod = stmt.constructorMethod &&
  2550. new ClassMethod(stmt.constructorMethod.name, stmt.constructorMethod.params, this.visitAllStatements(stmt.constructorMethod.body, context), stmt.constructorMethod.type, stmt.constructorMethod.modifiers);
  2551. var methods = stmt.methods.map(function (method) { return new ClassMethod(method.name, method.params, _this.visitAllStatements(method.body, context), method.type, method.modifiers); });
  2552. return this.transformStmt(new ClassStmt(stmt.name, parent, stmt.fields, getters, ctorMethod, methods, stmt.modifiers, stmt.sourceSpan), context);
  2553. };
  2554. AstTransformer.prototype.visitIfStmt = function (stmt, context) {
  2555. return this.transformStmt(new IfStmt(stmt.condition.visitExpression(this, context), this.visitAllStatements(stmt.trueCase, context), this.visitAllStatements(stmt.falseCase, context), stmt.sourceSpan, stmt.leadingComments), context);
  2556. };
  2557. AstTransformer.prototype.visitTryCatchStmt = function (stmt, context) {
  2558. return this.transformStmt(new TryCatchStmt(this.visitAllStatements(stmt.bodyStmts, context), this.visitAllStatements(stmt.catchStmts, context), stmt.sourceSpan, stmt.leadingComments), context);
  2559. };
  2560. AstTransformer.prototype.visitThrowStmt = function (stmt, context) {
  2561. return this.transformStmt(new ThrowStmt(stmt.error.visitExpression(this, context), stmt.sourceSpan, stmt.leadingComments), context);
  2562. };
  2563. AstTransformer.prototype.visitAllStatements = function (stmts, context) {
  2564. var _this = this;
  2565. return stmts.map(function (stmt) { return stmt.visitStatement(_this, context); });
  2566. };
  2567. return AstTransformer;
  2568. }());
  2569. var RecursiveAstVisitor = /** @class */ (function () {
  2570. function RecursiveAstVisitor() {
  2571. }
  2572. RecursiveAstVisitor.prototype.visitType = function (ast, context) {
  2573. return ast;
  2574. };
  2575. RecursiveAstVisitor.prototype.visitExpression = function (ast, context) {
  2576. if (ast.type) {
  2577. ast.type.visitType(this, context);
  2578. }
  2579. return ast;
  2580. };
  2581. RecursiveAstVisitor.prototype.visitBuiltinType = function (type, context) {
  2582. return this.visitType(type, context);
  2583. };
  2584. RecursiveAstVisitor.prototype.visitExpressionType = function (type, context) {
  2585. var _this = this;
  2586. type.value.visitExpression(this, context);
  2587. if (type.typeParams !== null) {
  2588. type.typeParams.forEach(function (param) { return _this.visitType(param, context); });
  2589. }
  2590. return this.visitType(type, context);
  2591. };
  2592. RecursiveAstVisitor.prototype.visitArrayType = function (type, context) {
  2593. return this.visitType(type, context);
  2594. };
  2595. RecursiveAstVisitor.prototype.visitMapType = function (type, context) {
  2596. return this.visitType(type, context);
  2597. };
  2598. RecursiveAstVisitor.prototype.visitWrappedNodeExpr = function (ast, context) {
  2599. return ast;
  2600. };
  2601. RecursiveAstVisitor.prototype.visitTypeofExpr = function (ast, context) {
  2602. return this.visitExpression(ast, context);
  2603. };
  2604. RecursiveAstVisitor.prototype.visitReadVarExpr = function (ast, context) {
  2605. return this.visitExpression(ast, context);
  2606. };
  2607. RecursiveAstVisitor.prototype.visitWriteVarExpr = function (ast, context) {
  2608. ast.value.visitExpression(this, context);
  2609. return this.visitExpression(ast, context);
  2610. };
  2611. RecursiveAstVisitor.prototype.visitWriteKeyExpr = function (ast, context) {
  2612. ast.receiver.visitExpression(this, context);
  2613. ast.index.visitExpression(this, context);
  2614. ast.value.visitExpression(this, context);
  2615. return this.visitExpression(ast, context);
  2616. };
  2617. RecursiveAstVisitor.prototype.visitWritePropExpr = function (ast, context) {
  2618. ast.receiver.visitExpression(this, context);
  2619. ast.value.visitExpression(this, context);
  2620. return this.visitExpression(ast, context);
  2621. };
  2622. RecursiveAstVisitor.prototype.visitInvokeMethodExpr = function (ast, context) {
  2623. ast.receiver.visitExpression(this, context);
  2624. this.visitAllExpressions(ast.args, context);
  2625. return this.visitExpression(ast, context);
  2626. };
  2627. RecursiveAstVisitor.prototype.visitInvokeFunctionExpr = function (ast, context) {
  2628. ast.fn.visitExpression(this, context);
  2629. this.visitAllExpressions(ast.args, context);
  2630. return this.visitExpression(ast, context);
  2631. };
  2632. RecursiveAstVisitor.prototype.visitTaggedTemplateExpr = function (ast, context) {
  2633. ast.tag.visitExpression(this, context);
  2634. this.visitAllExpressions(ast.template.expressions, context);
  2635. return this.visitExpression(ast, context);
  2636. };
  2637. RecursiveAstVisitor.prototype.visitInstantiateExpr = function (ast, context) {
  2638. ast.classExpr.visitExpression(this, context);
  2639. this.visitAllExpressions(ast.args, context);
  2640. return this.visitExpression(ast, context);
  2641. };
  2642. RecursiveAstVisitor.prototype.visitLiteralExpr = function (ast, context) {
  2643. return this.visitExpression(ast, context);
  2644. };
  2645. RecursiveAstVisitor.prototype.visitLocalizedString = function (ast, context) {
  2646. return this.visitExpression(ast, context);
  2647. };
  2648. RecursiveAstVisitor.prototype.visitExternalExpr = function (ast, context) {
  2649. var _this = this;
  2650. if (ast.typeParams) {
  2651. ast.typeParams.forEach(function (type) { return type.visitType(_this, context); });
  2652. }
  2653. return this.visitExpression(ast, context);
  2654. };
  2655. RecursiveAstVisitor.prototype.visitConditionalExpr = function (ast, context) {
  2656. ast.condition.visitExpression(this, context);
  2657. ast.trueCase.visitExpression(this, context);
  2658. ast.falseCase.visitExpression(this, context);
  2659. return this.visitExpression(ast, context);
  2660. };
  2661. RecursiveAstVisitor.prototype.visitNotExpr = function (ast, context) {
  2662. ast.condition.visitExpression(this, context);
  2663. return this.visitExpression(ast, context);
  2664. };
  2665. RecursiveAstVisitor.prototype.visitAssertNotNullExpr = function (ast, context) {
  2666. ast.condition.visitExpression(this, context);
  2667. return this.visitExpression(ast, context);
  2668. };
  2669. RecursiveAstVisitor.prototype.visitCastExpr = function (ast, context) {
  2670. ast.value.visitExpression(this, context);
  2671. return this.visitExpression(ast, context);
  2672. };
  2673. RecursiveAstVisitor.prototype.visitFunctionExpr = function (ast, context) {
  2674. this.visitAllStatements(ast.statements, context);
  2675. return this.visitExpression(ast, context);
  2676. };
  2677. RecursiveAstVisitor.prototype.visitUnaryOperatorExpr = function (ast, context) {
  2678. ast.expr.visitExpression(this, context);
  2679. return this.visitExpression(ast, context);
  2680. };
  2681. RecursiveAstVisitor.prototype.visitBinaryOperatorExpr = function (ast, context) {
  2682. ast.lhs.visitExpression(this, context);
  2683. ast.rhs.visitExpression(this, context);
  2684. return this.visitExpression(ast, context);
  2685. };
  2686. RecursiveAstVisitor.prototype.visitReadPropExpr = function (ast, context) {
  2687. ast.receiver.visitExpression(this, context);
  2688. return this.visitExpression(ast, context);
  2689. };
  2690. RecursiveAstVisitor.prototype.visitReadKeyExpr = function (ast, context) {
  2691. ast.receiver.visitExpression(this, context);
  2692. ast.index.visitExpression(this, context);
  2693. return this.visitExpression(ast, context);
  2694. };
  2695. RecursiveAstVisitor.prototype.visitLiteralArrayExpr = function (ast, context) {
  2696. this.visitAllExpressions(ast.entries, context);
  2697. return this.visitExpression(ast, context);
  2698. };
  2699. RecursiveAstVisitor.prototype.visitLiteralMapExpr = function (ast, context) {
  2700. var _this = this;
  2701. ast.entries.forEach(function (entry) { return entry.value.visitExpression(_this, context); });
  2702. return this.visitExpression(ast, context);
  2703. };
  2704. RecursiveAstVisitor.prototype.visitCommaExpr = function (ast, context) {
  2705. this.visitAllExpressions(ast.parts, context);
  2706. return this.visitExpression(ast, context);
  2707. };
  2708. RecursiveAstVisitor.prototype.visitAllExpressions = function (exprs, context) {
  2709. var _this = this;
  2710. exprs.forEach(function (expr) { return expr.visitExpression(_this, context); });
  2711. };
  2712. RecursiveAstVisitor.prototype.visitDeclareVarStmt = function (stmt, context) {
  2713. if (stmt.value) {
  2714. stmt.value.visitExpression(this, context);
  2715. }
  2716. if (stmt.type) {
  2717. stmt.type.visitType(this, context);
  2718. }
  2719. return stmt;
  2720. };
  2721. RecursiveAstVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) {
  2722. this.visitAllStatements(stmt.statements, context);
  2723. if (stmt.type) {
  2724. stmt.type.visitType(this, context);
  2725. }
  2726. return stmt;
  2727. };
  2728. RecursiveAstVisitor.prototype.visitExpressionStmt = function (stmt, context) {
  2729. stmt.expr.visitExpression(this, context);
  2730. return stmt;
  2731. };
  2732. RecursiveAstVisitor.prototype.visitReturnStmt = function (stmt, context) {
  2733. stmt.value.visitExpression(this, context);
  2734. return stmt;
  2735. };
  2736. RecursiveAstVisitor.prototype.visitDeclareClassStmt = function (stmt, context) {
  2737. var _this = this;
  2738. stmt.parent.visitExpression(this, context);
  2739. stmt.getters.forEach(function (getter) { return _this.visitAllStatements(getter.body, context); });
  2740. if (stmt.constructorMethod) {
  2741. this.visitAllStatements(stmt.constructorMethod.body, context);
  2742. }
  2743. stmt.methods.forEach(function (method) { return _this.visitAllStatements(method.body, context); });
  2744. return stmt;
  2745. };
  2746. RecursiveAstVisitor.prototype.visitIfStmt = function (stmt, context) {
  2747. stmt.condition.visitExpression(this, context);
  2748. this.visitAllStatements(stmt.trueCase, context);
  2749. this.visitAllStatements(stmt.falseCase, context);
  2750. return stmt;
  2751. };
  2752. RecursiveAstVisitor.prototype.visitTryCatchStmt = function (stmt, context) {
  2753. this.visitAllStatements(stmt.bodyStmts, context);
  2754. this.visitAllStatements(stmt.catchStmts, context);
  2755. return stmt;
  2756. };
  2757. RecursiveAstVisitor.prototype.visitThrowStmt = function (stmt, context) {
  2758. stmt.error.visitExpression(this, context);
  2759. return stmt;
  2760. };
  2761. RecursiveAstVisitor.prototype.visitAllStatements = function (stmts, context) {
  2762. var _this = this;
  2763. stmts.forEach(function (stmt) { return stmt.visitStatement(_this, context); });
  2764. };
  2765. return RecursiveAstVisitor;
  2766. }());
  2767. function findReadVarNames(stmts) {
  2768. var visitor = new _ReadVarVisitor();
  2769. visitor.visitAllStatements(stmts, null);
  2770. return visitor.varNames;
  2771. }
  2772. var _ReadVarVisitor = /** @class */ (function (_super) {
  2773. __extends(_ReadVarVisitor, _super);
  2774. function _ReadVarVisitor() {
  2775. var _this = _super.apply(this, __spreadArray([], __read(arguments))) || this;
  2776. _this.varNames = new Set();
  2777. return _this;
  2778. }
  2779. _ReadVarVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) {
  2780. // Don't descend into nested functions
  2781. return stmt;
  2782. };
  2783. _ReadVarVisitor.prototype.visitDeclareClassStmt = function (stmt, context) {
  2784. // Don't descend into nested classes
  2785. return stmt;
  2786. };
  2787. _ReadVarVisitor.prototype.visitReadVarExpr = function (ast, context) {
  2788. if (ast.name) {
  2789. this.varNames.add(ast.name);
  2790. }
  2791. return null;
  2792. };
  2793. return _ReadVarVisitor;
  2794. }(RecursiveAstVisitor));
  2795. function collectExternalReferences(stmts) {
  2796. var visitor = new _FindExternalReferencesVisitor();
  2797. visitor.visitAllStatements(stmts, null);
  2798. return visitor.externalReferences;
  2799. }
  2800. var _FindExternalReferencesVisitor = /** @class */ (function (_super) {
  2801. __extends(_FindExternalReferencesVisitor, _super);
  2802. function _FindExternalReferencesVisitor() {
  2803. var _this = _super.apply(this, __spreadArray([], __read(arguments))) || this;
  2804. _this.externalReferences = [];
  2805. return _this;
  2806. }
  2807. _FindExternalReferencesVisitor.prototype.visitExternalExpr = function (e, context) {
  2808. this.externalReferences.push(e.value);
  2809. return _super.prototype.visitExternalExpr.call(this, e, context);
  2810. };
  2811. return _FindExternalReferencesVisitor;
  2812. }(RecursiveAstVisitor));
  2813. function applySourceSpanToStatementIfNeeded(stmt, sourceSpan) {
  2814. if (!sourceSpan) {
  2815. return stmt;
  2816. }
  2817. var transformer = new _ApplySourceSpanTransformer(sourceSpan);
  2818. return stmt.visitStatement(transformer, null);
  2819. }
  2820. function applySourceSpanToExpressionIfNeeded(expr, sourceSpan) {
  2821. if (!sourceSpan) {
  2822. return expr;
  2823. }
  2824. var transformer = new _ApplySourceSpanTransformer(sourceSpan);
  2825. return expr.visitExpression(transformer, null);
  2826. }
  2827. var _ApplySourceSpanTransformer = /** @class */ (function (_super) {
  2828. __extends(_ApplySourceSpanTransformer, _super);
  2829. function _ApplySourceSpanTransformer(sourceSpan) {
  2830. var _this = _super.call(this) || this;
  2831. _this.sourceSpan = sourceSpan;
  2832. return _this;
  2833. }
  2834. _ApplySourceSpanTransformer.prototype._clone = function (obj) {
  2835. var e_1, _e;
  2836. var clone = Object.create(obj.constructor.prototype);
  2837. try {
  2838. for (var _f = __values(Object.keys(obj)), _g = _f.next(); !_g.done; _g = _f.next()) {
  2839. var prop = _g.value;
  2840. clone[prop] = obj[prop];
  2841. }
  2842. }
  2843. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  2844. finally {
  2845. try {
  2846. if (_g && !_g.done && (_e = _f.return)) _e.call(_f);
  2847. }
  2848. finally { if (e_1) throw e_1.error; }
  2849. }
  2850. return clone;
  2851. };
  2852. _ApplySourceSpanTransformer.prototype.transformExpr = function (expr, context) {
  2853. if (!expr.sourceSpan) {
  2854. expr = this._clone(expr);
  2855. expr.sourceSpan = this.sourceSpan;
  2856. }
  2857. return expr;
  2858. };
  2859. _ApplySourceSpanTransformer.prototype.transformStmt = function (stmt, context) {
  2860. if (!stmt.sourceSpan) {
  2861. stmt = this._clone(stmt);
  2862. stmt.sourceSpan = this.sourceSpan;
  2863. }
  2864. return stmt;
  2865. };
  2866. return _ApplySourceSpanTransformer;
  2867. }(AstTransformer));
  2868. function leadingComment(text, multiline, trailingNewline) {
  2869. if (multiline === void 0) { multiline = false; }
  2870. if (trailingNewline === void 0) { trailingNewline = true; }
  2871. return new LeadingComment(text, multiline, trailingNewline);
  2872. }
  2873. function jsDocComment(tags) {
  2874. if (tags === void 0) { tags = []; }
  2875. return new JSDocComment(tags);
  2876. }
  2877. function variable(name, type, sourceSpan) {
  2878. return new ReadVarExpr(name, type, sourceSpan);
  2879. }
  2880. function importExpr(id, typeParams, sourceSpan) {
  2881. if (typeParams === void 0) { typeParams = null; }
  2882. return new ExternalExpr(id, null, typeParams, sourceSpan);
  2883. }
  2884. function importType(id, typeParams, typeModifiers) {
  2885. return id != null ? expressionType(importExpr(id, typeParams, null), typeModifiers) : null;
  2886. }
  2887. function expressionType(expr, typeModifiers, typeParams) {
  2888. return new ExpressionType(expr, typeModifiers, typeParams);
  2889. }
  2890. function typeofExpr(expr) {
  2891. return new TypeofExpr(expr);
  2892. }
  2893. function literalArr(values, type, sourceSpan) {
  2894. return new LiteralArrayExpr(values, type, sourceSpan);
  2895. }
  2896. function literalMap(values, type) {
  2897. if (type === void 0) { type = null; }
  2898. return new LiteralMapExpr(values.map(function (e) { return new LiteralMapEntry(e.key, e.value, e.quoted); }), type, null);
  2899. }
  2900. function unary(operator, expr, type, sourceSpan) {
  2901. return new UnaryOperatorExpr(operator, expr, type, sourceSpan);
  2902. }
  2903. function not(expr, sourceSpan) {
  2904. return new NotExpr(expr, sourceSpan);
  2905. }
  2906. function assertNotNull(expr, sourceSpan) {
  2907. return new AssertNotNull(expr, sourceSpan);
  2908. }
  2909. function fn(params, body, type, sourceSpan, name) {
  2910. return new FunctionExpr(params, body, type, sourceSpan, name);
  2911. }
  2912. function ifStmt(condition, thenClause, elseClause, sourceSpan, leadingComments) {
  2913. return new IfStmt(condition, thenClause, elseClause, sourceSpan, leadingComments);
  2914. }
  2915. function taggedTemplate(tag, template, type, sourceSpan) {
  2916. return new TaggedTemplateExpr(tag, template, type, sourceSpan);
  2917. }
  2918. function literal(value, type, sourceSpan) {
  2919. return new LiteralExpr(value, type, sourceSpan);
  2920. }
  2921. function localizedString(metaBlock, messageParts, placeholderNames, expressions, sourceSpan) {
  2922. return new LocalizedString(metaBlock, messageParts, placeholderNames, expressions, sourceSpan);
  2923. }
  2924. function isNull(exp) {
  2925. return exp instanceof LiteralExpr && exp.value === null;
  2926. }
  2927. /*
  2928. * Serializes a `Tag` into a string.
  2929. * Returns a string like " @foo {bar} baz" (note the leading whitespace before `@foo`).
  2930. */
  2931. function tagToString(tag) {
  2932. var out = '';
  2933. if (tag.tagName) {
  2934. out += " @" + tag.tagName;
  2935. }
  2936. if (tag.text) {
  2937. if (tag.text.match(/\/\*|\*\//)) {
  2938. throw new Error('JSDoc text cannot contain "/*" and "*/"');
  2939. }
  2940. out += ' ' + tag.text.replace(/@/g, '\\@');
  2941. }
  2942. return out;
  2943. }
  2944. function serializeTags(tags) {
  2945. var e_2, _e;
  2946. if (tags.length === 0)
  2947. return '';
  2948. if (tags.length === 1 && tags[0].tagName && !tags[0].text) {
  2949. // The JSDOC comment is a single simple tag: e.g `/** @tagname */`.
  2950. return "*" + tagToString(tags[0]) + " ";
  2951. }
  2952. var out = '*\n';
  2953. try {
  2954. for (var tags_1 = __values(tags), tags_1_1 = tags_1.next(); !tags_1_1.done; tags_1_1 = tags_1.next()) {
  2955. var tag = tags_1_1.value;
  2956. out += ' *';
  2957. // If the tagToString is multi-line, insert " * " prefixes on lines.
  2958. out += tagToString(tag).replace(/\n/g, '\n * ');
  2959. out += '\n';
  2960. }
  2961. }
  2962. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  2963. finally {
  2964. try {
  2965. if (tags_1_1 && !tags_1_1.done && (_e = tags_1.return)) _e.call(tags_1);
  2966. }
  2967. finally { if (e_2) throw e_2.error; }
  2968. }
  2969. out += ' ';
  2970. return out;
  2971. }
  2972. var CONSTANT_PREFIX = '_c';
  2973. /**
  2974. * `ConstantPool` tries to reuse literal factories when two or more literals are identical.
  2975. * We determine whether literals are identical by creating a key out of their AST using the
  2976. * `KeyVisitor`. This constant is used to replace dynamic expressions which can't be safely
  2977. * converted into a key. E.g. given an expression `{foo: bar()}`, since we don't know what
  2978. * the result of `bar` will be, we create a key that looks like `{foo: <unknown>}`. Note
  2979. * that we use a variable, rather than something like `null` in order to avoid collisions.
  2980. */
  2981. var UNKNOWN_VALUE_KEY = variable('<unknown>');
  2982. /**
  2983. * Context to use when producing a key.
  2984. *
  2985. * This ensures we see the constant not the reference variable when producing
  2986. * a key.
  2987. */
  2988. var KEY_CONTEXT = {};
  2989. /**
  2990. * Generally all primitive values are excluded from the `ConstantPool`, but there is an exclusion
  2991. * for strings that reach a certain length threshold. This constant defines the length threshold for
  2992. * strings.
  2993. */
  2994. var POOL_INCLUSION_LENGTH_THRESHOLD_FOR_STRINGS = 50;
  2995. /**
  2996. * A node that is a place-holder that allows the node to be replaced when the actual
  2997. * node is known.
  2998. *
  2999. * This allows the constant pool to change an expression from a direct reference to
  3000. * a constant to a shared constant. It returns a fix-up node that is later allowed to
  3001. * change the referenced expression.
  3002. */
  3003. var FixupExpression = /** @class */ (function (_super) {
  3004. __extends(FixupExpression, _super);
  3005. function FixupExpression(resolved) {
  3006. var _this = _super.call(this, resolved.type) || this;
  3007. _this.resolved = resolved;
  3008. _this.original = resolved;
  3009. return _this;
  3010. }
  3011. FixupExpression.prototype.visitExpression = function (visitor, context) {
  3012. if (context === KEY_CONTEXT) {
  3013. // When producing a key we want to traverse the constant not the
  3014. // variable used to refer to it.
  3015. return this.original.visitExpression(visitor, context);
  3016. }
  3017. else {
  3018. return this.resolved.visitExpression(visitor, context);
  3019. }
  3020. };
  3021. FixupExpression.prototype.isEquivalent = function (e) {
  3022. return e instanceof FixupExpression && this.resolved.isEquivalent(e.resolved);
  3023. };
  3024. FixupExpression.prototype.isConstant = function () {
  3025. return true;
  3026. };
  3027. FixupExpression.prototype.fixup = function (expression) {
  3028. this.resolved = expression;
  3029. this.shared = true;
  3030. };
  3031. return FixupExpression;
  3032. }(Expression));
  3033. /**
  3034. * A constant pool allows a code emitter to share constant in an output context.
  3035. *
  3036. * The constant pool also supports sharing access to ivy definitions references.
  3037. */
  3038. var ConstantPool = /** @class */ (function () {
  3039. function ConstantPool(isClosureCompilerEnabled) {
  3040. if (isClosureCompilerEnabled === void 0) { isClosureCompilerEnabled = false; }
  3041. this.isClosureCompilerEnabled = isClosureCompilerEnabled;
  3042. this.statements = [];
  3043. this.literals = new Map();
  3044. this.literalFactories = new Map();
  3045. this.injectorDefinitions = new Map();
  3046. this.directiveDefinitions = new Map();
  3047. this.componentDefinitions = new Map();
  3048. this.pipeDefinitions = new Map();
  3049. this.nextNameIndex = 0;
  3050. }
  3051. ConstantPool.prototype.getConstLiteral = function (literal, forceShared) {
  3052. if ((literal instanceof LiteralExpr && !isLongStringLiteral(literal)) ||
  3053. literal instanceof FixupExpression) {
  3054. // Do no put simple literals into the constant pool or try to produce a constant for a
  3055. // reference to a constant.
  3056. return literal;
  3057. }
  3058. var key = this.keyOf(literal);
  3059. var fixup = this.literals.get(key);
  3060. var newValue = false;
  3061. if (!fixup) {
  3062. fixup = new FixupExpression(literal);
  3063. this.literals.set(key, fixup);
  3064. newValue = true;
  3065. }
  3066. if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
  3067. // Replace the expression with a variable
  3068. var name = this.freshName();
  3069. var definition = void 0;
  3070. var usage = void 0;
  3071. if (this.isClosureCompilerEnabled && isLongStringLiteral(literal)) {
  3072. // For string literals, Closure will **always** inline the string at
  3073. // **all** usages, duplicating it each time. For large strings, this
  3074. // unnecessarily bloats bundle size. To work around this restriction, we
  3075. // wrap the string in a function, and call that function for each usage.
  3076. // This tricks Closure into using inline logic for functions instead of
  3077. // string literals. Function calls are only inlined if the body is small
  3078. // enough to be worth it. By doing this, very large strings will be
  3079. // shared across multiple usages, rather than duplicating the string at
  3080. // each usage site.
  3081. //
  3082. // const myStr = function() { return "very very very long string"; };
  3083. // const usage1 = myStr();
  3084. // const usage2 = myStr();
  3085. definition = variable(name).set(new FunctionExpr([], // Params.
  3086. [
  3087. // Statements.
  3088. new ReturnStatement(literal),
  3089. ]));
  3090. usage = variable(name).callFn([]);
  3091. }
  3092. else {
  3093. // Just declare and use the variable directly, without a function call
  3094. // indirection. This saves a few bytes and avoids an unncessary call.
  3095. definition = variable(name).set(literal);
  3096. usage = variable(name);
  3097. }
  3098. this.statements.push(definition.toDeclStmt(INFERRED_TYPE, [exports.StmtModifier.Final]));
  3099. fixup.fixup(usage);
  3100. }
  3101. return fixup;
  3102. };
  3103. ConstantPool.prototype.getDefinition = function (type, kind, ctx, forceShared) {
  3104. if (forceShared === void 0) { forceShared = false; }
  3105. var definitions = this.definitionsOf(kind);
  3106. var fixup = definitions.get(type);
  3107. var newValue = false;
  3108. if (!fixup) {
  3109. var property = this.propertyNameOf(kind);
  3110. fixup = new FixupExpression(ctx.importExpr(type).prop(property));
  3111. definitions.set(type, fixup);
  3112. newValue = true;
  3113. }
  3114. if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
  3115. var name = this.freshName();
  3116. this.statements.push(variable(name).set(fixup.resolved).toDeclStmt(INFERRED_TYPE, [exports.StmtModifier.Final]));
  3117. fixup.fixup(variable(name));
  3118. }
  3119. return fixup;
  3120. };
  3121. ConstantPool.prototype.getLiteralFactory = function (literal) {
  3122. // Create a pure function that builds an array of a mix of constant and variable expressions
  3123. if (literal instanceof LiteralArrayExpr) {
  3124. var argumentsForKey = literal.entries.map(function (e) { return e.isConstant() ? e : UNKNOWN_VALUE_KEY; });
  3125. var key = this.keyOf(literalArr(argumentsForKey));
  3126. return this._getLiteralFactory(key, literal.entries, function (entries) { return literalArr(entries); });
  3127. }
  3128. else {
  3129. var expressionForKey = literalMap(literal.entries.map(function (e) { return ({
  3130. key: e.key,
  3131. value: e.value.isConstant() ? e.value : UNKNOWN_VALUE_KEY,
  3132. quoted: e.quoted
  3133. }); }));
  3134. var key = this.keyOf(expressionForKey);
  3135. return this._getLiteralFactory(key, literal.entries.map(function (e) { return e.value; }), function (entries) { return literalMap(entries.map(function (value, index) { return ({
  3136. key: literal.entries[index].key,
  3137. value: value,
  3138. quoted: literal.entries[index].quoted
  3139. }); })); });
  3140. }
  3141. };
  3142. ConstantPool.prototype._getLiteralFactory = function (key, values, resultMap) {
  3143. var _this = this;
  3144. var literalFactory = this.literalFactories.get(key);
  3145. var literalFactoryArguments = values.filter((function (e) { return !e.isConstant(); }));
  3146. if (!literalFactory) {
  3147. var resultExpressions = values.map(function (e, index) { return e.isConstant() ? _this.getConstLiteral(e, true) : variable("a" + index); });
  3148. var parameters = resultExpressions.filter(isVariable).map(function (e) { return new FnParam(e.name, DYNAMIC_TYPE); });
  3149. var pureFunctionDeclaration = fn(parameters, [new ReturnStatement(resultMap(resultExpressions))], INFERRED_TYPE);
  3150. var name = this.freshName();
  3151. this.statements.push(variable(name).set(pureFunctionDeclaration).toDeclStmt(INFERRED_TYPE, [
  3152. exports.StmtModifier.Final
  3153. ]));
  3154. literalFactory = variable(name);
  3155. this.literalFactories.set(key, literalFactory);
  3156. }
  3157. return { literalFactory: literalFactory, literalFactoryArguments: literalFactoryArguments };
  3158. };
  3159. /**
  3160. * Produce a unique name.
  3161. *
  3162. * The name might be unique among different prefixes if any of the prefixes end in
  3163. * a digit so the prefix should be a constant string (not based on user input) and
  3164. * must not end in a digit.
  3165. */
  3166. ConstantPool.prototype.uniqueName = function (prefix) {
  3167. return "" + prefix + this.nextNameIndex++;
  3168. };
  3169. ConstantPool.prototype.definitionsOf = function (kind) {
  3170. switch (kind) {
  3171. case 2 /* Component */:
  3172. return this.componentDefinitions;
  3173. case 1 /* Directive */:
  3174. return this.directiveDefinitions;
  3175. case 0 /* Injector */:
  3176. return this.injectorDefinitions;
  3177. case 3 /* Pipe */:
  3178. return this.pipeDefinitions;
  3179. }
  3180. };
  3181. ConstantPool.prototype.propertyNameOf = function (kind) {
  3182. switch (kind) {
  3183. case 2 /* Component */:
  3184. return 'ɵcmp';
  3185. case 1 /* Directive */:
  3186. return 'ɵdir';
  3187. case 0 /* Injector */:
  3188. return 'ɵinj';
  3189. case 3 /* Pipe */:
  3190. return 'ɵpipe';
  3191. }
  3192. };
  3193. ConstantPool.prototype.freshName = function () {
  3194. return this.uniqueName(CONSTANT_PREFIX);
  3195. };
  3196. ConstantPool.prototype.keyOf = function (expression) {
  3197. return expression.visitExpression(new KeyVisitor(), KEY_CONTEXT);
  3198. };
  3199. return ConstantPool;
  3200. }());
  3201. /**
  3202. * Visitor used to determine if 2 expressions are equivalent and can be shared in the
  3203. * `ConstantPool`.
  3204. *
  3205. * When the id (string) generated by the visitor is equal, expressions are considered equivalent.
  3206. */
  3207. var KeyVisitor = /** @class */ (function () {
  3208. function KeyVisitor() {
  3209. this.visitWrappedNodeExpr = invalid;
  3210. this.visitWriteVarExpr = invalid;
  3211. this.visitWriteKeyExpr = invalid;
  3212. this.visitWritePropExpr = invalid;
  3213. this.visitInvokeMethodExpr = invalid;
  3214. this.visitInvokeFunctionExpr = invalid;
  3215. this.visitTaggedTemplateExpr = invalid;
  3216. this.visitInstantiateExpr = invalid;
  3217. this.visitConditionalExpr = invalid;
  3218. this.visitNotExpr = invalid;
  3219. this.visitAssertNotNullExpr = invalid;
  3220. this.visitCastExpr = invalid;
  3221. this.visitFunctionExpr = invalid;
  3222. this.visitUnaryOperatorExpr = invalid;
  3223. this.visitBinaryOperatorExpr = invalid;
  3224. this.visitReadPropExpr = invalid;
  3225. this.visitReadKeyExpr = invalid;
  3226. this.visitCommaExpr = invalid;
  3227. this.visitLocalizedString = invalid;
  3228. }
  3229. KeyVisitor.prototype.visitLiteralExpr = function (ast) {
  3230. return "" + (typeof ast.value === 'string' ? '"' + ast.value + '"' : ast.value);
  3231. };
  3232. KeyVisitor.prototype.visitLiteralArrayExpr = function (ast, context) {
  3233. var _this = this;
  3234. return "[" + ast.entries.map(function (entry) { return entry.visitExpression(_this, context); }).join(',') + "]";
  3235. };
  3236. KeyVisitor.prototype.visitLiteralMapExpr = function (ast, context) {
  3237. var _this = this;
  3238. var mapKey = function (entry) {
  3239. var quote = entry.quoted ? '"' : '';
  3240. return "" + quote + entry.key + quote;
  3241. };
  3242. var mapEntry = function (entry) { return mapKey(entry) + ":" + entry.value.visitExpression(_this, context); };
  3243. return "{" + ast.entries.map(mapEntry).join(',');
  3244. };
  3245. KeyVisitor.prototype.visitExternalExpr = function (ast) {
  3246. return ast.value.moduleName ? "EX:" + ast.value.moduleName + ":" + ast.value.name :
  3247. "EX:" + ast.value.runtime.name;
  3248. };
  3249. KeyVisitor.prototype.visitReadVarExpr = function (node) {
  3250. return "VAR:" + node.name;
  3251. };
  3252. KeyVisitor.prototype.visitTypeofExpr = function (node, context) {
  3253. return "TYPEOF:" + node.expr.visitExpression(this, context);
  3254. };
  3255. return KeyVisitor;
  3256. }());
  3257. function invalid(arg) {
  3258. throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name);
  3259. }
  3260. function isVariable(e) {
  3261. return e instanceof ReadVarExpr;
  3262. }
  3263. function isLongStringLiteral(expr) {
  3264. return expr instanceof LiteralExpr && typeof expr.value === 'string' &&
  3265. expr.value.length >= POOL_INCLUSION_LENGTH_THRESHOLD_FOR_STRINGS;
  3266. }
  3267. /**
  3268. * @license
  3269. * Copyright Google LLC All Rights Reserved.
  3270. *
  3271. * Use of this source code is governed by an MIT-style license that can be
  3272. * found in the LICENSE file at https://angular.io/license
  3273. */
  3274. var CORE = '@angular/core';
  3275. var Identifiers = /** @class */ (function () {
  3276. function Identifiers() {
  3277. }
  3278. return Identifiers;
  3279. }());
  3280. /* Methods */
  3281. Identifiers.NEW_METHOD = 'factory';
  3282. Identifiers.TRANSFORM_METHOD = 'transform';
  3283. Identifiers.PATCH_DEPS = 'patchedDeps';
  3284. Identifiers.core = { name: null, moduleName: CORE };
  3285. /* Instructions */
  3286. Identifiers.namespaceHTML = { name: 'ɵɵnamespaceHTML', moduleName: CORE };
  3287. Identifiers.namespaceMathML = { name: 'ɵɵnamespaceMathML', moduleName: CORE };
  3288. Identifiers.namespaceSVG = { name: 'ɵɵnamespaceSVG', moduleName: CORE };
  3289. Identifiers.element = { name: 'ɵɵelement', moduleName: CORE };
  3290. Identifiers.elementStart = { name: 'ɵɵelementStart', moduleName: CORE };
  3291. Identifiers.elementEnd = { name: 'ɵɵelementEnd', moduleName: CORE };
  3292. Identifiers.advance = { name: 'ɵɵadvance', moduleName: CORE };
  3293. Identifiers.syntheticHostProperty = { name: 'ɵɵsyntheticHostProperty', moduleName: CORE };
  3294. Identifiers.syntheticHostListener = { name: 'ɵɵsyntheticHostListener', moduleName: CORE };
  3295. Identifiers.attribute = { name: 'ɵɵattribute', moduleName: CORE };
  3296. Identifiers.attributeInterpolate1 = { name: 'ɵɵattributeInterpolate1', moduleName: CORE };
  3297. Identifiers.attributeInterpolate2 = { name: 'ɵɵattributeInterpolate2', moduleName: CORE };
  3298. Identifiers.attributeInterpolate3 = { name: 'ɵɵattributeInterpolate3', moduleName: CORE };
  3299. Identifiers.attributeInterpolate4 = { name: 'ɵɵattributeInterpolate4', moduleName: CORE };
  3300. Identifiers.attributeInterpolate5 = { name: 'ɵɵattributeInterpolate5', moduleName: CORE };
  3301. Identifiers.attributeInterpolate6 = { name: 'ɵɵattributeInterpolate6', moduleName: CORE };
  3302. Identifiers.attributeInterpolate7 = { name: 'ɵɵattributeInterpolate7', moduleName: CORE };
  3303. Identifiers.attributeInterpolate8 = { name: 'ɵɵattributeInterpolate8', moduleName: CORE };
  3304. Identifiers.attributeInterpolateV = { name: 'ɵɵattributeInterpolateV', moduleName: CORE };
  3305. Identifiers.classProp = { name: 'ɵɵclassProp', moduleName: CORE };
  3306. Identifiers.elementContainerStart = { name: 'ɵɵelementContainerStart', moduleName: CORE };
  3307. Identifiers.elementContainerEnd = { name: 'ɵɵelementContainerEnd', moduleName: CORE };
  3308. Identifiers.elementContainer = { name: 'ɵɵelementContainer', moduleName: CORE };
  3309. Identifiers.styleMap = { name: 'ɵɵstyleMap', moduleName: CORE };
  3310. Identifiers.styleMapInterpolate1 = { name: 'ɵɵstyleMapInterpolate1', moduleName: CORE };
  3311. Identifiers.styleMapInterpolate2 = { name: 'ɵɵstyleMapInterpolate2', moduleName: CORE };
  3312. Identifiers.styleMapInterpolate3 = { name: 'ɵɵstyleMapInterpolate3', moduleName: CORE };
  3313. Identifiers.styleMapInterpolate4 = { name: 'ɵɵstyleMapInterpolate4', moduleName: CORE };
  3314. Identifiers.styleMapInterpolate5 = { name: 'ɵɵstyleMapInterpolate5', moduleName: CORE };
  3315. Identifiers.styleMapInterpolate6 = { name: 'ɵɵstyleMapInterpolate6', moduleName: CORE };
  3316. Identifiers.styleMapInterpolate7 = { name: 'ɵɵstyleMapInterpolate7', moduleName: CORE };
  3317. Identifiers.styleMapInterpolate8 = { name: 'ɵɵstyleMapInterpolate8', moduleName: CORE };
  3318. Identifiers.styleMapInterpolateV = { name: 'ɵɵstyleMapInterpolateV', moduleName: CORE };
  3319. Identifiers.classMap = { name: 'ɵɵclassMap', moduleName: CORE };
  3320. Identifiers.classMapInterpolate1 = { name: 'ɵɵclassMapInterpolate1', moduleName: CORE };
  3321. Identifiers.classMapInterpolate2 = { name: 'ɵɵclassMapInterpolate2', moduleName: CORE };
  3322. Identifiers.classMapInterpolate3 = { name: 'ɵɵclassMapInterpolate3', moduleName: CORE };
  3323. Identifiers.classMapInterpolate4 = { name: 'ɵɵclassMapInterpolate4', moduleName: CORE };
  3324. Identifiers.classMapInterpolate5 = { name: 'ɵɵclassMapInterpolate5', moduleName: CORE };
  3325. Identifiers.classMapInterpolate6 = { name: 'ɵɵclassMapInterpolate6', moduleName: CORE };
  3326. Identifiers.classMapInterpolate7 = { name: 'ɵɵclassMapInterpolate7', moduleName: CORE };
  3327. Identifiers.classMapInterpolate8 = { name: 'ɵɵclassMapInterpolate8', moduleName: CORE };
  3328. Identifiers.classMapInterpolateV = { name: 'ɵɵclassMapInterpolateV', moduleName: CORE };
  3329. Identifiers.styleProp = { name: 'ɵɵstyleProp', moduleName: CORE };
  3330. Identifiers.stylePropInterpolate1 = { name: 'ɵɵstylePropInterpolate1', moduleName: CORE };
  3331. Identifiers.stylePropInterpolate2 = { name: 'ɵɵstylePropInterpolate2', moduleName: CORE };
  3332. Identifiers.stylePropInterpolate3 = { name: 'ɵɵstylePropInterpolate3', moduleName: CORE };
  3333. Identifiers.stylePropInterpolate4 = { name: 'ɵɵstylePropInterpolate4', moduleName: CORE };
  3334. Identifiers.stylePropInterpolate5 = { name: 'ɵɵstylePropInterpolate5', moduleName: CORE };
  3335. Identifiers.stylePropInterpolate6 = { name: 'ɵɵstylePropInterpolate6', moduleName: CORE };
  3336. Identifiers.stylePropInterpolate7 = { name: 'ɵɵstylePropInterpolate7', moduleName: CORE };
  3337. Identifiers.stylePropInterpolate8 = { name: 'ɵɵstylePropInterpolate8', moduleName: CORE };
  3338. Identifiers.stylePropInterpolateV = { name: 'ɵɵstylePropInterpolateV', moduleName: CORE };
  3339. Identifiers.nextContext = { name: 'ɵɵnextContext', moduleName: CORE };
  3340. Identifiers.templateCreate = { name: 'ɵɵtemplate', moduleName: CORE };
  3341. Identifiers.text = { name: 'ɵɵtext', moduleName: CORE };
  3342. Identifiers.enableBindings = { name: 'ɵɵenableBindings', moduleName: CORE };
  3343. Identifiers.disableBindings = { name: 'ɵɵdisableBindings', moduleName: CORE };
  3344. Identifiers.getCurrentView = { name: 'ɵɵgetCurrentView', moduleName: CORE };
  3345. Identifiers.textInterpolate = { name: 'ɵɵtextInterpolate', moduleName: CORE };
  3346. Identifiers.textInterpolate1 = { name: 'ɵɵtextInterpolate1', moduleName: CORE };
  3347. Identifiers.textInterpolate2 = { name: 'ɵɵtextInterpolate2', moduleName: CORE };
  3348. Identifiers.textInterpolate3 = { name: 'ɵɵtextInterpolate3', moduleName: CORE };
  3349. Identifiers.textInterpolate4 = { name: 'ɵɵtextInterpolate4', moduleName: CORE };
  3350. Identifiers.textInterpolate5 = { name: 'ɵɵtextInterpolate5', moduleName: CORE };
  3351. Identifiers.textInterpolate6 = { name: 'ɵɵtextInterpolate6', moduleName: CORE };
  3352. Identifiers.textInterpolate7 = { name: 'ɵɵtextInterpolate7', moduleName: CORE };
  3353. Identifiers.textInterpolate8 = { name: 'ɵɵtextInterpolate8', moduleName: CORE };
  3354. Identifiers.textInterpolateV = { name: 'ɵɵtextInterpolateV', moduleName: CORE };
  3355. Identifiers.restoreView = { name: 'ɵɵrestoreView', moduleName: CORE };
  3356. Identifiers.pureFunction0 = { name: 'ɵɵpureFunction0', moduleName: CORE };
  3357. Identifiers.pureFunction1 = { name: 'ɵɵpureFunction1', moduleName: CORE };
  3358. Identifiers.pureFunction2 = { name: 'ɵɵpureFunction2', moduleName: CORE };
  3359. Identifiers.pureFunction3 = { name: 'ɵɵpureFunction3', moduleName: CORE };
  3360. Identifiers.pureFunction4 = { name: 'ɵɵpureFunction4', moduleName: CORE };
  3361. Identifiers.pureFunction5 = { name: 'ɵɵpureFunction5', moduleName: CORE };
  3362. Identifiers.pureFunction6 = { name: 'ɵɵpureFunction6', moduleName: CORE };
  3363. Identifiers.pureFunction7 = { name: 'ɵɵpureFunction7', moduleName: CORE };
  3364. Identifiers.pureFunction8 = { name: 'ɵɵpureFunction8', moduleName: CORE };
  3365. Identifiers.pureFunctionV = { name: 'ɵɵpureFunctionV', moduleName: CORE };
  3366. Identifiers.pipeBind1 = { name: 'ɵɵpipeBind1', moduleName: CORE };
  3367. Identifiers.pipeBind2 = { name: 'ɵɵpipeBind2', moduleName: CORE };
  3368. Identifiers.pipeBind3 = { name: 'ɵɵpipeBind3', moduleName: CORE };
  3369. Identifiers.pipeBind4 = { name: 'ɵɵpipeBind4', moduleName: CORE };
  3370. Identifiers.pipeBindV = { name: 'ɵɵpipeBindV', moduleName: CORE };
  3371. Identifiers.hostProperty = { name: 'ɵɵhostProperty', moduleName: CORE };
  3372. Identifiers.property = { name: 'ɵɵproperty', moduleName: CORE };
  3373. Identifiers.propertyInterpolate = { name: 'ɵɵpropertyInterpolate', moduleName: CORE };
  3374. Identifiers.propertyInterpolate1 = { name: 'ɵɵpropertyInterpolate1', moduleName: CORE };
  3375. Identifiers.propertyInterpolate2 = { name: 'ɵɵpropertyInterpolate2', moduleName: CORE };
  3376. Identifiers.propertyInterpolate3 = { name: 'ɵɵpropertyInterpolate3', moduleName: CORE };
  3377. Identifiers.propertyInterpolate4 = { name: 'ɵɵpropertyInterpolate4', moduleName: CORE };
  3378. Identifiers.propertyInterpolate5 = { name: 'ɵɵpropertyInterpolate5', moduleName: CORE };
  3379. Identifiers.propertyInterpolate6 = { name: 'ɵɵpropertyInterpolate6', moduleName: CORE };
  3380. Identifiers.propertyInterpolate7 = { name: 'ɵɵpropertyInterpolate7', moduleName: CORE };
  3381. Identifiers.propertyInterpolate8 = { name: 'ɵɵpropertyInterpolate8', moduleName: CORE };
  3382. Identifiers.propertyInterpolateV = { name: 'ɵɵpropertyInterpolateV', moduleName: CORE };
  3383. Identifiers.i18n = { name: 'ɵɵi18n', moduleName: CORE };
  3384. Identifiers.i18nAttributes = { name: 'ɵɵi18nAttributes', moduleName: CORE };
  3385. Identifiers.i18nExp = { name: 'ɵɵi18nExp', moduleName: CORE };
  3386. Identifiers.i18nStart = { name: 'ɵɵi18nStart', moduleName: CORE };
  3387. Identifiers.i18nEnd = { name: 'ɵɵi18nEnd', moduleName: CORE };
  3388. Identifiers.i18nApply = { name: 'ɵɵi18nApply', moduleName: CORE };
  3389. Identifiers.i18nPostprocess = { name: 'ɵɵi18nPostprocess', moduleName: CORE };
  3390. Identifiers.pipe = { name: 'ɵɵpipe', moduleName: CORE };
  3391. Identifiers.projection = { name: 'ɵɵprojection', moduleName: CORE };
  3392. Identifiers.projectionDef = { name: 'ɵɵprojectionDef', moduleName: CORE };
  3393. Identifiers.reference = { name: 'ɵɵreference', moduleName: CORE };
  3394. Identifiers.inject = { name: 'ɵɵinject', moduleName: CORE };
  3395. Identifiers.injectAttribute = { name: 'ɵɵinjectAttribute', moduleName: CORE };
  3396. Identifiers.directiveInject = { name: 'ɵɵdirectiveInject', moduleName: CORE };
  3397. Identifiers.invalidFactory = { name: 'ɵɵinvalidFactory', moduleName: CORE };
  3398. Identifiers.invalidFactoryDep = { name: 'ɵɵinvalidFactoryDep', moduleName: CORE };
  3399. Identifiers.templateRefExtractor = { name: 'ɵɵtemplateRefExtractor', moduleName: CORE };
  3400. Identifiers.forwardRef = { name: 'forwardRef', moduleName: CORE };
  3401. Identifiers.resolveForwardRef = { name: 'resolveForwardRef', moduleName: CORE };
  3402. Identifiers.ɵɵdefineInjectable = { name: 'ɵɵdefineInjectable', moduleName: CORE };
  3403. Identifiers.declareInjectable = { name: 'ɵɵngDeclareInjectable', moduleName: CORE };
  3404. Identifiers.InjectableDeclaration = { name: 'ɵɵInjectableDeclaration', moduleName: CORE };
  3405. Identifiers.resolveWindow = { name: 'ɵɵresolveWindow', moduleName: CORE };
  3406. Identifiers.resolveDocument = { name: 'ɵɵresolveDocument', moduleName: CORE };
  3407. Identifiers.resolveBody = { name: 'ɵɵresolveBody', moduleName: CORE };
  3408. Identifiers.defineComponent = { name: 'ɵɵdefineComponent', moduleName: CORE };
  3409. Identifiers.declareComponent = { name: 'ɵɵngDeclareComponent', moduleName: CORE };
  3410. Identifiers.setComponentScope = { name: 'ɵɵsetComponentScope', moduleName: CORE };
  3411. Identifiers.ChangeDetectionStrategy = {
  3412. name: 'ChangeDetectionStrategy',
  3413. moduleName: CORE,
  3414. };
  3415. Identifiers.ViewEncapsulation = {
  3416. name: 'ViewEncapsulation',
  3417. moduleName: CORE,
  3418. };
  3419. Identifiers.ComponentDeclaration = {
  3420. name: 'ɵɵComponentDeclaration',
  3421. moduleName: CORE,
  3422. };
  3423. Identifiers.FactoryDeclaration = {
  3424. name: 'ɵɵFactoryDeclaration',
  3425. moduleName: CORE,
  3426. };
  3427. Identifiers.declareFactory = { name: 'ɵɵngDeclareFactory', moduleName: CORE };
  3428. Identifiers.FactoryTarget = { name: 'ɵɵFactoryTarget', moduleName: CORE };
  3429. Identifiers.defineDirective = { name: 'ɵɵdefineDirective', moduleName: CORE };
  3430. Identifiers.declareDirective = { name: 'ɵɵngDeclareDirective', moduleName: CORE };
  3431. Identifiers.DirectiveDeclaration = {
  3432. name: 'ɵɵDirectiveDeclaration',
  3433. moduleName: CORE,
  3434. };
  3435. Identifiers.InjectorDef = { name: 'ɵɵInjectorDef', moduleName: CORE };
  3436. Identifiers.InjectorDeclaration = { name: 'ɵɵInjectorDeclaration', moduleName: CORE };
  3437. Identifiers.defineInjector = { name: 'ɵɵdefineInjector', moduleName: CORE };
  3438. Identifiers.declareInjector = { name: 'ɵɵngDeclareInjector', moduleName: CORE };
  3439. Identifiers.NgModuleDeclaration = {
  3440. name: 'ɵɵNgModuleDeclaration',
  3441. moduleName: CORE,
  3442. };
  3443. Identifiers.ModuleWithProviders = {
  3444. name: 'ModuleWithProviders',
  3445. moduleName: CORE,
  3446. };
  3447. Identifiers.defineNgModule = { name: 'ɵɵdefineNgModule', moduleName: CORE };
  3448. Identifiers.declareNgModule = { name: 'ɵɵngDeclareNgModule', moduleName: CORE };
  3449. Identifiers.setNgModuleScope = { name: 'ɵɵsetNgModuleScope', moduleName: CORE };
  3450. Identifiers.PipeDeclaration = { name: 'ɵɵPipeDeclaration', moduleName: CORE };
  3451. Identifiers.definePipe = { name: 'ɵɵdefinePipe', moduleName: CORE };
  3452. Identifiers.declarePipe = { name: 'ɵɵngDeclarePipe', moduleName: CORE };
  3453. Identifiers.declareClassMetadata = { name: 'ɵɵngDeclareClassMetadata', moduleName: CORE };
  3454. Identifiers.setClassMetadata = { name: 'ɵsetClassMetadata', moduleName: CORE };
  3455. Identifiers.queryRefresh = { name: 'ɵɵqueryRefresh', moduleName: CORE };
  3456. Identifiers.viewQuery = { name: 'ɵɵviewQuery', moduleName: CORE };
  3457. Identifiers.loadQuery = { name: 'ɵɵloadQuery', moduleName: CORE };
  3458. Identifiers.contentQuery = { name: 'ɵɵcontentQuery', moduleName: CORE };
  3459. Identifiers.NgOnChangesFeature = { name: 'ɵɵNgOnChangesFeature', moduleName: CORE };
  3460. Identifiers.InheritDefinitionFeature = { name: 'ɵɵInheritDefinitionFeature', moduleName: CORE };
  3461. Identifiers.CopyDefinitionFeature = { name: 'ɵɵCopyDefinitionFeature', moduleName: CORE };
  3462. Identifiers.ProvidersFeature = { name: 'ɵɵProvidersFeature', moduleName: CORE };
  3463. Identifiers.listener = { name: 'ɵɵlistener', moduleName: CORE };
  3464. Identifiers.getInheritedFactory = {
  3465. name: 'ɵɵgetInheritedFactory',
  3466. moduleName: CORE,
  3467. };
  3468. // sanitization-related functions
  3469. Identifiers.sanitizeHtml = { name: 'ɵɵsanitizeHtml', moduleName: CORE };
  3470. Identifiers.sanitizeStyle = { name: 'ɵɵsanitizeStyle', moduleName: CORE };
  3471. Identifiers.sanitizeResourceUrl = { name: 'ɵɵsanitizeResourceUrl', moduleName: CORE };
  3472. Identifiers.sanitizeScript = { name: 'ɵɵsanitizeScript', moduleName: CORE };
  3473. Identifiers.sanitizeUrl = { name: 'ɵɵsanitizeUrl', moduleName: CORE };
  3474. Identifiers.sanitizeUrlOrResourceUrl = { name: 'ɵɵsanitizeUrlOrResourceUrl', moduleName: CORE };
  3475. Identifiers.trustConstantHtml = { name: 'ɵɵtrustConstantHtml', moduleName: CORE };
  3476. Identifiers.trustConstantResourceUrl = { name: 'ɵɵtrustConstantResourceUrl', moduleName: CORE };
  3477. /**
  3478. * @license
  3479. * Copyright Google LLC All Rights Reserved.
  3480. *
  3481. * Use of this source code is governed by an MIT-style license that can be
  3482. * found in the LICENSE file at https://angular.io/license
  3483. */
  3484. var DASH_CASE_REGEXP = /-+([a-z0-9])/g;
  3485. function dashCaseToCamelCase(input) {
  3486. return input.replace(DASH_CASE_REGEXP, function () {
  3487. var m = [];
  3488. for (var _i = 0; _i < arguments.length; _i++) {
  3489. m[_i] = arguments[_i];
  3490. }
  3491. return m[1].toUpperCase();
  3492. });
  3493. }
  3494. function splitAtColon(input, defaultValues) {
  3495. return _splitAt(input, ':', defaultValues);
  3496. }
  3497. function splitAtPeriod(input, defaultValues) {
  3498. return _splitAt(input, '.', defaultValues);
  3499. }
  3500. function _splitAt(input, character, defaultValues) {
  3501. var characterIndex = input.indexOf(character);
  3502. if (characterIndex == -1)
  3503. return defaultValues;
  3504. return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()];
  3505. }
  3506. function visitValue(value, visitor, context) {
  3507. if (Array.isArray(value)) {
  3508. return visitor.visitArray(value, context);
  3509. }
  3510. if (isStrictStringMap(value)) {
  3511. return visitor.visitStringMap(value, context);
  3512. }
  3513. if (value == null || typeof value == 'string' || typeof value == 'number' ||
  3514. typeof value == 'boolean') {
  3515. return visitor.visitPrimitive(value, context);
  3516. }
  3517. return visitor.visitOther(value, context);
  3518. }
  3519. function isDefined(val) {
  3520. return val !== null && val !== undefined;
  3521. }
  3522. function noUndefined(val) {
  3523. return val === undefined ? null : val;
  3524. }
  3525. var ValueTransformer = /** @class */ (function () {
  3526. function ValueTransformer() {
  3527. }
  3528. ValueTransformer.prototype.visitArray = function (arr, context) {
  3529. var _this = this;
  3530. return arr.map(function (value) { return visitValue(value, _this, context); });
  3531. };
  3532. ValueTransformer.prototype.visitStringMap = function (map, context) {
  3533. var _this = this;
  3534. var result = {};
  3535. Object.keys(map).forEach(function (key) {
  3536. result[key] = visitValue(map[key], _this, context);
  3537. });
  3538. return result;
  3539. };
  3540. ValueTransformer.prototype.visitPrimitive = function (value, context) {
  3541. return value;
  3542. };
  3543. ValueTransformer.prototype.visitOther = function (value, context) {
  3544. return value;
  3545. };
  3546. return ValueTransformer;
  3547. }());
  3548. var SyncAsync = {
  3549. assertSync: function (value) {
  3550. if (isPromise(value)) {
  3551. throw new Error("Illegal state: value cannot be a promise");
  3552. }
  3553. return value;
  3554. },
  3555. then: function (value, cb) {
  3556. return isPromise(value) ? value.then(cb) : cb(value);
  3557. },
  3558. all: function (syncAsyncValues) {
  3559. return syncAsyncValues.some(isPromise) ? Promise.all(syncAsyncValues) : syncAsyncValues;
  3560. }
  3561. };
  3562. function error(msg) {
  3563. throw new Error("Internal Error: " + msg);
  3564. }
  3565. function syntaxError(msg, parseErrors) {
  3566. var error = Error(msg);
  3567. error[ERROR_SYNTAX_ERROR] = true;
  3568. if (parseErrors)
  3569. error[ERROR_PARSE_ERRORS] = parseErrors;
  3570. return error;
  3571. }
  3572. var ERROR_SYNTAX_ERROR = 'ngSyntaxError';
  3573. var ERROR_PARSE_ERRORS = 'ngParseErrors';
  3574. function isSyntaxError(error) {
  3575. return error[ERROR_SYNTAX_ERROR];
  3576. }
  3577. function getParseErrors(error) {
  3578. return error[ERROR_PARSE_ERRORS] || [];
  3579. }
  3580. // Escape characters that have a special meaning in Regular Expressions
  3581. function escapeRegExp(s) {
  3582. return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
  3583. }
  3584. var STRING_MAP_PROTO = Object.getPrototypeOf({});
  3585. function isStrictStringMap(obj) {
  3586. return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO;
  3587. }
  3588. function utf8Encode(str) {
  3589. var encoded = [];
  3590. for (var index = 0; index < str.length; index++) {
  3591. var codePoint = str.charCodeAt(index);
  3592. // decode surrogate
  3593. // see https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  3594. if (codePoint >= 0xd800 && codePoint <= 0xdbff && str.length > (index + 1)) {
  3595. var low = str.charCodeAt(index + 1);
  3596. if (low >= 0xdc00 && low <= 0xdfff) {
  3597. index++;
  3598. codePoint = ((codePoint - 0xd800) << 10) + low - 0xdc00 + 0x10000;
  3599. }
  3600. }
  3601. if (codePoint <= 0x7f) {
  3602. encoded.push(codePoint);
  3603. }
  3604. else if (codePoint <= 0x7ff) {
  3605. encoded.push(((codePoint >> 6) & 0x1F) | 0xc0, (codePoint & 0x3f) | 0x80);
  3606. }
  3607. else if (codePoint <= 0xffff) {
  3608. encoded.push((codePoint >> 12) | 0xe0, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
  3609. }
  3610. else if (codePoint <= 0x1fffff) {
  3611. encoded.push(((codePoint >> 18) & 0x07) | 0xf0, ((codePoint >> 12) & 0x3f) | 0x80, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
  3612. }
  3613. }
  3614. return encoded;
  3615. }
  3616. function stringify(token) {
  3617. if (typeof token === 'string') {
  3618. return token;
  3619. }
  3620. if (Array.isArray(token)) {
  3621. return '[' + token.map(stringify).join(', ') + ']';
  3622. }
  3623. if (token == null) {
  3624. return '' + token;
  3625. }
  3626. if (token.overriddenName) {
  3627. return "" + token.overriddenName;
  3628. }
  3629. if (token.name) {
  3630. return "" + token.name;
  3631. }
  3632. if (!token.toString) {
  3633. return 'object';
  3634. }
  3635. // WARNING: do not try to `JSON.stringify(token)` here
  3636. // see https://github.com/angular/angular/issues/23440
  3637. var res = token.toString();
  3638. if (res == null) {
  3639. return '' + res;
  3640. }
  3641. var newLineIndex = res.indexOf('\n');
  3642. return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
  3643. }
  3644. /**
  3645. * Lazily retrieves the reference value from a forwardRef.
  3646. */
  3647. function resolveForwardRef(type) {
  3648. if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__')) {
  3649. return type();
  3650. }
  3651. else {
  3652. return type;
  3653. }
  3654. }
  3655. /**
  3656. * Determine if the argument is shaped like a Promise
  3657. */
  3658. function isPromise(obj) {
  3659. // allow any Promise/A+ compliant thenable.
  3660. // It's up to the caller to ensure that obj.then conforms to the spec
  3661. return !!obj && typeof obj.then === 'function';
  3662. }
  3663. var Version = /** @class */ (function () {
  3664. function Version(full) {
  3665. this.full = full;
  3666. var splits = full.split('.');
  3667. this.major = splits[0];
  3668. this.minor = splits[1];
  3669. this.patch = splits.slice(2).join('.');
  3670. }
  3671. return Version;
  3672. }());
  3673. var __window = typeof window !== 'undefined' && window;
  3674. var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
  3675. self instanceof WorkerGlobalScope && self;
  3676. var __global = typeof global !== 'undefined' && global;
  3677. // Check __global first, because in Node tests both __global and __window may be defined and _global
  3678. // should be __global in that case.
  3679. var _global = __global || __window || __self;
  3680. function newArray(size, value) {
  3681. var list = [];
  3682. for (var i = 0; i < size; i++) {
  3683. list.push(value);
  3684. }
  3685. return list;
  3686. }
  3687. /**
  3688. * Partitions a given array into 2 arrays, based on a boolean value returned by the condition
  3689. * function.
  3690. *
  3691. * @param arr Input array that should be partitioned
  3692. * @param conditionFn Condition function that is called for each item in a given array and returns a
  3693. * boolean value.
  3694. */
  3695. function partitionArray(arr, conditionFn) {
  3696. var e_1, _a;
  3697. var truthy = [];
  3698. var falsy = [];
  3699. try {
  3700. for (var arr_1 = __values(arr), arr_1_1 = arr_1.next(); !arr_1_1.done; arr_1_1 = arr_1.next()) {
  3701. var item = arr_1_1.value;
  3702. (conditionFn(item) ? truthy : falsy).push(item);
  3703. }
  3704. }
  3705. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  3706. finally {
  3707. try {
  3708. if (arr_1_1 && !arr_1_1.done && (_a = arr_1.return)) _a.call(arr_1);
  3709. }
  3710. finally { if (e_1) throw e_1.error; }
  3711. }
  3712. return [truthy, falsy];
  3713. }
  3714. /**
  3715. * @license
  3716. * Copyright Google LLC All Rights Reserved.
  3717. *
  3718. * Use of this source code is governed by an MIT-style license that can be
  3719. * found in the LICENSE file at https://angular.io/license
  3720. */
  3721. /**
  3722. * This is an R3 `Node`-like wrapper for a raw `html.Comment` node. We do not currently
  3723. * require the implementation of a visitor for Comments as they are only collected at
  3724. * the top-level of the R3 AST, and only if `Render3ParseOptions['collectCommentNodes']`
  3725. * is true.
  3726. */
  3727. var Comment = /** @class */ (function () {
  3728. function Comment(value, sourceSpan) {
  3729. this.value = value;
  3730. this.sourceSpan = sourceSpan;
  3731. }
  3732. Comment.prototype.visit = function (_visitor) {
  3733. throw new Error('visit() not implemented for Comment');
  3734. };
  3735. return Comment;
  3736. }());
  3737. var Text = /** @class */ (function () {
  3738. function Text(value, sourceSpan) {
  3739. this.value = value;
  3740. this.sourceSpan = sourceSpan;
  3741. }
  3742. Text.prototype.visit = function (visitor) {
  3743. return visitor.visitText(this);
  3744. };
  3745. return Text;
  3746. }());
  3747. var BoundText = /** @class */ (function () {
  3748. function BoundText(value, sourceSpan, i18n) {
  3749. this.value = value;
  3750. this.sourceSpan = sourceSpan;
  3751. this.i18n = i18n;
  3752. }
  3753. BoundText.prototype.visit = function (visitor) {
  3754. return visitor.visitBoundText(this);
  3755. };
  3756. return BoundText;
  3757. }());
  3758. /**
  3759. * Represents a text attribute in the template.
  3760. *
  3761. * `valueSpan` may not be present in cases where there is no value `<div a></div>`.
  3762. * `keySpan` may also not be present for synthetic attributes from ICU expansions.
  3763. */
  3764. var TextAttribute = /** @class */ (function () {
  3765. function TextAttribute(name, value, sourceSpan, keySpan, valueSpan, i18n) {
  3766. this.name = name;
  3767. this.value = value;
  3768. this.sourceSpan = sourceSpan;
  3769. this.keySpan = keySpan;
  3770. this.valueSpan = valueSpan;
  3771. this.i18n = i18n;
  3772. }
  3773. TextAttribute.prototype.visit = function (visitor) {
  3774. return visitor.visitTextAttribute(this);
  3775. };
  3776. return TextAttribute;
  3777. }());
  3778. var BoundAttribute = /** @class */ (function () {
  3779. function BoundAttribute(name, type, securityContext, value, unit, sourceSpan, keySpan, valueSpan, i18n) {
  3780. this.name = name;
  3781. this.type = type;
  3782. this.securityContext = securityContext;
  3783. this.value = value;
  3784. this.unit = unit;
  3785. this.sourceSpan = sourceSpan;
  3786. this.keySpan = keySpan;
  3787. this.valueSpan = valueSpan;
  3788. this.i18n = i18n;
  3789. }
  3790. BoundAttribute.fromBoundElementProperty = function (prop, i18n) {
  3791. if (prop.keySpan === undefined) {
  3792. throw new Error("Unexpected state: keySpan must be defined for bound attributes but was not for " + prop.name + ": " + prop.sourceSpan);
  3793. }
  3794. return new BoundAttribute(prop.name, prop.type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan, prop.keySpan, prop.valueSpan, i18n);
  3795. };
  3796. BoundAttribute.prototype.visit = function (visitor) {
  3797. return visitor.visitBoundAttribute(this);
  3798. };
  3799. return BoundAttribute;
  3800. }());
  3801. var BoundEvent = /** @class */ (function () {
  3802. function BoundEvent(name, type, handler, target, phase, sourceSpan, handlerSpan, keySpan) {
  3803. this.name = name;
  3804. this.type = type;
  3805. this.handler = handler;
  3806. this.target = target;
  3807. this.phase = phase;
  3808. this.sourceSpan = sourceSpan;
  3809. this.handlerSpan = handlerSpan;
  3810. this.keySpan = keySpan;
  3811. }
  3812. BoundEvent.fromParsedEvent = function (event) {
  3813. var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
  3814. var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
  3815. if (event.keySpan === undefined) {
  3816. throw new Error("Unexpected state: keySpan must be defined for bound event but was not for " + event.name + ": " + event.sourceSpan);
  3817. }
  3818. return new BoundEvent(event.name, event.type, event.handler, target, phase, event.sourceSpan, event.handlerSpan, event.keySpan);
  3819. };
  3820. BoundEvent.prototype.visit = function (visitor) {
  3821. return visitor.visitBoundEvent(this);
  3822. };
  3823. return BoundEvent;
  3824. }());
  3825. var Element = /** @class */ (function () {
  3826. function Element(name, attributes, inputs, outputs, children, references, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  3827. this.name = name;
  3828. this.attributes = attributes;
  3829. this.inputs = inputs;
  3830. this.outputs = outputs;
  3831. this.children = children;
  3832. this.references = references;
  3833. this.sourceSpan = sourceSpan;
  3834. this.startSourceSpan = startSourceSpan;
  3835. this.endSourceSpan = endSourceSpan;
  3836. this.i18n = i18n;
  3837. }
  3838. Element.prototype.visit = function (visitor) {
  3839. return visitor.visitElement(this);
  3840. };
  3841. return Element;
  3842. }());
  3843. var Template = /** @class */ (function () {
  3844. function Template(tagName, attributes, inputs, outputs, templateAttrs, children, references, variables, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  3845. this.tagName = tagName;
  3846. this.attributes = attributes;
  3847. this.inputs = inputs;
  3848. this.outputs = outputs;
  3849. this.templateAttrs = templateAttrs;
  3850. this.children = children;
  3851. this.references = references;
  3852. this.variables = variables;
  3853. this.sourceSpan = sourceSpan;
  3854. this.startSourceSpan = startSourceSpan;
  3855. this.endSourceSpan = endSourceSpan;
  3856. this.i18n = i18n;
  3857. }
  3858. Template.prototype.visit = function (visitor) {
  3859. return visitor.visitTemplate(this);
  3860. };
  3861. return Template;
  3862. }());
  3863. var Content = /** @class */ (function () {
  3864. function Content(selector, attributes, sourceSpan, i18n) {
  3865. this.selector = selector;
  3866. this.attributes = attributes;
  3867. this.sourceSpan = sourceSpan;
  3868. this.i18n = i18n;
  3869. this.name = 'ng-content';
  3870. }
  3871. Content.prototype.visit = function (visitor) {
  3872. return visitor.visitContent(this);
  3873. };
  3874. return Content;
  3875. }());
  3876. var Variable = /** @class */ (function () {
  3877. function Variable(name, value, sourceSpan, keySpan, valueSpan) {
  3878. this.name = name;
  3879. this.value = value;
  3880. this.sourceSpan = sourceSpan;
  3881. this.keySpan = keySpan;
  3882. this.valueSpan = valueSpan;
  3883. }
  3884. Variable.prototype.visit = function (visitor) {
  3885. return visitor.visitVariable(this);
  3886. };
  3887. return Variable;
  3888. }());
  3889. var Reference = /** @class */ (function () {
  3890. function Reference(name, value, sourceSpan, keySpan, valueSpan) {
  3891. this.name = name;
  3892. this.value = value;
  3893. this.sourceSpan = sourceSpan;
  3894. this.keySpan = keySpan;
  3895. this.valueSpan = valueSpan;
  3896. }
  3897. Reference.prototype.visit = function (visitor) {
  3898. return visitor.visitReference(this);
  3899. };
  3900. return Reference;
  3901. }());
  3902. var Icu = /** @class */ (function () {
  3903. function Icu(vars, placeholders, sourceSpan, i18n) {
  3904. this.vars = vars;
  3905. this.placeholders = placeholders;
  3906. this.sourceSpan = sourceSpan;
  3907. this.i18n = i18n;
  3908. }
  3909. Icu.prototype.visit = function (visitor) {
  3910. return visitor.visitIcu(this);
  3911. };
  3912. return Icu;
  3913. }());
  3914. var NullVisitor = /** @class */ (function () {
  3915. function NullVisitor() {
  3916. }
  3917. NullVisitor.prototype.visitElement = function (element) { };
  3918. NullVisitor.prototype.visitTemplate = function (template) { };
  3919. NullVisitor.prototype.visitContent = function (content) { };
  3920. NullVisitor.prototype.visitVariable = function (variable) { };
  3921. NullVisitor.prototype.visitReference = function (reference) { };
  3922. NullVisitor.prototype.visitTextAttribute = function (attribute) { };
  3923. NullVisitor.prototype.visitBoundAttribute = function (attribute) { };
  3924. NullVisitor.prototype.visitBoundEvent = function (attribute) { };
  3925. NullVisitor.prototype.visitText = function (text) { };
  3926. NullVisitor.prototype.visitBoundText = function (text) { };
  3927. NullVisitor.prototype.visitIcu = function (icu) { };
  3928. return NullVisitor;
  3929. }());
  3930. var RecursiveVisitor = /** @class */ (function () {
  3931. function RecursiveVisitor() {
  3932. }
  3933. RecursiveVisitor.prototype.visitElement = function (element) {
  3934. visitAll(this, element.attributes);
  3935. visitAll(this, element.children);
  3936. visitAll(this, element.references);
  3937. };
  3938. RecursiveVisitor.prototype.visitTemplate = function (template) {
  3939. visitAll(this, template.attributes);
  3940. visitAll(this, template.children);
  3941. visitAll(this, template.references);
  3942. visitAll(this, template.variables);
  3943. };
  3944. RecursiveVisitor.prototype.visitContent = function (content) { };
  3945. RecursiveVisitor.prototype.visitVariable = function (variable) { };
  3946. RecursiveVisitor.prototype.visitReference = function (reference) { };
  3947. RecursiveVisitor.prototype.visitTextAttribute = function (attribute) { };
  3948. RecursiveVisitor.prototype.visitBoundAttribute = function (attribute) { };
  3949. RecursiveVisitor.prototype.visitBoundEvent = function (attribute) { };
  3950. RecursiveVisitor.prototype.visitText = function (text) { };
  3951. RecursiveVisitor.prototype.visitBoundText = function (text) { };
  3952. RecursiveVisitor.prototype.visitIcu = function (icu) { };
  3953. return RecursiveVisitor;
  3954. }());
  3955. var TransformVisitor = /** @class */ (function () {
  3956. function TransformVisitor() {
  3957. }
  3958. TransformVisitor.prototype.visitElement = function (element) {
  3959. var newAttributes = transformAll(this, element.attributes);
  3960. var newInputs = transformAll(this, element.inputs);
  3961. var newOutputs = transformAll(this, element.outputs);
  3962. var newChildren = transformAll(this, element.children);
  3963. var newReferences = transformAll(this, element.references);
  3964. if (newAttributes != element.attributes || newInputs != element.inputs ||
  3965. newOutputs != element.outputs || newChildren != element.children ||
  3966. newReferences != element.references) {
  3967. return new Element(element.name, newAttributes, newInputs, newOutputs, newChildren, newReferences, element.sourceSpan, element.startSourceSpan, element.endSourceSpan);
  3968. }
  3969. return element;
  3970. };
  3971. TransformVisitor.prototype.visitTemplate = function (template) {
  3972. var newAttributes = transformAll(this, template.attributes);
  3973. var newInputs = transformAll(this, template.inputs);
  3974. var newOutputs = transformAll(this, template.outputs);
  3975. var newTemplateAttrs = transformAll(this, template.templateAttrs);
  3976. var newChildren = transformAll(this, template.children);
  3977. var newReferences = transformAll(this, template.references);
  3978. var newVariables = transformAll(this, template.variables);
  3979. if (newAttributes != template.attributes || newInputs != template.inputs ||
  3980. newOutputs != template.outputs || newTemplateAttrs != template.templateAttrs ||
  3981. newChildren != template.children || newReferences != template.references ||
  3982. newVariables != template.variables) {
  3983. return new Template(template.tagName, newAttributes, newInputs, newOutputs, newTemplateAttrs, newChildren, newReferences, newVariables, template.sourceSpan, template.startSourceSpan, template.endSourceSpan);
  3984. }
  3985. return template;
  3986. };
  3987. TransformVisitor.prototype.visitContent = function (content) {
  3988. return content;
  3989. };
  3990. TransformVisitor.prototype.visitVariable = function (variable) {
  3991. return variable;
  3992. };
  3993. TransformVisitor.prototype.visitReference = function (reference) {
  3994. return reference;
  3995. };
  3996. TransformVisitor.prototype.visitTextAttribute = function (attribute) {
  3997. return attribute;
  3998. };
  3999. TransformVisitor.prototype.visitBoundAttribute = function (attribute) {
  4000. return attribute;
  4001. };
  4002. TransformVisitor.prototype.visitBoundEvent = function (attribute) {
  4003. return attribute;
  4004. };
  4005. TransformVisitor.prototype.visitText = function (text) {
  4006. return text;
  4007. };
  4008. TransformVisitor.prototype.visitBoundText = function (text) {
  4009. return text;
  4010. };
  4011. TransformVisitor.prototype.visitIcu = function (icu) {
  4012. return icu;
  4013. };
  4014. return TransformVisitor;
  4015. }());
  4016. function visitAll(visitor, nodes) {
  4017. var e_1, _a, e_2, _b;
  4018. var result = [];
  4019. if (visitor.visit) {
  4020. try {
  4021. for (var nodes_1 = __values(nodes), nodes_1_1 = nodes_1.next(); !nodes_1_1.done; nodes_1_1 = nodes_1.next()) {
  4022. var node = nodes_1_1.value;
  4023. var newNode = visitor.visit(node) || node.visit(visitor);
  4024. }
  4025. }
  4026. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  4027. finally {
  4028. try {
  4029. if (nodes_1_1 && !nodes_1_1.done && (_a = nodes_1.return)) _a.call(nodes_1);
  4030. }
  4031. finally { if (e_1) throw e_1.error; }
  4032. }
  4033. }
  4034. else {
  4035. try {
  4036. for (var nodes_2 = __values(nodes), nodes_2_1 = nodes_2.next(); !nodes_2_1.done; nodes_2_1 = nodes_2.next()) {
  4037. var node = nodes_2_1.value;
  4038. var newNode = node.visit(visitor);
  4039. if (newNode) {
  4040. result.push(newNode);
  4041. }
  4042. }
  4043. }
  4044. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  4045. finally {
  4046. try {
  4047. if (nodes_2_1 && !nodes_2_1.done && (_b = nodes_2.return)) _b.call(nodes_2);
  4048. }
  4049. finally { if (e_2) throw e_2.error; }
  4050. }
  4051. }
  4052. return result;
  4053. }
  4054. function transformAll(visitor, nodes) {
  4055. var e_3, _a;
  4056. var result = [];
  4057. var changed = false;
  4058. try {
  4059. for (var nodes_3 = __values(nodes), nodes_3_1 = nodes_3.next(); !nodes_3_1.done; nodes_3_1 = nodes_3.next()) {
  4060. var node = nodes_3_1.value;
  4061. var newNode = node.visit(visitor);
  4062. if (newNode) {
  4063. result.push(newNode);
  4064. }
  4065. changed = changed || newNode != node;
  4066. }
  4067. }
  4068. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  4069. finally {
  4070. try {
  4071. if (nodes_3_1 && !nodes_3_1.done && (_a = nodes_3.return)) _a.call(nodes_3);
  4072. }
  4073. finally { if (e_3) throw e_3.error; }
  4074. }
  4075. return changed ? result : nodes;
  4076. }
  4077. /**
  4078. * @license
  4079. * Copyright Google LLC All Rights Reserved.
  4080. *
  4081. * Use of this source code is governed by an MIT-style license that can be
  4082. * found in the LICENSE file at https://angular.io/license
  4083. */
  4084. var Message = /** @class */ (function () {
  4085. /**
  4086. * @param nodes message AST
  4087. * @param placeholders maps placeholder names to static content and their source spans
  4088. * @param placeholderToMessage maps placeholder names to messages (used for nested ICU messages)
  4089. * @param meaning
  4090. * @param description
  4091. * @param customId
  4092. */
  4093. function Message(nodes, placeholders, placeholderToMessage, meaning, description, customId) {
  4094. this.nodes = nodes;
  4095. this.placeholders = placeholders;
  4096. this.placeholderToMessage = placeholderToMessage;
  4097. this.meaning = meaning;
  4098. this.description = description;
  4099. this.customId = customId;
  4100. this.id = this.customId;
  4101. /** The ids to use if there are no custom id and if `i18nLegacyMessageIdFormat` is not empty */
  4102. this.legacyIds = [];
  4103. if (nodes.length) {
  4104. this.sources = [{
  4105. filePath: nodes[0].sourceSpan.start.file.url,
  4106. startLine: nodes[0].sourceSpan.start.line + 1,
  4107. startCol: nodes[0].sourceSpan.start.col + 1,
  4108. endLine: nodes[nodes.length - 1].sourceSpan.end.line + 1,
  4109. endCol: nodes[0].sourceSpan.start.col + 1
  4110. }];
  4111. }
  4112. else {
  4113. this.sources = [];
  4114. }
  4115. }
  4116. return Message;
  4117. }());
  4118. var Text$1 = /** @class */ (function () {
  4119. function Text(value, sourceSpan) {
  4120. this.value = value;
  4121. this.sourceSpan = sourceSpan;
  4122. }
  4123. Text.prototype.visit = function (visitor, context) {
  4124. return visitor.visitText(this, context);
  4125. };
  4126. return Text;
  4127. }());
  4128. // TODO(vicb): do we really need this node (vs an array) ?
  4129. var Container = /** @class */ (function () {
  4130. function Container(children, sourceSpan) {
  4131. this.children = children;
  4132. this.sourceSpan = sourceSpan;
  4133. }
  4134. Container.prototype.visit = function (visitor, context) {
  4135. return visitor.visitContainer(this, context);
  4136. };
  4137. return Container;
  4138. }());
  4139. var Icu$1 = /** @class */ (function () {
  4140. function Icu(expression, type, cases, sourceSpan) {
  4141. this.expression = expression;
  4142. this.type = type;
  4143. this.cases = cases;
  4144. this.sourceSpan = sourceSpan;
  4145. }
  4146. Icu.prototype.visit = function (visitor, context) {
  4147. return visitor.visitIcu(this, context);
  4148. };
  4149. return Icu;
  4150. }());
  4151. var TagPlaceholder = /** @class */ (function () {
  4152. function TagPlaceholder(tag, attrs, startName, closeName, children, isVoid,
  4153. // TODO sourceSpan should cover all (we need a startSourceSpan and endSourceSpan)
  4154. sourceSpan, startSourceSpan, endSourceSpan) {
  4155. this.tag = tag;
  4156. this.attrs = attrs;
  4157. this.startName = startName;
  4158. this.closeName = closeName;
  4159. this.children = children;
  4160. this.isVoid = isVoid;
  4161. this.sourceSpan = sourceSpan;
  4162. this.startSourceSpan = startSourceSpan;
  4163. this.endSourceSpan = endSourceSpan;
  4164. }
  4165. TagPlaceholder.prototype.visit = function (visitor, context) {
  4166. return visitor.visitTagPlaceholder(this, context);
  4167. };
  4168. return TagPlaceholder;
  4169. }());
  4170. var Placeholder = /** @class */ (function () {
  4171. function Placeholder(value, name, sourceSpan) {
  4172. this.value = value;
  4173. this.name = name;
  4174. this.sourceSpan = sourceSpan;
  4175. }
  4176. Placeholder.prototype.visit = function (visitor, context) {
  4177. return visitor.visitPlaceholder(this, context);
  4178. };
  4179. return Placeholder;
  4180. }());
  4181. var IcuPlaceholder = /** @class */ (function () {
  4182. function IcuPlaceholder(value, name, sourceSpan) {
  4183. this.value = value;
  4184. this.name = name;
  4185. this.sourceSpan = sourceSpan;
  4186. }
  4187. IcuPlaceholder.prototype.visit = function (visitor, context) {
  4188. return visitor.visitIcuPlaceholder(this, context);
  4189. };
  4190. return IcuPlaceholder;
  4191. }());
  4192. // Clone the AST
  4193. var CloneVisitor = /** @class */ (function () {
  4194. function CloneVisitor() {
  4195. }
  4196. CloneVisitor.prototype.visitText = function (text, context) {
  4197. return new Text$1(text.value, text.sourceSpan);
  4198. };
  4199. CloneVisitor.prototype.visitContainer = function (container, context) {
  4200. var _this = this;
  4201. var children = container.children.map(function (n) { return n.visit(_this, context); });
  4202. return new Container(children, container.sourceSpan);
  4203. };
  4204. CloneVisitor.prototype.visitIcu = function (icu, context) {
  4205. var _this = this;
  4206. var cases = {};
  4207. Object.keys(icu.cases).forEach(function (key) { return cases[key] = icu.cases[key].visit(_this, context); });
  4208. var msg = new Icu$1(icu.expression, icu.type, cases, icu.sourceSpan);
  4209. msg.expressionPlaceholder = icu.expressionPlaceholder;
  4210. return msg;
  4211. };
  4212. CloneVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  4213. var _this = this;
  4214. var children = ph.children.map(function (n) { return n.visit(_this, context); });
  4215. return new TagPlaceholder(ph.tag, ph.attrs, ph.startName, ph.closeName, children, ph.isVoid, ph.sourceSpan, ph.startSourceSpan, ph.endSourceSpan);
  4216. };
  4217. CloneVisitor.prototype.visitPlaceholder = function (ph, context) {
  4218. return new Placeholder(ph.value, ph.name, ph.sourceSpan);
  4219. };
  4220. CloneVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  4221. return new IcuPlaceholder(ph.value, ph.name, ph.sourceSpan);
  4222. };
  4223. return CloneVisitor;
  4224. }());
  4225. // Visit all the nodes recursively
  4226. var RecurseVisitor = /** @class */ (function () {
  4227. function RecurseVisitor() {
  4228. }
  4229. RecurseVisitor.prototype.visitText = function (text, context) { };
  4230. RecurseVisitor.prototype.visitContainer = function (container, context) {
  4231. var _this = this;
  4232. container.children.forEach(function (child) { return child.visit(_this); });
  4233. };
  4234. RecurseVisitor.prototype.visitIcu = function (icu, context) {
  4235. var _this = this;
  4236. Object.keys(icu.cases).forEach(function (k) {
  4237. icu.cases[k].visit(_this);
  4238. });
  4239. };
  4240. RecurseVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  4241. var _this = this;
  4242. ph.children.forEach(function (child) { return child.visit(_this); });
  4243. };
  4244. RecurseVisitor.prototype.visitPlaceholder = function (ph, context) { };
  4245. RecurseVisitor.prototype.visitIcuPlaceholder = function (ph, context) { };
  4246. return RecurseVisitor;
  4247. }());
  4248. /**
  4249. * @license
  4250. * Copyright Google LLC All Rights Reserved.
  4251. *
  4252. * Use of this source code is governed by an MIT-style license that can be
  4253. * found in the LICENSE file at https://angular.io/license
  4254. */
  4255. /**
  4256. * Represents a big integer using a buffer of its individual digits, with the least significant
  4257. * digit stored at the beginning of the array (little endian).
  4258. *
  4259. * For performance reasons, each instance is mutable. The addition operation can be done in-place
  4260. * to reduce memory pressure of allocation for the digits array.
  4261. */
  4262. var BigInteger = /** @class */ (function () {
  4263. /**
  4264. * Creates a big integer using its individual digits in little endian storage.
  4265. */
  4266. function BigInteger(digits) {
  4267. this.digits = digits;
  4268. }
  4269. BigInteger.zero = function () {
  4270. return new BigInteger([0]);
  4271. };
  4272. BigInteger.one = function () {
  4273. return new BigInteger([1]);
  4274. };
  4275. /**
  4276. * Creates a clone of this instance.
  4277. */
  4278. BigInteger.prototype.clone = function () {
  4279. return new BigInteger(this.digits.slice());
  4280. };
  4281. /**
  4282. * Returns a new big integer with the sum of `this` and `other` as its value. This does not mutate
  4283. * `this` but instead returns a new instance, unlike `addToSelf`.
  4284. */
  4285. BigInteger.prototype.add = function (other) {
  4286. var result = this.clone();
  4287. result.addToSelf(other);
  4288. return result;
  4289. };
  4290. /**
  4291. * Adds `other` to the instance itself, thereby mutating its value.
  4292. */
  4293. BigInteger.prototype.addToSelf = function (other) {
  4294. var maxNrOfDigits = Math.max(this.digits.length, other.digits.length);
  4295. var carry = 0;
  4296. for (var i = 0; i < maxNrOfDigits; i++) {
  4297. var digitSum = carry;
  4298. if (i < this.digits.length) {
  4299. digitSum += this.digits[i];
  4300. }
  4301. if (i < other.digits.length) {
  4302. digitSum += other.digits[i];
  4303. }
  4304. if (digitSum >= 10) {
  4305. this.digits[i] = digitSum - 10;
  4306. carry = 1;
  4307. }
  4308. else {
  4309. this.digits[i] = digitSum;
  4310. carry = 0;
  4311. }
  4312. }
  4313. // Apply a remaining carry if needed.
  4314. if (carry > 0) {
  4315. this.digits[maxNrOfDigits] = 1;
  4316. }
  4317. };
  4318. /**
  4319. * Builds the decimal string representation of the big integer. As this is stored in
  4320. * little endian, the digits are concatenated in reverse order.
  4321. */
  4322. BigInteger.prototype.toString = function () {
  4323. var res = '';
  4324. for (var i = this.digits.length - 1; i >= 0; i--) {
  4325. res += this.digits[i];
  4326. }
  4327. return res;
  4328. };
  4329. return BigInteger;
  4330. }());
  4331. /**
  4332. * Represents a big integer which is optimized for multiplication operations, as its power-of-twos
  4333. * are memoized. See `multiplyBy()` for details on the multiplication algorithm.
  4334. */
  4335. var BigIntForMultiplication = /** @class */ (function () {
  4336. function BigIntForMultiplication(value) {
  4337. this.powerOfTwos = [value];
  4338. }
  4339. /**
  4340. * Returns the big integer itself.
  4341. */
  4342. BigIntForMultiplication.prototype.getValue = function () {
  4343. return this.powerOfTwos[0];
  4344. };
  4345. /**
  4346. * Computes the value for `num * b`, where `num` is a JS number and `b` is a big integer. The
  4347. * value for `b` is represented by a storage model that is optimized for this computation.
  4348. *
  4349. * This operation is implemented in N(log2(num)) by continuous halving of the number, where the
  4350. * least-significant bit (LSB) is tested in each iteration. If the bit is set, the bit's index is
  4351. * used as exponent into the power-of-two multiplication of `b`.
  4352. *
  4353. * As an example, consider the multiplication num=42, b=1337. In binary 42 is 0b00101010 and the
  4354. * algorithm unrolls into the following iterations:
  4355. *
  4356. * Iteration | num | LSB | b * 2^iter | Add? | product
  4357. * -----------|------------|------|------------|------|--------
  4358. * 0 | 0b00101010 | 0 | 1337 | No | 0
  4359. * 1 | 0b00010101 | 1 | 2674 | Yes | 2674
  4360. * 2 | 0b00001010 | 0 | 5348 | No | 2674
  4361. * 3 | 0b00000101 | 1 | 10696 | Yes | 13370
  4362. * 4 | 0b00000010 | 0 | 21392 | No | 13370
  4363. * 5 | 0b00000001 | 1 | 42784 | Yes | 56154
  4364. * 6 | 0b00000000 | 0 | 85568 | No | 56154
  4365. *
  4366. * The computed product of 56154 is indeed the correct result.
  4367. *
  4368. * The `BigIntForMultiplication` representation for a big integer provides memoized access to the
  4369. * power-of-two values to reduce the workload in computing those values.
  4370. */
  4371. BigIntForMultiplication.prototype.multiplyBy = function (num) {
  4372. var product = BigInteger.zero();
  4373. this.multiplyByAndAddTo(num, product);
  4374. return product;
  4375. };
  4376. /**
  4377. * See `multiplyBy()` for details. This function allows for the computed product to be added
  4378. * directly to the provided result big integer.
  4379. */
  4380. BigIntForMultiplication.prototype.multiplyByAndAddTo = function (num, result) {
  4381. for (var exponent = 0; num !== 0; num = num >>> 1, exponent++) {
  4382. if (num & 1) {
  4383. var value = this.getMultipliedByPowerOfTwo(exponent);
  4384. result.addToSelf(value);
  4385. }
  4386. }
  4387. };
  4388. /**
  4389. * Computes and memoizes the big integer value for `this.number * 2^exponent`.
  4390. */
  4391. BigIntForMultiplication.prototype.getMultipliedByPowerOfTwo = function (exponent) {
  4392. // Compute the powers up until the requested exponent, where each value is computed from its
  4393. // predecessor. This is simple as `this.number * 2^(exponent - 1)` only has to be doubled (i.e.
  4394. // added to itself) to reach `this.number * 2^exponent`.
  4395. for (var i = this.powerOfTwos.length; i <= exponent; i++) {
  4396. var previousPower = this.powerOfTwos[i - 1];
  4397. this.powerOfTwos[i] = previousPower.add(previousPower);
  4398. }
  4399. return this.powerOfTwos[exponent];
  4400. };
  4401. return BigIntForMultiplication;
  4402. }());
  4403. /**
  4404. * Represents an exponentiation operation for the provided base, of which exponents are computed and
  4405. * memoized. The results are represented by a `BigIntForMultiplication` which is tailored for
  4406. * multiplication operations by memoizing the power-of-twos. This effectively results in a matrix
  4407. * representation that is lazily computed upon request.
  4408. */
  4409. var BigIntExponentiation = /** @class */ (function () {
  4410. function BigIntExponentiation(base) {
  4411. this.base = base;
  4412. this.exponents = [new BigIntForMultiplication(BigInteger.one())];
  4413. }
  4414. /**
  4415. * Compute the value for `this.base^exponent`, resulting in a big integer that is optimized for
  4416. * further multiplication operations.
  4417. */
  4418. BigIntExponentiation.prototype.toThePowerOf = function (exponent) {
  4419. // Compute the results up until the requested exponent, where every value is computed from its
  4420. // predecessor. This is because `this.base^(exponent - 1)` only has to be multiplied by `base`
  4421. // to reach `this.base^exponent`.
  4422. for (var i = this.exponents.length; i <= exponent; i++) {
  4423. var value = this.exponents[i - 1].multiplyBy(this.base);
  4424. this.exponents[i] = new BigIntForMultiplication(value);
  4425. }
  4426. return this.exponents[exponent];
  4427. };
  4428. return BigIntExponentiation;
  4429. }());
  4430. /**
  4431. * Return the message id or compute it using the XLIFF1 digest.
  4432. */
  4433. function digest(message) {
  4434. return message.id || computeDigest(message);
  4435. }
  4436. /**
  4437. * Compute the message id using the XLIFF1 digest.
  4438. */
  4439. function computeDigest(message) {
  4440. return sha1(serializeNodes(message.nodes).join('') + ("[" + message.meaning + "]"));
  4441. }
  4442. /**
  4443. * Return the message id or compute it using the XLIFF2/XMB/$localize digest.
  4444. */
  4445. function decimalDigest(message) {
  4446. return message.id || computeDecimalDigest(message);
  4447. }
  4448. /**
  4449. * Compute the message id using the XLIFF2/XMB/$localize digest.
  4450. */
  4451. function computeDecimalDigest(message) {
  4452. var visitor = new _SerializerIgnoreIcuExpVisitor();
  4453. var parts = message.nodes.map(function (a) { return a.visit(visitor, null); });
  4454. return computeMsgId(parts.join(''), message.meaning);
  4455. }
  4456. /**
  4457. * Serialize the i18n ast to something xml-like in order to generate an UID.
  4458. *
  4459. * The visitor is also used in the i18n parser tests
  4460. *
  4461. * @internal
  4462. */
  4463. var _SerializerVisitor = /** @class */ (function () {
  4464. function _SerializerVisitor() {
  4465. }
  4466. _SerializerVisitor.prototype.visitText = function (text, context) {
  4467. return text.value;
  4468. };
  4469. _SerializerVisitor.prototype.visitContainer = function (container, context) {
  4470. var _this = this;
  4471. return "[" + container.children.map(function (child) { return child.visit(_this); }).join(', ') + "]";
  4472. };
  4473. _SerializerVisitor.prototype.visitIcu = function (icu, context) {
  4474. var _this = this;
  4475. var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  4476. return "{" + icu.expression + ", " + icu.type + ", " + strCases.join(', ') + "}";
  4477. };
  4478. _SerializerVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  4479. var _this = this;
  4480. return ph.isVoid ?
  4481. "<ph tag name=\"" + ph.startName + "\"/>" :
  4482. "<ph tag name=\"" + ph.startName + "\">" + ph.children.map(function (child) { return child.visit(_this); }).join(', ') + "</ph name=\"" + ph.closeName + "\">";
  4483. };
  4484. _SerializerVisitor.prototype.visitPlaceholder = function (ph, context) {
  4485. return ph.value ? "<ph name=\"" + ph.name + "\">" + ph.value + "</ph>" : "<ph name=\"" + ph.name + "\"/>";
  4486. };
  4487. _SerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  4488. return "<ph icu name=\"" + ph.name + "\">" + ph.value.visit(this) + "</ph>";
  4489. };
  4490. return _SerializerVisitor;
  4491. }());
  4492. var serializerVisitor = new _SerializerVisitor();
  4493. function serializeNodes(nodes) {
  4494. return nodes.map(function (a) { return a.visit(serializerVisitor, null); });
  4495. }
  4496. /**
  4497. * Serialize the i18n ast to something xml-like in order to generate an UID.
  4498. *
  4499. * Ignore the ICU expressions so that message IDs stays identical if only the expression changes.
  4500. *
  4501. * @internal
  4502. */
  4503. var _SerializerIgnoreIcuExpVisitor = /** @class */ (function (_super) {
  4504. __extends(_SerializerIgnoreIcuExpVisitor, _super);
  4505. function _SerializerIgnoreIcuExpVisitor() {
  4506. return _super !== null && _super.apply(this, arguments) || this;
  4507. }
  4508. _SerializerIgnoreIcuExpVisitor.prototype.visitIcu = function (icu, context) {
  4509. var _this = this;
  4510. var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  4511. // Do not take the expression into account
  4512. return "{" + icu.type + ", " + strCases.join(', ') + "}";
  4513. };
  4514. return _SerializerIgnoreIcuExpVisitor;
  4515. }(_SerializerVisitor));
  4516. /**
  4517. * Compute the SHA1 of the given string
  4518. *
  4519. * see https://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
  4520. *
  4521. * WARNING: this function has not been designed not tested with security in mind.
  4522. * DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT.
  4523. */
  4524. function sha1(str) {
  4525. var utf8 = utf8Encode(str);
  4526. var words32 = bytesToWords32(utf8, Endian.Big);
  4527. var len = utf8.length * 8;
  4528. var w = newArray(80);
  4529. var a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476, e = 0xc3d2e1f0;
  4530. words32[len >> 5] |= 0x80 << (24 - len % 32);
  4531. words32[((len + 64 >> 9) << 4) + 15] = len;
  4532. for (var i = 0; i < words32.length; i += 16) {
  4533. var h0 = a, h1 = b, h2 = c, h3 = d, h4 = e;
  4534. for (var j = 0; j < 80; j++) {
  4535. if (j < 16) {
  4536. w[j] = words32[i + j];
  4537. }
  4538. else {
  4539. w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
  4540. }
  4541. var fkVal = fk(j, b, c, d);
  4542. var f = fkVal[0];
  4543. var k = fkVal[1];
  4544. var temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
  4545. e = d;
  4546. d = c;
  4547. c = rol32(b, 30);
  4548. b = a;
  4549. a = temp;
  4550. }
  4551. a = add32(a, h0);
  4552. b = add32(b, h1);
  4553. c = add32(c, h2);
  4554. d = add32(d, h3);
  4555. e = add32(e, h4);
  4556. }
  4557. return bytesToHexString(words32ToByteString([a, b, c, d, e]));
  4558. }
  4559. function fk(index, b, c, d) {
  4560. if (index < 20) {
  4561. return [(b & c) | (~b & d), 0x5a827999];
  4562. }
  4563. if (index < 40) {
  4564. return [b ^ c ^ d, 0x6ed9eba1];
  4565. }
  4566. if (index < 60) {
  4567. return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc];
  4568. }
  4569. return [b ^ c ^ d, 0xca62c1d6];
  4570. }
  4571. /**
  4572. * Compute the fingerprint of the given string
  4573. *
  4574. * The output is 64 bit number encoded as a decimal string
  4575. *
  4576. * based on:
  4577. * https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
  4578. */
  4579. function fingerprint(str) {
  4580. var utf8 = utf8Encode(str);
  4581. var hi = hash32(utf8, 0);
  4582. var lo = hash32(utf8, 102072);
  4583. if (hi == 0 && (lo == 0 || lo == 1)) {
  4584. hi = hi ^ 0x130f9bef;
  4585. lo = lo ^ -0x6b5f56d8;
  4586. }
  4587. return [hi, lo];
  4588. }
  4589. function computeMsgId(msg, meaning) {
  4590. if (meaning === void 0) { meaning = ''; }
  4591. var msgFingerprint = fingerprint(msg);
  4592. if (meaning) {
  4593. var meaningFingerprint = fingerprint(meaning);
  4594. msgFingerprint = add64(rol64(msgFingerprint, 1), meaningFingerprint);
  4595. }
  4596. var hi = msgFingerprint[0];
  4597. var lo = msgFingerprint[1];
  4598. return wordsToDecimalString(hi & 0x7fffffff, lo);
  4599. }
  4600. function hash32(bytes, c) {
  4601. var a = 0x9e3779b9, b = 0x9e3779b9;
  4602. var i;
  4603. var len = bytes.length;
  4604. for (i = 0; i + 12 <= len; i += 12) {
  4605. a = add32(a, wordAt(bytes, i, Endian.Little));
  4606. b = add32(b, wordAt(bytes, i + 4, Endian.Little));
  4607. c = add32(c, wordAt(bytes, i + 8, Endian.Little));
  4608. var res = mix(a, b, c);
  4609. a = res[0], b = res[1], c = res[2];
  4610. }
  4611. a = add32(a, wordAt(bytes, i, Endian.Little));
  4612. b = add32(b, wordAt(bytes, i + 4, Endian.Little));
  4613. // the first byte of c is reserved for the length
  4614. c = add32(c, len);
  4615. c = add32(c, wordAt(bytes, i + 8, Endian.Little) << 8);
  4616. return mix(a, b, c)[2];
  4617. }
  4618. // clang-format off
  4619. function mix(a, b, c) {
  4620. a = sub32(a, b);
  4621. a = sub32(a, c);
  4622. a ^= c >>> 13;
  4623. b = sub32(b, c);
  4624. b = sub32(b, a);
  4625. b ^= a << 8;
  4626. c = sub32(c, a);
  4627. c = sub32(c, b);
  4628. c ^= b >>> 13;
  4629. a = sub32(a, b);
  4630. a = sub32(a, c);
  4631. a ^= c >>> 12;
  4632. b = sub32(b, c);
  4633. b = sub32(b, a);
  4634. b ^= a << 16;
  4635. c = sub32(c, a);
  4636. c = sub32(c, b);
  4637. c ^= b >>> 5;
  4638. a = sub32(a, b);
  4639. a = sub32(a, c);
  4640. a ^= c >>> 3;
  4641. b = sub32(b, c);
  4642. b = sub32(b, a);
  4643. b ^= a << 10;
  4644. c = sub32(c, a);
  4645. c = sub32(c, b);
  4646. c ^= b >>> 15;
  4647. return [a, b, c];
  4648. }
  4649. // clang-format on
  4650. // Utils
  4651. var Endian;
  4652. (function (Endian) {
  4653. Endian[Endian["Little"] = 0] = "Little";
  4654. Endian[Endian["Big"] = 1] = "Big";
  4655. })(Endian || (Endian = {}));
  4656. function add32(a, b) {
  4657. return add32to64(a, b)[1];
  4658. }
  4659. function add32to64(a, b) {
  4660. var low = (a & 0xffff) + (b & 0xffff);
  4661. var high = (a >>> 16) + (b >>> 16) + (low >>> 16);
  4662. return [high >>> 16, (high << 16) | (low & 0xffff)];
  4663. }
  4664. function add64(a, b) {
  4665. var ah = a[0], al = a[1];
  4666. var bh = b[0], bl = b[1];
  4667. var result = add32to64(al, bl);
  4668. var carry = result[0];
  4669. var l = result[1];
  4670. var h = add32(add32(ah, bh), carry);
  4671. return [h, l];
  4672. }
  4673. function sub32(a, b) {
  4674. var low = (a & 0xffff) - (b & 0xffff);
  4675. var high = (a >> 16) - (b >> 16) + (low >> 16);
  4676. return (high << 16) | (low & 0xffff);
  4677. }
  4678. // Rotate a 32b number left `count` position
  4679. function rol32(a, count) {
  4680. return (a << count) | (a >>> (32 - count));
  4681. }
  4682. // Rotate a 64b number left `count` position
  4683. function rol64(num, count) {
  4684. var hi = num[0], lo = num[1];
  4685. var h = (hi << count) | (lo >>> (32 - count));
  4686. var l = (lo << count) | (hi >>> (32 - count));
  4687. return [h, l];
  4688. }
  4689. function bytesToWords32(bytes, endian) {
  4690. var size = (bytes.length + 3) >>> 2;
  4691. var words32 = [];
  4692. for (var i = 0; i < size; i++) {
  4693. words32[i] = wordAt(bytes, i * 4, endian);
  4694. }
  4695. return words32;
  4696. }
  4697. function byteAt(bytes, index) {
  4698. return index >= bytes.length ? 0 : bytes[index];
  4699. }
  4700. function wordAt(bytes, index, endian) {
  4701. var word = 0;
  4702. if (endian === Endian.Big) {
  4703. for (var i = 0; i < 4; i++) {
  4704. word += byteAt(bytes, index + i) << (24 - 8 * i);
  4705. }
  4706. }
  4707. else {
  4708. for (var i = 0; i < 4; i++) {
  4709. word += byteAt(bytes, index + i) << 8 * i;
  4710. }
  4711. }
  4712. return word;
  4713. }
  4714. function words32ToByteString(words32) {
  4715. return words32.reduce(function (bytes, word) { return bytes.concat(word32ToByteString(word)); }, []);
  4716. }
  4717. function word32ToByteString(word) {
  4718. var bytes = [];
  4719. for (var i = 0; i < 4; i++) {
  4720. bytes.push((word >>> 8 * (3 - i)) & 0xff);
  4721. }
  4722. return bytes;
  4723. }
  4724. function bytesToHexString(bytes) {
  4725. var hex = '';
  4726. for (var i = 0; i < bytes.length; i++) {
  4727. var b = byteAt(bytes, i);
  4728. hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16);
  4729. }
  4730. return hex.toLowerCase();
  4731. }
  4732. /**
  4733. * Create a shared exponentiation pool for base-256 computations. This shared pool provides memoized
  4734. * power-of-256 results with memoized power-of-two computations for efficient multiplication.
  4735. *
  4736. * For our purposes, this can be safely stored as a global without memory concerns. The reason is
  4737. * that we encode two words, so only need the 0th (for the low word) and 4th (for the high word)
  4738. * exponent.
  4739. */
  4740. var base256 = new BigIntExponentiation(256);
  4741. /**
  4742. * Represents two 32-bit words as a single decimal number. This requires a big integer storage
  4743. * model as JS numbers are not accurate enough to represent the 64-bit number.
  4744. *
  4745. * Based on https://www.danvk.org/hex2dec.html
  4746. */
  4747. function wordsToDecimalString(hi, lo) {
  4748. // Encode the four bytes in lo in the lower digits of the decimal number.
  4749. // Note: the multiplication results in lo itself but represented by a big integer using its
  4750. // decimal digits.
  4751. var decimal = base256.toThePowerOf(0).multiplyBy(lo);
  4752. // Encode the four bytes in hi above the four lo bytes. lo is a maximum of (2^8)^4, which is why
  4753. // this multiplication factor is applied.
  4754. base256.toThePowerOf(4).multiplyByAndAddTo(hi, decimal);
  4755. return decimal.toString();
  4756. }
  4757. var Serializer = /** @class */ (function () {
  4758. function Serializer() {
  4759. }
  4760. // Creates a name mapper, see `PlaceholderMapper`
  4761. // Returning `null` means that no name mapping is used.
  4762. Serializer.prototype.createNameMapper = function (message) {
  4763. return null;
  4764. };
  4765. return Serializer;
  4766. }());
  4767. /**
  4768. * A simple mapper that take a function to transform an internal name to a public name
  4769. */
  4770. var SimplePlaceholderMapper = /** @class */ (function (_super) {
  4771. __extends(SimplePlaceholderMapper, _super);
  4772. // create a mapping from the message
  4773. function SimplePlaceholderMapper(message, mapName) {
  4774. var _this = _super.call(this) || this;
  4775. _this.mapName = mapName;
  4776. _this.internalToPublic = {};
  4777. _this.publicToNextId = {};
  4778. _this.publicToInternal = {};
  4779. message.nodes.forEach(function (node) { return node.visit(_this); });
  4780. return _this;
  4781. }
  4782. SimplePlaceholderMapper.prototype.toPublicName = function (internalName) {
  4783. return this.internalToPublic.hasOwnProperty(internalName) ?
  4784. this.internalToPublic[internalName] :
  4785. null;
  4786. };
  4787. SimplePlaceholderMapper.prototype.toInternalName = function (publicName) {
  4788. return this.publicToInternal.hasOwnProperty(publicName) ? this.publicToInternal[publicName] :
  4789. null;
  4790. };
  4791. SimplePlaceholderMapper.prototype.visitText = function (text, context) {
  4792. return null;
  4793. };
  4794. SimplePlaceholderMapper.prototype.visitTagPlaceholder = function (ph, context) {
  4795. this.visitPlaceholderName(ph.startName);
  4796. _super.prototype.visitTagPlaceholder.call(this, ph, context);
  4797. this.visitPlaceholderName(ph.closeName);
  4798. };
  4799. SimplePlaceholderMapper.prototype.visitPlaceholder = function (ph, context) {
  4800. this.visitPlaceholderName(ph.name);
  4801. };
  4802. SimplePlaceholderMapper.prototype.visitIcuPlaceholder = function (ph, context) {
  4803. this.visitPlaceholderName(ph.name);
  4804. };
  4805. // XMB placeholders could only contains A-Z, 0-9 and _
  4806. SimplePlaceholderMapper.prototype.visitPlaceholderName = function (internalName) {
  4807. if (!internalName || this.internalToPublic.hasOwnProperty(internalName)) {
  4808. return;
  4809. }
  4810. var publicName = this.mapName(internalName);
  4811. if (this.publicToInternal.hasOwnProperty(publicName)) {
  4812. // Create a new XMB when it has already been used
  4813. var nextId = this.publicToNextId[publicName];
  4814. this.publicToNextId[publicName] = nextId + 1;
  4815. publicName = publicName + "_" + nextId;
  4816. }
  4817. else {
  4818. this.publicToNextId[publicName] = 1;
  4819. }
  4820. this.internalToPublic[internalName] = publicName;
  4821. this.publicToInternal[publicName] = internalName;
  4822. };
  4823. return SimplePlaceholderMapper;
  4824. }(RecurseVisitor));
  4825. /**
  4826. * @license
  4827. * Copyright Google LLC All Rights Reserved.
  4828. *
  4829. * Use of this source code is governed by an MIT-style license that can be
  4830. * found in the LICENSE file at https://angular.io/license
  4831. */
  4832. var _Visitor = /** @class */ (function () {
  4833. function _Visitor() {
  4834. }
  4835. _Visitor.prototype.visitTag = function (tag) {
  4836. var _this = this;
  4837. var strAttrs = this._serializeAttributes(tag.attrs);
  4838. if (tag.children.length == 0) {
  4839. return "<" + tag.name + strAttrs + "/>";
  4840. }
  4841. var strChildren = tag.children.map(function (node) { return node.visit(_this); });
  4842. return "<" + tag.name + strAttrs + ">" + strChildren.join('') + "</" + tag.name + ">";
  4843. };
  4844. _Visitor.prototype.visitText = function (text) {
  4845. return text.value;
  4846. };
  4847. _Visitor.prototype.visitDeclaration = function (decl) {
  4848. return "<?xml" + this._serializeAttributes(decl.attrs) + " ?>";
  4849. };
  4850. _Visitor.prototype._serializeAttributes = function (attrs) {
  4851. var strAttrs = Object.keys(attrs).map(function (name) { return name + "=\"" + attrs[name] + "\""; }).join(' ');
  4852. return strAttrs.length > 0 ? ' ' + strAttrs : '';
  4853. };
  4854. _Visitor.prototype.visitDoctype = function (doctype) {
  4855. return "<!DOCTYPE " + doctype.rootTag + " [\n" + doctype.dtd + "\n]>";
  4856. };
  4857. return _Visitor;
  4858. }());
  4859. var _visitor = new _Visitor();
  4860. function serialize(nodes) {
  4861. return nodes.map(function (node) { return node.visit(_visitor); }).join('');
  4862. }
  4863. var Declaration = /** @class */ (function () {
  4864. function Declaration(unescapedAttrs) {
  4865. var _this = this;
  4866. this.attrs = {};
  4867. Object.keys(unescapedAttrs).forEach(function (k) {
  4868. _this.attrs[k] = escapeXml(unescapedAttrs[k]);
  4869. });
  4870. }
  4871. Declaration.prototype.visit = function (visitor) {
  4872. return visitor.visitDeclaration(this);
  4873. };
  4874. return Declaration;
  4875. }());
  4876. var Doctype = /** @class */ (function () {
  4877. function Doctype(rootTag, dtd) {
  4878. this.rootTag = rootTag;
  4879. this.dtd = dtd;
  4880. }
  4881. Doctype.prototype.visit = function (visitor) {
  4882. return visitor.visitDoctype(this);
  4883. };
  4884. return Doctype;
  4885. }());
  4886. var Tag = /** @class */ (function () {
  4887. function Tag(name, unescapedAttrs, children) {
  4888. var _this = this;
  4889. if (unescapedAttrs === void 0) { unescapedAttrs = {}; }
  4890. if (children === void 0) { children = []; }
  4891. this.name = name;
  4892. this.children = children;
  4893. this.attrs = {};
  4894. Object.keys(unescapedAttrs).forEach(function (k) {
  4895. _this.attrs[k] = escapeXml(unescapedAttrs[k]);
  4896. });
  4897. }
  4898. Tag.prototype.visit = function (visitor) {
  4899. return visitor.visitTag(this);
  4900. };
  4901. return Tag;
  4902. }());
  4903. var Text$2 = /** @class */ (function () {
  4904. function Text(unescapedValue) {
  4905. this.value = escapeXml(unescapedValue);
  4906. }
  4907. Text.prototype.visit = function (visitor) {
  4908. return visitor.visitText(this);
  4909. };
  4910. return Text;
  4911. }());
  4912. var CR = /** @class */ (function (_super) {
  4913. __extends(CR, _super);
  4914. function CR(ws) {
  4915. if (ws === void 0) { ws = 0; }
  4916. return _super.call(this, "\n" + new Array(ws + 1).join(' ')) || this;
  4917. }
  4918. return CR;
  4919. }(Text$2));
  4920. var _ESCAPED_CHARS = [
  4921. [/&/g, '&amp;'],
  4922. [/"/g, '&quot;'],
  4923. [/'/g, '&apos;'],
  4924. [/</g, '&lt;'],
  4925. [/>/g, '&gt;'],
  4926. ];
  4927. // Escape `_ESCAPED_CHARS` characters in the given text with encoded entities
  4928. function escapeXml(text) {
  4929. return _ESCAPED_CHARS.reduce(function (text, entry) { return text.replace(entry[0], entry[1]); }, text);
  4930. }
  4931. var _MESSAGES_TAG = 'messagebundle';
  4932. var _MESSAGE_TAG = 'msg';
  4933. var _PLACEHOLDER_TAG = 'ph';
  4934. var _EXAMPLE_TAG = 'ex';
  4935. var _SOURCE_TAG = 'source';
  4936. var _DOCTYPE = "<!ELEMENT messagebundle (msg)*>\n<!ATTLIST messagebundle class CDATA #IMPLIED>\n\n<!ELEMENT msg (#PCDATA|ph|source)*>\n<!ATTLIST msg id CDATA #IMPLIED>\n<!ATTLIST msg seq CDATA #IMPLIED>\n<!ATTLIST msg name CDATA #IMPLIED>\n<!ATTLIST msg desc CDATA #IMPLIED>\n<!ATTLIST msg meaning CDATA #IMPLIED>\n<!ATTLIST msg obsolete (obsolete) #IMPLIED>\n<!ATTLIST msg xml:space (default|preserve) \"default\">\n<!ATTLIST msg is_hidden CDATA #IMPLIED>\n\n<!ELEMENT source (#PCDATA)>\n\n<!ELEMENT ph (#PCDATA|ex)*>\n<!ATTLIST ph name CDATA #REQUIRED>\n\n<!ELEMENT ex (#PCDATA)>";
  4937. var Xmb = /** @class */ (function (_super) {
  4938. __extends(Xmb, _super);
  4939. function Xmb() {
  4940. return _super !== null && _super.apply(this, arguments) || this;
  4941. }
  4942. Xmb.prototype.write = function (messages, locale) {
  4943. var exampleVisitor = new ExampleVisitor();
  4944. var visitor = new _Visitor$1();
  4945. var rootNode = new Tag(_MESSAGES_TAG);
  4946. messages.forEach(function (message) {
  4947. var attrs = { id: message.id };
  4948. if (message.description) {
  4949. attrs['desc'] = message.description;
  4950. }
  4951. if (message.meaning) {
  4952. attrs['meaning'] = message.meaning;
  4953. }
  4954. var sourceTags = [];
  4955. message.sources.forEach(function (source) {
  4956. sourceTags.push(new Tag(_SOURCE_TAG, {}, [new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))]));
  4957. });
  4958. rootNode.children.push(new CR(2), new Tag(_MESSAGE_TAG, attrs, __spreadArray(__spreadArray([], __read(sourceTags)), __read(visitor.serialize(message.nodes)))));
  4959. });
  4960. rootNode.children.push(new CR());
  4961. return serialize([
  4962. new Declaration({ version: '1.0', encoding: 'UTF-8' }),
  4963. new CR(),
  4964. new Doctype(_MESSAGES_TAG, _DOCTYPE),
  4965. new CR(),
  4966. exampleVisitor.addDefaultExamples(rootNode),
  4967. new CR(),
  4968. ]);
  4969. };
  4970. Xmb.prototype.load = function (content, url) {
  4971. throw new Error('Unsupported');
  4972. };
  4973. Xmb.prototype.digest = function (message) {
  4974. return digest$1(message);
  4975. };
  4976. Xmb.prototype.createNameMapper = function (message) {
  4977. return new SimplePlaceholderMapper(message, toPublicName);
  4978. };
  4979. return Xmb;
  4980. }(Serializer));
  4981. var _Visitor$1 = /** @class */ (function () {
  4982. function _Visitor() {
  4983. }
  4984. _Visitor.prototype.visitText = function (text, context) {
  4985. return [new Text$2(text.value)];
  4986. };
  4987. _Visitor.prototype.visitContainer = function (container, context) {
  4988. var _this = this;
  4989. var nodes = [];
  4990. container.children.forEach(function (node) { return nodes.push.apply(nodes, __spreadArray([], __read(node.visit(_this)))); });
  4991. return nodes;
  4992. };
  4993. _Visitor.prototype.visitIcu = function (icu, context) {
  4994. var _this = this;
  4995. var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
  4996. Object.keys(icu.cases).forEach(function (c) {
  4997. nodes.push.apply(nodes, __spreadArray(__spreadArray([new Text$2(c + " {")], __read(icu.cases[c].visit(_this))), [new Text$2("} ")]));
  4998. });
  4999. nodes.push(new Text$2("}"));
  5000. return nodes;
  5001. };
  5002. _Visitor.prototype.visitTagPlaceholder = function (ph, context) {
  5003. var startTagAsText = new Text$2("<" + ph.tag + ">");
  5004. var startEx = new Tag(_EXAMPLE_TAG, {}, [startTagAsText]);
  5005. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  5006. var startTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.startName }, [startEx, startTagAsText]);
  5007. if (ph.isVoid) {
  5008. // void tags have no children nor closing tags
  5009. return [startTagPh];
  5010. }
  5011. var closeTagAsText = new Text$2("</" + ph.tag + ">");
  5012. var closeEx = new Tag(_EXAMPLE_TAG, {}, [closeTagAsText]);
  5013. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  5014. var closeTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.closeName }, [closeEx, closeTagAsText]);
  5015. return __spreadArray(__spreadArray([startTagPh], __read(this.serialize(ph.children))), [closeTagPh]);
  5016. };
  5017. _Visitor.prototype.visitPlaceholder = function (ph, context) {
  5018. var interpolationAsText = new Text$2("{{" + ph.value + "}}");
  5019. // Example tag needs to be not-empty for TC.
  5020. var exTag = new Tag(_EXAMPLE_TAG, {}, [interpolationAsText]);
  5021. return [
  5022. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  5023. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, interpolationAsText])
  5024. ];
  5025. };
  5026. _Visitor.prototype.visitIcuPlaceholder = function (ph, context) {
  5027. var icuExpression = ph.value.expression;
  5028. var icuType = ph.value.type;
  5029. var icuCases = Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ');
  5030. var icuAsText = new Text$2("{" + icuExpression + ", " + icuType + ", " + icuCases + "}");
  5031. var exTag = new Tag(_EXAMPLE_TAG, {}, [icuAsText]);
  5032. return [
  5033. // TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
  5034. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, icuAsText])
  5035. ];
  5036. };
  5037. _Visitor.prototype.serialize = function (nodes) {
  5038. var _this = this;
  5039. return [].concat.apply([], __spreadArray([], __read(nodes.map(function (node) { return node.visit(_this); }))));
  5040. };
  5041. return _Visitor;
  5042. }());
  5043. function digest$1(message) {
  5044. return decimalDigest(message);
  5045. }
  5046. // TC requires at least one non-empty example on placeholders
  5047. var ExampleVisitor = /** @class */ (function () {
  5048. function ExampleVisitor() {
  5049. }
  5050. ExampleVisitor.prototype.addDefaultExamples = function (node) {
  5051. node.visit(this);
  5052. return node;
  5053. };
  5054. ExampleVisitor.prototype.visitTag = function (tag) {
  5055. var _this = this;
  5056. if (tag.name === _PLACEHOLDER_TAG) {
  5057. if (!tag.children || tag.children.length == 0) {
  5058. var exText = new Text$2(tag.attrs['name'] || '...');
  5059. tag.children = [new Tag(_EXAMPLE_TAG, {}, [exText])];
  5060. }
  5061. }
  5062. else if (tag.children) {
  5063. tag.children.forEach(function (node) { return node.visit(_this); });
  5064. }
  5065. };
  5066. ExampleVisitor.prototype.visitText = function (text) { };
  5067. ExampleVisitor.prototype.visitDeclaration = function (decl) { };
  5068. ExampleVisitor.prototype.visitDoctype = function (doctype) { };
  5069. return ExampleVisitor;
  5070. }());
  5071. // XMB/XTB placeholders can only contain A-Z, 0-9 and _
  5072. function toPublicName(internalName) {
  5073. return internalName.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
  5074. }
  5075. /* Closure variables holding messages must be named `MSG_[A-Z0-9]+` */
  5076. var CLOSURE_TRANSLATION_VAR_PREFIX = 'MSG_';
  5077. /**
  5078. * Prefix for non-`goog.getMsg` i18n-related vars.
  5079. * Note: the prefix uses lowercase characters intentionally due to a Closure behavior that
  5080. * considers variables like `I18N_0` as constants and throws an error when their value changes.
  5081. */
  5082. var TRANSLATION_VAR_PREFIX = 'i18n_';
  5083. /** Name of the i18n attributes **/
  5084. var I18N_ATTR = 'i18n';
  5085. var I18N_ATTR_PREFIX = 'i18n-';
  5086. /** Prefix of var expressions used in ICUs */
  5087. var I18N_ICU_VAR_PREFIX = 'VAR_';
  5088. /** Prefix of ICU expressions for post processing */
  5089. var I18N_ICU_MAPPING_PREFIX = 'I18N_EXP_';
  5090. /** Placeholder wrapper for i18n expressions **/
  5091. var I18N_PLACEHOLDER_SYMBOL = '�';
  5092. function isI18nAttribute(name) {
  5093. return name === I18N_ATTR || name.startsWith(I18N_ATTR_PREFIX);
  5094. }
  5095. function isI18nRootNode(meta) {
  5096. return meta instanceof Message;
  5097. }
  5098. function isSingleI18nIcu(meta) {
  5099. return isI18nRootNode(meta) && meta.nodes.length === 1 && meta.nodes[0] instanceof Icu$1;
  5100. }
  5101. function hasI18nMeta(node) {
  5102. return !!node.i18n;
  5103. }
  5104. function hasI18nAttrs(element) {
  5105. return element.attrs.some(function (attr) { return isI18nAttribute(attr.name); });
  5106. }
  5107. function icuFromI18nMessage(message) {
  5108. return message.nodes[0];
  5109. }
  5110. function wrapI18nPlaceholder(content, contextId) {
  5111. if (contextId === void 0) { contextId = 0; }
  5112. var blockId = contextId > 0 ? ":" + contextId : '';
  5113. return "" + I18N_PLACEHOLDER_SYMBOL + content + blockId + I18N_PLACEHOLDER_SYMBOL;
  5114. }
  5115. function assembleI18nBoundString(strings, bindingStartIndex, contextId) {
  5116. if (bindingStartIndex === void 0) { bindingStartIndex = 0; }
  5117. if (contextId === void 0) { contextId = 0; }
  5118. if (!strings.length)
  5119. return '';
  5120. var acc = '';
  5121. var lastIdx = strings.length - 1;
  5122. for (var i = 0; i < lastIdx; i++) {
  5123. acc += "" + strings[i] + wrapI18nPlaceholder(bindingStartIndex + i, contextId);
  5124. }
  5125. acc += strings[lastIdx];
  5126. return acc;
  5127. }
  5128. function getSeqNumberGenerator(startsAt) {
  5129. if (startsAt === void 0) { startsAt = 0; }
  5130. var current = startsAt;
  5131. return function () { return current++; };
  5132. }
  5133. function placeholdersToParams(placeholders) {
  5134. var params = {};
  5135. placeholders.forEach(function (values, key) {
  5136. params[key] = literal(values.length > 1 ? "[" + values.join('|') + "]" : values[0]);
  5137. });
  5138. return params;
  5139. }
  5140. function updatePlaceholderMap(map, name) {
  5141. var values = [];
  5142. for (var _i = 2; _i < arguments.length; _i++) {
  5143. values[_i - 2] = arguments[_i];
  5144. }
  5145. var current = map.get(name) || [];
  5146. current.push.apply(current, __spreadArray([], __read(values)));
  5147. map.set(name, current);
  5148. }
  5149. function assembleBoundTextPlaceholders(meta, bindingStartIndex, contextId) {
  5150. if (bindingStartIndex === void 0) { bindingStartIndex = 0; }
  5151. if (contextId === void 0) { contextId = 0; }
  5152. var startIdx = bindingStartIndex;
  5153. var placeholders = new Map();
  5154. var node = meta instanceof Message ? meta.nodes.find(function (node) { return node instanceof Container; }) : meta;
  5155. if (node) {
  5156. node
  5157. .children
  5158. .filter(function (child) { return child instanceof Placeholder; })
  5159. .forEach(function (child, idx) {
  5160. var content = wrapI18nPlaceholder(startIdx + idx, contextId);
  5161. updatePlaceholderMap(placeholders, child.name, content);
  5162. });
  5163. }
  5164. return placeholders;
  5165. }
  5166. /**
  5167. * Format the placeholder names in a map of placeholders to expressions.
  5168. *
  5169. * The placeholder names are converted from "internal" format (e.g. `START_TAG_DIV_1`) to "external"
  5170. * format (e.g. `startTagDiv_1`).
  5171. *
  5172. * @param params A map of placeholder names to expressions.
  5173. * @param useCamelCase whether to camelCase the placeholder name when formatting.
  5174. * @returns A new map of formatted placeholder names to expressions.
  5175. */
  5176. function i18nFormatPlaceholderNames(params, useCamelCase) {
  5177. if (params === void 0) { params = {}; }
  5178. var _params = {};
  5179. if (params && Object.keys(params).length) {
  5180. Object.keys(params).forEach(function (key) { return _params[formatI18nPlaceholderName(key, useCamelCase)] = params[key]; });
  5181. }
  5182. return _params;
  5183. }
  5184. /**
  5185. * Converts internal placeholder names to public-facing format
  5186. * (for example to use in goog.getMsg call).
  5187. * Example: `START_TAG_DIV_1` is converted to `startTagDiv_1`.
  5188. *
  5189. * @param name The placeholder name that should be formatted
  5190. * @returns Formatted placeholder name
  5191. */
  5192. function formatI18nPlaceholderName(name, useCamelCase) {
  5193. if (useCamelCase === void 0) { useCamelCase = true; }
  5194. var publicName = toPublicName(name);
  5195. if (!useCamelCase) {
  5196. return publicName;
  5197. }
  5198. var chunks = publicName.split('_');
  5199. if (chunks.length === 1) {
  5200. // if no "_" found - just lowercase the value
  5201. return name.toLowerCase();
  5202. }
  5203. var postfix;
  5204. // eject last element if it's a number
  5205. if (/^\d+$/.test(chunks[chunks.length - 1])) {
  5206. postfix = chunks.pop();
  5207. }
  5208. var raw = chunks.shift().toLowerCase();
  5209. if (chunks.length) {
  5210. raw += chunks.map(function (c) { return c.charAt(0).toUpperCase() + c.slice(1).toLowerCase(); }).join('');
  5211. }
  5212. return postfix ? raw + "_" + postfix : raw;
  5213. }
  5214. /**
  5215. * Generates a prefix for translation const name.
  5216. *
  5217. * @param extra Additional local prefix that should be injected into translation var name
  5218. * @returns Complete translation const prefix
  5219. */
  5220. function getTranslationConstPrefix(extra) {
  5221. return ("" + CLOSURE_TRANSLATION_VAR_PREFIX + extra).toUpperCase();
  5222. }
  5223. /**
  5224. * Generate AST to declare a variable. E.g. `var I18N_1;`.
  5225. * @param variable the name of the variable to declare.
  5226. */
  5227. function declareI18nVariable(variable) {
  5228. return new DeclareVarStmt(variable.name, undefined, INFERRED_TYPE, undefined, variable.sourceSpan);
  5229. }
  5230. /**
  5231. * Checks whether an object key contains potentially unsafe chars, thus the key should be wrapped in
  5232. * quotes. Note: we do not wrap all keys into quotes, as it may have impact on minification and may
  5233. * bot work in some cases when object keys are mangled by minifier.
  5234. *
  5235. * TODO(FW-1136): this is a temporary solution, we need to come up with a better way of working with
  5236. * inputs that contain potentially unsafe chars.
  5237. */
  5238. var UNSAFE_OBJECT_KEY_NAME_REGEXP = /[-.]/;
  5239. /** Name of the temporary to use during data binding */
  5240. var TEMPORARY_NAME = '_t';
  5241. /** Name of the context parameter passed into a template function */
  5242. var CONTEXT_NAME = 'ctx';
  5243. /** Name of the RenderFlag passed into a template function */
  5244. var RENDER_FLAGS = 'rf';
  5245. /** The prefix reference variables */
  5246. var REFERENCE_PREFIX = '_r';
  5247. /** The name of the implicit context reference */
  5248. var IMPLICIT_REFERENCE = '$implicit';
  5249. /** Non bindable attribute name **/
  5250. var NON_BINDABLE_ATTR = 'ngNonBindable';
  5251. /** Name for the variable keeping track of the context returned by `ɵɵrestoreView`. */
  5252. var RESTORED_VIEW_CONTEXT_NAME = 'restoredCtx';
  5253. /**
  5254. * Creates an allocator for a temporary variable.
  5255. *
  5256. * A variable declaration is added to the statements the first time the allocator is invoked.
  5257. */
  5258. function temporaryAllocator(statements, name) {
  5259. var temp = null;
  5260. return function () {
  5261. if (!temp) {
  5262. statements.push(new DeclareVarStmt(TEMPORARY_NAME, undefined, DYNAMIC_TYPE));
  5263. temp = variable(name);
  5264. }
  5265. return temp;
  5266. };
  5267. }
  5268. function unsupported(feature) {
  5269. if (this) {
  5270. throw new Error("Builder " + this.constructor.name + " doesn't support " + feature + " yet");
  5271. }
  5272. throw new Error("Feature " + feature + " is not supported yet");
  5273. }
  5274. function invalid$1(arg) {
  5275. throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name);
  5276. }
  5277. function asLiteral(value) {
  5278. if (Array.isArray(value)) {
  5279. return literalArr(value.map(asLiteral));
  5280. }
  5281. return literal(value, INFERRED_TYPE);
  5282. }
  5283. function conditionallyCreateMapObjectLiteral(keys, keepDeclared) {
  5284. if (Object.getOwnPropertyNames(keys).length > 0) {
  5285. return mapToExpression(keys, keepDeclared);
  5286. }
  5287. return null;
  5288. }
  5289. function mapToExpression(map, keepDeclared) {
  5290. return literalMap(Object.getOwnPropertyNames(map).map(function (key) {
  5291. var _a, _b;
  5292. // canonical syntax: `dirProp: publicProp`
  5293. // if there is no `:`, use dirProp = elProp
  5294. var value = map[key];
  5295. var declaredName;
  5296. var publicName;
  5297. var minifiedName;
  5298. var needsDeclaredName;
  5299. if (Array.isArray(value)) {
  5300. _a = __read(value, 2), publicName = _a[0], declaredName = _a[1];
  5301. minifiedName = key;
  5302. needsDeclaredName = publicName !== declaredName;
  5303. }
  5304. else {
  5305. _b = __read(splitAtColon(key, [key, value]), 2), declaredName = _b[0], publicName = _b[1];
  5306. minifiedName = declaredName;
  5307. // Only include the declared name if extracted from the key, i.e. the key contains a colon.
  5308. // Otherwise the declared name should be omitted even if it is different from the public name,
  5309. // as it may have already been minified.
  5310. needsDeclaredName = publicName !== declaredName && key.includes(':');
  5311. }
  5312. return {
  5313. key: minifiedName,
  5314. // put quotes around keys that contain potentially unsafe characters
  5315. quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(minifiedName),
  5316. value: (keepDeclared && needsDeclaredName) ?
  5317. literalArr([asLiteral(publicName), asLiteral(declaredName)]) :
  5318. asLiteral(publicName)
  5319. };
  5320. }));
  5321. }
  5322. /**
  5323. * Remove trailing null nodes as they are implied.
  5324. */
  5325. function trimTrailingNulls(parameters) {
  5326. while (isNull(parameters[parameters.length - 1])) {
  5327. parameters.pop();
  5328. }
  5329. return parameters;
  5330. }
  5331. function getQueryPredicate(query, constantPool) {
  5332. if (Array.isArray(query.predicate)) {
  5333. var predicate_1 = [];
  5334. query.predicate.forEach(function (selector) {
  5335. // Each item in predicates array may contain strings with comma-separated refs
  5336. // (for ex. 'ref, ref1, ..., refN'), thus we extract individual refs and store them
  5337. // as separate array entities
  5338. var selectors = selector.split(',').map(function (token) { return literal(token.trim()); });
  5339. predicate_1.push.apply(predicate_1, __spreadArray([], __read(selectors)));
  5340. });
  5341. return constantPool.getConstLiteral(literalArr(predicate_1), true);
  5342. }
  5343. else {
  5344. return query.predicate;
  5345. }
  5346. }
  5347. /**
  5348. * A representation for an object literal used during codegen of definition objects. The generic
  5349. * type `T` allows to reference a documented type of the generated structure, such that the
  5350. * property names that are set can be resolved to their documented declaration.
  5351. */
  5352. var DefinitionMap = /** @class */ (function () {
  5353. function DefinitionMap() {
  5354. this.values = [];
  5355. }
  5356. DefinitionMap.prototype.set = function (key, value) {
  5357. if (value) {
  5358. this.values.push({ key: key, value: value, quoted: false });
  5359. }
  5360. };
  5361. DefinitionMap.prototype.toLiteralMap = function () {
  5362. return literalMap(this.values);
  5363. };
  5364. return DefinitionMap;
  5365. }());
  5366. /**
  5367. * Extract a map of properties to values for a given element or template node, which can be used
  5368. * by the directive matching machinery.
  5369. *
  5370. * @param elOrTpl the element or template in question
  5371. * @return an object set up for directive matching. For attributes on the element/template, this
  5372. * object maps a property name to its (static) value. For any bindings, this map simply maps the
  5373. * property name to an empty string.
  5374. */
  5375. function getAttrsForDirectiveMatching(elOrTpl) {
  5376. var attributesMap = {};
  5377. if (elOrTpl instanceof Template && elOrTpl.tagName !== 'ng-template') {
  5378. elOrTpl.templateAttrs.forEach(function (a) { return attributesMap[a.name] = ''; });
  5379. }
  5380. else {
  5381. elOrTpl.attributes.forEach(function (a) {
  5382. if (!isI18nAttribute(a.name)) {
  5383. attributesMap[a.name] = a.value;
  5384. }
  5385. });
  5386. elOrTpl.inputs.forEach(function (i) {
  5387. attributesMap[i.name] = '';
  5388. });
  5389. elOrTpl.outputs.forEach(function (o) {
  5390. attributesMap[o.name] = '';
  5391. });
  5392. }
  5393. return attributesMap;
  5394. }
  5395. /** Returns a call expression to a chained instruction, e.g. `property(params[0])(params[1])`. */
  5396. function chainedInstruction(reference, calls, span) {
  5397. var expression = importExpr(reference, null, span);
  5398. if (calls.length > 0) {
  5399. for (var i = 0; i < calls.length; i++) {
  5400. expression = expression.callFn(calls[i], span);
  5401. }
  5402. }
  5403. else {
  5404. // Add a blank invocation, in case the `calls` array is empty.
  5405. expression = expression.callFn([], span);
  5406. }
  5407. return expression;
  5408. }
  5409. /**
  5410. * Gets the number of arguments expected to be passed to a generated instruction in the case of
  5411. * interpolation instructions.
  5412. * @param interpolation An interpolation ast
  5413. */
  5414. function getInterpolationArgsLength(interpolation) {
  5415. var expressions = interpolation.expressions, strings = interpolation.strings;
  5416. if (expressions.length === 1 && strings.length === 2 && strings[0] === '' && strings[1] === '') {
  5417. // If the interpolation has one interpolated value, but the prefix and suffix are both empty
  5418. // strings, we only pass one argument, to a special instruction like `propertyInterpolate` or
  5419. // `textInterpolate`.
  5420. return 1;
  5421. }
  5422. else {
  5423. return expressions.length + strings.length;
  5424. }
  5425. }
  5426. /**
  5427. * @license
  5428. * Copyright Google LLC All Rights Reserved.
  5429. *
  5430. * Use of this source code is governed by an MIT-style license that can be
  5431. * found in the LICENSE file at https://angular.io/license
  5432. */
  5433. /**
  5434. * Creates an array literal expression from the given array, mapping all values to an expression
  5435. * using the provided mapping function. If the array is empty or null, then null is returned.
  5436. *
  5437. * @param values The array to transfer into literal array expression.
  5438. * @param mapper The logic to use for creating an expression for the array's values.
  5439. * @returns An array literal expression representing `values`, or null if `values` is empty or
  5440. * is itself null.
  5441. */
  5442. function toOptionalLiteralArray(values, mapper) {
  5443. if (values === null || values.length === 0) {
  5444. return null;
  5445. }
  5446. return literalArr(values.map(function (value) { return mapper(value); }));
  5447. }
  5448. /**
  5449. * Creates an object literal expression from the given object, mapping all values to an expression
  5450. * using the provided mapping function. If the object has no keys, then null is returned.
  5451. *
  5452. * @param object The object to transfer into an object literal expression.
  5453. * @param mapper The logic to use for creating an expression for the object's values.
  5454. * @returns An object literal expression representing `object`, or null if `object` does not have
  5455. * any keys.
  5456. */
  5457. function toOptionalLiteralMap(object, mapper) {
  5458. var entries = Object.keys(object).map(function (key) {
  5459. var value = object[key];
  5460. return { key: key, value: mapper(value), quoted: true };
  5461. });
  5462. if (entries.length > 0) {
  5463. return literalMap(entries);
  5464. }
  5465. else {
  5466. return null;
  5467. }
  5468. }
  5469. function compileDependencies(deps) {
  5470. if (deps === 'invalid') {
  5471. // The `deps` can be set to the string "invalid" by the `unwrapConstructorDependencies()`
  5472. // function, which tries to convert `ConstructorDeps` into `R3DependencyMetadata[]`.
  5473. return literal('invalid');
  5474. }
  5475. else if (deps === null) {
  5476. return literal(null);
  5477. }
  5478. else {
  5479. return literalArr(deps.map(compileDependency));
  5480. }
  5481. }
  5482. function compileDependency(dep) {
  5483. var depMeta = new DefinitionMap();
  5484. depMeta.set('token', dep.token);
  5485. if (dep.attributeNameType !== null) {
  5486. depMeta.set('attribute', literal(true));
  5487. }
  5488. if (dep.host) {
  5489. depMeta.set('host', literal(true));
  5490. }
  5491. if (dep.optional) {
  5492. depMeta.set('optional', literal(true));
  5493. }
  5494. if (dep.self) {
  5495. depMeta.set('self', literal(true));
  5496. }
  5497. if (dep.skipSelf) {
  5498. depMeta.set('skipSelf', literal(true));
  5499. }
  5500. return depMeta.toLiteralMap();
  5501. }
  5502. /**
  5503. * Generate an expression that has the given `expr` wrapped in the following form:
  5504. *
  5505. * ```
  5506. * forwardRef(() => expr)
  5507. * ```
  5508. */
  5509. function generateForwardRef(expr) {
  5510. return importExpr(Identifiers.forwardRef).callFn([fn([], [new ReturnStatement(expr)])]);
  5511. }
  5512. /**
  5513. * @license
  5514. * Copyright Google LLC All Rights Reserved.
  5515. *
  5516. * Use of this source code is governed by an MIT-style license that can be
  5517. * found in the LICENSE file at https://angular.io/license
  5518. */
  5519. // https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
  5520. var VERSION = 3;
  5521. var JS_B64_PREFIX = '# sourceMappingURL=data:application/json;base64,';
  5522. var SourceMapGenerator = /** @class */ (function () {
  5523. function SourceMapGenerator(file) {
  5524. if (file === void 0) { file = null; }
  5525. this.file = file;
  5526. this.sourcesContent = new Map();
  5527. this.lines = [];
  5528. this.lastCol0 = 0;
  5529. this.hasMappings = false;
  5530. }
  5531. // The content is `null` when the content is expected to be loaded using the URL
  5532. SourceMapGenerator.prototype.addSource = function (url, content) {
  5533. if (content === void 0) { content = null; }
  5534. if (!this.sourcesContent.has(url)) {
  5535. this.sourcesContent.set(url, content);
  5536. }
  5537. return this;
  5538. };
  5539. SourceMapGenerator.prototype.addLine = function () {
  5540. this.lines.push([]);
  5541. this.lastCol0 = 0;
  5542. return this;
  5543. };
  5544. SourceMapGenerator.prototype.addMapping = function (col0, sourceUrl, sourceLine0, sourceCol0) {
  5545. if (!this.currentLine) {
  5546. throw new Error("A line must be added before mappings can be added");
  5547. }
  5548. if (sourceUrl != null && !this.sourcesContent.has(sourceUrl)) {
  5549. throw new Error("Unknown source file \"" + sourceUrl + "\"");
  5550. }
  5551. if (col0 == null) {
  5552. throw new Error("The column in the generated code must be provided");
  5553. }
  5554. if (col0 < this.lastCol0) {
  5555. throw new Error("Mapping should be added in output order");
  5556. }
  5557. if (sourceUrl && (sourceLine0 == null || sourceCol0 == null)) {
  5558. throw new Error("The source location must be provided when a source url is provided");
  5559. }
  5560. this.hasMappings = true;
  5561. this.lastCol0 = col0;
  5562. this.currentLine.push({ col0: col0, sourceUrl: sourceUrl, sourceLine0: sourceLine0, sourceCol0: sourceCol0 });
  5563. return this;
  5564. };
  5565. Object.defineProperty(SourceMapGenerator.prototype, "currentLine", {
  5566. /**
  5567. * @internal strip this from published d.ts files due to
  5568. * https://github.com/microsoft/TypeScript/issues/36216
  5569. */
  5570. get: function () {
  5571. return this.lines.slice(-1)[0];
  5572. },
  5573. enumerable: false,
  5574. configurable: true
  5575. });
  5576. SourceMapGenerator.prototype.toJSON = function () {
  5577. var _this = this;
  5578. if (!this.hasMappings) {
  5579. return null;
  5580. }
  5581. var sourcesIndex = new Map();
  5582. var sources = [];
  5583. var sourcesContent = [];
  5584. Array.from(this.sourcesContent.keys()).forEach(function (url, i) {
  5585. sourcesIndex.set(url, i);
  5586. sources.push(url);
  5587. sourcesContent.push(_this.sourcesContent.get(url) || null);
  5588. });
  5589. var mappings = '';
  5590. var lastCol0 = 0;
  5591. var lastSourceIndex = 0;
  5592. var lastSourceLine0 = 0;
  5593. var lastSourceCol0 = 0;
  5594. this.lines.forEach(function (segments) {
  5595. lastCol0 = 0;
  5596. mappings += segments
  5597. .map(function (segment) {
  5598. // zero-based starting column of the line in the generated code
  5599. var segAsStr = toBase64VLQ(segment.col0 - lastCol0);
  5600. lastCol0 = segment.col0;
  5601. if (segment.sourceUrl != null) {
  5602. // zero-based index into the “sources” list
  5603. segAsStr +=
  5604. toBase64VLQ(sourcesIndex.get(segment.sourceUrl) - lastSourceIndex);
  5605. lastSourceIndex = sourcesIndex.get(segment.sourceUrl);
  5606. // the zero-based starting line in the original source
  5607. segAsStr += toBase64VLQ(segment.sourceLine0 - lastSourceLine0);
  5608. lastSourceLine0 = segment.sourceLine0;
  5609. // the zero-based starting column in the original source
  5610. segAsStr += toBase64VLQ(segment.sourceCol0 - lastSourceCol0);
  5611. lastSourceCol0 = segment.sourceCol0;
  5612. }
  5613. return segAsStr;
  5614. })
  5615. .join(',');
  5616. mappings += ';';
  5617. });
  5618. mappings = mappings.slice(0, -1);
  5619. return {
  5620. 'file': this.file || '',
  5621. 'version': VERSION,
  5622. 'sourceRoot': '',
  5623. 'sources': sources,
  5624. 'sourcesContent': sourcesContent,
  5625. 'mappings': mappings,
  5626. };
  5627. };
  5628. SourceMapGenerator.prototype.toJsComment = function () {
  5629. return this.hasMappings ? '//' + JS_B64_PREFIX + toBase64String(JSON.stringify(this, null, 0)) :
  5630. '';
  5631. };
  5632. return SourceMapGenerator;
  5633. }());
  5634. function toBase64String(value) {
  5635. var b64 = '';
  5636. var encoded = utf8Encode(value);
  5637. for (var i = 0; i < encoded.length;) {
  5638. var i1 = encoded[i++];
  5639. var i2 = i < encoded.length ? encoded[i++] : null;
  5640. var i3 = i < encoded.length ? encoded[i++] : null;
  5641. b64 += toBase64Digit(i1 >> 2);
  5642. b64 += toBase64Digit(((i1 & 3) << 4) | (i2 === null ? 0 : i2 >> 4));
  5643. b64 += i2 === null ? '=' : toBase64Digit(((i2 & 15) << 2) | (i3 === null ? 0 : i3 >> 6));
  5644. b64 += i2 === null || i3 === null ? '=' : toBase64Digit(i3 & 63);
  5645. }
  5646. return b64;
  5647. }
  5648. function toBase64VLQ(value) {
  5649. value = value < 0 ? ((-value) << 1) + 1 : value << 1;
  5650. var out = '';
  5651. do {
  5652. var digit = value & 31;
  5653. value = value >> 5;
  5654. if (value > 0) {
  5655. digit = digit | 32;
  5656. }
  5657. out += toBase64Digit(digit);
  5658. } while (value > 0);
  5659. return out;
  5660. }
  5661. var B64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  5662. function toBase64Digit(value) {
  5663. if (value < 0 || value >= 64) {
  5664. throw new Error("Can only encode value in the range [0, 63]");
  5665. }
  5666. return B64_DIGITS[value];
  5667. }
  5668. var _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g;
  5669. var _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i;
  5670. var _INDENT_WITH = ' ';
  5671. var CATCH_ERROR_VAR$1 = variable('error', null, null);
  5672. var CATCH_STACK_VAR$1 = variable('stack', null, null);
  5673. var _EmittedLine = /** @class */ (function () {
  5674. function _EmittedLine(indent) {
  5675. this.indent = indent;
  5676. this.partsLength = 0;
  5677. this.parts = [];
  5678. this.srcSpans = [];
  5679. }
  5680. return _EmittedLine;
  5681. }());
  5682. var EmitterVisitorContext = /** @class */ (function () {
  5683. function EmitterVisitorContext(_indent) {
  5684. this._indent = _indent;
  5685. this._classes = [];
  5686. this._preambleLineCount = 0;
  5687. this._lines = [new _EmittedLine(_indent)];
  5688. }
  5689. EmitterVisitorContext.createRoot = function () {
  5690. return new EmitterVisitorContext(0);
  5691. };
  5692. Object.defineProperty(EmitterVisitorContext.prototype, "_currentLine", {
  5693. /**
  5694. * @internal strip this from published d.ts files due to
  5695. * https://github.com/microsoft/TypeScript/issues/36216
  5696. */
  5697. get: function () {
  5698. return this._lines[this._lines.length - 1];
  5699. },
  5700. enumerable: false,
  5701. configurable: true
  5702. });
  5703. EmitterVisitorContext.prototype.println = function (from, lastPart) {
  5704. if (lastPart === void 0) { lastPart = ''; }
  5705. this.print(from || null, lastPart, true);
  5706. };
  5707. EmitterVisitorContext.prototype.lineIsEmpty = function () {
  5708. return this._currentLine.parts.length === 0;
  5709. };
  5710. EmitterVisitorContext.prototype.lineLength = function () {
  5711. return this._currentLine.indent * _INDENT_WITH.length + this._currentLine.partsLength;
  5712. };
  5713. EmitterVisitorContext.prototype.print = function (from, part, newLine) {
  5714. if (newLine === void 0) { newLine = false; }
  5715. if (part.length > 0) {
  5716. this._currentLine.parts.push(part);
  5717. this._currentLine.partsLength += part.length;
  5718. this._currentLine.srcSpans.push(from && from.sourceSpan || null);
  5719. }
  5720. if (newLine) {
  5721. this._lines.push(new _EmittedLine(this._indent));
  5722. }
  5723. };
  5724. EmitterVisitorContext.prototype.removeEmptyLastLine = function () {
  5725. if (this.lineIsEmpty()) {
  5726. this._lines.pop();
  5727. }
  5728. };
  5729. EmitterVisitorContext.prototype.incIndent = function () {
  5730. this._indent++;
  5731. if (this.lineIsEmpty()) {
  5732. this._currentLine.indent = this._indent;
  5733. }
  5734. };
  5735. EmitterVisitorContext.prototype.decIndent = function () {
  5736. this._indent--;
  5737. if (this.lineIsEmpty()) {
  5738. this._currentLine.indent = this._indent;
  5739. }
  5740. };
  5741. EmitterVisitorContext.prototype.pushClass = function (clazz) {
  5742. this._classes.push(clazz);
  5743. };
  5744. EmitterVisitorContext.prototype.popClass = function () {
  5745. return this._classes.pop();
  5746. };
  5747. Object.defineProperty(EmitterVisitorContext.prototype, "currentClass", {
  5748. get: function () {
  5749. return this._classes.length > 0 ? this._classes[this._classes.length - 1] : null;
  5750. },
  5751. enumerable: false,
  5752. configurable: true
  5753. });
  5754. EmitterVisitorContext.prototype.toSource = function () {
  5755. return this.sourceLines
  5756. .map(function (l) { return l.parts.length > 0 ? _createIndent(l.indent) + l.parts.join('') : ''; })
  5757. .join('\n');
  5758. };
  5759. EmitterVisitorContext.prototype.toSourceMapGenerator = function (genFilePath, startsAtLine) {
  5760. if (startsAtLine === void 0) { startsAtLine = 0; }
  5761. var map = new SourceMapGenerator(genFilePath);
  5762. var firstOffsetMapped = false;
  5763. var mapFirstOffsetIfNeeded = function () {
  5764. if (!firstOffsetMapped) {
  5765. // Add a single space so that tools won't try to load the file from disk.
  5766. // Note: We are using virtual urls like `ng:///`, so we have to
  5767. // provide a content here.
  5768. map.addSource(genFilePath, ' ').addMapping(0, genFilePath, 0, 0);
  5769. firstOffsetMapped = true;
  5770. }
  5771. };
  5772. for (var i = 0; i < startsAtLine; i++) {
  5773. map.addLine();
  5774. mapFirstOffsetIfNeeded();
  5775. }
  5776. this.sourceLines.forEach(function (line, lineIdx) {
  5777. map.addLine();
  5778. var spans = line.srcSpans;
  5779. var parts = line.parts;
  5780. var col0 = line.indent * _INDENT_WITH.length;
  5781. var spanIdx = 0;
  5782. // skip leading parts without source spans
  5783. while (spanIdx < spans.length && !spans[spanIdx]) {
  5784. col0 += parts[spanIdx].length;
  5785. spanIdx++;
  5786. }
  5787. if (spanIdx < spans.length && lineIdx === 0 && col0 === 0) {
  5788. firstOffsetMapped = true;
  5789. }
  5790. else {
  5791. mapFirstOffsetIfNeeded();
  5792. }
  5793. while (spanIdx < spans.length) {
  5794. var span = spans[spanIdx];
  5795. var source = span.start.file;
  5796. var sourceLine = span.start.line;
  5797. var sourceCol = span.start.col;
  5798. map.addSource(source.url, source.content)
  5799. .addMapping(col0, source.url, sourceLine, sourceCol);
  5800. col0 += parts[spanIdx].length;
  5801. spanIdx++;
  5802. // assign parts without span or the same span to the previous segment
  5803. while (spanIdx < spans.length && (span === spans[spanIdx] || !spans[spanIdx])) {
  5804. col0 += parts[spanIdx].length;
  5805. spanIdx++;
  5806. }
  5807. }
  5808. });
  5809. return map;
  5810. };
  5811. EmitterVisitorContext.prototype.setPreambleLineCount = function (count) {
  5812. return this._preambleLineCount = count;
  5813. };
  5814. EmitterVisitorContext.prototype.spanOf = function (line, column) {
  5815. var emittedLine = this._lines[line - this._preambleLineCount];
  5816. if (emittedLine) {
  5817. var columnsLeft = column - _createIndent(emittedLine.indent).length;
  5818. for (var partIndex = 0; partIndex < emittedLine.parts.length; partIndex++) {
  5819. var part = emittedLine.parts[partIndex];
  5820. if (part.length > columnsLeft) {
  5821. return emittedLine.srcSpans[partIndex];
  5822. }
  5823. columnsLeft -= part.length;
  5824. }
  5825. }
  5826. return null;
  5827. };
  5828. Object.defineProperty(EmitterVisitorContext.prototype, "sourceLines", {
  5829. /**
  5830. * @internal strip this from published d.ts files due to
  5831. * https://github.com/microsoft/TypeScript/issues/36216
  5832. */
  5833. get: function () {
  5834. if (this._lines.length && this._lines[this._lines.length - 1].parts.length === 0) {
  5835. return this._lines.slice(0, -1);
  5836. }
  5837. return this._lines;
  5838. },
  5839. enumerable: false,
  5840. configurable: true
  5841. });
  5842. return EmitterVisitorContext;
  5843. }());
  5844. var AbstractEmitterVisitor = /** @class */ (function () {
  5845. function AbstractEmitterVisitor(_escapeDollarInStrings) {
  5846. this._escapeDollarInStrings = _escapeDollarInStrings;
  5847. }
  5848. AbstractEmitterVisitor.prototype.printLeadingComments = function (stmt, ctx) {
  5849. var e_1, _a;
  5850. if (stmt.leadingComments === undefined) {
  5851. return;
  5852. }
  5853. try {
  5854. for (var _b = __values(stmt.leadingComments), _c = _b.next(); !_c.done; _c = _b.next()) {
  5855. var comment = _c.value;
  5856. if (comment instanceof JSDocComment) {
  5857. ctx.print(stmt, "/*" + comment.toString() + "*/", comment.trailingNewline);
  5858. }
  5859. else {
  5860. if (comment.multiline) {
  5861. ctx.print(stmt, "/* " + comment.text + " */", comment.trailingNewline);
  5862. }
  5863. else {
  5864. comment.text.split('\n').forEach(function (line) {
  5865. ctx.println(stmt, "// " + line);
  5866. });
  5867. }
  5868. }
  5869. }
  5870. }
  5871. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  5872. finally {
  5873. try {
  5874. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  5875. }
  5876. finally { if (e_1) throw e_1.error; }
  5877. }
  5878. };
  5879. AbstractEmitterVisitor.prototype.visitExpressionStmt = function (stmt, ctx) {
  5880. this.printLeadingComments(stmt, ctx);
  5881. stmt.expr.visitExpression(this, ctx);
  5882. ctx.println(stmt, ';');
  5883. return null;
  5884. };
  5885. AbstractEmitterVisitor.prototype.visitReturnStmt = function (stmt, ctx) {
  5886. this.printLeadingComments(stmt, ctx);
  5887. ctx.print(stmt, "return ");
  5888. stmt.value.visitExpression(this, ctx);
  5889. ctx.println(stmt, ';');
  5890. return null;
  5891. };
  5892. AbstractEmitterVisitor.prototype.visitIfStmt = function (stmt, ctx) {
  5893. this.printLeadingComments(stmt, ctx);
  5894. ctx.print(stmt, "if (");
  5895. stmt.condition.visitExpression(this, ctx);
  5896. ctx.print(stmt, ") {");
  5897. var hasElseCase = stmt.falseCase != null && stmt.falseCase.length > 0;
  5898. if (stmt.trueCase.length <= 1 && !hasElseCase) {
  5899. ctx.print(stmt, " ");
  5900. this.visitAllStatements(stmt.trueCase, ctx);
  5901. ctx.removeEmptyLastLine();
  5902. ctx.print(stmt, " ");
  5903. }
  5904. else {
  5905. ctx.println();
  5906. ctx.incIndent();
  5907. this.visitAllStatements(stmt.trueCase, ctx);
  5908. ctx.decIndent();
  5909. if (hasElseCase) {
  5910. ctx.println(stmt, "} else {");
  5911. ctx.incIndent();
  5912. this.visitAllStatements(stmt.falseCase, ctx);
  5913. ctx.decIndent();
  5914. }
  5915. }
  5916. ctx.println(stmt, "}");
  5917. return null;
  5918. };
  5919. AbstractEmitterVisitor.prototype.visitThrowStmt = function (stmt, ctx) {
  5920. this.printLeadingComments(stmt, ctx);
  5921. ctx.print(stmt, "throw ");
  5922. stmt.error.visitExpression(this, ctx);
  5923. ctx.println(stmt, ";");
  5924. return null;
  5925. };
  5926. AbstractEmitterVisitor.prototype.visitWriteVarExpr = function (expr, ctx) {
  5927. var lineWasEmpty = ctx.lineIsEmpty();
  5928. if (!lineWasEmpty) {
  5929. ctx.print(expr, '(');
  5930. }
  5931. ctx.print(expr, expr.name + " = ");
  5932. expr.value.visitExpression(this, ctx);
  5933. if (!lineWasEmpty) {
  5934. ctx.print(expr, ')');
  5935. }
  5936. return null;
  5937. };
  5938. AbstractEmitterVisitor.prototype.visitWriteKeyExpr = function (expr, ctx) {
  5939. var lineWasEmpty = ctx.lineIsEmpty();
  5940. if (!lineWasEmpty) {
  5941. ctx.print(expr, '(');
  5942. }
  5943. expr.receiver.visitExpression(this, ctx);
  5944. ctx.print(expr, "[");
  5945. expr.index.visitExpression(this, ctx);
  5946. ctx.print(expr, "] = ");
  5947. expr.value.visitExpression(this, ctx);
  5948. if (!lineWasEmpty) {
  5949. ctx.print(expr, ')');
  5950. }
  5951. return null;
  5952. };
  5953. AbstractEmitterVisitor.prototype.visitWritePropExpr = function (expr, ctx) {
  5954. var lineWasEmpty = ctx.lineIsEmpty();
  5955. if (!lineWasEmpty) {
  5956. ctx.print(expr, '(');
  5957. }
  5958. expr.receiver.visitExpression(this, ctx);
  5959. ctx.print(expr, "." + expr.name + " = ");
  5960. expr.value.visitExpression(this, ctx);
  5961. if (!lineWasEmpty) {
  5962. ctx.print(expr, ')');
  5963. }
  5964. return null;
  5965. };
  5966. AbstractEmitterVisitor.prototype.visitInvokeMethodExpr = function (expr, ctx) {
  5967. expr.receiver.visitExpression(this, ctx);
  5968. var name = expr.name;
  5969. if (expr.builtin != null) {
  5970. name = this.getBuiltinMethodName(expr.builtin);
  5971. if (name == null) {
  5972. // some builtins just mean to skip the call.
  5973. return null;
  5974. }
  5975. }
  5976. ctx.print(expr, "." + name + "(");
  5977. this.visitAllExpressions(expr.args, ctx, ",");
  5978. ctx.print(expr, ")");
  5979. return null;
  5980. };
  5981. AbstractEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) {
  5982. expr.fn.visitExpression(this, ctx);
  5983. ctx.print(expr, "(");
  5984. this.visitAllExpressions(expr.args, ctx, ',');
  5985. ctx.print(expr, ")");
  5986. return null;
  5987. };
  5988. AbstractEmitterVisitor.prototype.visitTaggedTemplateExpr = function (expr, ctx) {
  5989. expr.tag.visitExpression(this, ctx);
  5990. ctx.print(expr, '`' + expr.template.elements[0].rawText);
  5991. for (var i = 1; i < expr.template.elements.length; i++) {
  5992. ctx.print(expr, '${');
  5993. expr.template.expressions[i - 1].visitExpression(this, ctx);
  5994. ctx.print(expr, "}" + expr.template.elements[i].rawText);
  5995. }
  5996. ctx.print(expr, '`');
  5997. return null;
  5998. };
  5999. AbstractEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  6000. throw new Error('Abstract emitter cannot visit WrappedNodeExpr.');
  6001. };
  6002. AbstractEmitterVisitor.prototype.visitTypeofExpr = function (expr, ctx) {
  6003. ctx.print(expr, 'typeof ');
  6004. expr.expr.visitExpression(this, ctx);
  6005. };
  6006. AbstractEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) {
  6007. var varName = ast.name;
  6008. if (ast.builtin != null) {
  6009. switch (ast.builtin) {
  6010. case exports.BuiltinVar.Super:
  6011. varName = 'super';
  6012. break;
  6013. case exports.BuiltinVar.This:
  6014. varName = 'this';
  6015. break;
  6016. case exports.BuiltinVar.CatchError:
  6017. varName = CATCH_ERROR_VAR$1.name;
  6018. break;
  6019. case exports.BuiltinVar.CatchStack:
  6020. varName = CATCH_STACK_VAR$1.name;
  6021. break;
  6022. default:
  6023. throw new Error("Unknown builtin variable " + ast.builtin);
  6024. }
  6025. }
  6026. ctx.print(ast, varName);
  6027. return null;
  6028. };
  6029. AbstractEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
  6030. ctx.print(ast, "new ");
  6031. ast.classExpr.visitExpression(this, ctx);
  6032. ctx.print(ast, "(");
  6033. this.visitAllExpressions(ast.args, ctx, ',');
  6034. ctx.print(ast, ")");
  6035. return null;
  6036. };
  6037. AbstractEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
  6038. var value = ast.value;
  6039. if (typeof value === 'string') {
  6040. ctx.print(ast, escapeIdentifier(value, this._escapeDollarInStrings));
  6041. }
  6042. else {
  6043. ctx.print(ast, "" + value);
  6044. }
  6045. return null;
  6046. };
  6047. AbstractEmitterVisitor.prototype.visitLocalizedString = function (ast, ctx) {
  6048. var head = ast.serializeI18nHead();
  6049. ctx.print(ast, '$localize `' + head.raw);
  6050. for (var i = 1; i < ast.messageParts.length; i++) {
  6051. ctx.print(ast, '${');
  6052. ast.expressions[i - 1].visitExpression(this, ctx);
  6053. ctx.print(ast, "}" + ast.serializeI18nTemplatePart(i).raw);
  6054. }
  6055. ctx.print(ast, '`');
  6056. return null;
  6057. };
  6058. AbstractEmitterVisitor.prototype.visitConditionalExpr = function (ast, ctx) {
  6059. ctx.print(ast, "(");
  6060. ast.condition.visitExpression(this, ctx);
  6061. ctx.print(ast, '? ');
  6062. ast.trueCase.visitExpression(this, ctx);
  6063. ctx.print(ast, ': ');
  6064. ast.falseCase.visitExpression(this, ctx);
  6065. ctx.print(ast, ")");
  6066. return null;
  6067. };
  6068. AbstractEmitterVisitor.prototype.visitNotExpr = function (ast, ctx) {
  6069. ctx.print(ast, '!');
  6070. ast.condition.visitExpression(this, ctx);
  6071. return null;
  6072. };
  6073. AbstractEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) {
  6074. ast.condition.visitExpression(this, ctx);
  6075. return null;
  6076. };
  6077. AbstractEmitterVisitor.prototype.visitUnaryOperatorExpr = function (ast, ctx) {
  6078. var opStr;
  6079. switch (ast.operator) {
  6080. case exports.UnaryOperator.Plus:
  6081. opStr = '+';
  6082. break;
  6083. case exports.UnaryOperator.Minus:
  6084. opStr = '-';
  6085. break;
  6086. default:
  6087. throw new Error("Unknown operator " + ast.operator);
  6088. }
  6089. if (ast.parens)
  6090. ctx.print(ast, "(");
  6091. ctx.print(ast, opStr);
  6092. ast.expr.visitExpression(this, ctx);
  6093. if (ast.parens)
  6094. ctx.print(ast, ")");
  6095. return null;
  6096. };
  6097. AbstractEmitterVisitor.prototype.visitBinaryOperatorExpr = function (ast, ctx) {
  6098. var opStr;
  6099. switch (ast.operator) {
  6100. case exports.BinaryOperator.Equals:
  6101. opStr = '==';
  6102. break;
  6103. case exports.BinaryOperator.Identical:
  6104. opStr = '===';
  6105. break;
  6106. case exports.BinaryOperator.NotEquals:
  6107. opStr = '!=';
  6108. break;
  6109. case exports.BinaryOperator.NotIdentical:
  6110. opStr = '!==';
  6111. break;
  6112. case exports.BinaryOperator.And:
  6113. opStr = '&&';
  6114. break;
  6115. case exports.BinaryOperator.BitwiseAnd:
  6116. opStr = '&';
  6117. break;
  6118. case exports.BinaryOperator.Or:
  6119. opStr = '||';
  6120. break;
  6121. case exports.BinaryOperator.Plus:
  6122. opStr = '+';
  6123. break;
  6124. case exports.BinaryOperator.Minus:
  6125. opStr = '-';
  6126. break;
  6127. case exports.BinaryOperator.Divide:
  6128. opStr = '/';
  6129. break;
  6130. case exports.BinaryOperator.Multiply:
  6131. opStr = '*';
  6132. break;
  6133. case exports.BinaryOperator.Modulo:
  6134. opStr = '%';
  6135. break;
  6136. case exports.BinaryOperator.Lower:
  6137. opStr = '<';
  6138. break;
  6139. case exports.BinaryOperator.LowerEquals:
  6140. opStr = '<=';
  6141. break;
  6142. case exports.BinaryOperator.Bigger:
  6143. opStr = '>';
  6144. break;
  6145. case exports.BinaryOperator.BiggerEquals:
  6146. opStr = '>=';
  6147. break;
  6148. case exports.BinaryOperator.NullishCoalesce:
  6149. opStr = '??';
  6150. break;
  6151. default:
  6152. throw new Error("Unknown operator " + ast.operator);
  6153. }
  6154. if (ast.parens)
  6155. ctx.print(ast, "(");
  6156. ast.lhs.visitExpression(this, ctx);
  6157. ctx.print(ast, " " + opStr + " ");
  6158. ast.rhs.visitExpression(this, ctx);
  6159. if (ast.parens)
  6160. ctx.print(ast, ")");
  6161. return null;
  6162. };
  6163. AbstractEmitterVisitor.prototype.visitReadPropExpr = function (ast, ctx) {
  6164. ast.receiver.visitExpression(this, ctx);
  6165. ctx.print(ast, ".");
  6166. ctx.print(ast, ast.name);
  6167. return null;
  6168. };
  6169. AbstractEmitterVisitor.prototype.visitReadKeyExpr = function (ast, ctx) {
  6170. ast.receiver.visitExpression(this, ctx);
  6171. ctx.print(ast, "[");
  6172. ast.index.visitExpression(this, ctx);
  6173. ctx.print(ast, "]");
  6174. return null;
  6175. };
  6176. AbstractEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
  6177. ctx.print(ast, "[");
  6178. this.visitAllExpressions(ast.entries, ctx, ',');
  6179. ctx.print(ast, "]");
  6180. return null;
  6181. };
  6182. AbstractEmitterVisitor.prototype.visitLiteralMapExpr = function (ast, ctx) {
  6183. var _this = this;
  6184. ctx.print(ast, "{");
  6185. this.visitAllObjects(function (entry) {
  6186. ctx.print(ast, escapeIdentifier(entry.key, _this._escapeDollarInStrings, entry.quoted) + ":");
  6187. entry.value.visitExpression(_this, ctx);
  6188. }, ast.entries, ctx, ',');
  6189. ctx.print(ast, "}");
  6190. return null;
  6191. };
  6192. AbstractEmitterVisitor.prototype.visitCommaExpr = function (ast, ctx) {
  6193. ctx.print(ast, '(');
  6194. this.visitAllExpressions(ast.parts, ctx, ',');
  6195. ctx.print(ast, ')');
  6196. return null;
  6197. };
  6198. AbstractEmitterVisitor.prototype.visitAllExpressions = function (expressions, ctx, separator) {
  6199. var _this = this;
  6200. this.visitAllObjects(function (expr) { return expr.visitExpression(_this, ctx); }, expressions, ctx, separator);
  6201. };
  6202. AbstractEmitterVisitor.prototype.visitAllObjects = function (handler, expressions, ctx, separator) {
  6203. var incrementedIndent = false;
  6204. for (var i = 0; i < expressions.length; i++) {
  6205. if (i > 0) {
  6206. if (ctx.lineLength() > 80) {
  6207. ctx.print(null, separator, true);
  6208. if (!incrementedIndent) {
  6209. // continuation are marked with double indent.
  6210. ctx.incIndent();
  6211. ctx.incIndent();
  6212. incrementedIndent = true;
  6213. }
  6214. }
  6215. else {
  6216. ctx.print(null, separator, false);
  6217. }
  6218. }
  6219. handler(expressions[i]);
  6220. }
  6221. if (incrementedIndent) {
  6222. // continuation are marked with double indent.
  6223. ctx.decIndent();
  6224. ctx.decIndent();
  6225. }
  6226. };
  6227. AbstractEmitterVisitor.prototype.visitAllStatements = function (statements, ctx) {
  6228. var _this = this;
  6229. statements.forEach(function (stmt) { return stmt.visitStatement(_this, ctx); });
  6230. };
  6231. return AbstractEmitterVisitor;
  6232. }());
  6233. function escapeIdentifier(input, escapeDollar, alwaysQuote) {
  6234. if (alwaysQuote === void 0) { alwaysQuote = true; }
  6235. if (input == null) {
  6236. return null;
  6237. }
  6238. var body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, function () {
  6239. var match = [];
  6240. for (var _i = 0; _i < arguments.length; _i++) {
  6241. match[_i] = arguments[_i];
  6242. }
  6243. if (match[0] == '$') {
  6244. return escapeDollar ? '\\$' : '$';
  6245. }
  6246. else if (match[0] == '\n') {
  6247. return '\\n';
  6248. }
  6249. else if (match[0] == '\r') {
  6250. return '\\r';
  6251. }
  6252. else {
  6253. return "\\" + match[0];
  6254. }
  6255. });
  6256. var requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body);
  6257. return requiresQuotes ? "'" + body + "'" : body;
  6258. }
  6259. function _createIndent(count) {
  6260. var res = '';
  6261. for (var i = 0; i < count; i++) {
  6262. res += _INDENT_WITH;
  6263. }
  6264. return res;
  6265. }
  6266. /**
  6267. * @license
  6268. * Copyright Google LLC All Rights Reserved.
  6269. *
  6270. * Use of this source code is governed by an MIT-style license that can be
  6271. * found in the LICENSE file at https://angular.io/license
  6272. */
  6273. function typeWithParameters(type, numParams) {
  6274. if (numParams === 0) {
  6275. return expressionType(type);
  6276. }
  6277. var params = [];
  6278. for (var i = 0; i < numParams; i++) {
  6279. params.push(DYNAMIC_TYPE);
  6280. }
  6281. return expressionType(type, undefined, params);
  6282. }
  6283. var ANIMATE_SYMBOL_PREFIX = '@';
  6284. function prepareSyntheticPropertyName(name) {
  6285. return "" + ANIMATE_SYMBOL_PREFIX + name;
  6286. }
  6287. function prepareSyntheticListenerName(name, phase) {
  6288. return "" + ANIMATE_SYMBOL_PREFIX + name + "." + phase;
  6289. }
  6290. function getSafePropertyAccessString(accessor, name) {
  6291. var escapedName = escapeIdentifier(name, false, false);
  6292. return escapedName !== name ? accessor + "[" + escapedName + "]" : accessor + "." + name;
  6293. }
  6294. function prepareSyntheticListenerFunctionName(name, phase) {
  6295. return "animation_" + name + "_" + phase;
  6296. }
  6297. function jitOnlyGuardedExpression(expr) {
  6298. return guardedExpression('ngJitMode', expr);
  6299. }
  6300. function devOnlyGuardedExpression(expr) {
  6301. return guardedExpression('ngDevMode', expr);
  6302. }
  6303. function guardedExpression(guard, expr) {
  6304. var guardExpr = new ExternalExpr({ name: guard, moduleName: null });
  6305. var guardNotDefined = new BinaryOperatorExpr(exports.BinaryOperator.Identical, new TypeofExpr(guardExpr), literal('undefined'));
  6306. var guardUndefinedOrTrue = new BinaryOperatorExpr(exports.BinaryOperator.Or, guardNotDefined, guardExpr, /* type */ undefined,
  6307. /* sourceSpan */ undefined, true);
  6308. return new BinaryOperatorExpr(exports.BinaryOperator.And, guardUndefinedOrTrue, expr);
  6309. }
  6310. function wrapReference(value) {
  6311. var wrapped = new WrappedNodeExpr(value);
  6312. return { value: wrapped, type: wrapped };
  6313. }
  6314. function refsToArray(refs, shouldForwardDeclare) {
  6315. var values = literalArr(refs.map(function (ref) { return ref.value; }));
  6316. return shouldForwardDeclare ? fn([], [new ReturnStatement(values)]) : values;
  6317. }
  6318. /**
  6319. * @license
  6320. * Copyright Google LLC All Rights Reserved.
  6321. *
  6322. * Use of this source code is governed by an MIT-style license that can be
  6323. * found in the LICENSE file at https://angular.io/license
  6324. */
  6325. var R3FactoryDelegateType;
  6326. (function (R3FactoryDelegateType) {
  6327. R3FactoryDelegateType[R3FactoryDelegateType["Class"] = 0] = "Class";
  6328. R3FactoryDelegateType[R3FactoryDelegateType["Function"] = 1] = "Function";
  6329. })(R3FactoryDelegateType || (R3FactoryDelegateType = {}));
  6330. (function (FactoryTarget) {
  6331. FactoryTarget[FactoryTarget["Directive"] = 0] = "Directive";
  6332. FactoryTarget[FactoryTarget["Component"] = 1] = "Component";
  6333. FactoryTarget[FactoryTarget["Injectable"] = 2] = "Injectable";
  6334. FactoryTarget[FactoryTarget["Pipe"] = 3] = "Pipe";
  6335. FactoryTarget[FactoryTarget["NgModule"] = 4] = "NgModule";
  6336. })(exports.FactoryTarget || (exports.FactoryTarget = {}));
  6337. /**
  6338. * Construct a factory function expression for the given `R3FactoryMetadata`.
  6339. */
  6340. function compileFactoryFunction(meta) {
  6341. var t = variable('t');
  6342. var baseFactoryVar = null;
  6343. // The type to instantiate via constructor invocation. If there is no delegated factory, meaning
  6344. // this type is always created by constructor invocation, then this is the type-to-create
  6345. // parameter provided by the user (t) if specified, or the current type if not. If there is a
  6346. // delegated factory (which is used to create the current type) then this is only the type-to-
  6347. // create parameter (t).
  6348. var typeForCtor = !isDelegatedFactoryMetadata(meta) ?
  6349. new BinaryOperatorExpr(exports.BinaryOperator.Or, t, meta.internalType) :
  6350. t;
  6351. var ctorExpr = null;
  6352. if (meta.deps !== null) {
  6353. // There is a constructor (either explicitly or implicitly defined).
  6354. if (meta.deps !== 'invalid') {
  6355. ctorExpr = new InstantiateExpr(typeForCtor, injectDependencies(meta.deps, meta.target));
  6356. }
  6357. }
  6358. else {
  6359. // There is no constructor, use the base class' factory to construct typeForCtor.
  6360. baseFactoryVar = variable("\u0275" + meta.name + "_BaseFactory");
  6361. ctorExpr = baseFactoryVar.callFn([typeForCtor]);
  6362. }
  6363. var body = [];
  6364. var retExpr = null;
  6365. function makeConditionalFactory(nonCtorExpr) {
  6366. var r = variable('r');
  6367. body.push(r.set(NULL_EXPR).toDeclStmt());
  6368. var ctorStmt = ctorExpr !== null ? r.set(ctorExpr).toStmt() :
  6369. importExpr(Identifiers.invalidFactory).callFn([]).toStmt();
  6370. body.push(ifStmt(t, [ctorStmt], [r.set(nonCtorExpr).toStmt()]));
  6371. return r;
  6372. }
  6373. if (isDelegatedFactoryMetadata(meta)) {
  6374. // This type is created with a delegated factory. If a type parameter is not specified, call
  6375. // the factory instead.
  6376. var delegateArgs = injectDependencies(meta.delegateDeps, meta.target);
  6377. // Either call `new delegate(...)` or `delegate(...)` depending on meta.delegateType.
  6378. var factoryExpr = new (meta.delegateType === R3FactoryDelegateType.Class ?
  6379. InstantiateExpr :
  6380. InvokeFunctionExpr)(meta.delegate, delegateArgs);
  6381. retExpr = makeConditionalFactory(factoryExpr);
  6382. }
  6383. else if (isExpressionFactoryMetadata(meta)) {
  6384. // TODO(alxhub): decide whether to lower the value here or in the caller
  6385. retExpr = makeConditionalFactory(meta.expression);
  6386. }
  6387. else {
  6388. retExpr = ctorExpr;
  6389. }
  6390. if (retExpr === null) {
  6391. // The expression cannot be formed so render an `ɵɵinvalidFactory()` call.
  6392. body.push(importExpr(Identifiers.invalidFactory).callFn([]).toStmt());
  6393. }
  6394. else if (baseFactoryVar !== null) {
  6395. // This factory uses a base factory, so call `ɵɵgetInheritedFactory()` to compute it.
  6396. var getInheritedFactoryCall = importExpr(Identifiers.getInheritedFactory).callFn([meta.internalType]);
  6397. // Memoize the base factoryFn: `baseFactory || (baseFactory = ɵɵgetInheritedFactory(...))`
  6398. var baseFactory = new BinaryOperatorExpr(exports.BinaryOperator.Or, baseFactoryVar, baseFactoryVar.set(getInheritedFactoryCall));
  6399. body.push(new ReturnStatement(baseFactory.callFn([typeForCtor])));
  6400. }
  6401. else {
  6402. // This is straightforward factory, just return it.
  6403. body.push(new ReturnStatement(retExpr));
  6404. }
  6405. var factoryFn = fn([new FnParam('t', DYNAMIC_TYPE)], body, INFERRED_TYPE, undefined, meta.name + "_Factory");
  6406. if (baseFactoryVar !== null) {
  6407. // There is a base factory variable so wrap its declaration along with the factory function into
  6408. // an IIFE.
  6409. factoryFn = fn([], [
  6410. new DeclareVarStmt(baseFactoryVar.name),
  6411. new ReturnStatement(factoryFn)
  6412. ]).callFn([], /* sourceSpan */ undefined, /* pure */ true);
  6413. }
  6414. return {
  6415. expression: factoryFn,
  6416. statements: [],
  6417. type: createFactoryType(meta),
  6418. };
  6419. }
  6420. function createFactoryType(meta) {
  6421. var ctorDepsType = meta.deps !== null && meta.deps !== 'invalid' ? createCtorDepsType(meta.deps) : NONE_TYPE;
  6422. return expressionType(importExpr(Identifiers.FactoryDeclaration, [typeWithParameters(meta.type.type, meta.typeArgumentCount), ctorDepsType]));
  6423. }
  6424. function injectDependencies(deps, target) {
  6425. return deps.map(function (dep, index) { return compileInjectDependency(dep, target, index); });
  6426. }
  6427. function compileInjectDependency(dep, target, index) {
  6428. // Interpret the dependency according to its resolved type.
  6429. if (dep.token === null) {
  6430. return importExpr(Identifiers.invalidFactoryDep).callFn([literal(index)]);
  6431. }
  6432. else if (dep.attributeNameType === null) {
  6433. // Build up the injection flags according to the metadata.
  6434. var flags = 0 /* Default */ | (dep.self ? 2 /* Self */ : 0) |
  6435. (dep.skipSelf ? 4 /* SkipSelf */ : 0) | (dep.host ? 1 /* Host */ : 0) |
  6436. (dep.optional ? 8 /* Optional */ : 0) |
  6437. (target === exports.FactoryTarget.Pipe ? 16 /* ForPipe */ : 0);
  6438. // If this dependency is optional or otherwise has non-default flags, then additional
  6439. // parameters describing how to inject the dependency must be passed to the inject function
  6440. // that's being used.
  6441. var flagsParam = (flags !== 0 /* Default */ || dep.optional) ? literal(flags) : null;
  6442. // Build up the arguments to the injectFn call.
  6443. var injectArgs = [dep.token];
  6444. if (flagsParam) {
  6445. injectArgs.push(flagsParam);
  6446. }
  6447. var injectFn = getInjectFn(target);
  6448. return importExpr(injectFn).callFn(injectArgs);
  6449. }
  6450. else {
  6451. // The `dep.attributeTypeName` value is defined, which indicates that this is an `@Attribute()`
  6452. // type dependency. For the generated JS we still want to use the `dep.token` value in case the
  6453. // name given for the attribute is not a string literal. For example given `@Attribute(foo())`,
  6454. // we want to generate `ɵɵinjectAttribute(foo())`.
  6455. //
  6456. // The `dep.attributeTypeName` is only actually used (in `createCtorDepType()`) to generate
  6457. // typings.
  6458. return importExpr(Identifiers.injectAttribute).callFn([dep.token]);
  6459. }
  6460. }
  6461. function createCtorDepsType(deps) {
  6462. var hasTypes = false;
  6463. var attributeTypes = deps.map(function (dep) {
  6464. var type = createCtorDepType(dep);
  6465. if (type !== null) {
  6466. hasTypes = true;
  6467. return type;
  6468. }
  6469. else {
  6470. return literal(null);
  6471. }
  6472. });
  6473. if (hasTypes) {
  6474. return expressionType(literalArr(attributeTypes));
  6475. }
  6476. else {
  6477. return NONE_TYPE;
  6478. }
  6479. }
  6480. function createCtorDepType(dep) {
  6481. var entries = [];
  6482. if (dep.attributeNameType !== null) {
  6483. entries.push({ key: 'attribute', value: dep.attributeNameType, quoted: false });
  6484. }
  6485. if (dep.optional) {
  6486. entries.push({ key: 'optional', value: literal(true), quoted: false });
  6487. }
  6488. if (dep.host) {
  6489. entries.push({ key: 'host', value: literal(true), quoted: false });
  6490. }
  6491. if (dep.self) {
  6492. entries.push({ key: 'self', value: literal(true), quoted: false });
  6493. }
  6494. if (dep.skipSelf) {
  6495. entries.push({ key: 'skipSelf', value: literal(true), quoted: false });
  6496. }
  6497. return entries.length > 0 ? literalMap(entries) : null;
  6498. }
  6499. function isDelegatedFactoryMetadata(meta) {
  6500. return meta.delegateType !== undefined;
  6501. }
  6502. function isExpressionFactoryMetadata(meta) {
  6503. return meta.expression !== undefined;
  6504. }
  6505. function getInjectFn(target) {
  6506. switch (target) {
  6507. case exports.FactoryTarget.Component:
  6508. case exports.FactoryTarget.Directive:
  6509. case exports.FactoryTarget.Pipe:
  6510. return Identifiers.directiveInject;
  6511. case exports.FactoryTarget.NgModule:
  6512. case exports.FactoryTarget.Injectable:
  6513. default:
  6514. return Identifiers.inject;
  6515. }
  6516. }
  6517. /**
  6518. * @license
  6519. * Copyright Google LLC All Rights Reserved.
  6520. *
  6521. * Use of this source code is governed by an MIT-style license that can be
  6522. * found in the LICENSE file at https://angular.io/license
  6523. */
  6524. function createR3ProviderExpression(expression, isForwardRef) {
  6525. return { expression: expression, isForwardRef: isForwardRef };
  6526. }
  6527. function compileInjectable(meta, resolveForwardRefs) {
  6528. var result = null;
  6529. var factoryMeta = {
  6530. name: meta.name,
  6531. type: meta.type,
  6532. internalType: meta.internalType,
  6533. typeArgumentCount: meta.typeArgumentCount,
  6534. deps: [],
  6535. target: exports.FactoryTarget.Injectable,
  6536. };
  6537. if (meta.useClass !== undefined) {
  6538. // meta.useClass has two modes of operation. Either deps are specified, in which case `new` is
  6539. // used to instantiate the class with dependencies injected, or deps are not specified and
  6540. // the factory of the class is used to instantiate it.
  6541. //
  6542. // A special case exists for useClass: Type where Type is the injectable type itself and no
  6543. // deps are specified, in which case 'useClass' is effectively ignored.
  6544. var useClassOnSelf = meta.useClass.expression.isEquivalent(meta.internalType);
  6545. var deps = undefined;
  6546. if (meta.deps !== undefined) {
  6547. deps = meta.deps;
  6548. }
  6549. if (deps !== undefined) {
  6550. // factory: () => new meta.useClass(...deps)
  6551. result = compileFactoryFunction(Object.assign(Object.assign({}, factoryMeta), { delegate: meta.useClass.expression, delegateDeps: deps, delegateType: R3FactoryDelegateType.Class }));
  6552. }
  6553. else if (useClassOnSelf) {
  6554. result = compileFactoryFunction(factoryMeta);
  6555. }
  6556. else {
  6557. result = {
  6558. statements: [],
  6559. expression: delegateToFactory(meta.type.value, meta.useClass.expression, resolveForwardRefs)
  6560. };
  6561. }
  6562. }
  6563. else if (meta.useFactory !== undefined) {
  6564. if (meta.deps !== undefined) {
  6565. result = compileFactoryFunction(Object.assign(Object.assign({}, factoryMeta), { delegate: meta.useFactory, delegateDeps: meta.deps || [], delegateType: R3FactoryDelegateType.Function }));
  6566. }
  6567. else {
  6568. result = {
  6569. statements: [],
  6570. expression: fn([], [new ReturnStatement(meta.useFactory.callFn([]))])
  6571. };
  6572. }
  6573. }
  6574. else if (meta.useValue !== undefined) {
  6575. // Note: it's safe to use `meta.useValue` instead of the `USE_VALUE in meta` check used for
  6576. // client code because meta.useValue is an Expression which will be defined even if the actual
  6577. // value is undefined.
  6578. result = compileFactoryFunction(Object.assign(Object.assign({}, factoryMeta), { expression: meta.useValue.expression }));
  6579. }
  6580. else if (meta.useExisting !== undefined) {
  6581. // useExisting is an `inject` call on the existing token.
  6582. result = compileFactoryFunction(Object.assign(Object.assign({}, factoryMeta), { expression: importExpr(Identifiers.inject).callFn([meta.useExisting.expression]) }));
  6583. }
  6584. else {
  6585. result = {
  6586. statements: [],
  6587. expression: delegateToFactory(meta.type.value, meta.internalType, resolveForwardRefs)
  6588. };
  6589. }
  6590. var token = meta.internalType;
  6591. var injectableProps = new DefinitionMap();
  6592. injectableProps.set('token', token);
  6593. injectableProps.set('factory', result.expression);
  6594. // Only generate providedIn property if it has a non-null value
  6595. if (meta.providedIn.expression.value !== null) {
  6596. injectableProps.set('providedIn', meta.providedIn.isForwardRef ? generateForwardRef(meta.providedIn.expression) :
  6597. meta.providedIn.expression);
  6598. }
  6599. var expression = importExpr(Identifiers.ɵɵdefineInjectable)
  6600. .callFn([injectableProps.toLiteralMap()], undefined, true);
  6601. return {
  6602. expression: expression,
  6603. type: createInjectableType(meta),
  6604. statements: result.statements,
  6605. };
  6606. }
  6607. function createInjectableType(meta) {
  6608. return new ExpressionType(importExpr(Identifiers.InjectableDeclaration, [typeWithParameters(meta.type.type, meta.typeArgumentCount)]));
  6609. }
  6610. function delegateToFactory(type, internalType, unwrapForwardRefs) {
  6611. if (type.node === internalType.node) {
  6612. // The types are the same, so we can simply delegate directly to the type's factory.
  6613. // ```
  6614. // factory: type.ɵfac
  6615. // ```
  6616. return internalType.prop('ɵfac');
  6617. }
  6618. if (!unwrapForwardRefs) {
  6619. // The type is not wrapped in a `forwardRef()`, so we create a simple factory function that
  6620. // accepts a sub-type as an argument.
  6621. // ```
  6622. // factory: function(t) { return internalType.ɵfac(t); }
  6623. // ```
  6624. return createFactoryFunction(internalType);
  6625. }
  6626. // The internalType is actually wrapped in a `forwardRef()` so we need to resolve that before
  6627. // calling its factory.
  6628. // ```
  6629. // factory: function(t) { return core.resolveForwardRef(type).ɵfac(t); }
  6630. // ```
  6631. var unwrappedType = importExpr(Identifiers.resolveForwardRef).callFn([internalType]);
  6632. return createFactoryFunction(unwrappedType);
  6633. }
  6634. function createFactoryFunction(type) {
  6635. return fn([new FnParam('t', DYNAMIC_TYPE)], [new ReturnStatement(type.callMethod('ɵfac', [variable('t')]))]);
  6636. }
  6637. /**
  6638. * @license
  6639. * Copyright Google LLC All Rights Reserved.
  6640. *
  6641. * Use of this source code is governed by an MIT-style license that can be
  6642. * found in the LICENSE file at https://angular.io/license
  6643. */
  6644. function assertArrayOfStrings(identifier, value) {
  6645. if (value == null) {
  6646. return;
  6647. }
  6648. if (!Array.isArray(value)) {
  6649. throw new Error("Expected '" + identifier + "' to be an array of strings.");
  6650. }
  6651. for (var i = 0; i < value.length; i += 1) {
  6652. if (typeof value[i] !== 'string') {
  6653. throw new Error("Expected '" + identifier + "' to be an array of strings.");
  6654. }
  6655. }
  6656. }
  6657. var UNUSABLE_INTERPOLATION_REGEXPS = [
  6658. /^\s*$/,
  6659. /[<>]/,
  6660. /^[{}]$/,
  6661. /&(#|[a-z])/i,
  6662. /^\/\//, // comment
  6663. ];
  6664. function assertInterpolationSymbols(identifier, value) {
  6665. if (value != null && !(Array.isArray(value) && value.length == 2)) {
  6666. throw new Error("Expected '" + identifier + "' to be an array, [start, end].");
  6667. }
  6668. else if (value != null) {
  6669. var start_1 = value[0];
  6670. var end_1 = value[1];
  6671. // Check for unusable interpolation symbols
  6672. UNUSABLE_INTERPOLATION_REGEXPS.forEach(function (regexp) {
  6673. if (regexp.test(start_1) || regexp.test(end_1)) {
  6674. throw new Error("['" + start_1 + "', '" + end_1 + "'] contains unusable interpolation symbol.");
  6675. }
  6676. });
  6677. }
  6678. }
  6679. /**
  6680. * @license
  6681. * Copyright Google LLC All Rights Reserved.
  6682. *
  6683. * Use of this source code is governed by an MIT-style license that can be
  6684. * found in the LICENSE file at https://angular.io/license
  6685. */
  6686. var InterpolationConfig = /** @class */ (function () {
  6687. function InterpolationConfig(start, end) {
  6688. this.start = start;
  6689. this.end = end;
  6690. }
  6691. InterpolationConfig.fromArray = function (markers) {
  6692. if (!markers) {
  6693. return DEFAULT_INTERPOLATION_CONFIG;
  6694. }
  6695. assertInterpolationSymbols('interpolation', markers);
  6696. return new InterpolationConfig(markers[0], markers[1]);
  6697. };
  6698. return InterpolationConfig;
  6699. }());
  6700. var DEFAULT_INTERPOLATION_CONFIG = new InterpolationConfig('{{', '}}');
  6701. /**
  6702. * @license
  6703. * Copyright Google LLC All Rights Reserved.
  6704. *
  6705. * Use of this source code is governed by an MIT-style license that can be
  6706. * found in the LICENSE file at https://angular.io/license
  6707. */
  6708. /**
  6709. * A token representing the a reference to a static type.
  6710. *
  6711. * This token is unique for a filePath and name and can be used as a hash table key.
  6712. */
  6713. var StaticSymbol = /** @class */ (function () {
  6714. function StaticSymbol(filePath, name, members) {
  6715. this.filePath = filePath;
  6716. this.name = name;
  6717. this.members = members;
  6718. }
  6719. StaticSymbol.prototype.assertNoMembers = function () {
  6720. if (this.members.length) {
  6721. throw new Error("Illegal state: symbol without members expected, but got " + JSON.stringify(this) + ".");
  6722. }
  6723. };
  6724. return StaticSymbol;
  6725. }());
  6726. /**
  6727. * A cache of static symbol used by the StaticReflector to return the same symbol for the
  6728. * same symbol values.
  6729. */
  6730. var StaticSymbolCache = /** @class */ (function () {
  6731. function StaticSymbolCache() {
  6732. this.cache = new Map();
  6733. }
  6734. StaticSymbolCache.prototype.get = function (declarationFile, name, members) {
  6735. members = members || [];
  6736. var memberSuffix = members.length ? "." + members.join('.') : '';
  6737. var key = "\"" + declarationFile + "\"." + name + memberSuffix;
  6738. var result = this.cache.get(key);
  6739. if (!result) {
  6740. result = new StaticSymbol(declarationFile, name, members);
  6741. this.cache.set(key, result);
  6742. }
  6743. return result;
  6744. };
  6745. return StaticSymbolCache;
  6746. }());
  6747. /**
  6748. * @license
  6749. * Copyright Google LLC All Rights Reserved.
  6750. *
  6751. * Use of this source code is governed by an MIT-style license that can be
  6752. * found in the LICENSE file at https://angular.io/license
  6753. */
  6754. // group 0: "[prop] or (event) or @trigger"
  6755. // group 1: "prop" from "[prop]"
  6756. // group 2: "event" from "(event)"
  6757. // group 3: "@trigger" from "@trigger"
  6758. var HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/;
  6759. function sanitizeIdentifier(name) {
  6760. return name.replace(/\W/g, '_');
  6761. }
  6762. var _anonymousTypeIndex = 0;
  6763. function identifierName(compileIdentifier) {
  6764. if (!compileIdentifier || !compileIdentifier.reference) {
  6765. return null;
  6766. }
  6767. var ref = compileIdentifier.reference;
  6768. if (ref instanceof StaticSymbol) {
  6769. return ref.name;
  6770. }
  6771. if (ref['__anonymousType']) {
  6772. return ref['__anonymousType'];
  6773. }
  6774. if (ref['__forward_ref__']) {
  6775. // We do not want to try to stringify a `forwardRef()` function because that would cause the
  6776. // inner function to be evaluated too early, defeating the whole point of the `forwardRef`.
  6777. return '__forward_ref__';
  6778. }
  6779. var identifier = stringify(ref);
  6780. if (identifier.indexOf('(') >= 0) {
  6781. // case: anonymous functions!
  6782. identifier = "anonymous_" + _anonymousTypeIndex++;
  6783. ref['__anonymousType'] = identifier;
  6784. }
  6785. else {
  6786. identifier = sanitizeIdentifier(identifier);
  6787. }
  6788. return identifier;
  6789. }
  6790. function identifierModuleUrl(compileIdentifier) {
  6791. var ref = compileIdentifier.reference;
  6792. if (ref instanceof StaticSymbol) {
  6793. return ref.filePath;
  6794. }
  6795. // Runtime type
  6796. return "./" + stringify(ref);
  6797. }
  6798. function viewClassName(compType, embeddedTemplateIndex) {
  6799. return "View_" + identifierName({ reference: compType }) + "_" + embeddedTemplateIndex;
  6800. }
  6801. function rendererTypeName(compType) {
  6802. return "RenderType_" + identifierName({ reference: compType });
  6803. }
  6804. function hostViewClassName(compType) {
  6805. return "HostView_" + identifierName({ reference: compType });
  6806. }
  6807. function componentFactoryName(compType) {
  6808. return identifierName({ reference: compType }) + "NgFactory";
  6809. }
  6810. (function (CompileSummaryKind) {
  6811. CompileSummaryKind[CompileSummaryKind["Pipe"] = 0] = "Pipe";
  6812. CompileSummaryKind[CompileSummaryKind["Directive"] = 1] = "Directive";
  6813. CompileSummaryKind[CompileSummaryKind["NgModule"] = 2] = "NgModule";
  6814. CompileSummaryKind[CompileSummaryKind["Injectable"] = 3] = "Injectable";
  6815. })(exports.CompileSummaryKind || (exports.CompileSummaryKind = {}));
  6816. function tokenName(token) {
  6817. return token.value != null ? sanitizeIdentifier(token.value) : identifierName(token.identifier);
  6818. }
  6819. function tokenReference(token) {
  6820. if (token.identifier != null) {
  6821. return token.identifier.reference;
  6822. }
  6823. else {
  6824. return token.value;
  6825. }
  6826. }
  6827. /**
  6828. * Metadata about a stylesheet
  6829. */
  6830. var CompileStylesheetMetadata = /** @class */ (function () {
  6831. function CompileStylesheetMetadata(_a) {
  6832. var _b = _a === void 0 ? {} : _a, moduleUrl = _b.moduleUrl, styles = _b.styles, styleUrls = _b.styleUrls;
  6833. this.moduleUrl = moduleUrl || null;
  6834. this.styles = _normalizeArray(styles);
  6835. this.styleUrls = _normalizeArray(styleUrls);
  6836. }
  6837. return CompileStylesheetMetadata;
  6838. }());
  6839. /**
  6840. * Metadata regarding compilation of a template.
  6841. */
  6842. var CompileTemplateMetadata = /** @class */ (function () {
  6843. function CompileTemplateMetadata(_a) {
  6844. var encapsulation = _a.encapsulation, template = _a.template, templateUrl = _a.templateUrl, htmlAst = _a.htmlAst, styles = _a.styles, styleUrls = _a.styleUrls, externalStylesheets = _a.externalStylesheets, animations = _a.animations, ngContentSelectors = _a.ngContentSelectors, interpolation = _a.interpolation, isInline = _a.isInline, preserveWhitespaces = _a.preserveWhitespaces;
  6845. this.encapsulation = encapsulation;
  6846. this.template = template;
  6847. this.templateUrl = templateUrl;
  6848. this.htmlAst = htmlAst;
  6849. this.styles = _normalizeArray(styles);
  6850. this.styleUrls = _normalizeArray(styleUrls);
  6851. this.externalStylesheets = _normalizeArray(externalStylesheets);
  6852. this.animations = animations ? flatten(animations) : [];
  6853. this.ngContentSelectors = ngContentSelectors || [];
  6854. if (interpolation && interpolation.length != 2) {
  6855. throw new Error("'interpolation' should have a start and an end symbol.");
  6856. }
  6857. this.interpolation = interpolation;
  6858. this.isInline = isInline;
  6859. this.preserveWhitespaces = preserveWhitespaces;
  6860. }
  6861. CompileTemplateMetadata.prototype.toSummary = function () {
  6862. return {
  6863. ngContentSelectors: this.ngContentSelectors,
  6864. encapsulation: this.encapsulation,
  6865. styles: this.styles,
  6866. animations: this.animations
  6867. };
  6868. };
  6869. return CompileTemplateMetadata;
  6870. }());
  6871. /**
  6872. * Metadata regarding compilation of a directive.
  6873. */
  6874. var CompileDirectiveMetadata = /** @class */ (function () {
  6875. function CompileDirectiveMetadata(_a) {
  6876. var isHost = _a.isHost, type = _a.type, isComponent = _a.isComponent, selector = _a.selector, exportAs = _a.exportAs, changeDetection = _a.changeDetection, inputs = _a.inputs, outputs = _a.outputs, hostListeners = _a.hostListeners, hostProperties = _a.hostProperties, hostAttributes = _a.hostAttributes, providers = _a.providers, viewProviders = _a.viewProviders, queries = _a.queries, guards = _a.guards, viewQueries = _a.viewQueries, entryComponents = _a.entryComponents, template = _a.template, componentViewType = _a.componentViewType, rendererType = _a.rendererType, componentFactory = _a.componentFactory;
  6877. this.isHost = !!isHost;
  6878. this.type = type;
  6879. this.isComponent = isComponent;
  6880. this.selector = selector;
  6881. this.exportAs = exportAs;
  6882. this.changeDetection = changeDetection;
  6883. this.inputs = inputs;
  6884. this.outputs = outputs;
  6885. this.hostListeners = hostListeners;
  6886. this.hostProperties = hostProperties;
  6887. this.hostAttributes = hostAttributes;
  6888. this.providers = _normalizeArray(providers);
  6889. this.viewProviders = _normalizeArray(viewProviders);
  6890. this.queries = _normalizeArray(queries);
  6891. this.guards = guards;
  6892. this.viewQueries = _normalizeArray(viewQueries);
  6893. this.entryComponents = _normalizeArray(entryComponents);
  6894. this.template = template;
  6895. this.componentViewType = componentViewType;
  6896. this.rendererType = rendererType;
  6897. this.componentFactory = componentFactory;
  6898. }
  6899. CompileDirectiveMetadata.create = function (_a) {
  6900. var isHost = _a.isHost, type = _a.type, isComponent = _a.isComponent, selector = _a.selector, exportAs = _a.exportAs, changeDetection = _a.changeDetection, inputs = _a.inputs, outputs = _a.outputs, host = _a.host, providers = _a.providers, viewProviders = _a.viewProviders, queries = _a.queries, guards = _a.guards, viewQueries = _a.viewQueries, entryComponents = _a.entryComponents, template = _a.template, componentViewType = _a.componentViewType, rendererType = _a.rendererType, componentFactory = _a.componentFactory;
  6901. var hostListeners = {};
  6902. var hostProperties = {};
  6903. var hostAttributes = {};
  6904. if (host != null) {
  6905. Object.keys(host).forEach(function (key) {
  6906. var value = host[key];
  6907. var matches = key.match(HOST_REG_EXP);
  6908. if (matches === null) {
  6909. hostAttributes[key] = value;
  6910. }
  6911. else if (matches[1] != null) {
  6912. hostProperties[matches[1]] = value;
  6913. }
  6914. else if (matches[2] != null) {
  6915. hostListeners[matches[2]] = value;
  6916. }
  6917. });
  6918. }
  6919. var inputsMap = {};
  6920. if (inputs != null) {
  6921. inputs.forEach(function (bindConfig) {
  6922. // canonical syntax: `dirProp: elProp`
  6923. // if there is no `:`, use dirProp = elProp
  6924. var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
  6925. inputsMap[parts[0]] = parts[1];
  6926. });
  6927. }
  6928. var outputsMap = {};
  6929. if (outputs != null) {
  6930. outputs.forEach(function (bindConfig) {
  6931. // canonical syntax: `dirProp: elProp`
  6932. // if there is no `:`, use dirProp = elProp
  6933. var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
  6934. outputsMap[parts[0]] = parts[1];
  6935. });
  6936. }
  6937. return new CompileDirectiveMetadata({
  6938. isHost: isHost,
  6939. type: type,
  6940. isComponent: !!isComponent,
  6941. selector: selector,
  6942. exportAs: exportAs,
  6943. changeDetection: changeDetection,
  6944. inputs: inputsMap,
  6945. outputs: outputsMap,
  6946. hostListeners: hostListeners,
  6947. hostProperties: hostProperties,
  6948. hostAttributes: hostAttributes,
  6949. providers: providers,
  6950. viewProviders: viewProviders,
  6951. queries: queries,
  6952. guards: guards,
  6953. viewQueries: viewQueries,
  6954. entryComponents: entryComponents,
  6955. template: template,
  6956. componentViewType: componentViewType,
  6957. rendererType: rendererType,
  6958. componentFactory: componentFactory,
  6959. });
  6960. };
  6961. CompileDirectiveMetadata.prototype.toSummary = function () {
  6962. return {
  6963. summaryKind: exports.CompileSummaryKind.Directive,
  6964. type: this.type,
  6965. isComponent: this.isComponent,
  6966. selector: this.selector,
  6967. exportAs: this.exportAs,
  6968. inputs: this.inputs,
  6969. outputs: this.outputs,
  6970. hostListeners: this.hostListeners,
  6971. hostProperties: this.hostProperties,
  6972. hostAttributes: this.hostAttributes,
  6973. providers: this.providers,
  6974. viewProviders: this.viewProviders,
  6975. queries: this.queries,
  6976. guards: this.guards,
  6977. viewQueries: this.viewQueries,
  6978. entryComponents: this.entryComponents,
  6979. changeDetection: this.changeDetection,
  6980. template: this.template && this.template.toSummary(),
  6981. componentViewType: this.componentViewType,
  6982. rendererType: this.rendererType,
  6983. componentFactory: this.componentFactory
  6984. };
  6985. };
  6986. return CompileDirectiveMetadata;
  6987. }());
  6988. var CompilePipeMetadata = /** @class */ (function () {
  6989. function CompilePipeMetadata(_a) {
  6990. var type = _a.type, name = _a.name, pure = _a.pure;
  6991. this.type = type;
  6992. this.name = name;
  6993. this.pure = !!pure;
  6994. }
  6995. CompilePipeMetadata.prototype.toSummary = function () {
  6996. return {
  6997. summaryKind: exports.CompileSummaryKind.Pipe,
  6998. type: this.type,
  6999. name: this.name,
  7000. pure: this.pure
  7001. };
  7002. };
  7003. return CompilePipeMetadata;
  7004. }());
  7005. var CompileShallowModuleMetadata = /** @class */ (function () {
  7006. function CompileShallowModuleMetadata() {
  7007. }
  7008. return CompileShallowModuleMetadata;
  7009. }());
  7010. /**
  7011. * Metadata regarding compilation of a module.
  7012. */
  7013. var CompileNgModuleMetadata = /** @class */ (function () {
  7014. function CompileNgModuleMetadata(_a) {
  7015. var type = _a.type, providers = _a.providers, declaredDirectives = _a.declaredDirectives, exportedDirectives = _a.exportedDirectives, declaredPipes = _a.declaredPipes, exportedPipes = _a.exportedPipes, entryComponents = _a.entryComponents, bootstrapComponents = _a.bootstrapComponents, importedModules = _a.importedModules, exportedModules = _a.exportedModules, schemas = _a.schemas, transitiveModule = _a.transitiveModule, id = _a.id;
  7016. this.type = type || null;
  7017. this.declaredDirectives = _normalizeArray(declaredDirectives);
  7018. this.exportedDirectives = _normalizeArray(exportedDirectives);
  7019. this.declaredPipes = _normalizeArray(declaredPipes);
  7020. this.exportedPipes = _normalizeArray(exportedPipes);
  7021. this.providers = _normalizeArray(providers);
  7022. this.entryComponents = _normalizeArray(entryComponents);
  7023. this.bootstrapComponents = _normalizeArray(bootstrapComponents);
  7024. this.importedModules = _normalizeArray(importedModules);
  7025. this.exportedModules = _normalizeArray(exportedModules);
  7026. this.schemas = _normalizeArray(schemas);
  7027. this.id = id || null;
  7028. this.transitiveModule = transitiveModule || null;
  7029. }
  7030. CompileNgModuleMetadata.prototype.toSummary = function () {
  7031. var module = this.transitiveModule;
  7032. return {
  7033. summaryKind: exports.CompileSummaryKind.NgModule,
  7034. type: this.type,
  7035. entryComponents: module.entryComponents,
  7036. providers: module.providers,
  7037. modules: module.modules,
  7038. exportedDirectives: module.exportedDirectives,
  7039. exportedPipes: module.exportedPipes
  7040. };
  7041. };
  7042. return CompileNgModuleMetadata;
  7043. }());
  7044. var TransitiveCompileNgModuleMetadata = /** @class */ (function () {
  7045. function TransitiveCompileNgModuleMetadata() {
  7046. this.directivesSet = new Set();
  7047. this.directives = [];
  7048. this.exportedDirectivesSet = new Set();
  7049. this.exportedDirectives = [];
  7050. this.pipesSet = new Set();
  7051. this.pipes = [];
  7052. this.exportedPipesSet = new Set();
  7053. this.exportedPipes = [];
  7054. this.modulesSet = new Set();
  7055. this.modules = [];
  7056. this.entryComponentsSet = new Set();
  7057. this.entryComponents = [];
  7058. this.providers = [];
  7059. }
  7060. TransitiveCompileNgModuleMetadata.prototype.addProvider = function (provider, module) {
  7061. this.providers.push({ provider: provider, module: module });
  7062. };
  7063. TransitiveCompileNgModuleMetadata.prototype.addDirective = function (id) {
  7064. if (!this.directivesSet.has(id.reference)) {
  7065. this.directivesSet.add(id.reference);
  7066. this.directives.push(id);
  7067. }
  7068. };
  7069. TransitiveCompileNgModuleMetadata.prototype.addExportedDirective = function (id) {
  7070. if (!this.exportedDirectivesSet.has(id.reference)) {
  7071. this.exportedDirectivesSet.add(id.reference);
  7072. this.exportedDirectives.push(id);
  7073. }
  7074. };
  7075. TransitiveCompileNgModuleMetadata.prototype.addPipe = function (id) {
  7076. if (!this.pipesSet.has(id.reference)) {
  7077. this.pipesSet.add(id.reference);
  7078. this.pipes.push(id);
  7079. }
  7080. };
  7081. TransitiveCompileNgModuleMetadata.prototype.addExportedPipe = function (id) {
  7082. if (!this.exportedPipesSet.has(id.reference)) {
  7083. this.exportedPipesSet.add(id.reference);
  7084. this.exportedPipes.push(id);
  7085. }
  7086. };
  7087. TransitiveCompileNgModuleMetadata.prototype.addModule = function (id) {
  7088. if (!this.modulesSet.has(id.reference)) {
  7089. this.modulesSet.add(id.reference);
  7090. this.modules.push(id);
  7091. }
  7092. };
  7093. TransitiveCompileNgModuleMetadata.prototype.addEntryComponent = function (ec) {
  7094. if (!this.entryComponentsSet.has(ec.componentType)) {
  7095. this.entryComponentsSet.add(ec.componentType);
  7096. this.entryComponents.push(ec);
  7097. }
  7098. };
  7099. return TransitiveCompileNgModuleMetadata;
  7100. }());
  7101. function _normalizeArray(obj) {
  7102. return obj || [];
  7103. }
  7104. var ProviderMeta = /** @class */ (function () {
  7105. function ProviderMeta(token, _a) {
  7106. var useClass = _a.useClass, useValue = _a.useValue, useExisting = _a.useExisting, useFactory = _a.useFactory, deps = _a.deps, multi = _a.multi;
  7107. this.token = token;
  7108. this.useClass = useClass || null;
  7109. this.useValue = useValue;
  7110. this.useExisting = useExisting;
  7111. this.useFactory = useFactory || null;
  7112. this.dependencies = deps || null;
  7113. this.multi = !!multi;
  7114. }
  7115. return ProviderMeta;
  7116. }());
  7117. function flatten(list) {
  7118. return list.reduce(function (flat, item) {
  7119. var flatItem = Array.isArray(item) ? flatten(item) : item;
  7120. return flat.concat(flatItem);
  7121. }, []);
  7122. }
  7123. function jitSourceUrl(url) {
  7124. // Note: We need 3 "/" so that ng shows up as a separate domain
  7125. // in the chrome dev tools.
  7126. return url.replace(/(\w+:\/\/[\w:-]+)?(\/+)?/, 'ng:///');
  7127. }
  7128. function templateSourceUrl(ngModuleType, compMeta, templateMeta) {
  7129. var url;
  7130. if (templateMeta.isInline) {
  7131. if (compMeta.type.reference instanceof StaticSymbol) {
  7132. // Note: a .ts file might contain multiple components with inline templates,
  7133. // so we need to give them unique urls, as these will be used for sourcemaps.
  7134. url = compMeta.type.reference.filePath + "." + compMeta.type.reference.name + ".html";
  7135. }
  7136. else {
  7137. url = identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".html";
  7138. }
  7139. }
  7140. else {
  7141. url = templateMeta.templateUrl;
  7142. }
  7143. return compMeta.type.reference instanceof StaticSymbol ? url : jitSourceUrl(url);
  7144. }
  7145. function sharedStylesheetJitUrl(meta, id) {
  7146. var pathParts = meta.moduleUrl.split(/\/\\/g);
  7147. var baseName = pathParts[pathParts.length - 1];
  7148. return jitSourceUrl("css/" + id + baseName + ".ngstyle.js");
  7149. }
  7150. function ngModuleJitUrl(moduleMeta) {
  7151. return jitSourceUrl(identifierName(moduleMeta.type) + "/module.ngfactory.js");
  7152. }
  7153. function templateJitUrl(ngModuleType, compMeta) {
  7154. return jitSourceUrl(identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".ngfactory.js");
  7155. }
  7156. /**
  7157. * In TypeScript, tagged template functions expect a "template object", which is an array of
  7158. * "cooked" strings plus a `raw` property that contains an array of "raw" strings. This is
  7159. * typically constructed with a function called `__makeTemplateObject(cooked, raw)`, but it may not
  7160. * be available in all environments.
  7161. *
  7162. * This is a JavaScript polyfill that uses __makeTemplateObject when it's available, but otherwise
  7163. * creates an inline helper with the same functionality.
  7164. *
  7165. * In the inline function, if `Object.defineProperty` is available we use that to attach the `raw`
  7166. * array.
  7167. */
  7168. var makeTemplateObjectPolyfill = '(this&&this.__makeTemplateObject||function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e})';
  7169. var AbstractJsEmitterVisitor = /** @class */ (function (_super) {
  7170. __extends(AbstractJsEmitterVisitor, _super);
  7171. function AbstractJsEmitterVisitor() {
  7172. return _super.call(this, false) || this;
  7173. }
  7174. AbstractJsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  7175. var _this = this;
  7176. ctx.pushClass(stmt);
  7177. this._visitClassConstructor(stmt, ctx);
  7178. if (stmt.parent != null) {
  7179. ctx.print(stmt, stmt.name + ".prototype = Object.create(");
  7180. stmt.parent.visitExpression(this, ctx);
  7181. ctx.println(stmt, ".prototype);");
  7182. }
  7183. stmt.getters.forEach(function (getter) { return _this._visitClassGetter(stmt, getter, ctx); });
  7184. stmt.methods.forEach(function (method) { return _this._visitClassMethod(stmt, method, ctx); });
  7185. ctx.popClass();
  7186. return null;
  7187. };
  7188. AbstractJsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) {
  7189. ctx.print(stmt, "function " + stmt.name + "(");
  7190. if (stmt.constructorMethod != null) {
  7191. this._visitParams(stmt.constructorMethod.params, ctx);
  7192. }
  7193. ctx.println(stmt, ") {");
  7194. ctx.incIndent();
  7195. if (stmt.constructorMethod != null) {
  7196. if (stmt.constructorMethod.body.length > 0) {
  7197. ctx.println(stmt, "var self = this;");
  7198. this.visitAllStatements(stmt.constructorMethod.body, ctx);
  7199. }
  7200. }
  7201. ctx.decIndent();
  7202. ctx.println(stmt, "}");
  7203. };
  7204. AbstractJsEmitterVisitor.prototype._visitClassGetter = function (stmt, getter, ctx) {
  7205. ctx.println(stmt, "Object.defineProperty(" + stmt.name + ".prototype, '" + getter.name + "', { get: function() {");
  7206. ctx.incIndent();
  7207. if (getter.body.length > 0) {
  7208. ctx.println(stmt, "var self = this;");
  7209. this.visitAllStatements(getter.body, ctx);
  7210. }
  7211. ctx.decIndent();
  7212. ctx.println(stmt, "}});");
  7213. };
  7214. AbstractJsEmitterVisitor.prototype._visitClassMethod = function (stmt, method, ctx) {
  7215. ctx.print(stmt, stmt.name + ".prototype." + method.name + " = function(");
  7216. this._visitParams(method.params, ctx);
  7217. ctx.println(stmt, ") {");
  7218. ctx.incIndent();
  7219. if (method.body.length > 0) {
  7220. ctx.println(stmt, "var self = this;");
  7221. this.visitAllStatements(method.body, ctx);
  7222. }
  7223. ctx.decIndent();
  7224. ctx.println(stmt, "};");
  7225. };
  7226. AbstractJsEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  7227. throw new Error('Cannot emit a WrappedNodeExpr in Javascript.');
  7228. };
  7229. AbstractJsEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) {
  7230. if (ast.builtin === exports.BuiltinVar.This) {
  7231. ctx.print(ast, 'self');
  7232. }
  7233. else if (ast.builtin === exports.BuiltinVar.Super) {
  7234. throw new Error("'super' needs to be handled at a parent ast node, not at the variable level!");
  7235. }
  7236. else {
  7237. _super.prototype.visitReadVarExpr.call(this, ast, ctx);
  7238. }
  7239. return null;
  7240. };
  7241. AbstractJsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  7242. ctx.print(stmt, "var " + stmt.name);
  7243. if (stmt.value) {
  7244. ctx.print(stmt, ' = ');
  7245. stmt.value.visitExpression(this, ctx);
  7246. }
  7247. ctx.println(stmt, ";");
  7248. return null;
  7249. };
  7250. AbstractJsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) {
  7251. ast.value.visitExpression(this, ctx);
  7252. return null;
  7253. };
  7254. AbstractJsEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) {
  7255. var fnExpr = expr.fn;
  7256. if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === exports.BuiltinVar.Super) {
  7257. ctx.currentClass.parent.visitExpression(this, ctx);
  7258. ctx.print(expr, ".call(this");
  7259. if (expr.args.length > 0) {
  7260. ctx.print(expr, ", ");
  7261. this.visitAllExpressions(expr.args, ctx, ',');
  7262. }
  7263. ctx.print(expr, ")");
  7264. }
  7265. else {
  7266. _super.prototype.visitInvokeFunctionExpr.call(this, expr, ctx);
  7267. }
  7268. return null;
  7269. };
  7270. AbstractJsEmitterVisitor.prototype.visitTaggedTemplateExpr = function (ast, ctx) {
  7271. var _this = this;
  7272. // The following convoluted piece of code is effectively the downlevelled equivalent of
  7273. // ```
  7274. // tag`...`
  7275. // ```
  7276. // which is effectively like:
  7277. // ```
  7278. // tag(__makeTemplateObject(cooked, raw), expression1, expression2, ...);
  7279. // ```
  7280. var elements = ast.template.elements;
  7281. ast.tag.visitExpression(this, ctx);
  7282. ctx.print(ast, "(" + makeTemplateObjectPolyfill + "(");
  7283. ctx.print(ast, "[" + elements.map(function (part) { return escapeIdentifier(part.text, false); }).join(', ') + "], ");
  7284. ctx.print(ast, "[" + elements.map(function (part) { return escapeIdentifier(part.rawText, false); }).join(', ') + "])");
  7285. ast.template.expressions.forEach(function (expression) {
  7286. ctx.print(ast, ', ');
  7287. expression.visitExpression(_this, ctx);
  7288. });
  7289. ctx.print(ast, ')');
  7290. return null;
  7291. };
  7292. AbstractJsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) {
  7293. ctx.print(ast, "function" + (ast.name ? ' ' + ast.name : '') + "(");
  7294. this._visitParams(ast.params, ctx);
  7295. ctx.println(ast, ") {");
  7296. ctx.incIndent();
  7297. this.visitAllStatements(ast.statements, ctx);
  7298. ctx.decIndent();
  7299. ctx.print(ast, "}");
  7300. return null;
  7301. };
  7302. AbstractJsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  7303. ctx.print(stmt, "function " + stmt.name + "(");
  7304. this._visitParams(stmt.params, ctx);
  7305. ctx.println(stmt, ") {");
  7306. ctx.incIndent();
  7307. this.visitAllStatements(stmt.statements, ctx);
  7308. ctx.decIndent();
  7309. ctx.println(stmt, "}");
  7310. return null;
  7311. };
  7312. AbstractJsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) {
  7313. ctx.println(stmt, "try {");
  7314. ctx.incIndent();
  7315. this.visitAllStatements(stmt.bodyStmts, ctx);
  7316. ctx.decIndent();
  7317. ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {");
  7318. ctx.incIndent();
  7319. var catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack')).toDeclStmt(null, [
  7320. exports.StmtModifier.Final
  7321. ])].concat(stmt.catchStmts);
  7322. this.visitAllStatements(catchStmts, ctx);
  7323. ctx.decIndent();
  7324. ctx.println(stmt, "}");
  7325. return null;
  7326. };
  7327. AbstractJsEmitterVisitor.prototype.visitLocalizedString = function (ast, ctx) {
  7328. var _this = this;
  7329. // The following convoluted piece of code is effectively the downlevelled equivalent of
  7330. // ```
  7331. // $localize `...`
  7332. // ```
  7333. // which is effectively like:
  7334. // ```
  7335. // $localize(__makeTemplateObject(cooked, raw), expression1, expression2, ...);
  7336. // ```
  7337. ctx.print(ast, "$localize(" + makeTemplateObjectPolyfill + "(");
  7338. var parts = [ast.serializeI18nHead()];
  7339. for (var i = 1; i < ast.messageParts.length; i++) {
  7340. parts.push(ast.serializeI18nTemplatePart(i));
  7341. }
  7342. ctx.print(ast, "[" + parts.map(function (part) { return escapeIdentifier(part.cooked, false); }).join(', ') + "], ");
  7343. ctx.print(ast, "[" + parts.map(function (part) { return escapeIdentifier(part.raw, false); }).join(', ') + "])");
  7344. ast.expressions.forEach(function (expression) {
  7345. ctx.print(ast, ', ');
  7346. expression.visitExpression(_this, ctx);
  7347. });
  7348. ctx.print(ast, ')');
  7349. return null;
  7350. };
  7351. AbstractJsEmitterVisitor.prototype._visitParams = function (params, ctx) {
  7352. this.visitAllObjects(function (param) { return ctx.print(null, param.name); }, params, ctx, ',');
  7353. };
  7354. AbstractJsEmitterVisitor.prototype.getBuiltinMethodName = function (method) {
  7355. var name;
  7356. switch (method) {
  7357. case exports.BuiltinMethod.ConcatArray:
  7358. name = 'concat';
  7359. break;
  7360. case exports.BuiltinMethod.SubscribeObservable:
  7361. name = 'subscribe';
  7362. break;
  7363. case exports.BuiltinMethod.Bind:
  7364. name = 'bind';
  7365. break;
  7366. default:
  7367. throw new Error("Unknown builtin method: " + method);
  7368. }
  7369. return name;
  7370. };
  7371. return AbstractJsEmitterVisitor;
  7372. }(AbstractEmitterVisitor));
  7373. /**
  7374. * The Trusted Types policy, or null if Trusted Types are not
  7375. * enabled/supported, or undefined if the policy has not been created yet.
  7376. */
  7377. var policy;
  7378. /**
  7379. * Returns the Trusted Types policy, or null if Trusted Types are not
  7380. * enabled/supported. The first call to this function will create the policy.
  7381. */
  7382. function getPolicy() {
  7383. if (policy === undefined) {
  7384. policy = null;
  7385. if (_global.trustedTypes) {
  7386. try {
  7387. policy =
  7388. _global.trustedTypes.createPolicy('angular#unsafe-jit', {
  7389. createScript: function (s) { return s; },
  7390. });
  7391. }
  7392. catch (_a) {
  7393. // trustedTypes.createPolicy throws if called with a name that is
  7394. // already registered, even in report-only mode. Until the API changes,
  7395. // catch the error not to break the applications functionally. In such
  7396. // cases, the code will fall back to using strings.
  7397. }
  7398. }
  7399. }
  7400. return policy;
  7401. }
  7402. /**
  7403. * Unsafely promote a string to a TrustedScript, falling back to strings when
  7404. * Trusted Types are not available.
  7405. * @security In particular, it must be assured that the provided string will
  7406. * never cause an XSS vulnerability if used in a context that will be
  7407. * interpreted and executed as a script by a browser, e.g. when calling eval.
  7408. */
  7409. function trustedScriptFromString(script) {
  7410. var _a;
  7411. return ((_a = getPolicy()) === null || _a === void 0 ? void 0 : _a.createScript(script)) || script;
  7412. }
  7413. /**
  7414. * Unsafely call the Function constructor with the given string arguments.
  7415. * @security This is a security-sensitive function; any use of this function
  7416. * must go through security review. In particular, it must be assured that it
  7417. * is only called from the JIT compiler, as use in other code can lead to XSS
  7418. * vulnerabilities.
  7419. */
  7420. function newTrustedFunctionForJIT() {
  7421. var args = [];
  7422. for (var _i = 0; _i < arguments.length; _i++) {
  7423. args[_i] = arguments[_i];
  7424. }
  7425. if (!_global.trustedTypes) {
  7426. // In environments that don't support Trusted Types, fall back to the most
  7427. // straightforward implementation:
  7428. return new (Function.bind.apply(Function, __spreadArray([void 0], __read(args))))();
  7429. }
  7430. // Chrome currently does not support passing TrustedScript to the Function
  7431. // constructor. The following implements the workaround proposed on the page
  7432. // below, where the Chromium bug is also referenced:
  7433. // https://github.com/w3c/webappsec-trusted-types/wiki/Trusted-Types-for-function-constructor
  7434. var fnArgs = args.slice(0, -1).join(',');
  7435. var fnBody = args[args.length - 1];
  7436. var body = "(function anonymous(" + fnArgs + "\n) { " + fnBody + "\n})";
  7437. // Using eval directly confuses the compiler and prevents this module from
  7438. // being stripped out of JS binaries even if not used. The global['eval']
  7439. // indirection fixes that.
  7440. var fn = _global['eval'](trustedScriptFromString(body));
  7441. if (fn.bind === undefined) {
  7442. // Workaround for a browser bug that only exists in Chrome 83, where passing
  7443. // a TrustedScript to eval just returns the TrustedScript back without
  7444. // evaluating it. In that case, fall back to the most straightforward
  7445. // implementation:
  7446. return new (Function.bind.apply(Function, __spreadArray([void 0], __read(args))))();
  7447. }
  7448. // To completely mimic the behavior of calling "new Function", two more
  7449. // things need to happen:
  7450. // 1. Stringifying the resulting function should return its source code
  7451. fn.toString = function () { return body; };
  7452. // 2. When calling the resulting function, `this` should refer to `global`
  7453. return fn.bind(_global);
  7454. // When Trusted Types support in Function constructors is widely available,
  7455. // the implementation of this function can be simplified to:
  7456. // return new Function(...args.map(a => trustedScriptFromString(a)));
  7457. }
  7458. /**
  7459. * A helper class to manage the evaluation of JIT generated code.
  7460. */
  7461. var JitEvaluator = /** @class */ (function () {
  7462. function JitEvaluator() {
  7463. }
  7464. /**
  7465. *
  7466. * @param sourceUrl The URL of the generated code.
  7467. * @param statements An array of Angular statement AST nodes to be evaluated.
  7468. * @param reflector A helper used when converting the statements to executable code.
  7469. * @param createSourceMaps If true then create a source-map for the generated code and include it
  7470. * inline as a source-map comment.
  7471. * @returns A map of all the variables in the generated code.
  7472. */
  7473. JitEvaluator.prototype.evaluateStatements = function (sourceUrl, statements, reflector, createSourceMaps) {
  7474. var converter = new JitEmitterVisitor(reflector);
  7475. var ctx = EmitterVisitorContext.createRoot();
  7476. // Ensure generated code is in strict mode
  7477. if (statements.length > 0 && !isUseStrictStatement(statements[0])) {
  7478. statements = __spreadArray([
  7479. literal('use strict').toStmt()
  7480. ], __read(statements));
  7481. }
  7482. converter.visitAllStatements(statements, ctx);
  7483. converter.createReturnStmt(ctx);
  7484. return this.evaluateCode(sourceUrl, ctx, converter.getArgs(), createSourceMaps);
  7485. };
  7486. /**
  7487. * Evaluate a piece of JIT generated code.
  7488. * @param sourceUrl The URL of this generated code.
  7489. * @param ctx A context object that contains an AST of the code to be evaluated.
  7490. * @param vars A map containing the names and values of variables that the evaluated code might
  7491. * reference.
  7492. * @param createSourceMap If true then create a source-map for the generated code and include it
  7493. * inline as a source-map comment.
  7494. * @returns The result of evaluating the code.
  7495. */
  7496. JitEvaluator.prototype.evaluateCode = function (sourceUrl, ctx, vars, createSourceMap) {
  7497. var fnBody = "\"use strict\";" + ctx.toSource() + "\n//# sourceURL=" + sourceUrl;
  7498. var fnArgNames = [];
  7499. var fnArgValues = [];
  7500. for (var argName in vars) {
  7501. fnArgValues.push(vars[argName]);
  7502. fnArgNames.push(argName);
  7503. }
  7504. if (createSourceMap) {
  7505. // using `new Function(...)` generates a header, 1 line of no arguments, 2 lines otherwise
  7506. // E.g. ```
  7507. // function anonymous(a,b,c
  7508. // /**/) { ... }```
  7509. // We don't want to hard code this fact, so we auto detect it via an empty function first.
  7510. var emptyFn = newTrustedFunctionForJIT.apply(void 0, __spreadArray([], __read(fnArgNames.concat('return null;')))).toString();
  7511. var headerLines = emptyFn.slice(0, emptyFn.indexOf('return null;')).split('\n').length - 1;
  7512. fnBody += "\n" + ctx.toSourceMapGenerator(sourceUrl, headerLines).toJsComment();
  7513. }
  7514. var fn = newTrustedFunctionForJIT.apply(void 0, __spreadArray([], __read(fnArgNames.concat(fnBody))));
  7515. return this.executeFunction(fn, fnArgValues);
  7516. };
  7517. /**
  7518. * Execute a JIT generated function by calling it.
  7519. *
  7520. * This method can be overridden in tests to capture the functions that are generated
  7521. * by this `JitEvaluator` class.
  7522. *
  7523. * @param fn A function to execute.
  7524. * @param args The arguments to pass to the function being executed.
  7525. * @returns The return value of the executed function.
  7526. */
  7527. JitEvaluator.prototype.executeFunction = function (fn, args) {
  7528. return fn.apply(void 0, __spreadArray([], __read(args)));
  7529. };
  7530. return JitEvaluator;
  7531. }());
  7532. /**
  7533. * An Angular AST visitor that converts AST nodes into executable JavaScript code.
  7534. */
  7535. var JitEmitterVisitor = /** @class */ (function (_super) {
  7536. __extends(JitEmitterVisitor, _super);
  7537. function JitEmitterVisitor(reflector) {
  7538. var _this = _super.call(this) || this;
  7539. _this.reflector = reflector;
  7540. _this._evalArgNames = [];
  7541. _this._evalArgValues = [];
  7542. _this._evalExportedVars = [];
  7543. return _this;
  7544. }
  7545. JitEmitterVisitor.prototype.createReturnStmt = function (ctx) {
  7546. var stmt = new ReturnStatement(new LiteralMapExpr(this._evalExportedVars.map(function (resultVar) { return new LiteralMapEntry(resultVar, variable(resultVar), false); })));
  7547. stmt.visitStatement(this, ctx);
  7548. };
  7549. JitEmitterVisitor.prototype.getArgs = function () {
  7550. var result = {};
  7551. for (var i = 0; i < this._evalArgNames.length; i++) {
  7552. result[this._evalArgNames[i]] = this._evalArgValues[i];
  7553. }
  7554. return result;
  7555. };
  7556. JitEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) {
  7557. this._emitReferenceToExternal(ast, this.reflector.resolveExternalReference(ast.value), ctx);
  7558. return null;
  7559. };
  7560. JitEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  7561. this._emitReferenceToExternal(ast, ast.node, ctx);
  7562. return null;
  7563. };
  7564. JitEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  7565. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  7566. this._evalExportedVars.push(stmt.name);
  7567. }
  7568. return _super.prototype.visitDeclareVarStmt.call(this, stmt, ctx);
  7569. };
  7570. JitEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  7571. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  7572. this._evalExportedVars.push(stmt.name);
  7573. }
  7574. return _super.prototype.visitDeclareFunctionStmt.call(this, stmt, ctx);
  7575. };
  7576. JitEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  7577. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  7578. this._evalExportedVars.push(stmt.name);
  7579. }
  7580. return _super.prototype.visitDeclareClassStmt.call(this, stmt, ctx);
  7581. };
  7582. JitEmitterVisitor.prototype._emitReferenceToExternal = function (ast, value, ctx) {
  7583. var id = this._evalArgValues.indexOf(value);
  7584. if (id === -1) {
  7585. id = this._evalArgValues.length;
  7586. this._evalArgValues.push(value);
  7587. var name = identifierName({ reference: value }) || 'val';
  7588. this._evalArgNames.push("jit_" + name + "_" + id);
  7589. }
  7590. ctx.print(ast, this._evalArgNames[id]);
  7591. };
  7592. return JitEmitterVisitor;
  7593. }(AbstractJsEmitterVisitor));
  7594. function isUseStrictStatement(statement) {
  7595. return statement.isEquivalent(literal('use strict').toStmt());
  7596. }
  7597. /**
  7598. * @license
  7599. * Copyright Google LLC All Rights Reserved.
  7600. *
  7601. * Use of this source code is governed by an MIT-style license that can be
  7602. * found in the LICENSE file at https://angular.io/license
  7603. */
  7604. var $EOF = 0;
  7605. var $BSPACE = 8;
  7606. var $TAB = 9;
  7607. var $LF = 10;
  7608. var $VTAB = 11;
  7609. var $FF = 12;
  7610. var $CR = 13;
  7611. var $SPACE = 32;
  7612. var $BANG = 33;
  7613. var $DQ = 34;
  7614. var $HASH = 35;
  7615. var $$ = 36;
  7616. var $PERCENT = 37;
  7617. var $AMPERSAND = 38;
  7618. var $SQ = 39;
  7619. var $LPAREN = 40;
  7620. var $RPAREN = 41;
  7621. var $STAR = 42;
  7622. var $PLUS = 43;
  7623. var $COMMA = 44;
  7624. var $MINUS = 45;
  7625. var $PERIOD = 46;
  7626. var $SLASH = 47;
  7627. var $COLON = 58;
  7628. var $SEMICOLON = 59;
  7629. var $LT = 60;
  7630. var $EQ = 61;
  7631. var $GT = 62;
  7632. var $QUESTION = 63;
  7633. var $0 = 48;
  7634. var $7 = 55;
  7635. var $9 = 57;
  7636. var $A = 65;
  7637. var $E = 69;
  7638. var $F = 70;
  7639. var $X = 88;
  7640. var $Z = 90;
  7641. var $LBRACKET = 91;
  7642. var $BACKSLASH = 92;
  7643. var $RBRACKET = 93;
  7644. var $CARET = 94;
  7645. var $_ = 95;
  7646. var $a = 97;
  7647. var $b = 98;
  7648. var $e = 101;
  7649. var $f = 102;
  7650. var $n = 110;
  7651. var $r = 114;
  7652. var $t = 116;
  7653. var $u = 117;
  7654. var $v = 118;
  7655. var $x = 120;
  7656. var $z = 122;
  7657. var $LBRACE = 123;
  7658. var $BAR = 124;
  7659. var $RBRACE = 125;
  7660. var $NBSP = 160;
  7661. var $PIPE = 124;
  7662. var $TILDA = 126;
  7663. var $AT = 64;
  7664. var $BT = 96;
  7665. function isWhitespace(code) {
  7666. return (code >= $TAB && code <= $SPACE) || (code == $NBSP);
  7667. }
  7668. function isDigit(code) {
  7669. return $0 <= code && code <= $9;
  7670. }
  7671. function isAsciiLetter(code) {
  7672. return code >= $a && code <= $z || code >= $A && code <= $Z;
  7673. }
  7674. function isAsciiHexDigit(code) {
  7675. return code >= $a && code <= $f || code >= $A && code <= $F || isDigit(code);
  7676. }
  7677. function isNewLine(code) {
  7678. return code === $LF || code === $CR;
  7679. }
  7680. function isOctalDigit(code) {
  7681. return $0 <= code && code <= $7;
  7682. }
  7683. /**
  7684. * @license
  7685. * Copyright Google LLC All Rights Reserved.
  7686. *
  7687. * Use of this source code is governed by an MIT-style license that can be
  7688. * found in the LICENSE file at https://angular.io/license
  7689. */
  7690. var ParseLocation = /** @class */ (function () {
  7691. function ParseLocation(file, offset, line, col) {
  7692. this.file = file;
  7693. this.offset = offset;
  7694. this.line = line;
  7695. this.col = col;
  7696. }
  7697. ParseLocation.prototype.toString = function () {
  7698. return this.offset != null ? this.file.url + "@" + this.line + ":" + this.col : this.file.url;
  7699. };
  7700. ParseLocation.prototype.moveBy = function (delta) {
  7701. var source = this.file.content;
  7702. var len = source.length;
  7703. var offset = this.offset;
  7704. var line = this.line;
  7705. var col = this.col;
  7706. while (offset > 0 && delta < 0) {
  7707. offset--;
  7708. delta++;
  7709. var ch = source.charCodeAt(offset);
  7710. if (ch == $LF) {
  7711. line--;
  7712. var priorLine = source.substr(0, offset - 1).lastIndexOf(String.fromCharCode($LF));
  7713. col = priorLine > 0 ? offset - priorLine : offset;
  7714. }
  7715. else {
  7716. col--;
  7717. }
  7718. }
  7719. while (offset < len && delta > 0) {
  7720. var ch = source.charCodeAt(offset);
  7721. offset++;
  7722. delta--;
  7723. if (ch == $LF) {
  7724. line++;
  7725. col = 0;
  7726. }
  7727. else {
  7728. col++;
  7729. }
  7730. }
  7731. return new ParseLocation(this.file, offset, line, col);
  7732. };
  7733. // Return the source around the location
  7734. // Up to `maxChars` or `maxLines` on each side of the location
  7735. ParseLocation.prototype.getContext = function (maxChars, maxLines) {
  7736. var content = this.file.content;
  7737. var startOffset = this.offset;
  7738. if (startOffset != null) {
  7739. if (startOffset > content.length - 1) {
  7740. startOffset = content.length - 1;
  7741. }
  7742. var endOffset = startOffset;
  7743. var ctxChars = 0;
  7744. var ctxLines = 0;
  7745. while (ctxChars < maxChars && startOffset > 0) {
  7746. startOffset--;
  7747. ctxChars++;
  7748. if (content[startOffset] == '\n') {
  7749. if (++ctxLines == maxLines) {
  7750. break;
  7751. }
  7752. }
  7753. }
  7754. ctxChars = 0;
  7755. ctxLines = 0;
  7756. while (ctxChars < maxChars && endOffset < content.length - 1) {
  7757. endOffset++;
  7758. ctxChars++;
  7759. if (content[endOffset] == '\n') {
  7760. if (++ctxLines == maxLines) {
  7761. break;
  7762. }
  7763. }
  7764. }
  7765. return {
  7766. before: content.substring(startOffset, this.offset),
  7767. after: content.substring(this.offset, endOffset + 1),
  7768. };
  7769. }
  7770. return null;
  7771. };
  7772. return ParseLocation;
  7773. }());
  7774. var ParseSourceFile = /** @class */ (function () {
  7775. function ParseSourceFile(content, url) {
  7776. this.content = content;
  7777. this.url = url;
  7778. }
  7779. return ParseSourceFile;
  7780. }());
  7781. var ParseSourceSpan = /** @class */ (function () {
  7782. /**
  7783. * Create an object that holds information about spans of tokens/nodes captured during
  7784. * lexing/parsing of text.
  7785. *
  7786. * @param start
  7787. * The location of the start of the span (having skipped leading trivia).
  7788. * Skipping leading trivia makes source-spans more "user friendly", since things like HTML
  7789. * elements will appear to begin at the start of the opening tag, rather than at the start of any
  7790. * leading trivia, which could include newlines.
  7791. *
  7792. * @param end
  7793. * The location of the end of the span.
  7794. *
  7795. * @param fullStart
  7796. * The start of the token without skipping the leading trivia.
  7797. * This is used by tooling that splits tokens further, such as extracting Angular interpolations
  7798. * from text tokens. Such tooling creates new source-spans relative to the original token's
  7799. * source-span. If leading trivia characters have been skipped then the new source-spans may be
  7800. * incorrectly offset.
  7801. *
  7802. * @param details
  7803. * Additional information (such as identifier names) that should be associated with the span.
  7804. */
  7805. function ParseSourceSpan(start, end, fullStart, details) {
  7806. if (fullStart === void 0) { fullStart = start; }
  7807. if (details === void 0) { details = null; }
  7808. this.start = start;
  7809. this.end = end;
  7810. this.fullStart = fullStart;
  7811. this.details = details;
  7812. }
  7813. ParseSourceSpan.prototype.toString = function () {
  7814. return this.start.file.content.substring(this.start.offset, this.end.offset);
  7815. };
  7816. return ParseSourceSpan;
  7817. }());
  7818. (function (ParseErrorLevel) {
  7819. ParseErrorLevel[ParseErrorLevel["WARNING"] = 0] = "WARNING";
  7820. ParseErrorLevel[ParseErrorLevel["ERROR"] = 1] = "ERROR";
  7821. })(exports.ParseErrorLevel || (exports.ParseErrorLevel = {}));
  7822. var ParseError = /** @class */ (function () {
  7823. function ParseError(span, msg, level) {
  7824. if (level === void 0) { level = exports.ParseErrorLevel.ERROR; }
  7825. this.span = span;
  7826. this.msg = msg;
  7827. this.level = level;
  7828. }
  7829. ParseError.prototype.contextualMessage = function () {
  7830. var ctx = this.span.start.getContext(100, 3);
  7831. return ctx ? this.msg + " (\"" + ctx.before + "[" + exports.ParseErrorLevel[this.level] + " ->]" + ctx.after + "\")" :
  7832. this.msg;
  7833. };
  7834. ParseError.prototype.toString = function () {
  7835. var details = this.span.details ? ", " + this.span.details : '';
  7836. return this.contextualMessage() + ": " + this.span.start + details;
  7837. };
  7838. return ParseError;
  7839. }());
  7840. function typeSourceSpan(kind, type) {
  7841. var moduleUrl = identifierModuleUrl(type);
  7842. var sourceFileName = moduleUrl != null ? "in " + kind + " " + identifierName(type) + " in " + moduleUrl :
  7843. "in " + kind + " " + identifierName(type);
  7844. var sourceFile = new ParseSourceFile('', sourceFileName);
  7845. return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
  7846. }
  7847. /**
  7848. * Generates Source Span object for a given R3 Type for JIT mode.
  7849. *
  7850. * @param kind Component or Directive.
  7851. * @param typeName name of the Component or Directive.
  7852. * @param sourceUrl reference to Component or Directive source.
  7853. * @returns instance of ParseSourceSpan that represent a given Component or Directive.
  7854. */
  7855. function r3JitTypeSourceSpan(kind, typeName, sourceUrl) {
  7856. var sourceFileName = "in " + kind + " " + typeName + " in " + sourceUrl;
  7857. var sourceFile = new ParseSourceFile('', sourceFileName);
  7858. return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
  7859. }
  7860. /**
  7861. * @license
  7862. * Copyright Google LLC All Rights Reserved.
  7863. *
  7864. * Use of this source code is governed by an MIT-style license that can be
  7865. * found in the LICENSE file at https://angular.io/license
  7866. */
  7867. function compileInjector(meta) {
  7868. var definitionMap = new DefinitionMap();
  7869. if (meta.providers !== null) {
  7870. definitionMap.set('providers', meta.providers);
  7871. }
  7872. if (meta.imports.length > 0) {
  7873. definitionMap.set('imports', literalArr(meta.imports));
  7874. }
  7875. var expression = importExpr(Identifiers.defineInjector).callFn([definitionMap.toLiteralMap()], undefined, true);
  7876. var type = createInjectorType(meta);
  7877. return { expression: expression, type: type, statements: [] };
  7878. }
  7879. function createInjectorType(meta) {
  7880. return new ExpressionType(importExpr(Identifiers.InjectorDeclaration, [new ExpressionType(meta.type.type)]));
  7881. }
  7882. /**
  7883. * @license
  7884. * Copyright Google LLC All Rights Reserved.
  7885. *
  7886. * Use of this source code is governed by an MIT-style license that can be
  7887. * found in the LICENSE file at https://angular.io/license
  7888. */
  7889. /**
  7890. * Implementation of `CompileReflector` which resolves references to @angular/core
  7891. * symbols at runtime, according to a consumer-provided mapping.
  7892. *
  7893. * Only supports `resolveExternalReference`, all other methods throw.
  7894. */
  7895. var R3JitReflector = /** @class */ (function () {
  7896. function R3JitReflector(context) {
  7897. this.context = context;
  7898. }
  7899. R3JitReflector.prototype.resolveExternalReference = function (ref) {
  7900. // This reflector only handles @angular/core imports.
  7901. if (ref.moduleName !== '@angular/core') {
  7902. throw new Error("Cannot resolve external reference to " + ref.moduleName + ", only references to @angular/core are supported.");
  7903. }
  7904. if (!this.context.hasOwnProperty(ref.name)) {
  7905. throw new Error("No value provided for @angular/core symbol '" + ref.name + "'.");
  7906. }
  7907. return this.context[ref.name];
  7908. };
  7909. R3JitReflector.prototype.parameters = function (typeOrFunc) {
  7910. throw new Error('Not implemented.');
  7911. };
  7912. R3JitReflector.prototype.annotations = function (typeOrFunc) {
  7913. throw new Error('Not implemented.');
  7914. };
  7915. R3JitReflector.prototype.shallowAnnotations = function (typeOrFunc) {
  7916. throw new Error('Not implemented.');
  7917. };
  7918. R3JitReflector.prototype.tryAnnotations = function (typeOrFunc) {
  7919. throw new Error('Not implemented.');
  7920. };
  7921. R3JitReflector.prototype.propMetadata = function (typeOrFunc) {
  7922. throw new Error('Not implemented.');
  7923. };
  7924. R3JitReflector.prototype.hasLifecycleHook = function (type, lcProperty) {
  7925. throw new Error('Not implemented.');
  7926. };
  7927. R3JitReflector.prototype.guards = function (typeOrFunc) {
  7928. throw new Error('Not implemented.');
  7929. };
  7930. R3JitReflector.prototype.componentModuleUrl = function (type, cmpMetadata) {
  7931. throw new Error('Not implemented.');
  7932. };
  7933. return R3JitReflector;
  7934. }());
  7935. /**
  7936. * @license
  7937. * Copyright Google LLC All Rights Reserved.
  7938. *
  7939. * Use of this source code is governed by an MIT-style license that can be
  7940. * found in the LICENSE file at https://angular.io/license
  7941. */
  7942. /**
  7943. * Construct an `R3NgModuleDef` for the given `R3NgModuleMetadata`.
  7944. */
  7945. function compileNgModule(meta) {
  7946. var internalType = meta.internalType, bootstrap = meta.bootstrap, declarations = meta.declarations, imports = meta.imports, exports = meta.exports, schemas = meta.schemas, containsForwardDecls = meta.containsForwardDecls, emitInline = meta.emitInline, id = meta.id;
  7947. var statements = [];
  7948. var definitionMap = new DefinitionMap();
  7949. definitionMap.set('type', internalType);
  7950. if (bootstrap.length > 0) {
  7951. definitionMap.set('bootstrap', refsToArray(bootstrap, containsForwardDecls));
  7952. }
  7953. // If requested to emit scope information inline, pass the `declarations`, `imports` and `exports`
  7954. // to the `ɵɵdefineNgModule()` call. The JIT compilation uses this.
  7955. if (emitInline) {
  7956. if (declarations.length > 0) {
  7957. definitionMap.set('declarations', refsToArray(declarations, containsForwardDecls));
  7958. }
  7959. if (imports.length > 0) {
  7960. definitionMap.set('imports', refsToArray(imports, containsForwardDecls));
  7961. }
  7962. if (exports.length > 0) {
  7963. definitionMap.set('exports', refsToArray(exports, containsForwardDecls));
  7964. }
  7965. }
  7966. // If not emitting inline, the scope information is not passed into `ɵɵdefineNgModule` as it would
  7967. // prevent tree-shaking of the declarations, imports and exports references.
  7968. else {
  7969. var setNgModuleScopeCall = generateSetNgModuleScopeCall(meta);
  7970. if (setNgModuleScopeCall !== null) {
  7971. statements.push(setNgModuleScopeCall);
  7972. }
  7973. }
  7974. if (schemas !== null && schemas.length > 0) {
  7975. definitionMap.set('schemas', literalArr(schemas.map(function (ref) { return ref.value; })));
  7976. }
  7977. if (id !== null) {
  7978. definitionMap.set('id', id);
  7979. }
  7980. var expression = importExpr(Identifiers.defineNgModule).callFn([definitionMap.toLiteralMap()], undefined, true);
  7981. var type = createNgModuleType(meta);
  7982. return { expression: expression, type: type, statements: statements };
  7983. }
  7984. /**
  7985. * This function is used in JIT mode to generate the call to `ɵɵdefineNgModule()` from a call to
  7986. * `ɵɵngDeclareNgModule()`.
  7987. */
  7988. function compileNgModuleDeclarationExpression(meta) {
  7989. var definitionMap = new DefinitionMap();
  7990. definitionMap.set('type', new WrappedNodeExpr(meta.type));
  7991. if (meta.bootstrap !== undefined) {
  7992. definitionMap.set('bootstrap', new WrappedNodeExpr(meta.bootstrap));
  7993. }
  7994. if (meta.declarations !== undefined) {
  7995. definitionMap.set('declarations', new WrappedNodeExpr(meta.declarations));
  7996. }
  7997. if (meta.imports !== undefined) {
  7998. definitionMap.set('imports', new WrappedNodeExpr(meta.imports));
  7999. }
  8000. if (meta.exports !== undefined) {
  8001. definitionMap.set('exports', new WrappedNodeExpr(meta.exports));
  8002. }
  8003. if (meta.schemas !== undefined) {
  8004. definitionMap.set('schemas', new WrappedNodeExpr(meta.schemas));
  8005. }
  8006. if (meta.id !== undefined) {
  8007. definitionMap.set('id', new WrappedNodeExpr(meta.id));
  8008. }
  8009. return importExpr(Identifiers.defineNgModule).callFn([definitionMap.toLiteralMap()]);
  8010. }
  8011. function createNgModuleType(_a) {
  8012. var moduleType = _a.type, declarations = _a.declarations, imports = _a.imports, exports = _a.exports;
  8013. return new ExpressionType(importExpr(Identifiers.NgModuleDeclaration, [
  8014. new ExpressionType(moduleType.type), tupleTypeOf(declarations), tupleTypeOf(imports),
  8015. tupleTypeOf(exports)
  8016. ]));
  8017. }
  8018. /**
  8019. * Generates a function call to `ɵɵsetNgModuleScope` with all necessary information so that the
  8020. * transitive module scope can be computed during runtime in JIT mode. This call is marked pure
  8021. * such that the references to declarations, imports and exports may be elided causing these
  8022. * symbols to become tree-shakeable.
  8023. */
  8024. function generateSetNgModuleScopeCall(meta) {
  8025. var moduleType = meta.adjacentType, declarations = meta.declarations, imports = meta.imports, exports = meta.exports, containsForwardDecls = meta.containsForwardDecls;
  8026. var scopeMap = new DefinitionMap();
  8027. if (declarations.length > 0) {
  8028. scopeMap.set('declarations', refsToArray(declarations, containsForwardDecls));
  8029. }
  8030. if (imports.length > 0) {
  8031. scopeMap.set('imports', refsToArray(imports, containsForwardDecls));
  8032. }
  8033. if (exports.length > 0) {
  8034. scopeMap.set('exports', refsToArray(exports, containsForwardDecls));
  8035. }
  8036. if (Object.keys(scopeMap.values).length === 0) {
  8037. return null;
  8038. }
  8039. // setNgModuleScope(...)
  8040. var fnCall = new InvokeFunctionExpr(
  8041. /* fn */ importExpr(Identifiers.setNgModuleScope),
  8042. /* args */ [moduleType, scopeMap.toLiteralMap()]);
  8043. // (ngJitMode guard) && setNgModuleScope(...)
  8044. var guardedCall = jitOnlyGuardedExpression(fnCall);
  8045. // function() { (ngJitMode guard) && setNgModuleScope(...); }
  8046. var iife = new FunctionExpr(
  8047. /* params */ [],
  8048. /* statements */ [guardedCall.toStmt()]);
  8049. // (function() { (ngJitMode guard) && setNgModuleScope(...); })()
  8050. var iifeCall = new InvokeFunctionExpr(
  8051. /* fn */ iife,
  8052. /* args */ []);
  8053. return iifeCall.toStmt();
  8054. }
  8055. function tupleTypeOf(exp) {
  8056. var types = exp.map(function (ref) { return typeofExpr(ref.type); });
  8057. return exp.length > 0 ? expressionType(literalArr(types)) : NONE_TYPE;
  8058. }
  8059. /**
  8060. * @license
  8061. * Copyright Google LLC All Rights Reserved.
  8062. *
  8063. * Use of this source code is governed by an MIT-style license that can be
  8064. * found in the LICENSE file at https://angular.io/license
  8065. */
  8066. function compilePipeFromMetadata(metadata) {
  8067. var definitionMapValues = [];
  8068. // e.g. `name: 'myPipe'`
  8069. definitionMapValues.push({ key: 'name', value: literal(metadata.pipeName), quoted: false });
  8070. // e.g. `type: MyPipe`
  8071. definitionMapValues.push({ key: 'type', value: metadata.type.value, quoted: false });
  8072. // e.g. `pure: true`
  8073. definitionMapValues.push({ key: 'pure', value: literal(metadata.pure), quoted: false });
  8074. var expression = importExpr(Identifiers.definePipe).callFn([literalMap(definitionMapValues)], undefined, true);
  8075. var type = createPipeType(metadata);
  8076. return { expression: expression, type: type, statements: [] };
  8077. }
  8078. function createPipeType(metadata) {
  8079. return new ExpressionType(importExpr(Identifiers.PipeDeclaration, [
  8080. typeWithParameters(metadata.type.type, metadata.typeArgumentCount),
  8081. new ExpressionType(new LiteralExpr(metadata.pipeName)),
  8082. ]));
  8083. }
  8084. /**
  8085. * @license
  8086. * Copyright Google LLC All Rights Reserved.
  8087. *
  8088. * Use of this source code is governed by an MIT-style license that can be
  8089. * found in the LICENSE file at https://angular.io/license
  8090. */
  8091. var ParserError = /** @class */ (function () {
  8092. function ParserError(message, input, errLocation, ctxLocation) {
  8093. this.input = input;
  8094. this.errLocation = errLocation;
  8095. this.ctxLocation = ctxLocation;
  8096. this.message = "Parser Error: " + message + " " + errLocation + " [" + input + "] in " + ctxLocation;
  8097. }
  8098. return ParserError;
  8099. }());
  8100. var ParseSpan = /** @class */ (function () {
  8101. function ParseSpan(start, end) {
  8102. this.start = start;
  8103. this.end = end;
  8104. }
  8105. ParseSpan.prototype.toAbsolute = function (absoluteOffset) {
  8106. return new AbsoluteSourceSpan(absoluteOffset + this.start, absoluteOffset + this.end);
  8107. };
  8108. return ParseSpan;
  8109. }());
  8110. var AST = /** @class */ (function () {
  8111. function AST(span,
  8112. /**
  8113. * Absolute location of the expression AST in a source code file.
  8114. */
  8115. sourceSpan) {
  8116. this.span = span;
  8117. this.sourceSpan = sourceSpan;
  8118. }
  8119. AST.prototype.visit = function (visitor, context) {
  8120. if (context === void 0) { context = null; }
  8121. return null;
  8122. };
  8123. AST.prototype.toString = function () {
  8124. return 'AST';
  8125. };
  8126. return AST;
  8127. }());
  8128. var ASTWithName = /** @class */ (function (_super) {
  8129. __extends(ASTWithName, _super);
  8130. function ASTWithName(span, sourceSpan, nameSpan) {
  8131. var _this = _super.call(this, span, sourceSpan) || this;
  8132. _this.nameSpan = nameSpan;
  8133. return _this;
  8134. }
  8135. return ASTWithName;
  8136. }(AST));
  8137. /**
  8138. * Represents a quoted expression of the form:
  8139. *
  8140. * quote = prefix `:` uninterpretedExpression
  8141. * prefix = identifier
  8142. * uninterpretedExpression = arbitrary string
  8143. *
  8144. * A quoted expression is meant to be pre-processed by an AST transformer that
  8145. * converts it into another AST that no longer contains quoted expressions.
  8146. * It is meant to allow third-party developers to extend Angular template
  8147. * expression language. The `uninterpretedExpression` part of the quote is
  8148. * therefore not interpreted by the Angular's own expression parser.
  8149. */
  8150. var Quote = /** @class */ (function (_super) {
  8151. __extends(Quote, _super);
  8152. function Quote(span, sourceSpan, prefix, uninterpretedExpression, location) {
  8153. var _this = _super.call(this, span, sourceSpan) || this;
  8154. _this.prefix = prefix;
  8155. _this.uninterpretedExpression = uninterpretedExpression;
  8156. _this.location = location;
  8157. return _this;
  8158. }
  8159. Quote.prototype.visit = function (visitor, context) {
  8160. if (context === void 0) { context = null; }
  8161. return visitor.visitQuote(this, context);
  8162. };
  8163. Quote.prototype.toString = function () {
  8164. return 'Quote';
  8165. };
  8166. return Quote;
  8167. }(AST));
  8168. var EmptyExpr = /** @class */ (function (_super) {
  8169. __extends(EmptyExpr, _super);
  8170. function EmptyExpr() {
  8171. return _super !== null && _super.apply(this, arguments) || this;
  8172. }
  8173. EmptyExpr.prototype.visit = function (visitor, context) {
  8174. if (context === void 0) { context = null; }
  8175. // do nothing
  8176. };
  8177. return EmptyExpr;
  8178. }(AST));
  8179. var ImplicitReceiver = /** @class */ (function (_super) {
  8180. __extends(ImplicitReceiver, _super);
  8181. function ImplicitReceiver() {
  8182. return _super !== null && _super.apply(this, arguments) || this;
  8183. }
  8184. ImplicitReceiver.prototype.visit = function (visitor, context) {
  8185. if (context === void 0) { context = null; }
  8186. return visitor.visitImplicitReceiver(this, context);
  8187. };
  8188. return ImplicitReceiver;
  8189. }(AST));
  8190. /**
  8191. * Receiver when something is accessed through `this` (e.g. `this.foo`). Note that this class
  8192. * inherits from `ImplicitReceiver`, because accessing something through `this` is treated the
  8193. * same as accessing it implicitly inside of an Angular template (e.g. `[attr.title]="this.title"`
  8194. * is the same as `[attr.title]="title"`.). Inheriting allows for the `this` accesses to be treated
  8195. * the same as implicit ones, except for a couple of exceptions like `$event` and `$any`.
  8196. * TODO: we should find a way for this class not to extend from `ImplicitReceiver` in the future.
  8197. */
  8198. var ThisReceiver = /** @class */ (function (_super) {
  8199. __extends(ThisReceiver, _super);
  8200. function ThisReceiver() {
  8201. return _super !== null && _super.apply(this, arguments) || this;
  8202. }
  8203. ThisReceiver.prototype.visit = function (visitor, context) {
  8204. if (context === void 0) { context = null; }
  8205. var _a;
  8206. return (_a = visitor.visitThisReceiver) === null || _a === void 0 ? void 0 : _a.call(visitor, this, context);
  8207. };
  8208. return ThisReceiver;
  8209. }(ImplicitReceiver));
  8210. /**
  8211. * Multiple expressions separated by a semicolon.
  8212. */
  8213. var Chain = /** @class */ (function (_super) {
  8214. __extends(Chain, _super);
  8215. function Chain(span, sourceSpan, expressions) {
  8216. var _this = _super.call(this, span, sourceSpan) || this;
  8217. _this.expressions = expressions;
  8218. return _this;
  8219. }
  8220. Chain.prototype.visit = function (visitor, context) {
  8221. if (context === void 0) { context = null; }
  8222. return visitor.visitChain(this, context);
  8223. };
  8224. return Chain;
  8225. }(AST));
  8226. var Conditional = /** @class */ (function (_super) {
  8227. __extends(Conditional, _super);
  8228. function Conditional(span, sourceSpan, condition, trueExp, falseExp) {
  8229. var _this = _super.call(this, span, sourceSpan) || this;
  8230. _this.condition = condition;
  8231. _this.trueExp = trueExp;
  8232. _this.falseExp = falseExp;
  8233. return _this;
  8234. }
  8235. Conditional.prototype.visit = function (visitor, context) {
  8236. if (context === void 0) { context = null; }
  8237. return visitor.visitConditional(this, context);
  8238. };
  8239. return Conditional;
  8240. }(AST));
  8241. var PropertyRead = /** @class */ (function (_super) {
  8242. __extends(PropertyRead, _super);
  8243. function PropertyRead(span, sourceSpan, nameSpan, receiver, name) {
  8244. var _this = _super.call(this, span, sourceSpan, nameSpan) || this;
  8245. _this.receiver = receiver;
  8246. _this.name = name;
  8247. return _this;
  8248. }
  8249. PropertyRead.prototype.visit = function (visitor, context) {
  8250. if (context === void 0) { context = null; }
  8251. return visitor.visitPropertyRead(this, context);
  8252. };
  8253. return PropertyRead;
  8254. }(ASTWithName));
  8255. var PropertyWrite = /** @class */ (function (_super) {
  8256. __extends(PropertyWrite, _super);
  8257. function PropertyWrite(span, sourceSpan, nameSpan, receiver, name, value) {
  8258. var _this = _super.call(this, span, sourceSpan, nameSpan) || this;
  8259. _this.receiver = receiver;
  8260. _this.name = name;
  8261. _this.value = value;
  8262. return _this;
  8263. }
  8264. PropertyWrite.prototype.visit = function (visitor, context) {
  8265. if (context === void 0) { context = null; }
  8266. return visitor.visitPropertyWrite(this, context);
  8267. };
  8268. return PropertyWrite;
  8269. }(ASTWithName));
  8270. var SafePropertyRead = /** @class */ (function (_super) {
  8271. __extends(SafePropertyRead, _super);
  8272. function SafePropertyRead(span, sourceSpan, nameSpan, receiver, name) {
  8273. var _this = _super.call(this, span, sourceSpan, nameSpan) || this;
  8274. _this.receiver = receiver;
  8275. _this.name = name;
  8276. return _this;
  8277. }
  8278. SafePropertyRead.prototype.visit = function (visitor, context) {
  8279. if (context === void 0) { context = null; }
  8280. return visitor.visitSafePropertyRead(this, context);
  8281. };
  8282. return SafePropertyRead;
  8283. }(ASTWithName));
  8284. var KeyedRead = /** @class */ (function (_super) {
  8285. __extends(KeyedRead, _super);
  8286. function KeyedRead(span, sourceSpan, obj, key) {
  8287. var _this = _super.call(this, span, sourceSpan) || this;
  8288. _this.obj = obj;
  8289. _this.key = key;
  8290. return _this;
  8291. }
  8292. KeyedRead.prototype.visit = function (visitor, context) {
  8293. if (context === void 0) { context = null; }
  8294. return visitor.visitKeyedRead(this, context);
  8295. };
  8296. return KeyedRead;
  8297. }(AST));
  8298. var KeyedWrite = /** @class */ (function (_super) {
  8299. __extends(KeyedWrite, _super);
  8300. function KeyedWrite(span, sourceSpan, obj, key, value) {
  8301. var _this = _super.call(this, span, sourceSpan) || this;
  8302. _this.obj = obj;
  8303. _this.key = key;
  8304. _this.value = value;
  8305. return _this;
  8306. }
  8307. KeyedWrite.prototype.visit = function (visitor, context) {
  8308. if (context === void 0) { context = null; }
  8309. return visitor.visitKeyedWrite(this, context);
  8310. };
  8311. return KeyedWrite;
  8312. }(AST));
  8313. var BindingPipe = /** @class */ (function (_super) {
  8314. __extends(BindingPipe, _super);
  8315. function BindingPipe(span, sourceSpan, exp, name, args, nameSpan) {
  8316. var _this = _super.call(this, span, sourceSpan, nameSpan) || this;
  8317. _this.exp = exp;
  8318. _this.name = name;
  8319. _this.args = args;
  8320. return _this;
  8321. }
  8322. BindingPipe.prototype.visit = function (visitor, context) {
  8323. if (context === void 0) { context = null; }
  8324. return visitor.visitPipe(this, context);
  8325. };
  8326. return BindingPipe;
  8327. }(ASTWithName));
  8328. var LiteralPrimitive = /** @class */ (function (_super) {
  8329. __extends(LiteralPrimitive, _super);
  8330. function LiteralPrimitive(span, sourceSpan, value) {
  8331. var _this = _super.call(this, span, sourceSpan) || this;
  8332. _this.value = value;
  8333. return _this;
  8334. }
  8335. LiteralPrimitive.prototype.visit = function (visitor, context) {
  8336. if (context === void 0) { context = null; }
  8337. return visitor.visitLiteralPrimitive(this, context);
  8338. };
  8339. return LiteralPrimitive;
  8340. }(AST));
  8341. var LiteralArray = /** @class */ (function (_super) {
  8342. __extends(LiteralArray, _super);
  8343. function LiteralArray(span, sourceSpan, expressions) {
  8344. var _this = _super.call(this, span, sourceSpan) || this;
  8345. _this.expressions = expressions;
  8346. return _this;
  8347. }
  8348. LiteralArray.prototype.visit = function (visitor, context) {
  8349. if (context === void 0) { context = null; }
  8350. return visitor.visitLiteralArray(this, context);
  8351. };
  8352. return LiteralArray;
  8353. }(AST));
  8354. var LiteralMap = /** @class */ (function (_super) {
  8355. __extends(LiteralMap, _super);
  8356. function LiteralMap(span, sourceSpan, keys, values) {
  8357. var _this = _super.call(this, span, sourceSpan) || this;
  8358. _this.keys = keys;
  8359. _this.values = values;
  8360. return _this;
  8361. }
  8362. LiteralMap.prototype.visit = function (visitor, context) {
  8363. if (context === void 0) { context = null; }
  8364. return visitor.visitLiteralMap(this, context);
  8365. };
  8366. return LiteralMap;
  8367. }(AST));
  8368. var Interpolation = /** @class */ (function (_super) {
  8369. __extends(Interpolation, _super);
  8370. function Interpolation(span, sourceSpan, strings, expressions) {
  8371. var _this = _super.call(this, span, sourceSpan) || this;
  8372. _this.strings = strings;
  8373. _this.expressions = expressions;
  8374. return _this;
  8375. }
  8376. Interpolation.prototype.visit = function (visitor, context) {
  8377. if (context === void 0) { context = null; }
  8378. return visitor.visitInterpolation(this, context);
  8379. };
  8380. return Interpolation;
  8381. }(AST));
  8382. var Binary = /** @class */ (function (_super) {
  8383. __extends(Binary, _super);
  8384. function Binary(span, sourceSpan, operation, left, right) {
  8385. var _this = _super.call(this, span, sourceSpan) || this;
  8386. _this.operation = operation;
  8387. _this.left = left;
  8388. _this.right = right;
  8389. return _this;
  8390. }
  8391. Binary.prototype.visit = function (visitor, context) {
  8392. if (context === void 0) { context = null; }
  8393. return visitor.visitBinary(this, context);
  8394. };
  8395. return Binary;
  8396. }(AST));
  8397. /**
  8398. * For backwards compatibility reasons, `Unary` inherits from `Binary` and mimics the binary AST
  8399. * node that was originally used. This inheritance relation can be deleted in some future major,
  8400. * after consumers have been given a chance to fully support Unary.
  8401. */
  8402. var Unary = /** @class */ (function (_super) {
  8403. __extends(Unary, _super);
  8404. /**
  8405. * During the deprecation period this constructor is private, to avoid consumers from creating
  8406. * a `Unary` with the fallback properties for `Binary`.
  8407. */
  8408. function Unary(span, sourceSpan, operator, expr, binaryOp, binaryLeft, binaryRight) {
  8409. var _this = _super.call(this, span, sourceSpan, binaryOp, binaryLeft, binaryRight) || this;
  8410. _this.operator = operator;
  8411. _this.expr = expr;
  8412. return _this;
  8413. }
  8414. /**
  8415. * Creates a unary minus expression "-x", represented as `Binary` using "0 - x".
  8416. */
  8417. Unary.createMinus = function (span, sourceSpan, expr) {
  8418. return new Unary(span, sourceSpan, '-', expr, '-', new LiteralPrimitive(span, sourceSpan, 0), expr);
  8419. };
  8420. /**
  8421. * Creates a unary plus expression "+x", represented as `Binary` using "x - 0".
  8422. */
  8423. Unary.createPlus = function (span, sourceSpan, expr) {
  8424. return new Unary(span, sourceSpan, '+', expr, '-', expr, new LiteralPrimitive(span, sourceSpan, 0));
  8425. };
  8426. Unary.prototype.visit = function (visitor, context) {
  8427. if (context === void 0) { context = null; }
  8428. if (visitor.visitUnary !== undefined) {
  8429. return visitor.visitUnary(this, context);
  8430. }
  8431. return visitor.visitBinary(this, context);
  8432. };
  8433. return Unary;
  8434. }(Binary));
  8435. var PrefixNot = /** @class */ (function (_super) {
  8436. __extends(PrefixNot, _super);
  8437. function PrefixNot(span, sourceSpan, expression) {
  8438. var _this = _super.call(this, span, sourceSpan) || this;
  8439. _this.expression = expression;
  8440. return _this;
  8441. }
  8442. PrefixNot.prototype.visit = function (visitor, context) {
  8443. if (context === void 0) { context = null; }
  8444. return visitor.visitPrefixNot(this, context);
  8445. };
  8446. return PrefixNot;
  8447. }(AST));
  8448. var NonNullAssert = /** @class */ (function (_super) {
  8449. __extends(NonNullAssert, _super);
  8450. function NonNullAssert(span, sourceSpan, expression) {
  8451. var _this = _super.call(this, span, sourceSpan) || this;
  8452. _this.expression = expression;
  8453. return _this;
  8454. }
  8455. NonNullAssert.prototype.visit = function (visitor, context) {
  8456. if (context === void 0) { context = null; }
  8457. return visitor.visitNonNullAssert(this, context);
  8458. };
  8459. return NonNullAssert;
  8460. }(AST));
  8461. var MethodCall = /** @class */ (function (_super) {
  8462. __extends(MethodCall, _super);
  8463. function MethodCall(span, sourceSpan, nameSpan, receiver, name, args, argumentSpan) {
  8464. var _this = _super.call(this, span, sourceSpan, nameSpan) || this;
  8465. _this.receiver = receiver;
  8466. _this.name = name;
  8467. _this.args = args;
  8468. _this.argumentSpan = argumentSpan;
  8469. return _this;
  8470. }
  8471. MethodCall.prototype.visit = function (visitor, context) {
  8472. if (context === void 0) { context = null; }
  8473. return visitor.visitMethodCall(this, context);
  8474. };
  8475. return MethodCall;
  8476. }(ASTWithName));
  8477. var SafeMethodCall = /** @class */ (function (_super) {
  8478. __extends(SafeMethodCall, _super);
  8479. function SafeMethodCall(span, sourceSpan, nameSpan, receiver, name, args, argumentSpan) {
  8480. var _this = _super.call(this, span, sourceSpan, nameSpan) || this;
  8481. _this.receiver = receiver;
  8482. _this.name = name;
  8483. _this.args = args;
  8484. _this.argumentSpan = argumentSpan;
  8485. return _this;
  8486. }
  8487. SafeMethodCall.prototype.visit = function (visitor, context) {
  8488. if (context === void 0) { context = null; }
  8489. return visitor.visitSafeMethodCall(this, context);
  8490. };
  8491. return SafeMethodCall;
  8492. }(ASTWithName));
  8493. var FunctionCall = /** @class */ (function (_super) {
  8494. __extends(FunctionCall, _super);
  8495. function FunctionCall(span, sourceSpan, target, args) {
  8496. var _this = _super.call(this, span, sourceSpan) || this;
  8497. _this.target = target;
  8498. _this.args = args;
  8499. return _this;
  8500. }
  8501. FunctionCall.prototype.visit = function (visitor, context) {
  8502. if (context === void 0) { context = null; }
  8503. return visitor.visitFunctionCall(this, context);
  8504. };
  8505. return FunctionCall;
  8506. }(AST));
  8507. /**
  8508. * Records the absolute position of a text span in a source file, where `start` and `end` are the
  8509. * starting and ending byte offsets, respectively, of the text span in a source file.
  8510. */
  8511. var AbsoluteSourceSpan = /** @class */ (function () {
  8512. function AbsoluteSourceSpan(start, end) {
  8513. this.start = start;
  8514. this.end = end;
  8515. }
  8516. return AbsoluteSourceSpan;
  8517. }());
  8518. var ASTWithSource = /** @class */ (function (_super) {
  8519. __extends(ASTWithSource, _super);
  8520. function ASTWithSource(ast, source, location, absoluteOffset, errors) {
  8521. var _this = _super.call(this, new ParseSpan(0, source === null ? 0 : source.length), new AbsoluteSourceSpan(absoluteOffset, source === null ? absoluteOffset : absoluteOffset + source.length)) || this;
  8522. _this.ast = ast;
  8523. _this.source = source;
  8524. _this.location = location;
  8525. _this.errors = errors;
  8526. return _this;
  8527. }
  8528. ASTWithSource.prototype.visit = function (visitor, context) {
  8529. if (context === void 0) { context = null; }
  8530. if (visitor.visitASTWithSource) {
  8531. return visitor.visitASTWithSource(this, context);
  8532. }
  8533. return this.ast.visit(visitor, context);
  8534. };
  8535. ASTWithSource.prototype.toString = function () {
  8536. return this.source + " in " + this.location;
  8537. };
  8538. return ASTWithSource;
  8539. }(AST));
  8540. var VariableBinding = /** @class */ (function () {
  8541. /**
  8542. * @param sourceSpan entire span of the binding.
  8543. * @param key name of the LHS along with its span.
  8544. * @param value optional value for the RHS along with its span.
  8545. */
  8546. function VariableBinding(sourceSpan, key, value) {
  8547. this.sourceSpan = sourceSpan;
  8548. this.key = key;
  8549. this.value = value;
  8550. }
  8551. return VariableBinding;
  8552. }());
  8553. var ExpressionBinding = /** @class */ (function () {
  8554. /**
  8555. * @param sourceSpan entire span of the binding.
  8556. * @param key binding name, like ngForOf, ngForTrackBy, ngIf, along with its
  8557. * span. Note that the length of the span may not be the same as
  8558. * `key.source.length`. For example,
  8559. * 1. key.source = ngFor, key.span is for "ngFor"
  8560. * 2. key.source = ngForOf, key.span is for "of"
  8561. * 3. key.source = ngForTrackBy, key.span is for "trackBy"
  8562. * @param value optional expression for the RHS.
  8563. */
  8564. function ExpressionBinding(sourceSpan, key, value) {
  8565. this.sourceSpan = sourceSpan;
  8566. this.key = key;
  8567. this.value = value;
  8568. }
  8569. return ExpressionBinding;
  8570. }());
  8571. var RecursiveAstVisitor$1 = /** @class */ (function () {
  8572. function RecursiveAstVisitor() {
  8573. }
  8574. RecursiveAstVisitor.prototype.visit = function (ast, context) {
  8575. // The default implementation just visits every node.
  8576. // Classes that extend RecursiveAstVisitor should override this function
  8577. // to selectively visit the specified node.
  8578. ast.visit(this, context);
  8579. };
  8580. RecursiveAstVisitor.prototype.visitUnary = function (ast, context) {
  8581. this.visit(ast.expr, context);
  8582. };
  8583. RecursiveAstVisitor.prototype.visitBinary = function (ast, context) {
  8584. this.visit(ast.left, context);
  8585. this.visit(ast.right, context);
  8586. };
  8587. RecursiveAstVisitor.prototype.visitChain = function (ast, context) {
  8588. this.visitAll(ast.expressions, context);
  8589. };
  8590. RecursiveAstVisitor.prototype.visitConditional = function (ast, context) {
  8591. this.visit(ast.condition, context);
  8592. this.visit(ast.trueExp, context);
  8593. this.visit(ast.falseExp, context);
  8594. };
  8595. RecursiveAstVisitor.prototype.visitPipe = function (ast, context) {
  8596. this.visit(ast.exp, context);
  8597. this.visitAll(ast.args, context);
  8598. };
  8599. RecursiveAstVisitor.prototype.visitFunctionCall = function (ast, context) {
  8600. if (ast.target) {
  8601. this.visit(ast.target, context);
  8602. }
  8603. this.visitAll(ast.args, context);
  8604. };
  8605. RecursiveAstVisitor.prototype.visitImplicitReceiver = function (ast, context) { };
  8606. RecursiveAstVisitor.prototype.visitThisReceiver = function (ast, context) { };
  8607. RecursiveAstVisitor.prototype.visitInterpolation = function (ast, context) {
  8608. this.visitAll(ast.expressions, context);
  8609. };
  8610. RecursiveAstVisitor.prototype.visitKeyedRead = function (ast, context) {
  8611. this.visit(ast.obj, context);
  8612. this.visit(ast.key, context);
  8613. };
  8614. RecursiveAstVisitor.prototype.visitKeyedWrite = function (ast, context) {
  8615. this.visit(ast.obj, context);
  8616. this.visit(ast.key, context);
  8617. this.visit(ast.value, context);
  8618. };
  8619. RecursiveAstVisitor.prototype.visitLiteralArray = function (ast, context) {
  8620. this.visitAll(ast.expressions, context);
  8621. };
  8622. RecursiveAstVisitor.prototype.visitLiteralMap = function (ast, context) {
  8623. this.visitAll(ast.values, context);
  8624. };
  8625. RecursiveAstVisitor.prototype.visitLiteralPrimitive = function (ast, context) { };
  8626. RecursiveAstVisitor.prototype.visitMethodCall = function (ast, context) {
  8627. this.visit(ast.receiver, context);
  8628. this.visitAll(ast.args, context);
  8629. };
  8630. RecursiveAstVisitor.prototype.visitPrefixNot = function (ast, context) {
  8631. this.visit(ast.expression, context);
  8632. };
  8633. RecursiveAstVisitor.prototype.visitNonNullAssert = function (ast, context) {
  8634. this.visit(ast.expression, context);
  8635. };
  8636. RecursiveAstVisitor.prototype.visitPropertyRead = function (ast, context) {
  8637. this.visit(ast.receiver, context);
  8638. };
  8639. RecursiveAstVisitor.prototype.visitPropertyWrite = function (ast, context) {
  8640. this.visit(ast.receiver, context);
  8641. this.visit(ast.value, context);
  8642. };
  8643. RecursiveAstVisitor.prototype.visitSafePropertyRead = function (ast, context) {
  8644. this.visit(ast.receiver, context);
  8645. };
  8646. RecursiveAstVisitor.prototype.visitSafeMethodCall = function (ast, context) {
  8647. this.visit(ast.receiver, context);
  8648. this.visitAll(ast.args, context);
  8649. };
  8650. RecursiveAstVisitor.prototype.visitQuote = function (ast, context) { };
  8651. // This is not part of the AstVisitor interface, just a helper method
  8652. RecursiveAstVisitor.prototype.visitAll = function (asts, context) {
  8653. var e_1, _b;
  8654. try {
  8655. for (var asts_1 = __values(asts), asts_1_1 = asts_1.next(); !asts_1_1.done; asts_1_1 = asts_1.next()) {
  8656. var ast = asts_1_1.value;
  8657. this.visit(ast, context);
  8658. }
  8659. }
  8660. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  8661. finally {
  8662. try {
  8663. if (asts_1_1 && !asts_1_1.done && (_b = asts_1.return)) _b.call(asts_1);
  8664. }
  8665. finally { if (e_1) throw e_1.error; }
  8666. }
  8667. };
  8668. return RecursiveAstVisitor;
  8669. }());
  8670. var AstTransformer$1 = /** @class */ (function () {
  8671. function AstTransformer() {
  8672. }
  8673. AstTransformer.prototype.visitImplicitReceiver = function (ast, context) {
  8674. return ast;
  8675. };
  8676. AstTransformer.prototype.visitThisReceiver = function (ast, context) {
  8677. return ast;
  8678. };
  8679. AstTransformer.prototype.visitInterpolation = function (ast, context) {
  8680. return new Interpolation(ast.span, ast.sourceSpan, ast.strings, this.visitAll(ast.expressions));
  8681. };
  8682. AstTransformer.prototype.visitLiteralPrimitive = function (ast, context) {
  8683. return new LiteralPrimitive(ast.span, ast.sourceSpan, ast.value);
  8684. };
  8685. AstTransformer.prototype.visitPropertyRead = function (ast, context) {
  8686. return new PropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name);
  8687. };
  8688. AstTransformer.prototype.visitPropertyWrite = function (ast, context) {
  8689. return new PropertyWrite(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name, ast.value.visit(this));
  8690. };
  8691. AstTransformer.prototype.visitSafePropertyRead = function (ast, context) {
  8692. return new SafePropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name);
  8693. };
  8694. AstTransformer.prototype.visitMethodCall = function (ast, context) {
  8695. return new MethodCall(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name, this.visitAll(ast.args), ast.argumentSpan);
  8696. };
  8697. AstTransformer.prototype.visitSafeMethodCall = function (ast, context) {
  8698. return new SafeMethodCall(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name, this.visitAll(ast.args), ast.argumentSpan);
  8699. };
  8700. AstTransformer.prototype.visitFunctionCall = function (ast, context) {
  8701. return new FunctionCall(ast.span, ast.sourceSpan, ast.target.visit(this), this.visitAll(ast.args));
  8702. };
  8703. AstTransformer.prototype.visitLiteralArray = function (ast, context) {
  8704. return new LiteralArray(ast.span, ast.sourceSpan, this.visitAll(ast.expressions));
  8705. };
  8706. AstTransformer.prototype.visitLiteralMap = function (ast, context) {
  8707. return new LiteralMap(ast.span, ast.sourceSpan, ast.keys, this.visitAll(ast.values));
  8708. };
  8709. AstTransformer.prototype.visitUnary = function (ast, context) {
  8710. switch (ast.operator) {
  8711. case '+':
  8712. return Unary.createPlus(ast.span, ast.sourceSpan, ast.expr.visit(this));
  8713. case '-':
  8714. return Unary.createMinus(ast.span, ast.sourceSpan, ast.expr.visit(this));
  8715. default:
  8716. throw new Error("Unknown unary operator " + ast.operator);
  8717. }
  8718. };
  8719. AstTransformer.prototype.visitBinary = function (ast, context) {
  8720. return new Binary(ast.span, ast.sourceSpan, ast.operation, ast.left.visit(this), ast.right.visit(this));
  8721. };
  8722. AstTransformer.prototype.visitPrefixNot = function (ast, context) {
  8723. return new PrefixNot(ast.span, ast.sourceSpan, ast.expression.visit(this));
  8724. };
  8725. AstTransformer.prototype.visitNonNullAssert = function (ast, context) {
  8726. return new NonNullAssert(ast.span, ast.sourceSpan, ast.expression.visit(this));
  8727. };
  8728. AstTransformer.prototype.visitConditional = function (ast, context) {
  8729. return new Conditional(ast.span, ast.sourceSpan, ast.condition.visit(this), ast.trueExp.visit(this), ast.falseExp.visit(this));
  8730. };
  8731. AstTransformer.prototype.visitPipe = function (ast, context) {
  8732. return new BindingPipe(ast.span, ast.sourceSpan, ast.exp.visit(this), ast.name, this.visitAll(ast.args), ast.nameSpan);
  8733. };
  8734. AstTransformer.prototype.visitKeyedRead = function (ast, context) {
  8735. return new KeyedRead(ast.span, ast.sourceSpan, ast.obj.visit(this), ast.key.visit(this));
  8736. };
  8737. AstTransformer.prototype.visitKeyedWrite = function (ast, context) {
  8738. return new KeyedWrite(ast.span, ast.sourceSpan, ast.obj.visit(this), ast.key.visit(this), ast.value.visit(this));
  8739. };
  8740. AstTransformer.prototype.visitAll = function (asts) {
  8741. var res = [];
  8742. for (var i = 0; i < asts.length; ++i) {
  8743. res[i] = asts[i].visit(this);
  8744. }
  8745. return res;
  8746. };
  8747. AstTransformer.prototype.visitChain = function (ast, context) {
  8748. return new Chain(ast.span, ast.sourceSpan, this.visitAll(ast.expressions));
  8749. };
  8750. AstTransformer.prototype.visitQuote = function (ast, context) {
  8751. return new Quote(ast.span, ast.sourceSpan, ast.prefix, ast.uninterpretedExpression, ast.location);
  8752. };
  8753. return AstTransformer;
  8754. }());
  8755. // A transformer that only creates new nodes if the transformer makes a change or
  8756. // a change is made a child node.
  8757. var AstMemoryEfficientTransformer = /** @class */ (function () {
  8758. function AstMemoryEfficientTransformer() {
  8759. }
  8760. AstMemoryEfficientTransformer.prototype.visitImplicitReceiver = function (ast, context) {
  8761. return ast;
  8762. };
  8763. AstMemoryEfficientTransformer.prototype.visitThisReceiver = function (ast, context) {
  8764. return ast;
  8765. };
  8766. AstMemoryEfficientTransformer.prototype.visitInterpolation = function (ast, context) {
  8767. var expressions = this.visitAll(ast.expressions);
  8768. if (expressions !== ast.expressions)
  8769. return new Interpolation(ast.span, ast.sourceSpan, ast.strings, expressions);
  8770. return ast;
  8771. };
  8772. AstMemoryEfficientTransformer.prototype.visitLiteralPrimitive = function (ast, context) {
  8773. return ast;
  8774. };
  8775. AstMemoryEfficientTransformer.prototype.visitPropertyRead = function (ast, context) {
  8776. var receiver = ast.receiver.visit(this);
  8777. if (receiver !== ast.receiver) {
  8778. return new PropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name);
  8779. }
  8780. return ast;
  8781. };
  8782. AstMemoryEfficientTransformer.prototype.visitPropertyWrite = function (ast, context) {
  8783. var receiver = ast.receiver.visit(this);
  8784. var value = ast.value.visit(this);
  8785. if (receiver !== ast.receiver || value !== ast.value) {
  8786. return new PropertyWrite(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name, value);
  8787. }
  8788. return ast;
  8789. };
  8790. AstMemoryEfficientTransformer.prototype.visitSafePropertyRead = function (ast, context) {
  8791. var receiver = ast.receiver.visit(this);
  8792. if (receiver !== ast.receiver) {
  8793. return new SafePropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name);
  8794. }
  8795. return ast;
  8796. };
  8797. AstMemoryEfficientTransformer.prototype.visitMethodCall = function (ast, context) {
  8798. var receiver = ast.receiver.visit(this);
  8799. var args = this.visitAll(ast.args);
  8800. if (receiver !== ast.receiver || args !== ast.args) {
  8801. return new MethodCall(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name, args, ast.argumentSpan);
  8802. }
  8803. return ast;
  8804. };
  8805. AstMemoryEfficientTransformer.prototype.visitSafeMethodCall = function (ast, context) {
  8806. var receiver = ast.receiver.visit(this);
  8807. var args = this.visitAll(ast.args);
  8808. if (receiver !== ast.receiver || args !== ast.args) {
  8809. return new SafeMethodCall(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name, args, ast.argumentSpan);
  8810. }
  8811. return ast;
  8812. };
  8813. AstMemoryEfficientTransformer.prototype.visitFunctionCall = function (ast, context) {
  8814. var target = ast.target && ast.target.visit(this);
  8815. var args = this.visitAll(ast.args);
  8816. if (target !== ast.target || args !== ast.args) {
  8817. return new FunctionCall(ast.span, ast.sourceSpan, target, args);
  8818. }
  8819. return ast;
  8820. };
  8821. AstMemoryEfficientTransformer.prototype.visitLiteralArray = function (ast, context) {
  8822. var expressions = this.visitAll(ast.expressions);
  8823. if (expressions !== ast.expressions) {
  8824. return new LiteralArray(ast.span, ast.sourceSpan, expressions);
  8825. }
  8826. return ast;
  8827. };
  8828. AstMemoryEfficientTransformer.prototype.visitLiteralMap = function (ast, context) {
  8829. var values = this.visitAll(ast.values);
  8830. if (values !== ast.values) {
  8831. return new LiteralMap(ast.span, ast.sourceSpan, ast.keys, values);
  8832. }
  8833. return ast;
  8834. };
  8835. AstMemoryEfficientTransformer.prototype.visitUnary = function (ast, context) {
  8836. var expr = ast.expr.visit(this);
  8837. if (expr !== ast.expr) {
  8838. switch (ast.operator) {
  8839. case '+':
  8840. return Unary.createPlus(ast.span, ast.sourceSpan, expr);
  8841. case '-':
  8842. return Unary.createMinus(ast.span, ast.sourceSpan, expr);
  8843. default:
  8844. throw new Error("Unknown unary operator " + ast.operator);
  8845. }
  8846. }
  8847. return ast;
  8848. };
  8849. AstMemoryEfficientTransformer.prototype.visitBinary = function (ast, context) {
  8850. var left = ast.left.visit(this);
  8851. var right = ast.right.visit(this);
  8852. if (left !== ast.left || right !== ast.right) {
  8853. return new Binary(ast.span, ast.sourceSpan, ast.operation, left, right);
  8854. }
  8855. return ast;
  8856. };
  8857. AstMemoryEfficientTransformer.prototype.visitPrefixNot = function (ast, context) {
  8858. var expression = ast.expression.visit(this);
  8859. if (expression !== ast.expression) {
  8860. return new PrefixNot(ast.span, ast.sourceSpan, expression);
  8861. }
  8862. return ast;
  8863. };
  8864. AstMemoryEfficientTransformer.prototype.visitNonNullAssert = function (ast, context) {
  8865. var expression = ast.expression.visit(this);
  8866. if (expression !== ast.expression) {
  8867. return new NonNullAssert(ast.span, ast.sourceSpan, expression);
  8868. }
  8869. return ast;
  8870. };
  8871. AstMemoryEfficientTransformer.prototype.visitConditional = function (ast, context) {
  8872. var condition = ast.condition.visit(this);
  8873. var trueExp = ast.trueExp.visit(this);
  8874. var falseExp = ast.falseExp.visit(this);
  8875. if (condition !== ast.condition || trueExp !== ast.trueExp || falseExp !== ast.falseExp) {
  8876. return new Conditional(ast.span, ast.sourceSpan, condition, trueExp, falseExp);
  8877. }
  8878. return ast;
  8879. };
  8880. AstMemoryEfficientTransformer.prototype.visitPipe = function (ast, context) {
  8881. var exp = ast.exp.visit(this);
  8882. var args = this.visitAll(ast.args);
  8883. if (exp !== ast.exp || args !== ast.args) {
  8884. return new BindingPipe(ast.span, ast.sourceSpan, exp, ast.name, args, ast.nameSpan);
  8885. }
  8886. return ast;
  8887. };
  8888. AstMemoryEfficientTransformer.prototype.visitKeyedRead = function (ast, context) {
  8889. var obj = ast.obj.visit(this);
  8890. var key = ast.key.visit(this);
  8891. if (obj !== ast.obj || key !== ast.key) {
  8892. return new KeyedRead(ast.span, ast.sourceSpan, obj, key);
  8893. }
  8894. return ast;
  8895. };
  8896. AstMemoryEfficientTransformer.prototype.visitKeyedWrite = function (ast, context) {
  8897. var obj = ast.obj.visit(this);
  8898. var key = ast.key.visit(this);
  8899. var value = ast.value.visit(this);
  8900. if (obj !== ast.obj || key !== ast.key || value !== ast.value) {
  8901. return new KeyedWrite(ast.span, ast.sourceSpan, obj, key, value);
  8902. }
  8903. return ast;
  8904. };
  8905. AstMemoryEfficientTransformer.prototype.visitAll = function (asts) {
  8906. var res = [];
  8907. var modified = false;
  8908. for (var i = 0; i < asts.length; ++i) {
  8909. var original = asts[i];
  8910. var value = original.visit(this);
  8911. res[i] = value;
  8912. modified = modified || value !== original;
  8913. }
  8914. return modified ? res : asts;
  8915. };
  8916. AstMemoryEfficientTransformer.prototype.visitChain = function (ast, context) {
  8917. var expressions = this.visitAll(ast.expressions);
  8918. if (expressions !== ast.expressions) {
  8919. return new Chain(ast.span, ast.sourceSpan, expressions);
  8920. }
  8921. return ast;
  8922. };
  8923. AstMemoryEfficientTransformer.prototype.visitQuote = function (ast, context) {
  8924. return ast;
  8925. };
  8926. return AstMemoryEfficientTransformer;
  8927. }());
  8928. // Bindings
  8929. var ParsedProperty = /** @class */ (function () {
  8930. function ParsedProperty(name, expression, type,
  8931. // TODO(FW-2095): `keySpan` should really be required but allows `undefined` so VE does
  8932. // not need to be updated. Make `keySpan` required when VE is removed.
  8933. sourceSpan, keySpan, valueSpan) {
  8934. this.name = name;
  8935. this.expression = expression;
  8936. this.type = type;
  8937. this.sourceSpan = sourceSpan;
  8938. this.keySpan = keySpan;
  8939. this.valueSpan = valueSpan;
  8940. this.isLiteral = this.type === exports.ParsedPropertyType.LITERAL_ATTR;
  8941. this.isAnimation = this.type === exports.ParsedPropertyType.ANIMATION;
  8942. }
  8943. return ParsedProperty;
  8944. }());
  8945. (function (ParsedPropertyType) {
  8946. ParsedPropertyType[ParsedPropertyType["DEFAULT"] = 0] = "DEFAULT";
  8947. ParsedPropertyType[ParsedPropertyType["LITERAL_ATTR"] = 1] = "LITERAL_ATTR";
  8948. ParsedPropertyType[ParsedPropertyType["ANIMATION"] = 2] = "ANIMATION";
  8949. })(exports.ParsedPropertyType || (exports.ParsedPropertyType = {}));
  8950. var ParsedEvent = /** @class */ (function () {
  8951. // Regular events have a target
  8952. // Animation events have a phase
  8953. function ParsedEvent(name, targetOrPhase, type, handler, sourceSpan,
  8954. // TODO(FW-2095): keySpan should be required but was made optional to avoid changing VE
  8955. handlerSpan, keySpan) {
  8956. this.name = name;
  8957. this.targetOrPhase = targetOrPhase;
  8958. this.type = type;
  8959. this.handler = handler;
  8960. this.sourceSpan = sourceSpan;
  8961. this.handlerSpan = handlerSpan;
  8962. this.keySpan = keySpan;
  8963. }
  8964. return ParsedEvent;
  8965. }());
  8966. /**
  8967. * ParsedVariable represents a variable declaration in a microsyntax expression.
  8968. */
  8969. var ParsedVariable = /** @class */ (function () {
  8970. function ParsedVariable(name, value, sourceSpan, keySpan, valueSpan) {
  8971. this.name = name;
  8972. this.value = value;
  8973. this.sourceSpan = sourceSpan;
  8974. this.keySpan = keySpan;
  8975. this.valueSpan = valueSpan;
  8976. }
  8977. return ParsedVariable;
  8978. }());
  8979. var BoundElementProperty = /** @class */ (function () {
  8980. function BoundElementProperty(name, type, securityContext, value, unit, sourceSpan, keySpan, valueSpan) {
  8981. this.name = name;
  8982. this.type = type;
  8983. this.securityContext = securityContext;
  8984. this.value = value;
  8985. this.unit = unit;
  8986. this.sourceSpan = sourceSpan;
  8987. this.keySpan = keySpan;
  8988. this.valueSpan = valueSpan;
  8989. }
  8990. return BoundElementProperty;
  8991. }());
  8992. /**
  8993. * @license
  8994. * Copyright Google LLC All Rights Reserved.
  8995. *
  8996. * Use of this source code is governed by an MIT-style license that can be
  8997. * found in the LICENSE file at https://angular.io/license
  8998. */
  8999. var CORE$1 = '@angular/core';
  9000. var Identifiers$1 = /** @class */ (function () {
  9001. function Identifiers() {
  9002. }
  9003. return Identifiers;
  9004. }());
  9005. Identifiers$1.ANALYZE_FOR_ENTRY_COMPONENTS = {
  9006. name: 'ANALYZE_FOR_ENTRY_COMPONENTS',
  9007. moduleName: CORE$1,
  9008. };
  9009. Identifiers$1.ElementRef = { name: 'ElementRef', moduleName: CORE$1 };
  9010. Identifiers$1.NgModuleRef = { name: 'NgModuleRef', moduleName: CORE$1 };
  9011. Identifiers$1.ViewContainerRef = { name: 'ViewContainerRef', moduleName: CORE$1 };
  9012. Identifiers$1.ChangeDetectorRef = {
  9013. name: 'ChangeDetectorRef',
  9014. moduleName: CORE$1,
  9015. };
  9016. Identifiers$1.QueryList = { name: 'QueryList', moduleName: CORE$1 };
  9017. Identifiers$1.TemplateRef = { name: 'TemplateRef', moduleName: CORE$1 };
  9018. Identifiers$1.Renderer2 = { name: 'Renderer2', moduleName: CORE$1 };
  9019. Identifiers$1.CodegenComponentFactoryResolver = {
  9020. name: 'ɵCodegenComponentFactoryResolver',
  9021. moduleName: CORE$1,
  9022. };
  9023. Identifiers$1.ComponentFactoryResolver = {
  9024. name: 'ComponentFactoryResolver',
  9025. moduleName: CORE$1,
  9026. };
  9027. Identifiers$1.ComponentFactory = { name: 'ComponentFactory', moduleName: CORE$1 };
  9028. Identifiers$1.ComponentRef = { name: 'ComponentRef', moduleName: CORE$1 };
  9029. Identifiers$1.NgModuleFactory = { name: 'NgModuleFactory', moduleName: CORE$1 };
  9030. Identifiers$1.createModuleFactory = {
  9031. name: 'ɵcmf',
  9032. moduleName: CORE$1,
  9033. };
  9034. Identifiers$1.moduleDef = {
  9035. name: 'ɵmod',
  9036. moduleName: CORE$1,
  9037. };
  9038. Identifiers$1.moduleProviderDef = {
  9039. name: 'ɵmpd',
  9040. moduleName: CORE$1,
  9041. };
  9042. Identifiers$1.RegisterModuleFactoryFn = {
  9043. name: 'ɵregisterModuleFactory',
  9044. moduleName: CORE$1,
  9045. };
  9046. Identifiers$1.inject = { name: 'ɵɵinject', moduleName: CORE$1 };
  9047. Identifiers$1.directiveInject = { name: 'ɵɵdirectiveInject', moduleName: CORE$1 };
  9048. Identifiers$1.INJECTOR = { name: 'INJECTOR', moduleName: CORE$1 };
  9049. Identifiers$1.Injector = { name: 'Injector', moduleName: CORE$1 };
  9050. Identifiers$1.ViewEncapsulation = {
  9051. name: 'ViewEncapsulation',
  9052. moduleName: CORE$1,
  9053. };
  9054. Identifiers$1.ChangeDetectionStrategy = {
  9055. name: 'ChangeDetectionStrategy',
  9056. moduleName: CORE$1,
  9057. };
  9058. Identifiers$1.SecurityContext = {
  9059. name: 'SecurityContext',
  9060. moduleName: CORE$1,
  9061. };
  9062. Identifiers$1.LOCALE_ID = { name: 'LOCALE_ID', moduleName: CORE$1 };
  9063. Identifiers$1.TRANSLATIONS_FORMAT = {
  9064. name: 'TRANSLATIONS_FORMAT',
  9065. moduleName: CORE$1,
  9066. };
  9067. Identifiers$1.inlineInterpolate = {
  9068. name: 'ɵinlineInterpolate',
  9069. moduleName: CORE$1,
  9070. };
  9071. Identifiers$1.interpolate = { name: 'ɵinterpolate', moduleName: CORE$1 };
  9072. Identifiers$1.EMPTY_ARRAY = { name: 'ɵEMPTY_ARRAY', moduleName: CORE$1 };
  9073. Identifiers$1.EMPTY_MAP = { name: 'ɵEMPTY_MAP', moduleName: CORE$1 };
  9074. Identifiers$1.Renderer = { name: 'Renderer', moduleName: CORE$1 };
  9075. Identifiers$1.viewDef = { name: 'ɵvid', moduleName: CORE$1 };
  9076. Identifiers$1.elementDef = { name: 'ɵeld', moduleName: CORE$1 };
  9077. Identifiers$1.anchorDef = { name: 'ɵand', moduleName: CORE$1 };
  9078. Identifiers$1.textDef = { name: 'ɵted', moduleName: CORE$1 };
  9079. Identifiers$1.directiveDef = { name: 'ɵdid', moduleName: CORE$1 };
  9080. Identifiers$1.providerDef = { name: 'ɵprd', moduleName: CORE$1 };
  9081. Identifiers$1.queryDef = { name: 'ɵqud', moduleName: CORE$1 };
  9082. Identifiers$1.pureArrayDef = { name: 'ɵpad', moduleName: CORE$1 };
  9083. Identifiers$1.pureObjectDef = { name: 'ɵpod', moduleName: CORE$1 };
  9084. Identifiers$1.purePipeDef = { name: 'ɵppd', moduleName: CORE$1 };
  9085. Identifiers$1.pipeDef = { name: 'ɵpid', moduleName: CORE$1 };
  9086. Identifiers$1.nodeValue = { name: 'ɵnov', moduleName: CORE$1 };
  9087. Identifiers$1.ngContentDef = { name: 'ɵncd', moduleName: CORE$1 };
  9088. Identifiers$1.unwrapValue = { name: 'ɵunv', moduleName: CORE$1 };
  9089. Identifiers$1.createRendererType2 = { name: 'ɵcrt', moduleName: CORE$1 };
  9090. // type only
  9091. Identifiers$1.RendererType2 = {
  9092. name: 'RendererType2',
  9093. moduleName: CORE$1,
  9094. };
  9095. // type only
  9096. Identifiers$1.ViewDefinition = {
  9097. name: 'ɵViewDefinition',
  9098. moduleName: CORE$1,
  9099. };
  9100. Identifiers$1.createComponentFactory = { name: 'ɵccf', moduleName: CORE$1 };
  9101. function createTokenForReference(reference) {
  9102. return { identifier: { reference: reference } };
  9103. }
  9104. function createTokenForExternalReference(reflector, reference) {
  9105. return createTokenForReference(reflector.resolveExternalReference(reference));
  9106. }
  9107. var EventHandlerVars = /** @class */ (function () {
  9108. function EventHandlerVars() {
  9109. }
  9110. return EventHandlerVars;
  9111. }());
  9112. EventHandlerVars.event = variable('$event');
  9113. var ConvertActionBindingResult = /** @class */ (function () {
  9114. function ConvertActionBindingResult(
  9115. /**
  9116. * Render2 compatible statements,
  9117. */
  9118. stmts,
  9119. /**
  9120. * Variable name used with render2 compatible statements.
  9121. */
  9122. allowDefault) {
  9123. this.stmts = stmts;
  9124. this.allowDefault = allowDefault;
  9125. /**
  9126. * This is bit of a hack. It converts statements which render2 expects to statements which are
  9127. * expected by render3.
  9128. *
  9129. * Example: `<div click="doSomething($event)">` will generate:
  9130. *
  9131. * Render3:
  9132. * ```
  9133. * const pd_b:any = ((<any>ctx.doSomething($event)) !== false);
  9134. * return pd_b;
  9135. * ```
  9136. *
  9137. * but render2 expects:
  9138. * ```
  9139. * return ctx.doSomething($event);
  9140. * ```
  9141. */
  9142. // TODO(misko): remove this hack once we no longer support ViewEngine.
  9143. this.render3Stmts = stmts.map(function (statement) {
  9144. if (statement instanceof DeclareVarStmt && statement.name == allowDefault.name &&
  9145. statement.value instanceof BinaryOperatorExpr) {
  9146. var lhs = statement.value.lhs;
  9147. return new ReturnStatement(lhs.value);
  9148. }
  9149. return statement;
  9150. });
  9151. }
  9152. return ConvertActionBindingResult;
  9153. }());
  9154. /**
  9155. * Converts the given expression AST into an executable output AST, assuming the expression is
  9156. * used in an action binding (e.g. an event handler).
  9157. */
  9158. function convertActionBinding(localResolver, implicitReceiver, action, bindingId, interpolationFunction, baseSourceSpan, implicitReceiverAccesses, globals) {
  9159. if (!localResolver) {
  9160. localResolver = new DefaultLocalResolver(globals);
  9161. }
  9162. var actionWithoutBuiltins = convertPropertyBindingBuiltins({
  9163. createLiteralArrayConverter: function (argCount) {
  9164. // Note: no caching for literal arrays in actions.
  9165. return function (args) { return literalArr(args); };
  9166. },
  9167. createLiteralMapConverter: function (keys) {
  9168. // Note: no caching for literal maps in actions.
  9169. return function (values) {
  9170. var entries = keys.map(function (k, i) { return ({
  9171. key: k.key,
  9172. value: values[i],
  9173. quoted: k.quoted,
  9174. }); });
  9175. return literalMap(entries);
  9176. };
  9177. },
  9178. createPipeConverter: function (name) {
  9179. throw new Error("Illegal State: Actions are not allowed to contain pipes. Pipe: " + name);
  9180. }
  9181. }, action);
  9182. var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction, baseSourceSpan, implicitReceiverAccesses);
  9183. var actionStmts = [];
  9184. flattenStatements(actionWithoutBuiltins.visit(visitor, _Mode.Statement), actionStmts);
  9185. prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts);
  9186. if (visitor.usesImplicitReceiver) {
  9187. localResolver.notifyImplicitReceiverUse();
  9188. }
  9189. var lastIndex = actionStmts.length - 1;
  9190. var preventDefaultVar = null;
  9191. if (lastIndex >= 0) {
  9192. var lastStatement = actionStmts[lastIndex];
  9193. var returnExpr = convertStmtIntoExpression(lastStatement);
  9194. if (returnExpr) {
  9195. // Note: We need to cast the result of the method call to dynamic,
  9196. // as it might be a void method!
  9197. preventDefaultVar = createPreventDefaultVar(bindingId);
  9198. actionStmts[lastIndex] =
  9199. preventDefaultVar.set(returnExpr.cast(DYNAMIC_TYPE).notIdentical(literal(false)))
  9200. .toDeclStmt(null, [exports.StmtModifier.Final]);
  9201. }
  9202. }
  9203. return new ConvertActionBindingResult(actionStmts, preventDefaultVar);
  9204. }
  9205. function convertPropertyBindingBuiltins(converterFactory, ast) {
  9206. return convertBuiltins(converterFactory, ast);
  9207. }
  9208. var ConvertPropertyBindingResult = /** @class */ (function () {
  9209. function ConvertPropertyBindingResult(stmts, currValExpr) {
  9210. this.stmts = stmts;
  9211. this.currValExpr = currValExpr;
  9212. }
  9213. return ConvertPropertyBindingResult;
  9214. }());
  9215. var BindingForm;
  9216. (function (BindingForm) {
  9217. // The general form of binding expression, supports all expressions.
  9218. BindingForm[BindingForm["General"] = 0] = "General";
  9219. // Try to generate a simple binding (no temporaries or statements)
  9220. // otherwise generate a general binding
  9221. BindingForm[BindingForm["TrySimple"] = 1] = "TrySimple";
  9222. // Inlines assignment of temporaries into the generated expression. The result may still
  9223. // have statements attached for declarations of temporary variables.
  9224. // This is the only relevant form for Ivy, the other forms are only used in ViewEngine.
  9225. BindingForm[BindingForm["Expression"] = 2] = "Expression";
  9226. })(BindingForm || (BindingForm = {}));
  9227. /**
  9228. * Converts the given expression AST into an executable output AST, assuming the expression
  9229. * is used in property binding. The expression has to be preprocessed via
  9230. * `convertPropertyBindingBuiltins`.
  9231. */
  9232. function convertPropertyBinding(localResolver, implicitReceiver, expressionWithoutBuiltins, bindingId, form, interpolationFunction) {
  9233. if (!localResolver) {
  9234. localResolver = new DefaultLocalResolver();
  9235. }
  9236. var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction);
  9237. var outputExpr = expressionWithoutBuiltins.visit(visitor, _Mode.Expression);
  9238. var stmts = getStatementsFromVisitor(visitor, bindingId);
  9239. if (visitor.usesImplicitReceiver) {
  9240. localResolver.notifyImplicitReceiverUse();
  9241. }
  9242. if (visitor.temporaryCount === 0 && form == BindingForm.TrySimple) {
  9243. return new ConvertPropertyBindingResult([], outputExpr);
  9244. }
  9245. else if (form === BindingForm.Expression) {
  9246. return new ConvertPropertyBindingResult(stmts, outputExpr);
  9247. }
  9248. var currValExpr = createCurrValueExpr(bindingId);
  9249. stmts.push(currValExpr.set(outputExpr).toDeclStmt(DYNAMIC_TYPE, [exports.StmtModifier.Final]));
  9250. return new ConvertPropertyBindingResult(stmts, currValExpr);
  9251. }
  9252. /**
  9253. * Given some expression, such as a binding or interpolation expression, and a context expression to
  9254. * look values up on, visit each facet of the given expression resolving values from the context
  9255. * expression such that a list of arguments can be derived from the found values that can be used as
  9256. * arguments to an external update instruction.
  9257. *
  9258. * @param localResolver The resolver to use to look up expressions by name appropriately
  9259. * @param contextVariableExpression The expression representing the context variable used to create
  9260. * the final argument expressions
  9261. * @param expressionWithArgumentsToExtract The expression to visit to figure out what values need to
  9262. * be resolved and what arguments list to build.
  9263. * @param bindingId A name prefix used to create temporary variable names if they're needed for the
  9264. * arguments generated
  9265. * @returns An array of expressions that can be passed as arguments to instruction expressions like
  9266. * `o.importExpr(R3.propertyInterpolate).callFn(result)`
  9267. */
  9268. function convertUpdateArguments(localResolver, contextVariableExpression, expressionWithArgumentsToExtract, bindingId) {
  9269. var visitor = new _AstToIrVisitor(localResolver, contextVariableExpression, bindingId, undefined);
  9270. var outputExpr = expressionWithArgumentsToExtract.visit(visitor, _Mode.Expression);
  9271. if (visitor.usesImplicitReceiver) {
  9272. localResolver.notifyImplicitReceiverUse();
  9273. }
  9274. var stmts = getStatementsFromVisitor(visitor, bindingId);
  9275. // Removing the first argument, because it was a length for ViewEngine, not Ivy.
  9276. var args = outputExpr.args.slice(1);
  9277. if (expressionWithArgumentsToExtract instanceof Interpolation) {
  9278. // If we're dealing with an interpolation of 1 value with an empty prefix and suffix, reduce the
  9279. // args returned to just the value, because we're going to pass it to a special instruction.
  9280. var strings = expressionWithArgumentsToExtract.strings;
  9281. if (args.length === 3 && strings[0] === '' && strings[1] === '') {
  9282. // Single argument interpolate instructions.
  9283. args = [args[1]];
  9284. }
  9285. else if (args.length >= 19) {
  9286. // 19 or more arguments must be passed to the `interpolateV`-style instructions, which accept
  9287. // an array of arguments
  9288. args = [literalArr(args)];
  9289. }
  9290. }
  9291. return { stmts: stmts, args: args };
  9292. }
  9293. function getStatementsFromVisitor(visitor, bindingId) {
  9294. var stmts = [];
  9295. for (var i = 0; i < visitor.temporaryCount; i++) {
  9296. stmts.push(temporaryDeclaration(bindingId, i));
  9297. }
  9298. return stmts;
  9299. }
  9300. function convertBuiltins(converterFactory, ast) {
  9301. var visitor = new _BuiltinAstConverter(converterFactory);
  9302. return ast.visit(visitor);
  9303. }
  9304. function temporaryName(bindingId, temporaryNumber) {
  9305. return "tmp_" + bindingId + "_" + temporaryNumber;
  9306. }
  9307. function temporaryDeclaration(bindingId, temporaryNumber) {
  9308. return new DeclareVarStmt(temporaryName(bindingId, temporaryNumber));
  9309. }
  9310. function prependTemporaryDecls(temporaryCount, bindingId, statements) {
  9311. for (var i = temporaryCount - 1; i >= 0; i--) {
  9312. statements.unshift(temporaryDeclaration(bindingId, i));
  9313. }
  9314. }
  9315. var _Mode;
  9316. (function (_Mode) {
  9317. _Mode[_Mode["Statement"] = 0] = "Statement";
  9318. _Mode[_Mode["Expression"] = 1] = "Expression";
  9319. })(_Mode || (_Mode = {}));
  9320. function ensureStatementMode(mode, ast) {
  9321. if (mode !== _Mode.Statement) {
  9322. throw new Error("Expected a statement, but saw " + ast);
  9323. }
  9324. }
  9325. function ensureExpressionMode(mode, ast) {
  9326. if (mode !== _Mode.Expression) {
  9327. throw new Error("Expected an expression, but saw " + ast);
  9328. }
  9329. }
  9330. function convertToStatementIfNeeded(mode, expr) {
  9331. if (mode === _Mode.Statement) {
  9332. return expr.toStmt();
  9333. }
  9334. else {
  9335. return expr;
  9336. }
  9337. }
  9338. var _BuiltinAstConverter = /** @class */ (function (_super) {
  9339. __extends(_BuiltinAstConverter, _super);
  9340. function _BuiltinAstConverter(_converterFactory) {
  9341. var _this = _super.call(this) || this;
  9342. _this._converterFactory = _converterFactory;
  9343. return _this;
  9344. }
  9345. _BuiltinAstConverter.prototype.visitPipe = function (ast, context) {
  9346. var _this = this;
  9347. var args = __spreadArray([ast.exp], __read(ast.args)).map(function (ast) { return ast.visit(_this, context); });
  9348. return new BuiltinFunctionCall(ast.span, ast.sourceSpan, args, this._converterFactory.createPipeConverter(ast.name, args.length));
  9349. };
  9350. _BuiltinAstConverter.prototype.visitLiteralArray = function (ast, context) {
  9351. var _this = this;
  9352. var args = ast.expressions.map(function (ast) { return ast.visit(_this, context); });
  9353. return new BuiltinFunctionCall(ast.span, ast.sourceSpan, args, this._converterFactory.createLiteralArrayConverter(ast.expressions.length));
  9354. };
  9355. _BuiltinAstConverter.prototype.visitLiteralMap = function (ast, context) {
  9356. var _this = this;
  9357. var args = ast.values.map(function (ast) { return ast.visit(_this, context); });
  9358. return new BuiltinFunctionCall(ast.span, ast.sourceSpan, args, this._converterFactory.createLiteralMapConverter(ast.keys));
  9359. };
  9360. return _BuiltinAstConverter;
  9361. }(AstTransformer$1));
  9362. var _AstToIrVisitor = /** @class */ (function () {
  9363. function _AstToIrVisitor(_localResolver, _implicitReceiver, bindingId, interpolationFunction, baseSourceSpan, implicitReceiverAccesses) {
  9364. this._localResolver = _localResolver;
  9365. this._implicitReceiver = _implicitReceiver;
  9366. this.bindingId = bindingId;
  9367. this.interpolationFunction = interpolationFunction;
  9368. this.baseSourceSpan = baseSourceSpan;
  9369. this.implicitReceiverAccesses = implicitReceiverAccesses;
  9370. this._nodeMap = new Map();
  9371. this._resultMap = new Map();
  9372. this._currentTemporary = 0;
  9373. this.temporaryCount = 0;
  9374. this.usesImplicitReceiver = false;
  9375. }
  9376. _AstToIrVisitor.prototype.visitUnary = function (ast, mode) {
  9377. var op;
  9378. switch (ast.operator) {
  9379. case '+':
  9380. op = exports.UnaryOperator.Plus;
  9381. break;
  9382. case '-':
  9383. op = exports.UnaryOperator.Minus;
  9384. break;
  9385. default:
  9386. throw new Error("Unsupported operator " + ast.operator);
  9387. }
  9388. return convertToStatementIfNeeded(mode, new UnaryOperatorExpr(op, this._visit(ast.expr, _Mode.Expression), undefined, this.convertSourceSpan(ast.span)));
  9389. };
  9390. _AstToIrVisitor.prototype.visitBinary = function (ast, mode) {
  9391. var op;
  9392. switch (ast.operation) {
  9393. case '+':
  9394. op = exports.BinaryOperator.Plus;
  9395. break;
  9396. case '-':
  9397. op = exports.BinaryOperator.Minus;
  9398. break;
  9399. case '*':
  9400. op = exports.BinaryOperator.Multiply;
  9401. break;
  9402. case '/':
  9403. op = exports.BinaryOperator.Divide;
  9404. break;
  9405. case '%':
  9406. op = exports.BinaryOperator.Modulo;
  9407. break;
  9408. case '&&':
  9409. op = exports.BinaryOperator.And;
  9410. break;
  9411. case '||':
  9412. op = exports.BinaryOperator.Or;
  9413. break;
  9414. case '==':
  9415. op = exports.BinaryOperator.Equals;
  9416. break;
  9417. case '!=':
  9418. op = exports.BinaryOperator.NotEquals;
  9419. break;
  9420. case '===':
  9421. op = exports.BinaryOperator.Identical;
  9422. break;
  9423. case '!==':
  9424. op = exports.BinaryOperator.NotIdentical;
  9425. break;
  9426. case '<':
  9427. op = exports.BinaryOperator.Lower;
  9428. break;
  9429. case '>':
  9430. op = exports.BinaryOperator.Bigger;
  9431. break;
  9432. case '<=':
  9433. op = exports.BinaryOperator.LowerEquals;
  9434. break;
  9435. case '>=':
  9436. op = exports.BinaryOperator.BiggerEquals;
  9437. break;
  9438. case '??':
  9439. return this.convertNullishCoalesce(ast, mode);
  9440. default:
  9441. throw new Error("Unsupported operation " + ast.operation);
  9442. }
  9443. return convertToStatementIfNeeded(mode, new BinaryOperatorExpr(op, this._visit(ast.left, _Mode.Expression), this._visit(ast.right, _Mode.Expression), undefined, this.convertSourceSpan(ast.span)));
  9444. };
  9445. _AstToIrVisitor.prototype.visitChain = function (ast, mode) {
  9446. ensureStatementMode(mode, ast);
  9447. return this.visitAll(ast.expressions, mode);
  9448. };
  9449. _AstToIrVisitor.prototype.visitConditional = function (ast, mode) {
  9450. var value = this._visit(ast.condition, _Mode.Expression);
  9451. return convertToStatementIfNeeded(mode, value.conditional(this._visit(ast.trueExp, _Mode.Expression), this._visit(ast.falseExp, _Mode.Expression), this.convertSourceSpan(ast.span)));
  9452. };
  9453. _AstToIrVisitor.prototype.visitPipe = function (ast, mode) {
  9454. throw new Error("Illegal state: Pipes should have been converted into functions. Pipe: " + ast.name);
  9455. };
  9456. _AstToIrVisitor.prototype.visitFunctionCall = function (ast, mode) {
  9457. var convertedArgs = this.visitAll(ast.args, _Mode.Expression);
  9458. var fnResult;
  9459. if (ast instanceof BuiltinFunctionCall) {
  9460. fnResult = ast.converter(convertedArgs);
  9461. }
  9462. else {
  9463. fnResult = this._visit(ast.target, _Mode.Expression)
  9464. .callFn(convertedArgs, this.convertSourceSpan(ast.span));
  9465. }
  9466. return convertToStatementIfNeeded(mode, fnResult);
  9467. };
  9468. _AstToIrVisitor.prototype.visitImplicitReceiver = function (ast, mode) {
  9469. ensureExpressionMode(mode, ast);
  9470. this.usesImplicitReceiver = true;
  9471. return this._implicitReceiver;
  9472. };
  9473. _AstToIrVisitor.prototype.visitThisReceiver = function (ast, mode) {
  9474. return this.visitImplicitReceiver(ast, mode);
  9475. };
  9476. _AstToIrVisitor.prototype.visitInterpolation = function (ast, mode) {
  9477. ensureExpressionMode(mode, ast);
  9478. var args = [literal(ast.expressions.length)];
  9479. for (var i = 0; i < ast.strings.length - 1; i++) {
  9480. args.push(literal(ast.strings[i]));
  9481. args.push(this._visit(ast.expressions[i], _Mode.Expression));
  9482. }
  9483. args.push(literal(ast.strings[ast.strings.length - 1]));
  9484. if (this.interpolationFunction) {
  9485. return this.interpolationFunction(args);
  9486. }
  9487. return ast.expressions.length <= 9 ?
  9488. importExpr(Identifiers$1.inlineInterpolate).callFn(args) :
  9489. importExpr(Identifiers$1.interpolate).callFn([
  9490. args[0], literalArr(args.slice(1), undefined, this.convertSourceSpan(ast.span))
  9491. ]);
  9492. };
  9493. _AstToIrVisitor.prototype.visitKeyedRead = function (ast, mode) {
  9494. var leftMostSafe = this.leftMostSafeNode(ast);
  9495. if (leftMostSafe) {
  9496. return this.convertSafeAccess(ast, leftMostSafe, mode);
  9497. }
  9498. else {
  9499. return convertToStatementIfNeeded(mode, this._visit(ast.obj, _Mode.Expression).key(this._visit(ast.key, _Mode.Expression)));
  9500. }
  9501. };
  9502. _AstToIrVisitor.prototype.visitKeyedWrite = function (ast, mode) {
  9503. var obj = this._visit(ast.obj, _Mode.Expression);
  9504. var key = this._visit(ast.key, _Mode.Expression);
  9505. var value = this._visit(ast.value, _Mode.Expression);
  9506. return convertToStatementIfNeeded(mode, obj.key(key).set(value));
  9507. };
  9508. _AstToIrVisitor.prototype.visitLiteralArray = function (ast, mode) {
  9509. throw new Error("Illegal State: literal arrays should have been converted into functions");
  9510. };
  9511. _AstToIrVisitor.prototype.visitLiteralMap = function (ast, mode) {
  9512. throw new Error("Illegal State: literal maps should have been converted into functions");
  9513. };
  9514. _AstToIrVisitor.prototype.visitLiteralPrimitive = function (ast, mode) {
  9515. // For literal values of null, undefined, true, or false allow type interference
  9516. // to infer the type.
  9517. var type = ast.value === null || ast.value === undefined || ast.value === true || ast.value === true ?
  9518. INFERRED_TYPE :
  9519. undefined;
  9520. return convertToStatementIfNeeded(mode, literal(ast.value, type, this.convertSourceSpan(ast.span)));
  9521. };
  9522. _AstToIrVisitor.prototype._getLocal = function (name, receiver) {
  9523. var _a;
  9524. if (((_a = this._localResolver.globals) === null || _a === void 0 ? void 0 : _a.has(name)) && receiver instanceof ThisReceiver) {
  9525. return null;
  9526. }
  9527. return this._localResolver.getLocal(name);
  9528. };
  9529. _AstToIrVisitor.prototype.visitMethodCall = function (ast, mode) {
  9530. if (ast.receiver instanceof ImplicitReceiver &&
  9531. !(ast.receiver instanceof ThisReceiver) && ast.name === '$any') {
  9532. var args = this.visitAll(ast.args, _Mode.Expression);
  9533. if (args.length != 1) {
  9534. throw new Error("Invalid call to $any, expected 1 argument but received " + (args.length || 'none'));
  9535. }
  9536. return args[0].cast(DYNAMIC_TYPE, this.convertSourceSpan(ast.span));
  9537. }
  9538. var leftMostSafe = this.leftMostSafeNode(ast);
  9539. if (leftMostSafe) {
  9540. return this.convertSafeAccess(ast, leftMostSafe, mode);
  9541. }
  9542. else {
  9543. var args = this.visitAll(ast.args, _Mode.Expression);
  9544. var prevUsesImplicitReceiver = this.usesImplicitReceiver;
  9545. var result = null;
  9546. var receiver = this._visit(ast.receiver, _Mode.Expression);
  9547. if (receiver === this._implicitReceiver) {
  9548. var varExpr = this._getLocal(ast.name, ast.receiver);
  9549. if (varExpr) {
  9550. // Restore the previous "usesImplicitReceiver" state since the implicit
  9551. // receiver has been replaced with a resolved local expression.
  9552. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  9553. result = varExpr.callFn(args);
  9554. this.addImplicitReceiverAccess(ast.name);
  9555. }
  9556. }
  9557. if (result == null) {
  9558. result = receiver.callMethod(ast.name, args, this.convertSourceSpan(ast.span));
  9559. }
  9560. return convertToStatementIfNeeded(mode, result);
  9561. }
  9562. };
  9563. _AstToIrVisitor.prototype.visitPrefixNot = function (ast, mode) {
  9564. return convertToStatementIfNeeded(mode, not(this._visit(ast.expression, _Mode.Expression)));
  9565. };
  9566. _AstToIrVisitor.prototype.visitNonNullAssert = function (ast, mode) {
  9567. return convertToStatementIfNeeded(mode, assertNotNull(this._visit(ast.expression, _Mode.Expression)));
  9568. };
  9569. _AstToIrVisitor.prototype.visitPropertyRead = function (ast, mode) {
  9570. var leftMostSafe = this.leftMostSafeNode(ast);
  9571. if (leftMostSafe) {
  9572. return this.convertSafeAccess(ast, leftMostSafe, mode);
  9573. }
  9574. else {
  9575. var result = null;
  9576. var prevUsesImplicitReceiver = this.usesImplicitReceiver;
  9577. var receiver = this._visit(ast.receiver, _Mode.Expression);
  9578. if (receiver === this._implicitReceiver) {
  9579. result = this._getLocal(ast.name, ast.receiver);
  9580. if (result) {
  9581. // Restore the previous "usesImplicitReceiver" state since the implicit
  9582. // receiver has been replaced with a resolved local expression.
  9583. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  9584. this.addImplicitReceiverAccess(ast.name);
  9585. }
  9586. }
  9587. if (result == null) {
  9588. result = receiver.prop(ast.name);
  9589. }
  9590. return convertToStatementIfNeeded(mode, result);
  9591. }
  9592. };
  9593. _AstToIrVisitor.prototype.visitPropertyWrite = function (ast, mode) {
  9594. var receiver = this._visit(ast.receiver, _Mode.Expression);
  9595. var prevUsesImplicitReceiver = this.usesImplicitReceiver;
  9596. var varExpr = null;
  9597. if (receiver === this._implicitReceiver) {
  9598. var localExpr = this._getLocal(ast.name, ast.receiver);
  9599. if (localExpr) {
  9600. if (localExpr instanceof ReadPropExpr) {
  9601. // If the local variable is a property read expression, it's a reference
  9602. // to a 'context.property' value and will be used as the target of the
  9603. // write expression.
  9604. varExpr = localExpr;
  9605. // Restore the previous "usesImplicitReceiver" state since the implicit
  9606. // receiver has been replaced with a resolved local expression.
  9607. this.usesImplicitReceiver = prevUsesImplicitReceiver;
  9608. this.addImplicitReceiverAccess(ast.name);
  9609. }
  9610. else {
  9611. // Otherwise it's an error.
  9612. var receiver_1 = ast.name;
  9613. var value = (ast.value instanceof PropertyRead) ? ast.value.name : undefined;
  9614. throw new Error("Cannot assign value \"" + value + "\" to template variable \"" + receiver_1 + "\". Template variables are read-only.");
  9615. }
  9616. }
  9617. }
  9618. // If no local expression could be produced, use the original receiver's
  9619. // property as the target.
  9620. if (varExpr === null) {
  9621. varExpr = receiver.prop(ast.name);
  9622. }
  9623. return convertToStatementIfNeeded(mode, varExpr.set(this._visit(ast.value, _Mode.Expression)));
  9624. };
  9625. _AstToIrVisitor.prototype.visitSafePropertyRead = function (ast, mode) {
  9626. return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
  9627. };
  9628. _AstToIrVisitor.prototype.visitSafeMethodCall = function (ast, mode) {
  9629. return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
  9630. };
  9631. _AstToIrVisitor.prototype.visitAll = function (asts, mode) {
  9632. var _this = this;
  9633. return asts.map(function (ast) { return _this._visit(ast, mode); });
  9634. };
  9635. _AstToIrVisitor.prototype.visitQuote = function (ast, mode) {
  9636. throw new Error("Quotes are not supported for evaluation!\n Statement: " + ast.uninterpretedExpression + " located at " + ast.location);
  9637. };
  9638. _AstToIrVisitor.prototype._visit = function (ast, mode) {
  9639. var result = this._resultMap.get(ast);
  9640. if (result)
  9641. return result;
  9642. return (this._nodeMap.get(ast) || ast).visit(this, mode);
  9643. };
  9644. _AstToIrVisitor.prototype.convertSafeAccess = function (ast, leftMostSafe, mode) {
  9645. // If the expression contains a safe access node on the left it needs to be converted to
  9646. // an expression that guards the access to the member by checking the receiver for blank. As
  9647. // execution proceeds from left to right, the left most part of the expression must be guarded
  9648. // first but, because member access is left associative, the right side of the expression is at
  9649. // the top of the AST. The desired result requires lifting a copy of the left part of the
  9650. // expression up to test it for blank before generating the unguarded version.
  9651. // Consider, for example the following expression: a?.b.c?.d.e
  9652. // This results in the ast:
  9653. // .
  9654. // / \
  9655. // ?. e
  9656. // / \
  9657. // . d
  9658. // / \
  9659. // ?. c
  9660. // / \
  9661. // a b
  9662. // The following tree should be generated:
  9663. //
  9664. // /---- ? ----\
  9665. // / | \
  9666. // a /--- ? ---\ null
  9667. // / | \
  9668. // . . null
  9669. // / \ / \
  9670. // . c . e
  9671. // / \ / \
  9672. // a b . d
  9673. // / \
  9674. // . c
  9675. // / \
  9676. // a b
  9677. //
  9678. // Notice that the first guard condition is the left hand of the left most safe access node
  9679. // which comes in as leftMostSafe to this routine.
  9680. var guardedExpression = this._visit(leftMostSafe.receiver, _Mode.Expression);
  9681. var temporary = undefined;
  9682. if (this.needsTemporaryInSafeAccess(leftMostSafe.receiver)) {
  9683. // If the expression has method calls or pipes then we need to save the result into a
  9684. // temporary variable to avoid calling stateful or impure code more than once.
  9685. temporary = this.allocateTemporary();
  9686. // Preserve the result in the temporary variable
  9687. guardedExpression = temporary.set(guardedExpression);
  9688. // Ensure all further references to the guarded expression refer to the temporary instead.
  9689. this._resultMap.set(leftMostSafe.receiver, temporary);
  9690. }
  9691. var condition = guardedExpression.isBlank();
  9692. // Convert the ast to an unguarded access to the receiver's member. The map will substitute
  9693. // leftMostNode with its unguarded version in the call to `this.visit()`.
  9694. if (leftMostSafe instanceof SafeMethodCall) {
  9695. this._nodeMap.set(leftMostSafe, new MethodCall(leftMostSafe.span, leftMostSafe.sourceSpan, leftMostSafe.nameSpan, leftMostSafe.receiver, leftMostSafe.name, leftMostSafe.args, leftMostSafe.argumentSpan));
  9696. }
  9697. else {
  9698. this._nodeMap.set(leftMostSafe, new PropertyRead(leftMostSafe.span, leftMostSafe.sourceSpan, leftMostSafe.nameSpan, leftMostSafe.receiver, leftMostSafe.name));
  9699. }
  9700. // Recursively convert the node now without the guarded member access.
  9701. var access = this._visit(ast, _Mode.Expression);
  9702. // Remove the mapping. This is not strictly required as the converter only traverses each node
  9703. // once but is safer if the conversion is changed to traverse the nodes more than once.
  9704. this._nodeMap.delete(leftMostSafe);
  9705. // If we allocated a temporary, release it.
  9706. if (temporary) {
  9707. this.releaseTemporary(temporary);
  9708. }
  9709. // Produce the conditional
  9710. return convertToStatementIfNeeded(mode, condition.conditional(NULL_EXPR, access));
  9711. };
  9712. _AstToIrVisitor.prototype.convertNullishCoalesce = function (ast, mode) {
  9713. var left = this._visit(ast.left, _Mode.Expression);
  9714. var right = this._visit(ast.right, _Mode.Expression);
  9715. var temporary = this.allocateTemporary();
  9716. this.releaseTemporary(temporary);
  9717. // Generate the following expression. It is identical to how TS
  9718. // transpiles binary expressions with a nullish coalescing operator.
  9719. // let temp;
  9720. // (temp = a) !== null && temp !== undefined ? temp : b;
  9721. return convertToStatementIfNeeded(mode, temporary.set(left)
  9722. .notIdentical(NULL_EXPR)
  9723. .and(temporary.notIdentical(literal(undefined)))
  9724. .conditional(temporary, right));
  9725. };
  9726. // Given an expression of the form a?.b.c?.d.e then the left most safe node is
  9727. // the (a?.b). The . and ?. are left associative thus can be rewritten as:
  9728. // ((((a?.c).b).c)?.d).e. This returns the most deeply nested safe read or
  9729. // safe method call as this needs to be transformed initially to:
  9730. // a == null ? null : a.c.b.c?.d.e
  9731. // then to:
  9732. // a == null ? null : a.b.c == null ? null : a.b.c.d.e
  9733. _AstToIrVisitor.prototype.leftMostSafeNode = function (ast) {
  9734. var _this = this;
  9735. var visit = function (visitor, ast) {
  9736. return (_this._nodeMap.get(ast) || ast).visit(visitor);
  9737. };
  9738. return ast.visit({
  9739. visitUnary: function (ast) {
  9740. return null;
  9741. },
  9742. visitBinary: function (ast) {
  9743. return null;
  9744. },
  9745. visitChain: function (ast) {
  9746. return null;
  9747. },
  9748. visitConditional: function (ast) {
  9749. return null;
  9750. },
  9751. visitFunctionCall: function (ast) {
  9752. return null;
  9753. },
  9754. visitImplicitReceiver: function (ast) {
  9755. return null;
  9756. },
  9757. visitThisReceiver: function (ast) {
  9758. return null;
  9759. },
  9760. visitInterpolation: function (ast) {
  9761. return null;
  9762. },
  9763. visitKeyedRead: function (ast) {
  9764. return visit(this, ast.obj);
  9765. },
  9766. visitKeyedWrite: function (ast) {
  9767. return null;
  9768. },
  9769. visitLiteralArray: function (ast) {
  9770. return null;
  9771. },
  9772. visitLiteralMap: function (ast) {
  9773. return null;
  9774. },
  9775. visitLiteralPrimitive: function (ast) {
  9776. return null;
  9777. },
  9778. visitMethodCall: function (ast) {
  9779. return visit(this, ast.receiver);
  9780. },
  9781. visitPipe: function (ast) {
  9782. return null;
  9783. },
  9784. visitPrefixNot: function (ast) {
  9785. return null;
  9786. },
  9787. visitNonNullAssert: function (ast) {
  9788. return null;
  9789. },
  9790. visitPropertyRead: function (ast) {
  9791. return visit(this, ast.receiver);
  9792. },
  9793. visitPropertyWrite: function (ast) {
  9794. return null;
  9795. },
  9796. visitQuote: function (ast) {
  9797. return null;
  9798. },
  9799. visitSafeMethodCall: function (ast) {
  9800. return visit(this, ast.receiver) || ast;
  9801. },
  9802. visitSafePropertyRead: function (ast) {
  9803. return visit(this, ast.receiver) || ast;
  9804. }
  9805. });
  9806. };
  9807. // Returns true of the AST includes a method or a pipe indicating that, if the
  9808. // expression is used as the target of a safe property or method access then
  9809. // the expression should be stored into a temporary variable.
  9810. _AstToIrVisitor.prototype.needsTemporaryInSafeAccess = function (ast) {
  9811. var _this = this;
  9812. var visit = function (visitor, ast) {
  9813. return ast && (_this._nodeMap.get(ast) || ast).visit(visitor);
  9814. };
  9815. var visitSome = function (visitor, ast) {
  9816. return ast.some(function (ast) { return visit(visitor, ast); });
  9817. };
  9818. return ast.visit({
  9819. visitUnary: function (ast) {
  9820. return visit(this, ast.expr);
  9821. },
  9822. visitBinary: function (ast) {
  9823. return visit(this, ast.left) || visit(this, ast.right);
  9824. },
  9825. visitChain: function (ast) {
  9826. return false;
  9827. },
  9828. visitConditional: function (ast) {
  9829. return visit(this, ast.condition) || visit(this, ast.trueExp) || visit(this, ast.falseExp);
  9830. },
  9831. visitFunctionCall: function (ast) {
  9832. return true;
  9833. },
  9834. visitImplicitReceiver: function (ast) {
  9835. return false;
  9836. },
  9837. visitThisReceiver: function (ast) {
  9838. return false;
  9839. },
  9840. visitInterpolation: function (ast) {
  9841. return visitSome(this, ast.expressions);
  9842. },
  9843. visitKeyedRead: function (ast) {
  9844. return false;
  9845. },
  9846. visitKeyedWrite: function (ast) {
  9847. return false;
  9848. },
  9849. visitLiteralArray: function (ast) {
  9850. return true;
  9851. },
  9852. visitLiteralMap: function (ast) {
  9853. return true;
  9854. },
  9855. visitLiteralPrimitive: function (ast) {
  9856. return false;
  9857. },
  9858. visitMethodCall: function (ast) {
  9859. return true;
  9860. },
  9861. visitPipe: function (ast) {
  9862. return true;
  9863. },
  9864. visitPrefixNot: function (ast) {
  9865. return visit(this, ast.expression);
  9866. },
  9867. visitNonNullAssert: function (ast) {
  9868. return visit(this, ast.expression);
  9869. },
  9870. visitPropertyRead: function (ast) {
  9871. return false;
  9872. },
  9873. visitPropertyWrite: function (ast) {
  9874. return false;
  9875. },
  9876. visitQuote: function (ast) {
  9877. return false;
  9878. },
  9879. visitSafeMethodCall: function (ast) {
  9880. return true;
  9881. },
  9882. visitSafePropertyRead: function (ast) {
  9883. return false;
  9884. }
  9885. });
  9886. };
  9887. _AstToIrVisitor.prototype.allocateTemporary = function () {
  9888. var tempNumber = this._currentTemporary++;
  9889. this.temporaryCount = Math.max(this._currentTemporary, this.temporaryCount);
  9890. return new ReadVarExpr(temporaryName(this.bindingId, tempNumber));
  9891. };
  9892. _AstToIrVisitor.prototype.releaseTemporary = function (temporary) {
  9893. this._currentTemporary--;
  9894. if (temporary.name != temporaryName(this.bindingId, this._currentTemporary)) {
  9895. throw new Error("Temporary " + temporary.name + " released out of order");
  9896. }
  9897. };
  9898. /**
  9899. * Creates an absolute `ParseSourceSpan` from the relative `ParseSpan`.
  9900. *
  9901. * `ParseSpan` objects are relative to the start of the expression.
  9902. * This method converts these to full `ParseSourceSpan` objects that
  9903. * show where the span is within the overall source file.
  9904. *
  9905. * @param span the relative span to convert.
  9906. * @returns a `ParseSourceSpan` for the given span or null if no
  9907. * `baseSourceSpan` was provided to this class.
  9908. */
  9909. _AstToIrVisitor.prototype.convertSourceSpan = function (span) {
  9910. if (this.baseSourceSpan) {
  9911. var start = this.baseSourceSpan.start.moveBy(span.start);
  9912. var end = this.baseSourceSpan.start.moveBy(span.end);
  9913. var fullStart = this.baseSourceSpan.fullStart.moveBy(span.start);
  9914. return new ParseSourceSpan(start, end, fullStart);
  9915. }
  9916. else {
  9917. return null;
  9918. }
  9919. };
  9920. /** Adds the name of an AST to the list of implicit receiver accesses. */
  9921. _AstToIrVisitor.prototype.addImplicitReceiverAccess = function (name) {
  9922. if (this.implicitReceiverAccesses) {
  9923. this.implicitReceiverAccesses.add(name);
  9924. }
  9925. };
  9926. return _AstToIrVisitor;
  9927. }());
  9928. function flattenStatements(arg, output) {
  9929. if (Array.isArray(arg)) {
  9930. arg.forEach(function (entry) { return flattenStatements(entry, output); });
  9931. }
  9932. else {
  9933. output.push(arg);
  9934. }
  9935. }
  9936. var DefaultLocalResolver = /** @class */ (function () {
  9937. function DefaultLocalResolver(globals) {
  9938. this.globals = globals;
  9939. }
  9940. DefaultLocalResolver.prototype.notifyImplicitReceiverUse = function () { };
  9941. DefaultLocalResolver.prototype.getLocal = function (name) {
  9942. if (name === EventHandlerVars.event.name) {
  9943. return EventHandlerVars.event;
  9944. }
  9945. return null;
  9946. };
  9947. return DefaultLocalResolver;
  9948. }());
  9949. function createCurrValueExpr(bindingId) {
  9950. return variable("currVal_" + bindingId); // fix syntax highlighting: `
  9951. }
  9952. function createPreventDefaultVar(bindingId) {
  9953. return variable("pd_" + bindingId);
  9954. }
  9955. function convertStmtIntoExpression(stmt) {
  9956. if (stmt instanceof ExpressionStatement) {
  9957. return stmt.expr;
  9958. }
  9959. else if (stmt instanceof ReturnStatement) {
  9960. return stmt.value;
  9961. }
  9962. return null;
  9963. }
  9964. var BuiltinFunctionCall = /** @class */ (function (_super) {
  9965. __extends(BuiltinFunctionCall, _super);
  9966. function BuiltinFunctionCall(span, sourceSpan, args, converter) {
  9967. var _this = _super.call(this, span, sourceSpan, null, args) || this;
  9968. _this.args = args;
  9969. _this.converter = converter;
  9970. return _this;
  9971. }
  9972. return BuiltinFunctionCall;
  9973. }(FunctionCall));
  9974. /**
  9975. * @license
  9976. * Copyright Google LLC All Rights Reserved.
  9977. *
  9978. * Use of this source code is governed by an MIT-style license that can be
  9979. * found in the LICENSE file at https://angular.io/license
  9980. */
  9981. /**
  9982. * This file is a port of shadowCSS from webcomponents.js to TypeScript.
  9983. *
  9984. * Please make sure to keep to edits in sync with the source file.
  9985. *
  9986. * Source:
  9987. * https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js
  9988. *
  9989. * The original file level comment is reproduced below
  9990. */
  9991. /*
  9992. This is a limited shim for ShadowDOM css styling.
  9993. https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#styles
  9994. The intention here is to support only the styling features which can be
  9995. relatively simply implemented. The goal is to allow users to avoid the
  9996. most obvious pitfalls and do so without compromising performance significantly.
  9997. For ShadowDOM styling that's not covered here, a set of best practices
  9998. can be provided that should allow users to accomplish more complex styling.
  9999. The following is a list of specific ShadowDOM styling features and a brief
  10000. discussion of the approach used to shim.
  10001. Shimmed features:
  10002. * :host, :host-context: ShadowDOM allows styling of the shadowRoot's host
  10003. element using the :host rule. To shim this feature, the :host styles are
  10004. reformatted and prefixed with a given scope name and promoted to a
  10005. document level stylesheet.
  10006. For example, given a scope name of .foo, a rule like this:
  10007. :host {
  10008. background: red;
  10009. }
  10010. }
  10011. becomes:
  10012. .foo {
  10013. background: red;
  10014. }
  10015. * encapsulation: Styles defined within ShadowDOM, apply only to
  10016. dom inside the ShadowDOM. Polymer uses one of two techniques to implement
  10017. this feature.
  10018. By default, rules are prefixed with the host element tag name
  10019. as a descendant selector. This ensures styling does not leak out of the 'top'
  10020. of the element's ShadowDOM. For example,
  10021. div {
  10022. font-weight: bold;
  10023. }
  10024. becomes:
  10025. x-foo div {
  10026. font-weight: bold;
  10027. }
  10028. becomes:
  10029. Alternatively, if WebComponents.ShadowCSS.strictStyling is set to true then
  10030. selectors are scoped by adding an attribute selector suffix to each
  10031. simple selector that contains the host element tag name. Each element
  10032. in the element's ShadowDOM template is also given the scope attribute.
  10033. Thus, these rules match only elements that have the scope attribute.
  10034. For example, given a scope name of x-foo, a rule like this:
  10035. div {
  10036. font-weight: bold;
  10037. }
  10038. becomes:
  10039. div[x-foo] {
  10040. font-weight: bold;
  10041. }
  10042. Note that elements that are dynamically added to a scope must have the scope
  10043. selector added to them manually.
  10044. * upper/lower bound encapsulation: Styles which are defined outside a
  10045. shadowRoot should not cross the ShadowDOM boundary and should not apply
  10046. inside a shadowRoot.
  10047. This styling behavior is not emulated. Some possible ways to do this that
  10048. were rejected due to complexity and/or performance concerns include: (1) reset
  10049. every possible property for every possible selector for a given scope name;
  10050. (2) re-implement css in javascript.
  10051. As an alternative, users should make sure to use selectors
  10052. specific to the scope in which they are working.
  10053. * ::distributed: This behavior is not emulated. It's often not necessary
  10054. to style the contents of a specific insertion point and instead, descendants
  10055. of the host element can be styled selectively. Users can also create an
  10056. extra node around an insertion point and style that node's contents
  10057. via descendent selectors. For example, with a shadowRoot like this:
  10058. <style>
  10059. ::content(div) {
  10060. background: red;
  10061. }
  10062. </style>
  10063. <content></content>
  10064. could become:
  10065. <style>
  10066. / *@polyfill .content-container div * /
  10067. ::content(div) {
  10068. background: red;
  10069. }
  10070. </style>
  10071. <div class="content-container">
  10072. <content></content>
  10073. </div>
  10074. Note the use of @polyfill in the comment above a ShadowDOM specific style
  10075. declaration. This is a directive to the styling shim to use the selector
  10076. in comments in lieu of the next selector when running under polyfill.
  10077. */
  10078. var ShadowCss = /** @class */ (function () {
  10079. function ShadowCss() {
  10080. this.strictStyling = true;
  10081. }
  10082. /*
  10083. * Shim some cssText with the given selector. Returns cssText that can
  10084. * be included in the document via WebComponents.ShadowCSS.addCssToDocument(css).
  10085. *
  10086. * When strictStyling is true:
  10087. * - selector is the attribute added to all elements inside the host,
  10088. * - hostSelector is the attribute added to the host itself.
  10089. */
  10090. ShadowCss.prototype.shimCssText = function (cssText, selector, hostSelector) {
  10091. if (hostSelector === void 0) { hostSelector = ''; }
  10092. var commentsWithHash = extractCommentsWithHash(cssText);
  10093. cssText = stripComments(cssText);
  10094. cssText = this._insertDirectives(cssText);
  10095. var scopedCssText = this._scopeCssText(cssText, selector, hostSelector);
  10096. return __spreadArray([scopedCssText], __read(commentsWithHash)).join('\n');
  10097. };
  10098. ShadowCss.prototype._insertDirectives = function (cssText) {
  10099. cssText = this._insertPolyfillDirectivesInCssText(cssText);
  10100. return this._insertPolyfillRulesInCssText(cssText);
  10101. };
  10102. /*
  10103. * Process styles to convert native ShadowDOM rules that will trip
  10104. * up the css parser; we rely on decorating the stylesheet with inert rules.
  10105. *
  10106. * For example, we convert this rule:
  10107. *
  10108. * polyfill-next-selector { content: ':host menu-item'; }
  10109. * ::content menu-item {
  10110. *
  10111. * to this:
  10112. *
  10113. * scopeName menu-item {
  10114. *
  10115. **/
  10116. ShadowCss.prototype._insertPolyfillDirectivesInCssText = function (cssText) {
  10117. // Difference with webcomponents.js: does not handle comments
  10118. return cssText.replace(_cssContentNextSelectorRe, function () {
  10119. var m = [];
  10120. for (var _i = 0; _i < arguments.length; _i++) {
  10121. m[_i] = arguments[_i];
  10122. }
  10123. return m[2] + '{';
  10124. });
  10125. };
  10126. /*
  10127. * Process styles to add rules which will only apply under the polyfill
  10128. *
  10129. * For example, we convert this rule:
  10130. *
  10131. * polyfill-rule {
  10132. * content: ':host menu-item';
  10133. * ...
  10134. * }
  10135. *
  10136. * to this:
  10137. *
  10138. * scopeName menu-item {...}
  10139. *
  10140. **/
  10141. ShadowCss.prototype._insertPolyfillRulesInCssText = function (cssText) {
  10142. // Difference with webcomponents.js: does not handle comments
  10143. return cssText.replace(_cssContentRuleRe, function () {
  10144. var m = [];
  10145. for (var _i = 0; _i < arguments.length; _i++) {
  10146. m[_i] = arguments[_i];
  10147. }
  10148. var rule = m[0].replace(m[1], '').replace(m[2], '');
  10149. return m[4] + rule;
  10150. });
  10151. };
  10152. /* Ensure styles are scoped. Pseudo-scoping takes a rule like:
  10153. *
  10154. * .foo {... }
  10155. *
  10156. * and converts this to
  10157. *
  10158. * scopeName .foo { ... }
  10159. */
  10160. ShadowCss.prototype._scopeCssText = function (cssText, scopeSelector, hostSelector) {
  10161. var unscopedRules = this._extractUnscopedRulesFromCssText(cssText);
  10162. // replace :host and :host-context -shadowcsshost and -shadowcsshost respectively
  10163. cssText = this._insertPolyfillHostInCssText(cssText);
  10164. cssText = this._convertColonHost(cssText);
  10165. cssText = this._convertColonHostContext(cssText);
  10166. cssText = this._convertShadowDOMSelectors(cssText);
  10167. if (scopeSelector) {
  10168. cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector);
  10169. }
  10170. cssText = cssText + '\n' + unscopedRules;
  10171. return cssText.trim();
  10172. };
  10173. /*
  10174. * Process styles to add rules which will only apply under the polyfill
  10175. * and do not process via CSSOM. (CSSOM is destructive to rules on rare
  10176. * occasions, e.g. -webkit-calc on Safari.)
  10177. * For example, we convert this rule:
  10178. *
  10179. * @polyfill-unscoped-rule {
  10180. * content: 'menu-item';
  10181. * ... }
  10182. *
  10183. * to this:
  10184. *
  10185. * menu-item {...}
  10186. *
  10187. **/
  10188. ShadowCss.prototype._extractUnscopedRulesFromCssText = function (cssText) {
  10189. // Difference with webcomponents.js: does not handle comments
  10190. var r = '';
  10191. var m;
  10192. _cssContentUnscopedRuleRe.lastIndex = 0;
  10193. while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) {
  10194. var rule = m[0].replace(m[2], '').replace(m[1], m[4]);
  10195. r += rule + '\n\n';
  10196. }
  10197. return r;
  10198. };
  10199. /*
  10200. * convert a rule like :host(.foo) > .bar { }
  10201. *
  10202. * to
  10203. *
  10204. * .foo<scopeName> > .bar
  10205. */
  10206. ShadowCss.prototype._convertColonHost = function (cssText) {
  10207. return cssText.replace(_cssColonHostRe, function (_, hostSelectors, otherSelectors) {
  10208. var e_1, _b;
  10209. if (hostSelectors) {
  10210. var convertedSelectors = [];
  10211. var hostSelectorArray = hostSelectors.split(',').map(function (p) { return p.trim(); });
  10212. try {
  10213. for (var hostSelectorArray_1 = __values(hostSelectorArray), hostSelectorArray_1_1 = hostSelectorArray_1.next(); !hostSelectorArray_1_1.done; hostSelectorArray_1_1 = hostSelectorArray_1.next()) {
  10214. var hostSelector = hostSelectorArray_1_1.value;
  10215. if (!hostSelector)
  10216. break;
  10217. var convertedSelector = _polyfillHostNoCombinator + hostSelector.replace(_polyfillHost, '') + otherSelectors;
  10218. convertedSelectors.push(convertedSelector);
  10219. }
  10220. }
  10221. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  10222. finally {
  10223. try {
  10224. if (hostSelectorArray_1_1 && !hostSelectorArray_1_1.done && (_b = hostSelectorArray_1.return)) _b.call(hostSelectorArray_1);
  10225. }
  10226. finally { if (e_1) throw e_1.error; }
  10227. }
  10228. return convertedSelectors.join(',');
  10229. }
  10230. else {
  10231. return _polyfillHostNoCombinator + otherSelectors;
  10232. }
  10233. });
  10234. };
  10235. /*
  10236. * convert a rule like :host-context(.foo) > .bar { }
  10237. *
  10238. * to
  10239. *
  10240. * .foo<scopeName> > .bar, .foo <scopeName> > .bar { }
  10241. *
  10242. * and
  10243. *
  10244. * :host-context(.foo:host) .bar { ... }
  10245. *
  10246. * to
  10247. *
  10248. * .foo<scopeName> .bar { ... }
  10249. */
  10250. ShadowCss.prototype._convertColonHostContext = function (cssText) {
  10251. return cssText.replace(_cssColonHostContextReGlobal, function (selectorText) {
  10252. // We have captured a selector that contains a `:host-context` rule.
  10253. var _a;
  10254. // For backward compatibility `:host-context` may contain a comma separated list of selectors.
  10255. // Each context selector group will contain a list of host-context selectors that must match
  10256. // an ancestor of the host.
  10257. // (Normally `contextSelectorGroups` will only contain a single array of context selectors.)
  10258. var contextSelectorGroups = [[]];
  10259. // There may be more than `:host-context` in this selector so `selectorText` could look like:
  10260. // `:host-context(.one):host-context(.two)`.
  10261. // Execute `_cssColonHostContextRe` over and over until we have extracted all the
  10262. // `:host-context` selectors from this selector.
  10263. var match;
  10264. while (match = _cssColonHostContextRe.exec(selectorText)) {
  10265. // `match` = [':host-context(<selectors>)<rest>', <selectors>, <rest>]
  10266. // The `<selectors>` could actually be a comma separated list: `:host-context(.one, .two)`.
  10267. var newContextSelectors = ((_a = match[1]) !== null && _a !== void 0 ? _a : '').trim().split(',').map(function (m) { return m.trim(); }).filter(function (m) { return m !== ''; });
  10268. // We must duplicate the current selector group for each of these new selectors.
  10269. // For example if the current groups are:
  10270. // ```
  10271. // [
  10272. // ['a', 'b', 'c'],
  10273. // ['x', 'y', 'z'],
  10274. // ]
  10275. // ```
  10276. // And we have a new set of comma separated selectors: `:host-context(m,n)` then the new
  10277. // groups are:
  10278. // ```
  10279. // [
  10280. // ['a', 'b', 'c', 'm'],
  10281. // ['x', 'y', 'z', 'm'],
  10282. // ['a', 'b', 'c', 'n'],
  10283. // ['x', 'y', 'z', 'n'],
  10284. // ]
  10285. // ```
  10286. var contextSelectorGroupsLength = contextSelectorGroups.length;
  10287. repeatGroups(contextSelectorGroups, newContextSelectors.length);
  10288. for (var i = 0; i < newContextSelectors.length; i++) {
  10289. for (var j = 0; j < contextSelectorGroupsLength; j++) {
  10290. contextSelectorGroups[j + (i * contextSelectorGroupsLength)].push(newContextSelectors[i]);
  10291. }
  10292. }
  10293. // Update the `selectorText` and see repeat to see if there are more `:host-context`s.
  10294. selectorText = match[2];
  10295. }
  10296. // The context selectors now must be combined with each other to capture all the possible
  10297. // selectors that `:host-context` can match. See `combineHostContextSelectors()` for more
  10298. // info about how this is done.
  10299. return contextSelectorGroups
  10300. .map(function (contextSelectors) { return combineHostContextSelectors(contextSelectors, selectorText); })
  10301. .join(', ');
  10302. });
  10303. };
  10304. /*
  10305. * Convert combinators like ::shadow and pseudo-elements like ::content
  10306. * by replacing with space.
  10307. */
  10308. ShadowCss.prototype._convertShadowDOMSelectors = function (cssText) {
  10309. return _shadowDOMSelectorsRe.reduce(function (result, pattern) { return result.replace(pattern, ' '); }, cssText);
  10310. };
  10311. // change a selector like 'div' to 'name div'
  10312. ShadowCss.prototype._scopeSelectors = function (cssText, scopeSelector, hostSelector) {
  10313. var _this = this;
  10314. return processRules(cssText, function (rule) {
  10315. var selector = rule.selector;
  10316. var content = rule.content;
  10317. if (rule.selector[0] !== '@') {
  10318. selector =
  10319. _this._scopeSelector(rule.selector, scopeSelector, hostSelector, _this.strictStyling);
  10320. }
  10321. else if (rule.selector.startsWith('@media') || rule.selector.startsWith('@supports') ||
  10322. rule.selector.startsWith('@document')) {
  10323. content = _this._scopeSelectors(rule.content, scopeSelector, hostSelector);
  10324. }
  10325. else if (rule.selector.startsWith('@font-face') || rule.selector.startsWith('@page')) {
  10326. content = _this._stripScopingSelectors(rule.content);
  10327. }
  10328. return new CssRule(selector, content);
  10329. });
  10330. };
  10331. /**
  10332. * Handle a css text that is within a rule that should not contain scope selectors by simply
  10333. * removing them! An example of such a rule is `@font-face`.
  10334. *
  10335. * `@font-face` rules cannot contain nested selectors. Nor can they be nested under a selector.
  10336. * Normally this would be a syntax error by the author of the styles. But in some rare cases, such
  10337. * as importing styles from a library, and applying `:host ::ng-deep` to the imported styles, we
  10338. * can end up with broken css if the imported styles happen to contain @font-face rules.
  10339. *
  10340. * For example:
  10341. *
  10342. * ```
  10343. * :host ::ng-deep {
  10344. * import 'some/lib/containing/font-face';
  10345. * }
  10346. *
  10347. * Similar logic applies to `@page` rules which can contain a particular set of properties,
  10348. * as well as some specific at-rules. Since they can't be encapsulated, we have to strip
  10349. * any scoping selectors from them. For more information: https://www.w3.org/TR/css-page-3
  10350. * ```
  10351. */
  10352. ShadowCss.prototype._stripScopingSelectors = function (cssText) {
  10353. return processRules(cssText, function (rule) {
  10354. var selector = rule.selector.replace(_shadowDeepSelectors, ' ')
  10355. .replace(_polyfillHostNoCombinatorRe, ' ');
  10356. return new CssRule(selector, rule.content);
  10357. });
  10358. };
  10359. ShadowCss.prototype._scopeSelector = function (selector, scopeSelector, hostSelector, strict) {
  10360. var _this = this;
  10361. return selector.split(',')
  10362. .map(function (part) { return part.trim().split(_shadowDeepSelectors); })
  10363. .map(function (deepParts) {
  10364. var _b = __read(deepParts), shallowPart = _b[0], otherParts = _b.slice(1);
  10365. var applyScope = function (shallowPart) {
  10366. if (_this._selectorNeedsScoping(shallowPart, scopeSelector)) {
  10367. return strict ?
  10368. _this._applyStrictSelectorScope(shallowPart, scopeSelector, hostSelector) :
  10369. _this._applySelectorScope(shallowPart, scopeSelector, hostSelector);
  10370. }
  10371. else {
  10372. return shallowPart;
  10373. }
  10374. };
  10375. return __spreadArray([applyScope(shallowPart)], __read(otherParts)).join(' ');
  10376. })
  10377. .join(', ');
  10378. };
  10379. ShadowCss.prototype._selectorNeedsScoping = function (selector, scopeSelector) {
  10380. var re = this._makeScopeMatcher(scopeSelector);
  10381. return !re.test(selector);
  10382. };
  10383. ShadowCss.prototype._makeScopeMatcher = function (scopeSelector) {
  10384. var lre = /\[/g;
  10385. var rre = /\]/g;
  10386. scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]');
  10387. return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
  10388. };
  10389. ShadowCss.prototype._applySelectorScope = function (selector, scopeSelector, hostSelector) {
  10390. // Difference from webcomponents.js: scopeSelector could not be an array
  10391. return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector);
  10392. };
  10393. // scope via name and [is=name]
  10394. ShadowCss.prototype._applySimpleSelectorScope = function (selector, scopeSelector, hostSelector) {
  10395. // In Android browser, the lastIndex is not reset when the regex is used in String.replace()
  10396. _polyfillHostRe.lastIndex = 0;
  10397. if (_polyfillHostRe.test(selector)) {
  10398. var replaceBy_1 = this.strictStyling ? "[" + hostSelector + "]" : scopeSelector;
  10399. return selector
  10400. .replace(_polyfillHostNoCombinatorRe, function (hnc, selector) {
  10401. return selector.replace(/([^:]*)(:*)(.*)/, function (_, before, colon, after) {
  10402. return before + replaceBy_1 + colon + after;
  10403. });
  10404. })
  10405. .replace(_polyfillHostRe, replaceBy_1 + ' ');
  10406. }
  10407. return scopeSelector + ' ' + selector;
  10408. };
  10409. // return a selector with [name] suffix on each simple selector
  10410. // e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */
  10411. ShadowCss.prototype._applyStrictSelectorScope = function (selector, scopeSelector, hostSelector) {
  10412. var _this = this;
  10413. var isRe = /\[is=([^\]]*)\]/g;
  10414. scopeSelector = scopeSelector.replace(isRe, function (_) {
  10415. var parts = [];
  10416. for (var _i = 1; _i < arguments.length; _i++) {
  10417. parts[_i - 1] = arguments[_i];
  10418. }
  10419. return parts[0];
  10420. });
  10421. var attrName = '[' + scopeSelector + ']';
  10422. var _scopeSelectorPart = function (p) {
  10423. var scopedP = p.trim();
  10424. if (!scopedP) {
  10425. return '';
  10426. }
  10427. if (p.indexOf(_polyfillHostNoCombinator) > -1) {
  10428. scopedP = _this._applySimpleSelectorScope(p, scopeSelector, hostSelector);
  10429. }
  10430. else {
  10431. // remove :host since it should be unnecessary
  10432. var t = p.replace(_polyfillHostRe, '');
  10433. if (t.length > 0) {
  10434. var matches = t.match(/([^:]*)(:*)(.*)/);
  10435. if (matches) {
  10436. scopedP = matches[1] + attrName + matches[2] + matches[3];
  10437. }
  10438. }
  10439. }
  10440. return scopedP;
  10441. };
  10442. var safeContent = new SafeSelector(selector);
  10443. selector = safeContent.content();
  10444. var scopedSelector = '';
  10445. var startIndex = 0;
  10446. var res;
  10447. var sep = /( |>|\+|~(?!=))\s*/g;
  10448. // If a selector appears before :host it should not be shimmed as it
  10449. // matches on ancestor elements and not on elements in the host's shadow
  10450. // `:host-context(div)` is transformed to
  10451. // `-shadowcsshost-no-combinatordiv, div -shadowcsshost-no-combinator`
  10452. // the `div` is not part of the component in the 2nd selectors and should not be scoped.
  10453. // Historically `component-tag:host` was matching the component so we also want to preserve
  10454. // this behavior to avoid breaking legacy apps (it should not match).
  10455. // The behavior should be:
  10456. // - `tag:host` -> `tag[h]` (this is to avoid breaking legacy apps, should not match anything)
  10457. // - `tag :host` -> `tag [h]` (`tag` is not scoped because it's considered part of a
  10458. // `:host-context(tag)`)
  10459. var hasHost = selector.indexOf(_polyfillHostNoCombinator) > -1;
  10460. // Only scope parts after the first `-shadowcsshost-no-combinator` when it is present
  10461. var shouldScope = !hasHost;
  10462. while ((res = sep.exec(selector)) !== null) {
  10463. var separator = res[1];
  10464. var part_1 = selector.slice(startIndex, res.index).trim();
  10465. shouldScope = shouldScope || part_1.indexOf(_polyfillHostNoCombinator) > -1;
  10466. var scopedPart = shouldScope ? _scopeSelectorPart(part_1) : part_1;
  10467. scopedSelector += scopedPart + " " + separator + " ";
  10468. startIndex = sep.lastIndex;
  10469. }
  10470. var part = selector.substring(startIndex);
  10471. shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
  10472. scopedSelector += shouldScope ? _scopeSelectorPart(part) : part;
  10473. // replace the placeholders with their original values
  10474. return safeContent.restore(scopedSelector);
  10475. };
  10476. ShadowCss.prototype._insertPolyfillHostInCssText = function (selector) {
  10477. return selector.replace(_colonHostContextRe, _polyfillHostContext)
  10478. .replace(_colonHostRe, _polyfillHost);
  10479. };
  10480. return ShadowCss;
  10481. }());
  10482. var SafeSelector = /** @class */ (function () {
  10483. function SafeSelector(selector) {
  10484. var _this = this;
  10485. this.placeholders = [];
  10486. this.index = 0;
  10487. // Replaces attribute selectors with placeholders.
  10488. // The WS in [attr="va lue"] would otherwise be interpreted as a selector separator.
  10489. selector = this._escapeRegexMatches(selector, /(\[[^\]]*\])/g);
  10490. // CSS allows for certain special characters to be used in selectors if they're escaped.
  10491. // E.g. `.foo:blue` won't match a class called `foo:blue`, because the colon denotes a
  10492. // pseudo-class, but writing `.foo\:blue` will match, because the colon was escaped.
  10493. // Replace all escape sequences (`\` followed by a character) with a placeholder so
  10494. // that our handling of pseudo-selectors doesn't mess with them.
  10495. selector = this._escapeRegexMatches(selector, /(\\.)/g);
  10496. // Replaces the expression in `:nth-child(2n + 1)` with a placeholder.
  10497. // WS and "+" would otherwise be interpreted as selector separators.
  10498. this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, function (_, pseudo, exp) {
  10499. var replaceBy = "__ph-" + _this.index + "__";
  10500. _this.placeholders.push(exp);
  10501. _this.index++;
  10502. return pseudo + replaceBy;
  10503. });
  10504. }
  10505. SafeSelector.prototype.restore = function (content) {
  10506. var _this = this;
  10507. return content.replace(/__ph-(\d+)__/g, function (_ph, index) { return _this.placeholders[+index]; });
  10508. };
  10509. SafeSelector.prototype.content = function () {
  10510. return this._content;
  10511. };
  10512. /**
  10513. * Replaces all of the substrings that match a regex within a
  10514. * special string (e.g. `__ph-0__`, `__ph-1__`, etc).
  10515. */
  10516. SafeSelector.prototype._escapeRegexMatches = function (content, pattern) {
  10517. var _this = this;
  10518. return content.replace(pattern, function (_, keep) {
  10519. var replaceBy = "__ph-" + _this.index + "__";
  10520. _this.placeholders.push(keep);
  10521. _this.index++;
  10522. return replaceBy;
  10523. });
  10524. };
  10525. return SafeSelector;
  10526. }());
  10527. var _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim;
  10528. var _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
  10529. var _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
  10530. var _polyfillHost = '-shadowcsshost';
  10531. // note: :host-context pre-processed to -shadowcsshostcontext.
  10532. var _polyfillHostContext = '-shadowcsscontext';
  10533. var _parenSuffix = '(?:\\((' +
  10534. '(?:\\([^)(]*\\)|[^)(]*)+?' +
  10535. ')\\))?([^,{]*)';
  10536. var _cssColonHostRe = new RegExp(_polyfillHost + _parenSuffix, 'gim');
  10537. var _cssColonHostContextReGlobal = new RegExp(_polyfillHostContext + _parenSuffix, 'gim');
  10538. var _cssColonHostContextRe = new RegExp(_polyfillHostContext + _parenSuffix, 'im');
  10539. var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
  10540. var _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/;
  10541. var _shadowDOMSelectorsRe = [
  10542. /::shadow/g,
  10543. /::content/g,
  10544. // Deprecated selectors
  10545. /\/shadow-deep\//g,
  10546. /\/shadow\//g,
  10547. ];
  10548. // The deep combinator is deprecated in the CSS spec
  10549. // Support for `>>>`, `deep`, `::ng-deep` is then also deprecated and will be removed in the future.
  10550. // see https://github.com/angular/angular/pull/17677
  10551. var _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)|(?:::ng-deep)/g;
  10552. var _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$';
  10553. var _polyfillHostRe = /-shadowcsshost/gim;
  10554. var _colonHostRe = /:host/gim;
  10555. var _colonHostContextRe = /:host-context/gim;
  10556. var _commentRe = /\/\*\s*[\s\S]*?\*\//g;
  10557. function stripComments(input) {
  10558. return input.replace(_commentRe, '');
  10559. }
  10560. var _commentWithHashRe = /\/\*\s*#\s*source(Mapping)?URL=[\s\S]+?\*\//g;
  10561. function extractCommentsWithHash(input) {
  10562. return input.match(_commentWithHashRe) || [];
  10563. }
  10564. var BLOCK_PLACEHOLDER = '%BLOCK%';
  10565. var QUOTE_PLACEHOLDER = '%QUOTED%';
  10566. var _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g;
  10567. var _quotedRe = /%QUOTED%/g;
  10568. var CONTENT_PAIRS = new Map([['{', '}']]);
  10569. var QUOTE_PAIRS = new Map([["\"", "\""], ["'", "'"]]);
  10570. var CssRule = /** @class */ (function () {
  10571. function CssRule(selector, content) {
  10572. this.selector = selector;
  10573. this.content = content;
  10574. }
  10575. return CssRule;
  10576. }());
  10577. function processRules(input, ruleCallback) {
  10578. var inputWithEscapedQuotes = escapeBlocks(input, QUOTE_PAIRS, QUOTE_PLACEHOLDER);
  10579. var inputWithEscapedBlocks = escapeBlocks(inputWithEscapedQuotes.escapedString, CONTENT_PAIRS, BLOCK_PLACEHOLDER);
  10580. var nextBlockIndex = 0;
  10581. var nextQuoteIndex = 0;
  10582. return inputWithEscapedBlocks.escapedString
  10583. .replace(_ruleRe, function () {
  10584. var m = [];
  10585. for (var _i = 0; _i < arguments.length; _i++) {
  10586. m[_i] = arguments[_i];
  10587. }
  10588. var selector = m[2];
  10589. var content = '';
  10590. var suffix = m[4];
  10591. var contentPrefix = '';
  10592. if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) {
  10593. content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
  10594. suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1);
  10595. contentPrefix = '{';
  10596. }
  10597. var rule = ruleCallback(new CssRule(selector, content));
  10598. return "" + m[1] + rule.selector + m[3] + contentPrefix + rule.content + suffix;
  10599. })
  10600. .replace(_quotedRe, function () { return inputWithEscapedQuotes.blocks[nextQuoteIndex++]; });
  10601. }
  10602. var StringWithEscapedBlocks = /** @class */ (function () {
  10603. function StringWithEscapedBlocks(escapedString, blocks) {
  10604. this.escapedString = escapedString;
  10605. this.blocks = blocks;
  10606. }
  10607. return StringWithEscapedBlocks;
  10608. }());
  10609. function escapeBlocks(input, charPairs, placeholder) {
  10610. var resultParts = [];
  10611. var escapedBlocks = [];
  10612. var openCharCount = 0;
  10613. var nonBlockStartIndex = 0;
  10614. var blockStartIndex = -1;
  10615. var openChar;
  10616. var closeChar;
  10617. for (var i = 0; i < input.length; i++) {
  10618. var char = input[i];
  10619. if (char === '\\') {
  10620. i++;
  10621. }
  10622. else if (char === closeChar) {
  10623. openCharCount--;
  10624. if (openCharCount === 0) {
  10625. escapedBlocks.push(input.substring(blockStartIndex, i));
  10626. resultParts.push(placeholder);
  10627. nonBlockStartIndex = i;
  10628. blockStartIndex = -1;
  10629. openChar = closeChar = undefined;
  10630. }
  10631. }
  10632. else if (char === openChar) {
  10633. openCharCount++;
  10634. }
  10635. else if (openCharCount === 0 && charPairs.has(char)) {
  10636. openChar = char;
  10637. closeChar = charPairs.get(char);
  10638. openCharCount = 1;
  10639. blockStartIndex = i + 1;
  10640. resultParts.push(input.substring(nonBlockStartIndex, blockStartIndex));
  10641. }
  10642. }
  10643. if (blockStartIndex !== -1) {
  10644. escapedBlocks.push(input.substring(blockStartIndex));
  10645. resultParts.push(placeholder);
  10646. }
  10647. else {
  10648. resultParts.push(input.substring(nonBlockStartIndex));
  10649. }
  10650. return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks);
  10651. }
  10652. /**
  10653. * Combine the `contextSelectors` with the `hostMarker` and the `otherSelectors`
  10654. * to create a selector that matches the same as `:host-context()`.
  10655. *
  10656. * Given a single context selector `A` we need to output selectors that match on the host and as an
  10657. * ancestor of the host:
  10658. *
  10659. * ```
  10660. * A <hostMarker>, A<hostMarker> {}
  10661. * ```
  10662. *
  10663. * When there is more than one context selector we also have to create combinations of those
  10664. * selectors with each other. For example if there are `A` and `B` selectors the output is:
  10665. *
  10666. * ```
  10667. * AB<hostMarker>, AB <hostMarker>, A B<hostMarker>,
  10668. * B A<hostMarker>, A B <hostMarker>, B A <hostMarker> {}
  10669. * ```
  10670. *
  10671. * And so on...
  10672. *
  10673. * @param hostMarker the string that selects the host element.
  10674. * @param contextSelectors an array of context selectors that will be combined.
  10675. * @param otherSelectors the rest of the selectors that are not context selectors.
  10676. */
  10677. function combineHostContextSelectors(contextSelectors, otherSelectors) {
  10678. var hostMarker = _polyfillHostNoCombinator;
  10679. _polyfillHostRe.lastIndex = 0; // reset the regex to ensure we get an accurate test
  10680. var otherSelectorsHasHost = _polyfillHostRe.test(otherSelectors);
  10681. // If there are no context selectors then just output a host marker
  10682. if (contextSelectors.length === 0) {
  10683. return hostMarker + otherSelectors;
  10684. }
  10685. var combined = [contextSelectors.pop() || ''];
  10686. while (contextSelectors.length > 0) {
  10687. var length = combined.length;
  10688. var contextSelector = contextSelectors.pop();
  10689. for (var i = 0; i < length; i++) {
  10690. var previousSelectors = combined[i];
  10691. // Add the new selector as a descendant of the previous selectors
  10692. combined[length * 2 + i] = previousSelectors + ' ' + contextSelector;
  10693. // Add the new selector as an ancestor of the previous selectors
  10694. combined[length + i] = contextSelector + ' ' + previousSelectors;
  10695. // Add the new selector to act on the same element as the previous selectors
  10696. combined[i] = contextSelector + previousSelectors;
  10697. }
  10698. }
  10699. // Finally connect the selector to the `hostMarker`s: either acting directly on the host
  10700. // (A<hostMarker>) or as an ancestor (A <hostMarker>).
  10701. return combined
  10702. .map(function (s) { return otherSelectorsHasHost ?
  10703. "" + s + otherSelectors :
  10704. "" + s + hostMarker + otherSelectors + ", " + s + " " + hostMarker + otherSelectors; })
  10705. .join(',');
  10706. }
  10707. /**
  10708. * Mutate the given `groups` array so that there are `multiples` clones of the original array
  10709. * stored.
  10710. *
  10711. * For example `repeatGroups([a, b], 3)` will result in `[a, b, a, b, a, b]` - but importantly the
  10712. * newly added groups will be clones of the original.
  10713. *
  10714. * @param groups An array of groups of strings that will be repeated. This array is mutated
  10715. * in-place.
  10716. * @param multiples The number of times the current groups should appear.
  10717. */
  10718. function repeatGroups(groups, multiples) {
  10719. var length = groups.length;
  10720. for (var i = 1; i < multiples; i++) {
  10721. for (var j = 0; j < length; j++) {
  10722. groups[j + (i * length)] = groups[j].slice(0);
  10723. }
  10724. }
  10725. }
  10726. /**
  10727. * @license
  10728. * Copyright Google LLC All Rights Reserved.
  10729. *
  10730. * Use of this source code is governed by an MIT-style license that can be
  10731. * found in the LICENSE file at https://angular.io/license
  10732. */
  10733. var COMPONENT_VARIABLE = '%COMP%';
  10734. var HOST_ATTR = "_nghost-" + COMPONENT_VARIABLE;
  10735. var CONTENT_ATTR = "_ngcontent-" + COMPONENT_VARIABLE;
  10736. var StylesCompileDependency = /** @class */ (function () {
  10737. function StylesCompileDependency(name, moduleUrl, setValue) {
  10738. this.name = name;
  10739. this.moduleUrl = moduleUrl;
  10740. this.setValue = setValue;
  10741. }
  10742. return StylesCompileDependency;
  10743. }());
  10744. var CompiledStylesheet = /** @class */ (function () {
  10745. function CompiledStylesheet(outputCtx, stylesVar, dependencies, isShimmed, meta) {
  10746. this.outputCtx = outputCtx;
  10747. this.stylesVar = stylesVar;
  10748. this.dependencies = dependencies;
  10749. this.isShimmed = isShimmed;
  10750. this.meta = meta;
  10751. }
  10752. return CompiledStylesheet;
  10753. }());
  10754. var StyleCompiler = /** @class */ (function () {
  10755. function StyleCompiler(_urlResolver) {
  10756. this._urlResolver = _urlResolver;
  10757. this._shadowCss = new ShadowCss();
  10758. }
  10759. StyleCompiler.prototype.compileComponent = function (outputCtx, comp) {
  10760. var template = comp.template;
  10761. return this._compileStyles(outputCtx, comp, new CompileStylesheetMetadata({
  10762. styles: template.styles,
  10763. styleUrls: template.styleUrls,
  10764. moduleUrl: identifierModuleUrl(comp.type)
  10765. }), this.needsStyleShim(comp), true);
  10766. };
  10767. StyleCompiler.prototype.compileStyles = function (outputCtx, comp, stylesheet, shim) {
  10768. if (shim === void 0) { shim = this.needsStyleShim(comp); }
  10769. return this._compileStyles(outputCtx, comp, stylesheet, shim, false);
  10770. };
  10771. StyleCompiler.prototype.needsStyleShim = function (comp) {
  10772. return comp.template.encapsulation === ViewEncapsulation.Emulated;
  10773. };
  10774. StyleCompiler.prototype._compileStyles = function (outputCtx, comp, stylesheet, shim, isComponentStylesheet) {
  10775. var _this = this;
  10776. var styleExpressions = stylesheet.styles.map(function (plainStyle) { return literal(_this._shimIfNeeded(plainStyle, shim)); });
  10777. var dependencies = [];
  10778. stylesheet.styleUrls.forEach(function (styleUrl) {
  10779. var exprIndex = styleExpressions.length;
  10780. // Note: This placeholder will be filled later.
  10781. styleExpressions.push(null);
  10782. dependencies.push(new StylesCompileDependency(getStylesVarName(null), styleUrl, function (value) { return styleExpressions[exprIndex] = outputCtx.importExpr(value); }));
  10783. });
  10784. // styles variable contains plain strings and arrays of other styles arrays (recursive),
  10785. // so we set its type to dynamic.
  10786. var stylesVar = getStylesVarName(isComponentStylesheet ? comp : null);
  10787. var stmt = variable(stylesVar)
  10788. .set(literalArr(styleExpressions, new ArrayType(DYNAMIC_TYPE, [TypeModifier.Const])))
  10789. .toDeclStmt(null, isComponentStylesheet ? [exports.StmtModifier.Final] : [
  10790. exports.StmtModifier.Final, exports.StmtModifier.Exported
  10791. ]);
  10792. outputCtx.statements.push(stmt);
  10793. return new CompiledStylesheet(outputCtx, stylesVar, dependencies, shim, stylesheet);
  10794. };
  10795. StyleCompiler.prototype._shimIfNeeded = function (style, shim) {
  10796. return shim ? this._shadowCss.shimCssText(style, CONTENT_ATTR, HOST_ATTR) : style;
  10797. };
  10798. return StyleCompiler;
  10799. }());
  10800. function getStylesVarName(component) {
  10801. var result = "styles";
  10802. if (component) {
  10803. result += "_" + identifierName(component.type);
  10804. }
  10805. return result;
  10806. }
  10807. /**
  10808. * @license
  10809. * Copyright Google LLC All Rights Reserved.
  10810. *
  10811. * Use of this source code is governed by an MIT-style license that can be
  10812. * found in the LICENSE file at https://angular.io/license
  10813. */
  10814. /**
  10815. * A path is an ordered set of elements. Typically a path is to a
  10816. * particular offset in a source file. The head of the list is the top
  10817. * most node. The tail is the node that contains the offset directly.
  10818. *
  10819. * For example, the expression `a + b + c` might have an ast that looks
  10820. * like:
  10821. * +
  10822. * / \
  10823. * a +
  10824. * / \
  10825. * b c
  10826. *
  10827. * The path to the node at offset 9 would be `['+' at 1-10, '+' at 7-10,
  10828. * 'c' at 9-10]` and the path the node at offset 1 would be
  10829. * `['+' at 1-10, 'a' at 1-2]`.
  10830. */
  10831. var AstPath = /** @class */ (function () {
  10832. function AstPath(path, position) {
  10833. if (position === void 0) { position = -1; }
  10834. this.path = path;
  10835. this.position = position;
  10836. }
  10837. Object.defineProperty(AstPath.prototype, "empty", {
  10838. get: function () {
  10839. return !this.path || !this.path.length;
  10840. },
  10841. enumerable: false,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(AstPath.prototype, "head", {
  10845. get: function () {
  10846. return this.path[0];
  10847. },
  10848. enumerable: false,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(AstPath.prototype, "tail", {
  10852. get: function () {
  10853. return this.path[this.path.length - 1];
  10854. },
  10855. enumerable: false,
  10856. configurable: true
  10857. });
  10858. AstPath.prototype.parentOf = function (node) {
  10859. return node && this.path[this.path.indexOf(node) - 1];
  10860. };
  10861. AstPath.prototype.childOf = function (node) {
  10862. return this.path[this.path.indexOf(node) + 1];
  10863. };
  10864. AstPath.prototype.first = function (ctor) {
  10865. for (var i = this.path.length - 1; i >= 0; i--) {
  10866. var item = this.path[i];
  10867. if (item instanceof ctor)
  10868. return item;
  10869. }
  10870. };
  10871. AstPath.prototype.push = function (node) {
  10872. this.path.push(node);
  10873. };
  10874. AstPath.prototype.pop = function () {
  10875. return this.path.pop();
  10876. };
  10877. return AstPath;
  10878. }());
  10879. var NodeWithI18n = /** @class */ (function () {
  10880. function NodeWithI18n(sourceSpan, i18n) {
  10881. this.sourceSpan = sourceSpan;
  10882. this.i18n = i18n;
  10883. }
  10884. return NodeWithI18n;
  10885. }());
  10886. var Text$3 = /** @class */ (function (_super) {
  10887. __extends(Text, _super);
  10888. function Text(value, sourceSpan, i18n) {
  10889. var _this = _super.call(this, sourceSpan, i18n) || this;
  10890. _this.value = value;
  10891. return _this;
  10892. }
  10893. Text.prototype.visit = function (visitor, context) {
  10894. return visitor.visitText(this, context);
  10895. };
  10896. return Text;
  10897. }(NodeWithI18n));
  10898. var Expansion = /** @class */ (function (_super) {
  10899. __extends(Expansion, _super);
  10900. function Expansion(switchValue, type, cases, sourceSpan, switchValueSourceSpan, i18n) {
  10901. var _this = _super.call(this, sourceSpan, i18n) || this;
  10902. _this.switchValue = switchValue;
  10903. _this.type = type;
  10904. _this.cases = cases;
  10905. _this.switchValueSourceSpan = switchValueSourceSpan;
  10906. return _this;
  10907. }
  10908. Expansion.prototype.visit = function (visitor, context) {
  10909. return visitor.visitExpansion(this, context);
  10910. };
  10911. return Expansion;
  10912. }(NodeWithI18n));
  10913. var ExpansionCase = /** @class */ (function () {
  10914. function ExpansionCase(value, expression, sourceSpan, valueSourceSpan, expSourceSpan) {
  10915. this.value = value;
  10916. this.expression = expression;
  10917. this.sourceSpan = sourceSpan;
  10918. this.valueSourceSpan = valueSourceSpan;
  10919. this.expSourceSpan = expSourceSpan;
  10920. }
  10921. ExpansionCase.prototype.visit = function (visitor, context) {
  10922. return visitor.visitExpansionCase(this, context);
  10923. };
  10924. return ExpansionCase;
  10925. }());
  10926. var Attribute = /** @class */ (function (_super) {
  10927. __extends(Attribute, _super);
  10928. function Attribute(name, value, sourceSpan, keySpan, valueSpan, i18n) {
  10929. var _this = _super.call(this, sourceSpan, i18n) || this;
  10930. _this.name = name;
  10931. _this.value = value;
  10932. _this.keySpan = keySpan;
  10933. _this.valueSpan = valueSpan;
  10934. return _this;
  10935. }
  10936. Attribute.prototype.visit = function (visitor, context) {
  10937. return visitor.visitAttribute(this, context);
  10938. };
  10939. return Attribute;
  10940. }(NodeWithI18n));
  10941. var Element$1 = /** @class */ (function (_super) {
  10942. __extends(Element, _super);
  10943. function Element(name, attrs, children, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
  10944. if (endSourceSpan === void 0) { endSourceSpan = null; }
  10945. var _this = _super.call(this, sourceSpan, i18n) || this;
  10946. _this.name = name;
  10947. _this.attrs = attrs;
  10948. _this.children = children;
  10949. _this.startSourceSpan = startSourceSpan;
  10950. _this.endSourceSpan = endSourceSpan;
  10951. return _this;
  10952. }
  10953. Element.prototype.visit = function (visitor, context) {
  10954. return visitor.visitElement(this, context);
  10955. };
  10956. return Element;
  10957. }(NodeWithI18n));
  10958. var Comment$1 = /** @class */ (function () {
  10959. function Comment(value, sourceSpan) {
  10960. this.value = value;
  10961. this.sourceSpan = sourceSpan;
  10962. }
  10963. Comment.prototype.visit = function (visitor, context) {
  10964. return visitor.visitComment(this, context);
  10965. };
  10966. return Comment;
  10967. }());
  10968. function visitAll$1(visitor, nodes, context) {
  10969. if (context === void 0) { context = null; }
  10970. var result = [];
  10971. var visit = visitor.visit ?
  10972. function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } :
  10973. function (ast) { return ast.visit(visitor, context); };
  10974. nodes.forEach(function (ast) {
  10975. var astResult = visit(ast);
  10976. if (astResult) {
  10977. result.push(astResult);
  10978. }
  10979. });
  10980. return result;
  10981. }
  10982. var RecursiveVisitor$1 = /** @class */ (function () {
  10983. function RecursiveVisitor() {
  10984. }
  10985. RecursiveVisitor.prototype.visitElement = function (ast, context) {
  10986. this.visitChildren(context, function (visit) {
  10987. visit(ast.attrs);
  10988. visit(ast.children);
  10989. });
  10990. };
  10991. RecursiveVisitor.prototype.visitAttribute = function (ast, context) { };
  10992. RecursiveVisitor.prototype.visitText = function (ast, context) { };
  10993. RecursiveVisitor.prototype.visitComment = function (ast, context) { };
  10994. RecursiveVisitor.prototype.visitExpansion = function (ast, context) {
  10995. return this.visitChildren(context, function (visit) {
  10996. visit(ast.cases);
  10997. });
  10998. };
  10999. RecursiveVisitor.prototype.visitExpansionCase = function (ast, context) { };
  11000. RecursiveVisitor.prototype.visitChildren = function (context, cb) {
  11001. var results = [];
  11002. var t = this;
  11003. function visit(children) {
  11004. if (children)
  11005. results.push(visitAll$1(t, children, context));
  11006. }
  11007. cb(visit);
  11008. return Array.prototype.concat.apply([], results);
  11009. };
  11010. return RecursiveVisitor;
  11011. }());
  11012. function spanOf(ast) {
  11013. var start = ast.sourceSpan.start.offset;
  11014. var end = ast.sourceSpan.end.offset;
  11015. if (ast instanceof Element$1) {
  11016. if (ast.endSourceSpan) {
  11017. end = ast.endSourceSpan.end.offset;
  11018. }
  11019. else if (ast.children && ast.children.length) {
  11020. end = spanOf(ast.children[ast.children.length - 1]).end;
  11021. }
  11022. }
  11023. return { start: start, end: end };
  11024. }
  11025. function findNode(nodes, position) {
  11026. var path = [];
  11027. var visitor = new /** @class */ (function (_super) {
  11028. __extends(class_1, _super);
  11029. function class_1() {
  11030. return _super !== null && _super.apply(this, arguments) || this;
  11031. }
  11032. class_1.prototype.visit = function (ast, context) {
  11033. var span = spanOf(ast);
  11034. if (span.start <= position && position < span.end) {
  11035. path.push(ast);
  11036. }
  11037. else {
  11038. // Returning a value here will result in the children being skipped.
  11039. return true;
  11040. }
  11041. };
  11042. return class_1;
  11043. }(RecursiveVisitor$1));
  11044. visitAll$1(visitor, nodes);
  11045. return new AstPath(path, position);
  11046. }
  11047. var TokenType;
  11048. (function (TokenType) {
  11049. TokenType[TokenType["TAG_OPEN_START"] = 0] = "TAG_OPEN_START";
  11050. TokenType[TokenType["TAG_OPEN_END"] = 1] = "TAG_OPEN_END";
  11051. TokenType[TokenType["TAG_OPEN_END_VOID"] = 2] = "TAG_OPEN_END_VOID";
  11052. TokenType[TokenType["TAG_CLOSE"] = 3] = "TAG_CLOSE";
  11053. TokenType[TokenType["INCOMPLETE_TAG_OPEN"] = 4] = "INCOMPLETE_TAG_OPEN";
  11054. TokenType[TokenType["TEXT"] = 5] = "TEXT";
  11055. TokenType[TokenType["ESCAPABLE_RAW_TEXT"] = 6] = "ESCAPABLE_RAW_TEXT";
  11056. TokenType[TokenType["RAW_TEXT"] = 7] = "RAW_TEXT";
  11057. TokenType[TokenType["COMMENT_START"] = 8] = "COMMENT_START";
  11058. TokenType[TokenType["COMMENT_END"] = 9] = "COMMENT_END";
  11059. TokenType[TokenType["CDATA_START"] = 10] = "CDATA_START";
  11060. TokenType[TokenType["CDATA_END"] = 11] = "CDATA_END";
  11061. TokenType[TokenType["ATTR_NAME"] = 12] = "ATTR_NAME";
  11062. TokenType[TokenType["ATTR_QUOTE"] = 13] = "ATTR_QUOTE";
  11063. TokenType[TokenType["ATTR_VALUE"] = 14] = "ATTR_VALUE";
  11064. TokenType[TokenType["DOC_TYPE"] = 15] = "DOC_TYPE";
  11065. TokenType[TokenType["EXPANSION_FORM_START"] = 16] = "EXPANSION_FORM_START";
  11066. TokenType[TokenType["EXPANSION_CASE_VALUE"] = 17] = "EXPANSION_CASE_VALUE";
  11067. TokenType[TokenType["EXPANSION_CASE_EXP_START"] = 18] = "EXPANSION_CASE_EXP_START";
  11068. TokenType[TokenType["EXPANSION_CASE_EXP_END"] = 19] = "EXPANSION_CASE_EXP_END";
  11069. TokenType[TokenType["EXPANSION_FORM_END"] = 20] = "EXPANSION_FORM_END";
  11070. TokenType[TokenType["EOF"] = 21] = "EOF";
  11071. })(TokenType || (TokenType = {}));
  11072. var Token = /** @class */ (function () {
  11073. function Token(type, parts, sourceSpan) {
  11074. this.type = type;
  11075. this.parts = parts;
  11076. this.sourceSpan = sourceSpan;
  11077. }
  11078. return Token;
  11079. }());
  11080. var TokenError = /** @class */ (function (_super) {
  11081. __extends(TokenError, _super);
  11082. function TokenError(errorMsg, tokenType, span) {
  11083. var _this = _super.call(this, span, errorMsg) || this;
  11084. _this.tokenType = tokenType;
  11085. return _this;
  11086. }
  11087. return TokenError;
  11088. }(ParseError));
  11089. var TokenizeResult = /** @class */ (function () {
  11090. function TokenizeResult(tokens, errors, nonNormalizedIcuExpressions) {
  11091. this.tokens = tokens;
  11092. this.errors = errors;
  11093. this.nonNormalizedIcuExpressions = nonNormalizedIcuExpressions;
  11094. }
  11095. return TokenizeResult;
  11096. }());
  11097. function tokenize(source, url, getTagDefinition, options) {
  11098. if (options === void 0) { options = {}; }
  11099. var tokenizer = new _Tokenizer(new ParseSourceFile(source, url), getTagDefinition, options);
  11100. tokenizer.tokenize();
  11101. return new TokenizeResult(mergeTextTokens(tokenizer.tokens), tokenizer.errors, tokenizer.nonNormalizedIcuExpressions);
  11102. }
  11103. var _CR_OR_CRLF_REGEXP = /\r\n?/g;
  11104. function _unexpectedCharacterErrorMsg(charCode) {
  11105. var char = charCode === $EOF ? 'EOF' : String.fromCharCode(charCode);
  11106. return "Unexpected character \"" + char + "\"";
  11107. }
  11108. function _unknownEntityErrorMsg(entitySrc) {
  11109. return "Unknown entity \"" + entitySrc + "\" - use the \"&#<decimal>;\" or \"&#x<hex>;\" syntax";
  11110. }
  11111. function _unparsableEntityErrorMsg(type, entityStr) {
  11112. return "Unable to parse entity \"" + entityStr + "\" - " + type + " character reference entities must end with \";\"";
  11113. }
  11114. var CharacterReferenceType;
  11115. (function (CharacterReferenceType) {
  11116. CharacterReferenceType["HEX"] = "hexadecimal";
  11117. CharacterReferenceType["DEC"] = "decimal";
  11118. })(CharacterReferenceType || (CharacterReferenceType = {}));
  11119. var _ControlFlowError = /** @class */ (function () {
  11120. function _ControlFlowError(error) {
  11121. this.error = error;
  11122. }
  11123. return _ControlFlowError;
  11124. }());
  11125. // See https://www.w3.org/TR/html51/syntax.html#writing-html-documents
  11126. var _Tokenizer = /** @class */ (function () {
  11127. /**
  11128. * @param _file The html source file being tokenized.
  11129. * @param _getTagDefinition A function that will retrieve a tag definition for a given tag name.
  11130. * @param options Configuration of the tokenization.
  11131. */
  11132. function _Tokenizer(_file, _getTagDefinition, options) {
  11133. this._getTagDefinition = _getTagDefinition;
  11134. this._currentTokenStart = null;
  11135. this._currentTokenType = null;
  11136. this._expansionCaseStack = [];
  11137. this._inInterpolation = false;
  11138. this.tokens = [];
  11139. this.errors = [];
  11140. this.nonNormalizedIcuExpressions = [];
  11141. this._tokenizeIcu = options.tokenizeExpansionForms || false;
  11142. this._interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
  11143. this._leadingTriviaCodePoints =
  11144. options.leadingTriviaChars && options.leadingTriviaChars.map(function (c) { return c.codePointAt(0) || 0; });
  11145. var range = options.range || { endPos: _file.content.length, startPos: 0, startLine: 0, startCol: 0 };
  11146. this._cursor = options.escapedString ? new EscapedCharacterCursor(_file, range) :
  11147. new PlainCharacterCursor(_file, range);
  11148. this._preserveLineEndings = options.preserveLineEndings || false;
  11149. this._escapedString = options.escapedString || false;
  11150. this._i18nNormalizeLineEndingsInICUs = options.i18nNormalizeLineEndingsInICUs || false;
  11151. try {
  11152. this._cursor.init();
  11153. }
  11154. catch (e) {
  11155. this.handleError(e);
  11156. }
  11157. }
  11158. _Tokenizer.prototype._processCarriageReturns = function (content) {
  11159. if (this._preserveLineEndings) {
  11160. return content;
  11161. }
  11162. // https://www.w3.org/TR/html51/syntax.html#preprocessing-the-input-stream
  11163. // In order to keep the original position in the source, we can not
  11164. // pre-process it.
  11165. // Instead CRs are processed right before instantiating the tokens.
  11166. return content.replace(_CR_OR_CRLF_REGEXP, '\n');
  11167. };
  11168. _Tokenizer.prototype.tokenize = function () {
  11169. while (this._cursor.peek() !== $EOF) {
  11170. var start = this._cursor.clone();
  11171. try {
  11172. if (this._attemptCharCode($LT)) {
  11173. if (this._attemptCharCode($BANG)) {
  11174. if (this._attemptCharCode($LBRACKET)) {
  11175. this._consumeCdata(start);
  11176. }
  11177. else if (this._attemptCharCode($MINUS)) {
  11178. this._consumeComment(start);
  11179. }
  11180. else {
  11181. this._consumeDocType(start);
  11182. }
  11183. }
  11184. else if (this._attemptCharCode($SLASH)) {
  11185. this._consumeTagClose(start);
  11186. }
  11187. else {
  11188. this._consumeTagOpen(start);
  11189. }
  11190. }
  11191. else if (!(this._tokenizeIcu && this._tokenizeExpansionForm())) {
  11192. this._consumeText();
  11193. }
  11194. }
  11195. catch (e) {
  11196. this.handleError(e);
  11197. }
  11198. }
  11199. this._beginToken(TokenType.EOF);
  11200. this._endToken([]);
  11201. };
  11202. /**
  11203. * @returns whether an ICU token has been created
  11204. * @internal
  11205. */
  11206. _Tokenizer.prototype._tokenizeExpansionForm = function () {
  11207. if (this.isExpansionFormStart()) {
  11208. this._consumeExpansionFormStart();
  11209. return true;
  11210. }
  11211. if (isExpansionCaseStart(this._cursor.peek()) && this._isInExpansionForm()) {
  11212. this._consumeExpansionCaseStart();
  11213. return true;
  11214. }
  11215. if (this._cursor.peek() === $RBRACE) {
  11216. if (this._isInExpansionCase()) {
  11217. this._consumeExpansionCaseEnd();
  11218. return true;
  11219. }
  11220. if (this._isInExpansionForm()) {
  11221. this._consumeExpansionFormEnd();
  11222. return true;
  11223. }
  11224. }
  11225. return false;
  11226. };
  11227. _Tokenizer.prototype._beginToken = function (type, start) {
  11228. if (start === void 0) { start = this._cursor.clone(); }
  11229. this._currentTokenStart = start;
  11230. this._currentTokenType = type;
  11231. };
  11232. _Tokenizer.prototype._endToken = function (parts, end) {
  11233. if (this._currentTokenStart === null) {
  11234. throw new TokenError('Programming error - attempted to end a token when there was no start to the token', this._currentTokenType, this._cursor.getSpan(end));
  11235. }
  11236. if (this._currentTokenType === null) {
  11237. throw new TokenError('Programming error - attempted to end a token which has no token type', null, this._cursor.getSpan(this._currentTokenStart));
  11238. }
  11239. var token = new Token(this._currentTokenType, parts, this._cursor.getSpan(this._currentTokenStart, this._leadingTriviaCodePoints));
  11240. this.tokens.push(token);
  11241. this._currentTokenStart = null;
  11242. this._currentTokenType = null;
  11243. return token;
  11244. };
  11245. _Tokenizer.prototype._createError = function (msg, span) {
  11246. if (this._isInExpansionForm()) {
  11247. msg += " (Do you have an unescaped \"{\" in your template? Use \"{{ '{' }}\") to escape it.)";
  11248. }
  11249. var error = new TokenError(msg, this._currentTokenType, span);
  11250. this._currentTokenStart = null;
  11251. this._currentTokenType = null;
  11252. return new _ControlFlowError(error);
  11253. };
  11254. _Tokenizer.prototype.handleError = function (e) {
  11255. if (e instanceof CursorError) {
  11256. e = this._createError(e.msg, this._cursor.getSpan(e.cursor));
  11257. }
  11258. if (e instanceof _ControlFlowError) {
  11259. this.errors.push(e.error);
  11260. }
  11261. else {
  11262. throw e;
  11263. }
  11264. };
  11265. _Tokenizer.prototype._attemptCharCode = function (charCode) {
  11266. if (this._cursor.peek() === charCode) {
  11267. this._cursor.advance();
  11268. return true;
  11269. }
  11270. return false;
  11271. };
  11272. _Tokenizer.prototype._attemptCharCodeCaseInsensitive = function (charCode) {
  11273. if (compareCharCodeCaseInsensitive(this._cursor.peek(), charCode)) {
  11274. this._cursor.advance();
  11275. return true;
  11276. }
  11277. return false;
  11278. };
  11279. _Tokenizer.prototype._requireCharCode = function (charCode) {
  11280. var location = this._cursor.clone();
  11281. if (!this._attemptCharCode(charCode)) {
  11282. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
  11283. }
  11284. };
  11285. _Tokenizer.prototype._attemptStr = function (chars) {
  11286. var len = chars.length;
  11287. if (this._cursor.charsLeft() < len) {
  11288. return false;
  11289. }
  11290. var initialPosition = this._cursor.clone();
  11291. for (var i = 0; i < len; i++) {
  11292. if (!this._attemptCharCode(chars.charCodeAt(i))) {
  11293. // If attempting to parse the string fails, we want to reset the parser
  11294. // to where it was before the attempt
  11295. this._cursor = initialPosition;
  11296. return false;
  11297. }
  11298. }
  11299. return true;
  11300. };
  11301. _Tokenizer.prototype._attemptStrCaseInsensitive = function (chars) {
  11302. for (var i = 0; i < chars.length; i++) {
  11303. if (!this._attemptCharCodeCaseInsensitive(chars.charCodeAt(i))) {
  11304. return false;
  11305. }
  11306. }
  11307. return true;
  11308. };
  11309. _Tokenizer.prototype._requireStr = function (chars) {
  11310. var location = this._cursor.clone();
  11311. if (!this._attemptStr(chars)) {
  11312. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
  11313. }
  11314. };
  11315. _Tokenizer.prototype._attemptCharCodeUntilFn = function (predicate) {
  11316. while (!predicate(this._cursor.peek())) {
  11317. this._cursor.advance();
  11318. }
  11319. };
  11320. _Tokenizer.prototype._requireCharCodeUntilFn = function (predicate, len) {
  11321. var start = this._cursor.clone();
  11322. this._attemptCharCodeUntilFn(predicate);
  11323. if (this._cursor.diff(start) < len) {
  11324. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
  11325. }
  11326. };
  11327. _Tokenizer.prototype._attemptUntilChar = function (char) {
  11328. while (this._cursor.peek() !== char) {
  11329. this._cursor.advance();
  11330. }
  11331. };
  11332. _Tokenizer.prototype._readChar = function (decodeEntities) {
  11333. if (decodeEntities && this._cursor.peek() === $AMPERSAND) {
  11334. return this._decodeEntity();
  11335. }
  11336. else {
  11337. // Don't rely upon reading directly from `_input` as the actual char value
  11338. // may have been generated from an escape sequence.
  11339. var char = String.fromCodePoint(this._cursor.peek());
  11340. this._cursor.advance();
  11341. return char;
  11342. }
  11343. };
  11344. _Tokenizer.prototype._decodeEntity = function () {
  11345. var start = this._cursor.clone();
  11346. this._cursor.advance();
  11347. if (this._attemptCharCode($HASH)) {
  11348. var isHex = this._attemptCharCode($x) || this._attemptCharCode($X);
  11349. var codeStart = this._cursor.clone();
  11350. this._attemptCharCodeUntilFn(isDigitEntityEnd);
  11351. if (this._cursor.peek() != $SEMICOLON) {
  11352. // Advance cursor to include the peeked character in the string provided to the error
  11353. // message.
  11354. this._cursor.advance();
  11355. var entityType = isHex ? CharacterReferenceType.HEX : CharacterReferenceType.DEC;
  11356. throw this._createError(_unparsableEntityErrorMsg(entityType, this._cursor.getChars(start)), this._cursor.getSpan());
  11357. }
  11358. var strNum = this._cursor.getChars(codeStart);
  11359. this._cursor.advance();
  11360. try {
  11361. var charCode = parseInt(strNum, isHex ? 16 : 10);
  11362. return String.fromCharCode(charCode);
  11363. }
  11364. catch (_a) {
  11365. throw this._createError(_unknownEntityErrorMsg(this._cursor.getChars(start)), this._cursor.getSpan());
  11366. }
  11367. }
  11368. else {
  11369. var nameStart = this._cursor.clone();
  11370. this._attemptCharCodeUntilFn(isNamedEntityEnd);
  11371. if (this._cursor.peek() != $SEMICOLON) {
  11372. this._cursor = nameStart;
  11373. return '&';
  11374. }
  11375. var name = this._cursor.getChars(nameStart);
  11376. this._cursor.advance();
  11377. var char = NAMED_ENTITIES[name];
  11378. if (!char) {
  11379. throw this._createError(_unknownEntityErrorMsg(name), this._cursor.getSpan(start));
  11380. }
  11381. return char;
  11382. }
  11383. };
  11384. _Tokenizer.prototype._consumeRawText = function (decodeEntities, endMarkerPredicate) {
  11385. this._beginToken(decodeEntities ? TokenType.ESCAPABLE_RAW_TEXT : TokenType.RAW_TEXT);
  11386. var parts = [];
  11387. while (true) {
  11388. var tagCloseStart = this._cursor.clone();
  11389. var foundEndMarker = endMarkerPredicate();
  11390. this._cursor = tagCloseStart;
  11391. if (foundEndMarker) {
  11392. break;
  11393. }
  11394. parts.push(this._readChar(decodeEntities));
  11395. }
  11396. return this._endToken([this._processCarriageReturns(parts.join(''))]);
  11397. };
  11398. _Tokenizer.prototype._consumeComment = function (start) {
  11399. var _this = this;
  11400. this._beginToken(TokenType.COMMENT_START, start);
  11401. this._requireCharCode($MINUS);
  11402. this._endToken([]);
  11403. this._consumeRawText(false, function () { return _this._attemptStr('-->'); });
  11404. this._beginToken(TokenType.COMMENT_END);
  11405. this._requireStr('-->');
  11406. this._endToken([]);
  11407. };
  11408. _Tokenizer.prototype._consumeCdata = function (start) {
  11409. var _this = this;
  11410. this._beginToken(TokenType.CDATA_START, start);
  11411. this._requireStr('CDATA[');
  11412. this._endToken([]);
  11413. this._consumeRawText(false, function () { return _this._attemptStr(']]>'); });
  11414. this._beginToken(TokenType.CDATA_END);
  11415. this._requireStr(']]>');
  11416. this._endToken([]);
  11417. };
  11418. _Tokenizer.prototype._consumeDocType = function (start) {
  11419. this._beginToken(TokenType.DOC_TYPE, start);
  11420. var contentStart = this._cursor.clone();
  11421. this._attemptUntilChar($GT);
  11422. var content = this._cursor.getChars(contentStart);
  11423. this._cursor.advance();
  11424. this._endToken([content]);
  11425. };
  11426. _Tokenizer.prototype._consumePrefixAndName = function () {
  11427. var nameOrPrefixStart = this._cursor.clone();
  11428. var prefix = '';
  11429. while (this._cursor.peek() !== $COLON && !isPrefixEnd(this._cursor.peek())) {
  11430. this._cursor.advance();
  11431. }
  11432. var nameStart;
  11433. if (this._cursor.peek() === $COLON) {
  11434. prefix = this._cursor.getChars(nameOrPrefixStart);
  11435. this._cursor.advance();
  11436. nameStart = this._cursor.clone();
  11437. }
  11438. else {
  11439. nameStart = nameOrPrefixStart;
  11440. }
  11441. this._requireCharCodeUntilFn(isNameEnd, prefix === '' ? 0 : 1);
  11442. var name = this._cursor.getChars(nameStart);
  11443. return [prefix, name];
  11444. };
  11445. _Tokenizer.prototype._consumeTagOpen = function (start) {
  11446. var tagName;
  11447. var prefix;
  11448. var openTagToken;
  11449. try {
  11450. if (!isAsciiLetter(this._cursor.peek())) {
  11451. throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
  11452. }
  11453. openTagToken = this._consumeTagOpenStart(start);
  11454. prefix = openTagToken.parts[0];
  11455. tagName = openTagToken.parts[1];
  11456. this._attemptCharCodeUntilFn(isNotWhitespace);
  11457. while (this._cursor.peek() !== $SLASH && this._cursor.peek() !== $GT &&
  11458. this._cursor.peek() !== $LT && this._cursor.peek() !== $EOF) {
  11459. this._consumeAttributeName();
  11460. this._attemptCharCodeUntilFn(isNotWhitespace);
  11461. if (this._attemptCharCode($EQ)) {
  11462. this._attemptCharCodeUntilFn(isNotWhitespace);
  11463. this._consumeAttributeValue();
  11464. }
  11465. this._attemptCharCodeUntilFn(isNotWhitespace);
  11466. }
  11467. this._consumeTagOpenEnd();
  11468. }
  11469. catch (e) {
  11470. if (e instanceof _ControlFlowError) {
  11471. if (openTagToken) {
  11472. // We errored before we could close the opening tag, so it is incomplete.
  11473. openTagToken.type = TokenType.INCOMPLETE_TAG_OPEN;
  11474. }
  11475. else {
  11476. // When the start tag is invalid, assume we want a "<" as text.
  11477. // Back to back text tokens are merged at the end.
  11478. this._beginToken(TokenType.TEXT, start);
  11479. this._endToken(['<']);
  11480. }
  11481. return;
  11482. }
  11483. throw e;
  11484. }
  11485. var contentTokenType = this._getTagDefinition(tagName).getContentType(prefix);
  11486. if (contentTokenType === exports.TagContentType.RAW_TEXT) {
  11487. this._consumeRawTextWithTagClose(prefix, tagName, false);
  11488. }
  11489. else if (contentTokenType === exports.TagContentType.ESCAPABLE_RAW_TEXT) {
  11490. this._consumeRawTextWithTagClose(prefix, tagName, true);
  11491. }
  11492. };
  11493. _Tokenizer.prototype._consumeRawTextWithTagClose = function (prefix, tagName, decodeEntities) {
  11494. var _this = this;
  11495. this._consumeRawText(decodeEntities, function () {
  11496. if (!_this._attemptCharCode($LT))
  11497. return false;
  11498. if (!_this._attemptCharCode($SLASH))
  11499. return false;
  11500. _this._attemptCharCodeUntilFn(isNotWhitespace);
  11501. if (!_this._attemptStrCaseInsensitive(tagName))
  11502. return false;
  11503. _this._attemptCharCodeUntilFn(isNotWhitespace);
  11504. return _this._attemptCharCode($GT);
  11505. });
  11506. this._beginToken(TokenType.TAG_CLOSE);
  11507. this._requireCharCodeUntilFn(function (code) { return code === $GT; }, 3);
  11508. this._cursor.advance(); // Consume the `>`
  11509. this._endToken([prefix, tagName]);
  11510. };
  11511. _Tokenizer.prototype._consumeTagOpenStart = function (start) {
  11512. this._beginToken(TokenType.TAG_OPEN_START, start);
  11513. var parts = this._consumePrefixAndName();
  11514. return this._endToken(parts);
  11515. };
  11516. _Tokenizer.prototype._consumeAttributeName = function () {
  11517. var attrNameStart = this._cursor.peek();
  11518. if (attrNameStart === $SQ || attrNameStart === $DQ) {
  11519. throw this._createError(_unexpectedCharacterErrorMsg(attrNameStart), this._cursor.getSpan());
  11520. }
  11521. this._beginToken(TokenType.ATTR_NAME);
  11522. var prefixAndName = this._consumePrefixAndName();
  11523. this._endToken(prefixAndName);
  11524. };
  11525. _Tokenizer.prototype._consumeAttributeValue = function () {
  11526. var value;
  11527. if (this._cursor.peek() === $SQ || this._cursor.peek() === $DQ) {
  11528. this._beginToken(TokenType.ATTR_QUOTE);
  11529. var quoteChar = this._cursor.peek();
  11530. this._cursor.advance();
  11531. this._endToken([String.fromCodePoint(quoteChar)]);
  11532. this._beginToken(TokenType.ATTR_VALUE);
  11533. var parts = [];
  11534. while (this._cursor.peek() !== quoteChar) {
  11535. parts.push(this._readChar(true));
  11536. }
  11537. value = parts.join('');
  11538. this._endToken([this._processCarriageReturns(value)]);
  11539. this._beginToken(TokenType.ATTR_QUOTE);
  11540. this._cursor.advance();
  11541. this._endToken([String.fromCodePoint(quoteChar)]);
  11542. }
  11543. else {
  11544. this._beginToken(TokenType.ATTR_VALUE);
  11545. var valueStart = this._cursor.clone();
  11546. this._requireCharCodeUntilFn(isNameEnd, 1);
  11547. value = this._cursor.getChars(valueStart);
  11548. this._endToken([this._processCarriageReturns(value)]);
  11549. }
  11550. };
  11551. _Tokenizer.prototype._consumeTagOpenEnd = function () {
  11552. var tokenType = this._attemptCharCode($SLASH) ? TokenType.TAG_OPEN_END_VOID : TokenType.TAG_OPEN_END;
  11553. this._beginToken(tokenType);
  11554. this._requireCharCode($GT);
  11555. this._endToken([]);
  11556. };
  11557. _Tokenizer.prototype._consumeTagClose = function (start) {
  11558. this._beginToken(TokenType.TAG_CLOSE, start);
  11559. this._attemptCharCodeUntilFn(isNotWhitespace);
  11560. var prefixAndName = this._consumePrefixAndName();
  11561. this._attemptCharCodeUntilFn(isNotWhitespace);
  11562. this._requireCharCode($GT);
  11563. this._endToken(prefixAndName);
  11564. };
  11565. _Tokenizer.prototype._consumeExpansionFormStart = function () {
  11566. this._beginToken(TokenType.EXPANSION_FORM_START);
  11567. this._requireCharCode($LBRACE);
  11568. this._endToken([]);
  11569. this._expansionCaseStack.push(TokenType.EXPANSION_FORM_START);
  11570. this._beginToken(TokenType.RAW_TEXT);
  11571. var condition = this._readUntil($COMMA);
  11572. var normalizedCondition = this._processCarriageReturns(condition);
  11573. if (this._i18nNormalizeLineEndingsInICUs) {
  11574. // We explicitly want to normalize line endings for this text.
  11575. this._endToken([normalizedCondition]);
  11576. }
  11577. else {
  11578. // We are not normalizing line endings.
  11579. var conditionToken = this._endToken([condition]);
  11580. if (normalizedCondition !== condition) {
  11581. this.nonNormalizedIcuExpressions.push(conditionToken);
  11582. }
  11583. }
  11584. this._requireCharCode($COMMA);
  11585. this._attemptCharCodeUntilFn(isNotWhitespace);
  11586. this._beginToken(TokenType.RAW_TEXT);
  11587. var type = this._readUntil($COMMA);
  11588. this._endToken([type]);
  11589. this._requireCharCode($COMMA);
  11590. this._attemptCharCodeUntilFn(isNotWhitespace);
  11591. };
  11592. _Tokenizer.prototype._consumeExpansionCaseStart = function () {
  11593. this._beginToken(TokenType.EXPANSION_CASE_VALUE);
  11594. var value = this._readUntil($LBRACE).trim();
  11595. this._endToken([value]);
  11596. this._attemptCharCodeUntilFn(isNotWhitespace);
  11597. this._beginToken(TokenType.EXPANSION_CASE_EXP_START);
  11598. this._requireCharCode($LBRACE);
  11599. this._endToken([]);
  11600. this._attemptCharCodeUntilFn(isNotWhitespace);
  11601. this._expansionCaseStack.push(TokenType.EXPANSION_CASE_EXP_START);
  11602. };
  11603. _Tokenizer.prototype._consumeExpansionCaseEnd = function () {
  11604. this._beginToken(TokenType.EXPANSION_CASE_EXP_END);
  11605. this._requireCharCode($RBRACE);
  11606. this._endToken([]);
  11607. this._attemptCharCodeUntilFn(isNotWhitespace);
  11608. this._expansionCaseStack.pop();
  11609. };
  11610. _Tokenizer.prototype._consumeExpansionFormEnd = function () {
  11611. this._beginToken(TokenType.EXPANSION_FORM_END);
  11612. this._requireCharCode($RBRACE);
  11613. this._endToken([]);
  11614. this._expansionCaseStack.pop();
  11615. };
  11616. _Tokenizer.prototype._consumeText = function () {
  11617. var start = this._cursor.clone();
  11618. this._beginToken(TokenType.TEXT, start);
  11619. var parts = [];
  11620. do {
  11621. if (this._interpolationConfig && this._attemptStr(this._interpolationConfig.start)) {
  11622. parts.push(this._interpolationConfig.start);
  11623. this._inInterpolation = true;
  11624. }
  11625. else if (this._interpolationConfig && this._inInterpolation &&
  11626. this._attemptStr(this._interpolationConfig.end)) {
  11627. parts.push(this._interpolationConfig.end);
  11628. this._inInterpolation = false;
  11629. }
  11630. else {
  11631. parts.push(this._readChar(true));
  11632. }
  11633. } while (!this._isTextEnd());
  11634. this._endToken([this._processCarriageReturns(parts.join(''))]);
  11635. };
  11636. _Tokenizer.prototype._isTextEnd = function () {
  11637. if (this._cursor.peek() === $LT || this._cursor.peek() === $EOF) {
  11638. return true;
  11639. }
  11640. if (this._tokenizeIcu && !this._inInterpolation) {
  11641. if (this.isExpansionFormStart()) {
  11642. // start of an expansion form
  11643. return true;
  11644. }
  11645. if (this._cursor.peek() === $RBRACE && this._isInExpansionCase()) {
  11646. // end of and expansion case
  11647. return true;
  11648. }
  11649. }
  11650. return false;
  11651. };
  11652. _Tokenizer.prototype._readUntil = function (char) {
  11653. var start = this._cursor.clone();
  11654. this._attemptUntilChar(char);
  11655. return this._cursor.getChars(start);
  11656. };
  11657. _Tokenizer.prototype._isInExpansionCase = function () {
  11658. return this._expansionCaseStack.length > 0 &&
  11659. this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
  11660. TokenType.EXPANSION_CASE_EXP_START;
  11661. };
  11662. _Tokenizer.prototype._isInExpansionForm = function () {
  11663. return this._expansionCaseStack.length > 0 &&
  11664. this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
  11665. TokenType.EXPANSION_FORM_START;
  11666. };
  11667. _Tokenizer.prototype.isExpansionFormStart = function () {
  11668. if (this._cursor.peek() !== $LBRACE) {
  11669. return false;
  11670. }
  11671. if (this._interpolationConfig) {
  11672. var start = this._cursor.clone();
  11673. var isInterpolation = this._attemptStr(this._interpolationConfig.start);
  11674. this._cursor = start;
  11675. return !isInterpolation;
  11676. }
  11677. return true;
  11678. };
  11679. return _Tokenizer;
  11680. }());
  11681. function isNotWhitespace(code) {
  11682. return !isWhitespace(code) || code === $EOF;
  11683. }
  11684. function isNameEnd(code) {
  11685. return isWhitespace(code) || code === $GT || code === $LT ||
  11686. code === $SLASH || code === $SQ || code === $DQ || code === $EQ ||
  11687. code === $EOF;
  11688. }
  11689. function isPrefixEnd(code) {
  11690. return (code < $a || $z < code) && (code < $A || $Z < code) &&
  11691. (code < $0 || code > $9);
  11692. }
  11693. function isDigitEntityEnd(code) {
  11694. return code == $SEMICOLON || code == $EOF || !isAsciiHexDigit(code);
  11695. }
  11696. function isNamedEntityEnd(code) {
  11697. return code == $SEMICOLON || code == $EOF || !isAsciiLetter(code);
  11698. }
  11699. function isExpansionCaseStart(peek) {
  11700. return peek !== $RBRACE;
  11701. }
  11702. function compareCharCodeCaseInsensitive(code1, code2) {
  11703. return toUpperCaseCharCode(code1) == toUpperCaseCharCode(code2);
  11704. }
  11705. function toUpperCaseCharCode(code) {
  11706. return code >= $a && code <= $z ? code - $a + $A : code;
  11707. }
  11708. function mergeTextTokens(srcTokens) {
  11709. var dstTokens = [];
  11710. var lastDstToken = undefined;
  11711. for (var i = 0; i < srcTokens.length; i++) {
  11712. var token = srcTokens[i];
  11713. if (lastDstToken && lastDstToken.type == TokenType.TEXT && token.type == TokenType.TEXT) {
  11714. lastDstToken.parts[0] += token.parts[0];
  11715. lastDstToken.sourceSpan.end = token.sourceSpan.end;
  11716. }
  11717. else {
  11718. lastDstToken = token;
  11719. dstTokens.push(lastDstToken);
  11720. }
  11721. }
  11722. return dstTokens;
  11723. }
  11724. var PlainCharacterCursor = /** @class */ (function () {
  11725. function PlainCharacterCursor(fileOrCursor, range) {
  11726. if (fileOrCursor instanceof PlainCharacterCursor) {
  11727. this.file = fileOrCursor.file;
  11728. this.input = fileOrCursor.input;
  11729. this.end = fileOrCursor.end;
  11730. var state = fileOrCursor.state;
  11731. // Note: avoid using `{...fileOrCursor.state}` here as that has a severe performance penalty.
  11732. // In ES5 bundles the object spread operator is translated into the `__assign` helper, which
  11733. // is not optimized by VMs as efficiently as a raw object literal. Since this constructor is
  11734. // called in tight loops, this difference matters.
  11735. this.state = {
  11736. peek: state.peek,
  11737. offset: state.offset,
  11738. line: state.line,
  11739. column: state.column,
  11740. };
  11741. }
  11742. else {
  11743. if (!range) {
  11744. throw new Error('Programming error: the range argument must be provided with a file argument.');
  11745. }
  11746. this.file = fileOrCursor;
  11747. this.input = fileOrCursor.content;
  11748. this.end = range.endPos;
  11749. this.state = {
  11750. peek: -1,
  11751. offset: range.startPos,
  11752. line: range.startLine,
  11753. column: range.startCol,
  11754. };
  11755. }
  11756. }
  11757. PlainCharacterCursor.prototype.clone = function () {
  11758. return new PlainCharacterCursor(this);
  11759. };
  11760. PlainCharacterCursor.prototype.peek = function () {
  11761. return this.state.peek;
  11762. };
  11763. PlainCharacterCursor.prototype.charsLeft = function () {
  11764. return this.end - this.state.offset;
  11765. };
  11766. PlainCharacterCursor.prototype.diff = function (other) {
  11767. return this.state.offset - other.state.offset;
  11768. };
  11769. PlainCharacterCursor.prototype.advance = function () {
  11770. this.advanceState(this.state);
  11771. };
  11772. PlainCharacterCursor.prototype.init = function () {
  11773. this.updatePeek(this.state);
  11774. };
  11775. PlainCharacterCursor.prototype.getSpan = function (start, leadingTriviaCodePoints) {
  11776. start = start || this;
  11777. var fullStart = start;
  11778. if (leadingTriviaCodePoints) {
  11779. while (this.diff(start) > 0 && leadingTriviaCodePoints.indexOf(start.peek()) !== -1) {
  11780. if (fullStart === start) {
  11781. start = start.clone();
  11782. }
  11783. start.advance();
  11784. }
  11785. }
  11786. var startLocation = this.locationFromCursor(start);
  11787. var endLocation = this.locationFromCursor(this);
  11788. var fullStartLocation = fullStart !== start ? this.locationFromCursor(fullStart) : startLocation;
  11789. return new ParseSourceSpan(startLocation, endLocation, fullStartLocation);
  11790. };
  11791. PlainCharacterCursor.prototype.getChars = function (start) {
  11792. return this.input.substring(start.state.offset, this.state.offset);
  11793. };
  11794. PlainCharacterCursor.prototype.charAt = function (pos) {
  11795. return this.input.charCodeAt(pos);
  11796. };
  11797. PlainCharacterCursor.prototype.advanceState = function (state) {
  11798. if (state.offset >= this.end) {
  11799. this.state = state;
  11800. throw new CursorError('Unexpected character "EOF"', this);
  11801. }
  11802. var currentChar = this.charAt(state.offset);
  11803. if (currentChar === $LF) {
  11804. state.line++;
  11805. state.column = 0;
  11806. }
  11807. else if (!isNewLine(currentChar)) {
  11808. state.column++;
  11809. }
  11810. state.offset++;
  11811. this.updatePeek(state);
  11812. };
  11813. PlainCharacterCursor.prototype.updatePeek = function (state) {
  11814. state.peek = state.offset >= this.end ? $EOF : this.charAt(state.offset);
  11815. };
  11816. PlainCharacterCursor.prototype.locationFromCursor = function (cursor) {
  11817. return new ParseLocation(cursor.file, cursor.state.offset, cursor.state.line, cursor.state.column);
  11818. };
  11819. return PlainCharacterCursor;
  11820. }());
  11821. var EscapedCharacterCursor = /** @class */ (function (_super) {
  11822. __extends(EscapedCharacterCursor, _super);
  11823. function EscapedCharacterCursor(fileOrCursor, range) {
  11824. var _this = this;
  11825. if (fileOrCursor instanceof EscapedCharacterCursor) {
  11826. _this = _super.call(this, fileOrCursor) || this;
  11827. _this.internalState = Object.assign({}, fileOrCursor.internalState);
  11828. }
  11829. else {
  11830. _this = _super.call(this, fileOrCursor, range) || this;
  11831. _this.internalState = _this.state;
  11832. }
  11833. return _this;
  11834. }
  11835. EscapedCharacterCursor.prototype.advance = function () {
  11836. this.state = this.internalState;
  11837. _super.prototype.advance.call(this);
  11838. this.processEscapeSequence();
  11839. };
  11840. EscapedCharacterCursor.prototype.init = function () {
  11841. _super.prototype.init.call(this);
  11842. this.processEscapeSequence();
  11843. };
  11844. EscapedCharacterCursor.prototype.clone = function () {
  11845. return new EscapedCharacterCursor(this);
  11846. };
  11847. EscapedCharacterCursor.prototype.getChars = function (start) {
  11848. var cursor = start.clone();
  11849. var chars = '';
  11850. while (cursor.internalState.offset < this.internalState.offset) {
  11851. chars += String.fromCodePoint(cursor.peek());
  11852. cursor.advance();
  11853. }
  11854. return chars;
  11855. };
  11856. /**
  11857. * Process the escape sequence that starts at the current position in the text.
  11858. *
  11859. * This method is called to ensure that `peek` has the unescaped value of escape sequences.
  11860. */
  11861. EscapedCharacterCursor.prototype.processEscapeSequence = function () {
  11862. var _this = this;
  11863. var peek = function () { return _this.internalState.peek; };
  11864. if (peek() === $BACKSLASH) {
  11865. // We have hit an escape sequence so we need the internal state to become independent
  11866. // of the external state.
  11867. this.internalState = Object.assign({}, this.state);
  11868. // Move past the backslash
  11869. this.advanceState(this.internalState);
  11870. // First check for standard control char sequences
  11871. if (peek() === $n) {
  11872. this.state.peek = $LF;
  11873. }
  11874. else if (peek() === $r) {
  11875. this.state.peek = $CR;
  11876. }
  11877. else if (peek() === $v) {
  11878. this.state.peek = $VTAB;
  11879. }
  11880. else if (peek() === $t) {
  11881. this.state.peek = $TAB;
  11882. }
  11883. else if (peek() === $b) {
  11884. this.state.peek = $BSPACE;
  11885. }
  11886. else if (peek() === $f) {
  11887. this.state.peek = $FF;
  11888. }
  11889. // Now consider more complex sequences
  11890. else if (peek() === $u) {
  11891. // Unicode code-point sequence
  11892. this.advanceState(this.internalState); // advance past the `u` char
  11893. if (peek() === $LBRACE) {
  11894. // Variable length Unicode, e.g. `\x{123}`
  11895. this.advanceState(this.internalState); // advance past the `{` char
  11896. // Advance past the variable number of hex digits until we hit a `}` char
  11897. var digitStart = this.clone();
  11898. var length = 0;
  11899. while (peek() !== $RBRACE) {
  11900. this.advanceState(this.internalState);
  11901. length++;
  11902. }
  11903. this.state.peek = this.decodeHexDigits(digitStart, length);
  11904. }
  11905. else {
  11906. // Fixed length Unicode, e.g. `\u1234`
  11907. var digitStart = this.clone();
  11908. this.advanceState(this.internalState);
  11909. this.advanceState(this.internalState);
  11910. this.advanceState(this.internalState);
  11911. this.state.peek = this.decodeHexDigits(digitStart, 4);
  11912. }
  11913. }
  11914. else if (peek() === $x) {
  11915. // Hex char code, e.g. `\x2F`
  11916. this.advanceState(this.internalState); // advance past the `x` char
  11917. var digitStart = this.clone();
  11918. this.advanceState(this.internalState);
  11919. this.state.peek = this.decodeHexDigits(digitStart, 2);
  11920. }
  11921. else if (isOctalDigit(peek())) {
  11922. // Octal char code, e.g. `\012`,
  11923. var octal = '';
  11924. var length = 0;
  11925. var previous = this.clone();
  11926. while (isOctalDigit(peek()) && length < 3) {
  11927. previous = this.clone();
  11928. octal += String.fromCodePoint(peek());
  11929. this.advanceState(this.internalState);
  11930. length++;
  11931. }
  11932. this.state.peek = parseInt(octal, 8);
  11933. // Backup one char
  11934. this.internalState = previous.internalState;
  11935. }
  11936. else if (isNewLine(this.internalState.peek)) {
  11937. // Line continuation `\` followed by a new line
  11938. this.advanceState(this.internalState); // advance over the newline
  11939. this.state = this.internalState;
  11940. }
  11941. else {
  11942. // If none of the `if` blocks were executed then we just have an escaped normal character.
  11943. // In that case we just, effectively, skip the backslash from the character.
  11944. this.state.peek = this.internalState.peek;
  11945. }
  11946. }
  11947. };
  11948. EscapedCharacterCursor.prototype.decodeHexDigits = function (start, length) {
  11949. var hex = this.input.substr(start.internalState.offset, length);
  11950. var charCode = parseInt(hex, 16);
  11951. if (!isNaN(charCode)) {
  11952. return charCode;
  11953. }
  11954. else {
  11955. start.state = start.internalState;
  11956. throw new CursorError('Invalid hexadecimal escape sequence', start);
  11957. }
  11958. };
  11959. return EscapedCharacterCursor;
  11960. }(PlainCharacterCursor));
  11961. var CursorError = /** @class */ (function () {
  11962. function CursorError(msg, cursor) {
  11963. this.msg = msg;
  11964. this.cursor = cursor;
  11965. }
  11966. return CursorError;
  11967. }());
  11968. var TreeError = /** @class */ (function (_super) {
  11969. __extends(TreeError, _super);
  11970. function TreeError(elementName, span, msg) {
  11971. var _this = _super.call(this, span, msg) || this;
  11972. _this.elementName = elementName;
  11973. return _this;
  11974. }
  11975. TreeError.create = function (elementName, span, msg) {
  11976. return new TreeError(elementName, span, msg);
  11977. };
  11978. return TreeError;
  11979. }(ParseError));
  11980. var ParseTreeResult = /** @class */ (function () {
  11981. function ParseTreeResult(rootNodes, errors) {
  11982. this.rootNodes = rootNodes;
  11983. this.errors = errors;
  11984. }
  11985. return ParseTreeResult;
  11986. }());
  11987. var Parser = /** @class */ (function () {
  11988. function Parser(getTagDefinition) {
  11989. this.getTagDefinition = getTagDefinition;
  11990. }
  11991. Parser.prototype.parse = function (source, url, options) {
  11992. var tokenizeResult = tokenize(source, url, this.getTagDefinition, options);
  11993. var parser = new _TreeBuilder(tokenizeResult.tokens, this.getTagDefinition);
  11994. parser.build();
  11995. return new ParseTreeResult(parser.rootNodes, tokenizeResult.errors.concat(parser.errors));
  11996. };
  11997. return Parser;
  11998. }());
  11999. var _TreeBuilder = /** @class */ (function () {
  12000. function _TreeBuilder(tokens, getTagDefinition) {
  12001. this.tokens = tokens;
  12002. this.getTagDefinition = getTagDefinition;
  12003. this._index = -1;
  12004. this._elementStack = [];
  12005. this.rootNodes = [];
  12006. this.errors = [];
  12007. this._advance();
  12008. }
  12009. _TreeBuilder.prototype.build = function () {
  12010. while (this._peek.type !== TokenType.EOF) {
  12011. if (this._peek.type === TokenType.TAG_OPEN_START ||
  12012. this._peek.type === TokenType.INCOMPLETE_TAG_OPEN) {
  12013. this._consumeStartTag(this._advance());
  12014. }
  12015. else if (this._peek.type === TokenType.TAG_CLOSE) {
  12016. this._consumeEndTag(this._advance());
  12017. }
  12018. else if (this._peek.type === TokenType.CDATA_START) {
  12019. this._closeVoidElement();
  12020. this._consumeCdata(this._advance());
  12021. }
  12022. else if (this._peek.type === TokenType.COMMENT_START) {
  12023. this._closeVoidElement();
  12024. this._consumeComment(this._advance());
  12025. }
  12026. else if (this._peek.type === TokenType.TEXT || this._peek.type === TokenType.RAW_TEXT ||
  12027. this._peek.type === TokenType.ESCAPABLE_RAW_TEXT) {
  12028. this._closeVoidElement();
  12029. this._consumeText(this._advance());
  12030. }
  12031. else if (this._peek.type === TokenType.EXPANSION_FORM_START) {
  12032. this._consumeExpansion(this._advance());
  12033. }
  12034. else {
  12035. // Skip all other tokens...
  12036. this._advance();
  12037. }
  12038. }
  12039. };
  12040. _TreeBuilder.prototype._advance = function () {
  12041. var prev = this._peek;
  12042. if (this._index < this.tokens.length - 1) {
  12043. // Note: there is always an EOF token at the end
  12044. this._index++;
  12045. }
  12046. this._peek = this.tokens[this._index];
  12047. return prev;
  12048. };
  12049. _TreeBuilder.prototype._advanceIf = function (type) {
  12050. if (this._peek.type === type) {
  12051. return this._advance();
  12052. }
  12053. return null;
  12054. };
  12055. _TreeBuilder.prototype._consumeCdata = function (_startToken) {
  12056. this._consumeText(this._advance());
  12057. this._advanceIf(TokenType.CDATA_END);
  12058. };
  12059. _TreeBuilder.prototype._consumeComment = function (token) {
  12060. var text = this._advanceIf(TokenType.RAW_TEXT);
  12061. this._advanceIf(TokenType.COMMENT_END);
  12062. var value = text != null ? text.parts[0].trim() : null;
  12063. this._addToParent(new Comment$1(value, token.sourceSpan));
  12064. };
  12065. _TreeBuilder.prototype._consumeExpansion = function (token) {
  12066. var switchValue = this._advance();
  12067. var type = this._advance();
  12068. var cases = [];
  12069. // read =
  12070. while (this._peek.type === TokenType.EXPANSION_CASE_VALUE) {
  12071. var expCase = this._parseExpansionCase();
  12072. if (!expCase)
  12073. return; // error
  12074. cases.push(expCase);
  12075. }
  12076. // read the final }
  12077. if (this._peek.type !== TokenType.EXPANSION_FORM_END) {
  12078. this.errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '}'."));
  12079. return;
  12080. }
  12081. var sourceSpan = new ParseSourceSpan(token.sourceSpan.start, this._peek.sourceSpan.end, token.sourceSpan.fullStart);
  12082. this._addToParent(new Expansion(switchValue.parts[0], type.parts[0], cases, sourceSpan, switchValue.sourceSpan));
  12083. this._advance();
  12084. };
  12085. _TreeBuilder.prototype._parseExpansionCase = function () {
  12086. var value = this._advance();
  12087. // read {
  12088. if (this._peek.type !== TokenType.EXPANSION_CASE_EXP_START) {
  12089. this.errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '{'."));
  12090. return null;
  12091. }
  12092. // read until }
  12093. var start = this._advance();
  12094. var exp = this._collectExpansionExpTokens(start);
  12095. if (!exp)
  12096. return null;
  12097. var end = this._advance();
  12098. exp.push(new Token(TokenType.EOF, [], end.sourceSpan));
  12099. // parse everything in between { and }
  12100. var expansionCaseParser = new _TreeBuilder(exp, this.getTagDefinition);
  12101. expansionCaseParser.build();
  12102. if (expansionCaseParser.errors.length > 0) {
  12103. this.errors = this.errors.concat(expansionCaseParser.errors);
  12104. return null;
  12105. }
  12106. var sourceSpan = new ParseSourceSpan(value.sourceSpan.start, end.sourceSpan.end, value.sourceSpan.fullStart);
  12107. var expSourceSpan = new ParseSourceSpan(start.sourceSpan.start, end.sourceSpan.end, start.sourceSpan.fullStart);
  12108. return new ExpansionCase(value.parts[0], expansionCaseParser.rootNodes, sourceSpan, value.sourceSpan, expSourceSpan);
  12109. };
  12110. _TreeBuilder.prototype._collectExpansionExpTokens = function (start) {
  12111. var exp = [];
  12112. var expansionFormStack = [TokenType.EXPANSION_CASE_EXP_START];
  12113. while (true) {
  12114. if (this._peek.type === TokenType.EXPANSION_FORM_START ||
  12115. this._peek.type === TokenType.EXPANSION_CASE_EXP_START) {
  12116. expansionFormStack.push(this._peek.type);
  12117. }
  12118. if (this._peek.type === TokenType.EXPANSION_CASE_EXP_END) {
  12119. if (lastOnStack(expansionFormStack, TokenType.EXPANSION_CASE_EXP_START)) {
  12120. expansionFormStack.pop();
  12121. if (expansionFormStack.length == 0)
  12122. return exp;
  12123. }
  12124. else {
  12125. this.errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
  12126. return null;
  12127. }
  12128. }
  12129. if (this._peek.type === TokenType.EXPANSION_FORM_END) {
  12130. if (lastOnStack(expansionFormStack, TokenType.EXPANSION_FORM_START)) {
  12131. expansionFormStack.pop();
  12132. }
  12133. else {
  12134. this.errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
  12135. return null;
  12136. }
  12137. }
  12138. if (this._peek.type === TokenType.EOF) {
  12139. this.errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'."));
  12140. return null;
  12141. }
  12142. exp.push(this._advance());
  12143. }
  12144. };
  12145. _TreeBuilder.prototype._consumeText = function (token) {
  12146. var text = token.parts[0];
  12147. if (text.length > 0 && text[0] == '\n') {
  12148. var parent = this._getParentElement();
  12149. if (parent != null && parent.children.length == 0 &&
  12150. this.getTagDefinition(parent.name).ignoreFirstLf) {
  12151. text = text.substring(1);
  12152. }
  12153. }
  12154. if (text.length > 0) {
  12155. this._addToParent(new Text$3(text, token.sourceSpan));
  12156. }
  12157. };
  12158. _TreeBuilder.prototype._closeVoidElement = function () {
  12159. var el = this._getParentElement();
  12160. if (el && this.getTagDefinition(el.name).isVoid) {
  12161. this._elementStack.pop();
  12162. }
  12163. };
  12164. _TreeBuilder.prototype._consumeStartTag = function (startTagToken) {
  12165. var _a = __read(startTagToken.parts, 2), prefix = _a[0], name = _a[1];
  12166. var attrs = [];
  12167. while (this._peek.type === TokenType.ATTR_NAME) {
  12168. attrs.push(this._consumeAttr(this._advance()));
  12169. }
  12170. var fullName = this._getElementFullName(prefix, name, this._getParentElement());
  12171. var selfClosing = false;
  12172. // Note: There could have been a tokenizer error
  12173. // so that we don't get a token for the end tag...
  12174. if (this._peek.type === TokenType.TAG_OPEN_END_VOID) {
  12175. this._advance();
  12176. selfClosing = true;
  12177. var tagDef = this.getTagDefinition(fullName);
  12178. if (!(tagDef.canSelfClose || getNsPrefix(fullName) !== null || tagDef.isVoid)) {
  12179. this.errors.push(TreeError.create(fullName, startTagToken.sourceSpan, "Only void and foreign elements can be self closed \"" + startTagToken.parts[1] + "\""));
  12180. }
  12181. }
  12182. else if (this._peek.type === TokenType.TAG_OPEN_END) {
  12183. this._advance();
  12184. selfClosing = false;
  12185. }
  12186. var end = this._peek.sourceSpan.fullStart;
  12187. var span = new ParseSourceSpan(startTagToken.sourceSpan.start, end, startTagToken.sourceSpan.fullStart);
  12188. // Create a separate `startSpan` because `span` will be modified when there is an `end` span.
  12189. var startSpan = new ParseSourceSpan(startTagToken.sourceSpan.start, end, startTagToken.sourceSpan.fullStart);
  12190. var el = new Element$1(fullName, attrs, [], span, startSpan, undefined);
  12191. this._pushElement(el);
  12192. if (selfClosing) {
  12193. // Elements that are self-closed have their `endSourceSpan` set to the full span, as the
  12194. // element start tag also represents the end tag.
  12195. this._popElement(fullName, span);
  12196. }
  12197. else if (startTagToken.type === TokenType.INCOMPLETE_TAG_OPEN) {
  12198. // We already know the opening tag is not complete, so it is unlikely it has a corresponding
  12199. // close tag. Let's optimistically parse it as a full element and emit an error.
  12200. this._popElement(fullName, null);
  12201. this.errors.push(TreeError.create(fullName, span, "Opening tag \"" + fullName + "\" not terminated."));
  12202. }
  12203. };
  12204. _TreeBuilder.prototype._pushElement = function (el) {
  12205. var parentEl = this._getParentElement();
  12206. if (parentEl && this.getTagDefinition(parentEl.name).isClosedByChild(el.name)) {
  12207. this._elementStack.pop();
  12208. }
  12209. this._addToParent(el);
  12210. this._elementStack.push(el);
  12211. };
  12212. _TreeBuilder.prototype._consumeEndTag = function (endTagToken) {
  12213. var fullName = this._getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement());
  12214. if (this.getTagDefinition(fullName).isVoid) {
  12215. this.errors.push(TreeError.create(fullName, endTagToken.sourceSpan, "Void elements do not have end tags \"" + endTagToken.parts[1] + "\""));
  12216. }
  12217. else if (!this._popElement(fullName, endTagToken.sourceSpan)) {
  12218. var errMsg = "Unexpected closing tag \"" + fullName + "\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags";
  12219. this.errors.push(TreeError.create(fullName, endTagToken.sourceSpan, errMsg));
  12220. }
  12221. };
  12222. /**
  12223. * Closes the nearest element with the tag name `fullName` in the parse tree.
  12224. * `endSourceSpan` is the span of the closing tag, or null if the element does
  12225. * not have a closing tag (for example, this happens when an incomplete
  12226. * opening tag is recovered).
  12227. */
  12228. _TreeBuilder.prototype._popElement = function (fullName, endSourceSpan) {
  12229. var unexpectedCloseTagDetected = false;
  12230. for (var stackIndex = this._elementStack.length - 1; stackIndex >= 0; stackIndex--) {
  12231. var el = this._elementStack[stackIndex];
  12232. if (el.name == fullName) {
  12233. // Record the parse span with the element that is being closed. Any elements that are
  12234. // removed from the element stack at this point are closed implicitly, so they won't get
  12235. // an end source span (as there is no explicit closing element).
  12236. el.endSourceSpan = endSourceSpan;
  12237. el.sourceSpan.end = endSourceSpan !== null ? endSourceSpan.end : el.sourceSpan.end;
  12238. this._elementStack.splice(stackIndex, this._elementStack.length - stackIndex);
  12239. return !unexpectedCloseTagDetected;
  12240. }
  12241. if (!this.getTagDefinition(el.name).closedByParent) {
  12242. // Note that we encountered an unexpected close tag but continue processing the element
  12243. // stack so we can assign an `endSourceSpan` if there is a corresponding start tag for this
  12244. // end tag in the stack.
  12245. unexpectedCloseTagDetected = true;
  12246. }
  12247. }
  12248. return false;
  12249. };
  12250. _TreeBuilder.prototype._consumeAttr = function (attrName) {
  12251. var fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]);
  12252. var end = attrName.sourceSpan.end;
  12253. var value = '';
  12254. var valueSpan = undefined;
  12255. if (this._peek.type === TokenType.ATTR_QUOTE) {
  12256. this._advance();
  12257. }
  12258. if (this._peek.type === TokenType.ATTR_VALUE) {
  12259. var valueToken = this._advance();
  12260. value = valueToken.parts[0];
  12261. end = valueToken.sourceSpan.end;
  12262. valueSpan = valueToken.sourceSpan;
  12263. }
  12264. if (this._peek.type === TokenType.ATTR_QUOTE) {
  12265. var quoteToken = this._advance();
  12266. end = quoteToken.sourceSpan.end;
  12267. }
  12268. var keySpan = new ParseSourceSpan(attrName.sourceSpan.start, attrName.sourceSpan.end);
  12269. return new Attribute(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end, attrName.sourceSpan.fullStart), keySpan, valueSpan);
  12270. };
  12271. _TreeBuilder.prototype._getParentElement = function () {
  12272. return this._elementStack.length > 0 ? this._elementStack[this._elementStack.length - 1] : null;
  12273. };
  12274. _TreeBuilder.prototype._addToParent = function (node) {
  12275. var parent = this._getParentElement();
  12276. if (parent != null) {
  12277. parent.children.push(node);
  12278. }
  12279. else {
  12280. this.rootNodes.push(node);
  12281. }
  12282. };
  12283. _TreeBuilder.prototype._getElementFullName = function (prefix, localName, parentElement) {
  12284. if (prefix === '') {
  12285. prefix = this.getTagDefinition(localName).implicitNamespacePrefix || '';
  12286. if (prefix === '' && parentElement != null) {
  12287. var parentTagName = splitNsName(parentElement.name)[1];
  12288. var parentTagDefinition = this.getTagDefinition(parentTagName);
  12289. if (!parentTagDefinition.preventNamespaceInheritance) {
  12290. prefix = getNsPrefix(parentElement.name);
  12291. }
  12292. }
  12293. }
  12294. return mergeNsAndName(prefix, localName);
  12295. };
  12296. return _TreeBuilder;
  12297. }());
  12298. function lastOnStack(stack, element) {
  12299. return stack.length > 0 && stack[stack.length - 1] === element;
  12300. }
  12301. var HtmlParser = /** @class */ (function (_super) {
  12302. __extends(HtmlParser, _super);
  12303. function HtmlParser() {
  12304. return _super.call(this, getHtmlTagDefinition) || this;
  12305. }
  12306. HtmlParser.prototype.parse = function (source, url, options) {
  12307. return _super.prototype.parse.call(this, source, url, options);
  12308. };
  12309. return HtmlParser;
  12310. }(Parser));
  12311. /**
  12312. * @license
  12313. * Copyright Google LLC All Rights Reserved.
  12314. *
  12315. * Use of this source code is governed by an MIT-style license that can be
  12316. * found in the LICENSE file at https://angular.io/license
  12317. */
  12318. var PRESERVE_WS_ATTR_NAME = 'ngPreserveWhitespaces';
  12319. var SKIP_WS_TRIM_TAGS = new Set(['pre', 'template', 'textarea', 'script', 'style']);
  12320. // Equivalent to \s with \u00a0 (non-breaking space) excluded.
  12321. // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
  12322. var WS_CHARS = ' \f\n\r\t\v\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';
  12323. var NO_WS_REGEXP = new RegExp("[^" + WS_CHARS + "]");
  12324. var WS_REPLACE_REGEXP = new RegExp("[" + WS_CHARS + "]{2,}", 'g');
  12325. function hasPreserveWhitespacesAttr(attrs) {
  12326. return attrs.some(function (attr) { return attr.name === PRESERVE_WS_ATTR_NAME; });
  12327. }
  12328. /**
  12329. * Angular Dart introduced &ngsp; as a placeholder for non-removable space, see:
  12330. * https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart#L25-L32
  12331. * In Angular Dart &ngsp; is converted to the 0xE500 PUA (Private Use Areas) unicode character
  12332. * and later on replaced by a space. We are re-implementing the same idea here.
  12333. */
  12334. function replaceNgsp(value) {
  12335. // lexer is replacing the &ngsp; pseudo-entity with NGSP_UNICODE
  12336. return value.replace(new RegExp(NGSP_UNICODE, 'g'), ' ');
  12337. }
  12338. /**
  12339. * This visitor can walk HTML parse tree and remove / trim text nodes using the following rules:
  12340. * - consider spaces, tabs and new lines as whitespace characters;
  12341. * - drop text nodes consisting of whitespace characters only;
  12342. * - for all other text nodes replace consecutive whitespace characters with one space;
  12343. * - convert &ngsp; pseudo-entity to a single space;
  12344. *
  12345. * Removal and trimming of whitespaces have positive performance impact (less code to generate
  12346. * while compiling templates, faster view creation). At the same time it can be "destructive"
  12347. * in some cases (whitespaces can influence layout). Because of the potential of breaking layout
  12348. * this visitor is not activated by default in Angular 5 and people need to explicitly opt-in for
  12349. * whitespace removal. The default option for whitespace removal will be revisited in Angular 6
  12350. * and might be changed to "on" by default.
  12351. */
  12352. var WhitespaceVisitor = /** @class */ (function () {
  12353. function WhitespaceVisitor() {
  12354. }
  12355. WhitespaceVisitor.prototype.visitElement = function (element, context) {
  12356. if (SKIP_WS_TRIM_TAGS.has(element.name) || hasPreserveWhitespacesAttr(element.attrs)) {
  12357. // don't descent into elements where we need to preserve whitespaces
  12358. // but still visit all attributes to eliminate one used as a market to preserve WS
  12359. return new Element$1(element.name, visitAll$1(this, element.attrs), element.children, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  12360. }
  12361. return new Element$1(element.name, element.attrs, visitAllWithSiblings(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  12362. };
  12363. WhitespaceVisitor.prototype.visitAttribute = function (attribute, context) {
  12364. return attribute.name !== PRESERVE_WS_ATTR_NAME ? attribute : null;
  12365. };
  12366. WhitespaceVisitor.prototype.visitText = function (text, context) {
  12367. var isNotBlank = text.value.match(NO_WS_REGEXP);
  12368. var hasExpansionSibling = context &&
  12369. (context.prev instanceof Expansion || context.next instanceof Expansion);
  12370. if (isNotBlank || hasExpansionSibling) {
  12371. return new Text$3(replaceNgsp(text.value).replace(WS_REPLACE_REGEXP, ' '), text.sourceSpan, text.i18n);
  12372. }
  12373. return null;
  12374. };
  12375. WhitespaceVisitor.prototype.visitComment = function (comment, context) {
  12376. return comment;
  12377. };
  12378. WhitespaceVisitor.prototype.visitExpansion = function (expansion, context) {
  12379. return expansion;
  12380. };
  12381. WhitespaceVisitor.prototype.visitExpansionCase = function (expansionCase, context) {
  12382. return expansionCase;
  12383. };
  12384. return WhitespaceVisitor;
  12385. }());
  12386. function removeWhitespaces(htmlAstWithErrors) {
  12387. return new ParseTreeResult(visitAll$1(new WhitespaceVisitor(), htmlAstWithErrors.rootNodes), htmlAstWithErrors.errors);
  12388. }
  12389. function visitAllWithSiblings(visitor, nodes) {
  12390. var result = [];
  12391. nodes.forEach(function (ast, i) {
  12392. var context = { prev: nodes[i - 1], next: nodes[i + 1] };
  12393. var astResult = ast.visit(visitor, context);
  12394. if (astResult) {
  12395. result.push(astResult);
  12396. }
  12397. });
  12398. return result;
  12399. }
  12400. // http://cldr.unicode.org/index/cldr-spec/plural-rules
  12401. var PLURAL_CASES = ['zero', 'one', 'two', 'few', 'many', 'other'];
  12402. /**
  12403. * Expands special forms into elements.
  12404. *
  12405. * For example,
  12406. *
  12407. * ```
  12408. * { messages.length, plural,
  12409. * =0 {zero}
  12410. * =1 {one}
  12411. * other {more than one}
  12412. * }
  12413. * ```
  12414. *
  12415. * will be expanded into
  12416. *
  12417. * ```
  12418. * <ng-container [ngPlural]="messages.length">
  12419. * <ng-template ngPluralCase="=0">zero</ng-template>
  12420. * <ng-template ngPluralCase="=1">one</ng-template>
  12421. * <ng-template ngPluralCase="other">more than one</ng-template>
  12422. * </ng-container>
  12423. * ```
  12424. */
  12425. function expandNodes(nodes) {
  12426. var expander = new _Expander();
  12427. return new ExpansionResult(visitAll$1(expander, nodes), expander.isExpanded, expander.errors);
  12428. }
  12429. var ExpansionResult = /** @class */ (function () {
  12430. function ExpansionResult(nodes, expanded, errors) {
  12431. this.nodes = nodes;
  12432. this.expanded = expanded;
  12433. this.errors = errors;
  12434. }
  12435. return ExpansionResult;
  12436. }());
  12437. var ExpansionError = /** @class */ (function (_super) {
  12438. __extends(ExpansionError, _super);
  12439. function ExpansionError(span, errorMsg) {
  12440. return _super.call(this, span, errorMsg) || this;
  12441. }
  12442. return ExpansionError;
  12443. }(ParseError));
  12444. /**
  12445. * Expand expansion forms (plural, select) to directives
  12446. *
  12447. * @internal
  12448. */
  12449. var _Expander = /** @class */ (function () {
  12450. function _Expander() {
  12451. this.isExpanded = false;
  12452. this.errors = [];
  12453. }
  12454. _Expander.prototype.visitElement = function (element, context) {
  12455. return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan);
  12456. };
  12457. _Expander.prototype.visitAttribute = function (attribute, context) {
  12458. return attribute;
  12459. };
  12460. _Expander.prototype.visitText = function (text, context) {
  12461. return text;
  12462. };
  12463. _Expander.prototype.visitComment = function (comment, context) {
  12464. return comment;
  12465. };
  12466. _Expander.prototype.visitExpansion = function (icu, context) {
  12467. this.isExpanded = true;
  12468. return icu.type == 'plural' ? _expandPluralForm(icu, this.errors) :
  12469. _expandDefaultForm(icu, this.errors);
  12470. };
  12471. _Expander.prototype.visitExpansionCase = function (icuCase, context) {
  12472. throw new Error('Should not be reached');
  12473. };
  12474. return _Expander;
  12475. }());
  12476. // Plural forms are expanded to `NgPlural` and `NgPluralCase`s
  12477. function _expandPluralForm(ast, errors) {
  12478. var children = ast.cases.map(function (c) {
  12479. if (PLURAL_CASES.indexOf(c.value) == -1 && !c.value.match(/^=\d+$/)) {
  12480. errors.push(new ExpansionError(c.valueSourceSpan, "Plural cases should be \"=<number>\" or one of " + PLURAL_CASES.join(', ')));
  12481. }
  12482. var expansionResult = expandNodes(c.expression);
  12483. errors.push.apply(errors, __spreadArray([], __read(expansionResult.errors)));
  12484. return new Element$1("ng-template", [new Attribute('ngPluralCase', "" + c.value, c.valueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  12485. });
  12486. var switchAttr = new Attribute('[ngPlural]', ast.switchValue, ast.switchValueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */);
  12487. return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
  12488. }
  12489. // ICU messages (excluding plural form) are expanded to `NgSwitch` and `NgSwitchCase`s
  12490. function _expandDefaultForm(ast, errors) {
  12491. var children = ast.cases.map(function (c) {
  12492. var expansionResult = expandNodes(c.expression);
  12493. errors.push.apply(errors, __spreadArray([], __read(expansionResult.errors)));
  12494. if (c.value === 'other') {
  12495. // other is the default case when no values match
  12496. return new Element$1("ng-template", [new Attribute('ngSwitchDefault', '', c.valueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  12497. }
  12498. return new Element$1("ng-template", [new Attribute('ngSwitchCase', "" + c.value, c.valueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
  12499. });
  12500. var switchAttr = new Attribute('[ngSwitch]', ast.switchValue, ast.switchValueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */);
  12501. return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
  12502. }
  12503. var _a;
  12504. /**
  12505. * @license
  12506. * Copyright Google LLC All Rights Reserved.
  12507. *
  12508. * Use of this source code is governed by an MIT-style license that can be
  12509. * found in the LICENSE file at https://angular.io/license
  12510. */
  12511. /**
  12512. * A segment of text within the template.
  12513. */
  12514. var TextAst = /** @class */ (function () {
  12515. function TextAst(value, ngContentIndex, sourceSpan) {
  12516. this.value = value;
  12517. this.ngContentIndex = ngContentIndex;
  12518. this.sourceSpan = sourceSpan;
  12519. }
  12520. TextAst.prototype.visit = function (visitor, context) {
  12521. return visitor.visitText(this, context);
  12522. };
  12523. return TextAst;
  12524. }());
  12525. /**
  12526. * A bound expression within the text of a template.
  12527. */
  12528. var BoundTextAst = /** @class */ (function () {
  12529. function BoundTextAst(value, ngContentIndex, sourceSpan) {
  12530. this.value = value;
  12531. this.ngContentIndex = ngContentIndex;
  12532. this.sourceSpan = sourceSpan;
  12533. }
  12534. BoundTextAst.prototype.visit = function (visitor, context) {
  12535. return visitor.visitBoundText(this, context);
  12536. };
  12537. return BoundTextAst;
  12538. }());
  12539. /**
  12540. * A plain attribute on an element.
  12541. */
  12542. var AttrAst = /** @class */ (function () {
  12543. function AttrAst(name, value, sourceSpan) {
  12544. this.name = name;
  12545. this.value = value;
  12546. this.sourceSpan = sourceSpan;
  12547. }
  12548. AttrAst.prototype.visit = function (visitor, context) {
  12549. return visitor.visitAttr(this, context);
  12550. };
  12551. return AttrAst;
  12552. }());
  12553. var BoundPropertyMapping = (_a = {},
  12554. _a[4 /* Animation */] = 4 /* Animation */,
  12555. _a[1 /* Attribute */] = 1 /* Attribute */,
  12556. _a[2 /* Class */] = 2 /* Class */,
  12557. _a[0 /* Property */] = 0 /* Property */,
  12558. _a[3 /* Style */] = 3 /* Style */,
  12559. _a);
  12560. /**
  12561. * A binding for an element property (e.g. `[property]="expression"`) or an animation trigger (e.g.
  12562. * `[@trigger]="stateExp"`)
  12563. */
  12564. var BoundElementPropertyAst = /** @class */ (function () {
  12565. function BoundElementPropertyAst(name, type, securityContext, value, unit, sourceSpan) {
  12566. this.name = name;
  12567. this.type = type;
  12568. this.securityContext = securityContext;
  12569. this.value = value;
  12570. this.unit = unit;
  12571. this.sourceSpan = sourceSpan;
  12572. this.isAnimation = this.type === 4 /* Animation */;
  12573. }
  12574. BoundElementPropertyAst.fromBoundProperty = function (prop) {
  12575. var type = BoundPropertyMapping[prop.type];
  12576. return new BoundElementPropertyAst(prop.name, type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan);
  12577. };
  12578. BoundElementPropertyAst.prototype.visit = function (visitor, context) {
  12579. return visitor.visitElementProperty(this, context);
  12580. };
  12581. return BoundElementPropertyAst;
  12582. }());
  12583. /**
  12584. * A binding for an element event (e.g. `(event)="handler()"`) or an animation trigger event (e.g.
  12585. * `(@trigger.phase)="callback($event)"`).
  12586. */
  12587. var BoundEventAst = /** @class */ (function () {
  12588. function BoundEventAst(name, target, phase, handler, sourceSpan, handlerSpan) {
  12589. this.name = name;
  12590. this.target = target;
  12591. this.phase = phase;
  12592. this.handler = handler;
  12593. this.sourceSpan = sourceSpan;
  12594. this.handlerSpan = handlerSpan;
  12595. this.fullName = BoundEventAst.calcFullName(this.name, this.target, this.phase);
  12596. this.isAnimation = !!this.phase;
  12597. }
  12598. BoundEventAst.calcFullName = function (name, target, phase) {
  12599. if (target) {
  12600. return target + ":" + name;
  12601. }
  12602. if (phase) {
  12603. return "@" + name + "." + phase;
  12604. }
  12605. return name;
  12606. };
  12607. BoundEventAst.fromParsedEvent = function (event) {
  12608. var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
  12609. var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
  12610. return new BoundEventAst(event.name, target, phase, event.handler, event.sourceSpan, event.handlerSpan);
  12611. };
  12612. BoundEventAst.prototype.visit = function (visitor, context) {
  12613. return visitor.visitEvent(this, context);
  12614. };
  12615. return BoundEventAst;
  12616. }());
  12617. /**
  12618. * A reference declaration on an element (e.g. `let someName="expression"`).
  12619. */
  12620. var ReferenceAst = /** @class */ (function () {
  12621. function ReferenceAst(name, value, originalValue, sourceSpan) {
  12622. this.name = name;
  12623. this.value = value;
  12624. this.originalValue = originalValue;
  12625. this.sourceSpan = sourceSpan;
  12626. }
  12627. ReferenceAst.prototype.visit = function (visitor, context) {
  12628. return visitor.visitReference(this, context);
  12629. };
  12630. return ReferenceAst;
  12631. }());
  12632. /**
  12633. * A variable declaration on a <ng-template> (e.g. `var-someName="someLocalName"`).
  12634. */
  12635. var VariableAst = /** @class */ (function () {
  12636. function VariableAst(name, value, sourceSpan, valueSpan) {
  12637. this.name = name;
  12638. this.value = value;
  12639. this.sourceSpan = sourceSpan;
  12640. this.valueSpan = valueSpan;
  12641. }
  12642. VariableAst.fromParsedVariable = function (v) {
  12643. return new VariableAst(v.name, v.value, v.sourceSpan, v.valueSpan);
  12644. };
  12645. VariableAst.prototype.visit = function (visitor, context) {
  12646. return visitor.visitVariable(this, context);
  12647. };
  12648. return VariableAst;
  12649. }());
  12650. /**
  12651. * An element declaration in a template.
  12652. */
  12653. var ElementAst = /** @class */ (function () {
  12654. function ElementAst(name, attrs, inputs, outputs, references, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan, endSourceSpan) {
  12655. this.name = name;
  12656. this.attrs = attrs;
  12657. this.inputs = inputs;
  12658. this.outputs = outputs;
  12659. this.references = references;
  12660. this.directives = directives;
  12661. this.providers = providers;
  12662. this.hasViewContainer = hasViewContainer;
  12663. this.queryMatches = queryMatches;
  12664. this.children = children;
  12665. this.ngContentIndex = ngContentIndex;
  12666. this.sourceSpan = sourceSpan;
  12667. this.endSourceSpan = endSourceSpan;
  12668. }
  12669. ElementAst.prototype.visit = function (visitor, context) {
  12670. return visitor.visitElement(this, context);
  12671. };
  12672. return ElementAst;
  12673. }());
  12674. /**
  12675. * A `<ng-template>` element included in an Angular template.
  12676. */
  12677. var EmbeddedTemplateAst = /** @class */ (function () {
  12678. function EmbeddedTemplateAst(attrs, outputs, references, variables, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan) {
  12679. this.attrs = attrs;
  12680. this.outputs = outputs;
  12681. this.references = references;
  12682. this.variables = variables;
  12683. this.directives = directives;
  12684. this.providers = providers;
  12685. this.hasViewContainer = hasViewContainer;
  12686. this.queryMatches = queryMatches;
  12687. this.children = children;
  12688. this.ngContentIndex = ngContentIndex;
  12689. this.sourceSpan = sourceSpan;
  12690. }
  12691. EmbeddedTemplateAst.prototype.visit = function (visitor, context) {
  12692. return visitor.visitEmbeddedTemplate(this, context);
  12693. };
  12694. return EmbeddedTemplateAst;
  12695. }());
  12696. /**
  12697. * A directive property with a bound value (e.g. `*ngIf="condition").
  12698. */
  12699. var BoundDirectivePropertyAst = /** @class */ (function () {
  12700. function BoundDirectivePropertyAst(directiveName, templateName, value, sourceSpan) {
  12701. this.directiveName = directiveName;
  12702. this.templateName = templateName;
  12703. this.value = value;
  12704. this.sourceSpan = sourceSpan;
  12705. }
  12706. BoundDirectivePropertyAst.prototype.visit = function (visitor, context) {
  12707. return visitor.visitDirectiveProperty(this, context);
  12708. };
  12709. return BoundDirectivePropertyAst;
  12710. }());
  12711. /**
  12712. * A directive declared on an element.
  12713. */
  12714. var DirectiveAst = /** @class */ (function () {
  12715. function DirectiveAst(directive, inputs, hostProperties, hostEvents, contentQueryStartId, sourceSpan) {
  12716. this.directive = directive;
  12717. this.inputs = inputs;
  12718. this.hostProperties = hostProperties;
  12719. this.hostEvents = hostEvents;
  12720. this.contentQueryStartId = contentQueryStartId;
  12721. this.sourceSpan = sourceSpan;
  12722. }
  12723. DirectiveAst.prototype.visit = function (visitor, context) {
  12724. return visitor.visitDirective(this, context);
  12725. };
  12726. return DirectiveAst;
  12727. }());
  12728. /**
  12729. * A provider declared on an element
  12730. */
  12731. var ProviderAst = /** @class */ (function () {
  12732. function ProviderAst(token, multiProvider, eager, providers, providerType, lifecycleHooks, sourceSpan, isModule) {
  12733. this.token = token;
  12734. this.multiProvider = multiProvider;
  12735. this.eager = eager;
  12736. this.providers = providers;
  12737. this.providerType = providerType;
  12738. this.lifecycleHooks = lifecycleHooks;
  12739. this.sourceSpan = sourceSpan;
  12740. this.isModule = isModule;
  12741. }
  12742. ProviderAst.prototype.visit = function (visitor, context) {
  12743. // No visit method in the visitor for now...
  12744. return null;
  12745. };
  12746. return ProviderAst;
  12747. }());
  12748. (function (ProviderAstType) {
  12749. ProviderAstType[ProviderAstType["PublicService"] = 0] = "PublicService";
  12750. ProviderAstType[ProviderAstType["PrivateService"] = 1] = "PrivateService";
  12751. ProviderAstType[ProviderAstType["Component"] = 2] = "Component";
  12752. ProviderAstType[ProviderAstType["Directive"] = 3] = "Directive";
  12753. ProviderAstType[ProviderAstType["Builtin"] = 4] = "Builtin";
  12754. })(exports.ProviderAstType || (exports.ProviderAstType = {}));
  12755. /**
  12756. * Position where content is to be projected (instance of `<ng-content>` in a template).
  12757. */
  12758. var NgContentAst = /** @class */ (function () {
  12759. function NgContentAst(index, ngContentIndex, sourceSpan) {
  12760. this.index = index;
  12761. this.ngContentIndex = ngContentIndex;
  12762. this.sourceSpan = sourceSpan;
  12763. }
  12764. NgContentAst.prototype.visit = function (visitor, context) {
  12765. return visitor.visitNgContent(this, context);
  12766. };
  12767. return NgContentAst;
  12768. }());
  12769. /**
  12770. * A visitor that accepts each node but doesn't do anything. It is intended to be used
  12771. * as the base class for a visitor that is only interested in a subset of the node types.
  12772. */
  12773. var NullTemplateVisitor = /** @class */ (function () {
  12774. function NullTemplateVisitor() {
  12775. }
  12776. NullTemplateVisitor.prototype.visitNgContent = function (ast, context) { };
  12777. NullTemplateVisitor.prototype.visitEmbeddedTemplate = function (ast, context) { };
  12778. NullTemplateVisitor.prototype.visitElement = function (ast, context) { };
  12779. NullTemplateVisitor.prototype.visitReference = function (ast, context) { };
  12780. NullTemplateVisitor.prototype.visitVariable = function (ast, context) { };
  12781. NullTemplateVisitor.prototype.visitEvent = function (ast, context) { };
  12782. NullTemplateVisitor.prototype.visitElementProperty = function (ast, context) { };
  12783. NullTemplateVisitor.prototype.visitAttr = function (ast, context) { };
  12784. NullTemplateVisitor.prototype.visitBoundText = function (ast, context) { };
  12785. NullTemplateVisitor.prototype.visitText = function (ast, context) { };
  12786. NullTemplateVisitor.prototype.visitDirective = function (ast, context) { };
  12787. NullTemplateVisitor.prototype.visitDirectiveProperty = function (ast, context) { };
  12788. return NullTemplateVisitor;
  12789. }());
  12790. /**
  12791. * Base class that can be used to build a visitor that visits each node
  12792. * in an template ast recursively.
  12793. */
  12794. var RecursiveTemplateAstVisitor = /** @class */ (function (_super) {
  12795. __extends(RecursiveTemplateAstVisitor, _super);
  12796. function RecursiveTemplateAstVisitor() {
  12797. return _super.call(this) || this;
  12798. }
  12799. // Nodes with children
  12800. RecursiveTemplateAstVisitor.prototype.visitEmbeddedTemplate = function (ast, context) {
  12801. return this.visitChildren(context, function (visit) {
  12802. visit(ast.attrs);
  12803. visit(ast.references);
  12804. visit(ast.variables);
  12805. visit(ast.directives);
  12806. visit(ast.providers);
  12807. visit(ast.children);
  12808. });
  12809. };
  12810. RecursiveTemplateAstVisitor.prototype.visitElement = function (ast, context) {
  12811. return this.visitChildren(context, function (visit) {
  12812. visit(ast.attrs);
  12813. visit(ast.inputs);
  12814. visit(ast.outputs);
  12815. visit(ast.references);
  12816. visit(ast.directives);
  12817. visit(ast.providers);
  12818. visit(ast.children);
  12819. });
  12820. };
  12821. RecursiveTemplateAstVisitor.prototype.visitDirective = function (ast, context) {
  12822. return this.visitChildren(context, function (visit) {
  12823. visit(ast.inputs);
  12824. visit(ast.hostProperties);
  12825. visit(ast.hostEvents);
  12826. });
  12827. };
  12828. RecursiveTemplateAstVisitor.prototype.visitChildren = function (context, cb) {
  12829. var results = [];
  12830. var t = this;
  12831. function visit(children) {
  12832. if (children && children.length)
  12833. results.push(templateVisitAll(t, children, context));
  12834. }
  12835. cb(visit);
  12836. return Array.prototype.concat.apply([], results);
  12837. };
  12838. return RecursiveTemplateAstVisitor;
  12839. }(NullTemplateVisitor));
  12840. /**
  12841. * Visit every node in a list of {@link TemplateAst}s with the given {@link TemplateAstVisitor}.
  12842. */
  12843. function templateVisitAll(visitor, asts, context) {
  12844. if (context === void 0) { context = null; }
  12845. var result = [];
  12846. var visit = visitor.visit ?
  12847. function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } :
  12848. function (ast) { return ast.visit(visitor, context); };
  12849. asts.forEach(function (ast) {
  12850. var astResult = visit(ast);
  12851. if (astResult) {
  12852. result.push(astResult);
  12853. }
  12854. });
  12855. return result;
  12856. }
  12857. var ProviderError = /** @class */ (function (_super) {
  12858. __extends(ProviderError, _super);
  12859. function ProviderError(message, span) {
  12860. return _super.call(this, span, message) || this;
  12861. }
  12862. return ProviderError;
  12863. }(ParseError));
  12864. var ProviderViewContext = /** @class */ (function () {
  12865. function ProviderViewContext(reflector, component) {
  12866. var _this = this;
  12867. this.reflector = reflector;
  12868. this.component = component;
  12869. this.errors = [];
  12870. this.viewQueries = _getViewQueries(component);
  12871. this.viewProviders = new Map();
  12872. component.viewProviders.forEach(function (provider) {
  12873. if (_this.viewProviders.get(tokenReference(provider.token)) == null) {
  12874. _this.viewProviders.set(tokenReference(provider.token), true);
  12875. }
  12876. });
  12877. }
  12878. return ProviderViewContext;
  12879. }());
  12880. var ProviderElementContext = /** @class */ (function () {
  12881. function ProviderElementContext(viewContext, _parent, _isViewRoot, _directiveAsts, attrs, refs, isTemplate, contentQueryStartId, _sourceSpan) {
  12882. var _this = this;
  12883. this.viewContext = viewContext;
  12884. this._parent = _parent;
  12885. this._isViewRoot = _isViewRoot;
  12886. this._directiveAsts = _directiveAsts;
  12887. this._sourceSpan = _sourceSpan;
  12888. this._transformedProviders = new Map();
  12889. this._seenProviders = new Map();
  12890. this._queriedTokens = new Map();
  12891. this.transformedHasViewContainer = false;
  12892. this._attrs = {};
  12893. attrs.forEach(function (attrAst) { return _this._attrs[attrAst.name] = attrAst.value; });
  12894. var directivesMeta = _directiveAsts.map(function (directiveAst) { return directiveAst.directive; });
  12895. this._allProviders =
  12896. _resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors);
  12897. this._contentQueries = _getContentQueries(contentQueryStartId, directivesMeta);
  12898. Array.from(this._allProviders.values()).forEach(function (provider) {
  12899. _this._addQueryReadsTo(provider.token, provider.token, _this._queriedTokens);
  12900. });
  12901. if (isTemplate) {
  12902. var templateRefId = createTokenForExternalReference(this.viewContext.reflector, Identifiers$1.TemplateRef);
  12903. this._addQueryReadsTo(templateRefId, templateRefId, this._queriedTokens);
  12904. }
  12905. refs.forEach(function (refAst) {
  12906. var defaultQueryValue = refAst.value ||
  12907. createTokenForExternalReference(_this.viewContext.reflector, Identifiers$1.ElementRef);
  12908. _this._addQueryReadsTo({ value: refAst.name }, defaultQueryValue, _this._queriedTokens);
  12909. });
  12910. if (this._queriedTokens.get(this.viewContext.reflector.resolveExternalReference(Identifiers$1.ViewContainerRef))) {
  12911. this.transformedHasViewContainer = true;
  12912. }
  12913. // create the providers that we know are eager first
  12914. Array.from(this._allProviders.values()).forEach(function (provider) {
  12915. var eager = provider.eager || _this._queriedTokens.get(tokenReference(provider.token));
  12916. if (eager) {
  12917. _this._getOrCreateLocalProvider(provider.providerType, provider.token, true);
  12918. }
  12919. });
  12920. }
  12921. ProviderElementContext.prototype.afterElement = function () {
  12922. var _this = this;
  12923. // collect lazy providers
  12924. Array.from(this._allProviders.values()).forEach(function (provider) {
  12925. _this._getOrCreateLocalProvider(provider.providerType, provider.token, false);
  12926. });
  12927. };
  12928. Object.defineProperty(ProviderElementContext.prototype, "transformProviders", {
  12929. get: function () {
  12930. // Note: Maps keep their insertion order.
  12931. var lazyProviders = [];
  12932. var eagerProviders = [];
  12933. this._transformedProviders.forEach(function (provider) {
  12934. if (provider.eager) {
  12935. eagerProviders.push(provider);
  12936. }
  12937. else {
  12938. lazyProviders.push(provider);
  12939. }
  12940. });
  12941. return lazyProviders.concat(eagerProviders);
  12942. },
  12943. enumerable: false,
  12944. configurable: true
  12945. });
  12946. Object.defineProperty(ProviderElementContext.prototype, "transformedDirectiveAsts", {
  12947. get: function () {
  12948. var sortedProviderTypes = this.transformProviders.map(function (provider) { return provider.token.identifier; });
  12949. var sortedDirectives = this._directiveAsts.slice();
  12950. sortedDirectives.sort(function (dir1, dir2) { return sortedProviderTypes.indexOf(dir1.directive.type) -
  12951. sortedProviderTypes.indexOf(dir2.directive.type); });
  12952. return sortedDirectives;
  12953. },
  12954. enumerable: false,
  12955. configurable: true
  12956. });
  12957. Object.defineProperty(ProviderElementContext.prototype, "queryMatches", {
  12958. get: function () {
  12959. var allMatches = [];
  12960. this._queriedTokens.forEach(function (matches) {
  12961. allMatches.push.apply(allMatches, __spreadArray([], __read(matches)));
  12962. });
  12963. return allMatches;
  12964. },
  12965. enumerable: false,
  12966. configurable: true
  12967. });
  12968. ProviderElementContext.prototype._addQueryReadsTo = function (token, defaultValue, queryReadTokens) {
  12969. this._getQueriesFor(token).forEach(function (query) {
  12970. var queryValue = query.meta.read || defaultValue;
  12971. var tokenRef = tokenReference(queryValue);
  12972. var queryMatches = queryReadTokens.get(tokenRef);
  12973. if (!queryMatches) {
  12974. queryMatches = [];
  12975. queryReadTokens.set(tokenRef, queryMatches);
  12976. }
  12977. queryMatches.push({ queryId: query.queryId, value: queryValue });
  12978. });
  12979. };
  12980. ProviderElementContext.prototype._getQueriesFor = function (token) {
  12981. var result = [];
  12982. var currentEl = this;
  12983. var distance = 0;
  12984. var queries;
  12985. while (currentEl !== null) {
  12986. queries = currentEl._contentQueries.get(tokenReference(token));
  12987. if (queries) {
  12988. result.push.apply(result, __spreadArray([], __read(queries.filter(function (query) { return query.meta.descendants || distance <= 1; }))));
  12989. }
  12990. if (currentEl._directiveAsts.length > 0) {
  12991. distance++;
  12992. }
  12993. currentEl = currentEl._parent;
  12994. }
  12995. queries = this.viewContext.viewQueries.get(tokenReference(token));
  12996. if (queries) {
  12997. result.push.apply(result, __spreadArray([], __read(queries)));
  12998. }
  12999. return result;
  13000. };
  13001. ProviderElementContext.prototype._getOrCreateLocalProvider = function (requestingProviderType, token, eager) {
  13002. var _this = this;
  13003. var resolvedProvider = this._allProviders.get(tokenReference(token));
  13004. if (!resolvedProvider ||
  13005. ((requestingProviderType === exports.ProviderAstType.Directive ||
  13006. requestingProviderType === exports.ProviderAstType.PublicService) &&
  13007. resolvedProvider.providerType === exports.ProviderAstType.PrivateService) ||
  13008. ((requestingProviderType === exports.ProviderAstType.PrivateService ||
  13009. requestingProviderType === exports.ProviderAstType.PublicService) &&
  13010. resolvedProvider.providerType === exports.ProviderAstType.Builtin)) {
  13011. return null;
  13012. }
  13013. var transformedProviderAst = this._transformedProviders.get(tokenReference(token));
  13014. if (transformedProviderAst) {
  13015. return transformedProviderAst;
  13016. }
  13017. if (this._seenProviders.get(tokenReference(token)) != null) {
  13018. this.viewContext.errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), this._sourceSpan));
  13019. return null;
  13020. }
  13021. this._seenProviders.set(tokenReference(token), true);
  13022. var transformedProviders = resolvedProvider.providers.map(function (provider) {
  13023. var transformedUseValue = provider.useValue;
  13024. var transformedUseExisting = provider.useExisting;
  13025. var transformedDeps = undefined;
  13026. if (provider.useExisting != null) {
  13027. var existingDiDep = _this._getDependency(resolvedProvider.providerType, { token: provider.useExisting }, eager);
  13028. if (existingDiDep.token != null) {
  13029. transformedUseExisting = existingDiDep.token;
  13030. }
  13031. else {
  13032. transformedUseExisting = null;
  13033. transformedUseValue = existingDiDep.value;
  13034. }
  13035. }
  13036. else if (provider.useFactory) {
  13037. var deps = provider.deps || provider.useFactory.diDeps;
  13038. transformedDeps =
  13039. deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); });
  13040. }
  13041. else if (provider.useClass) {
  13042. var deps = provider.deps || provider.useClass.diDeps;
  13043. transformedDeps =
  13044. deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); });
  13045. }
  13046. return _transformProvider(provider, {
  13047. useExisting: transformedUseExisting,
  13048. useValue: transformedUseValue,
  13049. deps: transformedDeps
  13050. });
  13051. });
  13052. transformedProviderAst =
  13053. _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
  13054. this._transformedProviders.set(tokenReference(token), transformedProviderAst);
  13055. return transformedProviderAst;
  13056. };
  13057. ProviderElementContext.prototype._getLocalDependency = function (requestingProviderType, dep, eager) {
  13058. if (eager === void 0) { eager = false; }
  13059. if (dep.isAttribute) {
  13060. var attrValue = this._attrs[dep.token.value];
  13061. return { isValue: true, value: attrValue == null ? null : attrValue };
  13062. }
  13063. if (dep.token != null) {
  13064. // access builtints
  13065. if ((requestingProviderType === exports.ProviderAstType.Directive ||
  13066. requestingProviderType === exports.ProviderAstType.Component)) {
  13067. if (tokenReference(dep.token) ===
  13068. this.viewContext.reflector.resolveExternalReference(Identifiers$1.Renderer) ||
  13069. tokenReference(dep.token) ===
  13070. this.viewContext.reflector.resolveExternalReference(Identifiers$1.ElementRef) ||
  13071. tokenReference(dep.token) ===
  13072. this.viewContext.reflector.resolveExternalReference(Identifiers$1.ChangeDetectorRef) ||
  13073. tokenReference(dep.token) ===
  13074. this.viewContext.reflector.resolveExternalReference(Identifiers$1.TemplateRef)) {
  13075. return dep;
  13076. }
  13077. if (tokenReference(dep.token) ===
  13078. this.viewContext.reflector.resolveExternalReference(Identifiers$1.ViewContainerRef)) {
  13079. this.transformedHasViewContainer = true;
  13080. }
  13081. }
  13082. // access the injector
  13083. if (tokenReference(dep.token) ===
  13084. this.viewContext.reflector.resolveExternalReference(Identifiers$1.Injector)) {
  13085. return dep;
  13086. }
  13087. // access providers
  13088. if (this._getOrCreateLocalProvider(requestingProviderType, dep.token, eager) != null) {
  13089. return dep;
  13090. }
  13091. }
  13092. return null;
  13093. };
  13094. ProviderElementContext.prototype._getDependency = function (requestingProviderType, dep, eager) {
  13095. if (eager === void 0) { eager = false; }
  13096. var currElement = this;
  13097. var currEager = eager;
  13098. var result = null;
  13099. if (!dep.isSkipSelf) {
  13100. result = this._getLocalDependency(requestingProviderType, dep, eager);
  13101. }
  13102. if (dep.isSelf) {
  13103. if (!result && dep.isOptional) {
  13104. result = { isValue: true, value: null };
  13105. }
  13106. }
  13107. else {
  13108. // check parent elements
  13109. while (!result && currElement._parent) {
  13110. var prevElement = currElement;
  13111. currElement = currElement._parent;
  13112. if (prevElement._isViewRoot) {
  13113. currEager = false;
  13114. }
  13115. result = currElement._getLocalDependency(exports.ProviderAstType.PublicService, dep, currEager);
  13116. }
  13117. // check @Host restriction
  13118. if (!result) {
  13119. if (!dep.isHost || this.viewContext.component.isHost ||
  13120. this.viewContext.component.type.reference === tokenReference(dep.token) ||
  13121. this.viewContext.viewProviders.get(tokenReference(dep.token)) != null) {
  13122. result = dep;
  13123. }
  13124. else {
  13125. result = dep.isOptional ? { isValue: true, value: null } : null;
  13126. }
  13127. }
  13128. }
  13129. if (!result) {
  13130. this.viewContext.errors.push(new ProviderError("No provider for " + tokenName(dep.token), this._sourceSpan));
  13131. }
  13132. return result;
  13133. };
  13134. return ProviderElementContext;
  13135. }());
  13136. var NgModuleProviderAnalyzer = /** @class */ (function () {
  13137. function NgModuleProviderAnalyzer(reflector, ngModule, extraProviders, sourceSpan) {
  13138. var _this = this;
  13139. this.reflector = reflector;
  13140. this._transformedProviders = new Map();
  13141. this._seenProviders = new Map();
  13142. this._errors = [];
  13143. this._allProviders = new Map();
  13144. ngModule.transitiveModule.modules.forEach(function (ngModuleType) {
  13145. var ngModuleProvider = { token: { identifier: ngModuleType }, useClass: ngModuleType };
  13146. _resolveProviders([ngModuleProvider], exports.ProviderAstType.PublicService, true, sourceSpan, _this._errors, _this._allProviders, /* isModule */ true);
  13147. });
  13148. _resolveProviders(ngModule.transitiveModule.providers.map(function (entry) { return entry.provider; }).concat(extraProviders), exports.ProviderAstType.PublicService, false, sourceSpan, this._errors, this._allProviders,
  13149. /* isModule */ false);
  13150. }
  13151. NgModuleProviderAnalyzer.prototype.parse = function () {
  13152. var _this = this;
  13153. Array.from(this._allProviders.values()).forEach(function (provider) {
  13154. _this._getOrCreateLocalProvider(provider.token, provider.eager);
  13155. });
  13156. if (this._errors.length > 0) {
  13157. var errorString = this._errors.join('\n');
  13158. throw new Error("Provider parse errors:\n" + errorString);
  13159. }
  13160. // Note: Maps keep their insertion order.
  13161. var lazyProviders = [];
  13162. var eagerProviders = [];
  13163. this._transformedProviders.forEach(function (provider) {
  13164. if (provider.eager) {
  13165. eagerProviders.push(provider);
  13166. }
  13167. else {
  13168. lazyProviders.push(provider);
  13169. }
  13170. });
  13171. return lazyProviders.concat(eagerProviders);
  13172. };
  13173. NgModuleProviderAnalyzer.prototype._getOrCreateLocalProvider = function (token, eager) {
  13174. var _this = this;
  13175. var resolvedProvider = this._allProviders.get(tokenReference(token));
  13176. if (!resolvedProvider) {
  13177. return null;
  13178. }
  13179. var transformedProviderAst = this._transformedProviders.get(tokenReference(token));
  13180. if (transformedProviderAst) {
  13181. return transformedProviderAst;
  13182. }
  13183. if (this._seenProviders.get(tokenReference(token)) != null) {
  13184. this._errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), resolvedProvider.sourceSpan));
  13185. return null;
  13186. }
  13187. this._seenProviders.set(tokenReference(token), true);
  13188. var transformedProviders = resolvedProvider.providers.map(function (provider) {
  13189. var transformedUseValue = provider.useValue;
  13190. var transformedUseExisting = provider.useExisting;
  13191. var transformedDeps = undefined;
  13192. if (provider.useExisting != null) {
  13193. var existingDiDep = _this._getDependency({ token: provider.useExisting }, eager, resolvedProvider.sourceSpan);
  13194. if (existingDiDep.token != null) {
  13195. transformedUseExisting = existingDiDep.token;
  13196. }
  13197. else {
  13198. transformedUseExisting = null;
  13199. transformedUseValue = existingDiDep.value;
  13200. }
  13201. }
  13202. else if (provider.useFactory) {
  13203. var deps = provider.deps || provider.useFactory.diDeps;
  13204. transformedDeps =
  13205. deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); });
  13206. }
  13207. else if (provider.useClass) {
  13208. var deps = provider.deps || provider.useClass.diDeps;
  13209. transformedDeps =
  13210. deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); });
  13211. }
  13212. return _transformProvider(provider, {
  13213. useExisting: transformedUseExisting,
  13214. useValue: transformedUseValue,
  13215. deps: transformedDeps
  13216. });
  13217. });
  13218. transformedProviderAst =
  13219. _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
  13220. this._transformedProviders.set(tokenReference(token), transformedProviderAst);
  13221. return transformedProviderAst;
  13222. };
  13223. NgModuleProviderAnalyzer.prototype._getDependency = function (dep, eager, requestorSourceSpan) {
  13224. if (eager === void 0) { eager = false; }
  13225. var foundLocal = false;
  13226. if (!dep.isSkipSelf && dep.token != null) {
  13227. // access the injector
  13228. if (tokenReference(dep.token) ===
  13229. this.reflector.resolveExternalReference(Identifiers$1.Injector) ||
  13230. tokenReference(dep.token) ===
  13231. this.reflector.resolveExternalReference(Identifiers$1.ComponentFactoryResolver)) {
  13232. foundLocal = true;
  13233. // access providers
  13234. }
  13235. else if (this._getOrCreateLocalProvider(dep.token, eager) != null) {
  13236. foundLocal = true;
  13237. }
  13238. }
  13239. return dep;
  13240. };
  13241. return NgModuleProviderAnalyzer;
  13242. }());
  13243. function _transformProvider(provider, _a) {
  13244. var useExisting = _a.useExisting, useValue = _a.useValue, deps = _a.deps;
  13245. return {
  13246. token: provider.token,
  13247. useClass: provider.useClass,
  13248. useExisting: useExisting,
  13249. useFactory: provider.useFactory,
  13250. useValue: useValue,
  13251. deps: deps,
  13252. multi: provider.multi
  13253. };
  13254. }
  13255. function _transformProviderAst(provider, _a) {
  13256. var eager = _a.eager, providers = _a.providers;
  13257. return new ProviderAst(provider.token, provider.multiProvider, provider.eager || eager, providers, provider.providerType, provider.lifecycleHooks, provider.sourceSpan, provider.isModule);
  13258. }
  13259. function _resolveProvidersFromDirectives(directives, sourceSpan, targetErrors) {
  13260. var providersByToken = new Map();
  13261. directives.forEach(function (directive) {
  13262. var dirProvider = { token: { identifier: directive.type }, useClass: directive.type };
  13263. _resolveProviders([dirProvider], directive.isComponent ? exports.ProviderAstType.Component : exports.ProviderAstType.Directive, true, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  13264. });
  13265. // Note: directives need to be able to overwrite providers of a component!
  13266. var directivesWithComponentFirst = directives.filter(function (dir) { return dir.isComponent; }).concat(directives.filter(function (dir) { return !dir.isComponent; }));
  13267. directivesWithComponentFirst.forEach(function (directive) {
  13268. _resolveProviders(directive.providers, exports.ProviderAstType.PublicService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  13269. _resolveProviders(directive.viewProviders, exports.ProviderAstType.PrivateService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
  13270. });
  13271. return providersByToken;
  13272. }
  13273. function _resolveProviders(providers, providerType, eager, sourceSpan, targetErrors, targetProvidersByToken, isModule) {
  13274. providers.forEach(function (provider) {
  13275. var resolvedProvider = targetProvidersByToken.get(tokenReference(provider.token));
  13276. if (resolvedProvider != null && !!resolvedProvider.multiProvider !== !!provider.multi) {
  13277. targetErrors.push(new ProviderError("Mixing multi and non multi provider is not possible for token " + tokenName(resolvedProvider.token), sourceSpan));
  13278. }
  13279. if (!resolvedProvider) {
  13280. var lifecycleHooks = provider.token.identifier &&
  13281. provider.token.identifier.lifecycleHooks ?
  13282. provider.token.identifier.lifecycleHooks :
  13283. [];
  13284. var isUseValue = !(provider.useClass || provider.useExisting || provider.useFactory);
  13285. resolvedProvider = new ProviderAst(provider.token, !!provider.multi, eager || isUseValue, [provider], providerType, lifecycleHooks, sourceSpan, isModule);
  13286. targetProvidersByToken.set(tokenReference(provider.token), resolvedProvider);
  13287. }
  13288. else {
  13289. if (!provider.multi) {
  13290. resolvedProvider.providers.length = 0;
  13291. }
  13292. resolvedProvider.providers.push(provider);
  13293. }
  13294. });
  13295. }
  13296. function _getViewQueries(component) {
  13297. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  13298. var viewQueryId = 1;
  13299. var viewQueries = new Map();
  13300. if (component.viewQueries) {
  13301. component.viewQueries.forEach(function (query) { return _addQueryToTokenMap(viewQueries, { meta: query, queryId: viewQueryId++ }); });
  13302. }
  13303. return viewQueries;
  13304. }
  13305. function _getContentQueries(contentQueryStartId, directives) {
  13306. var contentQueryId = contentQueryStartId;
  13307. var contentQueries = new Map();
  13308. directives.forEach(function (directive, directiveIndex) {
  13309. if (directive.queries) {
  13310. directive.queries.forEach(function (query) { return _addQueryToTokenMap(contentQueries, { meta: query, queryId: contentQueryId++ }); });
  13311. }
  13312. });
  13313. return contentQueries;
  13314. }
  13315. function _addQueryToTokenMap(map, query) {
  13316. query.meta.selectors.forEach(function (token) {
  13317. var entry = map.get(tokenReference(token));
  13318. if (!entry) {
  13319. entry = [];
  13320. map.set(tokenReference(token), entry);
  13321. }
  13322. entry.push(query);
  13323. });
  13324. }
  13325. /**
  13326. * @license
  13327. * Copyright Google LLC All Rights Reserved.
  13328. *
  13329. * Use of this source code is governed by an MIT-style license that can be
  13330. * found in the LICENSE file at https://angular.io/license
  13331. */
  13332. var StyleWithImports = /** @class */ (function () {
  13333. function StyleWithImports(style, styleUrls) {
  13334. this.style = style;
  13335. this.styleUrls = styleUrls;
  13336. }
  13337. return StyleWithImports;
  13338. }());
  13339. function isStyleUrlResolvable(url) {
  13340. if (url == null || url.length === 0 || url[0] == '/')
  13341. return false;
  13342. var schemeMatch = url.match(URL_WITH_SCHEMA_REGEXP);
  13343. return schemeMatch === null || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
  13344. }
  13345. /**
  13346. * Rewrites stylesheets by resolving and removing the @import urls that
  13347. * are either relative or don't have a `package:` scheme
  13348. */
  13349. function extractStyleUrls(resolver, baseUrl, cssText) {
  13350. var foundUrls = [];
  13351. var modifiedCssText = cssText.replace(CSS_STRIPPABLE_COMMENT_REGEXP, '')
  13352. .replace(CSS_IMPORT_REGEXP, function () {
  13353. var m = [];
  13354. for (var _i = 0; _i < arguments.length; _i++) {
  13355. m[_i] = arguments[_i];
  13356. }
  13357. var url = m[1] || m[2];
  13358. if (!isStyleUrlResolvable(url)) {
  13359. // Do not attempt to resolve non-package absolute URLs with URI
  13360. // scheme
  13361. return m[0];
  13362. }
  13363. foundUrls.push(resolver.resolve(baseUrl, url));
  13364. return '';
  13365. });
  13366. return new StyleWithImports(modifiedCssText, foundUrls);
  13367. }
  13368. var CSS_IMPORT_REGEXP = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g;
  13369. var CSS_STRIPPABLE_COMMENT_REGEXP = /\/\*(?!#\s*(?:sourceURL|sourceMappingURL)=)[\s\S]+?\*\//g;
  13370. var URL_WITH_SCHEMA_REGEXP = /^([^:/?#]+):/;
  13371. var PROPERTY_PARTS_SEPARATOR = '.';
  13372. var ATTRIBUTE_PREFIX = 'attr';
  13373. var CLASS_PREFIX = 'class';
  13374. var STYLE_PREFIX = 'style';
  13375. var TEMPLATE_ATTR_PREFIX = '*';
  13376. var ANIMATE_PROP_PREFIX = 'animate-';
  13377. /**
  13378. * Parses bindings in templates and in the directive host area.
  13379. */
  13380. var BindingParser = /** @class */ (function () {
  13381. function BindingParser(_exprParser, _interpolationConfig, _schemaRegistry, pipes, errors) {
  13382. this._exprParser = _exprParser;
  13383. this._interpolationConfig = _interpolationConfig;
  13384. this._schemaRegistry = _schemaRegistry;
  13385. this.errors = errors;
  13386. this.pipesByName = null;
  13387. this._usedPipes = new Map();
  13388. // When the `pipes` parameter is `null`, do not check for used pipes
  13389. // This is used in IVY when we might not know the available pipes at compile time
  13390. if (pipes) {
  13391. var pipesByName_1 = new Map();
  13392. pipes.forEach(function (pipe) { return pipesByName_1.set(pipe.name, pipe); });
  13393. this.pipesByName = pipesByName_1;
  13394. }
  13395. }
  13396. Object.defineProperty(BindingParser.prototype, "interpolationConfig", {
  13397. get: function () {
  13398. return this._interpolationConfig;
  13399. },
  13400. enumerable: false,
  13401. configurable: true
  13402. });
  13403. BindingParser.prototype.getUsedPipes = function () {
  13404. return Array.from(this._usedPipes.values());
  13405. };
  13406. BindingParser.prototype.createBoundHostProperties = function (dirMeta, sourceSpan) {
  13407. var _this = this;
  13408. if (dirMeta.hostProperties) {
  13409. var boundProps_1 = [];
  13410. Object.keys(dirMeta.hostProperties).forEach(function (propName) {
  13411. var expression = dirMeta.hostProperties[propName];
  13412. if (typeof expression === 'string') {
  13413. _this.parsePropertyBinding(propName, expression, true, sourceSpan, sourceSpan.start.offset, undefined, [],
  13414. // Use the `sourceSpan` for `keySpan`. This isn't really accurate, but neither is the
  13415. // sourceSpan, as it represents the sourceSpan of the host itself rather than the
  13416. // source of the host binding (which doesn't exist in the template). Regardless,
  13417. // neither of these values are used in Ivy but are only here to satisfy the function
  13418. // signature. This should likely be refactored in the future so that `sourceSpan`
  13419. // isn't being used inaccurately.
  13420. boundProps_1, sourceSpan);
  13421. }
  13422. else {
  13423. _this._reportError("Value of the host property binding \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan);
  13424. }
  13425. });
  13426. return boundProps_1;
  13427. }
  13428. return null;
  13429. };
  13430. BindingParser.prototype.createDirectiveHostPropertyAsts = function (dirMeta, elementSelector, sourceSpan) {
  13431. var _this = this;
  13432. var boundProps = this.createBoundHostProperties(dirMeta, sourceSpan);
  13433. return boundProps &&
  13434. boundProps.map(function (prop) { return _this.createBoundElementProperty(elementSelector, prop); });
  13435. };
  13436. BindingParser.prototype.createDirectiveHostEventAsts = function (dirMeta, sourceSpan) {
  13437. var _this = this;
  13438. if (dirMeta.hostListeners) {
  13439. var targetEvents_1 = [];
  13440. Object.keys(dirMeta.hostListeners).forEach(function (propName) {
  13441. var expression = dirMeta.hostListeners[propName];
  13442. if (typeof expression === 'string') {
  13443. // Use the `sourceSpan` for `keySpan` and `handlerSpan`. This isn't really accurate, but
  13444. // neither is the `sourceSpan`, as it represents the `sourceSpan` of the host itself
  13445. // rather than the source of the host binding (which doesn't exist in the template).
  13446. // Regardless, neither of these values are used in Ivy but are only here to satisfy the
  13447. // function signature. This should likely be refactored in the future so that `sourceSpan`
  13448. // isn't being used inaccurately.
  13449. _this.parseEvent(propName, expression, sourceSpan, sourceSpan, [], targetEvents_1, sourceSpan);
  13450. }
  13451. else {
  13452. _this._reportError("Value of the host listener \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan);
  13453. }
  13454. });
  13455. return targetEvents_1;
  13456. }
  13457. return null;
  13458. };
  13459. BindingParser.prototype.parseInterpolation = function (value, sourceSpan) {
  13460. var sourceInfo = sourceSpan.start.toString();
  13461. var absoluteOffset = sourceSpan.fullStart.offset;
  13462. try {
  13463. var ast = this._exprParser.parseInterpolation(value, sourceInfo, absoluteOffset, this._interpolationConfig);
  13464. if (ast)
  13465. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  13466. this._checkPipes(ast, sourceSpan);
  13467. return ast;
  13468. }
  13469. catch (e) {
  13470. this._reportError("" + e, sourceSpan);
  13471. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset);
  13472. }
  13473. };
  13474. /**
  13475. * Similar to `parseInterpolation`, but treats the provided string as a single expression
  13476. * element that would normally appear within the interpolation prefix and suffix (`{{` and `}}`).
  13477. * This is used for parsing the switch expression in ICUs.
  13478. */
  13479. BindingParser.prototype.parseInterpolationExpression = function (expression, sourceSpan) {
  13480. var sourceInfo = sourceSpan.start.toString();
  13481. var absoluteOffset = sourceSpan.start.offset;
  13482. try {
  13483. var ast = this._exprParser.parseInterpolationExpression(expression, sourceInfo, absoluteOffset);
  13484. if (ast)
  13485. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  13486. this._checkPipes(ast, sourceSpan);
  13487. return ast;
  13488. }
  13489. catch (e) {
  13490. this._reportError("" + e, sourceSpan);
  13491. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset);
  13492. }
  13493. };
  13494. /**
  13495. * Parses the bindings in a microsyntax expression, and converts them to
  13496. * `ParsedProperty` or `ParsedVariable`.
  13497. *
  13498. * @param tplKey template binding name
  13499. * @param tplValue template binding value
  13500. * @param sourceSpan span of template binding relative to entire the template
  13501. * @param absoluteValueOffset start of the tplValue relative to the entire template
  13502. * @param targetMatchableAttrs potential attributes to match in the template
  13503. * @param targetProps target property bindings in the template
  13504. * @param targetVars target variables in the template
  13505. */
  13506. BindingParser.prototype.parseInlineTemplateBinding = function (tplKey, tplValue, sourceSpan, absoluteValueOffset, targetMatchableAttrs, targetProps, targetVars, isIvyAst) {
  13507. var e_1, _a;
  13508. var absoluteKeyOffset = sourceSpan.start.offset + TEMPLATE_ATTR_PREFIX.length;
  13509. var bindings = this._parseTemplateBindings(tplKey, tplValue, sourceSpan, absoluteKeyOffset, absoluteValueOffset);
  13510. try {
  13511. for (var bindings_1 = __values(bindings), bindings_1_1 = bindings_1.next(); !bindings_1_1.done; bindings_1_1 = bindings_1.next()) {
  13512. var binding = bindings_1_1.value;
  13513. // sourceSpan is for the entire HTML attribute. bindingSpan is for a particular
  13514. // binding within the microsyntax expression so it's more narrow than sourceSpan.
  13515. var bindingSpan = moveParseSourceSpan(sourceSpan, binding.sourceSpan);
  13516. var key = binding.key.source;
  13517. var keySpan = moveParseSourceSpan(sourceSpan, binding.key.span);
  13518. if (binding instanceof VariableBinding) {
  13519. var value = binding.value ? binding.value.source : '$implicit';
  13520. var valueSpan = binding.value ? moveParseSourceSpan(sourceSpan, binding.value.span) : undefined;
  13521. targetVars.push(new ParsedVariable(key, value, bindingSpan, keySpan, valueSpan));
  13522. }
  13523. else if (binding.value) {
  13524. var srcSpan = isIvyAst ? bindingSpan : sourceSpan;
  13525. var valueSpan = moveParseSourceSpan(sourceSpan, binding.value.ast.sourceSpan);
  13526. this._parsePropertyAst(key, binding.value, srcSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps);
  13527. }
  13528. else {
  13529. targetMatchableAttrs.push([key, '' /* value */]);
  13530. // Since this is a literal attribute with no RHS, source span should be
  13531. // just the key span.
  13532. this.parseLiteralAttr(key, null /* value */, keySpan, absoluteValueOffset, undefined /* valueSpan */, targetMatchableAttrs, targetProps, keySpan);
  13533. }
  13534. }
  13535. }
  13536. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  13537. finally {
  13538. try {
  13539. if (bindings_1_1 && !bindings_1_1.done && (_a = bindings_1.return)) _a.call(bindings_1);
  13540. }
  13541. finally { if (e_1) throw e_1.error; }
  13542. }
  13543. };
  13544. /**
  13545. * Parses the bindings in a microsyntax expression, e.g.
  13546. * ```
  13547. * <tag *tplKey="let value1 = prop; let value2 = localVar">
  13548. * ```
  13549. *
  13550. * @param tplKey template binding name
  13551. * @param tplValue template binding value
  13552. * @param sourceSpan span of template binding relative to entire the template
  13553. * @param absoluteKeyOffset start of the `tplKey`
  13554. * @param absoluteValueOffset start of the `tplValue`
  13555. */
  13556. BindingParser.prototype._parseTemplateBindings = function (tplKey, tplValue, sourceSpan, absoluteKeyOffset, absoluteValueOffset) {
  13557. var _this = this;
  13558. var sourceInfo = sourceSpan.start.toString();
  13559. try {
  13560. var bindingsResult = this._exprParser.parseTemplateBindings(tplKey, tplValue, sourceInfo, absoluteKeyOffset, absoluteValueOffset);
  13561. this._reportExpressionParserErrors(bindingsResult.errors, sourceSpan);
  13562. bindingsResult.templateBindings.forEach(function (binding) {
  13563. if (binding.value instanceof ASTWithSource) {
  13564. _this._checkPipes(binding.value, sourceSpan);
  13565. }
  13566. });
  13567. bindingsResult.warnings.forEach(function (warning) {
  13568. _this._reportError(warning, sourceSpan, exports.ParseErrorLevel.WARNING);
  13569. });
  13570. return bindingsResult.templateBindings;
  13571. }
  13572. catch (e) {
  13573. this._reportError("" + e, sourceSpan);
  13574. return [];
  13575. }
  13576. };
  13577. BindingParser.prototype.parseLiteralAttr = function (name, value, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs,
  13578. // TODO(atscott): keySpan is only optional here so VE template parser implementation does not
  13579. // have to change This should be required when VE is removed.
  13580. targetProps, keySpan) {
  13581. if (isAnimationLabel(name)) {
  13582. name = name.substring(1);
  13583. if (keySpan !== undefined) {
  13584. keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset));
  13585. }
  13586. if (value) {
  13587. this._reportError("Assigning animation triggers via @prop=\"exp\" attributes with an expression is invalid." +
  13588. " Use property bindings (e.g. [@prop]=\"exp\") or use an attribute without a value (e.g. @prop) instead.", sourceSpan, exports.ParseErrorLevel.ERROR);
  13589. }
  13590. this._parseAnimation(name, value, sourceSpan, absoluteOffset, keySpan, valueSpan, targetMatchableAttrs, targetProps);
  13591. }
  13592. else {
  13593. targetProps.push(new ParsedProperty(name, this._exprParser.wrapLiteralPrimitive(value, '', absoluteOffset), exports.ParsedPropertyType.LITERAL_ATTR, sourceSpan, keySpan, valueSpan));
  13594. }
  13595. };
  13596. BindingParser.prototype.parsePropertyBinding = function (name, expression, isHost, sourceSpan, absoluteOffset, valueSpan,
  13597. // TODO(atscott): keySpan is only optional here so VE template parser implementation does not
  13598. // have to change This should be required when VE is removed.
  13599. targetMatchableAttrs, targetProps, keySpan) {
  13600. if (name.length === 0) {
  13601. this._reportError("Property name is missing in binding", sourceSpan);
  13602. }
  13603. var isAnimationProp = false;
  13604. if (name.startsWith(ANIMATE_PROP_PREFIX)) {
  13605. isAnimationProp = true;
  13606. name = name.substring(ANIMATE_PROP_PREFIX.length);
  13607. if (keySpan !== undefined) {
  13608. keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + ANIMATE_PROP_PREFIX.length, keySpan.end.offset));
  13609. }
  13610. }
  13611. else if (isAnimationLabel(name)) {
  13612. isAnimationProp = true;
  13613. name = name.substring(1);
  13614. if (keySpan !== undefined) {
  13615. keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset));
  13616. }
  13617. }
  13618. if (isAnimationProp) {
  13619. this._parseAnimation(name, expression, sourceSpan, absoluteOffset, keySpan, valueSpan, targetMatchableAttrs, targetProps);
  13620. }
  13621. else {
  13622. this._parsePropertyAst(name, this._parseBinding(expression, isHost, valueSpan || sourceSpan, absoluteOffset), sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps);
  13623. }
  13624. };
  13625. BindingParser.prototype.parsePropertyInterpolation = function (name, value, sourceSpan, valueSpan, targetMatchableAttrs,
  13626. // TODO(atscott): keySpan is only optional here so VE template parser implementation does not
  13627. // have to change This should be required when VE is removed.
  13628. targetProps, keySpan) {
  13629. var expr = this.parseInterpolation(value, valueSpan || sourceSpan);
  13630. if (expr) {
  13631. this._parsePropertyAst(name, expr, sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps);
  13632. return true;
  13633. }
  13634. return false;
  13635. };
  13636. BindingParser.prototype._parsePropertyAst = function (name, ast, sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps) {
  13637. targetMatchableAttrs.push([name, ast.source]);
  13638. targetProps.push(new ParsedProperty(name, ast, exports.ParsedPropertyType.DEFAULT, sourceSpan, keySpan, valueSpan));
  13639. };
  13640. BindingParser.prototype._parseAnimation = function (name, expression, sourceSpan, absoluteOffset, keySpan, valueSpan, targetMatchableAttrs, targetProps) {
  13641. if (name.length === 0) {
  13642. this._reportError('Animation trigger is missing', sourceSpan);
  13643. }
  13644. // This will occur when a @trigger is not paired with an expression.
  13645. // For animations it is valid to not have an expression since */void
  13646. // states will be applied by angular when the element is attached/detached
  13647. var ast = this._parseBinding(expression || 'undefined', false, valueSpan || sourceSpan, absoluteOffset);
  13648. targetMatchableAttrs.push([name, ast.source]);
  13649. targetProps.push(new ParsedProperty(name, ast, exports.ParsedPropertyType.ANIMATION, sourceSpan, keySpan, valueSpan));
  13650. };
  13651. BindingParser.prototype._parseBinding = function (value, isHostBinding, sourceSpan, absoluteOffset) {
  13652. var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown)').toString();
  13653. try {
  13654. var ast = isHostBinding ?
  13655. this._exprParser.parseSimpleBinding(value, sourceInfo, absoluteOffset, this._interpolationConfig) :
  13656. this._exprParser.parseBinding(value, sourceInfo, absoluteOffset, this._interpolationConfig);
  13657. if (ast)
  13658. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  13659. this._checkPipes(ast, sourceSpan);
  13660. return ast;
  13661. }
  13662. catch (e) {
  13663. this._reportError("" + e, sourceSpan);
  13664. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset);
  13665. }
  13666. };
  13667. BindingParser.prototype.createBoundElementProperty = function (elementSelector, boundProp, skipValidation, mapPropertyName) {
  13668. if (skipValidation === void 0) { skipValidation = false; }
  13669. if (mapPropertyName === void 0) { mapPropertyName = true; }
  13670. if (boundProp.isAnimation) {
  13671. return new BoundElementProperty(boundProp.name, 4 /* Animation */, SecurityContext.NONE, boundProp.expression, null, boundProp.sourceSpan, boundProp.keySpan, boundProp.valueSpan);
  13672. }
  13673. var unit = null;
  13674. var bindingType = undefined;
  13675. var boundPropertyName = null;
  13676. var parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR);
  13677. var securityContexts = undefined;
  13678. // Check for special cases (prefix style, attr, class)
  13679. if (parts.length > 1) {
  13680. if (parts[0] == ATTRIBUTE_PREFIX) {
  13681. boundPropertyName = parts.slice(1).join(PROPERTY_PARTS_SEPARATOR);
  13682. if (!skipValidation) {
  13683. this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true);
  13684. }
  13685. securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, boundPropertyName, true);
  13686. var nsSeparatorIdx = boundPropertyName.indexOf(':');
  13687. if (nsSeparatorIdx > -1) {
  13688. var ns = boundPropertyName.substring(0, nsSeparatorIdx);
  13689. var name = boundPropertyName.substring(nsSeparatorIdx + 1);
  13690. boundPropertyName = mergeNsAndName(ns, name);
  13691. }
  13692. bindingType = 1 /* Attribute */;
  13693. }
  13694. else if (parts[0] == CLASS_PREFIX) {
  13695. boundPropertyName = parts[1];
  13696. bindingType = 2 /* Class */;
  13697. securityContexts = [SecurityContext.NONE];
  13698. }
  13699. else if (parts[0] == STYLE_PREFIX) {
  13700. unit = parts.length > 2 ? parts[2] : null;
  13701. boundPropertyName = parts[1];
  13702. bindingType = 3 /* Style */;
  13703. securityContexts = [SecurityContext.STYLE];
  13704. }
  13705. }
  13706. // If not a special case, use the full property name
  13707. if (boundPropertyName === null) {
  13708. var mappedPropName = this._schemaRegistry.getMappedPropName(boundProp.name);
  13709. boundPropertyName = mapPropertyName ? mappedPropName : boundProp.name;
  13710. securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, mappedPropName, false);
  13711. bindingType = 0 /* Property */;
  13712. if (!skipValidation) {
  13713. this._validatePropertyOrAttributeName(mappedPropName, boundProp.sourceSpan, false);
  13714. }
  13715. }
  13716. return new BoundElementProperty(boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit, boundProp.sourceSpan, boundProp.keySpan, boundProp.valueSpan);
  13717. };
  13718. // TODO: keySpan should be required but was made optional to avoid changing VE parser.
  13719. BindingParser.prototype.parseEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents, keySpan) {
  13720. if (name.length === 0) {
  13721. this._reportError("Event name is missing in binding", sourceSpan);
  13722. }
  13723. if (isAnimationLabel(name)) {
  13724. name = name.substr(1);
  13725. if (keySpan !== undefined) {
  13726. keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset));
  13727. }
  13728. this._parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents, keySpan);
  13729. }
  13730. else {
  13731. this._parseRegularEvent(name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents, keySpan);
  13732. }
  13733. };
  13734. BindingParser.prototype.calcPossibleSecurityContexts = function (selector, propName, isAttribute) {
  13735. var prop = this._schemaRegistry.getMappedPropName(propName);
  13736. return calcPossibleSecurityContexts(this._schemaRegistry, selector, prop, isAttribute);
  13737. };
  13738. BindingParser.prototype._parseAnimationEvent = function (name, expression, sourceSpan, handlerSpan, targetEvents, keySpan) {
  13739. var matches = splitAtPeriod(name, [name, '']);
  13740. var eventName = matches[0];
  13741. var phase = matches[1].toLowerCase();
  13742. var ast = this._parseAction(expression, handlerSpan);
  13743. targetEvents.push(new ParsedEvent(eventName, phase, 1 /* Animation */, ast, sourceSpan, handlerSpan, keySpan));
  13744. if (eventName.length === 0) {
  13745. this._reportError("Animation event name is missing in binding", sourceSpan);
  13746. }
  13747. if (phase) {
  13748. if (phase !== 'start' && phase !== 'done') {
  13749. this._reportError("The provided animation output phase value \"" + phase + "\" for \"@" + eventName + "\" is not supported (use start or done)", sourceSpan);
  13750. }
  13751. }
  13752. else {
  13753. this._reportError("The animation trigger output event (@" + eventName + ") is missing its phase value name (start or done are currently supported)", sourceSpan);
  13754. }
  13755. };
  13756. BindingParser.prototype._parseRegularEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents, keySpan) {
  13757. // long format: 'target: eventName'
  13758. var _a = __read(splitAtColon(name, [null, name]), 2), target = _a[0], eventName = _a[1];
  13759. var ast = this._parseAction(expression, handlerSpan);
  13760. targetMatchableAttrs.push([name, ast.source]);
  13761. targetEvents.push(new ParsedEvent(eventName, target, 0 /* Regular */, ast, sourceSpan, handlerSpan, keySpan));
  13762. // Don't detect directives for event names for now,
  13763. // so don't add the event name to the matchableAttrs
  13764. };
  13765. BindingParser.prototype._parseAction = function (value, sourceSpan) {
  13766. var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown').toString();
  13767. var absoluteOffset = (sourceSpan && sourceSpan.start) ? sourceSpan.start.offset : 0;
  13768. try {
  13769. var ast = this._exprParser.parseAction(value, sourceInfo, absoluteOffset, this._interpolationConfig);
  13770. if (ast) {
  13771. this._reportExpressionParserErrors(ast.errors, sourceSpan);
  13772. }
  13773. if (!ast || ast.ast instanceof EmptyExpr) {
  13774. this._reportError("Empty expressions are not allowed", sourceSpan);
  13775. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset);
  13776. }
  13777. this._checkPipes(ast, sourceSpan);
  13778. return ast;
  13779. }
  13780. catch (e) {
  13781. this._reportError("" + e, sourceSpan);
  13782. return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset);
  13783. }
  13784. };
  13785. BindingParser.prototype._reportError = function (message, sourceSpan, level) {
  13786. if (level === void 0) { level = exports.ParseErrorLevel.ERROR; }
  13787. this.errors.push(new ParseError(sourceSpan, message, level));
  13788. };
  13789. BindingParser.prototype._reportExpressionParserErrors = function (errors, sourceSpan) {
  13790. var e_2, _a;
  13791. try {
  13792. for (var errors_1 = __values(errors), errors_1_1 = errors_1.next(); !errors_1_1.done; errors_1_1 = errors_1.next()) {
  13793. var error = errors_1_1.value;
  13794. this._reportError(error.message, sourceSpan);
  13795. }
  13796. }
  13797. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  13798. finally {
  13799. try {
  13800. if (errors_1_1 && !errors_1_1.done && (_a = errors_1.return)) _a.call(errors_1);
  13801. }
  13802. finally { if (e_2) throw e_2.error; }
  13803. }
  13804. };
  13805. // Make sure all the used pipes are known in `this.pipesByName`
  13806. BindingParser.prototype._checkPipes = function (ast, sourceSpan) {
  13807. var _this = this;
  13808. if (ast && this.pipesByName) {
  13809. var collector = new PipeCollector();
  13810. ast.visit(collector);
  13811. collector.pipes.forEach(function (ast, pipeName) {
  13812. var pipeMeta = _this.pipesByName.get(pipeName);
  13813. if (!pipeMeta) {
  13814. _this._reportError("The pipe '" + pipeName + "' could not be found", new ParseSourceSpan(sourceSpan.start.moveBy(ast.span.start), sourceSpan.start.moveBy(ast.span.end)));
  13815. }
  13816. else {
  13817. _this._usedPipes.set(pipeName, pipeMeta);
  13818. }
  13819. });
  13820. }
  13821. };
  13822. /**
  13823. * @param propName the name of the property / attribute
  13824. * @param sourceSpan
  13825. * @param isAttr true when binding to an attribute
  13826. */
  13827. BindingParser.prototype._validatePropertyOrAttributeName = function (propName, sourceSpan, isAttr) {
  13828. var report = isAttr ? this._schemaRegistry.validateAttribute(propName) :
  13829. this._schemaRegistry.validateProperty(propName);
  13830. if (report.error) {
  13831. this._reportError(report.msg, sourceSpan, exports.ParseErrorLevel.ERROR);
  13832. }
  13833. };
  13834. return BindingParser;
  13835. }());
  13836. var PipeCollector = /** @class */ (function (_super) {
  13837. __extends(PipeCollector, _super);
  13838. function PipeCollector() {
  13839. var _this = _super.apply(this, __spreadArray([], __read(arguments))) || this;
  13840. _this.pipes = new Map();
  13841. return _this;
  13842. }
  13843. PipeCollector.prototype.visitPipe = function (ast, context) {
  13844. this.pipes.set(ast.name, ast);
  13845. ast.exp.visit(this);
  13846. this.visitAll(ast.args, context);
  13847. return null;
  13848. };
  13849. return PipeCollector;
  13850. }(RecursiveAstVisitor$1));
  13851. function isAnimationLabel(name) {
  13852. return name[0] == '@';
  13853. }
  13854. function calcPossibleSecurityContexts(registry, selector, propName, isAttribute) {
  13855. var ctxs = [];
  13856. CssSelector.parse(selector).forEach(function (selector) {
  13857. var elementNames = selector.element ? [selector.element] : registry.allKnownElementNames();
  13858. var notElementNames = new Set(selector.notSelectors.filter(function (selector) { return selector.isElementSelector(); })
  13859. .map(function (selector) { return selector.element; }));
  13860. var possibleElementNames = elementNames.filter(function (elementName) { return !notElementNames.has(elementName); });
  13861. ctxs.push.apply(ctxs, __spreadArray([], __read(possibleElementNames.map(function (elementName) { return registry.securityContext(elementName, propName, isAttribute); }))));
  13862. });
  13863. return ctxs.length === 0 ? [SecurityContext.NONE] : Array.from(new Set(ctxs)).sort();
  13864. }
  13865. /**
  13866. * Compute a new ParseSourceSpan based off an original `sourceSpan` by using
  13867. * absolute offsets from the specified `absoluteSpan`.
  13868. *
  13869. * @param sourceSpan original source span
  13870. * @param absoluteSpan absolute source span to move to
  13871. */
  13872. function moveParseSourceSpan(sourceSpan, absoluteSpan) {
  13873. // The difference of two absolute offsets provide the relative offset
  13874. var startDiff = absoluteSpan.start - sourceSpan.start.offset;
  13875. var endDiff = absoluteSpan.end - sourceSpan.end.offset;
  13876. return new ParseSourceSpan(sourceSpan.start.moveBy(startDiff), sourceSpan.end.moveBy(endDiff), sourceSpan.fullStart.moveBy(startDiff), sourceSpan.details);
  13877. }
  13878. /**
  13879. * @license
  13880. * Copyright Google LLC All Rights Reserved.
  13881. *
  13882. * Use of this source code is governed by an MIT-style license that can be
  13883. * found in the LICENSE file at https://angular.io/license
  13884. */
  13885. var NG_CONTENT_SELECT_ATTR = 'select';
  13886. var LINK_ELEMENT = 'link';
  13887. var LINK_STYLE_REL_ATTR = 'rel';
  13888. var LINK_STYLE_HREF_ATTR = 'href';
  13889. var LINK_STYLE_REL_VALUE = 'stylesheet';
  13890. var STYLE_ELEMENT = 'style';
  13891. var SCRIPT_ELEMENT = 'script';
  13892. var NG_NON_BINDABLE_ATTR = 'ngNonBindable';
  13893. var NG_PROJECT_AS = 'ngProjectAs';
  13894. function preparseElement(ast) {
  13895. var selectAttr = null;
  13896. var hrefAttr = null;
  13897. var relAttr = null;
  13898. var nonBindable = false;
  13899. var projectAs = '';
  13900. ast.attrs.forEach(function (attr) {
  13901. var lcAttrName = attr.name.toLowerCase();
  13902. if (lcAttrName == NG_CONTENT_SELECT_ATTR) {
  13903. selectAttr = attr.value;
  13904. }
  13905. else if (lcAttrName == LINK_STYLE_HREF_ATTR) {
  13906. hrefAttr = attr.value;
  13907. }
  13908. else if (lcAttrName == LINK_STYLE_REL_ATTR) {
  13909. relAttr = attr.value;
  13910. }
  13911. else if (attr.name == NG_NON_BINDABLE_ATTR) {
  13912. nonBindable = true;
  13913. }
  13914. else if (attr.name == NG_PROJECT_AS) {
  13915. if (attr.value.length > 0) {
  13916. projectAs = attr.value;
  13917. }
  13918. }
  13919. });
  13920. selectAttr = normalizeNgContentSelect(selectAttr);
  13921. var nodeName = ast.name.toLowerCase();
  13922. var type = PreparsedElementType.OTHER;
  13923. if (isNgContent(nodeName)) {
  13924. type = PreparsedElementType.NG_CONTENT;
  13925. }
  13926. else if (nodeName == STYLE_ELEMENT) {
  13927. type = PreparsedElementType.STYLE;
  13928. }
  13929. else if (nodeName == SCRIPT_ELEMENT) {
  13930. type = PreparsedElementType.SCRIPT;
  13931. }
  13932. else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) {
  13933. type = PreparsedElementType.STYLESHEET;
  13934. }
  13935. return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs);
  13936. }
  13937. var PreparsedElementType;
  13938. (function (PreparsedElementType) {
  13939. PreparsedElementType[PreparsedElementType["NG_CONTENT"] = 0] = "NG_CONTENT";
  13940. PreparsedElementType[PreparsedElementType["STYLE"] = 1] = "STYLE";
  13941. PreparsedElementType[PreparsedElementType["STYLESHEET"] = 2] = "STYLESHEET";
  13942. PreparsedElementType[PreparsedElementType["SCRIPT"] = 3] = "SCRIPT";
  13943. PreparsedElementType[PreparsedElementType["OTHER"] = 4] = "OTHER";
  13944. })(PreparsedElementType || (PreparsedElementType = {}));
  13945. var PreparsedElement = /** @class */ (function () {
  13946. function PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs) {
  13947. this.type = type;
  13948. this.selectAttr = selectAttr;
  13949. this.hrefAttr = hrefAttr;
  13950. this.nonBindable = nonBindable;
  13951. this.projectAs = projectAs;
  13952. }
  13953. return PreparsedElement;
  13954. }());
  13955. function normalizeNgContentSelect(selectAttr) {
  13956. if (selectAttr === null || selectAttr.length === 0) {
  13957. return '*';
  13958. }
  13959. return selectAttr;
  13960. }
  13961. var BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.*))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
  13962. // Group 1 = "bind-"
  13963. var KW_BIND_IDX = 1;
  13964. // Group 2 = "let-"
  13965. var KW_LET_IDX = 2;
  13966. // Group 3 = "ref-/#"
  13967. var KW_REF_IDX = 3;
  13968. // Group 4 = "on-"
  13969. var KW_ON_IDX = 4;
  13970. // Group 5 = "bindon-"
  13971. var KW_BINDON_IDX = 5;
  13972. // Group 6 = "@"
  13973. var KW_AT_IDX = 6;
  13974. // Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
  13975. var IDENT_KW_IDX = 7;
  13976. // Group 8 = identifier inside [()]
  13977. var IDENT_BANANA_BOX_IDX = 8;
  13978. // Group 9 = identifier inside []
  13979. var IDENT_PROPERTY_IDX = 9;
  13980. // Group 10 = identifier inside ()
  13981. var IDENT_EVENT_IDX = 10;
  13982. var TEMPLATE_ATTR_PREFIX$1 = '*';
  13983. var CLASS_ATTR = 'class';
  13984. var _TEXT_CSS_SELECTOR;
  13985. function TEXT_CSS_SELECTOR() {
  13986. if (!_TEXT_CSS_SELECTOR) {
  13987. _TEXT_CSS_SELECTOR = CssSelector.parse('*')[0];
  13988. }
  13989. return _TEXT_CSS_SELECTOR;
  13990. }
  13991. var TemplateParseError = /** @class */ (function (_super) {
  13992. __extends(TemplateParseError, _super);
  13993. function TemplateParseError(message, span, level) {
  13994. return _super.call(this, span, message, level) || this;
  13995. }
  13996. return TemplateParseError;
  13997. }(ParseError));
  13998. var TemplateParseResult = /** @class */ (function () {
  13999. function TemplateParseResult(templateAst, usedPipes, errors) {
  14000. this.templateAst = templateAst;
  14001. this.usedPipes = usedPipes;
  14002. this.errors = errors;
  14003. }
  14004. return TemplateParseResult;
  14005. }());
  14006. var TemplateParser = /** @class */ (function () {
  14007. function TemplateParser(_config, _reflector, _exprParser, _schemaRegistry, _htmlParser, _console, transforms) {
  14008. this._config = _config;
  14009. this._reflector = _reflector;
  14010. this._exprParser = _exprParser;
  14011. this._schemaRegistry = _schemaRegistry;
  14012. this._htmlParser = _htmlParser;
  14013. this._console = _console;
  14014. this.transforms = transforms;
  14015. }
  14016. Object.defineProperty(TemplateParser.prototype, "expressionParser", {
  14017. get: function () {
  14018. return this._exprParser;
  14019. },
  14020. enumerable: false,
  14021. configurable: true
  14022. });
  14023. TemplateParser.prototype.parse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
  14024. var _a;
  14025. var result = this.tryParse(component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces);
  14026. var warnings = result.errors.filter(function (error) { return error.level === exports.ParseErrorLevel.WARNING; });
  14027. var errors = result.errors.filter(function (error) { return error.level === exports.ParseErrorLevel.ERROR; });
  14028. if (warnings.length > 0) {
  14029. (_a = this._console) === null || _a === void 0 ? void 0 : _a.warn("Template parse warnings:\n" + warnings.join('\n'));
  14030. }
  14031. if (errors.length > 0) {
  14032. var errorString = errors.join('\n');
  14033. throw syntaxError("Template parse errors:\n" + errorString, errors);
  14034. }
  14035. return { template: result.templateAst, pipes: result.usedPipes };
  14036. };
  14037. TemplateParser.prototype.tryParse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
  14038. var htmlParseResult = typeof template === 'string' ?
  14039. this._htmlParser.parse(template, templateUrl, {
  14040. tokenizeExpansionForms: true,
  14041. interpolationConfig: this.getInterpolationConfig(component)
  14042. }) :
  14043. template;
  14044. if (!preserveWhitespaces) {
  14045. htmlParseResult = removeWhitespaces(htmlParseResult);
  14046. }
  14047. return this.tryParseHtml(this.expandHtml(htmlParseResult), component, directives, pipes, schemas);
  14048. };
  14049. TemplateParser.prototype.tryParseHtml = function (htmlAstWithErrors, component, directives, pipes, schemas) {
  14050. var result;
  14051. var errors = htmlAstWithErrors.errors;
  14052. var usedPipes = [];
  14053. if (htmlAstWithErrors.rootNodes.length > 0) {
  14054. var uniqDirectives = removeSummaryDuplicates(directives);
  14055. var uniqPipes = removeSummaryDuplicates(pipes);
  14056. var providerViewContext = new ProviderViewContext(this._reflector, component);
  14057. var interpolationConfig = undefined;
  14058. if (component.template && component.template.interpolation) {
  14059. interpolationConfig = {
  14060. start: component.template.interpolation[0],
  14061. end: component.template.interpolation[1]
  14062. };
  14063. }
  14064. var bindingParser = new BindingParser(this._exprParser, interpolationConfig, this._schemaRegistry, uniqPipes, errors);
  14065. var parseVisitor = new TemplateParseVisitor(this._reflector, this._config, providerViewContext, uniqDirectives, bindingParser, this._schemaRegistry, schemas, errors);
  14066. result = visitAll$1(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT);
  14067. errors.push.apply(errors, __spreadArray([], __read(providerViewContext.errors)));
  14068. usedPipes.push.apply(usedPipes, __spreadArray([], __read(bindingParser.getUsedPipes())));
  14069. }
  14070. else {
  14071. result = [];
  14072. }
  14073. this._assertNoReferenceDuplicationOnTemplate(result, errors);
  14074. if (errors.length > 0) {
  14075. return new TemplateParseResult(result, usedPipes, errors);
  14076. }
  14077. if (this.transforms) {
  14078. this.transforms.forEach(function (transform) {
  14079. result = templateVisitAll(transform, result);
  14080. });
  14081. }
  14082. return new TemplateParseResult(result, usedPipes, errors);
  14083. };
  14084. TemplateParser.prototype.expandHtml = function (htmlAstWithErrors, forced) {
  14085. if (forced === void 0) { forced = false; }
  14086. var errors = htmlAstWithErrors.errors;
  14087. if (errors.length == 0 || forced) {
  14088. // Transform ICU messages to angular directives
  14089. var expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes);
  14090. errors.push.apply(errors, __spreadArray([], __read(expandedHtmlAst.errors)));
  14091. htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors);
  14092. }
  14093. return htmlAstWithErrors;
  14094. };
  14095. TemplateParser.prototype.getInterpolationConfig = function (component) {
  14096. if (component.template) {
  14097. return InterpolationConfig.fromArray(component.template.interpolation);
  14098. }
  14099. return undefined;
  14100. };
  14101. /** @internal */
  14102. TemplateParser.prototype._assertNoReferenceDuplicationOnTemplate = function (result, errors) {
  14103. var existingReferences = [];
  14104. result.filter(function (element) { return !!element.references; })
  14105. .forEach(function (element) { return element.references.forEach(function (reference) {
  14106. var name = reference.name;
  14107. if (existingReferences.indexOf(name) < 0) {
  14108. existingReferences.push(name);
  14109. }
  14110. else {
  14111. var error = new TemplateParseError("Reference \"#" + name + "\" is defined several times", reference.sourceSpan, exports.ParseErrorLevel.ERROR);
  14112. errors.push(error);
  14113. }
  14114. }); });
  14115. };
  14116. return TemplateParser;
  14117. }());
  14118. var TemplateParseVisitor = /** @class */ (function () {
  14119. function TemplateParseVisitor(reflector, config, providerViewContext, directives, _bindingParser, _schemaRegistry, _schemas, _targetErrors) {
  14120. var _this = this;
  14121. this.reflector = reflector;
  14122. this.config = config;
  14123. this.providerViewContext = providerViewContext;
  14124. this._bindingParser = _bindingParser;
  14125. this._schemaRegistry = _schemaRegistry;
  14126. this._schemas = _schemas;
  14127. this._targetErrors = _targetErrors;
  14128. this.selectorMatcher = new SelectorMatcher();
  14129. this.directivesIndex = new Map();
  14130. this.ngContentCount = 0;
  14131. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  14132. this.contentQueryStartId = providerViewContext.component.viewQueries.length + 1;
  14133. directives.forEach(function (directive, index) {
  14134. var selector = CssSelector.parse(directive.selector);
  14135. _this.selectorMatcher.addSelectables(selector, directive);
  14136. _this.directivesIndex.set(directive, index);
  14137. });
  14138. }
  14139. TemplateParseVisitor.prototype.visitExpansion = function (expansion, context) {
  14140. return null;
  14141. };
  14142. TemplateParseVisitor.prototype.visitExpansionCase = function (expansionCase, context) {
  14143. return null;
  14144. };
  14145. TemplateParseVisitor.prototype.visitText = function (text, parent) {
  14146. var ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
  14147. var valueNoNgsp = replaceNgsp(text.value);
  14148. var expr = this._bindingParser.parseInterpolation(valueNoNgsp, text.sourceSpan);
  14149. return expr ? new BoundTextAst(expr, ngContentIndex, text.sourceSpan) :
  14150. new TextAst(valueNoNgsp, ngContentIndex, text.sourceSpan);
  14151. };
  14152. TemplateParseVisitor.prototype.visitAttribute = function (attribute, context) {
  14153. return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
  14154. };
  14155. TemplateParseVisitor.prototype.visitComment = function (comment, context) {
  14156. return null;
  14157. };
  14158. TemplateParseVisitor.prototype.visitElement = function (element, parent) {
  14159. var _this = this;
  14160. var queryStartIndex = this.contentQueryStartId;
  14161. var elName = element.name;
  14162. var preparsedElement = preparseElement(element);
  14163. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  14164. preparsedElement.type === PreparsedElementType.STYLE) {
  14165. // Skipping <script> for security reasons
  14166. // Skipping <style> as we already processed them
  14167. // in the StyleCompiler
  14168. return null;
  14169. }
  14170. if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
  14171. isStyleUrlResolvable(preparsedElement.hrefAttr)) {
  14172. // Skipping stylesheets with either relative urls or package scheme as we already processed
  14173. // them in the StyleCompiler
  14174. return null;
  14175. }
  14176. var matchableAttrs = [];
  14177. var elementOrDirectiveProps = [];
  14178. var elementOrDirectiveRefs = [];
  14179. var elementVars = [];
  14180. var events = [];
  14181. var templateElementOrDirectiveProps = [];
  14182. var templateMatchableAttrs = [];
  14183. var templateElementVars = [];
  14184. var hasInlineTemplates = false;
  14185. var attrs = [];
  14186. var isTemplateElement = isNgTemplate(element.name);
  14187. element.attrs.forEach(function (attr) {
  14188. var parsedVariables = [];
  14189. var hasBinding = _this._parseAttr(isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, events, elementOrDirectiveRefs, elementVars);
  14190. elementVars.push.apply(elementVars, __spreadArray([], __read(parsedVariables.map(function (v) { return VariableAst.fromParsedVariable(v); }))));
  14191. var templateValue;
  14192. var templateKey;
  14193. var normalizedName = _this._normalizeAttributeName(attr.name);
  14194. if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX$1)) {
  14195. templateValue = attr.value;
  14196. templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX$1.length);
  14197. }
  14198. var hasTemplateBinding = templateValue != null;
  14199. if (hasTemplateBinding) {
  14200. if (hasInlineTemplates) {
  14201. _this._reportError("Can't have multiple template bindings on one element. Use only one attribute prefixed with *", attr.sourceSpan);
  14202. }
  14203. hasInlineTemplates = true;
  14204. var parsedVariables_1 = [];
  14205. var absoluteOffset = (attr.valueSpan || attr.sourceSpan).start.offset;
  14206. _this._bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attr.sourceSpan, absoluteOffset, templateMatchableAttrs, templateElementOrDirectiveProps, parsedVariables_1, false /* isIvyAst */);
  14207. templateElementVars.push.apply(templateElementVars, __spreadArray([], __read(parsedVariables_1.map(function (v) { return VariableAst.fromParsedVariable(v); }))));
  14208. }
  14209. if (!hasBinding && !hasTemplateBinding) {
  14210. // don't include the bindings as attributes as well in the AST
  14211. attrs.push(_this.visitAttribute(attr, null));
  14212. matchableAttrs.push([attr.name, attr.value]);
  14213. }
  14214. });
  14215. var elementCssSelector = createElementCssSelector(elName, matchableAttrs);
  14216. var _b = this._parseDirectives(this.selectorMatcher, elementCssSelector), directiveMetas = _b.directives, matchElement = _b.matchElement;
  14217. var references = [];
  14218. var boundDirectivePropNames = new Set();
  14219. var directiveAsts = this._createDirectiveAsts(isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps, elementOrDirectiveRefs, element.sourceSpan, references, boundDirectivePropNames);
  14220. var elementProps = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, boundDirectivePropNames);
  14221. var isViewRoot = parent.isTemplateElement || hasInlineTemplates;
  14222. var providerContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, isViewRoot, directiveAsts, attrs, references, isTemplateElement, queryStartIndex, element.sourceSpan);
  14223. var children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, ElementContext.create(isTemplateElement, directiveAsts, isTemplateElement ? parent.providerContext : providerContext));
  14224. providerContext.afterElement();
  14225. // Override the actual selector when the `ngProjectAs` attribute is provided
  14226. var projectionSelector = preparsedElement.projectAs != '' ?
  14227. CssSelector.parse(preparsedElement.projectAs)[0] :
  14228. elementCssSelector;
  14229. var ngContentIndex = parent.findNgContentIndex(projectionSelector);
  14230. var parsedElement;
  14231. if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
  14232. // `<ng-content>` element
  14233. if (element.children && !element.children.every(_isEmptyTextNode)) {
  14234. this._reportError("<ng-content> element cannot have content.", element.sourceSpan);
  14235. }
  14236. parsedElement = new NgContentAst(this.ngContentCount++, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
  14237. }
  14238. else if (isTemplateElement) {
  14239. // `<ng-template>` element
  14240. this._assertAllEventsPublishedByDirectives(directiveAsts, events);
  14241. this._assertNoComponentsNorElementBindingsOnTemplate(directiveAsts, elementProps, element.sourceSpan);
  14242. parsedElement = new EmbeddedTemplateAst(attrs, events, references, elementVars, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
  14243. }
  14244. else {
  14245. // element other than `<ng-content>` and `<ng-template>`
  14246. this._assertElementExists(matchElement, element);
  14247. this._assertOnlyOneComponent(directiveAsts, element.sourceSpan);
  14248. var ngContentIndex_1 = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector);
  14249. parsedElement = new ElementAst(elName, attrs, elementProps, events, references, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex_1, element.sourceSpan, element.endSourceSpan || null);
  14250. }
  14251. if (hasInlineTemplates) {
  14252. // The element as a *-attribute
  14253. var templateQueryStartIndex = this.contentQueryStartId;
  14254. var templateSelector = createElementCssSelector('ng-template', templateMatchableAttrs);
  14255. var directives = this._parseDirectives(this.selectorMatcher, templateSelector).directives;
  14256. var templateBoundDirectivePropNames = new Set();
  14257. var templateDirectiveAsts = this._createDirectiveAsts(true, elName, directives, templateElementOrDirectiveProps, [], element.sourceSpan, [], templateBoundDirectivePropNames);
  14258. var templateElementProps = this._createElementPropertyAsts(elName, templateElementOrDirectiveProps, templateBoundDirectivePropNames);
  14259. this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectiveAsts, templateElementProps, element.sourceSpan);
  14260. var templateProviderContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, parent.isTemplateElement, templateDirectiveAsts, [], [], true, templateQueryStartIndex, element.sourceSpan);
  14261. templateProviderContext.afterElement();
  14262. parsedElement = new EmbeddedTemplateAst([], [], [], templateElementVars, templateProviderContext.transformedDirectiveAsts, templateProviderContext.transformProviders, templateProviderContext.transformedHasViewContainer, templateProviderContext.queryMatches, [parsedElement], ngContentIndex, element.sourceSpan);
  14263. }
  14264. return parsedElement;
  14265. };
  14266. TemplateParseVisitor.prototype._parseAttr = function (isTemplateElement, attr, targetMatchableAttrs, targetProps, targetEvents, targetRefs, targetVars) {
  14267. var name = this._normalizeAttributeName(attr.name);
  14268. var value = attr.value;
  14269. var srcSpan = attr.sourceSpan;
  14270. var absoluteOffset = attr.valueSpan ? attr.valueSpan.start.offset : srcSpan.start.offset;
  14271. var boundEvents = [];
  14272. var bindParts = name.match(BIND_NAME_REGEXP);
  14273. var hasBinding = false;
  14274. if (bindParts !== null) {
  14275. hasBinding = true;
  14276. if (bindParts[KW_BIND_IDX] != null) {
  14277. this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
  14278. }
  14279. else if (bindParts[KW_LET_IDX]) {
  14280. if (isTemplateElement) {
  14281. var identifier = bindParts[IDENT_KW_IDX];
  14282. this._parseVariable(identifier, value, srcSpan, targetVars);
  14283. }
  14284. else {
  14285. this._reportError("\"let-\" is only supported on ng-template elements.", srcSpan);
  14286. }
  14287. }
  14288. else if (bindParts[KW_REF_IDX]) {
  14289. var identifier = bindParts[IDENT_KW_IDX];
  14290. this._parseReference(identifier, value, srcSpan, targetRefs);
  14291. }
  14292. else if (bindParts[KW_ON_IDX]) {
  14293. this._bindingParser.parseEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  14294. }
  14295. else if (bindParts[KW_BINDON_IDX]) {
  14296. this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
  14297. this._parseAssignmentEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  14298. }
  14299. else if (bindParts[KW_AT_IDX]) {
  14300. this._bindingParser.parseLiteralAttr(name, value, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
  14301. }
  14302. else if (bindParts[IDENT_BANANA_BOX_IDX]) {
  14303. this._bindingParser.parsePropertyBinding(bindParts[IDENT_BANANA_BOX_IDX], value, false, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
  14304. this._parseAssignmentEvent(bindParts[IDENT_BANANA_BOX_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  14305. }
  14306. else if (bindParts[IDENT_PROPERTY_IDX]) {
  14307. this._bindingParser.parsePropertyBinding(bindParts[IDENT_PROPERTY_IDX], value, false, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
  14308. }
  14309. else if (bindParts[IDENT_EVENT_IDX]) {
  14310. this._bindingParser.parseEvent(bindParts[IDENT_EVENT_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
  14311. }
  14312. }
  14313. else {
  14314. hasBinding = this._bindingParser.parsePropertyInterpolation(name, value, srcSpan, attr.valueSpan, targetMatchableAttrs, targetProps);
  14315. }
  14316. if (!hasBinding) {
  14317. this._bindingParser.parseLiteralAttr(name, value, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
  14318. }
  14319. targetEvents.push.apply(targetEvents, __spreadArray([], __read(boundEvents.map(function (e) { return BoundEventAst.fromParsedEvent(e); }))));
  14320. return hasBinding;
  14321. };
  14322. TemplateParseVisitor.prototype._normalizeAttributeName = function (attrName) {
  14323. return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
  14324. };
  14325. TemplateParseVisitor.prototype._parseVariable = function (identifier, value, sourceSpan, targetVars) {
  14326. if (identifier.indexOf('-') > -1) {
  14327. this._reportError("\"-\" is not allowed in variable names", sourceSpan);
  14328. }
  14329. else if (identifier.length === 0) {
  14330. this._reportError("Variable does not have a name", sourceSpan);
  14331. }
  14332. targetVars.push(new VariableAst(identifier, value, sourceSpan));
  14333. };
  14334. TemplateParseVisitor.prototype._parseReference = function (identifier, value, sourceSpan, targetRefs) {
  14335. if (identifier.indexOf('-') > -1) {
  14336. this._reportError("\"-\" is not allowed in reference names", sourceSpan);
  14337. }
  14338. else if (identifier.length === 0) {
  14339. this._reportError("Reference does not have a name", sourceSpan);
  14340. }
  14341. targetRefs.push(new ElementOrDirectiveRef(identifier, value, sourceSpan));
  14342. };
  14343. TemplateParseVisitor.prototype._parseAssignmentEvent = function (name, expression, sourceSpan, valueSpan, targetMatchableAttrs, targetEvents) {
  14344. this._bindingParser.parseEvent(name + "Change", expression + "=$event", sourceSpan, valueSpan, targetMatchableAttrs, targetEvents);
  14345. };
  14346. TemplateParseVisitor.prototype._parseDirectives = function (selectorMatcher, elementCssSelector) {
  14347. var _this = this;
  14348. // Need to sort the directives so that we get consistent results throughout,
  14349. // as selectorMatcher uses Maps inside.
  14350. // Also deduplicate directives as they might match more than one time!
  14351. var directives = newArray(this.directivesIndex.size);
  14352. // Whether any directive selector matches on the element name
  14353. var matchElement = false;
  14354. selectorMatcher.match(elementCssSelector, function (selector, directive) {
  14355. directives[_this.directivesIndex.get(directive)] = directive;
  14356. matchElement = matchElement || selector.hasElementSelector();
  14357. });
  14358. return {
  14359. directives: directives.filter(function (dir) { return !!dir; }),
  14360. matchElement: matchElement,
  14361. };
  14362. };
  14363. TemplateParseVisitor.prototype._createDirectiveAsts = function (isTemplateElement, elementName, directives, props, elementOrDirectiveRefs, elementSourceSpan, targetReferences, targetBoundDirectivePropNames) {
  14364. var _this = this;
  14365. var matchedReferences = new Set();
  14366. var component = null;
  14367. var directiveAsts = directives.map(function (directive) {
  14368. var sourceSpan = new ParseSourceSpan(elementSourceSpan.start, elementSourceSpan.end, elementSourceSpan.fullStart, "Directive " + identifierName(directive.type));
  14369. if (directive.isComponent) {
  14370. component = directive;
  14371. }
  14372. var directiveProperties = [];
  14373. var boundProperties = _this._bindingParser.createDirectiveHostPropertyAsts(directive, elementName, sourceSpan);
  14374. var hostProperties = boundProperties.map(function (prop) { return BoundElementPropertyAst.fromBoundProperty(prop); });
  14375. // Note: We need to check the host properties here as well,
  14376. // as we don't know the element name in the DirectiveWrapperCompiler yet.
  14377. hostProperties = _this._checkPropertiesInSchema(elementName, hostProperties);
  14378. var parsedEvents = _this._bindingParser.createDirectiveHostEventAsts(directive, sourceSpan);
  14379. _this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties, targetBoundDirectivePropNames);
  14380. elementOrDirectiveRefs.forEach(function (elOrDirRef) {
  14381. if ((elOrDirRef.value.length === 0 && directive.isComponent) ||
  14382. (elOrDirRef.isReferenceToDirective(directive))) {
  14383. targetReferences.push(new ReferenceAst(elOrDirRef.name, createTokenForReference(directive.type.reference), elOrDirRef.value, elOrDirRef.sourceSpan));
  14384. matchedReferences.add(elOrDirRef.name);
  14385. }
  14386. });
  14387. var hostEvents = parsedEvents.map(function (e) { return BoundEventAst.fromParsedEvent(e); });
  14388. var contentQueryStartId = _this.contentQueryStartId;
  14389. _this.contentQueryStartId += directive.queries.length;
  14390. return new DirectiveAst(directive, directiveProperties, hostProperties, hostEvents, contentQueryStartId, sourceSpan);
  14391. });
  14392. elementOrDirectiveRefs.forEach(function (elOrDirRef) {
  14393. if (elOrDirRef.value.length > 0) {
  14394. if (!matchedReferences.has(elOrDirRef.name)) {
  14395. _this._reportError("There is no directive with \"exportAs\" set to \"" + elOrDirRef.value + "\"", elOrDirRef.sourceSpan);
  14396. }
  14397. }
  14398. else if (!component) {
  14399. var refToken = null;
  14400. if (isTemplateElement) {
  14401. refToken = createTokenForExternalReference(_this.reflector, Identifiers$1.TemplateRef);
  14402. }
  14403. targetReferences.push(new ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.value, elOrDirRef.sourceSpan));
  14404. }
  14405. });
  14406. return directiveAsts;
  14407. };
  14408. TemplateParseVisitor.prototype._createDirectivePropertyAsts = function (directiveProperties, boundProps, targetBoundDirectiveProps, targetBoundDirectivePropNames) {
  14409. if (directiveProperties) {
  14410. var boundPropsByName_1 = new Map();
  14411. boundProps.forEach(function (boundProp) {
  14412. var prevValue = boundPropsByName_1.get(boundProp.name);
  14413. if (!prevValue || prevValue.isLiteral) {
  14414. // give [a]="b" a higher precedence than a="b" on the same element
  14415. boundPropsByName_1.set(boundProp.name, boundProp);
  14416. }
  14417. });
  14418. Object.keys(directiveProperties).forEach(function (dirProp) {
  14419. var elProp = directiveProperties[dirProp];
  14420. var boundProp = boundPropsByName_1.get(elProp);
  14421. // Bindings are optional, so this binding only needs to be set up if an expression is given.
  14422. if (boundProp) {
  14423. targetBoundDirectivePropNames.add(boundProp.name);
  14424. if (!isEmptyExpression(boundProp.expression)) {
  14425. targetBoundDirectiveProps.push(new BoundDirectivePropertyAst(dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan));
  14426. }
  14427. }
  14428. });
  14429. }
  14430. };
  14431. TemplateParseVisitor.prototype._createElementPropertyAsts = function (elementName, props, boundDirectivePropNames) {
  14432. var _this = this;
  14433. var boundElementProps = [];
  14434. props.forEach(function (prop) {
  14435. if (!prop.isLiteral && !boundDirectivePropNames.has(prop.name)) {
  14436. var boundProp = _this._bindingParser.createBoundElementProperty(elementName, prop);
  14437. boundElementProps.push(BoundElementPropertyAst.fromBoundProperty(boundProp));
  14438. }
  14439. });
  14440. return this._checkPropertiesInSchema(elementName, boundElementProps);
  14441. };
  14442. TemplateParseVisitor.prototype._findComponentDirectives = function (directives) {
  14443. return directives.filter(function (directive) { return directive.directive.isComponent; });
  14444. };
  14445. TemplateParseVisitor.prototype._findComponentDirectiveNames = function (directives) {
  14446. return this._findComponentDirectives(directives)
  14447. .map(function (directive) { return identifierName(directive.directive.type); });
  14448. };
  14449. TemplateParseVisitor.prototype._assertOnlyOneComponent = function (directives, sourceSpan) {
  14450. var componentTypeNames = this._findComponentDirectiveNames(directives);
  14451. if (componentTypeNames.length > 1) {
  14452. this._reportError("More than one component matched on this element.\n" +
  14453. "Make sure that only one component's selector can match a given element.\n" +
  14454. ("Conflicting components: " + componentTypeNames.join(',')), sourceSpan);
  14455. }
  14456. };
  14457. /**
  14458. * Make sure that non-angular tags conform to the schemas.
  14459. *
  14460. * Note: An element is considered an angular tag when at least one directive selector matches the
  14461. * tag name.
  14462. *
  14463. * @param matchElement Whether any directive has matched on the tag name
  14464. * @param element the html element
  14465. */
  14466. TemplateParseVisitor.prototype._assertElementExists = function (matchElement, element) {
  14467. var elName = element.name.replace(/^:xhtml:/, '');
  14468. if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) {
  14469. var errorMsg = "'" + elName + "' is not a known element:\n";
  14470. errorMsg += "1. If '" + elName + "' is an Angular component, then verify that it is part of this module.\n";
  14471. if (elName.indexOf('-') > -1) {
  14472. errorMsg += "2. If '" + elName + "' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.";
  14473. }
  14474. else {
  14475. errorMsg +=
  14476. "2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
  14477. }
  14478. this._reportError(errorMsg, element.sourceSpan);
  14479. }
  14480. };
  14481. TemplateParseVisitor.prototype._assertNoComponentsNorElementBindingsOnTemplate = function (directives, elementProps, sourceSpan) {
  14482. var _this = this;
  14483. var componentTypeNames = this._findComponentDirectiveNames(directives);
  14484. if (componentTypeNames.length > 0) {
  14485. this._reportError("Components on an embedded template: " + componentTypeNames.join(','), sourceSpan);
  14486. }
  14487. elementProps.forEach(function (prop) {
  14488. _this._reportError("Property binding " + prop.name + " not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the \"@NgModule.declarations\".", sourceSpan);
  14489. });
  14490. };
  14491. TemplateParseVisitor.prototype._assertAllEventsPublishedByDirectives = function (directives, events) {
  14492. var _this = this;
  14493. var allDirectiveEvents = new Set();
  14494. directives.forEach(function (directive) {
  14495. Object.keys(directive.directive.outputs).forEach(function (k) {
  14496. var eventName = directive.directive.outputs[k];
  14497. allDirectiveEvents.add(eventName);
  14498. });
  14499. });
  14500. events.forEach(function (event) {
  14501. if (event.target != null || !allDirectiveEvents.has(event.name)) {
  14502. _this._reportError("Event binding " + event
  14503. .fullName + " not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the \"@NgModule.declarations\".", event.sourceSpan);
  14504. }
  14505. });
  14506. };
  14507. TemplateParseVisitor.prototype._checkPropertiesInSchema = function (elementName, boundProps) {
  14508. var _this = this;
  14509. // Note: We can't filter out empty expressions before this method,
  14510. // as we still want to validate them!
  14511. return boundProps.filter(function (boundProp) {
  14512. if (boundProp.type === 0 /* Property */ &&
  14513. !_this._schemaRegistry.hasProperty(elementName, boundProp.name, _this._schemas)) {
  14514. var errorMsg = "Can't bind to '" + boundProp.name + "' since it isn't a known property of '" + elementName + "'.";
  14515. if (elementName.startsWith('ng-')) {
  14516. errorMsg +=
  14517. "\n1. If '" + boundProp
  14518. .name + "' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component." +
  14519. "\n2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
  14520. }
  14521. else if (elementName.indexOf('-') > -1) {
  14522. errorMsg +=
  14523. "\n1. If '" + elementName + "' is an Angular component and it has '" + boundProp.name + "' input, then verify that it is part of this module." +
  14524. ("\n2. If '" + elementName + "' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.") +
  14525. "\n3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.";
  14526. }
  14527. _this._reportError(errorMsg, boundProp.sourceSpan);
  14528. }
  14529. return !isEmptyExpression(boundProp.value);
  14530. });
  14531. };
  14532. TemplateParseVisitor.prototype._reportError = function (message, sourceSpan, level) {
  14533. if (level === void 0) { level = exports.ParseErrorLevel.ERROR; }
  14534. this._targetErrors.push(new ParseError(sourceSpan, message, level));
  14535. };
  14536. return TemplateParseVisitor;
  14537. }());
  14538. var NonBindableVisitor = /** @class */ (function () {
  14539. function NonBindableVisitor() {
  14540. }
  14541. NonBindableVisitor.prototype.visitElement = function (ast, parent) {
  14542. var preparsedElement = preparseElement(ast);
  14543. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  14544. preparsedElement.type === PreparsedElementType.STYLE ||
  14545. preparsedElement.type === PreparsedElementType.STYLESHEET) {
  14546. // Skipping <script> for security reasons
  14547. // Skipping <style> and stylesheets as we already processed them
  14548. // in the StyleCompiler
  14549. return null;
  14550. }
  14551. var attrNameAndValues = ast.attrs.map(function (attr) { return [attr.name, attr.value]; });
  14552. var selector = createElementCssSelector(ast.name, attrNameAndValues);
  14553. var ngContentIndex = parent.findNgContentIndex(selector);
  14554. var children = visitAll$1(this, ast.children, EMPTY_ELEMENT_CONTEXT);
  14555. return new ElementAst(ast.name, visitAll$1(this, ast.attrs), [], [], [], [], [], false, [], children, ngContentIndex, ast.sourceSpan, ast.endSourceSpan);
  14556. };
  14557. NonBindableVisitor.prototype.visitComment = function (comment, context) {
  14558. return null;
  14559. };
  14560. NonBindableVisitor.prototype.visitAttribute = function (attribute, context) {
  14561. return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
  14562. };
  14563. NonBindableVisitor.prototype.visitText = function (text, parent) {
  14564. var ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
  14565. return new TextAst(text.value, ngContentIndex, text.sourceSpan);
  14566. };
  14567. NonBindableVisitor.prototype.visitExpansion = function (expansion, context) {
  14568. return expansion;
  14569. };
  14570. NonBindableVisitor.prototype.visitExpansionCase = function (expansionCase, context) {
  14571. return expansionCase;
  14572. };
  14573. return NonBindableVisitor;
  14574. }());
  14575. /**
  14576. * A reference to an element or directive in a template. E.g., the reference in this template:
  14577. *
  14578. * <div #myMenu="coolMenu">
  14579. *
  14580. * would be {name: 'myMenu', value: 'coolMenu', sourceSpan: ...}
  14581. */
  14582. var ElementOrDirectiveRef = /** @class */ (function () {
  14583. function ElementOrDirectiveRef(name, value, sourceSpan) {
  14584. this.name = name;
  14585. this.value = value;
  14586. this.sourceSpan = sourceSpan;
  14587. }
  14588. /** Gets whether this is a reference to the given directive. */
  14589. ElementOrDirectiveRef.prototype.isReferenceToDirective = function (directive) {
  14590. return splitExportAs(directive.exportAs).indexOf(this.value) !== -1;
  14591. };
  14592. return ElementOrDirectiveRef;
  14593. }());
  14594. /** Splits a raw, potentially comma-delimited `exportAs` value into an array of names. */
  14595. function splitExportAs(exportAs) {
  14596. return exportAs ? exportAs.split(',').map(function (e) { return e.trim(); }) : [];
  14597. }
  14598. function splitClasses(classAttrValue) {
  14599. return classAttrValue.trim().split(/\s+/g);
  14600. }
  14601. var ElementContext = /** @class */ (function () {
  14602. function ElementContext(isTemplateElement, _ngContentIndexMatcher, _wildcardNgContentIndex, providerContext) {
  14603. this.isTemplateElement = isTemplateElement;
  14604. this._ngContentIndexMatcher = _ngContentIndexMatcher;
  14605. this._wildcardNgContentIndex = _wildcardNgContentIndex;
  14606. this.providerContext = providerContext;
  14607. }
  14608. ElementContext.create = function (isTemplateElement, directives, providerContext) {
  14609. var matcher = new SelectorMatcher();
  14610. var wildcardNgContentIndex = null;
  14611. var component = directives.find(function (directive) { return directive.directive.isComponent; });
  14612. if (component) {
  14613. var ngContentSelectors = component.directive.template.ngContentSelectors;
  14614. for (var i = 0; i < ngContentSelectors.length; i++) {
  14615. var selector = ngContentSelectors[i];
  14616. if (selector === '*') {
  14617. wildcardNgContentIndex = i;
  14618. }
  14619. else {
  14620. matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i);
  14621. }
  14622. }
  14623. }
  14624. return new ElementContext(isTemplateElement, matcher, wildcardNgContentIndex, providerContext);
  14625. };
  14626. ElementContext.prototype.findNgContentIndex = function (selector) {
  14627. var ngContentIndices = [];
  14628. this._ngContentIndexMatcher.match(selector, function (selector, ngContentIndex) {
  14629. ngContentIndices.push(ngContentIndex);
  14630. });
  14631. ngContentIndices.sort();
  14632. if (this._wildcardNgContentIndex != null) {
  14633. ngContentIndices.push(this._wildcardNgContentIndex);
  14634. }
  14635. return ngContentIndices.length > 0 ? ngContentIndices[0] : null;
  14636. };
  14637. return ElementContext;
  14638. }());
  14639. function createElementCssSelector(elementName, attributes) {
  14640. var cssSelector = new CssSelector();
  14641. var elNameNoNs = splitNsName(elementName)[1];
  14642. cssSelector.setElement(elNameNoNs);
  14643. for (var i = 0; i < attributes.length; i++) {
  14644. var attrName = attributes[i][0];
  14645. var attrNameNoNs = splitNsName(attrName)[1];
  14646. var attrValue = attributes[i][1];
  14647. cssSelector.addAttribute(attrNameNoNs, attrValue);
  14648. if (attrName.toLowerCase() == CLASS_ATTR) {
  14649. var classes = splitClasses(attrValue);
  14650. classes.forEach(function (className) { return cssSelector.addClassName(className); });
  14651. }
  14652. }
  14653. return cssSelector;
  14654. }
  14655. var EMPTY_ELEMENT_CONTEXT = new ElementContext(true, new SelectorMatcher(), null, null);
  14656. var NON_BINDABLE_VISITOR = new NonBindableVisitor();
  14657. function _isEmptyTextNode(node) {
  14658. return node instanceof Text$3 && node.value.trim().length == 0;
  14659. }
  14660. function removeSummaryDuplicates(items) {
  14661. var map = new Map();
  14662. items.forEach(function (item) {
  14663. if (!map.get(item.type.reference)) {
  14664. map.set(item.type.reference, item);
  14665. }
  14666. });
  14667. return Array.from(map.values());
  14668. }
  14669. function isEmptyExpression(ast) {
  14670. if (ast instanceof ASTWithSource) {
  14671. ast = ast.ast;
  14672. }
  14673. return ast instanceof EmptyExpr;
  14674. }
  14675. /**
  14676. * @license
  14677. * Copyright Google LLC All Rights Reserved.
  14678. *
  14679. * Use of this source code is governed by an MIT-style license that can be
  14680. * found in the LICENSE file at https://angular.io/license
  14681. */
  14682. /**
  14683. * Parses string representation of a style and converts it into object literal.
  14684. *
  14685. * @param value string representation of style as used in the `style` attribute in HTML.
  14686. * Example: `color: red; height: auto`.
  14687. * @returns An array of style property name and value pairs, e.g. `['color', 'red', 'height',
  14688. * 'auto']`
  14689. */
  14690. function parse(value) {
  14691. // we use a string array here instead of a string map
  14692. // because a string-map is not guaranteed to retain the
  14693. // order of the entries whereas a string array can be
  14694. // constructed in a [key, value, key, value] format.
  14695. var styles = [];
  14696. var i = 0;
  14697. var parenDepth = 0;
  14698. var quote = 0 /* QuoteNone */;
  14699. var valueStart = 0;
  14700. var propStart = 0;
  14701. var currentProp = null;
  14702. var valueHasQuotes = false;
  14703. while (i < value.length) {
  14704. var token = value.charCodeAt(i++);
  14705. switch (token) {
  14706. case 40 /* OpenParen */:
  14707. parenDepth++;
  14708. break;
  14709. case 41 /* CloseParen */:
  14710. parenDepth--;
  14711. break;
  14712. case 39 /* QuoteSingle */:
  14713. // valueStart needs to be there since prop values don't
  14714. // have quotes in CSS
  14715. valueHasQuotes = valueHasQuotes || valueStart > 0;
  14716. if (quote === 0 /* QuoteNone */) {
  14717. quote = 39 /* QuoteSingle */;
  14718. }
  14719. else if (quote === 39 /* QuoteSingle */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
  14720. quote = 0 /* QuoteNone */;
  14721. }
  14722. break;
  14723. case 34 /* QuoteDouble */:
  14724. // same logic as above
  14725. valueHasQuotes = valueHasQuotes || valueStart > 0;
  14726. if (quote === 0 /* QuoteNone */) {
  14727. quote = 34 /* QuoteDouble */;
  14728. }
  14729. else if (quote === 34 /* QuoteDouble */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
  14730. quote = 0 /* QuoteNone */;
  14731. }
  14732. break;
  14733. case 58 /* Colon */:
  14734. if (!currentProp && parenDepth === 0 && quote === 0 /* QuoteNone */) {
  14735. currentProp = hyphenate(value.substring(propStart, i - 1).trim());
  14736. valueStart = i;
  14737. }
  14738. break;
  14739. case 59 /* Semicolon */:
  14740. if (currentProp && valueStart > 0 && parenDepth === 0 && quote === 0 /* QuoteNone */) {
  14741. var styleVal = value.substring(valueStart, i - 1).trim();
  14742. styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
  14743. propStart = i;
  14744. valueStart = 0;
  14745. currentProp = null;
  14746. valueHasQuotes = false;
  14747. }
  14748. break;
  14749. }
  14750. }
  14751. if (currentProp && valueStart) {
  14752. var styleVal = value.substr(valueStart).trim();
  14753. styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
  14754. }
  14755. return styles;
  14756. }
  14757. function stripUnnecessaryQuotes(value) {
  14758. var qS = value.charCodeAt(0);
  14759. var qE = value.charCodeAt(value.length - 1);
  14760. if (qS == qE && (qS == 39 /* QuoteSingle */ || qS == 34 /* QuoteDouble */)) {
  14761. var tempValue = value.substring(1, value.length - 1);
  14762. // special case to avoid using a multi-quoted string that was just chomped
  14763. // (e.g. `font-family: "Verdana", "sans-serif"`)
  14764. if (tempValue.indexOf('\'') == -1 && tempValue.indexOf('"') == -1) {
  14765. value = tempValue;
  14766. }
  14767. }
  14768. return value;
  14769. }
  14770. function hyphenate(value) {
  14771. return value
  14772. .replace(/[a-z][A-Z]/g, function (v) {
  14773. return v.charAt(0) + '-' + v.charAt(1);
  14774. })
  14775. .toLowerCase();
  14776. }
  14777. var IMPORTANT_FLAG = '!important';
  14778. /**
  14779. * Minimum amount of binding slots required in the runtime for style/class bindings.
  14780. *
  14781. * Styling in Angular uses up two slots in the runtime LView/TData data structures to
  14782. * record binding data, property information and metadata.
  14783. *
  14784. * When a binding is registered it will place the following information in the `LView`:
  14785. *
  14786. * slot 1) binding value
  14787. * slot 2) cached value (all other values collected before it in string form)
  14788. *
  14789. * When a binding is registered it will place the following information in the `TData`:
  14790. *
  14791. * slot 1) prop name
  14792. * slot 2) binding index that points to the previous style/class binding (and some extra config
  14793. * values)
  14794. *
  14795. * Let's imagine we have a binding that looks like so:
  14796. *
  14797. * ```
  14798. * <div [style.width]="x" [style.height]="y">
  14799. * ```
  14800. *
  14801. * Our `LView` and `TData` data-structures look like so:
  14802. *
  14803. * ```typescript
  14804. * LView = [
  14805. * // ...
  14806. * x, // value of x
  14807. * "width: x",
  14808. *
  14809. * y, // value of y
  14810. * "width: x; height: y",
  14811. * // ...
  14812. * ];
  14813. *
  14814. * TData = [
  14815. * // ...
  14816. * "width", // binding slot 20
  14817. * 0,
  14818. *
  14819. * "height",
  14820. * 20,
  14821. * // ...
  14822. * ];
  14823. * ```
  14824. *
  14825. * */
  14826. var MIN_STYLING_BINDING_SLOTS_REQUIRED = 2;
  14827. /**
  14828. * Produces creation/update instructions for all styling bindings (class and style)
  14829. *
  14830. * It also produces the creation instruction to register all initial styling values
  14831. * (which are all the static class="..." and style="..." attribute values that exist
  14832. * on an element within a template).
  14833. *
  14834. * The builder class below handles producing instructions for the following cases:
  14835. *
  14836. * - Static style/class attributes (style="..." and class="...")
  14837. * - Dynamic style/class map bindings ([style]="map" and [class]="map|string")
  14838. * - Dynamic style/class property bindings ([style.prop]="exp" and [class.name]="exp")
  14839. *
  14840. * Due to the complex relationship of all of these cases, the instructions generated
  14841. * for these attributes/properties/bindings must be done so in the correct order. The
  14842. * order which these must be generated is as follows:
  14843. *
  14844. * if (createMode) {
  14845. * styling(...)
  14846. * }
  14847. * if (updateMode) {
  14848. * styleMap(...)
  14849. * classMap(...)
  14850. * styleProp(...)
  14851. * classProp(...)
  14852. * }
  14853. *
  14854. * The creation/update methods within the builder class produce these instructions.
  14855. */
  14856. var StylingBuilder = /** @class */ (function () {
  14857. function StylingBuilder(_directiveExpr) {
  14858. this._directiveExpr = _directiveExpr;
  14859. /** Whether or not there are any static styling values present */
  14860. this._hasInitialValues = false;
  14861. /**
  14862. * Whether or not there are any styling bindings present
  14863. * (i.e. `[style]`, `[class]`, `[style.prop]` or `[class.name]`)
  14864. */
  14865. this.hasBindings = false;
  14866. this.hasBindingsWithPipes = false;
  14867. /** the input for [class] (if it exists) */
  14868. this._classMapInput = null;
  14869. /** the input for [style] (if it exists) */
  14870. this._styleMapInput = null;
  14871. /** an array of each [style.prop] input */
  14872. this._singleStyleInputs = null;
  14873. /** an array of each [class.name] input */
  14874. this._singleClassInputs = null;
  14875. this._lastStylingInput = null;
  14876. this._firstStylingInput = null;
  14877. // maps are used instead of hash maps because a Map will
  14878. // retain the ordering of the keys
  14879. /**
  14880. * Represents the location of each style binding in the template
  14881. * (e.g. `<div [style.width]="w" [style.height]="h">` implies
  14882. * that `width=0` and `height=1`)
  14883. */
  14884. this._stylesIndex = new Map();
  14885. /**
  14886. * Represents the location of each class binding in the template
  14887. * (e.g. `<div [class.big]="b" [class.hidden]="h">` implies
  14888. * that `big=0` and `hidden=1`)
  14889. */
  14890. this._classesIndex = new Map();
  14891. this._initialStyleValues = [];
  14892. this._initialClassValues = [];
  14893. }
  14894. /**
  14895. * Registers a given input to the styling builder to be later used when producing AOT code.
  14896. *
  14897. * The code below will only accept the input if it is somehow tied to styling (whether it be
  14898. * style/class bindings or static style/class attributes).
  14899. */
  14900. StylingBuilder.prototype.registerBoundInput = function (input) {
  14901. // [attr.style] or [attr.class] are skipped in the code below,
  14902. // they should not be treated as styling-based bindings since
  14903. // they are intended to be written directly to the attr and
  14904. // will therefore skip all style/class resolution that is present
  14905. // with style="", [style]="" and [style.prop]="", class="",
  14906. // [class.prop]="". [class]="" assignments
  14907. var binding = null;
  14908. var name = input.name;
  14909. switch (input.type) {
  14910. case 0 /* Property */:
  14911. binding = this.registerInputBasedOnName(name, input.value, input.sourceSpan);
  14912. break;
  14913. case 3 /* Style */:
  14914. binding = this.registerStyleInput(name, false, input.value, input.sourceSpan, input.unit);
  14915. break;
  14916. case 2 /* Class */:
  14917. binding = this.registerClassInput(name, false, input.value, input.sourceSpan);
  14918. break;
  14919. }
  14920. return binding ? true : false;
  14921. };
  14922. StylingBuilder.prototype.registerInputBasedOnName = function (name, expression, sourceSpan) {
  14923. var binding = null;
  14924. var prefix = name.substring(0, 6);
  14925. var isStyle = name === 'style' || prefix === 'style.' || prefix === 'style!';
  14926. var isClass = !isStyle && (name === 'class' || prefix === 'class.' || prefix === 'class!');
  14927. if (isStyle || isClass) {
  14928. var isMapBased = name.charAt(5) !== '.'; // style.prop or class.prop makes this a no
  14929. var property = name.substr(isMapBased ? 5 : 6); // the dot explains why there's a +1
  14930. if (isStyle) {
  14931. binding = this.registerStyleInput(property, isMapBased, expression, sourceSpan);
  14932. }
  14933. else {
  14934. binding = this.registerClassInput(property, isMapBased, expression, sourceSpan);
  14935. }
  14936. }
  14937. return binding;
  14938. };
  14939. StylingBuilder.prototype.registerStyleInput = function (name, isMapBased, value, sourceSpan, suffix) {
  14940. if (isEmptyExpression(value)) {
  14941. return null;
  14942. }
  14943. // CSS custom properties are case-sensitive so we shouldn't normalize them.
  14944. // See: https://www.w3.org/TR/css-variables-1/#defining-variables
  14945. if (!isCssCustomProperty(name)) {
  14946. name = hyphenate(name);
  14947. }
  14948. var _a = parseProperty(name), property = _a.property, hasOverrideFlag = _a.hasOverrideFlag, bindingSuffix = _a.suffix;
  14949. suffix = typeof suffix === 'string' && suffix.length !== 0 ? suffix : bindingSuffix;
  14950. var entry = { name: property, suffix: suffix, value: value, sourceSpan: sourceSpan, hasOverrideFlag: hasOverrideFlag };
  14951. if (isMapBased) {
  14952. this._styleMapInput = entry;
  14953. }
  14954. else {
  14955. (this._singleStyleInputs = this._singleStyleInputs || []).push(entry);
  14956. registerIntoMap(this._stylesIndex, property);
  14957. }
  14958. this._lastStylingInput = entry;
  14959. this._firstStylingInput = this._firstStylingInput || entry;
  14960. this._checkForPipes(value);
  14961. this.hasBindings = true;
  14962. return entry;
  14963. };
  14964. StylingBuilder.prototype.registerClassInput = function (name, isMapBased, value, sourceSpan) {
  14965. if (isEmptyExpression(value)) {
  14966. return null;
  14967. }
  14968. var _a = parseProperty(name), property = _a.property, hasOverrideFlag = _a.hasOverrideFlag;
  14969. var entry = { name: property, value: value, sourceSpan: sourceSpan, hasOverrideFlag: hasOverrideFlag, suffix: null };
  14970. if (isMapBased) {
  14971. this._classMapInput = entry;
  14972. }
  14973. else {
  14974. (this._singleClassInputs = this._singleClassInputs || []).push(entry);
  14975. registerIntoMap(this._classesIndex, property);
  14976. }
  14977. this._lastStylingInput = entry;
  14978. this._firstStylingInput = this._firstStylingInput || entry;
  14979. this._checkForPipes(value);
  14980. this.hasBindings = true;
  14981. return entry;
  14982. };
  14983. StylingBuilder.prototype._checkForPipes = function (value) {
  14984. if ((value instanceof ASTWithSource) && (value.ast instanceof BindingPipe)) {
  14985. this.hasBindingsWithPipes = true;
  14986. }
  14987. };
  14988. /**
  14989. * Registers the element's static style string value to the builder.
  14990. *
  14991. * @param value the style string (e.g. `width:100px; height:200px;`)
  14992. */
  14993. StylingBuilder.prototype.registerStyleAttr = function (value) {
  14994. this._initialStyleValues = parse(value);
  14995. this._hasInitialValues = true;
  14996. };
  14997. /**
  14998. * Registers the element's static class string value to the builder.
  14999. *
  15000. * @param value the className string (e.g. `disabled gold zoom`)
  15001. */
  15002. StylingBuilder.prototype.registerClassAttr = function (value) {
  15003. this._initialClassValues = value.trim().split(/\s+/g);
  15004. this._hasInitialValues = true;
  15005. };
  15006. /**
  15007. * Appends all styling-related expressions to the provided attrs array.
  15008. *
  15009. * @param attrs an existing array where each of the styling expressions
  15010. * will be inserted into.
  15011. */
  15012. StylingBuilder.prototype.populateInitialStylingAttrs = function (attrs) {
  15013. // [CLASS_MARKER, 'foo', 'bar', 'baz' ...]
  15014. if (this._initialClassValues.length) {
  15015. attrs.push(literal(1 /* Classes */));
  15016. for (var i = 0; i < this._initialClassValues.length; i++) {
  15017. attrs.push(literal(this._initialClassValues[i]));
  15018. }
  15019. }
  15020. // [STYLE_MARKER, 'width', '200px', 'height', '100px', ...]
  15021. if (this._initialStyleValues.length) {
  15022. attrs.push(literal(2 /* Styles */));
  15023. for (var i = 0; i < this._initialStyleValues.length; i += 2) {
  15024. attrs.push(literal(this._initialStyleValues[i]), literal(this._initialStyleValues[i + 1]));
  15025. }
  15026. }
  15027. };
  15028. /**
  15029. * Builds an instruction with all the expressions and parameters for `elementHostAttrs`.
  15030. *
  15031. * The instruction generation code below is used for producing the AOT statement code which is
  15032. * responsible for registering initial styles (within a directive hostBindings' creation block),
  15033. * as well as any of the provided attribute values, to the directive host element.
  15034. */
  15035. StylingBuilder.prototype.assignHostAttrs = function (attrs, definitionMap) {
  15036. if (this._directiveExpr && (attrs.length || this._hasInitialValues)) {
  15037. this.populateInitialStylingAttrs(attrs);
  15038. definitionMap.set('hostAttrs', literalArr(attrs));
  15039. }
  15040. };
  15041. /**
  15042. * Builds an instruction with all the expressions and parameters for `classMap`.
  15043. *
  15044. * The instruction data will contain all expressions for `classMap` to function
  15045. * which includes the `[class]` expression params.
  15046. */
  15047. StylingBuilder.prototype.buildClassMapInstruction = function (valueConverter) {
  15048. if (this._classMapInput) {
  15049. return this._buildMapBasedInstruction(valueConverter, true, this._classMapInput);
  15050. }
  15051. return null;
  15052. };
  15053. /**
  15054. * Builds an instruction with all the expressions and parameters for `styleMap`.
  15055. *
  15056. * The instruction data will contain all expressions for `styleMap` to function
  15057. * which includes the `[style]` expression params.
  15058. */
  15059. StylingBuilder.prototype.buildStyleMapInstruction = function (valueConverter) {
  15060. if (this._styleMapInput) {
  15061. return this._buildMapBasedInstruction(valueConverter, false, this._styleMapInput);
  15062. }
  15063. return null;
  15064. };
  15065. StylingBuilder.prototype._buildMapBasedInstruction = function (valueConverter, isClassBased, stylingInput) {
  15066. // each styling binding value is stored in the LView
  15067. // map-based bindings allocate two slots: one for the
  15068. // previous binding value and another for the previous
  15069. // className or style attribute value.
  15070. var totalBindingSlotsRequired = MIN_STYLING_BINDING_SLOTS_REQUIRED;
  15071. // these values must be outside of the update block so that they can
  15072. // be evaluated (the AST visit call) during creation time so that any
  15073. // pipes can be picked up in time before the template is built
  15074. var mapValue = stylingInput.value.visit(valueConverter);
  15075. var reference;
  15076. if (mapValue instanceof Interpolation) {
  15077. totalBindingSlotsRequired += mapValue.expressions.length;
  15078. reference = isClassBased ? getClassMapInterpolationExpression(mapValue) :
  15079. getStyleMapInterpolationExpression(mapValue);
  15080. }
  15081. else {
  15082. reference = isClassBased ? Identifiers.classMap : Identifiers.styleMap;
  15083. }
  15084. return {
  15085. reference: reference,
  15086. calls: [{
  15087. supportsInterpolation: true,
  15088. sourceSpan: stylingInput.sourceSpan,
  15089. allocateBindingSlots: totalBindingSlotsRequired,
  15090. params: function (convertFn) {
  15091. var convertResult = convertFn(mapValue);
  15092. var params = Array.isArray(convertResult) ? convertResult : [convertResult];
  15093. return params;
  15094. }
  15095. }]
  15096. };
  15097. };
  15098. StylingBuilder.prototype._buildSingleInputs = function (reference, inputs, valueConverter, getInterpolationExpressionFn, isClassBased) {
  15099. var instructions = [];
  15100. inputs.forEach(function (input) {
  15101. var previousInstruction = instructions[instructions.length - 1];
  15102. var value = input.value.visit(valueConverter);
  15103. var referenceForCall = reference;
  15104. // each styling binding value is stored in the LView
  15105. // but there are two values stored for each binding:
  15106. // 1) the value itself
  15107. // 2) an intermediate value (concatenation of style up to this point).
  15108. // We need to store the intermediate value so that we don't allocate
  15109. // the strings on each CD.
  15110. var totalBindingSlotsRequired = MIN_STYLING_BINDING_SLOTS_REQUIRED;
  15111. if (value instanceof Interpolation) {
  15112. totalBindingSlotsRequired += value.expressions.length;
  15113. if (getInterpolationExpressionFn) {
  15114. referenceForCall = getInterpolationExpressionFn(value);
  15115. }
  15116. }
  15117. var call = {
  15118. sourceSpan: input.sourceSpan,
  15119. allocateBindingSlots: totalBindingSlotsRequired,
  15120. supportsInterpolation: !!getInterpolationExpressionFn,
  15121. params: function (convertFn) {
  15122. // params => stylingProp(propName, value, suffix)
  15123. var params = [];
  15124. params.push(literal(input.name));
  15125. var convertResult = convertFn(value);
  15126. if (Array.isArray(convertResult)) {
  15127. params.push.apply(params, __spreadArray([], __read(convertResult)));
  15128. }
  15129. else {
  15130. params.push(convertResult);
  15131. }
  15132. // [style.prop] bindings may use suffix values (e.g. px, em, etc...), therefore,
  15133. // if that is detected then we need to pass that in as an optional param.
  15134. if (!isClassBased && input.suffix !== null) {
  15135. params.push(literal(input.suffix));
  15136. }
  15137. return params;
  15138. }
  15139. };
  15140. // If we ended up generating a call to the same instruction as the previous styling property
  15141. // we can chain the calls together safely to save some bytes, otherwise we have to generate
  15142. // a separate instruction call. This is primarily a concern with interpolation instructions
  15143. // where we may start off with one `reference`, but end up using another based on the
  15144. // number of interpolations.
  15145. if (previousInstruction && previousInstruction.reference === referenceForCall) {
  15146. previousInstruction.calls.push(call);
  15147. }
  15148. else {
  15149. instructions.push({ reference: referenceForCall, calls: [call] });
  15150. }
  15151. });
  15152. return instructions;
  15153. };
  15154. StylingBuilder.prototype._buildClassInputs = function (valueConverter) {
  15155. if (this._singleClassInputs) {
  15156. return this._buildSingleInputs(Identifiers.classProp, this._singleClassInputs, valueConverter, null, true);
  15157. }
  15158. return [];
  15159. };
  15160. StylingBuilder.prototype._buildStyleInputs = function (valueConverter) {
  15161. if (this._singleStyleInputs) {
  15162. return this._buildSingleInputs(Identifiers.styleProp, this._singleStyleInputs, valueConverter, getStylePropInterpolationExpression, false);
  15163. }
  15164. return [];
  15165. };
  15166. /**
  15167. * Constructs all instructions which contain the expressions that will be placed
  15168. * into the update block of a template function or a directive hostBindings function.
  15169. */
  15170. StylingBuilder.prototype.buildUpdateLevelInstructions = function (valueConverter) {
  15171. var instructions = [];
  15172. if (this.hasBindings) {
  15173. var styleMapInstruction = this.buildStyleMapInstruction(valueConverter);
  15174. if (styleMapInstruction) {
  15175. instructions.push(styleMapInstruction);
  15176. }
  15177. var classMapInstruction = this.buildClassMapInstruction(valueConverter);
  15178. if (classMapInstruction) {
  15179. instructions.push(classMapInstruction);
  15180. }
  15181. instructions.push.apply(instructions, __spreadArray([], __read(this._buildStyleInputs(valueConverter))));
  15182. instructions.push.apply(instructions, __spreadArray([], __read(this._buildClassInputs(valueConverter))));
  15183. }
  15184. return instructions;
  15185. };
  15186. return StylingBuilder;
  15187. }());
  15188. function registerIntoMap(map, key) {
  15189. if (!map.has(key)) {
  15190. map.set(key, map.size);
  15191. }
  15192. }
  15193. function parseProperty(name) {
  15194. var hasOverrideFlag = false;
  15195. var overrideIndex = name.indexOf(IMPORTANT_FLAG);
  15196. if (overrideIndex !== -1) {
  15197. name = overrideIndex > 0 ? name.substring(0, overrideIndex) : '';
  15198. hasOverrideFlag = true;
  15199. }
  15200. var suffix = null;
  15201. var property = name;
  15202. var unitIndex = name.lastIndexOf('.');
  15203. if (unitIndex > 0) {
  15204. suffix = name.substr(unitIndex + 1);
  15205. property = name.substring(0, unitIndex);
  15206. }
  15207. return { property: property, suffix: suffix, hasOverrideFlag: hasOverrideFlag };
  15208. }
  15209. /**
  15210. * Gets the instruction to generate for an interpolated class map.
  15211. * @param interpolation An Interpolation AST
  15212. */
  15213. function getClassMapInterpolationExpression(interpolation) {
  15214. switch (getInterpolationArgsLength(interpolation)) {
  15215. case 1:
  15216. return Identifiers.classMap;
  15217. case 3:
  15218. return Identifiers.classMapInterpolate1;
  15219. case 5:
  15220. return Identifiers.classMapInterpolate2;
  15221. case 7:
  15222. return Identifiers.classMapInterpolate3;
  15223. case 9:
  15224. return Identifiers.classMapInterpolate4;
  15225. case 11:
  15226. return Identifiers.classMapInterpolate5;
  15227. case 13:
  15228. return Identifiers.classMapInterpolate6;
  15229. case 15:
  15230. return Identifiers.classMapInterpolate7;
  15231. case 17:
  15232. return Identifiers.classMapInterpolate8;
  15233. default:
  15234. return Identifiers.classMapInterpolateV;
  15235. }
  15236. }
  15237. /**
  15238. * Gets the instruction to generate for an interpolated style map.
  15239. * @param interpolation An Interpolation AST
  15240. */
  15241. function getStyleMapInterpolationExpression(interpolation) {
  15242. switch (getInterpolationArgsLength(interpolation)) {
  15243. case 1:
  15244. return Identifiers.styleMap;
  15245. case 3:
  15246. return Identifiers.styleMapInterpolate1;
  15247. case 5:
  15248. return Identifiers.styleMapInterpolate2;
  15249. case 7:
  15250. return Identifiers.styleMapInterpolate3;
  15251. case 9:
  15252. return Identifiers.styleMapInterpolate4;
  15253. case 11:
  15254. return Identifiers.styleMapInterpolate5;
  15255. case 13:
  15256. return Identifiers.styleMapInterpolate6;
  15257. case 15:
  15258. return Identifiers.styleMapInterpolate7;
  15259. case 17:
  15260. return Identifiers.styleMapInterpolate8;
  15261. default:
  15262. return Identifiers.styleMapInterpolateV;
  15263. }
  15264. }
  15265. /**
  15266. * Gets the instruction to generate for an interpolated style prop.
  15267. * @param interpolation An Interpolation AST
  15268. */
  15269. function getStylePropInterpolationExpression(interpolation) {
  15270. switch (getInterpolationArgsLength(interpolation)) {
  15271. case 1:
  15272. return Identifiers.styleProp;
  15273. case 3:
  15274. return Identifiers.stylePropInterpolate1;
  15275. case 5:
  15276. return Identifiers.stylePropInterpolate2;
  15277. case 7:
  15278. return Identifiers.stylePropInterpolate3;
  15279. case 9:
  15280. return Identifiers.stylePropInterpolate4;
  15281. case 11:
  15282. return Identifiers.stylePropInterpolate5;
  15283. case 13:
  15284. return Identifiers.stylePropInterpolate6;
  15285. case 15:
  15286. return Identifiers.stylePropInterpolate7;
  15287. case 17:
  15288. return Identifiers.stylePropInterpolate8;
  15289. default:
  15290. return Identifiers.stylePropInterpolateV;
  15291. }
  15292. }
  15293. /**
  15294. * Checks whether property name is a custom CSS property.
  15295. * See: https://www.w3.org/TR/css-variables-1
  15296. */
  15297. function isCssCustomProperty(name) {
  15298. return name.startsWith('--');
  15299. }
  15300. /**
  15301. * @license
  15302. * Copyright Google LLC All Rights Reserved.
  15303. *
  15304. * Use of this source code is governed by an MIT-style license that can be
  15305. * found in the LICENSE file at https://angular.io/license
  15306. */
  15307. (function (TokenType) {
  15308. TokenType[TokenType["Character"] = 0] = "Character";
  15309. TokenType[TokenType["Identifier"] = 1] = "Identifier";
  15310. TokenType[TokenType["PrivateIdentifier"] = 2] = "PrivateIdentifier";
  15311. TokenType[TokenType["Keyword"] = 3] = "Keyword";
  15312. TokenType[TokenType["String"] = 4] = "String";
  15313. TokenType[TokenType["Operator"] = 5] = "Operator";
  15314. TokenType[TokenType["Number"] = 6] = "Number";
  15315. TokenType[TokenType["Error"] = 7] = "Error";
  15316. })(exports.TokenType || (exports.TokenType = {}));
  15317. var KEYWORDS = ['var', 'let', 'as', 'null', 'undefined', 'true', 'false', 'if', 'else', 'this'];
  15318. var Lexer = /** @class */ (function () {
  15319. function Lexer() {
  15320. }
  15321. Lexer.prototype.tokenize = function (text) {
  15322. var scanner = new _Scanner(text);
  15323. var tokens = [];
  15324. var token = scanner.scanToken();
  15325. while (token != null) {
  15326. tokens.push(token);
  15327. token = scanner.scanToken();
  15328. }
  15329. return tokens;
  15330. };
  15331. return Lexer;
  15332. }());
  15333. var Token$1 = /** @class */ (function () {
  15334. function Token(index, end, type, numValue, strValue) {
  15335. this.index = index;
  15336. this.end = end;
  15337. this.type = type;
  15338. this.numValue = numValue;
  15339. this.strValue = strValue;
  15340. }
  15341. Token.prototype.isCharacter = function (code) {
  15342. return this.type == exports.TokenType.Character && this.numValue == code;
  15343. };
  15344. Token.prototype.isNumber = function () {
  15345. return this.type == exports.TokenType.Number;
  15346. };
  15347. Token.prototype.isString = function () {
  15348. return this.type == exports.TokenType.String;
  15349. };
  15350. Token.prototype.isOperator = function (operator) {
  15351. return this.type == exports.TokenType.Operator && this.strValue == operator;
  15352. };
  15353. Token.prototype.isIdentifier = function () {
  15354. return this.type == exports.TokenType.Identifier;
  15355. };
  15356. Token.prototype.isPrivateIdentifier = function () {
  15357. return this.type == exports.TokenType.PrivateIdentifier;
  15358. };
  15359. Token.prototype.isKeyword = function () {
  15360. return this.type == exports.TokenType.Keyword;
  15361. };
  15362. Token.prototype.isKeywordLet = function () {
  15363. return this.type == exports.TokenType.Keyword && this.strValue == 'let';
  15364. };
  15365. Token.prototype.isKeywordAs = function () {
  15366. return this.type == exports.TokenType.Keyword && this.strValue == 'as';
  15367. };
  15368. Token.prototype.isKeywordNull = function () {
  15369. return this.type == exports.TokenType.Keyword && this.strValue == 'null';
  15370. };
  15371. Token.prototype.isKeywordUndefined = function () {
  15372. return this.type == exports.TokenType.Keyword && this.strValue == 'undefined';
  15373. };
  15374. Token.prototype.isKeywordTrue = function () {
  15375. return this.type == exports.TokenType.Keyword && this.strValue == 'true';
  15376. };
  15377. Token.prototype.isKeywordFalse = function () {
  15378. return this.type == exports.TokenType.Keyword && this.strValue == 'false';
  15379. };
  15380. Token.prototype.isKeywordThis = function () {
  15381. return this.type == exports.TokenType.Keyword && this.strValue == 'this';
  15382. };
  15383. Token.prototype.isError = function () {
  15384. return this.type == exports.TokenType.Error;
  15385. };
  15386. Token.prototype.toNumber = function () {
  15387. return this.type == exports.TokenType.Number ? this.numValue : -1;
  15388. };
  15389. Token.prototype.toString = function () {
  15390. switch (this.type) {
  15391. case exports.TokenType.Character:
  15392. case exports.TokenType.Identifier:
  15393. case exports.TokenType.Keyword:
  15394. case exports.TokenType.Operator:
  15395. case exports.TokenType.PrivateIdentifier:
  15396. case exports.TokenType.String:
  15397. case exports.TokenType.Error:
  15398. return this.strValue;
  15399. case exports.TokenType.Number:
  15400. return this.numValue.toString();
  15401. default:
  15402. return null;
  15403. }
  15404. };
  15405. return Token;
  15406. }());
  15407. function newCharacterToken(index, end, code) {
  15408. return new Token$1(index, end, exports.TokenType.Character, code, String.fromCharCode(code));
  15409. }
  15410. function newIdentifierToken(index, end, text) {
  15411. return new Token$1(index, end, exports.TokenType.Identifier, 0, text);
  15412. }
  15413. function newPrivateIdentifierToken(index, end, text) {
  15414. return new Token$1(index, end, exports.TokenType.PrivateIdentifier, 0, text);
  15415. }
  15416. function newKeywordToken(index, end, text) {
  15417. return new Token$1(index, end, exports.TokenType.Keyword, 0, text);
  15418. }
  15419. function newOperatorToken(index, end, text) {
  15420. return new Token$1(index, end, exports.TokenType.Operator, 0, text);
  15421. }
  15422. function newStringToken(index, end, text) {
  15423. return new Token$1(index, end, exports.TokenType.String, 0, text);
  15424. }
  15425. function newNumberToken(index, end, n) {
  15426. return new Token$1(index, end, exports.TokenType.Number, n, '');
  15427. }
  15428. function newErrorToken(index, end, message) {
  15429. return new Token$1(index, end, exports.TokenType.Error, 0, message);
  15430. }
  15431. var EOF = new Token$1(-1, -1, exports.TokenType.Character, 0, '');
  15432. var _Scanner = /** @class */ (function () {
  15433. function _Scanner(input) {
  15434. this.input = input;
  15435. this.peek = 0;
  15436. this.index = -1;
  15437. this.length = input.length;
  15438. this.advance();
  15439. }
  15440. _Scanner.prototype.advance = function () {
  15441. this.peek = ++this.index >= this.length ? $EOF : this.input.charCodeAt(this.index);
  15442. };
  15443. _Scanner.prototype.scanToken = function () {
  15444. var input = this.input, length = this.length;
  15445. var peek = this.peek, index = this.index;
  15446. // Skip whitespace.
  15447. while (peek <= $SPACE) {
  15448. if (++index >= length) {
  15449. peek = $EOF;
  15450. break;
  15451. }
  15452. else {
  15453. peek = input.charCodeAt(index);
  15454. }
  15455. }
  15456. this.peek = peek;
  15457. this.index = index;
  15458. if (index >= length) {
  15459. return null;
  15460. }
  15461. // Handle identifiers and numbers.
  15462. if (isIdentifierStart(peek))
  15463. return this.scanIdentifier();
  15464. if (isDigit(peek))
  15465. return this.scanNumber(index);
  15466. var start = index;
  15467. switch (peek) {
  15468. case $PERIOD:
  15469. this.advance();
  15470. return isDigit(this.peek) ? this.scanNumber(start) :
  15471. newCharacterToken(start, this.index, $PERIOD);
  15472. case $LPAREN:
  15473. case $RPAREN:
  15474. case $LBRACE:
  15475. case $RBRACE:
  15476. case $LBRACKET:
  15477. case $RBRACKET:
  15478. case $COMMA:
  15479. case $COLON:
  15480. case $SEMICOLON:
  15481. return this.scanCharacter(start, peek);
  15482. case $SQ:
  15483. case $DQ:
  15484. return this.scanString();
  15485. case $HASH:
  15486. return this.scanPrivateIdentifier();
  15487. case $PLUS:
  15488. case $MINUS:
  15489. case $STAR:
  15490. case $SLASH:
  15491. case $PERCENT:
  15492. case $CARET:
  15493. return this.scanOperator(start, String.fromCharCode(peek));
  15494. case $QUESTION:
  15495. return this.scanQuestion(start);
  15496. case $LT:
  15497. case $GT:
  15498. return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=');
  15499. case $BANG:
  15500. case $EQ:
  15501. return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=', $EQ, '=');
  15502. case $AMPERSAND:
  15503. return this.scanComplexOperator(start, '&', $AMPERSAND, '&');
  15504. case $BAR:
  15505. return this.scanComplexOperator(start, '|', $BAR, '|');
  15506. case $NBSP:
  15507. while (isWhitespace(this.peek))
  15508. this.advance();
  15509. return this.scanToken();
  15510. }
  15511. this.advance();
  15512. return this.error("Unexpected character [" + String.fromCharCode(peek) + "]", 0);
  15513. };
  15514. _Scanner.prototype.scanCharacter = function (start, code) {
  15515. this.advance();
  15516. return newCharacterToken(start, this.index, code);
  15517. };
  15518. _Scanner.prototype.scanOperator = function (start, str) {
  15519. this.advance();
  15520. return newOperatorToken(start, this.index, str);
  15521. };
  15522. /**
  15523. * Tokenize a 2/3 char long operator
  15524. *
  15525. * @param start start index in the expression
  15526. * @param one first symbol (always part of the operator)
  15527. * @param twoCode code point for the second symbol
  15528. * @param two second symbol (part of the operator when the second code point matches)
  15529. * @param threeCode code point for the third symbol
  15530. * @param three third symbol (part of the operator when provided and matches source expression)
  15531. */
  15532. _Scanner.prototype.scanComplexOperator = function (start, one, twoCode, two, threeCode, three) {
  15533. this.advance();
  15534. var str = one;
  15535. if (this.peek == twoCode) {
  15536. this.advance();
  15537. str += two;
  15538. }
  15539. if (threeCode != null && this.peek == threeCode) {
  15540. this.advance();
  15541. str += three;
  15542. }
  15543. return newOperatorToken(start, this.index, str);
  15544. };
  15545. _Scanner.prototype.scanIdentifier = function () {
  15546. var start = this.index;
  15547. this.advance();
  15548. while (isIdentifierPart(this.peek))
  15549. this.advance();
  15550. var str = this.input.substring(start, this.index);
  15551. return KEYWORDS.indexOf(str) > -1 ? newKeywordToken(start, this.index, str) :
  15552. newIdentifierToken(start, this.index, str);
  15553. };
  15554. /** Scans an ECMAScript private identifier. */
  15555. _Scanner.prototype.scanPrivateIdentifier = function () {
  15556. var start = this.index;
  15557. this.advance();
  15558. if (!isIdentifierStart(this.peek)) {
  15559. return this.error('Invalid character [#]', -1);
  15560. }
  15561. while (isIdentifierPart(this.peek))
  15562. this.advance();
  15563. var identifierName = this.input.substring(start, this.index);
  15564. return newPrivateIdentifierToken(start, this.index, identifierName);
  15565. };
  15566. _Scanner.prototype.scanNumber = function (start) {
  15567. var simple = (this.index === start);
  15568. this.advance(); // Skip initial digit.
  15569. while (true) {
  15570. if (isDigit(this.peek)) {
  15571. // Do nothing.
  15572. }
  15573. else if (this.peek == $PERIOD) {
  15574. simple = false;
  15575. }
  15576. else if (isExponentStart(this.peek)) {
  15577. this.advance();
  15578. if (isExponentSign(this.peek))
  15579. this.advance();
  15580. if (!isDigit(this.peek))
  15581. return this.error('Invalid exponent', -1);
  15582. simple = false;
  15583. }
  15584. else {
  15585. break;
  15586. }
  15587. this.advance();
  15588. }
  15589. var str = this.input.substring(start, this.index);
  15590. var value = simple ? parseIntAutoRadix(str) : parseFloat(str);
  15591. return newNumberToken(start, this.index, value);
  15592. };
  15593. _Scanner.prototype.scanString = function () {
  15594. var start = this.index;
  15595. var quote = this.peek;
  15596. this.advance(); // Skip initial quote.
  15597. var buffer = '';
  15598. var marker = this.index;
  15599. var input = this.input;
  15600. while (this.peek != quote) {
  15601. if (this.peek == $BACKSLASH) {
  15602. buffer += input.substring(marker, this.index);
  15603. this.advance();
  15604. var unescapedCode = void 0;
  15605. // Workaround for TS2.1-introduced type strictness
  15606. this.peek = this.peek;
  15607. if (this.peek == $u) {
  15608. // 4 character hex code for unicode character.
  15609. var hex = input.substring(this.index + 1, this.index + 5);
  15610. if (/^[0-9a-f]+$/i.test(hex)) {
  15611. unescapedCode = parseInt(hex, 16);
  15612. }
  15613. else {
  15614. return this.error("Invalid unicode escape [\\u" + hex + "]", 0);
  15615. }
  15616. for (var i = 0; i < 5; i++) {
  15617. this.advance();
  15618. }
  15619. }
  15620. else {
  15621. unescapedCode = unescape(this.peek);
  15622. this.advance();
  15623. }
  15624. buffer += String.fromCharCode(unescapedCode);
  15625. marker = this.index;
  15626. }
  15627. else if (this.peek == $EOF) {
  15628. return this.error('Unterminated quote', 0);
  15629. }
  15630. else {
  15631. this.advance();
  15632. }
  15633. }
  15634. var last = input.substring(marker, this.index);
  15635. this.advance(); // Skip terminating quote.
  15636. return newStringToken(start, this.index, buffer + last);
  15637. };
  15638. _Scanner.prototype.scanQuestion = function (start) {
  15639. this.advance();
  15640. var str = '?';
  15641. // Either `a ?? b` or 'a?.b'.
  15642. if (this.peek === $QUESTION || this.peek === $PERIOD) {
  15643. str += this.peek === $PERIOD ? '.' : '?';
  15644. this.advance();
  15645. }
  15646. return newOperatorToken(start, this.index, str);
  15647. };
  15648. _Scanner.prototype.error = function (message, offset) {
  15649. var position = this.index + offset;
  15650. return newErrorToken(position, this.index, "Lexer Error: " + message + " at column " + position + " in expression [" + this.input + "]");
  15651. };
  15652. return _Scanner;
  15653. }());
  15654. function isIdentifierStart(code) {
  15655. return ($a <= code && code <= $z) || ($A <= code && code <= $Z) ||
  15656. (code == $_) || (code == $$);
  15657. }
  15658. function isIdentifier(input) {
  15659. if (input.length == 0)
  15660. return false;
  15661. var scanner = new _Scanner(input);
  15662. if (!isIdentifierStart(scanner.peek))
  15663. return false;
  15664. scanner.advance();
  15665. while (scanner.peek !== $EOF) {
  15666. if (!isIdentifierPart(scanner.peek))
  15667. return false;
  15668. scanner.advance();
  15669. }
  15670. return true;
  15671. }
  15672. function isIdentifierPart(code) {
  15673. return isAsciiLetter(code) || isDigit(code) || (code == $_) ||
  15674. (code == $$);
  15675. }
  15676. function isExponentStart(code) {
  15677. return code == $e || code == $E;
  15678. }
  15679. function isExponentSign(code) {
  15680. return code == $MINUS || code == $PLUS;
  15681. }
  15682. function isQuote(code) {
  15683. return code === $SQ || code === $DQ || code === $BT;
  15684. }
  15685. function unescape(code) {
  15686. switch (code) {
  15687. case $n:
  15688. return $LF;
  15689. case $f:
  15690. return $FF;
  15691. case $r:
  15692. return $CR;
  15693. case $t:
  15694. return $TAB;
  15695. case $v:
  15696. return $VTAB;
  15697. default:
  15698. return code;
  15699. }
  15700. }
  15701. function parseIntAutoRadix(text) {
  15702. var result = parseInt(text);
  15703. if (isNaN(result)) {
  15704. throw new Error('Invalid integer literal when parsing ' + text);
  15705. }
  15706. return result;
  15707. }
  15708. var SplitInterpolation = /** @class */ (function () {
  15709. function SplitInterpolation(strings, expressions, offsets) {
  15710. this.strings = strings;
  15711. this.expressions = expressions;
  15712. this.offsets = offsets;
  15713. }
  15714. return SplitInterpolation;
  15715. }());
  15716. var TemplateBindingParseResult = /** @class */ (function () {
  15717. function TemplateBindingParseResult(templateBindings, warnings, errors) {
  15718. this.templateBindings = templateBindings;
  15719. this.warnings = warnings;
  15720. this.errors = errors;
  15721. }
  15722. return TemplateBindingParseResult;
  15723. }());
  15724. var Parser$1 = /** @class */ (function () {
  15725. function Parser(_lexer) {
  15726. this._lexer = _lexer;
  15727. this.errors = [];
  15728. this.simpleExpressionChecker = SimpleExpressionChecker;
  15729. }
  15730. Parser.prototype.parseAction = function (input, location, absoluteOffset, interpolationConfig) {
  15731. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  15732. this._checkNoInterpolation(input, location, interpolationConfig);
  15733. var sourceToLex = this._stripComments(input);
  15734. var tokens = this._lexer.tokenize(this._stripComments(input));
  15735. var ast = new _ParseAST(input, location, absoluteOffset, tokens, sourceToLex.length, true, this.errors, input.length - sourceToLex.length)
  15736. .parseChain();
  15737. return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
  15738. };
  15739. Parser.prototype.parseBinding = function (input, location, absoluteOffset, interpolationConfig) {
  15740. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  15741. var ast = this._parseBindingAst(input, location, absoluteOffset, interpolationConfig);
  15742. return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
  15743. };
  15744. Parser.prototype.checkSimpleExpression = function (ast) {
  15745. var checker = new this.simpleExpressionChecker();
  15746. ast.visit(checker);
  15747. return checker.errors;
  15748. };
  15749. Parser.prototype.parseSimpleBinding = function (input, location, absoluteOffset, interpolationConfig) {
  15750. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  15751. var ast = this._parseBindingAst(input, location, absoluteOffset, interpolationConfig);
  15752. var errors = this.checkSimpleExpression(ast);
  15753. if (errors.length > 0) {
  15754. this._reportError("Host binding expression cannot contain " + errors.join(' '), input, location);
  15755. }
  15756. return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
  15757. };
  15758. Parser.prototype._reportError = function (message, input, errLocation, ctxLocation) {
  15759. this.errors.push(new ParserError(message, input, errLocation, ctxLocation));
  15760. };
  15761. Parser.prototype._parseBindingAst = function (input, location, absoluteOffset, interpolationConfig) {
  15762. // Quotes expressions use 3rd-party expression language. We don't want to use
  15763. // our lexer or parser for that, so we check for that ahead of time.
  15764. var quote = this._parseQuote(input, location, absoluteOffset);
  15765. if (quote != null) {
  15766. return quote;
  15767. }
  15768. this._checkNoInterpolation(input, location, interpolationConfig);
  15769. var sourceToLex = this._stripComments(input);
  15770. var tokens = this._lexer.tokenize(sourceToLex);
  15771. return new _ParseAST(input, location, absoluteOffset, tokens, sourceToLex.length, false, this.errors, input.length - sourceToLex.length)
  15772. .parseChain();
  15773. };
  15774. Parser.prototype._parseQuote = function (input, location, absoluteOffset) {
  15775. if (input == null)
  15776. return null;
  15777. var prefixSeparatorIndex = input.indexOf(':');
  15778. if (prefixSeparatorIndex == -1)
  15779. return null;
  15780. var prefix = input.substring(0, prefixSeparatorIndex).trim();
  15781. if (!isIdentifier(prefix))
  15782. return null;
  15783. var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);
  15784. var span = new ParseSpan(0, input.length);
  15785. return new Quote(span, span.toAbsolute(absoluteOffset), prefix, uninterpretedExpression, location);
  15786. };
  15787. /**
  15788. * Parse microsyntax template expression and return a list of bindings or
  15789. * parsing errors in case the given expression is invalid.
  15790. *
  15791. * For example,
  15792. * ```
  15793. * <div *ngFor="let item of items">
  15794. * ^ ^ absoluteValueOffset for `templateValue`
  15795. * absoluteKeyOffset for `templateKey`
  15796. * ```
  15797. * contains three bindings:
  15798. * 1. ngFor -> null
  15799. * 2. item -> NgForOfContext.$implicit
  15800. * 3. ngForOf -> items
  15801. *
  15802. * This is apparent from the de-sugared template:
  15803. * ```
  15804. * <ng-template ngFor let-item [ngForOf]="items">
  15805. * ```
  15806. *
  15807. * @param templateKey name of directive, without the * prefix. For example: ngIf, ngFor
  15808. * @param templateValue RHS of the microsyntax attribute
  15809. * @param templateUrl template filename if it's external, component filename if it's inline
  15810. * @param absoluteKeyOffset start of the `templateKey`
  15811. * @param absoluteValueOffset start of the `templateValue`
  15812. */
  15813. Parser.prototype.parseTemplateBindings = function (templateKey, templateValue, templateUrl, absoluteKeyOffset, absoluteValueOffset) {
  15814. var tokens = this._lexer.tokenize(templateValue);
  15815. var parser = new _ParseAST(templateValue, templateUrl, absoluteValueOffset, tokens, templateValue.length, false /* parseAction */, this.errors, 0 /* relative offset */);
  15816. return parser.parseTemplateBindings({
  15817. source: templateKey,
  15818. span: new AbsoluteSourceSpan(absoluteKeyOffset, absoluteKeyOffset + templateKey.length),
  15819. });
  15820. };
  15821. Parser.prototype.parseInterpolation = function (input, location, absoluteOffset, interpolationConfig) {
  15822. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  15823. var _b = this.splitInterpolation(input, location, interpolationConfig), strings = _b.strings, expressions = _b.expressions, offsets = _b.offsets;
  15824. if (expressions.length === 0)
  15825. return null;
  15826. var expressionNodes = [];
  15827. for (var i = 0; i < expressions.length; ++i) {
  15828. var expressionText = expressions[i].text;
  15829. var sourceToLex = this._stripComments(expressionText);
  15830. var tokens = this._lexer.tokenize(sourceToLex);
  15831. var ast = new _ParseAST(input, location, absoluteOffset, tokens, sourceToLex.length, false, this.errors, offsets[i] + (expressionText.length - sourceToLex.length))
  15832. .parseChain();
  15833. expressionNodes.push(ast);
  15834. }
  15835. return this.createInterpolationAst(strings.map(function (s) { return s.text; }), expressionNodes, input, location, absoluteOffset);
  15836. };
  15837. /**
  15838. * Similar to `parseInterpolation`, but treats the provided string as a single expression
  15839. * element that would normally appear within the interpolation prefix and suffix (`{{` and `}}`).
  15840. * This is used for parsing the switch expression in ICUs.
  15841. */
  15842. Parser.prototype.parseInterpolationExpression = function (expression, location, absoluteOffset) {
  15843. var sourceToLex = this._stripComments(expression);
  15844. var tokens = this._lexer.tokenize(sourceToLex);
  15845. var ast = new _ParseAST(expression, location, absoluteOffset, tokens, sourceToLex.length,
  15846. /* parseAction */ false, this.errors, 0)
  15847. .parseChain();
  15848. var strings = ['', '']; // The prefix and suffix strings are both empty
  15849. return this.createInterpolationAst(strings, [ast], expression, location, absoluteOffset);
  15850. };
  15851. Parser.prototype.createInterpolationAst = function (strings, expressions, input, location, absoluteOffset) {
  15852. var span = new ParseSpan(0, input.length);
  15853. var interpolation = new Interpolation(span, span.toAbsolute(absoluteOffset), strings, expressions);
  15854. return new ASTWithSource(interpolation, input, location, absoluteOffset, this.errors);
  15855. };
  15856. /**
  15857. * Splits a string of text into "raw" text segments and expressions present in interpolations in
  15858. * the string.
  15859. * Returns `null` if there are no interpolations, otherwise a
  15860. * `SplitInterpolation` with splits that look like
  15861. * <raw text> <expression> <raw text> ... <raw text> <expression> <raw text>
  15862. */
  15863. Parser.prototype.splitInterpolation = function (input, location, interpolationConfig) {
  15864. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  15865. var strings = [];
  15866. var expressions = [];
  15867. var offsets = [];
  15868. var i = 0;
  15869. var atInterpolation = false;
  15870. var extendLastString = false;
  15871. var interpStart = interpolationConfig.start, interpEnd = interpolationConfig.end;
  15872. while (i < input.length) {
  15873. if (!atInterpolation) {
  15874. // parse until starting {{
  15875. var start = i;
  15876. i = input.indexOf(interpStart, i);
  15877. if (i === -1) {
  15878. i = input.length;
  15879. }
  15880. var text = input.substring(start, i);
  15881. strings.push({ text: text, start: start, end: i });
  15882. atInterpolation = true;
  15883. }
  15884. else {
  15885. // parse from starting {{ to ending }} while ignoring content inside quotes.
  15886. var fullStart = i;
  15887. var exprStart = fullStart + interpStart.length;
  15888. var exprEnd = this._getInterpolationEndIndex(input, interpEnd, exprStart);
  15889. if (exprEnd === -1) {
  15890. // Could not find the end of the interpolation; do not parse an expression.
  15891. // Instead we should extend the content on the last raw string.
  15892. atInterpolation = false;
  15893. extendLastString = true;
  15894. break;
  15895. }
  15896. var fullEnd = exprEnd + interpEnd.length;
  15897. var text = input.substring(exprStart, exprEnd);
  15898. if (text.trim().length === 0) {
  15899. this._reportError('Blank expressions are not allowed in interpolated strings', input, "at column " + i + " in", location);
  15900. }
  15901. expressions.push({ text: text, start: fullStart, end: fullEnd });
  15902. offsets.push(exprStart);
  15903. i = fullEnd;
  15904. atInterpolation = false;
  15905. }
  15906. }
  15907. if (!atInterpolation) {
  15908. // If we are now at a text section, add the remaining content as a raw string.
  15909. if (extendLastString) {
  15910. var piece = strings[strings.length - 1];
  15911. piece.text += input.substring(i);
  15912. piece.end = input.length;
  15913. }
  15914. else {
  15915. strings.push({ text: input.substring(i), start: i, end: input.length });
  15916. }
  15917. }
  15918. return new SplitInterpolation(strings, expressions, offsets);
  15919. };
  15920. Parser.prototype.wrapLiteralPrimitive = function (input, location, absoluteOffset) {
  15921. var span = new ParseSpan(0, input == null ? 0 : input.length);
  15922. return new ASTWithSource(new LiteralPrimitive(span, span.toAbsolute(absoluteOffset), input), input, location, absoluteOffset, this.errors);
  15923. };
  15924. Parser.prototype._stripComments = function (input) {
  15925. var i = this._commentStart(input);
  15926. return i != null ? input.substring(0, i).trim() : input;
  15927. };
  15928. Parser.prototype._commentStart = function (input) {
  15929. var outerQuote = null;
  15930. for (var i = 0; i < input.length - 1; i++) {
  15931. var char = input.charCodeAt(i);
  15932. var nextChar = input.charCodeAt(i + 1);
  15933. if (char === $SLASH && nextChar == $SLASH && outerQuote == null)
  15934. return i;
  15935. if (outerQuote === char) {
  15936. outerQuote = null;
  15937. }
  15938. else if (outerQuote == null && isQuote(char)) {
  15939. outerQuote = char;
  15940. }
  15941. }
  15942. return null;
  15943. };
  15944. Parser.prototype._checkNoInterpolation = function (input, location, _b) {
  15945. var e_1, _c;
  15946. var start = _b.start, end = _b.end;
  15947. var startIndex = -1;
  15948. var endIndex = -1;
  15949. try {
  15950. for (var _d = __values(this._forEachUnquotedChar(input, 0)), _e = _d.next(); !_e.done; _e = _d.next()) {
  15951. var charIndex = _e.value;
  15952. if (startIndex === -1) {
  15953. if (input.startsWith(start)) {
  15954. startIndex = charIndex;
  15955. }
  15956. }
  15957. else {
  15958. endIndex = this._getInterpolationEndIndex(input, end, charIndex);
  15959. if (endIndex > -1) {
  15960. break;
  15961. }
  15962. }
  15963. }
  15964. }
  15965. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  15966. finally {
  15967. try {
  15968. if (_e && !_e.done && (_c = _d.return)) _c.call(_d);
  15969. }
  15970. finally { if (e_1) throw e_1.error; }
  15971. }
  15972. if (startIndex > -1 && endIndex > -1) {
  15973. this._reportError("Got interpolation (" + start + end + ") where expression was expected", input, "at column " + startIndex + " in", location);
  15974. }
  15975. };
  15976. /**
  15977. * Finds the index of the end of an interpolation expression
  15978. * while ignoring comments and quoted content.
  15979. */
  15980. Parser.prototype._getInterpolationEndIndex = function (input, expressionEnd, start) {
  15981. var e_2, _b;
  15982. try {
  15983. for (var _c = __values(this._forEachUnquotedChar(input, start)), _d = _c.next(); !_d.done; _d = _c.next()) {
  15984. var charIndex = _d.value;
  15985. if (input.startsWith(expressionEnd, charIndex)) {
  15986. return charIndex;
  15987. }
  15988. // Nothing else in the expression matters after we've
  15989. // hit a comment so look directly for the end token.
  15990. if (input.startsWith('//', charIndex)) {
  15991. return input.indexOf(expressionEnd, charIndex);
  15992. }
  15993. }
  15994. }
  15995. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  15996. finally {
  15997. try {
  15998. if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
  15999. }
  16000. finally { if (e_2) throw e_2.error; }
  16001. }
  16002. return -1;
  16003. };
  16004. /**
  16005. * Generator used to iterate over the character indexes of a string that are outside of quotes.
  16006. * @param input String to loop through.
  16007. * @param start Index within the string at which to start.
  16008. */
  16009. Parser.prototype._forEachUnquotedChar = function (input, start) {
  16010. var currentQuote, escapeCount, i, char;
  16011. return __generator(this, function (_b) {
  16012. switch (_b.label) {
  16013. case 0:
  16014. currentQuote = null;
  16015. escapeCount = 0;
  16016. i = start;
  16017. _b.label = 1;
  16018. case 1:
  16019. if (!(i < input.length)) return [3 /*break*/, 6];
  16020. char = input[i];
  16021. if (!(isQuote(input.charCodeAt(i)) && (currentQuote === null || currentQuote === char) &&
  16022. escapeCount % 2 === 0)) return [3 /*break*/, 2];
  16023. currentQuote = currentQuote === null ? char : null;
  16024. return [3 /*break*/, 4];
  16025. case 2:
  16026. if (!(currentQuote === null)) return [3 /*break*/, 4];
  16027. return [4 /*yield*/, i];
  16028. case 3:
  16029. _b.sent();
  16030. _b.label = 4;
  16031. case 4:
  16032. escapeCount = char === '\\' ? escapeCount + 1 : 0;
  16033. _b.label = 5;
  16034. case 5:
  16035. i++;
  16036. return [3 /*break*/, 1];
  16037. case 6: return [2 /*return*/];
  16038. }
  16039. });
  16040. };
  16041. return Parser;
  16042. }());
  16043. var IvyParser = /** @class */ (function (_super) {
  16044. __extends(IvyParser, _super);
  16045. function IvyParser() {
  16046. var _this = _super.apply(this, __spreadArray([], __read(arguments))) || this;
  16047. _this.simpleExpressionChecker = IvySimpleExpressionChecker;
  16048. return _this;
  16049. }
  16050. return IvyParser;
  16051. }(Parser$1));
  16052. /** Describes a stateful context an expression parser is in. */
  16053. var ParseContextFlags;
  16054. (function (ParseContextFlags) {
  16055. ParseContextFlags[ParseContextFlags["None"] = 0] = "None";
  16056. /**
  16057. * A Writable context is one in which a value may be written to an lvalue.
  16058. * For example, after we see a property access, we may expect a write to the
  16059. * property via the "=" operator.
  16060. * prop
  16061. * ^ possible "=" after
  16062. */
  16063. ParseContextFlags[ParseContextFlags["Writable"] = 1] = "Writable";
  16064. })(ParseContextFlags || (ParseContextFlags = {}));
  16065. var _ParseAST = /** @class */ (function () {
  16066. function _ParseAST(input, location, absoluteOffset, tokens, inputLength, parseAction, errors, offset) {
  16067. this.input = input;
  16068. this.location = location;
  16069. this.absoluteOffset = absoluteOffset;
  16070. this.tokens = tokens;
  16071. this.inputLength = inputLength;
  16072. this.parseAction = parseAction;
  16073. this.errors = errors;
  16074. this.offset = offset;
  16075. this.rparensExpected = 0;
  16076. this.rbracketsExpected = 0;
  16077. this.rbracesExpected = 0;
  16078. this.context = ParseContextFlags.None;
  16079. // Cache of expression start and input indeces to the absolute source span they map to, used to
  16080. // prevent creating superfluous source spans in `sourceSpan`.
  16081. // A serial of the expression start and input index is used for mapping because both are stateful
  16082. // and may change for subsequent expressions visited by the parser.
  16083. this.sourceSpanCache = new Map();
  16084. this.index = 0;
  16085. }
  16086. _ParseAST.prototype.peek = function (offset) {
  16087. var i = this.index + offset;
  16088. return i < this.tokens.length ? this.tokens[i] : EOF;
  16089. };
  16090. Object.defineProperty(_ParseAST.prototype, "next", {
  16091. get: function () {
  16092. return this.peek(0);
  16093. },
  16094. enumerable: false,
  16095. configurable: true
  16096. });
  16097. Object.defineProperty(_ParseAST.prototype, "atEOF", {
  16098. /** Whether all the parser input has been processed. */
  16099. get: function () {
  16100. return this.index >= this.tokens.length;
  16101. },
  16102. enumerable: false,
  16103. configurable: true
  16104. });
  16105. Object.defineProperty(_ParseAST.prototype, "inputIndex", {
  16106. /**
  16107. * Index of the next token to be processed, or the end of the last token if all have been
  16108. * processed.
  16109. */
  16110. get: function () {
  16111. return this.atEOF ? this.currentEndIndex : this.next.index + this.offset;
  16112. },
  16113. enumerable: false,
  16114. configurable: true
  16115. });
  16116. Object.defineProperty(_ParseAST.prototype, "currentEndIndex", {
  16117. /**
  16118. * End index of the last processed token, or the start of the first token if none have been
  16119. * processed.
  16120. */
  16121. get: function () {
  16122. if (this.index > 0) {
  16123. var curToken = this.peek(-1);
  16124. return curToken.end + this.offset;
  16125. }
  16126. // No tokens have been processed yet; return the next token's start or the length of the input
  16127. // if there is no token.
  16128. if (this.tokens.length === 0) {
  16129. return this.inputLength + this.offset;
  16130. }
  16131. return this.next.index + this.offset;
  16132. },
  16133. enumerable: false,
  16134. configurable: true
  16135. });
  16136. Object.defineProperty(_ParseAST.prototype, "currentAbsoluteOffset", {
  16137. /**
  16138. * Returns the absolute offset of the start of the current token.
  16139. */
  16140. get: function () {
  16141. return this.absoluteOffset + this.inputIndex;
  16142. },
  16143. enumerable: false,
  16144. configurable: true
  16145. });
  16146. /**
  16147. * Retrieve a `ParseSpan` from `start` to the current position (or to `artificialEndIndex` if
  16148. * provided).
  16149. *
  16150. * @param start Position from which the `ParseSpan` will start.
  16151. * @param artificialEndIndex Optional ending index to be used if provided (and if greater than the
  16152. * natural ending index)
  16153. */
  16154. _ParseAST.prototype.span = function (start, artificialEndIndex) {
  16155. var endIndex = this.currentEndIndex;
  16156. if (artificialEndIndex !== undefined && artificialEndIndex > this.currentEndIndex) {
  16157. endIndex = artificialEndIndex;
  16158. }
  16159. // In some unusual parsing scenarios (like when certain tokens are missing and an `EmptyExpr` is
  16160. // being created), the current token may already be advanced beyond the `currentEndIndex`. This
  16161. // appears to be a deep-seated parser bug.
  16162. //
  16163. // As a workaround for now, swap the start and end indices to ensure a valid `ParseSpan`.
  16164. // TODO(alxhub): fix the bug upstream in the parser state, and remove this workaround.
  16165. if (start > endIndex) {
  16166. var tmp = endIndex;
  16167. endIndex = start;
  16168. start = tmp;
  16169. }
  16170. return new ParseSpan(start, endIndex);
  16171. };
  16172. _ParseAST.prototype.sourceSpan = function (start, artificialEndIndex) {
  16173. var serial = start + "@" + this.inputIndex + ":" + artificialEndIndex;
  16174. if (!this.sourceSpanCache.has(serial)) {
  16175. this.sourceSpanCache.set(serial, this.span(start, artificialEndIndex).toAbsolute(this.absoluteOffset));
  16176. }
  16177. return this.sourceSpanCache.get(serial);
  16178. };
  16179. _ParseAST.prototype.advance = function () {
  16180. this.index++;
  16181. };
  16182. /**
  16183. * Executes a callback in the provided context.
  16184. */
  16185. _ParseAST.prototype.withContext = function (context, cb) {
  16186. this.context |= context;
  16187. var ret = cb();
  16188. this.context ^= context;
  16189. return ret;
  16190. };
  16191. _ParseAST.prototype.consumeOptionalCharacter = function (code) {
  16192. if (this.next.isCharacter(code)) {
  16193. this.advance();
  16194. return true;
  16195. }
  16196. else {
  16197. return false;
  16198. }
  16199. };
  16200. _ParseAST.prototype.peekKeywordLet = function () {
  16201. return this.next.isKeywordLet();
  16202. };
  16203. _ParseAST.prototype.peekKeywordAs = function () {
  16204. return this.next.isKeywordAs();
  16205. };
  16206. /**
  16207. * Consumes an expected character, otherwise emits an error about the missing expected character
  16208. * and skips over the token stream until reaching a recoverable point.
  16209. *
  16210. * See `this.error` and `this.skip` for more details.
  16211. */
  16212. _ParseAST.prototype.expectCharacter = function (code) {
  16213. if (this.consumeOptionalCharacter(code))
  16214. return;
  16215. this.error("Missing expected " + String.fromCharCode(code));
  16216. };
  16217. _ParseAST.prototype.consumeOptionalOperator = function (op) {
  16218. if (this.next.isOperator(op)) {
  16219. this.advance();
  16220. return true;
  16221. }
  16222. else {
  16223. return false;
  16224. }
  16225. };
  16226. _ParseAST.prototype.expectOperator = function (operator) {
  16227. if (this.consumeOptionalOperator(operator))
  16228. return;
  16229. this.error("Missing expected operator " + operator);
  16230. };
  16231. _ParseAST.prototype.prettyPrintToken = function (tok) {
  16232. return tok === EOF ? 'end of input' : "token " + tok;
  16233. };
  16234. _ParseAST.prototype.expectIdentifierOrKeyword = function () {
  16235. var n = this.next;
  16236. if (!n.isIdentifier() && !n.isKeyword()) {
  16237. if (n.isPrivateIdentifier()) {
  16238. this._reportErrorForPrivateIdentifier(n, 'expected identifier or keyword');
  16239. }
  16240. else {
  16241. this.error("Unexpected " + this.prettyPrintToken(n) + ", expected identifier or keyword");
  16242. }
  16243. return null;
  16244. }
  16245. this.advance();
  16246. return n.toString();
  16247. };
  16248. _ParseAST.prototype.expectIdentifierOrKeywordOrString = function () {
  16249. var n = this.next;
  16250. if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) {
  16251. if (n.isPrivateIdentifier()) {
  16252. this._reportErrorForPrivateIdentifier(n, 'expected identifier, keyword or string');
  16253. }
  16254. else {
  16255. this.error("Unexpected " + this.prettyPrintToken(n) + ", expected identifier, keyword, or string");
  16256. }
  16257. return '';
  16258. }
  16259. this.advance();
  16260. return n.toString();
  16261. };
  16262. _ParseAST.prototype.parseChain = function () {
  16263. var exprs = [];
  16264. var start = this.inputIndex;
  16265. while (this.index < this.tokens.length) {
  16266. var expr = this.parsePipe();
  16267. exprs.push(expr);
  16268. if (this.consumeOptionalCharacter($SEMICOLON)) {
  16269. if (!this.parseAction) {
  16270. this.error('Binding expression cannot contain chained expression');
  16271. }
  16272. while (this.consumeOptionalCharacter($SEMICOLON)) {
  16273. } // read all semicolons
  16274. }
  16275. else if (this.index < this.tokens.length) {
  16276. this.error("Unexpected token '" + this.next + "'");
  16277. }
  16278. }
  16279. if (exprs.length == 0) {
  16280. // We have no expressions so create an empty expression that spans the entire input length
  16281. var artificialStart = this.offset;
  16282. var artificialEnd = this.offset + this.inputLength;
  16283. return new EmptyExpr(this.span(artificialStart, artificialEnd), this.sourceSpan(artificialStart, artificialEnd));
  16284. }
  16285. if (exprs.length == 1)
  16286. return exprs[0];
  16287. return new Chain(this.span(start), this.sourceSpan(start), exprs);
  16288. };
  16289. _ParseAST.prototype.parsePipe = function () {
  16290. var start = this.inputIndex;
  16291. var result = this.parseExpression();
  16292. if (this.consumeOptionalOperator('|')) {
  16293. if (this.parseAction) {
  16294. this.error('Cannot have a pipe in an action expression');
  16295. }
  16296. do {
  16297. var nameStart = this.inputIndex;
  16298. var nameId = this.expectIdentifierOrKeyword();
  16299. var nameSpan = void 0;
  16300. var fullSpanEnd = undefined;
  16301. if (nameId !== null) {
  16302. nameSpan = this.sourceSpan(nameStart);
  16303. }
  16304. else {
  16305. // No valid identifier was found, so we'll assume an empty pipe name ('').
  16306. nameId = '';
  16307. // However, there may have been whitespace present between the pipe character and the next
  16308. // token in the sequence (or the end of input). We want to track this whitespace so that
  16309. // the `BindingPipe` we produce covers not just the pipe character, but any trailing
  16310. // whitespace beyond it. Another way of thinking about this is that the zero-length name
  16311. // is assumed to be at the end of any whitespace beyond the pipe character.
  16312. //
  16313. // Therefore, we push the end of the `ParseSpan` for this pipe all the way up to the
  16314. // beginning of the next token, or until the end of input if the next token is EOF.
  16315. fullSpanEnd = this.next.index !== -1 ? this.next.index : this.inputLength + this.offset;
  16316. // The `nameSpan` for an empty pipe name is zero-length at the end of any whitespace
  16317. // beyond the pipe character.
  16318. nameSpan = new ParseSpan(fullSpanEnd, fullSpanEnd).toAbsolute(this.absoluteOffset);
  16319. }
  16320. var args = [];
  16321. while (this.consumeOptionalCharacter($COLON)) {
  16322. args.push(this.parseExpression());
  16323. // If there are additional expressions beyond the name, then the artificial end for the
  16324. // name is no longer relevant.
  16325. }
  16326. result = new BindingPipe(this.span(start), this.sourceSpan(start, fullSpanEnd), result, nameId, args, nameSpan);
  16327. } while (this.consumeOptionalOperator('|'));
  16328. }
  16329. return result;
  16330. };
  16331. _ParseAST.prototype.parseExpression = function () {
  16332. return this.parseConditional();
  16333. };
  16334. _ParseAST.prototype.parseConditional = function () {
  16335. var start = this.inputIndex;
  16336. var result = this.parseLogicalOr();
  16337. if (this.consumeOptionalOperator('?')) {
  16338. var yes = this.parsePipe();
  16339. var no = void 0;
  16340. if (!this.consumeOptionalCharacter($COLON)) {
  16341. var end = this.inputIndex;
  16342. var expression = this.input.substring(start, end);
  16343. this.error("Conditional expression " + expression + " requires all 3 expressions");
  16344. no = new EmptyExpr(this.span(start), this.sourceSpan(start));
  16345. }
  16346. else {
  16347. no = this.parsePipe();
  16348. }
  16349. return new Conditional(this.span(start), this.sourceSpan(start), result, yes, no);
  16350. }
  16351. else {
  16352. return result;
  16353. }
  16354. };
  16355. _ParseAST.prototype.parseLogicalOr = function () {
  16356. // '||'
  16357. var start = this.inputIndex;
  16358. var result = this.parseLogicalAnd();
  16359. while (this.consumeOptionalOperator('||')) {
  16360. var right = this.parseLogicalAnd();
  16361. result = new Binary(this.span(start), this.sourceSpan(start), '||', result, right);
  16362. }
  16363. return result;
  16364. };
  16365. _ParseAST.prototype.parseLogicalAnd = function () {
  16366. // '&&'
  16367. var start = this.inputIndex;
  16368. var result = this.parseNullishCoalescing();
  16369. while (this.consumeOptionalOperator('&&')) {
  16370. var right = this.parseNullishCoalescing();
  16371. result = new Binary(this.span(start), this.sourceSpan(start), '&&', result, right);
  16372. }
  16373. return result;
  16374. };
  16375. _ParseAST.prototype.parseNullishCoalescing = function () {
  16376. // '??'
  16377. var start = this.inputIndex;
  16378. var result = this.parseEquality();
  16379. while (this.consumeOptionalOperator('??')) {
  16380. var right = this.parseEquality();
  16381. result = new Binary(this.span(start), this.sourceSpan(start), '??', result, right);
  16382. }
  16383. return result;
  16384. };
  16385. _ParseAST.prototype.parseEquality = function () {
  16386. // '==','!=','===','!=='
  16387. var start = this.inputIndex;
  16388. var result = this.parseRelational();
  16389. while (this.next.type == exports.TokenType.Operator) {
  16390. var operator = this.next.strValue;
  16391. switch (operator) {
  16392. case '==':
  16393. case '===':
  16394. case '!=':
  16395. case '!==':
  16396. this.advance();
  16397. var right = this.parseRelational();
  16398. result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
  16399. continue;
  16400. }
  16401. break;
  16402. }
  16403. return result;
  16404. };
  16405. _ParseAST.prototype.parseRelational = function () {
  16406. // '<', '>', '<=', '>='
  16407. var start = this.inputIndex;
  16408. var result = this.parseAdditive();
  16409. while (this.next.type == exports.TokenType.Operator) {
  16410. var operator = this.next.strValue;
  16411. switch (operator) {
  16412. case '<':
  16413. case '>':
  16414. case '<=':
  16415. case '>=':
  16416. this.advance();
  16417. var right = this.parseAdditive();
  16418. result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
  16419. continue;
  16420. }
  16421. break;
  16422. }
  16423. return result;
  16424. };
  16425. _ParseAST.prototype.parseAdditive = function () {
  16426. // '+', '-'
  16427. var start = this.inputIndex;
  16428. var result = this.parseMultiplicative();
  16429. while (this.next.type == exports.TokenType.Operator) {
  16430. var operator = this.next.strValue;
  16431. switch (operator) {
  16432. case '+':
  16433. case '-':
  16434. this.advance();
  16435. var right = this.parseMultiplicative();
  16436. result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
  16437. continue;
  16438. }
  16439. break;
  16440. }
  16441. return result;
  16442. };
  16443. _ParseAST.prototype.parseMultiplicative = function () {
  16444. // '*', '%', '/'
  16445. var start = this.inputIndex;
  16446. var result = this.parsePrefix();
  16447. while (this.next.type == exports.TokenType.Operator) {
  16448. var operator = this.next.strValue;
  16449. switch (operator) {
  16450. case '*':
  16451. case '%':
  16452. case '/':
  16453. this.advance();
  16454. var right = this.parsePrefix();
  16455. result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
  16456. continue;
  16457. }
  16458. break;
  16459. }
  16460. return result;
  16461. };
  16462. _ParseAST.prototype.parsePrefix = function () {
  16463. if (this.next.type == exports.TokenType.Operator) {
  16464. var start = this.inputIndex;
  16465. var operator = this.next.strValue;
  16466. var result = void 0;
  16467. switch (operator) {
  16468. case '+':
  16469. this.advance();
  16470. result = this.parsePrefix();
  16471. return Unary.createPlus(this.span(start), this.sourceSpan(start), result);
  16472. case '-':
  16473. this.advance();
  16474. result = this.parsePrefix();
  16475. return Unary.createMinus(this.span(start), this.sourceSpan(start), result);
  16476. case '!':
  16477. this.advance();
  16478. result = this.parsePrefix();
  16479. return new PrefixNot(this.span(start), this.sourceSpan(start), result);
  16480. }
  16481. }
  16482. return this.parseCallChain();
  16483. };
  16484. _ParseAST.prototype.parseCallChain = function () {
  16485. var _this = this;
  16486. var start = this.inputIndex;
  16487. var result = this.parsePrimary();
  16488. while (true) {
  16489. if (this.consumeOptionalCharacter($PERIOD)) {
  16490. result = this.parseAccessMemberOrMethodCall(result, start, false);
  16491. }
  16492. else if (this.consumeOptionalOperator('?.')) {
  16493. result = this.parseAccessMemberOrMethodCall(result, start, true);
  16494. }
  16495. else if (this.consumeOptionalCharacter($LBRACKET)) {
  16496. this.withContext(ParseContextFlags.Writable, function () {
  16497. _this.rbracketsExpected++;
  16498. var key = _this.parsePipe();
  16499. if (key instanceof EmptyExpr) {
  16500. _this.error("Key access cannot be empty");
  16501. }
  16502. _this.rbracketsExpected--;
  16503. _this.expectCharacter($RBRACKET);
  16504. if (_this.consumeOptionalOperator('=')) {
  16505. var value = _this.parseConditional();
  16506. result = new KeyedWrite(_this.span(start), _this.sourceSpan(start), result, key, value);
  16507. }
  16508. else {
  16509. result = new KeyedRead(_this.span(start), _this.sourceSpan(start), result, key);
  16510. }
  16511. });
  16512. }
  16513. else if (this.consumeOptionalCharacter($LPAREN)) {
  16514. this.rparensExpected++;
  16515. var args = this.parseCallArguments();
  16516. this.rparensExpected--;
  16517. this.expectCharacter($RPAREN);
  16518. result = new FunctionCall(this.span(start), this.sourceSpan(start), result, args);
  16519. }
  16520. else if (this.consumeOptionalOperator('!')) {
  16521. result = new NonNullAssert(this.span(start), this.sourceSpan(start), result);
  16522. }
  16523. else {
  16524. return result;
  16525. }
  16526. }
  16527. };
  16528. _ParseAST.prototype.parsePrimary = function () {
  16529. var start = this.inputIndex;
  16530. if (this.consumeOptionalCharacter($LPAREN)) {
  16531. this.rparensExpected++;
  16532. var result = this.parsePipe();
  16533. this.rparensExpected--;
  16534. this.expectCharacter($RPAREN);
  16535. return result;
  16536. }
  16537. else if (this.next.isKeywordNull()) {
  16538. this.advance();
  16539. return new LiteralPrimitive(this.span(start), this.sourceSpan(start), null);
  16540. }
  16541. else if (this.next.isKeywordUndefined()) {
  16542. this.advance();
  16543. return new LiteralPrimitive(this.span(start), this.sourceSpan(start), void 0);
  16544. }
  16545. else if (this.next.isKeywordTrue()) {
  16546. this.advance();
  16547. return new LiteralPrimitive(this.span(start), this.sourceSpan(start), true);
  16548. }
  16549. else if (this.next.isKeywordFalse()) {
  16550. this.advance();
  16551. return new LiteralPrimitive(this.span(start), this.sourceSpan(start), false);
  16552. }
  16553. else if (this.next.isKeywordThis()) {
  16554. this.advance();
  16555. return new ThisReceiver(this.span(start), this.sourceSpan(start));
  16556. }
  16557. else if (this.consumeOptionalCharacter($LBRACKET)) {
  16558. this.rbracketsExpected++;
  16559. var elements = this.parseExpressionList($RBRACKET);
  16560. this.rbracketsExpected--;
  16561. this.expectCharacter($RBRACKET);
  16562. return new LiteralArray(this.span(start), this.sourceSpan(start), elements);
  16563. }
  16564. else if (this.next.isCharacter($LBRACE)) {
  16565. return this.parseLiteralMap();
  16566. }
  16567. else if (this.next.isIdentifier()) {
  16568. return this.parseAccessMemberOrMethodCall(new ImplicitReceiver(this.span(start), this.sourceSpan(start)), start, false);
  16569. }
  16570. else if (this.next.isNumber()) {
  16571. var value = this.next.toNumber();
  16572. this.advance();
  16573. return new LiteralPrimitive(this.span(start), this.sourceSpan(start), value);
  16574. }
  16575. else if (this.next.isString()) {
  16576. var literalValue = this.next.toString();
  16577. this.advance();
  16578. return new LiteralPrimitive(this.span(start), this.sourceSpan(start), literalValue);
  16579. }
  16580. else if (this.next.isPrivateIdentifier()) {
  16581. this._reportErrorForPrivateIdentifier(this.next, null);
  16582. return new EmptyExpr(this.span(start), this.sourceSpan(start));
  16583. }
  16584. else if (this.index >= this.tokens.length) {
  16585. this.error("Unexpected end of expression: " + this.input);
  16586. return new EmptyExpr(this.span(start), this.sourceSpan(start));
  16587. }
  16588. else {
  16589. this.error("Unexpected token " + this.next);
  16590. return new EmptyExpr(this.span(start), this.sourceSpan(start));
  16591. }
  16592. };
  16593. _ParseAST.prototype.parseExpressionList = function (terminator) {
  16594. var result = [];
  16595. do {
  16596. if (!this.next.isCharacter(terminator)) {
  16597. result.push(this.parsePipe());
  16598. }
  16599. else {
  16600. break;
  16601. }
  16602. } while (this.consumeOptionalCharacter($COMMA));
  16603. return result;
  16604. };
  16605. _ParseAST.prototype.parseLiteralMap = function () {
  16606. var keys = [];
  16607. var values = [];
  16608. var start = this.inputIndex;
  16609. this.expectCharacter($LBRACE);
  16610. if (!this.consumeOptionalCharacter($RBRACE)) {
  16611. this.rbracesExpected++;
  16612. do {
  16613. var quoted = this.next.isString();
  16614. var key = this.expectIdentifierOrKeywordOrString();
  16615. keys.push({ key: key, quoted: quoted });
  16616. this.expectCharacter($COLON);
  16617. values.push(this.parsePipe());
  16618. } while (this.consumeOptionalCharacter($COMMA));
  16619. this.rbracesExpected--;
  16620. this.expectCharacter($RBRACE);
  16621. }
  16622. return new LiteralMap(this.span(start), this.sourceSpan(start), keys, values);
  16623. };
  16624. _ParseAST.prototype.parseAccessMemberOrMethodCall = function (receiver, start, isSafe) {
  16625. var _this = this;
  16626. if (isSafe === void 0) { isSafe = false; }
  16627. var nameStart = this.inputIndex;
  16628. var id = this.withContext(ParseContextFlags.Writable, function () {
  16629. var _a;
  16630. var id = (_a = _this.expectIdentifierOrKeyword()) !== null && _a !== void 0 ? _a : '';
  16631. if (id.length === 0) {
  16632. _this.error("Expected identifier for property access", receiver.span.end);
  16633. }
  16634. return id;
  16635. });
  16636. var nameSpan = this.sourceSpan(nameStart);
  16637. if (this.consumeOptionalCharacter($LPAREN)) {
  16638. var argumentStart = this.inputIndex;
  16639. this.rparensExpected++;
  16640. var args = this.parseCallArguments();
  16641. var argumentSpan = this.span(argumentStart, this.inputIndex).toAbsolute(this.absoluteOffset);
  16642. this.expectCharacter($RPAREN);
  16643. this.rparensExpected--;
  16644. var span = this.span(start);
  16645. var sourceSpan = this.sourceSpan(start);
  16646. return isSafe ?
  16647. new SafeMethodCall(span, sourceSpan, nameSpan, receiver, id, args, argumentSpan) :
  16648. new MethodCall(span, sourceSpan, nameSpan, receiver, id, args, argumentSpan);
  16649. }
  16650. else {
  16651. if (isSafe) {
  16652. if (this.consumeOptionalOperator('=')) {
  16653. this.error('The \'?.\' operator cannot be used in the assignment');
  16654. return new EmptyExpr(this.span(start), this.sourceSpan(start));
  16655. }
  16656. else {
  16657. return new SafePropertyRead(this.span(start), this.sourceSpan(start), nameSpan, receiver, id);
  16658. }
  16659. }
  16660. else {
  16661. if (this.consumeOptionalOperator('=')) {
  16662. if (!this.parseAction) {
  16663. this.error('Bindings cannot contain assignments');
  16664. return new EmptyExpr(this.span(start), this.sourceSpan(start));
  16665. }
  16666. var value = this.parseConditional();
  16667. return new PropertyWrite(this.span(start), this.sourceSpan(start), nameSpan, receiver, id, value);
  16668. }
  16669. else {
  16670. return new PropertyRead(this.span(start), this.sourceSpan(start), nameSpan, receiver, id);
  16671. }
  16672. }
  16673. }
  16674. };
  16675. _ParseAST.prototype.parseCallArguments = function () {
  16676. if (this.next.isCharacter($RPAREN))
  16677. return [];
  16678. var positionals = [];
  16679. do {
  16680. positionals.push(this.parsePipe());
  16681. } while (this.consumeOptionalCharacter($COMMA));
  16682. return positionals;
  16683. };
  16684. /**
  16685. * Parses an identifier, a keyword, a string with an optional `-` in between,
  16686. * and returns the string along with its absolute source span.
  16687. */
  16688. _ParseAST.prototype.expectTemplateBindingKey = function () {
  16689. var result = '';
  16690. var operatorFound = false;
  16691. var start = this.currentAbsoluteOffset;
  16692. do {
  16693. result += this.expectIdentifierOrKeywordOrString();
  16694. operatorFound = this.consumeOptionalOperator('-');
  16695. if (operatorFound) {
  16696. result += '-';
  16697. }
  16698. } while (operatorFound);
  16699. return {
  16700. source: result,
  16701. span: new AbsoluteSourceSpan(start, start + result.length),
  16702. };
  16703. };
  16704. /**
  16705. * Parse microsyntax template expression and return a list of bindings or
  16706. * parsing errors in case the given expression is invalid.
  16707. *
  16708. * For example,
  16709. * ```
  16710. * <div *ngFor="let item of items; index as i; trackBy: func">
  16711. * ```
  16712. * contains five bindings:
  16713. * 1. ngFor -> null
  16714. * 2. item -> NgForOfContext.$implicit
  16715. * 3. ngForOf -> items
  16716. * 4. i -> NgForOfContext.index
  16717. * 5. ngForTrackBy -> func
  16718. *
  16719. * For a full description of the microsyntax grammar, see
  16720. * https://gist.github.com/mhevery/d3530294cff2e4a1b3fe15ff75d08855
  16721. *
  16722. * @param templateKey name of the microsyntax directive, like ngIf, ngFor,
  16723. * without the *, along with its absolute span.
  16724. */
  16725. _ParseAST.prototype.parseTemplateBindings = function (templateKey) {
  16726. var bindings = [];
  16727. // The first binding is for the template key itself
  16728. // In *ngFor="let item of items", key = "ngFor", value = null
  16729. // In *ngIf="cond | pipe", key = "ngIf", value = "cond | pipe"
  16730. bindings.push.apply(bindings, __spreadArray([], __read(this.parseDirectiveKeywordBindings(templateKey))));
  16731. while (this.index < this.tokens.length) {
  16732. // If it starts with 'let', then this must be variable declaration
  16733. var letBinding = this.parseLetBinding();
  16734. if (letBinding) {
  16735. bindings.push(letBinding);
  16736. }
  16737. else {
  16738. // Two possible cases here, either `value "as" key` or
  16739. // "directive-keyword expression". We don't know which case, but both
  16740. // "value" and "directive-keyword" are template binding key, so consume
  16741. // the key first.
  16742. var key = this.expectTemplateBindingKey();
  16743. // Peek at the next token, if it is "as" then this must be variable
  16744. // declaration.
  16745. var binding = this.parseAsBinding(key);
  16746. if (binding) {
  16747. bindings.push(binding);
  16748. }
  16749. else {
  16750. // Otherwise the key must be a directive keyword, like "of". Transform
  16751. // the key to actual key. Eg. of -> ngForOf, trackBy -> ngForTrackBy
  16752. key.source =
  16753. templateKey.source + key.source.charAt(0).toUpperCase() + key.source.substring(1);
  16754. bindings.push.apply(bindings, __spreadArray([], __read(this.parseDirectiveKeywordBindings(key))));
  16755. }
  16756. }
  16757. this.consumeStatementTerminator();
  16758. }
  16759. return new TemplateBindingParseResult(bindings, [] /* warnings */, this.errors);
  16760. };
  16761. /**
  16762. * Parse a directive keyword, followed by a mandatory expression.
  16763. * For example, "of items", "trackBy: func".
  16764. * The bindings are: ngForOf -> items, ngForTrackBy -> func
  16765. * There could be an optional "as" binding that follows the expression.
  16766. * For example,
  16767. * ```
  16768. * *ngFor="let item of items | slice:0:1 as collection".
  16769. * ^^ ^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
  16770. * keyword bound target optional 'as' binding
  16771. * ```
  16772. *
  16773. * @param key binding key, for example, ngFor, ngIf, ngForOf, along with its
  16774. * absolute span.
  16775. */
  16776. _ParseAST.prototype.parseDirectiveKeywordBindings = function (key) {
  16777. var bindings = [];
  16778. this.consumeOptionalCharacter($COLON); // trackBy: trackByFunction
  16779. var value = this.getDirectiveBoundTarget();
  16780. var spanEnd = this.currentAbsoluteOffset;
  16781. // The binding could optionally be followed by "as". For example,
  16782. // *ngIf="cond | pipe as x". In this case, the key in the "as" binding
  16783. // is "x" and the value is the template key itself ("ngIf"). Note that the
  16784. // 'key' in the current context now becomes the "value" in the next binding.
  16785. var asBinding = this.parseAsBinding(key);
  16786. if (!asBinding) {
  16787. this.consumeStatementTerminator();
  16788. spanEnd = this.currentAbsoluteOffset;
  16789. }
  16790. var sourceSpan = new AbsoluteSourceSpan(key.span.start, spanEnd);
  16791. bindings.push(new ExpressionBinding(sourceSpan, key, value));
  16792. if (asBinding) {
  16793. bindings.push(asBinding);
  16794. }
  16795. return bindings;
  16796. };
  16797. /**
  16798. * Return the expression AST for the bound target of a directive keyword
  16799. * binding. For example,
  16800. * ```
  16801. * *ngIf="condition | pipe"
  16802. * ^^^^^^^^^^^^^^^^ bound target for "ngIf"
  16803. * *ngFor="let item of items"
  16804. * ^^^^^ bound target for "ngForOf"
  16805. * ```
  16806. */
  16807. _ParseAST.prototype.getDirectiveBoundTarget = function () {
  16808. if (this.next === EOF || this.peekKeywordAs() || this.peekKeywordLet()) {
  16809. return null;
  16810. }
  16811. var ast = this.parsePipe(); // example: "condition | async"
  16812. var _b = ast.span, start = _b.start, end = _b.end;
  16813. var value = this.input.substring(start, end);
  16814. return new ASTWithSource(ast, value, this.location, this.absoluteOffset + start, this.errors);
  16815. };
  16816. /**
  16817. * Return the binding for a variable declared using `as`. Note that the order
  16818. * of the key-value pair in this declaration is reversed. For example,
  16819. * ```
  16820. * *ngFor="let item of items; index as i"
  16821. * ^^^^^ ^
  16822. * value key
  16823. * ```
  16824. *
  16825. * @param value name of the value in the declaration, "ngIf" in the example
  16826. * above, along with its absolute span.
  16827. */
  16828. _ParseAST.prototype.parseAsBinding = function (value) {
  16829. if (!this.peekKeywordAs()) {
  16830. return null;
  16831. }
  16832. this.advance(); // consume the 'as' keyword
  16833. var key = this.expectTemplateBindingKey();
  16834. this.consumeStatementTerminator();
  16835. var sourceSpan = new AbsoluteSourceSpan(value.span.start, this.currentAbsoluteOffset);
  16836. return new VariableBinding(sourceSpan, key, value);
  16837. };
  16838. /**
  16839. * Return the binding for a variable declared using `let`. For example,
  16840. * ```
  16841. * *ngFor="let item of items; let i=index;"
  16842. * ^^^^^^^^ ^^^^^^^^^^^
  16843. * ```
  16844. * In the first binding, `item` is bound to `NgForOfContext.$implicit`.
  16845. * In the second binding, `i` is bound to `NgForOfContext.index`.
  16846. */
  16847. _ParseAST.prototype.parseLetBinding = function () {
  16848. if (!this.peekKeywordLet()) {
  16849. return null;
  16850. }
  16851. var spanStart = this.currentAbsoluteOffset;
  16852. this.advance(); // consume the 'let' keyword
  16853. var key = this.expectTemplateBindingKey();
  16854. var value = null;
  16855. if (this.consumeOptionalOperator('=')) {
  16856. value = this.expectTemplateBindingKey();
  16857. }
  16858. this.consumeStatementTerminator();
  16859. var sourceSpan = new AbsoluteSourceSpan(spanStart, this.currentAbsoluteOffset);
  16860. return new VariableBinding(sourceSpan, key, value);
  16861. };
  16862. /**
  16863. * Consume the optional statement terminator: semicolon or comma.
  16864. */
  16865. _ParseAST.prototype.consumeStatementTerminator = function () {
  16866. this.consumeOptionalCharacter($SEMICOLON) || this.consumeOptionalCharacter($COMMA);
  16867. };
  16868. /**
  16869. * Records an error and skips over the token stream until reaching a recoverable point. See
  16870. * `this.skip` for more details on token skipping.
  16871. */
  16872. _ParseAST.prototype.error = function (message, index) {
  16873. if (index === void 0) { index = null; }
  16874. this.errors.push(new ParserError(message, this.input, this.locationText(index), this.location));
  16875. this.skip();
  16876. };
  16877. _ParseAST.prototype.locationText = function (index) {
  16878. if (index === void 0) { index = null; }
  16879. if (index == null)
  16880. index = this.index;
  16881. return (index < this.tokens.length) ? "at column " + (this.tokens[index].index + 1) + " in" :
  16882. "at the end of the expression";
  16883. };
  16884. /**
  16885. * Records an error for an unexpected private identifier being discovered.
  16886. * @param token Token representing a private identifier.
  16887. * @param extraMessage Optional additional message being appended to the error.
  16888. */
  16889. _ParseAST.prototype._reportErrorForPrivateIdentifier = function (token, extraMessage) {
  16890. var errorMessage = "Private identifiers are not supported. Unexpected private identifier: " + token;
  16891. if (extraMessage !== null) {
  16892. errorMessage += ", " + extraMessage;
  16893. }
  16894. this.error(errorMessage);
  16895. };
  16896. /**
  16897. * Error recovery should skip tokens until it encounters a recovery point.
  16898. *
  16899. * The following are treated as unconditional recovery points:
  16900. * - end of input
  16901. * - ';' (parseChain() is always the root production, and it expects a ';')
  16902. * - '|' (since pipes may be chained and each pipe expression may be treated independently)
  16903. *
  16904. * The following are conditional recovery points:
  16905. * - ')', '}', ']' if one of calling productions is expecting one of these symbols
  16906. * - This allows skip() to recover from errors such as '(a.) + 1' allowing more of the AST to
  16907. * be retained (it doesn't skip any tokens as the ')' is retained because of the '(' begins
  16908. * an '(' <expr> ')' production).
  16909. * The recovery points of grouping symbols must be conditional as they must be skipped if
  16910. * none of the calling productions are not expecting the closing token else we will never
  16911. * make progress in the case of an extraneous group closing symbol (such as a stray ')').
  16912. * That is, we skip a closing symbol if we are not in a grouping production.
  16913. * - '=' in a `Writable` context
  16914. * - In this context, we are able to recover after seeing the `=` operator, which
  16915. * signals the presence of an independent rvalue expression following the `=` operator.
  16916. *
  16917. * If a production expects one of these token it increments the corresponding nesting count,
  16918. * and then decrements it just prior to checking if the token is in the input.
  16919. */
  16920. _ParseAST.prototype.skip = function () {
  16921. var n = this.next;
  16922. while (this.index < this.tokens.length && !n.isCharacter($SEMICOLON) &&
  16923. !n.isOperator('|') && (this.rparensExpected <= 0 || !n.isCharacter($RPAREN)) &&
  16924. (this.rbracesExpected <= 0 || !n.isCharacter($RBRACE)) &&
  16925. (this.rbracketsExpected <= 0 || !n.isCharacter($RBRACKET)) &&
  16926. (!(this.context & ParseContextFlags.Writable) || !n.isOperator('='))) {
  16927. if (this.next.isError()) {
  16928. this.errors.push(new ParserError(this.next.toString(), this.input, this.locationText(), this.location));
  16929. }
  16930. this.advance();
  16931. n = this.next;
  16932. }
  16933. };
  16934. return _ParseAST;
  16935. }());
  16936. var SimpleExpressionChecker = /** @class */ (function () {
  16937. function SimpleExpressionChecker() {
  16938. this.errors = [];
  16939. }
  16940. SimpleExpressionChecker.prototype.visitImplicitReceiver = function (ast, context) { };
  16941. SimpleExpressionChecker.prototype.visitThisReceiver = function (ast, context) { };
  16942. SimpleExpressionChecker.prototype.visitInterpolation = function (ast, context) { };
  16943. SimpleExpressionChecker.prototype.visitLiteralPrimitive = function (ast, context) { };
  16944. SimpleExpressionChecker.prototype.visitPropertyRead = function (ast, context) { };
  16945. SimpleExpressionChecker.prototype.visitPropertyWrite = function (ast, context) { };
  16946. SimpleExpressionChecker.prototype.visitSafePropertyRead = function (ast, context) { };
  16947. SimpleExpressionChecker.prototype.visitMethodCall = function (ast, context) { };
  16948. SimpleExpressionChecker.prototype.visitSafeMethodCall = function (ast, context) { };
  16949. SimpleExpressionChecker.prototype.visitFunctionCall = function (ast, context) { };
  16950. SimpleExpressionChecker.prototype.visitLiteralArray = function (ast, context) {
  16951. this.visitAll(ast.expressions, context);
  16952. };
  16953. SimpleExpressionChecker.prototype.visitLiteralMap = function (ast, context) {
  16954. this.visitAll(ast.values, context);
  16955. };
  16956. SimpleExpressionChecker.prototype.visitUnary = function (ast, context) { };
  16957. SimpleExpressionChecker.prototype.visitBinary = function (ast, context) { };
  16958. SimpleExpressionChecker.prototype.visitPrefixNot = function (ast, context) { };
  16959. SimpleExpressionChecker.prototype.visitNonNullAssert = function (ast, context) { };
  16960. SimpleExpressionChecker.prototype.visitConditional = function (ast, context) { };
  16961. SimpleExpressionChecker.prototype.visitPipe = function (ast, context) {
  16962. this.errors.push('pipes');
  16963. };
  16964. SimpleExpressionChecker.prototype.visitKeyedRead = function (ast, context) { };
  16965. SimpleExpressionChecker.prototype.visitKeyedWrite = function (ast, context) { };
  16966. SimpleExpressionChecker.prototype.visitAll = function (asts, context) {
  16967. var _this = this;
  16968. return asts.map(function (node) { return node.visit(_this, context); });
  16969. };
  16970. SimpleExpressionChecker.prototype.visitChain = function (ast, context) { };
  16971. SimpleExpressionChecker.prototype.visitQuote = function (ast, context) { };
  16972. return SimpleExpressionChecker;
  16973. }());
  16974. /**
  16975. * This class implements SimpleExpressionChecker used in View Engine and performs more strict checks
  16976. * to make sure host bindings do not contain pipes. In View Engine, having pipes in host bindings is
  16977. * not supported as well, but in some cases (like `!(value | async)`) the error is not triggered at
  16978. * compile time. In order to preserve View Engine behavior, more strict checks are introduced for
  16979. * Ivy mode only.
  16980. */
  16981. var IvySimpleExpressionChecker = /** @class */ (function (_super) {
  16982. __extends(IvySimpleExpressionChecker, _super);
  16983. function IvySimpleExpressionChecker() {
  16984. var _this = _super.apply(this, __spreadArray([], __read(arguments))) || this;
  16985. _this.errors = [];
  16986. return _this;
  16987. }
  16988. IvySimpleExpressionChecker.prototype.visitPipe = function () {
  16989. this.errors.push('pipes');
  16990. };
  16991. return IvySimpleExpressionChecker;
  16992. }(RecursiveAstVisitor$1));
  16993. /**
  16994. * @license
  16995. * Copyright Google LLC All Rights Reserved.
  16996. *
  16997. * Use of this source code is governed by an MIT-style license that can be
  16998. * found in the LICENSE file at https://angular.io/license
  16999. */
  17000. function mapEntry(key, value) {
  17001. return { key: key, value: value, quoted: false };
  17002. }
  17003. function mapLiteral(obj, quoted) {
  17004. if (quoted === void 0) { quoted = false; }
  17005. return literalMap(Object.keys(obj).map(function (key) { return ({
  17006. key: key,
  17007. quoted: quoted,
  17008. value: obj[key],
  17009. }); }));
  17010. }
  17011. // =================================================================================================
  17012. // =================================================================================================
  17013. // =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
  17014. // =================================================================================================
  17015. // =================================================================================================
  17016. //
  17017. // DO NOT EDIT THIS LIST OF SECURITY SENSITIVE PROPERTIES WITHOUT A SECURITY REVIEW!
  17018. // Reach out to mprobst for details.
  17019. //
  17020. // =================================================================================================
  17021. /** Map from tagName|propertyName to SecurityContext. Properties applying to all tags use '*'. */
  17022. var _SECURITY_SCHEMA;
  17023. function SECURITY_SCHEMA() {
  17024. if (!_SECURITY_SCHEMA) {
  17025. _SECURITY_SCHEMA = {};
  17026. // Case is insignificant below, all element and attribute names are lower-cased for lookup.
  17027. registerContext(SecurityContext.HTML, [
  17028. 'iframe|srcdoc',
  17029. '*|innerHTML',
  17030. '*|outerHTML',
  17031. ]);
  17032. registerContext(SecurityContext.STYLE, ['*|style']);
  17033. // NB: no SCRIPT contexts here, they are never allowed due to the parser stripping them.
  17034. registerContext(SecurityContext.URL, [
  17035. '*|formAction', 'area|href', 'area|ping', 'audio|src', 'a|href',
  17036. 'a|ping', 'blockquote|cite', 'body|background', 'del|cite', 'form|action',
  17037. 'img|src', 'img|srcset', 'input|src', 'ins|cite', 'q|cite',
  17038. 'source|src', 'source|srcset', 'track|src', 'video|poster', 'video|src',
  17039. ]);
  17040. registerContext(SecurityContext.RESOURCE_URL, [
  17041. 'applet|code',
  17042. 'applet|codebase',
  17043. 'base|href',
  17044. 'embed|src',
  17045. 'frame|src',
  17046. 'head|profile',
  17047. 'html|manifest',
  17048. 'iframe|src',
  17049. 'link|href',
  17050. 'media|src',
  17051. 'object|codebase',
  17052. 'object|data',
  17053. 'script|src',
  17054. ]);
  17055. }
  17056. return _SECURITY_SCHEMA;
  17057. }
  17058. function registerContext(ctx, specs) {
  17059. var e_1, _a;
  17060. try {
  17061. for (var specs_1 = __values(specs), specs_1_1 = specs_1.next(); !specs_1_1.done; specs_1_1 = specs_1.next()) {
  17062. var spec = specs_1_1.value;
  17063. _SECURITY_SCHEMA[spec.toLowerCase()] = ctx;
  17064. }
  17065. }
  17066. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  17067. finally {
  17068. try {
  17069. if (specs_1_1 && !specs_1_1.done && (_a = specs_1.return)) _a.call(specs_1);
  17070. }
  17071. finally { if (e_1) throw e_1.error; }
  17072. }
  17073. }
  17074. /**
  17075. * @license
  17076. * Copyright Google LLC All Rights Reserved.
  17077. *
  17078. * Use of this source code is governed by an MIT-style license that can be
  17079. * found in the LICENSE file at https://angular.io/license
  17080. */
  17081. var ElementSchemaRegistry = /** @class */ (function () {
  17082. function ElementSchemaRegistry() {
  17083. }
  17084. return ElementSchemaRegistry;
  17085. }());
  17086. var BOOLEAN = 'boolean';
  17087. var NUMBER = 'number';
  17088. var STRING = 'string';
  17089. var OBJECT = 'object';
  17090. /**
  17091. * This array represents the DOM schema. It encodes inheritance, properties, and events.
  17092. *
  17093. * ## Overview
  17094. *
  17095. * Each line represents one kind of element. The `element_inheritance` and properties are joined
  17096. * using `element_inheritance|properties` syntax.
  17097. *
  17098. * ## Element Inheritance
  17099. *
  17100. * The `element_inheritance` can be further subdivided as `element1,element2,...^parentElement`.
  17101. * Here the individual elements are separated by `,` (commas). Every element in the list
  17102. * has identical properties.
  17103. *
  17104. * An `element` may inherit additional properties from `parentElement` If no `^parentElement` is
  17105. * specified then `""` (blank) element is assumed.
  17106. *
  17107. * NOTE: The blank element inherits from root `[Element]` element, the super element of all
  17108. * elements.
  17109. *
  17110. * NOTE an element prefix such as `:svg:` has no special meaning to the schema.
  17111. *
  17112. * ## Properties
  17113. *
  17114. * Each element has a set of properties separated by `,` (commas). Each property can be prefixed
  17115. * by a special character designating its type:
  17116. *
  17117. * - (no prefix): property is a string.
  17118. * - `*`: property represents an event.
  17119. * - `!`: property is a boolean.
  17120. * - `#`: property is a number.
  17121. * - `%`: property is an object.
  17122. *
  17123. * ## Query
  17124. *
  17125. * The class creates an internal squas representation which allows to easily answer the query of
  17126. * if a given property exist on a given element.
  17127. *
  17128. * NOTE: We don't yet support querying for types or events.
  17129. * NOTE: This schema is auto extracted from `schema_extractor.ts` located in the test folder,
  17130. * see dom_element_schema_registry_spec.ts
  17131. */
  17132. // =================================================================================================
  17133. // =================================================================================================
  17134. // =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
  17135. // =================================================================================================
  17136. // =================================================================================================
  17137. //
  17138. // DO NOT EDIT THIS DOM SCHEMA WITHOUT A SECURITY REVIEW!
  17139. //
  17140. // Newly added properties must be security reviewed and assigned an appropriate SecurityContext in
  17141. // dom_security_schema.ts. Reach out to mprobst & rjamet for details.
  17142. //
  17143. // =================================================================================================
  17144. var SCHEMA = [
  17145. '[Element]|textContent,%classList,className,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*copy,*cut,*paste,*search,*selectstart,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerHTML,#scrollLeft,#scrollTop,slot' +
  17146. /* added manually to avoid breaking changes */
  17147. ',*message,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored',
  17148. '[HTMLElement]^[Element]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,outerText,!spellcheck,%style,#tabIndex,title,!translate',
  17149. 'abbr,address,article,aside,b,bdi,bdo,cite,code,dd,dfn,dt,em,figcaption,figure,footer,header,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr^[HTMLElement]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,outerText,!spellcheck,%style,#tabIndex,title,!translate',
  17150. 'media^[HTMLElement]|!autoplay,!controls,%controlsList,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,*waitingforkey,#playbackRate,preload,src,%srcObject,#volume',
  17151. ':svg:^[HTMLElement]|*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,%style,#tabIndex',
  17152. ':svg:graphics^:svg:|',
  17153. ':svg:animation^:svg:|*begin,*end,*repeat',
  17154. ':svg:geometry^:svg:|',
  17155. ':svg:componentTransferFunction^:svg:|',
  17156. ':svg:gradient^:svg:|',
  17157. ':svg:textContent^:svg:graphics|',
  17158. ':svg:textPositioning^:svg:textContent|',
  17159. 'a^[HTMLElement]|charset,coords,download,hash,host,hostname,href,hreflang,name,password,pathname,ping,port,protocol,referrerPolicy,rel,rev,search,shape,target,text,type,username',
  17160. 'area^[HTMLElement]|alt,coords,download,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,rel,search,shape,target,username',
  17161. 'audio^media|',
  17162. 'br^[HTMLElement]|clear',
  17163. 'base^[HTMLElement]|href,target',
  17164. 'body^[HTMLElement]|aLink,background,bgColor,link,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,text,vLink',
  17165. 'button^[HTMLElement]|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value',
  17166. 'canvas^[HTMLElement]|#height,#width',
  17167. 'content^[HTMLElement]|select',
  17168. 'dl^[HTMLElement]|!compact',
  17169. 'datalist^[HTMLElement]|',
  17170. 'details^[HTMLElement]|!open',
  17171. 'dialog^[HTMLElement]|!open,returnValue',
  17172. 'dir^[HTMLElement]|!compact',
  17173. 'div^[HTMLElement]|align',
  17174. 'embed^[HTMLElement]|align,height,name,src,type,width',
  17175. 'fieldset^[HTMLElement]|!disabled,name',
  17176. 'font^[HTMLElement]|color,face,size',
  17177. 'form^[HTMLElement]|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target',
  17178. 'frame^[HTMLElement]|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src',
  17179. 'frameset^[HTMLElement]|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows',
  17180. 'hr^[HTMLElement]|align,color,!noShade,size,width',
  17181. 'head^[HTMLElement]|',
  17182. 'h1,h2,h3,h4,h5,h6^[HTMLElement]|align',
  17183. 'html^[HTMLElement]|version',
  17184. 'iframe^[HTMLElement]|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width',
  17185. 'img^[HTMLElement]|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width',
  17186. 'input^[HTMLElement]|accept,align,alt,autocapitalize,autocomplete,!autofocus,!checked,!defaultChecked,defaultValue,dirName,!disabled,%files,formAction,formEnctype,formMethod,!formNoValidate,formTarget,#height,!incremental,!indeterminate,max,#maxLength,min,#minLength,!multiple,name,pattern,placeholder,!readOnly,!required,selectionDirection,#selectionEnd,#selectionStart,#size,src,step,type,useMap,value,%valueAsDate,#valueAsNumber,#width',
  17187. 'li^[HTMLElement]|type,#value',
  17188. 'label^[HTMLElement]|htmlFor',
  17189. 'legend^[HTMLElement]|align',
  17190. 'link^[HTMLElement]|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,referrerPolicy,rel,%relList,rev,%sizes,target,type',
  17191. 'map^[HTMLElement]|name',
  17192. 'marquee^[HTMLElement]|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width',
  17193. 'menu^[HTMLElement]|!compact',
  17194. 'meta^[HTMLElement]|content,httpEquiv,name,scheme',
  17195. 'meter^[HTMLElement]|#high,#low,#max,#min,#optimum,#value',
  17196. 'ins,del^[HTMLElement]|cite,dateTime',
  17197. 'ol^[HTMLElement]|!compact,!reversed,#start,type',
  17198. 'object^[HTMLElement]|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width',
  17199. 'optgroup^[HTMLElement]|!disabled,label',
  17200. 'option^[HTMLElement]|!defaultSelected,!disabled,label,!selected,text,value',
  17201. 'output^[HTMLElement]|defaultValue,%htmlFor,name,value',
  17202. 'p^[HTMLElement]|align',
  17203. 'param^[HTMLElement]|name,type,value,valueType',
  17204. 'picture^[HTMLElement]|',
  17205. 'pre^[HTMLElement]|#width',
  17206. 'progress^[HTMLElement]|#max,#value',
  17207. 'q,blockquote,cite^[HTMLElement]|',
  17208. 'script^[HTMLElement]|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type',
  17209. 'select^[HTMLElement]|autocomplete,!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value',
  17210. 'shadow^[HTMLElement]|',
  17211. 'slot^[HTMLElement]|name',
  17212. 'source^[HTMLElement]|media,sizes,src,srcset,type',
  17213. 'span^[HTMLElement]|',
  17214. 'style^[HTMLElement]|!disabled,media,type',
  17215. 'caption^[HTMLElement]|align',
  17216. 'th,td^[HTMLElement]|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width',
  17217. 'col,colgroup^[HTMLElement]|align,ch,chOff,#span,vAlign,width',
  17218. 'table^[HTMLElement]|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width',
  17219. 'tr^[HTMLElement]|align,bgColor,ch,chOff,vAlign',
  17220. 'tfoot,thead,tbody^[HTMLElement]|align,ch,chOff,vAlign',
  17221. 'template^[HTMLElement]|',
  17222. 'textarea^[HTMLElement]|autocapitalize,autocomplete,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap',
  17223. 'title^[HTMLElement]|text',
  17224. 'track^[HTMLElement]|!default,kind,label,src,srclang',
  17225. 'ul^[HTMLElement]|!compact,type',
  17226. 'unknown^[HTMLElement]|',
  17227. 'video^media|#height,poster,#width',
  17228. ':svg:a^:svg:graphics|',
  17229. ':svg:animate^:svg:animation|',
  17230. ':svg:animateMotion^:svg:animation|',
  17231. ':svg:animateTransform^:svg:animation|',
  17232. ':svg:circle^:svg:geometry|',
  17233. ':svg:clipPath^:svg:graphics|',
  17234. ':svg:defs^:svg:graphics|',
  17235. ':svg:desc^:svg:|',
  17236. ':svg:discard^:svg:|',
  17237. ':svg:ellipse^:svg:geometry|',
  17238. ':svg:feBlend^:svg:|',
  17239. ':svg:feColorMatrix^:svg:|',
  17240. ':svg:feComponentTransfer^:svg:|',
  17241. ':svg:feComposite^:svg:|',
  17242. ':svg:feConvolveMatrix^:svg:|',
  17243. ':svg:feDiffuseLighting^:svg:|',
  17244. ':svg:feDisplacementMap^:svg:|',
  17245. ':svg:feDistantLight^:svg:|',
  17246. ':svg:feDropShadow^:svg:|',
  17247. ':svg:feFlood^:svg:|',
  17248. ':svg:feFuncA^:svg:componentTransferFunction|',
  17249. ':svg:feFuncB^:svg:componentTransferFunction|',
  17250. ':svg:feFuncG^:svg:componentTransferFunction|',
  17251. ':svg:feFuncR^:svg:componentTransferFunction|',
  17252. ':svg:feGaussianBlur^:svg:|',
  17253. ':svg:feImage^:svg:|',
  17254. ':svg:feMerge^:svg:|',
  17255. ':svg:feMergeNode^:svg:|',
  17256. ':svg:feMorphology^:svg:|',
  17257. ':svg:feOffset^:svg:|',
  17258. ':svg:fePointLight^:svg:|',
  17259. ':svg:feSpecularLighting^:svg:|',
  17260. ':svg:feSpotLight^:svg:|',
  17261. ':svg:feTile^:svg:|',
  17262. ':svg:feTurbulence^:svg:|',
  17263. ':svg:filter^:svg:|',
  17264. ':svg:foreignObject^:svg:graphics|',
  17265. ':svg:g^:svg:graphics|',
  17266. ':svg:image^:svg:graphics|',
  17267. ':svg:line^:svg:geometry|',
  17268. ':svg:linearGradient^:svg:gradient|',
  17269. ':svg:mpath^:svg:|',
  17270. ':svg:marker^:svg:|',
  17271. ':svg:mask^:svg:|',
  17272. ':svg:metadata^:svg:|',
  17273. ':svg:path^:svg:geometry|',
  17274. ':svg:pattern^:svg:|',
  17275. ':svg:polygon^:svg:geometry|',
  17276. ':svg:polyline^:svg:geometry|',
  17277. ':svg:radialGradient^:svg:gradient|',
  17278. ':svg:rect^:svg:geometry|',
  17279. ':svg:svg^:svg:graphics|#currentScale,#zoomAndPan',
  17280. ':svg:script^:svg:|type',
  17281. ':svg:set^:svg:animation|',
  17282. ':svg:stop^:svg:|',
  17283. ':svg:style^:svg:|!disabled,media,title,type',
  17284. ':svg:switch^:svg:graphics|',
  17285. ':svg:symbol^:svg:|',
  17286. ':svg:tspan^:svg:textPositioning|',
  17287. ':svg:text^:svg:textPositioning|',
  17288. ':svg:textPath^:svg:textContent|',
  17289. ':svg:title^:svg:|',
  17290. ':svg:use^:svg:graphics|',
  17291. ':svg:view^:svg:|#zoomAndPan',
  17292. 'data^[HTMLElement]|value',
  17293. 'keygen^[HTMLElement]|!autofocus,challenge,!disabled,form,keytype,name',
  17294. 'menuitem^[HTMLElement]|type,label,icon,!disabled,!checked,radiogroup,!default',
  17295. 'summary^[HTMLElement]|',
  17296. 'time^[HTMLElement]|dateTime',
  17297. ':svg:cursor^:svg:|',
  17298. ];
  17299. var _ATTR_TO_PROP = {
  17300. 'class': 'className',
  17301. 'for': 'htmlFor',
  17302. 'formaction': 'formAction',
  17303. 'innerHtml': 'innerHTML',
  17304. 'readonly': 'readOnly',
  17305. 'tabindex': 'tabIndex',
  17306. };
  17307. // Invert _ATTR_TO_PROP.
  17308. var _PROP_TO_ATTR = Object.keys(_ATTR_TO_PROP).reduce(function (inverted, attr) {
  17309. inverted[_ATTR_TO_PROP[attr]] = attr;
  17310. return inverted;
  17311. }, {});
  17312. var DomElementSchemaRegistry = /** @class */ (function (_super) {
  17313. __extends(DomElementSchemaRegistry, _super);
  17314. function DomElementSchemaRegistry() {
  17315. var _this = _super.call(this) || this;
  17316. _this._schema = {};
  17317. SCHEMA.forEach(function (encodedType) {
  17318. var type = {};
  17319. var _b = __read(encodedType.split('|'), 2), strType = _b[0], strProperties = _b[1];
  17320. var properties = strProperties.split(',');
  17321. var _c = __read(strType.split('^'), 2), typeNames = _c[0], superName = _c[1];
  17322. typeNames.split(',').forEach(function (tag) { return _this._schema[tag.toLowerCase()] = type; });
  17323. var superType = superName && _this._schema[superName.toLowerCase()];
  17324. if (superType) {
  17325. Object.keys(superType).forEach(function (prop) {
  17326. type[prop] = superType[prop];
  17327. });
  17328. }
  17329. properties.forEach(function (property) {
  17330. if (property.length > 0) {
  17331. switch (property[0]) {
  17332. case '*':
  17333. // We don't yet support events.
  17334. // If ever allowing to bind to events, GO THROUGH A SECURITY REVIEW, allowing events
  17335. // will
  17336. // almost certainly introduce bad XSS vulnerabilities.
  17337. // type[property.substring(1)] = EVENT;
  17338. break;
  17339. case '!':
  17340. type[property.substring(1)] = BOOLEAN;
  17341. break;
  17342. case '#':
  17343. type[property.substring(1)] = NUMBER;
  17344. break;
  17345. case '%':
  17346. type[property.substring(1)] = OBJECT;
  17347. break;
  17348. default:
  17349. type[property] = STRING;
  17350. }
  17351. }
  17352. });
  17353. });
  17354. return _this;
  17355. }
  17356. DomElementSchemaRegistry.prototype.hasProperty = function (tagName, propName, schemaMetas) {
  17357. if (schemaMetas.some(function (schema) { return schema.name === NO_ERRORS_SCHEMA.name; })) {
  17358. return true;
  17359. }
  17360. if (tagName.indexOf('-') > -1) {
  17361. if (isNgContainer(tagName) || isNgContent(tagName)) {
  17362. return false;
  17363. }
  17364. if (schemaMetas.some(function (schema) { return schema.name === CUSTOM_ELEMENTS_SCHEMA.name; })) {
  17365. // Can't tell now as we don't know which properties a custom element will get
  17366. // once it is instantiated
  17367. return true;
  17368. }
  17369. }
  17370. var elementProperties = this._schema[tagName.toLowerCase()] || this._schema['unknown'];
  17371. return !!elementProperties[propName];
  17372. };
  17373. DomElementSchemaRegistry.prototype.hasElement = function (tagName, schemaMetas) {
  17374. if (schemaMetas.some(function (schema) { return schema.name === NO_ERRORS_SCHEMA.name; })) {
  17375. return true;
  17376. }
  17377. if (tagName.indexOf('-') > -1) {
  17378. if (isNgContainer(tagName) || isNgContent(tagName)) {
  17379. return true;
  17380. }
  17381. if (schemaMetas.some(function (schema) { return schema.name === CUSTOM_ELEMENTS_SCHEMA.name; })) {
  17382. // Allow any custom elements
  17383. return true;
  17384. }
  17385. }
  17386. return !!this._schema[tagName.toLowerCase()];
  17387. };
  17388. /**
  17389. * securityContext returns the security context for the given property on the given DOM tag.
  17390. *
  17391. * Tag and property name are statically known and cannot change at runtime, i.e. it is not
  17392. * possible to bind a value into a changing attribute or tag name.
  17393. *
  17394. * The filtering is based on a list of allowed tags|attributes. All attributes in the schema
  17395. * above are assumed to have the 'NONE' security context, i.e. that they are safe inert
  17396. * string values. Only specific well known attack vectors are assigned their appropriate context.
  17397. */
  17398. DomElementSchemaRegistry.prototype.securityContext = function (tagName, propName, isAttribute) {
  17399. if (isAttribute) {
  17400. // NB: For security purposes, use the mapped property name, not the attribute name.
  17401. propName = this.getMappedPropName(propName);
  17402. }
  17403. // Make sure comparisons are case insensitive, so that case differences between attribute and
  17404. // property names do not have a security impact.
  17405. tagName = tagName.toLowerCase();
  17406. propName = propName.toLowerCase();
  17407. var ctx = SECURITY_SCHEMA()[tagName + '|' + propName];
  17408. if (ctx) {
  17409. return ctx;
  17410. }
  17411. ctx = SECURITY_SCHEMA()['*|' + propName];
  17412. return ctx ? ctx : SecurityContext.NONE;
  17413. };
  17414. DomElementSchemaRegistry.prototype.getMappedPropName = function (propName) {
  17415. return _ATTR_TO_PROP[propName] || propName;
  17416. };
  17417. DomElementSchemaRegistry.prototype.getDefaultComponentElementName = function () {
  17418. return 'ng-component';
  17419. };
  17420. DomElementSchemaRegistry.prototype.validateProperty = function (name) {
  17421. if (name.toLowerCase().startsWith('on')) {
  17422. var msg = "Binding to event property '" + name + "' is disallowed for security reasons, " +
  17423. ("please use (" + name.slice(2) + ")=...") +
  17424. ("\nIf '" + name + "' is a directive input, make sure the directive is imported by the") +
  17425. " current module.";
  17426. return { error: true, msg: msg };
  17427. }
  17428. else {
  17429. return { error: false };
  17430. }
  17431. };
  17432. DomElementSchemaRegistry.prototype.validateAttribute = function (name) {
  17433. if (name.toLowerCase().startsWith('on')) {
  17434. var msg = "Binding to event attribute '" + name + "' is disallowed for security reasons, " +
  17435. ("please use (" + name.slice(2) + ")=...");
  17436. return { error: true, msg: msg };
  17437. }
  17438. else {
  17439. return { error: false };
  17440. }
  17441. };
  17442. DomElementSchemaRegistry.prototype.allKnownElementNames = function () {
  17443. return Object.keys(this._schema);
  17444. };
  17445. DomElementSchemaRegistry.prototype.allKnownAttributesOfElement = function (tagName) {
  17446. var elementProperties = this._schema[tagName.toLowerCase()] || this._schema['unknown'];
  17447. // Convert properties to attributes.
  17448. return Object.keys(elementProperties).map(function (prop) { var _a; return (_a = _PROP_TO_ATTR[prop]) !== null && _a !== void 0 ? _a : prop; });
  17449. };
  17450. DomElementSchemaRegistry.prototype.normalizeAnimationStyleProperty = function (propName) {
  17451. return dashCaseToCamelCase(propName);
  17452. };
  17453. DomElementSchemaRegistry.prototype.normalizeAnimationStyleValue = function (camelCaseProp, userProvidedProp, val) {
  17454. var unit = '';
  17455. var strVal = val.toString().trim();
  17456. var errorMsg = null;
  17457. if (_isPixelDimensionStyle(camelCaseProp) && val !== 0 && val !== '0') {
  17458. if (typeof val === 'number') {
  17459. unit = 'px';
  17460. }
  17461. else {
  17462. var valAndSuffixMatch = val.match(/^[+-]?[\d\.]+([a-z]*)$/);
  17463. if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
  17464. errorMsg = "Please provide a CSS unit value for " + userProvidedProp + ":" + val;
  17465. }
  17466. }
  17467. }
  17468. return { error: errorMsg, value: strVal + unit };
  17469. };
  17470. return DomElementSchemaRegistry;
  17471. }(ElementSchemaRegistry));
  17472. function _isPixelDimensionStyle(prop) {
  17473. switch (prop) {
  17474. case 'width':
  17475. case 'height':
  17476. case 'minWidth':
  17477. case 'minHeight':
  17478. case 'maxWidth':
  17479. case 'maxHeight':
  17480. case 'left':
  17481. case 'top':
  17482. case 'bottom':
  17483. case 'right':
  17484. case 'fontSize':
  17485. case 'outlineWidth':
  17486. case 'outlineOffset':
  17487. case 'paddingTop':
  17488. case 'paddingLeft':
  17489. case 'paddingBottom':
  17490. case 'paddingRight':
  17491. case 'marginTop':
  17492. case 'marginLeft':
  17493. case 'marginBottom':
  17494. case 'marginRight':
  17495. case 'borderRadius':
  17496. case 'borderWidth':
  17497. case 'borderTopWidth':
  17498. case 'borderLeftWidth':
  17499. case 'borderRightWidth':
  17500. case 'borderBottomWidth':
  17501. case 'textIndent':
  17502. return true;
  17503. default:
  17504. return false;
  17505. }
  17506. }
  17507. /**
  17508. * @license
  17509. * Copyright Google LLC All Rights Reserved.
  17510. *
  17511. * Use of this source code is governed by an MIT-style license that can be
  17512. * found in the LICENSE file at https://angular.io/license
  17513. */
  17514. /**
  17515. * Set of tagName|propertyName corresponding to Trusted Types sinks. Properties applying to all
  17516. * tags use '*'.
  17517. *
  17518. * Extracted from, and should be kept in sync with
  17519. * https://w3c.github.io/webappsec-trusted-types/dist/spec/#integrations
  17520. */
  17521. var TRUSTED_TYPES_SINKS = new Set([
  17522. // NOTE: All strings in this set *must* be lowercase!
  17523. // TrustedHTML
  17524. 'iframe|srcdoc',
  17525. '*|innerhtml',
  17526. '*|outerhtml',
  17527. // NB: no TrustedScript here, as the corresponding tags are stripped by the compiler.
  17528. // TrustedScriptURL
  17529. 'embed|src',
  17530. 'object|codebase',
  17531. 'object|data',
  17532. ]);
  17533. /**
  17534. * isTrustedTypesSink returns true if the given property on the given DOM tag is a Trusted Types
  17535. * sink. In that case, use `ElementSchemaRegistry.securityContext` to determine which particular
  17536. * Trusted Type is required for values passed to the sink:
  17537. * - SecurityContext.HTML corresponds to TrustedHTML
  17538. * - SecurityContext.RESOURCE_URL corresponds to TrustedScriptURL
  17539. */
  17540. function isTrustedTypesSink(tagName, propName) {
  17541. // Make sure comparisons are case insensitive, so that case differences between attribute and
  17542. // property names do not have a security impact.
  17543. tagName = tagName.toLowerCase();
  17544. propName = propName.toLowerCase();
  17545. return TRUSTED_TYPES_SINKS.has(tagName + '|' + propName) ||
  17546. TRUSTED_TYPES_SINKS.has('*|' + propName);
  17547. }
  17548. var BIND_NAME_REGEXP$1 = /^(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.*)$/;
  17549. // Group 1 = "bind-"
  17550. var KW_BIND_IDX$1 = 1;
  17551. // Group 2 = "let-"
  17552. var KW_LET_IDX$1 = 2;
  17553. // Group 3 = "ref-/#"
  17554. var KW_REF_IDX$1 = 3;
  17555. // Group 4 = "on-"
  17556. var KW_ON_IDX$1 = 4;
  17557. // Group 5 = "bindon-"
  17558. var KW_BINDON_IDX$1 = 5;
  17559. // Group 6 = "@"
  17560. var KW_AT_IDX$1 = 6;
  17561. // Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
  17562. var IDENT_KW_IDX$1 = 7;
  17563. var BINDING_DELIMS = {
  17564. BANANA_BOX: { start: '[(', end: ')]' },
  17565. PROPERTY: { start: '[', end: ']' },
  17566. EVENT: { start: '(', end: ')' },
  17567. };
  17568. var TEMPLATE_ATTR_PREFIX$2 = '*';
  17569. function htmlAstToRender3Ast(htmlNodes, bindingParser, options) {
  17570. var transformer = new HtmlAstToIvyAst(bindingParser, options);
  17571. var ivyNodes = visitAll$1(transformer, htmlNodes);
  17572. // Errors might originate in either the binding parser or the html to ivy transformer
  17573. var allErrors = bindingParser.errors.concat(transformer.errors);
  17574. var result = {
  17575. nodes: ivyNodes,
  17576. errors: allErrors,
  17577. styleUrls: transformer.styleUrls,
  17578. styles: transformer.styles,
  17579. ngContentSelectors: transformer.ngContentSelectors
  17580. };
  17581. if (options.collectCommentNodes) {
  17582. result.commentNodes = transformer.commentNodes;
  17583. }
  17584. return result;
  17585. }
  17586. var HtmlAstToIvyAst = /** @class */ (function () {
  17587. function HtmlAstToIvyAst(bindingParser, options) {
  17588. this.bindingParser = bindingParser;
  17589. this.options = options;
  17590. this.errors = [];
  17591. this.styles = [];
  17592. this.styleUrls = [];
  17593. this.ngContentSelectors = [];
  17594. // This array will be populated if `Render3ParseOptions['collectCommentNodes']` is true
  17595. this.commentNodes = [];
  17596. this.inI18nBlock = false;
  17597. }
  17598. // HTML visitor
  17599. HtmlAstToIvyAst.prototype.visitElement = function (element) {
  17600. var e_1, _a;
  17601. var _this = this;
  17602. var isI18nRootElement = isI18nRootNode(element.i18n);
  17603. if (isI18nRootElement) {
  17604. if (this.inI18nBlock) {
  17605. this.reportError('Cannot mark an element as translatable inside of a translatable section. Please remove the nested i18n marker.', element.sourceSpan);
  17606. }
  17607. this.inI18nBlock = true;
  17608. }
  17609. var preparsedElement = preparseElement(element);
  17610. if (preparsedElement.type === PreparsedElementType.SCRIPT) {
  17611. return null;
  17612. }
  17613. else if (preparsedElement.type === PreparsedElementType.STYLE) {
  17614. var contents = textContents(element);
  17615. if (contents !== null) {
  17616. this.styles.push(contents);
  17617. }
  17618. return null;
  17619. }
  17620. else if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
  17621. isStyleUrlResolvable(preparsedElement.hrefAttr)) {
  17622. this.styleUrls.push(preparsedElement.hrefAttr);
  17623. return null;
  17624. }
  17625. // Whether the element is a `<ng-template>`
  17626. var isTemplateElement = isNgTemplate(element.name);
  17627. var parsedProperties = [];
  17628. var boundEvents = [];
  17629. var variables = [];
  17630. var references = [];
  17631. var attributes = [];
  17632. var i18nAttrsMeta = {};
  17633. var templateParsedProperties = [];
  17634. var templateVariables = [];
  17635. // Whether the element has any *-attribute
  17636. var elementHasInlineTemplate = false;
  17637. try {
  17638. for (var _b = __values(element.attrs), _c = _b.next(); !_c.done; _c = _b.next()) {
  17639. var attribute = _c.value;
  17640. var hasBinding = false;
  17641. var normalizedName = normalizeAttributeName(attribute.name);
  17642. // `*attr` defines template bindings
  17643. var isTemplateBinding = false;
  17644. if (attribute.i18n) {
  17645. i18nAttrsMeta[attribute.name] = attribute.i18n;
  17646. }
  17647. if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX$2)) {
  17648. // *-attributes
  17649. if (elementHasInlineTemplate) {
  17650. this.reportError("Can't have multiple template bindings on one element. Use only one attribute prefixed with *", attribute.sourceSpan);
  17651. }
  17652. isTemplateBinding = true;
  17653. elementHasInlineTemplate = true;
  17654. var templateValue = attribute.value;
  17655. var templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX$2.length);
  17656. var parsedVariables = [];
  17657. var absoluteValueOffset = attribute.valueSpan ?
  17658. attribute.valueSpan.start.offset :
  17659. // If there is no value span the attribute does not have a value, like `attr` in
  17660. //`<div attr></div>`. In this case, point to one character beyond the last character of
  17661. // the attribute name.
  17662. attribute.sourceSpan.start.offset + attribute.name.length;
  17663. this.bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attribute.sourceSpan, absoluteValueOffset, [], templateParsedProperties, parsedVariables, true /* isIvyAst */);
  17664. templateVariables.push.apply(templateVariables, __spreadArray([], __read(parsedVariables.map(function (v) { return new Variable(v.name, v.value, v.sourceSpan, v.keySpan, v.valueSpan); }))));
  17665. }
  17666. else {
  17667. // Check for variables, events, property bindings, interpolation
  17668. hasBinding = this.parseAttribute(isTemplateElement, attribute, [], parsedProperties, boundEvents, variables, references);
  17669. }
  17670. if (!hasBinding && !isTemplateBinding) {
  17671. // don't include the bindings as attributes as well in the AST
  17672. attributes.push(this.visitAttribute(attribute));
  17673. }
  17674. }
  17675. }
  17676. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  17677. finally {
  17678. try {
  17679. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  17680. }
  17681. finally { if (e_1) throw e_1.error; }
  17682. }
  17683. var children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR$1 : this, element.children);
  17684. var parsedElement;
  17685. if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
  17686. // `<ng-content>`
  17687. if (element.children &&
  17688. !element.children.every(function (node) { return isEmptyTextNode(node) || isCommentNode(node); })) {
  17689. this.reportError("<ng-content> element cannot have content.", element.sourceSpan);
  17690. }
  17691. var selector = preparsedElement.selectAttr;
  17692. var attrs = element.attrs.map(function (attr) { return _this.visitAttribute(attr); });
  17693. parsedElement = new Content(selector, attrs, element.sourceSpan, element.i18n);
  17694. this.ngContentSelectors.push(selector);
  17695. }
  17696. else if (isTemplateElement) {
  17697. // `<ng-template>`
  17698. var attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
  17699. parsedElement = new Template(element.name, attributes, attrs.bound, boundEvents, [ /* no template attributes */], children, references, variables, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  17700. }
  17701. else {
  17702. var attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
  17703. parsedElement = new Element(element.name, attributes, attrs.bound, boundEvents, children, references, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
  17704. }
  17705. if (elementHasInlineTemplate) {
  17706. // If this node is an inline-template (e.g. has *ngFor) then we need to create a template
  17707. // node that contains this node.
  17708. // Moreover, if the node is an element, then we need to hoist its attributes to the template
  17709. // node for matching against content projection selectors.
  17710. var attrs = this.extractAttributes('ng-template', templateParsedProperties, i18nAttrsMeta);
  17711. var templateAttrs_1 = [];
  17712. attrs.literal.forEach(function (attr) { return templateAttrs_1.push(attr); });
  17713. attrs.bound.forEach(function (attr) { return templateAttrs_1.push(attr); });
  17714. var hoistedAttrs = parsedElement instanceof Element ?
  17715. {
  17716. attributes: parsedElement.attributes,
  17717. inputs: parsedElement.inputs,
  17718. outputs: parsedElement.outputs,
  17719. } :
  17720. { attributes: [], inputs: [], outputs: [] };
  17721. // For <ng-template>s with structural directives on them, avoid passing i18n information to
  17722. // the wrapping template to prevent unnecessary i18n instructions from being generated. The
  17723. // necessary i18n meta information will be extracted from child elements.
  17724. var i18n = isTemplateElement && isI18nRootElement ? undefined : element.i18n;
  17725. // TODO(pk): test for this case
  17726. parsedElement = new Template(parsedElement.name, hoistedAttrs.attributes, hoistedAttrs.inputs, hoistedAttrs.outputs, templateAttrs_1, [parsedElement], [ /* no references */], templateVariables, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, i18n);
  17727. }
  17728. if (isI18nRootElement) {
  17729. this.inI18nBlock = false;
  17730. }
  17731. return parsedElement;
  17732. };
  17733. HtmlAstToIvyAst.prototype.visitAttribute = function (attribute) {
  17734. return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, attribute.keySpan, attribute.valueSpan, attribute.i18n);
  17735. };
  17736. HtmlAstToIvyAst.prototype.visitText = function (text) {
  17737. return this._visitTextWithInterpolation(text.value, text.sourceSpan, text.i18n);
  17738. };
  17739. HtmlAstToIvyAst.prototype.visitExpansion = function (expansion) {
  17740. var _this = this;
  17741. if (!expansion.i18n) {
  17742. // do not generate Icu in case it was created
  17743. // outside of i18n block in a template
  17744. return null;
  17745. }
  17746. if (!isI18nRootNode(expansion.i18n)) {
  17747. throw new Error("Invalid type \"" + expansion.i18n.constructor + "\" for \"i18n\" property of " + expansion.sourceSpan.toString() + ". Expected a \"Message\"");
  17748. }
  17749. var message = expansion.i18n;
  17750. var vars = {};
  17751. var placeholders = {};
  17752. // extract VARs from ICUs - we process them separately while
  17753. // assembling resulting message via goog.getMsg function, since
  17754. // we need to pass them to top-level goog.getMsg call
  17755. Object.keys(message.placeholders).forEach(function (key) {
  17756. var value = message.placeholders[key];
  17757. if (key.startsWith(I18N_ICU_VAR_PREFIX)) {
  17758. // Currently when the `plural` or `select` keywords in an ICU contain trailing spaces (e.g.
  17759. // `{count, select , ...}`), these spaces are also included into the key names in ICU vars
  17760. // (e.g. "VAR_SELECT "). These trailing spaces are not desirable, since they will later be
  17761. // converted into `_` symbols while normalizing placeholder names, which might lead to
  17762. // mismatches at runtime (i.e. placeholder will not be replaced with the correct value).
  17763. var formattedKey = key.trim();
  17764. var ast = _this.bindingParser.parseInterpolationExpression(value.text, value.sourceSpan);
  17765. vars[formattedKey] = new BoundText(ast, value.sourceSpan);
  17766. }
  17767. else {
  17768. placeholders[key] = _this._visitTextWithInterpolation(value.text, value.sourceSpan);
  17769. }
  17770. });
  17771. return new Icu(vars, placeholders, expansion.sourceSpan, message);
  17772. };
  17773. HtmlAstToIvyAst.prototype.visitExpansionCase = function (expansionCase) {
  17774. return null;
  17775. };
  17776. HtmlAstToIvyAst.prototype.visitComment = function (comment) {
  17777. if (this.options.collectCommentNodes) {
  17778. this.commentNodes.push(new Comment(comment.value || '', comment.sourceSpan));
  17779. }
  17780. return null;
  17781. };
  17782. // convert view engine `ParsedProperty` to a format suitable for IVY
  17783. HtmlAstToIvyAst.prototype.extractAttributes = function (elementName, properties, i18nPropsMeta) {
  17784. var _this = this;
  17785. var bound = [];
  17786. var literal = [];
  17787. properties.forEach(function (prop) {
  17788. var i18n = i18nPropsMeta[prop.name];
  17789. if (prop.isLiteral) {
  17790. literal.push(new TextAttribute(prop.name, prop.expression.source || '', prop.sourceSpan, prop.keySpan, prop.valueSpan, i18n));
  17791. }
  17792. else {
  17793. // Note that validation is skipped and property mapping is disabled
  17794. // due to the fact that we need to make sure a given prop is not an
  17795. // input of a directive and directive matching happens at runtime.
  17796. var bep = _this.bindingParser.createBoundElementProperty(elementName, prop, /* skipValidation */ true, /* mapPropertyName */ false);
  17797. bound.push(BoundAttribute.fromBoundElementProperty(bep, i18n));
  17798. }
  17799. });
  17800. return { bound: bound, literal: literal };
  17801. };
  17802. HtmlAstToIvyAst.prototype.parseAttribute = function (isTemplateElement, attribute, matchableAttributes, parsedProperties, boundEvents, variables, references) {
  17803. var name = normalizeAttributeName(attribute.name);
  17804. var value = attribute.value;
  17805. var srcSpan = attribute.sourceSpan;
  17806. var absoluteOffset = attribute.valueSpan ? attribute.valueSpan.start.offset : srcSpan.start.offset;
  17807. function createKeySpan(srcSpan, prefix, identifier) {
  17808. // We need to adjust the start location for the keySpan to account for the removed 'data-'
  17809. // prefix from `normalizeAttributeName`.
  17810. var normalizationAdjustment = attribute.name.length - name.length;
  17811. var keySpanStart = srcSpan.start.moveBy(prefix.length + normalizationAdjustment);
  17812. var keySpanEnd = keySpanStart.moveBy(identifier.length);
  17813. return new ParseSourceSpan(keySpanStart, keySpanEnd, keySpanStart, identifier);
  17814. }
  17815. var bindParts = name.match(BIND_NAME_REGEXP$1);
  17816. if (bindParts) {
  17817. if (bindParts[KW_BIND_IDX$1] != null) {
  17818. var identifier = bindParts[IDENT_KW_IDX$1];
  17819. var keySpan_1 = createKeySpan(srcSpan, bindParts[KW_BIND_IDX$1], identifier);
  17820. this.bindingParser.parsePropertyBinding(identifier, value, false, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties, keySpan_1);
  17821. }
  17822. else if (bindParts[KW_LET_IDX$1]) {
  17823. if (isTemplateElement) {
  17824. var identifier = bindParts[IDENT_KW_IDX$1];
  17825. var keySpan_2 = createKeySpan(srcSpan, bindParts[KW_LET_IDX$1], identifier);
  17826. this.parseVariable(identifier, value, srcSpan, keySpan_2, attribute.valueSpan, variables);
  17827. }
  17828. else {
  17829. this.reportError("\"let-\" is only supported on ng-template elements.", srcSpan);
  17830. }
  17831. }
  17832. else if (bindParts[KW_REF_IDX$1]) {
  17833. var identifier = bindParts[IDENT_KW_IDX$1];
  17834. var keySpan_3 = createKeySpan(srcSpan, bindParts[KW_REF_IDX$1], identifier);
  17835. this.parseReference(identifier, value, srcSpan, keySpan_3, attribute.valueSpan, references);
  17836. }
  17837. else if (bindParts[KW_ON_IDX$1]) {
  17838. var events = [];
  17839. var identifier = bindParts[IDENT_KW_IDX$1];
  17840. var keySpan_4 = createKeySpan(srcSpan, bindParts[KW_ON_IDX$1], identifier);
  17841. this.bindingParser.parseEvent(identifier, value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events, keySpan_4);
  17842. addEvents(events, boundEvents);
  17843. }
  17844. else if (bindParts[KW_BINDON_IDX$1]) {
  17845. var identifier = bindParts[IDENT_KW_IDX$1];
  17846. var keySpan_5 = createKeySpan(srcSpan, bindParts[KW_BINDON_IDX$1], identifier);
  17847. this.bindingParser.parsePropertyBinding(identifier, value, false, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties, keySpan_5);
  17848. this.parseAssignmentEvent(identifier, value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents, keySpan_5);
  17849. }
  17850. else if (bindParts[KW_AT_IDX$1]) {
  17851. var keySpan_6 = createKeySpan(srcSpan, '', name);
  17852. this.bindingParser.parseLiteralAttr(name, value, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties, keySpan_6);
  17853. }
  17854. return true;
  17855. }
  17856. // We didn't see a kw-prefixed property binding, but we have not yet checked
  17857. // for the []/()/[()] syntax.
  17858. var delims = null;
  17859. if (name.startsWith(BINDING_DELIMS.BANANA_BOX.start)) {
  17860. delims = BINDING_DELIMS.BANANA_BOX;
  17861. }
  17862. else if (name.startsWith(BINDING_DELIMS.PROPERTY.start)) {
  17863. delims = BINDING_DELIMS.PROPERTY;
  17864. }
  17865. else if (name.startsWith(BINDING_DELIMS.EVENT.start)) {
  17866. delims = BINDING_DELIMS.EVENT;
  17867. }
  17868. if (delims !== null &&
  17869. // NOTE: older versions of the parser would match a start/end delimited
  17870. // binding iff the property name was terminated by the ending delimiter
  17871. // and the identifier in the binding was non-empty.
  17872. // TODO(ayazhafiz): update this to handle malformed bindings.
  17873. name.endsWith(delims.end) && name.length > delims.start.length + delims.end.length) {
  17874. var identifier = name.substring(delims.start.length, name.length - delims.end.length);
  17875. var keySpan_7 = createKeySpan(srcSpan, delims.start, identifier);
  17876. if (delims.start === BINDING_DELIMS.BANANA_BOX.start) {
  17877. this.bindingParser.parsePropertyBinding(identifier, value, false, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties, keySpan_7);
  17878. this.parseAssignmentEvent(identifier, value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents, keySpan_7);
  17879. }
  17880. else if (delims.start === BINDING_DELIMS.PROPERTY.start) {
  17881. this.bindingParser.parsePropertyBinding(identifier, value, false, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties, keySpan_7);
  17882. }
  17883. else {
  17884. var events = [];
  17885. this.bindingParser.parseEvent(identifier, value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events, keySpan_7);
  17886. addEvents(events, boundEvents);
  17887. }
  17888. return true;
  17889. }
  17890. // No explicit binding found.
  17891. var keySpan = createKeySpan(srcSpan, '' /* prefix */, name);
  17892. var hasBinding = this.bindingParser.parsePropertyInterpolation(name, value, srcSpan, attribute.valueSpan, matchableAttributes, parsedProperties, keySpan);
  17893. return hasBinding;
  17894. };
  17895. HtmlAstToIvyAst.prototype._visitTextWithInterpolation = function (value, sourceSpan, i18n) {
  17896. var valueNoNgsp = replaceNgsp(value);
  17897. var expr = this.bindingParser.parseInterpolation(valueNoNgsp, sourceSpan);
  17898. return expr ? new BoundText(expr, sourceSpan, i18n) : new Text(valueNoNgsp, sourceSpan);
  17899. };
  17900. HtmlAstToIvyAst.prototype.parseVariable = function (identifier, value, sourceSpan, keySpan, valueSpan, variables) {
  17901. if (identifier.indexOf('-') > -1) {
  17902. this.reportError("\"-\" is not allowed in variable names", sourceSpan);
  17903. }
  17904. else if (identifier.length === 0) {
  17905. this.reportError("Variable does not have a name", sourceSpan);
  17906. }
  17907. variables.push(new Variable(identifier, value, sourceSpan, keySpan, valueSpan));
  17908. };
  17909. HtmlAstToIvyAst.prototype.parseReference = function (identifier, value, sourceSpan, keySpan, valueSpan, references) {
  17910. if (identifier.indexOf('-') > -1) {
  17911. this.reportError("\"-\" is not allowed in reference names", sourceSpan);
  17912. }
  17913. else if (identifier.length === 0) {
  17914. this.reportError("Reference does not have a name", sourceSpan);
  17915. }
  17916. else if (references.some(function (reference) { return reference.name === identifier; })) {
  17917. this.reportError("Reference \"#" + identifier + "\" is defined more than once", sourceSpan);
  17918. }
  17919. references.push(new Reference(identifier, value, sourceSpan, keySpan, valueSpan));
  17920. };
  17921. HtmlAstToIvyAst.prototype.parseAssignmentEvent = function (name, expression, sourceSpan, valueSpan, targetMatchableAttrs, boundEvents, keySpan) {
  17922. var events = [];
  17923. this.bindingParser.parseEvent(name + "Change", expression + "=$event", sourceSpan, valueSpan || sourceSpan, targetMatchableAttrs, events, keySpan);
  17924. addEvents(events, boundEvents);
  17925. };
  17926. HtmlAstToIvyAst.prototype.reportError = function (message, sourceSpan, level) {
  17927. if (level === void 0) { level = exports.ParseErrorLevel.ERROR; }
  17928. this.errors.push(new ParseError(sourceSpan, message, level));
  17929. };
  17930. return HtmlAstToIvyAst;
  17931. }());
  17932. var NonBindableVisitor$1 = /** @class */ (function () {
  17933. function NonBindableVisitor() {
  17934. }
  17935. NonBindableVisitor.prototype.visitElement = function (ast) {
  17936. var preparsedElement = preparseElement(ast);
  17937. if (preparsedElement.type === PreparsedElementType.SCRIPT ||
  17938. preparsedElement.type === PreparsedElementType.STYLE ||
  17939. preparsedElement.type === PreparsedElementType.STYLESHEET) {
  17940. // Skipping <script> for security reasons
  17941. // Skipping <style> and stylesheets as we already processed them
  17942. // in the StyleCompiler
  17943. return null;
  17944. }
  17945. var children = visitAll$1(this, ast.children, null);
  17946. return new Element(ast.name, visitAll$1(this, ast.attrs),
  17947. /* inputs */ [], /* outputs */ [], children, /* references */ [], ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan);
  17948. };
  17949. NonBindableVisitor.prototype.visitComment = function (comment) {
  17950. return null;
  17951. };
  17952. NonBindableVisitor.prototype.visitAttribute = function (attribute) {
  17953. return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, attribute.keySpan, attribute.valueSpan, attribute.i18n);
  17954. };
  17955. NonBindableVisitor.prototype.visitText = function (text) {
  17956. return new Text(text.value, text.sourceSpan);
  17957. };
  17958. NonBindableVisitor.prototype.visitExpansion = function (expansion) {
  17959. return null;
  17960. };
  17961. NonBindableVisitor.prototype.visitExpansionCase = function (expansionCase) {
  17962. return null;
  17963. };
  17964. return NonBindableVisitor;
  17965. }());
  17966. var NON_BINDABLE_VISITOR$1 = new NonBindableVisitor$1();
  17967. function normalizeAttributeName(attrName) {
  17968. return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
  17969. }
  17970. function addEvents(events, boundEvents) {
  17971. boundEvents.push.apply(boundEvents, __spreadArray([], __read(events.map(function (e) { return BoundEvent.fromParsedEvent(e); }))));
  17972. }
  17973. function isEmptyTextNode(node) {
  17974. return node instanceof Text$3 && node.value.trim().length == 0;
  17975. }
  17976. function isCommentNode(node) {
  17977. return node instanceof Comment$1;
  17978. }
  17979. function textContents(node) {
  17980. if (node.children.length !== 1 || !(node.children[0] instanceof Text$3)) {
  17981. return null;
  17982. }
  17983. else {
  17984. return node.children[0].value;
  17985. }
  17986. }
  17987. var TagType;
  17988. (function (TagType) {
  17989. TagType[TagType["ELEMENT"] = 0] = "ELEMENT";
  17990. TagType[TagType["TEMPLATE"] = 1] = "TEMPLATE";
  17991. })(TagType || (TagType = {}));
  17992. /**
  17993. * Generates an object that is used as a shared state between parent and all child contexts.
  17994. */
  17995. function setupRegistry() {
  17996. return { getUniqueId: getSeqNumberGenerator(), icus: new Map() };
  17997. }
  17998. /**
  17999. * I18nContext is a helper class which keeps track of all i18n-related aspects
  18000. * (accumulates placeholders, bindings, etc) between i18nStart and i18nEnd instructions.
  18001. *
  18002. * When we enter a nested template, the top-level context is being passed down
  18003. * to the nested component, which uses this context to generate a child instance
  18004. * of I18nContext class (to handle nested template) and at the end, reconciles it back
  18005. * with the parent context.
  18006. *
  18007. * @param index Instruction index of i18nStart, which initiates this context
  18008. * @param ref Reference to a translation const that represents the content if thus context
  18009. * @param level Nestng level defined for child contexts
  18010. * @param templateIndex Instruction index of a template which this context belongs to
  18011. * @param meta Meta information (id, meaning, description, etc) associated with this context
  18012. */
  18013. var I18nContext = /** @class */ (function () {
  18014. function I18nContext(index, ref, level, templateIndex, meta, registry) {
  18015. if (level === void 0) { level = 0; }
  18016. if (templateIndex === void 0) { templateIndex = null; }
  18017. this.index = index;
  18018. this.ref = ref;
  18019. this.level = level;
  18020. this.templateIndex = templateIndex;
  18021. this.meta = meta;
  18022. this.registry = registry;
  18023. this.bindings = new Set();
  18024. this.placeholders = new Map();
  18025. this.isEmitted = false;
  18026. this._unresolvedCtxCount = 0;
  18027. this._registry = registry || setupRegistry();
  18028. this.id = this._registry.getUniqueId();
  18029. }
  18030. I18nContext.prototype.appendTag = function (type, node, index, closed) {
  18031. if (node.isVoid && closed) {
  18032. return; // ignore "close" for void tags
  18033. }
  18034. var ph = node.isVoid || !closed ? node.startName : node.closeName;
  18035. var content = { type: type, index: index, ctx: this.id, isVoid: node.isVoid, closed: closed };
  18036. updatePlaceholderMap(this.placeholders, ph, content);
  18037. };
  18038. Object.defineProperty(I18nContext.prototype, "icus", {
  18039. get: function () {
  18040. return this._registry.icus;
  18041. },
  18042. enumerable: false,
  18043. configurable: true
  18044. });
  18045. Object.defineProperty(I18nContext.prototype, "isRoot", {
  18046. get: function () {
  18047. return this.level === 0;
  18048. },
  18049. enumerable: false,
  18050. configurable: true
  18051. });
  18052. Object.defineProperty(I18nContext.prototype, "isResolved", {
  18053. get: function () {
  18054. return this._unresolvedCtxCount === 0;
  18055. },
  18056. enumerable: false,
  18057. configurable: true
  18058. });
  18059. I18nContext.prototype.getSerializedPlaceholders = function () {
  18060. var result = new Map();
  18061. this.placeholders.forEach(function (values, key) { return result.set(key, values.map(serializePlaceholderValue)); });
  18062. return result;
  18063. };
  18064. // public API to accumulate i18n-related content
  18065. I18nContext.prototype.appendBinding = function (binding) {
  18066. this.bindings.add(binding);
  18067. };
  18068. I18nContext.prototype.appendIcu = function (name, ref) {
  18069. updatePlaceholderMap(this._registry.icus, name, ref);
  18070. };
  18071. I18nContext.prototype.appendBoundText = function (node) {
  18072. var _this = this;
  18073. var phs = assembleBoundTextPlaceholders(node, this.bindings.size, this.id);
  18074. phs.forEach(function (values, key) { return updatePlaceholderMap.apply(void 0, __spreadArray([_this.placeholders, key], __read(values))); });
  18075. };
  18076. I18nContext.prototype.appendTemplate = function (node, index) {
  18077. // add open and close tags at the same time,
  18078. // since we process nested templates separately
  18079. this.appendTag(TagType.TEMPLATE, node, index, false);
  18080. this.appendTag(TagType.TEMPLATE, node, index, true);
  18081. this._unresolvedCtxCount++;
  18082. };
  18083. I18nContext.prototype.appendElement = function (node, index, closed) {
  18084. this.appendTag(TagType.ELEMENT, node, index, closed);
  18085. };
  18086. I18nContext.prototype.appendProjection = function (node, index) {
  18087. // Add open and close tags at the same time, since `<ng-content>` has no content,
  18088. // so when we come across `<ng-content>` we can register both open and close tags.
  18089. // Note: runtime i18n logic doesn't distinguish `<ng-content>` tag placeholders and
  18090. // regular element tag placeholders, so we generate element placeholders for both types.
  18091. this.appendTag(TagType.ELEMENT, node, index, false);
  18092. this.appendTag(TagType.ELEMENT, node, index, true);
  18093. };
  18094. /**
  18095. * Generates an instance of a child context based on the root one,
  18096. * when we enter a nested template within I18n section.
  18097. *
  18098. * @param index Instruction index of corresponding i18nStart, which initiates this context
  18099. * @param templateIndex Instruction index of a template which this context belongs to
  18100. * @param meta Meta information (id, meaning, description, etc) associated with this context
  18101. *
  18102. * @returns I18nContext instance
  18103. */
  18104. I18nContext.prototype.forkChildContext = function (index, templateIndex, meta) {
  18105. return new I18nContext(index, this.ref, this.level + 1, templateIndex, meta, this._registry);
  18106. };
  18107. /**
  18108. * Reconciles child context into parent one once the end of the i18n block is reached (i18nEnd).
  18109. *
  18110. * @param context Child I18nContext instance to be reconciled with parent context.
  18111. */
  18112. I18nContext.prototype.reconcileChildContext = function (context) {
  18113. var _this = this;
  18114. // set the right context id for open and close
  18115. // template tags, so we can use it as sub-block ids
  18116. ['start', 'close'].forEach(function (op) {
  18117. var key = context.meta[op + "Name"];
  18118. var phs = _this.placeholders.get(key) || [];
  18119. var tag = phs.find(findTemplateFn(_this.id, context.templateIndex));
  18120. if (tag) {
  18121. tag.ctx = context.id;
  18122. }
  18123. });
  18124. // reconcile placeholders
  18125. var childPhs = context.placeholders;
  18126. childPhs.forEach(function (values, key) {
  18127. var phs = _this.placeholders.get(key);
  18128. if (!phs) {
  18129. _this.placeholders.set(key, values);
  18130. return;
  18131. }
  18132. // try to find matching template...
  18133. var tmplIdx = phs.findIndex(findTemplateFn(context.id, context.templateIndex));
  18134. if (tmplIdx >= 0) {
  18135. // ... if found - replace it with nested template content
  18136. var isCloseTag = key.startsWith('CLOSE');
  18137. var isTemplateTag = key.endsWith('NG-TEMPLATE');
  18138. if (isTemplateTag) {
  18139. // current template's content is placed before or after
  18140. // parent template tag, depending on the open/close atrribute
  18141. phs.splice.apply(phs, __spreadArray([tmplIdx + (isCloseTag ? 0 : 1), 0], __read(values)));
  18142. }
  18143. else {
  18144. var idx = isCloseTag ? values.length - 1 : 0;
  18145. values[idx].tmpl = phs[tmplIdx];
  18146. phs.splice.apply(phs, __spreadArray([tmplIdx, 1], __read(values)));
  18147. }
  18148. }
  18149. else {
  18150. // ... otherwise just append content to placeholder value
  18151. phs.push.apply(phs, __spreadArray([], __read(values)));
  18152. }
  18153. _this.placeholders.set(key, phs);
  18154. });
  18155. this._unresolvedCtxCount--;
  18156. };
  18157. return I18nContext;
  18158. }());
  18159. //
  18160. // Helper methods
  18161. //
  18162. function wrap(symbol, index, contextId, closed) {
  18163. var state = closed ? '/' : '';
  18164. return wrapI18nPlaceholder("" + state + symbol + index, contextId);
  18165. }
  18166. function wrapTag(symbol, _a, closed) {
  18167. var index = _a.index, ctx = _a.ctx, isVoid = _a.isVoid;
  18168. return isVoid ? wrap(symbol, index, ctx) + wrap(symbol, index, ctx, true) :
  18169. wrap(symbol, index, ctx, closed);
  18170. }
  18171. function findTemplateFn(ctx, templateIndex) {
  18172. return function (token) { return typeof token === 'object' && token.type === TagType.TEMPLATE &&
  18173. token.index === templateIndex && token.ctx === ctx; };
  18174. }
  18175. function serializePlaceholderValue(value) {
  18176. var element = function (data, closed) { return wrapTag('#', data, closed); };
  18177. var template = function (data, closed) { return wrapTag('*', data, closed); };
  18178. var projection = function (data, closed) { return wrapTag('!', data, closed); };
  18179. switch (value.type) {
  18180. case TagType.ELEMENT:
  18181. // close element tag
  18182. if (value.closed) {
  18183. return element(value, true) + (value.tmpl ? template(value.tmpl, true) : '');
  18184. }
  18185. // open element tag that also initiates a template
  18186. if (value.tmpl) {
  18187. return template(value.tmpl) + element(value) +
  18188. (value.isVoid ? template(value.tmpl, true) : '');
  18189. }
  18190. return element(value);
  18191. case TagType.TEMPLATE:
  18192. return template(value, value.closed);
  18193. default:
  18194. return value;
  18195. }
  18196. }
  18197. /**
  18198. * @license
  18199. * Copyright Google LLC All Rights Reserved.
  18200. *
  18201. * Use of this source code is governed by an MIT-style license that can be
  18202. * found in the LICENSE file at https://angular.io/license
  18203. */
  18204. var IcuSerializerVisitor = /** @class */ (function () {
  18205. function IcuSerializerVisitor() {
  18206. }
  18207. IcuSerializerVisitor.prototype.visitText = function (text) {
  18208. return text.value;
  18209. };
  18210. IcuSerializerVisitor.prototype.visitContainer = function (container) {
  18211. var _this = this;
  18212. return container.children.map(function (child) { return child.visit(_this); }).join('');
  18213. };
  18214. IcuSerializerVisitor.prototype.visitIcu = function (icu) {
  18215. var _this = this;
  18216. var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  18217. var result = "{" + icu.expressionPlaceholder + ", " + icu.type + ", " + strCases.join(' ') + "}";
  18218. return result;
  18219. };
  18220. IcuSerializerVisitor.prototype.visitTagPlaceholder = function (ph) {
  18221. var _this = this;
  18222. return ph.isVoid ?
  18223. this.formatPh(ph.startName) :
  18224. "" + this.formatPh(ph.startName) + ph.children.map(function (child) { return child.visit(_this); }).join('') + this.formatPh(ph.closeName);
  18225. };
  18226. IcuSerializerVisitor.prototype.visitPlaceholder = function (ph) {
  18227. return this.formatPh(ph.name);
  18228. };
  18229. IcuSerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  18230. return this.formatPh(ph.name);
  18231. };
  18232. IcuSerializerVisitor.prototype.formatPh = function (value) {
  18233. return "{" + formatI18nPlaceholderName(value, /* useCamelCase */ false) + "}";
  18234. };
  18235. return IcuSerializerVisitor;
  18236. }());
  18237. var serializer = new IcuSerializerVisitor();
  18238. function serializeIcuNode(icu) {
  18239. return icu.visit(serializer);
  18240. }
  18241. /**
  18242. * @license
  18243. * Copyright Google LLC All Rights Reserved.
  18244. *
  18245. * Use of this source code is governed by an MIT-style license that can be
  18246. * found in the LICENSE file at https://angular.io/license
  18247. */
  18248. var TAG_TO_PLACEHOLDER_NAMES = {
  18249. 'A': 'LINK',
  18250. 'B': 'BOLD_TEXT',
  18251. 'BR': 'LINE_BREAK',
  18252. 'EM': 'EMPHASISED_TEXT',
  18253. 'H1': 'HEADING_LEVEL1',
  18254. 'H2': 'HEADING_LEVEL2',
  18255. 'H3': 'HEADING_LEVEL3',
  18256. 'H4': 'HEADING_LEVEL4',
  18257. 'H5': 'HEADING_LEVEL5',
  18258. 'H6': 'HEADING_LEVEL6',
  18259. 'HR': 'HORIZONTAL_RULE',
  18260. 'I': 'ITALIC_TEXT',
  18261. 'LI': 'LIST_ITEM',
  18262. 'LINK': 'MEDIA_LINK',
  18263. 'OL': 'ORDERED_LIST',
  18264. 'P': 'PARAGRAPH',
  18265. 'Q': 'QUOTATION',
  18266. 'S': 'STRIKETHROUGH_TEXT',
  18267. 'SMALL': 'SMALL_TEXT',
  18268. 'SUB': 'SUBSTRIPT',
  18269. 'SUP': 'SUPERSCRIPT',
  18270. 'TBODY': 'TABLE_BODY',
  18271. 'TD': 'TABLE_CELL',
  18272. 'TFOOT': 'TABLE_FOOTER',
  18273. 'TH': 'TABLE_HEADER_CELL',
  18274. 'THEAD': 'TABLE_HEADER',
  18275. 'TR': 'TABLE_ROW',
  18276. 'TT': 'MONOSPACED_TEXT',
  18277. 'U': 'UNDERLINED_TEXT',
  18278. 'UL': 'UNORDERED_LIST',
  18279. };
  18280. /**
  18281. * Creates unique names for placeholder with different content.
  18282. *
  18283. * Returns the same placeholder name when the content is identical.
  18284. */
  18285. var PlaceholderRegistry = /** @class */ (function () {
  18286. function PlaceholderRegistry() {
  18287. // Count the occurrence of the base name top generate a unique name
  18288. this._placeHolderNameCounts = {};
  18289. // Maps signature to placeholder names
  18290. this._signatureToName = {};
  18291. }
  18292. PlaceholderRegistry.prototype.getStartTagPlaceholderName = function (tag, attrs, isVoid) {
  18293. var signature = this._hashTag(tag, attrs, isVoid);
  18294. if (this._signatureToName[signature]) {
  18295. return this._signatureToName[signature];
  18296. }
  18297. var upperTag = tag.toUpperCase();
  18298. var baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || "TAG_" + upperTag;
  18299. var name = this._generateUniqueName(isVoid ? baseName : "START_" + baseName);
  18300. this._signatureToName[signature] = name;
  18301. return name;
  18302. };
  18303. PlaceholderRegistry.prototype.getCloseTagPlaceholderName = function (tag) {
  18304. var signature = this._hashClosingTag(tag);
  18305. if (this._signatureToName[signature]) {
  18306. return this._signatureToName[signature];
  18307. }
  18308. var upperTag = tag.toUpperCase();
  18309. var baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || "TAG_" + upperTag;
  18310. var name = this._generateUniqueName("CLOSE_" + baseName);
  18311. this._signatureToName[signature] = name;
  18312. return name;
  18313. };
  18314. PlaceholderRegistry.prototype.getPlaceholderName = function (name, content) {
  18315. var upperName = name.toUpperCase();
  18316. var signature = "PH: " + upperName + "=" + content;
  18317. if (this._signatureToName[signature]) {
  18318. return this._signatureToName[signature];
  18319. }
  18320. var uniqueName = this._generateUniqueName(upperName);
  18321. this._signatureToName[signature] = uniqueName;
  18322. return uniqueName;
  18323. };
  18324. PlaceholderRegistry.prototype.getUniquePlaceholder = function (name) {
  18325. return this._generateUniqueName(name.toUpperCase());
  18326. };
  18327. // Generate a hash for a tag - does not take attribute order into account
  18328. PlaceholderRegistry.prototype._hashTag = function (tag, attrs, isVoid) {
  18329. var start = "<" + tag;
  18330. var strAttrs = Object.keys(attrs).sort().map(function (name) { return " " + name + "=" + attrs[name]; }).join('');
  18331. var end = isVoid ? '/>' : "></" + tag + ">";
  18332. return start + strAttrs + end;
  18333. };
  18334. PlaceholderRegistry.prototype._hashClosingTag = function (tag) {
  18335. return this._hashTag("/" + tag, {}, false);
  18336. };
  18337. PlaceholderRegistry.prototype._generateUniqueName = function (base) {
  18338. var seen = this._placeHolderNameCounts.hasOwnProperty(base);
  18339. if (!seen) {
  18340. this._placeHolderNameCounts[base] = 1;
  18341. return base;
  18342. }
  18343. var id = this._placeHolderNameCounts[base];
  18344. this._placeHolderNameCounts[base] = id + 1;
  18345. return base + "_" + id;
  18346. };
  18347. return PlaceholderRegistry;
  18348. }());
  18349. /**
  18350. * @license
  18351. * Copyright Google LLC All Rights Reserved.
  18352. *
  18353. * Use of this source code is governed by an MIT-style license that can be
  18354. * found in the LICENSE file at https://angular.io/license
  18355. */
  18356. var _expParser = new Parser$1(new Lexer());
  18357. /**
  18358. * Returns a function converting html nodes to an i18n Message given an interpolationConfig
  18359. */
  18360. function createI18nMessageFactory(interpolationConfig) {
  18361. var visitor = new _I18nVisitor(_expParser, interpolationConfig);
  18362. return function (nodes, meaning, description, customId, visitNodeFn) { return visitor.toI18nMessage(nodes, meaning, description, customId, visitNodeFn); };
  18363. }
  18364. function noopVisitNodeFn(_html, i18n) {
  18365. return i18n;
  18366. }
  18367. var _I18nVisitor = /** @class */ (function () {
  18368. function _I18nVisitor(_expressionParser, _interpolationConfig) {
  18369. this._expressionParser = _expressionParser;
  18370. this._interpolationConfig = _interpolationConfig;
  18371. }
  18372. _I18nVisitor.prototype.toI18nMessage = function (nodes, meaning, description, customId, visitNodeFn) {
  18373. if (meaning === void 0) { meaning = ''; }
  18374. if (description === void 0) { description = ''; }
  18375. if (customId === void 0) { customId = ''; }
  18376. var context = {
  18377. isIcu: nodes.length == 1 && nodes[0] instanceof Expansion,
  18378. icuDepth: 0,
  18379. placeholderRegistry: new PlaceholderRegistry(),
  18380. placeholderToContent: {},
  18381. placeholderToMessage: {},
  18382. visitNodeFn: visitNodeFn || noopVisitNodeFn,
  18383. };
  18384. var i18nodes = visitAll$1(this, nodes, context);
  18385. return new Message(i18nodes, context.placeholderToContent, context.placeholderToMessage, meaning, description, customId);
  18386. };
  18387. _I18nVisitor.prototype.visitElement = function (el, context) {
  18388. var _a;
  18389. var children = visitAll$1(this, el.children, context);
  18390. var attrs = {};
  18391. el.attrs.forEach(function (attr) {
  18392. // Do not visit the attributes, translatable ones are top-level ASTs
  18393. attrs[attr.name] = attr.value;
  18394. });
  18395. var isVoid = getHtmlTagDefinition(el.name).isVoid;
  18396. var startPhName = context.placeholderRegistry.getStartTagPlaceholderName(el.name, attrs, isVoid);
  18397. context.placeholderToContent[startPhName] = {
  18398. text: el.startSourceSpan.toString(),
  18399. sourceSpan: el.startSourceSpan,
  18400. };
  18401. var closePhName = '';
  18402. if (!isVoid) {
  18403. closePhName = context.placeholderRegistry.getCloseTagPlaceholderName(el.name);
  18404. context.placeholderToContent[closePhName] = {
  18405. text: "</" + el.name + ">",
  18406. sourceSpan: (_a = el.endSourceSpan) !== null && _a !== void 0 ? _a : el.sourceSpan,
  18407. };
  18408. }
  18409. var node = new TagPlaceholder(el.name, attrs, startPhName, closePhName, children, isVoid, el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
  18410. return context.visitNodeFn(el, node);
  18411. };
  18412. _I18nVisitor.prototype.visitAttribute = function (attribute, context) {
  18413. var node = this._visitTextWithInterpolation(attribute.value, attribute.valueSpan || attribute.sourceSpan, context, attribute.i18n);
  18414. return context.visitNodeFn(attribute, node);
  18415. };
  18416. _I18nVisitor.prototype.visitText = function (text, context) {
  18417. var node = this._visitTextWithInterpolation(text.value, text.sourceSpan, context, text.i18n);
  18418. return context.visitNodeFn(text, node);
  18419. };
  18420. _I18nVisitor.prototype.visitComment = function (comment, context) {
  18421. return null;
  18422. };
  18423. _I18nVisitor.prototype.visitExpansion = function (icu, context) {
  18424. var _this = this;
  18425. context.icuDepth++;
  18426. var i18nIcuCases = {};
  18427. var i18nIcu = new Icu$1(icu.switchValue, icu.type, i18nIcuCases, icu.sourceSpan);
  18428. icu.cases.forEach(function (caze) {
  18429. i18nIcuCases[caze.value] = new Container(caze.expression.map(function (node) { return node.visit(_this, context); }), caze.expSourceSpan);
  18430. });
  18431. context.icuDepth--;
  18432. if (context.isIcu || context.icuDepth > 0) {
  18433. // Returns an ICU node when:
  18434. // - the message (vs a part of the message) is an ICU message, or
  18435. // - the ICU message is nested.
  18436. var expPh = context.placeholderRegistry.getUniquePlaceholder("VAR_" + icu.type);
  18437. i18nIcu.expressionPlaceholder = expPh;
  18438. context.placeholderToContent[expPh] = {
  18439. text: icu.switchValue,
  18440. sourceSpan: icu.switchValueSourceSpan,
  18441. };
  18442. return context.visitNodeFn(icu, i18nIcu);
  18443. }
  18444. // Else returns a placeholder
  18445. // ICU placeholders should not be replaced with their original content but with the their
  18446. // translations.
  18447. // TODO(vicb): add a html.Node -> i18n.Message cache to avoid having to re-create the msg
  18448. var phName = context.placeholderRegistry.getPlaceholderName('ICU', icu.sourceSpan.toString());
  18449. context.placeholderToMessage[phName] = this.toI18nMessage([icu], '', '', '', undefined);
  18450. var node = new IcuPlaceholder(i18nIcu, phName, icu.sourceSpan);
  18451. return context.visitNodeFn(icu, node);
  18452. };
  18453. _I18nVisitor.prototype.visitExpansionCase = function (_icuCase, _context) {
  18454. throw new Error('Unreachable code');
  18455. };
  18456. /**
  18457. * Split the, potentially interpolated, text up into text and placeholder pieces.
  18458. *
  18459. * @param text The potentially interpolated string to be split.
  18460. * @param sourceSpan The span of the whole of the `text` string.
  18461. * @param context The current context of the visitor, used to compute and store placeholders.
  18462. * @param previousI18n Any i18n metadata associated with this `text` from a previous pass.
  18463. */
  18464. _I18nVisitor.prototype._visitTextWithInterpolation = function (text, sourceSpan, context, previousI18n) {
  18465. var _b = this._expressionParser.splitInterpolation(text, sourceSpan.start.toString(), this._interpolationConfig), strings = _b.strings, expressions = _b.expressions;
  18466. // No expressions, return a single text.
  18467. if (expressions.length === 0) {
  18468. return new Text$1(text, sourceSpan);
  18469. }
  18470. // Return a sequence of `Text` and `Placeholder` nodes grouped in a `Container`.
  18471. var nodes = [];
  18472. for (var i = 0; i < strings.length - 1; i++) {
  18473. this._addText(nodes, strings[i], sourceSpan);
  18474. this._addPlaceholder(nodes, context, expressions[i], sourceSpan);
  18475. }
  18476. // The last index contains no expression
  18477. this._addText(nodes, strings[strings.length - 1], sourceSpan);
  18478. // Whitespace removal may have invalidated the interpolation source-spans.
  18479. reusePreviousSourceSpans(nodes, previousI18n);
  18480. return new Container(nodes, sourceSpan);
  18481. };
  18482. /**
  18483. * Create a new `Text` node from the `textPiece` and add it to the `nodes` collection.
  18484. *
  18485. * @param nodes The nodes to which the created `Text` node should be added.
  18486. * @param textPiece The text and relative span information for this `Text` node.
  18487. * @param interpolationSpan The span of the whole interpolated text.
  18488. */
  18489. _I18nVisitor.prototype._addText = function (nodes, textPiece, interpolationSpan) {
  18490. if (textPiece.text.length > 0) {
  18491. // No need to add empty strings
  18492. var stringSpan = getOffsetSourceSpan(interpolationSpan, textPiece);
  18493. nodes.push(new Text$1(textPiece.text, stringSpan));
  18494. }
  18495. };
  18496. /**
  18497. * Create a new `Placeholder` node from the `expression` and add it to the `nodes` collection.
  18498. *
  18499. * @param nodes The nodes to which the created `Text` node should be added.
  18500. * @param context The current context of the visitor, used to compute and store placeholders.
  18501. * @param expression The expression text and relative span information for this `Placeholder`
  18502. * node.
  18503. * @param interpolationSpan The span of the whole interpolated text.
  18504. */
  18505. _I18nVisitor.prototype._addPlaceholder = function (nodes, context, expression, interpolationSpan) {
  18506. var sourceSpan = getOffsetSourceSpan(interpolationSpan, expression);
  18507. var baseName = extractPlaceholderName(expression.text) || 'INTERPOLATION';
  18508. var phName = context.placeholderRegistry.getPlaceholderName(baseName, expression.text);
  18509. var text = this._interpolationConfig.start + expression.text + this._interpolationConfig.end;
  18510. context.placeholderToContent[phName] = { text: text, sourceSpan: sourceSpan };
  18511. nodes.push(new Placeholder(expression.text, phName, sourceSpan));
  18512. };
  18513. return _I18nVisitor;
  18514. }());
  18515. /**
  18516. * Re-use the source-spans from `previousI18n` metadata for the `nodes`.
  18517. *
  18518. * Whitespace removal can invalidate the source-spans of interpolation nodes, so we
  18519. * reuse the source-span stored from a previous pass before the whitespace was removed.
  18520. *
  18521. * @param nodes The `Text` and `Placeholder` nodes to be processed.
  18522. * @param previousI18n Any i18n metadata for these `nodes` stored from a previous pass.
  18523. */
  18524. function reusePreviousSourceSpans(nodes, previousI18n) {
  18525. if (previousI18n instanceof Message) {
  18526. // The `previousI18n` is an i18n `Message`, so we are processing an `Attribute` with i18n
  18527. // metadata. The `Message` should consist only of a single `Container` that contains the
  18528. // parts (`Text` and `Placeholder`) to process.
  18529. assertSingleContainerMessage(previousI18n);
  18530. previousI18n = previousI18n.nodes[0];
  18531. }
  18532. if (previousI18n instanceof Container) {
  18533. // The `previousI18n` is a `Container`, which means that this is a second i18n extraction pass
  18534. // after whitespace has been removed from the AST ndoes.
  18535. assertEquivalentNodes(previousI18n.children, nodes);
  18536. // Reuse the source-spans from the first pass.
  18537. for (var i = 0; i < nodes.length; i++) {
  18538. nodes[i].sourceSpan = previousI18n.children[i].sourceSpan;
  18539. }
  18540. }
  18541. }
  18542. /**
  18543. * Asserts that the `message` contains exactly one `Container` node.
  18544. */
  18545. function assertSingleContainerMessage(message) {
  18546. var nodes = message.nodes;
  18547. if (nodes.length !== 1 || !(nodes[0] instanceof Container)) {
  18548. throw new Error('Unexpected previous i18n message - expected it to consist of only a single `Container` node.');
  18549. }
  18550. }
  18551. /**
  18552. * Asserts that the `previousNodes` and `node` collections have the same number of elements and
  18553. * corresponding elements have the same node type.
  18554. */
  18555. function assertEquivalentNodes(previousNodes, nodes) {
  18556. if (previousNodes.length !== nodes.length) {
  18557. throw new Error('The number of i18n message children changed between first and second pass.');
  18558. }
  18559. if (previousNodes.some(function (node, i) { return nodes[i].constructor !== node.constructor; })) {
  18560. throw new Error('The types of the i18n message children changed between first and second pass.');
  18561. }
  18562. }
  18563. /**
  18564. * Create a new `ParseSourceSpan` from the `sourceSpan`, offset by the `start` and `end` values.
  18565. */
  18566. function getOffsetSourceSpan(sourceSpan, _b) {
  18567. var start = _b.start, end = _b.end;
  18568. return new ParseSourceSpan(sourceSpan.fullStart.moveBy(start), sourceSpan.fullStart.moveBy(end));
  18569. }
  18570. var _CUSTOM_PH_EXP = /\/\/[\s\S]*i18n[\s\S]*\([\s\S]*ph[\s\S]*=[\s\S]*("|')([\s\S]*?)\1[\s\S]*\)/g;
  18571. function extractPlaceholderName(input) {
  18572. return input.split(_CUSTOM_PH_EXP)[2];
  18573. }
  18574. /**
  18575. * An i18n error.
  18576. */
  18577. var I18nError = /** @class */ (function (_super) {
  18578. __extends(I18nError, _super);
  18579. function I18nError(span, msg) {
  18580. return _super.call(this, span, msg) || this;
  18581. }
  18582. return I18nError;
  18583. }(ParseError));
  18584. var setI18nRefs = function (htmlNode, i18nNode) {
  18585. if (htmlNode instanceof NodeWithI18n) {
  18586. if (i18nNode instanceof IcuPlaceholder && htmlNode.i18n instanceof Message) {
  18587. // This html node represents an ICU but this is a second processing pass, and the legacy id
  18588. // was computed in the previous pass and stored in the `i18n` property as a message.
  18589. // We are about to wipe out that property so capture the previous message to be reused when
  18590. // generating the message for this ICU later. See `_generateI18nMessage()`.
  18591. i18nNode.previousMessage = htmlNode.i18n;
  18592. }
  18593. htmlNode.i18n = i18nNode;
  18594. }
  18595. return i18nNode;
  18596. };
  18597. /**
  18598. * This visitor walks over HTML parse tree and converts information stored in
  18599. * i18n-related attributes ("i18n" and "i18n-*") into i18n meta object that is
  18600. * stored with other element's and attribute's information.
  18601. */
  18602. var I18nMetaVisitor = /** @class */ (function () {
  18603. function I18nMetaVisitor(interpolationConfig, keepI18nAttrs, enableI18nLegacyMessageIdFormat) {
  18604. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  18605. if (keepI18nAttrs === void 0) { keepI18nAttrs = false; }
  18606. if (enableI18nLegacyMessageIdFormat === void 0) { enableI18nLegacyMessageIdFormat = false; }
  18607. this.interpolationConfig = interpolationConfig;
  18608. this.keepI18nAttrs = keepI18nAttrs;
  18609. this.enableI18nLegacyMessageIdFormat = enableI18nLegacyMessageIdFormat;
  18610. // whether visited nodes contain i18n information
  18611. this.hasI18nMeta = false;
  18612. this._errors = [];
  18613. // i18n message generation factory
  18614. this._createI18nMessage = createI18nMessageFactory(this.interpolationConfig);
  18615. }
  18616. I18nMetaVisitor.prototype._generateI18nMessage = function (nodes, meta, visitNodeFn) {
  18617. if (meta === void 0) { meta = ''; }
  18618. var _a = this._parseMetadata(meta), meaning = _a.meaning, description = _a.description, customId = _a.customId;
  18619. var message = this._createI18nMessage(nodes, meaning, description, customId, visitNodeFn);
  18620. this._setMessageId(message, meta);
  18621. this._setLegacyIds(message, meta);
  18622. return message;
  18623. };
  18624. I18nMetaVisitor.prototype.visitAllWithErrors = function (nodes) {
  18625. var _this = this;
  18626. var result = nodes.map(function (node) { return node.visit(_this, null); });
  18627. return new ParseTreeResult(result, this._errors);
  18628. };
  18629. I18nMetaVisitor.prototype.visitElement = function (element) {
  18630. var e_1, _a, e_2, _b;
  18631. if (hasI18nAttrs(element)) {
  18632. this.hasI18nMeta = true;
  18633. var attrs = [];
  18634. var attrsMeta = {};
  18635. try {
  18636. for (var _c = __values(element.attrs), _d = _c.next(); !_d.done; _d = _c.next()) {
  18637. var attr = _d.value;
  18638. if (attr.name === I18N_ATTR) {
  18639. // root 'i18n' node attribute
  18640. var i18n_1 = element.i18n || attr.value;
  18641. var message = this._generateI18nMessage(element.children, i18n_1, setI18nRefs);
  18642. // do not assign empty i18n meta
  18643. if (message.nodes.length) {
  18644. element.i18n = message;
  18645. }
  18646. }
  18647. else if (attr.name.startsWith(I18N_ATTR_PREFIX)) {
  18648. // 'i18n-*' attributes
  18649. var name = attr.name.slice(I18N_ATTR_PREFIX.length);
  18650. if (isTrustedTypesSink(element.name, name)) {
  18651. this._reportError(attr, "Translating attribute '" + name + "' is disallowed for security reasons.");
  18652. }
  18653. else {
  18654. attrsMeta[name] = attr.value;
  18655. }
  18656. }
  18657. else {
  18658. // non-i18n attributes
  18659. attrs.push(attr);
  18660. }
  18661. }
  18662. }
  18663. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  18664. finally {
  18665. try {
  18666. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  18667. }
  18668. finally { if (e_1) throw e_1.error; }
  18669. }
  18670. // set i18n meta for attributes
  18671. if (Object.keys(attrsMeta).length) {
  18672. try {
  18673. for (var attrs_1 = __values(attrs), attrs_1_1 = attrs_1.next(); !attrs_1_1.done; attrs_1_1 = attrs_1.next()) {
  18674. var attr = attrs_1_1.value;
  18675. var meta = attrsMeta[attr.name];
  18676. // do not create translation for empty attributes
  18677. if (meta !== undefined && attr.value) {
  18678. attr.i18n = this._generateI18nMessage([attr], attr.i18n || meta);
  18679. }
  18680. }
  18681. }
  18682. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  18683. finally {
  18684. try {
  18685. if (attrs_1_1 && !attrs_1_1.done && (_b = attrs_1.return)) _b.call(attrs_1);
  18686. }
  18687. finally { if (e_2) throw e_2.error; }
  18688. }
  18689. }
  18690. if (!this.keepI18nAttrs) {
  18691. // update element's attributes,
  18692. // keeping only non-i18n related ones
  18693. element.attrs = attrs;
  18694. }
  18695. }
  18696. visitAll$1(this, element.children, element.i18n);
  18697. return element;
  18698. };
  18699. I18nMetaVisitor.prototype.visitExpansion = function (expansion, currentMessage) {
  18700. var message;
  18701. var meta = expansion.i18n;
  18702. this.hasI18nMeta = true;
  18703. if (meta instanceof IcuPlaceholder) {
  18704. // set ICU placeholder name (e.g. "ICU_1"),
  18705. // generated while processing root element contents,
  18706. // so we can reference it when we output translation
  18707. var name = meta.name;
  18708. message = this._generateI18nMessage([expansion], meta);
  18709. var icu = icuFromI18nMessage(message);
  18710. icu.name = name;
  18711. }
  18712. else {
  18713. // ICU is a top level message, try to use metadata from container element if provided via
  18714. // `context` argument. Note: context may not be available for standalone ICUs (without
  18715. // wrapping element), so fallback to ICU metadata in this case.
  18716. message = this._generateI18nMessage([expansion], currentMessage || meta);
  18717. }
  18718. expansion.i18n = message;
  18719. return expansion;
  18720. };
  18721. I18nMetaVisitor.prototype.visitText = function (text) {
  18722. return text;
  18723. };
  18724. I18nMetaVisitor.prototype.visitAttribute = function (attribute) {
  18725. return attribute;
  18726. };
  18727. I18nMetaVisitor.prototype.visitComment = function (comment) {
  18728. return comment;
  18729. };
  18730. I18nMetaVisitor.prototype.visitExpansionCase = function (expansionCase) {
  18731. return expansionCase;
  18732. };
  18733. /**
  18734. * Parse the general form `meta` passed into extract the explicit metadata needed to create a
  18735. * `Message`.
  18736. *
  18737. * There are three possibilities for the `meta` variable
  18738. * 1) a string from an `i18n` template attribute: parse it to extract the metadata values.
  18739. * 2) a `Message` from a previous processing pass: reuse the metadata values in the message.
  18740. * 4) other: ignore this and just process the message metadata as normal
  18741. *
  18742. * @param meta the bucket that holds information about the message
  18743. * @returns the parsed metadata.
  18744. */
  18745. I18nMetaVisitor.prototype._parseMetadata = function (meta) {
  18746. return typeof meta === 'string' ? parseI18nMeta(meta) :
  18747. meta instanceof Message ? meta : {};
  18748. };
  18749. /**
  18750. * Generate (or restore) message id if not specified already.
  18751. */
  18752. I18nMetaVisitor.prototype._setMessageId = function (message, meta) {
  18753. if (!message.id) {
  18754. message.id = meta instanceof Message && meta.id || decimalDigest(message);
  18755. }
  18756. };
  18757. /**
  18758. * Update the `message` with a `legacyId` if necessary.
  18759. *
  18760. * @param message the message whose legacy id should be set
  18761. * @param meta information about the message being processed
  18762. */
  18763. I18nMetaVisitor.prototype._setLegacyIds = function (message, meta) {
  18764. if (this.enableI18nLegacyMessageIdFormat) {
  18765. message.legacyIds = [computeDigest(message), computeDecimalDigest(message)];
  18766. }
  18767. else if (typeof meta !== 'string') {
  18768. // This occurs if we are doing the 2nd pass after whitespace removal (see `parseTemplate()` in
  18769. // `packages/compiler/src/render3/view/template.ts`).
  18770. // In that case we want to reuse the legacy message generated in the 1st pass (see
  18771. // `setI18nRefs()`).
  18772. var previousMessage = meta instanceof Message ?
  18773. meta :
  18774. meta instanceof IcuPlaceholder ? meta.previousMessage : undefined;
  18775. message.legacyIds = previousMessage ? previousMessage.legacyIds : [];
  18776. }
  18777. };
  18778. I18nMetaVisitor.prototype._reportError = function (node, msg) {
  18779. this._errors.push(new I18nError(node.sourceSpan, msg));
  18780. };
  18781. return I18nMetaVisitor;
  18782. }());
  18783. /** I18n separators for metadata **/
  18784. var I18N_MEANING_SEPARATOR = '|';
  18785. var I18N_ID_SEPARATOR = '@@';
  18786. /**
  18787. * Parses i18n metas like:
  18788. * - "@@id",
  18789. * - "description[@@id]",
  18790. * - "meaning|description[@@id]"
  18791. * and returns an object with parsed output.
  18792. *
  18793. * @param meta String that represents i18n meta
  18794. * @returns Object with id, meaning and description fields
  18795. */
  18796. function parseI18nMeta(meta) {
  18797. var _a, _b;
  18798. if (meta === void 0) { meta = ''; }
  18799. var customId;
  18800. var meaning;
  18801. var description;
  18802. meta = meta.trim();
  18803. if (meta) {
  18804. var idIndex = meta.indexOf(I18N_ID_SEPARATOR);
  18805. var descIndex = meta.indexOf(I18N_MEANING_SEPARATOR);
  18806. var meaningAndDesc = void 0;
  18807. _a = __read((idIndex > -1) ? [meta.slice(0, idIndex), meta.slice(idIndex + 2)] : [meta, ''], 2), meaningAndDesc = _a[0], customId = _a[1];
  18808. _b = __read((descIndex > -1) ?
  18809. [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
  18810. ['', meaningAndDesc], 2), meaning = _b[0], description = _b[1];
  18811. }
  18812. return { customId: customId, meaning: meaning, description: description };
  18813. }
  18814. // Converts i18n meta information for a message (id, description, meaning)
  18815. // to a JsDoc statement formatted as expected by the Closure compiler.
  18816. function i18nMetaToJSDoc(meta) {
  18817. var tags = [];
  18818. if (meta.description) {
  18819. tags.push({ tagName: "desc" /* Desc */, text: meta.description });
  18820. }
  18821. if (meta.meaning) {
  18822. tags.push({ tagName: "meaning" /* Meaning */, text: meta.meaning });
  18823. }
  18824. return tags.length == 0 ? null : jsDocComment(tags);
  18825. }
  18826. /** Closure uses `goog.getMsg(message)` to lookup translations */
  18827. var GOOG_GET_MSG = 'goog.getMsg';
  18828. function createGoogleGetMsgStatements(variable$1, message, closureVar, params) {
  18829. var messageString = serializeI18nMessageForGetMsg(message);
  18830. var args = [literal(messageString)];
  18831. if (Object.keys(params).length) {
  18832. args.push(mapLiteral(params, true));
  18833. }
  18834. // /**
  18835. // * @desc description of message
  18836. // * @meaning meaning of message
  18837. // */
  18838. // const MSG_... = goog.getMsg(..);
  18839. // I18N_X = MSG_...;
  18840. var googGetMsgStmt = closureVar.set(variable(GOOG_GET_MSG).callFn(args)).toConstDecl();
  18841. var metaComment = i18nMetaToJSDoc(message);
  18842. if (metaComment !== null) {
  18843. googGetMsgStmt.addLeadingComment(metaComment);
  18844. }
  18845. var i18nAssignmentStmt = new ExpressionStatement(variable$1.set(closureVar));
  18846. return [googGetMsgStmt, i18nAssignmentStmt];
  18847. }
  18848. /**
  18849. * This visitor walks over i18n tree and generates its string representation, including ICUs and
  18850. * placeholders in `{$placeholder}` (for plain messages) or `{PLACEHOLDER}` (inside ICUs) format.
  18851. */
  18852. var GetMsgSerializerVisitor = /** @class */ (function () {
  18853. function GetMsgSerializerVisitor() {
  18854. }
  18855. GetMsgSerializerVisitor.prototype.formatPh = function (value) {
  18856. return "{$" + formatI18nPlaceholderName(value) + "}";
  18857. };
  18858. GetMsgSerializerVisitor.prototype.visitText = function (text) {
  18859. return text.value;
  18860. };
  18861. GetMsgSerializerVisitor.prototype.visitContainer = function (container) {
  18862. var _this = this;
  18863. return container.children.map(function (child) { return child.visit(_this); }).join('');
  18864. };
  18865. GetMsgSerializerVisitor.prototype.visitIcu = function (icu) {
  18866. return serializeIcuNode(icu);
  18867. };
  18868. GetMsgSerializerVisitor.prototype.visitTagPlaceholder = function (ph) {
  18869. var _this = this;
  18870. return ph.isVoid ?
  18871. this.formatPh(ph.startName) :
  18872. "" + this.formatPh(ph.startName) + ph.children.map(function (child) { return child.visit(_this); }).join('') + this.formatPh(ph.closeName);
  18873. };
  18874. GetMsgSerializerVisitor.prototype.visitPlaceholder = function (ph) {
  18875. return this.formatPh(ph.name);
  18876. };
  18877. GetMsgSerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  18878. return this.formatPh(ph.name);
  18879. };
  18880. return GetMsgSerializerVisitor;
  18881. }());
  18882. var serializerVisitor$1 = new GetMsgSerializerVisitor();
  18883. function serializeI18nMessageForGetMsg(message) {
  18884. return message.nodes.map(function (node) { return node.visit(serializerVisitor$1, null); }).join('');
  18885. }
  18886. function createLocalizeStatements(variable, message, params) {
  18887. var _c = serializeI18nMessageForLocalize(message), messageParts = _c.messageParts, placeHolders = _c.placeHolders;
  18888. var sourceSpan = getSourceSpan(message);
  18889. var expressions = placeHolders.map(function (ph) { return params[ph.text]; });
  18890. var localizedString$1 = localizedString(message, messageParts, placeHolders, expressions, sourceSpan);
  18891. var variableInitialization = variable.set(localizedString$1);
  18892. return [new ExpressionStatement(variableInitialization)];
  18893. }
  18894. /**
  18895. * This visitor walks over an i18n tree, capturing literal strings and placeholders.
  18896. *
  18897. * The result can be used for generating the `$localize` tagged template literals.
  18898. */
  18899. var LocalizeSerializerVisitor = /** @class */ (function () {
  18900. function LocalizeSerializerVisitor() {
  18901. }
  18902. LocalizeSerializerVisitor.prototype.visitText = function (text, context) {
  18903. if (context[context.length - 1] instanceof LiteralPiece) {
  18904. // Two literal pieces in a row means that there was some comment node in-between.
  18905. context[context.length - 1].text += text.value;
  18906. }
  18907. else {
  18908. context.push(new LiteralPiece(text.value, text.sourceSpan));
  18909. }
  18910. };
  18911. LocalizeSerializerVisitor.prototype.visitContainer = function (container, context) {
  18912. var _this = this;
  18913. container.children.forEach(function (child) { return child.visit(_this, context); });
  18914. };
  18915. LocalizeSerializerVisitor.prototype.visitIcu = function (icu, context) {
  18916. context.push(new LiteralPiece(serializeIcuNode(icu), icu.sourceSpan));
  18917. };
  18918. LocalizeSerializerVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  18919. var _this = this;
  18920. var _a, _b;
  18921. context.push(this.createPlaceholderPiece(ph.startName, (_a = ph.startSourceSpan) !== null && _a !== void 0 ? _a : ph.sourceSpan));
  18922. if (!ph.isVoid) {
  18923. ph.children.forEach(function (child) { return child.visit(_this, context); });
  18924. context.push(this.createPlaceholderPiece(ph.closeName, (_b = ph.endSourceSpan) !== null && _b !== void 0 ? _b : ph.sourceSpan));
  18925. }
  18926. };
  18927. LocalizeSerializerVisitor.prototype.visitPlaceholder = function (ph, context) {
  18928. context.push(this.createPlaceholderPiece(ph.name, ph.sourceSpan));
  18929. };
  18930. LocalizeSerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  18931. context.push(this.createPlaceholderPiece(ph.name, ph.sourceSpan));
  18932. };
  18933. LocalizeSerializerVisitor.prototype.createPlaceholderPiece = function (name, sourceSpan) {
  18934. return new PlaceholderPiece(formatI18nPlaceholderName(name, /* useCamelCase */ false), sourceSpan);
  18935. };
  18936. return LocalizeSerializerVisitor;
  18937. }());
  18938. var serializerVisitor$2 = new LocalizeSerializerVisitor();
  18939. /**
  18940. * Serialize an i18n message into two arrays: messageParts and placeholders.
  18941. *
  18942. * These arrays will be used to generate `$localize` tagged template literals.
  18943. *
  18944. * @param message The message to be serialized.
  18945. * @returns an object containing the messageParts and placeholders.
  18946. */
  18947. function serializeI18nMessageForLocalize(message) {
  18948. var pieces = [];
  18949. message.nodes.forEach(function (node) { return node.visit(serializerVisitor$2, pieces); });
  18950. return processMessagePieces(pieces);
  18951. }
  18952. function getSourceSpan(message) {
  18953. var startNode = message.nodes[0];
  18954. var endNode = message.nodes[message.nodes.length - 1];
  18955. return new ParseSourceSpan(startNode.sourceSpan.start, endNode.sourceSpan.end, startNode.sourceSpan.fullStart, startNode.sourceSpan.details);
  18956. }
  18957. /**
  18958. * Convert the list of serialized MessagePieces into two arrays.
  18959. *
  18960. * One contains the literal string pieces and the other the placeholders that will be replaced by
  18961. * expressions when rendering `$localize` tagged template literals.
  18962. *
  18963. * @param pieces The pieces to process.
  18964. * @returns an object containing the messageParts and placeholders.
  18965. */
  18966. function processMessagePieces(pieces) {
  18967. var messageParts = [];
  18968. var placeHolders = [];
  18969. if (pieces[0] instanceof PlaceholderPiece) {
  18970. // The first piece was a placeholder so we need to add an initial empty message part.
  18971. messageParts.push(createEmptyMessagePart(pieces[0].sourceSpan.start));
  18972. }
  18973. for (var i = 0; i < pieces.length; i++) {
  18974. var part = pieces[i];
  18975. if (part instanceof LiteralPiece) {
  18976. messageParts.push(part);
  18977. }
  18978. else {
  18979. placeHolders.push(part);
  18980. if (pieces[i - 1] instanceof PlaceholderPiece) {
  18981. // There were two placeholders in a row, so we need to add an empty message part.
  18982. messageParts.push(createEmptyMessagePart(pieces[i - 1].sourceSpan.end));
  18983. }
  18984. }
  18985. }
  18986. if (pieces[pieces.length - 1] instanceof PlaceholderPiece) {
  18987. // The last piece was a placeholder so we need to add a final empty message part.
  18988. messageParts.push(createEmptyMessagePart(pieces[pieces.length - 1].sourceSpan.end));
  18989. }
  18990. return { messageParts: messageParts, placeHolders: placeHolders };
  18991. }
  18992. function createEmptyMessagePart(location) {
  18993. return new LiteralPiece('', new ParseSourceSpan(location, location));
  18994. }
  18995. // Selector attribute name of `<ng-content>`
  18996. var NG_CONTENT_SELECT_ATTR$1 = 'select';
  18997. // Attribute name of `ngProjectAs`.
  18998. var NG_PROJECT_AS_ATTR_NAME = 'ngProjectAs';
  18999. // Global symbols available only inside event bindings.
  19000. var EVENT_BINDING_SCOPE_GLOBALS = new Set(['$event']);
  19001. // List of supported global targets for event listeners
  19002. var GLOBAL_TARGET_RESOLVERS = new Map([['window', Identifiers.resolveWindow], ['document', Identifiers.resolveDocument], ['body', Identifiers.resolveBody]]);
  19003. var LEADING_TRIVIA_CHARS = [' ', '\n', '\r', '\t'];
  19004. // if (rf & flags) { .. }
  19005. function renderFlagCheckIfStmt(flags, statements) {
  19006. return ifStmt(variable(RENDER_FLAGS).bitwiseAnd(literal(flags), null, false), statements);
  19007. }
  19008. function prepareEventListenerParameters(eventAst, handlerName, scope) {
  19009. if (handlerName === void 0) { handlerName = null; }
  19010. if (scope === void 0) { scope = null; }
  19011. var type = eventAst.type, name = eventAst.name, target = eventAst.target, phase = eventAst.phase, handler = eventAst.handler;
  19012. if (target && !GLOBAL_TARGET_RESOLVERS.has(target)) {
  19013. throw new Error("Unexpected global target '" + target + "' defined for '" + name + "' event.\n Supported list of global targets: " + Array.from(GLOBAL_TARGET_RESOLVERS.keys()) + ".");
  19014. }
  19015. var eventArgumentName = '$event';
  19016. var implicitReceiverAccesses = new Set();
  19017. var implicitReceiverExpr = (scope === null || scope.bindingLevel === 0) ?
  19018. variable(CONTEXT_NAME) :
  19019. scope.getOrCreateSharedContextVar(0);
  19020. var bindingExpr = convertActionBinding(scope, implicitReceiverExpr, handler, 'b', function () { return error('Unexpected interpolation'); }, eventAst.handlerSpan, implicitReceiverAccesses, EVENT_BINDING_SCOPE_GLOBALS);
  19021. var statements = [];
  19022. if (scope) {
  19023. // `variableDeclarations` needs to run first, because
  19024. // `restoreViewStatement` depends on the result.
  19025. statements.push.apply(statements, __spreadArray([], __read(scope.variableDeclarations())));
  19026. statements.unshift.apply(statements, __spreadArray([], __read(scope.restoreViewStatement())));
  19027. }
  19028. statements.push.apply(statements, __spreadArray([], __read(bindingExpr.render3Stmts)));
  19029. var eventName = type === 1 /* Animation */ ? prepareSyntheticListenerName(name, phase) : name;
  19030. var fnName = handlerName && sanitizeIdentifier(handlerName);
  19031. var fnArgs = [];
  19032. if (implicitReceiverAccesses.has(eventArgumentName)) {
  19033. fnArgs.push(new FnParam(eventArgumentName, DYNAMIC_TYPE));
  19034. }
  19035. var handlerFn = fn(fnArgs, statements, INFERRED_TYPE, null, fnName);
  19036. var params = [literal(eventName), handlerFn];
  19037. if (target) {
  19038. params.push(literal(false), // `useCapture` flag, defaults to `false`
  19039. importExpr(GLOBAL_TARGET_RESOLVERS.get(target)));
  19040. }
  19041. return params;
  19042. }
  19043. function createComponentDefConsts() {
  19044. return {
  19045. prepareStatements: [],
  19046. constExpressions: [],
  19047. i18nVarRefsCache: new Map(),
  19048. };
  19049. }
  19050. var TemplateDefinitionBuilder = /** @class */ (function () {
  19051. function TemplateDefinitionBuilder(constantPool, parentBindingScope, level, contextName, i18nContext, templateIndex, templateName, directiveMatcher, directives, pipeTypeByName, pipes, _namespace, relativeContextFilePath, i18nUseExternalIds, _constants) {
  19052. var _this = this;
  19053. if (level === void 0) { level = 0; }
  19054. if (_constants === void 0) { _constants = createComponentDefConsts(); }
  19055. this.constantPool = constantPool;
  19056. this.level = level;
  19057. this.contextName = contextName;
  19058. this.i18nContext = i18nContext;
  19059. this.templateIndex = templateIndex;
  19060. this.templateName = templateName;
  19061. this.directiveMatcher = directiveMatcher;
  19062. this.directives = directives;
  19063. this.pipeTypeByName = pipeTypeByName;
  19064. this.pipes = pipes;
  19065. this._namespace = _namespace;
  19066. this.i18nUseExternalIds = i18nUseExternalIds;
  19067. this._constants = _constants;
  19068. this._dataIndex = 0;
  19069. this._bindingContext = 0;
  19070. this._prefixCode = [];
  19071. /**
  19072. * List of callbacks to generate creation mode instructions. We store them here as we process
  19073. * the template so bindings in listeners are resolved only once all nodes have been visited.
  19074. * This ensures all local refs and context variables are available for matching.
  19075. */
  19076. this._creationCodeFns = [];
  19077. /**
  19078. * List of callbacks to generate update mode instructions. We store them here as we process
  19079. * the template so bindings are resolved only once all nodes have been visited. This ensures
  19080. * all local refs and context variables are available for matching.
  19081. */
  19082. this._updateCodeFns = [];
  19083. /** Index of the currently-selected node. */
  19084. this._currentIndex = 0;
  19085. /** Temporary variable declarations generated from visiting pipes, literals, etc. */
  19086. this._tempVariables = [];
  19087. /**
  19088. * List of callbacks to build nested templates. Nested templates must not be visited until
  19089. * after the parent template has finished visiting all of its nodes. This ensures that all
  19090. * local ref bindings in nested templates are able to find local ref values if the refs
  19091. * are defined after the template declaration.
  19092. */
  19093. this._nestedTemplateFns = [];
  19094. this._unsupported = unsupported;
  19095. // i18n context local to this template
  19096. this.i18n = null;
  19097. // Number of slots to reserve for pureFunctions
  19098. this._pureFunctionSlots = 0;
  19099. // Number of binding slots
  19100. this._bindingSlots = 0;
  19101. // Projection slots found in the template. Projection slots can distribute projected
  19102. // nodes based on a selector, or can just use the wildcard selector to match
  19103. // all nodes which aren't matching any selector.
  19104. this._ngContentReservedSlots = [];
  19105. // Number of non-default selectors found in all parent templates of this template. We need to
  19106. // track it to properly adjust projection slot index in the `projection` instruction.
  19107. this._ngContentSelectorsOffset = 0;
  19108. // Expression that should be used as implicit receiver when converting template
  19109. // expressions to output AST.
  19110. this._implicitReceiverExpr = null;
  19111. // These should be handled in the template or element directly.
  19112. this.visitReference = invalid$1;
  19113. this.visitVariable = invalid$1;
  19114. this.visitTextAttribute = invalid$1;
  19115. this.visitBoundAttribute = invalid$1;
  19116. this.visitBoundEvent = invalid$1;
  19117. this._bindingScope = parentBindingScope.nestedScope(level);
  19118. // Turn the relative context file path into an identifier by replacing non-alphanumeric
  19119. // characters with underscores.
  19120. this.fileBasedI18nSuffix = relativeContextFilePath.replace(/[^A-Za-z0-9]/g, '_') + '_';
  19121. this._valueConverter = new ValueConverter(constantPool, function () { return _this.allocateDataSlot(); }, function (numSlots) { return _this.allocatePureFunctionSlots(numSlots); }, function (name, localName, slot, value) {
  19122. var pipeType = pipeTypeByName.get(name);
  19123. if (pipeType) {
  19124. _this.pipes.add(pipeType);
  19125. }
  19126. _this._bindingScope.set(_this.level, localName, value);
  19127. _this.creationInstruction(null, Identifiers.pipe, [literal(slot), literal(name)]);
  19128. });
  19129. }
  19130. TemplateDefinitionBuilder.prototype.buildTemplateFunction = function (nodes, variables, ngContentSelectorsOffset, i18n) {
  19131. var _this = this;
  19132. if (ngContentSelectorsOffset === void 0) { ngContentSelectorsOffset = 0; }
  19133. this._ngContentSelectorsOffset = ngContentSelectorsOffset;
  19134. if (this._namespace !== Identifiers.namespaceHTML) {
  19135. this.creationInstruction(null, this._namespace);
  19136. }
  19137. // Create variable bindings
  19138. variables.forEach(function (v) { return _this.registerContextVariables(v); });
  19139. // Initiate i18n context in case:
  19140. // - this template has parent i18n context
  19141. // - or the template has i18n meta associated with it,
  19142. // but it's not initiated by the Element (e.g. <ng-template i18n>)
  19143. var initI18nContext = this.i18nContext ||
  19144. (isI18nRootNode(i18n) && !isSingleI18nIcu(i18n) &&
  19145. !(isSingleElementTemplate(nodes) && nodes[0].i18n === i18n));
  19146. var selfClosingI18nInstruction = hasTextChildrenOnly(nodes);
  19147. if (initI18nContext) {
  19148. this.i18nStart(null, i18n, selfClosingI18nInstruction);
  19149. }
  19150. // This is the initial pass through the nodes of this template. In this pass, we
  19151. // queue all creation mode and update mode instructions for generation in the second
  19152. // pass. It's necessary to separate the passes to ensure local refs are defined before
  19153. // resolving bindings. We also count bindings in this pass as we walk bound expressions.
  19154. visitAll(this, nodes);
  19155. // Add total binding count to pure function count so pure function instructions are
  19156. // generated with the correct slot offset when update instructions are processed.
  19157. this._pureFunctionSlots += this._bindingSlots;
  19158. // Pipes are walked in the first pass (to enqueue `pipe()` creation instructions and
  19159. // `pipeBind` update instructions), so we have to update the slot offsets manually
  19160. // to account for bindings.
  19161. this._valueConverter.updatePipeSlotOffsets(this._bindingSlots);
  19162. // Nested templates must be processed before creation instructions so template()
  19163. // instructions can be generated with the correct internal const count.
  19164. this._nestedTemplateFns.forEach(function (buildTemplateFn) { return buildTemplateFn(); });
  19165. // Output the `projectionDef` instruction when some `<ng-content>` tags are present.
  19166. // The `projectionDef` instruction is only emitted for the component template and
  19167. // is skipped for nested templates (<ng-template> tags).
  19168. if (this.level === 0 && this._ngContentReservedSlots.length) {
  19169. var parameters = [];
  19170. // By default the `projectionDef` instructions creates one slot for the wildcard
  19171. // selector if no parameters are passed. Therefore we only want to allocate a new
  19172. // array for the projection slots if the default projection slot is not sufficient.
  19173. if (this._ngContentReservedSlots.length > 1 || this._ngContentReservedSlots[0] !== '*') {
  19174. var r3ReservedSlots = this._ngContentReservedSlots.map(function (s) { return s !== '*' ? parseSelectorToR3Selector(s) : s; });
  19175. parameters.push(this.constantPool.getConstLiteral(asLiteral(r3ReservedSlots), true));
  19176. }
  19177. // Since we accumulate ngContent selectors while processing template elements,
  19178. // we *prepend* `projectionDef` to creation instructions block, to put it before
  19179. // any `projection` instructions
  19180. this.creationInstruction(null, Identifiers.projectionDef, parameters, /* prepend */ true);
  19181. }
  19182. if (initI18nContext) {
  19183. this.i18nEnd(null, selfClosingI18nInstruction);
  19184. }
  19185. // Generate all the creation mode instructions (e.g. resolve bindings in listeners)
  19186. var creationStatements = this._creationCodeFns.map(function (fn) { return fn(); });
  19187. // Generate all the update mode instructions (e.g. resolve property or text bindings)
  19188. var updateStatements = this._updateCodeFns.map(function (fn) { return fn(); });
  19189. // Variable declaration must occur after binding resolution so we can generate context
  19190. // instructions that build on each other.
  19191. // e.g. const b = nextContext().$implicit(); const b = nextContext();
  19192. var creationVariables = this._bindingScope.viewSnapshotStatements();
  19193. var updateVariables = this._bindingScope.variableDeclarations().concat(this._tempVariables);
  19194. var creationBlock = creationStatements.length > 0 ?
  19195. [renderFlagCheckIfStmt(1 /* Create */, creationVariables.concat(creationStatements))] :
  19196. [];
  19197. var updateBlock = updateStatements.length > 0 ?
  19198. [renderFlagCheckIfStmt(2 /* Update */, updateVariables.concat(updateStatements))] :
  19199. [];
  19200. return fn(
  19201. // i.e. (rf: RenderFlags, ctx: any)
  19202. [new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], __spreadArray(__spreadArray(__spreadArray([], __read(this._prefixCode)), __read(creationBlock)), __read(updateBlock)), INFERRED_TYPE, null, this.templateName);
  19203. };
  19204. // LocalResolver
  19205. TemplateDefinitionBuilder.prototype.getLocal = function (name) {
  19206. return this._bindingScope.get(name);
  19207. };
  19208. // LocalResolver
  19209. TemplateDefinitionBuilder.prototype.notifyImplicitReceiverUse = function () {
  19210. this._bindingScope.notifyImplicitReceiverUse();
  19211. };
  19212. TemplateDefinitionBuilder.prototype.i18nTranslate = function (message, params, ref, transformFn) {
  19213. var _c;
  19214. if (params === void 0) { params = {}; }
  19215. var _ref = ref || this.i18nGenerateMainBlockVar();
  19216. // Closure Compiler requires const names to start with `MSG_` but disallows any other const to
  19217. // start with `MSG_`. We define a variable starting with `MSG_` just for the `goog.getMsg` call
  19218. var closureVar = this.i18nGenerateClosureVar(message.id);
  19219. var statements = getTranslationDeclStmts(message, _ref, closureVar, params, transformFn);
  19220. (_c = this._constants.prepareStatements).push.apply(_c, __spreadArray([], __read(statements)));
  19221. return _ref;
  19222. };
  19223. TemplateDefinitionBuilder.prototype.registerContextVariables = function (variable$1) {
  19224. var scopedName = this._bindingScope.freshReferenceName();
  19225. var retrievalLevel = this.level;
  19226. var lhs = variable(variable$1.name + scopedName);
  19227. this._bindingScope.set(retrievalLevel, variable$1.name, lhs, 1 /* CONTEXT */, function (scope, relativeLevel) {
  19228. var rhs;
  19229. if (scope.bindingLevel === retrievalLevel) {
  19230. if (scope.isListenerScope() && scope.hasRestoreViewVariable()) {
  19231. // e.g. restoredCtx.
  19232. // We have to get the context from a view reference, if one is available, because
  19233. // the context that was passed in during creation may not be correct anymore.
  19234. // For more information see: https://github.com/angular/angular/pull/40360.
  19235. rhs = variable(RESTORED_VIEW_CONTEXT_NAME);
  19236. scope.notifyRestoredViewContextUse();
  19237. }
  19238. else {
  19239. // e.g. ctx
  19240. rhs = variable(CONTEXT_NAME);
  19241. }
  19242. }
  19243. else {
  19244. var sharedCtxVar = scope.getSharedContextName(retrievalLevel);
  19245. // e.g. ctx_r0 OR x(2);
  19246. rhs = sharedCtxVar ? sharedCtxVar : generateNextContextExpr(relativeLevel);
  19247. }
  19248. // e.g. const $item$ = x(2).$implicit;
  19249. return [lhs.set(rhs.prop(variable$1.value || IMPLICIT_REFERENCE)).toConstDecl()];
  19250. });
  19251. };
  19252. TemplateDefinitionBuilder.prototype.i18nAppendBindings = function (expressions) {
  19253. var _this = this;
  19254. if (expressions.length > 0) {
  19255. expressions.forEach(function (expression) { return _this.i18n.appendBinding(expression); });
  19256. }
  19257. };
  19258. TemplateDefinitionBuilder.prototype.i18nBindProps = function (props) {
  19259. var _this = this;
  19260. var bound = {};
  19261. Object.keys(props).forEach(function (key) {
  19262. var prop = props[key];
  19263. if (prop instanceof Text) {
  19264. bound[key] = literal(prop.value);
  19265. }
  19266. else {
  19267. var value = prop.value.visit(_this._valueConverter);
  19268. _this.allocateBindingSlots(value);
  19269. if (value instanceof Interpolation) {
  19270. var strings = value.strings, expressions = value.expressions;
  19271. var _c = _this.i18n, id = _c.id, bindings = _c.bindings;
  19272. var label = assembleI18nBoundString(strings, bindings.size, id);
  19273. _this.i18nAppendBindings(expressions);
  19274. bound[key] = literal(label);
  19275. }
  19276. }
  19277. });
  19278. return bound;
  19279. };
  19280. // Generates top level vars for i18n blocks (i.e. `i18n_N`).
  19281. TemplateDefinitionBuilder.prototype.i18nGenerateMainBlockVar = function () {
  19282. return variable(this.constantPool.uniqueName(TRANSLATION_VAR_PREFIX));
  19283. };
  19284. // Generates vars with Closure-specific names for i18n blocks (i.e. `MSG_XXX`).
  19285. TemplateDefinitionBuilder.prototype.i18nGenerateClosureVar = function (messageId) {
  19286. var name;
  19287. var suffix = this.fileBasedI18nSuffix.toUpperCase();
  19288. if (this.i18nUseExternalIds) {
  19289. var prefix = getTranslationConstPrefix("EXTERNAL_");
  19290. var uniqueSuffix = this.constantPool.uniqueName(suffix);
  19291. name = "" + prefix + sanitizeIdentifier(messageId) + "$$" + uniqueSuffix;
  19292. }
  19293. else {
  19294. var prefix = getTranslationConstPrefix(suffix);
  19295. name = this.constantPool.uniqueName(prefix);
  19296. }
  19297. return variable(name);
  19298. };
  19299. TemplateDefinitionBuilder.prototype.i18nUpdateRef = function (context) {
  19300. var icus = context.icus, meta = context.meta, isRoot = context.isRoot, isResolved = context.isResolved, isEmitted = context.isEmitted;
  19301. if (isRoot && isResolved && !isEmitted && !isSingleI18nIcu(meta)) {
  19302. context.isEmitted = true;
  19303. var placeholders = context.getSerializedPlaceholders();
  19304. var icuMapping_1 = {};
  19305. var params_1 = placeholders.size ? placeholdersToParams(placeholders) : {};
  19306. if (icus.size) {
  19307. icus.forEach(function (refs, key) {
  19308. if (refs.length === 1) {
  19309. // if we have one ICU defined for a given
  19310. // placeholder - just output its reference
  19311. params_1[key] = refs[0];
  19312. }
  19313. else {
  19314. // ... otherwise we need to activate post-processing
  19315. // to replace ICU placeholders with proper values
  19316. var placeholder = wrapI18nPlaceholder("" + I18N_ICU_MAPPING_PREFIX + key);
  19317. params_1[key] = literal(placeholder);
  19318. icuMapping_1[key] = literalArr(refs);
  19319. }
  19320. });
  19321. }
  19322. // translation requires post processing in 2 cases:
  19323. // - if we have placeholders with multiple values (ex. `START_DIV`: [�#1�, �#2�, ...])
  19324. // - if we have multiple ICUs that refer to the same placeholder name
  19325. var needsPostprocessing = Array.from(placeholders.values()).some(function (value) { return value.length > 1; }) ||
  19326. Object.keys(icuMapping_1).length;
  19327. var transformFn = void 0;
  19328. if (needsPostprocessing) {
  19329. transformFn = function (raw) {
  19330. var args = [raw];
  19331. if (Object.keys(icuMapping_1).length) {
  19332. args.push(mapLiteral(icuMapping_1, true));
  19333. }
  19334. return instruction(null, Identifiers.i18nPostprocess, args);
  19335. };
  19336. }
  19337. this.i18nTranslate(meta, params_1, context.ref, transformFn);
  19338. }
  19339. };
  19340. TemplateDefinitionBuilder.prototype.i18nStart = function (span, meta, selfClosing) {
  19341. if (span === void 0) { span = null; }
  19342. var index = this.allocateDataSlot();
  19343. this.i18n = this.i18nContext ?
  19344. this.i18nContext.forkChildContext(index, this.templateIndex, meta) :
  19345. new I18nContext(index, this.i18nGenerateMainBlockVar(), 0, this.templateIndex, meta);
  19346. // generate i18nStart instruction
  19347. var _c = this.i18n, id = _c.id, ref = _c.ref;
  19348. var params = [literal(index), this.addToConsts(ref)];
  19349. if (id > 0) {
  19350. // do not push 3rd argument (sub-block id)
  19351. // into i18nStart call for top level i18n context
  19352. params.push(literal(id));
  19353. }
  19354. this.creationInstruction(span, selfClosing ? Identifiers.i18n : Identifiers.i18nStart, params);
  19355. };
  19356. TemplateDefinitionBuilder.prototype.i18nEnd = function (span, selfClosing) {
  19357. var _this = this;
  19358. if (span === void 0) { span = null; }
  19359. if (!this.i18n) {
  19360. throw new Error('i18nEnd is executed with no i18n context present');
  19361. }
  19362. if (this.i18nContext) {
  19363. this.i18nContext.reconcileChildContext(this.i18n);
  19364. this.i18nUpdateRef(this.i18nContext);
  19365. }
  19366. else {
  19367. this.i18nUpdateRef(this.i18n);
  19368. }
  19369. // setup accumulated bindings
  19370. var _c = this.i18n, index = _c.index, bindings = _c.bindings;
  19371. if (bindings.size) {
  19372. var chainBindings_1 = [];
  19373. bindings.forEach(function (binding) {
  19374. chainBindings_1.push({ sourceSpan: span, value: function () { return _this.convertPropertyBinding(binding); } });
  19375. });
  19376. // for i18n block, advance to the most recent element index (by taking the current number of
  19377. // elements and subtracting one) before invoking `i18nExp` instructions, to make sure the
  19378. // necessary lifecycle hooks of components/directives are properly flushed.
  19379. this.updateInstructionChainWithAdvance(this.getConstCount() - 1, Identifiers.i18nExp, chainBindings_1);
  19380. this.updateInstruction(span, Identifiers.i18nApply, [literal(index)]);
  19381. }
  19382. if (!selfClosing) {
  19383. this.creationInstruction(span, Identifiers.i18nEnd);
  19384. }
  19385. this.i18n = null; // reset local i18n context
  19386. };
  19387. TemplateDefinitionBuilder.prototype.i18nAttributesInstruction = function (nodeIndex, attrs, sourceSpan) {
  19388. var _this = this;
  19389. var hasBindings = false;
  19390. var i18nAttrArgs = [];
  19391. var bindings = [];
  19392. attrs.forEach(function (attr) {
  19393. var message = attr.i18n;
  19394. var converted = attr.value.visit(_this._valueConverter);
  19395. _this.allocateBindingSlots(converted);
  19396. if (converted instanceof Interpolation) {
  19397. var placeholders = assembleBoundTextPlaceholders(message);
  19398. var params = placeholdersToParams(placeholders);
  19399. i18nAttrArgs.push(literal(attr.name), _this.i18nTranslate(message, params));
  19400. converted.expressions.forEach(function (expression) {
  19401. hasBindings = true;
  19402. bindings.push({
  19403. sourceSpan: sourceSpan,
  19404. value: function () { return _this.convertPropertyBinding(expression); },
  19405. });
  19406. });
  19407. }
  19408. });
  19409. if (bindings.length > 0) {
  19410. this.updateInstructionChainWithAdvance(nodeIndex, Identifiers.i18nExp, bindings);
  19411. }
  19412. if (i18nAttrArgs.length > 0) {
  19413. var index = literal(this.allocateDataSlot());
  19414. var constIndex = this.addToConsts(literalArr(i18nAttrArgs));
  19415. this.creationInstruction(sourceSpan, Identifiers.i18nAttributes, [index, constIndex]);
  19416. if (hasBindings) {
  19417. this.updateInstruction(sourceSpan, Identifiers.i18nApply, [index]);
  19418. }
  19419. }
  19420. };
  19421. TemplateDefinitionBuilder.prototype.getNamespaceInstruction = function (namespaceKey) {
  19422. switch (namespaceKey) {
  19423. case 'math':
  19424. return Identifiers.namespaceMathML;
  19425. case 'svg':
  19426. return Identifiers.namespaceSVG;
  19427. default:
  19428. return Identifiers.namespaceHTML;
  19429. }
  19430. };
  19431. TemplateDefinitionBuilder.prototype.addNamespaceInstruction = function (nsInstruction, element) {
  19432. this._namespace = nsInstruction;
  19433. this.creationInstruction(element.startSourceSpan, nsInstruction);
  19434. };
  19435. /**
  19436. * Adds an update instruction for an interpolated property or attribute, such as
  19437. * `prop="{{value}}"` or `attr.title="{{value}}"`
  19438. */
  19439. TemplateDefinitionBuilder.prototype.interpolatedUpdateInstruction = function (instruction, elementIndex, attrName, input, value, params) {
  19440. var _this = this;
  19441. this.updateInstructionWithAdvance(elementIndex, input.sourceSpan, instruction, function () { return __spreadArray(__spreadArray([literal(attrName)], __read(_this.getUpdateInstructionArguments(value))), __read(params)); });
  19442. };
  19443. TemplateDefinitionBuilder.prototype.visitContent = function (ngContent) {
  19444. var slot = this.allocateDataSlot();
  19445. var projectionSlotIdx = this._ngContentSelectorsOffset + this._ngContentReservedSlots.length;
  19446. var parameters = [literal(slot)];
  19447. this._ngContentReservedSlots.push(ngContent.selector);
  19448. var nonContentSelectAttributes = ngContent.attributes.filter(function (attr) { return attr.name.toLowerCase() !== NG_CONTENT_SELECT_ATTR$1; });
  19449. var attributes = this.getAttributeExpressions(ngContent.name, nonContentSelectAttributes, [], []);
  19450. if (attributes.length > 0) {
  19451. parameters.push(literal(projectionSlotIdx), literalArr(attributes));
  19452. }
  19453. else if (projectionSlotIdx !== 0) {
  19454. parameters.push(literal(projectionSlotIdx));
  19455. }
  19456. this.creationInstruction(ngContent.sourceSpan, Identifiers.projection, parameters);
  19457. if (this.i18n) {
  19458. this.i18n.appendProjection(ngContent.i18n, slot);
  19459. }
  19460. };
  19461. TemplateDefinitionBuilder.prototype.visitElement = function (element) {
  19462. var e_1, _c;
  19463. var _this = this;
  19464. var _a, _b;
  19465. var elementIndex = this.allocateDataSlot();
  19466. var stylingBuilder = new StylingBuilder(null);
  19467. var isNonBindableMode = false;
  19468. var isI18nRootElement = isI18nRootNode(element.i18n) && !isSingleI18nIcu(element.i18n);
  19469. var outputAttrs = [];
  19470. var _d = __read(splitNsName(element.name), 2), namespaceKey = _d[0], elementName = _d[1];
  19471. var isNgContainer$1 = isNgContainer(element.name);
  19472. try {
  19473. // Handle styling, i18n, ngNonBindable attributes
  19474. for (var _e = __values(element.attributes), _f = _e.next(); !_f.done; _f = _e.next()) {
  19475. var attr = _f.value;
  19476. var name = attr.name, value = attr.value;
  19477. if (name === NON_BINDABLE_ATTR) {
  19478. isNonBindableMode = true;
  19479. }
  19480. else if (name === 'style') {
  19481. stylingBuilder.registerStyleAttr(value);
  19482. }
  19483. else if (name === 'class') {
  19484. stylingBuilder.registerClassAttr(value);
  19485. }
  19486. else {
  19487. outputAttrs.push(attr);
  19488. }
  19489. }
  19490. }
  19491. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  19492. finally {
  19493. try {
  19494. if (_f && !_f.done && (_c = _e.return)) _c.call(_e);
  19495. }
  19496. finally { if (e_1) throw e_1.error; }
  19497. }
  19498. // Match directives on non i18n attributes
  19499. this.matchDirectives(element.name, element);
  19500. // Regular element or ng-container creation mode
  19501. var parameters = [literal(elementIndex)];
  19502. if (!isNgContainer$1) {
  19503. parameters.push(literal(elementName));
  19504. }
  19505. // Add the attributes
  19506. var allOtherInputs = [];
  19507. var boundI18nAttrs = [];
  19508. element.inputs.forEach(function (input) {
  19509. var stylingInputWasSet = stylingBuilder.registerBoundInput(input);
  19510. if (!stylingInputWasSet) {
  19511. if (input.type === 0 /* Property */ && input.i18n) {
  19512. boundI18nAttrs.push(input);
  19513. }
  19514. else {
  19515. allOtherInputs.push(input);
  19516. }
  19517. }
  19518. });
  19519. // add attributes for directive and projection matching purposes
  19520. var attributes = this.getAttributeExpressions(element.name, outputAttrs, allOtherInputs, element.outputs, stylingBuilder, [], boundI18nAttrs);
  19521. parameters.push(this.addAttrsToConsts(attributes));
  19522. // local refs (ex.: <div #foo #bar="baz">)
  19523. var refs = this.prepareRefsArray(element.references);
  19524. parameters.push(this.addToConsts(refs));
  19525. var wasInNamespace = this._namespace;
  19526. var currentNamespace = this.getNamespaceInstruction(namespaceKey);
  19527. // If the namespace is changing now, include an instruction to change it
  19528. // during element creation.
  19529. if (currentNamespace !== wasInNamespace) {
  19530. this.addNamespaceInstruction(currentNamespace, element);
  19531. }
  19532. if (this.i18n) {
  19533. this.i18n.appendElement(element.i18n, elementIndex);
  19534. }
  19535. // Note that we do not append text node instructions and ICUs inside i18n section,
  19536. // so we exclude them while calculating whether current element has children
  19537. var hasChildren = (!isI18nRootElement && this.i18n) ? !hasTextChildrenOnly(element.children) :
  19538. element.children.length > 0;
  19539. var createSelfClosingInstruction = !stylingBuilder.hasBindingsWithPipes &&
  19540. element.outputs.length === 0 && boundI18nAttrs.length === 0 && !hasChildren;
  19541. var createSelfClosingI18nInstruction = !createSelfClosingInstruction && hasTextChildrenOnly(element.children);
  19542. if (createSelfClosingInstruction) {
  19543. this.creationInstruction(element.sourceSpan, isNgContainer$1 ? Identifiers.elementContainer : Identifiers.element, trimTrailingNulls(parameters));
  19544. }
  19545. else {
  19546. this.creationInstruction(element.startSourceSpan, isNgContainer$1 ? Identifiers.elementContainerStart : Identifiers.elementStart, trimTrailingNulls(parameters));
  19547. if (isNonBindableMode) {
  19548. this.creationInstruction(element.startSourceSpan, Identifiers.disableBindings);
  19549. }
  19550. if (boundI18nAttrs.length > 0) {
  19551. this.i18nAttributesInstruction(elementIndex, boundI18nAttrs, (_a = element.startSourceSpan) !== null && _a !== void 0 ? _a : element.sourceSpan);
  19552. }
  19553. // Generate Listeners (outputs)
  19554. if (element.outputs.length > 0) {
  19555. var listeners = element.outputs.map(function (outputAst) { return ({
  19556. sourceSpan: outputAst.sourceSpan,
  19557. params: _this.prepareListenerParameter(element.name, outputAst, elementIndex)
  19558. }); });
  19559. this.creationInstructionChain(Identifiers.listener, listeners);
  19560. }
  19561. // Note: it's important to keep i18n/i18nStart instructions after i18nAttributes and
  19562. // listeners, to make sure i18nAttributes instruction targets current element at runtime.
  19563. if (isI18nRootElement) {
  19564. this.i18nStart(element.startSourceSpan, element.i18n, createSelfClosingI18nInstruction);
  19565. }
  19566. }
  19567. // the code here will collect all update-level styling instructions and add them to the
  19568. // update block of the template function AOT code. Instructions like `styleProp`,
  19569. // `styleMap`, `classMap`, `classProp`
  19570. // are all generated and assigned in the code below.
  19571. var stylingInstructions = stylingBuilder.buildUpdateLevelInstructions(this._valueConverter);
  19572. var limit = stylingInstructions.length - 1;
  19573. for (var i = 0; i <= limit; i++) {
  19574. var instruction_1 = stylingInstructions[i];
  19575. this._bindingSlots += this.processStylingUpdateInstruction(elementIndex, instruction_1);
  19576. }
  19577. // the reason why `undefined` is used is because the renderer understands this as a
  19578. // special value to symbolize that there is no RHS to this binding
  19579. // TODO (matsko): revisit this once FW-959 is approached
  19580. var emptyValueBindInstruction = literal(undefined);
  19581. var propertyBindings = [];
  19582. var attributeBindings = [];
  19583. // Generate element input bindings
  19584. allOtherInputs.forEach(function (input) {
  19585. var inputType = input.type;
  19586. if (inputType === 4 /* Animation */) {
  19587. var value_1 = input.value.visit(_this._valueConverter);
  19588. // animation bindings can be presented in the following formats:
  19589. // 1. [@binding]="fooExp"
  19590. // 2. [@binding]="{value:fooExp, params:{...}}"
  19591. // 3. [@binding]
  19592. // 4. @binding
  19593. // All formats will be valid for when a synthetic binding is created.
  19594. // The reasoning for this is because the renderer should get each
  19595. // synthetic binding value in the order of the array that they are
  19596. // defined in...
  19597. var hasValue_1 = value_1 instanceof LiteralPrimitive ? !!value_1.value : true;
  19598. _this.allocateBindingSlots(value_1);
  19599. propertyBindings.push({
  19600. name: prepareSyntheticPropertyName(input.name),
  19601. sourceSpan: input.sourceSpan,
  19602. value: function () { return hasValue_1 ? _this.convertPropertyBinding(value_1) : emptyValueBindInstruction; }
  19603. });
  19604. }
  19605. else {
  19606. // we must skip attributes with associated i18n context, since these attributes are handled
  19607. // separately and corresponding `i18nExp` and `i18nApply` instructions will be generated
  19608. if (input.i18n)
  19609. return;
  19610. var value_2 = input.value.visit(_this._valueConverter);
  19611. if (value_2 !== undefined) {
  19612. var params_2 = [];
  19613. var _c = __read(splitNsName(input.name), 2), attrNamespace = _c[0], attrName_1 = _c[1];
  19614. var isAttributeBinding = inputType === 1 /* Attribute */;
  19615. var sanitizationRef = resolveSanitizationFn(input.securityContext, isAttributeBinding);
  19616. if (sanitizationRef)
  19617. params_2.push(sanitizationRef);
  19618. if (attrNamespace) {
  19619. var namespaceLiteral = literal(attrNamespace);
  19620. if (sanitizationRef) {
  19621. params_2.push(namespaceLiteral);
  19622. }
  19623. else {
  19624. // If there wasn't a sanitization ref, we need to add
  19625. // an extra param so that we can pass in the namespace.
  19626. params_2.push(literal(null), namespaceLiteral);
  19627. }
  19628. }
  19629. _this.allocateBindingSlots(value_2);
  19630. if (inputType === 0 /* Property */) {
  19631. if (value_2 instanceof Interpolation) {
  19632. // prop="{{value}}" and friends
  19633. _this.interpolatedUpdateInstruction(getPropertyInterpolationExpression(value_2), elementIndex, attrName_1, input, value_2, params_2);
  19634. }
  19635. else {
  19636. // [prop]="value"
  19637. // Collect all the properties so that we can chain into a single function at the end.
  19638. propertyBindings.push({
  19639. name: attrName_1,
  19640. sourceSpan: input.sourceSpan,
  19641. value: function () { return _this.convertPropertyBinding(value_2); },
  19642. params: params_2
  19643. });
  19644. }
  19645. }
  19646. else if (inputType === 1 /* Attribute */) {
  19647. if (value_2 instanceof Interpolation && getInterpolationArgsLength(value_2) > 1) {
  19648. // attr.name="text{{value}}" and friends
  19649. _this.interpolatedUpdateInstruction(getAttributeInterpolationExpression(value_2), elementIndex, attrName_1, input, value_2, params_2);
  19650. }
  19651. else {
  19652. var boundValue_1 = value_2 instanceof Interpolation ? value_2.expressions[0] : value_2;
  19653. // [attr.name]="value" or attr.name="{{value}}"
  19654. // Collect the attribute bindings so that they can be chained at the end.
  19655. attributeBindings.push({
  19656. name: attrName_1,
  19657. sourceSpan: input.sourceSpan,
  19658. value: function () { return _this.convertPropertyBinding(boundValue_1); },
  19659. params: params_2
  19660. });
  19661. }
  19662. }
  19663. else {
  19664. // class prop
  19665. _this.updateInstructionWithAdvance(elementIndex, input.sourceSpan, Identifiers.classProp, function () {
  19666. return __spreadArray([
  19667. literal(elementIndex), literal(attrName_1), _this.convertPropertyBinding(value_2)
  19668. ], __read(params_2));
  19669. });
  19670. }
  19671. }
  19672. }
  19673. });
  19674. if (propertyBindings.length > 0) {
  19675. this.updateInstructionChainWithAdvance(elementIndex, Identifiers.property, propertyBindings);
  19676. }
  19677. if (attributeBindings.length > 0) {
  19678. this.updateInstructionChainWithAdvance(elementIndex, Identifiers.attribute, attributeBindings);
  19679. }
  19680. // Traverse element child nodes
  19681. visitAll(this, element.children);
  19682. if (!isI18nRootElement && this.i18n) {
  19683. this.i18n.appendElement(element.i18n, elementIndex, true);
  19684. }
  19685. if (!createSelfClosingInstruction) {
  19686. // Finish element construction mode.
  19687. var span = (_b = element.endSourceSpan) !== null && _b !== void 0 ? _b : element.sourceSpan;
  19688. if (isI18nRootElement) {
  19689. this.i18nEnd(span, createSelfClosingI18nInstruction);
  19690. }
  19691. if (isNonBindableMode) {
  19692. this.creationInstruction(span, Identifiers.enableBindings);
  19693. }
  19694. this.creationInstruction(span, isNgContainer$1 ? Identifiers.elementContainerEnd : Identifiers.elementEnd);
  19695. }
  19696. };
  19697. TemplateDefinitionBuilder.prototype.visitTemplate = function (template) {
  19698. var _this = this;
  19699. var _a;
  19700. var NG_TEMPLATE_TAG_NAME = 'ng-template';
  19701. var templateIndex = this.allocateDataSlot();
  19702. if (this.i18n) {
  19703. this.i18n.appendTemplate(template.i18n, templateIndex);
  19704. }
  19705. var tagNameWithoutNamespace = template.tagName ? splitNsName(template.tagName)[1] : template.tagName;
  19706. var contextName = "" + this.contextName + (template.tagName ? '_' + sanitizeIdentifier(template.tagName) : '') + "_" + templateIndex;
  19707. var templateName = contextName + "_Template";
  19708. var parameters = [
  19709. literal(templateIndex),
  19710. variable(templateName),
  19711. // We don't care about the tag's namespace here, because we infer
  19712. // it based on the parent nodes inside the template instruction.
  19713. literal(tagNameWithoutNamespace),
  19714. ];
  19715. // find directives matching on a given <ng-template> node
  19716. this.matchDirectives(NG_TEMPLATE_TAG_NAME, template);
  19717. // prepare attributes parameter (including attributes used for directive matching)
  19718. var attrsExprs = this.getAttributeExpressions(NG_TEMPLATE_TAG_NAME, template.attributes, template.inputs, template.outputs, undefined /* styles */, template.templateAttrs);
  19719. parameters.push(this.addAttrsToConsts(attrsExprs));
  19720. // local refs (ex.: <ng-template #foo>)
  19721. if (template.references && template.references.length) {
  19722. var refs = this.prepareRefsArray(template.references);
  19723. parameters.push(this.addToConsts(refs));
  19724. parameters.push(importExpr(Identifiers.templateRefExtractor));
  19725. }
  19726. // Create the template function
  19727. var templateVisitor = new TemplateDefinitionBuilder(this.constantPool, this._bindingScope, this.level + 1, contextName, this.i18n, templateIndex, templateName, this.directiveMatcher, this.directives, this.pipeTypeByName, this.pipes, this._namespace, this.fileBasedI18nSuffix, this.i18nUseExternalIds, this._constants);
  19728. // Nested templates must not be visited until after their parent templates have completed
  19729. // processing, so they are queued here until after the initial pass. Otherwise, we wouldn't
  19730. // be able to support bindings in nested templates to local refs that occur after the
  19731. // template definition. e.g. <div *ngIf="showing">{{ foo }}</div> <div #foo></div>
  19732. this._nestedTemplateFns.push(function () {
  19733. var _c;
  19734. var templateFunctionExpr = templateVisitor.buildTemplateFunction(template.children, template.variables, _this._ngContentReservedSlots.length + _this._ngContentSelectorsOffset, template.i18n);
  19735. _this.constantPool.statements.push(templateFunctionExpr.toDeclStmt(templateName));
  19736. if (templateVisitor._ngContentReservedSlots.length) {
  19737. (_c = _this._ngContentReservedSlots).push.apply(_c, __spreadArray([], __read(templateVisitor._ngContentReservedSlots)));
  19738. }
  19739. });
  19740. // e.g. template(1, MyComp_Template_1)
  19741. this.creationInstruction(template.sourceSpan, Identifiers.templateCreate, function () {
  19742. parameters.splice(2, 0, literal(templateVisitor.getConstCount()), literal(templateVisitor.getVarCount()));
  19743. return trimTrailingNulls(parameters);
  19744. });
  19745. // handle property bindings e.g. ɵɵproperty('ngForOf', ctx.items), et al;
  19746. this.templatePropertyBindings(templateIndex, template.templateAttrs);
  19747. // Only add normal input/output binding instructions on explicit <ng-template> elements.
  19748. if (tagNameWithoutNamespace === NG_TEMPLATE_TAG_NAME) {
  19749. var _c = __read(partitionArray(template.inputs, hasI18nMeta), 2), i18nInputs = _c[0], inputs = _c[1];
  19750. // Add i18n attributes that may act as inputs to directives. If such attributes are present,
  19751. // generate `i18nAttributes` instruction. Note: we generate it only for explicit <ng-template>
  19752. // elements, in case of inline templates, corresponding instructions will be generated in the
  19753. // nested template function.
  19754. if (i18nInputs.length > 0) {
  19755. this.i18nAttributesInstruction(templateIndex, i18nInputs, (_a = template.startSourceSpan) !== null && _a !== void 0 ? _a : template.sourceSpan);
  19756. }
  19757. // Add the input bindings
  19758. if (inputs.length > 0) {
  19759. this.templatePropertyBindings(templateIndex, inputs);
  19760. }
  19761. // Generate listeners for directive output
  19762. if (template.outputs.length > 0) {
  19763. var listeners = template.outputs.map(function (outputAst) { return ({
  19764. sourceSpan: outputAst.sourceSpan,
  19765. params: _this.prepareListenerParameter('ng_template', outputAst, templateIndex)
  19766. }); });
  19767. this.creationInstructionChain(Identifiers.listener, listeners);
  19768. }
  19769. }
  19770. };
  19771. TemplateDefinitionBuilder.prototype.visitBoundText = function (text) {
  19772. var _this = this;
  19773. if (this.i18n) {
  19774. var value_3 = text.value.visit(this._valueConverter);
  19775. this.allocateBindingSlots(value_3);
  19776. if (value_3 instanceof Interpolation) {
  19777. this.i18n.appendBoundText(text.i18n);
  19778. this.i18nAppendBindings(value_3.expressions);
  19779. }
  19780. return;
  19781. }
  19782. var nodeIndex = this.allocateDataSlot();
  19783. this.creationInstruction(text.sourceSpan, Identifiers.text, [literal(nodeIndex)]);
  19784. var value = text.value.visit(this._valueConverter);
  19785. this.allocateBindingSlots(value);
  19786. if (value instanceof Interpolation) {
  19787. this.updateInstructionWithAdvance(nodeIndex, text.sourceSpan, getTextInterpolationExpression(value), function () { return _this.getUpdateInstructionArguments(value); });
  19788. }
  19789. else {
  19790. error('Text nodes should be interpolated and never bound directly.');
  19791. }
  19792. };
  19793. TemplateDefinitionBuilder.prototype.visitText = function (text) {
  19794. // when a text element is located within a translatable
  19795. // block, we exclude this text element from instructions set,
  19796. // since it will be captured in i18n content and processed at runtime
  19797. if (!this.i18n) {
  19798. this.creationInstruction(text.sourceSpan, Identifiers.text, [literal(this.allocateDataSlot()), literal(text.value)]);
  19799. }
  19800. };
  19801. TemplateDefinitionBuilder.prototype.visitIcu = function (icu) {
  19802. var initWasInvoked = false;
  19803. // if an ICU was created outside of i18n block, we still treat
  19804. // it as a translatable entity and invoke i18nStart and i18nEnd
  19805. // to generate i18n context and the necessary instructions
  19806. if (!this.i18n) {
  19807. initWasInvoked = true;
  19808. this.i18nStart(null, icu.i18n, true);
  19809. }
  19810. var i18n = this.i18n;
  19811. var vars = this.i18nBindProps(icu.vars);
  19812. var placeholders = this.i18nBindProps(icu.placeholders);
  19813. // output ICU directly and keep ICU reference in context
  19814. var message = icu.i18n;
  19815. // we always need post-processing function for ICUs, to make sure that:
  19816. // - all placeholders in a form of {PLACEHOLDER} are replaced with actual values (note:
  19817. // `goog.getMsg` does not process ICUs and uses the `{PLACEHOLDER}` format for placeholders
  19818. // inside ICUs)
  19819. // - all ICU vars (such as `VAR_SELECT` or `VAR_PLURAL`) are replaced with correct values
  19820. var transformFn = function (raw) {
  19821. var params = Object.assign(Object.assign({}, vars), placeholders);
  19822. var formatted = i18nFormatPlaceholderNames(params, /* useCamelCase */ false);
  19823. return instruction(null, Identifiers.i18nPostprocess, [raw, mapLiteral(formatted, true)]);
  19824. };
  19825. // in case the whole i18n message is a single ICU - we do not need to
  19826. // create a separate top-level translation, we can use the root ref instead
  19827. // and make this ICU a top-level translation
  19828. // note: ICU placeholders are replaced with actual values in `i18nPostprocess` function
  19829. // separately, so we do not pass placeholders into `i18nTranslate` function.
  19830. if (isSingleI18nIcu(i18n.meta)) {
  19831. this.i18nTranslate(message, /* placeholders */ {}, i18n.ref, transformFn);
  19832. }
  19833. else {
  19834. // output ICU directly and keep ICU reference in context
  19835. var ref = this.i18nTranslate(message, /* placeholders */ {}, /* ref */ undefined, transformFn);
  19836. i18n.appendIcu(icuFromI18nMessage(message).name, ref);
  19837. }
  19838. if (initWasInvoked) {
  19839. this.i18nEnd(null, true);
  19840. }
  19841. return null;
  19842. };
  19843. TemplateDefinitionBuilder.prototype.allocateDataSlot = function () {
  19844. return this._dataIndex++;
  19845. };
  19846. TemplateDefinitionBuilder.prototype.getConstCount = function () {
  19847. return this._dataIndex;
  19848. };
  19849. TemplateDefinitionBuilder.prototype.getVarCount = function () {
  19850. return this._pureFunctionSlots;
  19851. };
  19852. TemplateDefinitionBuilder.prototype.getConsts = function () {
  19853. return this._constants;
  19854. };
  19855. TemplateDefinitionBuilder.prototype.getNgContentSelectors = function () {
  19856. return this._ngContentReservedSlots.length ?
  19857. this.constantPool.getConstLiteral(asLiteral(this._ngContentReservedSlots), true) :
  19858. null;
  19859. };
  19860. TemplateDefinitionBuilder.prototype.bindingContext = function () {
  19861. return "" + this._bindingContext++;
  19862. };
  19863. TemplateDefinitionBuilder.prototype.templatePropertyBindings = function (templateIndex, attrs) {
  19864. var _this = this;
  19865. var propertyBindings = [];
  19866. attrs.forEach(function (input) {
  19867. if (input instanceof BoundAttribute) {
  19868. var value_4 = input.value.visit(_this._valueConverter);
  19869. if (value_4 !== undefined) {
  19870. _this.allocateBindingSlots(value_4);
  19871. if (value_4 instanceof Interpolation) {
  19872. // Params typically contain attribute namespace and value sanitizer, which is applicable
  19873. // for regular HTML elements, but not applicable for <ng-template> (since props act as
  19874. // inputs to directives), so keep params array empty.
  19875. var params = [];
  19876. // prop="{{value}}" case
  19877. _this.interpolatedUpdateInstruction(getPropertyInterpolationExpression(value_4), templateIndex, input.name, input, value_4, params);
  19878. }
  19879. else {
  19880. // [prop]="value" case
  19881. propertyBindings.push({
  19882. name: input.name,
  19883. sourceSpan: input.sourceSpan,
  19884. value: function () { return _this.convertPropertyBinding(value_4); }
  19885. });
  19886. }
  19887. }
  19888. }
  19889. });
  19890. if (propertyBindings.length > 0) {
  19891. this.updateInstructionChainWithAdvance(templateIndex, Identifiers.property, propertyBindings);
  19892. }
  19893. };
  19894. // Bindings must only be resolved after all local refs have been visited, so all
  19895. // instructions are queued in callbacks that execute once the initial pass has completed.
  19896. // Otherwise, we wouldn't be able to support local refs that are defined after their
  19897. // bindings. e.g. {{ foo }} <div #foo></div>
  19898. TemplateDefinitionBuilder.prototype.instructionFn = function (fns, span, reference, paramsOrFn, prepend) {
  19899. if (prepend === void 0) { prepend = false; }
  19900. fns[prepend ? 'unshift' : 'push'](function () {
  19901. var params = Array.isArray(paramsOrFn) ? paramsOrFn : paramsOrFn();
  19902. return instruction(span, reference, params).toStmt();
  19903. });
  19904. };
  19905. TemplateDefinitionBuilder.prototype.processStylingUpdateInstruction = function (elementIndex, instruction) {
  19906. var _this = this;
  19907. var allocateBindingSlots = 0;
  19908. if (instruction) {
  19909. var calls_1 = [];
  19910. instruction.calls.forEach(function (call) {
  19911. allocateBindingSlots += call.allocateBindingSlots;
  19912. calls_1.push({
  19913. sourceSpan: call.sourceSpan,
  19914. value: function () {
  19915. return call.params(function (value) { return (call.supportsInterpolation && value instanceof Interpolation) ?
  19916. _this.getUpdateInstructionArguments(value) :
  19917. _this.convertPropertyBinding(value); });
  19918. }
  19919. });
  19920. });
  19921. this.updateInstructionChainWithAdvance(elementIndex, instruction.reference, calls_1);
  19922. }
  19923. return allocateBindingSlots;
  19924. };
  19925. TemplateDefinitionBuilder.prototype.creationInstruction = function (span, reference, paramsOrFn, prepend) {
  19926. this.instructionFn(this._creationCodeFns, span, reference, paramsOrFn || [], prepend);
  19927. };
  19928. TemplateDefinitionBuilder.prototype.creationInstructionChain = function (reference, calls) {
  19929. var span = calls.length ? calls[0].sourceSpan : null;
  19930. this._creationCodeFns.push(function () {
  19931. return chainedInstruction(reference, calls.map(function (call) { return call.params(); }), span).toStmt();
  19932. });
  19933. };
  19934. TemplateDefinitionBuilder.prototype.updateInstructionWithAdvance = function (nodeIndex, span, reference, paramsOrFn) {
  19935. this.addAdvanceInstructionIfNecessary(nodeIndex, span);
  19936. this.updateInstruction(span, reference, paramsOrFn);
  19937. };
  19938. TemplateDefinitionBuilder.prototype.updateInstruction = function (span, reference, paramsOrFn) {
  19939. this.instructionFn(this._updateCodeFns, span, reference, paramsOrFn || []);
  19940. };
  19941. TemplateDefinitionBuilder.prototype.updateInstructionChain = function (reference, bindings) {
  19942. var span = bindings.length ? bindings[0].sourceSpan : null;
  19943. this._updateCodeFns.push(function () {
  19944. var calls = bindings.map(function (property) {
  19945. var value = property.value();
  19946. var fnParams = Array.isArray(value) ? value : [value];
  19947. if (property.params) {
  19948. fnParams.push.apply(fnParams, __spreadArray([], __read(property.params)));
  19949. }
  19950. if (property.name) {
  19951. // We want the property name to always be the first function parameter.
  19952. fnParams.unshift(literal(property.name));
  19953. }
  19954. return fnParams;
  19955. });
  19956. return chainedInstruction(reference, calls, span).toStmt();
  19957. });
  19958. };
  19959. TemplateDefinitionBuilder.prototype.updateInstructionChainWithAdvance = function (nodeIndex, reference, bindings) {
  19960. this.addAdvanceInstructionIfNecessary(nodeIndex, bindings.length ? bindings[0].sourceSpan : null);
  19961. this.updateInstructionChain(reference, bindings);
  19962. };
  19963. TemplateDefinitionBuilder.prototype.addAdvanceInstructionIfNecessary = function (nodeIndex, span) {
  19964. if (nodeIndex !== this._currentIndex) {
  19965. var delta = nodeIndex - this._currentIndex;
  19966. if (delta < 1) {
  19967. throw new Error('advance instruction can only go forwards');
  19968. }
  19969. this.instructionFn(this._updateCodeFns, span, Identifiers.advance, [literal(delta)]);
  19970. this._currentIndex = nodeIndex;
  19971. }
  19972. };
  19973. TemplateDefinitionBuilder.prototype.allocatePureFunctionSlots = function (numSlots) {
  19974. var originalSlots = this._pureFunctionSlots;
  19975. this._pureFunctionSlots += numSlots;
  19976. return originalSlots;
  19977. };
  19978. TemplateDefinitionBuilder.prototype.allocateBindingSlots = function (value) {
  19979. this._bindingSlots += value instanceof Interpolation ? value.expressions.length : 1;
  19980. };
  19981. /**
  19982. * Gets an expression that refers to the implicit receiver. The implicit
  19983. * receiver is always the root level context.
  19984. */
  19985. TemplateDefinitionBuilder.prototype.getImplicitReceiverExpr = function () {
  19986. if (this._implicitReceiverExpr) {
  19987. return this._implicitReceiverExpr;
  19988. }
  19989. return this._implicitReceiverExpr = this.level === 0 ?
  19990. variable(CONTEXT_NAME) :
  19991. this._bindingScope.getOrCreateSharedContextVar(0);
  19992. };
  19993. TemplateDefinitionBuilder.prototype.convertPropertyBinding = function (value) {
  19994. var _c;
  19995. var convertedPropertyBinding = convertPropertyBinding(this, this.getImplicitReceiverExpr(), value, this.bindingContext(), BindingForm.Expression, function () { return error('Unexpected interpolation'); });
  19996. var valExpr = convertedPropertyBinding.currValExpr;
  19997. (_c = this._tempVariables).push.apply(_c, __spreadArray([], __read(convertedPropertyBinding.stmts)));
  19998. return valExpr;
  19999. };
  20000. /**
  20001. * Gets a list of argument expressions to pass to an update instruction expression. Also updates
  20002. * the temp variables state with temp variables that were identified as needing to be created
  20003. * while visiting the arguments.
  20004. * @param value The original expression we will be resolving an arguments list from.
  20005. */
  20006. TemplateDefinitionBuilder.prototype.getUpdateInstructionArguments = function (value) {
  20007. var _c;
  20008. var _d = convertUpdateArguments(this, this.getImplicitReceiverExpr(), value, this.bindingContext()), args = _d.args, stmts = _d.stmts;
  20009. (_c = this._tempVariables).push.apply(_c, __spreadArray([], __read(stmts)));
  20010. return args;
  20011. };
  20012. TemplateDefinitionBuilder.prototype.matchDirectives = function (elementName, elOrTpl) {
  20013. var _this = this;
  20014. if (this.directiveMatcher) {
  20015. var selector = createCssSelector(elementName, getAttrsForDirectiveMatching(elOrTpl));
  20016. this.directiveMatcher.match(selector, function (cssSelector, staticType) {
  20017. _this.directives.add(staticType);
  20018. });
  20019. }
  20020. };
  20021. /**
  20022. * Prepares all attribute expression values for the `TAttributes` array.
  20023. *
  20024. * The purpose of this function is to properly construct an attributes array that
  20025. * is passed into the `elementStart` (or just `element`) functions. Because there
  20026. * are many different types of attributes, the array needs to be constructed in a
  20027. * special way so that `elementStart` can properly evaluate them.
  20028. *
  20029. * The format looks like this:
  20030. *
  20031. * ```
  20032. * attrs = [prop, value, prop2, value2,
  20033. * PROJECT_AS, selector,
  20034. * CLASSES, class1, class2,
  20035. * STYLES, style1, value1, style2, value2,
  20036. * BINDINGS, name1, name2, name3,
  20037. * TEMPLATE, name4, name5, name6,
  20038. * I18N, name7, name8, ...]
  20039. * ```
  20040. *
  20041. * Note that this function will fully ignore all synthetic (@foo) attribute values
  20042. * because those values are intended to always be generated as property instructions.
  20043. */
  20044. TemplateDefinitionBuilder.prototype.getAttributeExpressions = function (elementName, renderAttributes, inputs, outputs, styles, templateAttrs, boundI18nAttrs) {
  20045. var e_2, _c;
  20046. if (templateAttrs === void 0) { templateAttrs = []; }
  20047. if (boundI18nAttrs === void 0) { boundI18nAttrs = []; }
  20048. var alreadySeen = new Set();
  20049. var attrExprs = [];
  20050. var ngProjectAsAttr;
  20051. try {
  20052. for (var renderAttributes_1 = __values(renderAttributes), renderAttributes_1_1 = renderAttributes_1.next(); !renderAttributes_1_1.done; renderAttributes_1_1 = renderAttributes_1.next()) {
  20053. var attr = renderAttributes_1_1.value;
  20054. if (attr.name === NG_PROJECT_AS_ATTR_NAME) {
  20055. ngProjectAsAttr = attr;
  20056. }
  20057. // Note that static i18n attributes aren't in the i18n array,
  20058. // because they're treated in the same way as regular attributes.
  20059. if (attr.i18n) {
  20060. // When i18n attributes are present on elements with structural directives
  20061. // (e.g. `<div *ngIf title="Hello" i18n-title>`), we want to avoid generating
  20062. // duplicate i18n translation blocks for `ɵɵtemplate` and `ɵɵelement` instruction
  20063. // attributes. So we do a cache lookup to see if suitable i18n translation block
  20064. // already exists.
  20065. var i18nVarRefsCache = this._constants.i18nVarRefsCache;
  20066. var i18nVarRef = void 0;
  20067. if (i18nVarRefsCache.has(attr.i18n)) {
  20068. i18nVarRef = i18nVarRefsCache.get(attr.i18n);
  20069. }
  20070. else {
  20071. i18nVarRef = this.i18nTranslate(attr.i18n);
  20072. i18nVarRefsCache.set(attr.i18n, i18nVarRef);
  20073. }
  20074. attrExprs.push(literal(attr.name), i18nVarRef);
  20075. }
  20076. else {
  20077. attrExprs.push.apply(attrExprs, __spreadArray(__spreadArray([], __read(getAttributeNameLiterals(attr.name))), [trustedConstAttribute(elementName, attr)]));
  20078. }
  20079. }
  20080. }
  20081. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  20082. finally {
  20083. try {
  20084. if (renderAttributes_1_1 && !renderAttributes_1_1.done && (_c = renderAttributes_1.return)) _c.call(renderAttributes_1);
  20085. }
  20086. finally { if (e_2) throw e_2.error; }
  20087. }
  20088. // Keep ngProjectAs next to the other name, value pairs so we can verify that we match
  20089. // ngProjectAs marker in the attribute name slot.
  20090. if (ngProjectAsAttr) {
  20091. attrExprs.push.apply(attrExprs, __spreadArray([], __read(getNgProjectAsLiteral(ngProjectAsAttr))));
  20092. }
  20093. function addAttrExpr(key, value) {
  20094. if (typeof key === 'string') {
  20095. if (!alreadySeen.has(key)) {
  20096. attrExprs.push.apply(attrExprs, __spreadArray([], __read(getAttributeNameLiterals(key))));
  20097. value !== undefined && attrExprs.push(value);
  20098. alreadySeen.add(key);
  20099. }
  20100. }
  20101. else {
  20102. attrExprs.push(literal(key));
  20103. }
  20104. }
  20105. // it's important that this occurs before BINDINGS and TEMPLATE because once `elementStart`
  20106. // comes across the BINDINGS or TEMPLATE markers then it will continue reading each value as
  20107. // as single property value cell by cell.
  20108. if (styles) {
  20109. styles.populateInitialStylingAttrs(attrExprs);
  20110. }
  20111. if (inputs.length || outputs.length) {
  20112. var attrsLengthBeforeInputs = attrExprs.length;
  20113. for (var i = 0; i < inputs.length; i++) {
  20114. var input = inputs[i];
  20115. // We don't want the animation and attribute bindings in the
  20116. // attributes array since they aren't used for directive matching.
  20117. if (input.type !== 4 /* Animation */ && input.type !== 1 /* Attribute */) {
  20118. addAttrExpr(input.name);
  20119. }
  20120. }
  20121. for (var i = 0; i < outputs.length; i++) {
  20122. var output = outputs[i];
  20123. if (output.type !== 1 /* Animation */) {
  20124. addAttrExpr(output.name);
  20125. }
  20126. }
  20127. // this is a cheap way of adding the marker only after all the input/output
  20128. // values have been filtered (by not including the animation ones) and added
  20129. // to the expressions. The marker is important because it tells the runtime
  20130. // code that this is where attributes without values start...
  20131. if (attrExprs.length !== attrsLengthBeforeInputs) {
  20132. attrExprs.splice(attrsLengthBeforeInputs, 0, literal(3 /* Bindings */));
  20133. }
  20134. }
  20135. if (templateAttrs.length) {
  20136. attrExprs.push(literal(4 /* Template */));
  20137. templateAttrs.forEach(function (attr) { return addAttrExpr(attr.name); });
  20138. }
  20139. if (boundI18nAttrs.length) {
  20140. attrExprs.push(literal(6 /* I18n */));
  20141. boundI18nAttrs.forEach(function (attr) { return addAttrExpr(attr.name); });
  20142. }
  20143. return attrExprs;
  20144. };
  20145. TemplateDefinitionBuilder.prototype.addToConsts = function (expression) {
  20146. if (isNull(expression)) {
  20147. return TYPED_NULL_EXPR;
  20148. }
  20149. var consts = this._constants.constExpressions;
  20150. // Try to reuse a literal that's already in the array, if possible.
  20151. for (var i = 0; i < consts.length; i++) {
  20152. if (consts[i].isEquivalent(expression)) {
  20153. return literal(i);
  20154. }
  20155. }
  20156. return literal(consts.push(expression) - 1);
  20157. };
  20158. TemplateDefinitionBuilder.prototype.addAttrsToConsts = function (attrs) {
  20159. return attrs.length > 0 ? this.addToConsts(literalArr(attrs)) : TYPED_NULL_EXPR;
  20160. };
  20161. TemplateDefinitionBuilder.prototype.prepareRefsArray = function (references) {
  20162. var _this = this;
  20163. if (!references || references.length === 0) {
  20164. return TYPED_NULL_EXPR;
  20165. }
  20166. var refsParam = flatten(references.map(function (reference) {
  20167. var slot = _this.allocateDataSlot();
  20168. // Generate the update temporary.
  20169. var variableName = _this._bindingScope.freshReferenceName();
  20170. var retrievalLevel = _this.level;
  20171. var lhs = variable(variableName);
  20172. _this._bindingScope.set(retrievalLevel, reference.name, lhs, 0 /* DEFAULT */, function (scope, relativeLevel) {
  20173. // e.g. nextContext(2);
  20174. var nextContextStmt = relativeLevel > 0 ? [generateNextContextExpr(relativeLevel).toStmt()] : [];
  20175. // e.g. const $foo$ = reference(1);
  20176. var refExpr = lhs.set(importExpr(Identifiers.reference).callFn([literal(slot)]));
  20177. return nextContextStmt.concat(refExpr.toConstDecl());
  20178. }, true);
  20179. return [reference.name, reference.value];
  20180. }));
  20181. return asLiteral(refsParam);
  20182. };
  20183. TemplateDefinitionBuilder.prototype.prepareListenerParameter = function (tagName, outputAst, index) {
  20184. var _this = this;
  20185. return function () {
  20186. var eventName = outputAst.name;
  20187. var bindingFnName = outputAst.type === 1 /* Animation */ ?
  20188. // synthetic @listener.foo values are treated the exact same as are standard listeners
  20189. prepareSyntheticListenerFunctionName(eventName, outputAst.phase) :
  20190. sanitizeIdentifier(eventName);
  20191. var handlerName = _this.templateName + "_" + tagName + "_" + bindingFnName + "_" + index + "_listener";
  20192. var scope = _this._bindingScope.nestedScope(_this._bindingScope.bindingLevel, EVENT_BINDING_SCOPE_GLOBALS);
  20193. return prepareEventListenerParameters(outputAst, handlerName, scope);
  20194. };
  20195. };
  20196. return TemplateDefinitionBuilder;
  20197. }());
  20198. var ValueConverter = /** @class */ (function (_super) {
  20199. __extends(ValueConverter, _super);
  20200. function ValueConverter(constantPool, allocateSlot, allocatePureFunctionSlots, definePipe) {
  20201. var _this = _super.call(this) || this;
  20202. _this.constantPool = constantPool;
  20203. _this.allocateSlot = allocateSlot;
  20204. _this.allocatePureFunctionSlots = allocatePureFunctionSlots;
  20205. _this.definePipe = definePipe;
  20206. _this._pipeBindExprs = [];
  20207. return _this;
  20208. }
  20209. // AstMemoryEfficientTransformer
  20210. ValueConverter.prototype.visitPipe = function (pipe, context) {
  20211. // Allocate a slot to create the pipe
  20212. var slot = this.allocateSlot();
  20213. var slotPseudoLocal = "PIPE:" + slot;
  20214. // Allocate one slot for the result plus one slot per pipe argument
  20215. var pureFunctionSlot = this.allocatePureFunctionSlots(2 + pipe.args.length);
  20216. var target = new PropertyRead(pipe.span, pipe.sourceSpan, pipe.nameSpan, new ImplicitReceiver(pipe.span, pipe.sourceSpan), slotPseudoLocal);
  20217. var _c = pipeBindingCallInfo(pipe.args), identifier = _c.identifier, isVarLength = _c.isVarLength;
  20218. this.definePipe(pipe.name, slotPseudoLocal, slot, importExpr(identifier));
  20219. var args = __spreadArray([pipe.exp], __read(pipe.args));
  20220. var convertedArgs = isVarLength ?
  20221. this.visitAll([new LiteralArray(pipe.span, pipe.sourceSpan, args)]) :
  20222. this.visitAll(args);
  20223. var pipeBindExpr = new FunctionCall(pipe.span, pipe.sourceSpan, target, __spreadArray([
  20224. new LiteralPrimitive(pipe.span, pipe.sourceSpan, slot),
  20225. new LiteralPrimitive(pipe.span, pipe.sourceSpan, pureFunctionSlot)
  20226. ], __read(convertedArgs)));
  20227. this._pipeBindExprs.push(pipeBindExpr);
  20228. return pipeBindExpr;
  20229. };
  20230. ValueConverter.prototype.updatePipeSlotOffsets = function (bindingSlots) {
  20231. this._pipeBindExprs.forEach(function (pipe) {
  20232. // update the slot offset arg (index 1) to account for binding slots
  20233. var slotOffset = pipe.args[1];
  20234. slotOffset.value += bindingSlots;
  20235. });
  20236. };
  20237. ValueConverter.prototype.visitLiteralArray = function (array, context) {
  20238. var _this = this;
  20239. return new BuiltinFunctionCall(array.span, array.sourceSpan, this.visitAll(array.expressions), function (values) {
  20240. // If the literal has calculated (non-literal) elements transform it into
  20241. // calls to literal factories that compose the literal and will cache intermediate
  20242. // values.
  20243. var literal = literalArr(values);
  20244. return getLiteralFactory(_this.constantPool, literal, _this.allocatePureFunctionSlots);
  20245. });
  20246. };
  20247. ValueConverter.prototype.visitLiteralMap = function (map, context) {
  20248. var _this = this;
  20249. return new BuiltinFunctionCall(map.span, map.sourceSpan, this.visitAll(map.values), function (values) {
  20250. // If the literal has calculated (non-literal) elements transform it into
  20251. // calls to literal factories that compose the literal and will cache intermediate
  20252. // values.
  20253. var literal = literalMap(values.map(function (value, index) { return ({ key: map.keys[index].key, value: value, quoted: map.keys[index].quoted }); }));
  20254. return getLiteralFactory(_this.constantPool, literal, _this.allocatePureFunctionSlots);
  20255. });
  20256. };
  20257. return ValueConverter;
  20258. }(AstMemoryEfficientTransformer));
  20259. // Pipes always have at least one parameter, the value they operate on
  20260. var pipeBindingIdentifiers = [Identifiers.pipeBind1, Identifiers.pipeBind2, Identifiers.pipeBind3, Identifiers.pipeBind4];
  20261. function pipeBindingCallInfo(args) {
  20262. var identifier = pipeBindingIdentifiers[args.length];
  20263. return {
  20264. identifier: identifier || Identifiers.pipeBindV,
  20265. isVarLength: !identifier,
  20266. };
  20267. }
  20268. var pureFunctionIdentifiers = [
  20269. Identifiers.pureFunction0, Identifiers.pureFunction1, Identifiers.pureFunction2, Identifiers.pureFunction3, Identifiers.pureFunction4,
  20270. Identifiers.pureFunction5, Identifiers.pureFunction6, Identifiers.pureFunction7, Identifiers.pureFunction8
  20271. ];
  20272. function pureFunctionCallInfo(args) {
  20273. var identifier = pureFunctionIdentifiers[args.length];
  20274. return {
  20275. identifier: identifier || Identifiers.pureFunctionV,
  20276. isVarLength: !identifier,
  20277. };
  20278. }
  20279. function instruction(span, reference, params) {
  20280. return importExpr(reference, null, span).callFn(params, span);
  20281. }
  20282. // e.g. x(2);
  20283. function generateNextContextExpr(relativeLevelDiff) {
  20284. return importExpr(Identifiers.nextContext)
  20285. .callFn(relativeLevelDiff > 1 ? [literal(relativeLevelDiff)] : []);
  20286. }
  20287. function getLiteralFactory(constantPool, literal$1, allocateSlots) {
  20288. var _c = constantPool.getLiteralFactory(literal$1), literalFactory = _c.literalFactory, literalFactoryArguments = _c.literalFactoryArguments;
  20289. // Allocate 1 slot for the result plus 1 per argument
  20290. var startSlot = allocateSlots(1 + literalFactoryArguments.length);
  20291. var _d = pureFunctionCallInfo(literalFactoryArguments), identifier = _d.identifier, isVarLength = _d.isVarLength;
  20292. // Literal factories are pure functions that only need to be re-invoked when the parameters
  20293. // change.
  20294. var args = [literal(startSlot), literalFactory];
  20295. if (isVarLength) {
  20296. args.push(literalArr(literalFactoryArguments));
  20297. }
  20298. else {
  20299. args.push.apply(args, __spreadArray([], __read(literalFactoryArguments)));
  20300. }
  20301. return importExpr(identifier).callFn(args);
  20302. }
  20303. /**
  20304. * Gets an array of literals that can be added to an expression
  20305. * to represent the name and namespace of an attribute. E.g.
  20306. * `:xlink:href` turns into `[AttributeMarker.NamespaceURI, 'xlink', 'href']`.
  20307. *
  20308. * @param name Name of the attribute, including the namespace.
  20309. */
  20310. function getAttributeNameLiterals(name) {
  20311. var _c = __read(splitNsName(name), 2), attributeNamespace = _c[0], attributeName = _c[1];
  20312. var nameLiteral = literal(attributeName);
  20313. if (attributeNamespace) {
  20314. return [
  20315. literal(0 /* NamespaceURI */), literal(attributeNamespace), nameLiteral
  20316. ];
  20317. }
  20318. return [nameLiteral];
  20319. }
  20320. /** The prefix used to get a shared context in BindingScope's map. */
  20321. var SHARED_CONTEXT_KEY = '$$shared_ctx$$';
  20322. var BindingScope = /** @class */ (function () {
  20323. function BindingScope(bindingLevel, parent, globals) {
  20324. var e_3, _c;
  20325. if (bindingLevel === void 0) { bindingLevel = 0; }
  20326. if (parent === void 0) { parent = null; }
  20327. this.bindingLevel = bindingLevel;
  20328. this.parent = parent;
  20329. this.globals = globals;
  20330. /** Keeps a map from local variables to their BindingData. */
  20331. this.map = new Map();
  20332. this.referenceNameIndex = 0;
  20333. this.restoreViewVariable = null;
  20334. this.usesRestoredViewContext = false;
  20335. if (globals !== undefined) {
  20336. try {
  20337. for (var globals_1 = __values(globals), globals_1_1 = globals_1.next(); !globals_1_1.done; globals_1_1 = globals_1.next()) {
  20338. var name = globals_1_1.value;
  20339. this.set(0, name, variable(name));
  20340. }
  20341. }
  20342. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  20343. finally {
  20344. try {
  20345. if (globals_1_1 && !globals_1_1.done && (_c = globals_1.return)) _c.call(globals_1);
  20346. }
  20347. finally { if (e_3) throw e_3.error; }
  20348. }
  20349. }
  20350. }
  20351. BindingScope.createRootScope = function () {
  20352. return new BindingScope();
  20353. };
  20354. BindingScope.prototype.get = function (name) {
  20355. var current = this;
  20356. while (current) {
  20357. var value = current.map.get(name);
  20358. if (value != null) {
  20359. if (current !== this) {
  20360. // make a local copy and reset the `declare` state
  20361. value = {
  20362. retrievalLevel: value.retrievalLevel,
  20363. lhs: value.lhs,
  20364. declareLocalCallback: value.declareLocalCallback,
  20365. declare: false,
  20366. priority: value.priority,
  20367. localRef: value.localRef
  20368. };
  20369. // Cache the value locally.
  20370. this.map.set(name, value);
  20371. // Possibly generate a shared context var
  20372. this.maybeGenerateSharedContextVar(value);
  20373. this.maybeRestoreView(value.retrievalLevel, value.localRef);
  20374. }
  20375. if (value.declareLocalCallback && !value.declare) {
  20376. value.declare = true;
  20377. }
  20378. return value.lhs;
  20379. }
  20380. current = current.parent;
  20381. }
  20382. // If we get to this point, we are looking for a property on the top level component
  20383. // - If level === 0, we are on the top and don't need to re-declare `ctx`.
  20384. // - If level > 0, we are in an embedded view. We need to retrieve the name of the
  20385. // local var we used to store the component context, e.g. const $comp$ = x();
  20386. return this.bindingLevel === 0 ? null : this.getComponentProperty(name);
  20387. };
  20388. /**
  20389. * Create a local variable for later reference.
  20390. *
  20391. * @param retrievalLevel The level from which this value can be retrieved
  20392. * @param name Name of the variable.
  20393. * @param lhs AST representing the left hand side of the `let lhs = rhs;`.
  20394. * @param priority The sorting priority of this var
  20395. * @param declareLocalCallback The callback to invoke when declaring this local var
  20396. * @param localRef Whether or not this is a local ref
  20397. */
  20398. BindingScope.prototype.set = function (retrievalLevel, name, lhs, priority /* DEFAULT */, declareLocalCallback, localRef) {
  20399. if (priority === void 0) { priority = 0; }
  20400. if (this.map.has(name)) {
  20401. if (localRef) {
  20402. // Do not throw an error if it's a local ref and do not update existing value,
  20403. // so the first defined ref is always returned.
  20404. return this;
  20405. }
  20406. error("The name " + name + " is already defined in scope to be " + this.map.get(name));
  20407. }
  20408. this.map.set(name, {
  20409. retrievalLevel: retrievalLevel,
  20410. lhs: lhs,
  20411. declare: false,
  20412. declareLocalCallback: declareLocalCallback,
  20413. priority: priority,
  20414. localRef: localRef || false
  20415. });
  20416. return this;
  20417. };
  20418. // Implemented as part of LocalResolver.
  20419. BindingScope.prototype.getLocal = function (name) {
  20420. return this.get(name);
  20421. };
  20422. // Implemented as part of LocalResolver.
  20423. BindingScope.prototype.notifyImplicitReceiverUse = function () {
  20424. if (this.bindingLevel !== 0) {
  20425. // Since the implicit receiver is accessed in an embedded view, we need to
  20426. // ensure that we declare a shared context variable for the current template
  20427. // in the update variables.
  20428. this.map.get(SHARED_CONTEXT_KEY + 0).declare = true;
  20429. }
  20430. };
  20431. BindingScope.prototype.nestedScope = function (level, globals) {
  20432. var newScope = new BindingScope(level, this, globals);
  20433. if (level > 0)
  20434. newScope.generateSharedContextVar(0);
  20435. return newScope;
  20436. };
  20437. /**
  20438. * Gets or creates a shared context variable and returns its expression. Note that
  20439. * this does not mean that the shared variable will be declared. Variables in the
  20440. * binding scope will be only declared if they are used.
  20441. */
  20442. BindingScope.prototype.getOrCreateSharedContextVar = function (retrievalLevel) {
  20443. var bindingKey = SHARED_CONTEXT_KEY + retrievalLevel;
  20444. if (!this.map.has(bindingKey)) {
  20445. this.generateSharedContextVar(retrievalLevel);
  20446. }
  20447. // Shared context variables are always generated as "ReadVarExpr".
  20448. return this.map.get(bindingKey).lhs;
  20449. };
  20450. BindingScope.prototype.getSharedContextName = function (retrievalLevel) {
  20451. var sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + retrievalLevel);
  20452. // Shared context variables are always generated as "ReadVarExpr".
  20453. return sharedCtxObj && sharedCtxObj.declare ? sharedCtxObj.lhs : null;
  20454. };
  20455. BindingScope.prototype.maybeGenerateSharedContextVar = function (value) {
  20456. if (value.priority === 1 /* CONTEXT */ &&
  20457. value.retrievalLevel < this.bindingLevel) {
  20458. var sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + value.retrievalLevel);
  20459. if (sharedCtxObj) {
  20460. sharedCtxObj.declare = true;
  20461. }
  20462. else {
  20463. this.generateSharedContextVar(value.retrievalLevel);
  20464. }
  20465. }
  20466. };
  20467. BindingScope.prototype.generateSharedContextVar = function (retrievalLevel) {
  20468. var lhs = variable(CONTEXT_NAME + this.freshReferenceName());
  20469. this.map.set(SHARED_CONTEXT_KEY + retrievalLevel, {
  20470. retrievalLevel: retrievalLevel,
  20471. lhs: lhs,
  20472. declareLocalCallback: function (scope, relativeLevel) {
  20473. // const ctx_r0 = nextContext(2);
  20474. return [lhs.set(generateNextContextExpr(relativeLevel)).toConstDecl()];
  20475. },
  20476. declare: false,
  20477. priority: 2 /* SHARED_CONTEXT */,
  20478. localRef: false
  20479. });
  20480. };
  20481. BindingScope.prototype.getComponentProperty = function (name) {
  20482. var componentValue = this.map.get(SHARED_CONTEXT_KEY + 0);
  20483. componentValue.declare = true;
  20484. this.maybeRestoreView(0, false);
  20485. return componentValue.lhs.prop(name);
  20486. };
  20487. BindingScope.prototype.maybeRestoreView = function (retrievalLevel, localRefLookup) {
  20488. // We want to restore the current view in listener fns if:
  20489. // 1 - we are accessing a value in a parent view, which requires walking the view tree rather
  20490. // than using the ctx arg. In this case, the retrieval and binding level will be different.
  20491. // 2 - we are looking up a local ref, which requires restoring the view where the local
  20492. // ref is stored
  20493. if (this.isListenerScope() && (retrievalLevel < this.bindingLevel || localRefLookup)) {
  20494. if (!this.parent.restoreViewVariable) {
  20495. // parent saves variable to generate a shared `const $s$ = getCurrentView();` instruction
  20496. this.parent.restoreViewVariable = variable(this.parent.freshReferenceName());
  20497. }
  20498. this.restoreViewVariable = this.parent.restoreViewVariable;
  20499. }
  20500. };
  20501. BindingScope.prototype.restoreViewStatement = function () {
  20502. var statements = [];
  20503. if (this.restoreViewVariable) {
  20504. var restoreCall = instruction(null, Identifiers.restoreView, [this.restoreViewVariable]);
  20505. // Either `const restoredCtx = restoreView($state$);` or `restoreView($state$);`
  20506. // depending on whether it is being used.
  20507. statements.push(this.usesRestoredViewContext ?
  20508. variable(RESTORED_VIEW_CONTEXT_NAME).set(restoreCall).toConstDecl() :
  20509. restoreCall.toStmt());
  20510. }
  20511. return statements;
  20512. };
  20513. BindingScope.prototype.viewSnapshotStatements = function () {
  20514. // const $state$ = getCurrentView();
  20515. return this.restoreViewVariable ?
  20516. [this.restoreViewVariable.set(instruction(null, Identifiers.getCurrentView, [])).toConstDecl()] :
  20517. [];
  20518. };
  20519. BindingScope.prototype.isListenerScope = function () {
  20520. return this.parent && this.parent.bindingLevel === this.bindingLevel;
  20521. };
  20522. BindingScope.prototype.variableDeclarations = function () {
  20523. var _this = this;
  20524. var currentContextLevel = 0;
  20525. return Array.from(this.map.values())
  20526. .filter(function (value) { return value.declare; })
  20527. .sort(function (a, b) { return b.retrievalLevel - a.retrievalLevel || b.priority - a.priority; })
  20528. .reduce(function (stmts, value) {
  20529. var levelDiff = _this.bindingLevel - value.retrievalLevel;
  20530. var currStmts = value.declareLocalCallback(_this, levelDiff - currentContextLevel);
  20531. currentContextLevel = levelDiff;
  20532. return stmts.concat(currStmts);
  20533. }, []);
  20534. };
  20535. BindingScope.prototype.freshReferenceName = function () {
  20536. var current = this;
  20537. // Find the top scope as it maintains the global reference count
  20538. while (current.parent)
  20539. current = current.parent;
  20540. var ref = "" + REFERENCE_PREFIX + current.referenceNameIndex++;
  20541. return ref;
  20542. };
  20543. BindingScope.prototype.hasRestoreViewVariable = function () {
  20544. return !!this.restoreViewVariable;
  20545. };
  20546. BindingScope.prototype.notifyRestoredViewContextUse = function () {
  20547. this.usesRestoredViewContext = true;
  20548. };
  20549. return BindingScope;
  20550. }());
  20551. /**
  20552. * Creates a `CssSelector` given a tag name and a map of attributes
  20553. */
  20554. function createCssSelector(elementName, attributes) {
  20555. var cssSelector = new CssSelector();
  20556. var elementNameNoNs = splitNsName(elementName)[1];
  20557. cssSelector.setElement(elementNameNoNs);
  20558. Object.getOwnPropertyNames(attributes).forEach(function (name) {
  20559. var nameNoNs = splitNsName(name)[1];
  20560. var value = attributes[name];
  20561. cssSelector.addAttribute(nameNoNs, value);
  20562. if (name.toLowerCase() === 'class') {
  20563. var classes = value.trim().split(/\s+/);
  20564. classes.forEach(function (className) { return cssSelector.addClassName(className); });
  20565. }
  20566. });
  20567. return cssSelector;
  20568. }
  20569. /**
  20570. * Creates an array of expressions out of an `ngProjectAs` attributes
  20571. * which can be added to the instruction parameters.
  20572. */
  20573. function getNgProjectAsLiteral(attribute) {
  20574. // Parse the attribute value into a CssSelectorList. Note that we only take the
  20575. // first selector, because we don't support multiple selectors in ngProjectAs.
  20576. var parsedR3Selector = parseSelectorToR3Selector(attribute.value)[0];
  20577. return [literal(5 /* ProjectAs */), asLiteral(parsedR3Selector)];
  20578. }
  20579. /**
  20580. * Gets the instruction to generate for an interpolated property
  20581. * @param interpolation An Interpolation AST
  20582. */
  20583. function getPropertyInterpolationExpression(interpolation) {
  20584. switch (getInterpolationArgsLength(interpolation)) {
  20585. case 1:
  20586. return Identifiers.propertyInterpolate;
  20587. case 3:
  20588. return Identifiers.propertyInterpolate1;
  20589. case 5:
  20590. return Identifiers.propertyInterpolate2;
  20591. case 7:
  20592. return Identifiers.propertyInterpolate3;
  20593. case 9:
  20594. return Identifiers.propertyInterpolate4;
  20595. case 11:
  20596. return Identifiers.propertyInterpolate5;
  20597. case 13:
  20598. return Identifiers.propertyInterpolate6;
  20599. case 15:
  20600. return Identifiers.propertyInterpolate7;
  20601. case 17:
  20602. return Identifiers.propertyInterpolate8;
  20603. default:
  20604. return Identifiers.propertyInterpolateV;
  20605. }
  20606. }
  20607. /**
  20608. * Gets the instruction to generate for an interpolated attribute
  20609. * @param interpolation An Interpolation AST
  20610. */
  20611. function getAttributeInterpolationExpression(interpolation) {
  20612. switch (getInterpolationArgsLength(interpolation)) {
  20613. case 3:
  20614. return Identifiers.attributeInterpolate1;
  20615. case 5:
  20616. return Identifiers.attributeInterpolate2;
  20617. case 7:
  20618. return Identifiers.attributeInterpolate3;
  20619. case 9:
  20620. return Identifiers.attributeInterpolate4;
  20621. case 11:
  20622. return Identifiers.attributeInterpolate5;
  20623. case 13:
  20624. return Identifiers.attributeInterpolate6;
  20625. case 15:
  20626. return Identifiers.attributeInterpolate7;
  20627. case 17:
  20628. return Identifiers.attributeInterpolate8;
  20629. default:
  20630. return Identifiers.attributeInterpolateV;
  20631. }
  20632. }
  20633. /**
  20634. * Gets the instruction to generate for interpolated text.
  20635. * @param interpolation An Interpolation AST
  20636. */
  20637. function getTextInterpolationExpression(interpolation) {
  20638. switch (getInterpolationArgsLength(interpolation)) {
  20639. case 1:
  20640. return Identifiers.textInterpolate;
  20641. case 3:
  20642. return Identifiers.textInterpolate1;
  20643. case 5:
  20644. return Identifiers.textInterpolate2;
  20645. case 7:
  20646. return Identifiers.textInterpolate3;
  20647. case 9:
  20648. return Identifiers.textInterpolate4;
  20649. case 11:
  20650. return Identifiers.textInterpolate5;
  20651. case 13:
  20652. return Identifiers.textInterpolate6;
  20653. case 15:
  20654. return Identifiers.textInterpolate7;
  20655. case 17:
  20656. return Identifiers.textInterpolate8;
  20657. default:
  20658. return Identifiers.textInterpolateV;
  20659. }
  20660. }
  20661. /**
  20662. * Parse a template into render3 `Node`s and additional metadata, with no other dependencies.
  20663. *
  20664. * @param template text of the template to parse
  20665. * @param templateUrl URL to use for source mapping of the parsed template
  20666. * @param options options to modify how the template is parsed
  20667. */
  20668. function parseTemplate(template, templateUrl, options) {
  20669. if (options === void 0) { options = {}; }
  20670. var interpolationConfig = options.interpolationConfig, preserveWhitespaces = options.preserveWhitespaces, enableI18nLegacyMessageIdFormat = options.enableI18nLegacyMessageIdFormat;
  20671. var bindingParser = makeBindingParser(interpolationConfig);
  20672. var htmlParser = new HtmlParser();
  20673. var parseResult = htmlParser.parse(template, templateUrl, Object.assign(Object.assign({ leadingTriviaChars: LEADING_TRIVIA_CHARS }, options), { tokenizeExpansionForms: true }));
  20674. if (!options.alwaysAttemptHtmlToR3AstConversion && parseResult.errors &&
  20675. parseResult.errors.length > 0) {
  20676. var parsedTemplate_1 = {
  20677. interpolationConfig: interpolationConfig,
  20678. preserveWhitespaces: preserveWhitespaces,
  20679. errors: parseResult.errors,
  20680. nodes: [],
  20681. styleUrls: [],
  20682. styles: [],
  20683. ngContentSelectors: []
  20684. };
  20685. if (options.collectCommentNodes) {
  20686. parsedTemplate_1.commentNodes = [];
  20687. }
  20688. return parsedTemplate_1;
  20689. }
  20690. var rootNodes = parseResult.rootNodes;
  20691. // process i18n meta information (scan attributes, generate ids)
  20692. // before we run whitespace removal process, because existing i18n
  20693. // extraction process (ng extract-i18n) relies on a raw content to generate
  20694. // message ids
  20695. var i18nMetaVisitor = new I18nMetaVisitor(interpolationConfig, /* keepI18nAttrs */ !preserveWhitespaces, enableI18nLegacyMessageIdFormat);
  20696. var i18nMetaResult = i18nMetaVisitor.visitAllWithErrors(rootNodes);
  20697. if (!options.alwaysAttemptHtmlToR3AstConversion && i18nMetaResult.errors &&
  20698. i18nMetaResult.errors.length > 0) {
  20699. var parsedTemplate_2 = {
  20700. interpolationConfig: interpolationConfig,
  20701. preserveWhitespaces: preserveWhitespaces,
  20702. errors: i18nMetaResult.errors,
  20703. nodes: [],
  20704. styleUrls: [],
  20705. styles: [],
  20706. ngContentSelectors: []
  20707. };
  20708. if (options.collectCommentNodes) {
  20709. parsedTemplate_2.commentNodes = [];
  20710. }
  20711. return parsedTemplate_2;
  20712. }
  20713. rootNodes = i18nMetaResult.rootNodes;
  20714. if (!preserveWhitespaces) {
  20715. rootNodes = visitAll$1(new WhitespaceVisitor(), rootNodes);
  20716. // run i18n meta visitor again in case whitespaces are removed (because that might affect
  20717. // generated i18n message content) and first pass indicated that i18n content is present in a
  20718. // template. During this pass i18n IDs generated at the first pass will be preserved, so we can
  20719. // mimic existing extraction process (ng extract-i18n)
  20720. if (i18nMetaVisitor.hasI18nMeta) {
  20721. rootNodes = visitAll$1(new I18nMetaVisitor(interpolationConfig, /* keepI18nAttrs */ false), rootNodes);
  20722. }
  20723. }
  20724. var _c = htmlAstToRender3Ast(rootNodes, bindingParser, { collectCommentNodes: !!options.collectCommentNodes }), nodes = _c.nodes, errors = _c.errors, styleUrls = _c.styleUrls, styles = _c.styles, ngContentSelectors = _c.ngContentSelectors, commentNodes = _c.commentNodes;
  20725. errors.push.apply(errors, __spreadArray(__spreadArray([], __read(parseResult.errors)), __read(i18nMetaResult.errors)));
  20726. var parsedTemplate = {
  20727. interpolationConfig: interpolationConfig,
  20728. preserveWhitespaces: preserveWhitespaces,
  20729. errors: errors.length > 0 ? errors : null,
  20730. nodes: nodes,
  20731. styleUrls: styleUrls,
  20732. styles: styles,
  20733. ngContentSelectors: ngContentSelectors
  20734. };
  20735. if (options.collectCommentNodes) {
  20736. parsedTemplate.commentNodes = commentNodes;
  20737. }
  20738. return parsedTemplate;
  20739. }
  20740. var elementRegistry = new DomElementSchemaRegistry();
  20741. /**
  20742. * Construct a `BindingParser` with a default configuration.
  20743. */
  20744. function makeBindingParser(interpolationConfig) {
  20745. if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
  20746. return new BindingParser(new IvyParser(new Lexer()), interpolationConfig, elementRegistry, null, []);
  20747. }
  20748. function resolveSanitizationFn(context, isAttribute) {
  20749. switch (context) {
  20750. case SecurityContext.HTML:
  20751. return importExpr(Identifiers.sanitizeHtml);
  20752. case SecurityContext.SCRIPT:
  20753. return importExpr(Identifiers.sanitizeScript);
  20754. case SecurityContext.STYLE:
  20755. // the compiler does not fill in an instruction for [style.prop?] binding
  20756. // values because the style algorithm knows internally what props are subject
  20757. // to sanitization (only [attr.style] values are explicitly sanitized)
  20758. return isAttribute ? importExpr(Identifiers.sanitizeStyle) : null;
  20759. case SecurityContext.URL:
  20760. return importExpr(Identifiers.sanitizeUrl);
  20761. case SecurityContext.RESOURCE_URL:
  20762. return importExpr(Identifiers.sanitizeResourceUrl);
  20763. default:
  20764. return null;
  20765. }
  20766. }
  20767. function trustedConstAttribute(tagName, attr) {
  20768. var value = asLiteral(attr.value);
  20769. if (isTrustedTypesSink(tagName, attr.name)) {
  20770. switch (elementRegistry.securityContext(tagName, attr.name, /* isAttribute */ true)) {
  20771. case SecurityContext.HTML:
  20772. return taggedTemplate(importExpr(Identifiers.trustConstantHtml), new TemplateLiteral([new TemplateLiteralElement(attr.value)], []), undefined, attr.valueSpan);
  20773. // NB: no SecurityContext.SCRIPT here, as the corresponding tags are stripped by the compiler.
  20774. case SecurityContext.RESOURCE_URL:
  20775. return taggedTemplate(importExpr(Identifiers.trustConstantResourceUrl), new TemplateLiteral([new TemplateLiteralElement(attr.value)], []), undefined, attr.valueSpan);
  20776. default:
  20777. return value;
  20778. }
  20779. }
  20780. else {
  20781. return value;
  20782. }
  20783. }
  20784. function isSingleElementTemplate(children) {
  20785. return children.length === 1 && children[0] instanceof Element;
  20786. }
  20787. function isTextNode(node) {
  20788. return node instanceof Text || node instanceof BoundText || node instanceof Icu;
  20789. }
  20790. function hasTextChildrenOnly(children) {
  20791. return children.every(isTextNode);
  20792. }
  20793. /** Name of the global variable that is used to determine if we use Closure translations or not */
  20794. var NG_I18N_CLOSURE_MODE = 'ngI18nClosureMode';
  20795. /**
  20796. * Generate statements that define a given translation message.
  20797. *
  20798. * ```
  20799. * var I18N_1;
  20800. * if (typeof ngI18nClosureMode !== undefined && ngI18nClosureMode) {
  20801. * var MSG_EXTERNAL_XXX = goog.getMsg(
  20802. * "Some message with {$interpolation}!",
  20803. * { "interpolation": "\uFFFD0\uFFFD" }
  20804. * );
  20805. * I18N_1 = MSG_EXTERNAL_XXX;
  20806. * }
  20807. * else {
  20808. * I18N_1 = $localize`Some message with ${'\uFFFD0\uFFFD'}!`;
  20809. * }
  20810. * ```
  20811. *
  20812. * @param message The original i18n AST message node
  20813. * @param variable The variable that will be assigned the translation, e.g. `I18N_1`.
  20814. * @param closureVar The variable for Closure `goog.getMsg` calls, e.g. `MSG_EXTERNAL_XXX`.
  20815. * @param params Object mapping placeholder names to their values (e.g.
  20816. * `{ "interpolation": "\uFFFD0\uFFFD" }`).
  20817. * @param transformFn Optional transformation function that will be applied to the translation (e.g.
  20818. * post-processing).
  20819. * @returns An array of statements that defined a given translation.
  20820. */
  20821. function getTranslationDeclStmts(message, variable, closureVar, params, transformFn) {
  20822. if (params === void 0) { params = {}; }
  20823. var statements = [
  20824. declareI18nVariable(variable),
  20825. ifStmt(createClosureModeGuard(), createGoogleGetMsgStatements(variable, message, closureVar, i18nFormatPlaceholderNames(params, /* useCamelCase */ true)), createLocalizeStatements(variable, message, i18nFormatPlaceholderNames(params, /* useCamelCase */ false))),
  20826. ];
  20827. if (transformFn) {
  20828. statements.push(new ExpressionStatement(variable.set(transformFn(variable))));
  20829. }
  20830. return statements;
  20831. }
  20832. /**
  20833. * Create the expression that will be used to guard the closure mode block
  20834. * It is equivalent to:
  20835. *
  20836. * ```
  20837. * typeof ngI18nClosureMode !== undefined && ngI18nClosureMode
  20838. * ```
  20839. */
  20840. function createClosureModeGuard() {
  20841. return typeofExpr(variable(NG_I18N_CLOSURE_MODE))
  20842. .notIdentical(literal('undefined', STRING_TYPE))
  20843. .and(variable(NG_I18N_CLOSURE_MODE));
  20844. }
  20845. // This regex matches any binding names that contain the "attr." prefix, e.g. "attr.required"
  20846. // If there is a match, the first matching group will contain the attribute name to bind.
  20847. var ATTR_REGEX = /attr\.([^\]]+)/;
  20848. function baseDirectiveFields(meta, constantPool, bindingParser) {
  20849. var definitionMap = new DefinitionMap();
  20850. var selectors = parseSelectorToR3Selector(meta.selector);
  20851. // e.g. `type: MyDirective`
  20852. definitionMap.set('type', meta.internalType);
  20853. // e.g. `selectors: [['', 'someDir', '']]`
  20854. if (selectors.length > 0) {
  20855. definitionMap.set('selectors', asLiteral(selectors));
  20856. }
  20857. if (meta.queries.length > 0) {
  20858. // e.g. `contentQueries: (rf, ctx, dirIndex) => { ... }
  20859. definitionMap.set('contentQueries', createContentQueriesFunction(meta.queries, constantPool, meta.name));
  20860. }
  20861. if (meta.viewQueries.length) {
  20862. definitionMap.set('viewQuery', createViewQueriesFunction(meta.viewQueries, constantPool, meta.name));
  20863. }
  20864. // e.g. `hostBindings: (rf, ctx) => { ... }
  20865. definitionMap.set('hostBindings', createHostBindingsFunction(meta.host, meta.typeSourceSpan, bindingParser, constantPool, meta.selector || '', meta.name, definitionMap));
  20866. // e.g 'inputs: {a: 'a'}`
  20867. definitionMap.set('inputs', conditionallyCreateMapObjectLiteral(meta.inputs, true));
  20868. // e.g 'outputs: {a: 'a'}`
  20869. definitionMap.set('outputs', conditionallyCreateMapObjectLiteral(meta.outputs));
  20870. if (meta.exportAs !== null) {
  20871. definitionMap.set('exportAs', literalArr(meta.exportAs.map(function (e) { return literal(e); })));
  20872. }
  20873. return definitionMap;
  20874. }
  20875. /**
  20876. * Add features to the definition map.
  20877. */
  20878. function addFeatures(definitionMap, meta) {
  20879. // e.g. `features: [NgOnChangesFeature]`
  20880. var features = [];
  20881. var providers = meta.providers;
  20882. var viewProviders = meta.viewProviders;
  20883. if (providers || viewProviders) {
  20884. var args = [providers || new LiteralArrayExpr([])];
  20885. if (viewProviders) {
  20886. args.push(viewProviders);
  20887. }
  20888. features.push(importExpr(Identifiers.ProvidersFeature).callFn(args));
  20889. }
  20890. if (meta.usesInheritance) {
  20891. features.push(importExpr(Identifiers.InheritDefinitionFeature));
  20892. }
  20893. if (meta.fullInheritance) {
  20894. features.push(importExpr(Identifiers.CopyDefinitionFeature));
  20895. }
  20896. if (meta.lifecycle.usesOnChanges) {
  20897. features.push(importExpr(Identifiers.NgOnChangesFeature));
  20898. }
  20899. if (features.length) {
  20900. definitionMap.set('features', literalArr(features));
  20901. }
  20902. }
  20903. /**
  20904. * Compile a directive for the render3 runtime as defined by the `R3DirectiveMetadata`.
  20905. */
  20906. function compileDirectiveFromMetadata(meta, constantPool, bindingParser) {
  20907. var definitionMap = baseDirectiveFields(meta, constantPool, bindingParser);
  20908. addFeatures(definitionMap, meta);
  20909. var expression = importExpr(Identifiers.defineDirective).callFn([definitionMap.toLiteralMap()], undefined, true);
  20910. var type = createDirectiveType(meta);
  20911. return { expression: expression, type: type, statements: [] };
  20912. }
  20913. /**
  20914. * Compile a component for the render3 runtime as defined by the `R3ComponentMetadata`.
  20915. */
  20916. function compileComponentFromMetadata(meta, constantPool, bindingParser) {
  20917. var e_1, _a;
  20918. var definitionMap = baseDirectiveFields(meta, constantPool, bindingParser);
  20919. addFeatures(definitionMap, meta);
  20920. var selector = meta.selector && CssSelector.parse(meta.selector);
  20921. var firstSelector = selector && selector[0];
  20922. // e.g. `attr: ["class", ".my.app"]`
  20923. // This is optional an only included if the first selector of a component specifies attributes.
  20924. if (firstSelector) {
  20925. var selectorAttributes = firstSelector.getAttrs();
  20926. if (selectorAttributes.length) {
  20927. definitionMap.set('attrs', constantPool.getConstLiteral(literalArr(selectorAttributes.map(function (value) { return value != null ? literal(value) : literal(undefined); })),
  20928. /* forceShared */ true));
  20929. }
  20930. }
  20931. // Generate the CSS matcher that recognize directive
  20932. var directiveMatcher = null;
  20933. if (meta.directives.length > 0) {
  20934. var matcher = new SelectorMatcher();
  20935. try {
  20936. for (var _b = __values(meta.directives), _c = _b.next(); !_c.done; _c = _b.next()) {
  20937. var _d = _c.value, selector_1 = _d.selector, type_1 = _d.type;
  20938. matcher.addSelectables(CssSelector.parse(selector_1), type_1);
  20939. }
  20940. }
  20941. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  20942. finally {
  20943. try {
  20944. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  20945. }
  20946. finally { if (e_1) throw e_1.error; }
  20947. }
  20948. directiveMatcher = matcher;
  20949. }
  20950. // e.g. `template: function MyComponent_Template(_ctx, _cm) {...}`
  20951. var templateTypeName = meta.name;
  20952. var templateName = templateTypeName ? templateTypeName + "_Template" : null;
  20953. var directivesUsed = new Set();
  20954. var pipesUsed = new Set();
  20955. var changeDetection = meta.changeDetection;
  20956. var template = meta.template;
  20957. var templateBuilder = new TemplateDefinitionBuilder(constantPool, BindingScope.createRootScope(), 0, templateTypeName, null, null, templateName, directiveMatcher, directivesUsed, meta.pipes, pipesUsed, Identifiers.namespaceHTML, meta.relativeContextFilePath, meta.i18nUseExternalIds);
  20958. var templateFunctionExpression = templateBuilder.buildTemplateFunction(template.nodes, []);
  20959. // We need to provide this so that dynamically generated components know what
  20960. // projected content blocks to pass through to the component when it is instantiated.
  20961. var ngContentSelectors = templateBuilder.getNgContentSelectors();
  20962. if (ngContentSelectors) {
  20963. definitionMap.set('ngContentSelectors', ngContentSelectors);
  20964. }
  20965. // e.g. `decls: 2`
  20966. definitionMap.set('decls', literal(templateBuilder.getConstCount()));
  20967. // e.g. `vars: 2`
  20968. definitionMap.set('vars', literal(templateBuilder.getVarCount()));
  20969. // Generate `consts` section of ComponentDef:
  20970. // - either as an array:
  20971. // `consts: [['one', 'two'], ['three', 'four']]`
  20972. // - or as a factory function in case additional statements are present (to support i18n):
  20973. // `consts: function() { var i18n_0; if (ngI18nClosureMode) {...} else {...} return [i18n_0]; }`
  20974. var _e = templateBuilder.getConsts(), constExpressions = _e.constExpressions, prepareStatements = _e.prepareStatements;
  20975. if (constExpressions.length > 0) {
  20976. var constsExpr = literalArr(constExpressions);
  20977. // Prepare statements are present - turn `consts` into a function.
  20978. if (prepareStatements.length > 0) {
  20979. constsExpr = fn([], __spreadArray(__spreadArray([], __read(prepareStatements)), [new ReturnStatement(constsExpr)]));
  20980. }
  20981. definitionMap.set('consts', constsExpr);
  20982. }
  20983. definitionMap.set('template', templateFunctionExpression);
  20984. // e.g. `directives: [MyDirective]`
  20985. if (directivesUsed.size) {
  20986. var directivesList = literalArr(Array.from(directivesUsed));
  20987. var directivesExpr = compileDeclarationList(directivesList, meta.declarationListEmitMode);
  20988. definitionMap.set('directives', directivesExpr);
  20989. }
  20990. // e.g. `pipes: [MyPipe]`
  20991. if (pipesUsed.size) {
  20992. var pipesList = literalArr(Array.from(pipesUsed));
  20993. var pipesExpr = compileDeclarationList(pipesList, meta.declarationListEmitMode);
  20994. definitionMap.set('pipes', pipesExpr);
  20995. }
  20996. if (meta.encapsulation === null) {
  20997. meta.encapsulation = ViewEncapsulation.Emulated;
  20998. }
  20999. // e.g. `styles: [str1, str2]`
  21000. if (meta.styles && meta.styles.length) {
  21001. var styleValues = meta.encapsulation == ViewEncapsulation.Emulated ?
  21002. compileStyles(meta.styles, CONTENT_ATTR, HOST_ATTR) :
  21003. meta.styles;
  21004. var strings = styleValues.map(function (str) { return constantPool.getConstLiteral(literal(str)); });
  21005. definitionMap.set('styles', literalArr(strings));
  21006. }
  21007. else if (meta.encapsulation === ViewEncapsulation.Emulated) {
  21008. // If there is no style, don't generate css selectors on elements
  21009. meta.encapsulation = ViewEncapsulation.None;
  21010. }
  21011. // Only set view encapsulation if it's not the default value
  21012. if (meta.encapsulation !== ViewEncapsulation.Emulated) {
  21013. definitionMap.set('encapsulation', literal(meta.encapsulation));
  21014. }
  21015. // e.g. `animation: [trigger('123', [])]`
  21016. if (meta.animations !== null) {
  21017. definitionMap.set('data', literalMap([{ key: 'animation', value: meta.animations, quoted: false }]));
  21018. }
  21019. // Only set the change detection flag if it's defined and it's not the default.
  21020. if (changeDetection != null && changeDetection !== ChangeDetectionStrategy.Default) {
  21021. definitionMap.set('changeDetection', literal(changeDetection));
  21022. }
  21023. var expression = importExpr(Identifiers.defineComponent).callFn([definitionMap.toLiteralMap()], undefined, true);
  21024. var type = createComponentType(meta);
  21025. return { expression: expression, type: type, statements: [] };
  21026. }
  21027. /**
  21028. * Creates the type specification from the component meta. This type is inserted into .d.ts files
  21029. * to be consumed by upstream compilations.
  21030. */
  21031. function createComponentType(meta) {
  21032. var typeParams = createDirectiveTypeParams(meta);
  21033. typeParams.push(stringArrayAsType(meta.template.ngContentSelectors));
  21034. return expressionType(importExpr(Identifiers.ComponentDeclaration, typeParams));
  21035. }
  21036. /**
  21037. * Compiles the array literal of declarations into an expression according to the provided emit
  21038. * mode.
  21039. */
  21040. function compileDeclarationList(list, mode) {
  21041. switch (mode) {
  21042. case 0 /* Direct */:
  21043. // directives: [MyDir],
  21044. return list;
  21045. case 1 /* Closure */:
  21046. // directives: function () { return [MyDir]; }
  21047. return fn([], [new ReturnStatement(list)]);
  21048. case 2 /* ClosureResolved */:
  21049. // directives: function () { return [MyDir].map(ng.resolveForwardRef); }
  21050. var resolvedList = list.callMethod('map', [importExpr(Identifiers.resolveForwardRef)]);
  21051. return fn([], [new ReturnStatement(resolvedList)]);
  21052. }
  21053. }
  21054. function prepareQueryParams(query, constantPool) {
  21055. var parameters = [getQueryPredicate(query, constantPool), literal(toQueryFlags(query))];
  21056. if (query.read) {
  21057. parameters.push(query.read);
  21058. }
  21059. return parameters;
  21060. }
  21061. /**
  21062. * Translates query flags into `TQueryFlags` type in packages/core/src/render3/interfaces/query.ts
  21063. * @param query
  21064. */
  21065. function toQueryFlags(query) {
  21066. return (query.descendants ? 1 /* descendants */ : 0 /* none */) |
  21067. (query.static ? 2 /* isStatic */ : 0 /* none */) |
  21068. (query.emitDistinctChangesOnly ? 4 /* emitDistinctChangesOnly */ : 0 /* none */);
  21069. }
  21070. function convertAttributesToExpressions(attributes) {
  21071. var e_2, _a;
  21072. var values = [];
  21073. try {
  21074. for (var _b = __values(Object.getOwnPropertyNames(attributes)), _c = _b.next(); !_c.done; _c = _b.next()) {
  21075. var key = _c.value;
  21076. var value = attributes[key];
  21077. values.push(literal(key), value);
  21078. }
  21079. }
  21080. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  21081. finally {
  21082. try {
  21083. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  21084. }
  21085. finally { if (e_2) throw e_2.error; }
  21086. }
  21087. return values;
  21088. }
  21089. // Define and update any content queries
  21090. function createContentQueriesFunction(queries, constantPool, name) {
  21091. var e_3, _a;
  21092. var createStatements = [];
  21093. var updateStatements = [];
  21094. var tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
  21095. try {
  21096. for (var queries_1 = __values(queries), queries_1_1 = queries_1.next(); !queries_1_1.done; queries_1_1 = queries_1.next()) {
  21097. var query = queries_1_1.value;
  21098. // creation, e.g. r3.contentQuery(dirIndex, somePredicate, true, null);
  21099. createStatements.push(importExpr(Identifiers.contentQuery)
  21100. .callFn(__spreadArray([variable('dirIndex')], __read(prepareQueryParams(query, constantPool))))
  21101. .toStmt());
  21102. // update, e.g. (r3.queryRefresh(tmp = r3.loadQuery()) && (ctx.someDir = tmp));
  21103. var temporary = tempAllocator();
  21104. var getQueryList = importExpr(Identifiers.loadQuery).callFn([]);
  21105. var refresh = importExpr(Identifiers.queryRefresh).callFn([temporary.set(getQueryList)]);
  21106. var updateDirective = variable(CONTEXT_NAME)
  21107. .prop(query.propertyName)
  21108. .set(query.first ? temporary.prop('first') : temporary);
  21109. updateStatements.push(refresh.and(updateDirective).toStmt());
  21110. }
  21111. }
  21112. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  21113. finally {
  21114. try {
  21115. if (queries_1_1 && !queries_1_1.done && (_a = queries_1.return)) _a.call(queries_1);
  21116. }
  21117. finally { if (e_3) throw e_3.error; }
  21118. }
  21119. var contentQueriesFnName = name ? name + "_ContentQueries" : null;
  21120. return fn([
  21121. new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null),
  21122. new FnParam('dirIndex', null)
  21123. ], [
  21124. renderFlagCheckIfStmt(1 /* Create */, createStatements),
  21125. renderFlagCheckIfStmt(2 /* Update */, updateStatements)
  21126. ], INFERRED_TYPE, null, contentQueriesFnName);
  21127. }
  21128. function stringAsType(str) {
  21129. return expressionType(literal(str));
  21130. }
  21131. function stringMapAsType(map) {
  21132. var mapValues = Object.keys(map).map(function (key) {
  21133. var value = Array.isArray(map[key]) ? map[key][0] : map[key];
  21134. return {
  21135. key: key,
  21136. value: literal(value),
  21137. quoted: true,
  21138. };
  21139. });
  21140. return expressionType(literalMap(mapValues));
  21141. }
  21142. function stringArrayAsType(arr) {
  21143. return arr.length > 0 ? expressionType(literalArr(arr.map(function (value) { return literal(value); }))) :
  21144. NONE_TYPE;
  21145. }
  21146. function createDirectiveTypeParams(meta) {
  21147. // On the type side, remove newlines from the selector as it will need to fit into a TypeScript
  21148. // string literal, which must be on one line.
  21149. var selectorForType = meta.selector !== null ? meta.selector.replace(/\n/g, '') : null;
  21150. return [
  21151. typeWithParameters(meta.type.type, meta.typeArgumentCount),
  21152. selectorForType !== null ? stringAsType(selectorForType) : NONE_TYPE,
  21153. meta.exportAs !== null ? stringArrayAsType(meta.exportAs) : NONE_TYPE,
  21154. stringMapAsType(meta.inputs),
  21155. stringMapAsType(meta.outputs),
  21156. stringArrayAsType(meta.queries.map(function (q) { return q.propertyName; })),
  21157. ];
  21158. }
  21159. /**
  21160. * Creates the type specification from the directive meta. This type is inserted into .d.ts files
  21161. * to be consumed by upstream compilations.
  21162. */
  21163. function createDirectiveType(meta) {
  21164. var typeParams = createDirectiveTypeParams(meta);
  21165. return expressionType(importExpr(Identifiers.DirectiveDeclaration, typeParams));
  21166. }
  21167. // Define and update any view queries
  21168. function createViewQueriesFunction(viewQueries, constantPool, name) {
  21169. var createStatements = [];
  21170. var updateStatements = [];
  21171. var tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
  21172. viewQueries.forEach(function (query) {
  21173. // creation, e.g. r3.viewQuery(somePredicate, true);
  21174. var queryDefinition = importExpr(Identifiers.viewQuery).callFn(prepareQueryParams(query, constantPool));
  21175. createStatements.push(queryDefinition.toStmt());
  21176. // update, e.g. (r3.queryRefresh(tmp = r3.loadQuery()) && (ctx.someDir = tmp));
  21177. var temporary = tempAllocator();
  21178. var getQueryList = importExpr(Identifiers.loadQuery).callFn([]);
  21179. var refresh = importExpr(Identifiers.queryRefresh).callFn([temporary.set(getQueryList)]);
  21180. var updateDirective = variable(CONTEXT_NAME)
  21181. .prop(query.propertyName)
  21182. .set(query.first ? temporary.prop('first') : temporary);
  21183. updateStatements.push(refresh.and(updateDirective).toStmt());
  21184. });
  21185. var viewQueryFnName = name ? name + "_Query" : null;
  21186. return fn([new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], [
  21187. renderFlagCheckIfStmt(1 /* Create */, createStatements),
  21188. renderFlagCheckIfStmt(2 /* Update */, updateStatements)
  21189. ], INFERRED_TYPE, null, viewQueryFnName);
  21190. }
  21191. // Return a host binding function or null if one is not necessary.
  21192. function createHostBindingsFunction(hostBindingsMetadata, typeSourceSpan, bindingParser, constantPool, selector, name, definitionMap) {
  21193. var bindingContext = variable(CONTEXT_NAME);
  21194. var styleBuilder = new StylingBuilder(bindingContext);
  21195. var _a = hostBindingsMetadata.specialAttributes, styleAttr = _a.styleAttr, classAttr = _a.classAttr;
  21196. if (styleAttr !== undefined) {
  21197. styleBuilder.registerStyleAttr(styleAttr);
  21198. }
  21199. if (classAttr !== undefined) {
  21200. styleBuilder.registerClassAttr(classAttr);
  21201. }
  21202. var createStatements = [];
  21203. var updateStatements = [];
  21204. var hostBindingSourceSpan = typeSourceSpan;
  21205. var directiveSummary = metadataAsSummary(hostBindingsMetadata);
  21206. // Calculate host event bindings
  21207. var eventBindings = bindingParser.createDirectiveHostEventAsts(directiveSummary, hostBindingSourceSpan);
  21208. if (eventBindings && eventBindings.length) {
  21209. var listeners = createHostListeners(eventBindings, name);
  21210. createStatements.push.apply(createStatements, __spreadArray([], __read(listeners)));
  21211. }
  21212. // Calculate the host property bindings
  21213. var bindings = bindingParser.createBoundHostProperties(directiveSummary, hostBindingSourceSpan);
  21214. var allOtherBindings = [];
  21215. // We need to calculate the total amount of binding slots required by
  21216. // all the instructions together before any value conversions happen.
  21217. // Value conversions may require additional slots for interpolation and
  21218. // bindings with pipes. These calculates happen after this block.
  21219. var totalHostVarsCount = 0;
  21220. bindings && bindings.forEach(function (binding) {
  21221. var stylingInputWasSet = styleBuilder.registerInputBasedOnName(binding.name, binding.expression, hostBindingSourceSpan);
  21222. if (stylingInputWasSet) {
  21223. totalHostVarsCount += MIN_STYLING_BINDING_SLOTS_REQUIRED;
  21224. }
  21225. else {
  21226. allOtherBindings.push(binding);
  21227. totalHostVarsCount++;
  21228. }
  21229. });
  21230. var valueConverter;
  21231. var getValueConverter = function () {
  21232. if (!valueConverter) {
  21233. var hostVarsCountFn = function (numSlots) {
  21234. var originalVarsCount = totalHostVarsCount;
  21235. totalHostVarsCount += numSlots;
  21236. return originalVarsCount;
  21237. };
  21238. valueConverter = new ValueConverter(constantPool, function () { return error('Unexpected node'); }, // new nodes are illegal here
  21239. hostVarsCountFn, function () { return error('Unexpected pipe'); }); // pipes are illegal here
  21240. }
  21241. return valueConverter;
  21242. };
  21243. var propertyBindings = [];
  21244. var attributeBindings = [];
  21245. var syntheticHostBindings = [];
  21246. allOtherBindings.forEach(function (binding) {
  21247. // resolve literal arrays and literal objects
  21248. var value = binding.expression.visit(getValueConverter());
  21249. var bindingExpr = bindingFn(bindingContext, value);
  21250. var _a = getBindingNameAndInstruction(binding), bindingName = _a.bindingName, instruction = _a.instruction, isAttribute = _a.isAttribute;
  21251. var securityContexts = bindingParser.calcPossibleSecurityContexts(selector, bindingName, isAttribute)
  21252. .filter(function (context) { return context !== SecurityContext.NONE; });
  21253. var sanitizerFn = null;
  21254. if (securityContexts.length) {
  21255. if (securityContexts.length === 2 &&
  21256. securityContexts.indexOf(SecurityContext.URL) > -1 &&
  21257. securityContexts.indexOf(SecurityContext.RESOURCE_URL) > -1) {
  21258. // Special case for some URL attributes (such as "src" and "href") that may be a part
  21259. // of different security contexts. In this case we use special sanitization function and
  21260. // select the actual sanitizer at runtime based on a tag name that is provided while
  21261. // invoking sanitization function.
  21262. sanitizerFn = importExpr(Identifiers.sanitizeUrlOrResourceUrl);
  21263. }
  21264. else {
  21265. sanitizerFn = resolveSanitizationFn(securityContexts[0], isAttribute);
  21266. }
  21267. }
  21268. var instructionParams = [literal(bindingName), bindingExpr.currValExpr];
  21269. if (sanitizerFn) {
  21270. instructionParams.push(sanitizerFn);
  21271. }
  21272. updateStatements.push.apply(updateStatements, __spreadArray([], __read(bindingExpr.stmts)));
  21273. if (instruction === Identifiers.hostProperty) {
  21274. propertyBindings.push(instructionParams);
  21275. }
  21276. else if (instruction === Identifiers.attribute) {
  21277. attributeBindings.push(instructionParams);
  21278. }
  21279. else if (instruction === Identifiers.syntheticHostProperty) {
  21280. syntheticHostBindings.push(instructionParams);
  21281. }
  21282. else {
  21283. updateStatements.push(importExpr(instruction).callFn(instructionParams).toStmt());
  21284. }
  21285. });
  21286. if (propertyBindings.length > 0) {
  21287. updateStatements.push(chainedInstruction(Identifiers.hostProperty, propertyBindings).toStmt());
  21288. }
  21289. if (attributeBindings.length > 0) {
  21290. updateStatements.push(chainedInstruction(Identifiers.attribute, attributeBindings).toStmt());
  21291. }
  21292. if (syntheticHostBindings.length > 0) {
  21293. updateStatements.push(chainedInstruction(Identifiers.syntheticHostProperty, syntheticHostBindings).toStmt());
  21294. }
  21295. // since we're dealing with directives/components and both have hostBinding
  21296. // functions, we need to generate a special hostAttrs instruction that deals
  21297. // with both the assignment of styling as well as static attributes to the host
  21298. // element. The instruction below will instruct all initial styling (styling
  21299. // that is inside of a host binding within a directive/component) to be attached
  21300. // to the host element alongside any of the provided host attributes that were
  21301. // collected earlier.
  21302. var hostAttrs = convertAttributesToExpressions(hostBindingsMetadata.attributes);
  21303. styleBuilder.assignHostAttrs(hostAttrs, definitionMap);
  21304. if (styleBuilder.hasBindings) {
  21305. // finally each binding that was registered in the statement above will need to be added to
  21306. // the update block of a component/directive templateFn/hostBindingsFn so that the bindings
  21307. // are evaluated and updated for the element.
  21308. styleBuilder.buildUpdateLevelInstructions(getValueConverter()).forEach(function (instruction) {
  21309. if (instruction.calls.length > 0) {
  21310. var calls_1 = [];
  21311. instruction.calls.forEach(function (call) {
  21312. // we subtract a value of `1` here because the binding slot was already allocated
  21313. // at the top of this method when all the input bindings were counted.
  21314. totalHostVarsCount +=
  21315. Math.max(call.allocateBindingSlots - MIN_STYLING_BINDING_SLOTS_REQUIRED, 0);
  21316. calls_1.push(convertStylingCall(call, bindingContext, bindingFn));
  21317. });
  21318. updateStatements.push(chainedInstruction(instruction.reference, calls_1).toStmt());
  21319. }
  21320. });
  21321. }
  21322. if (totalHostVarsCount) {
  21323. definitionMap.set('hostVars', literal(totalHostVarsCount));
  21324. }
  21325. if (createStatements.length > 0 || updateStatements.length > 0) {
  21326. var hostBindingsFnName = name ? name + "_HostBindings" : null;
  21327. var statements = [];
  21328. if (createStatements.length > 0) {
  21329. statements.push(renderFlagCheckIfStmt(1 /* Create */, createStatements));
  21330. }
  21331. if (updateStatements.length > 0) {
  21332. statements.push(renderFlagCheckIfStmt(2 /* Update */, updateStatements));
  21333. }
  21334. return fn([new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], statements, INFERRED_TYPE, null, hostBindingsFnName);
  21335. }
  21336. return null;
  21337. }
  21338. function bindingFn(implicit, value) {
  21339. return convertPropertyBinding(null, implicit, value, 'b', BindingForm.Expression, function () { return error('Unexpected interpolation'); });
  21340. }
  21341. function convertStylingCall(call, bindingContext, bindingFn) {
  21342. return call.params(function (value) { return bindingFn(bindingContext, value).currValExpr; });
  21343. }
  21344. function getBindingNameAndInstruction(binding) {
  21345. var bindingName = binding.name;
  21346. var instruction;
  21347. // Check to see if this is an attr binding or a property binding
  21348. var attrMatches = bindingName.match(ATTR_REGEX);
  21349. if (attrMatches) {
  21350. bindingName = attrMatches[1];
  21351. instruction = Identifiers.attribute;
  21352. }
  21353. else {
  21354. if (binding.isAnimation) {
  21355. bindingName = prepareSyntheticPropertyName(bindingName);
  21356. // host bindings that have a synthetic property (e.g. @foo) should always be rendered
  21357. // in the context of the component and not the parent. Therefore there is a special
  21358. // compatibility instruction available for this purpose.
  21359. instruction = Identifiers.syntheticHostProperty;
  21360. }
  21361. else {
  21362. instruction = Identifiers.hostProperty;
  21363. }
  21364. }
  21365. return { bindingName: bindingName, instruction: instruction, isAttribute: !!attrMatches };
  21366. }
  21367. function createHostListeners(eventBindings, name) {
  21368. var listeners = [];
  21369. var syntheticListeners = [];
  21370. var instructions = [];
  21371. eventBindings.forEach(function (binding) {
  21372. var bindingName = binding.name && sanitizeIdentifier(binding.name);
  21373. var bindingFnName = binding.type === 1 /* Animation */ ?
  21374. prepareSyntheticListenerFunctionName(bindingName, binding.targetOrPhase) :
  21375. bindingName;
  21376. var handlerName = name && bindingName ? name + "_" + bindingFnName + "_HostBindingHandler" : null;
  21377. var params = prepareEventListenerParameters(BoundEvent.fromParsedEvent(binding), handlerName);
  21378. if (binding.type == 1 /* Animation */) {
  21379. syntheticListeners.push(params);
  21380. }
  21381. else {
  21382. listeners.push(params);
  21383. }
  21384. });
  21385. if (syntheticListeners.length > 0) {
  21386. instructions.push(chainedInstruction(Identifiers.syntheticHostListener, syntheticListeners).toStmt());
  21387. }
  21388. if (listeners.length > 0) {
  21389. instructions.push(chainedInstruction(Identifiers.listener, listeners).toStmt());
  21390. }
  21391. return instructions;
  21392. }
  21393. function metadataAsSummary(meta) {
  21394. // clang-format off
  21395. return {
  21396. // This is used by the BindingParser, which only deals with listeners and properties. There's no
  21397. // need to pass attributes to it.
  21398. hostAttributes: {},
  21399. hostListeners: meta.listeners,
  21400. hostProperties: meta.properties,
  21401. };
  21402. // clang-format on
  21403. }
  21404. var HOST_REG_EXP$1 = /^(?:\[([^\]]+)\])|(?:\(([^\)]+)\))$/;
  21405. function parseHostBindings(host) {
  21406. var e_4, _a;
  21407. var attributes = {};
  21408. var listeners = {};
  21409. var properties = {};
  21410. var specialAttributes = {};
  21411. try {
  21412. for (var _b = __values(Object.keys(host)), _c = _b.next(); !_c.done; _c = _b.next()) {
  21413. var key = _c.value;
  21414. var value = host[key];
  21415. var matches = key.match(HOST_REG_EXP$1);
  21416. if (matches === null) {
  21417. switch (key) {
  21418. case 'class':
  21419. if (typeof value !== 'string') {
  21420. // TODO(alxhub): make this a diagnostic.
  21421. throw new Error("Class binding must be string");
  21422. }
  21423. specialAttributes.classAttr = value;
  21424. break;
  21425. case 'style':
  21426. if (typeof value !== 'string') {
  21427. // TODO(alxhub): make this a diagnostic.
  21428. throw new Error("Style binding must be string");
  21429. }
  21430. specialAttributes.styleAttr = value;
  21431. break;
  21432. default:
  21433. if (typeof value === 'string') {
  21434. attributes[key] = literal(value);
  21435. }
  21436. else {
  21437. attributes[key] = value;
  21438. }
  21439. }
  21440. }
  21441. else if (matches[1 /* Binding */] != null) {
  21442. if (typeof value !== 'string') {
  21443. // TODO(alxhub): make this a diagnostic.
  21444. throw new Error("Property binding must be string");
  21445. }
  21446. // synthetic properties (the ones that have a `@` as a prefix)
  21447. // are still treated the same as regular properties. Therefore
  21448. // there is no point in storing them in a separate map.
  21449. properties[matches[1 /* Binding */]] = value;
  21450. }
  21451. else if (matches[2 /* Event */] != null) {
  21452. if (typeof value !== 'string') {
  21453. // TODO(alxhub): make this a diagnostic.
  21454. throw new Error("Event binding must be string");
  21455. }
  21456. listeners[matches[2 /* Event */]] = value;
  21457. }
  21458. }
  21459. }
  21460. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  21461. finally {
  21462. try {
  21463. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  21464. }
  21465. finally { if (e_4) throw e_4.error; }
  21466. }
  21467. return { attributes: attributes, listeners: listeners, properties: properties, specialAttributes: specialAttributes };
  21468. }
  21469. /**
  21470. * Verifies host bindings and returns the list of errors (if any). Empty array indicates that a
  21471. * given set of host bindings has no errors.
  21472. *
  21473. * @param bindings set of host bindings to verify.
  21474. * @param sourceSpan source span where host bindings were defined.
  21475. * @returns array of errors associated with a given set of host bindings.
  21476. */
  21477. function verifyHostBindings(bindings, sourceSpan) {
  21478. var summary = metadataAsSummary(bindings);
  21479. // TODO: abstract out host bindings verification logic and use it instead of
  21480. // creating events and properties ASTs to detect errors (FW-996)
  21481. var bindingParser = makeBindingParser();
  21482. bindingParser.createDirectiveHostEventAsts(summary, sourceSpan);
  21483. bindingParser.createBoundHostProperties(summary, sourceSpan);
  21484. return bindingParser.errors;
  21485. }
  21486. function compileStyles(styles, selector, hostSelector) {
  21487. var shadowCss = new ShadowCss();
  21488. return styles.map(function (style) {
  21489. return shadowCss.shimCssText(style, selector, hostSelector);
  21490. });
  21491. }
  21492. /**
  21493. * @license
  21494. * Copyright Google LLC All Rights Reserved.
  21495. *
  21496. * Use of this source code is governed by an MIT-style license that can be
  21497. * found in the LICENSE file at https://angular.io/license
  21498. */
  21499. /**
  21500. * An interface for retrieving documents by URL that the compiler uses
  21501. * to load templates.
  21502. */
  21503. var ResourceLoader = /** @class */ (function () {
  21504. function ResourceLoader() {
  21505. }
  21506. ResourceLoader.prototype.get = function (url) {
  21507. return '';
  21508. };
  21509. return ResourceLoader;
  21510. }());
  21511. var CompilerFacadeImpl = /** @class */ (function () {
  21512. function CompilerFacadeImpl(jitEvaluator) {
  21513. if (jitEvaluator === void 0) { jitEvaluator = new JitEvaluator(); }
  21514. this.jitEvaluator = jitEvaluator;
  21515. this.FactoryTarget = exports.FactoryTarget;
  21516. this.ResourceLoader = ResourceLoader;
  21517. this.elementSchemaRegistry = new DomElementSchemaRegistry();
  21518. }
  21519. CompilerFacadeImpl.prototype.compilePipe = function (angularCoreEnv, sourceMapUrl, facade) {
  21520. var metadata = {
  21521. name: facade.name,
  21522. type: wrapReference(facade.type),
  21523. internalType: new WrappedNodeExpr(facade.type),
  21524. typeArgumentCount: 0,
  21525. deps: null,
  21526. pipeName: facade.pipeName,
  21527. pure: facade.pure,
  21528. };
  21529. var res = compilePipeFromMetadata(metadata);
  21530. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
  21531. };
  21532. CompilerFacadeImpl.prototype.compilePipeDeclaration = function (angularCoreEnv, sourceMapUrl, declaration) {
  21533. var meta = convertDeclarePipeFacadeToMetadata(declaration);
  21534. var res = compilePipeFromMetadata(meta);
  21535. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
  21536. };
  21537. CompilerFacadeImpl.prototype.compileInjectable = function (angularCoreEnv, sourceMapUrl, facade) {
  21538. var _a;
  21539. var _j = compileInjectable({
  21540. name: facade.name,
  21541. type: wrapReference(facade.type),
  21542. internalType: new WrappedNodeExpr(facade.type),
  21543. typeArgumentCount: facade.typeArgumentCount,
  21544. providedIn: computeProvidedIn(facade.providedIn),
  21545. useClass: convertToProviderExpression(facade, USE_CLASS),
  21546. useFactory: wrapExpression(facade, USE_FACTORY),
  21547. useValue: convertToProviderExpression(facade, USE_VALUE),
  21548. useExisting: convertToProviderExpression(facade, USE_EXISTING),
  21549. deps: (_a = facade.deps) === null || _a === void 0 ? void 0 : _a.map(convertR3DependencyMetadata),
  21550. },
  21551. /* resolveForwardRefs */ true), expression = _j.expression, statements = _j.statements;
  21552. return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
  21553. };
  21554. CompilerFacadeImpl.prototype.compileInjectableDeclaration = function (angularCoreEnv, sourceMapUrl, facade) {
  21555. var _a;
  21556. var _j = compileInjectable({
  21557. name: facade.type.name,
  21558. type: wrapReference(facade.type),
  21559. internalType: new WrappedNodeExpr(facade.type),
  21560. typeArgumentCount: 0,
  21561. providedIn: computeProvidedIn(facade.providedIn),
  21562. useClass: convertToProviderExpression(facade, USE_CLASS),
  21563. useFactory: wrapExpression(facade, USE_FACTORY),
  21564. useValue: convertToProviderExpression(facade, USE_VALUE),
  21565. useExisting: convertToProviderExpression(facade, USE_EXISTING),
  21566. deps: (_a = facade.deps) === null || _a === void 0 ? void 0 : _a.map(convertR3DeclareDependencyMetadata),
  21567. },
  21568. /* resolveForwardRefs */ true), expression = _j.expression, statements = _j.statements;
  21569. return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
  21570. };
  21571. CompilerFacadeImpl.prototype.compileInjector = function (angularCoreEnv, sourceMapUrl, facade) {
  21572. var meta = {
  21573. name: facade.name,
  21574. type: wrapReference(facade.type),
  21575. internalType: new WrappedNodeExpr(facade.type),
  21576. providers: new WrappedNodeExpr(facade.providers),
  21577. imports: facade.imports.map(function (i) { return new WrappedNodeExpr(i); }),
  21578. };
  21579. var res = compileInjector(meta);
  21580. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
  21581. };
  21582. CompilerFacadeImpl.prototype.compileInjectorDeclaration = function (angularCoreEnv, sourceMapUrl, declaration) {
  21583. var meta = convertDeclareInjectorFacadeToMetadata(declaration);
  21584. var res = compileInjector(meta);
  21585. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
  21586. };
  21587. CompilerFacadeImpl.prototype.compileNgModule = function (angularCoreEnv, sourceMapUrl, facade) {
  21588. var meta = {
  21589. type: wrapReference(facade.type),
  21590. internalType: new WrappedNodeExpr(facade.type),
  21591. adjacentType: new WrappedNodeExpr(facade.type),
  21592. bootstrap: facade.bootstrap.map(wrapReference),
  21593. declarations: facade.declarations.map(wrapReference),
  21594. imports: facade.imports.map(wrapReference),
  21595. exports: facade.exports.map(wrapReference),
  21596. emitInline: true,
  21597. containsForwardDecls: false,
  21598. schemas: facade.schemas ? facade.schemas.map(wrapReference) : null,
  21599. id: facade.id ? new WrappedNodeExpr(facade.id) : null,
  21600. };
  21601. var res = compileNgModule(meta);
  21602. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
  21603. };
  21604. CompilerFacadeImpl.prototype.compileNgModuleDeclaration = function (angularCoreEnv, sourceMapUrl, declaration) {
  21605. var expression = compileNgModuleDeclarationExpression(declaration);
  21606. return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, []);
  21607. };
  21608. CompilerFacadeImpl.prototype.compileDirective = function (angularCoreEnv, sourceMapUrl, facade) {
  21609. var meta = convertDirectiveFacadeToMetadata(facade);
  21610. return this.compileDirectiveFromMeta(angularCoreEnv, sourceMapUrl, meta);
  21611. };
  21612. CompilerFacadeImpl.prototype.compileDirectiveDeclaration = function (angularCoreEnv, sourceMapUrl, declaration) {
  21613. var typeSourceSpan = this.createParseSourceSpan('Directive', declaration.type.name, sourceMapUrl);
  21614. var meta = convertDeclareDirectiveFacadeToMetadata(declaration, typeSourceSpan);
  21615. return this.compileDirectiveFromMeta(angularCoreEnv, sourceMapUrl, meta);
  21616. };
  21617. CompilerFacadeImpl.prototype.compileDirectiveFromMeta = function (angularCoreEnv, sourceMapUrl, meta) {
  21618. var constantPool = new ConstantPool();
  21619. var bindingParser = makeBindingParser();
  21620. var res = compileDirectiveFromMetadata(meta, constantPool, bindingParser);
  21621. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, constantPool.statements);
  21622. };
  21623. CompilerFacadeImpl.prototype.compileComponent = function (angularCoreEnv, sourceMapUrl, facade) {
  21624. // Parse the template and check for errors.
  21625. var _j = parseJitTemplate(facade.template, facade.name, sourceMapUrl, facade.preserveWhitespaces, facade.interpolation), template = _j.template, interpolation = _j.interpolation;
  21626. // Compile the component metadata, including template, into an expression.
  21627. var meta = Object.assign(Object.assign(Object.assign({}, facade), convertDirectiveFacadeToMetadata(facade)), { selector: facade.selector || this.elementSchemaRegistry.getDefaultComponentElementName(), template: template, declarationListEmitMode: 0 /* Direct */, styles: __spreadArray(__spreadArray([], __read(facade.styles)), __read(template.styles)), encapsulation: facade.encapsulation, interpolation: interpolation, changeDetection: facade.changeDetection, animations: facade.animations != null ? new WrappedNodeExpr(facade.animations) : null, viewProviders: facade.viewProviders != null ? new WrappedNodeExpr(facade.viewProviders) :
  21628. null, relativeContextFilePath: '', i18nUseExternalIds: true });
  21629. var jitExpressionSourceMap = "ng:///" + facade.name + ".js";
  21630. return this.compileComponentFromMeta(angularCoreEnv, jitExpressionSourceMap, meta);
  21631. };
  21632. CompilerFacadeImpl.prototype.compileComponentDeclaration = function (angularCoreEnv, sourceMapUrl, declaration) {
  21633. var typeSourceSpan = this.createParseSourceSpan('Component', declaration.type.name, sourceMapUrl);
  21634. var meta = convertDeclareComponentFacadeToMetadata(declaration, typeSourceSpan, sourceMapUrl);
  21635. return this.compileComponentFromMeta(angularCoreEnv, sourceMapUrl, meta);
  21636. };
  21637. CompilerFacadeImpl.prototype.compileComponentFromMeta = function (angularCoreEnv, sourceMapUrl, meta) {
  21638. var constantPool = new ConstantPool();
  21639. var bindingParser = makeBindingParser(meta.interpolation);
  21640. var res = compileComponentFromMetadata(meta, constantPool, bindingParser);
  21641. return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, constantPool.statements);
  21642. };
  21643. CompilerFacadeImpl.prototype.compileFactory = function (angularCoreEnv, sourceMapUrl, meta) {
  21644. var factoryRes = compileFactoryFunction({
  21645. name: meta.name,
  21646. type: wrapReference(meta.type),
  21647. internalType: new WrappedNodeExpr(meta.type),
  21648. typeArgumentCount: meta.typeArgumentCount,
  21649. deps: convertR3DependencyMetadataArray(meta.deps),
  21650. target: meta.target,
  21651. });
  21652. return this.jitExpression(factoryRes.expression, angularCoreEnv, sourceMapUrl, factoryRes.statements);
  21653. };
  21654. CompilerFacadeImpl.prototype.compileFactoryDeclaration = function (angularCoreEnv, sourceMapUrl, meta) {
  21655. var factoryRes = compileFactoryFunction({
  21656. name: meta.type.name,
  21657. type: wrapReference(meta.type),
  21658. internalType: new WrappedNodeExpr(meta.type),
  21659. typeArgumentCount: 0,
  21660. deps: meta.deps && meta.deps.map(convertR3DeclareDependencyMetadata),
  21661. target: meta.target,
  21662. });
  21663. return this.jitExpression(factoryRes.expression, angularCoreEnv, sourceMapUrl, factoryRes.statements);
  21664. };
  21665. CompilerFacadeImpl.prototype.createParseSourceSpan = function (kind, typeName, sourceUrl) {
  21666. return r3JitTypeSourceSpan(kind, typeName, sourceUrl);
  21667. };
  21668. /**
  21669. * JIT compiles an expression and returns the result of executing that expression.
  21670. *
  21671. * @param def the definition which will be compiled and executed to get the value to patch
  21672. * @param context an object map of @angular/core symbol names to symbols which will be available
  21673. * in the context of the compiled expression
  21674. * @param sourceUrl a URL to use for the source map of the compiled expression
  21675. * @param preStatements a collection of statements that should be evaluated before the expression.
  21676. */
  21677. CompilerFacadeImpl.prototype.jitExpression = function (def, context, sourceUrl, preStatements) {
  21678. // The ConstantPool may contain Statements which declare variables used in the final expression.
  21679. // Therefore, its statements need to precede the actual JIT operation. The final statement is a
  21680. // declaration of $def which is set to the expression being compiled.
  21681. var statements = __spreadArray(__spreadArray([], __read(preStatements)), [
  21682. new DeclareVarStmt('$def', def, undefined, [exports.StmtModifier.Exported]),
  21683. ]);
  21684. var res = this.jitEvaluator.evaluateStatements(sourceUrl, statements, new R3JitReflector(context), /* enableSourceMaps */ true);
  21685. return res['$def'];
  21686. };
  21687. return CompilerFacadeImpl;
  21688. }());
  21689. var USE_CLASS = Object.keys({ useClass: null })[0];
  21690. var USE_FACTORY = Object.keys({ useFactory: null })[0];
  21691. var USE_VALUE = Object.keys({ useValue: null })[0];
  21692. var USE_EXISTING = Object.keys({ useExisting: null })[0];
  21693. function convertToR3QueryMetadata(facade) {
  21694. return Object.assign(Object.assign({}, facade), { predicate: Array.isArray(facade.predicate) ? facade.predicate :
  21695. new WrappedNodeExpr(facade.predicate), read: facade.read ? new WrappedNodeExpr(facade.read) : null, static: facade.static, emitDistinctChangesOnly: facade.emitDistinctChangesOnly });
  21696. }
  21697. function convertQueryDeclarationToMetadata(declaration) {
  21698. var _a, _b, _c, _d;
  21699. return {
  21700. propertyName: declaration.propertyName,
  21701. first: (_a = declaration.first) !== null && _a !== void 0 ? _a : false,
  21702. predicate: Array.isArray(declaration.predicate) ? declaration.predicate :
  21703. new WrappedNodeExpr(declaration.predicate),
  21704. descendants: (_b = declaration.descendants) !== null && _b !== void 0 ? _b : false,
  21705. read: declaration.read ? new WrappedNodeExpr(declaration.read) : null,
  21706. static: (_c = declaration.static) !== null && _c !== void 0 ? _c : false,
  21707. emitDistinctChangesOnly: (_d = declaration.emitDistinctChangesOnly) !== null && _d !== void 0 ? _d : true,
  21708. };
  21709. }
  21710. function convertDirectiveFacadeToMetadata(facade) {
  21711. var inputsFromMetadata = parseInputOutputs(facade.inputs || []);
  21712. var outputsFromMetadata = parseInputOutputs(facade.outputs || []);
  21713. var propMetadata = facade.propMetadata;
  21714. var inputsFromType = {};
  21715. var outputsFromType = {};
  21716. var _loop_1 = function (field) {
  21717. if (propMetadata.hasOwnProperty(field)) {
  21718. propMetadata[field].forEach(function (ann) {
  21719. if (isInput(ann)) {
  21720. inputsFromType[field] =
  21721. ann.bindingPropertyName ? [ann.bindingPropertyName, field] : field;
  21722. }
  21723. else if (isOutput(ann)) {
  21724. outputsFromType[field] = ann.bindingPropertyName || field;
  21725. }
  21726. });
  21727. }
  21728. };
  21729. for (var field in propMetadata) {
  21730. _loop_1(field);
  21731. }
  21732. return Object.assign(Object.assign({}, facade), { typeArgumentCount: 0, typeSourceSpan: facade.typeSourceSpan, type: wrapReference(facade.type), internalType: new WrappedNodeExpr(facade.type), deps: null, host: extractHostBindings(facade.propMetadata, facade.typeSourceSpan, facade.host), inputs: Object.assign(Object.assign({}, inputsFromMetadata), inputsFromType), outputs: Object.assign(Object.assign({}, outputsFromMetadata), outputsFromType), queries: facade.queries.map(convertToR3QueryMetadata), providers: facade.providers != null ? new WrappedNodeExpr(facade.providers) : null, viewQueries: facade.viewQueries.map(convertToR3QueryMetadata), fullInheritance: false });
  21733. }
  21734. function convertDeclareDirectiveFacadeToMetadata(declaration, typeSourceSpan) {
  21735. var _a, _b, _c, _d, _e, _f, _g, _h;
  21736. return {
  21737. name: declaration.type.name,
  21738. type: wrapReference(declaration.type),
  21739. typeSourceSpan: typeSourceSpan,
  21740. internalType: new WrappedNodeExpr(declaration.type),
  21741. selector: (_a = declaration.selector) !== null && _a !== void 0 ? _a : null,
  21742. inputs: (_b = declaration.inputs) !== null && _b !== void 0 ? _b : {},
  21743. outputs: (_c = declaration.outputs) !== null && _c !== void 0 ? _c : {},
  21744. host: convertHostDeclarationToMetadata(declaration.host),
  21745. queries: ((_d = declaration.queries) !== null && _d !== void 0 ? _d : []).map(convertQueryDeclarationToMetadata),
  21746. viewQueries: ((_e = declaration.viewQueries) !== null && _e !== void 0 ? _e : []).map(convertQueryDeclarationToMetadata),
  21747. providers: declaration.providers !== undefined ? new WrappedNodeExpr(declaration.providers) :
  21748. null,
  21749. exportAs: (_f = declaration.exportAs) !== null && _f !== void 0 ? _f : null,
  21750. usesInheritance: (_g = declaration.usesInheritance) !== null && _g !== void 0 ? _g : false,
  21751. lifecycle: { usesOnChanges: (_h = declaration.usesOnChanges) !== null && _h !== void 0 ? _h : false },
  21752. deps: null,
  21753. typeArgumentCount: 0,
  21754. fullInheritance: false,
  21755. };
  21756. }
  21757. function convertHostDeclarationToMetadata(host) {
  21758. if (host === void 0) { host = {}; }
  21759. var _a, _b, _c;
  21760. return {
  21761. attributes: convertOpaqueValuesToExpressions((_a = host.attributes) !== null && _a !== void 0 ? _a : {}),
  21762. listeners: (_b = host.listeners) !== null && _b !== void 0 ? _b : {},
  21763. properties: (_c = host.properties) !== null && _c !== void 0 ? _c : {},
  21764. specialAttributes: {
  21765. classAttr: host.classAttribute,
  21766. styleAttr: host.styleAttribute,
  21767. },
  21768. };
  21769. }
  21770. function convertOpaqueValuesToExpressions(obj) {
  21771. var e_1, _j;
  21772. var result = {};
  21773. try {
  21774. for (var _k = __values(Object.keys(obj)), _l = _k.next(); !_l.done; _l = _k.next()) {
  21775. var key = _l.value;
  21776. result[key] = new WrappedNodeExpr(obj[key]);
  21777. }
  21778. }
  21779. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  21780. finally {
  21781. try {
  21782. if (_l && !_l.done && (_j = _k.return)) _j.call(_k);
  21783. }
  21784. finally { if (e_1) throw e_1.error; }
  21785. }
  21786. return result;
  21787. }
  21788. function convertDeclareComponentFacadeToMetadata(declaration, typeSourceSpan, sourceMapUrl) {
  21789. var _a, _b, _c, _d, _e, _f;
  21790. var _j = parseJitTemplate(declaration.template, declaration.type.name, sourceMapUrl, (_a = declaration.preserveWhitespaces) !== null && _a !== void 0 ? _a : false, declaration.interpolation), template = _j.template, interpolation = _j.interpolation;
  21791. return Object.assign(Object.assign({}, convertDeclareDirectiveFacadeToMetadata(declaration, typeSourceSpan)), { template: template, styles: (_b = declaration.styles) !== null && _b !== void 0 ? _b : [], directives: ((_c = declaration.components) !== null && _c !== void 0 ? _c : [])
  21792. .concat((_d = declaration.directives) !== null && _d !== void 0 ? _d : [])
  21793. .map(convertUsedDirectiveDeclarationToMetadata), pipes: convertUsedPipesToMetadata(declaration.pipes), viewProviders: declaration.viewProviders !== undefined ?
  21794. new WrappedNodeExpr(declaration.viewProviders) :
  21795. null, animations: declaration.animations !== undefined ? new WrappedNodeExpr(declaration.animations) :
  21796. null, changeDetection: (_e = declaration.changeDetection) !== null && _e !== void 0 ? _e : ChangeDetectionStrategy.Default, encapsulation: (_f = declaration.encapsulation) !== null && _f !== void 0 ? _f : ViewEncapsulation.Emulated, interpolation: interpolation, declarationListEmitMode: 2 /* ClosureResolved */, relativeContextFilePath: '', i18nUseExternalIds: true });
  21797. }
  21798. function convertUsedDirectiveDeclarationToMetadata(declaration) {
  21799. var _a, _b, _c;
  21800. return {
  21801. selector: declaration.selector,
  21802. type: new WrappedNodeExpr(declaration.type),
  21803. inputs: (_a = declaration.inputs) !== null && _a !== void 0 ? _a : [],
  21804. outputs: (_b = declaration.outputs) !== null && _b !== void 0 ? _b : [],
  21805. exportAs: (_c = declaration.exportAs) !== null && _c !== void 0 ? _c : null,
  21806. };
  21807. }
  21808. function convertUsedPipesToMetadata(declaredPipes) {
  21809. var e_2, _j;
  21810. var pipes = new Map();
  21811. if (declaredPipes === undefined) {
  21812. return pipes;
  21813. }
  21814. try {
  21815. for (var _k = __values(Object.keys(declaredPipes)), _l = _k.next(); !_l.done; _l = _k.next()) {
  21816. var pipeName = _l.value;
  21817. var pipeType = declaredPipes[pipeName];
  21818. pipes.set(pipeName, new WrappedNodeExpr(pipeType));
  21819. }
  21820. }
  21821. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  21822. finally {
  21823. try {
  21824. if (_l && !_l.done && (_j = _k.return)) _j.call(_k);
  21825. }
  21826. finally { if (e_2) throw e_2.error; }
  21827. }
  21828. return pipes;
  21829. }
  21830. function parseJitTemplate(template, typeName, sourceMapUrl, preserveWhitespaces, interpolation) {
  21831. var interpolationConfig = interpolation ? InterpolationConfig.fromArray(interpolation) : DEFAULT_INTERPOLATION_CONFIG;
  21832. // Parse the template and check for errors.
  21833. var parsed = parseTemplate(template, sourceMapUrl, { preserveWhitespaces: preserveWhitespaces, interpolationConfig: interpolationConfig });
  21834. if (parsed.errors !== null) {
  21835. var errors = parsed.errors.map(function (err) { return err.toString(); }).join(', ');
  21836. throw new Error("Errors during JIT compilation of template for " + typeName + ": " + errors);
  21837. }
  21838. return { template: parsed, interpolation: interpolationConfig };
  21839. }
  21840. /**
  21841. * Convert the expression, if present to an `R3ProviderExpression`.
  21842. *
  21843. * In JIT mode we do not want the compiler to wrap the expression in a `forwardRef()` call because,
  21844. * if it is referencing a type that has not yet been defined, it will have already been wrapped in
  21845. * a `forwardRef()` - either by the application developer or during partial-compilation. Thus we can
  21846. * set `isForwardRef` to `false`.
  21847. */
  21848. function convertToProviderExpression(obj, property) {
  21849. if (obj.hasOwnProperty(property)) {
  21850. return createR3ProviderExpression(new WrappedNodeExpr(obj[property]), /* isForwardRef */ false);
  21851. }
  21852. else {
  21853. return undefined;
  21854. }
  21855. }
  21856. function wrapExpression(obj, property) {
  21857. if (obj.hasOwnProperty(property)) {
  21858. return new WrappedNodeExpr(obj[property]);
  21859. }
  21860. else {
  21861. return undefined;
  21862. }
  21863. }
  21864. function computeProvidedIn(providedIn) {
  21865. var expression = (providedIn == null || typeof providedIn === 'string') ?
  21866. new LiteralExpr(providedIn !== null && providedIn !== void 0 ? providedIn : null) :
  21867. new WrappedNodeExpr(providedIn);
  21868. // See `convertToProviderExpression()` for why `isForwardRef` is false.
  21869. return createR3ProviderExpression(expression, /* isForwardRef */ false);
  21870. }
  21871. function convertR3DependencyMetadataArray(facades) {
  21872. return facades == null ? null : facades.map(convertR3DependencyMetadata);
  21873. }
  21874. function convertR3DependencyMetadata(facade) {
  21875. var isAttributeDep = facade.attribute != null; // both `null` and `undefined`
  21876. var rawToken = facade.token === null ? null : new WrappedNodeExpr(facade.token);
  21877. // In JIT mode, if the dep is an `@Attribute()` then we use the attribute name given in
  21878. // `attribute` rather than the `token`.
  21879. var token = isAttributeDep ? new WrappedNodeExpr(facade.attribute) : rawToken;
  21880. return createR3DependencyMetadata(token, isAttributeDep, facade.host, facade.optional, facade.self, facade.skipSelf);
  21881. }
  21882. function convertR3DeclareDependencyMetadata(facade) {
  21883. var _a, _b, _c, _d, _e;
  21884. var isAttributeDep = (_a = facade.attribute) !== null && _a !== void 0 ? _a : false;
  21885. var token = facade.token === null ? null : new WrappedNodeExpr(facade.token);
  21886. return createR3DependencyMetadata(token, isAttributeDep, (_b = facade.host) !== null && _b !== void 0 ? _b : false, (_c = facade.optional) !== null && _c !== void 0 ? _c : false, (_d = facade.self) !== null && _d !== void 0 ? _d : false, (_e = facade.skipSelf) !== null && _e !== void 0 ? _e : false);
  21887. }
  21888. function createR3DependencyMetadata(token, isAttributeDep, host, optional, self, skipSelf) {
  21889. // If the dep is an `@Attribute()` the `attributeNameType` ought to be the `unknown` type.
  21890. // But types are not available at runtime so we just use a literal `"<unknown>"` string as a dummy
  21891. // marker.
  21892. var attributeNameType = isAttributeDep ? literal('unknown') : null;
  21893. return { token: token, attributeNameType: attributeNameType, host: host, optional: optional, self: self, skipSelf: skipSelf };
  21894. }
  21895. function extractHostBindings(propMetadata, sourceSpan, host) {
  21896. // First parse the declarations from the metadata.
  21897. var bindings = parseHostBindings(host || {});
  21898. // After that check host bindings for errors
  21899. var errors = verifyHostBindings(bindings, sourceSpan);
  21900. if (errors.length) {
  21901. throw new Error(errors.map(function (error) { return error.msg; }).join('\n'));
  21902. }
  21903. var _loop_2 = function (field) {
  21904. if (propMetadata.hasOwnProperty(field)) {
  21905. propMetadata[field].forEach(function (ann) {
  21906. if (isHostBinding(ann)) {
  21907. // Since this is a decorator, we know that the value is a class member. Always access it
  21908. // through `this` so that further down the line it can't be confused for a literal value
  21909. // (e.g. if there's a property called `true`).
  21910. bindings.properties[ann.hostPropertyName || field] =
  21911. getSafePropertyAccessString('this', field);
  21912. }
  21913. else if (isHostListener(ann)) {
  21914. bindings.listeners[ann.eventName || field] = field + "(" + (ann.args || []).join(',') + ")";
  21915. }
  21916. });
  21917. }
  21918. };
  21919. // Next, loop over the properties of the object, looking for @HostBinding and @HostListener.
  21920. for (var field in propMetadata) {
  21921. _loop_2(field);
  21922. }
  21923. return bindings;
  21924. }
  21925. function isHostBinding(value) {
  21926. return value.ngMetadataName === 'HostBinding';
  21927. }
  21928. function isHostListener(value) {
  21929. return value.ngMetadataName === 'HostListener';
  21930. }
  21931. function isInput(value) {
  21932. return value.ngMetadataName === 'Input';
  21933. }
  21934. function isOutput(value) {
  21935. return value.ngMetadataName === 'Output';
  21936. }
  21937. function parseInputOutputs(values) {
  21938. return values.reduce(function (map, value) {
  21939. var _j = __read(value.split(',').map(function (piece) { return piece.trim(); }), 2), field = _j[0], property = _j[1];
  21940. map[field] = property || field;
  21941. return map;
  21942. }, {});
  21943. }
  21944. function convertDeclarePipeFacadeToMetadata(declaration) {
  21945. var _a;
  21946. return {
  21947. name: declaration.type.name,
  21948. type: wrapReference(declaration.type),
  21949. internalType: new WrappedNodeExpr(declaration.type),
  21950. typeArgumentCount: 0,
  21951. pipeName: declaration.name,
  21952. deps: null,
  21953. pure: (_a = declaration.pure) !== null && _a !== void 0 ? _a : true,
  21954. };
  21955. }
  21956. function convertDeclareInjectorFacadeToMetadata(declaration) {
  21957. return {
  21958. name: declaration.type.name,
  21959. type: wrapReference(declaration.type),
  21960. internalType: new WrappedNodeExpr(declaration.type),
  21961. providers: declaration.providers !== undefined ? new WrappedNodeExpr(declaration.providers) :
  21962. null,
  21963. imports: declaration.imports !== undefined ?
  21964. declaration.imports.map(function (i) { return new WrappedNodeExpr(i); }) :
  21965. [],
  21966. };
  21967. }
  21968. function publishFacade(global) {
  21969. var ng = global.ng || (global.ng = {});
  21970. ng.ɵcompilerFacade = new CompilerFacadeImpl();
  21971. }
  21972. /**
  21973. * @license
  21974. * Copyright Google LLC All Rights Reserved.
  21975. *
  21976. * Use of this source code is governed by an MIT-style license that can be
  21977. * found in the LICENSE file at https://angular.io/license
  21978. */
  21979. var VERSION$1 = new Version('12.0.5');
  21980. /**
  21981. * @license
  21982. * Copyright Google LLC All Rights Reserved.
  21983. *
  21984. * Use of this source code is governed by an MIT-style license that can be
  21985. * found in the LICENSE file at https://angular.io/license
  21986. */
  21987. var CompilerConfig = /** @class */ (function () {
  21988. function CompilerConfig(_a) {
  21989. var _b = _a === void 0 ? {} : _a, _c = _b.defaultEncapsulation, defaultEncapsulation = _c === void 0 ? ViewEncapsulation.Emulated : _c, _d = _b.useJit, useJit = _d === void 0 ? true : _d, _e = _b.jitDevMode, jitDevMode = _e === void 0 ? false : _e, _f = _b.missingTranslation, missingTranslation = _f === void 0 ? null : _f, preserveWhitespaces = _b.preserveWhitespaces, strictInjectionParameters = _b.strictInjectionParameters;
  21990. this.defaultEncapsulation = defaultEncapsulation;
  21991. this.useJit = !!useJit;
  21992. this.jitDevMode = !!jitDevMode;
  21993. this.missingTranslation = missingTranslation;
  21994. this.preserveWhitespaces = preserveWhitespacesDefault(noUndefined(preserveWhitespaces));
  21995. this.strictInjectionParameters = strictInjectionParameters === true;
  21996. }
  21997. return CompilerConfig;
  21998. }());
  21999. function preserveWhitespacesDefault(preserveWhitespacesOption, defaultSetting) {
  22000. if (defaultSetting === void 0) { defaultSetting = false; }
  22001. return preserveWhitespacesOption === null ? defaultSetting : preserveWhitespacesOption;
  22002. }
  22003. var DirectiveNormalizer = /** @class */ (function () {
  22004. function DirectiveNormalizer(_resourceLoader, _urlResolver, _htmlParser, _config) {
  22005. this._resourceLoader = _resourceLoader;
  22006. this._urlResolver = _urlResolver;
  22007. this._htmlParser = _htmlParser;
  22008. this._config = _config;
  22009. this._resourceLoaderCache = new Map();
  22010. }
  22011. DirectiveNormalizer.prototype.clearCache = function () {
  22012. this._resourceLoaderCache.clear();
  22013. };
  22014. DirectiveNormalizer.prototype.clearCacheFor = function (normalizedDirective) {
  22015. var _this = this;
  22016. if (!normalizedDirective.isComponent) {
  22017. return;
  22018. }
  22019. var template = normalizedDirective.template;
  22020. this._resourceLoaderCache.delete(template.templateUrl);
  22021. template.externalStylesheets.forEach(function (stylesheet) {
  22022. _this._resourceLoaderCache.delete(stylesheet.moduleUrl);
  22023. });
  22024. };
  22025. DirectiveNormalizer.prototype._fetch = function (url) {
  22026. var result = this._resourceLoaderCache.get(url);
  22027. if (!result) {
  22028. result = this._resourceLoader.get(url);
  22029. this._resourceLoaderCache.set(url, result);
  22030. }
  22031. return result;
  22032. };
  22033. DirectiveNormalizer.prototype.normalizeTemplate = function (prenormData) {
  22034. var _this = this;
  22035. if (isDefined(prenormData.template)) {
  22036. if (isDefined(prenormData.templateUrl)) {
  22037. throw syntaxError("'" + stringify(prenormData
  22038. .componentType) + "' component cannot define both template and templateUrl");
  22039. }
  22040. if (typeof prenormData.template !== 'string') {
  22041. throw syntaxError("The template specified for component " + stringify(prenormData.componentType) + " is not a string");
  22042. }
  22043. }
  22044. else if (isDefined(prenormData.templateUrl)) {
  22045. if (typeof prenormData.templateUrl !== 'string') {
  22046. throw syntaxError("The templateUrl specified for component " + stringify(prenormData.componentType) + " is not a string");
  22047. }
  22048. }
  22049. else {
  22050. throw syntaxError("No template specified for component " + stringify(prenormData.componentType));
  22051. }
  22052. if (isDefined(prenormData.preserveWhitespaces) &&
  22053. typeof prenormData.preserveWhitespaces !== 'boolean') {
  22054. throw syntaxError("The preserveWhitespaces option for component " + stringify(prenormData.componentType) + " must be a boolean");
  22055. }
  22056. return SyncAsync.then(this._preParseTemplate(prenormData), function (preparsedTemplate) { return _this._normalizeTemplateMetadata(prenormData, preparsedTemplate); });
  22057. };
  22058. DirectiveNormalizer.prototype._preParseTemplate = function (prenomData) {
  22059. var _this = this;
  22060. var template;
  22061. var templateUrl;
  22062. if (prenomData.template != null) {
  22063. template = prenomData.template;
  22064. templateUrl = prenomData.moduleUrl;
  22065. }
  22066. else {
  22067. templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, prenomData.templateUrl);
  22068. template = this._fetch(templateUrl);
  22069. }
  22070. return SyncAsync.then(template, function (template) { return _this._preparseLoadedTemplate(prenomData, template, templateUrl); });
  22071. };
  22072. DirectiveNormalizer.prototype._preparseLoadedTemplate = function (prenormData, template, templateAbsUrl) {
  22073. var isInline = !!prenormData.template;
  22074. var interpolationConfig = InterpolationConfig.fromArray(prenormData.interpolation);
  22075. var templateUrl = templateSourceUrl({ reference: prenormData.ngModuleType }, { type: { reference: prenormData.componentType } }, { isInline: isInline, templateUrl: templateAbsUrl });
  22076. var rootNodesAndErrors = this._htmlParser.parse(template, templateUrl, { tokenizeExpansionForms: true, interpolationConfig: interpolationConfig });
  22077. if (rootNodesAndErrors.errors.length > 0) {
  22078. var errorString = rootNodesAndErrors.errors.join('\n');
  22079. throw syntaxError("Template parse errors:\n" + errorString);
  22080. }
  22081. var templateMetadataStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: prenormData.styles, moduleUrl: prenormData.moduleUrl }));
  22082. var visitor = new TemplatePreparseVisitor();
  22083. visitAll$1(visitor, rootNodesAndErrors.rootNodes);
  22084. var templateStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: visitor.styles, styleUrls: visitor.styleUrls, moduleUrl: templateAbsUrl }));
  22085. var styles = templateMetadataStyles.styles.concat(templateStyles.styles);
  22086. var inlineStyleUrls = templateMetadataStyles.styleUrls.concat(templateStyles.styleUrls);
  22087. var styleUrls = this
  22088. ._normalizeStylesheet(new CompileStylesheetMetadata({ styleUrls: prenormData.styleUrls, moduleUrl: prenormData.moduleUrl }))
  22089. .styleUrls;
  22090. return {
  22091. template: template,
  22092. templateUrl: templateAbsUrl,
  22093. isInline: isInline,
  22094. htmlAst: rootNodesAndErrors,
  22095. styles: styles,
  22096. inlineStyleUrls: inlineStyleUrls,
  22097. styleUrls: styleUrls,
  22098. ngContentSelectors: visitor.ngContentSelectors,
  22099. };
  22100. };
  22101. DirectiveNormalizer.prototype._normalizeTemplateMetadata = function (prenormData, preparsedTemplate) {
  22102. var _this = this;
  22103. return SyncAsync.then(this._loadMissingExternalStylesheets(preparsedTemplate.styleUrls.concat(preparsedTemplate.inlineStyleUrls)), function (externalStylesheets) { return _this._normalizeLoadedTemplateMetadata(prenormData, preparsedTemplate, externalStylesheets); });
  22104. };
  22105. DirectiveNormalizer.prototype._normalizeLoadedTemplateMetadata = function (prenormData, preparsedTemplate, stylesheets) {
  22106. var _this = this;
  22107. // Algorithm:
  22108. // - produce exactly 1 entry per original styleUrl in
  22109. // CompileTemplateMetadata.externalStylesheets with all styles inlined
  22110. // - inline all styles that are referenced by the template into CompileTemplateMetadata.styles.
  22111. // Reason: be able to determine how many stylesheets there are even without loading
  22112. // the template nor the stylesheets, so we can create a stub for TypeScript always synchronously
  22113. // (as resource loading may be async)
  22114. var styles = __spreadArray([], __read(preparsedTemplate.styles));
  22115. this._inlineStyles(preparsedTemplate.inlineStyleUrls, stylesheets, styles);
  22116. var styleUrls = preparsedTemplate.styleUrls;
  22117. var externalStylesheets = styleUrls.map(function (styleUrl) {
  22118. var stylesheet = stylesheets.get(styleUrl);
  22119. var styles = __spreadArray([], __read(stylesheet.styles));
  22120. _this._inlineStyles(stylesheet.styleUrls, stylesheets, styles);
  22121. return new CompileStylesheetMetadata({ moduleUrl: styleUrl, styles: styles });
  22122. });
  22123. var encapsulation = prenormData.encapsulation;
  22124. if (encapsulation == null) {
  22125. encapsulation = this._config.defaultEncapsulation;
  22126. }
  22127. if (encapsulation === ViewEncapsulation.Emulated && styles.length === 0 &&
  22128. styleUrls.length === 0) {
  22129. encapsulation = ViewEncapsulation.None;
  22130. }
  22131. return new CompileTemplateMetadata({
  22132. encapsulation: encapsulation,
  22133. template: preparsedTemplate.template,
  22134. templateUrl: preparsedTemplate.templateUrl,
  22135. htmlAst: preparsedTemplate.htmlAst,
  22136. styles: styles,
  22137. styleUrls: styleUrls,
  22138. ngContentSelectors: preparsedTemplate.ngContentSelectors,
  22139. animations: prenormData.animations,
  22140. interpolation: prenormData.interpolation,
  22141. isInline: preparsedTemplate.isInline,
  22142. externalStylesheets: externalStylesheets,
  22143. preserveWhitespaces: preserveWhitespacesDefault(prenormData.preserveWhitespaces, this._config.preserveWhitespaces),
  22144. });
  22145. };
  22146. DirectiveNormalizer.prototype._inlineStyles = function (styleUrls, stylesheets, targetStyles) {
  22147. var _this = this;
  22148. styleUrls.forEach(function (styleUrl) {
  22149. var stylesheet = stylesheets.get(styleUrl);
  22150. stylesheet.styles.forEach(function (style) { return targetStyles.push(style); });
  22151. _this._inlineStyles(stylesheet.styleUrls, stylesheets, targetStyles);
  22152. });
  22153. };
  22154. DirectiveNormalizer.prototype._loadMissingExternalStylesheets = function (styleUrls, loadedStylesheets) {
  22155. var _this = this;
  22156. if (loadedStylesheets === void 0) { loadedStylesheets = new Map(); }
  22157. return SyncAsync.then(SyncAsync.all(styleUrls.filter(function (styleUrl) { return !loadedStylesheets.has(styleUrl); })
  22158. .map(function (styleUrl) { return SyncAsync.then(_this._fetch(styleUrl), function (loadedStyle) {
  22159. var stylesheet = _this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: [loadedStyle], moduleUrl: styleUrl }));
  22160. loadedStylesheets.set(styleUrl, stylesheet);
  22161. return _this._loadMissingExternalStylesheets(stylesheet.styleUrls, loadedStylesheets);
  22162. }); })), function (_) { return loadedStylesheets; });
  22163. };
  22164. DirectiveNormalizer.prototype._normalizeStylesheet = function (stylesheet) {
  22165. var _this = this;
  22166. var moduleUrl = stylesheet.moduleUrl;
  22167. var allStyleUrls = stylesheet.styleUrls.filter(isStyleUrlResolvable)
  22168. .map(function (url) { return _this._urlResolver.resolve(moduleUrl, url); });
  22169. var allStyles = stylesheet.styles.map(function (style) {
  22170. var styleWithImports = extractStyleUrls(_this._urlResolver, moduleUrl, style);
  22171. allStyleUrls.push.apply(allStyleUrls, __spreadArray([], __read(styleWithImports.styleUrls)));
  22172. return styleWithImports.style;
  22173. });
  22174. return new CompileStylesheetMetadata({ styles: allStyles, styleUrls: allStyleUrls, moduleUrl: moduleUrl });
  22175. };
  22176. return DirectiveNormalizer;
  22177. }());
  22178. var TemplatePreparseVisitor = /** @class */ (function () {
  22179. function TemplatePreparseVisitor() {
  22180. this.ngContentSelectors = [];
  22181. this.styles = [];
  22182. this.styleUrls = [];
  22183. this.ngNonBindableStackCount = 0;
  22184. }
  22185. TemplatePreparseVisitor.prototype.visitElement = function (ast, context) {
  22186. var preparsedElement = preparseElement(ast);
  22187. switch (preparsedElement.type) {
  22188. case PreparsedElementType.NG_CONTENT:
  22189. if (this.ngNonBindableStackCount === 0) {
  22190. this.ngContentSelectors.push(preparsedElement.selectAttr);
  22191. }
  22192. break;
  22193. case PreparsedElementType.STYLE:
  22194. var textContent_1 = '';
  22195. ast.children.forEach(function (child) {
  22196. if (child instanceof Text$3) {
  22197. textContent_1 += child.value;
  22198. }
  22199. });
  22200. this.styles.push(textContent_1);
  22201. break;
  22202. case PreparsedElementType.STYLESHEET:
  22203. this.styleUrls.push(preparsedElement.hrefAttr);
  22204. break;
  22205. default:
  22206. break;
  22207. }
  22208. if (preparsedElement.nonBindable) {
  22209. this.ngNonBindableStackCount++;
  22210. }
  22211. visitAll$1(this, ast.children);
  22212. if (preparsedElement.nonBindable) {
  22213. this.ngNonBindableStackCount--;
  22214. }
  22215. return null;
  22216. };
  22217. TemplatePreparseVisitor.prototype.visitExpansion = function (ast, context) {
  22218. visitAll$1(this, ast.cases);
  22219. };
  22220. TemplatePreparseVisitor.prototype.visitExpansionCase = function (ast, context) {
  22221. visitAll$1(this, ast.expression);
  22222. };
  22223. TemplatePreparseVisitor.prototype.visitComment = function (ast, context) {
  22224. return null;
  22225. };
  22226. TemplatePreparseVisitor.prototype.visitAttribute = function (ast, context) {
  22227. return null;
  22228. };
  22229. TemplatePreparseVisitor.prototype.visitText = function (ast, context) {
  22230. return null;
  22231. };
  22232. return TemplatePreparseVisitor;
  22233. }());
  22234. /**
  22235. * @license
  22236. * Copyright Google LLC All Rights Reserved.
  22237. *
  22238. * Use of this source code is governed by an MIT-style license that can be
  22239. * found in the LICENSE file at https://angular.io/license
  22240. */
  22241. var QUERY_METADATA_IDENTIFIERS = [
  22242. createViewChild,
  22243. createViewChildren,
  22244. createContentChild,
  22245. createContentChildren,
  22246. ];
  22247. /*
  22248. * Resolve a `Type` for {@link Directive}.
  22249. *
  22250. * This interface can be overridden by the application developer to create custom behavior.
  22251. *
  22252. * See {@link Compiler}
  22253. */
  22254. var DirectiveResolver = /** @class */ (function () {
  22255. function DirectiveResolver(_reflector) {
  22256. this._reflector = _reflector;
  22257. }
  22258. DirectiveResolver.prototype.isDirective = function (type) {
  22259. var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  22260. return typeMetadata && typeMetadata.some(isDirectiveMetadata);
  22261. };
  22262. DirectiveResolver.prototype.resolve = function (type, throwIfNotFound) {
  22263. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  22264. var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  22265. if (typeMetadata) {
  22266. var metadata = findLast(typeMetadata, isDirectiveMetadata);
  22267. if (metadata) {
  22268. var propertyMetadata = this._reflector.propMetadata(type);
  22269. var guards = this._reflector.guards(type);
  22270. return this._mergeWithPropertyMetadata(metadata, propertyMetadata, guards, type);
  22271. }
  22272. }
  22273. if (throwIfNotFound) {
  22274. throw new Error("No Directive annotation found on " + stringify(type));
  22275. }
  22276. return null;
  22277. };
  22278. DirectiveResolver.prototype._mergeWithPropertyMetadata = function (dm, propertyMetadata, guards, directiveType) {
  22279. var inputs = [];
  22280. var outputs = [];
  22281. var host = {};
  22282. var queries = {};
  22283. Object.keys(propertyMetadata).forEach(function (propName) {
  22284. var input = findLast(propertyMetadata[propName], function (a) { return createInput.isTypeOf(a); });
  22285. if (input) {
  22286. if (input.bindingPropertyName) {
  22287. inputs.push(propName + ": " + input.bindingPropertyName);
  22288. }
  22289. else {
  22290. inputs.push(propName);
  22291. }
  22292. }
  22293. var output = findLast(propertyMetadata[propName], function (a) { return createOutput.isTypeOf(a); });
  22294. if (output) {
  22295. if (output.bindingPropertyName) {
  22296. outputs.push(propName + ": " + output.bindingPropertyName);
  22297. }
  22298. else {
  22299. outputs.push(propName);
  22300. }
  22301. }
  22302. var hostBindings = propertyMetadata[propName].filter(function (a) { return createHostBinding.isTypeOf(a); });
  22303. hostBindings.forEach(function (hostBinding) {
  22304. if (hostBinding.hostPropertyName) {
  22305. var startWith = hostBinding.hostPropertyName[0];
  22306. if (startWith === '(') {
  22307. throw new Error("@HostBinding can not bind to events. Use @HostListener instead.");
  22308. }
  22309. else if (startWith === '[') {
  22310. throw new Error("@HostBinding parameter should be a property name, 'class.<name>', or 'attr.<name>'.");
  22311. }
  22312. host["[" + hostBinding.hostPropertyName + "]"] = propName;
  22313. }
  22314. else {
  22315. host["[" + propName + "]"] = propName;
  22316. }
  22317. });
  22318. var hostListeners = propertyMetadata[propName].filter(function (a) { return createHostListener.isTypeOf(a); });
  22319. hostListeners.forEach(function (hostListener) {
  22320. var args = hostListener.args || [];
  22321. host["(" + hostListener.eventName + ")"] = propName + "(" + args.join(',') + ")";
  22322. });
  22323. var query = findLast(propertyMetadata[propName], function (a) { return QUERY_METADATA_IDENTIFIERS.some(function (i) { return i.isTypeOf(a); }); });
  22324. if (query) {
  22325. queries[propName] = query;
  22326. }
  22327. });
  22328. return this._merge(dm, inputs, outputs, host, queries, guards, directiveType);
  22329. };
  22330. DirectiveResolver.prototype._extractPublicName = function (def) {
  22331. return splitAtColon(def, [null, def])[1].trim();
  22332. };
  22333. DirectiveResolver.prototype._dedupeBindings = function (bindings) {
  22334. var names = new Set();
  22335. var publicNames = new Set();
  22336. var reversedResult = [];
  22337. // go last to first to allow later entries to overwrite previous entries
  22338. for (var i = bindings.length - 1; i >= 0; i--) {
  22339. var binding = bindings[i];
  22340. var name = this._extractPublicName(binding);
  22341. publicNames.add(name);
  22342. if (!names.has(name)) {
  22343. names.add(name);
  22344. reversedResult.push(binding);
  22345. }
  22346. }
  22347. return reversedResult.reverse();
  22348. };
  22349. DirectiveResolver.prototype._merge = function (directive, inputs, outputs, host, queries, guards, directiveType) {
  22350. var mergedInputs = this._dedupeBindings(directive.inputs ? directive.inputs.concat(inputs) : inputs);
  22351. var mergedOutputs = this._dedupeBindings(directive.outputs ? directive.outputs.concat(outputs) : outputs);
  22352. var mergedHost = directive.host ? Object.assign(Object.assign({}, directive.host), host) : host;
  22353. var mergedQueries = directive.queries ? Object.assign(Object.assign({}, directive.queries), queries) : queries;
  22354. if (createComponent.isTypeOf(directive)) {
  22355. var comp = directive;
  22356. return createComponent({
  22357. selector: comp.selector,
  22358. inputs: mergedInputs,
  22359. outputs: mergedOutputs,
  22360. host: mergedHost,
  22361. exportAs: comp.exportAs,
  22362. moduleId: comp.moduleId,
  22363. queries: mergedQueries,
  22364. changeDetection: comp.changeDetection,
  22365. providers: comp.providers,
  22366. viewProviders: comp.viewProviders,
  22367. entryComponents: comp.entryComponents,
  22368. template: comp.template,
  22369. templateUrl: comp.templateUrl,
  22370. styles: comp.styles,
  22371. styleUrls: comp.styleUrls,
  22372. encapsulation: comp.encapsulation,
  22373. animations: comp.animations,
  22374. interpolation: comp.interpolation,
  22375. preserveWhitespaces: directive.preserveWhitespaces,
  22376. });
  22377. }
  22378. else {
  22379. return createDirective({
  22380. selector: directive.selector,
  22381. inputs: mergedInputs,
  22382. outputs: mergedOutputs,
  22383. host: mergedHost,
  22384. exportAs: directive.exportAs,
  22385. queries: mergedQueries,
  22386. providers: directive.providers,
  22387. guards: guards
  22388. });
  22389. }
  22390. };
  22391. return DirectiveResolver;
  22392. }());
  22393. function isDirectiveMetadata(type) {
  22394. return createDirective.isTypeOf(type) || createComponent.isTypeOf(type);
  22395. }
  22396. function findLast(arr, condition) {
  22397. for (var i = arr.length - 1; i >= 0; i--) {
  22398. if (condition(arr[i])) {
  22399. return arr[i];
  22400. }
  22401. }
  22402. return null;
  22403. }
  22404. var _I18N_ATTR = 'i18n';
  22405. var _I18N_ATTR_PREFIX = 'i18n-';
  22406. var _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
  22407. var MEANING_SEPARATOR = '|';
  22408. var ID_SEPARATOR = '@@';
  22409. var i18nCommentsWarned = false;
  22410. /**
  22411. * Extract translatable messages from an html AST
  22412. */
  22413. function extractMessages(nodes, interpolationConfig, implicitTags, implicitAttrs) {
  22414. var visitor = new _Visitor$2(implicitTags, implicitAttrs);
  22415. return visitor.extract(nodes, interpolationConfig);
  22416. }
  22417. function mergeTranslations(nodes, translations, interpolationConfig, implicitTags, implicitAttrs) {
  22418. var visitor = new _Visitor$2(implicitTags, implicitAttrs);
  22419. return visitor.merge(nodes, translations, interpolationConfig);
  22420. }
  22421. var ExtractionResult = /** @class */ (function () {
  22422. function ExtractionResult(messages, errors) {
  22423. this.messages = messages;
  22424. this.errors = errors;
  22425. }
  22426. return ExtractionResult;
  22427. }());
  22428. var _VisitorMode;
  22429. (function (_VisitorMode) {
  22430. _VisitorMode[_VisitorMode["Extract"] = 0] = "Extract";
  22431. _VisitorMode[_VisitorMode["Merge"] = 1] = "Merge";
  22432. })(_VisitorMode || (_VisitorMode = {}));
  22433. /**
  22434. * This Visitor is used:
  22435. * 1. to extract all the translatable strings from an html AST (see `extract()`),
  22436. * 2. to replace the translatable strings with the actual translations (see `merge()`)
  22437. *
  22438. * @internal
  22439. */
  22440. var _Visitor$2 = /** @class */ (function () {
  22441. function _Visitor(_implicitTags, _implicitAttrs) {
  22442. this._implicitTags = _implicitTags;
  22443. this._implicitAttrs = _implicitAttrs;
  22444. }
  22445. /**
  22446. * Extracts the messages from the tree
  22447. */
  22448. _Visitor.prototype.extract = function (nodes, interpolationConfig) {
  22449. var _this = this;
  22450. this._init(_VisitorMode.Extract, interpolationConfig);
  22451. nodes.forEach(function (node) { return node.visit(_this, null); });
  22452. if (this._inI18nBlock) {
  22453. this._reportError(nodes[nodes.length - 1], 'Unclosed block');
  22454. }
  22455. return new ExtractionResult(this._messages, this._errors);
  22456. };
  22457. /**
  22458. * Returns a tree where all translatable nodes are translated
  22459. */
  22460. _Visitor.prototype.merge = function (nodes, translations, interpolationConfig) {
  22461. this._init(_VisitorMode.Merge, interpolationConfig);
  22462. this._translations = translations;
  22463. // Construct a single fake root element
  22464. var wrapper = new Element$1('wrapper', [], nodes, undefined, undefined, undefined);
  22465. var translatedNode = wrapper.visit(this, null);
  22466. if (this._inI18nBlock) {
  22467. this._reportError(nodes[nodes.length - 1], 'Unclosed block');
  22468. }
  22469. return new ParseTreeResult(translatedNode.children, this._errors);
  22470. };
  22471. _Visitor.prototype.visitExpansionCase = function (icuCase, context) {
  22472. // Parse cases for translatable html attributes
  22473. var expression = visitAll$1(this, icuCase.expression, context);
  22474. if (this._mode === _VisitorMode.Merge) {
  22475. return new ExpansionCase(icuCase.value, expression, icuCase.sourceSpan, icuCase.valueSourceSpan, icuCase.expSourceSpan);
  22476. }
  22477. };
  22478. _Visitor.prototype.visitExpansion = function (icu, context) {
  22479. this._mayBeAddBlockChildren(icu);
  22480. var wasInIcu = this._inIcu;
  22481. if (!this._inIcu) {
  22482. // nested ICU messages should not be extracted but top-level translated as a whole
  22483. if (this._isInTranslatableSection) {
  22484. this._addMessage([icu]);
  22485. }
  22486. this._inIcu = true;
  22487. }
  22488. var cases = visitAll$1(this, icu.cases, context);
  22489. if (this._mode === _VisitorMode.Merge) {
  22490. icu = new Expansion(icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
  22491. }
  22492. this._inIcu = wasInIcu;
  22493. return icu;
  22494. };
  22495. _Visitor.prototype.visitComment = function (comment, context) {
  22496. var isOpening = _isOpeningComment(comment);
  22497. if (isOpening && this._isInTranslatableSection) {
  22498. this._reportError(comment, 'Could not start a block inside a translatable section');
  22499. return;
  22500. }
  22501. var isClosing = _isClosingComment(comment);
  22502. if (isClosing && !this._inI18nBlock) {
  22503. this._reportError(comment, 'Trying to close an unopened block');
  22504. return;
  22505. }
  22506. if (!this._inI18nNode && !this._inIcu) {
  22507. if (!this._inI18nBlock) {
  22508. if (isOpening) {
  22509. // deprecated from v5 you should use <ng-container i18n> instead of i18n comments
  22510. if (!i18nCommentsWarned && console && console.warn) {
  22511. i18nCommentsWarned = true;
  22512. var details = comment.sourceSpan.details ? ", " + comment.sourceSpan.details : '';
  22513. // TODO(ocombe): use a log service once there is a public one available
  22514. console.warn("I18n comments are deprecated, use an <ng-container> element instead (" + comment.sourceSpan.start + details + ")");
  22515. }
  22516. this._inI18nBlock = true;
  22517. this._blockStartDepth = this._depth;
  22518. this._blockChildren = [];
  22519. this._blockMeaningAndDesc =
  22520. comment.value.replace(_I18N_COMMENT_PREFIX_REGEXP, '').trim();
  22521. this._openTranslatableSection(comment);
  22522. }
  22523. }
  22524. else {
  22525. if (isClosing) {
  22526. if (this._depth == this._blockStartDepth) {
  22527. this._closeTranslatableSection(comment, this._blockChildren);
  22528. this._inI18nBlock = false;
  22529. var message = this._addMessage(this._blockChildren, this._blockMeaningAndDesc);
  22530. // merge attributes in sections
  22531. var nodes = this._translateMessage(comment, message);
  22532. return visitAll$1(this, nodes);
  22533. }
  22534. else {
  22535. this._reportError(comment, 'I18N blocks should not cross element boundaries');
  22536. return;
  22537. }
  22538. }
  22539. }
  22540. }
  22541. };
  22542. _Visitor.prototype.visitText = function (text, context) {
  22543. if (this._isInTranslatableSection) {
  22544. this._mayBeAddBlockChildren(text);
  22545. }
  22546. return text;
  22547. };
  22548. _Visitor.prototype.visitElement = function (el, context) {
  22549. var _this = this;
  22550. this._mayBeAddBlockChildren(el);
  22551. this._depth++;
  22552. var wasInI18nNode = this._inI18nNode;
  22553. var wasInImplicitNode = this._inImplicitNode;
  22554. var childNodes = [];
  22555. var translatedChildNodes = undefined;
  22556. // Extract:
  22557. // - top level nodes with the (implicit) "i18n" attribute if not already in a section
  22558. // - ICU messages
  22559. var i18nAttr = _getI18nAttr(el);
  22560. var i18nMeta = i18nAttr ? i18nAttr.value : '';
  22561. var isImplicit = this._implicitTags.some(function (tag) { return el.name === tag; }) && !this._inIcu &&
  22562. !this._isInTranslatableSection;
  22563. var isTopLevelImplicit = !wasInImplicitNode && isImplicit;
  22564. this._inImplicitNode = wasInImplicitNode || isImplicit;
  22565. if (!this._isInTranslatableSection && !this._inIcu) {
  22566. if (i18nAttr || isTopLevelImplicit) {
  22567. this._inI18nNode = true;
  22568. var message = this._addMessage(el.children, i18nMeta);
  22569. translatedChildNodes = this._translateMessage(el, message);
  22570. }
  22571. if (this._mode == _VisitorMode.Extract) {
  22572. var isTranslatable = i18nAttr || isTopLevelImplicit;
  22573. if (isTranslatable)
  22574. this._openTranslatableSection(el);
  22575. visitAll$1(this, el.children);
  22576. if (isTranslatable)
  22577. this._closeTranslatableSection(el, el.children);
  22578. }
  22579. }
  22580. else {
  22581. if (i18nAttr || isTopLevelImplicit) {
  22582. this._reportError(el, 'Could not mark an element as translatable inside a translatable section');
  22583. }
  22584. if (this._mode == _VisitorMode.Extract) {
  22585. // Descend into child nodes for extraction
  22586. visitAll$1(this, el.children);
  22587. }
  22588. }
  22589. if (this._mode === _VisitorMode.Merge) {
  22590. var visitNodes = translatedChildNodes || el.children;
  22591. visitNodes.forEach(function (child) {
  22592. var visited = child.visit(_this, context);
  22593. if (visited && !_this._isInTranslatableSection) {
  22594. // Do not add the children from translatable sections (= i18n blocks here)
  22595. // They will be added later in this loop when the block closes (i.e. on `<!-- /i18n -->`)
  22596. childNodes = childNodes.concat(visited);
  22597. }
  22598. });
  22599. }
  22600. this._visitAttributesOf(el);
  22601. this._depth--;
  22602. this._inI18nNode = wasInI18nNode;
  22603. this._inImplicitNode = wasInImplicitNode;
  22604. if (this._mode === _VisitorMode.Merge) {
  22605. var translatedAttrs = this._translateAttributes(el);
  22606. return new Element$1(el.name, translatedAttrs, childNodes, el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
  22607. }
  22608. return null;
  22609. };
  22610. _Visitor.prototype.visitAttribute = function (attribute, context) {
  22611. throw new Error('unreachable code');
  22612. };
  22613. _Visitor.prototype._init = function (mode, interpolationConfig) {
  22614. this._mode = mode;
  22615. this._inI18nBlock = false;
  22616. this._inI18nNode = false;
  22617. this._depth = 0;
  22618. this._inIcu = false;
  22619. this._msgCountAtSectionStart = undefined;
  22620. this._errors = [];
  22621. this._messages = [];
  22622. this._inImplicitNode = false;
  22623. this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
  22624. };
  22625. // looks for translatable attributes
  22626. _Visitor.prototype._visitAttributesOf = function (el) {
  22627. var _this = this;
  22628. var explicitAttrNameToValue = {};
  22629. var implicitAttrNames = this._implicitAttrs[el.name] || [];
  22630. el.attrs.filter(function (attr) { return attr.name.startsWith(_I18N_ATTR_PREFIX); })
  22631. .forEach(function (attr) { return explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
  22632. attr.value; });
  22633. el.attrs.forEach(function (attr) {
  22634. if (attr.name in explicitAttrNameToValue) {
  22635. _this._addMessage([attr], explicitAttrNameToValue[attr.name]);
  22636. }
  22637. else if (implicitAttrNames.some(function (name) { return attr.name === name; })) {
  22638. _this._addMessage([attr]);
  22639. }
  22640. });
  22641. };
  22642. // add a translatable message
  22643. _Visitor.prototype._addMessage = function (ast, msgMeta) {
  22644. if (ast.length == 0 ||
  22645. ast.length == 1 && ast[0] instanceof Attribute && !ast[0].value) {
  22646. // Do not create empty messages
  22647. return null;
  22648. }
  22649. var _a = _parseMessageMeta(msgMeta), meaning = _a.meaning, description = _a.description, id = _a.id;
  22650. var message = this._createI18nMessage(ast, meaning, description, id);
  22651. this._messages.push(message);
  22652. return message;
  22653. };
  22654. // Translates the given message given the `TranslationBundle`
  22655. // This is used for translating elements / blocks - see `_translateAttributes` for attributes
  22656. // no-op when called in extraction mode (returns [])
  22657. _Visitor.prototype._translateMessage = function (el, message) {
  22658. if (message && this._mode === _VisitorMode.Merge) {
  22659. var nodes = this._translations.get(message);
  22660. if (nodes) {
  22661. return nodes;
  22662. }
  22663. this._reportError(el, "Translation unavailable for message id=\"" + this._translations.digest(message) + "\"");
  22664. }
  22665. return [];
  22666. };
  22667. // translate the attributes of an element and remove i18n specific attributes
  22668. _Visitor.prototype._translateAttributes = function (el) {
  22669. var _this = this;
  22670. var attributes = el.attrs;
  22671. var i18nParsedMessageMeta = {};
  22672. attributes.forEach(function (attr) {
  22673. if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
  22674. i18nParsedMessageMeta[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
  22675. _parseMessageMeta(attr.value);
  22676. }
  22677. });
  22678. var translatedAttributes = [];
  22679. attributes.forEach(function (attr) {
  22680. if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
  22681. // strip i18n specific attributes
  22682. return;
  22683. }
  22684. if (attr.value && attr.value != '' && i18nParsedMessageMeta.hasOwnProperty(attr.name)) {
  22685. var _a = i18nParsedMessageMeta[attr.name], meaning = _a.meaning, description = _a.description, id = _a.id;
  22686. var message = _this._createI18nMessage([attr], meaning, description, id);
  22687. var nodes = _this._translations.get(message);
  22688. if (nodes) {
  22689. if (nodes.length == 0) {
  22690. translatedAttributes.push(new Attribute(attr.name, '', attr.sourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */));
  22691. }
  22692. else if (nodes[0] instanceof Text$3) {
  22693. var value = nodes[0].value;
  22694. translatedAttributes.push(new Attribute(attr.name, value, attr.sourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */));
  22695. }
  22696. else {
  22697. _this._reportError(el, "Unexpected translation for attribute \"" + attr.name + "\" (id=\"" + (id || _this._translations.digest(message)) + "\")");
  22698. }
  22699. }
  22700. else {
  22701. _this._reportError(el, "Translation unavailable for attribute \"" + attr.name + "\" (id=\"" + (id || _this._translations.digest(message)) + "\")");
  22702. }
  22703. }
  22704. else {
  22705. translatedAttributes.push(attr);
  22706. }
  22707. });
  22708. return translatedAttributes;
  22709. };
  22710. /**
  22711. * Add the node as a child of the block when:
  22712. * - we are in a block,
  22713. * - we are not inside a ICU message (those are handled separately),
  22714. * - the node is a "direct child" of the block
  22715. */
  22716. _Visitor.prototype._mayBeAddBlockChildren = function (node) {
  22717. if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
  22718. this._blockChildren.push(node);
  22719. }
  22720. };
  22721. /**
  22722. * Marks the start of a section, see `_closeTranslatableSection`
  22723. */
  22724. _Visitor.prototype._openTranslatableSection = function (node) {
  22725. if (this._isInTranslatableSection) {
  22726. this._reportError(node, 'Unexpected section start');
  22727. }
  22728. else {
  22729. this._msgCountAtSectionStart = this._messages.length;
  22730. }
  22731. };
  22732. Object.defineProperty(_Visitor.prototype, "_isInTranslatableSection", {
  22733. /**
  22734. * A translatable section could be:
  22735. * - the content of translatable element,
  22736. * - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
  22737. */
  22738. get: function () {
  22739. return this._msgCountAtSectionStart !== void 0;
  22740. },
  22741. enumerable: false,
  22742. configurable: true
  22743. });
  22744. /**
  22745. * Terminates a section.
  22746. *
  22747. * If a section has only one significant children (comments not significant) then we should not
  22748. * keep the message from this children:
  22749. *
  22750. * `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
  22751. * - one for the <p> content with meaning and description,
  22752. * - another one for the ICU message.
  22753. *
  22754. * In this case the last message is discarded as it contains less information (the AST is
  22755. * otherwise identical).
  22756. *
  22757. * Note that we should still keep messages extracted from attributes inside the section (ie in the
  22758. * ICU message here)
  22759. */
  22760. _Visitor.prototype._closeTranslatableSection = function (node, directChildren) {
  22761. if (!this._isInTranslatableSection) {
  22762. this._reportError(node, 'Unexpected section end');
  22763. return;
  22764. }
  22765. var startIndex = this._msgCountAtSectionStart;
  22766. var significantChildren = directChildren.reduce(function (count, node) { return count + (node instanceof Comment$1 ? 0 : 1); }, 0);
  22767. if (significantChildren == 1) {
  22768. for (var i = this._messages.length - 1; i >= startIndex; i--) {
  22769. var ast = this._messages[i].nodes;
  22770. if (!(ast.length == 1 && ast[0] instanceof Text$1)) {
  22771. this._messages.splice(i, 1);
  22772. break;
  22773. }
  22774. }
  22775. }
  22776. this._msgCountAtSectionStart = undefined;
  22777. };
  22778. _Visitor.prototype._reportError = function (node, msg) {
  22779. this._errors.push(new I18nError(node.sourceSpan, msg));
  22780. };
  22781. return _Visitor;
  22782. }());
  22783. function _isOpeningComment(n) {
  22784. return !!(n instanceof Comment$1 && n.value && n.value.startsWith('i18n'));
  22785. }
  22786. function _isClosingComment(n) {
  22787. return !!(n instanceof Comment$1 && n.value && n.value === '/i18n');
  22788. }
  22789. function _getI18nAttr(p) {
  22790. return p.attrs.find(function (attr) { return attr.name === _I18N_ATTR; }) || null;
  22791. }
  22792. function _parseMessageMeta(i18n) {
  22793. if (!i18n)
  22794. return { meaning: '', description: '', id: '' };
  22795. var idIndex = i18n.indexOf(ID_SEPARATOR);
  22796. var descIndex = i18n.indexOf(MEANING_SEPARATOR);
  22797. var _a = __read((idIndex > -1) ? [i18n.slice(0, idIndex), i18n.slice(idIndex + 2)] : [i18n, ''], 2), meaningAndDesc = _a[0], id = _a[1];
  22798. var _b = __read((descIndex > -1) ?
  22799. [meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
  22800. ['', meaningAndDesc], 2), meaning = _b[0], description = _b[1];
  22801. return { meaning: meaning, description: description, id: id.trim() };
  22802. }
  22803. /**
  22804. * @license
  22805. * Copyright Google LLC All Rights Reserved.
  22806. *
  22807. * Use of this source code is governed by an MIT-style license that can be
  22808. * found in the LICENSE file at https://angular.io/license
  22809. */
  22810. var XmlTagDefinition = /** @class */ (function () {
  22811. function XmlTagDefinition() {
  22812. this.closedByParent = false;
  22813. this.isVoid = false;
  22814. this.ignoreFirstLf = false;
  22815. this.canSelfClose = true;
  22816. this.preventNamespaceInheritance = false;
  22817. }
  22818. XmlTagDefinition.prototype.requireExtraParent = function (currentParent) {
  22819. return false;
  22820. };
  22821. XmlTagDefinition.prototype.isClosedByChild = function (name) {
  22822. return false;
  22823. };
  22824. XmlTagDefinition.prototype.getContentType = function () {
  22825. return exports.TagContentType.PARSABLE_DATA;
  22826. };
  22827. return XmlTagDefinition;
  22828. }());
  22829. var _TAG_DEFINITION = new XmlTagDefinition();
  22830. function getXmlTagDefinition(tagName) {
  22831. return _TAG_DEFINITION;
  22832. }
  22833. var XmlParser = /** @class */ (function (_super) {
  22834. __extends(XmlParser, _super);
  22835. function XmlParser() {
  22836. return _super.call(this, getXmlTagDefinition) || this;
  22837. }
  22838. XmlParser.prototype.parse = function (source, url, options) {
  22839. return _super.prototype.parse.call(this, source, url, options);
  22840. };
  22841. return XmlParser;
  22842. }(Parser));
  22843. var _VERSION = '1.2';
  22844. var _XMLNS = 'urn:oasis:names:tc:xliff:document:1.2';
  22845. // TODO(vicb): make this a param (s/_/-/)
  22846. var _DEFAULT_SOURCE_LANG = 'en';
  22847. var _PLACEHOLDER_TAG$1 = 'x';
  22848. var _MARKER_TAG = 'mrk';
  22849. var _FILE_TAG = 'file';
  22850. var _SOURCE_TAG$1 = 'source';
  22851. var _SEGMENT_SOURCE_TAG = 'seg-source';
  22852. var _ALT_TRANS_TAG = 'alt-trans';
  22853. var _TARGET_TAG = 'target';
  22854. var _UNIT_TAG = 'trans-unit';
  22855. var _CONTEXT_GROUP_TAG = 'context-group';
  22856. var _CONTEXT_TAG = 'context';
  22857. // https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html
  22858. // https://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html
  22859. var Xliff = /** @class */ (function (_super) {
  22860. __extends(Xliff, _super);
  22861. function Xliff() {
  22862. return _super !== null && _super.apply(this, arguments) || this;
  22863. }
  22864. Xliff.prototype.write = function (messages, locale) {
  22865. var visitor = new _WriteVisitor();
  22866. var transUnits = [];
  22867. messages.forEach(function (message) {
  22868. var _a;
  22869. var contextTags = [];
  22870. message.sources.forEach(function (source) {
  22871. var contextGroupTag = new Tag(_CONTEXT_GROUP_TAG, { purpose: 'location' });
  22872. contextGroupTag.children.push(new CR(10), new Tag(_CONTEXT_TAG, { 'context-type': 'sourcefile' }, [new Text$2(source.filePath)]), new CR(10), new Tag(_CONTEXT_TAG, { 'context-type': 'linenumber' }, [new Text$2("" + source.startLine)]), new CR(8));
  22873. contextTags.push(new CR(8), contextGroupTag);
  22874. });
  22875. var transUnit = new Tag(_UNIT_TAG, { id: message.id, datatype: 'html' });
  22876. (_a = transUnit.children).push.apply(_a, __spreadArray([new CR(8), new Tag(_SOURCE_TAG$1, {}, visitor.serialize(message.nodes))], __read(contextTags)));
  22877. if (message.description) {
  22878. transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'description' }, [new Text$2(message.description)]));
  22879. }
  22880. if (message.meaning) {
  22881. transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'meaning' }, [new Text$2(message.meaning)]));
  22882. }
  22883. transUnit.children.push(new CR(6));
  22884. transUnits.push(new CR(6), transUnit);
  22885. });
  22886. var body = new Tag('body', {}, __spreadArray(__spreadArray([], __read(transUnits)), [new CR(4)]));
  22887. var file = new Tag('file', {
  22888. 'source-language': locale || _DEFAULT_SOURCE_LANG,
  22889. datatype: 'plaintext',
  22890. original: 'ng2.template',
  22891. }, [new CR(4), body, new CR(2)]);
  22892. var xliff = new Tag('xliff', { version: _VERSION, xmlns: _XMLNS }, [new CR(2), file, new CR()]);
  22893. return serialize([
  22894. new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
  22895. ]);
  22896. };
  22897. Xliff.prototype.load = function (content, url) {
  22898. // xliff to xml nodes
  22899. var xliffParser = new XliffParser();
  22900. var _a = xliffParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
  22901. // xml nodes to i18n nodes
  22902. var i18nNodesByMsgId = {};
  22903. var converter = new XmlToI18n();
  22904. Object.keys(msgIdToHtml).forEach(function (msgId) {
  22905. var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
  22906. errors.push.apply(errors, __spreadArray([], __read(e)));
  22907. i18nNodesByMsgId[msgId] = i18nNodes;
  22908. });
  22909. if (errors.length) {
  22910. throw new Error("xliff parse errors:\n" + errors.join('\n'));
  22911. }
  22912. return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
  22913. };
  22914. Xliff.prototype.digest = function (message) {
  22915. return digest(message);
  22916. };
  22917. return Xliff;
  22918. }(Serializer));
  22919. var _WriteVisitor = /** @class */ (function () {
  22920. function _WriteVisitor() {
  22921. }
  22922. _WriteVisitor.prototype.visitText = function (text, context) {
  22923. return [new Text$2(text.value)];
  22924. };
  22925. _WriteVisitor.prototype.visitContainer = function (container, context) {
  22926. var _this = this;
  22927. var nodes = [];
  22928. container.children.forEach(function (node) { return nodes.push.apply(nodes, __spreadArray([], __read(node.visit(_this)))); });
  22929. return nodes;
  22930. };
  22931. _WriteVisitor.prototype.visitIcu = function (icu, context) {
  22932. var _this = this;
  22933. var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
  22934. Object.keys(icu.cases).forEach(function (c) {
  22935. nodes.push.apply(nodes, __spreadArray(__spreadArray([new Text$2(c + " {")], __read(icu.cases[c].visit(_this))), [new Text$2("} ")]));
  22936. });
  22937. nodes.push(new Text$2("}"));
  22938. return nodes;
  22939. };
  22940. _WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  22941. var ctype = getCtypeForTag(ph.tag);
  22942. if (ph.isVoid) {
  22943. // void tags have no children nor closing tags
  22944. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype: ctype, 'equiv-text': "<" + ph.tag + "/>" })];
  22945. }
  22946. var startTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype: ctype, 'equiv-text': "<" + ph.tag + ">" });
  22947. var closeTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.closeName, ctype: ctype, 'equiv-text': "</" + ph.tag + ">" });
  22948. return __spreadArray(__spreadArray([startTagPh], __read(this.serialize(ph.children))), [closeTagPh]);
  22949. };
  22950. _WriteVisitor.prototype.visitPlaceholder = function (ph, context) {
  22951. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': "{{" + ph.value + "}}" })];
  22952. };
  22953. _WriteVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  22954. var equivText = "{" + ph.value.expression + ", " + ph.value.type + ", " + Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ') + "}";
  22955. return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': equivText })];
  22956. };
  22957. _WriteVisitor.prototype.serialize = function (nodes) {
  22958. var _this = this;
  22959. return [].concat.apply([], __spreadArray([], __read(nodes.map(function (node) { return node.visit(_this); }))));
  22960. };
  22961. return _WriteVisitor;
  22962. }());
  22963. // TODO(vicb): add error management (structure)
  22964. // Extract messages as xml nodes from the xliff file
  22965. var XliffParser = /** @class */ (function () {
  22966. function XliffParser() {
  22967. this._locale = null;
  22968. }
  22969. XliffParser.prototype.parse = function (xliff, url) {
  22970. this._unitMlString = null;
  22971. this._msgIdToHtml = {};
  22972. var xml = new XmlParser().parse(xliff, url);
  22973. this._errors = xml.errors;
  22974. visitAll$1(this, xml.rootNodes, null);
  22975. return {
  22976. msgIdToHtml: this._msgIdToHtml,
  22977. errors: this._errors,
  22978. locale: this._locale,
  22979. };
  22980. };
  22981. XliffParser.prototype.visitElement = function (element, context) {
  22982. switch (element.name) {
  22983. case _UNIT_TAG:
  22984. this._unitMlString = null;
  22985. var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
  22986. if (!idAttr) {
  22987. this._addError(element, "<" + _UNIT_TAG + "> misses the \"id\" attribute");
  22988. }
  22989. else {
  22990. var id = idAttr.value;
  22991. if (this._msgIdToHtml.hasOwnProperty(id)) {
  22992. this._addError(element, "Duplicated translations for msg " + id);
  22993. }
  22994. else {
  22995. visitAll$1(this, element.children, null);
  22996. if (typeof this._unitMlString === 'string') {
  22997. this._msgIdToHtml[id] = this._unitMlString;
  22998. }
  22999. else {
  23000. this._addError(element, "Message " + id + " misses a translation");
  23001. }
  23002. }
  23003. }
  23004. break;
  23005. // ignore those tags
  23006. case _SOURCE_TAG$1:
  23007. case _SEGMENT_SOURCE_TAG:
  23008. case _ALT_TRANS_TAG:
  23009. break;
  23010. case _TARGET_TAG:
  23011. var innerTextStart = element.startSourceSpan.end.offset;
  23012. var innerTextEnd = element.endSourceSpan.start.offset;
  23013. var content = element.startSourceSpan.start.file.content;
  23014. var innerText = content.slice(innerTextStart, innerTextEnd);
  23015. this._unitMlString = innerText;
  23016. break;
  23017. case _FILE_TAG:
  23018. var localeAttr = element.attrs.find(function (attr) { return attr.name === 'target-language'; });
  23019. if (localeAttr) {
  23020. this._locale = localeAttr.value;
  23021. }
  23022. visitAll$1(this, element.children, null);
  23023. break;
  23024. default:
  23025. // TODO(vicb): assert file structure, xliff version
  23026. // For now only recurse on unhandled nodes
  23027. visitAll$1(this, element.children, null);
  23028. }
  23029. };
  23030. XliffParser.prototype.visitAttribute = function (attribute, context) { };
  23031. XliffParser.prototype.visitText = function (text, context) { };
  23032. XliffParser.prototype.visitComment = function (comment, context) { };
  23033. XliffParser.prototype.visitExpansion = function (expansion, context) { };
  23034. XliffParser.prototype.visitExpansionCase = function (expansionCase, context) { };
  23035. XliffParser.prototype._addError = function (node, message) {
  23036. this._errors.push(new I18nError(node.sourceSpan, message));
  23037. };
  23038. return XliffParser;
  23039. }());
  23040. // Convert ml nodes (xliff syntax) to i18n nodes
  23041. var XmlToI18n = /** @class */ (function () {
  23042. function XmlToI18n() {
  23043. }
  23044. XmlToI18n.prototype.convert = function (message, url) {
  23045. var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  23046. this._errors = xmlIcu.errors;
  23047. var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  23048. [] : [].concat.apply([], __spreadArray([], __read(visitAll$1(this, xmlIcu.rootNodes))));
  23049. return {
  23050. i18nNodes: i18nNodes,
  23051. errors: this._errors,
  23052. };
  23053. };
  23054. XmlToI18n.prototype.visitText = function (text, context) {
  23055. return new Text$1(text.value, text.sourceSpan);
  23056. };
  23057. XmlToI18n.prototype.visitElement = function (el, context) {
  23058. if (el.name === _PLACEHOLDER_TAG$1) {
  23059. var nameAttr = el.attrs.find(function (attr) { return attr.name === 'id'; });
  23060. if (nameAttr) {
  23061. return new Placeholder('', nameAttr.value, el.sourceSpan);
  23062. }
  23063. this._addError(el, "<" + _PLACEHOLDER_TAG$1 + "> misses the \"id\" attribute");
  23064. return null;
  23065. }
  23066. if (el.name === _MARKER_TAG) {
  23067. return [].concat.apply([], __spreadArray([], __read(visitAll$1(this, el.children))));
  23068. }
  23069. this._addError(el, "Unexpected tag");
  23070. return null;
  23071. };
  23072. XmlToI18n.prototype.visitExpansion = function (icu, context) {
  23073. var caseMap = {};
  23074. visitAll$1(this, icu.cases).forEach(function (c) {
  23075. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  23076. });
  23077. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  23078. };
  23079. XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
  23080. return {
  23081. value: icuCase.value,
  23082. nodes: visitAll$1(this, icuCase.expression),
  23083. };
  23084. };
  23085. XmlToI18n.prototype.visitComment = function (comment, context) { };
  23086. XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
  23087. XmlToI18n.prototype._addError = function (node, message) {
  23088. this._errors.push(new I18nError(node.sourceSpan, message));
  23089. };
  23090. return XmlToI18n;
  23091. }());
  23092. function getCtypeForTag(tag) {
  23093. switch (tag.toLowerCase()) {
  23094. case 'br':
  23095. return 'lb';
  23096. case 'img':
  23097. return 'image';
  23098. default:
  23099. return "x-" + tag;
  23100. }
  23101. }
  23102. var _VERSION$1 = '2.0';
  23103. var _XMLNS$1 = 'urn:oasis:names:tc:xliff:document:2.0';
  23104. // TODO(vicb): make this a param (s/_/-/)
  23105. var _DEFAULT_SOURCE_LANG$1 = 'en';
  23106. var _PLACEHOLDER_TAG$2 = 'ph';
  23107. var _PLACEHOLDER_SPANNING_TAG = 'pc';
  23108. var _MARKER_TAG$1 = 'mrk';
  23109. var _XLIFF_TAG = 'xliff';
  23110. var _SOURCE_TAG$2 = 'source';
  23111. var _TARGET_TAG$1 = 'target';
  23112. var _UNIT_TAG$1 = 'unit';
  23113. // https://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html
  23114. var Xliff2 = /** @class */ (function (_super) {
  23115. __extends(Xliff2, _super);
  23116. function Xliff2() {
  23117. return _super !== null && _super.apply(this, arguments) || this;
  23118. }
  23119. Xliff2.prototype.write = function (messages, locale) {
  23120. var visitor = new _WriteVisitor$1();
  23121. var units = [];
  23122. messages.forEach(function (message) {
  23123. var unit = new Tag(_UNIT_TAG$1, { id: message.id });
  23124. var notes = new Tag('notes');
  23125. if (message.description || message.meaning) {
  23126. if (message.description) {
  23127. notes.children.push(new CR(8), new Tag('note', { category: 'description' }, [new Text$2(message.description)]));
  23128. }
  23129. if (message.meaning) {
  23130. notes.children.push(new CR(8), new Tag('note', { category: 'meaning' }, [new Text$2(message.meaning)]));
  23131. }
  23132. }
  23133. message.sources.forEach(function (source) {
  23134. notes.children.push(new CR(8), new Tag('note', { category: 'location' }, [
  23135. new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))
  23136. ]));
  23137. });
  23138. notes.children.push(new CR(6));
  23139. unit.children.push(new CR(6), notes);
  23140. var segment = new Tag('segment');
  23141. segment.children.push(new CR(8), new Tag(_SOURCE_TAG$2, {}, visitor.serialize(message.nodes)), new CR(6));
  23142. unit.children.push(new CR(6), segment, new CR(4));
  23143. units.push(new CR(4), unit);
  23144. });
  23145. var file = new Tag('file', { 'original': 'ng.template', id: 'ngi18n' }, __spreadArray(__spreadArray([], __read(units)), [new CR(2)]));
  23146. var xliff = new Tag(_XLIFF_TAG, { version: _VERSION$1, xmlns: _XMLNS$1, srcLang: locale || _DEFAULT_SOURCE_LANG$1 }, [new CR(2), file, new CR()]);
  23147. return serialize([
  23148. new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
  23149. ]);
  23150. };
  23151. Xliff2.prototype.load = function (content, url) {
  23152. // xliff to xml nodes
  23153. var xliff2Parser = new Xliff2Parser();
  23154. var _a = xliff2Parser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
  23155. // xml nodes to i18n nodes
  23156. var i18nNodesByMsgId = {};
  23157. var converter = new XmlToI18n$1();
  23158. Object.keys(msgIdToHtml).forEach(function (msgId) {
  23159. var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
  23160. errors.push.apply(errors, __spreadArray([], __read(e)));
  23161. i18nNodesByMsgId[msgId] = i18nNodes;
  23162. });
  23163. if (errors.length) {
  23164. throw new Error("xliff2 parse errors:\n" + errors.join('\n'));
  23165. }
  23166. return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
  23167. };
  23168. Xliff2.prototype.digest = function (message) {
  23169. return decimalDigest(message);
  23170. };
  23171. return Xliff2;
  23172. }(Serializer));
  23173. var _WriteVisitor$1 = /** @class */ (function () {
  23174. function _WriteVisitor() {
  23175. }
  23176. _WriteVisitor.prototype.visitText = function (text, context) {
  23177. return [new Text$2(text.value)];
  23178. };
  23179. _WriteVisitor.prototype.visitContainer = function (container, context) {
  23180. var _this = this;
  23181. var nodes = [];
  23182. container.children.forEach(function (node) { return nodes.push.apply(nodes, __spreadArray([], __read(node.visit(_this)))); });
  23183. return nodes;
  23184. };
  23185. _WriteVisitor.prototype.visitIcu = function (icu, context) {
  23186. var _this = this;
  23187. var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
  23188. Object.keys(icu.cases).forEach(function (c) {
  23189. nodes.push.apply(nodes, __spreadArray(__spreadArray([new Text$2(c + " {")], __read(icu.cases[c].visit(_this))), [new Text$2("} ")]));
  23190. });
  23191. nodes.push(new Text$2("}"));
  23192. return nodes;
  23193. };
  23194. _WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  23195. var _this = this;
  23196. var type = getTypeForTag(ph.tag);
  23197. if (ph.isVoid) {
  23198. var tagPh = new Tag(_PLACEHOLDER_TAG$2, {
  23199. id: (this._nextPlaceholderId++).toString(),
  23200. equiv: ph.startName,
  23201. type: type,
  23202. disp: "<" + ph.tag + "/>",
  23203. });
  23204. return [tagPh];
  23205. }
  23206. var tagPc = new Tag(_PLACEHOLDER_SPANNING_TAG, {
  23207. id: (this._nextPlaceholderId++).toString(),
  23208. equivStart: ph.startName,
  23209. equivEnd: ph.closeName,
  23210. type: type,
  23211. dispStart: "<" + ph.tag + ">",
  23212. dispEnd: "</" + ph.tag + ">",
  23213. });
  23214. var nodes = [].concat.apply([], __spreadArray([], __read(ph.children.map(function (node) { return node.visit(_this); }))));
  23215. if (nodes.length) {
  23216. nodes.forEach(function (node) { return tagPc.children.push(node); });
  23217. }
  23218. else {
  23219. tagPc.children.push(new Text$2(''));
  23220. }
  23221. return [tagPc];
  23222. };
  23223. _WriteVisitor.prototype.visitPlaceholder = function (ph, context) {
  23224. var idStr = (this._nextPlaceholderId++).toString();
  23225. return [new Tag(_PLACEHOLDER_TAG$2, {
  23226. id: idStr,
  23227. equiv: ph.name,
  23228. disp: "{{" + ph.value + "}}",
  23229. })];
  23230. };
  23231. _WriteVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  23232. var cases = Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ');
  23233. var idStr = (this._nextPlaceholderId++).toString();
  23234. return [new Tag(_PLACEHOLDER_TAG$2, { id: idStr, equiv: ph.name, disp: "{" + ph.value.expression + ", " + ph.value.type + ", " + cases + "}" })];
  23235. };
  23236. _WriteVisitor.prototype.serialize = function (nodes) {
  23237. var _this = this;
  23238. this._nextPlaceholderId = 0;
  23239. return [].concat.apply([], __spreadArray([], __read(nodes.map(function (node) { return node.visit(_this); }))));
  23240. };
  23241. return _WriteVisitor;
  23242. }());
  23243. // Extract messages as xml nodes from the xliff file
  23244. var Xliff2Parser = /** @class */ (function () {
  23245. function Xliff2Parser() {
  23246. this._locale = null;
  23247. }
  23248. Xliff2Parser.prototype.parse = function (xliff, url) {
  23249. this._unitMlString = null;
  23250. this._msgIdToHtml = {};
  23251. var xml = new XmlParser().parse(xliff, url);
  23252. this._errors = xml.errors;
  23253. visitAll$1(this, xml.rootNodes, null);
  23254. return {
  23255. msgIdToHtml: this._msgIdToHtml,
  23256. errors: this._errors,
  23257. locale: this._locale,
  23258. };
  23259. };
  23260. Xliff2Parser.prototype.visitElement = function (element, context) {
  23261. switch (element.name) {
  23262. case _UNIT_TAG$1:
  23263. this._unitMlString = null;
  23264. var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
  23265. if (!idAttr) {
  23266. this._addError(element, "<" + _UNIT_TAG$1 + "> misses the \"id\" attribute");
  23267. }
  23268. else {
  23269. var id = idAttr.value;
  23270. if (this._msgIdToHtml.hasOwnProperty(id)) {
  23271. this._addError(element, "Duplicated translations for msg " + id);
  23272. }
  23273. else {
  23274. visitAll$1(this, element.children, null);
  23275. if (typeof this._unitMlString === 'string') {
  23276. this._msgIdToHtml[id] = this._unitMlString;
  23277. }
  23278. else {
  23279. this._addError(element, "Message " + id + " misses a translation");
  23280. }
  23281. }
  23282. }
  23283. break;
  23284. case _SOURCE_TAG$2:
  23285. // ignore source message
  23286. break;
  23287. case _TARGET_TAG$1:
  23288. var innerTextStart = element.startSourceSpan.end.offset;
  23289. var innerTextEnd = element.endSourceSpan.start.offset;
  23290. var content = element.startSourceSpan.start.file.content;
  23291. var innerText = content.slice(innerTextStart, innerTextEnd);
  23292. this._unitMlString = innerText;
  23293. break;
  23294. case _XLIFF_TAG:
  23295. var localeAttr = element.attrs.find(function (attr) { return attr.name === 'trgLang'; });
  23296. if (localeAttr) {
  23297. this._locale = localeAttr.value;
  23298. }
  23299. var versionAttr = element.attrs.find(function (attr) { return attr.name === 'version'; });
  23300. if (versionAttr) {
  23301. var version = versionAttr.value;
  23302. if (version !== '2.0') {
  23303. this._addError(element, "The XLIFF file version " + version + " is not compatible with XLIFF 2.0 serializer");
  23304. }
  23305. else {
  23306. visitAll$1(this, element.children, null);
  23307. }
  23308. }
  23309. break;
  23310. default:
  23311. visitAll$1(this, element.children, null);
  23312. }
  23313. };
  23314. Xliff2Parser.prototype.visitAttribute = function (attribute, context) { };
  23315. Xliff2Parser.prototype.visitText = function (text, context) { };
  23316. Xliff2Parser.prototype.visitComment = function (comment, context) { };
  23317. Xliff2Parser.prototype.visitExpansion = function (expansion, context) { };
  23318. Xliff2Parser.prototype.visitExpansionCase = function (expansionCase, context) { };
  23319. Xliff2Parser.prototype._addError = function (node, message) {
  23320. this._errors.push(new I18nError(node.sourceSpan, message));
  23321. };
  23322. return Xliff2Parser;
  23323. }());
  23324. // Convert ml nodes (xliff syntax) to i18n nodes
  23325. var XmlToI18n$1 = /** @class */ (function () {
  23326. function XmlToI18n() {
  23327. }
  23328. XmlToI18n.prototype.convert = function (message, url) {
  23329. var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  23330. this._errors = xmlIcu.errors;
  23331. var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  23332. [] : [].concat.apply([], __spreadArray([], __read(visitAll$1(this, xmlIcu.rootNodes))));
  23333. return {
  23334. i18nNodes: i18nNodes,
  23335. errors: this._errors,
  23336. };
  23337. };
  23338. XmlToI18n.prototype.visitText = function (text, context) {
  23339. return new Text$1(text.value, text.sourceSpan);
  23340. };
  23341. XmlToI18n.prototype.visitElement = function (el, context) {
  23342. var _this = this;
  23343. switch (el.name) {
  23344. case _PLACEHOLDER_TAG$2:
  23345. var nameAttr = el.attrs.find(function (attr) { return attr.name === 'equiv'; });
  23346. if (nameAttr) {
  23347. return [new Placeholder('', nameAttr.value, el.sourceSpan)];
  23348. }
  23349. this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equiv\" attribute");
  23350. break;
  23351. case _PLACEHOLDER_SPANNING_TAG:
  23352. var startAttr = el.attrs.find(function (attr) { return attr.name === 'equivStart'; });
  23353. var endAttr = el.attrs.find(function (attr) { return attr.name === 'equivEnd'; });
  23354. if (!startAttr) {
  23355. this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equivStart\" attribute");
  23356. }
  23357. else if (!endAttr) {
  23358. this._addError(el, "<" + _PLACEHOLDER_TAG$2 + "> misses the \"equivEnd\" attribute");
  23359. }
  23360. else {
  23361. var startId = startAttr.value;
  23362. var endId = endAttr.value;
  23363. var nodes = [];
  23364. return nodes.concat.apply(nodes, __spreadArray(__spreadArray([new Placeholder('', startId, el.sourceSpan)], __read(el.children.map(function (node) { return node.visit(_this, null); }))), [new Placeholder('', endId, el.sourceSpan)]));
  23365. }
  23366. break;
  23367. case _MARKER_TAG$1:
  23368. return [].concat.apply([], __spreadArray([], __read(visitAll$1(this, el.children))));
  23369. default:
  23370. this._addError(el, "Unexpected tag");
  23371. }
  23372. return null;
  23373. };
  23374. XmlToI18n.prototype.visitExpansion = function (icu, context) {
  23375. var caseMap = {};
  23376. visitAll$1(this, icu.cases).forEach(function (c) {
  23377. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  23378. });
  23379. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  23380. };
  23381. XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
  23382. return {
  23383. value: icuCase.value,
  23384. nodes: [].concat.apply([], __spreadArray([], __read(visitAll$1(this, icuCase.expression)))),
  23385. };
  23386. };
  23387. XmlToI18n.prototype.visitComment = function (comment, context) { };
  23388. XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
  23389. XmlToI18n.prototype._addError = function (node, message) {
  23390. this._errors.push(new I18nError(node.sourceSpan, message));
  23391. };
  23392. return XmlToI18n;
  23393. }());
  23394. function getTypeForTag(tag) {
  23395. switch (tag.toLowerCase()) {
  23396. case 'br':
  23397. case 'b':
  23398. case 'i':
  23399. case 'u':
  23400. return 'fmt';
  23401. case 'img':
  23402. return 'image';
  23403. case 'a':
  23404. return 'link';
  23405. default:
  23406. return 'other';
  23407. }
  23408. }
  23409. var _TRANSLATIONS_TAG = 'translationbundle';
  23410. var _TRANSLATION_TAG = 'translation';
  23411. var _PLACEHOLDER_TAG$3 = 'ph';
  23412. var Xtb = /** @class */ (function (_super) {
  23413. __extends(Xtb, _super);
  23414. function Xtb() {
  23415. return _super !== null && _super.apply(this, arguments) || this;
  23416. }
  23417. Xtb.prototype.write = function (messages, locale) {
  23418. throw new Error('Unsupported');
  23419. };
  23420. Xtb.prototype.load = function (content, url) {
  23421. // xtb to xml nodes
  23422. var xtbParser = new XtbParser();
  23423. var _a = xtbParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
  23424. // xml nodes to i18n nodes
  23425. var i18nNodesByMsgId = {};
  23426. var converter = new XmlToI18n$2();
  23427. // Because we should be able to load xtb files that rely on features not supported by angular,
  23428. // we need to delay the conversion of html to i18n nodes so that non angular messages are not
  23429. // converted
  23430. Object.keys(msgIdToHtml).forEach(function (msgId) {
  23431. var valueFn = function () {
  23432. var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, errors = _a.errors;
  23433. if (errors.length) {
  23434. throw new Error("xtb parse errors:\n" + errors.join('\n'));
  23435. }
  23436. return i18nNodes;
  23437. };
  23438. createLazyProperty(i18nNodesByMsgId, msgId, valueFn);
  23439. });
  23440. if (errors.length) {
  23441. throw new Error("xtb parse errors:\n" + errors.join('\n'));
  23442. }
  23443. return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
  23444. };
  23445. Xtb.prototype.digest = function (message) {
  23446. return digest$1(message);
  23447. };
  23448. Xtb.prototype.createNameMapper = function (message) {
  23449. return new SimplePlaceholderMapper(message, toPublicName);
  23450. };
  23451. return Xtb;
  23452. }(Serializer));
  23453. function createLazyProperty(messages, id, valueFn) {
  23454. Object.defineProperty(messages, id, {
  23455. configurable: true,
  23456. enumerable: true,
  23457. get: function () {
  23458. var value = valueFn();
  23459. Object.defineProperty(messages, id, { enumerable: true, value: value });
  23460. return value;
  23461. },
  23462. set: function (_) {
  23463. throw new Error('Could not overwrite an XTB translation');
  23464. },
  23465. });
  23466. }
  23467. // Extract messages as xml nodes from the xtb file
  23468. var XtbParser = /** @class */ (function () {
  23469. function XtbParser() {
  23470. this._locale = null;
  23471. }
  23472. XtbParser.prototype.parse = function (xtb, url) {
  23473. this._bundleDepth = 0;
  23474. this._msgIdToHtml = {};
  23475. // We can not parse the ICU messages at this point as some messages might not originate
  23476. // from Angular that could not be lex'd.
  23477. var xml = new XmlParser().parse(xtb, url);
  23478. this._errors = xml.errors;
  23479. visitAll$1(this, xml.rootNodes);
  23480. return {
  23481. msgIdToHtml: this._msgIdToHtml,
  23482. errors: this._errors,
  23483. locale: this._locale,
  23484. };
  23485. };
  23486. XtbParser.prototype.visitElement = function (element, context) {
  23487. switch (element.name) {
  23488. case _TRANSLATIONS_TAG:
  23489. this._bundleDepth++;
  23490. if (this._bundleDepth > 1) {
  23491. this._addError(element, "<" + _TRANSLATIONS_TAG + "> elements can not be nested");
  23492. }
  23493. var langAttr = element.attrs.find(function (attr) { return attr.name === 'lang'; });
  23494. if (langAttr) {
  23495. this._locale = langAttr.value;
  23496. }
  23497. visitAll$1(this, element.children, null);
  23498. this._bundleDepth--;
  23499. break;
  23500. case _TRANSLATION_TAG:
  23501. var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
  23502. if (!idAttr) {
  23503. this._addError(element, "<" + _TRANSLATION_TAG + "> misses the \"id\" attribute");
  23504. }
  23505. else {
  23506. var id = idAttr.value;
  23507. if (this._msgIdToHtml.hasOwnProperty(id)) {
  23508. this._addError(element, "Duplicated translations for msg " + id);
  23509. }
  23510. else {
  23511. var innerTextStart = element.startSourceSpan.end.offset;
  23512. var innerTextEnd = element.endSourceSpan.start.offset;
  23513. var content = element.startSourceSpan.start.file.content;
  23514. var innerText = content.slice(innerTextStart, innerTextEnd);
  23515. this._msgIdToHtml[id] = innerText;
  23516. }
  23517. }
  23518. break;
  23519. default:
  23520. this._addError(element, 'Unexpected tag');
  23521. }
  23522. };
  23523. XtbParser.prototype.visitAttribute = function (attribute, context) { };
  23524. XtbParser.prototype.visitText = function (text, context) { };
  23525. XtbParser.prototype.visitComment = function (comment, context) { };
  23526. XtbParser.prototype.visitExpansion = function (expansion, context) { };
  23527. XtbParser.prototype.visitExpansionCase = function (expansionCase, context) { };
  23528. XtbParser.prototype._addError = function (node, message) {
  23529. this._errors.push(new I18nError(node.sourceSpan, message));
  23530. };
  23531. return XtbParser;
  23532. }());
  23533. // Convert ml nodes (xtb syntax) to i18n nodes
  23534. var XmlToI18n$2 = /** @class */ (function () {
  23535. function XmlToI18n() {
  23536. }
  23537. XmlToI18n.prototype.convert = function (message, url) {
  23538. var xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
  23539. this._errors = xmlIcu.errors;
  23540. var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
  23541. [] :
  23542. visitAll$1(this, xmlIcu.rootNodes);
  23543. return {
  23544. i18nNodes: i18nNodes,
  23545. errors: this._errors,
  23546. };
  23547. };
  23548. XmlToI18n.prototype.visitText = function (text, context) {
  23549. return new Text$1(text.value, text.sourceSpan);
  23550. };
  23551. XmlToI18n.prototype.visitExpansion = function (icu, context) {
  23552. var caseMap = {};
  23553. visitAll$1(this, icu.cases).forEach(function (c) {
  23554. caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
  23555. });
  23556. return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
  23557. };
  23558. XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
  23559. return {
  23560. value: icuCase.value,
  23561. nodes: visitAll$1(this, icuCase.expression),
  23562. };
  23563. };
  23564. XmlToI18n.prototype.visitElement = function (el, context) {
  23565. if (el.name === _PLACEHOLDER_TAG$3) {
  23566. var nameAttr = el.attrs.find(function (attr) { return attr.name === 'name'; });
  23567. if (nameAttr) {
  23568. return new Placeholder('', nameAttr.value, el.sourceSpan);
  23569. }
  23570. this._addError(el, "<" + _PLACEHOLDER_TAG$3 + "> misses the \"name\" attribute");
  23571. }
  23572. else {
  23573. this._addError(el, "Unexpected tag");
  23574. }
  23575. return null;
  23576. };
  23577. XmlToI18n.prototype.visitComment = function (comment, context) { };
  23578. XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
  23579. XmlToI18n.prototype._addError = function (node, message) {
  23580. this._errors.push(new I18nError(node.sourceSpan, message));
  23581. };
  23582. return XmlToI18n;
  23583. }());
  23584. /**
  23585. * A container for translated messages
  23586. */
  23587. var TranslationBundle = /** @class */ (function () {
  23588. function TranslationBundle(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console) {
  23589. if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
  23590. if (missingTranslationStrategy === void 0) { missingTranslationStrategy = MissingTranslationStrategy.Warning; }
  23591. this._i18nNodesByMsgId = _i18nNodesByMsgId;
  23592. this.digest = digest;
  23593. this.mapperFactory = mapperFactory;
  23594. this._i18nToHtml = new I18nToHtmlVisitor(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console);
  23595. }
  23596. // Creates a `TranslationBundle` by parsing the given `content` with the `serializer`.
  23597. TranslationBundle.load = function (content, url, serializer, missingTranslationStrategy, console) {
  23598. var _a = serializer.load(content, url), locale = _a.locale, i18nNodesByMsgId = _a.i18nNodesByMsgId;
  23599. var digestFn = function (m) { return serializer.digest(m); };
  23600. var mapperFactory = function (m) { return serializer.createNameMapper(m); };
  23601. return new TranslationBundle(i18nNodesByMsgId, locale, digestFn, mapperFactory, missingTranslationStrategy, console);
  23602. };
  23603. // Returns the translation as HTML nodes from the given source message.
  23604. TranslationBundle.prototype.get = function (srcMsg) {
  23605. var html = this._i18nToHtml.convert(srcMsg);
  23606. if (html.errors.length) {
  23607. throw new Error(html.errors.join('\n'));
  23608. }
  23609. return html.nodes;
  23610. };
  23611. TranslationBundle.prototype.has = function (srcMsg) {
  23612. return this.digest(srcMsg) in this._i18nNodesByMsgId;
  23613. };
  23614. return TranslationBundle;
  23615. }());
  23616. var I18nToHtmlVisitor = /** @class */ (function () {
  23617. function I18nToHtmlVisitor(_i18nNodesByMsgId, _locale, _digest, _mapperFactory, _missingTranslationStrategy, _console) {
  23618. if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
  23619. this._i18nNodesByMsgId = _i18nNodesByMsgId;
  23620. this._locale = _locale;
  23621. this._digest = _digest;
  23622. this._mapperFactory = _mapperFactory;
  23623. this._missingTranslationStrategy = _missingTranslationStrategy;
  23624. this._console = _console;
  23625. this._contextStack = [];
  23626. this._errors = [];
  23627. }
  23628. I18nToHtmlVisitor.prototype.convert = function (srcMsg) {
  23629. this._contextStack.length = 0;
  23630. this._errors.length = 0;
  23631. // i18n to text
  23632. var text = this._convertToText(srcMsg);
  23633. // text to html
  23634. var url = srcMsg.nodes[0].sourceSpan.start.file.url;
  23635. var html = new HtmlParser().parse(text, url, { tokenizeExpansionForms: true });
  23636. return {
  23637. nodes: html.rootNodes,
  23638. errors: __spreadArray(__spreadArray([], __read(this._errors)), __read(html.errors)),
  23639. };
  23640. };
  23641. I18nToHtmlVisitor.prototype.visitText = function (text, context) {
  23642. // `convert()` uses an `HtmlParser` to return `html.Node`s
  23643. // we should then make sure that any special characters are escaped
  23644. return escapeXml(text.value);
  23645. };
  23646. I18nToHtmlVisitor.prototype.visitContainer = function (container, context) {
  23647. var _this = this;
  23648. return container.children.map(function (n) { return n.visit(_this); }).join('');
  23649. };
  23650. I18nToHtmlVisitor.prototype.visitIcu = function (icu, context) {
  23651. var _this = this;
  23652. var cases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
  23653. // TODO(vicb): Once all format switch to using expression placeholders
  23654. // we should throw when the placeholder is not in the source message
  23655. var exp = this._srcMsg.placeholders.hasOwnProperty(icu.expression) ?
  23656. this._srcMsg.placeholders[icu.expression].text :
  23657. icu.expression;
  23658. return "{" + exp + ", " + icu.type + ", " + cases.join(' ') + "}";
  23659. };
  23660. I18nToHtmlVisitor.prototype.visitPlaceholder = function (ph, context) {
  23661. var phName = this._mapper(ph.name);
  23662. if (this._srcMsg.placeholders.hasOwnProperty(phName)) {
  23663. return this._srcMsg.placeholders[phName].text;
  23664. }
  23665. if (this._srcMsg.placeholderToMessage.hasOwnProperty(phName)) {
  23666. return this._convertToText(this._srcMsg.placeholderToMessage[phName]);
  23667. }
  23668. this._addError(ph, "Unknown placeholder \"" + ph.name + "\"");
  23669. return '';
  23670. };
  23671. // Loaded message contains only placeholders (vs tag and icu placeholders).
  23672. // However when a translation can not be found, we need to serialize the source message
  23673. // which can contain tag placeholders
  23674. I18nToHtmlVisitor.prototype.visitTagPlaceholder = function (ph, context) {
  23675. var _this = this;
  23676. var tag = "" + ph.tag;
  23677. var attrs = Object.keys(ph.attrs).map(function (name) { return name + "=\"" + ph.attrs[name] + "\""; }).join(' ');
  23678. if (ph.isVoid) {
  23679. return "<" + tag + " " + attrs + "/>";
  23680. }
  23681. var children = ph.children.map(function (c) { return c.visit(_this); }).join('');
  23682. return "<" + tag + " " + attrs + ">" + children + "</" + tag + ">";
  23683. };
  23684. // Loaded message contains only placeholders (vs tag and icu placeholders).
  23685. // However when a translation can not be found, we need to serialize the source message
  23686. // which can contain tag placeholders
  23687. I18nToHtmlVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
  23688. // An ICU placeholder references the source message to be serialized
  23689. return this._convertToText(this._srcMsg.placeholderToMessage[ph.name]);
  23690. };
  23691. /**
  23692. * Convert a source message to a translated text string:
  23693. * - text nodes are replaced with their translation,
  23694. * - placeholders are replaced with their content,
  23695. * - ICU nodes are converted to ICU expressions.
  23696. */
  23697. I18nToHtmlVisitor.prototype._convertToText = function (srcMsg) {
  23698. var _this = this;
  23699. var id = this._digest(srcMsg);
  23700. var mapper = this._mapperFactory ? this._mapperFactory(srcMsg) : null;
  23701. var nodes;
  23702. this._contextStack.push({ msg: this._srcMsg, mapper: this._mapper });
  23703. this._srcMsg = srcMsg;
  23704. if (this._i18nNodesByMsgId.hasOwnProperty(id)) {
  23705. // When there is a translation use its nodes as the source
  23706. // And create a mapper to convert serialized placeholder names to internal names
  23707. nodes = this._i18nNodesByMsgId[id];
  23708. this._mapper = function (name) { return mapper ? mapper.toInternalName(name) : name; };
  23709. }
  23710. else {
  23711. // When no translation has been found
  23712. // - report an error / a warning / nothing,
  23713. // - use the nodes from the original message
  23714. // - placeholders are already internal and need no mapper
  23715. if (this._missingTranslationStrategy === MissingTranslationStrategy.Error) {
  23716. var ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
  23717. this._addError(srcMsg.nodes[0], "Missing translation for message \"" + id + "\"" + ctx);
  23718. }
  23719. else if (this._console &&
  23720. this._missingTranslationStrategy === MissingTranslationStrategy.Warning) {
  23721. var ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
  23722. this._console.warn("Missing translation for message \"" + id + "\"" + ctx);
  23723. }
  23724. nodes = srcMsg.nodes;
  23725. this._mapper = function (name) { return name; };
  23726. }
  23727. var text = nodes.map(function (node) { return node.visit(_this); }).join('');
  23728. var context = this._contextStack.pop();
  23729. this._srcMsg = context.msg;
  23730. this._mapper = context.mapper;
  23731. return text;
  23732. };
  23733. I18nToHtmlVisitor.prototype._addError = function (el, msg) {
  23734. this._errors.push(new I18nError(el.sourceSpan, msg));
  23735. };
  23736. return I18nToHtmlVisitor;
  23737. }());
  23738. /**
  23739. * @license
  23740. * Copyright Google LLC All Rights Reserved.
  23741. *
  23742. * Use of this source code is governed by an MIT-style license that can be
  23743. * found in the LICENSE file at https://angular.io/license
  23744. */
  23745. var I18NHtmlParser = /** @class */ (function () {
  23746. function I18NHtmlParser(_htmlParser, translations, translationsFormat, missingTranslation, console) {
  23747. if (missingTranslation === void 0) { missingTranslation = MissingTranslationStrategy.Warning; }
  23748. this._htmlParser = _htmlParser;
  23749. if (translations) {
  23750. var serializer = createSerializer(translationsFormat);
  23751. this._translationBundle =
  23752. TranslationBundle.load(translations, 'i18n', serializer, missingTranslation, console);
  23753. }
  23754. else {
  23755. this._translationBundle =
  23756. new TranslationBundle({}, null, digest, undefined, missingTranslation, console);
  23757. }
  23758. }
  23759. I18NHtmlParser.prototype.parse = function (source, url, options) {
  23760. if (options === void 0) { options = {}; }
  23761. var interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
  23762. var parseResult = this._htmlParser.parse(source, url, Object.assign({ interpolationConfig: interpolationConfig }, options));
  23763. if (parseResult.errors.length) {
  23764. return new ParseTreeResult(parseResult.rootNodes, parseResult.errors);
  23765. }
  23766. return mergeTranslations(parseResult.rootNodes, this._translationBundle, interpolationConfig, [], {});
  23767. };
  23768. return I18NHtmlParser;
  23769. }());
  23770. function createSerializer(format) {
  23771. format = (format || 'xlf').toLowerCase();
  23772. switch (format) {
  23773. case 'xmb':
  23774. return new Xmb();
  23775. case 'xtb':
  23776. return new Xtb();
  23777. case 'xliff2':
  23778. case 'xlf2':
  23779. return new Xliff2();
  23780. case 'xliff':
  23781. case 'xlf':
  23782. default:
  23783. return new Xliff();
  23784. }
  23785. }
  23786. /**
  23787. * @license
  23788. * Copyright Google LLC All Rights Reserved.
  23789. *
  23790. * Use of this source code is governed by an MIT-style license that can be
  23791. * found in the LICENSE file at https://angular.io/license
  23792. */
  23793. var QUOTED_KEYS = '$quoted$';
  23794. function convertValueToOutputAst(ctx, value, type) {
  23795. if (type === void 0) { type = null; }
  23796. return visitValue(value, new _ValueOutputAstTransformer(ctx), type);
  23797. }
  23798. var _ValueOutputAstTransformer = /** @class */ (function () {
  23799. function _ValueOutputAstTransformer(ctx) {
  23800. this.ctx = ctx;
  23801. }
  23802. _ValueOutputAstTransformer.prototype.visitArray = function (arr, type) {
  23803. var values = [];
  23804. // Note Array.map() must not be used to convert the values because it will
  23805. // skip over empty elements in arrays constructed using `new Array(length)`,
  23806. // resulting in `undefined` elements. This breaks the type guarantee that
  23807. // all values in `o.LiteralArrayExpr` are of type `o.Expression`.
  23808. // See test case in `value_util_spec.ts`.
  23809. for (var i = 0; i < arr.length; ++i) {
  23810. values.push(visitValue(arr[i], this, null /* context */));
  23811. }
  23812. return literalArr(values, type);
  23813. };
  23814. _ValueOutputAstTransformer.prototype.visitStringMap = function (map, type) {
  23815. var _this = this;
  23816. var entries = [];
  23817. var quotedSet = new Set(map && map[QUOTED_KEYS]);
  23818. Object.keys(map).forEach(function (key) {
  23819. entries.push(new LiteralMapEntry(key, visitValue(map[key], _this, null), quotedSet.has(key)));
  23820. });
  23821. return new LiteralMapExpr(entries, type);
  23822. };
  23823. _ValueOutputAstTransformer.prototype.visitPrimitive = function (value, type) {
  23824. return literal(value, type);
  23825. };
  23826. _ValueOutputAstTransformer.prototype.visitOther = function (value, type) {
  23827. if (value instanceof Expression) {
  23828. return value;
  23829. }
  23830. else {
  23831. return this.ctx.importExpr(value);
  23832. }
  23833. };
  23834. return _ValueOutputAstTransformer;
  23835. }());
  23836. /**
  23837. * @license
  23838. * Copyright Google LLC All Rights Reserved.
  23839. *
  23840. * Use of this source code is governed by an MIT-style license that can be
  23841. * found in the LICENSE file at https://angular.io/license
  23842. */
  23843. function mapEntry$1(key, value) {
  23844. return { key: key, value: value, quoted: false };
  23845. }
  23846. var InjectableCompiler = /** @class */ (function () {
  23847. function InjectableCompiler(reflector, alwaysGenerateDef) {
  23848. this.reflector = reflector;
  23849. this.alwaysGenerateDef = alwaysGenerateDef;
  23850. this.tokenInjector = reflector.resolveExternalReference(Identifiers$1.Injector);
  23851. }
  23852. InjectableCompiler.prototype.depsArray = function (deps, ctx) {
  23853. var _this = this;
  23854. return deps.map(function (dep) {
  23855. var token = dep;
  23856. var args = [token];
  23857. var flags = 0 /* Default */;
  23858. if (Array.isArray(dep)) {
  23859. for (var i = 0; i < dep.length; i++) {
  23860. var v = dep[i];
  23861. if (v) {
  23862. if (v.ngMetadataName === 'Optional') {
  23863. flags |= 8 /* Optional */;
  23864. }
  23865. else if (v.ngMetadataName === 'SkipSelf') {
  23866. flags |= 4 /* SkipSelf */;
  23867. }
  23868. else if (v.ngMetadataName === 'Self') {
  23869. flags |= 2 /* Self */;
  23870. }
  23871. else if (v.ngMetadataName === 'Inject') {
  23872. token = v.token;
  23873. }
  23874. else {
  23875. token = v;
  23876. }
  23877. }
  23878. }
  23879. }
  23880. var tokenExpr;
  23881. if (typeof token === 'string') {
  23882. tokenExpr = literal(token);
  23883. }
  23884. else if (token === _this.tokenInjector) {
  23885. tokenExpr = importExpr(Identifiers$1.INJECTOR);
  23886. }
  23887. else {
  23888. tokenExpr = ctx.importExpr(token);
  23889. }
  23890. if (flags !== 0 /* Default */) {
  23891. args = [tokenExpr, literal(flags)];
  23892. }
  23893. else {
  23894. args = [tokenExpr];
  23895. }
  23896. return importExpr(Identifiers$1.inject).callFn(args);
  23897. });
  23898. };
  23899. InjectableCompiler.prototype.factoryFor = function (injectable, ctx) {
  23900. var retValue;
  23901. if (injectable.useExisting) {
  23902. retValue = importExpr(Identifiers$1.inject).callFn([ctx.importExpr(injectable.useExisting)]);
  23903. }
  23904. else if (injectable.useFactory) {
  23905. var deps = injectable.deps || [];
  23906. if (deps.length > 0) {
  23907. retValue = ctx.importExpr(injectable.useFactory).callFn(this.depsArray(deps, ctx));
  23908. }
  23909. else {
  23910. return ctx.importExpr(injectable.useFactory);
  23911. }
  23912. }
  23913. else if (injectable.useValue) {
  23914. retValue = convertValueToOutputAst(ctx, injectable.useValue);
  23915. }
  23916. else {
  23917. var clazz = injectable.useClass || injectable.symbol;
  23918. var depArgs = this.depsArray(this.reflector.parameters(clazz), ctx);
  23919. retValue = new InstantiateExpr(ctx.importExpr(clazz), depArgs);
  23920. }
  23921. return fn([], [new ReturnStatement(retValue)], undefined, undefined, injectable.symbol.name + '_Factory');
  23922. };
  23923. InjectableCompiler.prototype.injectableDef = function (injectable, ctx) {
  23924. var providedIn = NULL_EXPR;
  23925. if (injectable.providedIn !== undefined) {
  23926. if (injectable.providedIn === null) {
  23927. providedIn = NULL_EXPR;
  23928. }
  23929. else if (typeof injectable.providedIn === 'string') {
  23930. providedIn = literal(injectable.providedIn);
  23931. }
  23932. else {
  23933. providedIn = ctx.importExpr(injectable.providedIn);
  23934. }
  23935. }
  23936. var def = [
  23937. mapEntry$1('factory', this.factoryFor(injectable, ctx)),
  23938. mapEntry$1('token', ctx.importExpr(injectable.type.reference)),
  23939. mapEntry$1('providedIn', providedIn),
  23940. ];
  23941. return importExpr(Identifiers.ɵɵdefineInjectable).callFn([literalMap(def)], undefined, true);
  23942. };
  23943. InjectableCompiler.prototype.compile = function (injectable, ctx) {
  23944. if (this.alwaysGenerateDef || injectable.providedIn !== undefined) {
  23945. var className = identifierName(injectable.type);
  23946. var clazz = new ClassStmt(className, null, [
  23947. new ClassField('ɵprov', INFERRED_TYPE, [exports.StmtModifier.Static], this.injectableDef(injectable, ctx)),
  23948. ], [], new ClassMethod(null, [], []), []);
  23949. ctx.statements.push(clazz);
  23950. }
  23951. };
  23952. return InjectableCompiler;
  23953. }());
  23954. /**
  23955. * @license
  23956. * Copyright Google LLC All Rights Reserved.
  23957. *
  23958. * Use of this source code is governed by an MIT-style license that can be
  23959. * found in the LICENSE file at https://angular.io/license
  23960. */
  23961. var STRIP_SRC_FILE_SUFFIXES = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/;
  23962. var GENERATED_FILE = /\.ngfactory\.|\.ngsummary\./;
  23963. var JIT_SUMMARY_FILE = /\.ngsummary\./;
  23964. var JIT_SUMMARY_NAME = /NgSummary$/;
  23965. function ngfactoryFilePath(filePath, forceSourceFile) {
  23966. if (forceSourceFile === void 0) { forceSourceFile = false; }
  23967. var urlWithSuffix = splitTypescriptSuffix(filePath, forceSourceFile);
  23968. return urlWithSuffix[0] + ".ngfactory" + normalizeGenFileSuffix(urlWithSuffix[1]);
  23969. }
  23970. function stripGeneratedFileSuffix(filePath) {
  23971. return filePath.replace(GENERATED_FILE, '.');
  23972. }
  23973. function isGeneratedFile(filePath) {
  23974. return GENERATED_FILE.test(filePath);
  23975. }
  23976. function splitTypescriptSuffix(path, forceSourceFile) {
  23977. if (forceSourceFile === void 0) { forceSourceFile = false; }
  23978. if (path.endsWith('.d.ts')) {
  23979. return [path.slice(0, -5), forceSourceFile ? '.ts' : '.d.ts'];
  23980. }
  23981. var lastDot = path.lastIndexOf('.');
  23982. if (lastDot !== -1) {
  23983. return [path.substring(0, lastDot), path.substring(lastDot)];
  23984. }
  23985. return [path, ''];
  23986. }
  23987. function normalizeGenFileSuffix(srcFileSuffix) {
  23988. return srcFileSuffix === '.tsx' ? '.ts' : srcFileSuffix;
  23989. }
  23990. function summaryFileName(fileName) {
  23991. var fileNameWithoutSuffix = fileName.replace(STRIP_SRC_FILE_SUFFIXES, '');
  23992. return fileNameWithoutSuffix + ".ngsummary.json";
  23993. }
  23994. function summaryForJitFileName(fileName, forceSourceFile) {
  23995. if (forceSourceFile === void 0) { forceSourceFile = false; }
  23996. var urlWithSuffix = splitTypescriptSuffix(stripGeneratedFileSuffix(fileName), forceSourceFile);
  23997. return urlWithSuffix[0] + ".ngsummary" + urlWithSuffix[1];
  23998. }
  23999. function stripSummaryForJitFileSuffix(filePath) {
  24000. return filePath.replace(JIT_SUMMARY_FILE, '.');
  24001. }
  24002. function summaryForJitName(symbolName) {
  24003. return symbolName + "NgSummary";
  24004. }
  24005. function stripSummaryForJitNameSuffix(symbolName) {
  24006. return symbolName.replace(JIT_SUMMARY_NAME, '');
  24007. }
  24008. var LOWERED_SYMBOL = /\u0275\d+/;
  24009. function isLoweredSymbol(name) {
  24010. return LOWERED_SYMBOL.test(name);
  24011. }
  24012. function createLoweredSymbol(id) {
  24013. return "\u0275" + id;
  24014. }
  24015. /**
  24016. * @license
  24017. * Copyright Google LLC All Rights Reserved.
  24018. *
  24019. * Use of this source code is governed by an MIT-style license that can be
  24020. * found in the LICENSE file at https://angular.io/license
  24021. */
  24022. var LifecycleHooks;
  24023. (function (LifecycleHooks) {
  24024. LifecycleHooks[LifecycleHooks["OnInit"] = 0] = "OnInit";
  24025. LifecycleHooks[LifecycleHooks["OnDestroy"] = 1] = "OnDestroy";
  24026. LifecycleHooks[LifecycleHooks["DoCheck"] = 2] = "DoCheck";
  24027. LifecycleHooks[LifecycleHooks["OnChanges"] = 3] = "OnChanges";
  24028. LifecycleHooks[LifecycleHooks["AfterContentInit"] = 4] = "AfterContentInit";
  24029. LifecycleHooks[LifecycleHooks["AfterContentChecked"] = 5] = "AfterContentChecked";
  24030. LifecycleHooks[LifecycleHooks["AfterViewInit"] = 6] = "AfterViewInit";
  24031. LifecycleHooks[LifecycleHooks["AfterViewChecked"] = 7] = "AfterViewChecked";
  24032. })(LifecycleHooks || (LifecycleHooks = {}));
  24033. var LIFECYCLE_HOOKS_VALUES = [
  24034. LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges,
  24035. LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit,
  24036. LifecycleHooks.AfterViewChecked
  24037. ];
  24038. function hasLifecycleHook(reflector, hook, token) {
  24039. return reflector.hasLifecycleHook(token, getHookName(hook));
  24040. }
  24041. function getAllLifecycleHooks(reflector, token) {
  24042. return LIFECYCLE_HOOKS_VALUES.filter(function (hook) { return hasLifecycleHook(reflector, hook, token); });
  24043. }
  24044. function getHookName(hook) {
  24045. switch (hook) {
  24046. case LifecycleHooks.OnInit:
  24047. return 'ngOnInit';
  24048. case LifecycleHooks.OnDestroy:
  24049. return 'ngOnDestroy';
  24050. case LifecycleHooks.DoCheck:
  24051. return 'ngDoCheck';
  24052. case LifecycleHooks.OnChanges:
  24053. return 'ngOnChanges';
  24054. case LifecycleHooks.AfterContentInit:
  24055. return 'ngAfterContentInit';
  24056. case LifecycleHooks.AfterContentChecked:
  24057. return 'ngAfterContentChecked';
  24058. case LifecycleHooks.AfterViewInit:
  24059. return 'ngAfterViewInit';
  24060. case LifecycleHooks.AfterViewChecked:
  24061. return 'ngAfterViewChecked';
  24062. default:
  24063. // This default case is not needed by TypeScript compiler, as the switch is exhaustive.
  24064. // However Closure Compiler does not understand that and reports an error in typed mode.
  24065. // The `throw new Error` below works around the problem, and the unexpected: never variable
  24066. // makes sure tsc still checks this code is unreachable.
  24067. var unexpected = hook;
  24068. throw new Error("unexpected " + unexpected);
  24069. }
  24070. }
  24071. var ERROR_COMPONENT_TYPE = 'ngComponentType';
  24072. var MISSING_NG_MODULE_METADATA_ERROR_DATA = 'ngMissingNgModuleMetadataErrorData';
  24073. function getMissingNgModuleMetadataErrorData(error) {
  24074. var _a;
  24075. return (_a = error[MISSING_NG_MODULE_METADATA_ERROR_DATA]) !== null && _a !== void 0 ? _a : null;
  24076. }
  24077. // Design notes:
  24078. // - don't lazily create metadata:
  24079. // For some metadata, we need to do async work sometimes,
  24080. // so the user has to kick off this loading.
  24081. // But we want to report errors even when the async work is
  24082. // not required to check that the user would have been able
  24083. // to wait correctly.
  24084. var CompileMetadataResolver = /** @class */ (function () {
  24085. function CompileMetadataResolver(_config, _htmlParser, _ngModuleResolver, _directiveResolver, _pipeResolver, _summaryResolver, _schemaRegistry, _directiveNormalizer, _console, _staticSymbolCache, _reflector, _errorCollector) {
  24086. this._config = _config;
  24087. this._htmlParser = _htmlParser;
  24088. this._ngModuleResolver = _ngModuleResolver;
  24089. this._directiveResolver = _directiveResolver;
  24090. this._pipeResolver = _pipeResolver;
  24091. this._summaryResolver = _summaryResolver;
  24092. this._schemaRegistry = _schemaRegistry;
  24093. this._directiveNormalizer = _directiveNormalizer;
  24094. this._console = _console;
  24095. this._staticSymbolCache = _staticSymbolCache;
  24096. this._reflector = _reflector;
  24097. this._errorCollector = _errorCollector;
  24098. this._nonNormalizedDirectiveCache = new Map();
  24099. this._directiveCache = new Map();
  24100. this._summaryCache = new Map();
  24101. this._pipeCache = new Map();
  24102. this._ngModuleCache = new Map();
  24103. this._ngModuleOfTypes = new Map();
  24104. this._shallowModuleCache = new Map();
  24105. }
  24106. CompileMetadataResolver.prototype.getReflector = function () {
  24107. return this._reflector;
  24108. };
  24109. CompileMetadataResolver.prototype.clearCacheFor = function (type) {
  24110. var dirMeta = this._directiveCache.get(type);
  24111. this._directiveCache.delete(type);
  24112. this._nonNormalizedDirectiveCache.delete(type);
  24113. this._summaryCache.delete(type);
  24114. this._pipeCache.delete(type);
  24115. this._ngModuleOfTypes.delete(type);
  24116. // Clear all of the NgModule as they contain transitive information!
  24117. this._ngModuleCache.clear();
  24118. if (dirMeta) {
  24119. this._directiveNormalizer.clearCacheFor(dirMeta);
  24120. }
  24121. };
  24122. CompileMetadataResolver.prototype.clearCache = function () {
  24123. this._directiveCache.clear();
  24124. this._nonNormalizedDirectiveCache.clear();
  24125. this._summaryCache.clear();
  24126. this._pipeCache.clear();
  24127. this._ngModuleCache.clear();
  24128. this._ngModuleOfTypes.clear();
  24129. this._directiveNormalizer.clearCache();
  24130. };
  24131. CompileMetadataResolver.prototype._createProxyClass = function (baseType, name) {
  24132. var delegate = null;
  24133. var proxyClass = function () {
  24134. if (!delegate) {
  24135. throw new Error("Illegal state: Class " + name + " for type " + stringify(baseType) + " is not compiled yet!");
  24136. }
  24137. return delegate.apply(this, arguments);
  24138. };
  24139. proxyClass.setDelegate = function (d) {
  24140. delegate = d;
  24141. proxyClass.prototype = d.prototype;
  24142. };
  24143. // Make stringify work correctly
  24144. proxyClass.overriddenName = name;
  24145. return proxyClass;
  24146. };
  24147. CompileMetadataResolver.prototype.getGeneratedClass = function (dirType, name) {
  24148. if (dirType instanceof StaticSymbol) {
  24149. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), name);
  24150. }
  24151. else {
  24152. return this._createProxyClass(dirType, name);
  24153. }
  24154. };
  24155. CompileMetadataResolver.prototype.getComponentViewClass = function (dirType) {
  24156. return this.getGeneratedClass(dirType, viewClassName(dirType, 0));
  24157. };
  24158. CompileMetadataResolver.prototype.getHostComponentViewClass = function (dirType) {
  24159. return this.getGeneratedClass(dirType, hostViewClassName(dirType));
  24160. };
  24161. CompileMetadataResolver.prototype.getHostComponentType = function (dirType) {
  24162. var name = identifierName({ reference: dirType }) + "_Host";
  24163. if (dirType instanceof StaticSymbol) {
  24164. return this._staticSymbolCache.get(dirType.filePath, name);
  24165. }
  24166. return this._createProxyClass(dirType, name);
  24167. };
  24168. CompileMetadataResolver.prototype.getRendererType = function (dirType) {
  24169. if (dirType instanceof StaticSymbol) {
  24170. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), rendererTypeName(dirType));
  24171. }
  24172. else {
  24173. // returning an object as proxy,
  24174. // that we fill later during runtime compilation.
  24175. return {};
  24176. }
  24177. };
  24178. CompileMetadataResolver.prototype.getComponentFactory = function (selector, dirType, inputs, outputs) {
  24179. if (dirType instanceof StaticSymbol) {
  24180. return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), componentFactoryName(dirType));
  24181. }
  24182. else {
  24183. var hostView = this.getHostComponentViewClass(dirType);
  24184. // Note: ngContentSelectors will be filled later once the template is
  24185. // loaded.
  24186. var createComponentFactory = this._reflector.resolveExternalReference(Identifiers$1.createComponentFactory);
  24187. return createComponentFactory(selector, dirType, hostView, inputs, outputs, []);
  24188. }
  24189. };
  24190. CompileMetadataResolver.prototype.initComponentFactory = function (factory, ngContentSelectors) {
  24191. var _b;
  24192. if (!(factory instanceof StaticSymbol)) {
  24193. (_b = factory.ngContentSelectors).push.apply(_b, __spreadArray([], __read(ngContentSelectors)));
  24194. }
  24195. };
  24196. CompileMetadataResolver.prototype._loadSummary = function (type, kind) {
  24197. var typeSummary = this._summaryCache.get(type);
  24198. if (!typeSummary) {
  24199. var summary = this._summaryResolver.resolveSummary(type);
  24200. typeSummary = summary ? summary.type : null;
  24201. this._summaryCache.set(type, typeSummary || null);
  24202. }
  24203. return typeSummary && typeSummary.summaryKind === kind ? typeSummary : null;
  24204. };
  24205. CompileMetadataResolver.prototype.getHostComponentMetadata = function (compMeta, hostViewType) {
  24206. var hostType = this.getHostComponentType(compMeta.type.reference);
  24207. if (!hostViewType) {
  24208. hostViewType = this.getHostComponentViewClass(hostType);
  24209. }
  24210. // Note: ! is ok here as this method should only be called with normalized directive
  24211. // metadata, which always fills in the selector.
  24212. var template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate();
  24213. var templateUrl = '';
  24214. var htmlAst = this._htmlParser.parse(template, templateUrl);
  24215. return CompileDirectiveMetadata.create({
  24216. isHost: true,
  24217. type: { reference: hostType, diDeps: [], lifecycleHooks: [] },
  24218. template: new CompileTemplateMetadata({
  24219. encapsulation: ViewEncapsulation.None,
  24220. template: template,
  24221. templateUrl: templateUrl,
  24222. htmlAst: htmlAst,
  24223. styles: [],
  24224. styleUrls: [],
  24225. ngContentSelectors: [],
  24226. animations: [],
  24227. isInline: true,
  24228. externalStylesheets: [],
  24229. interpolation: null,
  24230. preserveWhitespaces: false,
  24231. }),
  24232. exportAs: null,
  24233. changeDetection: ChangeDetectionStrategy.Default,
  24234. inputs: [],
  24235. outputs: [],
  24236. host: {},
  24237. isComponent: true,
  24238. selector: '*',
  24239. providers: [],
  24240. viewProviders: [],
  24241. queries: [],
  24242. guards: {},
  24243. viewQueries: [],
  24244. componentViewType: hostViewType,
  24245. rendererType: { id: '__Host__', encapsulation: ViewEncapsulation.None, styles: [], data: {} },
  24246. entryComponents: [],
  24247. componentFactory: null
  24248. });
  24249. };
  24250. CompileMetadataResolver.prototype.loadDirectiveMetadata = function (ngModuleType, directiveType, isSync) {
  24251. var _this = this;
  24252. if (this._directiveCache.has(directiveType)) {
  24253. return null;
  24254. }
  24255. directiveType = resolveForwardRef(directiveType);
  24256. var _b = this.getNonNormalizedDirectiveMetadata(directiveType), annotation = _b.annotation, metadata = _b.metadata;
  24257. var createDirectiveMetadata = function (templateMetadata) {
  24258. var normalizedDirMeta = new CompileDirectiveMetadata({
  24259. isHost: false,
  24260. type: metadata.type,
  24261. isComponent: metadata.isComponent,
  24262. selector: metadata.selector,
  24263. exportAs: metadata.exportAs,
  24264. changeDetection: metadata.changeDetection,
  24265. inputs: metadata.inputs,
  24266. outputs: metadata.outputs,
  24267. hostListeners: metadata.hostListeners,
  24268. hostProperties: metadata.hostProperties,
  24269. hostAttributes: metadata.hostAttributes,
  24270. providers: metadata.providers,
  24271. viewProviders: metadata.viewProviders,
  24272. queries: metadata.queries,
  24273. guards: metadata.guards,
  24274. viewQueries: metadata.viewQueries,
  24275. entryComponents: metadata.entryComponents,
  24276. componentViewType: metadata.componentViewType,
  24277. rendererType: metadata.rendererType,
  24278. componentFactory: metadata.componentFactory,
  24279. template: templateMetadata
  24280. });
  24281. if (templateMetadata) {
  24282. _this.initComponentFactory(metadata.componentFactory, templateMetadata.ngContentSelectors);
  24283. }
  24284. _this._directiveCache.set(directiveType, normalizedDirMeta);
  24285. _this._summaryCache.set(directiveType, normalizedDirMeta.toSummary());
  24286. return null;
  24287. };
  24288. if (metadata.isComponent) {
  24289. var template = metadata.template;
  24290. var templateMeta = this._directiveNormalizer.normalizeTemplate({
  24291. ngModuleType: ngModuleType,
  24292. componentType: directiveType,
  24293. moduleUrl: this._reflector.componentModuleUrl(directiveType, annotation),
  24294. encapsulation: template.encapsulation,
  24295. template: template.template,
  24296. templateUrl: template.templateUrl,
  24297. styles: template.styles,
  24298. styleUrls: template.styleUrls,
  24299. animations: template.animations,
  24300. interpolation: template.interpolation,
  24301. preserveWhitespaces: template.preserveWhitespaces
  24302. });
  24303. if (isPromise(templateMeta) && isSync) {
  24304. this._reportError(componentStillLoadingError(directiveType), directiveType);
  24305. return null;
  24306. }
  24307. return SyncAsync.then(templateMeta, createDirectiveMetadata);
  24308. }
  24309. else {
  24310. // directive
  24311. createDirectiveMetadata(null);
  24312. return null;
  24313. }
  24314. };
  24315. CompileMetadataResolver.prototype.getNonNormalizedDirectiveMetadata = function (directiveType) {
  24316. var _this = this;
  24317. directiveType = resolveForwardRef(directiveType);
  24318. if (!directiveType) {
  24319. return null;
  24320. }
  24321. var cacheEntry = this._nonNormalizedDirectiveCache.get(directiveType);
  24322. if (cacheEntry) {
  24323. return cacheEntry;
  24324. }
  24325. var dirMeta = this._directiveResolver.resolve(directiveType, false);
  24326. if (!dirMeta) {
  24327. return null;
  24328. }
  24329. var nonNormalizedTemplateMetadata = undefined;
  24330. if (createComponent.isTypeOf(dirMeta)) {
  24331. // component
  24332. var compMeta = dirMeta;
  24333. assertArrayOfStrings('styles', compMeta.styles);
  24334. assertArrayOfStrings('styleUrls', compMeta.styleUrls);
  24335. assertInterpolationSymbols('interpolation', compMeta.interpolation);
  24336. var animations = compMeta.animations;
  24337. nonNormalizedTemplateMetadata = new CompileTemplateMetadata({
  24338. encapsulation: noUndefined(compMeta.encapsulation),
  24339. template: noUndefined(compMeta.template),
  24340. templateUrl: noUndefined(compMeta.templateUrl),
  24341. htmlAst: null,
  24342. styles: compMeta.styles || [],
  24343. styleUrls: compMeta.styleUrls || [],
  24344. animations: animations || [],
  24345. interpolation: noUndefined(compMeta.interpolation),
  24346. isInline: !!compMeta.template,
  24347. externalStylesheets: [],
  24348. ngContentSelectors: [],
  24349. preserveWhitespaces: noUndefined(dirMeta.preserveWhitespaces),
  24350. });
  24351. }
  24352. var changeDetectionStrategy = null;
  24353. var viewProviders = [];
  24354. var entryComponentMetadata = [];
  24355. var selector = dirMeta.selector;
  24356. if (createComponent.isTypeOf(dirMeta)) {
  24357. // Component
  24358. var compMeta = dirMeta;
  24359. changeDetectionStrategy = compMeta.changeDetection;
  24360. if (compMeta.viewProviders) {
  24361. viewProviders = this._getProvidersMetadata(compMeta.viewProviders, entryComponentMetadata, "viewProviders for \"" + stringifyType(directiveType) + "\"", [], directiveType);
  24362. }
  24363. if (compMeta.entryComponents) {
  24364. entryComponentMetadata = flattenAndDedupeArray(compMeta.entryComponents)
  24365. .map(function (type) { return _this._getEntryComponentMetadata(type); })
  24366. .concat(entryComponentMetadata);
  24367. }
  24368. if (!selector) {
  24369. selector = this._schemaRegistry.getDefaultComponentElementName();
  24370. }
  24371. }
  24372. else {
  24373. // Directive
  24374. if (!selector) {
  24375. selector = null;
  24376. }
  24377. }
  24378. var providers = [];
  24379. if (dirMeta.providers != null) {
  24380. providers = this._getProvidersMetadata(dirMeta.providers, entryComponentMetadata, "providers for \"" + stringifyType(directiveType) + "\"", [], directiveType);
  24381. }
  24382. var queries = [];
  24383. var viewQueries = [];
  24384. if (dirMeta.queries != null) {
  24385. queries = this._getQueriesMetadata(dirMeta.queries, false, directiveType);
  24386. viewQueries = this._getQueriesMetadata(dirMeta.queries, true, directiveType);
  24387. }
  24388. var metadata = CompileDirectiveMetadata.create({
  24389. isHost: false,
  24390. selector: selector,
  24391. exportAs: noUndefined(dirMeta.exportAs),
  24392. isComponent: !!nonNormalizedTemplateMetadata,
  24393. type: this._getTypeMetadata(directiveType),
  24394. template: nonNormalizedTemplateMetadata,
  24395. changeDetection: changeDetectionStrategy,
  24396. inputs: dirMeta.inputs || [],
  24397. outputs: dirMeta.outputs || [],
  24398. host: dirMeta.host || {},
  24399. providers: providers || [],
  24400. viewProviders: viewProviders || [],
  24401. queries: queries || [],
  24402. guards: dirMeta.guards || {},
  24403. viewQueries: viewQueries || [],
  24404. entryComponents: entryComponentMetadata,
  24405. componentViewType: nonNormalizedTemplateMetadata ? this.getComponentViewClass(directiveType) :
  24406. null,
  24407. rendererType: nonNormalizedTemplateMetadata ? this.getRendererType(directiveType) : null,
  24408. componentFactory: null
  24409. });
  24410. if (nonNormalizedTemplateMetadata) {
  24411. metadata.componentFactory =
  24412. this.getComponentFactory(selector, directiveType, metadata.inputs, metadata.outputs);
  24413. }
  24414. cacheEntry = { metadata: metadata, annotation: dirMeta };
  24415. this._nonNormalizedDirectiveCache.set(directiveType, cacheEntry);
  24416. return cacheEntry;
  24417. };
  24418. /**
  24419. * Gets the metadata for the given directive.
  24420. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
  24421. */
  24422. CompileMetadataResolver.prototype.getDirectiveMetadata = function (directiveType) {
  24423. var dirMeta = this._directiveCache.get(directiveType);
  24424. if (!dirMeta) {
  24425. this._reportError(syntaxError("Illegal state: getDirectiveMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Directive " + stringifyType(directiveType) + "."), directiveType);
  24426. }
  24427. return dirMeta;
  24428. };
  24429. CompileMetadataResolver.prototype.getDirectiveSummary = function (dirType) {
  24430. var dirSummary = this._loadSummary(dirType, exports.CompileSummaryKind.Directive);
  24431. if (!dirSummary) {
  24432. this._reportError(syntaxError("Illegal state: Could not load the summary for directive " + stringifyType(dirType) + "."), dirType);
  24433. }
  24434. return dirSummary;
  24435. };
  24436. CompileMetadataResolver.prototype.isDirective = function (type) {
  24437. return !!this._loadSummary(type, exports.CompileSummaryKind.Directive) ||
  24438. this._directiveResolver.isDirective(type);
  24439. };
  24440. CompileMetadataResolver.prototype.isAbstractDirective = function (type) {
  24441. var summary = this._loadSummary(type, exports.CompileSummaryKind.Directive);
  24442. if (summary && !summary.isComponent) {
  24443. return !summary.selector;
  24444. }
  24445. var meta = this._directiveResolver.resolve(type, false);
  24446. if (meta && !createComponent.isTypeOf(meta)) {
  24447. return !meta.selector;
  24448. }
  24449. return false;
  24450. };
  24451. CompileMetadataResolver.prototype.isPipe = function (type) {
  24452. return !!this._loadSummary(type, exports.CompileSummaryKind.Pipe) ||
  24453. this._pipeResolver.isPipe(type);
  24454. };
  24455. CompileMetadataResolver.prototype.isNgModule = function (type) {
  24456. return !!this._loadSummary(type, exports.CompileSummaryKind.NgModule) ||
  24457. this._ngModuleResolver.isNgModule(type);
  24458. };
  24459. CompileMetadataResolver.prototype.getNgModuleSummary = function (moduleType, alreadyCollecting) {
  24460. if (alreadyCollecting === void 0) { alreadyCollecting = null; }
  24461. var moduleSummary = this._loadSummary(moduleType, exports.CompileSummaryKind.NgModule);
  24462. if (!moduleSummary) {
  24463. var moduleMeta = this.getNgModuleMetadata(moduleType, false, alreadyCollecting);
  24464. moduleSummary = moduleMeta ? moduleMeta.toSummary() : null;
  24465. if (moduleSummary) {
  24466. this._summaryCache.set(moduleType, moduleSummary);
  24467. }
  24468. }
  24469. return moduleSummary;
  24470. };
  24471. /**
  24472. * Loads the declared directives and pipes of an NgModule.
  24473. */
  24474. CompileMetadataResolver.prototype.loadNgModuleDirectiveAndPipeMetadata = function (moduleType, isSync, throwIfNotFound) {
  24475. var _this = this;
  24476. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  24477. var ngModule = this.getNgModuleMetadata(moduleType, throwIfNotFound);
  24478. var loading = [];
  24479. if (ngModule) {
  24480. ngModule.declaredDirectives.forEach(function (id) {
  24481. var promise = _this.loadDirectiveMetadata(moduleType, id.reference, isSync);
  24482. if (promise) {
  24483. loading.push(promise);
  24484. }
  24485. });
  24486. ngModule.declaredPipes.forEach(function (id) { return _this._loadPipeMetadata(id.reference); });
  24487. }
  24488. return Promise.all(loading);
  24489. };
  24490. CompileMetadataResolver.prototype.getShallowModuleMetadata = function (moduleType) {
  24491. var compileMeta = this._shallowModuleCache.get(moduleType);
  24492. if (compileMeta) {
  24493. return compileMeta;
  24494. }
  24495. var ngModuleMeta = findLast(this._reflector.shallowAnnotations(moduleType), createNgModule.isTypeOf);
  24496. compileMeta = {
  24497. type: this._getTypeMetadata(moduleType),
  24498. rawExports: ngModuleMeta.exports,
  24499. rawImports: ngModuleMeta.imports,
  24500. rawProviders: ngModuleMeta.providers,
  24501. };
  24502. this._shallowModuleCache.set(moduleType, compileMeta);
  24503. return compileMeta;
  24504. };
  24505. CompileMetadataResolver.prototype.getNgModuleMetadata = function (moduleType, throwIfNotFound, alreadyCollecting) {
  24506. var _this = this;
  24507. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  24508. if (alreadyCollecting === void 0) { alreadyCollecting = null; }
  24509. moduleType = resolveForwardRef(moduleType);
  24510. var compileMeta = this._ngModuleCache.get(moduleType);
  24511. if (compileMeta) {
  24512. return compileMeta;
  24513. }
  24514. var meta = this._ngModuleResolver.resolve(moduleType, throwIfNotFound);
  24515. if (!meta) {
  24516. return null;
  24517. }
  24518. var declaredDirectives = [];
  24519. var exportedNonModuleIdentifiers = [];
  24520. var declaredPipes = [];
  24521. var importedModules = [];
  24522. var exportedModules = [];
  24523. var providers = [];
  24524. var entryComponents = [];
  24525. var bootstrapComponents = [];
  24526. var schemas = [];
  24527. if (meta.imports) {
  24528. flattenAndDedupeArray(meta.imports).forEach(function (importedType) {
  24529. var importedModuleType = undefined;
  24530. if (isValidType(importedType)) {
  24531. importedModuleType = importedType;
  24532. }
  24533. else if (importedType && importedType.ngModule) {
  24534. var moduleWithProviders = importedType;
  24535. importedModuleType = moduleWithProviders.ngModule;
  24536. if (moduleWithProviders.providers) {
  24537. providers.push.apply(providers, __spreadArray([], __read(_this._getProvidersMetadata(moduleWithProviders.providers, entryComponents, "provider for the NgModule '" + stringifyType(importedModuleType) + "'", [], importedType))));
  24538. }
  24539. }
  24540. if (importedModuleType) {
  24541. if (_this._checkSelfImport(moduleType, importedModuleType))
  24542. return;
  24543. if (!alreadyCollecting)
  24544. alreadyCollecting = new Set();
  24545. if (alreadyCollecting.has(importedModuleType)) {
  24546. _this._reportError(syntaxError(_this._getTypeDescriptor(importedModuleType) + " '" + stringifyType(importedType) + "' is imported recursively by the module '" + stringifyType(moduleType) + "'."), moduleType);
  24547. return;
  24548. }
  24549. alreadyCollecting.add(importedModuleType);
  24550. var importedModuleSummary = _this.getNgModuleSummary(importedModuleType, alreadyCollecting);
  24551. alreadyCollecting.delete(importedModuleType);
  24552. if (!importedModuleSummary) {
  24553. var err = syntaxError("Unexpected " + _this._getTypeDescriptor(importedType) + " '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'. Please add a @NgModule annotation.");
  24554. // If possible, record additional context for this error to enable more useful
  24555. // diagnostics on the compiler side.
  24556. if (importedType instanceof StaticSymbol) {
  24557. err[MISSING_NG_MODULE_METADATA_ERROR_DATA] = {
  24558. fileName: importedType.filePath,
  24559. className: importedType.name,
  24560. };
  24561. }
  24562. _this._reportError(err, moduleType);
  24563. return;
  24564. }
  24565. importedModules.push(importedModuleSummary);
  24566. }
  24567. else {
  24568. _this._reportError(syntaxError("Unexpected value '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'"), moduleType);
  24569. return;
  24570. }
  24571. });
  24572. }
  24573. if (meta.exports) {
  24574. flattenAndDedupeArray(meta.exports).forEach(function (exportedType) {
  24575. if (!isValidType(exportedType)) {
  24576. _this._reportError(syntaxError("Unexpected value '" + stringifyType(exportedType) + "' exported by the module '" + stringifyType(moduleType) + "'"), moduleType);
  24577. return;
  24578. }
  24579. if (!alreadyCollecting)
  24580. alreadyCollecting = new Set();
  24581. if (alreadyCollecting.has(exportedType)) {
  24582. _this._reportError(syntaxError(_this._getTypeDescriptor(exportedType) + " '" + stringify(exportedType) + "' is exported recursively by the module '" + stringifyType(moduleType) + "'"), moduleType);
  24583. return;
  24584. }
  24585. alreadyCollecting.add(exportedType);
  24586. var exportedModuleSummary = _this.getNgModuleSummary(exportedType, alreadyCollecting);
  24587. alreadyCollecting.delete(exportedType);
  24588. if (exportedModuleSummary) {
  24589. exportedModules.push(exportedModuleSummary);
  24590. }
  24591. else {
  24592. exportedNonModuleIdentifiers.push(_this._getIdentifierMetadata(exportedType));
  24593. }
  24594. });
  24595. }
  24596. // Note: This will be modified later, so we rely on
  24597. // getting a new instance every time!
  24598. var transitiveModule = this._getTransitiveNgModuleMetadata(importedModules, exportedModules);
  24599. if (meta.declarations) {
  24600. flattenAndDedupeArray(meta.declarations).forEach(function (declaredType) {
  24601. if (!isValidType(declaredType)) {
  24602. _this._reportError(syntaxError("Unexpected value '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'"), moduleType);
  24603. return;
  24604. }
  24605. var declaredIdentifier = _this._getIdentifierMetadata(declaredType);
  24606. if (_this.isDirective(declaredType)) {
  24607. if (_this.isAbstractDirective(declaredType)) {
  24608. _this._reportError(syntaxError("Directive " + stringifyType(declaredType) + " has no selector, please add it!"), declaredType);
  24609. }
  24610. transitiveModule.addDirective(declaredIdentifier);
  24611. declaredDirectives.push(declaredIdentifier);
  24612. _this._addTypeToModule(declaredType, moduleType);
  24613. }
  24614. else if (_this.isPipe(declaredType)) {
  24615. transitiveModule.addPipe(declaredIdentifier);
  24616. transitiveModule.pipes.push(declaredIdentifier);
  24617. declaredPipes.push(declaredIdentifier);
  24618. _this._addTypeToModule(declaredType, moduleType);
  24619. }
  24620. else {
  24621. _this._reportError(syntaxError("Unexpected " + _this._getTypeDescriptor(declaredType) + " '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'. Please add a @Pipe/@Directive/@Component annotation."), moduleType);
  24622. return;
  24623. }
  24624. });
  24625. }
  24626. var exportedDirectives = [];
  24627. var exportedPipes = [];
  24628. exportedNonModuleIdentifiers.forEach(function (exportedId) {
  24629. if (transitiveModule.directivesSet.has(exportedId.reference)) {
  24630. exportedDirectives.push(exportedId);
  24631. transitiveModule.addExportedDirective(exportedId);
  24632. }
  24633. else if (transitiveModule.pipesSet.has(exportedId.reference)) {
  24634. exportedPipes.push(exportedId);
  24635. transitiveModule.addExportedPipe(exportedId);
  24636. }
  24637. else {
  24638. _this._reportError(syntaxError("Can't export " + _this._getTypeDescriptor(exportedId.reference) + " " + stringifyType(exportedId.reference) + " from " + stringifyType(moduleType) + " as it was neither declared nor imported!"), moduleType);
  24639. return;
  24640. }
  24641. });
  24642. // The providers of the module have to go last
  24643. // so that they overwrite any other provider we already added.
  24644. if (meta.providers) {
  24645. providers.push.apply(providers, __spreadArray([], __read(this._getProvidersMetadata(meta.providers, entryComponents, "provider for the NgModule '" + stringifyType(moduleType) + "'", [], moduleType))));
  24646. }
  24647. if (meta.entryComponents) {
  24648. entryComponents.push.apply(entryComponents, __spreadArray([], __read(flattenAndDedupeArray(meta.entryComponents)
  24649. .map(function (type) { return _this._getEntryComponentMetadata(type); }))));
  24650. }
  24651. if (meta.bootstrap) {
  24652. flattenAndDedupeArray(meta.bootstrap).forEach(function (type) {
  24653. if (!isValidType(type)) {
  24654. _this._reportError(syntaxError("Unexpected value '" + stringifyType(type) + "' used in the bootstrap property of module '" + stringifyType(moduleType) + "'"), moduleType);
  24655. return;
  24656. }
  24657. bootstrapComponents.push(_this._getIdentifierMetadata(type));
  24658. });
  24659. }
  24660. entryComponents.push.apply(entryComponents, __spreadArray([], __read(bootstrapComponents.map(function (type) { return _this._getEntryComponentMetadata(type.reference); }))));
  24661. if (meta.schemas) {
  24662. schemas.push.apply(schemas, __spreadArray([], __read(flattenAndDedupeArray(meta.schemas))));
  24663. }
  24664. compileMeta = new CompileNgModuleMetadata({
  24665. type: this._getTypeMetadata(moduleType),
  24666. providers: providers,
  24667. entryComponents: entryComponents,
  24668. bootstrapComponents: bootstrapComponents,
  24669. schemas: schemas,
  24670. declaredDirectives: declaredDirectives,
  24671. exportedDirectives: exportedDirectives,
  24672. declaredPipes: declaredPipes,
  24673. exportedPipes: exportedPipes,
  24674. importedModules: importedModules,
  24675. exportedModules: exportedModules,
  24676. transitiveModule: transitiveModule,
  24677. id: meta.id || null,
  24678. });
  24679. entryComponents.forEach(function (id) { return transitiveModule.addEntryComponent(id); });
  24680. providers.forEach(function (provider) { return transitiveModule.addProvider(provider, compileMeta.type); });
  24681. transitiveModule.addModule(compileMeta.type);
  24682. this._ngModuleCache.set(moduleType, compileMeta);
  24683. return compileMeta;
  24684. };
  24685. CompileMetadataResolver.prototype._checkSelfImport = function (moduleType, importedModuleType) {
  24686. if (moduleType === importedModuleType) {
  24687. this._reportError(syntaxError("'" + stringifyType(moduleType) + "' module can't import itself"), moduleType);
  24688. return true;
  24689. }
  24690. return false;
  24691. };
  24692. CompileMetadataResolver.prototype._getTypeDescriptor = function (type) {
  24693. if (isValidType(type)) {
  24694. if (this.isDirective(type)) {
  24695. return 'directive';
  24696. }
  24697. if (this.isPipe(type)) {
  24698. return 'pipe';
  24699. }
  24700. if (this.isNgModule(type)) {
  24701. return 'module';
  24702. }
  24703. }
  24704. if (type.provide) {
  24705. return 'provider';
  24706. }
  24707. return 'value';
  24708. };
  24709. CompileMetadataResolver.prototype._addTypeToModule = function (type, moduleType) {
  24710. var oldModule = this._ngModuleOfTypes.get(type);
  24711. if (oldModule && oldModule !== moduleType) {
  24712. this._reportError(syntaxError("Type " + stringifyType(type) + " is part of the declarations of 2 modules: " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + "! " +
  24713. ("Please consider moving " + stringifyType(type) + " to a higher module that imports " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ". ") +
  24714. ("You can also create a new NgModule that exports and includes " + stringifyType(type) + " then import that NgModule in " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ".")), moduleType);
  24715. return;
  24716. }
  24717. this._ngModuleOfTypes.set(type, moduleType);
  24718. };
  24719. CompileMetadataResolver.prototype._getTransitiveNgModuleMetadata = function (importedModules, exportedModules) {
  24720. // collect `providers` / `entryComponents` from all imported and all exported modules
  24721. var result = new TransitiveCompileNgModuleMetadata();
  24722. var modulesByToken = new Map();
  24723. importedModules.concat(exportedModules).forEach(function (modSummary) {
  24724. modSummary.modules.forEach(function (mod) { return result.addModule(mod); });
  24725. modSummary.entryComponents.forEach(function (comp) { return result.addEntryComponent(comp); });
  24726. var addedTokens = new Set();
  24727. modSummary.providers.forEach(function (entry) {
  24728. var tokenRef = tokenReference(entry.provider.token);
  24729. var prevModules = modulesByToken.get(tokenRef);
  24730. if (!prevModules) {
  24731. prevModules = new Set();
  24732. modulesByToken.set(tokenRef, prevModules);
  24733. }
  24734. var moduleRef = entry.module.reference;
  24735. // Note: the providers of one module may still contain multiple providers
  24736. // per token (e.g. for multi providers), and we need to preserve these.
  24737. if (addedTokens.has(tokenRef) || !prevModules.has(moduleRef)) {
  24738. prevModules.add(moduleRef);
  24739. addedTokens.add(tokenRef);
  24740. result.addProvider(entry.provider, entry.module);
  24741. }
  24742. });
  24743. });
  24744. exportedModules.forEach(function (modSummary) {
  24745. modSummary.exportedDirectives.forEach(function (id) { return result.addExportedDirective(id); });
  24746. modSummary.exportedPipes.forEach(function (id) { return result.addExportedPipe(id); });
  24747. });
  24748. importedModules.forEach(function (modSummary) {
  24749. modSummary.exportedDirectives.forEach(function (id) { return result.addDirective(id); });
  24750. modSummary.exportedPipes.forEach(function (id) { return result.addPipe(id); });
  24751. });
  24752. return result;
  24753. };
  24754. CompileMetadataResolver.prototype._getIdentifierMetadata = function (type) {
  24755. type = resolveForwardRef(type);
  24756. return { reference: type };
  24757. };
  24758. CompileMetadataResolver.prototype.isInjectable = function (type) {
  24759. var annotations = this._reflector.tryAnnotations(type);
  24760. return annotations.some(function (ann) { return createInjectable.isTypeOf(ann); });
  24761. };
  24762. CompileMetadataResolver.prototype.getInjectableSummary = function (type) {
  24763. return {
  24764. summaryKind: exports.CompileSummaryKind.Injectable,
  24765. type: this._getTypeMetadata(type, null, false)
  24766. };
  24767. };
  24768. CompileMetadataResolver.prototype.getInjectableMetadata = function (type, dependencies, throwOnUnknownDeps) {
  24769. if (dependencies === void 0) { dependencies = null; }
  24770. if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
  24771. var typeSummary = this._loadSummary(type, exports.CompileSummaryKind.Injectable);
  24772. var typeMetadata = typeSummary ?
  24773. typeSummary.type :
  24774. this._getTypeMetadata(type, dependencies, throwOnUnknownDeps);
  24775. var annotations = this._reflector.annotations(type).filter(function (ann) { return createInjectable.isTypeOf(ann); });
  24776. if (annotations.length === 0) {
  24777. return null;
  24778. }
  24779. var meta = annotations[annotations.length - 1];
  24780. return {
  24781. symbol: type,
  24782. type: typeMetadata,
  24783. providedIn: meta.providedIn,
  24784. useValue: meta.useValue,
  24785. useClass: meta.useClass,
  24786. useExisting: meta.useExisting,
  24787. useFactory: meta.useFactory,
  24788. deps: meta.deps,
  24789. };
  24790. };
  24791. CompileMetadataResolver.prototype._getTypeMetadata = function (type, dependencies, throwOnUnknownDeps) {
  24792. if (dependencies === void 0) { dependencies = null; }
  24793. if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
  24794. var identifier = this._getIdentifierMetadata(type);
  24795. return {
  24796. reference: identifier.reference,
  24797. diDeps: this._getDependenciesMetadata(identifier.reference, dependencies, throwOnUnknownDeps),
  24798. lifecycleHooks: getAllLifecycleHooks(this._reflector, identifier.reference),
  24799. };
  24800. };
  24801. CompileMetadataResolver.prototype._getFactoryMetadata = function (factory, dependencies) {
  24802. if (dependencies === void 0) { dependencies = null; }
  24803. factory = resolveForwardRef(factory);
  24804. return { reference: factory, diDeps: this._getDependenciesMetadata(factory, dependencies) };
  24805. };
  24806. /**
  24807. * Gets the metadata for the given pipe.
  24808. * This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
  24809. */
  24810. CompileMetadataResolver.prototype.getPipeMetadata = function (pipeType) {
  24811. var pipeMeta = this._pipeCache.get(pipeType);
  24812. if (!pipeMeta) {
  24813. this._reportError(syntaxError("Illegal state: getPipeMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Pipe " + stringifyType(pipeType) + "."), pipeType);
  24814. }
  24815. return pipeMeta || null;
  24816. };
  24817. CompileMetadataResolver.prototype.getPipeSummary = function (pipeType) {
  24818. var pipeSummary = this._loadSummary(pipeType, exports.CompileSummaryKind.Pipe);
  24819. if (!pipeSummary) {
  24820. this._reportError(syntaxError("Illegal state: Could not load the summary for pipe " + stringifyType(pipeType) + "."), pipeType);
  24821. }
  24822. return pipeSummary;
  24823. };
  24824. CompileMetadataResolver.prototype.getOrLoadPipeMetadata = function (pipeType) {
  24825. var pipeMeta = this._pipeCache.get(pipeType);
  24826. if (!pipeMeta) {
  24827. pipeMeta = this._loadPipeMetadata(pipeType);
  24828. }
  24829. return pipeMeta;
  24830. };
  24831. CompileMetadataResolver.prototype._loadPipeMetadata = function (pipeType) {
  24832. pipeType = resolveForwardRef(pipeType);
  24833. var pipeAnnotation = this._pipeResolver.resolve(pipeType);
  24834. var pipeMeta = new CompilePipeMetadata({
  24835. type: this._getTypeMetadata(pipeType),
  24836. name: pipeAnnotation.name,
  24837. pure: !!pipeAnnotation.pure
  24838. });
  24839. this._pipeCache.set(pipeType, pipeMeta);
  24840. this._summaryCache.set(pipeType, pipeMeta.toSummary());
  24841. return pipeMeta;
  24842. };
  24843. CompileMetadataResolver.prototype._getDependenciesMetadata = function (typeOrFunc, dependencies, throwOnUnknownDeps) {
  24844. var _this = this;
  24845. if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
  24846. var hasUnknownDeps = false;
  24847. var params = dependencies || this._reflector.parameters(typeOrFunc) || [];
  24848. var dependenciesMetadata = params.map(function (param) {
  24849. var isAttribute = false;
  24850. var isHost = false;
  24851. var isSelf = false;
  24852. var isSkipSelf = false;
  24853. var isOptional = false;
  24854. var token = null;
  24855. if (Array.isArray(param)) {
  24856. param.forEach(function (paramEntry) {
  24857. if (createHost.isTypeOf(paramEntry)) {
  24858. isHost = true;
  24859. }
  24860. else if (createSelf.isTypeOf(paramEntry)) {
  24861. isSelf = true;
  24862. }
  24863. else if (createSkipSelf.isTypeOf(paramEntry)) {
  24864. isSkipSelf = true;
  24865. }
  24866. else if (createOptional.isTypeOf(paramEntry)) {
  24867. isOptional = true;
  24868. }
  24869. else if (createAttribute.isTypeOf(paramEntry)) {
  24870. isAttribute = true;
  24871. token = paramEntry.attributeName;
  24872. }
  24873. else if (createInject.isTypeOf(paramEntry)) {
  24874. token = paramEntry.token;
  24875. }
  24876. else if (createInjectionToken.isTypeOf(paramEntry) ||
  24877. paramEntry instanceof StaticSymbol) {
  24878. token = paramEntry;
  24879. }
  24880. else if (isValidType(paramEntry) && token == null) {
  24881. token = paramEntry;
  24882. }
  24883. });
  24884. }
  24885. else {
  24886. token = param;
  24887. }
  24888. if (token == null) {
  24889. hasUnknownDeps = true;
  24890. return {};
  24891. }
  24892. return {
  24893. isAttribute: isAttribute,
  24894. isHost: isHost,
  24895. isSelf: isSelf,
  24896. isSkipSelf: isSkipSelf,
  24897. isOptional: isOptional,
  24898. token: _this._getTokenMetadata(token)
  24899. };
  24900. });
  24901. if (hasUnknownDeps) {
  24902. var depsTokens = dependenciesMetadata.map(function (dep) { return dep.token ? stringifyType(dep.token) : '?'; }).join(', ');
  24903. var message = "Can't resolve all parameters for " + stringifyType(typeOrFunc) + ": (" + depsTokens + ").";
  24904. if (throwOnUnknownDeps || this._config.strictInjectionParameters) {
  24905. this._reportError(syntaxError(message), typeOrFunc);
  24906. }
  24907. }
  24908. return dependenciesMetadata;
  24909. };
  24910. CompileMetadataResolver.prototype._getTokenMetadata = function (token) {
  24911. token = resolveForwardRef(token);
  24912. var compileToken;
  24913. if (typeof token === 'string') {
  24914. compileToken = { value: token };
  24915. }
  24916. else {
  24917. compileToken = { identifier: { reference: token } };
  24918. }
  24919. return compileToken;
  24920. };
  24921. CompileMetadataResolver.prototype._getProvidersMetadata = function (providers, targetEntryComponents, debugInfo, compileProviders, type) {
  24922. var _this = this;
  24923. if (compileProviders === void 0) { compileProviders = []; }
  24924. providers.forEach(function (provider, providerIdx) {
  24925. if (Array.isArray(provider)) {
  24926. _this._getProvidersMetadata(provider, targetEntryComponents, debugInfo, compileProviders);
  24927. }
  24928. else {
  24929. provider = resolveForwardRef(provider);
  24930. var providerMeta = undefined;
  24931. if (provider && typeof provider === 'object' && provider.hasOwnProperty('provide')) {
  24932. _this._validateProvider(provider);
  24933. providerMeta = new ProviderMeta(provider.provide, provider);
  24934. }
  24935. else if (isValidType(provider)) {
  24936. providerMeta = new ProviderMeta(provider, { useClass: provider });
  24937. }
  24938. else if (provider === void 0) {
  24939. _this._reportError(syntaxError("Encountered undefined provider! Usually this means you have a circular dependencies. This might be caused by using 'barrel' index.ts files."));
  24940. return;
  24941. }
  24942. else {
  24943. var providersInfo = providers
  24944. .reduce(function (soFar, seenProvider, seenProviderIdx) {
  24945. if (seenProviderIdx < providerIdx) {
  24946. soFar.push("" + stringifyType(seenProvider));
  24947. }
  24948. else if (seenProviderIdx == providerIdx) {
  24949. soFar.push("?" + stringifyType(seenProvider) + "?");
  24950. }
  24951. else if (seenProviderIdx == providerIdx + 1) {
  24952. soFar.push('...');
  24953. }
  24954. return soFar;
  24955. }, [])
  24956. .join(', ');
  24957. _this._reportError(syntaxError("Invalid " + (debugInfo ?
  24958. debugInfo :
  24959. 'provider') + " - only instances of Provider and Type are allowed, got: [" + providersInfo + "]"), type);
  24960. return;
  24961. }
  24962. if (providerMeta.token ===
  24963. _this._reflector.resolveExternalReference(Identifiers$1.ANALYZE_FOR_ENTRY_COMPONENTS)) {
  24964. targetEntryComponents.push.apply(targetEntryComponents, __spreadArray([], __read(_this._getEntryComponentsFromProvider(providerMeta, type))));
  24965. }
  24966. else {
  24967. compileProviders.push(_this.getProviderMetadata(providerMeta));
  24968. }
  24969. }
  24970. });
  24971. return compileProviders;
  24972. };
  24973. CompileMetadataResolver.prototype._validateProvider = function (provider) {
  24974. if (provider.hasOwnProperty('useClass') && provider.useClass == null) {
  24975. this._reportError(syntaxError("Invalid provider for " + stringifyType(provider.provide) + ". useClass cannot be " + provider.useClass + ".\n Usually it happens when:\n 1. There's a circular dependency (might be caused by using index.ts (barrel) files).\n 2. Class was used before it was declared. Use forwardRef in this case."));
  24976. }
  24977. };
  24978. CompileMetadataResolver.prototype._getEntryComponentsFromProvider = function (provider, type) {
  24979. var _this = this;
  24980. var components = [];
  24981. var collectedIdentifiers = [];
  24982. if (provider.useFactory || provider.useExisting || provider.useClass) {
  24983. this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports useValue!"), type);
  24984. return [];
  24985. }
  24986. if (!provider.multi) {
  24987. this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports 'multi = true'!"), type);
  24988. return [];
  24989. }
  24990. extractIdentifiers(provider.useValue, collectedIdentifiers);
  24991. collectedIdentifiers.forEach(function (identifier) {
  24992. var entry = _this._getEntryComponentMetadata(identifier.reference, false);
  24993. if (entry) {
  24994. components.push(entry);
  24995. }
  24996. });
  24997. return components;
  24998. };
  24999. CompileMetadataResolver.prototype._getEntryComponentMetadata = function (dirType, throwIfNotFound) {
  25000. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  25001. var dirMeta = this.getNonNormalizedDirectiveMetadata(dirType);
  25002. if (dirMeta && dirMeta.metadata.isComponent) {
  25003. return { componentType: dirType, componentFactory: dirMeta.metadata.componentFactory };
  25004. }
  25005. var dirSummary = this._loadSummary(dirType, exports.CompileSummaryKind.Directive);
  25006. if (dirSummary && dirSummary.isComponent) {
  25007. return { componentType: dirType, componentFactory: dirSummary.componentFactory };
  25008. }
  25009. if (throwIfNotFound) {
  25010. throw syntaxError(dirType.name + " cannot be used as an entry component.");
  25011. }
  25012. return null;
  25013. };
  25014. CompileMetadataResolver.prototype._getInjectableTypeMetadata = function (type, dependencies) {
  25015. if (dependencies === void 0) { dependencies = null; }
  25016. var typeSummary = this._loadSummary(type, exports.CompileSummaryKind.Injectable);
  25017. if (typeSummary) {
  25018. return typeSummary.type;
  25019. }
  25020. return this._getTypeMetadata(type, dependencies);
  25021. };
  25022. CompileMetadataResolver.prototype.getProviderMetadata = function (provider) {
  25023. var compileDeps = undefined;
  25024. var compileTypeMetadata = null;
  25025. var compileFactoryMetadata = null;
  25026. var token = this._getTokenMetadata(provider.token);
  25027. if (provider.useClass) {
  25028. compileTypeMetadata =
  25029. this._getInjectableTypeMetadata(provider.useClass, provider.dependencies);
  25030. compileDeps = compileTypeMetadata.diDeps;
  25031. if (provider.token === provider.useClass) {
  25032. // use the compileTypeMetadata as it contains information about lifecycleHooks...
  25033. token = { identifier: compileTypeMetadata };
  25034. }
  25035. }
  25036. else if (provider.useFactory) {
  25037. compileFactoryMetadata = this._getFactoryMetadata(provider.useFactory, provider.dependencies);
  25038. compileDeps = compileFactoryMetadata.diDeps;
  25039. }
  25040. return {
  25041. token: token,
  25042. useClass: compileTypeMetadata,
  25043. useValue: provider.useValue,
  25044. useFactory: compileFactoryMetadata,
  25045. useExisting: provider.useExisting ? this._getTokenMetadata(provider.useExisting) : undefined,
  25046. deps: compileDeps,
  25047. multi: provider.multi
  25048. };
  25049. };
  25050. CompileMetadataResolver.prototype._getQueriesMetadata = function (queries, isViewQuery, directiveType) {
  25051. var _this = this;
  25052. var res = [];
  25053. Object.keys(queries).forEach(function (propertyName) {
  25054. var query = queries[propertyName];
  25055. if (query.isViewQuery === isViewQuery) {
  25056. res.push(_this._getQueryMetadata(query, propertyName, directiveType));
  25057. }
  25058. });
  25059. return res;
  25060. };
  25061. CompileMetadataResolver.prototype._queryVarBindings = function (selector) {
  25062. return selector.split(/\s*,\s*/);
  25063. };
  25064. CompileMetadataResolver.prototype._getQueryMetadata = function (q, propertyName, typeOrFunc) {
  25065. var _this = this;
  25066. var selectors;
  25067. if (typeof q.selector === 'string') {
  25068. selectors =
  25069. this._queryVarBindings(q.selector).map(function (varName) { return _this._getTokenMetadata(varName); });
  25070. }
  25071. else {
  25072. if (!q.selector) {
  25073. this._reportError(syntaxError("Can't construct a query for the property \"" + propertyName + "\" of \"" + stringifyType(typeOrFunc) + "\" since the query selector wasn't defined."), typeOrFunc);
  25074. selectors = [];
  25075. }
  25076. else {
  25077. selectors = [this._getTokenMetadata(q.selector)];
  25078. }
  25079. }
  25080. return {
  25081. selectors: selectors,
  25082. first: q.first,
  25083. descendants: q.descendants,
  25084. emitDistinctChangesOnly: q.emitDistinctChangesOnly,
  25085. propertyName: propertyName,
  25086. read: q.read ? this._getTokenMetadata(q.read) : null,
  25087. static: q.static
  25088. };
  25089. };
  25090. CompileMetadataResolver.prototype._reportError = function (error, type, otherType) {
  25091. if (this._errorCollector) {
  25092. this._errorCollector(error, type);
  25093. if (otherType) {
  25094. this._errorCollector(error, otherType);
  25095. }
  25096. }
  25097. else {
  25098. throw error;
  25099. }
  25100. };
  25101. return CompileMetadataResolver;
  25102. }());
  25103. function flattenArray(tree, out) {
  25104. if (out === void 0) { out = []; }
  25105. if (tree) {
  25106. for (var i = 0; i < tree.length; i++) {
  25107. var item = resolveForwardRef(tree[i]);
  25108. if (Array.isArray(item)) {
  25109. flattenArray(item, out);
  25110. }
  25111. else {
  25112. out.push(item);
  25113. }
  25114. }
  25115. }
  25116. return out;
  25117. }
  25118. function dedupeArray(array) {
  25119. if (array) {
  25120. return Array.from(new Set(array));
  25121. }
  25122. return [];
  25123. }
  25124. function flattenAndDedupeArray(tree) {
  25125. return dedupeArray(flattenArray(tree));
  25126. }
  25127. function isValidType(value) {
  25128. return (value instanceof StaticSymbol) || (value instanceof Type);
  25129. }
  25130. function extractIdentifiers(value, targetIdentifiers) {
  25131. visitValue(value, new _CompileValueConverter(), targetIdentifiers);
  25132. }
  25133. var _CompileValueConverter = /** @class */ (function (_super) {
  25134. __extends(_CompileValueConverter, _super);
  25135. function _CompileValueConverter() {
  25136. return _super !== null && _super.apply(this, arguments) || this;
  25137. }
  25138. _CompileValueConverter.prototype.visitOther = function (value, targetIdentifiers) {
  25139. targetIdentifiers.push({ reference: value });
  25140. };
  25141. return _CompileValueConverter;
  25142. }(ValueTransformer));
  25143. function stringifyType(type) {
  25144. if (type instanceof StaticSymbol) {
  25145. return type.name + " in " + type.filePath;
  25146. }
  25147. else {
  25148. return stringify(type);
  25149. }
  25150. }
  25151. /**
  25152. * Indicates that a component is still being loaded in a synchronous compile.
  25153. */
  25154. function componentStillLoadingError(compType) {
  25155. var error = Error("Can't compile synchronously as " + stringify(compType) + " is still being loaded!");
  25156. error[ERROR_COMPONENT_TYPE] = compType;
  25157. return error;
  25158. }
  25159. /**
  25160. * @license
  25161. * Copyright Google LLC All Rights Reserved.
  25162. *
  25163. * Use of this source code is governed by an MIT-style license that can be
  25164. * found in the LICENSE file at https://angular.io/license
  25165. */
  25166. function providerDef(ctx, providerAst) {
  25167. var flags = 0 /* None */;
  25168. if (!providerAst.eager) {
  25169. flags |= 4096 /* LazyProvider */;
  25170. }
  25171. if (providerAst.providerType === exports.ProviderAstType.PrivateService) {
  25172. flags |= 8192 /* PrivateProvider */;
  25173. }
  25174. if (providerAst.isModule) {
  25175. flags |= 1073741824 /* TypeModuleProvider */;
  25176. }
  25177. providerAst.lifecycleHooks.forEach(function (lifecycleHook) {
  25178. // for regular providers, we only support ngOnDestroy
  25179. if (lifecycleHook === LifecycleHooks.OnDestroy ||
  25180. providerAst.providerType === exports.ProviderAstType.Directive ||
  25181. providerAst.providerType === exports.ProviderAstType.Component) {
  25182. flags |= lifecycleHookToNodeFlag(lifecycleHook);
  25183. }
  25184. });
  25185. var _a = providerAst.multiProvider ?
  25186. multiProviderDef(ctx, flags, providerAst.providers) :
  25187. singleProviderDef(ctx, flags, providerAst.providerType, providerAst.providers[0]), providerExpr = _a.providerExpr, providerFlags = _a.flags, depsExpr = _a.depsExpr;
  25188. return {
  25189. providerExpr: providerExpr,
  25190. flags: providerFlags,
  25191. depsExpr: depsExpr,
  25192. tokenExpr: tokenExpr(ctx, providerAst.token),
  25193. };
  25194. }
  25195. function multiProviderDef(ctx, flags, providers) {
  25196. var allDepDefs = [];
  25197. var allParams = [];
  25198. var exprs = providers.map(function (provider, providerIndex) {
  25199. var expr;
  25200. if (provider.useClass) {
  25201. var depExprs = convertDeps(providerIndex, provider.deps || provider.useClass.diDeps);
  25202. expr = ctx.importExpr(provider.useClass.reference).instantiate(depExprs);
  25203. }
  25204. else if (provider.useFactory) {
  25205. var depExprs = convertDeps(providerIndex, provider.deps || provider.useFactory.diDeps);
  25206. expr = ctx.importExpr(provider.useFactory.reference).callFn(depExprs);
  25207. }
  25208. else if (provider.useExisting) {
  25209. var depExprs = convertDeps(providerIndex, [{ token: provider.useExisting }]);
  25210. expr = depExprs[0];
  25211. }
  25212. else {
  25213. expr = convertValueToOutputAst(ctx, provider.useValue);
  25214. }
  25215. return expr;
  25216. });
  25217. var providerExpr = fn(allParams, [new ReturnStatement(literalArr(exprs))], INFERRED_TYPE);
  25218. return {
  25219. providerExpr: providerExpr,
  25220. flags: flags | 1024 /* TypeFactoryProvider */,
  25221. depsExpr: literalArr(allDepDefs)
  25222. };
  25223. function convertDeps(providerIndex, deps) {
  25224. return deps.map(function (dep, depIndex) {
  25225. var paramName = "p" + providerIndex + "_" + depIndex;
  25226. allParams.push(new FnParam(paramName, DYNAMIC_TYPE));
  25227. allDepDefs.push(depDef(ctx, dep));
  25228. return variable(paramName);
  25229. });
  25230. }
  25231. }
  25232. function singleProviderDef(ctx, flags, providerType, providerMeta) {
  25233. var providerExpr;
  25234. var deps;
  25235. if (providerType === exports.ProviderAstType.Directive || providerType === exports.ProviderAstType.Component) {
  25236. providerExpr = ctx.importExpr(providerMeta.useClass.reference);
  25237. flags |= 16384 /* TypeDirective */;
  25238. deps = providerMeta.deps || providerMeta.useClass.diDeps;
  25239. }
  25240. else {
  25241. if (providerMeta.useClass) {
  25242. providerExpr = ctx.importExpr(providerMeta.useClass.reference);
  25243. flags |= 512 /* TypeClassProvider */;
  25244. deps = providerMeta.deps || providerMeta.useClass.diDeps;
  25245. }
  25246. else if (providerMeta.useFactory) {
  25247. providerExpr = ctx.importExpr(providerMeta.useFactory.reference);
  25248. flags |= 1024 /* TypeFactoryProvider */;
  25249. deps = providerMeta.deps || providerMeta.useFactory.diDeps;
  25250. }
  25251. else if (providerMeta.useExisting) {
  25252. providerExpr = NULL_EXPR;
  25253. flags |= 2048 /* TypeUseExistingProvider */;
  25254. deps = [{ token: providerMeta.useExisting }];
  25255. }
  25256. else {
  25257. providerExpr = convertValueToOutputAst(ctx, providerMeta.useValue);
  25258. flags |= 256 /* TypeValueProvider */;
  25259. deps = [];
  25260. }
  25261. }
  25262. var depsExpr = literalArr(deps.map(function (dep) { return depDef(ctx, dep); }));
  25263. return { providerExpr: providerExpr, flags: flags, depsExpr: depsExpr };
  25264. }
  25265. function tokenExpr(ctx, tokenMeta) {
  25266. return tokenMeta.identifier ? ctx.importExpr(tokenMeta.identifier.reference) :
  25267. literal(tokenMeta.value);
  25268. }
  25269. function depDef(ctx, dep) {
  25270. // Note: the following fields have already been normalized out by provider_analyzer:
  25271. // - isAttribute, isHost
  25272. var expr = dep.isValue ? convertValueToOutputAst(ctx, dep.value) : tokenExpr(ctx, dep.token);
  25273. var flags = 0 /* None */;
  25274. if (dep.isSkipSelf) {
  25275. flags |= 1 /* SkipSelf */;
  25276. }
  25277. if (dep.isOptional) {
  25278. flags |= 2 /* Optional */;
  25279. }
  25280. if (dep.isSelf) {
  25281. flags |= 4 /* Self */;
  25282. }
  25283. if (dep.isValue) {
  25284. flags |= 8 /* Value */;
  25285. }
  25286. return flags === 0 /* None */ ? expr : literalArr([literal(flags), expr]);
  25287. }
  25288. function lifecycleHookToNodeFlag(lifecycleHook) {
  25289. var nodeFlag = 0 /* None */;
  25290. switch (lifecycleHook) {
  25291. case LifecycleHooks.AfterContentChecked:
  25292. nodeFlag = 2097152 /* AfterContentChecked */;
  25293. break;
  25294. case LifecycleHooks.AfterContentInit:
  25295. nodeFlag = 1048576 /* AfterContentInit */;
  25296. break;
  25297. case LifecycleHooks.AfterViewChecked:
  25298. nodeFlag = 8388608 /* AfterViewChecked */;
  25299. break;
  25300. case LifecycleHooks.AfterViewInit:
  25301. nodeFlag = 4194304 /* AfterViewInit */;
  25302. break;
  25303. case LifecycleHooks.DoCheck:
  25304. nodeFlag = 262144 /* DoCheck */;
  25305. break;
  25306. case LifecycleHooks.OnChanges:
  25307. nodeFlag = 524288 /* OnChanges */;
  25308. break;
  25309. case LifecycleHooks.OnDestroy:
  25310. nodeFlag = 131072 /* OnDestroy */;
  25311. break;
  25312. case LifecycleHooks.OnInit:
  25313. nodeFlag = 65536 /* OnInit */;
  25314. break;
  25315. }
  25316. return nodeFlag;
  25317. }
  25318. function componentFactoryResolverProviderDef(reflector, ctx, flags, entryComponents) {
  25319. var entryComponentFactories = entryComponents.map(function (entryComponent) { return ctx.importExpr(entryComponent.componentFactory); });
  25320. var token = createTokenForExternalReference(reflector, Identifiers$1.ComponentFactoryResolver);
  25321. var classMeta = {
  25322. diDeps: [
  25323. { isValue: true, value: literalArr(entryComponentFactories) },
  25324. { token: token, isSkipSelf: true, isOptional: true },
  25325. { token: createTokenForExternalReference(reflector, Identifiers$1.NgModuleRef) },
  25326. ],
  25327. lifecycleHooks: [],
  25328. reference: reflector.resolveExternalReference(Identifiers$1.CodegenComponentFactoryResolver)
  25329. };
  25330. var _a = singleProviderDef(ctx, flags, exports.ProviderAstType.PrivateService, {
  25331. token: token,
  25332. multi: false,
  25333. useClass: classMeta,
  25334. }), providerExpr = _a.providerExpr, providerFlags = _a.flags, depsExpr = _a.depsExpr;
  25335. return { providerExpr: providerExpr, flags: providerFlags, depsExpr: depsExpr, tokenExpr: tokenExpr(ctx, token) };
  25336. }
  25337. /**
  25338. * @license
  25339. * Copyright Google LLC All Rights Reserved.
  25340. *
  25341. * Use of this source code is governed by an MIT-style license that can be
  25342. * found in the LICENSE file at https://angular.io/license
  25343. */
  25344. var NgModuleCompileResult = /** @class */ (function () {
  25345. function NgModuleCompileResult(ngModuleFactoryVar) {
  25346. this.ngModuleFactoryVar = ngModuleFactoryVar;
  25347. }
  25348. return NgModuleCompileResult;
  25349. }());
  25350. var LOG_VAR = variable('_l');
  25351. var NgModuleCompiler = /** @class */ (function () {
  25352. function NgModuleCompiler(reflector) {
  25353. this.reflector = reflector;
  25354. }
  25355. NgModuleCompiler.prototype.compile = function (ctx, ngModuleMeta, extraProviders) {
  25356. var sourceSpan = typeSourceSpan('NgModule', ngModuleMeta.type);
  25357. var entryComponentFactories = ngModuleMeta.transitiveModule.entryComponents;
  25358. var bootstrapComponents = ngModuleMeta.bootstrapComponents;
  25359. var providerParser = new NgModuleProviderAnalyzer(this.reflector, ngModuleMeta, extraProviders, sourceSpan);
  25360. var providerDefs = [componentFactoryResolverProviderDef(this.reflector, ctx, 0 /* None */, entryComponentFactories)]
  25361. .concat(providerParser.parse().map(function (provider) { return providerDef(ctx, provider); }))
  25362. .map(function (_a) {
  25363. var providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, flags = _a.flags, tokenExpr = _a.tokenExpr;
  25364. return importExpr(Identifiers$1.moduleProviderDef).callFn([
  25365. literal(flags), tokenExpr, providerExpr, depsExpr
  25366. ]);
  25367. });
  25368. var ngModuleDef = importExpr(Identifiers$1.moduleDef).callFn([literalArr(providerDefs)]);
  25369. var ngModuleDefFactory = fn([new FnParam(LOG_VAR.name)], [new ReturnStatement(ngModuleDef)], INFERRED_TYPE);
  25370. var ngModuleFactoryVar = identifierName(ngModuleMeta.type) + "NgFactory";
  25371. this._createNgModuleFactory(ctx, ngModuleMeta.type.reference, importExpr(Identifiers$1.createModuleFactory).callFn([
  25372. ctx.importExpr(ngModuleMeta.type.reference),
  25373. literalArr(bootstrapComponents.map(function (id) { return ctx.importExpr(id.reference); })),
  25374. ngModuleDefFactory
  25375. ]));
  25376. if (ngModuleMeta.id) {
  25377. var id = typeof ngModuleMeta.id === 'string' ? literal(ngModuleMeta.id) :
  25378. ctx.importExpr(ngModuleMeta.id);
  25379. var registerFactoryStmt = importExpr(Identifiers$1.RegisterModuleFactoryFn)
  25380. .callFn([id, variable(ngModuleFactoryVar)])
  25381. .toStmt();
  25382. ctx.statements.push(registerFactoryStmt);
  25383. }
  25384. return new NgModuleCompileResult(ngModuleFactoryVar);
  25385. };
  25386. NgModuleCompiler.prototype.createStub = function (ctx, ngModuleReference) {
  25387. this._createNgModuleFactory(ctx, ngModuleReference, NULL_EXPR);
  25388. };
  25389. NgModuleCompiler.prototype._createNgModuleFactory = function (ctx, reference, value) {
  25390. var ngModuleFactoryVar = identifierName({ reference: reference }) + "NgFactory";
  25391. var ngModuleFactoryStmt = variable(ngModuleFactoryVar)
  25392. .set(value)
  25393. .toDeclStmt(importType(Identifiers$1.NgModuleFactory, [expressionType(ctx.importExpr(reference))], [TypeModifier.Const]), [exports.StmtModifier.Final, exports.StmtModifier.Exported]);
  25394. ctx.statements.push(ngModuleFactoryStmt);
  25395. };
  25396. return NgModuleCompiler;
  25397. }());
  25398. /**
  25399. * @license
  25400. * Copyright Google LLC All Rights Reserved.
  25401. *
  25402. * Use of this source code is governed by an MIT-style license that can be
  25403. * found in the LICENSE file at https://angular.io/license
  25404. */
  25405. /**
  25406. * Resolves types to {@link NgModule}.
  25407. */
  25408. var NgModuleResolver = /** @class */ (function () {
  25409. function NgModuleResolver(_reflector) {
  25410. this._reflector = _reflector;
  25411. }
  25412. NgModuleResolver.prototype.isNgModule = function (type) {
  25413. return this._reflector.annotations(type).some(createNgModule.isTypeOf);
  25414. };
  25415. NgModuleResolver.prototype.resolve = function (type, throwIfNotFound) {
  25416. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  25417. var ngModuleMeta = findLast(this._reflector.annotations(type), createNgModule.isTypeOf);
  25418. if (ngModuleMeta) {
  25419. return ngModuleMeta;
  25420. }
  25421. else {
  25422. if (throwIfNotFound) {
  25423. throw new Error("No NgModule metadata found for '" + stringify(type) + "'.");
  25424. }
  25425. return null;
  25426. }
  25427. };
  25428. return NgModuleResolver;
  25429. }());
  25430. function debugOutputAstAsTypeScript(ast) {
  25431. var converter = new _TsEmitterVisitor();
  25432. var ctx = EmitterVisitorContext.createRoot();
  25433. var asts = Array.isArray(ast) ? ast : [ast];
  25434. asts.forEach(function (ast) {
  25435. if (ast instanceof Statement) {
  25436. ast.visitStatement(converter, ctx);
  25437. }
  25438. else if (ast instanceof Expression) {
  25439. ast.visitExpression(converter, ctx);
  25440. }
  25441. else if (ast instanceof Type$1) {
  25442. ast.visitType(converter, ctx);
  25443. }
  25444. else {
  25445. throw new Error("Don't know how to print debug info for " + ast);
  25446. }
  25447. });
  25448. return ctx.toSource();
  25449. }
  25450. var TypeScriptEmitter = /** @class */ (function () {
  25451. function TypeScriptEmitter() {
  25452. }
  25453. TypeScriptEmitter.prototype.emitStatementsAndContext = function (genFilePath, stmts, preamble, emitSourceMaps, referenceFilter, importFilter) {
  25454. if (preamble === void 0) { preamble = ''; }
  25455. if (emitSourceMaps === void 0) { emitSourceMaps = true; }
  25456. var converter = new _TsEmitterVisitor(referenceFilter, importFilter);
  25457. var ctx = EmitterVisitorContext.createRoot();
  25458. converter.visitAllStatements(stmts, ctx);
  25459. var preambleLines = preamble ? preamble.split('\n') : [];
  25460. converter.reexports.forEach(function (reexports, exportedModuleName) {
  25461. var reexportsCode = reexports.map(function (reexport) { return reexport.name + " as " + reexport.as; }).join(',');
  25462. preambleLines.push("export {" + reexportsCode + "} from '" + exportedModuleName + "';");
  25463. });
  25464. converter.importsWithPrefixes.forEach(function (prefix, importedModuleName) {
  25465. // Note: can't write the real word for import as it screws up system.js auto detection...
  25466. preambleLines.push("imp" +
  25467. ("ort * as " + prefix + " from '" + importedModuleName + "';"));
  25468. });
  25469. var sm = emitSourceMaps ?
  25470. ctx.toSourceMapGenerator(genFilePath, preambleLines.length).toJsComment() :
  25471. '';
  25472. var lines = __spreadArray(__spreadArray([], __read(preambleLines)), [ctx.toSource(), sm]);
  25473. if (sm) {
  25474. // always add a newline at the end, as some tools have bugs without it.
  25475. lines.push('');
  25476. }
  25477. ctx.setPreambleLineCount(preambleLines.length);
  25478. return { sourceText: lines.join('\n'), context: ctx };
  25479. };
  25480. TypeScriptEmitter.prototype.emitStatements = function (genFilePath, stmts, preamble) {
  25481. if (preamble === void 0) { preamble = ''; }
  25482. return this.emitStatementsAndContext(genFilePath, stmts, preamble).sourceText;
  25483. };
  25484. return TypeScriptEmitter;
  25485. }());
  25486. var _TsEmitterVisitor = /** @class */ (function (_super) {
  25487. __extends(_TsEmitterVisitor, _super);
  25488. function _TsEmitterVisitor(referenceFilter, importFilter) {
  25489. var _this = _super.call(this, false) || this;
  25490. _this.referenceFilter = referenceFilter;
  25491. _this.importFilter = importFilter;
  25492. _this.typeExpression = 0;
  25493. _this.importsWithPrefixes = new Map();
  25494. _this.reexports = new Map();
  25495. return _this;
  25496. }
  25497. _TsEmitterVisitor.prototype.visitType = function (t, ctx, defaultType) {
  25498. if (defaultType === void 0) { defaultType = 'any'; }
  25499. if (t) {
  25500. this.typeExpression++;
  25501. t.visitType(this, ctx);
  25502. this.typeExpression--;
  25503. }
  25504. else {
  25505. ctx.print(null, defaultType);
  25506. }
  25507. };
  25508. _TsEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
  25509. var value = ast.value;
  25510. if (value == null && ast.type != INFERRED_TYPE) {
  25511. ctx.print(ast, "(" + value + " as any)");
  25512. return null;
  25513. }
  25514. return _super.prototype.visitLiteralExpr.call(this, ast, ctx);
  25515. };
  25516. // Temporary workaround to support strictNullCheck enabled consumers of ngc emit.
  25517. // In SNC mode, [] have the type never[], so we cast here to any[].
  25518. // TODO: narrow the cast to a more explicit type, or use a pattern that does not
  25519. // start with [].concat. see https://github.com/angular/angular/pull/11846
  25520. _TsEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
  25521. if (ast.entries.length === 0) {
  25522. ctx.print(ast, '(');
  25523. }
  25524. var result = _super.prototype.visitLiteralArrayExpr.call(this, ast, ctx);
  25525. if (ast.entries.length === 0) {
  25526. ctx.print(ast, ' as any[])');
  25527. }
  25528. return result;
  25529. };
  25530. _TsEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) {
  25531. this._visitIdentifier(ast.value, ast.typeParams, ctx);
  25532. return null;
  25533. };
  25534. _TsEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) {
  25535. var result = _super.prototype.visitAssertNotNullExpr.call(this, ast, ctx);
  25536. ctx.print(ast, '!');
  25537. return result;
  25538. };
  25539. _TsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  25540. if (stmt.hasModifier(exports.StmtModifier.Exported) && stmt.value instanceof ExternalExpr &&
  25541. !stmt.type) {
  25542. // check for a reexport
  25543. var _a = stmt.value.value, name = _a.name, moduleName = _a.moduleName;
  25544. if (moduleName) {
  25545. var reexports = this.reexports.get(moduleName);
  25546. if (!reexports) {
  25547. reexports = [];
  25548. this.reexports.set(moduleName, reexports);
  25549. }
  25550. reexports.push({ name: name, as: stmt.name });
  25551. return null;
  25552. }
  25553. }
  25554. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  25555. ctx.print(stmt, "export ");
  25556. }
  25557. if (stmt.hasModifier(exports.StmtModifier.Final)) {
  25558. ctx.print(stmt, "const");
  25559. }
  25560. else {
  25561. ctx.print(stmt, "var");
  25562. }
  25563. ctx.print(stmt, " " + stmt.name);
  25564. this._printColonType(stmt.type, ctx);
  25565. if (stmt.value) {
  25566. ctx.print(stmt, " = ");
  25567. stmt.value.visitExpression(this, ctx);
  25568. }
  25569. ctx.println(stmt, ";");
  25570. return null;
  25571. };
  25572. _TsEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  25573. throw new Error('Cannot visit a WrappedNodeExpr when outputting Typescript.');
  25574. };
  25575. _TsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) {
  25576. ctx.print(ast, "(<");
  25577. ast.type.visitType(this, ctx);
  25578. ctx.print(ast, ">");
  25579. ast.value.visitExpression(this, ctx);
  25580. ctx.print(ast, ")");
  25581. return null;
  25582. };
  25583. _TsEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
  25584. ctx.print(ast, "new ");
  25585. this.typeExpression++;
  25586. ast.classExpr.visitExpression(this, ctx);
  25587. this.typeExpression--;
  25588. ctx.print(ast, "(");
  25589. this.visitAllExpressions(ast.args, ctx, ',');
  25590. ctx.print(ast, ")");
  25591. return null;
  25592. };
  25593. _TsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  25594. var _this = this;
  25595. ctx.pushClass(stmt);
  25596. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  25597. ctx.print(stmt, "export ");
  25598. }
  25599. ctx.print(stmt, "class " + stmt.name);
  25600. if (stmt.parent != null) {
  25601. ctx.print(stmt, " extends ");
  25602. this.typeExpression++;
  25603. stmt.parent.visitExpression(this, ctx);
  25604. this.typeExpression--;
  25605. }
  25606. ctx.println(stmt, " {");
  25607. ctx.incIndent();
  25608. stmt.fields.forEach(function (field) { return _this._visitClassField(field, ctx); });
  25609. if (stmt.constructorMethod != null) {
  25610. this._visitClassConstructor(stmt, ctx);
  25611. }
  25612. stmt.getters.forEach(function (getter) { return _this._visitClassGetter(getter, ctx); });
  25613. stmt.methods.forEach(function (method) { return _this._visitClassMethod(method, ctx); });
  25614. ctx.decIndent();
  25615. ctx.println(stmt, "}");
  25616. ctx.popClass();
  25617. return null;
  25618. };
  25619. _TsEmitterVisitor.prototype._visitClassField = function (field, ctx) {
  25620. if (field.hasModifier(exports.StmtModifier.Private)) {
  25621. // comment out as a workaround for #10967
  25622. ctx.print(null, "/*private*/ ");
  25623. }
  25624. if (field.hasModifier(exports.StmtModifier.Static)) {
  25625. ctx.print(null, 'static ');
  25626. }
  25627. ctx.print(null, field.name);
  25628. this._printColonType(field.type, ctx);
  25629. if (field.initializer) {
  25630. ctx.print(null, ' = ');
  25631. field.initializer.visitExpression(this, ctx);
  25632. }
  25633. ctx.println(null, ";");
  25634. };
  25635. _TsEmitterVisitor.prototype._visitClassGetter = function (getter, ctx) {
  25636. if (getter.hasModifier(exports.StmtModifier.Private)) {
  25637. ctx.print(null, "private ");
  25638. }
  25639. ctx.print(null, "get " + getter.name + "()");
  25640. this._printColonType(getter.type, ctx);
  25641. ctx.println(null, " {");
  25642. ctx.incIndent();
  25643. this.visitAllStatements(getter.body, ctx);
  25644. ctx.decIndent();
  25645. ctx.println(null, "}");
  25646. };
  25647. _TsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) {
  25648. ctx.print(stmt, "constructor(");
  25649. this._visitParams(stmt.constructorMethod.params, ctx);
  25650. ctx.println(stmt, ") {");
  25651. ctx.incIndent();
  25652. this.visitAllStatements(stmt.constructorMethod.body, ctx);
  25653. ctx.decIndent();
  25654. ctx.println(stmt, "}");
  25655. };
  25656. _TsEmitterVisitor.prototype._visitClassMethod = function (method, ctx) {
  25657. if (method.hasModifier(exports.StmtModifier.Private)) {
  25658. ctx.print(null, "private ");
  25659. }
  25660. ctx.print(null, method.name + "(");
  25661. this._visitParams(method.params, ctx);
  25662. ctx.print(null, ")");
  25663. this._printColonType(method.type, ctx, 'void');
  25664. ctx.println(null, " {");
  25665. ctx.incIndent();
  25666. this.visitAllStatements(method.body, ctx);
  25667. ctx.decIndent();
  25668. ctx.println(null, "}");
  25669. };
  25670. _TsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) {
  25671. if (ast.name) {
  25672. ctx.print(ast, 'function ');
  25673. ctx.print(ast, ast.name);
  25674. }
  25675. ctx.print(ast, "(");
  25676. this._visitParams(ast.params, ctx);
  25677. ctx.print(ast, ")");
  25678. this._printColonType(ast.type, ctx, 'void');
  25679. if (!ast.name) {
  25680. ctx.print(ast, " => ");
  25681. }
  25682. ctx.println(ast, '{');
  25683. ctx.incIndent();
  25684. this.visitAllStatements(ast.statements, ctx);
  25685. ctx.decIndent();
  25686. ctx.print(ast, "}");
  25687. return null;
  25688. };
  25689. _TsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  25690. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  25691. ctx.print(stmt, "export ");
  25692. }
  25693. ctx.print(stmt, "function " + stmt.name + "(");
  25694. this._visitParams(stmt.params, ctx);
  25695. ctx.print(stmt, ")");
  25696. this._printColonType(stmt.type, ctx, 'void');
  25697. ctx.println(stmt, " {");
  25698. ctx.incIndent();
  25699. this.visitAllStatements(stmt.statements, ctx);
  25700. ctx.decIndent();
  25701. ctx.println(stmt, "}");
  25702. return null;
  25703. };
  25704. _TsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) {
  25705. ctx.println(stmt, "try {");
  25706. ctx.incIndent();
  25707. this.visitAllStatements(stmt.bodyStmts, ctx);
  25708. ctx.decIndent();
  25709. ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {");
  25710. ctx.incIndent();
  25711. var catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack', null)).toDeclStmt(null, [
  25712. exports.StmtModifier.Final
  25713. ])].concat(stmt.catchStmts);
  25714. this.visitAllStatements(catchStmts, ctx);
  25715. ctx.decIndent();
  25716. ctx.println(stmt, "}");
  25717. return null;
  25718. };
  25719. _TsEmitterVisitor.prototype.visitBuiltinType = function (type, ctx) {
  25720. var typeStr;
  25721. switch (type.name) {
  25722. case exports.BuiltinTypeName.Bool:
  25723. typeStr = 'boolean';
  25724. break;
  25725. case exports.BuiltinTypeName.Dynamic:
  25726. typeStr = 'any';
  25727. break;
  25728. case exports.BuiltinTypeName.Function:
  25729. typeStr = 'Function';
  25730. break;
  25731. case exports.BuiltinTypeName.Number:
  25732. typeStr = 'number';
  25733. break;
  25734. case exports.BuiltinTypeName.Int:
  25735. typeStr = 'number';
  25736. break;
  25737. case exports.BuiltinTypeName.String:
  25738. typeStr = 'string';
  25739. break;
  25740. case exports.BuiltinTypeName.None:
  25741. typeStr = 'never';
  25742. break;
  25743. default:
  25744. throw new Error("Unsupported builtin type " + type.name);
  25745. }
  25746. ctx.print(null, typeStr);
  25747. return null;
  25748. };
  25749. _TsEmitterVisitor.prototype.visitExpressionType = function (ast, ctx) {
  25750. var _this = this;
  25751. ast.value.visitExpression(this, ctx);
  25752. if (ast.typeParams !== null) {
  25753. ctx.print(null, '<');
  25754. this.visitAllObjects(function (type) { return _this.visitType(type, ctx); }, ast.typeParams, ctx, ',');
  25755. ctx.print(null, '>');
  25756. }
  25757. return null;
  25758. };
  25759. _TsEmitterVisitor.prototype.visitArrayType = function (type, ctx) {
  25760. this.visitType(type.of, ctx);
  25761. ctx.print(null, "[]");
  25762. return null;
  25763. };
  25764. _TsEmitterVisitor.prototype.visitMapType = function (type, ctx) {
  25765. ctx.print(null, "{[key: string]:");
  25766. this.visitType(type.valueType, ctx);
  25767. ctx.print(null, "}");
  25768. return null;
  25769. };
  25770. _TsEmitterVisitor.prototype.getBuiltinMethodName = function (method) {
  25771. var name;
  25772. switch (method) {
  25773. case exports.BuiltinMethod.ConcatArray:
  25774. name = 'concat';
  25775. break;
  25776. case exports.BuiltinMethod.SubscribeObservable:
  25777. name = 'subscribe';
  25778. break;
  25779. case exports.BuiltinMethod.Bind:
  25780. name = 'bind';
  25781. break;
  25782. default:
  25783. throw new Error("Unknown builtin method: " + method);
  25784. }
  25785. return name;
  25786. };
  25787. _TsEmitterVisitor.prototype._visitParams = function (params, ctx) {
  25788. var _this = this;
  25789. this.visitAllObjects(function (param) {
  25790. ctx.print(null, param.name);
  25791. _this._printColonType(param.type, ctx);
  25792. }, params, ctx, ',');
  25793. };
  25794. _TsEmitterVisitor.prototype._visitIdentifier = function (value, typeParams, ctx) {
  25795. var _this = this;
  25796. var name = value.name, moduleName = value.moduleName;
  25797. if (this.referenceFilter && this.referenceFilter(value)) {
  25798. ctx.print(null, '(null as any)');
  25799. return;
  25800. }
  25801. if (moduleName && (!this.importFilter || !this.importFilter(value))) {
  25802. var prefix = this.importsWithPrefixes.get(moduleName);
  25803. if (prefix == null) {
  25804. prefix = "i" + this.importsWithPrefixes.size;
  25805. this.importsWithPrefixes.set(moduleName, prefix);
  25806. }
  25807. ctx.print(null, prefix + ".");
  25808. }
  25809. ctx.print(null, name);
  25810. if (this.typeExpression > 0) {
  25811. // If we are in a type expression that refers to a generic type then supply
  25812. // the required type parameters. If there were not enough type parameters
  25813. // supplied, supply any as the type. Outside a type expression the reference
  25814. // should not supply type parameters and be treated as a simple value reference
  25815. // to the constructor function itself.
  25816. var suppliedParameters = typeParams || [];
  25817. if (suppliedParameters.length > 0) {
  25818. ctx.print(null, "<");
  25819. this.visitAllObjects(function (type) { return type.visitType(_this, ctx); }, typeParams, ctx, ',');
  25820. ctx.print(null, ">");
  25821. }
  25822. }
  25823. };
  25824. _TsEmitterVisitor.prototype._printColonType = function (type, ctx, defaultType) {
  25825. if (type !== INFERRED_TYPE) {
  25826. ctx.print(null, ':');
  25827. this.visitType(type, ctx, defaultType);
  25828. }
  25829. };
  25830. return _TsEmitterVisitor;
  25831. }(AbstractEmitterVisitor));
  25832. /**
  25833. * @license
  25834. * Copyright Google LLC All Rights Reserved.
  25835. *
  25836. * Use of this source code is governed by an MIT-style license that can be
  25837. * found in the LICENSE file at https://angular.io/license
  25838. */
  25839. /**
  25840. * Resolve a `Type` for {@link Pipe}.
  25841. *
  25842. * This interface can be overridden by the application developer to create custom behavior.
  25843. *
  25844. * See {@link Compiler}
  25845. */
  25846. var PipeResolver = /** @class */ (function () {
  25847. function PipeResolver(_reflector) {
  25848. this._reflector = _reflector;
  25849. }
  25850. PipeResolver.prototype.isPipe = function (type) {
  25851. var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
  25852. return typeMetadata && typeMetadata.some(createPipe.isTypeOf);
  25853. };
  25854. /**
  25855. * Return {@link Pipe} for a given `Type`.
  25856. */
  25857. PipeResolver.prototype.resolve = function (type, throwIfNotFound) {
  25858. if (throwIfNotFound === void 0) { throwIfNotFound = true; }
  25859. var metas = this._reflector.annotations(resolveForwardRef(type));
  25860. if (metas) {
  25861. var annotation = findLast(metas, createPipe.isTypeOf);
  25862. if (annotation) {
  25863. return annotation;
  25864. }
  25865. }
  25866. if (throwIfNotFound) {
  25867. throw new Error("No Pipe decorator found on " + stringify(type));
  25868. }
  25869. return null;
  25870. };
  25871. return PipeResolver;
  25872. }());
  25873. /**
  25874. * Generates code that is used to type check templates.
  25875. */
  25876. var TypeCheckCompiler = /** @class */ (function () {
  25877. function TypeCheckCompiler(options, reflector) {
  25878. this.options = options;
  25879. this.reflector = reflector;
  25880. }
  25881. /**
  25882. * Important notes:
  25883. * - This must not produce new `import` statements, but only refer to types outside
  25884. * of the file via the variables provided via externalReferenceVars.
  25885. * This allows Typescript to reuse the old program's structure as no imports have changed.
  25886. * - This must not produce any exports, as this would pollute the .d.ts file
  25887. * and also violate the point above.
  25888. */
  25889. TypeCheckCompiler.prototype.compileComponent = function (componentId, component, template, usedPipes, externalReferenceVars, ctx) {
  25890. var _this = this;
  25891. var pipes = new Map();
  25892. usedPipes.forEach(function (p) { return pipes.set(p.name, p.type.reference); });
  25893. var embeddedViewCount = 0;
  25894. var viewBuilderFactory = function (parent, guards) {
  25895. var embeddedViewIndex = embeddedViewCount++;
  25896. return new ViewBuilder(_this.options, _this.reflector, externalReferenceVars, parent, component.type.reference, component.isHost, embeddedViewIndex, pipes, guards, ctx, viewBuilderFactory);
  25897. };
  25898. var visitor = viewBuilderFactory(null, []);
  25899. visitor.visitAll([], template);
  25900. return visitor.build(componentId);
  25901. };
  25902. return TypeCheckCompiler;
  25903. }());
  25904. var DYNAMIC_VAR_NAME = '_any';
  25905. var TypeCheckLocalResolver = /** @class */ (function () {
  25906. function TypeCheckLocalResolver() {
  25907. }
  25908. TypeCheckLocalResolver.prototype.notifyImplicitReceiverUse = function () { };
  25909. TypeCheckLocalResolver.prototype.getLocal = function (name) {
  25910. if (name === EventHandlerVars.event.name) {
  25911. // References to the event should not be type-checked.
  25912. // TODO(chuckj): determine a better type for the event.
  25913. return variable(DYNAMIC_VAR_NAME);
  25914. }
  25915. return null;
  25916. };
  25917. return TypeCheckLocalResolver;
  25918. }());
  25919. var defaultResolver = new TypeCheckLocalResolver();
  25920. var ViewBuilder = /** @class */ (function () {
  25921. function ViewBuilder(options, reflector, externalReferenceVars, parent, component, isHostComponent, embeddedViewIndex, pipes, guards, ctx, viewBuilderFactory) {
  25922. this.options = options;
  25923. this.reflector = reflector;
  25924. this.externalReferenceVars = externalReferenceVars;
  25925. this.parent = parent;
  25926. this.component = component;
  25927. this.isHostComponent = isHostComponent;
  25928. this.embeddedViewIndex = embeddedViewIndex;
  25929. this.pipes = pipes;
  25930. this.guards = guards;
  25931. this.ctx = ctx;
  25932. this.viewBuilderFactory = viewBuilderFactory;
  25933. this.refOutputVars = new Map();
  25934. this.variables = [];
  25935. this.children = [];
  25936. this.updates = [];
  25937. this.actions = [];
  25938. }
  25939. ViewBuilder.prototype.getOutputVar = function (type) {
  25940. var varName;
  25941. if (type === this.component && this.isHostComponent) {
  25942. varName = DYNAMIC_VAR_NAME;
  25943. }
  25944. else if (type instanceof StaticSymbol) {
  25945. varName = this.externalReferenceVars.get(type);
  25946. }
  25947. else {
  25948. varName = DYNAMIC_VAR_NAME;
  25949. }
  25950. if (!varName) {
  25951. throw new Error("Illegal State: referring to a type without a variable " + JSON.stringify(type));
  25952. }
  25953. return varName;
  25954. };
  25955. ViewBuilder.prototype.getTypeGuardExpressions = function (ast) {
  25956. var e_1, _a, e_2, _b;
  25957. var result = __spreadArray([], __read(this.guards));
  25958. try {
  25959. for (var _c = __values(ast.directives), _d = _c.next(); !_d.done; _d = _c.next()) {
  25960. var directive = _d.value;
  25961. try {
  25962. for (var _e = (e_2 = void 0, __values(directive.inputs)), _f = _e.next(); !_f.done; _f = _e.next()) {
  25963. var input = _f.value;
  25964. var guard = directive.directive.guards[input.directiveName];
  25965. if (guard) {
  25966. var useIf = guard === 'UseIf';
  25967. result.push({
  25968. guard: guard,
  25969. useIf: useIf,
  25970. expression: {
  25971. context: this.component,
  25972. value: input.value,
  25973. sourceSpan: input.sourceSpan,
  25974. },
  25975. });
  25976. }
  25977. }
  25978. }
  25979. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  25980. finally {
  25981. try {
  25982. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  25983. }
  25984. finally { if (e_2) throw e_2.error; }
  25985. }
  25986. }
  25987. }
  25988. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  25989. finally {
  25990. try {
  25991. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  25992. }
  25993. finally { if (e_1) throw e_1.error; }
  25994. }
  25995. return result;
  25996. };
  25997. ViewBuilder.prototype.visitAll = function (variables, astNodes) {
  25998. this.variables = variables;
  25999. templateVisitAll(this, astNodes);
  26000. };
  26001. ViewBuilder.prototype.build = function (componentId, targetStatements) {
  26002. var e_3, _a;
  26003. var _this = this;
  26004. if (targetStatements === void 0) { targetStatements = []; }
  26005. this.children.forEach(function (child) { return child.build(componentId, targetStatements); });
  26006. var viewStmts = [variable(DYNAMIC_VAR_NAME).set(NULL_EXPR).toDeclStmt(DYNAMIC_TYPE)];
  26007. var bindingCount = 0;
  26008. this.updates.forEach(function (expression) {
  26009. var _a = _this.preprocessUpdateExpression(expression), sourceSpan = _a.sourceSpan, context = _a.context, value = _a.value;
  26010. var bindingId = "" + bindingCount++;
  26011. var nameResolver = context === _this.component ? _this : defaultResolver;
  26012. var _b = convertPropertyBinding(nameResolver, variable(_this.getOutputVar(context)), value, bindingId, BindingForm.General), stmts = _b.stmts, currValExpr = _b.currValExpr;
  26013. stmts.push(new ExpressionStatement(currValExpr));
  26014. viewStmts.push.apply(viewStmts, __spreadArray([], __read(stmts.map(function (stmt) { return applySourceSpanToStatementIfNeeded(stmt, sourceSpan); }))));
  26015. });
  26016. this.actions.forEach(function (_a) {
  26017. var sourceSpan = _a.sourceSpan, context = _a.context, value = _a.value;
  26018. var bindingId = "" + bindingCount++;
  26019. var nameResolver = context === _this.component ? _this : defaultResolver;
  26020. var stmts = convertActionBinding(nameResolver, variable(_this.getOutputVar(context)), value, bindingId).stmts;
  26021. viewStmts.push.apply(viewStmts, __spreadArray([], __read(stmts.map(function (stmt) { return applySourceSpanToStatementIfNeeded(stmt, sourceSpan); }))));
  26022. });
  26023. if (this.guards.length) {
  26024. var guardExpression = undefined;
  26025. try {
  26026. for (var _b = __values(this.guards), _c = _b.next(); !_c.done; _c = _b.next()) {
  26027. var guard = _c.value;
  26028. var _d = this.preprocessUpdateExpression(guard.expression), context = _d.context, value = _d.value;
  26029. var bindingId = "" + bindingCount++;
  26030. var nameResolver = context === this.component ? this : defaultResolver;
  26031. // We only support support simple expressions and ignore others as they
  26032. // are unlikely to affect type narrowing.
  26033. var _e = convertPropertyBinding(nameResolver, variable(this.getOutputVar(context)), value, bindingId, BindingForm.TrySimple), stmts = _e.stmts, currValExpr = _e.currValExpr;
  26034. if (stmts.length == 0) {
  26035. var guardClause = guard.useIf ? currValExpr : this.ctx.importExpr(guard.guard).callFn([currValExpr]);
  26036. guardExpression = guardExpression ? guardExpression.and(guardClause) : guardClause;
  26037. }
  26038. }
  26039. }
  26040. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  26041. finally {
  26042. try {
  26043. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  26044. }
  26045. finally { if (e_3) throw e_3.error; }
  26046. }
  26047. if (guardExpression) {
  26048. viewStmts = [new IfStmt(guardExpression, viewStmts)];
  26049. }
  26050. }
  26051. var viewName = "_View_" + componentId + "_" + this.embeddedViewIndex;
  26052. var viewFactory = new DeclareFunctionStmt(viewName, [], viewStmts);
  26053. targetStatements.push(viewFactory);
  26054. return targetStatements;
  26055. };
  26056. ViewBuilder.prototype.visitBoundText = function (ast, context) {
  26057. var _this = this;
  26058. var astWithSource = ast.value;
  26059. var inter = astWithSource.ast;
  26060. inter.expressions.forEach(function (expr) { return _this.updates.push({ context: _this.component, value: expr, sourceSpan: ast.sourceSpan }); });
  26061. };
  26062. ViewBuilder.prototype.visitEmbeddedTemplate = function (ast, context) {
  26063. this.visitElementOrTemplate(ast);
  26064. // Note: The old view compiler used to use an `any` type
  26065. // for the context in any embedded view.
  26066. // We keep this behaivor behind a flag for now.
  26067. if (this.options.fullTemplateTypeCheck) {
  26068. // Find any applicable type guards. For example, NgIf has a type guard on ngIf
  26069. // (see NgIf.ngIfTypeGuard) that can be used to indicate that a template is only
  26070. // stamped out if ngIf is truthy so any bindings in the template can assume that,
  26071. // if a nullable type is used for ngIf, that expression is not null or undefined.
  26072. var guards = this.getTypeGuardExpressions(ast);
  26073. var childVisitor = this.viewBuilderFactory(this, guards);
  26074. this.children.push(childVisitor);
  26075. childVisitor.visitAll(ast.variables, ast.children);
  26076. }
  26077. };
  26078. ViewBuilder.prototype.visitElement = function (ast, context) {
  26079. var _this = this;
  26080. this.visitElementOrTemplate(ast);
  26081. var inputDefs = [];
  26082. var updateRendererExpressions = [];
  26083. var outputDefs = [];
  26084. ast.inputs.forEach(function (inputAst) {
  26085. _this.updates.push({ context: _this.component, value: inputAst.value, sourceSpan: inputAst.sourceSpan });
  26086. });
  26087. templateVisitAll(this, ast.children);
  26088. };
  26089. ViewBuilder.prototype.visitElementOrTemplate = function (ast) {
  26090. var _this = this;
  26091. ast.directives.forEach(function (dirAst) {
  26092. _this.visitDirective(dirAst);
  26093. });
  26094. ast.references.forEach(function (ref) {
  26095. var outputVarType = null;
  26096. // Note: The old view compiler used to use an `any` type
  26097. // for directives exposed via `exportAs`.
  26098. // We keep this behaivor behind a flag for now.
  26099. if (ref.value && ref.value.identifier && _this.options.fullTemplateTypeCheck) {
  26100. outputVarType = ref.value.identifier.reference;
  26101. }
  26102. else {
  26103. outputVarType = exports.BuiltinTypeName.Dynamic;
  26104. }
  26105. _this.refOutputVars.set(ref.name, outputVarType);
  26106. });
  26107. ast.outputs.forEach(function (outputAst) {
  26108. _this.actions.push({ context: _this.component, value: outputAst.handler, sourceSpan: outputAst.sourceSpan });
  26109. });
  26110. };
  26111. ViewBuilder.prototype.visitDirective = function (dirAst) {
  26112. var _this = this;
  26113. var dirType = dirAst.directive.type.reference;
  26114. dirAst.inputs.forEach(function (input) { return _this.updates.push({ context: _this.component, value: input.value, sourceSpan: input.sourceSpan }); });
  26115. // Note: The old view compiler used to use an `any` type
  26116. // for expressions in host properties / events.
  26117. // We keep this behaivor behind a flag for now.
  26118. if (this.options.fullTemplateTypeCheck) {
  26119. dirAst.hostProperties.forEach(function (inputAst) { return _this.updates.push({ context: dirType, value: inputAst.value, sourceSpan: inputAst.sourceSpan }); });
  26120. dirAst.hostEvents.forEach(function (hostEventAst) { return _this.actions.push({
  26121. context: dirType,
  26122. value: hostEventAst.handler,
  26123. sourceSpan: hostEventAst.sourceSpan
  26124. }); });
  26125. }
  26126. };
  26127. ViewBuilder.prototype.notifyImplicitReceiverUse = function () { };
  26128. ViewBuilder.prototype.getLocal = function (name) {
  26129. if (name == EventHandlerVars.event.name) {
  26130. return variable(this.getOutputVar(exports.BuiltinTypeName.Dynamic));
  26131. }
  26132. for (var currBuilder = this; currBuilder; currBuilder = currBuilder.parent) {
  26133. var outputVarType = void 0;
  26134. // check references
  26135. outputVarType = currBuilder.refOutputVars.get(name);
  26136. if (outputVarType == null) {
  26137. // check variables
  26138. var varAst = currBuilder.variables.find(function (varAst) { return varAst.name === name; });
  26139. if (varAst) {
  26140. outputVarType = exports.BuiltinTypeName.Dynamic;
  26141. }
  26142. }
  26143. if (outputVarType != null) {
  26144. return variable(this.getOutputVar(outputVarType));
  26145. }
  26146. }
  26147. return null;
  26148. };
  26149. ViewBuilder.prototype.pipeOutputVar = function (name) {
  26150. var pipe = this.pipes.get(name);
  26151. if (!pipe) {
  26152. throw new Error("Illegal State: Could not find pipe " + name + " in template of " + this.component);
  26153. }
  26154. return this.getOutputVar(pipe);
  26155. };
  26156. ViewBuilder.prototype.preprocessUpdateExpression = function (expression) {
  26157. var _this = this;
  26158. return {
  26159. sourceSpan: expression.sourceSpan,
  26160. context: expression.context,
  26161. value: convertPropertyBindingBuiltins({
  26162. createLiteralArrayConverter: function (argCount) { return function (args) {
  26163. var arr = literalArr(args);
  26164. // Note: The old view compiler used to use an `any` type
  26165. // for arrays.
  26166. return _this.options.fullTemplateTypeCheck ? arr : arr.cast(DYNAMIC_TYPE);
  26167. }; },
  26168. createLiteralMapConverter: function (keys) { return function (values) {
  26169. var entries = keys.map(function (k, i) { return ({
  26170. key: k.key,
  26171. value: values[i],
  26172. quoted: k.quoted,
  26173. }); });
  26174. var map = literalMap(entries);
  26175. // Note: The old view compiler used to use an `any` type
  26176. // for maps.
  26177. return _this.options.fullTemplateTypeCheck ? map : map.cast(DYNAMIC_TYPE);
  26178. }; },
  26179. createPipeConverter: function (name, argCount) { return function (args) {
  26180. // Note: The old view compiler used to use an `any` type
  26181. // for pipes.
  26182. var pipeExpr = _this.options.fullTemplateTypeCheck ?
  26183. variable(_this.pipeOutputVar(name)) :
  26184. variable(_this.getOutputVar(exports.BuiltinTypeName.Dynamic));
  26185. return pipeExpr.callMethod('transform', args);
  26186. }; },
  26187. }, expression.value)
  26188. };
  26189. };
  26190. ViewBuilder.prototype.visitNgContent = function (ast, context) { };
  26191. ViewBuilder.prototype.visitText = function (ast, context) { };
  26192. ViewBuilder.prototype.visitDirectiveProperty = function (ast, context) { };
  26193. ViewBuilder.prototype.visitReference = function (ast, context) { };
  26194. ViewBuilder.prototype.visitVariable = function (ast, context) { };
  26195. ViewBuilder.prototype.visitEvent = function (ast, context) { };
  26196. ViewBuilder.prototype.visitElementProperty = function (ast, context) { };
  26197. ViewBuilder.prototype.visitAttr = function (ast, context) { };
  26198. return ViewBuilder;
  26199. }());
  26200. var CLASS_ATTR$1 = 'class';
  26201. var STYLE_ATTR = 'style';
  26202. var IMPLICIT_TEMPLATE_VAR = '\$implicit';
  26203. var ViewCompileResult = /** @class */ (function () {
  26204. function ViewCompileResult(viewClassVar, rendererTypeVar) {
  26205. this.viewClassVar = viewClassVar;
  26206. this.rendererTypeVar = rendererTypeVar;
  26207. }
  26208. return ViewCompileResult;
  26209. }());
  26210. var ViewCompiler = /** @class */ (function () {
  26211. function ViewCompiler(_reflector) {
  26212. this._reflector = _reflector;
  26213. }
  26214. ViewCompiler.prototype.compileComponent = function (outputCtx, component, template, styles, usedPipes) {
  26215. var _a;
  26216. var _this = this;
  26217. var embeddedViewCount = 0;
  26218. var renderComponentVarName = undefined;
  26219. if (!component.isHost) {
  26220. var template_1 = component.template;
  26221. var customRenderData = [];
  26222. if (template_1.animations && template_1.animations.length) {
  26223. customRenderData.push(new LiteralMapEntry('animation', convertValueToOutputAst(outputCtx, template_1.animations), true));
  26224. }
  26225. var renderComponentVar = variable(rendererTypeName(component.type.reference));
  26226. renderComponentVarName = renderComponentVar.name;
  26227. outputCtx.statements.push(renderComponentVar
  26228. .set(importExpr(Identifiers$1.createRendererType2).callFn([new LiteralMapExpr([
  26229. new LiteralMapEntry('encapsulation', literal(template_1.encapsulation), false),
  26230. new LiteralMapEntry('styles', styles, false),
  26231. new LiteralMapEntry('data', new LiteralMapExpr(customRenderData), false)
  26232. ])]))
  26233. .toDeclStmt(importType(Identifiers$1.RendererType2), [exports.StmtModifier.Final, exports.StmtModifier.Exported]));
  26234. }
  26235. var viewBuilderFactory = function (parent) {
  26236. var embeddedViewIndex = embeddedViewCount++;
  26237. return new ViewBuilder$1(_this._reflector, outputCtx, parent, component, embeddedViewIndex, usedPipes, viewBuilderFactory);
  26238. };
  26239. var visitor = viewBuilderFactory(null);
  26240. visitor.visitAll([], template);
  26241. (_a = outputCtx.statements).push.apply(_a, __spreadArray([], __read(visitor.build())));
  26242. return new ViewCompileResult(visitor.viewName, renderComponentVarName);
  26243. };
  26244. return ViewCompiler;
  26245. }());
  26246. var LOG_VAR$1 = variable('_l');
  26247. var VIEW_VAR = variable('_v');
  26248. var CHECK_VAR = variable('_ck');
  26249. var COMP_VAR = variable('_co');
  26250. var EVENT_NAME_VAR = variable('en');
  26251. var ALLOW_DEFAULT_VAR = variable("ad");
  26252. var ViewBuilder$1 = /** @class */ (function () {
  26253. function ViewBuilder(reflector, outputCtx, parent, component, embeddedViewIndex, usedPipes, viewBuilderFactory) {
  26254. this.reflector = reflector;
  26255. this.outputCtx = outputCtx;
  26256. this.parent = parent;
  26257. this.component = component;
  26258. this.embeddedViewIndex = embeddedViewIndex;
  26259. this.usedPipes = usedPipes;
  26260. this.viewBuilderFactory = viewBuilderFactory;
  26261. this.nodes = [];
  26262. this.purePipeNodeIndices = Object.create(null);
  26263. // Need Object.create so that we don't have builtin values...
  26264. this.refNodeIndices = Object.create(null);
  26265. this.variables = [];
  26266. this.children = [];
  26267. // TODO(tbosch): The old view compiler used to use an `any` type
  26268. // for the context in any embedded view. We keep this behaivor for now
  26269. // to be able to introduce the new view compiler without too many errors.
  26270. this.compType = this.embeddedViewIndex > 0 ?
  26271. DYNAMIC_TYPE :
  26272. expressionType(outputCtx.importExpr(this.component.type.reference));
  26273. this.viewName = viewClassName(this.component.type.reference, this.embeddedViewIndex);
  26274. }
  26275. ViewBuilder.prototype.visitAll = function (variables, astNodes) {
  26276. var _this = this;
  26277. this.variables = variables;
  26278. // create the pipes for the pure pipes immediately, so that we know their indices.
  26279. if (!this.parent) {
  26280. this.usedPipes.forEach(function (pipe) {
  26281. if (pipe.pure) {
  26282. _this.purePipeNodeIndices[pipe.name] = _this._createPipe(null, pipe);
  26283. }
  26284. });
  26285. }
  26286. if (!this.parent) {
  26287. this.component.viewQueries.forEach(function (query, queryIndex) {
  26288. // Note: queries start with id 1 so we can use the number in a Bloom filter!
  26289. var queryId = queryIndex + 1;
  26290. var bindingType = query.first ? 0 /* First */ : 1 /* All */;
  26291. var flags = 134217728 /* TypeViewQuery */ | calcQueryFlags(query);
  26292. _this.nodes.push(function () { return ({
  26293. sourceSpan: null,
  26294. nodeFlags: flags,
  26295. nodeDef: importExpr(Identifiers$1.queryDef).callFn([
  26296. literal(flags), literal(queryId),
  26297. new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType), false)])
  26298. ])
  26299. }); });
  26300. });
  26301. }
  26302. templateVisitAll(this, astNodes);
  26303. if (this.parent && (astNodes.length === 0 || needsAdditionalRootNode(astNodes))) {
  26304. // if the view is an embedded view, then we need to add an additional root node in some cases
  26305. this.nodes.push(function () { return ({
  26306. sourceSpan: null,
  26307. nodeFlags: 1 /* TypeElement */,
  26308. nodeDef: importExpr(Identifiers$1.anchorDef).callFn([
  26309. literal(0 /* None */), NULL_EXPR, NULL_EXPR, literal(0)
  26310. ])
  26311. }); });
  26312. }
  26313. };
  26314. ViewBuilder.prototype.build = function (targetStatements) {
  26315. if (targetStatements === void 0) { targetStatements = []; }
  26316. this.children.forEach(function (child) { return child.build(targetStatements); });
  26317. var _a = this._createNodeExpressions(), updateRendererStmts = _a.updateRendererStmts, updateDirectivesStmts = _a.updateDirectivesStmts, nodeDefExprs = _a.nodeDefExprs;
  26318. var updateRendererFn = this._createUpdateFn(updateRendererStmts);
  26319. var updateDirectivesFn = this._createUpdateFn(updateDirectivesStmts);
  26320. var viewFlags = 0 /* None */;
  26321. if (!this.parent && this.component.changeDetection === ChangeDetectionStrategy.OnPush) {
  26322. viewFlags |= 2 /* OnPush */;
  26323. }
  26324. var viewFactory = new DeclareFunctionStmt(this.viewName, [new FnParam(LOG_VAR$1.name)], [new ReturnStatement(importExpr(Identifiers$1.viewDef).callFn([
  26325. literal(viewFlags),
  26326. literalArr(nodeDefExprs),
  26327. updateDirectivesFn,
  26328. updateRendererFn,
  26329. ]))], importType(Identifiers$1.ViewDefinition), this.embeddedViewIndex === 0 ? [exports.StmtModifier.Exported] : []);
  26330. targetStatements.push(viewFactory);
  26331. return targetStatements;
  26332. };
  26333. ViewBuilder.prototype._createUpdateFn = function (updateStmts) {
  26334. var updateFn;
  26335. if (updateStmts.length > 0) {
  26336. var preStmts = [];
  26337. if (!this.component.isHost && findReadVarNames(updateStmts).has(COMP_VAR.name)) {
  26338. preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
  26339. }
  26340. updateFn = fn([
  26341. new FnParam(CHECK_VAR.name, INFERRED_TYPE),
  26342. new FnParam(VIEW_VAR.name, INFERRED_TYPE)
  26343. ], __spreadArray(__spreadArray([], __read(preStmts)), __read(updateStmts)), INFERRED_TYPE);
  26344. }
  26345. else {
  26346. updateFn = NULL_EXPR;
  26347. }
  26348. return updateFn;
  26349. };
  26350. ViewBuilder.prototype.visitNgContent = function (ast, context) {
  26351. // ngContentDef(ngContentIndex: number, index: number): NodeDef;
  26352. this.nodes.push(function () { return ({
  26353. sourceSpan: ast.sourceSpan,
  26354. nodeFlags: 8 /* TypeNgContent */,
  26355. nodeDef: importExpr(Identifiers$1.ngContentDef)
  26356. .callFn([literal(ast.ngContentIndex), literal(ast.index)])
  26357. }); });
  26358. };
  26359. ViewBuilder.prototype.visitText = function (ast, context) {
  26360. // Static text nodes have no check function
  26361. var checkIndex = -1;
  26362. this.nodes.push(function () { return ({
  26363. sourceSpan: ast.sourceSpan,
  26364. nodeFlags: 2 /* TypeText */,
  26365. nodeDef: importExpr(Identifiers$1.textDef).callFn([
  26366. literal(checkIndex),
  26367. literal(ast.ngContentIndex),
  26368. literalArr([literal(ast.value)]),
  26369. ])
  26370. }); });
  26371. };
  26372. ViewBuilder.prototype.visitBoundText = function (ast, context) {
  26373. var _this = this;
  26374. var nodeIndex = this.nodes.length;
  26375. // reserve the space in the nodeDefs array
  26376. this.nodes.push(null);
  26377. var astWithSource = ast.value;
  26378. var inter = astWithSource.ast;
  26379. var updateRendererExpressions = inter.expressions.map(function (expr, bindingIndex) { return _this._preprocessUpdateExpression({ nodeIndex: nodeIndex, bindingIndex: bindingIndex, sourceSpan: ast.sourceSpan, context: COMP_VAR, value: expr }); });
  26380. // Check index is the same as the node index during compilation
  26381. // They might only differ at runtime
  26382. var checkIndex = nodeIndex;
  26383. this.nodes[nodeIndex] = function () { return ({
  26384. sourceSpan: ast.sourceSpan,
  26385. nodeFlags: 2 /* TypeText */,
  26386. nodeDef: importExpr(Identifiers$1.textDef).callFn([
  26387. literal(checkIndex),
  26388. literal(ast.ngContentIndex),
  26389. literalArr(inter.strings.map(function (s) { return literal(s); })),
  26390. ]),
  26391. updateRenderer: updateRendererExpressions
  26392. }); };
  26393. };
  26394. ViewBuilder.prototype.visitEmbeddedTemplate = function (ast, context) {
  26395. var _this = this;
  26396. var nodeIndex = this.nodes.length;
  26397. // reserve the space in the nodeDefs array
  26398. this.nodes.push(null);
  26399. var _a = this._visitElementOrTemplate(nodeIndex, ast), flags = _a.flags, queryMatchesExpr = _a.queryMatchesExpr, hostEvents = _a.hostEvents;
  26400. var childVisitor = this.viewBuilderFactory(this);
  26401. this.children.push(childVisitor);
  26402. childVisitor.visitAll(ast.variables, ast.children);
  26403. var childCount = this.nodes.length - nodeIndex - 1;
  26404. // anchorDef(
  26405. // flags: NodeFlags, matchedQueries: [string, QueryValueType][], ngContentIndex: number,
  26406. // childCount: number, handleEventFn?: ElementHandleEventFn, templateFactory?:
  26407. // ViewDefinitionFactory): NodeDef;
  26408. this.nodes[nodeIndex] = function () { return ({
  26409. sourceSpan: ast.sourceSpan,
  26410. nodeFlags: 1 /* TypeElement */ | flags,
  26411. nodeDef: importExpr(Identifiers$1.anchorDef).callFn([
  26412. literal(flags),
  26413. queryMatchesExpr,
  26414. literal(ast.ngContentIndex),
  26415. literal(childCount),
  26416. _this._createElementHandleEventFn(nodeIndex, hostEvents),
  26417. variable(childVisitor.viewName),
  26418. ])
  26419. }); };
  26420. };
  26421. ViewBuilder.prototype.visitElement = function (ast, context) {
  26422. var _this = this;
  26423. var nodeIndex = this.nodes.length;
  26424. // reserve the space in the nodeDefs array so we can add children
  26425. this.nodes.push(null);
  26426. // Using a null element name creates an anchor.
  26427. var elName = isNgContainer(ast.name) ? null : ast.name;
  26428. var _a = this._visitElementOrTemplate(nodeIndex, ast), flags = _a.flags, usedEvents = _a.usedEvents, queryMatchesExpr = _a.queryMatchesExpr, dirHostBindings = _a.hostBindings, hostEvents = _a.hostEvents;
  26429. var inputDefs = [];
  26430. var updateRendererExpressions = [];
  26431. var outputDefs = [];
  26432. if (elName) {
  26433. var hostBindings = ast.inputs
  26434. .map(function (inputAst) { return ({
  26435. context: COMP_VAR,
  26436. inputAst: inputAst,
  26437. dirAst: null,
  26438. }); })
  26439. .concat(dirHostBindings);
  26440. if (hostBindings.length) {
  26441. updateRendererExpressions =
  26442. hostBindings.map(function (hostBinding, bindingIndex) { return _this._preprocessUpdateExpression({
  26443. context: hostBinding.context,
  26444. nodeIndex: nodeIndex,
  26445. bindingIndex: bindingIndex,
  26446. sourceSpan: hostBinding.inputAst.sourceSpan,
  26447. value: hostBinding.inputAst.value
  26448. }); });
  26449. inputDefs = hostBindings.map(function (hostBinding) { return elementBindingDef(hostBinding.inputAst, hostBinding.dirAst); });
  26450. }
  26451. outputDefs = usedEvents.map(function (_a) {
  26452. var _b = __read(_a, 2), target = _b[0], eventName = _b[1];
  26453. return literalArr([literal(target), literal(eventName)]);
  26454. });
  26455. }
  26456. templateVisitAll(this, ast.children);
  26457. var childCount = this.nodes.length - nodeIndex - 1;
  26458. var compAst = ast.directives.find(function (dirAst) { return dirAst.directive.isComponent; });
  26459. var compRendererType = NULL_EXPR;
  26460. var compView = NULL_EXPR;
  26461. if (compAst) {
  26462. compView = this.outputCtx.importExpr(compAst.directive.componentViewType);
  26463. compRendererType = this.outputCtx.importExpr(compAst.directive.rendererType);
  26464. }
  26465. // Check index is the same as the node index during compilation
  26466. // They might only differ at runtime
  26467. var checkIndex = nodeIndex;
  26468. this.nodes[nodeIndex] = function () { return ({
  26469. sourceSpan: ast.sourceSpan,
  26470. nodeFlags: 1 /* TypeElement */ | flags,
  26471. nodeDef: importExpr(Identifiers$1.elementDef).callFn([
  26472. literal(checkIndex),
  26473. literal(flags),
  26474. queryMatchesExpr,
  26475. literal(ast.ngContentIndex),
  26476. literal(childCount),
  26477. literal(elName),
  26478. elName ? fixedAttrsDef(ast) : NULL_EXPR,
  26479. inputDefs.length ? literalArr(inputDefs) : NULL_EXPR,
  26480. outputDefs.length ? literalArr(outputDefs) : NULL_EXPR,
  26481. _this._createElementHandleEventFn(nodeIndex, hostEvents),
  26482. compView,
  26483. compRendererType,
  26484. ]),
  26485. updateRenderer: updateRendererExpressions
  26486. }); };
  26487. };
  26488. ViewBuilder.prototype._visitElementOrTemplate = function (nodeIndex, ast) {
  26489. var _this = this;
  26490. var flags = 0 /* None */;
  26491. if (ast.hasViewContainer) {
  26492. flags |= 16777216 /* EmbeddedViews */;
  26493. }
  26494. var usedEvents = new Map();
  26495. ast.outputs.forEach(function (event) {
  26496. var _a = elementEventNameAndTarget(event, null), name = _a.name, target = _a.target;
  26497. usedEvents.set(elementEventFullName(target, name), [target, name]);
  26498. });
  26499. ast.directives.forEach(function (dirAst) {
  26500. dirAst.hostEvents.forEach(function (event) {
  26501. var _a = elementEventNameAndTarget(event, dirAst), name = _a.name, target = _a.target;
  26502. usedEvents.set(elementEventFullName(target, name), [target, name]);
  26503. });
  26504. });
  26505. var hostBindings = [];
  26506. var hostEvents = [];
  26507. this._visitComponentFactoryResolverProvider(ast.directives);
  26508. ast.providers.forEach(function (providerAst) {
  26509. var dirAst = undefined;
  26510. ast.directives.forEach(function (localDirAst) {
  26511. if (localDirAst.directive.type.reference === tokenReference(providerAst.token)) {
  26512. dirAst = localDirAst;
  26513. }
  26514. });
  26515. if (dirAst) {
  26516. var _a = _this._visitDirective(providerAst, dirAst, ast.references, ast.queryMatches, usedEvents), dirHostBindings = _a.hostBindings, dirHostEvents = _a.hostEvents;
  26517. hostBindings.push.apply(hostBindings, __spreadArray([], __read(dirHostBindings)));
  26518. hostEvents.push.apply(hostEvents, __spreadArray([], __read(dirHostEvents)));
  26519. }
  26520. else {
  26521. _this._visitProvider(providerAst, ast.queryMatches);
  26522. }
  26523. });
  26524. var queryMatchExprs = [];
  26525. ast.queryMatches.forEach(function (match) {
  26526. var valueType = undefined;
  26527. if (tokenReference(match.value) ===
  26528. _this.reflector.resolveExternalReference(Identifiers$1.ElementRef)) {
  26529. valueType = 0 /* ElementRef */;
  26530. }
  26531. else if (tokenReference(match.value) ===
  26532. _this.reflector.resolveExternalReference(Identifiers$1.ViewContainerRef)) {
  26533. valueType = 3 /* ViewContainerRef */;
  26534. }
  26535. else if (tokenReference(match.value) ===
  26536. _this.reflector.resolveExternalReference(Identifiers$1.TemplateRef)) {
  26537. valueType = 2 /* TemplateRef */;
  26538. }
  26539. if (valueType != null) {
  26540. queryMatchExprs.push(literalArr([literal(match.queryId), literal(valueType)]));
  26541. }
  26542. });
  26543. ast.references.forEach(function (ref) {
  26544. var valueType = undefined;
  26545. if (!ref.value) {
  26546. valueType = 1 /* RenderElement */;
  26547. }
  26548. else if (tokenReference(ref.value) ===
  26549. _this.reflector.resolveExternalReference(Identifiers$1.TemplateRef)) {
  26550. valueType = 2 /* TemplateRef */;
  26551. }
  26552. if (valueType != null) {
  26553. _this.refNodeIndices[ref.name] = nodeIndex;
  26554. queryMatchExprs.push(literalArr([literal(ref.name), literal(valueType)]));
  26555. }
  26556. });
  26557. ast.outputs.forEach(function (outputAst) {
  26558. hostEvents.push({ context: COMP_VAR, eventAst: outputAst, dirAst: null });
  26559. });
  26560. return {
  26561. flags: flags,
  26562. usedEvents: Array.from(usedEvents.values()),
  26563. queryMatchesExpr: queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
  26564. hostBindings: hostBindings,
  26565. hostEvents: hostEvents
  26566. };
  26567. };
  26568. ViewBuilder.prototype._visitDirective = function (providerAst, dirAst, refs, queryMatches, usedEvents) {
  26569. var _this = this;
  26570. var nodeIndex = this.nodes.length;
  26571. // reserve the space in the nodeDefs array so we can add children
  26572. this.nodes.push(null);
  26573. dirAst.directive.queries.forEach(function (query, queryIndex) {
  26574. var queryId = dirAst.contentQueryStartId + queryIndex;
  26575. var flags = 67108864 /* TypeContentQuery */ | calcQueryFlags(query);
  26576. var bindingType = query.first ? 0 /* First */ : 1 /* All */;
  26577. _this.nodes.push(function () { return ({
  26578. sourceSpan: dirAst.sourceSpan,
  26579. nodeFlags: flags,
  26580. nodeDef: importExpr(Identifiers$1.queryDef).callFn([
  26581. literal(flags), literal(queryId),
  26582. new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType), false)])
  26583. ]),
  26584. }); });
  26585. });
  26586. // Note: the operation below might also create new nodeDefs,
  26587. // but we don't want them to be a child of a directive,
  26588. // as they might be a provider/pipe on their own.
  26589. // I.e. we only allow queries as children of directives nodes.
  26590. var childCount = this.nodes.length - nodeIndex - 1;
  26591. var _a = this._visitProviderOrDirective(providerAst, queryMatches), flags = _a.flags, queryMatchExprs = _a.queryMatchExprs, providerExpr = _a.providerExpr, depsExpr = _a.depsExpr;
  26592. refs.forEach(function (ref) {
  26593. if (ref.value && tokenReference(ref.value) === tokenReference(providerAst.token)) {
  26594. _this.refNodeIndices[ref.name] = nodeIndex;
  26595. queryMatchExprs.push(literalArr([literal(ref.name), literal(4 /* Provider */)]));
  26596. }
  26597. });
  26598. if (dirAst.directive.isComponent) {
  26599. flags |= 32768 /* Component */;
  26600. }
  26601. var inputDefs = dirAst.inputs.map(function (inputAst, inputIndex) {
  26602. var mapValue = literalArr([literal(inputIndex), literal(inputAst.directiveName)]);
  26603. // Note: it's important to not quote the key so that we can capture renames by minifiers!
  26604. return new LiteralMapEntry(inputAst.directiveName, mapValue, false);
  26605. });
  26606. var outputDefs = [];
  26607. var dirMeta = dirAst.directive;
  26608. Object.keys(dirMeta.outputs).forEach(function (propName) {
  26609. var eventName = dirMeta.outputs[propName];
  26610. if (usedEvents.has(eventName)) {
  26611. // Note: it's important to not quote the key so that we can capture renames by minifiers!
  26612. outputDefs.push(new LiteralMapEntry(propName, literal(eventName), false));
  26613. }
  26614. });
  26615. var updateDirectiveExpressions = [];
  26616. if (dirAst.inputs.length || (flags & (262144 /* DoCheck */ | 65536 /* OnInit */)) > 0) {
  26617. updateDirectiveExpressions =
  26618. dirAst.inputs.map(function (input, bindingIndex) { return _this._preprocessUpdateExpression({
  26619. nodeIndex: nodeIndex,
  26620. bindingIndex: bindingIndex,
  26621. sourceSpan: input.sourceSpan,
  26622. context: COMP_VAR,
  26623. value: input.value
  26624. }); });
  26625. }
  26626. var dirContextExpr = importExpr(Identifiers$1.nodeValue).callFn([VIEW_VAR, literal(nodeIndex)]);
  26627. var hostBindings = dirAst.hostProperties.map(function (inputAst) { return ({
  26628. context: dirContextExpr,
  26629. dirAst: dirAst,
  26630. inputAst: inputAst,
  26631. }); });
  26632. var hostEvents = dirAst.hostEvents.map(function (hostEventAst) { return ({
  26633. context: dirContextExpr,
  26634. eventAst: hostEventAst,
  26635. dirAst: dirAst,
  26636. }); });
  26637. // Check index is the same as the node index during compilation
  26638. // They might only differ at runtime
  26639. var checkIndex = nodeIndex;
  26640. this.nodes[nodeIndex] = function () { return ({
  26641. sourceSpan: dirAst.sourceSpan,
  26642. nodeFlags: 16384 /* TypeDirective */ | flags,
  26643. nodeDef: importExpr(Identifiers$1.directiveDef).callFn([
  26644. literal(checkIndex),
  26645. literal(flags),
  26646. queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
  26647. literal(childCount),
  26648. providerExpr,
  26649. depsExpr,
  26650. inputDefs.length ? new LiteralMapExpr(inputDefs) : NULL_EXPR,
  26651. outputDefs.length ? new LiteralMapExpr(outputDefs) : NULL_EXPR,
  26652. ]),
  26653. updateDirectives: updateDirectiveExpressions,
  26654. directive: dirAst.directive.type,
  26655. }); };
  26656. return { hostBindings: hostBindings, hostEvents: hostEvents };
  26657. };
  26658. ViewBuilder.prototype._visitProvider = function (providerAst, queryMatches) {
  26659. this._addProviderNode(this._visitProviderOrDirective(providerAst, queryMatches));
  26660. };
  26661. ViewBuilder.prototype._visitComponentFactoryResolverProvider = function (directives) {
  26662. var componentDirMeta = directives.find(function (dirAst) { return dirAst.directive.isComponent; });
  26663. if (componentDirMeta && componentDirMeta.directive.entryComponents.length) {
  26664. var _a = componentFactoryResolverProviderDef(this.reflector, this.outputCtx, 8192 /* PrivateProvider */, componentDirMeta.directive.entryComponents), providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, flags = _a.flags, tokenExpr = _a.tokenExpr;
  26665. this._addProviderNode({
  26666. providerExpr: providerExpr,
  26667. depsExpr: depsExpr,
  26668. flags: flags,
  26669. tokenExpr: tokenExpr,
  26670. queryMatchExprs: [],
  26671. sourceSpan: componentDirMeta.sourceSpan
  26672. });
  26673. }
  26674. };
  26675. ViewBuilder.prototype._addProviderNode = function (data) {
  26676. // providerDef(
  26677. // flags: NodeFlags, matchedQueries: [string, QueryValueType][], token:any,
  26678. // value: any, deps: ([DepFlags, any] | any)[]): NodeDef;
  26679. this.nodes.push(function () { return ({
  26680. sourceSpan: data.sourceSpan,
  26681. nodeFlags: data.flags,
  26682. nodeDef: importExpr(Identifiers$1.providerDef).callFn([
  26683. literal(data.flags),
  26684. data.queryMatchExprs.length ? literalArr(data.queryMatchExprs) : NULL_EXPR,
  26685. data.tokenExpr, data.providerExpr, data.depsExpr
  26686. ])
  26687. }); });
  26688. };
  26689. ViewBuilder.prototype._visitProviderOrDirective = function (providerAst, queryMatches) {
  26690. var flags = 0 /* None */;
  26691. var queryMatchExprs = [];
  26692. queryMatches.forEach(function (match) {
  26693. if (tokenReference(match.value) === tokenReference(providerAst.token)) {
  26694. queryMatchExprs.push(literalArr([literal(match.queryId), literal(4 /* Provider */)]));
  26695. }
  26696. });
  26697. var _a = providerDef(this.outputCtx, providerAst), providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, providerFlags = _a.flags, tokenExpr = _a.tokenExpr;
  26698. return {
  26699. flags: flags | providerFlags,
  26700. queryMatchExprs: queryMatchExprs,
  26701. providerExpr: providerExpr,
  26702. depsExpr: depsExpr,
  26703. tokenExpr: tokenExpr,
  26704. sourceSpan: providerAst.sourceSpan
  26705. };
  26706. };
  26707. ViewBuilder.prototype.getLocal = function (name) {
  26708. if (name == EventHandlerVars.event.name) {
  26709. return EventHandlerVars.event;
  26710. }
  26711. var currViewExpr = VIEW_VAR;
  26712. for (var currBuilder = this; currBuilder; currBuilder = currBuilder.parent,
  26713. currViewExpr = currViewExpr.prop('parent').cast(DYNAMIC_TYPE)) {
  26714. // check references
  26715. var refNodeIndex = currBuilder.refNodeIndices[name];
  26716. if (refNodeIndex != null) {
  26717. return importExpr(Identifiers$1.nodeValue).callFn([currViewExpr, literal(refNodeIndex)]);
  26718. }
  26719. // check variables
  26720. var varAst = currBuilder.variables.find(function (varAst) { return varAst.name === name; });
  26721. if (varAst) {
  26722. var varValue = varAst.value || IMPLICIT_TEMPLATE_VAR;
  26723. return currViewExpr.prop('context').prop(varValue);
  26724. }
  26725. }
  26726. return null;
  26727. };
  26728. ViewBuilder.prototype.notifyImplicitReceiverUse = function () {
  26729. // Not needed in View Engine as View Engine walks through the generated
  26730. // expressions to figure out if the implicit receiver is used and needs
  26731. // to be generated as part of the pre-update statements.
  26732. };
  26733. ViewBuilder.prototype._createLiteralArrayConverter = function (sourceSpan, argCount) {
  26734. if (argCount === 0) {
  26735. var valueExpr_1 = importExpr(Identifiers$1.EMPTY_ARRAY);
  26736. return function () { return valueExpr_1; };
  26737. }
  26738. var checkIndex = this.nodes.length;
  26739. this.nodes.push(function () { return ({
  26740. sourceSpan: sourceSpan,
  26741. nodeFlags: 32 /* TypePureArray */,
  26742. nodeDef: importExpr(Identifiers$1.pureArrayDef).callFn([
  26743. literal(checkIndex),
  26744. literal(argCount),
  26745. ])
  26746. }); });
  26747. return function (args) { return callCheckStmt(checkIndex, args); };
  26748. };
  26749. ViewBuilder.prototype._createLiteralMapConverter = function (sourceSpan, keys) {
  26750. if (keys.length === 0) {
  26751. var valueExpr_2 = importExpr(Identifiers$1.EMPTY_MAP);
  26752. return function () { return valueExpr_2; };
  26753. }
  26754. var map = literalMap(keys.map(function (e, i) { return (Object.assign(Object.assign({}, e), { value: literal(i) })); }));
  26755. var checkIndex = this.nodes.length;
  26756. this.nodes.push(function () { return ({
  26757. sourceSpan: sourceSpan,
  26758. nodeFlags: 64 /* TypePureObject */,
  26759. nodeDef: importExpr(Identifiers$1.pureObjectDef).callFn([
  26760. literal(checkIndex),
  26761. map,
  26762. ])
  26763. }); });
  26764. return function (args) { return callCheckStmt(checkIndex, args); };
  26765. };
  26766. ViewBuilder.prototype._createPipeConverter = function (expression, name, argCount) {
  26767. var pipe = this.usedPipes.find(function (pipeSummary) { return pipeSummary.name === name; });
  26768. if (pipe.pure) {
  26769. var checkIndex_1 = this.nodes.length;
  26770. this.nodes.push(function () { return ({
  26771. sourceSpan: expression.sourceSpan,
  26772. nodeFlags: 128 /* TypePurePipe */,
  26773. nodeDef: importExpr(Identifiers$1.purePipeDef).callFn([
  26774. literal(checkIndex_1),
  26775. literal(argCount),
  26776. ])
  26777. }); });
  26778. // find underlying pipe in the component view
  26779. var compViewExpr = VIEW_VAR;
  26780. var compBuilder = this;
  26781. while (compBuilder.parent) {
  26782. compBuilder = compBuilder.parent;
  26783. compViewExpr = compViewExpr.prop('parent').cast(DYNAMIC_TYPE);
  26784. }
  26785. var pipeNodeIndex = compBuilder.purePipeNodeIndices[name];
  26786. var pipeValueExpr_1 = importExpr(Identifiers$1.nodeValue).callFn([compViewExpr, literal(pipeNodeIndex)]);
  26787. return function (args) { return callUnwrapValue(expression.nodeIndex, expression.bindingIndex, callCheckStmt(checkIndex_1, [pipeValueExpr_1].concat(args))); };
  26788. }
  26789. else {
  26790. var nodeIndex = this._createPipe(expression.sourceSpan, pipe);
  26791. var nodeValueExpr_1 = importExpr(Identifiers$1.nodeValue).callFn([VIEW_VAR, literal(nodeIndex)]);
  26792. return function (args) { return callUnwrapValue(expression.nodeIndex, expression.bindingIndex, nodeValueExpr_1.callMethod('transform', args)); };
  26793. }
  26794. };
  26795. ViewBuilder.prototype._createPipe = function (sourceSpan, pipe) {
  26796. var _this = this;
  26797. var nodeIndex = this.nodes.length;
  26798. var flags = 0 /* None */;
  26799. pipe.type.lifecycleHooks.forEach(function (lifecycleHook) {
  26800. // for pipes, we only support ngOnDestroy
  26801. if (lifecycleHook === LifecycleHooks.OnDestroy) {
  26802. flags |= lifecycleHookToNodeFlag(lifecycleHook);
  26803. }
  26804. });
  26805. var depExprs = pipe.type.diDeps.map(function (diDep) { return depDef(_this.outputCtx, diDep); });
  26806. // function pipeDef(
  26807. // flags: NodeFlags, ctor: any, deps: ([DepFlags, any] | any)[]): NodeDef
  26808. this.nodes.push(function () { return ({
  26809. sourceSpan: sourceSpan,
  26810. nodeFlags: 16 /* TypePipe */,
  26811. nodeDef: importExpr(Identifiers$1.pipeDef).callFn([
  26812. literal(flags), _this.outputCtx.importExpr(pipe.type.reference), literalArr(depExprs)
  26813. ])
  26814. }); });
  26815. return nodeIndex;
  26816. };
  26817. /**
  26818. * For the AST in `UpdateExpression.value`:
  26819. * - create nodes for pipes, literal arrays and, literal maps,
  26820. * - update the AST to replace pipes, literal arrays and, literal maps with calls to check fn.
  26821. *
  26822. * WARNING: This might create new nodeDefs (for pipes and literal arrays and literal maps)!
  26823. */
  26824. ViewBuilder.prototype._preprocessUpdateExpression = function (expression) {
  26825. var _this = this;
  26826. return {
  26827. nodeIndex: expression.nodeIndex,
  26828. bindingIndex: expression.bindingIndex,
  26829. sourceSpan: expression.sourceSpan,
  26830. context: expression.context,
  26831. value: convertPropertyBindingBuiltins({
  26832. createLiteralArrayConverter: function (argCount) { return _this._createLiteralArrayConverter(expression.sourceSpan, argCount); },
  26833. createLiteralMapConverter: function (keys) { return _this._createLiteralMapConverter(expression.sourceSpan, keys); },
  26834. createPipeConverter: function (name, argCount) { return _this._createPipeConverter(expression, name, argCount); }
  26835. }, expression.value)
  26836. };
  26837. };
  26838. ViewBuilder.prototype._createNodeExpressions = function () {
  26839. var self = this;
  26840. var updateBindingCount = 0;
  26841. var updateRendererStmts = [];
  26842. var updateDirectivesStmts = [];
  26843. var nodeDefExprs = this.nodes.map(function (factory, nodeIndex) {
  26844. var _a = factory(), nodeDef = _a.nodeDef, nodeFlags = _a.nodeFlags, updateDirectives = _a.updateDirectives, updateRenderer = _a.updateRenderer, sourceSpan = _a.sourceSpan;
  26845. if (updateRenderer) {
  26846. updateRendererStmts.push.apply(updateRendererStmts, __spreadArray([], __read(createUpdateStatements(nodeIndex, sourceSpan, updateRenderer, false))));
  26847. }
  26848. if (updateDirectives) {
  26849. updateDirectivesStmts.push.apply(updateDirectivesStmts, __spreadArray([], __read(createUpdateStatements(nodeIndex, sourceSpan, updateDirectives, (nodeFlags & (262144 /* DoCheck */ | 65536 /* OnInit */)) > 0))));
  26850. }
  26851. // We use a comma expression to call the log function before
  26852. // the nodeDef function, but still use the result of the nodeDef function
  26853. // as the value.
  26854. // Note: We only add the logger to elements / text nodes,
  26855. // so we don't generate too much code.
  26856. var logWithNodeDef = nodeFlags & 3 /* CatRenderNode */ ?
  26857. new CommaExpr([LOG_VAR$1.callFn([]).callFn([]), nodeDef]) :
  26858. nodeDef;
  26859. return applySourceSpanToExpressionIfNeeded(logWithNodeDef, sourceSpan);
  26860. });
  26861. return { updateRendererStmts: updateRendererStmts, updateDirectivesStmts: updateDirectivesStmts, nodeDefExprs: nodeDefExprs };
  26862. function createUpdateStatements(nodeIndex, sourceSpan, expressions, allowEmptyExprs) {
  26863. var updateStmts = [];
  26864. var exprs = expressions.map(function (_a) {
  26865. var sourceSpan = _a.sourceSpan, context = _a.context, value = _a.value;
  26866. var bindingId = "" + updateBindingCount++;
  26867. var nameResolver = context === COMP_VAR ? self : null;
  26868. var _b = convertPropertyBinding(nameResolver, context, value, bindingId, BindingForm.General), stmts = _b.stmts, currValExpr = _b.currValExpr;
  26869. updateStmts.push.apply(updateStmts, __spreadArray([], __read(stmts.map(function (stmt) { return applySourceSpanToStatementIfNeeded(stmt, sourceSpan); }))));
  26870. return applySourceSpanToExpressionIfNeeded(currValExpr, sourceSpan);
  26871. });
  26872. if (expressions.length || allowEmptyExprs) {
  26873. updateStmts.push(applySourceSpanToStatementIfNeeded(callCheckStmt(nodeIndex, exprs).toStmt(), sourceSpan));
  26874. }
  26875. return updateStmts;
  26876. }
  26877. };
  26878. ViewBuilder.prototype._createElementHandleEventFn = function (nodeIndex, handlers) {
  26879. var _this = this;
  26880. var handleEventStmts = [];
  26881. var handleEventBindingCount = 0;
  26882. handlers.forEach(function (_a) {
  26883. var context = _a.context, eventAst = _a.eventAst, dirAst = _a.dirAst;
  26884. var bindingId = "" + handleEventBindingCount++;
  26885. var nameResolver = context === COMP_VAR ? _this : null;
  26886. var _b = convertActionBinding(nameResolver, context, eventAst.handler, bindingId), stmts = _b.stmts, allowDefault = _b.allowDefault;
  26887. var trueStmts = stmts;
  26888. if (allowDefault) {
  26889. trueStmts.push(ALLOW_DEFAULT_VAR.set(allowDefault.and(ALLOW_DEFAULT_VAR)).toStmt());
  26890. }
  26891. var _c = elementEventNameAndTarget(eventAst, dirAst), eventTarget = _c.target, eventName = _c.name;
  26892. var fullEventName = elementEventFullName(eventTarget, eventName);
  26893. handleEventStmts.push(applySourceSpanToStatementIfNeeded(new IfStmt(literal(fullEventName).identical(EVENT_NAME_VAR), trueStmts), eventAst.sourceSpan));
  26894. });
  26895. var handleEventFn;
  26896. if (handleEventStmts.length > 0) {
  26897. var preStmts = [ALLOW_DEFAULT_VAR.set(literal(true)).toDeclStmt(BOOL_TYPE)];
  26898. if (!this.component.isHost && findReadVarNames(handleEventStmts).has(COMP_VAR.name)) {
  26899. preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
  26900. }
  26901. handleEventFn = fn([
  26902. new FnParam(VIEW_VAR.name, INFERRED_TYPE),
  26903. new FnParam(EVENT_NAME_VAR.name, INFERRED_TYPE),
  26904. new FnParam(EventHandlerVars.event.name, INFERRED_TYPE)
  26905. ], __spreadArray(__spreadArray(__spreadArray([], __read(preStmts)), __read(handleEventStmts)), [new ReturnStatement(ALLOW_DEFAULT_VAR)]), INFERRED_TYPE);
  26906. }
  26907. else {
  26908. handleEventFn = NULL_EXPR;
  26909. }
  26910. return handleEventFn;
  26911. };
  26912. ViewBuilder.prototype.visitDirective = function (ast, context) { };
  26913. ViewBuilder.prototype.visitDirectiveProperty = function (ast, context) { };
  26914. ViewBuilder.prototype.visitReference = function (ast, context) { };
  26915. ViewBuilder.prototype.visitVariable = function (ast, context) { };
  26916. ViewBuilder.prototype.visitEvent = function (ast, context) { };
  26917. ViewBuilder.prototype.visitElementProperty = function (ast, context) { };
  26918. ViewBuilder.prototype.visitAttr = function (ast, context) { };
  26919. return ViewBuilder;
  26920. }());
  26921. function needsAdditionalRootNode(astNodes) {
  26922. var lastAstNode = astNodes[astNodes.length - 1];
  26923. if (lastAstNode instanceof EmbeddedTemplateAst) {
  26924. return lastAstNode.hasViewContainer;
  26925. }
  26926. if (lastAstNode instanceof ElementAst) {
  26927. if (isNgContainer(lastAstNode.name) && lastAstNode.children.length) {
  26928. return needsAdditionalRootNode(lastAstNode.children);
  26929. }
  26930. return lastAstNode.hasViewContainer;
  26931. }
  26932. return lastAstNode instanceof NgContentAst;
  26933. }
  26934. function elementBindingDef(inputAst, dirAst) {
  26935. var inputType = inputAst.type;
  26936. switch (inputType) {
  26937. case 1 /* Attribute */:
  26938. return literalArr([
  26939. literal(1 /* TypeElementAttribute */), literal(inputAst.name),
  26940. literal(inputAst.securityContext)
  26941. ]);
  26942. case 0 /* Property */:
  26943. return literalArr([
  26944. literal(8 /* TypeProperty */), literal(inputAst.name),
  26945. literal(inputAst.securityContext)
  26946. ]);
  26947. case 4 /* Animation */:
  26948. var bindingType = 8 /* TypeProperty */ |
  26949. (dirAst && dirAst.directive.isComponent ? 32 /* SyntheticHostProperty */ :
  26950. 16 /* SyntheticProperty */);
  26951. return literalArr([
  26952. literal(bindingType), literal('@' + inputAst.name), literal(inputAst.securityContext)
  26953. ]);
  26954. case 2 /* Class */:
  26955. return literalArr([literal(2 /* TypeElementClass */), literal(inputAst.name), NULL_EXPR]);
  26956. case 3 /* Style */:
  26957. return literalArr([
  26958. literal(4 /* TypeElementStyle */), literal(inputAst.name), literal(inputAst.unit)
  26959. ]);
  26960. default:
  26961. // This default case is not needed by TypeScript compiler, as the switch is exhaustive.
  26962. // However Closure Compiler does not understand that and reports an error in typed mode.
  26963. // The `throw new Error` below works around the problem, and the unexpected: never variable
  26964. // makes sure tsc still checks this code is unreachable.
  26965. var unexpected = inputType;
  26966. throw new Error("unexpected " + unexpected);
  26967. }
  26968. }
  26969. function fixedAttrsDef(elementAst) {
  26970. var mapResult = Object.create(null);
  26971. elementAst.attrs.forEach(function (attrAst) {
  26972. mapResult[attrAst.name] = attrAst.value;
  26973. });
  26974. elementAst.directives.forEach(function (dirAst) {
  26975. Object.keys(dirAst.directive.hostAttributes).forEach(function (name) {
  26976. var value = dirAst.directive.hostAttributes[name];
  26977. var prevValue = mapResult[name];
  26978. mapResult[name] = prevValue != null ? mergeAttributeValue(name, prevValue, value) : value;
  26979. });
  26980. });
  26981. // Note: We need to sort to get a defined output order
  26982. // for tests and for caching generated artifacts...
  26983. return literalArr(Object.keys(mapResult).sort().map(function (attrName) { return literalArr([literal(attrName), literal(mapResult[attrName])]); }));
  26984. }
  26985. function mergeAttributeValue(attrName, attrValue1, attrValue2) {
  26986. if (attrName == CLASS_ATTR$1 || attrName == STYLE_ATTR) {
  26987. return attrValue1 + " " + attrValue2;
  26988. }
  26989. else {
  26990. return attrValue2;
  26991. }
  26992. }
  26993. function callCheckStmt(nodeIndex, exprs) {
  26994. if (exprs.length > 10) {
  26995. return CHECK_VAR.callFn([VIEW_VAR, literal(nodeIndex), literal(1 /* Dynamic */), literalArr(exprs)]);
  26996. }
  26997. else {
  26998. return CHECK_VAR.callFn(__spreadArray([VIEW_VAR, literal(nodeIndex), literal(0 /* Inline */)], __read(exprs)));
  26999. }
  27000. }
  27001. function callUnwrapValue(nodeIndex, bindingIdx, expr) {
  27002. return importExpr(Identifiers$1.unwrapValue).callFn([
  27003. VIEW_VAR, literal(nodeIndex), literal(bindingIdx), expr
  27004. ]);
  27005. }
  27006. function elementEventNameAndTarget(eventAst, dirAst) {
  27007. if (eventAst.isAnimation) {
  27008. return {
  27009. name: "@" + eventAst.name + "." + eventAst.phase,
  27010. target: dirAst && dirAst.directive.isComponent ? 'component' : null
  27011. };
  27012. }
  27013. else {
  27014. return eventAst;
  27015. }
  27016. }
  27017. function calcQueryFlags(query) {
  27018. var flags = 0 /* None */;
  27019. // Note: We only make queries static that query for a single item and the user specifically
  27020. // set the to be static. This is because of backwards compatibility with the old view compiler...
  27021. if (query.first && query.static) {
  27022. flags |= 268435456 /* StaticQuery */;
  27023. }
  27024. else {
  27025. flags |= 536870912 /* DynamicQuery */;
  27026. }
  27027. if (query.emitDistinctChangesOnly) {
  27028. flags |= -2147483648 /* EmitDistinctChangesOnly */;
  27029. }
  27030. return flags;
  27031. }
  27032. function elementEventFullName(target, name) {
  27033. return target ? target + ":" + name : name;
  27034. }
  27035. /**
  27036. * A container for message extracted from the templates.
  27037. */
  27038. var MessageBundle = /** @class */ (function () {
  27039. function MessageBundle(_htmlParser, _implicitTags, _implicitAttrs, _locale) {
  27040. if (_locale === void 0) { _locale = null; }
  27041. this._htmlParser = _htmlParser;
  27042. this._implicitTags = _implicitTags;
  27043. this._implicitAttrs = _implicitAttrs;
  27044. this._locale = _locale;
  27045. this._messages = [];
  27046. }
  27047. MessageBundle.prototype.updateFromTemplate = function (html, url, interpolationConfig) {
  27048. var _a;
  27049. var htmlParserResult = this._htmlParser.parse(html, url, { tokenizeExpansionForms: true, interpolationConfig: interpolationConfig });
  27050. if (htmlParserResult.errors.length) {
  27051. return htmlParserResult.errors;
  27052. }
  27053. var i18nParserResult = extractMessages(htmlParserResult.rootNodes, interpolationConfig, this._implicitTags, this._implicitAttrs);
  27054. if (i18nParserResult.errors.length) {
  27055. return i18nParserResult.errors;
  27056. }
  27057. (_a = this._messages).push.apply(_a, __spreadArray([], __read(i18nParserResult.messages)));
  27058. return [];
  27059. };
  27060. // Return the message in the internal format
  27061. // The public (serialized) format might be different, see the `write` method.
  27062. MessageBundle.prototype.getMessages = function () {
  27063. return this._messages;
  27064. };
  27065. MessageBundle.prototype.write = function (serializer, filterSources) {
  27066. var messages = {};
  27067. var mapperVisitor = new MapPlaceholderNames();
  27068. // Deduplicate messages based on their ID
  27069. this._messages.forEach(function (message) {
  27070. var _a;
  27071. var id = serializer.digest(message);
  27072. if (!messages.hasOwnProperty(id)) {
  27073. messages[id] = message;
  27074. }
  27075. else {
  27076. (_a = messages[id].sources).push.apply(_a, __spreadArray([], __read(message.sources)));
  27077. }
  27078. });
  27079. // Transform placeholder names using the serializer mapping
  27080. var msgList = Object.keys(messages).map(function (id) {
  27081. var mapper = serializer.createNameMapper(messages[id]);
  27082. var src = messages[id];
  27083. var nodes = mapper ? mapperVisitor.convert(src.nodes, mapper) : src.nodes;
  27084. var transformedMessage = new Message(nodes, {}, {}, src.meaning, src.description, id);
  27085. transformedMessage.sources = src.sources;
  27086. if (filterSources) {
  27087. transformedMessage.sources.forEach(function (source) { return source.filePath = filterSources(source.filePath); });
  27088. }
  27089. return transformedMessage;
  27090. });
  27091. return serializer.write(msgList, this._locale);
  27092. };
  27093. return MessageBundle;
  27094. }());
  27095. // Transform an i18n AST by renaming the placeholder nodes with the given mapper
  27096. var MapPlaceholderNames = /** @class */ (function (_super) {
  27097. __extends(MapPlaceholderNames, _super);
  27098. function MapPlaceholderNames() {
  27099. return _super !== null && _super.apply(this, arguments) || this;
  27100. }
  27101. MapPlaceholderNames.prototype.convert = function (nodes, mapper) {
  27102. var _this = this;
  27103. return mapper ? nodes.map(function (n) { return n.visit(_this, mapper); }) : nodes;
  27104. };
  27105. MapPlaceholderNames.prototype.visitTagPlaceholder = function (ph, mapper) {
  27106. var _this = this;
  27107. var startName = mapper.toPublicName(ph.startName);
  27108. var closeName = ph.closeName ? mapper.toPublicName(ph.closeName) : ph.closeName;
  27109. var children = ph.children.map(function (n) { return n.visit(_this, mapper); });
  27110. return new TagPlaceholder(ph.tag, ph.attrs, startName, closeName, children, ph.isVoid, ph.sourceSpan, ph.startSourceSpan, ph.endSourceSpan);
  27111. };
  27112. MapPlaceholderNames.prototype.visitPlaceholder = function (ph, mapper) {
  27113. return new Placeholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
  27114. };
  27115. MapPlaceholderNames.prototype.visitIcuPlaceholder = function (ph, mapper) {
  27116. return new IcuPlaceholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
  27117. };
  27118. return MapPlaceholderNames;
  27119. }(CloneVisitor));
  27120. /**
  27121. * @license
  27122. * Copyright Google LLC All Rights Reserved.
  27123. *
  27124. * Use of this source code is governed by an MIT-style license that can be
  27125. * found in the LICENSE file at https://angular.io/license
  27126. */
  27127. var GeneratedFile = /** @class */ (function () {
  27128. function GeneratedFile(srcFileUrl, genFileUrl, sourceOrStmts) {
  27129. this.srcFileUrl = srcFileUrl;
  27130. this.genFileUrl = genFileUrl;
  27131. if (typeof sourceOrStmts === 'string') {
  27132. this.source = sourceOrStmts;
  27133. this.stmts = null;
  27134. }
  27135. else {
  27136. this.source = null;
  27137. this.stmts = sourceOrStmts;
  27138. }
  27139. }
  27140. GeneratedFile.prototype.isEquivalent = function (other) {
  27141. if (this.genFileUrl !== other.genFileUrl) {
  27142. return false;
  27143. }
  27144. if (this.source) {
  27145. return this.source === other.source;
  27146. }
  27147. if (other.stmts == null) {
  27148. return false;
  27149. }
  27150. // Note: the constructor guarantees that if this.source is not filled,
  27151. // then this.stmts is.
  27152. return areAllEquivalent(this.stmts, other.stmts);
  27153. };
  27154. return GeneratedFile;
  27155. }());
  27156. function toTypeScript(file, preamble) {
  27157. if (preamble === void 0) { preamble = ''; }
  27158. if (!file.stmts) {
  27159. throw new Error("Illegal state: No stmts present on GeneratedFile " + file.genFileUrl);
  27160. }
  27161. return new TypeScriptEmitter().emitStatements(file.genFileUrl, file.stmts, preamble);
  27162. }
  27163. function listLazyRoutes(moduleMeta, reflector) {
  27164. var e_1, _a, e_2, _b;
  27165. var allLazyRoutes = [];
  27166. try {
  27167. for (var _c = __values(moduleMeta.transitiveModule.providers), _d = _c.next(); !_d.done; _d = _c.next()) {
  27168. var _e = _d.value, provider = _e.provider, module = _e.module;
  27169. if (tokenReference(provider.token) === reflector.ROUTES) {
  27170. var loadChildren = _collectLoadChildren(provider.useValue);
  27171. try {
  27172. for (var loadChildren_1 = (e_2 = void 0, __values(loadChildren)), loadChildren_1_1 = loadChildren_1.next(); !loadChildren_1_1.done; loadChildren_1_1 = loadChildren_1.next()) {
  27173. var route = loadChildren_1_1.value;
  27174. allLazyRoutes.push(parseLazyRoute(route, reflector, module.reference));
  27175. }
  27176. }
  27177. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  27178. finally {
  27179. try {
  27180. if (loadChildren_1_1 && !loadChildren_1_1.done && (_b = loadChildren_1.return)) _b.call(loadChildren_1);
  27181. }
  27182. finally { if (e_2) throw e_2.error; }
  27183. }
  27184. }
  27185. }
  27186. }
  27187. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  27188. finally {
  27189. try {
  27190. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  27191. }
  27192. finally { if (e_1) throw e_1.error; }
  27193. }
  27194. return allLazyRoutes;
  27195. }
  27196. function _collectLoadChildren(routes, target) {
  27197. var e_3, _a;
  27198. if (target === void 0) { target = []; }
  27199. if (typeof routes === 'string') {
  27200. target.push(routes);
  27201. }
  27202. else if (Array.isArray(routes)) {
  27203. try {
  27204. for (var routes_1 = __values(routes), routes_1_1 = routes_1.next(); !routes_1_1.done; routes_1_1 = routes_1.next()) {
  27205. var route = routes_1_1.value;
  27206. _collectLoadChildren(route, target);
  27207. }
  27208. }
  27209. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  27210. finally {
  27211. try {
  27212. if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
  27213. }
  27214. finally { if (e_3) throw e_3.error; }
  27215. }
  27216. }
  27217. else if (routes.loadChildren) {
  27218. _collectLoadChildren(routes.loadChildren, target);
  27219. }
  27220. else if (routes.children) {
  27221. _collectLoadChildren(routes.children, target);
  27222. }
  27223. return target;
  27224. }
  27225. function parseLazyRoute(route, reflector, module) {
  27226. var _a = __read(route.split('#'), 2), routePath = _a[0], routeName = _a[1];
  27227. var referencedModule = reflector.resolveExternalReference({
  27228. moduleName: routePath,
  27229. name: routeName,
  27230. }, module ? module.filePath : undefined);
  27231. return { route: route, module: module || referencedModule, referencedModule: referencedModule };
  27232. }
  27233. var TS = /^(?!.*\.d\.ts$).*\.ts$/;
  27234. var ResolvedStaticSymbol = /** @class */ (function () {
  27235. function ResolvedStaticSymbol(symbol, metadata) {
  27236. this.symbol = symbol;
  27237. this.metadata = metadata;
  27238. }
  27239. return ResolvedStaticSymbol;
  27240. }());
  27241. var SUPPORTED_SCHEMA_VERSION = 4;
  27242. /**
  27243. * This class is responsible for loading metadata per symbol,
  27244. * and normalizing references between symbols.
  27245. *
  27246. * Internally, it only uses symbols without members,
  27247. * and deduces the values for symbols with members based
  27248. * on these symbols.
  27249. */
  27250. var StaticSymbolResolver = /** @class */ (function () {
  27251. function StaticSymbolResolver(host, staticSymbolCache, summaryResolver, errorRecorder) {
  27252. this.host = host;
  27253. this.staticSymbolCache = staticSymbolCache;
  27254. this.summaryResolver = summaryResolver;
  27255. this.errorRecorder = errorRecorder;
  27256. this.metadataCache = new Map();
  27257. // Note: this will only contain StaticSymbols without members!
  27258. this.resolvedSymbols = new Map();
  27259. // Note: this will only contain StaticSymbols without members!
  27260. this.importAs = new Map();
  27261. this.symbolResourcePaths = new Map();
  27262. this.symbolFromFile = new Map();
  27263. this.knownFileNameToModuleNames = new Map();
  27264. }
  27265. StaticSymbolResolver.prototype.resolveSymbol = function (staticSymbol) {
  27266. if (staticSymbol.members.length > 0) {
  27267. return this._resolveSymbolMembers(staticSymbol);
  27268. }
  27269. // Note: always ask for a summary first,
  27270. // as we might have read shallow metadata via a .d.ts file
  27271. // for the symbol.
  27272. var resultFromSummary = this._resolveSymbolFromSummary(staticSymbol);
  27273. if (resultFromSummary) {
  27274. return resultFromSummary;
  27275. }
  27276. var resultFromCache = this.resolvedSymbols.get(staticSymbol);
  27277. if (resultFromCache) {
  27278. return resultFromCache;
  27279. }
  27280. // Note: Some users use libraries that were not compiled with ngc, i.e. they don't
  27281. // have summaries, only .d.ts files. So we always need to check both, the summary
  27282. // and metadata.
  27283. this._createSymbolsOf(staticSymbol.filePath);
  27284. return this.resolvedSymbols.get(staticSymbol);
  27285. };
  27286. /**
  27287. * getImportAs produces a symbol that can be used to import the given symbol.
  27288. * The import might be different than the symbol if the symbol is exported from
  27289. * a library with a summary; in which case we want to import the symbol from the
  27290. * ngfactory re-export instead of directly to avoid introducing a direct dependency
  27291. * on an otherwise indirect dependency.
  27292. *
  27293. * @param staticSymbol the symbol for which to generate a import symbol
  27294. */
  27295. StaticSymbolResolver.prototype.getImportAs = function (staticSymbol, useSummaries) {
  27296. if (useSummaries === void 0) { useSummaries = true; }
  27297. if (staticSymbol.members.length) {
  27298. var baseSymbol = this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name);
  27299. var baseImportAs = this.getImportAs(baseSymbol, useSummaries);
  27300. return baseImportAs ?
  27301. this.getStaticSymbol(baseImportAs.filePath, baseImportAs.name, staticSymbol.members) :
  27302. null;
  27303. }
  27304. var summarizedFileName = stripSummaryForJitFileSuffix(staticSymbol.filePath);
  27305. if (summarizedFileName !== staticSymbol.filePath) {
  27306. var summarizedName = stripSummaryForJitNameSuffix(staticSymbol.name);
  27307. var baseSymbol = this.getStaticSymbol(summarizedFileName, summarizedName, staticSymbol.members);
  27308. var baseImportAs = this.getImportAs(baseSymbol, useSummaries);
  27309. return baseImportAs ? this.getStaticSymbol(summaryForJitFileName(baseImportAs.filePath), summaryForJitName(baseImportAs.name), baseSymbol.members) :
  27310. null;
  27311. }
  27312. var result = (useSummaries && this.summaryResolver.getImportAs(staticSymbol)) || null;
  27313. if (!result) {
  27314. result = this.importAs.get(staticSymbol);
  27315. }
  27316. return result;
  27317. };
  27318. /**
  27319. * getResourcePath produces the path to the original location of the symbol and should
  27320. * be used to determine the relative location of resource references recorded in
  27321. * symbol metadata.
  27322. */
  27323. StaticSymbolResolver.prototype.getResourcePath = function (staticSymbol) {
  27324. return this.symbolResourcePaths.get(staticSymbol) || staticSymbol.filePath;
  27325. };
  27326. /**
  27327. * getTypeArity returns the number of generic type parameters the given symbol
  27328. * has. If the symbol is not a type the result is null.
  27329. */
  27330. StaticSymbolResolver.prototype.getTypeArity = function (staticSymbol) {
  27331. // If the file is a factory/ngsummary file, don't resolve the symbol as doing so would
  27332. // cause the metadata for an factory/ngsummary file to be loaded which doesn't exist.
  27333. // All references to generated classes must include the correct arity whenever
  27334. // generating code.
  27335. if (isGeneratedFile(staticSymbol.filePath)) {
  27336. return null;
  27337. }
  27338. var resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(staticSymbol));
  27339. while (resolvedSymbol && resolvedSymbol.metadata instanceof StaticSymbol) {
  27340. resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(resolvedSymbol.metadata));
  27341. }
  27342. return (resolvedSymbol && resolvedSymbol.metadata && resolvedSymbol.metadata.arity) || null;
  27343. };
  27344. StaticSymbolResolver.prototype.getKnownModuleName = function (filePath) {
  27345. return this.knownFileNameToModuleNames.get(filePath) || null;
  27346. };
  27347. StaticSymbolResolver.prototype.recordImportAs = function (sourceSymbol, targetSymbol) {
  27348. sourceSymbol.assertNoMembers();
  27349. targetSymbol.assertNoMembers();
  27350. this.importAs.set(sourceSymbol, targetSymbol);
  27351. };
  27352. StaticSymbolResolver.prototype.recordModuleNameForFileName = function (fileName, moduleName) {
  27353. this.knownFileNameToModuleNames.set(fileName, moduleName);
  27354. };
  27355. /**
  27356. * Invalidate all information derived from the given file and return the
  27357. * static symbols contained in the file.
  27358. *
  27359. * @param fileName the file to invalidate
  27360. */
  27361. StaticSymbolResolver.prototype.invalidateFile = function (fileName) {
  27362. var e_1, _a;
  27363. this.metadataCache.delete(fileName);
  27364. var symbols = this.symbolFromFile.get(fileName);
  27365. if (!symbols) {
  27366. return [];
  27367. }
  27368. this.symbolFromFile.delete(fileName);
  27369. try {
  27370. for (var symbols_1 = __values(symbols), symbols_1_1 = symbols_1.next(); !symbols_1_1.done; symbols_1_1 = symbols_1.next()) {
  27371. var symbol = symbols_1_1.value;
  27372. this.resolvedSymbols.delete(symbol);
  27373. this.importAs.delete(symbol);
  27374. this.symbolResourcePaths.delete(symbol);
  27375. }
  27376. }
  27377. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  27378. finally {
  27379. try {
  27380. if (symbols_1_1 && !symbols_1_1.done && (_a = symbols_1.return)) _a.call(symbols_1);
  27381. }
  27382. finally { if (e_1) throw e_1.error; }
  27383. }
  27384. return symbols;
  27385. };
  27386. /** @internal */
  27387. StaticSymbolResolver.prototype.ignoreErrorsFor = function (cb) {
  27388. var recorder = this.errorRecorder;
  27389. this.errorRecorder = function () { };
  27390. try {
  27391. return cb();
  27392. }
  27393. finally {
  27394. this.errorRecorder = recorder;
  27395. }
  27396. };
  27397. StaticSymbolResolver.prototype._resolveSymbolMembers = function (staticSymbol) {
  27398. var members = staticSymbol.members;
  27399. var baseResolvedSymbol = this.resolveSymbol(this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name));
  27400. if (!baseResolvedSymbol) {
  27401. return null;
  27402. }
  27403. var baseMetadata = unwrapResolvedMetadata(baseResolvedSymbol.metadata);
  27404. if (baseMetadata instanceof StaticSymbol) {
  27405. return new ResolvedStaticSymbol(staticSymbol, this.getStaticSymbol(baseMetadata.filePath, baseMetadata.name, members));
  27406. }
  27407. else if (baseMetadata && baseMetadata.__symbolic === 'class') {
  27408. if (baseMetadata.statics && members.length === 1) {
  27409. return new ResolvedStaticSymbol(staticSymbol, baseMetadata.statics[members[0]]);
  27410. }
  27411. }
  27412. else {
  27413. var value = baseMetadata;
  27414. for (var i = 0; i < members.length && value; i++) {
  27415. value = value[members[i]];
  27416. }
  27417. return new ResolvedStaticSymbol(staticSymbol, value);
  27418. }
  27419. return null;
  27420. };
  27421. StaticSymbolResolver.prototype._resolveSymbolFromSummary = function (staticSymbol) {
  27422. var summary = this.summaryResolver.resolveSummary(staticSymbol);
  27423. return summary ? new ResolvedStaticSymbol(staticSymbol, summary.metadata) : null;
  27424. };
  27425. /**
  27426. * getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
  27427. * All types passed to the StaticResolver should be pseudo-types returned by this method.
  27428. *
  27429. * @param declarationFile the absolute path of the file where the symbol is declared
  27430. * @param name the name of the type.
  27431. * @param members a symbol for a static member of the named type
  27432. */
  27433. StaticSymbolResolver.prototype.getStaticSymbol = function (declarationFile, name, members) {
  27434. return this.staticSymbolCache.get(declarationFile, name, members);
  27435. };
  27436. /**
  27437. * hasDecorators checks a file's metadata for the presence of decorators without evaluating the
  27438. * metadata.
  27439. *
  27440. * @param filePath the absolute path to examine for decorators.
  27441. * @returns true if any class in the file has a decorator.
  27442. */
  27443. StaticSymbolResolver.prototype.hasDecorators = function (filePath) {
  27444. var metadata = this.getModuleMetadata(filePath);
  27445. if (metadata['metadata']) {
  27446. return Object.keys(metadata['metadata']).some(function (metadataKey) {
  27447. var entry = metadata['metadata'][metadataKey];
  27448. return entry && entry.__symbolic === 'class' && entry.decorators;
  27449. });
  27450. }
  27451. return false;
  27452. };
  27453. StaticSymbolResolver.prototype.getSymbolsOf = function (filePath) {
  27454. var summarySymbols = this.summaryResolver.getSymbolsOf(filePath);
  27455. if (summarySymbols) {
  27456. return summarySymbols;
  27457. }
  27458. // Note: Some users use libraries that were not compiled with ngc, i.e. they don't
  27459. // have summaries, only .d.ts files, but `summaryResolver.isLibraryFile` returns true.
  27460. this._createSymbolsOf(filePath);
  27461. return this.symbolFromFile.get(filePath) || [];
  27462. };
  27463. StaticSymbolResolver.prototype._createSymbolsOf = function (filePath) {
  27464. var e_2, _a, e_3, _b;
  27465. var _this = this;
  27466. if (this.symbolFromFile.has(filePath)) {
  27467. return;
  27468. }
  27469. var resolvedSymbols = [];
  27470. var metadata = this.getModuleMetadata(filePath);
  27471. if (metadata['importAs']) {
  27472. // Index bundle indices should use the importAs module name defined
  27473. // in the bundle.
  27474. this.knownFileNameToModuleNames.set(filePath, metadata['importAs']);
  27475. }
  27476. // handle the symbols in one of the re-export location
  27477. if (metadata['exports']) {
  27478. var _loop_1 = function (moduleExport) {
  27479. // handle the symbols in the list of explicitly re-exported symbols.
  27480. if (moduleExport.export) {
  27481. moduleExport.export.forEach(function (exportSymbol) {
  27482. var symbolName;
  27483. if (typeof exportSymbol === 'string') {
  27484. symbolName = exportSymbol;
  27485. }
  27486. else {
  27487. symbolName = exportSymbol.as;
  27488. }
  27489. symbolName = unescapeIdentifier(symbolName);
  27490. var symName = symbolName;
  27491. if (typeof exportSymbol !== 'string') {
  27492. symName = unescapeIdentifier(exportSymbol.name);
  27493. }
  27494. var resolvedModule = _this.resolveModule(moduleExport.from, filePath);
  27495. if (resolvedModule) {
  27496. var targetSymbol = _this.getStaticSymbol(resolvedModule, symName);
  27497. var sourceSymbol = _this.getStaticSymbol(filePath, symbolName);
  27498. resolvedSymbols.push(_this.createExport(sourceSymbol, targetSymbol));
  27499. }
  27500. });
  27501. }
  27502. else {
  27503. // Handle the symbols loaded by 'export *' directives.
  27504. var resolvedModule = this_1.resolveModule(moduleExport.from, filePath);
  27505. if (resolvedModule && resolvedModule !== filePath) {
  27506. var nestedExports = this_1.getSymbolsOf(resolvedModule);
  27507. nestedExports.forEach(function (targetSymbol) {
  27508. var sourceSymbol = _this.getStaticSymbol(filePath, targetSymbol.name);
  27509. resolvedSymbols.push(_this.createExport(sourceSymbol, targetSymbol));
  27510. });
  27511. }
  27512. }
  27513. };
  27514. var this_1 = this;
  27515. try {
  27516. for (var _c = __values(metadata['exports']), _d = _c.next(); !_d.done; _d = _c.next()) {
  27517. var moduleExport = _d.value;
  27518. _loop_1(moduleExport);
  27519. }
  27520. }
  27521. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  27522. finally {
  27523. try {
  27524. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  27525. }
  27526. finally { if (e_2) throw e_2.error; }
  27527. }
  27528. }
  27529. // handle the actual metadata. Has to be after the exports
  27530. // as there might be collisions in the names, and we want the symbols
  27531. // of the current module to win ofter reexports.
  27532. if (metadata['metadata']) {
  27533. // handle direct declarations of the symbol
  27534. var topLevelSymbolNames_1 = new Set(Object.keys(metadata['metadata']).map(unescapeIdentifier));
  27535. var origins_1 = metadata['origins'] || {};
  27536. Object.keys(metadata['metadata']).forEach(function (metadataKey) {
  27537. var symbolMeta = metadata['metadata'][metadataKey];
  27538. var name = unescapeIdentifier(metadataKey);
  27539. var symbol = _this.getStaticSymbol(filePath, name);
  27540. var origin = origins_1.hasOwnProperty(metadataKey) && origins_1[metadataKey];
  27541. if (origin) {
  27542. // If the symbol is from a bundled index, use the declaration location of the
  27543. // symbol so relative references (such as './my.html') will be calculated
  27544. // correctly.
  27545. var originFilePath = _this.resolveModule(origin, filePath);
  27546. if (!originFilePath) {
  27547. _this.reportError(new Error("Couldn't resolve original symbol for " + origin + " from " + _this.host.getOutputName(filePath)));
  27548. }
  27549. else {
  27550. _this.symbolResourcePaths.set(symbol, originFilePath);
  27551. }
  27552. }
  27553. resolvedSymbols.push(_this.createResolvedSymbol(symbol, filePath, topLevelSymbolNames_1, symbolMeta));
  27554. });
  27555. }
  27556. var uniqueSymbols = new Set();
  27557. try {
  27558. for (var resolvedSymbols_1 = __values(resolvedSymbols), resolvedSymbols_1_1 = resolvedSymbols_1.next(); !resolvedSymbols_1_1.done; resolvedSymbols_1_1 = resolvedSymbols_1.next()) {
  27559. var resolvedSymbol = resolvedSymbols_1_1.value;
  27560. this.resolvedSymbols.set(resolvedSymbol.symbol, resolvedSymbol);
  27561. uniqueSymbols.add(resolvedSymbol.symbol);
  27562. }
  27563. }
  27564. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  27565. finally {
  27566. try {
  27567. if (resolvedSymbols_1_1 && !resolvedSymbols_1_1.done && (_b = resolvedSymbols_1.return)) _b.call(resolvedSymbols_1);
  27568. }
  27569. finally { if (e_3) throw e_3.error; }
  27570. }
  27571. this.symbolFromFile.set(filePath, Array.from(uniqueSymbols));
  27572. };
  27573. StaticSymbolResolver.prototype.createResolvedSymbol = function (sourceSymbol, topLevelPath, topLevelSymbolNames, metadata) {
  27574. var _this = this;
  27575. // For classes that don't have Angular summaries / metadata,
  27576. // we only keep their arity, but nothing else
  27577. // (e.g. their constructor parameters).
  27578. // We do this to prevent introducing deep imports
  27579. // as we didn't generate .ngfactory.ts files with proper reexports.
  27580. var isTsFile = TS.test(sourceSymbol.filePath);
  27581. if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) && !isTsFile && metadata &&
  27582. metadata['__symbolic'] === 'class') {
  27583. var transformedMeta_1 = { __symbolic: 'class', arity: metadata.arity };
  27584. return new ResolvedStaticSymbol(sourceSymbol, transformedMeta_1);
  27585. }
  27586. var _originalFileMemo;
  27587. var getOriginalName = function () {
  27588. if (!_originalFileMemo) {
  27589. // Guess what the original file name is from the reference. If it has a `.d.ts` extension
  27590. // replace it with `.ts`. If it already has `.ts` just leave it in place. If it doesn't have
  27591. // .ts or .d.ts, append `.ts'. Also, if it is in `node_modules`, trim the `node_module`
  27592. // location as it is not important to finding the file.
  27593. _originalFileMemo =
  27594. _this.host.getOutputName(topLevelPath.replace(/((\.ts)|(\.d\.ts)|)$/, '.ts')
  27595. .replace(/^.*node_modules[/\\]/, ''));
  27596. }
  27597. return _originalFileMemo;
  27598. };
  27599. var self = this;
  27600. var ReferenceTransformer = /** @class */ (function (_super) {
  27601. __extends(ReferenceTransformer, _super);
  27602. function ReferenceTransformer() {
  27603. return _super !== null && _super.apply(this, arguments) || this;
  27604. }
  27605. ReferenceTransformer.prototype.visitStringMap = function (map, functionParams) {
  27606. var symbolic = map['__symbolic'];
  27607. if (symbolic === 'function') {
  27608. var oldLen = functionParams.length;
  27609. functionParams.push.apply(functionParams, __spreadArray([], __read((map['parameters'] || []))));
  27610. var result = _super.prototype.visitStringMap.call(this, map, functionParams);
  27611. functionParams.length = oldLen;
  27612. return result;
  27613. }
  27614. else if (symbolic === 'reference') {
  27615. var module = map['module'];
  27616. var name = map['name'] ? unescapeIdentifier(map['name']) : map['name'];
  27617. if (!name) {
  27618. return null;
  27619. }
  27620. var filePath = void 0;
  27621. if (module) {
  27622. filePath = self.resolveModule(module, sourceSymbol.filePath);
  27623. if (!filePath) {
  27624. return {
  27625. __symbolic: 'error',
  27626. message: "Could not resolve " + module + " relative to " + self.host.getMetadataFor(sourceSymbol.filePath) + ".",
  27627. line: map['line'],
  27628. character: map['character'],
  27629. fileName: getOriginalName()
  27630. };
  27631. }
  27632. return {
  27633. __symbolic: 'resolved',
  27634. symbol: self.getStaticSymbol(filePath, name),
  27635. line: map['line'],
  27636. character: map['character'],
  27637. fileName: getOriginalName()
  27638. };
  27639. }
  27640. else if (functionParams.indexOf(name) >= 0) {
  27641. // reference to a function parameter
  27642. return { __symbolic: 'reference', name: name };
  27643. }
  27644. else {
  27645. if (topLevelSymbolNames.has(name)) {
  27646. return self.getStaticSymbol(topLevelPath, name);
  27647. }
  27648. // ambient value
  27649. null;
  27650. }
  27651. }
  27652. else if (symbolic === 'error') {
  27653. return Object.assign(Object.assign({}, map), { fileName: getOriginalName() });
  27654. }
  27655. else {
  27656. return _super.prototype.visitStringMap.call(this, map, functionParams);
  27657. }
  27658. };
  27659. return ReferenceTransformer;
  27660. }(ValueTransformer));
  27661. var transformedMeta = visitValue(metadata, new ReferenceTransformer(), []);
  27662. var unwrappedTransformedMeta = unwrapResolvedMetadata(transformedMeta);
  27663. if (unwrappedTransformedMeta instanceof StaticSymbol) {
  27664. return this.createExport(sourceSymbol, unwrappedTransformedMeta);
  27665. }
  27666. return new ResolvedStaticSymbol(sourceSymbol, transformedMeta);
  27667. };
  27668. StaticSymbolResolver.prototype.createExport = function (sourceSymbol, targetSymbol) {
  27669. sourceSymbol.assertNoMembers();
  27670. targetSymbol.assertNoMembers();
  27671. if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) &&
  27672. this.summaryResolver.isLibraryFile(targetSymbol.filePath)) {
  27673. // This case is for an ng library importing symbols from a plain ts library
  27674. // transitively.
  27675. // Note: We rely on the fact that we discover symbols in the direction
  27676. // from source files to library files
  27677. this.importAs.set(targetSymbol, this.getImportAs(sourceSymbol) || sourceSymbol);
  27678. }
  27679. return new ResolvedStaticSymbol(sourceSymbol, targetSymbol);
  27680. };
  27681. StaticSymbolResolver.prototype.reportError = function (error, context, path) {
  27682. if (this.errorRecorder) {
  27683. this.errorRecorder(error, (context && context.filePath) || path);
  27684. }
  27685. else {
  27686. throw error;
  27687. }
  27688. };
  27689. /**
  27690. * @param module an absolute path to a module file.
  27691. */
  27692. StaticSymbolResolver.prototype.getModuleMetadata = function (module) {
  27693. var moduleMetadata = this.metadataCache.get(module);
  27694. if (!moduleMetadata) {
  27695. var moduleMetadatas = this.host.getMetadataFor(module);
  27696. if (moduleMetadatas) {
  27697. var maxVersion_1 = -1;
  27698. moduleMetadatas.forEach(function (md) {
  27699. if (md && md['version'] > maxVersion_1) {
  27700. maxVersion_1 = md['version'];
  27701. moduleMetadata = md;
  27702. }
  27703. });
  27704. }
  27705. if (!moduleMetadata) {
  27706. moduleMetadata =
  27707. { __symbolic: 'module', version: SUPPORTED_SCHEMA_VERSION, module: module, metadata: {} };
  27708. }
  27709. if (moduleMetadata['version'] != SUPPORTED_SCHEMA_VERSION) {
  27710. var errorMessage = moduleMetadata['version'] == 2 ?
  27711. "Unsupported metadata version " + moduleMetadata['version'] + " for module " + module + ". This module should be compiled with a newer version of ngc" :
  27712. "Metadata version mismatch for module " + this.host.getOutputName(module) + ", found version " + moduleMetadata['version'] + ", expected " + SUPPORTED_SCHEMA_VERSION;
  27713. this.reportError(new Error(errorMessage));
  27714. }
  27715. this.metadataCache.set(module, moduleMetadata);
  27716. }
  27717. return moduleMetadata;
  27718. };
  27719. StaticSymbolResolver.prototype.getSymbolByModule = function (module, symbolName, containingFile) {
  27720. var filePath = this.resolveModule(module, containingFile);
  27721. if (!filePath) {
  27722. this.reportError(new Error("Could not resolve module " + module + (containingFile ? ' relative to ' + this.host.getOutputName(containingFile) : '')));
  27723. return this.getStaticSymbol("ERROR:" + module, symbolName);
  27724. }
  27725. return this.getStaticSymbol(filePath, symbolName);
  27726. };
  27727. StaticSymbolResolver.prototype.resolveModule = function (module, containingFile) {
  27728. try {
  27729. return this.host.moduleNameToFileName(module, containingFile);
  27730. }
  27731. catch (e) {
  27732. console.error("Could not resolve module '" + module + "' relative to file " + containingFile);
  27733. this.reportError(e, undefined, containingFile);
  27734. }
  27735. return null;
  27736. };
  27737. return StaticSymbolResolver;
  27738. }());
  27739. // Remove extra underscore from escaped identifier.
  27740. // See https://github.com/Microsoft/TypeScript/blob/master/src/compiler/utilities.ts
  27741. function unescapeIdentifier(identifier) {
  27742. return identifier.startsWith('___') ? identifier.substr(1) : identifier;
  27743. }
  27744. function unwrapResolvedMetadata(metadata) {
  27745. if (metadata && metadata.__symbolic === 'resolved') {
  27746. return metadata.symbol;
  27747. }
  27748. return metadata;
  27749. }
  27750. function serializeSummaries(srcFileName, forJitCtx, summaryResolver, symbolResolver, symbols, types, createExternalSymbolReexports) {
  27751. if (createExternalSymbolReexports === void 0) { createExternalSymbolReexports = false; }
  27752. var toJsonSerializer = new ToJsonSerializer(symbolResolver, summaryResolver, srcFileName);
  27753. // for symbols, we use everything except for the class metadata itself
  27754. // (we keep the statics though), as the class metadata is contained in the
  27755. // CompileTypeSummary.
  27756. symbols.forEach(function (resolvedSymbol) { return toJsonSerializer.addSummary({ symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata }); });
  27757. // Add type summaries.
  27758. types.forEach(function (_a) {
  27759. var summary = _a.summary, metadata = _a.metadata;
  27760. toJsonSerializer.addSummary({ symbol: summary.type.reference, metadata: undefined, type: summary });
  27761. });
  27762. var _a = toJsonSerializer.serialize(createExternalSymbolReexports), json = _a.json, exportAs = _a.exportAs;
  27763. if (forJitCtx) {
  27764. var forJitSerializer_1 = new ForJitSerializer(forJitCtx, symbolResolver, summaryResolver);
  27765. types.forEach(function (_a) {
  27766. var summary = _a.summary, metadata = _a.metadata;
  27767. forJitSerializer_1.addSourceType(summary, metadata);
  27768. });
  27769. toJsonSerializer.unprocessedSymbolSummariesBySymbol.forEach(function (summary) {
  27770. if (summaryResolver.isLibraryFile(summary.symbol.filePath) && summary.type) {
  27771. forJitSerializer_1.addLibType(summary.type);
  27772. }
  27773. });
  27774. forJitSerializer_1.serialize(exportAs);
  27775. }
  27776. return { json: json, exportAs: exportAs };
  27777. }
  27778. function deserializeSummaries(symbolCache, summaryResolver, libraryFileName, json) {
  27779. var deserializer = new FromJsonDeserializer(symbolCache, summaryResolver);
  27780. return deserializer.deserialize(libraryFileName, json);
  27781. }
  27782. function createForJitStub(outputCtx, reference) {
  27783. return createSummaryForJitFunction(outputCtx, reference, NULL_EXPR);
  27784. }
  27785. function createSummaryForJitFunction(outputCtx, reference, value) {
  27786. var fnName = summaryForJitName(reference.name);
  27787. outputCtx.statements.push(fn([], [new ReturnStatement(value)], new ArrayType(DYNAMIC_TYPE)).toDeclStmt(fnName, [
  27788. exports.StmtModifier.Final, exports.StmtModifier.Exported
  27789. ]));
  27790. }
  27791. var ToJsonSerializer = /** @class */ (function (_super) {
  27792. __extends(ToJsonSerializer, _super);
  27793. function ToJsonSerializer(symbolResolver, summaryResolver, srcFileName) {
  27794. var _this = _super.call(this) || this;
  27795. _this.symbolResolver = symbolResolver;
  27796. _this.summaryResolver = summaryResolver;
  27797. _this.srcFileName = srcFileName;
  27798. // Note: This only contains symbols without members.
  27799. _this.symbols = [];
  27800. _this.indexBySymbol = new Map();
  27801. _this.reexportedBy = new Map();
  27802. // This now contains a `__symbol: number` in the place of
  27803. // StaticSymbols, but otherwise has the same shape as the original objects.
  27804. _this.processedSummaryBySymbol = new Map();
  27805. _this.processedSummaries = [];
  27806. _this.unprocessedSymbolSummariesBySymbol = new Map();
  27807. _this.moduleName = symbolResolver.getKnownModuleName(srcFileName);
  27808. return _this;
  27809. }
  27810. ToJsonSerializer.prototype.addSummary = function (summary) {
  27811. var _this = this;
  27812. var unprocessedSummary = this.unprocessedSymbolSummariesBySymbol.get(summary.symbol);
  27813. var processedSummary = this.processedSummaryBySymbol.get(summary.symbol);
  27814. if (!unprocessedSummary) {
  27815. unprocessedSummary = { symbol: summary.symbol, metadata: undefined };
  27816. this.unprocessedSymbolSummariesBySymbol.set(summary.symbol, unprocessedSummary);
  27817. processedSummary = { symbol: this.processValue(summary.symbol, 0 /* None */) };
  27818. this.processedSummaries.push(processedSummary);
  27819. this.processedSummaryBySymbol.set(summary.symbol, processedSummary);
  27820. }
  27821. if (!unprocessedSummary.metadata && summary.metadata) {
  27822. var metadata_1 = summary.metadata || {};
  27823. if (metadata_1.__symbolic === 'class') {
  27824. // For classes, we keep everything except their class decorators.
  27825. // We need to keep e.g. the ctor args, method names, method decorators
  27826. // so that the class can be extended in another compilation unit.
  27827. // We don't keep the class decorators as
  27828. // 1) they refer to data
  27829. // that should not cause a rebuild of downstream compilation units
  27830. // (e.g. inline templates of @Component, or @NgModule.declarations)
  27831. // 2) their data is already captured in TypeSummaries, e.g. DirectiveSummary.
  27832. var clone_1 = {};
  27833. Object.keys(metadata_1).forEach(function (propName) {
  27834. if (propName !== 'decorators') {
  27835. clone_1[propName] = metadata_1[propName];
  27836. }
  27837. });
  27838. metadata_1 = clone_1;
  27839. }
  27840. else if (isCall(metadata_1)) {
  27841. if (!isFunctionCall(metadata_1) && !isMethodCallOnVariable(metadata_1)) {
  27842. // Don't store complex calls as we won't be able to simplify them anyways later on.
  27843. metadata_1 = {
  27844. __symbolic: 'error',
  27845. message: 'Complex function calls are not supported.',
  27846. };
  27847. }
  27848. }
  27849. // Note: We need to keep storing ctor calls for e.g.
  27850. // `export const x = new InjectionToken(...)`
  27851. unprocessedSummary.metadata = metadata_1;
  27852. processedSummary.metadata = this.processValue(metadata_1, 1 /* ResolveValue */);
  27853. if (metadata_1 instanceof StaticSymbol &&
  27854. this.summaryResolver.isLibraryFile(metadata_1.filePath)) {
  27855. var declarationSymbol = this.symbols[this.indexBySymbol.get(metadata_1)];
  27856. if (!isLoweredSymbol(declarationSymbol.name)) {
  27857. // Note: symbols that were introduced during codegen in the user file can have a reexport
  27858. // if a user used `export *`. However, we can't rely on this as tsickle will change
  27859. // `export *` into named exports, using only the information from the typechecker.
  27860. // As we introduce the new symbols after typecheck, Tsickle does not know about them,
  27861. // and omits them when expanding `export *`.
  27862. // So we have to keep reexporting these symbols manually via .ngfactory files.
  27863. this.reexportedBy.set(declarationSymbol, summary.symbol);
  27864. }
  27865. }
  27866. }
  27867. if (!unprocessedSummary.type && summary.type) {
  27868. unprocessedSummary.type = summary.type;
  27869. // Note: We don't add the summaries of all referenced symbols as for the ResolvedSymbols,
  27870. // as the type summaries already contain the transitive data that they require
  27871. // (in a minimal way).
  27872. processedSummary.type = this.processValue(summary.type, 0 /* None */);
  27873. // except for reexported directives / pipes, so we need to store
  27874. // their summaries explicitly.
  27875. if (summary.type.summaryKind === exports.CompileSummaryKind.NgModule) {
  27876. var ngModuleSummary = summary.type;
  27877. ngModuleSummary.exportedDirectives.concat(ngModuleSummary.exportedPipes).forEach(function (id) {
  27878. var symbol = id.reference;
  27879. if (_this.summaryResolver.isLibraryFile(symbol.filePath) &&
  27880. !_this.unprocessedSymbolSummariesBySymbol.has(symbol)) {
  27881. var summary_1 = _this.summaryResolver.resolveSummary(symbol);
  27882. if (summary_1) {
  27883. _this.addSummary(summary_1);
  27884. }
  27885. }
  27886. });
  27887. }
  27888. }
  27889. };
  27890. /**
  27891. * @param createExternalSymbolReexports Whether external static symbols should be re-exported.
  27892. * This can be enabled if external symbols should be re-exported by the current module in
  27893. * order to avoid dynamically generated module dependencies which can break strict dependency
  27894. * enforcements (as in Google3). Read more here: https://github.com/angular/angular/issues/25644
  27895. */
  27896. ToJsonSerializer.prototype.serialize = function (createExternalSymbolReexports) {
  27897. var _this = this;
  27898. var exportAs = [];
  27899. var json = JSON.stringify({
  27900. moduleName: this.moduleName,
  27901. summaries: this.processedSummaries,
  27902. symbols: this.symbols.map(function (symbol, index) {
  27903. symbol.assertNoMembers();
  27904. var importAs = undefined;
  27905. if (_this.summaryResolver.isLibraryFile(symbol.filePath)) {
  27906. var reexportSymbol = _this.reexportedBy.get(symbol);
  27907. if (reexportSymbol) {
  27908. // In case the given external static symbol is already manually exported by the
  27909. // user, we just proxy the external static symbol reference to the manual export.
  27910. // This ensures that the AOT compiler imports the external symbol through the
  27911. // user export and does not introduce another dependency which is not needed.
  27912. importAs = _this.indexBySymbol.get(reexportSymbol);
  27913. }
  27914. else if (createExternalSymbolReexports) {
  27915. // In this case, the given external static symbol is *not* manually exported by
  27916. // the user, and we manually create a re-export in the factory file so that we
  27917. // don't introduce another module dependency. This is useful when running within
  27918. // Bazel so that the AOT compiler does not introduce any module dependencies
  27919. // which can break the strict dependency enforcement. (e.g. as in Google3)
  27920. // Read more about this here: https://github.com/angular/angular/issues/25644
  27921. var summary = _this.unprocessedSymbolSummariesBySymbol.get(symbol);
  27922. if (!summary || !summary.metadata || summary.metadata.__symbolic !== 'interface') {
  27923. importAs = symbol.name + "_" + index;
  27924. exportAs.push({ symbol: symbol, exportAs: importAs });
  27925. }
  27926. }
  27927. }
  27928. return {
  27929. __symbol: index,
  27930. name: symbol.name,
  27931. filePath: _this.summaryResolver.toSummaryFileName(symbol.filePath, _this.srcFileName),
  27932. importAs: importAs
  27933. };
  27934. })
  27935. });
  27936. return { json: json, exportAs: exportAs };
  27937. };
  27938. ToJsonSerializer.prototype.processValue = function (value, flags) {
  27939. return visitValue(value, this, flags);
  27940. };
  27941. ToJsonSerializer.prototype.visitOther = function (value, context) {
  27942. if (value instanceof StaticSymbol) {
  27943. var baseSymbol = this.symbolResolver.getStaticSymbol(value.filePath, value.name);
  27944. var index = this.visitStaticSymbol(baseSymbol, context);
  27945. return { __symbol: index, members: value.members };
  27946. }
  27947. };
  27948. /**
  27949. * Strip line and character numbers from ngsummaries.
  27950. * Emitting them causes white spaces changes to retrigger upstream
  27951. * recompilations in bazel.
  27952. * TODO: find out a way to have line and character numbers in errors without
  27953. * excessive recompilation in bazel.
  27954. */
  27955. ToJsonSerializer.prototype.visitStringMap = function (map, context) {
  27956. if (map['__symbolic'] === 'resolved') {
  27957. return visitValue(map['symbol'], this, context);
  27958. }
  27959. if (map['__symbolic'] === 'error') {
  27960. delete map['line'];
  27961. delete map['character'];
  27962. }
  27963. return _super.prototype.visitStringMap.call(this, map, context);
  27964. };
  27965. /**
  27966. * Returns null if the options.resolveValue is true, and the summary for the symbol
  27967. * resolved to a type or could not be resolved.
  27968. */
  27969. ToJsonSerializer.prototype.visitStaticSymbol = function (baseSymbol, flags) {
  27970. var index = this.indexBySymbol.get(baseSymbol);
  27971. var summary = null;
  27972. if (flags & 1 /* ResolveValue */ &&
  27973. this.summaryResolver.isLibraryFile(baseSymbol.filePath)) {
  27974. if (this.unprocessedSymbolSummariesBySymbol.has(baseSymbol)) {
  27975. // the summary for this symbol was already added
  27976. // -> nothing to do.
  27977. return index;
  27978. }
  27979. summary = this.loadSummary(baseSymbol);
  27980. if (summary && summary.metadata instanceof StaticSymbol) {
  27981. // The summary is a reexport
  27982. index = this.visitStaticSymbol(summary.metadata, flags);
  27983. // reset the summary as it is just a reexport, so we don't want to store it.
  27984. summary = null;
  27985. }
  27986. }
  27987. else if (index != null) {
  27988. // Note: == on purpose to compare with undefined!
  27989. // No summary and the symbol is already added -> nothing to do.
  27990. return index;
  27991. }
  27992. // Note: == on purpose to compare with undefined!
  27993. if (index == null) {
  27994. index = this.symbols.length;
  27995. this.symbols.push(baseSymbol);
  27996. }
  27997. this.indexBySymbol.set(baseSymbol, index);
  27998. if (summary) {
  27999. this.addSummary(summary);
  28000. }
  28001. return index;
  28002. };
  28003. ToJsonSerializer.prototype.loadSummary = function (symbol) {
  28004. var summary = this.summaryResolver.resolveSummary(symbol);
  28005. if (!summary) {
  28006. // some symbols might originate from a plain typescript library
  28007. // that just exported .d.ts and .metadata.json files, i.e. where no summary
  28008. // files were created.
  28009. var resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
  28010. if (resolvedSymbol) {
  28011. summary = { symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata };
  28012. }
  28013. }
  28014. return summary;
  28015. };
  28016. return ToJsonSerializer;
  28017. }(ValueTransformer));
  28018. var ForJitSerializer = /** @class */ (function () {
  28019. function ForJitSerializer(outputCtx, symbolResolver, summaryResolver) {
  28020. this.outputCtx = outputCtx;
  28021. this.symbolResolver = symbolResolver;
  28022. this.summaryResolver = summaryResolver;
  28023. this.data = [];
  28024. }
  28025. ForJitSerializer.prototype.addSourceType = function (summary, metadata) {
  28026. this.data.push({ summary: summary, metadata: metadata, isLibrary: false });
  28027. };
  28028. ForJitSerializer.prototype.addLibType = function (summary) {
  28029. this.data.push({ summary: summary, metadata: null, isLibrary: true });
  28030. };
  28031. ForJitSerializer.prototype.serialize = function (exportAsArr) {
  28032. var e_1, _a, e_2, _b, e_3, _c;
  28033. var _this = this;
  28034. var exportAsBySymbol = new Map();
  28035. try {
  28036. for (var exportAsArr_1 = __values(exportAsArr), exportAsArr_1_1 = exportAsArr_1.next(); !exportAsArr_1_1.done; exportAsArr_1_1 = exportAsArr_1.next()) {
  28037. var _d = exportAsArr_1_1.value, symbol = _d.symbol, exportAs = _d.exportAs;
  28038. exportAsBySymbol.set(symbol, exportAs);
  28039. }
  28040. }
  28041. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  28042. finally {
  28043. try {
  28044. if (exportAsArr_1_1 && !exportAsArr_1_1.done && (_a = exportAsArr_1.return)) _a.call(exportAsArr_1);
  28045. }
  28046. finally { if (e_1) throw e_1.error; }
  28047. }
  28048. var ngModuleSymbols = new Set();
  28049. try {
  28050. for (var _e = __values(this.data), _f = _e.next(); !_f.done; _f = _e.next()) {
  28051. var _g = _f.value, summary = _g.summary, metadata = _g.metadata, isLibrary = _g.isLibrary;
  28052. if (summary.summaryKind === exports.CompileSummaryKind.NgModule) {
  28053. // collect the symbols that refer to NgModule classes.
  28054. // Note: we can't just rely on `summary.type.summaryKind` to determine this as
  28055. // we don't add the summaries of all referenced symbols when we serialize type summaries.
  28056. // See serializeSummaries for details.
  28057. ngModuleSymbols.add(summary.type.reference);
  28058. var modSummary = summary;
  28059. try {
  28060. for (var _h = (e_3 = void 0, __values(modSummary.modules)), _j = _h.next(); !_j.done; _j = _h.next()) {
  28061. var mod = _j.value;
  28062. ngModuleSymbols.add(mod.reference);
  28063. }
  28064. }
  28065. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  28066. finally {
  28067. try {
  28068. if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
  28069. }
  28070. finally { if (e_3) throw e_3.error; }
  28071. }
  28072. }
  28073. if (!isLibrary) {
  28074. var fnName = summaryForJitName(summary.type.reference.name);
  28075. createSummaryForJitFunction(this.outputCtx, summary.type.reference, this.serializeSummaryWithDeps(summary, metadata));
  28076. }
  28077. }
  28078. }
  28079. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  28080. finally {
  28081. try {
  28082. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  28083. }
  28084. finally { if (e_2) throw e_2.error; }
  28085. }
  28086. ngModuleSymbols.forEach(function (ngModuleSymbol) {
  28087. if (_this.summaryResolver.isLibraryFile(ngModuleSymbol.filePath)) {
  28088. var exportAs = exportAsBySymbol.get(ngModuleSymbol) || ngModuleSymbol.name;
  28089. var jitExportAsName = summaryForJitName(exportAs);
  28090. _this.outputCtx.statements.push(variable(jitExportAsName)
  28091. .set(_this.serializeSummaryRef(ngModuleSymbol))
  28092. .toDeclStmt(null, [exports.StmtModifier.Exported]));
  28093. }
  28094. });
  28095. };
  28096. ForJitSerializer.prototype.serializeSummaryWithDeps = function (summary, metadata) {
  28097. var _this = this;
  28098. var expressions = [this.serializeSummary(summary)];
  28099. var providers = [];
  28100. if (metadata instanceof CompileNgModuleMetadata) {
  28101. expressions.push.apply(expressions, __spreadArray([], __read(
  28102. // For directives / pipes, we only add the declared ones,
  28103. // and rely on transitively importing NgModules to get the transitive
  28104. // summaries.
  28105. metadata.declaredDirectives.concat(metadata.declaredPipes)
  28106. .map(function (type) { return type.reference; })
  28107. // For modules,
  28108. // we also add the summaries for modules
  28109. // from libraries.
  28110. // This is ok as we produce reexports for all transitive modules.
  28111. .concat(metadata.transitiveModule.modules.map(function (type) { return type.reference; })
  28112. .filter(function (ref) { return ref !== metadata.type.reference; }))
  28113. .map(function (ref) { return _this.serializeSummaryRef(ref); }))));
  28114. // Note: We don't use `NgModuleSummary.providers`, as that one is transitive,
  28115. // and we already have transitive modules.
  28116. providers = metadata.providers;
  28117. }
  28118. else if (summary.summaryKind === exports.CompileSummaryKind.Directive) {
  28119. var dirSummary = summary;
  28120. providers = dirSummary.providers.concat(dirSummary.viewProviders);
  28121. }
  28122. // Note: We can't just refer to the `ngsummary.ts` files for `useClass` providers (as we do for
  28123. // declaredDirectives / declaredPipes), as we allow
  28124. // providers without ctor arguments to skip the `@Injectable` decorator,
  28125. // i.e. we didn't generate .ngsummary.ts files for these.
  28126. expressions.push.apply(expressions, __spreadArray([], __read(providers.filter(function (provider) { return !!provider.useClass; }).map(function (provider) { return _this.serializeSummary({
  28127. summaryKind: exports.CompileSummaryKind.Injectable,
  28128. type: provider.useClass
  28129. }); }))));
  28130. return literalArr(expressions);
  28131. };
  28132. ForJitSerializer.prototype.serializeSummaryRef = function (typeSymbol) {
  28133. var jitImportedSymbol = this.symbolResolver.getStaticSymbol(summaryForJitFileName(typeSymbol.filePath), summaryForJitName(typeSymbol.name));
  28134. return this.outputCtx.importExpr(jitImportedSymbol);
  28135. };
  28136. ForJitSerializer.prototype.serializeSummary = function (data) {
  28137. var outputCtx = this.outputCtx;
  28138. var Transformer = /** @class */ (function () {
  28139. function Transformer() {
  28140. }
  28141. Transformer.prototype.visitArray = function (arr, context) {
  28142. var _this = this;
  28143. return literalArr(arr.map(function (entry) { return visitValue(entry, _this, context); }));
  28144. };
  28145. Transformer.prototype.visitStringMap = function (map, context) {
  28146. var _this = this;
  28147. return new LiteralMapExpr(Object.keys(map).map(function (key) { return new LiteralMapEntry(key, visitValue(map[key], _this, context), false); }));
  28148. };
  28149. Transformer.prototype.visitPrimitive = function (value, context) {
  28150. return literal(value);
  28151. };
  28152. Transformer.prototype.visitOther = function (value, context) {
  28153. if (value instanceof StaticSymbol) {
  28154. return outputCtx.importExpr(value);
  28155. }
  28156. else {
  28157. throw new Error("Illegal State: Encountered value " + value);
  28158. }
  28159. };
  28160. return Transformer;
  28161. }());
  28162. return visitValue(data, new Transformer(), null);
  28163. };
  28164. return ForJitSerializer;
  28165. }());
  28166. var FromJsonDeserializer = /** @class */ (function (_super) {
  28167. __extends(FromJsonDeserializer, _super);
  28168. function FromJsonDeserializer(symbolCache, summaryResolver) {
  28169. var _this = _super.call(this) || this;
  28170. _this.symbolCache = symbolCache;
  28171. _this.summaryResolver = summaryResolver;
  28172. return _this;
  28173. }
  28174. FromJsonDeserializer.prototype.deserialize = function (libraryFileName, json) {
  28175. var _this = this;
  28176. var data = JSON.parse(json);
  28177. var allImportAs = [];
  28178. this.symbols = data.symbols.map(function (serializedSymbol) { return _this.symbolCache.get(_this.summaryResolver.fromSummaryFileName(serializedSymbol.filePath, libraryFileName), serializedSymbol.name); });
  28179. data.symbols.forEach(function (serializedSymbol, index) {
  28180. var symbol = _this.symbols[index];
  28181. var importAs = serializedSymbol.importAs;
  28182. if (typeof importAs === 'number') {
  28183. allImportAs.push({ symbol: symbol, importAs: _this.symbols[importAs] });
  28184. }
  28185. else if (typeof importAs === 'string') {
  28186. allImportAs.push({ symbol: symbol, importAs: _this.symbolCache.get(ngfactoryFilePath(libraryFileName), importAs) });
  28187. }
  28188. });
  28189. var summaries = visitValue(data.summaries, this, null);
  28190. return { moduleName: data.moduleName, summaries: summaries, importAs: allImportAs };
  28191. };
  28192. FromJsonDeserializer.prototype.visitStringMap = function (map, context) {
  28193. if ('__symbol' in map) {
  28194. var baseSymbol = this.symbols[map['__symbol']];
  28195. var members = map['members'];
  28196. return members.length ? this.symbolCache.get(baseSymbol.filePath, baseSymbol.name, members) :
  28197. baseSymbol;
  28198. }
  28199. else {
  28200. return _super.prototype.visitStringMap.call(this, map, context);
  28201. }
  28202. };
  28203. return FromJsonDeserializer;
  28204. }(ValueTransformer));
  28205. function isCall(metadata) {
  28206. return metadata && metadata.__symbolic === 'call';
  28207. }
  28208. function isFunctionCall(metadata) {
  28209. return isCall(metadata) && unwrapResolvedMetadata(metadata.expression) instanceof StaticSymbol;
  28210. }
  28211. function isMethodCallOnVariable(metadata) {
  28212. return isCall(metadata) && metadata.expression && metadata.expression.__symbolic === 'select' &&
  28213. unwrapResolvedMetadata(metadata.expression.expression) instanceof StaticSymbol;
  28214. }
  28215. var AotCompiler = /** @class */ (function () {
  28216. function AotCompiler(_config, _options, _host, reflector, _metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _typeCheckCompiler, _ngModuleCompiler, _injectableCompiler, _outputEmitter, _summaryResolver, _symbolResolver) {
  28217. this._config = _config;
  28218. this._options = _options;
  28219. this._host = _host;
  28220. this.reflector = reflector;
  28221. this._metadataResolver = _metadataResolver;
  28222. this._templateParser = _templateParser;
  28223. this._styleCompiler = _styleCompiler;
  28224. this._viewCompiler = _viewCompiler;
  28225. this._typeCheckCompiler = _typeCheckCompiler;
  28226. this._ngModuleCompiler = _ngModuleCompiler;
  28227. this._injectableCompiler = _injectableCompiler;
  28228. this._outputEmitter = _outputEmitter;
  28229. this._summaryResolver = _summaryResolver;
  28230. this._symbolResolver = _symbolResolver;
  28231. this._templateAstCache = new Map();
  28232. this._analyzedFiles = new Map();
  28233. this._analyzedFilesForInjectables = new Map();
  28234. }
  28235. AotCompiler.prototype.clearCache = function () {
  28236. this._metadataResolver.clearCache();
  28237. };
  28238. AotCompiler.prototype.analyzeModulesSync = function (rootFiles) {
  28239. var _this = this;
  28240. var analyzeResult = analyzeAndValidateNgModules(rootFiles, this._host, this._symbolResolver, this._metadataResolver);
  28241. analyzeResult.ngModules.forEach(function (ngModule) { return _this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, true); });
  28242. return analyzeResult;
  28243. };
  28244. AotCompiler.prototype.analyzeModulesAsync = function (rootFiles) {
  28245. var _this = this;
  28246. var analyzeResult = analyzeAndValidateNgModules(rootFiles, this._host, this._symbolResolver, this._metadataResolver);
  28247. return Promise
  28248. .all(analyzeResult.ngModules.map(function (ngModule) { return _this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false); }))
  28249. .then(function () { return analyzeResult; });
  28250. };
  28251. AotCompiler.prototype._analyzeFile = function (fileName) {
  28252. var analyzedFile = this._analyzedFiles.get(fileName);
  28253. if (!analyzedFile) {
  28254. analyzedFile =
  28255. analyzeFile(this._host, this._symbolResolver, this._metadataResolver, fileName);
  28256. this._analyzedFiles.set(fileName, analyzedFile);
  28257. }
  28258. return analyzedFile;
  28259. };
  28260. AotCompiler.prototype._analyzeFileForInjectables = function (fileName) {
  28261. var analyzedFile = this._analyzedFilesForInjectables.get(fileName);
  28262. if (!analyzedFile) {
  28263. analyzedFile = analyzeFileForInjectables(this._host, this._symbolResolver, this._metadataResolver, fileName);
  28264. this._analyzedFilesForInjectables.set(fileName, analyzedFile);
  28265. }
  28266. return analyzedFile;
  28267. };
  28268. AotCompiler.prototype.findGeneratedFileNames = function (fileName) {
  28269. var _this = this;
  28270. var genFileNames = [];
  28271. var file = this._analyzeFile(fileName);
  28272. // Make sure we create a .ngfactory if we have a injectable/directive/pipe/NgModule
  28273. // or a reference to a non source file.
  28274. // Note: This is overestimating the required .ngfactory files as the real calculation is harder.
  28275. // Only do this for StubEmitFlags.Basic, as adding a type check block
  28276. // does not change this file (as we generate type check blocks based on NgModules).
  28277. if (this._options.allowEmptyCodegenFiles || file.directives.length || file.pipes.length ||
  28278. file.injectables.length || file.ngModules.length || file.exportsNonSourceFiles) {
  28279. genFileNames.push(ngfactoryFilePath(file.fileName, true));
  28280. if (this._options.enableSummariesForJit) {
  28281. genFileNames.push(summaryForJitFileName(file.fileName, true));
  28282. }
  28283. }
  28284. var fileSuffix = normalizeGenFileSuffix(splitTypescriptSuffix(file.fileName, true)[1]);
  28285. file.directives.forEach(function (dirSymbol) {
  28286. var compMeta = _this._metadataResolver.getNonNormalizedDirectiveMetadata(dirSymbol).metadata;
  28287. if (!compMeta.isComponent) {
  28288. return;
  28289. }
  28290. // Note: compMeta is a component and therefore template is non null.
  28291. compMeta.template.styleUrls.forEach(function (styleUrl) {
  28292. var normalizedUrl = _this._host.resourceNameToFileName(styleUrl, file.fileName);
  28293. if (!normalizedUrl) {
  28294. throw syntaxError("Couldn't resolve resource " + styleUrl + " relative to " + file.fileName);
  28295. }
  28296. var needsShim = (compMeta.template.encapsulation ||
  28297. _this._config.defaultEncapsulation) === ViewEncapsulation.Emulated;
  28298. genFileNames.push(_stylesModuleUrl(normalizedUrl, needsShim, fileSuffix));
  28299. if (_this._options.allowEmptyCodegenFiles) {
  28300. genFileNames.push(_stylesModuleUrl(normalizedUrl, !needsShim, fileSuffix));
  28301. }
  28302. });
  28303. });
  28304. return genFileNames;
  28305. };
  28306. AotCompiler.prototype.emitBasicStub = function (genFileName, originalFileName) {
  28307. var outputCtx = this._createOutputContext(genFileName);
  28308. if (genFileName.endsWith('.ngfactory.ts')) {
  28309. if (!originalFileName) {
  28310. throw new Error("Assertion error: require the original file for .ngfactory.ts stubs. File: " + genFileName);
  28311. }
  28312. var originalFile = this._analyzeFile(originalFileName);
  28313. this._createNgFactoryStub(outputCtx, originalFile, 1 /* Basic */);
  28314. }
  28315. else if (genFileName.endsWith('.ngsummary.ts')) {
  28316. if (this._options.enableSummariesForJit) {
  28317. if (!originalFileName) {
  28318. throw new Error("Assertion error: require the original file for .ngsummary.ts stubs. File: " + genFileName);
  28319. }
  28320. var originalFile = this._analyzeFile(originalFileName);
  28321. _createEmptyStub(outputCtx);
  28322. originalFile.ngModules.forEach(function (ngModule) {
  28323. // create exports that user code can reference
  28324. createForJitStub(outputCtx, ngModule.type.reference);
  28325. });
  28326. }
  28327. }
  28328. else if (genFileName.endsWith('.ngstyle.ts')) {
  28329. _createEmptyStub(outputCtx);
  28330. }
  28331. // Note: for the stubs, we don't need a property srcFileUrl,
  28332. // as later on in emitAllImpls we will create the proper GeneratedFiles with the
  28333. // correct srcFileUrl.
  28334. // This is good as e.g. for .ngstyle.ts files we can't derive
  28335. // the url of components based on the genFileUrl.
  28336. return this._codegenSourceModule('unknown', outputCtx);
  28337. };
  28338. AotCompiler.prototype.emitTypeCheckStub = function (genFileName, originalFileName) {
  28339. var originalFile = this._analyzeFile(originalFileName);
  28340. var outputCtx = this._createOutputContext(genFileName);
  28341. if (genFileName.endsWith('.ngfactory.ts')) {
  28342. this._createNgFactoryStub(outputCtx, originalFile, 2 /* TypeCheck */);
  28343. }
  28344. return outputCtx.statements.length > 0 ?
  28345. this._codegenSourceModule(originalFile.fileName, outputCtx) :
  28346. null;
  28347. };
  28348. AotCompiler.prototype.loadFilesAsync = function (fileNames, tsFiles) {
  28349. var _this = this;
  28350. var files = fileNames.map(function (fileName) { return _this._analyzeFile(fileName); });
  28351. var loadingPromises = [];
  28352. files.forEach(function (file) { return file.ngModules.forEach(function (ngModule) { return loadingPromises.push(_this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false)); }); });
  28353. var analyzedInjectables = tsFiles.map(function (tsFile) { return _this._analyzeFileForInjectables(tsFile); });
  28354. return Promise.all(loadingPromises).then(function (_) { return ({
  28355. analyzedModules: mergeAndValidateNgFiles(files),
  28356. analyzedInjectables: analyzedInjectables,
  28357. }); });
  28358. };
  28359. AotCompiler.prototype.loadFilesSync = function (fileNames, tsFiles) {
  28360. var _this = this;
  28361. var files = fileNames.map(function (fileName) { return _this._analyzeFile(fileName); });
  28362. files.forEach(function (file) { return file.ngModules.forEach(function (ngModule) { return _this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, true); }); });
  28363. var analyzedInjectables = tsFiles.map(function (tsFile) { return _this._analyzeFileForInjectables(tsFile); });
  28364. return {
  28365. analyzedModules: mergeAndValidateNgFiles(files),
  28366. analyzedInjectables: analyzedInjectables,
  28367. };
  28368. };
  28369. AotCompiler.prototype._createNgFactoryStub = function (outputCtx, file, emitFlags) {
  28370. var _this = this;
  28371. var componentId = 0;
  28372. file.ngModules.forEach(function (ngModuleMeta, ngModuleIndex) {
  28373. // Note: the code below needs to executed for StubEmitFlags.Basic and StubEmitFlags.TypeCheck,
  28374. // so we don't change the .ngfactory file too much when adding the type-check block.
  28375. // create exports that user code can reference
  28376. _this._ngModuleCompiler.createStub(outputCtx, ngModuleMeta.type.reference);
  28377. // add references to the symbols from the metadata.
  28378. // These can be used by the type check block for components,
  28379. // and they also cause TypeScript to include these files into the program too,
  28380. // which will make them part of the analyzedFiles.
  28381. var externalReferences = __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(ngModuleMeta.transitiveModule.directives.map(function (d) { return d.reference; }))), __read(ngModuleMeta.transitiveModule.pipes.map(function (d) { return d.reference; }))), __read(ngModuleMeta.importedModules.map(function (m) { return m.type.reference; }))), __read(ngModuleMeta.exportedModules.map(function (m) { return m.type.reference; }))), __read(_this._externalIdentifierReferences([Identifiers$1.TemplateRef, Identifiers$1.ElementRef])));
  28382. var externalReferenceVars = new Map();
  28383. externalReferences.forEach(function (ref, typeIndex) {
  28384. externalReferenceVars.set(ref, "_decl" + ngModuleIndex + "_" + typeIndex);
  28385. });
  28386. externalReferenceVars.forEach(function (varName, reference) {
  28387. outputCtx.statements.push(variable(varName)
  28388. .set(NULL_EXPR.cast(DYNAMIC_TYPE))
  28389. .toDeclStmt(expressionType(outputCtx.importExpr(reference, /* typeParams */ null, /* useSummaries */ false))));
  28390. });
  28391. if (emitFlags & 2 /* TypeCheck */) {
  28392. // add the type-check block for all components of the NgModule
  28393. ngModuleMeta.declaredDirectives.forEach(function (dirId) {
  28394. var compMeta = _this._metadataResolver.getDirectiveMetadata(dirId.reference);
  28395. if (!compMeta.isComponent) {
  28396. return;
  28397. }
  28398. componentId++;
  28399. _this._createTypeCheckBlock(outputCtx, compMeta.type.reference.name + "_Host_" + componentId, ngModuleMeta, _this._metadataResolver.getHostComponentMetadata(compMeta), [compMeta.type], externalReferenceVars);
  28400. _this._createTypeCheckBlock(outputCtx, compMeta.type.reference.name + "_" + componentId, ngModuleMeta, compMeta, ngModuleMeta.transitiveModule.directives, externalReferenceVars);
  28401. });
  28402. }
  28403. });
  28404. if (outputCtx.statements.length === 0) {
  28405. _createEmptyStub(outputCtx);
  28406. }
  28407. };
  28408. AotCompiler.prototype._externalIdentifierReferences = function (references) {
  28409. var e_1, _a;
  28410. var result = [];
  28411. try {
  28412. for (var references_1 = __values(references), references_1_1 = references_1.next(); !references_1_1.done; references_1_1 = references_1.next()) {
  28413. var reference = references_1_1.value;
  28414. var token = createTokenForExternalReference(this.reflector, reference);
  28415. if (token.identifier) {
  28416. result.push(token.identifier.reference);
  28417. }
  28418. }
  28419. }
  28420. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  28421. finally {
  28422. try {
  28423. if (references_1_1 && !references_1_1.done && (_a = references_1.return)) _a.call(references_1);
  28424. }
  28425. finally { if (e_1) throw e_1.error; }
  28426. }
  28427. return result;
  28428. };
  28429. AotCompiler.prototype._createTypeCheckBlock = function (ctx, componentId, moduleMeta, compMeta, directives, externalReferenceVars) {
  28430. var _a;
  28431. var _b = this._parseTemplate(compMeta, moduleMeta, directives), parsedTemplate = _b.template, usedPipes = _b.pipes;
  28432. (_a = ctx.statements).push.apply(_a, __spreadArray([], __read(this._typeCheckCompiler.compileComponent(componentId, compMeta, parsedTemplate, usedPipes, externalReferenceVars, ctx))));
  28433. };
  28434. AotCompiler.prototype.emitMessageBundle = function (analyzeResult, locale) {
  28435. var _this = this;
  28436. var errors = [];
  28437. var htmlParser = new HtmlParser();
  28438. // TODO(vicb): implicit tags & attributes
  28439. var messageBundle = new MessageBundle(htmlParser, [], {}, locale);
  28440. analyzeResult.files.forEach(function (file) {
  28441. var compMetas = [];
  28442. file.directives.forEach(function (directiveType) {
  28443. var dirMeta = _this._metadataResolver.getDirectiveMetadata(directiveType);
  28444. if (dirMeta && dirMeta.isComponent) {
  28445. compMetas.push(dirMeta);
  28446. }
  28447. });
  28448. compMetas.forEach(function (compMeta) {
  28449. var html = compMeta.template.template;
  28450. // Template URL points to either an HTML or TS file depending on whether
  28451. // the file is used with `templateUrl:` or `template:`, respectively.
  28452. var templateUrl = compMeta.template.templateUrl;
  28453. var interpolationConfig = InterpolationConfig.fromArray(compMeta.template.interpolation);
  28454. errors.push.apply(errors, __spreadArray([], __read(messageBundle.updateFromTemplate(html, templateUrl, interpolationConfig))));
  28455. });
  28456. });
  28457. if (errors.length) {
  28458. throw new Error(errors.map(function (e) { return e.toString(); }).join('\n'));
  28459. }
  28460. return messageBundle;
  28461. };
  28462. AotCompiler.prototype.emitAllPartialModules2 = function (files) {
  28463. var _this = this;
  28464. // Using reduce like this is a select many pattern (where map is a select pattern)
  28465. return files.reduce(function (r, file) {
  28466. r.push.apply(r, __spreadArray([], __read(_this._emitPartialModule2(file.fileName, file.injectables))));
  28467. return r;
  28468. }, []);
  28469. };
  28470. AotCompiler.prototype._emitPartialModule2 = function (fileName, injectables) {
  28471. var _this = this;
  28472. var context = this._createOutputContext(fileName);
  28473. injectables.forEach(function (injectable) { return _this._injectableCompiler.compile(injectable, context); });
  28474. if (context.statements && context.statements.length > 0) {
  28475. return [{ fileName: fileName, statements: __spreadArray(__spreadArray([], __read(context.constantPool.statements)), __read(context.statements)) }];
  28476. }
  28477. return [];
  28478. };
  28479. AotCompiler.prototype.emitAllImpls = function (analyzeResult) {
  28480. var _this = this;
  28481. var ngModuleByPipeOrDirective = analyzeResult.ngModuleByPipeOrDirective, files = analyzeResult.files;
  28482. var sourceModules = files.map(function (file) { return _this._compileImplFile(file.fileName, ngModuleByPipeOrDirective, file.directives, file.pipes, file.ngModules, file.injectables); });
  28483. return flatten(sourceModules);
  28484. };
  28485. AotCompiler.prototype._compileImplFile = function (srcFileUrl, ngModuleByPipeOrDirective, directives, pipes, ngModules, injectables) {
  28486. var _this = this;
  28487. var fileSuffix = normalizeGenFileSuffix(splitTypescriptSuffix(srcFileUrl, true)[1]);
  28488. var generatedFiles = [];
  28489. var outputCtx = this._createOutputContext(ngfactoryFilePath(srcFileUrl, true));
  28490. generatedFiles.push.apply(generatedFiles, __spreadArray([], __read(this._createSummary(srcFileUrl, directives, pipes, ngModules, injectables, outputCtx))));
  28491. // compile all ng modules
  28492. ngModules.forEach(function (ngModuleMeta) { return _this._compileModule(outputCtx, ngModuleMeta); });
  28493. // compile components
  28494. directives.forEach(function (dirType) {
  28495. var compMeta = _this._metadataResolver.getDirectiveMetadata(dirType);
  28496. if (!compMeta.isComponent) {
  28497. return;
  28498. }
  28499. var ngModule = ngModuleByPipeOrDirective.get(dirType);
  28500. if (!ngModule) {
  28501. throw new Error("Internal Error: cannot determine the module for component " + identifierName(compMeta.type) + "!");
  28502. }
  28503. // compile styles
  28504. var componentStylesheet = _this._styleCompiler.compileComponent(outputCtx, compMeta);
  28505. // Note: compMeta is a component and therefore template is non null.
  28506. compMeta.template.externalStylesheets.forEach(function (stylesheetMeta) {
  28507. // Note: fill non shim and shim style files as they might
  28508. // be shared by component with and without ViewEncapsulation.
  28509. var shim = _this._styleCompiler.needsStyleShim(compMeta);
  28510. generatedFiles.push(_this._codegenStyles(srcFileUrl, compMeta, stylesheetMeta, shim, fileSuffix));
  28511. if (_this._options.allowEmptyCodegenFiles) {
  28512. generatedFiles.push(_this._codegenStyles(srcFileUrl, compMeta, stylesheetMeta, !shim, fileSuffix));
  28513. }
  28514. });
  28515. // compile components
  28516. var compViewVars = _this._compileComponent(outputCtx, compMeta, ngModule, ngModule.transitiveModule.directives, componentStylesheet, fileSuffix);
  28517. _this._compileComponentFactory(outputCtx, compMeta, ngModule, fileSuffix);
  28518. });
  28519. if (outputCtx.statements.length > 0 || this._options.allowEmptyCodegenFiles) {
  28520. var srcModule = this._codegenSourceModule(srcFileUrl, outputCtx);
  28521. generatedFiles.unshift(srcModule);
  28522. }
  28523. return generatedFiles;
  28524. };
  28525. AotCompiler.prototype._createSummary = function (srcFileName, directives, pipes, ngModules, injectables, ngFactoryCtx) {
  28526. var _this = this;
  28527. var symbolSummaries = this._symbolResolver.getSymbolsOf(srcFileName)
  28528. .map(function (symbol) { return _this._symbolResolver.resolveSymbol(symbol); });
  28529. var typeData = __spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(ngModules.map(function (meta) { return ({
  28530. summary: _this._metadataResolver.getNgModuleSummary(meta.type.reference),
  28531. metadata: _this._metadataResolver.getNgModuleMetadata(meta.type.reference)
  28532. }); }))), __read(directives.map(function (ref) { return ({
  28533. summary: _this._metadataResolver.getDirectiveSummary(ref),
  28534. metadata: _this._metadataResolver.getDirectiveMetadata(ref)
  28535. }); }))), __read(pipes.map(function (ref) { return ({
  28536. summary: _this._metadataResolver.getPipeSummary(ref),
  28537. metadata: _this._metadataResolver.getPipeMetadata(ref)
  28538. }); }))), __read(injectables.map(function (ref) { return ({
  28539. summary: _this._metadataResolver.getInjectableSummary(ref.symbol),
  28540. metadata: _this._metadataResolver.getInjectableSummary(ref.symbol).type
  28541. }); })));
  28542. var forJitOutputCtx = this._options.enableSummariesForJit ?
  28543. this._createOutputContext(summaryForJitFileName(srcFileName, true)) :
  28544. null;
  28545. var _a = serializeSummaries(srcFileName, forJitOutputCtx, this._summaryResolver, this._symbolResolver, symbolSummaries, typeData, this._options.createExternalSymbolFactoryReexports), json = _a.json, exportAs = _a.exportAs;
  28546. exportAs.forEach(function (entry) {
  28547. ngFactoryCtx.statements.push(variable(entry.exportAs).set(ngFactoryCtx.importExpr(entry.symbol)).toDeclStmt(null, [
  28548. exports.StmtModifier.Exported
  28549. ]));
  28550. });
  28551. var summaryJson = new GeneratedFile(srcFileName, summaryFileName(srcFileName), json);
  28552. var result = [summaryJson];
  28553. if (forJitOutputCtx) {
  28554. result.push(this._codegenSourceModule(srcFileName, forJitOutputCtx));
  28555. }
  28556. return result;
  28557. };
  28558. AotCompiler.prototype._compileModule = function (outputCtx, ngModule) {
  28559. var providers = [];
  28560. if (this._options.locale) {
  28561. var normalizedLocale = this._options.locale.replace(/_/g, '-');
  28562. providers.push({
  28563. token: createTokenForExternalReference(this.reflector, Identifiers$1.LOCALE_ID),
  28564. useValue: normalizedLocale,
  28565. });
  28566. }
  28567. if (this._options.i18nFormat) {
  28568. providers.push({
  28569. token: createTokenForExternalReference(this.reflector, Identifiers$1.TRANSLATIONS_FORMAT),
  28570. useValue: this._options.i18nFormat
  28571. });
  28572. }
  28573. this._ngModuleCompiler.compile(outputCtx, ngModule, providers);
  28574. };
  28575. AotCompiler.prototype._compileComponentFactory = function (outputCtx, compMeta, ngModule, fileSuffix) {
  28576. var hostMeta = this._metadataResolver.getHostComponentMetadata(compMeta);
  28577. var hostViewFactoryVar = this._compileComponent(outputCtx, hostMeta, ngModule, [compMeta.type], null, fileSuffix)
  28578. .viewClassVar;
  28579. var compFactoryVar = componentFactoryName(compMeta.type.reference);
  28580. var inputsExprs = [];
  28581. for (var propName in compMeta.inputs) {
  28582. var templateName = compMeta.inputs[propName];
  28583. // Don't quote so that the key gets minified...
  28584. inputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
  28585. }
  28586. var outputsExprs = [];
  28587. for (var propName in compMeta.outputs) {
  28588. var templateName = compMeta.outputs[propName];
  28589. // Don't quote so that the key gets minified...
  28590. outputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
  28591. }
  28592. outputCtx.statements.push(variable(compFactoryVar)
  28593. .set(importExpr(Identifiers$1.createComponentFactory).callFn([
  28594. literal(compMeta.selector), outputCtx.importExpr(compMeta.type.reference),
  28595. variable(hostViewFactoryVar), new LiteralMapExpr(inputsExprs),
  28596. new LiteralMapExpr(outputsExprs),
  28597. literalArr(compMeta.template.ngContentSelectors.map(function (selector) { return literal(selector); }))
  28598. ]))
  28599. .toDeclStmt(importType(Identifiers$1.ComponentFactory, [expressionType(outputCtx.importExpr(compMeta.type.reference))], [TypeModifier.Const]), [exports.StmtModifier.Final, exports.StmtModifier.Exported]));
  28600. };
  28601. AotCompiler.prototype._compileComponent = function (outputCtx, compMeta, ngModule, directiveIdentifiers, componentStyles, fileSuffix) {
  28602. var _a = this._parseTemplate(compMeta, ngModule, directiveIdentifiers), parsedTemplate = _a.template, usedPipes = _a.pipes;
  28603. var stylesExpr = componentStyles ? variable(componentStyles.stylesVar) : literalArr([]);
  28604. var viewResult = this._viewCompiler.compileComponent(outputCtx, compMeta, parsedTemplate, stylesExpr, usedPipes);
  28605. if (componentStyles) {
  28606. _resolveStyleStatements(this._symbolResolver, componentStyles, this._styleCompiler.needsStyleShim(compMeta), fileSuffix);
  28607. }
  28608. return viewResult;
  28609. };
  28610. AotCompiler.prototype._parseTemplate = function (compMeta, ngModule, directiveIdentifiers) {
  28611. var _this = this;
  28612. if (this._templateAstCache.has(compMeta.type.reference)) {
  28613. return this._templateAstCache.get(compMeta.type.reference);
  28614. }
  28615. var preserveWhitespaces = compMeta.template.preserveWhitespaces;
  28616. var directives = directiveIdentifiers.map(function (dir) { return _this._metadataResolver.getDirectiveSummary(dir.reference); });
  28617. var pipes = ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
  28618. var result = this._templateParser.parse(compMeta, compMeta.template.htmlAst, directives, pipes, ngModule.schemas, templateSourceUrl(ngModule.type, compMeta, compMeta.template), preserveWhitespaces);
  28619. this._templateAstCache.set(compMeta.type.reference, result);
  28620. return result;
  28621. };
  28622. AotCompiler.prototype._createOutputContext = function (genFilePath) {
  28623. var _this = this;
  28624. var importExpr$1 = function (symbol, typeParams, useSummaries) {
  28625. if (typeParams === void 0) { typeParams = null; }
  28626. if (useSummaries === void 0) { useSummaries = true; }
  28627. if (!(symbol instanceof StaticSymbol)) {
  28628. throw new Error("Internal error: unknown identifier " + JSON.stringify(symbol));
  28629. }
  28630. var arity = _this._symbolResolver.getTypeArity(symbol) || 0;
  28631. var _a = _this._symbolResolver.getImportAs(symbol, useSummaries) || symbol, filePath = _a.filePath, name = _a.name, members = _a.members;
  28632. var importModule = _this._fileNameToModuleName(filePath, genFilePath);
  28633. // It should be good enough to compare filePath to genFilePath and if they are equal
  28634. // there is a self reference. However, ngfactory files generate to .ts but their
  28635. // symbols have .d.ts so a simple compare is insufficient. They should be canonical
  28636. // and is tracked by #17705.
  28637. var selfReference = _this._fileNameToModuleName(genFilePath, genFilePath);
  28638. var moduleName = importModule === selfReference ? null : importModule;
  28639. // If we are in a type expression that refers to a generic type then supply
  28640. // the required type parameters. If there were not enough type parameters
  28641. // supplied, supply any as the type. Outside a type expression the reference
  28642. // should not supply type parameters and be treated as a simple value reference
  28643. // to the constructor function itself.
  28644. var suppliedTypeParams = typeParams || [];
  28645. var missingTypeParamsCount = arity - suppliedTypeParams.length;
  28646. var allTypeParams = suppliedTypeParams.concat(newArray(missingTypeParamsCount, DYNAMIC_TYPE));
  28647. return members.reduce(function (expr, memberName) { return expr.prop(memberName); }, importExpr(new ExternalReference(moduleName, name, null), allTypeParams));
  28648. };
  28649. return { statements: [], genFilePath: genFilePath, importExpr: importExpr$1, constantPool: new ConstantPool() };
  28650. };
  28651. AotCompiler.prototype._fileNameToModuleName = function (importedFilePath, containingFilePath) {
  28652. return this._summaryResolver.getKnownModuleName(importedFilePath) ||
  28653. this._symbolResolver.getKnownModuleName(importedFilePath) ||
  28654. this._host.fileNameToModuleName(importedFilePath, containingFilePath);
  28655. };
  28656. AotCompiler.prototype._codegenStyles = function (srcFileUrl, compMeta, stylesheetMetadata, isShimmed, fileSuffix) {
  28657. var outputCtx = this._createOutputContext(_stylesModuleUrl(stylesheetMetadata.moduleUrl, isShimmed, fileSuffix));
  28658. var compiledStylesheet = this._styleCompiler.compileStyles(outputCtx, compMeta, stylesheetMetadata, isShimmed);
  28659. _resolveStyleStatements(this._symbolResolver, compiledStylesheet, isShimmed, fileSuffix);
  28660. return this._codegenSourceModule(srcFileUrl, outputCtx);
  28661. };
  28662. AotCompiler.prototype._codegenSourceModule = function (srcFileUrl, ctx) {
  28663. return new GeneratedFile(srcFileUrl, ctx.genFilePath, ctx.statements);
  28664. };
  28665. AotCompiler.prototype.listLazyRoutes = function (entryRoute, analyzedModules) {
  28666. var e_2, _a, e_3, _b;
  28667. var self = this;
  28668. if (entryRoute) {
  28669. var symbol = parseLazyRoute(entryRoute, this.reflector).referencedModule;
  28670. return visitLazyRoute(symbol);
  28671. }
  28672. else if (analyzedModules) {
  28673. var allLazyRoutes = [];
  28674. try {
  28675. for (var _c = __values(analyzedModules.ngModules), _d = _c.next(); !_d.done; _d = _c.next()) {
  28676. var ngModule = _d.value;
  28677. var lazyRoutes = listLazyRoutes(ngModule, this.reflector);
  28678. try {
  28679. for (var lazyRoutes_1 = (e_3 = void 0, __values(lazyRoutes)), lazyRoutes_1_1 = lazyRoutes_1.next(); !lazyRoutes_1_1.done; lazyRoutes_1_1 = lazyRoutes_1.next()) {
  28680. var lazyRoute = lazyRoutes_1_1.value;
  28681. allLazyRoutes.push(lazyRoute);
  28682. }
  28683. }
  28684. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  28685. finally {
  28686. try {
  28687. if (lazyRoutes_1_1 && !lazyRoutes_1_1.done && (_b = lazyRoutes_1.return)) _b.call(lazyRoutes_1);
  28688. }
  28689. finally { if (e_3) throw e_3.error; }
  28690. }
  28691. }
  28692. }
  28693. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  28694. finally {
  28695. try {
  28696. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  28697. }
  28698. finally { if (e_2) throw e_2.error; }
  28699. }
  28700. return allLazyRoutes;
  28701. }
  28702. else {
  28703. throw new Error("Either route or analyzedModules has to be specified!");
  28704. }
  28705. function visitLazyRoute(symbol, seenRoutes, allLazyRoutes) {
  28706. var e_4, _a;
  28707. if (seenRoutes === void 0) { seenRoutes = new Set(); }
  28708. if (allLazyRoutes === void 0) { allLazyRoutes = []; }
  28709. // Support pointing to default exports, but stop recursing there,
  28710. // as the StaticReflector does not yet support default exports.
  28711. if (seenRoutes.has(symbol) || !symbol.name) {
  28712. return allLazyRoutes;
  28713. }
  28714. seenRoutes.add(symbol);
  28715. var lazyRoutes = listLazyRoutes(self._metadataResolver.getNgModuleMetadata(symbol, true), self.reflector);
  28716. try {
  28717. for (var lazyRoutes_2 = __values(lazyRoutes), lazyRoutes_2_1 = lazyRoutes_2.next(); !lazyRoutes_2_1.done; lazyRoutes_2_1 = lazyRoutes_2.next()) {
  28718. var lazyRoute = lazyRoutes_2_1.value;
  28719. allLazyRoutes.push(lazyRoute);
  28720. visitLazyRoute(lazyRoute.referencedModule, seenRoutes, allLazyRoutes);
  28721. }
  28722. }
  28723. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  28724. finally {
  28725. try {
  28726. if (lazyRoutes_2_1 && !lazyRoutes_2_1.done && (_a = lazyRoutes_2.return)) _a.call(lazyRoutes_2);
  28727. }
  28728. finally { if (e_4) throw e_4.error; }
  28729. }
  28730. return allLazyRoutes;
  28731. }
  28732. };
  28733. return AotCompiler;
  28734. }());
  28735. function _createEmptyStub(outputCtx) {
  28736. // Note: We need to produce at least one import statement so that
  28737. // TypeScript knows that the file is an es6 module. Otherwise our generated
  28738. // exports / imports won't be emitted properly by TypeScript.
  28739. outputCtx.statements.push(importExpr(Identifiers$1.ComponentFactory).toStmt());
  28740. }
  28741. function _resolveStyleStatements(symbolResolver, compileResult, needsShim, fileSuffix) {
  28742. compileResult.dependencies.forEach(function (dep) {
  28743. dep.setValue(symbolResolver.getStaticSymbol(_stylesModuleUrl(dep.moduleUrl, needsShim, fileSuffix), dep.name));
  28744. });
  28745. }
  28746. function _stylesModuleUrl(stylesheetUrl, shim, suffix) {
  28747. return "" + stylesheetUrl + (shim ? '.shim' : '') + ".ngstyle" + suffix;
  28748. }
  28749. function analyzeNgModules(fileNames, host, staticSymbolResolver, metadataResolver) {
  28750. var files = _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver);
  28751. return mergeAnalyzedFiles(files);
  28752. }
  28753. function analyzeAndValidateNgModules(fileNames, host, staticSymbolResolver, metadataResolver) {
  28754. return validateAnalyzedModules(analyzeNgModules(fileNames, host, staticSymbolResolver, metadataResolver));
  28755. }
  28756. function validateAnalyzedModules(analyzedModules) {
  28757. if (analyzedModules.symbolsMissingModule && analyzedModules.symbolsMissingModule.length) {
  28758. var messages = analyzedModules.symbolsMissingModule.map(function (s) { return "Cannot determine the module for class " + s.name + " in " + s.filePath + "! Add " + s.name + " to the NgModule to fix it."; });
  28759. throw syntaxError(messages.join('\n'));
  28760. }
  28761. return analyzedModules;
  28762. }
  28763. // Analyzes all of the program files,
  28764. // including files that are not part of the program
  28765. // but are referenced by an NgModule.
  28766. function _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver) {
  28767. var seenFiles = new Set();
  28768. var files = [];
  28769. var visitFile = function (fileName) {
  28770. if (seenFiles.has(fileName) || !host.isSourceFile(fileName)) {
  28771. return false;
  28772. }
  28773. seenFiles.add(fileName);
  28774. var analyzedFile = analyzeFile(host, staticSymbolResolver, metadataResolver, fileName);
  28775. files.push(analyzedFile);
  28776. analyzedFile.ngModules.forEach(function (ngModule) {
  28777. ngModule.transitiveModule.modules.forEach(function (modMeta) { return visitFile(modMeta.reference.filePath); });
  28778. });
  28779. };
  28780. fileNames.forEach(function (fileName) { return visitFile(fileName); });
  28781. return files;
  28782. }
  28783. function analyzeFile(host, staticSymbolResolver, metadataResolver, fileName) {
  28784. var abstractDirectives = [];
  28785. var directives = [];
  28786. var pipes = [];
  28787. var injectables = [];
  28788. var ngModules = [];
  28789. var hasDecorators = staticSymbolResolver.hasDecorators(fileName);
  28790. var exportsNonSourceFiles = false;
  28791. var isDeclarationFile = fileName.endsWith('.d.ts');
  28792. // Don't analyze .d.ts files that have no decorators as a shortcut
  28793. // to speed up the analysis. This prevents us from
  28794. // resolving the references in these files.
  28795. // Note: exportsNonSourceFiles is only needed when compiling with summaries,
  28796. // which is not the case when .d.ts files are treated as input files.
  28797. if (!isDeclarationFile || hasDecorators) {
  28798. staticSymbolResolver.getSymbolsOf(fileName).forEach(function (symbol) {
  28799. var resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
  28800. var symbolMeta = resolvedSymbol.metadata;
  28801. if (!symbolMeta || symbolMeta.__symbolic === 'error') {
  28802. return;
  28803. }
  28804. var isNgSymbol = false;
  28805. if (symbolMeta.__symbolic === 'class') {
  28806. if (metadataResolver.isDirective(symbol)) {
  28807. isNgSymbol = true;
  28808. // This directive either has a selector or doesn't. Selector-less directives get tracked
  28809. // in abstractDirectives, not directives. The compiler doesn't deal with selector-less
  28810. // directives at all, really, other than to persist their metadata. This is done so that
  28811. // apps will have an easier time migrating to Ivy, which requires the selector-less
  28812. // annotations to be applied.
  28813. if (!metadataResolver.isAbstractDirective(symbol)) {
  28814. // The directive is an ordinary directive.
  28815. directives.push(symbol);
  28816. }
  28817. else {
  28818. // The directive has no selector and is an "abstract" directive, so track it
  28819. // accordingly.
  28820. abstractDirectives.push(symbol);
  28821. }
  28822. }
  28823. else if (metadataResolver.isPipe(symbol)) {
  28824. isNgSymbol = true;
  28825. pipes.push(symbol);
  28826. }
  28827. else if (metadataResolver.isNgModule(symbol)) {
  28828. var ngModule = metadataResolver.getNgModuleMetadata(symbol, false);
  28829. if (ngModule) {
  28830. isNgSymbol = true;
  28831. ngModules.push(ngModule);
  28832. }
  28833. }
  28834. else if (metadataResolver.isInjectable(symbol)) {
  28835. isNgSymbol = true;
  28836. var injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
  28837. if (injectable) {
  28838. injectables.push(injectable);
  28839. }
  28840. }
  28841. }
  28842. if (!isNgSymbol) {
  28843. exportsNonSourceFiles =
  28844. exportsNonSourceFiles || isValueExportingNonSourceFile(host, symbolMeta);
  28845. }
  28846. });
  28847. }
  28848. return {
  28849. fileName: fileName,
  28850. directives: directives,
  28851. abstractDirectives: abstractDirectives,
  28852. pipes: pipes,
  28853. ngModules: ngModules,
  28854. injectables: injectables,
  28855. exportsNonSourceFiles: exportsNonSourceFiles,
  28856. };
  28857. }
  28858. function analyzeFileForInjectables(host, staticSymbolResolver, metadataResolver, fileName) {
  28859. var injectables = [];
  28860. var shallowModules = [];
  28861. if (staticSymbolResolver.hasDecorators(fileName)) {
  28862. staticSymbolResolver.getSymbolsOf(fileName).forEach(function (symbol) {
  28863. var resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
  28864. var symbolMeta = resolvedSymbol.metadata;
  28865. if (!symbolMeta || symbolMeta.__symbolic === 'error') {
  28866. return;
  28867. }
  28868. if (symbolMeta.__symbolic === 'class') {
  28869. if (metadataResolver.isInjectable(symbol)) {
  28870. var injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
  28871. if (injectable) {
  28872. injectables.push(injectable);
  28873. }
  28874. }
  28875. else if (metadataResolver.isNgModule(symbol)) {
  28876. var module = metadataResolver.getShallowModuleMetadata(symbol);
  28877. if (module) {
  28878. shallowModules.push(module);
  28879. }
  28880. }
  28881. }
  28882. });
  28883. }
  28884. return { fileName: fileName, injectables: injectables, shallowModules: shallowModules };
  28885. }
  28886. function isValueExportingNonSourceFile(host, metadata) {
  28887. var exportsNonSourceFiles = false;
  28888. var Visitor = /** @class */ (function () {
  28889. function Visitor() {
  28890. }
  28891. Visitor.prototype.visitArray = function (arr, context) {
  28892. var _this = this;
  28893. arr.forEach(function (v) { return visitValue(v, _this, context); });
  28894. };
  28895. Visitor.prototype.visitStringMap = function (map, context) {
  28896. var _this = this;
  28897. Object.keys(map).forEach(function (key) { return visitValue(map[key], _this, context); });
  28898. };
  28899. Visitor.prototype.visitPrimitive = function (value, context) { };
  28900. Visitor.prototype.visitOther = function (value, context) {
  28901. if (value instanceof StaticSymbol && !host.isSourceFile(value.filePath)) {
  28902. exportsNonSourceFiles = true;
  28903. }
  28904. };
  28905. return Visitor;
  28906. }());
  28907. visitValue(metadata, new Visitor(), null);
  28908. return exportsNonSourceFiles;
  28909. }
  28910. function mergeAnalyzedFiles(analyzedFiles) {
  28911. var allNgModules = [];
  28912. var ngModuleByPipeOrDirective = new Map();
  28913. var allPipesAndDirectives = new Set();
  28914. analyzedFiles.forEach(function (af) {
  28915. af.ngModules.forEach(function (ngModule) {
  28916. allNgModules.push(ngModule);
  28917. ngModule.declaredDirectives.forEach(function (d) { return ngModuleByPipeOrDirective.set(d.reference, ngModule); });
  28918. ngModule.declaredPipes.forEach(function (p) { return ngModuleByPipeOrDirective.set(p.reference, ngModule); });
  28919. });
  28920. af.directives.forEach(function (d) { return allPipesAndDirectives.add(d); });
  28921. af.pipes.forEach(function (p) { return allPipesAndDirectives.add(p); });
  28922. });
  28923. var symbolsMissingModule = [];
  28924. allPipesAndDirectives.forEach(function (ref) {
  28925. if (!ngModuleByPipeOrDirective.has(ref)) {
  28926. symbolsMissingModule.push(ref);
  28927. }
  28928. });
  28929. return {
  28930. ngModules: allNgModules,
  28931. ngModuleByPipeOrDirective: ngModuleByPipeOrDirective,
  28932. symbolsMissingModule: symbolsMissingModule,
  28933. files: analyzedFiles
  28934. };
  28935. }
  28936. function mergeAndValidateNgFiles(files) {
  28937. return validateAnalyzedModules(mergeAnalyzedFiles(files));
  28938. }
  28939. var FORMATTED_MESSAGE = 'ngFormattedMessage';
  28940. function indentStr(level) {
  28941. if (level <= 0)
  28942. return '';
  28943. if (level < 6)
  28944. return ['', ' ', ' ', ' ', ' ', ' '][level];
  28945. var half = indentStr(Math.floor(level / 2));
  28946. return half + half + (level % 2 === 1 ? ' ' : '');
  28947. }
  28948. function formatChain(chain, indent) {
  28949. var e_1, _a;
  28950. if (indent === void 0) { indent = 0; }
  28951. if (!chain)
  28952. return '';
  28953. var position = chain.position ?
  28954. chain.position.fileName + "(" + (chain.position.line + 1) + "," + (chain.position.column + 1) + ")" :
  28955. '';
  28956. var prefix = position && indent === 0 ? position + ": " : '';
  28957. var postfix = position && indent !== 0 ? " at " + position : '';
  28958. var message = "" + prefix + chain.message + postfix;
  28959. if (chain.next) {
  28960. try {
  28961. for (var _b = __values(chain.next), _c = _b.next(); !_c.done; _c = _b.next()) {
  28962. var kid = _c.value;
  28963. message += '\n' + formatChain(kid, indent + 2);
  28964. }
  28965. }
  28966. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  28967. finally {
  28968. try {
  28969. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  28970. }
  28971. finally { if (e_1) throw e_1.error; }
  28972. }
  28973. }
  28974. return "" + indentStr(indent) + message;
  28975. }
  28976. function formattedError(chain) {
  28977. var message = formatChain(chain) + '.';
  28978. var error = syntaxError(message);
  28979. error[FORMATTED_MESSAGE] = true;
  28980. error.chain = chain;
  28981. error.position = chain.position;
  28982. return error;
  28983. }
  28984. function isFormattedError(error) {
  28985. return !!error[FORMATTED_MESSAGE];
  28986. }
  28987. var ANGULAR_CORE = '@angular/core';
  28988. var ANGULAR_ROUTER = '@angular/router';
  28989. var HIDDEN_KEY = /^\$.*\$$/;
  28990. var IGNORE = {
  28991. __symbolic: 'ignore'
  28992. };
  28993. var USE_VALUE$1 = 'useValue';
  28994. var PROVIDE = 'provide';
  28995. var REFERENCE_SET = new Set([USE_VALUE$1, 'useFactory', 'data', 'id', 'loadChildren']);
  28996. var TYPEGUARD_POSTFIX = 'TypeGuard';
  28997. var USE_IF = 'UseIf';
  28998. function shouldIgnore(value) {
  28999. return value && value.__symbolic == 'ignore';
  29000. }
  29001. /**
  29002. * A static reflector implements enough of the Reflector API that is necessary to compile
  29003. * templates statically.
  29004. */
  29005. var StaticReflector = /** @class */ (function () {
  29006. function StaticReflector(summaryResolver, symbolResolver, knownMetadataClasses, knownMetadataFunctions, errorRecorder) {
  29007. var _this = this;
  29008. if (knownMetadataClasses === void 0) { knownMetadataClasses = []; }
  29009. if (knownMetadataFunctions === void 0) { knownMetadataFunctions = []; }
  29010. this.summaryResolver = summaryResolver;
  29011. this.symbolResolver = symbolResolver;
  29012. this.errorRecorder = errorRecorder;
  29013. this.annotationCache = new Map();
  29014. this.shallowAnnotationCache = new Map();
  29015. this.propertyCache = new Map();
  29016. this.parameterCache = new Map();
  29017. this.methodCache = new Map();
  29018. this.staticCache = new Map();
  29019. this.conversionMap = new Map();
  29020. this.resolvedExternalReferences = new Map();
  29021. this.annotationForParentClassWithSummaryKind = new Map();
  29022. this.initializeConversionMap();
  29023. knownMetadataClasses.forEach(function (kc) { return _this._registerDecoratorOrConstructor(_this.getStaticSymbol(kc.filePath, kc.name), kc.ctor); });
  29024. knownMetadataFunctions.forEach(function (kf) { return _this._registerFunction(_this.getStaticSymbol(kf.filePath, kf.name), kf.fn); });
  29025. this.annotationForParentClassWithSummaryKind.set(exports.CompileSummaryKind.Directive, [createDirective, createComponent]);
  29026. this.annotationForParentClassWithSummaryKind.set(exports.CompileSummaryKind.Pipe, [createPipe]);
  29027. this.annotationForParentClassWithSummaryKind.set(exports.CompileSummaryKind.NgModule, [createNgModule]);
  29028. this.annotationForParentClassWithSummaryKind.set(exports.CompileSummaryKind.Injectable, [createInjectable, createPipe, createDirective, createComponent, createNgModule]);
  29029. }
  29030. StaticReflector.prototype.componentModuleUrl = function (typeOrFunc) {
  29031. var staticSymbol = this.findSymbolDeclaration(typeOrFunc);
  29032. return this.symbolResolver.getResourcePath(staticSymbol);
  29033. };
  29034. /**
  29035. * Invalidate the specified `symbols` on program change.
  29036. * @param symbols
  29037. */
  29038. StaticReflector.prototype.invalidateSymbols = function (symbols) {
  29039. var e_1, _a;
  29040. try {
  29041. for (var symbols_1 = __values(symbols), symbols_1_1 = symbols_1.next(); !symbols_1_1.done; symbols_1_1 = symbols_1.next()) {
  29042. var symbol = symbols_1_1.value;
  29043. this.annotationCache.delete(symbol);
  29044. this.shallowAnnotationCache.delete(symbol);
  29045. this.propertyCache.delete(symbol);
  29046. this.parameterCache.delete(symbol);
  29047. this.methodCache.delete(symbol);
  29048. this.staticCache.delete(symbol);
  29049. this.conversionMap.delete(symbol);
  29050. }
  29051. }
  29052. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  29053. finally {
  29054. try {
  29055. if (symbols_1_1 && !symbols_1_1.done && (_a = symbols_1.return)) _a.call(symbols_1);
  29056. }
  29057. finally { if (e_1) throw e_1.error; }
  29058. }
  29059. };
  29060. StaticReflector.prototype.resolveExternalReference = function (ref, containingFile) {
  29061. var key = undefined;
  29062. if (!containingFile) {
  29063. key = ref.moduleName + ":" + ref.name;
  29064. var declarationSymbol_1 = this.resolvedExternalReferences.get(key);
  29065. if (declarationSymbol_1)
  29066. return declarationSymbol_1;
  29067. }
  29068. var refSymbol = this.symbolResolver.getSymbolByModule(ref.moduleName, ref.name, containingFile);
  29069. var declarationSymbol = this.findSymbolDeclaration(refSymbol);
  29070. if (!containingFile) {
  29071. this.symbolResolver.recordModuleNameForFileName(refSymbol.filePath, ref.moduleName);
  29072. this.symbolResolver.recordImportAs(declarationSymbol, refSymbol);
  29073. }
  29074. if (key) {
  29075. this.resolvedExternalReferences.set(key, declarationSymbol);
  29076. }
  29077. return declarationSymbol;
  29078. };
  29079. StaticReflector.prototype.findDeclaration = function (moduleUrl, name, containingFile) {
  29080. return this.findSymbolDeclaration(this.symbolResolver.getSymbolByModule(moduleUrl, name, containingFile));
  29081. };
  29082. StaticReflector.prototype.tryFindDeclaration = function (moduleUrl, name, containingFile) {
  29083. var _this = this;
  29084. return this.symbolResolver.ignoreErrorsFor(function () { return _this.findDeclaration(moduleUrl, name, containingFile); });
  29085. };
  29086. StaticReflector.prototype.findSymbolDeclaration = function (symbol) {
  29087. var resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
  29088. if (resolvedSymbol) {
  29089. var resolvedMetadata = resolvedSymbol.metadata;
  29090. if (resolvedMetadata && resolvedMetadata.__symbolic === 'resolved') {
  29091. resolvedMetadata = resolvedMetadata.symbol;
  29092. }
  29093. if (resolvedMetadata instanceof StaticSymbol) {
  29094. return this.findSymbolDeclaration(resolvedSymbol.metadata);
  29095. }
  29096. }
  29097. return symbol;
  29098. };
  29099. StaticReflector.prototype.tryAnnotations = function (type) {
  29100. var originalRecorder = this.errorRecorder;
  29101. this.errorRecorder = function (error, fileName) { };
  29102. try {
  29103. return this.annotations(type);
  29104. }
  29105. finally {
  29106. this.errorRecorder = originalRecorder;
  29107. }
  29108. };
  29109. StaticReflector.prototype.annotations = function (type) {
  29110. var _this = this;
  29111. return this._annotations(type, function (type, decorators) { return _this.simplify(type, decorators); }, this.annotationCache);
  29112. };
  29113. StaticReflector.prototype.shallowAnnotations = function (type) {
  29114. var _this = this;
  29115. return this._annotations(type, function (type, decorators) { return _this.simplify(type, decorators, true); }, this.shallowAnnotationCache);
  29116. };
  29117. StaticReflector.prototype._annotations = function (type, simplify, annotationCache) {
  29118. var annotations = annotationCache.get(type);
  29119. if (!annotations) {
  29120. annotations = [];
  29121. var classMetadata = this.getTypeMetadata(type);
  29122. var parentType = this.findParentType(type, classMetadata);
  29123. if (parentType) {
  29124. var parentAnnotations = this.annotations(parentType);
  29125. annotations.push.apply(annotations, __spreadArray([], __read(parentAnnotations)));
  29126. }
  29127. var ownAnnotations_1 = [];
  29128. if (classMetadata['decorators']) {
  29129. ownAnnotations_1 = simplify(type, classMetadata['decorators']);
  29130. if (ownAnnotations_1) {
  29131. annotations.push.apply(annotations, __spreadArray([], __read(ownAnnotations_1)));
  29132. }
  29133. }
  29134. if (parentType && !this.summaryResolver.isLibraryFile(type.filePath) &&
  29135. this.summaryResolver.isLibraryFile(parentType.filePath)) {
  29136. var summary = this.summaryResolver.resolveSummary(parentType);
  29137. if (summary && summary.type) {
  29138. var requiredAnnotationTypes = this.annotationForParentClassWithSummaryKind.get(summary.type.summaryKind);
  29139. var typeHasRequiredAnnotation = requiredAnnotationTypes.some(function (requiredType) { return ownAnnotations_1.some(function (ann) { return requiredType.isTypeOf(ann); }); });
  29140. if (!typeHasRequiredAnnotation) {
  29141. this.reportError(formatMetadataError(metadataError("Class " + type.name + " in " + type.filePath + " extends from a " + exports.CompileSummaryKind[summary.type.summaryKind] + " in another compilation unit without duplicating the decorator",
  29142. /* summary */ undefined, "Please add a " + requiredAnnotationTypes.map(function (type) { return type.ngMetadataName; })
  29143. .join(' or ') + " decorator to the class"), type), type);
  29144. }
  29145. }
  29146. }
  29147. annotationCache.set(type, annotations.filter(function (ann) { return !!ann; }));
  29148. }
  29149. return annotations;
  29150. };
  29151. StaticReflector.prototype.propMetadata = function (type) {
  29152. var _this = this;
  29153. var propMetadata = this.propertyCache.get(type);
  29154. if (!propMetadata) {
  29155. var classMetadata = this.getTypeMetadata(type);
  29156. propMetadata = {};
  29157. var parentType = this.findParentType(type, classMetadata);
  29158. if (parentType) {
  29159. var parentPropMetadata_1 = this.propMetadata(parentType);
  29160. Object.keys(parentPropMetadata_1).forEach(function (parentProp) {
  29161. propMetadata[parentProp] = parentPropMetadata_1[parentProp];
  29162. });
  29163. }
  29164. var members_1 = classMetadata['members'] || {};
  29165. Object.keys(members_1).forEach(function (propName) {
  29166. var propData = members_1[propName];
  29167. var prop = propData
  29168. .find(function (a) { return a['__symbolic'] == 'property' || a['__symbolic'] == 'method'; });
  29169. var decorators = [];
  29170. // hasOwnProperty() is used here to make sure we do not look up methods
  29171. // on `Object.prototype`.
  29172. if (propMetadata === null || propMetadata === void 0 ? void 0 : propMetadata.hasOwnProperty(propName)) {
  29173. decorators.push.apply(decorators, __spreadArray([], __read(propMetadata[propName])));
  29174. }
  29175. propMetadata[propName] = decorators;
  29176. if (prop && prop['decorators']) {
  29177. decorators.push.apply(decorators, __spreadArray([], __read(_this.simplify(type, prop['decorators']))));
  29178. }
  29179. });
  29180. this.propertyCache.set(type, propMetadata);
  29181. }
  29182. return propMetadata;
  29183. };
  29184. StaticReflector.prototype.parameters = function (type) {
  29185. var _this = this;
  29186. if (!(type instanceof StaticSymbol)) {
  29187. this.reportError(new Error("parameters received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
  29188. return [];
  29189. }
  29190. try {
  29191. var parameters_1 = this.parameterCache.get(type);
  29192. if (!parameters_1) {
  29193. var classMetadata = this.getTypeMetadata(type);
  29194. var parentType = this.findParentType(type, classMetadata);
  29195. var members = classMetadata ? classMetadata['members'] : null;
  29196. var ctorData = members ? members['__ctor__'] : null;
  29197. if (ctorData) {
  29198. var ctor = ctorData.find(function (a) { return a['__symbolic'] == 'constructor'; });
  29199. var rawParameterTypes = ctor['parameters'] || [];
  29200. var parameterDecorators_1 = this.simplify(type, ctor['parameterDecorators'] || []);
  29201. parameters_1 = [];
  29202. rawParameterTypes.forEach(function (rawParamType, index) {
  29203. var nestedResult = [];
  29204. var paramType = _this.trySimplify(type, rawParamType);
  29205. if (paramType)
  29206. nestedResult.push(paramType);
  29207. var decorators = parameterDecorators_1 ? parameterDecorators_1[index] : null;
  29208. if (decorators) {
  29209. nestedResult.push.apply(nestedResult, __spreadArray([], __read(decorators)));
  29210. }
  29211. parameters_1.push(nestedResult);
  29212. });
  29213. }
  29214. else if (parentType) {
  29215. parameters_1 = this.parameters(parentType);
  29216. }
  29217. if (!parameters_1) {
  29218. parameters_1 = [];
  29219. }
  29220. this.parameterCache.set(type, parameters_1);
  29221. }
  29222. return parameters_1;
  29223. }
  29224. catch (e) {
  29225. console.error("Failed on type " + JSON.stringify(type) + " with error " + e);
  29226. throw e;
  29227. }
  29228. };
  29229. StaticReflector.prototype._methodNames = function (type) {
  29230. var methodNames = this.methodCache.get(type);
  29231. if (!methodNames) {
  29232. var classMetadata = this.getTypeMetadata(type);
  29233. methodNames = {};
  29234. var parentType = this.findParentType(type, classMetadata);
  29235. if (parentType) {
  29236. var parentMethodNames_1 = this._methodNames(parentType);
  29237. Object.keys(parentMethodNames_1).forEach(function (parentProp) {
  29238. methodNames[parentProp] = parentMethodNames_1[parentProp];
  29239. });
  29240. }
  29241. var members_2 = classMetadata['members'] || {};
  29242. Object.keys(members_2).forEach(function (propName) {
  29243. var propData = members_2[propName];
  29244. var isMethod = propData.some(function (a) { return a['__symbolic'] == 'method'; });
  29245. methodNames[propName] = methodNames[propName] || isMethod;
  29246. });
  29247. this.methodCache.set(type, methodNames);
  29248. }
  29249. return methodNames;
  29250. };
  29251. StaticReflector.prototype._staticMembers = function (type) {
  29252. var staticMembers = this.staticCache.get(type);
  29253. if (!staticMembers) {
  29254. var classMetadata = this.getTypeMetadata(type);
  29255. var staticMemberData = classMetadata['statics'] || {};
  29256. staticMembers = Object.keys(staticMemberData);
  29257. this.staticCache.set(type, staticMembers);
  29258. }
  29259. return staticMembers;
  29260. };
  29261. StaticReflector.prototype.findParentType = function (type, classMetadata) {
  29262. var parentType = this.trySimplify(type, classMetadata['extends']);
  29263. if (parentType instanceof StaticSymbol) {
  29264. return parentType;
  29265. }
  29266. };
  29267. StaticReflector.prototype.hasLifecycleHook = function (type, lcProperty) {
  29268. if (!(type instanceof StaticSymbol)) {
  29269. this.reportError(new Error("hasLifecycleHook received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
  29270. }
  29271. try {
  29272. return !!this._methodNames(type)[lcProperty];
  29273. }
  29274. catch (e) {
  29275. console.error("Failed on type " + JSON.stringify(type) + " with error " + e);
  29276. throw e;
  29277. }
  29278. };
  29279. StaticReflector.prototype.guards = function (type) {
  29280. var e_2, _a;
  29281. if (!(type instanceof StaticSymbol)) {
  29282. this.reportError(new Error("guards received " + JSON.stringify(type) + " which is not a StaticSymbol"), type);
  29283. return {};
  29284. }
  29285. var staticMembers = this._staticMembers(type);
  29286. var result = {};
  29287. try {
  29288. for (var staticMembers_1 = __values(staticMembers), staticMembers_1_1 = staticMembers_1.next(); !staticMembers_1_1.done; staticMembers_1_1 = staticMembers_1.next()) {
  29289. var name = staticMembers_1_1.value;
  29290. if (name.endsWith(TYPEGUARD_POSTFIX)) {
  29291. var property = name.substr(0, name.length - TYPEGUARD_POSTFIX.length);
  29292. var value = void 0;
  29293. if (property.endsWith(USE_IF)) {
  29294. property = name.substr(0, property.length - USE_IF.length);
  29295. value = USE_IF;
  29296. }
  29297. else {
  29298. value = this.getStaticSymbol(type.filePath, type.name, [name]);
  29299. }
  29300. result[property] = value;
  29301. }
  29302. }
  29303. }
  29304. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  29305. finally {
  29306. try {
  29307. if (staticMembers_1_1 && !staticMembers_1_1.done && (_a = staticMembers_1.return)) _a.call(staticMembers_1);
  29308. }
  29309. finally { if (e_2) throw e_2.error; }
  29310. }
  29311. return result;
  29312. };
  29313. StaticReflector.prototype._registerDecoratorOrConstructor = function (type, ctor) {
  29314. this.conversionMap.set(type, function (context, args) { return new (ctor.bind.apply(ctor, __spreadArray([void 0], __read(args))))(); });
  29315. };
  29316. StaticReflector.prototype._registerFunction = function (type, fn) {
  29317. this.conversionMap.set(type, function (context, args) { return fn.apply(undefined, args); });
  29318. };
  29319. StaticReflector.prototype.initializeConversionMap = function () {
  29320. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Injectable'), createInjectable);
  29321. this.injectionToken = this.findDeclaration(ANGULAR_CORE, 'InjectionToken');
  29322. this.opaqueToken = this.findDeclaration(ANGULAR_CORE, 'OpaqueToken');
  29323. this.ROUTES = this.tryFindDeclaration(ANGULAR_ROUTER, 'ROUTES');
  29324. this.ANALYZE_FOR_ENTRY_COMPONENTS =
  29325. this.findDeclaration(ANGULAR_CORE, 'ANALYZE_FOR_ENTRY_COMPONENTS');
  29326. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
  29327. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
  29328. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
  29329. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Inject'), createInject);
  29330. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
  29331. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Attribute'), createAttribute);
  29332. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChild'), createContentChild);
  29333. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChildren'), createContentChildren);
  29334. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChild'), createViewChild);
  29335. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChildren'), createViewChildren);
  29336. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Input'), createInput);
  29337. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Output'), createOutput);
  29338. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Pipe'), createPipe);
  29339. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostBinding'), createHostBinding);
  29340. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostListener'), createHostListener);
  29341. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Directive'), createDirective);
  29342. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Component'), createComponent);
  29343. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'NgModule'), createNgModule);
  29344. // Note: Some metadata classes can be used directly with Provider.deps.
  29345. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
  29346. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
  29347. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
  29348. this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
  29349. };
  29350. /**
  29351. * getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
  29352. * All types passed to the StaticResolver should be pseudo-types returned by this method.
  29353. *
  29354. * @param declarationFile the absolute path of the file where the symbol is declared
  29355. * @param name the name of the type.
  29356. */
  29357. StaticReflector.prototype.getStaticSymbol = function (declarationFile, name, members) {
  29358. return this.symbolResolver.getStaticSymbol(declarationFile, name, members);
  29359. };
  29360. /**
  29361. * Simplify but discard any errors
  29362. */
  29363. StaticReflector.prototype.trySimplify = function (context, value) {
  29364. var originalRecorder = this.errorRecorder;
  29365. this.errorRecorder = function (error, fileName) { };
  29366. var result = this.simplify(context, value);
  29367. this.errorRecorder = originalRecorder;
  29368. return result;
  29369. };
  29370. /** @internal */
  29371. StaticReflector.prototype.simplify = function (context, value, lazy) {
  29372. if (lazy === void 0) { lazy = false; }
  29373. var self = this;
  29374. var scope = BindingScope$1.empty;
  29375. var calling = new Map();
  29376. var rootContext = context;
  29377. function simplifyInContext(context, value, depth, references) {
  29378. function resolveReferenceValue(staticSymbol) {
  29379. var resolvedSymbol = self.symbolResolver.resolveSymbol(staticSymbol);
  29380. return resolvedSymbol ? resolvedSymbol.metadata : null;
  29381. }
  29382. function simplifyEagerly(value) {
  29383. return simplifyInContext(context, value, depth, 0);
  29384. }
  29385. function simplifyLazily(value) {
  29386. return simplifyInContext(context, value, depth, references + 1);
  29387. }
  29388. function simplifyNested(nestedContext, value) {
  29389. if (nestedContext === context) {
  29390. // If the context hasn't changed let the exception propagate unmodified.
  29391. return simplifyInContext(nestedContext, value, depth + 1, references);
  29392. }
  29393. try {
  29394. return simplifyInContext(nestedContext, value, depth + 1, references);
  29395. }
  29396. catch (e) {
  29397. if (isMetadataError(e)) {
  29398. // Propagate the message text up but add a message to the chain that explains how we got
  29399. // here.
  29400. // e.chain implies e.symbol
  29401. var summaryMsg = e.chain ? 'references \'' + e.symbol.name + '\'' : errorSummary(e);
  29402. var summary = "'" + nestedContext.name + "' " + summaryMsg;
  29403. var chain = { message: summary, position: e.position, next: e.chain };
  29404. // TODO(chuckj): retrieve the position information indirectly from the collectors node
  29405. // map if the metadata is from a .ts file.
  29406. self.error({
  29407. message: e.message,
  29408. advise: e.advise,
  29409. context: e.context,
  29410. chain: chain,
  29411. symbol: nestedContext
  29412. }, context);
  29413. }
  29414. else {
  29415. // It is probably an internal error.
  29416. throw e;
  29417. }
  29418. }
  29419. }
  29420. function simplifyCall(functionSymbol, targetFunction, args, targetExpression) {
  29421. if (targetFunction && targetFunction['__symbolic'] == 'function') {
  29422. if (calling.get(functionSymbol)) {
  29423. self.error({
  29424. message: 'Recursion is not supported',
  29425. summary: "called '" + functionSymbol.name + "' recursively",
  29426. value: targetFunction
  29427. }, functionSymbol);
  29428. }
  29429. try {
  29430. var value_1 = targetFunction['value'];
  29431. if (value_1 && (depth != 0 || value_1.__symbolic != 'error')) {
  29432. var parameters = targetFunction['parameters'];
  29433. var defaults = targetFunction.defaults;
  29434. args = args.map(function (arg) { return simplifyNested(context, arg); })
  29435. .map(function (arg) { return shouldIgnore(arg) ? undefined : arg; });
  29436. if (defaults && defaults.length > args.length) {
  29437. args.push.apply(args, __spreadArray([], __read(defaults.slice(args.length).map(function (value) { return simplify(value); }))));
  29438. }
  29439. calling.set(functionSymbol, true);
  29440. var functionScope = BindingScope$1.build();
  29441. for (var i = 0; i < parameters.length; i++) {
  29442. functionScope.define(parameters[i], args[i]);
  29443. }
  29444. var oldScope = scope;
  29445. var result_1;
  29446. try {
  29447. scope = functionScope.done();
  29448. result_1 = simplifyNested(functionSymbol, value_1);
  29449. }
  29450. finally {
  29451. scope = oldScope;
  29452. }
  29453. return result_1;
  29454. }
  29455. }
  29456. finally {
  29457. calling.delete(functionSymbol);
  29458. }
  29459. }
  29460. if (depth === 0) {
  29461. // If depth is 0 we are evaluating the top level expression that is describing element
  29462. // decorator. In this case, it is a decorator we don't understand, such as a custom
  29463. // non-angular decorator, and we should just ignore it.
  29464. return IGNORE;
  29465. }
  29466. var position = undefined;
  29467. if (targetExpression && targetExpression.__symbolic == 'resolved') {
  29468. var line = targetExpression.line;
  29469. var character = targetExpression.character;
  29470. var fileName = targetExpression.fileName;
  29471. if (fileName != null && line != null && character != null) {
  29472. position = { fileName: fileName, line: line, column: character };
  29473. }
  29474. }
  29475. self.error({
  29476. message: FUNCTION_CALL_NOT_SUPPORTED,
  29477. context: functionSymbol,
  29478. value: targetFunction,
  29479. position: position
  29480. }, context);
  29481. }
  29482. function simplify(expression) {
  29483. var e_3, _a, e_4, _b;
  29484. if (isPrimitive(expression)) {
  29485. return expression;
  29486. }
  29487. if (Array.isArray(expression)) {
  29488. var result_2 = [];
  29489. try {
  29490. for (var expression_1 = __values(expression), expression_1_1 = expression_1.next(); !expression_1_1.done; expression_1_1 = expression_1.next()) {
  29491. var item = expression_1_1.value;
  29492. // Check for a spread expression
  29493. if (item && item.__symbolic === 'spread') {
  29494. // We call with references as 0 because we require the actual value and cannot
  29495. // tolerate a reference here.
  29496. var spreadArray = simplifyEagerly(item.expression);
  29497. if (Array.isArray(spreadArray)) {
  29498. try {
  29499. for (var spreadArray_1 = (e_4 = void 0, __values(spreadArray)), spreadArray_1_1 = spreadArray_1.next(); !spreadArray_1_1.done; spreadArray_1_1 = spreadArray_1.next()) {
  29500. var spreadItem = spreadArray_1_1.value;
  29501. result_2.push(spreadItem);
  29502. }
  29503. }
  29504. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  29505. finally {
  29506. try {
  29507. if (spreadArray_1_1 && !spreadArray_1_1.done && (_b = spreadArray_1.return)) _b.call(spreadArray_1);
  29508. }
  29509. finally { if (e_4) throw e_4.error; }
  29510. }
  29511. continue;
  29512. }
  29513. }
  29514. var value_2 = simplify(item);
  29515. if (shouldIgnore(value_2)) {
  29516. continue;
  29517. }
  29518. result_2.push(value_2);
  29519. }
  29520. }
  29521. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  29522. finally {
  29523. try {
  29524. if (expression_1_1 && !expression_1_1.done && (_a = expression_1.return)) _a.call(expression_1);
  29525. }
  29526. finally { if (e_3) throw e_3.error; }
  29527. }
  29528. return result_2;
  29529. }
  29530. if (expression instanceof StaticSymbol) {
  29531. // Stop simplification at builtin symbols or if we are in a reference context and
  29532. // the symbol doesn't have members.
  29533. if (expression === self.injectionToken || self.conversionMap.has(expression) ||
  29534. (references > 0 && !expression.members.length)) {
  29535. return expression;
  29536. }
  29537. else {
  29538. var staticSymbol = expression;
  29539. var declarationValue = resolveReferenceValue(staticSymbol);
  29540. if (declarationValue != null) {
  29541. return simplifyNested(staticSymbol, declarationValue);
  29542. }
  29543. else {
  29544. return staticSymbol;
  29545. }
  29546. }
  29547. }
  29548. if (expression) {
  29549. if (expression['__symbolic']) {
  29550. var staticSymbol = void 0;
  29551. switch (expression['__symbolic']) {
  29552. case 'binop':
  29553. var left = simplify(expression['left']);
  29554. if (shouldIgnore(left))
  29555. return left;
  29556. var right = simplify(expression['right']);
  29557. if (shouldIgnore(right))
  29558. return right;
  29559. switch (expression['operator']) {
  29560. case '&&':
  29561. return left && right;
  29562. case '||':
  29563. return left || right;
  29564. case '|':
  29565. return left | right;
  29566. case '^':
  29567. return left ^ right;
  29568. case '&':
  29569. return left & right;
  29570. case '==':
  29571. return left == right;
  29572. case '!=':
  29573. return left != right;
  29574. case '===':
  29575. return left === right;
  29576. case '!==':
  29577. return left !== right;
  29578. case '<':
  29579. return left < right;
  29580. case '>':
  29581. return left > right;
  29582. case '<=':
  29583. return left <= right;
  29584. case '>=':
  29585. return left >= right;
  29586. case '<<':
  29587. return left << right;
  29588. case '>>':
  29589. return left >> right;
  29590. case '+':
  29591. return left + right;
  29592. case '-':
  29593. return left - right;
  29594. case '*':
  29595. return left * right;
  29596. case '/':
  29597. return left / right;
  29598. case '%':
  29599. return left % right;
  29600. case '??':
  29601. return left !== null && left !== void 0 ? left : right;
  29602. }
  29603. return null;
  29604. case 'if':
  29605. var condition = simplify(expression['condition']);
  29606. return condition ? simplify(expression['thenExpression']) :
  29607. simplify(expression['elseExpression']);
  29608. case 'pre':
  29609. var operand = simplify(expression['operand']);
  29610. if (shouldIgnore(operand))
  29611. return operand;
  29612. switch (expression['operator']) {
  29613. case '+':
  29614. return operand;
  29615. case '-':
  29616. return -operand;
  29617. case '!':
  29618. return !operand;
  29619. case '~':
  29620. return ~operand;
  29621. }
  29622. return null;
  29623. case 'index':
  29624. var indexTarget = simplifyEagerly(expression['expression']);
  29625. var index = simplifyEagerly(expression['index']);
  29626. if (indexTarget && isPrimitive(index))
  29627. return indexTarget[index];
  29628. return null;
  29629. case 'select':
  29630. var member = expression['member'];
  29631. var selectContext = context;
  29632. var selectTarget = simplify(expression['expression']);
  29633. if (selectTarget instanceof StaticSymbol) {
  29634. var members = selectTarget.members.concat(member);
  29635. selectContext =
  29636. self.getStaticSymbol(selectTarget.filePath, selectTarget.name, members);
  29637. var declarationValue = resolveReferenceValue(selectContext);
  29638. if (declarationValue != null) {
  29639. return simplifyNested(selectContext, declarationValue);
  29640. }
  29641. else {
  29642. return selectContext;
  29643. }
  29644. }
  29645. if (selectTarget && isPrimitive(member))
  29646. return simplifyNested(selectContext, selectTarget[member]);
  29647. return null;
  29648. case 'reference':
  29649. // Note: This only has to deal with variable references, as symbol references have
  29650. // been converted into 'resolved'
  29651. // in the StaticSymbolResolver.
  29652. var name = expression['name'];
  29653. var localValue = scope.resolve(name);
  29654. if (localValue != BindingScope$1.missing) {
  29655. return localValue;
  29656. }
  29657. break;
  29658. case 'resolved':
  29659. try {
  29660. return simplify(expression.symbol);
  29661. }
  29662. catch (e) {
  29663. // If an error is reported evaluating the symbol record the position of the
  29664. // reference in the error so it can
  29665. // be reported in the error message generated from the exception.
  29666. if (isMetadataError(e) && expression.fileName != null &&
  29667. expression.line != null && expression.character != null) {
  29668. e.position = {
  29669. fileName: expression.fileName,
  29670. line: expression.line,
  29671. column: expression.character
  29672. };
  29673. }
  29674. throw e;
  29675. }
  29676. case 'class':
  29677. return context;
  29678. case 'function':
  29679. return context;
  29680. case 'new':
  29681. case 'call':
  29682. // Determine if the function is a built-in conversion
  29683. staticSymbol = simplifyInContext(context, expression['expression'], depth + 1, /* references */ 0);
  29684. if (staticSymbol instanceof StaticSymbol) {
  29685. if (staticSymbol === self.injectionToken || staticSymbol === self.opaqueToken) {
  29686. // if somebody calls new InjectionToken, don't create an InjectionToken,
  29687. // but rather return the symbol to which the InjectionToken is assigned to.
  29688. // OpaqueToken is supported too as it is required by the language service to
  29689. // support v4 and prior versions of Angular.
  29690. return context;
  29691. }
  29692. var argExpressions = expression['arguments'] || [];
  29693. var converter = self.conversionMap.get(staticSymbol);
  29694. if (converter) {
  29695. var args = argExpressions.map(function (arg) { return simplifyNested(context, arg); })
  29696. .map(function (arg) { return shouldIgnore(arg) ? undefined : arg; });
  29697. return converter(context, args);
  29698. }
  29699. else {
  29700. // Determine if the function is one we can simplify.
  29701. var targetFunction = resolveReferenceValue(staticSymbol);
  29702. return simplifyCall(staticSymbol, targetFunction, argExpressions, expression['expression']);
  29703. }
  29704. }
  29705. return IGNORE;
  29706. case 'error':
  29707. var message = expression.message;
  29708. if (expression['line'] != null) {
  29709. self.error({
  29710. message: message,
  29711. context: expression.context,
  29712. value: expression,
  29713. position: {
  29714. fileName: expression['fileName'],
  29715. line: expression['line'],
  29716. column: expression['character']
  29717. }
  29718. }, context);
  29719. }
  29720. else {
  29721. self.error({ message: message, context: expression.context }, context);
  29722. }
  29723. return IGNORE;
  29724. case 'ignore':
  29725. return expression;
  29726. }
  29727. return null;
  29728. }
  29729. return mapStringMap(expression, function (value, name) {
  29730. if (REFERENCE_SET.has(name)) {
  29731. if (name === USE_VALUE$1 && PROVIDE in expression) {
  29732. // If this is a provider expression, check for special tokens that need the value
  29733. // during analysis.
  29734. var provide = simplify(expression.provide);
  29735. if (provide === self.ROUTES || provide == self.ANALYZE_FOR_ENTRY_COMPONENTS) {
  29736. return simplify(value);
  29737. }
  29738. }
  29739. return simplifyLazily(value);
  29740. }
  29741. return simplify(value);
  29742. });
  29743. }
  29744. return IGNORE;
  29745. }
  29746. return simplify(value);
  29747. }
  29748. var result;
  29749. try {
  29750. result = simplifyInContext(context, value, 0, lazy ? 1 : 0);
  29751. }
  29752. catch (e) {
  29753. if (this.errorRecorder) {
  29754. this.reportError(e, context);
  29755. }
  29756. else {
  29757. throw formatMetadataError(e, context);
  29758. }
  29759. }
  29760. if (shouldIgnore(result)) {
  29761. return undefined;
  29762. }
  29763. return result;
  29764. };
  29765. StaticReflector.prototype.getTypeMetadata = function (type) {
  29766. var resolvedSymbol = this.symbolResolver.resolveSymbol(type);
  29767. return resolvedSymbol && resolvedSymbol.metadata ? resolvedSymbol.metadata :
  29768. { __symbolic: 'class' };
  29769. };
  29770. StaticReflector.prototype.reportError = function (error, context, path) {
  29771. if (this.errorRecorder) {
  29772. this.errorRecorder(formatMetadataError(error, context), (context && context.filePath) || path);
  29773. }
  29774. else {
  29775. throw error;
  29776. }
  29777. };
  29778. StaticReflector.prototype.error = function (_a, reportingContext) {
  29779. var message = _a.message, summary = _a.summary, advise = _a.advise, position = _a.position, context = _a.context, value = _a.value, symbol = _a.symbol, chain = _a.chain;
  29780. this.reportError(metadataError(message, summary, advise, position, symbol, context, chain), reportingContext);
  29781. };
  29782. return StaticReflector;
  29783. }());
  29784. var METADATA_ERROR = 'ngMetadataError';
  29785. function metadataError(message, summary, advise, position, symbol, context, chain) {
  29786. var error = syntaxError(message);
  29787. error[METADATA_ERROR] = true;
  29788. if (advise)
  29789. error.advise = advise;
  29790. if (position)
  29791. error.position = position;
  29792. if (summary)
  29793. error.summary = summary;
  29794. if (context)
  29795. error.context = context;
  29796. if (chain)
  29797. error.chain = chain;
  29798. if (symbol)
  29799. error.symbol = symbol;
  29800. return error;
  29801. }
  29802. function isMetadataError(error) {
  29803. return !!error[METADATA_ERROR];
  29804. }
  29805. var REFERENCE_TO_NONEXPORTED_CLASS = 'Reference to non-exported class';
  29806. var VARIABLE_NOT_INITIALIZED = 'Variable not initialized';
  29807. var DESTRUCTURE_NOT_SUPPORTED = 'Destructuring not supported';
  29808. var COULD_NOT_RESOLVE_TYPE = 'Could not resolve type';
  29809. var FUNCTION_CALL_NOT_SUPPORTED = 'Function call not supported';
  29810. var REFERENCE_TO_LOCAL_SYMBOL = 'Reference to a local symbol';
  29811. var LAMBDA_NOT_SUPPORTED = 'Lambda not supported';
  29812. function expandedMessage(message, context) {
  29813. switch (message) {
  29814. case REFERENCE_TO_NONEXPORTED_CLASS:
  29815. if (context && context.className) {
  29816. return "References to a non-exported class are not supported in decorators but " + context.className + " was referenced.";
  29817. }
  29818. break;
  29819. case VARIABLE_NOT_INITIALIZED:
  29820. return 'Only initialized variables and constants can be referenced in decorators because the value of this variable is needed by the template compiler';
  29821. case DESTRUCTURE_NOT_SUPPORTED:
  29822. return 'Referencing an exported destructured variable or constant is not supported in decorators and this value is needed by the template compiler';
  29823. case COULD_NOT_RESOLVE_TYPE:
  29824. if (context && context.typeName) {
  29825. return "Could not resolve type " + context.typeName;
  29826. }
  29827. break;
  29828. case FUNCTION_CALL_NOT_SUPPORTED:
  29829. if (context && context.name) {
  29830. return "Function calls are not supported in decorators but '" + context.name + "' was called";
  29831. }
  29832. return 'Function calls are not supported in decorators';
  29833. case REFERENCE_TO_LOCAL_SYMBOL:
  29834. if (context && context.name) {
  29835. return "Reference to a local (non-exported) symbols are not supported in decorators but '" + context.name + "' was referenced";
  29836. }
  29837. break;
  29838. case LAMBDA_NOT_SUPPORTED:
  29839. return "Function expressions are not supported in decorators";
  29840. }
  29841. return message;
  29842. }
  29843. function messageAdvise(message, context) {
  29844. switch (message) {
  29845. case REFERENCE_TO_NONEXPORTED_CLASS:
  29846. if (context && context.className) {
  29847. return "Consider exporting '" + context.className + "'";
  29848. }
  29849. break;
  29850. case DESTRUCTURE_NOT_SUPPORTED:
  29851. return 'Consider simplifying to avoid destructuring';
  29852. case REFERENCE_TO_LOCAL_SYMBOL:
  29853. if (context && context.name) {
  29854. return "Consider exporting '" + context.name + "'";
  29855. }
  29856. break;
  29857. case LAMBDA_NOT_SUPPORTED:
  29858. return "Consider changing the function expression into an exported function";
  29859. }
  29860. return undefined;
  29861. }
  29862. function errorSummary(error) {
  29863. if (error.summary) {
  29864. return error.summary;
  29865. }
  29866. switch (error.message) {
  29867. case REFERENCE_TO_NONEXPORTED_CLASS:
  29868. if (error.context && error.context.className) {
  29869. return "references non-exported class " + error.context.className;
  29870. }
  29871. break;
  29872. case VARIABLE_NOT_INITIALIZED:
  29873. return 'is not initialized';
  29874. case DESTRUCTURE_NOT_SUPPORTED:
  29875. return 'is a destructured variable';
  29876. case COULD_NOT_RESOLVE_TYPE:
  29877. return 'could not be resolved';
  29878. case FUNCTION_CALL_NOT_SUPPORTED:
  29879. if (error.context && error.context.name) {
  29880. return "calls '" + error.context.name + "'";
  29881. }
  29882. return "calls a function";
  29883. case REFERENCE_TO_LOCAL_SYMBOL:
  29884. if (error.context && error.context.name) {
  29885. return "references local variable " + error.context.name;
  29886. }
  29887. return "references a local variable";
  29888. }
  29889. return 'contains the error';
  29890. }
  29891. function mapStringMap(input, transform) {
  29892. if (!input)
  29893. return {};
  29894. var result = {};
  29895. Object.keys(input).forEach(function (key) {
  29896. var value = transform(input[key], key);
  29897. if (!shouldIgnore(value)) {
  29898. if (HIDDEN_KEY.test(key)) {
  29899. Object.defineProperty(result, key, { enumerable: false, configurable: true, value: value });
  29900. }
  29901. else {
  29902. result[key] = value;
  29903. }
  29904. }
  29905. });
  29906. return result;
  29907. }
  29908. function isPrimitive(o) {
  29909. return o === null || (typeof o !== 'function' && typeof o !== 'object');
  29910. }
  29911. var BindingScope$1 = /** @class */ (function () {
  29912. function BindingScope() {
  29913. }
  29914. BindingScope.build = function () {
  29915. var current = new Map();
  29916. return {
  29917. define: function (name, value) {
  29918. current.set(name, value);
  29919. return this;
  29920. },
  29921. done: function () {
  29922. return current.size > 0 ? new PopulatedScope(current) : BindingScope.empty;
  29923. }
  29924. };
  29925. };
  29926. return BindingScope;
  29927. }());
  29928. BindingScope$1.missing = {};
  29929. BindingScope$1.empty = { resolve: function (name) { return BindingScope$1.missing; } };
  29930. var PopulatedScope = /** @class */ (function (_super) {
  29931. __extends(PopulatedScope, _super);
  29932. function PopulatedScope(bindings) {
  29933. var _this = _super.call(this) || this;
  29934. _this.bindings = bindings;
  29935. return _this;
  29936. }
  29937. PopulatedScope.prototype.resolve = function (name) {
  29938. return this.bindings.has(name) ? this.bindings.get(name) : BindingScope$1.missing;
  29939. };
  29940. return PopulatedScope;
  29941. }(BindingScope$1));
  29942. function formatMetadataMessageChain(chain, advise) {
  29943. var expanded = expandedMessage(chain.message, chain.context);
  29944. var nesting = chain.symbol ? " in '" + chain.symbol.name + "'" : '';
  29945. var message = "" + expanded + nesting;
  29946. var position = chain.position;
  29947. var next = chain.next ?
  29948. formatMetadataMessageChain(chain.next, advise) :
  29949. advise ? { message: advise } : undefined;
  29950. return { message: message, position: position, next: next ? [next] : undefined };
  29951. }
  29952. function formatMetadataError(e, context) {
  29953. if (isMetadataError(e)) {
  29954. // Produce a formatted version of the and leaving enough information in the original error
  29955. // to recover the formatting information to eventually produce a diagnostic error message.
  29956. var position = e.position;
  29957. var chain = {
  29958. message: "Error during template compile of '" + context.name + "'",
  29959. position: position,
  29960. next: { message: e.message, next: e.chain, context: e.context, symbol: e.symbol }
  29961. };
  29962. var advise = e.advise || messageAdvise(e.message, e.context);
  29963. return formattedError(formatMetadataMessageChain(chain, advise));
  29964. }
  29965. return e;
  29966. }
  29967. /**
  29968. * @license
  29969. * Copyright Google LLC All Rights Reserved.
  29970. *
  29971. * Use of this source code is governed by an MIT-style license that can be
  29972. * found in the LICENSE file at https://angular.io/license
  29973. */
  29974. var AotSummaryResolver = /** @class */ (function () {
  29975. function AotSummaryResolver(host, staticSymbolCache) {
  29976. this.host = host;
  29977. this.staticSymbolCache = staticSymbolCache;
  29978. // Note: this will only contain StaticSymbols without members!
  29979. this.summaryCache = new Map();
  29980. this.loadedFilePaths = new Map();
  29981. // Note: this will only contain StaticSymbols without members!
  29982. this.importAs = new Map();
  29983. this.knownFileNameToModuleNames = new Map();
  29984. }
  29985. AotSummaryResolver.prototype.isLibraryFile = function (filePath) {
  29986. // Note: We need to strip the .ngfactory. file path,
  29987. // so this method also works for generated files
  29988. // (for which host.isSourceFile will always return false).
  29989. return !this.host.isSourceFile(stripGeneratedFileSuffix(filePath));
  29990. };
  29991. AotSummaryResolver.prototype.toSummaryFileName = function (filePath, referringSrcFileName) {
  29992. return this.host.toSummaryFileName(filePath, referringSrcFileName);
  29993. };
  29994. AotSummaryResolver.prototype.fromSummaryFileName = function (fileName, referringLibFileName) {
  29995. return this.host.fromSummaryFileName(fileName, referringLibFileName);
  29996. };
  29997. AotSummaryResolver.prototype.resolveSummary = function (staticSymbol) {
  29998. var rootSymbol = staticSymbol.members.length ?
  29999. this.staticSymbolCache.get(staticSymbol.filePath, staticSymbol.name) :
  30000. staticSymbol;
  30001. var summary = this.summaryCache.get(rootSymbol);
  30002. if (!summary) {
  30003. this._loadSummaryFile(staticSymbol.filePath);
  30004. summary = this.summaryCache.get(staticSymbol);
  30005. }
  30006. return (rootSymbol === staticSymbol && summary) || null;
  30007. };
  30008. AotSummaryResolver.prototype.getSymbolsOf = function (filePath) {
  30009. if (this._loadSummaryFile(filePath)) {
  30010. return Array.from(this.summaryCache.keys()).filter(function (symbol) { return symbol.filePath === filePath; });
  30011. }
  30012. return null;
  30013. };
  30014. AotSummaryResolver.prototype.getImportAs = function (staticSymbol) {
  30015. staticSymbol.assertNoMembers();
  30016. return this.importAs.get(staticSymbol);
  30017. };
  30018. /**
  30019. * Converts a file path to a module name that can be used as an `import`.
  30020. */
  30021. AotSummaryResolver.prototype.getKnownModuleName = function (importedFilePath) {
  30022. return this.knownFileNameToModuleNames.get(importedFilePath) || null;
  30023. };
  30024. AotSummaryResolver.prototype.addSummary = function (summary) {
  30025. this.summaryCache.set(summary.symbol, summary);
  30026. };
  30027. AotSummaryResolver.prototype._loadSummaryFile = function (filePath) {
  30028. var _this = this;
  30029. var hasSummary = this.loadedFilePaths.get(filePath);
  30030. if (hasSummary != null) {
  30031. return hasSummary;
  30032. }
  30033. var json = null;
  30034. if (this.isLibraryFile(filePath)) {
  30035. var summaryFilePath = summaryFileName(filePath);
  30036. try {
  30037. json = this.host.loadSummary(summaryFilePath);
  30038. }
  30039. catch (e) {
  30040. console.error("Error loading summary file " + summaryFilePath);
  30041. throw e;
  30042. }
  30043. }
  30044. hasSummary = json != null;
  30045. this.loadedFilePaths.set(filePath, hasSummary);
  30046. if (json) {
  30047. var _a = deserializeSummaries(this.staticSymbolCache, this, filePath, json), moduleName = _a.moduleName, summaries = _a.summaries, importAs = _a.importAs;
  30048. summaries.forEach(function (summary) { return _this.summaryCache.set(summary.symbol, summary); });
  30049. if (moduleName) {
  30050. this.knownFileNameToModuleNames.set(filePath, moduleName);
  30051. }
  30052. importAs.forEach(function (importAs) {
  30053. _this.importAs.set(importAs.symbol, importAs.importAs);
  30054. });
  30055. }
  30056. return hasSummary;
  30057. };
  30058. return AotSummaryResolver;
  30059. }());
  30060. /**
  30061. * @license
  30062. * Copyright Google LLC All Rights Reserved.
  30063. *
  30064. * Use of this source code is governed by an MIT-style license that can be
  30065. * found in the LICENSE file at https://angular.io/license
  30066. */
  30067. function createAotUrlResolver(host) {
  30068. return {
  30069. resolve: function (basePath, url) {
  30070. var filePath = host.resourceNameToFileName(url, basePath);
  30071. if (!filePath) {
  30072. throw syntaxError("Couldn't resolve resource " + url + " from " + basePath);
  30073. }
  30074. return filePath;
  30075. }
  30076. };
  30077. }
  30078. /**
  30079. * Creates a new AotCompiler based on options and a host.
  30080. */
  30081. function createAotCompiler(compilerHost, options, errorCollector) {
  30082. var translations = options.translations || '';
  30083. var urlResolver = createAotUrlResolver(compilerHost);
  30084. var symbolCache = new StaticSymbolCache();
  30085. var summaryResolver = new AotSummaryResolver(compilerHost, symbolCache);
  30086. var symbolResolver = new StaticSymbolResolver(compilerHost, symbolCache, summaryResolver);
  30087. var staticReflector = new StaticReflector(summaryResolver, symbolResolver, [], [], errorCollector);
  30088. var htmlParser;
  30089. if (!!options.enableIvy) {
  30090. // Ivy handles i18n at the compiler level so we must use a regular parser
  30091. htmlParser = new HtmlParser();
  30092. }
  30093. else {
  30094. htmlParser = new I18NHtmlParser(new HtmlParser(), translations, options.i18nFormat, options.missingTranslation, console);
  30095. }
  30096. var config = new CompilerConfig({
  30097. defaultEncapsulation: ViewEncapsulation.Emulated,
  30098. useJit: false,
  30099. missingTranslation: options.missingTranslation,
  30100. preserveWhitespaces: options.preserveWhitespaces,
  30101. strictInjectionParameters: options.strictInjectionParameters,
  30102. });
  30103. var normalizer = new DirectiveNormalizer({ get: function (url) { return compilerHost.loadResource(url); } }, urlResolver, htmlParser, config);
  30104. var expressionParser = new Parser$1(new Lexer());
  30105. var elementSchemaRegistry = new DomElementSchemaRegistry();
  30106. var tmplParser = new TemplateParser(config, staticReflector, expressionParser, elementSchemaRegistry, htmlParser, console, []);
  30107. var resolver = new CompileMetadataResolver(config, htmlParser, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector, errorCollector);
  30108. // TODO(vicb): do not pass options.i18nFormat here
  30109. var viewCompiler = new ViewCompiler(staticReflector);
  30110. var typeCheckCompiler = new TypeCheckCompiler(options, staticReflector);
  30111. var compiler = new AotCompiler(config, options, compilerHost, staticReflector, resolver, tmplParser, new StyleCompiler(urlResolver), viewCompiler, typeCheckCompiler, new NgModuleCompiler(staticReflector), new InjectableCompiler(staticReflector, !!options.enableIvy), new TypeScriptEmitter(), summaryResolver, symbolResolver);
  30112. return { compiler: compiler, reflector: staticReflector };
  30113. }
  30114. var SummaryResolver = /** @class */ (function () {
  30115. function SummaryResolver() {
  30116. }
  30117. return SummaryResolver;
  30118. }());
  30119. var JitSummaryResolver = /** @class */ (function () {
  30120. function JitSummaryResolver() {
  30121. this._summaries = new Map();
  30122. }
  30123. JitSummaryResolver.prototype.isLibraryFile = function () {
  30124. return false;
  30125. };
  30126. JitSummaryResolver.prototype.toSummaryFileName = function (fileName) {
  30127. return fileName;
  30128. };
  30129. JitSummaryResolver.prototype.fromSummaryFileName = function (fileName) {
  30130. return fileName;
  30131. };
  30132. JitSummaryResolver.prototype.resolveSummary = function (reference) {
  30133. return this._summaries.get(reference) || null;
  30134. };
  30135. JitSummaryResolver.prototype.getSymbolsOf = function () {
  30136. return [];
  30137. };
  30138. JitSummaryResolver.prototype.getImportAs = function (reference) {
  30139. return reference;
  30140. };
  30141. JitSummaryResolver.prototype.getKnownModuleName = function (fileName) {
  30142. return null;
  30143. };
  30144. JitSummaryResolver.prototype.addSummary = function (summary) {
  30145. this._summaries.set(summary.symbol, summary);
  30146. };
  30147. return JitSummaryResolver;
  30148. }());
  30149. function interpretStatements(statements, reflector) {
  30150. var ctx = new _ExecutionContext(null, null, null, new Map());
  30151. var visitor = new StatementInterpreter(reflector);
  30152. visitor.visitAllStatements(statements, ctx);
  30153. var result = {};
  30154. ctx.exports.forEach(function (exportName) {
  30155. result[exportName] = ctx.vars.get(exportName);
  30156. });
  30157. return result;
  30158. }
  30159. function _executeFunctionStatements(varNames, varValues, statements, ctx, visitor) {
  30160. var childCtx = ctx.createChildWihtLocalVars();
  30161. for (var i = 0; i < varNames.length; i++) {
  30162. childCtx.vars.set(varNames[i], varValues[i]);
  30163. }
  30164. var result = visitor.visitAllStatements(statements, childCtx);
  30165. return result ? result.value : null;
  30166. }
  30167. var _ExecutionContext = /** @class */ (function () {
  30168. function _ExecutionContext(parent, instance, className, vars) {
  30169. this.parent = parent;
  30170. this.instance = instance;
  30171. this.className = className;
  30172. this.vars = vars;
  30173. this.exports = [];
  30174. }
  30175. _ExecutionContext.prototype.createChildWihtLocalVars = function () {
  30176. return new _ExecutionContext(this, this.instance, this.className, new Map());
  30177. };
  30178. return _ExecutionContext;
  30179. }());
  30180. var ReturnValue = /** @class */ (function () {
  30181. function ReturnValue(value) {
  30182. this.value = value;
  30183. }
  30184. return ReturnValue;
  30185. }());
  30186. function createDynamicClass(_classStmt, _ctx, _visitor) {
  30187. var propertyDescriptors = {};
  30188. _classStmt.getters.forEach(function (getter) {
  30189. // Note: use `function` instead of arrow function to capture `this`
  30190. propertyDescriptors[getter.name] = {
  30191. configurable: false,
  30192. get: function () {
  30193. var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
  30194. return _executeFunctionStatements([], [], getter.body, instanceCtx, _visitor);
  30195. }
  30196. };
  30197. });
  30198. _classStmt.methods.forEach(function (method) {
  30199. var paramNames = method.params.map(function (param) { return param.name; });
  30200. // Note: use `function` instead of arrow function to capture `this`
  30201. propertyDescriptors[method.name] = {
  30202. writable: false,
  30203. configurable: false,
  30204. value: function () {
  30205. var args = [];
  30206. for (var _i = 0; _i < arguments.length; _i++) {
  30207. args[_i] = arguments[_i];
  30208. }
  30209. var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
  30210. return _executeFunctionStatements(paramNames, args, method.body, instanceCtx, _visitor);
  30211. }
  30212. };
  30213. });
  30214. var ctorParamNames = _classStmt.constructorMethod.params.map(function (param) { return param.name; });
  30215. // Note: use `function` instead of arrow function to capture `this`
  30216. var ctor = function () {
  30217. var _this = this;
  30218. var args = [];
  30219. for (var _i = 0; _i < arguments.length; _i++) {
  30220. args[_i] = arguments[_i];
  30221. }
  30222. var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
  30223. _classStmt.fields.forEach(function (field) {
  30224. _this[field.name] = undefined;
  30225. });
  30226. _executeFunctionStatements(ctorParamNames, args, _classStmt.constructorMethod.body, instanceCtx, _visitor);
  30227. };
  30228. var superClass = _classStmt.parent ? _classStmt.parent.visitExpression(_visitor, _ctx) : Object;
  30229. ctor.prototype = Object.create(superClass.prototype, propertyDescriptors);
  30230. return ctor;
  30231. }
  30232. var StatementInterpreter = /** @class */ (function () {
  30233. function StatementInterpreter(reflector) {
  30234. this.reflector = reflector;
  30235. }
  30236. StatementInterpreter.prototype.debugAst = function (ast) {
  30237. return debugOutputAstAsTypeScript(ast);
  30238. };
  30239. StatementInterpreter.prototype.visitDeclareVarStmt = function (stmt, ctx) {
  30240. var initialValue = stmt.value ? stmt.value.visitExpression(this, ctx) : undefined;
  30241. ctx.vars.set(stmt.name, initialValue);
  30242. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  30243. ctx.exports.push(stmt.name);
  30244. }
  30245. return null;
  30246. };
  30247. StatementInterpreter.prototype.visitWriteVarExpr = function (expr, ctx) {
  30248. var value = expr.value.visitExpression(this, ctx);
  30249. var currCtx = ctx;
  30250. while (currCtx != null) {
  30251. if (currCtx.vars.has(expr.name)) {
  30252. currCtx.vars.set(expr.name, value);
  30253. return value;
  30254. }
  30255. currCtx = currCtx.parent;
  30256. }
  30257. throw new Error("Not declared variable " + expr.name);
  30258. };
  30259. StatementInterpreter.prototype.visitWrappedNodeExpr = function (ast, ctx) {
  30260. throw new Error('Cannot interpret a WrappedNodeExpr.');
  30261. };
  30262. StatementInterpreter.prototype.visitTypeofExpr = function (ast, ctx) {
  30263. throw new Error('Cannot interpret a TypeofExpr');
  30264. };
  30265. StatementInterpreter.prototype.visitReadVarExpr = function (ast, ctx) {
  30266. var varName = ast.name;
  30267. if (ast.builtin != null) {
  30268. switch (ast.builtin) {
  30269. case exports.BuiltinVar.Super:
  30270. return Object.getPrototypeOf(ctx.instance);
  30271. case exports.BuiltinVar.This:
  30272. return ctx.instance;
  30273. case exports.BuiltinVar.CatchError:
  30274. varName = CATCH_ERROR_VAR$2;
  30275. break;
  30276. case exports.BuiltinVar.CatchStack:
  30277. varName = CATCH_STACK_VAR$2;
  30278. break;
  30279. default:
  30280. throw new Error("Unknown builtin variable " + ast.builtin);
  30281. }
  30282. }
  30283. var currCtx = ctx;
  30284. while (currCtx != null) {
  30285. if (currCtx.vars.has(varName)) {
  30286. return currCtx.vars.get(varName);
  30287. }
  30288. currCtx = currCtx.parent;
  30289. }
  30290. throw new Error("Not declared variable " + varName);
  30291. };
  30292. StatementInterpreter.prototype.visitWriteKeyExpr = function (expr, ctx) {
  30293. var receiver = expr.receiver.visitExpression(this, ctx);
  30294. var index = expr.index.visitExpression(this, ctx);
  30295. var value = expr.value.visitExpression(this, ctx);
  30296. receiver[index] = value;
  30297. return value;
  30298. };
  30299. StatementInterpreter.prototype.visitWritePropExpr = function (expr, ctx) {
  30300. var receiver = expr.receiver.visitExpression(this, ctx);
  30301. var value = expr.value.visitExpression(this, ctx);
  30302. receiver[expr.name] = value;
  30303. return value;
  30304. };
  30305. StatementInterpreter.prototype.visitInvokeMethodExpr = function (expr, ctx) {
  30306. var receiver = expr.receiver.visitExpression(this, ctx);
  30307. var args = this.visitAllExpressions(expr.args, ctx);
  30308. var result;
  30309. if (expr.builtin != null) {
  30310. switch (expr.builtin) {
  30311. case exports.BuiltinMethod.ConcatArray:
  30312. result = receiver.concat.apply(receiver, __spreadArray([], __read(args)));
  30313. break;
  30314. case exports.BuiltinMethod.SubscribeObservable:
  30315. result = receiver.subscribe({ next: args[0] });
  30316. break;
  30317. case exports.BuiltinMethod.Bind:
  30318. result = receiver.bind.apply(receiver, __spreadArray([], __read(args)));
  30319. break;
  30320. default:
  30321. throw new Error("Unknown builtin method " + expr.builtin);
  30322. }
  30323. }
  30324. else {
  30325. result = receiver[expr.name].apply(receiver, args);
  30326. }
  30327. return result;
  30328. };
  30329. StatementInterpreter.prototype.visitInvokeFunctionExpr = function (stmt, ctx) {
  30330. var args = this.visitAllExpressions(stmt.args, ctx);
  30331. var fnExpr = stmt.fn;
  30332. if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === exports.BuiltinVar.Super) {
  30333. ctx.instance.constructor.prototype.constructor.apply(ctx.instance, args);
  30334. return null;
  30335. }
  30336. else {
  30337. var fn = stmt.fn.visitExpression(this, ctx);
  30338. return fn.apply(null, args);
  30339. }
  30340. };
  30341. StatementInterpreter.prototype.visitTaggedTemplateExpr = function (expr, ctx) {
  30342. var templateElements = expr.template.elements.map(function (e) { return e.text; });
  30343. Object.defineProperty(templateElements, 'raw', { value: expr.template.elements.map(function (e) { return e.rawText; }) });
  30344. var args = this.visitAllExpressions(expr.template.expressions, ctx);
  30345. args.unshift(templateElements);
  30346. var tag = expr.tag.visitExpression(this, ctx);
  30347. return tag.apply(null, args);
  30348. };
  30349. StatementInterpreter.prototype.visitReturnStmt = function (stmt, ctx) {
  30350. return new ReturnValue(stmt.value.visitExpression(this, ctx));
  30351. };
  30352. StatementInterpreter.prototype.visitDeclareClassStmt = function (stmt, ctx) {
  30353. var clazz = createDynamicClass(stmt, ctx, this);
  30354. ctx.vars.set(stmt.name, clazz);
  30355. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  30356. ctx.exports.push(stmt.name);
  30357. }
  30358. return null;
  30359. };
  30360. StatementInterpreter.prototype.visitExpressionStmt = function (stmt, ctx) {
  30361. return stmt.expr.visitExpression(this, ctx);
  30362. };
  30363. StatementInterpreter.prototype.visitIfStmt = function (stmt, ctx) {
  30364. var condition = stmt.condition.visitExpression(this, ctx);
  30365. if (condition) {
  30366. return this.visitAllStatements(stmt.trueCase, ctx);
  30367. }
  30368. else if (stmt.falseCase != null) {
  30369. return this.visitAllStatements(stmt.falseCase, ctx);
  30370. }
  30371. return null;
  30372. };
  30373. StatementInterpreter.prototype.visitTryCatchStmt = function (stmt, ctx) {
  30374. try {
  30375. return this.visitAllStatements(stmt.bodyStmts, ctx);
  30376. }
  30377. catch (e) {
  30378. var childCtx = ctx.createChildWihtLocalVars();
  30379. childCtx.vars.set(CATCH_ERROR_VAR$2, e);
  30380. childCtx.vars.set(CATCH_STACK_VAR$2, e.stack);
  30381. return this.visitAllStatements(stmt.catchStmts, childCtx);
  30382. }
  30383. };
  30384. StatementInterpreter.prototype.visitThrowStmt = function (stmt, ctx) {
  30385. throw stmt.error.visitExpression(this, ctx);
  30386. };
  30387. StatementInterpreter.prototype.visitInstantiateExpr = function (ast, ctx) {
  30388. var args = this.visitAllExpressions(ast.args, ctx);
  30389. var clazz = ast.classExpr.visitExpression(this, ctx);
  30390. return new (clazz.bind.apply(clazz, __spreadArray([void 0], __read(args))))();
  30391. };
  30392. StatementInterpreter.prototype.visitLiteralExpr = function (ast, ctx) {
  30393. return ast.value;
  30394. };
  30395. StatementInterpreter.prototype.visitLocalizedString = function (ast, context) {
  30396. return null;
  30397. };
  30398. StatementInterpreter.prototype.visitExternalExpr = function (ast, ctx) {
  30399. return this.reflector.resolveExternalReference(ast.value);
  30400. };
  30401. StatementInterpreter.prototype.visitConditionalExpr = function (ast, ctx) {
  30402. if (ast.condition.visitExpression(this, ctx)) {
  30403. return ast.trueCase.visitExpression(this, ctx);
  30404. }
  30405. else if (ast.falseCase != null) {
  30406. return ast.falseCase.visitExpression(this, ctx);
  30407. }
  30408. return null;
  30409. };
  30410. StatementInterpreter.prototype.visitNotExpr = function (ast, ctx) {
  30411. return !ast.condition.visitExpression(this, ctx);
  30412. };
  30413. StatementInterpreter.prototype.visitAssertNotNullExpr = function (ast, ctx) {
  30414. return ast.condition.visitExpression(this, ctx);
  30415. };
  30416. StatementInterpreter.prototype.visitCastExpr = function (ast, ctx) {
  30417. return ast.value.visitExpression(this, ctx);
  30418. };
  30419. StatementInterpreter.prototype.visitFunctionExpr = function (ast, ctx) {
  30420. var paramNames = ast.params.map(function (param) { return param.name; });
  30421. return _declareFn(paramNames, ast.statements, ctx, this);
  30422. };
  30423. StatementInterpreter.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
  30424. var paramNames = stmt.params.map(function (param) { return param.name; });
  30425. ctx.vars.set(stmt.name, _declareFn(paramNames, stmt.statements, ctx, this));
  30426. if (stmt.hasModifier(exports.StmtModifier.Exported)) {
  30427. ctx.exports.push(stmt.name);
  30428. }
  30429. return null;
  30430. };
  30431. StatementInterpreter.prototype.visitUnaryOperatorExpr = function (ast, ctx) {
  30432. var _this = this;
  30433. var rhs = function () { return ast.expr.visitExpression(_this, ctx); };
  30434. switch (ast.operator) {
  30435. case exports.UnaryOperator.Plus:
  30436. return +rhs();
  30437. case exports.UnaryOperator.Minus:
  30438. return -rhs();
  30439. default:
  30440. throw new Error("Unknown operator " + ast.operator);
  30441. }
  30442. };
  30443. StatementInterpreter.prototype.visitBinaryOperatorExpr = function (ast, ctx) {
  30444. var _this = this;
  30445. var _a;
  30446. var lhs = function () { return ast.lhs.visitExpression(_this, ctx); };
  30447. var rhs = function () { return ast.rhs.visitExpression(_this, ctx); };
  30448. switch (ast.operator) {
  30449. case exports.BinaryOperator.Equals:
  30450. return lhs() == rhs();
  30451. case exports.BinaryOperator.Identical:
  30452. return lhs() === rhs();
  30453. case exports.BinaryOperator.NotEquals:
  30454. return lhs() != rhs();
  30455. case exports.BinaryOperator.NotIdentical:
  30456. return lhs() !== rhs();
  30457. case exports.BinaryOperator.And:
  30458. return lhs() && rhs();
  30459. case exports.BinaryOperator.Or:
  30460. return lhs() || rhs();
  30461. case exports.BinaryOperator.Plus:
  30462. return lhs() + rhs();
  30463. case exports.BinaryOperator.Minus:
  30464. return lhs() - rhs();
  30465. case exports.BinaryOperator.Divide:
  30466. return lhs() / rhs();
  30467. case exports.BinaryOperator.Multiply:
  30468. return lhs() * rhs();
  30469. case exports.BinaryOperator.Modulo:
  30470. return lhs() % rhs();
  30471. case exports.BinaryOperator.Lower:
  30472. return lhs() < rhs();
  30473. case exports.BinaryOperator.LowerEquals:
  30474. return lhs() <= rhs();
  30475. case exports.BinaryOperator.Bigger:
  30476. return lhs() > rhs();
  30477. case exports.BinaryOperator.BiggerEquals:
  30478. return lhs() >= rhs();
  30479. case exports.BinaryOperator.NullishCoalesce:
  30480. return (_a = lhs()) !== null && _a !== void 0 ? _a : rhs();
  30481. default:
  30482. throw new Error("Unknown operator " + ast.operator);
  30483. }
  30484. };
  30485. StatementInterpreter.prototype.visitReadPropExpr = function (ast, ctx) {
  30486. var result;
  30487. var receiver = ast.receiver.visitExpression(this, ctx);
  30488. result = receiver[ast.name];
  30489. return result;
  30490. };
  30491. StatementInterpreter.prototype.visitReadKeyExpr = function (ast, ctx) {
  30492. var receiver = ast.receiver.visitExpression(this, ctx);
  30493. var prop = ast.index.visitExpression(this, ctx);
  30494. return receiver[prop];
  30495. };
  30496. StatementInterpreter.prototype.visitLiteralArrayExpr = function (ast, ctx) {
  30497. return this.visitAllExpressions(ast.entries, ctx);
  30498. };
  30499. StatementInterpreter.prototype.visitLiteralMapExpr = function (ast, ctx) {
  30500. var _this = this;
  30501. var result = {};
  30502. ast.entries.forEach(function (entry) { return result[entry.key] = entry.value.visitExpression(_this, ctx); });
  30503. return result;
  30504. };
  30505. StatementInterpreter.prototype.visitCommaExpr = function (ast, context) {
  30506. var values = this.visitAllExpressions(ast.parts, context);
  30507. return values[values.length - 1];
  30508. };
  30509. StatementInterpreter.prototype.visitAllExpressions = function (expressions, ctx) {
  30510. var _this = this;
  30511. return expressions.map(function (expr) { return expr.visitExpression(_this, ctx); });
  30512. };
  30513. StatementInterpreter.prototype.visitAllStatements = function (statements, ctx) {
  30514. for (var i = 0; i < statements.length; i++) {
  30515. var stmt = statements[i];
  30516. var val = stmt.visitStatement(this, ctx);
  30517. if (val instanceof ReturnValue) {
  30518. return val;
  30519. }
  30520. }
  30521. return null;
  30522. };
  30523. return StatementInterpreter;
  30524. }());
  30525. function _declareFn(varNames, statements, ctx, visitor) {
  30526. return function () {
  30527. var args = [];
  30528. for (var _i = 0; _i < arguments.length; _i++) {
  30529. args[_i] = arguments[_i];
  30530. }
  30531. return _executeFunctionStatements(varNames, args, statements, ctx, visitor);
  30532. };
  30533. }
  30534. var CATCH_ERROR_VAR$2 = 'error';
  30535. var CATCH_STACK_VAR$2 = 'stack';
  30536. /**
  30537. * @license
  30538. * Copyright Google LLC All Rights Reserved.
  30539. *
  30540. * Use of this source code is governed by an MIT-style license that can be
  30541. * found in the LICENSE file at https://angular.io/license
  30542. */
  30543. /**
  30544. * An internal module of the Angular compiler that begins with component types,
  30545. * extracts templates, and eventually produces a compiled version of the component
  30546. * ready for linking into an application.
  30547. *
  30548. * @security When compiling templates at runtime, you must ensure that the entire template comes
  30549. * from a trusted source. Attacker-controlled data introduced by a template could expose your
  30550. * application to XSS risks. For more detail, see the [Security Guide](https://g.co/ng/security).
  30551. */
  30552. var JitCompiler = /** @class */ (function () {
  30553. function JitCompiler(_metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _ngModuleCompiler, _summaryResolver, _reflector, _jitEvaluator, _compilerConfig, _console, getExtraNgModuleProviders) {
  30554. this._metadataResolver = _metadataResolver;
  30555. this._templateParser = _templateParser;
  30556. this._styleCompiler = _styleCompiler;
  30557. this._viewCompiler = _viewCompiler;
  30558. this._ngModuleCompiler = _ngModuleCompiler;
  30559. this._summaryResolver = _summaryResolver;
  30560. this._reflector = _reflector;
  30561. this._jitEvaluator = _jitEvaluator;
  30562. this._compilerConfig = _compilerConfig;
  30563. this._console = _console;
  30564. this.getExtraNgModuleProviders = getExtraNgModuleProviders;
  30565. this._compiledTemplateCache = new Map();
  30566. this._compiledHostTemplateCache = new Map();
  30567. this._compiledDirectiveWrapperCache = new Map();
  30568. this._compiledNgModuleCache = new Map();
  30569. this._sharedStylesheetCount = 0;
  30570. this._addedAotSummaries = new Set();
  30571. }
  30572. JitCompiler.prototype.compileModuleSync = function (moduleType) {
  30573. return SyncAsync.assertSync(this._compileModuleAndComponents(moduleType, true));
  30574. };
  30575. JitCompiler.prototype.compileModuleAsync = function (moduleType) {
  30576. return Promise.resolve(this._compileModuleAndComponents(moduleType, false));
  30577. };
  30578. JitCompiler.prototype.compileModuleAndAllComponentsSync = function (moduleType) {
  30579. return SyncAsync.assertSync(this._compileModuleAndAllComponents(moduleType, true));
  30580. };
  30581. JitCompiler.prototype.compileModuleAndAllComponentsAsync = function (moduleType) {
  30582. return Promise.resolve(this._compileModuleAndAllComponents(moduleType, false));
  30583. };
  30584. JitCompiler.prototype.getComponentFactory = function (component) {
  30585. var summary = this._metadataResolver.getDirectiveSummary(component);
  30586. return summary.componentFactory;
  30587. };
  30588. JitCompiler.prototype.loadAotSummaries = function (summaries) {
  30589. this.clearCache();
  30590. this._addAotSummaries(summaries);
  30591. };
  30592. JitCompiler.prototype._addAotSummaries = function (fn) {
  30593. if (this._addedAotSummaries.has(fn)) {
  30594. return;
  30595. }
  30596. this._addedAotSummaries.add(fn);
  30597. var summaries = fn();
  30598. for (var i = 0; i < summaries.length; i++) {
  30599. var entry = summaries[i];
  30600. if (typeof entry === 'function') {
  30601. this._addAotSummaries(entry);
  30602. }
  30603. else {
  30604. var summary = entry;
  30605. this._summaryResolver.addSummary({ symbol: summary.type.reference, metadata: null, type: summary });
  30606. }
  30607. }
  30608. };
  30609. JitCompiler.prototype.hasAotSummary = function (ref) {
  30610. return !!this._summaryResolver.resolveSummary(ref);
  30611. };
  30612. JitCompiler.prototype._filterJitIdentifiers = function (ids) {
  30613. var _this = this;
  30614. return ids.map(function (mod) { return mod.reference; }).filter(function (ref) { return !_this.hasAotSummary(ref); });
  30615. };
  30616. JitCompiler.prototype._compileModuleAndComponents = function (moduleType, isSync) {
  30617. var _this = this;
  30618. return SyncAsync.then(this._loadModules(moduleType, isSync), function () {
  30619. _this._compileComponents(moduleType, null);
  30620. return _this._compileModule(moduleType);
  30621. });
  30622. };
  30623. JitCompiler.prototype._compileModuleAndAllComponents = function (moduleType, isSync) {
  30624. var _this = this;
  30625. return SyncAsync.then(this._loadModules(moduleType, isSync), function () {
  30626. var componentFactories = [];
  30627. _this._compileComponents(moduleType, componentFactories);
  30628. return {
  30629. ngModuleFactory: _this._compileModule(moduleType),
  30630. componentFactories: componentFactories
  30631. };
  30632. });
  30633. };
  30634. JitCompiler.prototype._loadModules = function (mainModule, isSync) {
  30635. var _this = this;
  30636. var loading = [];
  30637. var mainNgModule = this._metadataResolver.getNgModuleMetadata(mainModule);
  30638. // Note: for runtime compilation, we want to transitively compile all modules,
  30639. // so we also need to load the declared directives / pipes for all nested modules.
  30640. this._filterJitIdentifiers(mainNgModule.transitiveModule.modules).forEach(function (nestedNgModule) {
  30641. // getNgModuleMetadata only returns null if the value passed in is not an NgModule
  30642. var moduleMeta = _this._metadataResolver.getNgModuleMetadata(nestedNgModule);
  30643. _this._filterJitIdentifiers(moduleMeta.declaredDirectives).forEach(function (ref) {
  30644. var promise = _this._metadataResolver.loadDirectiveMetadata(moduleMeta.type.reference, ref, isSync);
  30645. if (promise) {
  30646. loading.push(promise);
  30647. }
  30648. });
  30649. _this._filterJitIdentifiers(moduleMeta.declaredPipes)
  30650. .forEach(function (ref) { return _this._metadataResolver.getOrLoadPipeMetadata(ref); });
  30651. });
  30652. return SyncAsync.all(loading);
  30653. };
  30654. JitCompiler.prototype._compileModule = function (moduleType) {
  30655. var ngModuleFactory = this._compiledNgModuleCache.get(moduleType);
  30656. if (!ngModuleFactory) {
  30657. var moduleMeta = this._metadataResolver.getNgModuleMetadata(moduleType);
  30658. // Always provide a bound Compiler
  30659. var extraProviders = this.getExtraNgModuleProviders(moduleMeta.type.reference);
  30660. var outputCtx = createOutputContext();
  30661. var compileResult = this._ngModuleCompiler.compile(outputCtx, moduleMeta, extraProviders);
  30662. ngModuleFactory = this._interpretOrJit(ngModuleJitUrl(moduleMeta), outputCtx.statements)[compileResult.ngModuleFactoryVar];
  30663. this._compiledNgModuleCache.set(moduleMeta.type.reference, ngModuleFactory);
  30664. }
  30665. return ngModuleFactory;
  30666. };
  30667. /**
  30668. * @internal
  30669. */
  30670. JitCompiler.prototype._compileComponents = function (mainModule, allComponentFactories) {
  30671. var _this = this;
  30672. var ngModule = this._metadataResolver.getNgModuleMetadata(mainModule);
  30673. var moduleByJitDirective = new Map();
  30674. var templates = new Set();
  30675. var transJitModules = this._filterJitIdentifiers(ngModule.transitiveModule.modules);
  30676. transJitModules.forEach(function (localMod) {
  30677. var localModuleMeta = _this._metadataResolver.getNgModuleMetadata(localMod);
  30678. _this._filterJitIdentifiers(localModuleMeta.declaredDirectives).forEach(function (dirRef) {
  30679. moduleByJitDirective.set(dirRef, localModuleMeta);
  30680. var dirMeta = _this._metadataResolver.getDirectiveMetadata(dirRef);
  30681. if (dirMeta.isComponent) {
  30682. templates.add(_this._createCompiledTemplate(dirMeta, localModuleMeta));
  30683. if (allComponentFactories) {
  30684. var template = _this._createCompiledHostTemplate(dirMeta.type.reference, localModuleMeta);
  30685. templates.add(template);
  30686. allComponentFactories.push(dirMeta.componentFactory);
  30687. }
  30688. }
  30689. });
  30690. });
  30691. transJitModules.forEach(function (localMod) {
  30692. var localModuleMeta = _this._metadataResolver.getNgModuleMetadata(localMod);
  30693. _this._filterJitIdentifiers(localModuleMeta.declaredDirectives).forEach(function (dirRef) {
  30694. var dirMeta = _this._metadataResolver.getDirectiveMetadata(dirRef);
  30695. if (dirMeta.isComponent) {
  30696. dirMeta.entryComponents.forEach(function (entryComponentType) {
  30697. var moduleMeta = moduleByJitDirective.get(entryComponentType.componentType);
  30698. templates.add(_this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
  30699. });
  30700. }
  30701. });
  30702. localModuleMeta.entryComponents.forEach(function (entryComponentType) {
  30703. if (!_this.hasAotSummary(entryComponentType.componentType)) {
  30704. var moduleMeta = moduleByJitDirective.get(entryComponentType.componentType);
  30705. templates.add(_this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
  30706. }
  30707. });
  30708. });
  30709. templates.forEach(function (template) { return _this._compileTemplate(template); });
  30710. };
  30711. JitCompiler.prototype.clearCacheFor = function (type) {
  30712. this._compiledNgModuleCache.delete(type);
  30713. this._metadataResolver.clearCacheFor(type);
  30714. this._compiledHostTemplateCache.delete(type);
  30715. var compiledTemplate = this._compiledTemplateCache.get(type);
  30716. if (compiledTemplate) {
  30717. this._compiledTemplateCache.delete(type);
  30718. }
  30719. };
  30720. JitCompiler.prototype.clearCache = function () {
  30721. // Note: don't clear the _addedAotSummaries, as they don't change!
  30722. this._metadataResolver.clearCache();
  30723. this._compiledTemplateCache.clear();
  30724. this._compiledHostTemplateCache.clear();
  30725. this._compiledNgModuleCache.clear();
  30726. };
  30727. JitCompiler.prototype._createCompiledHostTemplate = function (compType, ngModule) {
  30728. if (!ngModule) {
  30729. throw new Error("Component " + stringify(compType) + " is not part of any NgModule or the module has not been imported into your module.");
  30730. }
  30731. var compiledTemplate = this._compiledHostTemplateCache.get(compType);
  30732. if (!compiledTemplate) {
  30733. var compMeta = this._metadataResolver.getDirectiveMetadata(compType);
  30734. assertComponent(compMeta);
  30735. var hostMeta = this._metadataResolver.getHostComponentMetadata(compMeta, compMeta.componentFactory.viewDefFactory);
  30736. compiledTemplate =
  30737. new CompiledTemplate(true, compMeta.type, hostMeta, ngModule, [compMeta.type]);
  30738. this._compiledHostTemplateCache.set(compType, compiledTemplate);
  30739. }
  30740. return compiledTemplate;
  30741. };
  30742. JitCompiler.prototype._createCompiledTemplate = function (compMeta, ngModule) {
  30743. var compiledTemplate = this._compiledTemplateCache.get(compMeta.type.reference);
  30744. if (!compiledTemplate) {
  30745. assertComponent(compMeta);
  30746. compiledTemplate = new CompiledTemplate(false, compMeta.type, compMeta, ngModule, ngModule.transitiveModule.directives);
  30747. this._compiledTemplateCache.set(compMeta.type.reference, compiledTemplate);
  30748. }
  30749. return compiledTemplate;
  30750. };
  30751. JitCompiler.prototype._compileTemplate = function (template) {
  30752. var _this = this;
  30753. if (template.isCompiled) {
  30754. return;
  30755. }
  30756. var compMeta = template.compMeta;
  30757. var externalStylesheetsByModuleUrl = new Map();
  30758. var outputContext = createOutputContext();
  30759. var componentStylesheet = this._styleCompiler.compileComponent(outputContext, compMeta);
  30760. compMeta.template.externalStylesheets.forEach(function (stylesheetMeta) {
  30761. var compiledStylesheet = _this._styleCompiler.compileStyles(createOutputContext(), compMeta, stylesheetMeta);
  30762. externalStylesheetsByModuleUrl.set(stylesheetMeta.moduleUrl, compiledStylesheet);
  30763. });
  30764. this._resolveStylesCompileResult(componentStylesheet, externalStylesheetsByModuleUrl);
  30765. var pipes = template.ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
  30766. var _a = this._parseTemplate(compMeta, template.ngModule, template.directives), parsedTemplate = _a.template, usedPipes = _a.pipes;
  30767. var compileResult = this._viewCompiler.compileComponent(outputContext, compMeta, parsedTemplate, variable(componentStylesheet.stylesVar), usedPipes);
  30768. var evalResult = this._interpretOrJit(templateJitUrl(template.ngModule.type, template.compMeta), outputContext.statements);
  30769. var viewClass = evalResult[compileResult.viewClassVar];
  30770. var rendererType = evalResult[compileResult.rendererTypeVar];
  30771. template.compiled(viewClass, rendererType);
  30772. };
  30773. JitCompiler.prototype._parseTemplate = function (compMeta, ngModule, directiveIdentifiers) {
  30774. var _this = this;
  30775. // Note: ! is ok here as components always have a template.
  30776. var preserveWhitespaces = compMeta.template.preserveWhitespaces;
  30777. var directives = directiveIdentifiers.map(function (dir) { return _this._metadataResolver.getDirectiveSummary(dir.reference); });
  30778. var pipes = ngModule.transitiveModule.pipes.map(function (pipe) { return _this._metadataResolver.getPipeSummary(pipe.reference); });
  30779. return this._templateParser.parse(compMeta, compMeta.template.htmlAst, directives, pipes, ngModule.schemas, templateSourceUrl(ngModule.type, compMeta, compMeta.template), preserveWhitespaces);
  30780. };
  30781. JitCompiler.prototype._resolveStylesCompileResult = function (result, externalStylesheetsByModuleUrl) {
  30782. var _this = this;
  30783. result.dependencies.forEach(function (dep, i) {
  30784. var nestedCompileResult = externalStylesheetsByModuleUrl.get(dep.moduleUrl);
  30785. var nestedStylesArr = _this._resolveAndEvalStylesCompileResult(nestedCompileResult, externalStylesheetsByModuleUrl);
  30786. dep.setValue(nestedStylesArr);
  30787. });
  30788. };
  30789. JitCompiler.prototype._resolveAndEvalStylesCompileResult = function (result, externalStylesheetsByModuleUrl) {
  30790. this._resolveStylesCompileResult(result, externalStylesheetsByModuleUrl);
  30791. return this._interpretOrJit(sharedStylesheetJitUrl(result.meta, this._sharedStylesheetCount++), result.outputCtx.statements)[result.stylesVar];
  30792. };
  30793. JitCompiler.prototype._interpretOrJit = function (sourceUrl, statements) {
  30794. if (!this._compilerConfig.useJit) {
  30795. return interpretStatements(statements, this._reflector);
  30796. }
  30797. else {
  30798. return this._jitEvaluator.evaluateStatements(sourceUrl, statements, this._reflector, this._compilerConfig.jitDevMode);
  30799. }
  30800. };
  30801. return JitCompiler;
  30802. }());
  30803. var CompiledTemplate = /** @class */ (function () {
  30804. function CompiledTemplate(isHost, compType, compMeta, ngModule, directives) {
  30805. this.isHost = isHost;
  30806. this.compType = compType;
  30807. this.compMeta = compMeta;
  30808. this.ngModule = ngModule;
  30809. this.directives = directives;
  30810. this._viewClass = null;
  30811. this.isCompiled = false;
  30812. }
  30813. CompiledTemplate.prototype.compiled = function (viewClass, rendererType) {
  30814. this._viewClass = viewClass;
  30815. this.compMeta.componentViewType.setDelegate(viewClass);
  30816. for (var prop in rendererType) {
  30817. this.compMeta.rendererType[prop] = rendererType[prop];
  30818. }
  30819. this.isCompiled = true;
  30820. };
  30821. return CompiledTemplate;
  30822. }());
  30823. function assertComponent(meta) {
  30824. if (!meta.isComponent) {
  30825. throw new Error("Could not compile '" + identifierName(meta.type) + "' because it is not a component.");
  30826. }
  30827. }
  30828. function createOutputContext() {
  30829. var importExpr$1 = function (symbol) { return importExpr({ name: identifierName(symbol), moduleName: null, runtime: symbol }); };
  30830. return { statements: [], genFilePath: '', importExpr: importExpr$1, constantPool: new ConstantPool() };
  30831. }
  30832. /**
  30833. * @license
  30834. * Copyright Google LLC All Rights Reserved.
  30835. *
  30836. * Use of this source code is governed by an MIT-style license that can be
  30837. * found in the LICENSE file at https://angular.io/license
  30838. */
  30839. /**
  30840. * Provides access to reflection data about symbols that the compiler needs.
  30841. */
  30842. var CompileReflector = /** @class */ (function () {
  30843. function CompileReflector() {
  30844. }
  30845. return CompileReflector;
  30846. }());
  30847. /**
  30848. * @license
  30849. * Copyright Google LLC All Rights Reserved.
  30850. *
  30851. * Use of this source code is governed by an MIT-style license that can be
  30852. * found in the LICENSE file at https://angular.io/license
  30853. */
  30854. /**
  30855. * Create a {@link UrlResolver} with no package prefix.
  30856. */
  30857. function createUrlResolverWithoutPackagePrefix() {
  30858. return new UrlResolver();
  30859. }
  30860. function createOfflineCompileUrlResolver() {
  30861. return new UrlResolver('.');
  30862. }
  30863. var UrlResolver = /** @class */ (function () {
  30864. function UrlResolverImpl(_packagePrefix) {
  30865. if (_packagePrefix === void 0) { _packagePrefix = null; }
  30866. this._packagePrefix = _packagePrefix;
  30867. }
  30868. /**
  30869. * Resolves the `url` given the `baseUrl`:
  30870. * - when the `url` is null, the `baseUrl` is returned,
  30871. * - if `url` is relative ('path/to/here', './path/to/here'), the resolved url is a combination of
  30872. * `baseUrl` and `url`,
  30873. * - if `url` is absolute (it has a scheme: 'http://', 'https://' or start with '/'), the `url` is
  30874. * returned as is (ignoring the `baseUrl`)
  30875. */
  30876. UrlResolverImpl.prototype.resolve = function (baseUrl, url) {
  30877. var resolvedUrl = url;
  30878. if (baseUrl != null && baseUrl.length > 0) {
  30879. resolvedUrl = _resolveUrl(baseUrl, resolvedUrl);
  30880. }
  30881. var resolvedParts = _split(resolvedUrl);
  30882. var prefix = this._packagePrefix;
  30883. if (prefix != null && resolvedParts != null &&
  30884. resolvedParts[_ComponentIndex.Scheme] == 'package') {
  30885. var path = resolvedParts[_ComponentIndex.Path];
  30886. prefix = prefix.replace(/\/+$/, '');
  30887. path = path.replace(/^\/+/, '');
  30888. return prefix + "/" + path;
  30889. }
  30890. return resolvedUrl;
  30891. };
  30892. return UrlResolverImpl;
  30893. }());
  30894. /**
  30895. * Extract the scheme of a URL.
  30896. */
  30897. function getUrlScheme(url) {
  30898. var match = _split(url);
  30899. return (match && match[_ComponentIndex.Scheme]) || '';
  30900. }
  30901. // The code below is adapted from Traceur:
  30902. // https://github.com/google/traceur-compiler/blob/9511c1dafa972bf0de1202a8a863bad02f0f95a8/src/runtime/url.js
  30903. /**
  30904. * Builds a URI string from already-encoded parts.
  30905. *
  30906. * No encoding is performed. Any component may be omitted as either null or
  30907. * undefined.
  30908. *
  30909. * @param opt_scheme The scheme such as 'http'.
  30910. * @param opt_userInfo The user name before the '@'.
  30911. * @param opt_domain The domain such as 'www.google.com', already
  30912. * URI-encoded.
  30913. * @param opt_port The port number.
  30914. * @param opt_path The path, already URI-encoded. If it is not
  30915. * empty, it must begin with a slash.
  30916. * @param opt_queryData The URI-encoded query data.
  30917. * @param opt_fragment The URI-encoded fragment identifier.
  30918. * @return The fully combined URI.
  30919. */
  30920. function _buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
  30921. var out = [];
  30922. if (opt_scheme != null) {
  30923. out.push(opt_scheme + ':');
  30924. }
  30925. if (opt_domain != null) {
  30926. out.push('//');
  30927. if (opt_userInfo != null) {
  30928. out.push(opt_userInfo + '@');
  30929. }
  30930. out.push(opt_domain);
  30931. if (opt_port != null) {
  30932. out.push(':' + opt_port);
  30933. }
  30934. }
  30935. if (opt_path != null) {
  30936. out.push(opt_path);
  30937. }
  30938. if (opt_queryData != null) {
  30939. out.push('?' + opt_queryData);
  30940. }
  30941. if (opt_fragment != null) {
  30942. out.push('#' + opt_fragment);
  30943. }
  30944. return out.join('');
  30945. }
  30946. /**
  30947. * A regular expression for breaking a URI into its component parts.
  30948. *
  30949. * {@link https://tools.ietf.org/html/rfc3986#appendix-B} says
  30950. * As the "first-match-wins" algorithm is identical to the "greedy"
  30951. * disambiguation method used by POSIX regular expressions, it is natural and
  30952. * commonplace to use a regular expression for parsing the potential five
  30953. * components of a URI reference.
  30954. *
  30955. * The following line is the regular expression for breaking-down a
  30956. * well-formed URI reference into its components.
  30957. *
  30958. * <pre>
  30959. * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
  30960. * 12 3 4 5 6 7 8 9
  30961. * </pre>
  30962. *
  30963. * The numbers in the second line above are only to assist readability; they
  30964. * indicate the reference points for each subexpression (i.e., each paired
  30965. * parenthesis). We refer to the value matched for subexpression <n> as $<n>.
  30966. * For example, matching the above expression to
  30967. * <pre>
  30968. * http://www.ics.uci.edu/pub/ietf/uri/#Related
  30969. * </pre>
  30970. * results in the following subexpression matches:
  30971. * <pre>
  30972. * $1 = http:
  30973. * $2 = http
  30974. * $3 = //www.ics.uci.edu
  30975. * $4 = www.ics.uci.edu
  30976. * $5 = /pub/ietf/uri/
  30977. * $6 = <undefined>
  30978. * $7 = <undefined>
  30979. * $8 = #Related
  30980. * $9 = Related
  30981. * </pre>
  30982. * where <undefined> indicates that the component is not present, as is the
  30983. * case for the query component in the above example. Therefore, we can
  30984. * determine the value of the five components as
  30985. * <pre>
  30986. * scheme = $2
  30987. * authority = $4
  30988. * path = $5
  30989. * query = $7
  30990. * fragment = $9
  30991. * </pre>
  30992. *
  30993. * The regular expression has been modified slightly to expose the
  30994. * userInfo, domain, and port separately from the authority.
  30995. * The modified version yields
  30996. * <pre>
  30997. * $1 = http scheme
  30998. * $2 = <undefined> userInfo -\
  30999. * $3 = www.ics.uci.edu domain | authority
  31000. * $4 = <undefined> port -/
  31001. * $5 = /pub/ietf/uri/ path
  31002. * $6 = <undefined> query without ?
  31003. * $7 = Related fragment without #
  31004. * </pre>
  31005. * @internal
  31006. */
  31007. var _splitRe = new RegExp('^' +
  31008. '(?:' +
  31009. '([^:/?#.]+)' + // scheme - ignore special characters
  31010. // used by other URL parts such as :,
  31011. // ?, /, #, and .
  31012. ':)?' +
  31013. '(?://' +
  31014. '(?:([^/?#]*)@)?' + // userInfo
  31015. '([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters,
  31016. // digits, dashes, dots, percent
  31017. // escapes, and unicode characters.
  31018. '(?::([0-9]+))?' + // port
  31019. ')?' +
  31020. '([^?#]+)?' + // path
  31021. '(?:\\?([^#]*))?' + // query
  31022. '(?:#(.*))?' + // fragment
  31023. '$');
  31024. /**
  31025. * The index of each URI component in the return value of goog.uri.utils.split.
  31026. * @enum {number}
  31027. */
  31028. var _ComponentIndex;
  31029. (function (_ComponentIndex) {
  31030. _ComponentIndex[_ComponentIndex["Scheme"] = 1] = "Scheme";
  31031. _ComponentIndex[_ComponentIndex["UserInfo"] = 2] = "UserInfo";
  31032. _ComponentIndex[_ComponentIndex["Domain"] = 3] = "Domain";
  31033. _ComponentIndex[_ComponentIndex["Port"] = 4] = "Port";
  31034. _ComponentIndex[_ComponentIndex["Path"] = 5] = "Path";
  31035. _ComponentIndex[_ComponentIndex["QueryData"] = 6] = "QueryData";
  31036. _ComponentIndex[_ComponentIndex["Fragment"] = 7] = "Fragment";
  31037. })(_ComponentIndex || (_ComponentIndex = {}));
  31038. /**
  31039. * Splits a URI into its component parts.
  31040. *
  31041. * Each component can be accessed via the component indices; for example:
  31042. * <pre>
  31043. * goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA];
  31044. * </pre>
  31045. *
  31046. * @param uri The URI string to examine.
  31047. * @return Each component still URI-encoded.
  31048. * Each component that is present will contain the encoded value, whereas
  31049. * components that are not present will be undefined or empty, depending
  31050. * on the browser's regular expression implementation. Never null, since
  31051. * arbitrary strings may still look like path names.
  31052. */
  31053. function _split(uri) {
  31054. return uri.match(_splitRe);
  31055. }
  31056. /**
  31057. * Removes dot segments in given path component, as described in
  31058. * RFC 3986, section 5.2.4.
  31059. *
  31060. * @param path A non-empty path component.
  31061. * @return Path component with removed dot segments.
  31062. */
  31063. function _removeDotSegments(path) {
  31064. if (path == '/')
  31065. return '/';
  31066. var leadingSlash = path[0] == '/' ? '/' : '';
  31067. var trailingSlash = path[path.length - 1] === '/' ? '/' : '';
  31068. var segments = path.split('/');
  31069. var out = [];
  31070. var up = 0;
  31071. for (var pos = 0; pos < segments.length; pos++) {
  31072. var segment = segments[pos];
  31073. switch (segment) {
  31074. case '':
  31075. case '.':
  31076. break;
  31077. case '..':
  31078. if (out.length > 0) {
  31079. out.pop();
  31080. }
  31081. else {
  31082. up++;
  31083. }
  31084. break;
  31085. default:
  31086. out.push(segment);
  31087. }
  31088. }
  31089. if (leadingSlash == '') {
  31090. while (up-- > 0) {
  31091. out.unshift('..');
  31092. }
  31093. if (out.length === 0)
  31094. out.push('.');
  31095. }
  31096. return leadingSlash + out.join('/') + trailingSlash;
  31097. }
  31098. /**
  31099. * Takes an array of the parts from split and canonicalizes the path part
  31100. * and then joins all the parts.
  31101. */
  31102. function _joinAndCanonicalizePath(parts) {
  31103. var path = parts[_ComponentIndex.Path];
  31104. path = path == null ? '' : _removeDotSegments(path);
  31105. parts[_ComponentIndex.Path] = path;
  31106. return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]);
  31107. }
  31108. /**
  31109. * Resolves a URL.
  31110. * @param base The URL acting as the base URL.
  31111. * @param to The URL to resolve.
  31112. */
  31113. function _resolveUrl(base, url) {
  31114. var parts = _split(encodeURI(url));
  31115. var baseParts = _split(base);
  31116. if (parts[_ComponentIndex.Scheme] != null) {
  31117. return _joinAndCanonicalizePath(parts);
  31118. }
  31119. else {
  31120. parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme];
  31121. }
  31122. for (var i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
  31123. if (parts[i] == null) {
  31124. parts[i] = baseParts[i];
  31125. }
  31126. }
  31127. if (parts[_ComponentIndex.Path][0] == '/') {
  31128. return _joinAndCanonicalizePath(parts);
  31129. }
  31130. var path = baseParts[_ComponentIndex.Path];
  31131. if (path == null)
  31132. path = '/';
  31133. var index = path.lastIndexOf('/');
  31134. path = path.substring(0, index + 1) + parts[_ComponentIndex.Path];
  31135. parts[_ComponentIndex.Path] = path;
  31136. return _joinAndCanonicalizePath(parts);
  31137. }
  31138. var Extractor = /** @class */ (function () {
  31139. function Extractor(host, staticSymbolResolver, messageBundle, metadataResolver) {
  31140. this.host = host;
  31141. this.staticSymbolResolver = staticSymbolResolver;
  31142. this.messageBundle = messageBundle;
  31143. this.metadataResolver = metadataResolver;
  31144. }
  31145. Extractor.prototype.extract = function (rootFiles) {
  31146. var _this = this;
  31147. var _a = analyzeAndValidateNgModules(rootFiles, this.host, this.staticSymbolResolver, this.metadataResolver), files = _a.files, ngModules = _a.ngModules;
  31148. return Promise
  31149. .all(ngModules.map(function (ngModule) { return _this.metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false); }))
  31150. .then(function () {
  31151. var errors = [];
  31152. files.forEach(function (file) {
  31153. var compMetas = [];
  31154. file.directives.forEach(function (directiveType) {
  31155. var dirMeta = _this.metadataResolver.getDirectiveMetadata(directiveType);
  31156. if (dirMeta && dirMeta.isComponent) {
  31157. compMetas.push(dirMeta);
  31158. }
  31159. });
  31160. compMetas.forEach(function (compMeta) {
  31161. var html = compMeta.template.template;
  31162. // Template URL points to either an HTML or TS file depending on
  31163. // whether the file is used with `templateUrl:` or `template:`,
  31164. // respectively.
  31165. var templateUrl = compMeta.template.templateUrl;
  31166. var interpolationConfig = InterpolationConfig.fromArray(compMeta.template.interpolation);
  31167. errors.push.apply(errors, __spreadArray([], __read(_this.messageBundle.updateFromTemplate(html, templateUrl, interpolationConfig))));
  31168. });
  31169. });
  31170. if (errors.length) {
  31171. throw new Error(errors.map(function (e) { return e.toString(); }).join('\n'));
  31172. }
  31173. return _this.messageBundle;
  31174. });
  31175. };
  31176. Extractor.create = function (host, locale) {
  31177. var htmlParser = new HtmlParser();
  31178. var urlResolver = createAotUrlResolver(host);
  31179. var symbolCache = new StaticSymbolCache();
  31180. var summaryResolver = new AotSummaryResolver(host, symbolCache);
  31181. var staticSymbolResolver = new StaticSymbolResolver(host, symbolCache, summaryResolver);
  31182. var staticReflector = new StaticReflector(summaryResolver, staticSymbolResolver);
  31183. var config = new CompilerConfig({ defaultEncapsulation: ViewEncapsulation.Emulated, useJit: false });
  31184. var normalizer = new DirectiveNormalizer({ get: function (url) { return host.loadResource(url); } }, urlResolver, htmlParser, config);
  31185. var elementSchemaRegistry = new DomElementSchemaRegistry();
  31186. var resolver = new CompileMetadataResolver(config, htmlParser, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector);
  31187. // TODO(vicb): implicit tags & attributes
  31188. var messageBundle = new MessageBundle(htmlParser, [], {}, locale);
  31189. var extractor = new Extractor(host, staticSymbolResolver, messageBundle, resolver);
  31190. return { extractor: extractor, staticReflector: staticReflector };
  31191. };
  31192. return Extractor;
  31193. }());
  31194. /**
  31195. * @license
  31196. * Copyright Google LLC All Rights Reserved.
  31197. *
  31198. * Use of this source code is governed by an MIT-style license that can be
  31199. * found in the LICENSE file at https://angular.io/license
  31200. */
  31201. var FactoryTarget;
  31202. (function (FactoryTarget) {
  31203. FactoryTarget[FactoryTarget["Directive"] = 0] = "Directive";
  31204. FactoryTarget[FactoryTarget["Component"] = 1] = "Component";
  31205. FactoryTarget[FactoryTarget["Injectable"] = 2] = "Injectable";
  31206. FactoryTarget[FactoryTarget["Pipe"] = 3] = "Pipe";
  31207. FactoryTarget[FactoryTarget["NgModule"] = 4] = "NgModule";
  31208. })(FactoryTarget || (FactoryTarget = {}));
  31209. /**
  31210. * Processes `Target`s with a given set of directives and performs a binding operation, which
  31211. * returns an object similar to TypeScript's `ts.TypeChecker` that contains knowledge about the
  31212. * target.
  31213. */
  31214. var R3TargetBinder = /** @class */ (function () {
  31215. function R3TargetBinder(directiveMatcher) {
  31216. this.directiveMatcher = directiveMatcher;
  31217. }
  31218. /**
  31219. * Perform a binding operation on the given `Target` and return a `BoundTarget` which contains
  31220. * metadata about the types referenced in the template.
  31221. */
  31222. R3TargetBinder.prototype.bind = function (target) {
  31223. if (!target.template) {
  31224. // TODO(alxhub): handle targets which contain things like HostBindings, etc.
  31225. throw new Error('Binding without a template not yet supported');
  31226. }
  31227. // First, parse the template into a `Scope` structure. This operation captures the syntactic
  31228. // scopes in the template and makes them available for later use.
  31229. var scope = Scope.apply(target.template);
  31230. // Use the `Scope` to extract the entities present at every level of the template.
  31231. var templateEntities = extractTemplateEntities(scope);
  31232. // Next, perform directive matching on the template using the `DirectiveBinder`. This returns:
  31233. // - directives: Map of nodes (elements & ng-templates) to the directives on them.
  31234. // - bindings: Map of inputs, outputs, and attributes to the directive/element that claims
  31235. // them. TODO(alxhub): handle multiple directives claiming an input/output/etc.
  31236. // - references: Map of #references to their targets.
  31237. var _b = DirectiveBinder.apply(target.template, this.directiveMatcher), directives = _b.directives, bindings = _b.bindings, references = _b.references;
  31238. // Finally, run the TemplateBinder to bind references, variables, and other entities within the
  31239. // template. This extracts all the metadata that doesn't depend on directive matching.
  31240. var _c = TemplateBinder.apply(target.template, scope), expressions = _c.expressions, symbols = _c.symbols, nestingLevel = _c.nestingLevel, usedPipes = _c.usedPipes;
  31241. return new R3BoundTarget(target, directives, bindings, references, expressions, symbols, nestingLevel, templateEntities, usedPipes);
  31242. };
  31243. return R3TargetBinder;
  31244. }());
  31245. /**
  31246. * Represents a binding scope within a template.
  31247. *
  31248. * Any variables, references, or other named entities declared within the template will
  31249. * be captured and available by name in `namedEntities`. Additionally, child templates will
  31250. * be analyzed and have their child `Scope`s available in `childScopes`.
  31251. */
  31252. var Scope = /** @class */ (function () {
  31253. function Scope(parentScope, template) {
  31254. this.parentScope = parentScope;
  31255. this.template = template;
  31256. /**
  31257. * Named members of the `Scope`, such as `Reference`s or `Variable`s.
  31258. */
  31259. this.namedEntities = new Map();
  31260. /**
  31261. * Child `Scope`s for immediately nested `Template`s.
  31262. */
  31263. this.childScopes = new Map();
  31264. }
  31265. Scope.newRootScope = function () {
  31266. return new Scope(null, null);
  31267. };
  31268. /**
  31269. * Process a template (either as a `Template` sub-template with variables, or a plain array of
  31270. * template `Node`s) and construct its `Scope`.
  31271. */
  31272. Scope.apply = function (template) {
  31273. var scope = Scope.newRootScope();
  31274. scope.ingest(template);
  31275. return scope;
  31276. };
  31277. /**
  31278. * Internal method to process the template and populate the `Scope`.
  31279. */
  31280. Scope.prototype.ingest = function (template) {
  31281. var _this = this;
  31282. if (template instanceof Template) {
  31283. // Variables on an <ng-template> are defined in the inner scope.
  31284. template.variables.forEach(function (node) { return _this.visitVariable(node); });
  31285. // Process the nodes of the template.
  31286. template.children.forEach(function (node) { return node.visit(_this); });
  31287. }
  31288. else {
  31289. // No overarching `Template` instance, so process the nodes directly.
  31290. template.forEach(function (node) { return node.visit(_this); });
  31291. }
  31292. };
  31293. Scope.prototype.visitElement = function (element) {
  31294. var _this = this;
  31295. // `Element`s in the template may have `Reference`s which are captured in the scope.
  31296. element.references.forEach(function (node) { return _this.visitReference(node); });
  31297. // Recurse into the `Element`'s children.
  31298. element.children.forEach(function (node) { return node.visit(_this); });
  31299. };
  31300. Scope.prototype.visitTemplate = function (template) {
  31301. var _this = this;
  31302. // References on a <ng-template> are defined in the outer scope, so capture them before
  31303. // processing the template's child scope.
  31304. template.references.forEach(function (node) { return _this.visitReference(node); });
  31305. // Next, create an inner scope and process the template within it.
  31306. var scope = new Scope(this, template);
  31307. scope.ingest(template);
  31308. this.childScopes.set(template, scope);
  31309. };
  31310. Scope.prototype.visitVariable = function (variable) {
  31311. // Declare the variable if it's not already.
  31312. this.maybeDeclare(variable);
  31313. };
  31314. Scope.prototype.visitReference = function (reference) {
  31315. // Declare the variable if it's not already.
  31316. this.maybeDeclare(reference);
  31317. };
  31318. // Unused visitors.
  31319. Scope.prototype.visitContent = function (content) { };
  31320. Scope.prototype.visitBoundAttribute = function (attr) { };
  31321. Scope.prototype.visitBoundEvent = function (event) { };
  31322. Scope.prototype.visitBoundText = function (text) { };
  31323. Scope.prototype.visitText = function (text) { };
  31324. Scope.prototype.visitTextAttribute = function (attr) { };
  31325. Scope.prototype.visitIcu = function (icu) { };
  31326. Scope.prototype.maybeDeclare = function (thing) {
  31327. // Declare something with a name, as long as that name isn't taken.
  31328. if (!this.namedEntities.has(thing.name)) {
  31329. this.namedEntities.set(thing.name, thing);
  31330. }
  31331. };
  31332. /**
  31333. * Look up a variable within this `Scope`.
  31334. *
  31335. * This can recurse into a parent `Scope` if it's available.
  31336. */
  31337. Scope.prototype.lookup = function (name) {
  31338. if (this.namedEntities.has(name)) {
  31339. // Found in the local scope.
  31340. return this.namedEntities.get(name);
  31341. }
  31342. else if (this.parentScope !== null) {
  31343. // Not in the local scope, but there's a parent scope so check there.
  31344. return this.parentScope.lookup(name);
  31345. }
  31346. else {
  31347. // At the top level and it wasn't found.
  31348. return null;
  31349. }
  31350. };
  31351. /**
  31352. * Get the child scope for a `Template`.
  31353. *
  31354. * This should always be defined.
  31355. */
  31356. Scope.prototype.getChildScope = function (template) {
  31357. var res = this.childScopes.get(template);
  31358. if (res === undefined) {
  31359. throw new Error("Assertion error: child scope for " + template + " not found");
  31360. }
  31361. return res;
  31362. };
  31363. return Scope;
  31364. }());
  31365. /**
  31366. * Processes a template and matches directives on nodes (elements and templates).
  31367. *
  31368. * Usually used via the static `apply()` method.
  31369. */
  31370. var DirectiveBinder = /** @class */ (function () {
  31371. function DirectiveBinder(matcher, directives, bindings, references) {
  31372. this.matcher = matcher;
  31373. this.directives = directives;
  31374. this.bindings = bindings;
  31375. this.references = references;
  31376. }
  31377. /**
  31378. * Process a template (list of `Node`s) and perform directive matching against each node.
  31379. *
  31380. * @param template the list of template `Node`s to match (recursively).
  31381. * @param selectorMatcher a `SelectorMatcher` containing the directives that are in scope for
  31382. * this template.
  31383. * @returns three maps which contain information about directives in the template: the
  31384. * `directives` map which lists directives matched on each node, the `bindings` map which
  31385. * indicates which directives claimed which bindings (inputs, outputs, etc), and the `references`
  31386. * map which resolves #references (`Reference`s) within the template to the named directive or
  31387. * template node.
  31388. */
  31389. DirectiveBinder.apply = function (template, selectorMatcher) {
  31390. var directives = new Map();
  31391. var bindings = new Map();
  31392. var references = new Map();
  31393. var matcher = new DirectiveBinder(selectorMatcher, directives, bindings, references);
  31394. matcher.ingest(template);
  31395. return { directives: directives, bindings: bindings, references: references };
  31396. };
  31397. DirectiveBinder.prototype.ingest = function (template) {
  31398. var _this = this;
  31399. template.forEach(function (node) { return node.visit(_this); });
  31400. };
  31401. DirectiveBinder.prototype.visitElement = function (element) {
  31402. this.visitElementOrTemplate(element.name, element);
  31403. };
  31404. DirectiveBinder.prototype.visitTemplate = function (template) {
  31405. this.visitElementOrTemplate('ng-template', template);
  31406. };
  31407. DirectiveBinder.prototype.visitElementOrTemplate = function (elementName, node) {
  31408. var _this = this;
  31409. // First, determine the HTML shape of the node for the purpose of directive matching.
  31410. // Do this by building up a `CssSelector` for the node.
  31411. var cssSelector = createCssSelector(elementName, getAttrsForDirectiveMatching(node));
  31412. // Next, use the `SelectorMatcher` to get the list of directives on the node.
  31413. var directives = [];
  31414. this.matcher.match(cssSelector, function (_, directive) { return directives.push(directive); });
  31415. if (directives.length > 0) {
  31416. this.directives.set(node, directives);
  31417. }
  31418. // Resolve any references that are created on this node.
  31419. node.references.forEach(function (ref) {
  31420. var dirTarget = null;
  31421. // If the reference expression is empty, then it matches the "primary" directive on the node
  31422. // (if there is one). Otherwise it matches the host node itself (either an element or
  31423. // <ng-template> node).
  31424. if (ref.value.trim() === '') {
  31425. // This could be a reference to a component if there is one.
  31426. dirTarget = directives.find(function (dir) { return dir.isComponent; }) || null;
  31427. }
  31428. else {
  31429. // This should be a reference to a directive exported via exportAs.
  31430. dirTarget =
  31431. directives.find(function (dir) { return dir.exportAs !== null && dir.exportAs.some(function (value) { return value === ref.value; }); }) ||
  31432. null;
  31433. // Check if a matching directive was found.
  31434. if (dirTarget === null) {
  31435. // No matching directive was found - this reference points to an unknown target. Leave it
  31436. // unmapped.
  31437. return;
  31438. }
  31439. }
  31440. if (dirTarget !== null) {
  31441. // This reference points to a directive.
  31442. _this.references.set(ref, { directive: dirTarget, node: node });
  31443. }
  31444. else {
  31445. // This reference points to the node itself.
  31446. _this.references.set(ref, node);
  31447. }
  31448. });
  31449. var setAttributeBinding = function (attribute, ioType) {
  31450. var dir = directives.find(function (dir) { return dir[ioType].hasBindingPropertyName(attribute.name); });
  31451. var binding = dir !== undefined ? dir : node;
  31452. _this.bindings.set(attribute, binding);
  31453. };
  31454. // Node inputs (bound attributes) and text attributes can be bound to an
  31455. // input on a directive.
  31456. node.inputs.forEach(function (input) { return setAttributeBinding(input, 'inputs'); });
  31457. node.attributes.forEach(function (attr) { return setAttributeBinding(attr, 'inputs'); });
  31458. if (node instanceof Template) {
  31459. node.templateAttrs.forEach(function (attr) { return setAttributeBinding(attr, 'inputs'); });
  31460. }
  31461. // Node outputs (bound events) can be bound to an output on a directive.
  31462. node.outputs.forEach(function (output) { return setAttributeBinding(output, 'outputs'); });
  31463. // Recurse into the node's children.
  31464. node.children.forEach(function (child) { return child.visit(_this); });
  31465. };
  31466. // Unused visitors.
  31467. DirectiveBinder.prototype.visitContent = function (content) { };
  31468. DirectiveBinder.prototype.visitVariable = function (variable) { };
  31469. DirectiveBinder.prototype.visitReference = function (reference) { };
  31470. DirectiveBinder.prototype.visitTextAttribute = function (attribute) { };
  31471. DirectiveBinder.prototype.visitBoundAttribute = function (attribute) { };
  31472. DirectiveBinder.prototype.visitBoundEvent = function (attribute) { };
  31473. DirectiveBinder.prototype.visitBoundAttributeOrEvent = function (node) { };
  31474. DirectiveBinder.prototype.visitText = function (text) { };
  31475. DirectiveBinder.prototype.visitBoundText = function (text) { };
  31476. DirectiveBinder.prototype.visitIcu = function (icu) { };
  31477. return DirectiveBinder;
  31478. }());
  31479. /**
  31480. * Processes a template and extract metadata about expressions and symbols within.
  31481. *
  31482. * This is a companion to the `DirectiveBinder` that doesn't require knowledge of directives matched
  31483. * within the template in order to operate.
  31484. *
  31485. * Expressions are visited by the superclass `RecursiveAstVisitor`, with custom logic provided
  31486. * by overridden methods from that visitor.
  31487. */
  31488. var TemplateBinder = /** @class */ (function (_super) {
  31489. __extends(TemplateBinder, _super);
  31490. function TemplateBinder(bindings, symbols, usedPipes, nestingLevel, scope, template, level) {
  31491. var _this = _super.call(this) || this;
  31492. _this.bindings = bindings;
  31493. _this.symbols = symbols;
  31494. _this.usedPipes = usedPipes;
  31495. _this.nestingLevel = nestingLevel;
  31496. _this.scope = scope;
  31497. _this.template = template;
  31498. _this.level = level;
  31499. _this.pipesUsed = [];
  31500. // Save a bit of processing time by constructing this closure in advance.
  31501. _this.visitNode = function (node) { return node.visit(_this); };
  31502. return _this;
  31503. }
  31504. // This method is defined to reconcile the type of TemplateBinder since both
  31505. // RecursiveAstVisitor and Visitor define the visit() method in their
  31506. // interfaces.
  31507. TemplateBinder.prototype.visit = function (node, context) {
  31508. if (node instanceof AST) {
  31509. node.visit(this, context);
  31510. }
  31511. else {
  31512. node.visit(this);
  31513. }
  31514. };
  31515. /**
  31516. * Process a template and extract metadata about expressions and symbols within.
  31517. *
  31518. * @param template the nodes of the template to process
  31519. * @param scope the `Scope` of the template being processed.
  31520. * @returns three maps which contain metadata about the template: `expressions` which interprets
  31521. * special `AST` nodes in expressions as pointing to references or variables declared within the
  31522. * template, `symbols` which maps those variables and references to the nested `Template` which
  31523. * declares them, if any, and `nestingLevel` which associates each `Template` with a integer
  31524. * nesting level (how many levels deep within the template structure the `Template` is), starting
  31525. * at 1.
  31526. */
  31527. TemplateBinder.apply = function (template, scope) {
  31528. var expressions = new Map();
  31529. var symbols = new Map();
  31530. var nestingLevel = new Map();
  31531. var usedPipes = new Set();
  31532. // The top-level template has nesting level 0.
  31533. var binder = new TemplateBinder(expressions, symbols, usedPipes, nestingLevel, scope, template instanceof Template ? template : null, 0);
  31534. binder.ingest(template);
  31535. return { expressions: expressions, symbols: symbols, nestingLevel: nestingLevel, usedPipes: usedPipes };
  31536. };
  31537. TemplateBinder.prototype.ingest = function (template) {
  31538. if (template instanceof Template) {
  31539. // For <ng-template>s, process only variables and child nodes. Inputs, outputs, templateAttrs,
  31540. // and references were all processed in the scope of the containing template.
  31541. template.variables.forEach(this.visitNode);
  31542. template.children.forEach(this.visitNode);
  31543. // Set the nesting level.
  31544. this.nestingLevel.set(template, this.level);
  31545. }
  31546. else {
  31547. // Visit each node from the top-level template.
  31548. template.forEach(this.visitNode);
  31549. }
  31550. };
  31551. TemplateBinder.prototype.visitElement = function (element) {
  31552. // Visit the inputs, outputs, and children of the element.
  31553. element.inputs.forEach(this.visitNode);
  31554. element.outputs.forEach(this.visitNode);
  31555. element.children.forEach(this.visitNode);
  31556. };
  31557. TemplateBinder.prototype.visitTemplate = function (template) {
  31558. // First, visit inputs, outputs and template attributes of the template node.
  31559. template.inputs.forEach(this.visitNode);
  31560. template.outputs.forEach(this.visitNode);
  31561. template.templateAttrs.forEach(this.visitNode);
  31562. // References are also evaluated in the outer context.
  31563. template.references.forEach(this.visitNode);
  31564. // Next, recurse into the template using its scope, and bumping the nesting level up by one.
  31565. var childScope = this.scope.getChildScope(template);
  31566. var binder = new TemplateBinder(this.bindings, this.symbols, this.usedPipes, this.nestingLevel, childScope, template, this.level + 1);
  31567. binder.ingest(template);
  31568. };
  31569. TemplateBinder.prototype.visitVariable = function (variable) {
  31570. // Register the `Variable` as a symbol in the current `Template`.
  31571. if (this.template !== null) {
  31572. this.symbols.set(variable, this.template);
  31573. }
  31574. };
  31575. TemplateBinder.prototype.visitReference = function (reference) {
  31576. // Register the `Reference` as a symbol in the current `Template`.
  31577. if (this.template !== null) {
  31578. this.symbols.set(reference, this.template);
  31579. }
  31580. };
  31581. // Unused template visitors
  31582. TemplateBinder.prototype.visitText = function (text) { };
  31583. TemplateBinder.prototype.visitContent = function (content) { };
  31584. TemplateBinder.prototype.visitTextAttribute = function (attribute) { };
  31585. TemplateBinder.prototype.visitIcu = function (icu) {
  31586. var _this = this;
  31587. Object.keys(icu.vars).forEach(function (key) { return icu.vars[key].visit(_this); });
  31588. Object.keys(icu.placeholders).forEach(function (key) { return icu.placeholders[key].visit(_this); });
  31589. };
  31590. // The remaining visitors are concerned with processing AST expressions within template bindings
  31591. TemplateBinder.prototype.visitBoundAttribute = function (attribute) {
  31592. attribute.value.visit(this);
  31593. };
  31594. TemplateBinder.prototype.visitBoundEvent = function (event) {
  31595. event.handler.visit(this);
  31596. };
  31597. TemplateBinder.prototype.visitBoundText = function (text) {
  31598. text.value.visit(this);
  31599. };
  31600. TemplateBinder.prototype.visitPipe = function (ast, context) {
  31601. this.usedPipes.add(ast.name);
  31602. return _super.prototype.visitPipe.call(this, ast, context);
  31603. };
  31604. // These five types of AST expressions can refer to expression roots, which could be variables
  31605. // or references in the current scope.
  31606. TemplateBinder.prototype.visitPropertyRead = function (ast, context) {
  31607. this.maybeMap(context, ast, ast.name);
  31608. return _super.prototype.visitPropertyRead.call(this, ast, context);
  31609. };
  31610. TemplateBinder.prototype.visitSafePropertyRead = function (ast, context) {
  31611. this.maybeMap(context, ast, ast.name);
  31612. return _super.prototype.visitSafePropertyRead.call(this, ast, context);
  31613. };
  31614. TemplateBinder.prototype.visitPropertyWrite = function (ast, context) {
  31615. this.maybeMap(context, ast, ast.name);
  31616. return _super.prototype.visitPropertyWrite.call(this, ast, context);
  31617. };
  31618. TemplateBinder.prototype.visitMethodCall = function (ast, context) {
  31619. this.maybeMap(context, ast, ast.name);
  31620. return _super.prototype.visitMethodCall.call(this, ast, context);
  31621. };
  31622. TemplateBinder.prototype.visitSafeMethodCall = function (ast, context) {
  31623. this.maybeMap(context, ast, ast.name);
  31624. return _super.prototype.visitSafeMethodCall.call(this, ast, context);
  31625. };
  31626. TemplateBinder.prototype.maybeMap = function (scope, ast, name) {
  31627. // If the receiver of the expression isn't the `ImplicitReceiver`, this isn't the root of an
  31628. // `AST` expression that maps to a `Variable` or `Reference`.
  31629. if (!(ast.receiver instanceof ImplicitReceiver)) {
  31630. return;
  31631. }
  31632. // Check whether the name exists in the current scope. If so, map it. Otherwise, the name is
  31633. // probably a property on the top-level component context.
  31634. var target = this.scope.lookup(name);
  31635. if (target !== null) {
  31636. this.bindings.set(ast, target);
  31637. }
  31638. };
  31639. return TemplateBinder;
  31640. }(RecursiveAstVisitor$1));
  31641. /**
  31642. * Metadata container for a `Target` that allows queries for specific bits of metadata.
  31643. *
  31644. * See `BoundTarget` for documentation on the individual methods.
  31645. */
  31646. var R3BoundTarget = /** @class */ (function () {
  31647. function R3BoundTarget(target, directives, bindings, references, exprTargets, symbols, nestingLevel, templateEntities, usedPipes) {
  31648. this.target = target;
  31649. this.directives = directives;
  31650. this.bindings = bindings;
  31651. this.references = references;
  31652. this.exprTargets = exprTargets;
  31653. this.symbols = symbols;
  31654. this.nestingLevel = nestingLevel;
  31655. this.templateEntities = templateEntities;
  31656. this.usedPipes = usedPipes;
  31657. }
  31658. R3BoundTarget.prototype.getEntitiesInTemplateScope = function (template) {
  31659. var _a;
  31660. return (_a = this.templateEntities.get(template)) !== null && _a !== void 0 ? _a : new Set();
  31661. };
  31662. R3BoundTarget.prototype.getDirectivesOfNode = function (node) {
  31663. return this.directives.get(node) || null;
  31664. };
  31665. R3BoundTarget.prototype.getReferenceTarget = function (ref) {
  31666. return this.references.get(ref) || null;
  31667. };
  31668. R3BoundTarget.prototype.getConsumerOfBinding = function (binding) {
  31669. return this.bindings.get(binding) || null;
  31670. };
  31671. R3BoundTarget.prototype.getExpressionTarget = function (expr) {
  31672. return this.exprTargets.get(expr) || null;
  31673. };
  31674. R3BoundTarget.prototype.getTemplateOfSymbol = function (symbol) {
  31675. return this.symbols.get(symbol) || null;
  31676. };
  31677. R3BoundTarget.prototype.getNestingLevel = function (template) {
  31678. return this.nestingLevel.get(template) || 0;
  31679. };
  31680. R3BoundTarget.prototype.getUsedDirectives = function () {
  31681. var set = new Set();
  31682. this.directives.forEach(function (dirs) { return dirs.forEach(function (dir) { return set.add(dir); }); });
  31683. return Array.from(set.values());
  31684. };
  31685. R3BoundTarget.prototype.getUsedPipes = function () {
  31686. return Array.from(this.usedPipes);
  31687. };
  31688. return R3BoundTarget;
  31689. }());
  31690. function extractTemplateEntities(rootScope) {
  31691. var e_1, _b, e_2, _c;
  31692. var entityMap = new Map();
  31693. function extractScopeEntities(scope) {
  31694. if (entityMap.has(scope.template)) {
  31695. return entityMap.get(scope.template);
  31696. }
  31697. var currentEntities = scope.namedEntities;
  31698. var templateEntities;
  31699. if (scope.parentScope !== null) {
  31700. templateEntities = new Map(__spreadArray(__spreadArray([], __read(extractScopeEntities(scope.parentScope))), __read(currentEntities)));
  31701. }
  31702. else {
  31703. templateEntities = new Map(currentEntities);
  31704. }
  31705. entityMap.set(scope.template, templateEntities);
  31706. return templateEntities;
  31707. }
  31708. var scopesToProcess = [rootScope];
  31709. while (scopesToProcess.length > 0) {
  31710. var scope = scopesToProcess.pop();
  31711. try {
  31712. for (var _d = (e_1 = void 0, __values(scope.childScopes.values())), _e = _d.next(); !_e.done; _e = _d.next()) {
  31713. var childScope = _e.value;
  31714. scopesToProcess.push(childScope);
  31715. }
  31716. }
  31717. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  31718. finally {
  31719. try {
  31720. if (_e && !_e.done && (_b = _d.return)) _b.call(_d);
  31721. }
  31722. finally { if (e_1) throw e_1.error; }
  31723. }
  31724. extractScopeEntities(scope);
  31725. }
  31726. var templateEntities = new Map();
  31727. try {
  31728. for (var entityMap_1 = __values(entityMap), entityMap_1_1 = entityMap_1.next(); !entityMap_1_1.done; entityMap_1_1 = entityMap_1.next()) {
  31729. var _f = __read(entityMap_1_1.value, 2), template = _f[0], entities = _f[1];
  31730. templateEntities.set(template, new Set(entities.values()));
  31731. }
  31732. }
  31733. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  31734. finally {
  31735. try {
  31736. if (entityMap_1_1 && !entityMap_1_1.done && (_c = entityMap_1.return)) _c.call(entityMap_1);
  31737. }
  31738. finally { if (e_2) throw e_2.error; }
  31739. }
  31740. return templateEntities;
  31741. }
  31742. /**
  31743. * @license
  31744. * Copyright Google LLC All Rights Reserved.
  31745. *
  31746. * Use of this source code is governed by an MIT-style license that can be
  31747. * found in the LICENSE file at https://angular.io/license
  31748. */
  31749. function compileClassMetadata(metadata) {
  31750. var _a, _b;
  31751. // Generate an ngDevMode guarded call to setClassMetadata with the class identifier and its
  31752. // metadata.
  31753. var fnCall = importExpr(Identifiers.setClassMetadata).callFn([
  31754. metadata.type,
  31755. metadata.decorators,
  31756. (_a = metadata.ctorParameters) !== null && _a !== void 0 ? _a : literal(null),
  31757. (_b = metadata.propDecorators) !== null && _b !== void 0 ? _b : literal(null),
  31758. ]);
  31759. var iife = fn([], [devOnlyGuardedExpression(fnCall).toStmt()]);
  31760. return iife.callFn([]);
  31761. }
  31762. /**
  31763. * @license
  31764. * Copyright Google LLC All Rights Reserved.
  31765. *
  31766. * Use of this source code is governed by an MIT-style license that can be
  31767. * found in the LICENSE file at https://angular.io/license
  31768. */
  31769. /**
  31770. * Every time we make a breaking change to the declaration interface or partial-linker behavior, we
  31771. * must update this constant to prevent old partial-linkers from incorrectly processing the
  31772. * declaration.
  31773. *
  31774. * Do not include any prerelease in these versions as they are ignored.
  31775. */
  31776. var MINIMUM_PARTIAL_LINKER_VERSION = '12.0.0';
  31777. function compileDeclareClassMetadata(metadata) {
  31778. var definitionMap = new DefinitionMap();
  31779. definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION));
  31780. definitionMap.set('version', literal('12.0.5'));
  31781. definitionMap.set('ngImport', importExpr(Identifiers.core));
  31782. definitionMap.set('type', metadata.type);
  31783. definitionMap.set('decorators', metadata.decorators);
  31784. definitionMap.set('ctorParameters', metadata.ctorParameters);
  31785. definitionMap.set('propDecorators', metadata.propDecorators);
  31786. return importExpr(Identifiers.declareClassMetadata).callFn([definitionMap.toLiteralMap()]);
  31787. }
  31788. /**
  31789. * @license
  31790. * Copyright Google LLC All Rights Reserved.
  31791. *
  31792. * Use of this source code is governed by an MIT-style license that can be
  31793. * found in the LICENSE file at https://angular.io/license
  31794. */
  31795. /**
  31796. * Every time we make a breaking change to the declaration interface or partial-linker behavior, we
  31797. * must update this constant to prevent old partial-linkers from incorrectly processing the
  31798. * declaration.
  31799. *
  31800. * Do not include any prerelease in these versions as they are ignored.
  31801. */
  31802. var MINIMUM_PARTIAL_LINKER_VERSION$1 = '12.0.0';
  31803. /**
  31804. * Compile a directive declaration defined by the `R3DirectiveMetadata`.
  31805. */
  31806. function compileDeclareDirectiveFromMetadata(meta) {
  31807. var definitionMap = createDirectiveDefinitionMap(meta);
  31808. var expression = importExpr(Identifiers.declareDirective).callFn([definitionMap.toLiteralMap()]);
  31809. var type = createDirectiveType(meta);
  31810. return { expression: expression, type: type, statements: [] };
  31811. }
  31812. /**
  31813. * Gathers the declaration fields for a directive into a `DefinitionMap`. This allows for reusing
  31814. * this logic for components, as they extend the directive metadata.
  31815. */
  31816. function createDirectiveDefinitionMap(meta) {
  31817. var definitionMap = new DefinitionMap();
  31818. definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION$1));
  31819. definitionMap.set('version', literal('12.0.5'));
  31820. // e.g. `type: MyDirective`
  31821. definitionMap.set('type', meta.internalType);
  31822. // e.g. `selector: 'some-dir'`
  31823. if (meta.selector !== null) {
  31824. definitionMap.set('selector', literal(meta.selector));
  31825. }
  31826. definitionMap.set('inputs', conditionallyCreateMapObjectLiteral(meta.inputs, true));
  31827. definitionMap.set('outputs', conditionallyCreateMapObjectLiteral(meta.outputs));
  31828. definitionMap.set('host', compileHostMetadata(meta.host));
  31829. definitionMap.set('providers', meta.providers);
  31830. if (meta.queries.length > 0) {
  31831. definitionMap.set('queries', literalArr(meta.queries.map(compileQuery)));
  31832. }
  31833. if (meta.viewQueries.length > 0) {
  31834. definitionMap.set('viewQueries', literalArr(meta.viewQueries.map(compileQuery)));
  31835. }
  31836. if (meta.exportAs !== null) {
  31837. definitionMap.set('exportAs', asLiteral(meta.exportAs));
  31838. }
  31839. if (meta.usesInheritance) {
  31840. definitionMap.set('usesInheritance', literal(true));
  31841. }
  31842. if (meta.lifecycle.usesOnChanges) {
  31843. definitionMap.set('usesOnChanges', literal(true));
  31844. }
  31845. definitionMap.set('ngImport', importExpr(Identifiers.core));
  31846. return definitionMap;
  31847. }
  31848. /**
  31849. * Compiles the metadata of a single query into its partial declaration form as declared
  31850. * by `R3DeclareQueryMetadata`.
  31851. */
  31852. function compileQuery(query) {
  31853. var meta = new DefinitionMap();
  31854. meta.set('propertyName', literal(query.propertyName));
  31855. if (query.first) {
  31856. meta.set('first', literal(true));
  31857. }
  31858. meta.set('predicate', Array.isArray(query.predicate) ? asLiteral(query.predicate) : query.predicate);
  31859. if (!query.emitDistinctChangesOnly) {
  31860. // `emitDistinctChangesOnly` is special because we expect it to be `true`.
  31861. // Therefore we explicitly emit the field, and explicitly place it only when it's `false`.
  31862. meta.set('emitDistinctChangesOnly', literal(false));
  31863. }
  31864. else {
  31865. // The linker will assume that an absent `emitDistinctChangesOnly` flag is by default `true`.
  31866. }
  31867. if (query.descendants) {
  31868. meta.set('descendants', literal(true));
  31869. }
  31870. meta.set('read', query.read);
  31871. if (query.static) {
  31872. meta.set('static', literal(true));
  31873. }
  31874. return meta.toLiteralMap();
  31875. }
  31876. /**
  31877. * Compiles the host metadata into its partial declaration form as declared
  31878. * in `R3DeclareDirectiveMetadata['host']`
  31879. */
  31880. function compileHostMetadata(meta) {
  31881. var hostMetadata = new DefinitionMap();
  31882. hostMetadata.set('attributes', toOptionalLiteralMap(meta.attributes, function (expression) { return expression; }));
  31883. hostMetadata.set('listeners', toOptionalLiteralMap(meta.listeners, literal));
  31884. hostMetadata.set('properties', toOptionalLiteralMap(meta.properties, literal));
  31885. if (meta.specialAttributes.styleAttr) {
  31886. hostMetadata.set('styleAttribute', literal(meta.specialAttributes.styleAttr));
  31887. }
  31888. if (meta.specialAttributes.classAttr) {
  31889. hostMetadata.set('classAttribute', literal(meta.specialAttributes.classAttr));
  31890. }
  31891. if (hostMetadata.values.length > 0) {
  31892. return hostMetadata.toLiteralMap();
  31893. }
  31894. else {
  31895. return null;
  31896. }
  31897. }
  31898. /**
  31899. * Compile a component declaration defined by the `R3ComponentMetadata`.
  31900. */
  31901. function compileDeclareComponentFromMetadata(meta, template, additionalTemplateInfo) {
  31902. var definitionMap = createComponentDefinitionMap(meta, template, additionalTemplateInfo);
  31903. var expression = importExpr(Identifiers.declareComponent).callFn([definitionMap.toLiteralMap()]);
  31904. var type = createComponentType(meta);
  31905. return { expression: expression, type: type, statements: [] };
  31906. }
  31907. /**
  31908. * Gathers the declaration fields for a component into a `DefinitionMap`.
  31909. */
  31910. function createComponentDefinitionMap(meta, template, templateInfo) {
  31911. var definitionMap = createDirectiveDefinitionMap(meta);
  31912. definitionMap.set('template', getTemplateExpression(template, templateInfo));
  31913. if (templateInfo.isInline) {
  31914. definitionMap.set('isInline', literal(true));
  31915. }
  31916. definitionMap.set('styles', toOptionalLiteralArray(meta.styles, literal));
  31917. definitionMap.set('components', compileUsedDirectiveMetadata(meta, function (directive) { return directive.isComponent === true; }));
  31918. definitionMap.set('directives', compileUsedDirectiveMetadata(meta, function (directive) { return directive.isComponent !== true; }));
  31919. definitionMap.set('pipes', compileUsedPipeMetadata(meta));
  31920. definitionMap.set('viewProviders', meta.viewProviders);
  31921. definitionMap.set('animations', meta.animations);
  31922. if (meta.changeDetection !== undefined) {
  31923. definitionMap.set('changeDetection', importExpr(Identifiers.ChangeDetectionStrategy)
  31924. .prop(ChangeDetectionStrategy[meta.changeDetection]));
  31925. }
  31926. if (meta.encapsulation !== ViewEncapsulation.Emulated) {
  31927. definitionMap.set('encapsulation', importExpr(Identifiers.ViewEncapsulation).prop(ViewEncapsulation[meta.encapsulation]));
  31928. }
  31929. if (meta.interpolation !== DEFAULT_INTERPOLATION_CONFIG) {
  31930. definitionMap.set('interpolation', literalArr([literal(meta.interpolation.start), literal(meta.interpolation.end)]));
  31931. }
  31932. if (template.preserveWhitespaces === true) {
  31933. definitionMap.set('preserveWhitespaces', literal(true));
  31934. }
  31935. return definitionMap;
  31936. }
  31937. function getTemplateExpression(template, templateInfo) {
  31938. // If the template has been defined using a direct literal, we use that expression directly
  31939. // without any modifications. This is ensures proper source mapping from the partially
  31940. // compiled code to the source file declaring the template. Note that this does not capture
  31941. // template literals referenced indirectly through an identifier.
  31942. if (templateInfo.inlineTemplateLiteralExpression !== null) {
  31943. return templateInfo.inlineTemplateLiteralExpression;
  31944. }
  31945. // If the template is defined inline but not through a literal, the template has been resolved
  31946. // through static interpretation. We create a literal but cannot provide any source span. Note
  31947. // that we cannot use the expression defining the template because the linker expects the template
  31948. // to be defined as a literal in the declaration.
  31949. if (templateInfo.isInline) {
  31950. return literal(templateInfo.content, null, null);
  31951. }
  31952. // The template is external so we must synthesize an expression node with
  31953. // the appropriate source-span.
  31954. var contents = templateInfo.content;
  31955. var file = new ParseSourceFile(contents, templateInfo.sourceUrl);
  31956. var start = new ParseLocation(file, 0, 0, 0);
  31957. var end = computeEndLocation(file, contents);
  31958. var span = new ParseSourceSpan(start, end);
  31959. return literal(contents, null, span);
  31960. }
  31961. function computeEndLocation(file, contents) {
  31962. var length = contents.length;
  31963. var lineStart = 0;
  31964. var lastLineStart = 0;
  31965. var line = 0;
  31966. do {
  31967. lineStart = contents.indexOf('\n', lastLineStart);
  31968. if (lineStart !== -1) {
  31969. lastLineStart = lineStart + 1;
  31970. line++;
  31971. }
  31972. } while (lineStart !== -1);
  31973. return new ParseLocation(file, length, line, length - lastLineStart);
  31974. }
  31975. /**
  31976. * Compiles the directives as registered in the component metadata into an array literal of the
  31977. * individual directives. If the component does not use any directives, then null is returned.
  31978. */
  31979. function compileUsedDirectiveMetadata(meta, predicate) {
  31980. var wrapType = meta.declarationListEmitMode !== 0 /* Direct */ ?
  31981. generateForwardRef :
  31982. function (expr) { return expr; };
  31983. var directives = meta.directives.filter(predicate);
  31984. return toOptionalLiteralArray(directives, function (directive) {
  31985. var dirMeta = new DefinitionMap();
  31986. dirMeta.set('type', wrapType(directive.type));
  31987. dirMeta.set('selector', literal(directive.selector));
  31988. dirMeta.set('inputs', toOptionalLiteralArray(directive.inputs, literal));
  31989. dirMeta.set('outputs', toOptionalLiteralArray(directive.outputs, literal));
  31990. dirMeta.set('exportAs', toOptionalLiteralArray(directive.exportAs, literal));
  31991. return dirMeta.toLiteralMap();
  31992. });
  31993. }
  31994. /**
  31995. * Compiles the pipes as registered in the component metadata into an object literal, where the
  31996. * pipe's name is used as key and a reference to its type as value. If the component does not use
  31997. * any pipes, then null is returned.
  31998. */
  31999. function compileUsedPipeMetadata(meta) {
  32000. var e_1, _a;
  32001. if (meta.pipes.size === 0) {
  32002. return null;
  32003. }
  32004. var wrapType = meta.declarationListEmitMode !== 0 /* Direct */ ?
  32005. generateForwardRef :
  32006. function (expr) { return expr; };
  32007. var entries = [];
  32008. try {
  32009. for (var _b = __values(meta.pipes), _c = _b.next(); !_c.done; _c = _b.next()) {
  32010. var _d = __read(_c.value, 2), name = _d[0], pipe = _d[1];
  32011. entries.push({ key: name, value: wrapType(pipe), quoted: true });
  32012. }
  32013. }
  32014. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  32015. finally {
  32016. try {
  32017. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  32018. }
  32019. finally { if (e_1) throw e_1.error; }
  32020. }
  32021. return literalMap(entries);
  32022. }
  32023. /**
  32024. * @license
  32025. * Copyright Google LLC All Rights Reserved.
  32026. *
  32027. * Use of this source code is governed by an MIT-style license that can be
  32028. * found in the LICENSE file at https://angular.io/license
  32029. */
  32030. /**
  32031. * Every time we make a breaking change to the declaration interface or partial-linker behavior, we
  32032. * must update this constant to prevent old partial-linkers from incorrectly processing the
  32033. * declaration.
  32034. *
  32035. * Do not include any prerelease in these versions as they are ignored.
  32036. */
  32037. var MINIMUM_PARTIAL_LINKER_VERSION$2 = '12.0.0';
  32038. function compileDeclareFactoryFunction(meta) {
  32039. var definitionMap = new DefinitionMap();
  32040. definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION$2));
  32041. definitionMap.set('version', literal('12.0.5'));
  32042. definitionMap.set('ngImport', importExpr(Identifiers.core));
  32043. definitionMap.set('type', meta.internalType);
  32044. definitionMap.set('deps', compileDependencies(meta.deps));
  32045. definitionMap.set('target', importExpr(Identifiers.FactoryTarget).prop(exports.FactoryTarget[meta.target]));
  32046. return {
  32047. expression: importExpr(Identifiers.declareFactory).callFn([definitionMap.toLiteralMap()]),
  32048. statements: [],
  32049. type: createFactoryType(meta),
  32050. };
  32051. }
  32052. /**
  32053. * @license
  32054. * Copyright Google LLC All Rights Reserved.
  32055. *
  32056. * Use of this source code is governed by an MIT-style license that can be
  32057. * found in the LICENSE file at https://angular.io/license
  32058. */
  32059. /**
  32060. * Every time we make a breaking change to the declaration interface or partial-linker behavior, we
  32061. * must update this constant to prevent old partial-linkers from incorrectly processing the
  32062. * declaration.
  32063. *
  32064. * Do not include any prerelease in these versions as they are ignored.
  32065. */
  32066. var MINIMUM_PARTIAL_LINKER_VERSION$3 = '12.0.0';
  32067. /**
  32068. * Compile a Injectable declaration defined by the `R3InjectableMetadata`.
  32069. */
  32070. function compileDeclareInjectableFromMetadata(meta) {
  32071. var definitionMap = createInjectableDefinitionMap(meta);
  32072. var expression = importExpr(Identifiers.declareInjectable).callFn([definitionMap.toLiteralMap()]);
  32073. var type = createInjectableType(meta);
  32074. return { expression: expression, type: type, statements: [] };
  32075. }
  32076. /**
  32077. * Gathers the declaration fields for a Injectable into a `DefinitionMap`.
  32078. */
  32079. function createInjectableDefinitionMap(meta) {
  32080. var definitionMap = new DefinitionMap();
  32081. definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION$3));
  32082. definitionMap.set('version', literal('12.0.5'));
  32083. definitionMap.set('ngImport', importExpr(Identifiers.core));
  32084. definitionMap.set('type', meta.internalType);
  32085. // Only generate providedIn property if it has a non-null value
  32086. if (meta.providedIn !== undefined) {
  32087. var providedIn = convertFromProviderExpression(meta.providedIn);
  32088. if (providedIn.value !== null) {
  32089. definitionMap.set('providedIn', providedIn);
  32090. }
  32091. }
  32092. if (meta.useClass !== undefined) {
  32093. definitionMap.set('useClass', convertFromProviderExpression(meta.useClass));
  32094. }
  32095. if (meta.useExisting !== undefined) {
  32096. definitionMap.set('useExisting', convertFromProviderExpression(meta.useExisting));
  32097. }
  32098. if (meta.useValue !== undefined) {
  32099. definitionMap.set('useValue', convertFromProviderExpression(meta.useValue));
  32100. }
  32101. // Factories do not contain `ForwardRef`s since any types are already wrapped in a function call
  32102. // so the types will not be eagerly evaluated. Therefore we do not need to process this expression
  32103. // with `convertFromProviderExpression()`.
  32104. if (meta.useFactory !== undefined) {
  32105. definitionMap.set('useFactory', meta.useFactory);
  32106. }
  32107. if (meta.deps !== undefined) {
  32108. definitionMap.set('deps', literalArr(meta.deps.map(compileDependency)));
  32109. }
  32110. return definitionMap;
  32111. }
  32112. /**
  32113. * Convert an `R3ProviderExpression` to an `Expression`, possibly wrapping its expression in a
  32114. * `forwardRef()` call.
  32115. *
  32116. * If `R3ProviderExpression.isForwardRef` is true then the expression was originally wrapped in a
  32117. * `forwardRef()` call to prevent the value from being eagerly evaluated in the code.
  32118. *
  32119. * Normally, the linker will statically process the code, putting the `expression` inside a factory
  32120. * function so the `forwardRef()` wrapper is not evaluated before it has been defined. But if the
  32121. * partial declaration is evaluated by the JIT compiler the `forwardRef()` call is still needed to
  32122. * prevent eager evaluation of the `expression`.
  32123. *
  32124. * So in partial declarations, expressions that could be forward-refs are wrapped in `forwardRef()`
  32125. * calls, and this is then unwrapped in the linker as necessary.
  32126. *
  32127. * See `packages/compiler-cli/src/ngtsc/annotations/src/injectable.ts` and
  32128. * `packages/compiler/src/jit_compiler_facade.ts` for more information.
  32129. */
  32130. function convertFromProviderExpression(_a) {
  32131. var expression = _a.expression, isForwardRef = _a.isForwardRef;
  32132. return isForwardRef ? generateForwardRef(expression) : expression;
  32133. }
  32134. /**
  32135. * @license
  32136. * Copyright Google LLC All Rights Reserved.
  32137. *
  32138. * Use of this source code is governed by an MIT-style license that can be
  32139. * found in the LICENSE file at https://angular.io/license
  32140. */
  32141. /**
  32142. * Every time we make a breaking change to the declaration interface or partial-linker behavior, we
  32143. * must update this constant to prevent old partial-linkers from incorrectly processing the
  32144. * declaration.
  32145. *
  32146. * Do not include any prerelease in these versions as they are ignored.
  32147. */
  32148. var MINIMUM_PARTIAL_LINKER_VERSION$4 = '12.0.0';
  32149. function compileDeclareInjectorFromMetadata(meta) {
  32150. var definitionMap = createInjectorDefinitionMap(meta);
  32151. var expression = importExpr(Identifiers.declareInjector).callFn([definitionMap.toLiteralMap()]);
  32152. var type = createInjectorType(meta);
  32153. return { expression: expression, type: type, statements: [] };
  32154. }
  32155. /**
  32156. * Gathers the declaration fields for an Injector into a `DefinitionMap`.
  32157. */
  32158. function createInjectorDefinitionMap(meta) {
  32159. var definitionMap = new DefinitionMap();
  32160. definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION$4));
  32161. definitionMap.set('version', literal('12.0.5'));
  32162. definitionMap.set('ngImport', importExpr(Identifiers.core));
  32163. definitionMap.set('type', meta.internalType);
  32164. definitionMap.set('providers', meta.providers);
  32165. if (meta.imports.length > 0) {
  32166. definitionMap.set('imports', literalArr(meta.imports));
  32167. }
  32168. return definitionMap;
  32169. }
  32170. /**
  32171. * @license
  32172. * Copyright Google LLC All Rights Reserved.
  32173. *
  32174. * Use of this source code is governed by an MIT-style license that can be
  32175. * found in the LICENSE file at https://angular.io/license
  32176. */
  32177. /**
  32178. * Every time we make a breaking change to the declaration interface or partial-linker behavior, we
  32179. * must update this constant to prevent old partial-linkers from incorrectly processing the
  32180. * declaration.
  32181. *
  32182. * Do not include any prerelease in these versions as they are ignored.
  32183. */
  32184. var MINIMUM_PARTIAL_LINKER_VERSION$5 = '12.0.0';
  32185. function compileDeclareNgModuleFromMetadata(meta) {
  32186. var definitionMap = createNgModuleDefinitionMap(meta);
  32187. var expression = importExpr(Identifiers.declareNgModule).callFn([definitionMap.toLiteralMap()]);
  32188. var type = createNgModuleType(meta);
  32189. return { expression: expression, type: type, statements: [] };
  32190. }
  32191. /**
  32192. * Gathers the declaration fields for an NgModule into a `DefinitionMap`.
  32193. */
  32194. function createNgModuleDefinitionMap(meta) {
  32195. var definitionMap = new DefinitionMap();
  32196. definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION$5));
  32197. definitionMap.set('version', literal('12.0.5'));
  32198. definitionMap.set('ngImport', importExpr(Identifiers.core));
  32199. definitionMap.set('type', meta.internalType);
  32200. // We only generate the keys in the metadata if the arrays contain values.
  32201. // We must wrap the arrays inside a function if any of the values are a forward reference to a
  32202. // not-yet-declared class. This is to support JIT execution of the `ɵɵngDeclareNgModule()` call.
  32203. // In the linker these wrappers are stripped and then reapplied for the `ɵɵdefineNgModule()` call.
  32204. if (meta.bootstrap.length > 0) {
  32205. definitionMap.set('bootstrap', refsToArray(meta.bootstrap, meta.containsForwardDecls));
  32206. }
  32207. if (meta.declarations.length > 0) {
  32208. definitionMap.set('declarations', refsToArray(meta.declarations, meta.containsForwardDecls));
  32209. }
  32210. if (meta.imports.length > 0) {
  32211. definitionMap.set('imports', refsToArray(meta.imports, meta.containsForwardDecls));
  32212. }
  32213. if (meta.exports.length > 0) {
  32214. definitionMap.set('exports', refsToArray(meta.exports, meta.containsForwardDecls));
  32215. }
  32216. if (meta.schemas !== null && meta.schemas.length > 0) {
  32217. definitionMap.set('schemas', literalArr(meta.schemas.map(function (ref) { return ref.value; })));
  32218. }
  32219. if (meta.id !== null) {
  32220. definitionMap.set('id', meta.id);
  32221. }
  32222. return definitionMap;
  32223. }
  32224. /**
  32225. * @license
  32226. * Copyright Google LLC All Rights Reserved.
  32227. *
  32228. * Use of this source code is governed by an MIT-style license that can be
  32229. * found in the LICENSE file at https://angular.io/license
  32230. */
  32231. /**
  32232. * Every time we make a breaking change to the declaration interface or partial-linker behavior, we
  32233. * must update this constant to prevent old partial-linkers from incorrectly processing the
  32234. * declaration.
  32235. *
  32236. * Do not include any prerelease in these versions as they are ignored.
  32237. */
  32238. var MINIMUM_PARTIAL_LINKER_VERSION$6 = '12.0.0';
  32239. /**
  32240. * Compile a Pipe declaration defined by the `R3PipeMetadata`.
  32241. */
  32242. function compileDeclarePipeFromMetadata(meta) {
  32243. var definitionMap = createPipeDefinitionMap(meta);
  32244. var expression = importExpr(Identifiers.declarePipe).callFn([definitionMap.toLiteralMap()]);
  32245. var type = createPipeType(meta);
  32246. return { expression: expression, type: type, statements: [] };
  32247. }
  32248. /**
  32249. * Gathers the declaration fields for a Pipe into a `DefinitionMap`.
  32250. */
  32251. function createPipeDefinitionMap(meta) {
  32252. var definitionMap = new DefinitionMap();
  32253. definitionMap.set('minVersion', literal(MINIMUM_PARTIAL_LINKER_VERSION$6));
  32254. definitionMap.set('version', literal('12.0.5'));
  32255. definitionMap.set('ngImport', importExpr(Identifiers.core));
  32256. // e.g. `type: MyPipe`
  32257. definitionMap.set('type', meta.internalType);
  32258. // e.g. `name: "myPipe"`
  32259. definitionMap.set('name', literal(meta.pipeName));
  32260. if (meta.pure === false) {
  32261. // e.g. `pure: false`
  32262. definitionMap.set('pure', literal(meta.pure));
  32263. }
  32264. return definitionMap;
  32265. }
  32266. /**
  32267. * @license
  32268. * Copyright Google LLC All Rights Reserved.
  32269. *
  32270. * Use of this source code is governed by an MIT-style license that can be
  32271. * found in the LICENSE file at https://angular.io/license
  32272. */
  32273. // This file only reexports content of the `src` folder. Keep it that way.
  32274. // This function call has a global side effects and publishes the compiler into global namespace for
  32275. // the late binding of the Compiler to the @angular/core for jit compilation.
  32276. publishFacade(_global);
  32277. /**
  32278. * @license
  32279. * Copyright Google LLC All Rights Reserved.
  32280. *
  32281. * Use of this source code is governed by an MIT-style license that can be
  32282. * found in the LICENSE file at https://angular.io/license
  32283. */
  32284. // This file only reexports content of the `src` folder. Keep it that way.
  32285. /**
  32286. * @license
  32287. * Copyright Google LLC All Rights Reserved.
  32288. *
  32289. * Use of this source code is governed by an MIT-style license that can be
  32290. * found in the LICENSE file at https://angular.io/license
  32291. */
  32292. /**
  32293. * @license
  32294. * Copyright Google LLC All Rights Reserved.
  32295. *
  32296. * Use of this source code is governed by an MIT-style license that can be
  32297. * found in the LICENSE file at https://angular.io/license
  32298. */
  32299. exports.AST = AST;
  32300. exports.ASTWithName = ASTWithName;
  32301. exports.ASTWithSource = ASTWithSource;
  32302. exports.AbsoluteSourceSpan = AbsoluteSourceSpan;
  32303. exports.AotCompiler = AotCompiler;
  32304. exports.AotSummaryResolver = AotSummaryResolver;
  32305. exports.ArrayType = ArrayType;
  32306. exports.AssertNotNull = AssertNotNull;
  32307. exports.AstMemoryEfficientTransformer = AstMemoryEfficientTransformer;
  32308. exports.AstPath = AstPath;
  32309. exports.AstTransformer = AstTransformer$1;
  32310. exports.AttrAst = AttrAst;
  32311. exports.Attribute = Attribute;
  32312. exports.Binary = Binary;
  32313. exports.BinaryOperatorExpr = BinaryOperatorExpr;
  32314. exports.BindingPipe = BindingPipe;
  32315. exports.BoundDirectivePropertyAst = BoundDirectivePropertyAst;
  32316. exports.BoundElementProperty = BoundElementProperty;
  32317. exports.BoundElementPropertyAst = BoundElementPropertyAst;
  32318. exports.BoundEventAst = BoundEventAst;
  32319. exports.BoundTextAst = BoundTextAst;
  32320. exports.BuiltinType = BuiltinType;
  32321. exports.CONTENT_ATTR = CONTENT_ATTR;
  32322. exports.CUSTOM_ELEMENTS_SCHEMA = CUSTOM_ELEMENTS_SCHEMA;
  32323. exports.CastExpr = CastExpr;
  32324. exports.Chain = Chain;
  32325. exports.ClassField = ClassField;
  32326. exports.ClassMethod = ClassMethod;
  32327. exports.ClassStmt = ClassStmt;
  32328. exports.CommaExpr = CommaExpr;
  32329. exports.Comment = Comment$1;
  32330. exports.CompileDirectiveMetadata = CompileDirectiveMetadata;
  32331. exports.CompileMetadataResolver = CompileMetadataResolver;
  32332. exports.CompileNgModuleMetadata = CompileNgModuleMetadata;
  32333. exports.CompilePipeMetadata = CompilePipeMetadata;
  32334. exports.CompileReflector = CompileReflector;
  32335. exports.CompileShallowModuleMetadata = CompileShallowModuleMetadata;
  32336. exports.CompileStylesheetMetadata = CompileStylesheetMetadata;
  32337. exports.CompileTemplateMetadata = CompileTemplateMetadata;
  32338. exports.CompiledStylesheet = CompiledStylesheet;
  32339. exports.CompilerConfig = CompilerConfig;
  32340. exports.Conditional = Conditional;
  32341. exports.ConditionalExpr = ConditionalExpr;
  32342. exports.ConstantPool = ConstantPool;
  32343. exports.CssSelector = CssSelector;
  32344. exports.DEFAULT_INTERPOLATION_CONFIG = DEFAULT_INTERPOLATION_CONFIG;
  32345. exports.DYNAMIC_TYPE = DYNAMIC_TYPE;
  32346. exports.DeclareFunctionStmt = DeclareFunctionStmt;
  32347. exports.DeclareVarStmt = DeclareVarStmt;
  32348. exports.DirectiveAst = DirectiveAst;
  32349. exports.DirectiveNormalizer = DirectiveNormalizer;
  32350. exports.DirectiveResolver = DirectiveResolver;
  32351. exports.DomElementSchemaRegistry = DomElementSchemaRegistry;
  32352. exports.EOF = EOF;
  32353. exports.ERROR_COMPONENT_TYPE = ERROR_COMPONENT_TYPE;
  32354. exports.Element = Element$1;
  32355. exports.ElementAst = ElementAst;
  32356. exports.ElementSchemaRegistry = ElementSchemaRegistry;
  32357. exports.EmbeddedTemplateAst = EmbeddedTemplateAst;
  32358. exports.EmitterVisitorContext = EmitterVisitorContext;
  32359. exports.EmptyExpr = EmptyExpr;
  32360. exports.Expansion = Expansion;
  32361. exports.ExpansionCase = ExpansionCase;
  32362. exports.Expression = Expression;
  32363. exports.ExpressionBinding = ExpressionBinding;
  32364. exports.ExpressionStatement = ExpressionStatement;
  32365. exports.ExpressionType = ExpressionType;
  32366. exports.ExternalExpr = ExternalExpr;
  32367. exports.ExternalReference = ExternalReference;
  32368. exports.Extractor = Extractor;
  32369. exports.FunctionCall = FunctionCall;
  32370. exports.FunctionExpr = FunctionExpr;
  32371. exports.GeneratedFile = GeneratedFile;
  32372. exports.HOST_ATTR = HOST_ATTR;
  32373. exports.HtmlParser = HtmlParser;
  32374. exports.HtmlTagDefinition = HtmlTagDefinition;
  32375. exports.I18NHtmlParser = I18NHtmlParser;
  32376. exports.Identifiers = Identifiers$1;
  32377. exports.IfStmt = IfStmt;
  32378. exports.ImplicitReceiver = ImplicitReceiver;
  32379. exports.InstantiateExpr = InstantiateExpr;
  32380. exports.Interpolation = Interpolation;
  32381. exports.InterpolationConfig = InterpolationConfig;
  32382. exports.InvokeFunctionExpr = InvokeFunctionExpr;
  32383. exports.InvokeMethodExpr = InvokeMethodExpr;
  32384. exports.IvyParser = IvyParser;
  32385. exports.JSDocComment = JSDocComment;
  32386. exports.JitCompiler = JitCompiler;
  32387. exports.JitEvaluator = JitEvaluator;
  32388. exports.JitSummaryResolver = JitSummaryResolver;
  32389. exports.KeyedRead = KeyedRead;
  32390. exports.KeyedWrite = KeyedWrite;
  32391. exports.LeadingComment = LeadingComment;
  32392. exports.Lexer = Lexer;
  32393. exports.LiteralArray = LiteralArray;
  32394. exports.LiteralArrayExpr = LiteralArrayExpr;
  32395. exports.LiteralExpr = LiteralExpr;
  32396. exports.LiteralMap = LiteralMap;
  32397. exports.LiteralMapExpr = LiteralMapExpr;
  32398. exports.LiteralPrimitive = LiteralPrimitive;
  32399. exports.LocalizedString = LocalizedString;
  32400. exports.MapType = MapType;
  32401. exports.MessageBundle = MessageBundle;
  32402. exports.MethodCall = MethodCall;
  32403. exports.NAMED_ENTITIES = NAMED_ENTITIES;
  32404. exports.NGSP_UNICODE = NGSP_UNICODE;
  32405. exports.NONE_TYPE = NONE_TYPE;
  32406. exports.NO_ERRORS_SCHEMA = NO_ERRORS_SCHEMA;
  32407. exports.NgContentAst = NgContentAst;
  32408. exports.NgModuleCompiler = NgModuleCompiler;
  32409. exports.NgModuleResolver = NgModuleResolver;
  32410. exports.NodeWithI18n = NodeWithI18n;
  32411. exports.NonNullAssert = NonNullAssert;
  32412. exports.NotExpr = NotExpr;
  32413. exports.NullTemplateVisitor = NullTemplateVisitor;
  32414. exports.ParseError = ParseError;
  32415. exports.ParseLocation = ParseLocation;
  32416. exports.ParseSourceFile = ParseSourceFile;
  32417. exports.ParseSourceSpan = ParseSourceSpan;
  32418. exports.ParseSpan = ParseSpan;
  32419. exports.ParseTreeResult = ParseTreeResult;
  32420. exports.ParsedEvent = ParsedEvent;
  32421. exports.ParsedProperty = ParsedProperty;
  32422. exports.ParsedVariable = ParsedVariable;
  32423. exports.Parser = Parser$1;
  32424. exports.ParserError = ParserError;
  32425. exports.PipeResolver = PipeResolver;
  32426. exports.PrefixNot = PrefixNot;
  32427. exports.PropertyRead = PropertyRead;
  32428. exports.PropertyWrite = PropertyWrite;
  32429. exports.ProviderAst = ProviderAst;
  32430. exports.ProviderMeta = ProviderMeta;
  32431. exports.Quote = Quote;
  32432. exports.R3BoundTarget = R3BoundTarget;
  32433. exports.R3Identifiers = Identifiers;
  32434. exports.R3TargetBinder = R3TargetBinder;
  32435. exports.ReadKeyExpr = ReadKeyExpr;
  32436. exports.ReadPropExpr = ReadPropExpr;
  32437. exports.ReadVarExpr = ReadVarExpr;
  32438. exports.RecursiveAstVisitor = RecursiveAstVisitor$1;
  32439. exports.RecursiveTemplateAstVisitor = RecursiveTemplateAstVisitor;
  32440. exports.RecursiveVisitor = RecursiveVisitor$1;
  32441. exports.ReferenceAst = ReferenceAst;
  32442. exports.ResolvedStaticSymbol = ResolvedStaticSymbol;
  32443. exports.ResourceLoader = ResourceLoader;
  32444. exports.ReturnStatement = ReturnStatement;
  32445. exports.STRING_TYPE = STRING_TYPE;
  32446. exports.SafeMethodCall = SafeMethodCall;
  32447. exports.SafePropertyRead = SafePropertyRead;
  32448. exports.SelectorContext = SelectorContext;
  32449. exports.SelectorListContext = SelectorListContext;
  32450. exports.SelectorMatcher = SelectorMatcher;
  32451. exports.Serializer = Serializer;
  32452. exports.SplitInterpolation = SplitInterpolation;
  32453. exports.Statement = Statement;
  32454. exports.StaticReflector = StaticReflector;
  32455. exports.StaticSymbol = StaticSymbol;
  32456. exports.StaticSymbolCache = StaticSymbolCache;
  32457. exports.StaticSymbolResolver = StaticSymbolResolver;
  32458. exports.StyleCompiler = StyleCompiler;
  32459. exports.StylesCompileDependency = StylesCompileDependency;
  32460. exports.SummaryResolver = SummaryResolver;
  32461. exports.TaggedTemplateExpr = TaggedTemplateExpr;
  32462. exports.TemplateBindingParseResult = TemplateBindingParseResult;
  32463. exports.TemplateLiteral = TemplateLiteral;
  32464. exports.TemplateLiteralElement = TemplateLiteralElement;
  32465. exports.TemplateParseError = TemplateParseError;
  32466. exports.TemplateParseResult = TemplateParseResult;
  32467. exports.TemplateParser = TemplateParser;
  32468. exports.Text = Text$3;
  32469. exports.TextAst = TextAst;
  32470. exports.ThisReceiver = ThisReceiver;
  32471. exports.ThrowStmt = ThrowStmt;
  32472. exports.TmplAstBoundAttribute = BoundAttribute;
  32473. exports.TmplAstBoundEvent = BoundEvent;
  32474. exports.TmplAstBoundText = BoundText;
  32475. exports.TmplAstContent = Content;
  32476. exports.TmplAstElement = Element;
  32477. exports.TmplAstIcu = Icu;
  32478. exports.TmplAstRecursiveVisitor = RecursiveVisitor;
  32479. exports.TmplAstReference = Reference;
  32480. exports.TmplAstTemplate = Template;
  32481. exports.TmplAstText = Text;
  32482. exports.TmplAstTextAttribute = TextAttribute;
  32483. exports.TmplAstVariable = Variable;
  32484. exports.Token = Token$1;
  32485. exports.TransitiveCompileNgModuleMetadata = TransitiveCompileNgModuleMetadata;
  32486. exports.TreeError = TreeError;
  32487. exports.TryCatchStmt = TryCatchStmt;
  32488. exports.Type = Type$1;
  32489. exports.TypeScriptEmitter = TypeScriptEmitter;
  32490. exports.TypeofExpr = TypeofExpr;
  32491. exports.Unary = Unary;
  32492. exports.UnaryOperatorExpr = UnaryOperatorExpr;
  32493. exports.UrlResolver = UrlResolver;
  32494. exports.VERSION = VERSION$1;
  32495. exports.VariableAst = VariableAst;
  32496. exports.VariableBinding = VariableBinding;
  32497. exports.Version = Version;
  32498. exports.ViewCompiler = ViewCompiler;
  32499. exports.WrappedNodeExpr = WrappedNodeExpr;
  32500. exports.WriteKeyExpr = WriteKeyExpr;
  32501. exports.WritePropExpr = WritePropExpr;
  32502. exports.WriteVarExpr = WriteVarExpr;
  32503. exports.Xliff = Xliff;
  32504. exports.Xliff2 = Xliff2;
  32505. exports.Xmb = Xmb;
  32506. exports.XmlParser = XmlParser;
  32507. exports.Xtb = Xtb;
  32508. exports._ParseAST = _ParseAST;
  32509. exports.analyzeAndValidateNgModules = analyzeAndValidateNgModules;
  32510. exports.analyzeFile = analyzeFile;
  32511. exports.analyzeFileForInjectables = analyzeFileForInjectables;
  32512. exports.analyzeNgModules = analyzeNgModules;
  32513. exports.collectExternalReferences = collectExternalReferences;
  32514. exports.compileClassMetadata = compileClassMetadata;
  32515. exports.compileComponentFromMetadata = compileComponentFromMetadata;
  32516. exports.compileDeclareClassMetadata = compileDeclareClassMetadata;
  32517. exports.compileDeclareComponentFromMetadata = compileDeclareComponentFromMetadata;
  32518. exports.compileDeclareDirectiveFromMetadata = compileDeclareDirectiveFromMetadata;
  32519. exports.compileDeclareFactoryFunction = compileDeclareFactoryFunction;
  32520. exports.compileDeclareInjectableFromMetadata = compileDeclareInjectableFromMetadata;
  32521. exports.compileDeclareInjectorFromMetadata = compileDeclareInjectorFromMetadata;
  32522. exports.compileDeclareNgModuleFromMetadata = compileDeclareNgModuleFromMetadata;
  32523. exports.compileDeclarePipeFromMetadata = compileDeclarePipeFromMetadata;
  32524. exports.compileDirectiveFromMetadata = compileDirectiveFromMetadata;
  32525. exports.compileFactoryFunction = compileFactoryFunction;
  32526. exports.compileInjectable = compileInjectable;
  32527. exports.compileInjector = compileInjector;
  32528. exports.compileNgModule = compileNgModule;
  32529. exports.compilePipeFromMetadata = compilePipeFromMetadata;
  32530. exports.componentFactoryName = componentFactoryName;
  32531. exports.computeMsgId = computeMsgId;
  32532. exports.core = core;
  32533. exports.createAotCompiler = createAotCompiler;
  32534. exports.createAotUrlResolver = createAotUrlResolver;
  32535. exports.createElementCssSelector = createElementCssSelector;
  32536. exports.createInjectableType = createInjectableType;
  32537. exports.createLoweredSymbol = createLoweredSymbol;
  32538. exports.createOfflineCompileUrlResolver = createOfflineCompileUrlResolver;
  32539. exports.createR3ProviderExpression = createR3ProviderExpression;
  32540. exports.createUrlResolverWithoutPackagePrefix = createUrlResolverWithoutPackagePrefix;
  32541. exports.debugOutputAstAsTypeScript = debugOutputAstAsTypeScript;
  32542. exports.devOnlyGuardedExpression = devOnlyGuardedExpression;
  32543. exports.findNode = findNode;
  32544. exports.flatten = flatten;
  32545. exports.formattedError = formattedError;
  32546. exports.getHtmlTagDefinition = getHtmlTagDefinition;
  32547. exports.getMissingNgModuleMetadataErrorData = getMissingNgModuleMetadataErrorData;
  32548. exports.getNsPrefix = getNsPrefix;
  32549. exports.getParseErrors = getParseErrors;
  32550. exports.getSafePropertyAccessString = getSafePropertyAccessString;
  32551. exports.getUrlScheme = getUrlScheme;
  32552. exports.hostViewClassName = hostViewClassName;
  32553. exports.identifierModuleUrl = identifierModuleUrl;
  32554. exports.identifierName = identifierName;
  32555. exports.isEmptyExpression = isEmptyExpression;
  32556. exports.isFormattedError = isFormattedError;
  32557. exports.isIdentifier = isIdentifier;
  32558. exports.isLoweredSymbol = isLoweredSymbol;
  32559. exports.isNgContainer = isNgContainer;
  32560. exports.isNgContent = isNgContent;
  32561. exports.isNgTemplate = isNgTemplate;
  32562. exports.isQuote = isQuote;
  32563. exports.isSyntaxError = isSyntaxError;
  32564. exports.jsDocComment = jsDocComment;
  32565. exports.leadingComment = leadingComment;
  32566. exports.literalMap = literalMap;
  32567. exports.makeBindingParser = makeBindingParser;
  32568. exports.mergeAnalyzedFiles = mergeAnalyzedFiles;
  32569. exports.mergeNsAndName = mergeNsAndName;
  32570. exports.ngModuleJitUrl = ngModuleJitUrl;
  32571. exports.parseHostBindings = parseHostBindings;
  32572. exports.parseTemplate = parseTemplate;
  32573. exports.preserveWhitespacesDefault = preserveWhitespacesDefault;
  32574. exports.publishFacade = publishFacade;
  32575. exports.r3JitTypeSourceSpan = r3JitTypeSourceSpan;
  32576. exports.removeSummaryDuplicates = removeSummaryDuplicates;
  32577. exports.rendererTypeName = rendererTypeName;
  32578. exports.sanitizeIdentifier = sanitizeIdentifier;
  32579. exports.sharedStylesheetJitUrl = sharedStylesheetJitUrl;
  32580. exports.splitClasses = splitClasses;
  32581. exports.splitNsName = splitNsName;
  32582. exports.syntaxError = syntaxError;
  32583. exports.templateJitUrl = templateJitUrl;
  32584. exports.templateSourceUrl = templateSourceUrl;
  32585. exports.templateVisitAll = templateVisitAll;
  32586. exports.toTypeScript = toTypeScript;
  32587. exports.tokenName = tokenName;
  32588. exports.tokenReference = tokenReference;
  32589. exports.typeSourceSpan = typeSourceSpan;
  32590. exports.unescapeIdentifier = unescapeIdentifier;
  32591. exports.unwrapResolvedMetadata = unwrapResolvedMetadata;
  32592. exports.verifyHostBindings = verifyHostBindings;
  32593. exports.viewClassName = viewClassName;
  32594. exports.visitAll = visitAll$1;
  32595. Object.defineProperty(exports, '__esModule', { value: true });
  32596. })));
  32597. //# sourceMappingURL=compiler.umd.js.map