@angular-eslint/bundled-angular-compiler 13.2.1 → 14.0.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +3 -2
- package/dist/index.js +227 -169
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @license Angular
|
|
2
|
+
* @license Angular v14.0.0-rc.2
|
|
3
3
|
* (c) 2010-2022 Google LLC. https://angular.io/
|
|
4
4
|
* License: MIT
|
|
5
5
|
*/ /**
|
|
@@ -59,10 +59,10 @@ return (_b=(_a=TAG_DEFINITIONS[tagName])!==null&&_a!==void 0?_a:TAG_DEFINITIONS[
|
|
|
59
59
|
* ```
|
|
60
60
|
* ['key1', 'value1', 'key2', '']
|
|
61
61
|
* ```
|
|
62
|
-
*/this.attrs=[];this.notSelectors=[];}static parse(selector){const results=[];const _addResult=(res,cssSel)=>{if(cssSel.notSelectors.length>0&&!cssSel.element&&cssSel.classNames.length==0&&cssSel.attrs.length==0){cssSel.element='*';}res.push(cssSel);};let cssSelector=new CssSelector();let match;let current=cssSelector;let inNot=false;_SELECTOR_REGEXP.lastIndex=0;while(match=_SELECTOR_REGEXP.exec(selector)){if(match[1/* NOT */]){if(inNot){throw new Error('Nesting :not in a selector is not allowed');}inNot=true;current=new CssSelector();cssSelector.notSelectors.push(current);}const tag=match[2/* TAG */];if(tag){const prefix=match[3/* PREFIX */];if(prefix==='#'){// #hash
|
|
63
|
-
current.addAttribute('id',tag.
|
|
64
|
-
current.addClassName(tag.
|
|
65
|
-
current.setElement(tag);}}const attribute=match[4/* ATTRIBUTE */];if(attribute){current.addAttribute(current.unescapeAttribute(attribute),match[6/* ATTRIBUTE_VALUE */]);}if(match[7/* NOT_END */]){inNot=false;current=cssSelector;}if(match[8/* SEPARATOR */]){if(inNot){throw new Error('Multiple selectors in :not are not supported');}_addResult(results,cssSelector);cssSelector=current=new CssSelector();}}_addResult(results,cssSelector);return results;}/**
|
|
62
|
+
*/this.attrs=[];this.notSelectors=[];}static parse(selector){const results=[];const _addResult=(res,cssSel)=>{if(cssSel.notSelectors.length>0&&!cssSel.element&&cssSel.classNames.length==0&&cssSel.attrs.length==0){cssSel.element='*';}res.push(cssSel);};let cssSelector=new CssSelector();let match;let current=cssSelector;let inNot=false;_SELECTOR_REGEXP.lastIndex=0;while(match=_SELECTOR_REGEXP.exec(selector)){if(match[1/* SelectorRegexp.NOT */]){if(inNot){throw new Error('Nesting :not in a selector is not allowed');}inNot=true;current=new CssSelector();cssSelector.notSelectors.push(current);}const tag=match[2/* SelectorRegexp.TAG */];if(tag){const prefix=match[3/* SelectorRegexp.PREFIX */];if(prefix==='#'){// #hash
|
|
63
|
+
current.addAttribute('id',tag.slice(1));}else if(prefix==='.'){// Class
|
|
64
|
+
current.addClassName(tag.slice(1));}else {// Element
|
|
65
|
+
current.setElement(tag);}}const attribute=match[4/* SelectorRegexp.ATTRIBUTE */];if(attribute){current.addAttribute(current.unescapeAttribute(attribute),match[6/* SelectorRegexp.ATTRIBUTE_VALUE */]);}if(match[7/* SelectorRegexp.NOT_END */]){inNot=false;current=cssSelector;}if(match[8/* SelectorRegexp.SEPARATOR */]){if(inNot){throw new Error('Multiple selectors in :not are not supported');}_addResult(results,cssSelector);cssSelector=current=new CssSelector();}}_addResult(results,cssSelector);return results;}/**
|
|
66
66
|
* Unescape `\$` sequences from the CSS attribute selector.
|
|
67
67
|
*
|
|
68
68
|
* This is needed because `$` can have a special meaning in CSS selectors,
|
|
@@ -106,7 +106,7 @@ class SelectorContext{constructor(selector,cbContext,listContext){this.selector=
|
|
|
106
106
|
*/ // Stores the default value of `emitDistinctChangesOnly` when the `emitDistinctChangesOnly` is not
|
|
107
107
|
// explicitly set.
|
|
108
108
|
const emitDistinctChangesOnlyDefaultValue=true;exports.ViewEncapsulation = void 0;(function(ViewEncapsulation){ViewEncapsulation[ViewEncapsulation["Emulated"]=0]="Emulated";// Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
|
|
109
|
-
ViewEncapsulation[ViewEncapsulation["None"]=2]="None";ViewEncapsulation[ViewEncapsulation["ShadowDom"]=3]="ShadowDom";})(exports.ViewEncapsulation||(exports.ViewEncapsulation={}));exports.ChangeDetectionStrategy = void 0;(function(ChangeDetectionStrategy){ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"]=0]="OnPush";ChangeDetectionStrategy[ChangeDetectionStrategy["Default"]=1]="Default";})(exports.ChangeDetectionStrategy||(exports.ChangeDetectionStrategy={}));const CUSTOM_ELEMENTS_SCHEMA={name:'custom-elements'};const NO_ERRORS_SCHEMA={name:'no-errors-schema'};const Type$1=Function;var SecurityContext;(function(SecurityContext){SecurityContext[SecurityContext["NONE"]=0]="NONE";SecurityContext[SecurityContext["HTML"]=1]="HTML";SecurityContext[SecurityContext["STYLE"]=2]="STYLE";SecurityContext[SecurityContext["SCRIPT"]=3]="SCRIPT";SecurityContext[SecurityContext["URL"]=4]="URL";SecurityContext[SecurityContext["RESOURCE_URL"]=5]="RESOURCE_URL";})(SecurityContext||(SecurityContext={}));var MissingTranslationStrategy;(function(MissingTranslationStrategy){MissingTranslationStrategy[MissingTranslationStrategy["Error"]=0]="Error";MissingTranslationStrategy[MissingTranslationStrategy["Warning"]=1]="Warning";MissingTranslationStrategy[MissingTranslationStrategy["Ignore"]=2]="Ignore";})(MissingTranslationStrategy||(MissingTranslationStrategy={}));function parserSelectorToSimpleSelector(selector){const classes=selector.classNames&&selector.classNames.length?[8/* CLASS */,...selector.classNames]:[];const elementName=selector.element&&selector.element!=='*'?selector.element:'';return [elementName,...selector.attrs,...classes];}function parserSelectorToNegativeSelector(selector){const classes=selector.classNames&&selector.classNames.length?[8/* CLASS */,...selector.classNames]:[];if(selector.element){return [1/* NOT */|4/* ELEMENT */,selector.element,...selector.attrs,...classes];}else if(selector.attrs.length){return [1/* NOT */|2/* ATTRIBUTE */,...selector.attrs,...classes];}else {return selector.classNames&&selector.classNames.length?[1/* NOT */|8/* CLASS */,...selector.classNames]:[];}}function parserSelectorToR3Selector(selector){const positive=parserSelectorToSimpleSelector(selector);const negative=selector.notSelectors&&selector.notSelectors.length?selector.notSelectors.map(notSelector=>parserSelectorToNegativeSelector(notSelector)):[];return positive.concat(...negative);}function parseSelectorToR3Selector(selector){return selector?CssSelector.parse(selector).map(parserSelectorToR3Selector):[];}var core=/*#__PURE__*/Object.freeze({__proto__:null,emitDistinctChangesOnlyDefaultValue:emitDistinctChangesOnlyDefaultValue,get ViewEncapsulation(){return exports.ViewEncapsulation;},get ChangeDetectionStrategy(){return exports.ChangeDetectionStrategy;},CUSTOM_ELEMENTS_SCHEMA:CUSTOM_ELEMENTS_SCHEMA,NO_ERRORS_SCHEMA:NO_ERRORS_SCHEMA,Type:Type$1,get SecurityContext(){return SecurityContext;},get MissingTranslationStrategy(){return MissingTranslationStrategy;},parseSelectorToR3Selector:parseSelectorToR3Selector});/**
|
|
109
|
+
ViewEncapsulation[ViewEncapsulation["None"]=2]="None";ViewEncapsulation[ViewEncapsulation["ShadowDom"]=3]="ShadowDom";})(exports.ViewEncapsulation||(exports.ViewEncapsulation={}));exports.ChangeDetectionStrategy = void 0;(function(ChangeDetectionStrategy){ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"]=0]="OnPush";ChangeDetectionStrategy[ChangeDetectionStrategy["Default"]=1]="Default";})(exports.ChangeDetectionStrategy||(exports.ChangeDetectionStrategy={}));const CUSTOM_ELEMENTS_SCHEMA={name:'custom-elements'};const NO_ERRORS_SCHEMA={name:'no-errors-schema'};const Type$1=Function;var SecurityContext;(function(SecurityContext){SecurityContext[SecurityContext["NONE"]=0]="NONE";SecurityContext[SecurityContext["HTML"]=1]="HTML";SecurityContext[SecurityContext["STYLE"]=2]="STYLE";SecurityContext[SecurityContext["SCRIPT"]=3]="SCRIPT";SecurityContext[SecurityContext["URL"]=4]="URL";SecurityContext[SecurityContext["RESOURCE_URL"]=5]="RESOURCE_URL";})(SecurityContext||(SecurityContext={}));var MissingTranslationStrategy;(function(MissingTranslationStrategy){MissingTranslationStrategy[MissingTranslationStrategy["Error"]=0]="Error";MissingTranslationStrategy[MissingTranslationStrategy["Warning"]=1]="Warning";MissingTranslationStrategy[MissingTranslationStrategy["Ignore"]=2]="Ignore";})(MissingTranslationStrategy||(MissingTranslationStrategy={}));function parserSelectorToSimpleSelector(selector){const classes=selector.classNames&&selector.classNames.length?[8/* SelectorFlags.CLASS */,...selector.classNames]:[];const elementName=selector.element&&selector.element!=='*'?selector.element:'';return [elementName,...selector.attrs,...classes];}function parserSelectorToNegativeSelector(selector){const classes=selector.classNames&&selector.classNames.length?[8/* SelectorFlags.CLASS */,...selector.classNames]:[];if(selector.element){return [1/* SelectorFlags.NOT */|4/* SelectorFlags.ELEMENT */,selector.element,...selector.attrs,...classes];}else if(selector.attrs.length){return [1/* SelectorFlags.NOT */|2/* SelectorFlags.ATTRIBUTE */,...selector.attrs,...classes];}else {return selector.classNames&&selector.classNames.length?[1/* SelectorFlags.NOT */|8/* SelectorFlags.CLASS */,...selector.classNames]:[];}}function parserSelectorToR3Selector(selector){const positive=parserSelectorToSimpleSelector(selector);const negative=selector.notSelectors&&selector.notSelectors.length?selector.notSelectors.map(notSelector=>parserSelectorToNegativeSelector(notSelector)):[];return positive.concat(...negative);}function parseSelectorToR3Selector(selector){return selector?CssSelector.parse(selector).map(parserSelectorToR3Selector):[];}var core=/*#__PURE__*/Object.freeze({__proto__:null,emitDistinctChangesOnlyDefaultValue:emitDistinctChangesOnlyDefaultValue,get ViewEncapsulation(){return exports.ViewEncapsulation;},get ChangeDetectionStrategy(){return exports.ChangeDetectionStrategy;},CUSTOM_ELEMENTS_SCHEMA:CUSTOM_ELEMENTS_SCHEMA,NO_ERRORS_SCHEMA:NO_ERRORS_SCHEMA,Type:Type$1,get SecurityContext(){return SecurityContext;},get MissingTranslationStrategy(){return MissingTranslationStrategy;},parseSelectorToR3Selector:parseSelectorToR3Selector});/**
|
|
110
110
|
* @license
|
|
111
111
|
* Copyright Google LLC All Rights Reserved.
|
|
112
112
|
*
|
|
@@ -117,9 +117,11 @@ function utf8Encode(str){let encoded=[];for(let index=0;index<str.length;index++
|
|
|
117
117
|
// see https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
|
|
118
118
|
if(codePoint>=0xd800&&codePoint<=0xdbff&&str.length>index+1){const low=str.charCodeAt(index+1);if(low>=0xdc00&&low<=0xdfff){index++;codePoint=(codePoint-0xd800<<10)+low-0xdc00+0x10000;}}if(codePoint<=0x7f){encoded.push(codePoint);}else if(codePoint<=0x7ff){encoded.push(codePoint>>6&0x1F|0xc0,codePoint&0x3f|0x80);}else if(codePoint<=0xffff){encoded.push(codePoint>>12|0xe0,codePoint>>6&0x3f|0x80,codePoint&0x3f|0x80);}else if(codePoint<=0x1fffff){encoded.push(codePoint>>18&0x07|0xf0,codePoint>>12&0x3f|0x80,codePoint>>6&0x3f|0x80,codePoint&0x3f|0x80);}}return encoded;}function stringify(token){if(typeof token==='string'){return token;}if(Array.isArray(token)){return '['+token.map(stringify).join(', ')+']';}if(token==null){return ''+token;}if(token.overriddenName){return `${token.overriddenName}`;}if(token.name){return `${token.name}`;}if(!token.toString){return 'object';}// WARNING: do not try to `JSON.stringify(token)` here
|
|
119
119
|
// see https://github.com/angular/angular/issues/23440
|
|
120
|
-
const res=token.toString();if(res==null){return ''+res;}const newLineIndex=res.indexOf('\n');return newLineIndex===-1?res:res.substring(0,newLineIndex);}class Version{constructor(full){this.full=full;const splits=full.split('.');this.major=splits[0];this.minor=splits[1];this.patch=splits.slice(2).join('.');}}
|
|
121
|
-
// should
|
|
122
|
-
|
|
120
|
+
const res=token.toString();if(res==null){return ''+res;}const newLineIndex=res.indexOf('\n');return newLineIndex===-1?res:res.substring(0,newLineIndex);}class Version{constructor(full){this.full=full;const splits=full.split('.');this.major=splits[0];this.minor=splits[1];this.patch=splits.slice(2).join('.');}}// Check `global` first, because in Node tests both `global` and `window` may be defined and our
|
|
121
|
+
// `_global` variable should point to the NodeJS `global` in that case. Note: Typeof/Instanceof
|
|
122
|
+
// checks are considered side-effects in Terser. We explicitly mark this as side-effect free:
|
|
123
|
+
// https://github.com/terser/terser/issues/250.
|
|
124
|
+
const _global=/* @__PURE__ */(()=>typeof global!=='undefined'&&global||typeof window!=='undefined'&&window||typeof self!=='undefined'&&typeof WorkerGlobalScope!=='undefined'&&self instanceof WorkerGlobalScope&&self)();function newArray(size,value){const list=[];for(let i=0;i<size;i++){list.push(value);}return list;}/**
|
|
123
125
|
* Partitions a given array into 2 arrays, based on a boolean value returned by the condition
|
|
124
126
|
* function.
|
|
125
127
|
*
|
|
@@ -398,7 +400,7 @@ if(literal instanceof LiteralArrayExpr){const argumentsForKey=literal.entries.ma
|
|
|
398
400
|
*
|
|
399
401
|
* Use of this source code is governed by an MIT-style license that can be
|
|
400
402
|
* found in the LICENSE file at https://angular.io/license
|
|
401
|
-
*/const CORE='@angular/core';class Identifiers{}/* Methods */Identifiers.NEW_METHOD='factory';Identifiers.TRANSFORM_METHOD='transform';Identifiers.PATCH_DEPS='patchedDeps';Identifiers.core={name:null,moduleName:CORE};/* Instructions */Identifiers.namespaceHTML={name:'ɵɵnamespaceHTML',moduleName:CORE};Identifiers.namespaceMathML={name:'ɵɵnamespaceMathML',moduleName:CORE};Identifiers.namespaceSVG={name:'ɵɵnamespaceSVG',moduleName:CORE};Identifiers.element={name:'ɵɵelement',moduleName:CORE};Identifiers.elementStart={name:'ɵɵelementStart',moduleName:CORE};Identifiers.elementEnd={name:'ɵɵelementEnd',moduleName:CORE};Identifiers.advance={name:'ɵɵadvance',moduleName:CORE};Identifiers.syntheticHostProperty={name:'ɵɵsyntheticHostProperty',moduleName:CORE};Identifiers.syntheticHostListener={name:'ɵɵsyntheticHostListener',moduleName:CORE};Identifiers.attribute={name:'ɵɵattribute',moduleName:CORE};Identifiers.attributeInterpolate1={name:'ɵɵattributeInterpolate1',moduleName:CORE};Identifiers.attributeInterpolate2={name:'ɵɵattributeInterpolate2',moduleName:CORE};Identifiers.attributeInterpolate3={name:'ɵɵattributeInterpolate3',moduleName:CORE};Identifiers.attributeInterpolate4={name:'ɵɵattributeInterpolate4',moduleName:CORE};Identifiers.attributeInterpolate5={name:'ɵɵattributeInterpolate5',moduleName:CORE};Identifiers.attributeInterpolate6={name:'ɵɵattributeInterpolate6',moduleName:CORE};Identifiers.attributeInterpolate7={name:'ɵɵattributeInterpolate7',moduleName:CORE};Identifiers.attributeInterpolate8={name:'ɵɵattributeInterpolate8',moduleName:CORE};Identifiers.attributeInterpolateV={name:'ɵɵattributeInterpolateV',moduleName:CORE};Identifiers.classProp={name:'ɵɵclassProp',moduleName:CORE};Identifiers.elementContainerStart={name:'ɵɵelementContainerStart',moduleName:CORE};Identifiers.elementContainerEnd={name:'ɵɵelementContainerEnd',moduleName:CORE};Identifiers.elementContainer={name:'ɵɵelementContainer',moduleName:CORE};Identifiers.styleMap={name:'ɵɵstyleMap',moduleName:CORE};Identifiers.styleMapInterpolate1={name:'ɵɵstyleMapInterpolate1',moduleName:CORE};Identifiers.styleMapInterpolate2={name:'ɵɵstyleMapInterpolate2',moduleName:CORE};Identifiers.styleMapInterpolate3={name:'ɵɵstyleMapInterpolate3',moduleName:CORE};Identifiers.styleMapInterpolate4={name:'ɵɵstyleMapInterpolate4',moduleName:CORE};Identifiers.styleMapInterpolate5={name:'ɵɵstyleMapInterpolate5',moduleName:CORE};Identifiers.styleMapInterpolate6={name:'ɵɵstyleMapInterpolate6',moduleName:CORE};Identifiers.styleMapInterpolate7={name:'ɵɵstyleMapInterpolate7',moduleName:CORE};Identifiers.styleMapInterpolate8={name:'ɵɵstyleMapInterpolate8',moduleName:CORE};Identifiers.styleMapInterpolateV={name:'ɵɵstyleMapInterpolateV',moduleName:CORE};Identifiers.classMap={name:'ɵɵclassMap',moduleName:CORE};Identifiers.classMapInterpolate1={name:'ɵɵclassMapInterpolate1',moduleName:CORE};Identifiers.classMapInterpolate2={name:'ɵɵclassMapInterpolate2',moduleName:CORE};Identifiers.classMapInterpolate3={name:'ɵɵclassMapInterpolate3',moduleName:CORE};Identifiers.classMapInterpolate4={name:'ɵɵclassMapInterpolate4',moduleName:CORE};Identifiers.classMapInterpolate5={name:'ɵɵclassMapInterpolate5',moduleName:CORE};Identifiers.classMapInterpolate6={name:'ɵɵclassMapInterpolate6',moduleName:CORE};Identifiers.classMapInterpolate7={name:'ɵɵclassMapInterpolate7',moduleName:CORE};Identifiers.classMapInterpolate8={name:'ɵɵclassMapInterpolate8',moduleName:CORE};Identifiers.classMapInterpolateV={name:'ɵɵclassMapInterpolateV',moduleName:CORE};Identifiers.styleProp={name:'ɵɵstyleProp',moduleName:CORE};Identifiers.stylePropInterpolate1={name:'ɵɵstylePropInterpolate1',moduleName:CORE};Identifiers.stylePropInterpolate2={name:'ɵɵstylePropInterpolate2',moduleName:CORE};Identifiers.stylePropInterpolate3={name:'ɵɵstylePropInterpolate3',moduleName:CORE};Identifiers.stylePropInterpolate4={name:'ɵɵstylePropInterpolate4',moduleName:CORE};Identifiers.stylePropInterpolate5={name:'ɵɵstylePropInterpolate5',moduleName:CORE};Identifiers.stylePropInterpolate6={name:'ɵɵstylePropInterpolate6',moduleName:CORE};Identifiers.stylePropInterpolate7={name:'ɵɵstylePropInterpolate7',moduleName:CORE};Identifiers.stylePropInterpolate8={name:'ɵɵstylePropInterpolate8',moduleName:CORE};Identifiers.stylePropInterpolateV={name:'ɵɵstylePropInterpolateV',moduleName:CORE};Identifiers.nextContext={name:'ɵɵnextContext',moduleName:CORE};Identifiers.templateCreate={name:'ɵɵtemplate',moduleName:CORE};Identifiers.text={name:'ɵɵtext',moduleName:CORE};Identifiers.enableBindings={name:'ɵɵenableBindings',moduleName:CORE};Identifiers.disableBindings={name:'ɵɵdisableBindings',moduleName:CORE};Identifiers.getCurrentView={name:'ɵɵgetCurrentView',moduleName:CORE};Identifiers.textInterpolate={name:'ɵɵtextInterpolate',moduleName:CORE};Identifiers.textInterpolate1={name:'ɵɵtextInterpolate1',moduleName:CORE};Identifiers.textInterpolate2={name:'ɵɵtextInterpolate2',moduleName:CORE};Identifiers.textInterpolate3={name:'ɵɵtextInterpolate3',moduleName:CORE};Identifiers.textInterpolate4={name:'ɵɵtextInterpolate4',moduleName:CORE};Identifiers.textInterpolate5={name:'ɵɵtextInterpolate5',moduleName:CORE};Identifiers.textInterpolate6={name:'ɵɵtextInterpolate6',moduleName:CORE};Identifiers.textInterpolate7={name:'ɵɵtextInterpolate7',moduleName:CORE};Identifiers.textInterpolate8={name:'ɵɵtextInterpolate8',moduleName:CORE};Identifiers.textInterpolateV={name:'ɵɵtextInterpolateV',moduleName:CORE};Identifiers.restoreView={name:'ɵɵrestoreView',moduleName:CORE};Identifiers.pureFunction0={name:'ɵɵpureFunction0',moduleName:CORE};Identifiers.pureFunction1={name:'ɵɵpureFunction1',moduleName:CORE};Identifiers.pureFunction2={name:'ɵɵpureFunction2',moduleName:CORE};Identifiers.pureFunction3={name:'ɵɵpureFunction3',moduleName:CORE};Identifiers.pureFunction4={name:'ɵɵpureFunction4',moduleName:CORE};Identifiers.pureFunction5={name:'ɵɵpureFunction5',moduleName:CORE};Identifiers.pureFunction6={name:'ɵɵpureFunction6',moduleName:CORE};Identifiers.pureFunction7={name:'ɵɵpureFunction7',moduleName:CORE};Identifiers.pureFunction8={name:'ɵɵpureFunction8',moduleName:CORE};Identifiers.pureFunctionV={name:'ɵɵpureFunctionV',moduleName:CORE};Identifiers.pipeBind1={name:'ɵɵpipeBind1',moduleName:CORE};Identifiers.pipeBind2={name:'ɵɵpipeBind2',moduleName:CORE};Identifiers.pipeBind3={name:'ɵɵpipeBind3',moduleName:CORE};Identifiers.pipeBind4={name:'ɵɵpipeBind4',moduleName:CORE};Identifiers.pipeBindV={name:'ɵɵpipeBindV',moduleName:CORE};Identifiers.hostProperty={name:'ɵɵhostProperty',moduleName:CORE};Identifiers.property={name:'ɵɵproperty',moduleName:CORE};Identifiers.propertyInterpolate={name:'ɵɵpropertyInterpolate',moduleName:CORE};Identifiers.propertyInterpolate1={name:'ɵɵpropertyInterpolate1',moduleName:CORE};Identifiers.propertyInterpolate2={name:'ɵɵpropertyInterpolate2',moduleName:CORE};Identifiers.propertyInterpolate3={name:'ɵɵpropertyInterpolate3',moduleName:CORE};Identifiers.propertyInterpolate4={name:'ɵɵpropertyInterpolate4',moduleName:CORE};Identifiers.propertyInterpolate5={name:'ɵɵpropertyInterpolate5',moduleName:CORE};Identifiers.propertyInterpolate6={name:'ɵɵpropertyInterpolate6',moduleName:CORE};Identifiers.propertyInterpolate7={name:'ɵɵpropertyInterpolate7',moduleName:CORE};Identifiers.propertyInterpolate8={name:'ɵɵpropertyInterpolate8',moduleName:CORE};Identifiers.propertyInterpolateV={name:'ɵɵpropertyInterpolateV',moduleName:CORE};Identifiers.i18n={name:'ɵɵi18n',moduleName:CORE};Identifiers.i18nAttributes={name:'ɵɵi18nAttributes',moduleName:CORE};Identifiers.i18nExp={name:'ɵɵi18nExp',moduleName:CORE};Identifiers.i18nStart={name:'ɵɵi18nStart',moduleName:CORE};Identifiers.i18nEnd={name:'ɵɵi18nEnd',moduleName:CORE};Identifiers.i18nApply={name:'ɵɵi18nApply',moduleName:CORE};Identifiers.i18nPostprocess={name:'ɵɵi18nPostprocess',moduleName:CORE};Identifiers.pipe={name:'ɵɵpipe',moduleName:CORE};Identifiers.projection={name:'ɵɵprojection',moduleName:CORE};Identifiers.projectionDef={name:'ɵɵprojectionDef',moduleName:CORE};Identifiers.reference={name:'ɵɵreference',moduleName:CORE};Identifiers.inject={name:'ɵɵinject',moduleName:CORE};Identifiers.injectAttribute={name:'ɵɵinjectAttribute',moduleName:CORE};Identifiers.directiveInject={name:'ɵɵdirectiveInject',moduleName:CORE};Identifiers.invalidFactory={name:'ɵɵinvalidFactory',moduleName:CORE};Identifiers.invalidFactoryDep={name:'ɵɵinvalidFactoryDep',moduleName:CORE};Identifiers.templateRefExtractor={name:'ɵɵtemplateRefExtractor',moduleName:CORE};Identifiers.forwardRef={name:'forwardRef',moduleName:CORE};Identifiers.resolveForwardRef={name:'resolveForwardRef',moduleName:CORE};Identifiers.ɵɵdefineInjectable={name:'ɵɵdefineInjectable',moduleName:CORE};Identifiers.declareInjectable={name:'ɵɵngDeclareInjectable',moduleName:CORE};Identifiers.InjectableDeclaration={name:'ɵɵInjectableDeclaration',moduleName:CORE};Identifiers.resolveWindow={name:'ɵɵresolveWindow',moduleName:CORE};Identifiers.resolveDocument={name:'ɵɵresolveDocument',moduleName:CORE};Identifiers.resolveBody={name:'ɵɵresolveBody',moduleName:CORE};Identifiers.defineComponent={name:'ɵɵdefineComponent',moduleName:CORE};Identifiers.declareComponent={name:'ɵɵngDeclareComponent',moduleName:CORE};Identifiers.setComponentScope={name:'ɵɵsetComponentScope',moduleName:CORE};Identifiers.ChangeDetectionStrategy={name:'ChangeDetectionStrategy',moduleName:CORE};Identifiers.ViewEncapsulation={name:'ViewEncapsulation',moduleName:CORE};Identifiers.ComponentDeclaration={name:'ɵɵComponentDeclaration',moduleName:CORE};Identifiers.FactoryDeclaration={name:'ɵɵFactoryDeclaration',moduleName:CORE};Identifiers.declareFactory={name:'ɵɵngDeclareFactory',moduleName:CORE};Identifiers.FactoryTarget={name:'ɵɵFactoryTarget',moduleName:CORE};Identifiers.defineDirective={name:'ɵɵdefineDirective',moduleName:CORE};Identifiers.declareDirective={name:'ɵɵngDeclareDirective',moduleName:CORE};Identifiers.DirectiveDeclaration={name:'ɵɵDirectiveDeclaration',moduleName:CORE};Identifiers.InjectorDef={name:'ɵɵInjectorDef',moduleName:CORE};Identifiers.InjectorDeclaration={name:'ɵɵInjectorDeclaration',moduleName:CORE};Identifiers.defineInjector={name:'ɵɵdefineInjector',moduleName:CORE};Identifiers.declareInjector={name:'ɵɵngDeclareInjector',moduleName:CORE};Identifiers.NgModuleDeclaration={name:'ɵɵNgModuleDeclaration',moduleName:CORE};Identifiers.ModuleWithProviders={name:'ModuleWithProviders',moduleName:CORE};Identifiers.defineNgModule={name:'ɵɵdefineNgModule',moduleName:CORE};Identifiers.declareNgModule={name:'ɵɵngDeclareNgModule',moduleName:CORE};Identifiers.setNgModuleScope={name:'ɵɵsetNgModuleScope',moduleName:CORE};Identifiers.PipeDeclaration={name:'ɵɵPipeDeclaration',moduleName:CORE};Identifiers.definePipe={name:'ɵɵdefinePipe',moduleName:CORE};Identifiers.declarePipe={name:'ɵɵngDeclarePipe',moduleName:CORE};Identifiers.declareClassMetadata={name:'ɵɵngDeclareClassMetadata',moduleName:CORE};Identifiers.setClassMetadata={name:'ɵsetClassMetadata',moduleName:CORE};Identifiers.queryRefresh={name:'ɵɵqueryRefresh',moduleName:CORE};Identifiers.viewQuery={name:'ɵɵviewQuery',moduleName:CORE};Identifiers.loadQuery={name:'ɵɵloadQuery',moduleName:CORE};Identifiers.contentQuery={name:'ɵɵcontentQuery',moduleName:CORE};Identifiers.NgOnChangesFeature={name:'ɵɵNgOnChangesFeature',moduleName:CORE};Identifiers.InheritDefinitionFeature={name:'ɵɵInheritDefinitionFeature',moduleName:CORE};Identifiers.CopyDefinitionFeature={name:'ɵɵCopyDefinitionFeature',moduleName:CORE};Identifiers.ProvidersFeature={name:'ɵɵProvidersFeature',moduleName:CORE};Identifiers.listener={name:'ɵɵlistener',moduleName:CORE};Identifiers.getInheritedFactory={name:'ɵɵgetInheritedFactory',moduleName:CORE};// sanitization-related functions
|
|
403
|
+
*/const CORE='@angular/core';class Identifiers{}/* Methods */Identifiers.NEW_METHOD='factory';Identifiers.TRANSFORM_METHOD='transform';Identifiers.PATCH_DEPS='patchedDeps';Identifiers.core={name:null,moduleName:CORE};/* Instructions */Identifiers.namespaceHTML={name:'ɵɵnamespaceHTML',moduleName:CORE};Identifiers.namespaceMathML={name:'ɵɵnamespaceMathML',moduleName:CORE};Identifiers.namespaceSVG={name:'ɵɵnamespaceSVG',moduleName:CORE};Identifiers.element={name:'ɵɵelement',moduleName:CORE};Identifiers.elementStart={name:'ɵɵelementStart',moduleName:CORE};Identifiers.elementEnd={name:'ɵɵelementEnd',moduleName:CORE};Identifiers.advance={name:'ɵɵadvance',moduleName:CORE};Identifiers.syntheticHostProperty={name:'ɵɵsyntheticHostProperty',moduleName:CORE};Identifiers.syntheticHostListener={name:'ɵɵsyntheticHostListener',moduleName:CORE};Identifiers.attribute={name:'ɵɵattribute',moduleName:CORE};Identifiers.attributeInterpolate1={name:'ɵɵattributeInterpolate1',moduleName:CORE};Identifiers.attributeInterpolate2={name:'ɵɵattributeInterpolate2',moduleName:CORE};Identifiers.attributeInterpolate3={name:'ɵɵattributeInterpolate3',moduleName:CORE};Identifiers.attributeInterpolate4={name:'ɵɵattributeInterpolate4',moduleName:CORE};Identifiers.attributeInterpolate5={name:'ɵɵattributeInterpolate5',moduleName:CORE};Identifiers.attributeInterpolate6={name:'ɵɵattributeInterpolate6',moduleName:CORE};Identifiers.attributeInterpolate7={name:'ɵɵattributeInterpolate7',moduleName:CORE};Identifiers.attributeInterpolate8={name:'ɵɵattributeInterpolate8',moduleName:CORE};Identifiers.attributeInterpolateV={name:'ɵɵattributeInterpolateV',moduleName:CORE};Identifiers.classProp={name:'ɵɵclassProp',moduleName:CORE};Identifiers.elementContainerStart={name:'ɵɵelementContainerStart',moduleName:CORE};Identifiers.elementContainerEnd={name:'ɵɵelementContainerEnd',moduleName:CORE};Identifiers.elementContainer={name:'ɵɵelementContainer',moduleName:CORE};Identifiers.styleMap={name:'ɵɵstyleMap',moduleName:CORE};Identifiers.styleMapInterpolate1={name:'ɵɵstyleMapInterpolate1',moduleName:CORE};Identifiers.styleMapInterpolate2={name:'ɵɵstyleMapInterpolate2',moduleName:CORE};Identifiers.styleMapInterpolate3={name:'ɵɵstyleMapInterpolate3',moduleName:CORE};Identifiers.styleMapInterpolate4={name:'ɵɵstyleMapInterpolate4',moduleName:CORE};Identifiers.styleMapInterpolate5={name:'ɵɵstyleMapInterpolate5',moduleName:CORE};Identifiers.styleMapInterpolate6={name:'ɵɵstyleMapInterpolate6',moduleName:CORE};Identifiers.styleMapInterpolate7={name:'ɵɵstyleMapInterpolate7',moduleName:CORE};Identifiers.styleMapInterpolate8={name:'ɵɵstyleMapInterpolate8',moduleName:CORE};Identifiers.styleMapInterpolateV={name:'ɵɵstyleMapInterpolateV',moduleName:CORE};Identifiers.classMap={name:'ɵɵclassMap',moduleName:CORE};Identifiers.classMapInterpolate1={name:'ɵɵclassMapInterpolate1',moduleName:CORE};Identifiers.classMapInterpolate2={name:'ɵɵclassMapInterpolate2',moduleName:CORE};Identifiers.classMapInterpolate3={name:'ɵɵclassMapInterpolate3',moduleName:CORE};Identifiers.classMapInterpolate4={name:'ɵɵclassMapInterpolate4',moduleName:CORE};Identifiers.classMapInterpolate5={name:'ɵɵclassMapInterpolate5',moduleName:CORE};Identifiers.classMapInterpolate6={name:'ɵɵclassMapInterpolate6',moduleName:CORE};Identifiers.classMapInterpolate7={name:'ɵɵclassMapInterpolate7',moduleName:CORE};Identifiers.classMapInterpolate8={name:'ɵɵclassMapInterpolate8',moduleName:CORE};Identifiers.classMapInterpolateV={name:'ɵɵclassMapInterpolateV',moduleName:CORE};Identifiers.styleProp={name:'ɵɵstyleProp',moduleName:CORE};Identifiers.stylePropInterpolate1={name:'ɵɵstylePropInterpolate1',moduleName:CORE};Identifiers.stylePropInterpolate2={name:'ɵɵstylePropInterpolate2',moduleName:CORE};Identifiers.stylePropInterpolate3={name:'ɵɵstylePropInterpolate3',moduleName:CORE};Identifiers.stylePropInterpolate4={name:'ɵɵstylePropInterpolate4',moduleName:CORE};Identifiers.stylePropInterpolate5={name:'ɵɵstylePropInterpolate5',moduleName:CORE};Identifiers.stylePropInterpolate6={name:'ɵɵstylePropInterpolate6',moduleName:CORE};Identifiers.stylePropInterpolate7={name:'ɵɵstylePropInterpolate7',moduleName:CORE};Identifiers.stylePropInterpolate8={name:'ɵɵstylePropInterpolate8',moduleName:CORE};Identifiers.stylePropInterpolateV={name:'ɵɵstylePropInterpolateV',moduleName:CORE};Identifiers.nextContext={name:'ɵɵnextContext',moduleName:CORE};Identifiers.resetView={name:'ɵɵresetView',moduleName:CORE};Identifiers.templateCreate={name:'ɵɵtemplate',moduleName:CORE};Identifiers.text={name:'ɵɵtext',moduleName:CORE};Identifiers.enableBindings={name:'ɵɵenableBindings',moduleName:CORE};Identifiers.disableBindings={name:'ɵɵdisableBindings',moduleName:CORE};Identifiers.getCurrentView={name:'ɵɵgetCurrentView',moduleName:CORE};Identifiers.textInterpolate={name:'ɵɵtextInterpolate',moduleName:CORE};Identifiers.textInterpolate1={name:'ɵɵtextInterpolate1',moduleName:CORE};Identifiers.textInterpolate2={name:'ɵɵtextInterpolate2',moduleName:CORE};Identifiers.textInterpolate3={name:'ɵɵtextInterpolate3',moduleName:CORE};Identifiers.textInterpolate4={name:'ɵɵtextInterpolate4',moduleName:CORE};Identifiers.textInterpolate5={name:'ɵɵtextInterpolate5',moduleName:CORE};Identifiers.textInterpolate6={name:'ɵɵtextInterpolate6',moduleName:CORE};Identifiers.textInterpolate7={name:'ɵɵtextInterpolate7',moduleName:CORE};Identifiers.textInterpolate8={name:'ɵɵtextInterpolate8',moduleName:CORE};Identifiers.textInterpolateV={name:'ɵɵtextInterpolateV',moduleName:CORE};Identifiers.restoreView={name:'ɵɵrestoreView',moduleName:CORE};Identifiers.pureFunction0={name:'ɵɵpureFunction0',moduleName:CORE};Identifiers.pureFunction1={name:'ɵɵpureFunction1',moduleName:CORE};Identifiers.pureFunction2={name:'ɵɵpureFunction2',moduleName:CORE};Identifiers.pureFunction3={name:'ɵɵpureFunction3',moduleName:CORE};Identifiers.pureFunction4={name:'ɵɵpureFunction4',moduleName:CORE};Identifiers.pureFunction5={name:'ɵɵpureFunction5',moduleName:CORE};Identifiers.pureFunction6={name:'ɵɵpureFunction6',moduleName:CORE};Identifiers.pureFunction7={name:'ɵɵpureFunction7',moduleName:CORE};Identifiers.pureFunction8={name:'ɵɵpureFunction8',moduleName:CORE};Identifiers.pureFunctionV={name:'ɵɵpureFunctionV',moduleName:CORE};Identifiers.pipeBind1={name:'ɵɵpipeBind1',moduleName:CORE};Identifiers.pipeBind2={name:'ɵɵpipeBind2',moduleName:CORE};Identifiers.pipeBind3={name:'ɵɵpipeBind3',moduleName:CORE};Identifiers.pipeBind4={name:'ɵɵpipeBind4',moduleName:CORE};Identifiers.pipeBindV={name:'ɵɵpipeBindV',moduleName:CORE};Identifiers.hostProperty={name:'ɵɵhostProperty',moduleName:CORE};Identifiers.property={name:'ɵɵproperty',moduleName:CORE};Identifiers.propertyInterpolate={name:'ɵɵpropertyInterpolate',moduleName:CORE};Identifiers.propertyInterpolate1={name:'ɵɵpropertyInterpolate1',moduleName:CORE};Identifiers.propertyInterpolate2={name:'ɵɵpropertyInterpolate2',moduleName:CORE};Identifiers.propertyInterpolate3={name:'ɵɵpropertyInterpolate3',moduleName:CORE};Identifiers.propertyInterpolate4={name:'ɵɵpropertyInterpolate4',moduleName:CORE};Identifiers.propertyInterpolate5={name:'ɵɵpropertyInterpolate5',moduleName:CORE};Identifiers.propertyInterpolate6={name:'ɵɵpropertyInterpolate6',moduleName:CORE};Identifiers.propertyInterpolate7={name:'ɵɵpropertyInterpolate7',moduleName:CORE};Identifiers.propertyInterpolate8={name:'ɵɵpropertyInterpolate8',moduleName:CORE};Identifiers.propertyInterpolateV={name:'ɵɵpropertyInterpolateV',moduleName:CORE};Identifiers.i18n={name:'ɵɵi18n',moduleName:CORE};Identifiers.i18nAttributes={name:'ɵɵi18nAttributes',moduleName:CORE};Identifiers.i18nExp={name:'ɵɵi18nExp',moduleName:CORE};Identifiers.i18nStart={name:'ɵɵi18nStart',moduleName:CORE};Identifiers.i18nEnd={name:'ɵɵi18nEnd',moduleName:CORE};Identifiers.i18nApply={name:'ɵɵi18nApply',moduleName:CORE};Identifiers.i18nPostprocess={name:'ɵɵi18nPostprocess',moduleName:CORE};Identifiers.pipe={name:'ɵɵpipe',moduleName:CORE};Identifiers.projection={name:'ɵɵprojection',moduleName:CORE};Identifiers.projectionDef={name:'ɵɵprojectionDef',moduleName:CORE};Identifiers.reference={name:'ɵɵreference',moduleName:CORE};Identifiers.inject={name:'ɵɵinject',moduleName:CORE};Identifiers.injectAttribute={name:'ɵɵinjectAttribute',moduleName:CORE};Identifiers.directiveInject={name:'ɵɵdirectiveInject',moduleName:CORE};Identifiers.invalidFactory={name:'ɵɵinvalidFactory',moduleName:CORE};Identifiers.invalidFactoryDep={name:'ɵɵinvalidFactoryDep',moduleName:CORE};Identifiers.templateRefExtractor={name:'ɵɵtemplateRefExtractor',moduleName:CORE};Identifiers.forwardRef={name:'forwardRef',moduleName:CORE};Identifiers.resolveForwardRef={name:'resolveForwardRef',moduleName:CORE};Identifiers.ɵɵdefineInjectable={name:'ɵɵdefineInjectable',moduleName:CORE};Identifiers.declareInjectable={name:'ɵɵngDeclareInjectable',moduleName:CORE};Identifiers.InjectableDeclaration={name:'ɵɵInjectableDeclaration',moduleName:CORE};Identifiers.resolveWindow={name:'ɵɵresolveWindow',moduleName:CORE};Identifiers.resolveDocument={name:'ɵɵresolveDocument',moduleName:CORE};Identifiers.resolveBody={name:'ɵɵresolveBody',moduleName:CORE};Identifiers.defineComponent={name:'ɵɵdefineComponent',moduleName:CORE};Identifiers.declareComponent={name:'ɵɵngDeclareComponent',moduleName:CORE};Identifiers.setComponentScope={name:'ɵɵsetComponentScope',moduleName:CORE};Identifiers.ChangeDetectionStrategy={name:'ChangeDetectionStrategy',moduleName:CORE};Identifiers.ViewEncapsulation={name:'ViewEncapsulation',moduleName:CORE};Identifiers.ComponentDeclaration={name:'ɵɵComponentDeclaration',moduleName:CORE};Identifiers.FactoryDeclaration={name:'ɵɵFactoryDeclaration',moduleName:CORE};Identifiers.declareFactory={name:'ɵɵngDeclareFactory',moduleName:CORE};Identifiers.FactoryTarget={name:'ɵɵFactoryTarget',moduleName:CORE};Identifiers.defineDirective={name:'ɵɵdefineDirective',moduleName:CORE};Identifiers.declareDirective={name:'ɵɵngDeclareDirective',moduleName:CORE};Identifiers.DirectiveDeclaration={name:'ɵɵDirectiveDeclaration',moduleName:CORE};Identifiers.InjectorDef={name:'ɵɵInjectorDef',moduleName:CORE};Identifiers.InjectorDeclaration={name:'ɵɵInjectorDeclaration',moduleName:CORE};Identifiers.defineInjector={name:'ɵɵdefineInjector',moduleName:CORE};Identifiers.declareInjector={name:'ɵɵngDeclareInjector',moduleName:CORE};Identifiers.NgModuleDeclaration={name:'ɵɵNgModuleDeclaration',moduleName:CORE};Identifiers.ModuleWithProviders={name:'ModuleWithProviders',moduleName:CORE};Identifiers.defineNgModule={name:'ɵɵdefineNgModule',moduleName:CORE};Identifiers.declareNgModule={name:'ɵɵngDeclareNgModule',moduleName:CORE};Identifiers.setNgModuleScope={name:'ɵɵsetNgModuleScope',moduleName:CORE};Identifiers.registerNgModuleType={name:'ɵɵregisterNgModuleType',moduleName:CORE};Identifiers.PipeDeclaration={name:'ɵɵPipeDeclaration',moduleName:CORE};Identifiers.definePipe={name:'ɵɵdefinePipe',moduleName:CORE};Identifiers.declarePipe={name:'ɵɵngDeclarePipe',moduleName:CORE};Identifiers.declareClassMetadata={name:'ɵɵngDeclareClassMetadata',moduleName:CORE};Identifiers.setClassMetadata={name:'ɵsetClassMetadata',moduleName:CORE};Identifiers.queryRefresh={name:'ɵɵqueryRefresh',moduleName:CORE};Identifiers.viewQuery={name:'ɵɵviewQuery',moduleName:CORE};Identifiers.loadQuery={name:'ɵɵloadQuery',moduleName:CORE};Identifiers.contentQuery={name:'ɵɵcontentQuery',moduleName:CORE};Identifiers.NgOnChangesFeature={name:'ɵɵNgOnChangesFeature',moduleName:CORE};Identifiers.InheritDefinitionFeature={name:'ɵɵInheritDefinitionFeature',moduleName:CORE};Identifiers.CopyDefinitionFeature={name:'ɵɵCopyDefinitionFeature',moduleName:CORE};Identifiers.StandaloneFeature={name:'ɵɵStandaloneFeature',moduleName:CORE};Identifiers.ProvidersFeature={name:'ɵɵProvidersFeature',moduleName:CORE};Identifiers.listener={name:'ɵɵlistener',moduleName:CORE};Identifiers.getInheritedFactory={name:'ɵɵgetInheritedFactory',moduleName:CORE};// sanitization-related functions
|
|
402
404
|
Identifiers.sanitizeHtml={name:'ɵɵsanitizeHtml',moduleName:CORE};Identifiers.sanitizeStyle={name:'ɵɵsanitizeStyle',moduleName:CORE};Identifiers.sanitizeResourceUrl={name:'ɵɵsanitizeResourceUrl',moduleName:CORE};Identifiers.sanitizeScript={name:'ɵɵsanitizeScript',moduleName:CORE};Identifiers.sanitizeUrl={name:'ɵɵsanitizeUrl',moduleName:CORE};Identifiers.sanitizeUrlOrResourceUrl={name:'ɵɵsanitizeUrlOrResourceUrl',moduleName:CORE};Identifiers.trustConstantHtml={name:'ɵɵtrustConstantHtml',moduleName:CORE};Identifiers.trustConstantResourceUrl={name:'ɵɵtrustConstantResourceUrl',moduleName:CORE};/**
|
|
403
405
|
* @license
|
|
404
406
|
* Copyright Google LLC All Rights Reserved.
|
|
@@ -449,7 +451,7 @@ ctx.decIndent();ctx.decIndent();}}visitAllStatements(statements,ctx){statements.
|
|
|
449
451
|
*
|
|
450
452
|
* See `packages/compiler-cli/src/ngtsc/annotations/src/injectable.ts` and
|
|
451
453
|
* `packages/compiler/src/jit_compiler_facade.ts` for more information.
|
|
452
|
-
*/function convertFromMaybeForwardRefExpression({expression,forwardRef}){switch(forwardRef){case 0/* None */:case 1/* Wrapped */:return expression;case 2/* Unwrapped */:return generateForwardRef(expression);}}/**
|
|
454
|
+
*/function convertFromMaybeForwardRefExpression({expression,forwardRef}){switch(forwardRef){case 0/* ForwardRefHandling.None */:case 1/* ForwardRefHandling.Wrapped */:return expression;case 2/* ForwardRefHandling.Unwrapped */:return generateForwardRef(expression);}}/**
|
|
453
455
|
* Generate an expression that has the given `expr` wrapped in the following form:
|
|
454
456
|
*
|
|
455
457
|
* ```
|
|
@@ -476,10 +478,10 @@ body.push(new ReturnStatement(retExpr));}let factoryFn=fn([new FnParam('t',DYNAM
|
|
|
476
478
|
// an IIFE.
|
|
477
479
|
factoryFn=fn([],[new DeclareVarStmt(baseFactoryVar.name),new ReturnStatement(factoryFn)]).callFn([],/* sourceSpan */undefined,/* pure */true);}return {expression:factoryFn,statements:[],type:createFactoryType(meta)};}function createFactoryType(meta){const ctorDepsType=meta.deps!==null&&meta.deps!=='invalid'?createCtorDepsType(meta.deps):NONE_TYPE;return expressionType(importExpr(Identifiers.FactoryDeclaration,[typeWithParameters(meta.type.type,meta.typeArgumentCount),ctorDepsType]));}function injectDependencies(deps,target){return deps.map((dep,index)=>compileInjectDependency(dep,target,index));}function compileInjectDependency(dep,target,index){// Interpret the dependency according to its resolved type.
|
|
478
480
|
if(dep.token===null){return importExpr(Identifiers.invalidFactoryDep).callFn([literal(index)]);}else if(dep.attributeNameType===null){// Build up the injection flags according to the metadata.
|
|
479
|
-
const flags=0/* Default */|(dep.self?2/* Self */:0)|(dep.skipSelf?4/* SkipSelf */:0)|(dep.host?1/* Host */:0)|(dep.optional?8/* Optional */:0)|(target===exports.FactoryTarget.Pipe?16/* ForPipe */:0);// If this dependency is optional or otherwise has non-default flags, then additional
|
|
481
|
+
const flags=0/* InjectFlags.Default */|(dep.self?2/* InjectFlags.Self */:0)|(dep.skipSelf?4/* InjectFlags.SkipSelf */:0)|(dep.host?1/* InjectFlags.Host */:0)|(dep.optional?8/* InjectFlags.Optional */:0)|(target===exports.FactoryTarget.Pipe?16/* InjectFlags.ForPipe */:0);// If this dependency is optional or otherwise has non-default flags, then additional
|
|
480
482
|
// parameters describing how to inject the dependency must be passed to the inject function
|
|
481
483
|
// that's being used.
|
|
482
|
-
let flagsParam=flags!==0/* Default */||dep.optional?literal(flags):null;// Build up the arguments to the injectFn call.
|
|
484
|
+
let flagsParam=flags!==0/* InjectFlags.Default */||dep.optional?literal(flags):null;// Build up the arguments to the injectFn call.
|
|
483
485
|
const injectArgs=[dep.token];if(flagsParam){injectArgs.push(flagsParam);}const injectFn=getInjectFn(target);return importExpr(injectFn).callFn(injectArgs);}else {// The `dep.attributeTypeName` value is defined, which indicates that this is an `@Attribute()`
|
|
484
486
|
// type dependency. For the generated JS we still want to use the `dep.token` value in case the
|
|
485
487
|
// name given for the attribute is not a string literal. For example given `@Attribute(foo())`,
|
|
@@ -503,7 +505,7 @@ return importExpr(Identifiers.injectAttribute).callFn([dep.token]);}}function cr
|
|
|
503
505
|
*
|
|
504
506
|
* `valueSpan` may not be present in cases where there is no value `<div a></div>`.
|
|
505
507
|
* `keySpan` may also not be present for synthetic attributes from ICU expansions.
|
|
506
|
-
*/class TextAttribute{constructor(name,value,sourceSpan,keySpan,valueSpan,i18n){this.name=name;this.value=value;this.sourceSpan=sourceSpan;this.keySpan=keySpan;this.valueSpan=valueSpan;this.i18n=i18n;}visit(visitor){return visitor.visitTextAttribute(this);}}class BoundAttribute{constructor(name,type,securityContext,value,unit,sourceSpan,keySpan,valueSpan,i18n){this.name=name;this.type=type;this.securityContext=securityContext;this.value=value;this.unit=unit;this.sourceSpan=sourceSpan;this.keySpan=keySpan;this.valueSpan=valueSpan;this.i18n=i18n;}static fromBoundElementProperty(prop,i18n){if(prop.keySpan===undefined){throw new Error(`Unexpected state: keySpan must be defined for bound attributes but was not for ${prop.name}: ${prop.sourceSpan}`);}return new BoundAttribute(prop.name,prop.type,prop.securityContext,prop.value,prop.unit,prop.sourceSpan,prop.keySpan,prop.valueSpan,i18n);}visit(visitor){return visitor.visitBoundAttribute(this);}}class BoundEvent{constructor(name,type,handler,target,phase,sourceSpan,handlerSpan,keySpan){this.name=name;this.type=type;this.handler=handler;this.target=target;this.phase=phase;this.sourceSpan=sourceSpan;this.handlerSpan=handlerSpan;this.keySpan=keySpan;}static fromParsedEvent(event){const target=event.type===0/* Regular */?event.targetOrPhase:null;const phase=event.type===1/* Animation */?event.targetOrPhase:null;if(event.keySpan===undefined){throw new Error(`Unexpected state: keySpan must be defined for bound event but was not for ${event.name}: ${event.sourceSpan}`);}return new BoundEvent(event.name,event.type,event.handler,target,phase,event.sourceSpan,event.handlerSpan,event.keySpan);}visit(visitor){return visitor.visitBoundEvent(this);}}class Element$1{constructor(name,attributes,inputs,outputs,children,references,sourceSpan,startSourceSpan,endSourceSpan,i18n){this.name=name;this.attributes=attributes;this.inputs=inputs;this.outputs=outputs;this.children=children;this.references=references;this.sourceSpan=sourceSpan;this.startSourceSpan=startSourceSpan;this.endSourceSpan=endSourceSpan;this.i18n=i18n;}visit(visitor){return visitor.visitElement(this);}}class Template{constructor(// tagName is the name of the container element, if applicable.
|
|
508
|
+
*/class TextAttribute{constructor(name,value,sourceSpan,keySpan,valueSpan,i18n){this.name=name;this.value=value;this.sourceSpan=sourceSpan;this.keySpan=keySpan;this.valueSpan=valueSpan;this.i18n=i18n;}visit(visitor){return visitor.visitTextAttribute(this);}}class BoundAttribute{constructor(name,type,securityContext,value,unit,sourceSpan,keySpan,valueSpan,i18n){this.name=name;this.type=type;this.securityContext=securityContext;this.value=value;this.unit=unit;this.sourceSpan=sourceSpan;this.keySpan=keySpan;this.valueSpan=valueSpan;this.i18n=i18n;}static fromBoundElementProperty(prop,i18n){if(prop.keySpan===undefined){throw new Error(`Unexpected state: keySpan must be defined for bound attributes but was not for ${prop.name}: ${prop.sourceSpan}`);}return new BoundAttribute(prop.name,prop.type,prop.securityContext,prop.value,prop.unit,prop.sourceSpan,prop.keySpan,prop.valueSpan,i18n);}visit(visitor){return visitor.visitBoundAttribute(this);}}class BoundEvent{constructor(name,type,handler,target,phase,sourceSpan,handlerSpan,keySpan){this.name=name;this.type=type;this.handler=handler;this.target=target;this.phase=phase;this.sourceSpan=sourceSpan;this.handlerSpan=handlerSpan;this.keySpan=keySpan;}static fromParsedEvent(event){const target=event.type===0/* ParsedEventType.Regular */?event.targetOrPhase:null;const phase=event.type===1/* ParsedEventType.Animation */?event.targetOrPhase:null;if(event.keySpan===undefined){throw new Error(`Unexpected state: keySpan must be defined for bound event but was not for ${event.name}: ${event.sourceSpan}`);}return new BoundEvent(event.name,event.type,event.handler,target,phase,event.sourceSpan,event.handlerSpan,event.keySpan);}visit(visitor){return visitor.visitBoundEvent(this);}}class Element$1{constructor(name,attributes,inputs,outputs,children,references,sourceSpan,startSourceSpan,endSourceSpan,i18n){this.name=name;this.attributes=attributes;this.inputs=inputs;this.outputs=outputs;this.children=children;this.references=references;this.sourceSpan=sourceSpan;this.startSourceSpan=startSourceSpan;this.endSourceSpan=endSourceSpan;this.i18n=i18n;}visit(visitor){return visitor.visitElement(this);}}class Template{constructor(// tagName is the name of the container element, if applicable.
|
|
507
509
|
// `null` is a special case for when there is a structural directive on an `ng-template` so
|
|
508
510
|
// the renderer can differentiate between the synthetic template and the one written in the
|
|
509
511
|
// file.
|
|
@@ -597,7 +599,7 @@ function toPublicName(internalName){return internalName.toUpperCase().replace(/[
|
|
|
597
599
|
* @param params A map of placeholder names to expressions.
|
|
598
600
|
* @param useCamelCase whether to camelCase the placeholder name when formatting.
|
|
599
601
|
* @returns A new map of formatted placeholder names to expressions.
|
|
600
|
-
*/function
|
|
602
|
+
*/function formatI18nPlaceholderNamesInMap(params={},useCamelCase){const _params={};if(params&&Object.keys(params).length){Object.keys(params).forEach(key=>_params[formatI18nPlaceholderName(key,useCamelCase)]=params[key]);}return _params;}/**
|
|
601
603
|
* Converts internal placeholder names to public-facing format
|
|
602
604
|
* (for example to use in goog.getMsg call).
|
|
603
605
|
* Example: `START_TAG_DIV_1` is converted to `startTagDiv_1`.
|
|
@@ -627,7 +629,11 @@ if(/^\d+$/.test(chunks[chunks.length-1])){postfix=chunks.pop();}let raw=chunks.s
|
|
|
627
629
|
*
|
|
628
630
|
* TODO(FW-1136): this is a temporary solution, we need to come up with a better way of working with
|
|
629
631
|
* inputs that contain potentially unsafe chars.
|
|
630
|
-
*/const UNSAFE_OBJECT_KEY_NAME_REGEXP=/[-.]/;/** Name of the temporary to use during data binding */const TEMPORARY_NAME='_t';/** Name of the context parameter passed into a template function */const CONTEXT_NAME='ctx';/** Name of the RenderFlag passed into a template function */const RENDER_FLAGS='rf';/** The prefix reference variables */const REFERENCE_PREFIX='_r';/** The name of the implicit context reference */const IMPLICIT_REFERENCE='$implicit';/** Non bindable attribute name **/const NON_BINDABLE_ATTR='ngNonBindable';/** Name for the variable keeping track of the context returned by `ɵɵrestoreView`. */const RESTORED_VIEW_CONTEXT_NAME='restoredCtx';/**
|
|
632
|
+
*/const UNSAFE_OBJECT_KEY_NAME_REGEXP=/[-.]/;/** Name of the temporary to use during data binding */const TEMPORARY_NAME='_t';/** Name of the context parameter passed into a template function */const CONTEXT_NAME='ctx';/** Name of the RenderFlag passed into a template function */const RENDER_FLAGS='rf';/** The prefix reference variables */const REFERENCE_PREFIX='_r';/** The name of the implicit context reference */const IMPLICIT_REFERENCE='$implicit';/** Non bindable attribute name **/const NON_BINDABLE_ATTR='ngNonBindable';/** Name for the variable keeping track of the context returned by `ɵɵrestoreView`. */const RESTORED_VIEW_CONTEXT_NAME='restoredCtx';/**
|
|
633
|
+
* Maximum length of a single instruction chain. Because our output AST uses recursion, we're
|
|
634
|
+
* limited in how many expressions we can nest before we reach the call stack limit. This
|
|
635
|
+
* length is set very conservatively in order to reduce the chance of problems.
|
|
636
|
+
*/const MAX_CHAIN_LENGTH=500;/** Instructions that support chaining. */const CHAINABLE_INSTRUCTIONS=new Set([Identifiers.element,Identifiers.elementStart,Identifiers.elementEnd,Identifiers.elementContainer,Identifiers.elementContainerStart,Identifiers.elementContainerEnd,Identifiers.i18nExp,Identifiers.listener,Identifiers.classProp,Identifiers.syntheticHostListener,Identifiers.hostProperty,Identifiers.syntheticHostProperty,Identifiers.property,Identifiers.propertyInterpolate1,Identifiers.propertyInterpolate2,Identifiers.propertyInterpolate3,Identifiers.propertyInterpolate4,Identifiers.propertyInterpolate5,Identifiers.propertyInterpolate6,Identifiers.propertyInterpolate7,Identifiers.propertyInterpolate8,Identifiers.propertyInterpolateV,Identifiers.attribute,Identifiers.attributeInterpolate1,Identifiers.attributeInterpolate2,Identifiers.attributeInterpolate3,Identifiers.attributeInterpolate4,Identifiers.attributeInterpolate5,Identifiers.attributeInterpolate6,Identifiers.attributeInterpolate7,Identifiers.attributeInterpolate8,Identifiers.attributeInterpolateV,Identifiers.styleProp,Identifiers.stylePropInterpolate1,Identifiers.stylePropInterpolate2,Identifiers.stylePropInterpolate3,Identifiers.stylePropInterpolate4,Identifiers.stylePropInterpolate5,Identifiers.stylePropInterpolate6,Identifiers.stylePropInterpolate7,Identifiers.stylePropInterpolate8,Identifiers.stylePropInterpolateV,Identifiers.textInterpolate,Identifiers.textInterpolate1,Identifiers.textInterpolate2,Identifiers.textInterpolate3,Identifiers.textInterpolate4,Identifiers.textInterpolate5,Identifiers.textInterpolate6,Identifiers.textInterpolate7,Identifiers.textInterpolate8,Identifiers.textInterpolateV]);/** Generates a call to a single instruction. */function invokeInstruction(span,reference,params){return importExpr(reference,null,span).callFn(params,span);}/**
|
|
631
637
|
* Creates an allocator for a temporary variable.
|
|
632
638
|
*
|
|
633
639
|
* A variable declaration is added to the statements the first time the allocator is invoked.
|
|
@@ -643,7 +649,7 @@ quoted:UNSAFE_OBJECT_KEY_NAME_REGEXP.test(minifiedName),value:keepDeclared&&need
|
|
|
643
649
|
// (for ex. 'ref, ref1, ..., refN'), thus we extract individual refs and store them
|
|
644
650
|
// as separate array entities
|
|
645
651
|
const selectors=selector.split(',').map(token=>literal(token.trim()));predicate.push(...selectors);});return constantPool.getConstLiteral(literalArr(predicate),true);}else {// The original predicate may have been wrapped in a `forwardRef()` call.
|
|
646
|
-
switch(query.predicate.forwardRef){case 0/* None */:case 2/* Unwrapped */:return query.predicate.expression;case 1/* Wrapped */:return importExpr(Identifiers.resolveForwardRef).callFn([query.predicate.expression]);}}}/**
|
|
652
|
+
switch(query.predicate.forwardRef){case 0/* ForwardRefHandling.None */:case 2/* ForwardRefHandling.Unwrapped */:return query.predicate.expression;case 1/* ForwardRefHandling.Wrapped */:return importExpr(Identifiers.resolveForwardRef).callFn([query.predicate.expression]);}}}/**
|
|
647
653
|
* A representation for an object literal used during codegen of definition objects. The generic
|
|
648
654
|
* type `T` allows to reference a documented type of the generated structure, such that the
|
|
649
655
|
* property names that are set can be resolved to their documented declaration.
|
|
@@ -665,10 +671,10 @@ switch(query.predicate.forwardRef){case 0/* None */:case 2/* Unwrapped */:return
|
|
|
665
671
|
return 1;}else {return expressions.length+strings.length;}}/**
|
|
666
672
|
* Generates the final instruction call statements based on the passed in configuration.
|
|
667
673
|
* Will try to chain instructions as much as possible, if chaining is supported.
|
|
668
|
-
*/function getInstructionStatements(instructions){var _a;const statements=[];let pendingExpression=null;let pendingExpressionType=null;for(const current of instructions){const resolvedParams=(_a=typeof current.paramsOrFn==='function'?current.paramsOrFn():current.paramsOrFn)!==null&&_a!==void 0?_a:[];const params=Array.isArray(resolvedParams)?resolvedParams:[resolvedParams];// If the current instruction is the same as the previous one
|
|
674
|
+
*/function getInstructionStatements(instructions){var _a;const statements=[];let pendingExpression=null;let pendingExpressionType=null;let chainLength=0;for(const current of instructions){const resolvedParams=(_a=typeof current.paramsOrFn==='function'?current.paramsOrFn():current.paramsOrFn)!==null&&_a!==void 0?_a:[];const params=Array.isArray(resolvedParams)?resolvedParams:[resolvedParams];// If the current instruction is the same as the previous one
|
|
669
675
|
// and it can be chained, add another call to the chain.
|
|
670
|
-
if(pendingExpressionType===current.reference&&CHAINABLE_INSTRUCTIONS.has(pendingExpressionType)){// We'll always have a pending expression when there's a pending expression type.
|
|
671
|
-
pendingExpression=pendingExpression.callFn(params,pendingExpression.sourceSpan);}else {if(pendingExpression!==null){statements.push(pendingExpression.toStmt());}pendingExpression=invokeInstruction(current.span,current.reference,params);pendingExpressionType=current.reference;}}// Since the current instruction adds the previous one to the statements,
|
|
676
|
+
if(chainLength<MAX_CHAIN_LENGTH&&pendingExpressionType===current.reference&&CHAINABLE_INSTRUCTIONS.has(pendingExpressionType)){// We'll always have a pending expression when there's a pending expression type.
|
|
677
|
+
pendingExpression=pendingExpression.callFn(params,pendingExpression.sourceSpan);chainLength++;}else {if(pendingExpression!==null){statements.push(pendingExpression.toStmt());}pendingExpression=invokeInstruction(current.span,current.reference,params);pendingExpressionType=current.reference;chainLength=0;}}// Since the current instruction adds the previous one to the statements,
|
|
672
678
|
// we may be left with the final one at the end that is still pending.
|
|
673
679
|
if(pendingExpression!==null){statements.push(pendingExpression.toStmt());}return statements;}/**
|
|
674
680
|
* @license
|
|
@@ -728,7 +734,7 @@ UNUSABLE_INTERPOLATION_REGEXPS.forEach(regexp=>{if(regexp.test(start)||regexp.te
|
|
|
728
734
|
*
|
|
729
735
|
* Use of this source code is governed by an MIT-style license that can be
|
|
730
736
|
* found in the LICENSE file at https://angular.io/license
|
|
731
|
-
*/class ParseLocation{constructor(file,offset,line,col){this.file=file;this.offset=offset;this.line=line;this.col=col;}toString(){return this.offset!=null?`${this.file.url}@${this.line}:${this.col}`:this.file.url;}moveBy(delta){const source=this.file.content;const len=source.length;let offset=this.offset;let line=this.line;let col=this.col;while(offset>0&&delta<0){offset--;delta++;const ch=source.charCodeAt(offset);if(ch==$LF){line--;const priorLine=source.
|
|
737
|
+
*/class ParseLocation{constructor(file,offset,line,col){this.file=file;this.offset=offset;this.line=line;this.col=col;}toString(){return this.offset!=null?`${this.file.url}@${this.line}:${this.col}`:this.file.url;}moveBy(delta){const source=this.file.content;const len=source.length;let offset=this.offset;let line=this.line;let col=this.col;while(offset>0&&delta<0){offset--;delta++;const ch=source.charCodeAt(offset);if(ch==$LF){line--;const priorLine=source.substring(0,offset-1).lastIndexOf(String.fromCharCode($LF));col=priorLine>0?offset-priorLine:offset;}else {col--;}}while(offset<len&&delta>0){const ch=source.charCodeAt(offset);offset++;delta--;if(ch==$LF){line++;col=0;}else {col++;}}return new ParseLocation(this.file,offset,line,col);}// Return the source around the location
|
|
732
738
|
// Up to `maxChars` or `maxLines` on each side of the location
|
|
733
739
|
getContext(maxChars,maxLines){const content=this.file.content;let startOffset=this.offset;if(startOffset!=null){if(startOffset>content.length-1){startOffset=content.length-1;}let endOffset=startOffset;let ctxChars=0;let ctxLines=0;while(ctxChars<maxChars&&startOffset>0){startOffset--;ctxChars++;if(content[startOffset]=='\n'){if(++ctxLines==maxLines){break;}}}ctxChars=0;ctxLines=0;while(ctxChars<maxChars&&endOffset<content.length-1){endOffset++;ctxChars++;if(content[endOffset]=='\n'){if(++ctxLines==maxLines){break;}}}return {before:content.substring(startOffset,this.offset),after:content.substring(this.offset,endOffset+1)};}return null;}}class ParseSourceFile{constructor(content,url){this.content=content;this.url=url;}}class ParseSourceSpan{/**
|
|
734
740
|
* Create an object that holds information about spans of tokens/nodes captured during
|
|
@@ -912,12 +918,35 @@ if(ref.moduleName!=='@angular/core'){throw new Error(`Cannot resolve external re
|
|
|
912
918
|
* Use of this source code is governed by an MIT-style license that can be
|
|
913
919
|
* found in the LICENSE file at https://angular.io/license
|
|
914
920
|
*/ /**
|
|
921
|
+
* How the selector scope of an NgModule (its declarations, imports, and exports) should be emitted
|
|
922
|
+
* as a part of the NgModule definition.
|
|
923
|
+
*/exports.R3SelectorScopeMode = void 0;(function(R3SelectorScopeMode){/**
|
|
924
|
+
* Emit the declarations inline into the module definition.
|
|
925
|
+
*
|
|
926
|
+
* This option is useful in certain contexts where it's known that JIT support is required. The
|
|
927
|
+
* tradeoff here is that this emit style prevents directives and pipes from being tree-shaken if
|
|
928
|
+
* they are unused, but the NgModule is used.
|
|
929
|
+
*/R3SelectorScopeMode[R3SelectorScopeMode["Inline"]=0]="Inline";/**
|
|
930
|
+
* Emit the declarations using a side effectful function call, `ɵɵsetNgModuleScope`, that is
|
|
931
|
+
* guarded with the `ngJitMode` flag.
|
|
932
|
+
*
|
|
933
|
+
* This form of emit supports JIT and can be optimized away if the `ngJitMode` flag is set to
|
|
934
|
+
* false, which allows unused directives and pipes to be tree-shaken.
|
|
935
|
+
*/R3SelectorScopeMode[R3SelectorScopeMode["SideEffect"]=1]="SideEffect";/**
|
|
936
|
+
* Don't generate selector scopes at all.
|
|
937
|
+
*
|
|
938
|
+
* This is useful for contexts where JIT support is known to be unnecessary.
|
|
939
|
+
*/R3SelectorScopeMode[R3SelectorScopeMode["Omit"]=2]="Omit";})(exports.R3SelectorScopeMode||(exports.R3SelectorScopeMode={}));/**
|
|
915
940
|
* Construct an `R3NgModuleDef` for the given `R3NgModuleMetadata`.
|
|
916
|
-
*/function compileNgModule(meta){const{internalType,bootstrap,declarations,imports,exports,schemas,containsForwardDecls,
|
|
917
|
-
// to the `ɵɵdefineNgModule()` call
|
|
918
|
-
if(
|
|
919
|
-
// prevent tree-shaking of the declarations, imports and exports references.
|
|
920
|
-
|
|
941
|
+
*/function compileNgModule(meta){const{adjacentType,internalType,bootstrap,declarations,imports,exports: exports$1,schemas,containsForwardDecls,selectorScopeMode,id}=meta;const statements=[];const definitionMap=new DefinitionMap();definitionMap.set('type',internalType);if(bootstrap.length>0){definitionMap.set('bootstrap',refsToArray(bootstrap,containsForwardDecls));}if(selectorScopeMode===exports.R3SelectorScopeMode.Inline){// If requested to emit scope information inline, pass the `declarations`, `imports` and
|
|
942
|
+
// `exports` to the `ɵɵdefineNgModule()` call directly.
|
|
943
|
+
if(declarations.length>0){definitionMap.set('declarations',refsToArray(declarations,containsForwardDecls));}if(imports.length>0){definitionMap.set('imports',refsToArray(imports,containsForwardDecls));}if(exports$1.length>0){definitionMap.set('exports',refsToArray(exports$1,containsForwardDecls));}}else if(selectorScopeMode===exports.R3SelectorScopeMode.SideEffect){// In this mode, scope information is not passed into `ɵɵdefineNgModule` as it
|
|
944
|
+
// would prevent tree-shaking of the declarations, imports and exports references. Instead, it's
|
|
945
|
+
// patched onto the NgModule definition with a `ɵɵsetNgModuleScope` call that's guarded by the
|
|
946
|
+
// `ngJitMode` flag.
|
|
947
|
+
const setNgModuleScopeCall=generateSetNgModuleScopeCall(meta);if(setNgModuleScopeCall!==null){statements.push(setNgModuleScopeCall);}}else;if(schemas!==null&&schemas.length>0){definitionMap.set('schemas',literalArr(schemas.map(ref=>ref.value)));}if(id!==null){definitionMap.set('id',id);// Generate a side-effectful call to register this NgModule by its id, as per the semantics of
|
|
948
|
+
// NgModule ids.
|
|
949
|
+
statements.push(importExpr(Identifiers.registerNgModuleType).callFn([adjacentType,id]).toStmt());}const expression=importExpr(Identifiers.defineNgModule).callFn([definitionMap.toLiteralMap()],undefined,true);const type=createNgModuleType(meta);return {expression,type,statements};}/**
|
|
921
950
|
* This function is used in JIT mode to generate the call to `ɵɵdefineNgModule()` from a call to
|
|
922
951
|
* `ɵɵngDeclareNgModule()`.
|
|
923
952
|
*/function compileNgModuleDeclarationExpression(meta){const definitionMap=new DefinitionMap();definitionMap.set('type',new WrappedNodeExpr(meta.type));if(meta.bootstrap!==undefined){definitionMap.set('bootstrap',new WrappedNodeExpr(meta.bootstrap));}if(meta.declarations!==undefined){definitionMap.set('declarations',new WrappedNodeExpr(meta.declarations));}if(meta.imports!==undefined){definitionMap.set('imports',new WrappedNodeExpr(meta.imports));}if(meta.exports!==undefined){definitionMap.set('exports',new WrappedNodeExpr(meta.exports));}if(meta.schemas!==undefined){definitionMap.set('schemas',new WrappedNodeExpr(meta.schemas));}if(meta.id!==undefined){definitionMap.set('id',new WrappedNodeExpr(meta.id));}return importExpr(Identifiers.defineNgModule).callFn([definitionMap.toLiteralMap()]);}function createNgModuleType({type:moduleType,declarations,imports,exports}){return new ExpressionType(importExpr(Identifiers.NgModuleDeclaration,[new ExpressionType(moduleType.type),tupleTypeOf(declarations),tupleTypeOf(imports),tupleTypeOf(exports)]));}/**
|
|
@@ -938,7 +967,13 @@ const iifeCall=new InvokeFunctionExpr(/* fn */iife,/* args */[]);return iifeCall
|
|
|
938
967
|
*/function compilePipeFromMetadata(metadata){const definitionMapValues=[];// e.g. `name: 'myPipe'`
|
|
939
968
|
definitionMapValues.push({key:'name',value:literal(metadata.pipeName),quoted:false});// e.g. `type: MyPipe`
|
|
940
969
|
definitionMapValues.push({key:'type',value:metadata.type.value,quoted:false});// e.g. `pure: true`
|
|
941
|
-
definitionMapValues.push({key:'pure',value:literal(metadata.pure),quoted:false});const expression=importExpr(Identifiers.definePipe).callFn([literalMap(definitionMapValues)],undefined,true);const type=createPipeType(metadata);return {expression,type,statements:[]};}function createPipeType(metadata){return new ExpressionType(importExpr(Identifiers.PipeDeclaration,[typeWithParameters(metadata.type.type,metadata.typeArgumentCount),new ExpressionType(new LiteralExpr(metadata.pipeName))]));}/**
|
|
970
|
+
definitionMapValues.push({key:'pure',value:literal(metadata.pure),quoted:false});if(metadata.isStandalone){definitionMapValues.push({key:'standalone',value:literal(true),quoted:false});}const expression=importExpr(Identifiers.definePipe).callFn([literalMap(definitionMapValues)],undefined,true);const type=createPipeType(metadata);return {expression,type,statements:[]};}function createPipeType(metadata){return new ExpressionType(importExpr(Identifiers.PipeDeclaration,[typeWithParameters(metadata.type.type,metadata.typeArgumentCount),new ExpressionType(new LiteralExpr(metadata.pipeName)),new ExpressionType(new LiteralExpr(metadata.isStandalone))]));}/**
|
|
971
|
+
* @license
|
|
972
|
+
* Copyright Google LLC All Rights Reserved.
|
|
973
|
+
*
|
|
974
|
+
* Use of this source code is governed by an MIT-style license that can be
|
|
975
|
+
* found in the LICENSE file at https://angular.io/license
|
|
976
|
+
*/exports.R3TemplateDependencyKind = void 0;(function(R3TemplateDependencyKind){R3TemplateDependencyKind[R3TemplateDependencyKind["Directive"]=0]="Directive";R3TemplateDependencyKind[R3TemplateDependencyKind["Pipe"]=1]="Pipe";R3TemplateDependencyKind[R3TemplateDependencyKind["NgModule"]=2]="NgModule";})(exports.R3TemplateDependencyKind||(exports.R3TemplateDependencyKind={}));/**
|
|
942
977
|
* @license
|
|
943
978
|
* Copyright Google LLC All Rights Reserved.
|
|
944
979
|
*
|
|
@@ -946,19 +981,7 @@ definitionMapValues.push({key:'pure',value:literal(metadata.pure),quoted:false})
|
|
|
946
981
|
* found in the LICENSE file at https://angular.io/license
|
|
947
982
|
*/class ParserError{constructor(message,input,errLocation,ctxLocation){this.input=input;this.errLocation=errLocation;this.ctxLocation=ctxLocation;this.message=`Parser Error: ${message} ${errLocation} [${input}] in ${ctxLocation}`;}}class ParseSpan{constructor(start,end){this.start=start;this.end=end;}toAbsolute(absoluteOffset){return new AbsoluteSourceSpan(absoluteOffset+this.start,absoluteOffset+this.end);}}class AST{constructor(span,/**
|
|
948
983
|
* Absolute location of the expression AST in a source code file.
|
|
949
|
-
*/sourceSpan){this.span=span;this.sourceSpan=sourceSpan;}toString(){return 'AST';}}class ASTWithName extends AST{constructor(span,sourceSpan,nameSpan){super(span,sourceSpan);this.nameSpan=nameSpan;}}
|
|
950
|
-
* Represents a quoted expression of the form:
|
|
951
|
-
*
|
|
952
|
-
* quote = prefix `:` uninterpretedExpression
|
|
953
|
-
* prefix = identifier
|
|
954
|
-
* uninterpretedExpression = arbitrary string
|
|
955
|
-
*
|
|
956
|
-
* A quoted expression is meant to be pre-processed by an AST transformer that
|
|
957
|
-
* converts it into another AST that no longer contains quoted expressions.
|
|
958
|
-
* It is meant to allow third-party developers to extend Angular template
|
|
959
|
-
* expression language. The `uninterpretedExpression` part of the quote is
|
|
960
|
-
* therefore not interpreted by the Angular's own expression parser.
|
|
961
|
-
*/class Quote extends AST{constructor(span,sourceSpan,prefix,uninterpretedExpression,location){super(span,sourceSpan);this.prefix=prefix;this.uninterpretedExpression=uninterpretedExpression;this.location=location;}visit(visitor,context=null){return visitor.visitQuote(this,context);}toString(){return 'Quote';}}class EmptyExpr extends AST{visit(visitor,context=null){// do nothing
|
|
984
|
+
*/sourceSpan){this.span=span;this.sourceSpan=sourceSpan;}toString(){return 'AST';}}class ASTWithName extends AST{constructor(span,sourceSpan,nameSpan){super(span,sourceSpan);this.nameSpan=nameSpan;}}class EmptyExpr extends AST{visit(visitor,context=null){// do nothing
|
|
962
985
|
}}class ImplicitReceiver extends AST{visit(visitor,context=null){return visitor.visitImplicitReceiver(this,context);}}/**
|
|
963
986
|
* Receiver when something is accessed through `this` (e.g. `this.foo`). Note that this class
|
|
964
987
|
* inherits from `ImplicitReceiver`, because accessing something through `this` is treated the
|
|
@@ -1000,10 +1023,10 @@ this.left=null;this.right=null;this.operation=null;}/**
|
|
|
1000
1023
|
*/constructor(sourceSpan,key,value){this.sourceSpan=sourceSpan;this.key=key;this.value=value;}}class RecursiveAstVisitor{visit(ast,context){// The default implementation just visits every node.
|
|
1001
1024
|
// Classes that extend RecursiveAstVisitor should override this function
|
|
1002
1025
|
// to selectively visit the specified node.
|
|
1003
|
-
ast.visit(this,context);}visitUnary(ast,context){this.visit(ast.expr,context);}visitBinary(ast,context){this.visit(ast.left,context);this.visit(ast.right,context);}visitChain(ast,context){this.visitAll(ast.expressions,context);}visitConditional(ast,context){this.visit(ast.condition,context);this.visit(ast.trueExp,context);this.visit(ast.falseExp,context);}visitPipe(ast,context){this.visit(ast.exp,context);this.visitAll(ast.args,context);}visitImplicitReceiver(ast,context){}visitThisReceiver(ast,context){}visitInterpolation(ast,context){this.visitAll(ast.expressions,context);}visitKeyedRead(ast,context){this.visit(ast.receiver,context);this.visit(ast.key,context);}visitKeyedWrite(ast,context){this.visit(ast.receiver,context);this.visit(ast.key,context);this.visit(ast.value,context);}visitLiteralArray(ast,context){this.visitAll(ast.expressions,context);}visitLiteralMap(ast,context){this.visitAll(ast.values,context);}visitLiteralPrimitive(ast,context){}visitPrefixNot(ast,context){this.visit(ast.expression,context);}visitNonNullAssert(ast,context){this.visit(ast.expression,context);}visitPropertyRead(ast,context){this.visit(ast.receiver,context);}visitPropertyWrite(ast,context){this.visit(ast.receiver,context);this.visit(ast.value,context);}visitSafePropertyRead(ast,context){this.visit(ast.receiver,context);}visitSafeKeyedRead(ast,context){this.visit(ast.receiver,context);this.visit(ast.key,context);}visitCall(ast,context){this.visit(ast.receiver,context);this.visitAll(ast.args,context);}visitSafeCall(ast,context){this.visit(ast.receiver,context);this.visitAll(ast.args,context);}
|
|
1004
|
-
visitAll(asts,context){for(const ast of asts){this.visit(ast,context);}}}class AstTransformer{visitImplicitReceiver(ast,context){return ast;}visitThisReceiver(ast,context){return ast;}visitInterpolation(ast,context){return new Interpolation(ast.span,ast.sourceSpan,ast.strings,this.visitAll(ast.expressions));}visitLiteralPrimitive(ast,context){return new LiteralPrimitive(ast.span,ast.sourceSpan,ast.value);}visitPropertyRead(ast,context){return new PropertyRead(ast.span,ast.sourceSpan,ast.nameSpan,ast.receiver.visit(this),ast.name);}visitPropertyWrite(ast,context){return new PropertyWrite(ast.span,ast.sourceSpan,ast.nameSpan,ast.receiver.visit(this),ast.name,ast.value.visit(this));}visitSafePropertyRead(ast,context){return new SafePropertyRead(ast.span,ast.sourceSpan,ast.nameSpan,ast.receiver.visit(this),ast.name);}visitLiteralArray(ast,context){return new LiteralArray(ast.span,ast.sourceSpan,this.visitAll(ast.expressions));}visitLiteralMap(ast,context){return new LiteralMap(ast.span,ast.sourceSpan,ast.keys,this.visitAll(ast.values));}visitUnary(ast,context){switch(ast.operator){case'+':return Unary.createPlus(ast.span,ast.sourceSpan,ast.expr.visit(this));case'-':return Unary.createMinus(ast.span,ast.sourceSpan,ast.expr.visit(this));default:throw new Error(`Unknown unary operator ${ast.operator}`);}}visitBinary(ast,context){return new Binary(ast.span,ast.sourceSpan,ast.operation,ast.left.visit(this),ast.right.visit(this));}visitPrefixNot(ast,context){return new PrefixNot(ast.span,ast.sourceSpan,ast.expression.visit(this));}visitNonNullAssert(ast,context){return new NonNullAssert(ast.span,ast.sourceSpan,ast.expression.visit(this));}visitConditional(ast,context){return new Conditional(ast.span,ast.sourceSpan,ast.condition.visit(this),ast.trueExp.visit(this),ast.falseExp.visit(this));}visitPipe(ast,context){return new BindingPipe(ast.span,ast.sourceSpan,ast.exp.visit(this),ast.name,this.visitAll(ast.args),ast.nameSpan);}visitKeyedRead(ast,context){return new KeyedRead(ast.span,ast.sourceSpan,ast.receiver.visit(this),ast.key.visit(this));}visitKeyedWrite(ast,context){return new KeyedWrite(ast.span,ast.sourceSpan,ast.receiver.visit(this),ast.key.visit(this),ast.value.visit(this));}visitCall(ast,context){return new Call(ast.span,ast.sourceSpan,ast.receiver.visit(this),this.visitAll(ast.args),ast.argumentSpan);}visitSafeCall(ast,context){return new SafeCall(ast.span,ast.sourceSpan,ast.receiver.visit(this),this.visitAll(ast.args),ast.argumentSpan);}visitAll(asts){const res=[];for(let i=0;i<asts.length;++i){res[i]=asts[i].visit(this);}return res;}visitChain(ast,context){return new Chain(ast.span,ast.sourceSpan,this.visitAll(ast.expressions));}
|
|
1026
|
+
ast.visit(this,context);}visitUnary(ast,context){this.visit(ast.expr,context);}visitBinary(ast,context){this.visit(ast.left,context);this.visit(ast.right,context);}visitChain(ast,context){this.visitAll(ast.expressions,context);}visitConditional(ast,context){this.visit(ast.condition,context);this.visit(ast.trueExp,context);this.visit(ast.falseExp,context);}visitPipe(ast,context){this.visit(ast.exp,context);this.visitAll(ast.args,context);}visitImplicitReceiver(ast,context){}visitThisReceiver(ast,context){}visitInterpolation(ast,context){this.visitAll(ast.expressions,context);}visitKeyedRead(ast,context){this.visit(ast.receiver,context);this.visit(ast.key,context);}visitKeyedWrite(ast,context){this.visit(ast.receiver,context);this.visit(ast.key,context);this.visit(ast.value,context);}visitLiteralArray(ast,context){this.visitAll(ast.expressions,context);}visitLiteralMap(ast,context){this.visitAll(ast.values,context);}visitLiteralPrimitive(ast,context){}visitPrefixNot(ast,context){this.visit(ast.expression,context);}visitNonNullAssert(ast,context){this.visit(ast.expression,context);}visitPropertyRead(ast,context){this.visit(ast.receiver,context);}visitPropertyWrite(ast,context){this.visit(ast.receiver,context);this.visit(ast.value,context);}visitSafePropertyRead(ast,context){this.visit(ast.receiver,context);}visitSafeKeyedRead(ast,context){this.visit(ast.receiver,context);this.visit(ast.key,context);}visitCall(ast,context){this.visit(ast.receiver,context);this.visitAll(ast.args,context);}visitSafeCall(ast,context){this.visit(ast.receiver,context);this.visitAll(ast.args,context);}// This is not part of the AstVisitor interface, just a helper method
|
|
1027
|
+
visitAll(asts,context){for(const ast of asts){this.visit(ast,context);}}}class AstTransformer{visitImplicitReceiver(ast,context){return ast;}visitThisReceiver(ast,context){return ast;}visitInterpolation(ast,context){return new Interpolation(ast.span,ast.sourceSpan,ast.strings,this.visitAll(ast.expressions));}visitLiteralPrimitive(ast,context){return new LiteralPrimitive(ast.span,ast.sourceSpan,ast.value);}visitPropertyRead(ast,context){return new PropertyRead(ast.span,ast.sourceSpan,ast.nameSpan,ast.receiver.visit(this),ast.name);}visitPropertyWrite(ast,context){return new PropertyWrite(ast.span,ast.sourceSpan,ast.nameSpan,ast.receiver.visit(this),ast.name,ast.value.visit(this));}visitSafePropertyRead(ast,context){return new SafePropertyRead(ast.span,ast.sourceSpan,ast.nameSpan,ast.receiver.visit(this),ast.name);}visitLiteralArray(ast,context){return new LiteralArray(ast.span,ast.sourceSpan,this.visitAll(ast.expressions));}visitLiteralMap(ast,context){return new LiteralMap(ast.span,ast.sourceSpan,ast.keys,this.visitAll(ast.values));}visitUnary(ast,context){switch(ast.operator){case'+':return Unary.createPlus(ast.span,ast.sourceSpan,ast.expr.visit(this));case'-':return Unary.createMinus(ast.span,ast.sourceSpan,ast.expr.visit(this));default:throw new Error(`Unknown unary operator ${ast.operator}`);}}visitBinary(ast,context){return new Binary(ast.span,ast.sourceSpan,ast.operation,ast.left.visit(this),ast.right.visit(this));}visitPrefixNot(ast,context){return new PrefixNot(ast.span,ast.sourceSpan,ast.expression.visit(this));}visitNonNullAssert(ast,context){return new NonNullAssert(ast.span,ast.sourceSpan,ast.expression.visit(this));}visitConditional(ast,context){return new Conditional(ast.span,ast.sourceSpan,ast.condition.visit(this),ast.trueExp.visit(this),ast.falseExp.visit(this));}visitPipe(ast,context){return new BindingPipe(ast.span,ast.sourceSpan,ast.exp.visit(this),ast.name,this.visitAll(ast.args),ast.nameSpan);}visitKeyedRead(ast,context){return new KeyedRead(ast.span,ast.sourceSpan,ast.receiver.visit(this),ast.key.visit(this));}visitKeyedWrite(ast,context){return new KeyedWrite(ast.span,ast.sourceSpan,ast.receiver.visit(this),ast.key.visit(this),ast.value.visit(this));}visitCall(ast,context){return new Call(ast.span,ast.sourceSpan,ast.receiver.visit(this),this.visitAll(ast.args),ast.argumentSpan);}visitSafeCall(ast,context){return new SafeCall(ast.span,ast.sourceSpan,ast.receiver.visit(this),this.visitAll(ast.args),ast.argumentSpan);}visitAll(asts){const res=[];for(let i=0;i<asts.length;++i){res[i]=asts[i].visit(this);}return res;}visitChain(ast,context){return new Chain(ast.span,ast.sourceSpan,this.visitAll(ast.expressions));}visitSafeKeyedRead(ast,context){return new SafeKeyedRead(ast.span,ast.sourceSpan,ast.receiver.visit(this),ast.key.visit(this));}}// A transformer that only creates new nodes if the transformer makes a change or
|
|
1005
1028
|
// a change is made a child node.
|
|
1006
|
-
class AstMemoryEfficientTransformer{visitImplicitReceiver(ast,context){return ast;}visitThisReceiver(ast,context){return ast;}visitInterpolation(ast,context){const expressions=this.visitAll(ast.expressions);if(expressions!==ast.expressions)return new Interpolation(ast.span,ast.sourceSpan,ast.strings,expressions);return ast;}visitLiteralPrimitive(ast,context){return ast;}visitPropertyRead(ast,context){const receiver=ast.receiver.visit(this);if(receiver!==ast.receiver){return new PropertyRead(ast.span,ast.sourceSpan,ast.nameSpan,receiver,ast.name);}return ast;}visitPropertyWrite(ast,context){const receiver=ast.receiver.visit(this);const value=ast.value.visit(this);if(receiver!==ast.receiver||value!==ast.value){return new PropertyWrite(ast.span,ast.sourceSpan,ast.nameSpan,receiver,ast.name,value);}return ast;}visitSafePropertyRead(ast,context){const receiver=ast.receiver.visit(this);if(receiver!==ast.receiver){return new SafePropertyRead(ast.span,ast.sourceSpan,ast.nameSpan,receiver,ast.name);}return ast;}visitLiteralArray(ast,context){const expressions=this.visitAll(ast.expressions);if(expressions!==ast.expressions){return new LiteralArray(ast.span,ast.sourceSpan,expressions);}return ast;}visitLiteralMap(ast,context){const values=this.visitAll(ast.values);if(values!==ast.values){return new LiteralMap(ast.span,ast.sourceSpan,ast.keys,values);}return ast;}visitUnary(ast,context){const expr=ast.expr.visit(this);if(expr!==ast.expr){switch(ast.operator){case'+':return Unary.createPlus(ast.span,ast.sourceSpan,expr);case'-':return Unary.createMinus(ast.span,ast.sourceSpan,expr);default:throw new Error(`Unknown unary operator ${ast.operator}`);}}return ast;}visitBinary(ast,context){const left=ast.left.visit(this);const right=ast.right.visit(this);if(left!==ast.left||right!==ast.right){return new Binary(ast.span,ast.sourceSpan,ast.operation,left,right);}return ast;}visitPrefixNot(ast,context){const expression=ast.expression.visit(this);if(expression!==ast.expression){return new PrefixNot(ast.span,ast.sourceSpan,expression);}return ast;}visitNonNullAssert(ast,context){const expression=ast.expression.visit(this);if(expression!==ast.expression){return new NonNullAssert(ast.span,ast.sourceSpan,expression);}return ast;}visitConditional(ast,context){const condition=ast.condition.visit(this);const trueExp=ast.trueExp.visit(this);const falseExp=ast.falseExp.visit(this);if(condition!==ast.condition||trueExp!==ast.trueExp||falseExp!==ast.falseExp){return new Conditional(ast.span,ast.sourceSpan,condition,trueExp,falseExp);}return ast;}visitPipe(ast,context){const exp=ast.exp.visit(this);const args=this.visitAll(ast.args);if(exp!==ast.exp||args!==ast.args){return new BindingPipe(ast.span,ast.sourceSpan,exp,ast.name,args,ast.nameSpan);}return ast;}visitKeyedRead(ast,context){const obj=ast.receiver.visit(this);const key=ast.key.visit(this);if(obj!==ast.receiver||key!==ast.key){return new KeyedRead(ast.span,ast.sourceSpan,obj,key);}return ast;}visitKeyedWrite(ast,context){const obj=ast.receiver.visit(this);const key=ast.key.visit(this);const value=ast.value.visit(this);if(obj!==ast.receiver||key!==ast.key||value!==ast.value){return new KeyedWrite(ast.span,ast.sourceSpan,obj,key,value);}return ast;}visitAll(asts){const res=[];let modified=false;for(let i=0;i<asts.length;++i){const original=asts[i];const value=original.visit(this);res[i]=value;modified=modified||value!==original;}return modified?res:asts;}visitChain(ast,context){const expressions=this.visitAll(ast.expressions);if(expressions!==ast.expressions){return new Chain(ast.span,ast.sourceSpan,expressions);}return ast;}visitCall(ast,context){const receiver=ast.receiver.visit(this);const args=this.visitAll(ast.args);if(receiver!==ast.receiver||args!==ast.args){return new Call(ast.span,ast.sourceSpan,receiver,args,ast.argumentSpan);}return ast;}visitSafeCall(ast,context){const receiver=ast.receiver.visit(this);const args=this.visitAll(ast.args);if(receiver!==ast.receiver||args!==ast.args){return new SafeCall(ast.span,ast.sourceSpan,receiver,args,ast.argumentSpan);}return ast;}
|
|
1029
|
+
class AstMemoryEfficientTransformer{visitImplicitReceiver(ast,context){return ast;}visitThisReceiver(ast,context){return ast;}visitInterpolation(ast,context){const expressions=this.visitAll(ast.expressions);if(expressions!==ast.expressions)return new Interpolation(ast.span,ast.sourceSpan,ast.strings,expressions);return ast;}visitLiteralPrimitive(ast,context){return ast;}visitPropertyRead(ast,context){const receiver=ast.receiver.visit(this);if(receiver!==ast.receiver){return new PropertyRead(ast.span,ast.sourceSpan,ast.nameSpan,receiver,ast.name);}return ast;}visitPropertyWrite(ast,context){const receiver=ast.receiver.visit(this);const value=ast.value.visit(this);if(receiver!==ast.receiver||value!==ast.value){return new PropertyWrite(ast.span,ast.sourceSpan,ast.nameSpan,receiver,ast.name,value);}return ast;}visitSafePropertyRead(ast,context){const receiver=ast.receiver.visit(this);if(receiver!==ast.receiver){return new SafePropertyRead(ast.span,ast.sourceSpan,ast.nameSpan,receiver,ast.name);}return ast;}visitLiteralArray(ast,context){const expressions=this.visitAll(ast.expressions);if(expressions!==ast.expressions){return new LiteralArray(ast.span,ast.sourceSpan,expressions);}return ast;}visitLiteralMap(ast,context){const values=this.visitAll(ast.values);if(values!==ast.values){return new LiteralMap(ast.span,ast.sourceSpan,ast.keys,values);}return ast;}visitUnary(ast,context){const expr=ast.expr.visit(this);if(expr!==ast.expr){switch(ast.operator){case'+':return Unary.createPlus(ast.span,ast.sourceSpan,expr);case'-':return Unary.createMinus(ast.span,ast.sourceSpan,expr);default:throw new Error(`Unknown unary operator ${ast.operator}`);}}return ast;}visitBinary(ast,context){const left=ast.left.visit(this);const right=ast.right.visit(this);if(left!==ast.left||right!==ast.right){return new Binary(ast.span,ast.sourceSpan,ast.operation,left,right);}return ast;}visitPrefixNot(ast,context){const expression=ast.expression.visit(this);if(expression!==ast.expression){return new PrefixNot(ast.span,ast.sourceSpan,expression);}return ast;}visitNonNullAssert(ast,context){const expression=ast.expression.visit(this);if(expression!==ast.expression){return new NonNullAssert(ast.span,ast.sourceSpan,expression);}return ast;}visitConditional(ast,context){const condition=ast.condition.visit(this);const trueExp=ast.trueExp.visit(this);const falseExp=ast.falseExp.visit(this);if(condition!==ast.condition||trueExp!==ast.trueExp||falseExp!==ast.falseExp){return new Conditional(ast.span,ast.sourceSpan,condition,trueExp,falseExp);}return ast;}visitPipe(ast,context){const exp=ast.exp.visit(this);const args=this.visitAll(ast.args);if(exp!==ast.exp||args!==ast.args){return new BindingPipe(ast.span,ast.sourceSpan,exp,ast.name,args,ast.nameSpan);}return ast;}visitKeyedRead(ast,context){const obj=ast.receiver.visit(this);const key=ast.key.visit(this);if(obj!==ast.receiver||key!==ast.key){return new KeyedRead(ast.span,ast.sourceSpan,obj,key);}return ast;}visitKeyedWrite(ast,context){const obj=ast.receiver.visit(this);const key=ast.key.visit(this);const value=ast.value.visit(this);if(obj!==ast.receiver||key!==ast.key||value!==ast.value){return new KeyedWrite(ast.span,ast.sourceSpan,obj,key,value);}return ast;}visitAll(asts){const res=[];let modified=false;for(let i=0;i<asts.length;++i){const original=asts[i];const value=original.visit(this);res[i]=value;modified=modified||value!==original;}return modified?res:asts;}visitChain(ast,context){const expressions=this.visitAll(ast.expressions);if(expressions!==ast.expressions){return new Chain(ast.span,ast.sourceSpan,expressions);}return ast;}visitCall(ast,context){const receiver=ast.receiver.visit(this);const args=this.visitAll(ast.args);if(receiver!==ast.receiver||args!==ast.args){return new Call(ast.span,ast.sourceSpan,receiver,args,ast.argumentSpan);}return ast;}visitSafeCall(ast,context){const receiver=ast.receiver.visit(this);const args=this.visitAll(ast.args);if(receiver!==ast.receiver||args!==ast.args){return new SafeCall(ast.span,ast.sourceSpan,receiver,args,ast.argumentSpan);}return ast;}visitSafeKeyedRead(ast,context){const obj=ast.receiver.visit(this);const key=ast.key.visit(this);if(obj!==ast.receiver||key!==ast.key){return new SafeKeyedRead(ast.span,ast.sourceSpan,obj,key);}return ast;}}// Bindings
|
|
1007
1030
|
class ParsedProperty{constructor(name,expression,type,sourceSpan,keySpan,valueSpan){this.name=name;this.expression=expression;this.type=type;this.sourceSpan=sourceSpan;this.keySpan=keySpan;this.valueSpan=valueSpan;this.isLiteral=this.type===exports.ParsedPropertyType.LITERAL_ATTR;this.isAnimation=this.type===exports.ParsedPropertyType.ANIMATION;}}exports.ParsedPropertyType = void 0;(function(ParsedPropertyType){ParsedPropertyType[ParsedPropertyType["DEFAULT"]=0]="DEFAULT";ParsedPropertyType[ParsedPropertyType["LITERAL_ATTR"]=1]="LITERAL_ATTR";ParsedPropertyType[ParsedPropertyType["ANIMATION"]=2]="ANIMATION";})(exports.ParsedPropertyType||(exports.ParsedPropertyType={}));class ParsedEvent{// Regular events have a target
|
|
1008
1031
|
// Animation events have a phase
|
|
1009
1032
|
constructor(name,targetOrPhase,type,handler,sourceSpan,handlerSpan,keySpan){this.name=name;this.targetOrPhase=targetOrPhase;this.type=type;this.handler=handler;this.sourceSpan=sourceSpan;this.handlerSpan=handlerSpan;this.keySpan=keySpan;}}/**
|
|
@@ -1056,8 +1079,7 @@ varExpr=localExpr;// Restore the previous "usesImplicitReceiver" state since the
|
|
|
1056
1079
|
this.usesImplicitReceiver=prevUsesImplicitReceiver;this.addImplicitReceiverAccess(ast.name);}else {// Otherwise it's an error.
|
|
1057
1080
|
const receiver=ast.name;const value=ast.value instanceof PropertyRead?ast.value.name:undefined;throw new Error(`Cannot assign value "${value}" to template variable "${receiver}". Template variables are read-only.`);}}}// If no local expression could be produced, use the original receiver's
|
|
1058
1081
|
// property as the target.
|
|
1059
|
-
if(varExpr===null){varExpr=receiver.prop(ast.name,this.convertSourceSpan(ast.span));}return convertToStatementIfNeeded(mode,varExpr.set(this._visit(ast.value,_Mode.Expression)));}visitSafePropertyRead(ast,mode){return this.convertSafeAccess(ast,this.leftMostSafeNode(ast),mode);}visitSafeKeyedRead(ast,mode){return this.convertSafeAccess(ast,this.leftMostSafeNode(ast),mode);}visitAll(asts,mode){return asts.map(ast=>this._visit(ast,mode));}
|
|
1060
|
-
Statement: ${ast.uninterpretedExpression} located at ${ast.location}`);}visitCall(ast,mode){const leftMostSafe=this.leftMostSafeNode(ast);if(leftMostSafe){return this.convertSafeAccess(ast,leftMostSafe,mode);}const convertedArgs=this.visitAll(ast.args,_Mode.Expression);if(ast instanceof BuiltinFunctionCall){return convertToStatementIfNeeded(mode,ast.converter(convertedArgs));}const receiver=ast.receiver;if(receiver instanceof PropertyRead&&receiver.receiver instanceof ImplicitReceiver&&!(receiver.receiver instanceof ThisReceiver)&&receiver.name==='$any'){if(convertedArgs.length!==1){throw new Error(`Invalid call to $any, expected 1 argument but received ${convertedArgs.length||'none'}`);}return convertToStatementIfNeeded(mode,convertedArgs[0]);}const call=this._visit(receiver,_Mode.Expression).callFn(convertedArgs,this.convertSourceSpan(ast.span));return convertToStatementIfNeeded(mode,call);}visitSafeCall(ast,mode){return this.convertSafeAccess(ast,this.leftMostSafeNode(ast),mode);}_visit(ast,mode){const result=this._resultMap.get(ast);if(result)return result;return (this._nodeMap.get(ast)||ast).visit(this,mode);}convertSafeAccess(ast,leftMostSafe,mode){// If the expression contains a safe access node on the left it needs to be converted to
|
|
1082
|
+
if(varExpr===null){varExpr=receiver.prop(ast.name,this.convertSourceSpan(ast.span));}return convertToStatementIfNeeded(mode,varExpr.set(this._visit(ast.value,_Mode.Expression)));}visitSafePropertyRead(ast,mode){return this.convertSafeAccess(ast,this.leftMostSafeNode(ast),mode);}visitSafeKeyedRead(ast,mode){return this.convertSafeAccess(ast,this.leftMostSafeNode(ast),mode);}visitAll(asts,mode){return asts.map(ast=>this._visit(ast,mode));}visitCall(ast,mode){const leftMostSafe=this.leftMostSafeNode(ast);if(leftMostSafe){return this.convertSafeAccess(ast,leftMostSafe,mode);}const convertedArgs=this.visitAll(ast.args,_Mode.Expression);if(ast instanceof BuiltinFunctionCall){return convertToStatementIfNeeded(mode,ast.converter(convertedArgs));}const receiver=ast.receiver;if(receiver instanceof PropertyRead&&receiver.receiver instanceof ImplicitReceiver&&!(receiver.receiver instanceof ThisReceiver)&&receiver.name==='$any'){if(convertedArgs.length!==1){throw new Error(`Invalid call to $any, expected 1 argument but received ${convertedArgs.length||'none'}`);}return convertToStatementIfNeeded(mode,convertedArgs[0]);}const call=this._visit(receiver,_Mode.Expression).callFn(convertedArgs,this.convertSourceSpan(ast.span));return convertToStatementIfNeeded(mode,call);}visitSafeCall(ast,mode){return this.convertSafeAccess(ast,this.leftMostSafeNode(ast),mode);}_visit(ast,mode){const result=this._resultMap.get(ast);if(result)return result;return (this._nodeMap.get(ast)||ast).visit(this,mode);}convertSafeAccess(ast,leftMostSafe,mode){// If the expression contains a safe access node on the left it needs to be converted to
|
|
1061
1083
|
// an expression that guards the access to the member by checking the receiver for blank. As
|
|
1062
1084
|
// execution proceeds from left to right, the left most part of the expression must be guarded
|
|
1063
1085
|
// first but, because member access is left associative, the right side of the expression is at
|
|
@@ -1114,10 +1136,10 @@ return convertToStatementIfNeeded(mode,temporary.set(left).notIdentical(NULL_EXP
|
|
|
1114
1136
|
// a == null ? null : a.c.b.c?.d.e
|
|
1115
1137
|
// then to:
|
|
1116
1138
|
// a == null ? null : a.b.c == null ? null : a.b.c.d.e
|
|
1117
|
-
leftMostSafeNode(ast){const visit=(visitor,ast)=>{return (this._nodeMap.get(ast)||ast).visit(visitor);};return ast.visit({visitUnary(ast){return null;},visitBinary(ast){return null;},visitChain(ast){return null;},visitConditional(ast){return null;},visitCall(ast){return visit(this,ast.receiver);},visitSafeCall(ast){return visit(this,ast.receiver)||ast;},visitImplicitReceiver(ast){return null;},visitThisReceiver(ast){return null;},visitInterpolation(ast){return null;},visitKeyedRead(ast){return visit(this,ast.receiver);},visitKeyedWrite(ast){return null;},visitLiteralArray(ast){return null;},visitLiteralMap(ast){return null;},visitLiteralPrimitive(ast){return null;},visitPipe(ast){return null;},visitPrefixNot(ast){return null;},visitNonNullAssert(ast){return null;},visitPropertyRead(ast){return visit(this,ast.receiver);},visitPropertyWrite(ast){return null;},
|
|
1139
|
+
leftMostSafeNode(ast){const visit=(visitor,ast)=>{return (this._nodeMap.get(ast)||ast).visit(visitor);};return ast.visit({visitUnary(ast){return null;},visitBinary(ast){return null;},visitChain(ast){return null;},visitConditional(ast){return null;},visitCall(ast){return visit(this,ast.receiver);},visitSafeCall(ast){return visit(this,ast.receiver)||ast;},visitImplicitReceiver(ast){return null;},visitThisReceiver(ast){return null;},visitInterpolation(ast){return null;},visitKeyedRead(ast){return visit(this,ast.receiver);},visitKeyedWrite(ast){return null;},visitLiteralArray(ast){return null;},visitLiteralMap(ast){return null;},visitLiteralPrimitive(ast){return null;},visitPipe(ast){return null;},visitPrefixNot(ast){return null;},visitNonNullAssert(ast){return null;},visitPropertyRead(ast){return visit(this,ast.receiver);},visitPropertyWrite(ast){return null;},visitSafePropertyRead(ast){return visit(this,ast.receiver)||ast;},visitSafeKeyedRead(ast){return visit(this,ast.receiver)||ast;}});}// Returns true of the AST includes a method or a pipe indicating that, if the
|
|
1118
1140
|
// expression is used as the target of a safe property or method access then
|
|
1119
1141
|
// the expression should be stored into a temporary variable.
|
|
1120
|
-
needsTemporaryInSafeAccess(ast){const visit=(visitor,ast)=>{return ast&&(this._nodeMap.get(ast)||ast).visit(visitor);};const visitSome=(visitor,ast)=>{return ast.some(ast=>visit(visitor,ast));};return ast.visit({visitUnary(ast){return visit(this,ast.expr);},visitBinary(ast){return visit(this,ast.left)||visit(this,ast.right);},visitChain(ast){return false;},visitConditional(ast){return visit(this,ast.condition)||visit(this,ast.trueExp)||visit(this,ast.falseExp);},visitCall(ast){return true;},visitSafeCall(ast){return true;},visitImplicitReceiver(ast){return false;},visitThisReceiver(ast){return false;},visitInterpolation(ast){return visitSome(this,ast.expressions);},visitKeyedRead(ast){return false;},visitKeyedWrite(ast){return false;},visitLiteralArray(ast){return true;},visitLiteralMap(ast){return true;},visitLiteralPrimitive(ast){return false;},visitPipe(ast){return true;},visitPrefixNot(ast){return visit(this,ast.expression);},visitNonNullAssert(ast){return visit(this,ast.expression);},visitPropertyRead(ast){return false;},visitPropertyWrite(ast){return false;},
|
|
1142
|
+
needsTemporaryInSafeAccess(ast){const visit=(visitor,ast)=>{return ast&&(this._nodeMap.get(ast)||ast).visit(visitor);};const visitSome=(visitor,ast)=>{return ast.some(ast=>visit(visitor,ast));};return ast.visit({visitUnary(ast){return visit(this,ast.expr);},visitBinary(ast){return visit(this,ast.left)||visit(this,ast.right);},visitChain(ast){return false;},visitConditional(ast){return visit(this,ast.condition)||visit(this,ast.trueExp)||visit(this,ast.falseExp);},visitCall(ast){return true;},visitSafeCall(ast){return true;},visitImplicitReceiver(ast){return false;},visitThisReceiver(ast){return false;},visitInterpolation(ast){return visitSome(this,ast.expressions);},visitKeyedRead(ast){return false;},visitKeyedWrite(ast){return false;},visitLiteralArray(ast){return true;},visitLiteralMap(ast){return true;},visitLiteralPrimitive(ast){return false;},visitPipe(ast){return true;},visitPrefixNot(ast){return visit(this,ast.expression);},visitNonNullAssert(ast){return visit(this,ast.expression);},visitPropertyRead(ast){return false;},visitPropertyWrite(ast){return false;},visitSafePropertyRead(ast){return false;},visitSafeKeyedRead(ast){return false;}});}allocateTemporary(){const tempNumber=this._currentTemporary++;this.temporaryCount=Math.max(this._currentTemporary,this.temporaryCount);return new ReadVarExpr(temporaryName(this.bindingId,tempNumber));}releaseTemporary(temporary){this._currentTemporary--;if(temporary.name!=temporaryName(this.bindingId,this._currentTemporary)){throw new Error(`Temporary ${temporary.name} released out of order`);}}/**
|
|
1121
1143
|
* Creates an absolute `ParseSourceSpan` from the relative `ParseSpan`.
|
|
1122
1144
|
*
|
|
1123
1145
|
* `ParseSpan` objects are relative to the start of the expression.
|
|
@@ -1485,10 +1507,10 @@ return combined.map(s=>otherSelectorsHasHost?`${s}${otherSelectors}`:`${s}${host
|
|
|
1485
1507
|
// because a string-map is not guaranteed to retain the
|
|
1486
1508
|
// order of the entries whereas a string array can be
|
|
1487
1509
|
// constructed in a [key, value, key, value] format.
|
|
1488
|
-
const styles=[];let i=0;let parenDepth=0;let quote=0/* QuoteNone */;let valueStart=0;let propStart=0;let currentProp=null;let valueHasQuotes=false;while(i<value.length){const token=value.charCodeAt(i++);switch(token){case 40/* OpenParen */:parenDepth++;break;case 41/* CloseParen */:parenDepth--;break;case 39/* QuoteSingle */:// valueStart needs to be there since prop values don't
|
|
1510
|
+
const styles=[];let i=0;let parenDepth=0;let quote=0/* Char.QuoteNone */;let valueStart=0;let propStart=0;let currentProp=null;let valueHasQuotes=false;while(i<value.length){const token=value.charCodeAt(i++);switch(token){case 40/* Char.OpenParen */:parenDepth++;break;case 41/* Char.CloseParen */:parenDepth--;break;case 39/* Char.QuoteSingle */:// valueStart needs to be there since prop values don't
|
|
1489
1511
|
// have quotes in CSS
|
|
1490
|
-
valueHasQuotes=valueHasQuotes||valueStart>0;if(quote===0/* QuoteNone */){quote=39/* QuoteSingle */;}else if(quote===39/* QuoteSingle */&&value.charCodeAt(i-1)!==92/* BackSlash */){quote=0/* QuoteNone */;}break;case 34/* QuoteDouble */:// same logic as above
|
|
1491
|
-
valueHasQuotes=valueHasQuotes||valueStart>0;if(quote===0/* QuoteNone */){quote=34/* QuoteDouble */;}else if(quote===34/* QuoteDouble */&&value.charCodeAt(i-1)!==92/* BackSlash */){quote=0/* QuoteNone */;}break;case 58/* Colon */:if(!currentProp&&parenDepth===0&"e===0/* QuoteNone */){currentProp=hyphenate(value.substring(propStart,i-1).trim());valueStart=i;}break;case 59/* Semicolon */:if(currentProp&&valueStart>0&&parenDepth===0&"e===0/* QuoteNone */){const styleVal=value.substring(valueStart,i-1).trim();styles.push(currentProp,valueHasQuotes?stripUnnecessaryQuotes(styleVal):styleVal);propStart=i;valueStart=0;currentProp=null;valueHasQuotes=false;}break;}}if(currentProp&&valueStart){const styleVal=value.
|
|
1512
|
+
valueHasQuotes=valueHasQuotes||valueStart>0;if(quote===0/* Char.QuoteNone */){quote=39/* Char.QuoteSingle */;}else if(quote===39/* Char.QuoteSingle */&&value.charCodeAt(i-1)!==92/* Char.BackSlash */){quote=0/* Char.QuoteNone */;}break;case 34/* Char.QuoteDouble */:// same logic as above
|
|
1513
|
+
valueHasQuotes=valueHasQuotes||valueStart>0;if(quote===0/* Char.QuoteNone */){quote=34/* Char.QuoteDouble */;}else if(quote===34/* Char.QuoteDouble */&&value.charCodeAt(i-1)!==92/* Char.BackSlash */){quote=0/* Char.QuoteNone */;}break;case 58/* Char.Colon */:if(!currentProp&&parenDepth===0&"e===0/* Char.QuoteNone */){currentProp=hyphenate(value.substring(propStart,i-1).trim());valueStart=i;}break;case 59/* Char.Semicolon */:if(currentProp&&valueStart>0&&parenDepth===0&"e===0/* Char.QuoteNone */){const styleVal=value.substring(valueStart,i-1).trim();styles.push(currentProp,valueHasQuotes?stripUnnecessaryQuotes(styleVal):styleVal);propStart=i;valueStart=0;currentProp=null;valueHasQuotes=false;}break;}}if(currentProp&&valueStart){const styleVal=value.slice(valueStart).trim();styles.push(currentProp,valueHasQuotes?stripUnnecessaryQuotes(styleVal):styleVal);}return styles;}function stripUnnecessaryQuotes(value){const qS=value.charCodeAt(0);const qE=value.charCodeAt(value.length-1);if(qS==qE&&(qS==39/* Char.QuoteSingle */||qS==34/* Char.QuoteDouble */)){const tempValue=value.substring(1,value.length-1);// special case to avoid using a multi-quoted string that was just chomped
|
|
1492
1514
|
// (e.g. `font-family: "Verdana", "sans-serif"`)
|
|
1493
1515
|
if(tempValue.indexOf('\'')==-1&&tempValue.indexOf('"')==-1){value=tempValue;}}return value;}function hyphenate(value){return value.replace(/[a-z][A-Z]/g,v=>{return v.charAt(0)+'-'+v.charAt(1);}).toLowerCase();}const IMPORTANT_FLAG='!important';/**
|
|
1494
1516
|
* Minimum amount of binding slots required in the runtime for style/class bindings.
|
|
@@ -1589,8 +1611,8 @@ if(tempValue.indexOf('\'')==-1&&tempValue.indexOf('"')==-1){value=tempValue;}}re
|
|
|
1589
1611
|
// will therefore skip all style/class resolution that is present
|
|
1590
1612
|
// with style="", [style]="" and [style.prop]="", class="",
|
|
1591
1613
|
// [class.prop]="". [class]="" assignments
|
|
1592
|
-
let binding=null;let name=input.name;switch(input.type){case 0/* Property */:binding=this.registerInputBasedOnName(name,input.value,input.sourceSpan);break;case 3/* Style */:binding=this.registerStyleInput(name,false,input.value,input.sourceSpan,input.unit);break;case 2/* Class */:binding=this.registerClassInput(name,false,input.value,input.sourceSpan);break;}return binding?true:false;}registerInputBasedOnName(name,expression,sourceSpan){let binding=null;const prefix=name.substring(0,6);const isStyle=name==='style'||prefix==='style.'||prefix==='style!';const isClass=!isStyle&&(name==='class'||prefix==='class.'||prefix==='class!');if(isStyle||isClass){const isMapBased=name.charAt(5)!=='.';// style.prop or class.prop makes this a no
|
|
1593
|
-
const property=name.
|
|
1614
|
+
let binding=null;let name=input.name;switch(input.type){case 0/* BindingType.Property */:binding=this.registerInputBasedOnName(name,input.value,input.sourceSpan);break;case 3/* BindingType.Style */:binding=this.registerStyleInput(name,false,input.value,input.sourceSpan,input.unit);break;case 2/* BindingType.Class */:binding=this.registerClassInput(name,false,input.value,input.sourceSpan);break;}return binding?true:false;}registerInputBasedOnName(name,expression,sourceSpan){let binding=null;const prefix=name.substring(0,6);const isStyle=name==='style'||prefix==='style.'||prefix==='style!';const isClass=!isStyle&&(name==='class'||prefix==='class.'||prefix==='class!');if(isStyle||isClass){const isMapBased=name.charAt(5)!=='.';// style.prop or class.prop makes this a no
|
|
1615
|
+
const property=name.slice(isMapBased?5:6);// the dot explains why there's a +1
|
|
1594
1616
|
if(isStyle){binding=this.registerStyleInput(property,isMapBased,expression,sourceSpan);}else {binding=this.registerClassInput(property,isMapBased,expression,sourceSpan);}}return binding;}registerStyleInput(name,isMapBased,value,sourceSpan,suffix){if(isEmptyExpression(value)){return null;}// CSS custom properties are case-sensitive so we shouldn't normalize them.
|
|
1595
1617
|
// See: https://www.w3.org/TR/css-variables-1/#defining-variables
|
|
1596
1618
|
if(!isCssCustomProperty(name)){name=hyphenate(name);}const{property,hasOverrideFlag,suffix:bindingSuffix}=parseProperty(name);suffix=typeof suffix==='string'&&suffix.length!==0?suffix:bindingSuffix;const entry={name:property,suffix:suffix,value,sourceSpan,hasOverrideFlag};if(isMapBased){this._styleMapInput=entry;}else {(this._singleStyleInputs=this._singleStyleInputs||[]).push(entry);registerIntoMap(this._stylesIndex,property);}this._lastStylingInput=entry;this._firstStylingInput=this._firstStylingInput||entry;this._checkForPipes(value);this.hasBindings=true;return entry;}registerClassInput(name,isMapBased,value,sourceSpan){if(isEmptyExpression(value)){return null;}const{property,hasOverrideFlag}=parseProperty(name);const entry={name:property,value,sourceSpan,hasOverrideFlag,suffix:null};if(isMapBased){this._classMapInput=entry;}else {(this._singleClassInputs=this._singleClassInputs||[]).push(entry);registerIntoMap(this._classesIndex,property);}this._lastStylingInput=entry;this._firstStylingInput=this._firstStylingInput||entry;this._checkForPipes(value);this.hasBindings=true;return entry;}_checkForPipes(value){if(value instanceof ASTWithSource&&value.ast instanceof BindingPipe){this.hasBindingsWithPipes=true;}}/**
|
|
@@ -1607,8 +1629,8 @@ if(!isCssCustomProperty(name)){name=hyphenate(name);}const{property,hasOverrideF
|
|
|
1607
1629
|
* @param attrs an existing array where each of the styling expressions
|
|
1608
1630
|
* will be inserted into.
|
|
1609
1631
|
*/populateInitialStylingAttrs(attrs){// [CLASS_MARKER, 'foo', 'bar', 'baz' ...]
|
|
1610
|
-
if(this._initialClassValues.length){attrs.push(literal(1/* Classes */));for(let i=0;i<this._initialClassValues.length;i++){attrs.push(literal(this._initialClassValues[i]));}}// [STYLE_MARKER, 'width', '200px', 'height', '100px', ...]
|
|
1611
|
-
if(this._initialStyleValues.length){attrs.push(literal(2/* Styles */));for(let i=0;i<this._initialStyleValues.length;i+=2){attrs.push(literal(this._initialStyleValues[i]),literal(this._initialStyleValues[i+1]));}}}/**
|
|
1632
|
+
if(this._initialClassValues.length){attrs.push(literal(1/* AttributeMarker.Classes */));for(let i=0;i<this._initialClassValues.length;i++){attrs.push(literal(this._initialClassValues[i]));}}// [STYLE_MARKER, 'width', '200px', 'height', '100px', ...]
|
|
1633
|
+
if(this._initialStyleValues.length){attrs.push(literal(2/* AttributeMarker.Styles */));for(let i=0;i<this._initialStyleValues.length;i+=2){attrs.push(literal(this._initialStyleValues[i]),literal(this._initialStyleValues[i+1]));}}}/**
|
|
1612
1634
|
* Builds an instruction with all the expressions and parameters for `elementHostAttrs`.
|
|
1613
1635
|
*
|
|
1614
1636
|
* The instruction generation code below is used for producing the AOT statement code which is
|
|
@@ -1648,7 +1670,7 @@ if(!isClassBased&&input.suffix!==null){params.push(literal(input.suffix));}retur
|
|
|
1648
1670
|
if(previousInstruction&&previousInstruction.reference===referenceForCall){previousInstruction.calls.push(call);}else {instructions.push({reference:referenceForCall,calls:[call]});}});return instructions;}_buildClassInputs(valueConverter){if(this._singleClassInputs){return this._buildSingleInputs(Identifiers.classProp,this._singleClassInputs,valueConverter,null,true);}return [];}_buildStyleInputs(valueConverter){if(this._singleStyleInputs){return this._buildSingleInputs(Identifiers.styleProp,this._singleStyleInputs,valueConverter,getStylePropInterpolationExpression,false);}return [];}/**
|
|
1649
1671
|
* Constructs all instructions which contain the expressions that will be placed
|
|
1650
1672
|
* into the update block of a template function or a directive hostBindings function.
|
|
1651
|
-
*/buildUpdateLevelInstructions(valueConverter){const instructions=[];if(this.hasBindings){const styleMapInstruction=this.buildStyleMapInstruction(valueConverter);if(styleMapInstruction){instructions.push(styleMapInstruction);}const classMapInstruction=this.buildClassMapInstruction(valueConverter);if(classMapInstruction){instructions.push(classMapInstruction);}instructions.push(...this._buildStyleInputs(valueConverter));instructions.push(...this._buildClassInputs(valueConverter));}return instructions;}}function registerIntoMap(map,key){if(!map.has(key)){map.set(key,map.size);}}function parseProperty(name){let hasOverrideFlag=false;const overrideIndex=name.indexOf(IMPORTANT_FLAG);if(overrideIndex!==-1){name=overrideIndex>0?name.substring(0,overrideIndex):'';hasOverrideFlag=true;}let suffix=null;let property=name;const unitIndex=name.lastIndexOf('.');if(unitIndex>0){suffix=name.
|
|
1673
|
+
*/buildUpdateLevelInstructions(valueConverter){const instructions=[];if(this.hasBindings){const styleMapInstruction=this.buildStyleMapInstruction(valueConverter);if(styleMapInstruction){instructions.push(styleMapInstruction);}const classMapInstruction=this.buildClassMapInstruction(valueConverter);if(classMapInstruction){instructions.push(classMapInstruction);}instructions.push(...this._buildStyleInputs(valueConverter));instructions.push(...this._buildClassInputs(valueConverter));}return instructions;}}function registerIntoMap(map,key){if(!map.has(key)){map.set(key,map.size);}}function parseProperty(name){let hasOverrideFlag=false;const overrideIndex=name.indexOf(IMPORTANT_FLAG);if(overrideIndex!==-1){name=overrideIndex>0?name.substring(0,overrideIndex):'';hasOverrideFlag=true;}let suffix=null;let property=name;const unitIndex=name.lastIndexOf('.');if(unitIndex>0){suffix=name.slice(unitIndex+1);property=name.substring(0,unitIndex);}return {property,suffix,hasOverrideFlag};}/**
|
|
1652
1674
|
* Gets the instruction to generate for an interpolated class map.
|
|
1653
1675
|
* @param interpolation An Interpolation AST
|
|
1654
1676
|
*/function getClassMapInterpolationExpression(interpolation){switch(getInterpolationArgsLength(interpolation)){case 1:return Identifiers.classMap;case 3:return Identifiers.classMapInterpolate1;case 5:return Identifiers.classMapInterpolate2;case 7:return Identifiers.classMapInterpolate3;case 9:return Identifiers.classMapInterpolate4;case 11:return Identifiers.classMapInterpolate5;case 13:return Identifiers.classMapInterpolate6;case 15:return Identifiers.classMapInterpolate7;case 17:return Identifiers.classMapInterpolate8;default:return Identifiers.classMapInterpolateV;}}/**
|
|
@@ -1694,9 +1716,7 @@ if(this.peek===$QUESTION||this.peek===$PERIOD){str+=this.peek===$PERIOD?'.':'?';
|
|
|
1694
1716
|
*
|
|
1695
1717
|
* Use of this source code is governed by an MIT-style license that can be
|
|
1696
1718
|
* found in the LICENSE file at https://angular.io/license
|
|
1697
|
-
*/class SplitInterpolation{constructor(strings,expressions,offsets){this.strings=strings;this.expressions=expressions;this.offsets=offsets;}}class TemplateBindingParseResult{constructor(templateBindings,warnings,errors){this.templateBindings=templateBindings;this.warnings=warnings;this.errors=errors;}}class Parser$1{constructor(_lexer){this._lexer=_lexer;this.errors=[];}parseAction(input,isAssignmentEvent,location,absoluteOffset,interpolationConfig=DEFAULT_INTERPOLATION_CONFIG){this._checkNoInterpolation(input,location,interpolationConfig);const sourceToLex=this._stripComments(input);const tokens=this._lexer.tokenize(sourceToLex);let flags=1/* Action */;if(isAssignmentEvent){flags|=2/* AssignmentEvent */;}const ast=new _ParseAST(input,location,absoluteOffset,tokens,flags,this.errors,0).parseChain();return new ASTWithSource(ast,input,location,absoluteOffset,this.errors);}parseBinding(input,location,absoluteOffset,interpolationConfig=DEFAULT_INTERPOLATION_CONFIG){const ast=this._parseBindingAst(input,location,absoluteOffset,interpolationConfig);return new ASTWithSource(ast,input,location,absoluteOffset,this.errors);}checkSimpleExpression(ast){const checker=new SimpleExpressionChecker();ast.visit(checker);return checker.errors;}parseSimpleBinding(input,location,absoluteOffset,interpolationConfig=DEFAULT_INTERPOLATION_CONFIG){const ast=this._parseBindingAst(input,location,absoluteOffset,interpolationConfig);const errors=this.checkSimpleExpression(ast);if(errors.length>0){this._reportError(`Host binding expression cannot contain ${errors.join(' ')}`,input,location);}return new ASTWithSource(ast,input,location,absoluteOffset,this.errors);}_reportError(message,input,errLocation,ctxLocation){this.errors.push(new ParserError(message,input,errLocation,ctxLocation));}_parseBindingAst(input,location,absoluteOffset,interpolationConfig){
|
|
1698
|
-
// our lexer or parser for that, so we check for that ahead of time.
|
|
1699
|
-
const quote=this._parseQuote(input,location,absoluteOffset);if(quote!=null){return quote;}this._checkNoInterpolation(input,location,interpolationConfig);const sourceToLex=this._stripComments(input);const tokens=this._lexer.tokenize(sourceToLex);return new _ParseAST(input,location,absoluteOffset,tokens,0/* None */,this.errors,0).parseChain();}_parseQuote(input,location,absoluteOffset){if(input==null)return null;const prefixSeparatorIndex=input.indexOf(':');if(prefixSeparatorIndex==-1)return null;const prefix=input.substring(0,prefixSeparatorIndex).trim();if(!isIdentifier(prefix))return null;const uninterpretedExpression=input.substring(prefixSeparatorIndex+1);const span=new ParseSpan(0,input.length);return new Quote(span,span.toAbsolute(absoluteOffset),prefix,uninterpretedExpression,location);}/**
|
|
1719
|
+
*/class SplitInterpolation{constructor(strings,expressions,offsets){this.strings=strings;this.expressions=expressions;this.offsets=offsets;}}class TemplateBindingParseResult{constructor(templateBindings,warnings,errors){this.templateBindings=templateBindings;this.warnings=warnings;this.errors=errors;}}class Parser$1{constructor(_lexer){this._lexer=_lexer;this.errors=[];}parseAction(input,isAssignmentEvent,location,absoluteOffset,interpolationConfig=DEFAULT_INTERPOLATION_CONFIG){this._checkNoInterpolation(input,location,interpolationConfig);const sourceToLex=this._stripComments(input);const tokens=this._lexer.tokenize(sourceToLex);let flags=1/* ParseFlags.Action */;if(isAssignmentEvent){flags|=2/* ParseFlags.AssignmentEvent */;}const ast=new _ParseAST(input,location,absoluteOffset,tokens,flags,this.errors,0).parseChain();return new ASTWithSource(ast,input,location,absoluteOffset,this.errors);}parseBinding(input,location,absoluteOffset,interpolationConfig=DEFAULT_INTERPOLATION_CONFIG){const ast=this._parseBindingAst(input,location,absoluteOffset,interpolationConfig);return new ASTWithSource(ast,input,location,absoluteOffset,this.errors);}checkSimpleExpression(ast){const checker=new SimpleExpressionChecker();ast.visit(checker);return checker.errors;}parseSimpleBinding(input,location,absoluteOffset,interpolationConfig=DEFAULT_INTERPOLATION_CONFIG){const ast=this._parseBindingAst(input,location,absoluteOffset,interpolationConfig);const errors=this.checkSimpleExpression(ast);if(errors.length>0){this._reportError(`Host binding expression cannot contain ${errors.join(' ')}`,input,location);}return new ASTWithSource(ast,input,location,absoluteOffset,this.errors);}_reportError(message,input,errLocation,ctxLocation){this.errors.push(new ParserError(message,input,errLocation,ctxLocation));}_parseBindingAst(input,location,absoluteOffset,interpolationConfig){this._checkNoInterpolation(input,location,interpolationConfig);const sourceToLex=this._stripComments(input);const tokens=this._lexer.tokenize(sourceToLex);return new _ParseAST(input,location,absoluteOffset,tokens,0/* ParseFlags.None */,this.errors,0).parseChain();}/**
|
|
1700
1720
|
* Parse microsyntax template expression and return a list of bindings or
|
|
1701
1721
|
* parsing errors in case the given expression is invalid.
|
|
1702
1722
|
*
|
|
@@ -1721,11 +1741,11 @@ const quote=this._parseQuote(input,location,absoluteOffset);if(quote!=null){retu
|
|
|
1721
1741
|
* @param templateUrl template filename if it's external, component filename if it's inline
|
|
1722
1742
|
* @param absoluteKeyOffset start of the `templateKey`
|
|
1723
1743
|
* @param absoluteValueOffset start of the `templateValue`
|
|
1724
|
-
*/parseTemplateBindings(templateKey,templateValue,templateUrl,absoluteKeyOffset,absoluteValueOffset){const tokens=this._lexer.tokenize(templateValue);const parser=new _ParseAST(templateValue,templateUrl,absoluteValueOffset,tokens,0/* None */,this.errors,0/* relative offset */);return parser.parseTemplateBindings({source:templateKey,span:new AbsoluteSourceSpan(absoluteKeyOffset,absoluteKeyOffset+templateKey.length)});}parseInterpolation(input,location,absoluteOffset,interpolatedTokens,interpolationConfig=DEFAULT_INTERPOLATION_CONFIG){const{strings,expressions,offsets}=this.splitInterpolation(input,location,interpolatedTokens,interpolationConfig);if(expressions.length===0)return null;const expressionNodes=[];for(let i=0;i<expressions.length;++i){const expressionText=expressions[i].text;const sourceToLex=this._stripComments(expressionText);const tokens=this._lexer.tokenize(sourceToLex);const ast=new _ParseAST(input,location,absoluteOffset,tokens,0/* None */,this.errors,offsets[i]).parseChain();expressionNodes.push(ast);}return this.createInterpolationAst(strings.map(s=>s.text),expressionNodes,input,location,absoluteOffset);}/**
|
|
1744
|
+
*/parseTemplateBindings(templateKey,templateValue,templateUrl,absoluteKeyOffset,absoluteValueOffset){const tokens=this._lexer.tokenize(templateValue);const parser=new _ParseAST(templateValue,templateUrl,absoluteValueOffset,tokens,0/* ParseFlags.None */,this.errors,0/* relative offset */);return parser.parseTemplateBindings({source:templateKey,span:new AbsoluteSourceSpan(absoluteKeyOffset,absoluteKeyOffset+templateKey.length)});}parseInterpolation(input,location,absoluteOffset,interpolatedTokens,interpolationConfig=DEFAULT_INTERPOLATION_CONFIG){const{strings,expressions,offsets}=this.splitInterpolation(input,location,interpolatedTokens,interpolationConfig);if(expressions.length===0)return null;const expressionNodes=[];for(let i=0;i<expressions.length;++i){const expressionText=expressions[i].text;const sourceToLex=this._stripComments(expressionText);const tokens=this._lexer.tokenize(sourceToLex);const ast=new _ParseAST(input,location,absoluteOffset,tokens,0/* ParseFlags.None */,this.errors,offsets[i]).parseChain();expressionNodes.push(ast);}return this.createInterpolationAst(strings.map(s=>s.text),expressionNodes,input,location,absoluteOffset);}/**
|
|
1725
1745
|
* Similar to `parseInterpolation`, but treats the provided string as a single expression
|
|
1726
1746
|
* element that would normally appear within the interpolation prefix and suffix (`{{` and `}}`).
|
|
1727
1747
|
* This is used for parsing the switch expression in ICUs.
|
|
1728
|
-
*/parseInterpolationExpression(expression,location,absoluteOffset){const sourceToLex=this._stripComments(expression);const tokens=this._lexer.tokenize(sourceToLex);const ast=new _ParseAST(expression,location,absoluteOffset,tokens,0/* None */,this.errors,0).parseChain();const strings=['',''];// The prefix and suffix strings are both empty
|
|
1748
|
+
*/parseInterpolationExpression(expression,location,absoluteOffset){const sourceToLex=this._stripComments(expression);const tokens=this._lexer.tokenize(sourceToLex);const ast=new _ParseAST(expression,location,absoluteOffset,tokens,0/* ParseFlags.None */,this.errors,0).parseChain();const strings=['',''];// The prefix and suffix strings are both empty
|
|
1729
1749
|
return this.createInterpolationAst(strings,[ast],expression,location,absoluteOffset);}createInterpolationAst(strings,expressions,input,location,absoluteOffset){const span=new ParseSpan(0,input.length);const interpolation=new Interpolation(span,span.toAbsolute(absoluteOffset),strings,expressions);return new ASTWithSource(interpolation,input,location,absoluteOffset,this.errors);}/**
|
|
1730
1750
|
* Splits a string of text into "raw" text segments and expressions present in interpolations in
|
|
1731
1751
|
* the string.
|
|
@@ -1788,9 +1808,9 @@ if(start>endIndex){const tmp=endIndex;endIndex=start;start=tmp;}return new Parse
|
|
|
1788
1808
|
* and skips over the token stream until reaching a recoverable point.
|
|
1789
1809
|
*
|
|
1790
1810
|
* See `this.error` and `this.skip` for more details.
|
|
1791
|
-
*/expectCharacter(code){if(this.consumeOptionalCharacter(code))return;this.error(`Missing expected ${String.fromCharCode(code)}`);}consumeOptionalOperator(op){if(this.next.isOperator(op)){this.advance();return true;}else {return false;}}expectOperator(operator){if(this.consumeOptionalOperator(operator))return;this.error(`Missing expected operator ${operator}`);}prettyPrintToken(tok){return tok===EOF?'end of input':`token ${tok}`;}expectIdentifierOrKeyword(){const n=this.next;if(!n.isIdentifier()&&!n.isKeyword()){if(n.isPrivateIdentifier()){this._reportErrorForPrivateIdentifier(n,'expected identifier or keyword');}else {this.error(`Unexpected ${this.prettyPrintToken(n)}, expected identifier or keyword`);}return null;}this.advance();return n.toString();}expectIdentifierOrKeywordOrString(){const n=this.next;if(!n.isIdentifier()&&!n.isKeyword()&&!n.isString()){if(n.isPrivateIdentifier()){this._reportErrorForPrivateIdentifier(n,'expected identifier, keyword or string');}else {this.error(`Unexpected ${this.prettyPrintToken(n)}, expected identifier, keyword, or string`);}return '';}this.advance();return n.toString();}parseChain(){const exprs=[];const start=this.inputIndex;while(this.index<this.tokens.length){const expr=this.parsePipe();exprs.push(expr);if(this.consumeOptionalCharacter($SEMICOLON)){if(!(this.parseFlags&1/* Action */)){this.error('Binding expression cannot contain chained expression');}while(this.consumeOptionalCharacter($SEMICOLON)){}// read all semicolons
|
|
1811
|
+
*/expectCharacter(code){if(this.consumeOptionalCharacter(code))return;this.error(`Missing expected ${String.fromCharCode(code)}`);}consumeOptionalOperator(op){if(this.next.isOperator(op)){this.advance();return true;}else {return false;}}expectOperator(operator){if(this.consumeOptionalOperator(operator))return;this.error(`Missing expected operator ${operator}`);}prettyPrintToken(tok){return tok===EOF?'end of input':`token ${tok}`;}expectIdentifierOrKeyword(){const n=this.next;if(!n.isIdentifier()&&!n.isKeyword()){if(n.isPrivateIdentifier()){this._reportErrorForPrivateIdentifier(n,'expected identifier or keyword');}else {this.error(`Unexpected ${this.prettyPrintToken(n)}, expected identifier or keyword`);}return null;}this.advance();return n.toString();}expectIdentifierOrKeywordOrString(){const n=this.next;if(!n.isIdentifier()&&!n.isKeyword()&&!n.isString()){if(n.isPrivateIdentifier()){this._reportErrorForPrivateIdentifier(n,'expected identifier, keyword or string');}else {this.error(`Unexpected ${this.prettyPrintToken(n)}, expected identifier, keyword, or string`);}return '';}this.advance();return n.toString();}parseChain(){const exprs=[];const start=this.inputIndex;while(this.index<this.tokens.length){const expr=this.parsePipe();exprs.push(expr);if(this.consumeOptionalCharacter($SEMICOLON)){if(!(this.parseFlags&1/* ParseFlags.Action */)){this.error('Binding expression cannot contain chained expression');}while(this.consumeOptionalCharacter($SEMICOLON)){}// read all semicolons
|
|
1792
1812
|
}else if(this.index<this.tokens.length){this.error(`Unexpected token '${this.next}'`);}}if(exprs.length==0){// We have no expressions so create an empty expression that spans the entire input length
|
|
1793
|
-
const artificialStart=this.offset;const artificialEnd=this.offset+this.input.length;return new EmptyExpr(this.span(artificialStart,artificialEnd),this.sourceSpan(artificialStart,artificialEnd));}if(exprs.length==1)return exprs[0];return new Chain(this.span(start),this.sourceSpan(start),exprs);}parsePipe(){const start=this.inputIndex;let result=this.parseExpression();if(this.consumeOptionalOperator('|')){if(this.parseFlags&1/* Action */){this.error('Cannot have a pipe in an action expression');}do{const nameStart=this.inputIndex;let nameId=this.expectIdentifierOrKeyword();let nameSpan;let fullSpanEnd=undefined;if(nameId!==null){nameSpan=this.sourceSpan(nameStart);}else {// No valid identifier was found, so we'll assume an empty pipe name ('').
|
|
1813
|
+
const artificialStart=this.offset;const artificialEnd=this.offset+this.input.length;return new EmptyExpr(this.span(artificialStart,artificialEnd),this.sourceSpan(artificialStart,artificialEnd));}if(exprs.length==1)return exprs[0];return new Chain(this.span(start),this.sourceSpan(start),exprs);}parsePipe(){const start=this.inputIndex;let result=this.parseExpression();if(this.consumeOptionalOperator('|')){if(this.parseFlags&1/* ParseFlags.Action */){this.error('Cannot have a pipe in an action expression');}do{const nameStart=this.inputIndex;let nameId=this.expectIdentifierOrKeyword();let nameSpan;let fullSpanEnd=undefined;if(nameId!==null){nameSpan=this.sourceSpan(nameStart);}else {// No valid identifier was found, so we'll assume an empty pipe name ('').
|
|
1794
1814
|
nameId='';// However, there may have been whitespace present between the pipe character and the next
|
|
1795
1815
|
// token in the sequence (or the end of input). We want to track this whitespace so that
|
|
1796
1816
|
// the `BindingPipe` we produce covers not just the pipe character, but any trailing
|
|
@@ -1811,12 +1831,12 @@ const start=this.inputIndex;let result=this.parseRelational();while(this.next.ty
|
|
|
1811
1831
|
const start=this.inputIndex;let result=this.parseAdditive();while(this.next.type==exports.TokenType.Operator){const operator=this.next.strValue;switch(operator){case'<':case'>':case'<=':case'>=':this.advance();const right=this.parseAdditive();result=new Binary(this.span(start),this.sourceSpan(start),operator,result,right);continue;}break;}return result;}parseAdditive(){// '+', '-'
|
|
1812
1832
|
const start=this.inputIndex;let result=this.parseMultiplicative();while(this.next.type==exports.TokenType.Operator){const operator=this.next.strValue;switch(operator){case'+':case'-':this.advance();let right=this.parseMultiplicative();result=new Binary(this.span(start),this.sourceSpan(start),operator,result,right);continue;}break;}return result;}parseMultiplicative(){// '*', '%', '/'
|
|
1813
1833
|
const start=this.inputIndex;let result=this.parsePrefix();while(this.next.type==exports.TokenType.Operator){const operator=this.next.strValue;switch(operator){case'*':case'%':case'/':this.advance();let right=this.parsePrefix();result=new Binary(this.span(start),this.sourceSpan(start),operator,result,right);continue;}break;}return result;}parsePrefix(){if(this.next.type==exports.TokenType.Operator){const start=this.inputIndex;const operator=this.next.strValue;let result;switch(operator){case'+':this.advance();result=this.parsePrefix();return Unary.createPlus(this.span(start),this.sourceSpan(start),result);case'-':this.advance();result=this.parsePrefix();return Unary.createMinus(this.span(start),this.sourceSpan(start),result);case'!':this.advance();result=this.parsePrefix();return new PrefixNot(this.span(start),this.sourceSpan(start),result);}}return this.parseCallChain();}parseCallChain(){const start=this.inputIndex;let result=this.parsePrimary();while(true){if(this.consumeOptionalCharacter($PERIOD)){result=this.parseAccessMember(result,start,false);}else if(this.consumeOptionalOperator('?.')){if(this.consumeOptionalCharacter($LPAREN)){result=this.parseCall(result,start,true);}else {result=this.consumeOptionalCharacter($LBRACKET)?this.parseKeyedReadOrWrite(result,start,true):this.parseAccessMember(result,start,true);}}else if(this.consumeOptionalCharacter($LBRACKET)){result=this.parseKeyedReadOrWrite(result,start,false);}else if(this.consumeOptionalCharacter($LPAREN)){result=this.parseCall(result,start,false);}else if(this.consumeOptionalOperator('!')){result=new NonNullAssert(this.span(start),this.sourceSpan(start),result);}else {return result;}}}parsePrimary(){const start=this.inputIndex;if(this.consumeOptionalCharacter($LPAREN)){this.rparensExpected++;const result=this.parsePipe();this.rparensExpected--;this.expectCharacter($RPAREN);return result;}else if(this.next.isKeywordNull()){this.advance();return new LiteralPrimitive(this.span(start),this.sourceSpan(start),null);}else if(this.next.isKeywordUndefined()){this.advance();return new LiteralPrimitive(this.span(start),this.sourceSpan(start),void 0);}else if(this.next.isKeywordTrue()){this.advance();return new LiteralPrimitive(this.span(start),this.sourceSpan(start),true);}else if(this.next.isKeywordFalse()){this.advance();return new LiteralPrimitive(this.span(start),this.sourceSpan(start),false);}else if(this.next.isKeywordThis()){this.advance();return new ThisReceiver(this.span(start),this.sourceSpan(start));}else if(this.consumeOptionalCharacter($LBRACKET)){this.rbracketsExpected++;const elements=this.parseExpressionList($RBRACKET);this.rbracketsExpected--;this.expectCharacter($RBRACKET);return new LiteralArray(this.span(start),this.sourceSpan(start),elements);}else if(this.next.isCharacter($LBRACE)){return this.parseLiteralMap();}else if(this.next.isIdentifier()){return this.parseAccessMember(new ImplicitReceiver(this.span(start),this.sourceSpan(start)),start,false);}else if(this.next.isNumber()){const value=this.next.toNumber();this.advance();return new LiteralPrimitive(this.span(start),this.sourceSpan(start),value);}else if(this.next.isString()){const literalValue=this.next.toString();this.advance();return new LiteralPrimitive(this.span(start),this.sourceSpan(start),literalValue);}else if(this.next.isPrivateIdentifier()){this._reportErrorForPrivateIdentifier(this.next,null);return new EmptyExpr(this.span(start),this.sourceSpan(start));}else if(this.index>=this.tokens.length){this.error(`Unexpected end of expression: ${this.input}`);return new EmptyExpr(this.span(start),this.sourceSpan(start));}else {this.error(`Unexpected token ${this.next}`);return new EmptyExpr(this.span(start),this.sourceSpan(start));}}parseExpressionList(terminator){const result=[];do{if(!this.next.isCharacter(terminator)){result.push(this.parsePipe());}else {break;}}while(this.consumeOptionalCharacter($COMMA));return result;}parseLiteralMap(){const keys=[];const values=[];const start=this.inputIndex;this.expectCharacter($LBRACE);if(!this.consumeOptionalCharacter($RBRACE)){this.rbracesExpected++;do{const keyStart=this.inputIndex;const quoted=this.next.isString();const key=this.expectIdentifierOrKeywordOrString();keys.push({key,quoted});// Properties with quoted keys can't use the shorthand syntax.
|
|
1814
|
-
if(quoted){this.expectCharacter($COLON);values.push(this.parsePipe());}else if(this.consumeOptionalCharacter($COLON)){values.push(this.parsePipe());}else {const span=this.span(keyStart);const sourceSpan=this.sourceSpan(keyStart);values.push(new PropertyRead(span,sourceSpan,sourceSpan,new ImplicitReceiver(span,sourceSpan),key));}}while(this.consumeOptionalCharacter($COMMA));this.rbracesExpected--;this.expectCharacter($RBRACE);}return new LiteralMap(this.span(start),this.sourceSpan(start),keys,values);}parseAccessMember(readReceiver,start,isSafe){const nameStart=this.inputIndex;const id=this.withContext(ParseContextFlags.Writable,()=>{var _a;const id=(_a=this.expectIdentifierOrKeyword())!==null&&_a!==void 0?_a:'';if(id.length===0){this.error(`Expected identifier for property access`,readReceiver.span.end);}return id;});const nameSpan=this.sourceSpan(nameStart);let receiver;if(isSafe){if(this.consumeOptionalAssignment()){this.error('The \'?.\' operator cannot be used in the assignment');receiver=new EmptyExpr(this.span(start),this.sourceSpan(start));}else {receiver=new SafePropertyRead(this.span(start),this.sourceSpan(start),nameSpan,readReceiver,id);}}else {if(this.consumeOptionalAssignment()){if(!(this.parseFlags&1/* Action */)){this.error('Bindings cannot contain assignments');return new EmptyExpr(this.span(start),this.sourceSpan(start));}const value=this.parseConditional();receiver=new PropertyWrite(this.span(start),this.sourceSpan(start),nameSpan,readReceiver,id,value);}else {receiver=new PropertyRead(this.span(start),this.sourceSpan(start),nameSpan,readReceiver,id);}}return receiver;}parseCall(receiver,start,isSafe){const argumentStart=this.inputIndex;this.rparensExpected++;const args=this.parseCallArguments();const argumentSpan=this.span(argumentStart,this.inputIndex).toAbsolute(this.absoluteOffset);this.expectCharacter($RPAREN);this.rparensExpected--;const span=this.span(start);const sourceSpan=this.sourceSpan(start);return isSafe?new SafeCall(span,sourceSpan,receiver,args,argumentSpan):new Call(span,sourceSpan,receiver,args,argumentSpan);}consumeOptionalAssignment(){// When parsing assignment events (originating from two-way-binding aka banana-in-a-box syntax),
|
|
1834
|
+
if(quoted){this.expectCharacter($COLON);values.push(this.parsePipe());}else if(this.consumeOptionalCharacter($COLON)){values.push(this.parsePipe());}else {const span=this.span(keyStart);const sourceSpan=this.sourceSpan(keyStart);values.push(new PropertyRead(span,sourceSpan,sourceSpan,new ImplicitReceiver(span,sourceSpan),key));}}while(this.consumeOptionalCharacter($COMMA));this.rbracesExpected--;this.expectCharacter($RBRACE);}return new LiteralMap(this.span(start),this.sourceSpan(start),keys,values);}parseAccessMember(readReceiver,start,isSafe){const nameStart=this.inputIndex;const id=this.withContext(ParseContextFlags.Writable,()=>{var _a;const id=(_a=this.expectIdentifierOrKeyword())!==null&&_a!==void 0?_a:'';if(id.length===0){this.error(`Expected identifier for property access`,readReceiver.span.end);}return id;});const nameSpan=this.sourceSpan(nameStart);let receiver;if(isSafe){if(this.consumeOptionalAssignment()){this.error('The \'?.\' operator cannot be used in the assignment');receiver=new EmptyExpr(this.span(start),this.sourceSpan(start));}else {receiver=new SafePropertyRead(this.span(start),this.sourceSpan(start),nameSpan,readReceiver,id);}}else {if(this.consumeOptionalAssignment()){if(!(this.parseFlags&1/* ParseFlags.Action */)){this.error('Bindings cannot contain assignments');return new EmptyExpr(this.span(start),this.sourceSpan(start));}const value=this.parseConditional();receiver=new PropertyWrite(this.span(start),this.sourceSpan(start),nameSpan,readReceiver,id,value);}else {receiver=new PropertyRead(this.span(start),this.sourceSpan(start),nameSpan,readReceiver,id);}}return receiver;}parseCall(receiver,start,isSafe){const argumentStart=this.inputIndex;this.rparensExpected++;const args=this.parseCallArguments();const argumentSpan=this.span(argumentStart,this.inputIndex).toAbsolute(this.absoluteOffset);this.expectCharacter($RPAREN);this.rparensExpected--;const span=this.span(start);const sourceSpan=this.sourceSpan(start);return isSafe?new SafeCall(span,sourceSpan,receiver,args,argumentSpan):new Call(span,sourceSpan,receiver,args,argumentSpan);}consumeOptionalAssignment(){// When parsing assignment events (originating from two-way-binding aka banana-in-a-box syntax),
|
|
1815
1835
|
// it is valid for the primary expression to be terminated by the non-null operator. This
|
|
1816
1836
|
// primary expression is substituted as LHS of the assignment operator to achieve
|
|
1817
1837
|
// two-way-binding, such that the LHS could be the non-null operator. The grammar doesn't
|
|
1818
1838
|
// naturally allow for this syntax, so assignment events are parsed specially.
|
|
1819
|
-
if(this.parseFlags&2/* AssignmentEvent */&&this.next.isOperator('!')&&this.peek(1).isOperator('=')){// First skip over the ! operator.
|
|
1839
|
+
if(this.parseFlags&2/* ParseFlags.AssignmentEvent */&&this.next.isOperator('!')&&this.peek(1).isOperator('=')){// First skip over the ! operator.
|
|
1820
1840
|
this.advance();// Then skip over the = operator, to fully consume the optional assignment operator.
|
|
1821
1841
|
this.advance();return true;}return this.consumeOptionalOperator('=');}parseCallArguments(){if(this.next.isCharacter($RPAREN))return [];const positionals=[];do{positionals.push(this.parsePipe());}while(this.consumeOptionalCharacter($COMMA));return positionals;}/**
|
|
1822
1842
|
* Parses an identifier, a keyword, a string with an optional `-` in between,
|
|
@@ -1947,7 +1967,7 @@ const key=this.expectTemplateBindingKey();let value=null;if(this.consumeOptional
|
|
|
1947
1967
|
* @param interpolatedTokens The tokens for the interpolated value.
|
|
1948
1968
|
*
|
|
1949
1969
|
* @returns A map of index locations in the decoded template to indexes in the original template
|
|
1950
|
-
*/function getIndexMapForOriginalTemplate(interpolatedTokens){let offsetMap=new Map();let consumedInOriginalTemplate=0;let consumedInInput=0;let tokenIndex=0;while(tokenIndex<interpolatedTokens.length){const currentToken=interpolatedTokens[tokenIndex];if(currentToken.type===9/* ENCODED_ENTITY */){const[decoded,encoded]=currentToken.parts;consumedInOriginalTemplate+=encoded.length;consumedInInput+=decoded.length;}else {const lengthOfParts=currentToken.parts.reduce((sum,current)=>sum+current.length,0);consumedInInput+=lengthOfParts;consumedInOriginalTemplate+=lengthOfParts;}offsetMap.set(consumedInInput,consumedInOriginalTemplate);tokenIndex++;}return offsetMap;}/**
|
|
1970
|
+
*/function getIndexMapForOriginalTemplate(interpolatedTokens){let offsetMap=new Map();let consumedInOriginalTemplate=0;let consumedInInput=0;let tokenIndex=0;while(tokenIndex<interpolatedTokens.length){const currentToken=interpolatedTokens[tokenIndex];if(currentToken.type===9/* MlParserTokenType.ENCODED_ENTITY */){const[decoded,encoded]=currentToken.parts;consumedInOriginalTemplate+=encoded.length;consumedInInput+=decoded.length;}else {const lengthOfParts=currentToken.parts.reduce((sum,current)=>sum+current.length,0);consumedInInput+=lengthOfParts;consumedInOriginalTemplate+=lengthOfParts;}offsetMap.set(consumedInInput,consumedInOriginalTemplate);tokenIndex++;}return offsetMap;}/**
|
|
1951
1971
|
* @license
|
|
1952
1972
|
* Copyright Google LLC All Rights Reserved.
|
|
1953
1973
|
*
|
|
@@ -1982,26 +2002,26 @@ class _Tokenizer{/**
|
|
|
1982
2002
|
// Instead CRs are processed right before instantiating the tokens.
|
|
1983
2003
|
return content.replace(_CR_OR_CRLF_REGEXP,'\n');}tokenize(){while(this._cursor.peek()!==$EOF){const start=this._cursor.clone();try{if(this._attemptCharCode($LT)){if(this._attemptCharCode($BANG)){if(this._attemptCharCode($LBRACKET)){this._consumeCdata(start);}else if(this._attemptCharCode($MINUS)){this._consumeComment(start);}else {this._consumeDocType(start);}}else if(this._attemptCharCode($SLASH)){this._consumeTagClose(start);}else {this._consumeTagOpen(start);}}else if(!(this._tokenizeIcu&&this._tokenizeExpansionForm())){// In (possibly interpolated) text the end of the text is given by `isTextEnd()`, while
|
|
1984
2004
|
// the premature end of an interpolation is given by the start of a new HTML element.
|
|
1985
|
-
this._consumeWithInterpolation(5/* TEXT */,8/* INTERPOLATION */,()=>this._isTextEnd(),()=>this._isTagStart());}}catch(e){this.handleError(e);}}this._beginToken(24/* EOF */);this._endToken([]);}/**
|
|
2005
|
+
this._consumeWithInterpolation(5/* TokenType.TEXT */,8/* TokenType.INTERPOLATION */,()=>this._isTextEnd(),()=>this._isTagStart());}}catch(e){this.handleError(e);}}this._beginToken(24/* TokenType.EOF */);this._endToken([]);}/**
|
|
1986
2006
|
* @returns whether an ICU token has been created
|
|
1987
2007
|
* @internal
|
|
1988
2008
|
*/_tokenizeExpansionForm(){if(this.isExpansionFormStart()){this._consumeExpansionFormStart();return true;}if(isExpansionCaseStart(this._cursor.peek())&&this._isInExpansionForm()){this._consumeExpansionCaseStart();return true;}if(this._cursor.peek()===$RBRACE){if(this._isInExpansionCase()){this._consumeExpansionCaseEnd();return true;}if(this._isInExpansionForm()){this._consumeExpansionFormEnd();return true;}}return false;}_beginToken(type,start=this._cursor.clone()){this._currentTokenStart=start;this._currentTokenType=type;}_endToken(parts,end){if(this._currentTokenStart===null){throw new TokenError('Programming error - attempted to end a token when there was no start to the token',this._currentTokenType,this._cursor.getSpan(end));}if(this._currentTokenType===null){throw new TokenError('Programming error - attempted to end a token which has no token type',null,this._cursor.getSpan(this._currentTokenStart));}const token={type:this._currentTokenType,parts,sourceSpan:(end!==null&&end!==void 0?end:this._cursor).getSpan(this._currentTokenStart,this._leadingTriviaCodePoints)};this.tokens.push(token);this._currentTokenStart=null;this._currentTokenType=null;return token;}_createError(msg,span){if(this._isInExpansionForm()){msg+=` (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.)`;}const error=new TokenError(msg,this._currentTokenType,span);this._currentTokenStart=null;this._currentTokenType=null;return new _ControlFlowError(error);}handleError(e){if(e instanceof CursorError){e=this._createError(e.msg,this._cursor.getSpan(e.cursor));}if(e instanceof _ControlFlowError){this.errors.push(e.error);}else {throw e;}}_attemptCharCode(charCode){if(this._cursor.peek()===charCode){this._cursor.advance();return true;}return false;}_attemptCharCodeCaseInsensitive(charCode){if(compareCharCodeCaseInsensitive(this._cursor.peek(),charCode)){this._cursor.advance();return true;}return false;}_requireCharCode(charCode){const location=this._cursor.clone();if(!this._attemptCharCode(charCode)){throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()),this._cursor.getSpan(location));}}_attemptStr(chars){const len=chars.length;if(this._cursor.charsLeft()<len){return false;}const initialPosition=this._cursor.clone();for(let i=0;i<len;i++){if(!this._attemptCharCode(chars.charCodeAt(i))){// If attempting to parse the string fails, we want to reset the parser
|
|
1989
2009
|
// to where it was before the attempt
|
|
1990
2010
|
this._cursor=initialPosition;return false;}}return true;}_attemptStrCaseInsensitive(chars){for(let i=0;i<chars.length;i++){if(!this._attemptCharCodeCaseInsensitive(chars.charCodeAt(i))){return false;}}return true;}_requireStr(chars){const location=this._cursor.clone();if(!this._attemptStr(chars)){throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()),this._cursor.getSpan(location));}}_attemptCharCodeUntilFn(predicate){while(!predicate(this._cursor.peek())){this._cursor.advance();}}_requireCharCodeUntilFn(predicate,len){const start=this._cursor.clone();this._attemptCharCodeUntilFn(predicate);if(this._cursor.diff(start)<len){throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()),this._cursor.getSpan(start));}}_attemptUntilChar(char){while(this._cursor.peek()!==char){this._cursor.advance();}}_readChar(){// Don't rely upon reading directly from `_input` as the actual char value
|
|
1991
2011
|
// may have been generated from an escape sequence.
|
|
1992
|
-
const char=String.fromCodePoint(this._cursor.peek());this._cursor.advance();return char;}_consumeEntity(textTokenType){this._beginToken(9/* ENCODED_ENTITY */);const start=this._cursor.clone();this._cursor.advance();if(this._attemptCharCode($HASH)){const isHex=this._attemptCharCode($x)||this._attemptCharCode($X);const codeStart=this._cursor.clone();this._attemptCharCodeUntilFn(isDigitEntityEnd);if(this._cursor.peek()!=$SEMICOLON){// Advance cursor to include the peeked character in the string provided to the error
|
|
2012
|
+
const char=String.fromCodePoint(this._cursor.peek());this._cursor.advance();return char;}_consumeEntity(textTokenType){this._beginToken(9/* TokenType.ENCODED_ENTITY */);const start=this._cursor.clone();this._cursor.advance();if(this._attemptCharCode($HASH)){const isHex=this._attemptCharCode($x)||this._attemptCharCode($X);const codeStart=this._cursor.clone();this._attemptCharCodeUntilFn(isDigitEntityEnd);if(this._cursor.peek()!=$SEMICOLON){// Advance cursor to include the peeked character in the string provided to the error
|
|
1993
2013
|
// message.
|
|
1994
2014
|
this._cursor.advance();const entityType=isHex?CharacterReferenceType.HEX:CharacterReferenceType.DEC;throw this._createError(_unparsableEntityErrorMsg(entityType,this._cursor.getChars(start)),this._cursor.getSpan());}const strNum=this._cursor.getChars(codeStart);this._cursor.advance();try{const charCode=parseInt(strNum,isHex?16:10);this._endToken([String.fromCharCode(charCode),this._cursor.getChars(start)]);}catch(_a){throw this._createError(_unknownEntityErrorMsg(this._cursor.getChars(start)),this._cursor.getSpan());}}else {const nameStart=this._cursor.clone();this._attemptCharCodeUntilFn(isNamedEntityEnd);if(this._cursor.peek()!=$SEMICOLON){// No semicolon was found so abort the encoded entity token that was in progress, and treat
|
|
1995
2015
|
// this as a text token
|
|
1996
|
-
this._beginToken(textTokenType,start);this._cursor=nameStart;this._endToken(['&']);}else {const name=this._cursor.getChars(nameStart);this._cursor.advance();const char=NAMED_ENTITIES[name];if(!char){throw this._createError(_unknownEntityErrorMsg(name),this._cursor.getSpan(start));}this._endToken([char,`&${name};`]);}}}_consumeRawText(consumeEntities,endMarkerPredicate){this._beginToken(consumeEntities?6/* ESCAPABLE_RAW_TEXT */:7/* RAW_TEXT */);const parts=[];while(true){const tagCloseStart=this._cursor.clone();const foundEndMarker=endMarkerPredicate();this._cursor=tagCloseStart;if(foundEndMarker){break;}if(consumeEntities&&this._cursor.peek()===$AMPERSAND){this._endToken([this._processCarriageReturns(parts.join(''))]);parts.length=0;this._consumeEntity(6/* ESCAPABLE_RAW_TEXT */);this._beginToken(6/* ESCAPABLE_RAW_TEXT */);}else {parts.push(this._readChar());}}this._endToken([this._processCarriageReturns(parts.join(''))]);}_consumeComment(start){this._beginToken(10/* COMMENT_START */,start);this._requireCharCode($MINUS);this._endToken([]);this._consumeRawText(false,()=>this._attemptStr('-->'));this._beginToken(11/* COMMENT_END */);this._requireStr('-->');this._endToken([]);}_consumeCdata(start){this._beginToken(12/* CDATA_START */,start);this._requireStr('CDATA[');this._endToken([]);this._consumeRawText(false,()=>this._attemptStr(']]>'));this._beginToken(13/* CDATA_END */);this._requireStr(']]>');this._endToken([]);}_consumeDocType(start){this._beginToken(18/* DOC_TYPE */,start);const contentStart=this._cursor.clone();this._attemptUntilChar($GT);const content=this._cursor.getChars(contentStart);this._cursor.advance();this._endToken([content]);}_consumePrefixAndName(){const nameOrPrefixStart=this._cursor.clone();let prefix='';while(this._cursor.peek()!==$COLON&&!isPrefixEnd(this._cursor.peek())){this._cursor.advance();}let nameStart;if(this._cursor.peek()===$COLON){prefix=this._cursor.getChars(nameOrPrefixStart);this._cursor.advance();nameStart=this._cursor.clone();}else {nameStart=nameOrPrefixStart;}this._requireCharCodeUntilFn(isNameEnd,prefix===''?0:1);const name=this._cursor.getChars(nameStart);return [prefix,name];}_consumeTagOpen(start){let tagName;let prefix;let openTagToken;try{if(!isAsciiLetter(this._cursor.peek())){throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()),this._cursor.getSpan(start));}openTagToken=this._consumeTagOpenStart(start);prefix=openTagToken.parts[0];tagName=openTagToken.parts[1];this._attemptCharCodeUntilFn(isNotWhitespace);while(this._cursor.peek()!==$SLASH&&this._cursor.peek()!==$GT&&this._cursor.peek()!==$LT&&this._cursor.peek()!==$EOF){this._consumeAttributeName();this._attemptCharCodeUntilFn(isNotWhitespace);if(this._attemptCharCode($EQ)){this._attemptCharCodeUntilFn(isNotWhitespace);this._consumeAttributeValue();}this._attemptCharCodeUntilFn(isNotWhitespace);}this._consumeTagOpenEnd();}catch(e){if(e instanceof _ControlFlowError){if(openTagToken){// We errored before we could close the opening tag, so it is incomplete.
|
|
1997
|
-
openTagToken.type=4/* INCOMPLETE_TAG_OPEN */;}else {// When the start tag is invalid, assume we want a "<" as text.
|
|
2016
|
+
this._beginToken(textTokenType,start);this._cursor=nameStart;this._endToken(['&']);}else {const name=this._cursor.getChars(nameStart);this._cursor.advance();const char=NAMED_ENTITIES[name];if(!char){throw this._createError(_unknownEntityErrorMsg(name),this._cursor.getSpan(start));}this._endToken([char,`&${name};`]);}}}_consumeRawText(consumeEntities,endMarkerPredicate){this._beginToken(consumeEntities?6/* TokenType.ESCAPABLE_RAW_TEXT */:7/* TokenType.RAW_TEXT */);const parts=[];while(true){const tagCloseStart=this._cursor.clone();const foundEndMarker=endMarkerPredicate();this._cursor=tagCloseStart;if(foundEndMarker){break;}if(consumeEntities&&this._cursor.peek()===$AMPERSAND){this._endToken([this._processCarriageReturns(parts.join(''))]);parts.length=0;this._consumeEntity(6/* TokenType.ESCAPABLE_RAW_TEXT */);this._beginToken(6/* TokenType.ESCAPABLE_RAW_TEXT */);}else {parts.push(this._readChar());}}this._endToken([this._processCarriageReturns(parts.join(''))]);}_consumeComment(start){this._beginToken(10/* TokenType.COMMENT_START */,start);this._requireCharCode($MINUS);this._endToken([]);this._consumeRawText(false,()=>this._attemptStr('-->'));this._beginToken(11/* TokenType.COMMENT_END */);this._requireStr('-->');this._endToken([]);}_consumeCdata(start){this._beginToken(12/* TokenType.CDATA_START */,start);this._requireStr('CDATA[');this._endToken([]);this._consumeRawText(false,()=>this._attemptStr(']]>'));this._beginToken(13/* TokenType.CDATA_END */);this._requireStr(']]>');this._endToken([]);}_consumeDocType(start){this._beginToken(18/* TokenType.DOC_TYPE */,start);const contentStart=this._cursor.clone();this._attemptUntilChar($GT);const content=this._cursor.getChars(contentStart);this._cursor.advance();this._endToken([content]);}_consumePrefixAndName(){const nameOrPrefixStart=this._cursor.clone();let prefix='';while(this._cursor.peek()!==$COLON&&!isPrefixEnd(this._cursor.peek())){this._cursor.advance();}let nameStart;if(this._cursor.peek()===$COLON){prefix=this._cursor.getChars(nameOrPrefixStart);this._cursor.advance();nameStart=this._cursor.clone();}else {nameStart=nameOrPrefixStart;}this._requireCharCodeUntilFn(isNameEnd,prefix===''?0:1);const name=this._cursor.getChars(nameStart);return [prefix,name];}_consumeTagOpen(start){let tagName;let prefix;let openTagToken;try{if(!isAsciiLetter(this._cursor.peek())){throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()),this._cursor.getSpan(start));}openTagToken=this._consumeTagOpenStart(start);prefix=openTagToken.parts[0];tagName=openTagToken.parts[1];this._attemptCharCodeUntilFn(isNotWhitespace);while(this._cursor.peek()!==$SLASH&&this._cursor.peek()!==$GT&&this._cursor.peek()!==$LT&&this._cursor.peek()!==$EOF){this._consumeAttributeName();this._attemptCharCodeUntilFn(isNotWhitespace);if(this._attemptCharCode($EQ)){this._attemptCharCodeUntilFn(isNotWhitespace);this._consumeAttributeValue();}this._attemptCharCodeUntilFn(isNotWhitespace);}this._consumeTagOpenEnd();}catch(e){if(e instanceof _ControlFlowError){if(openTagToken){// We errored before we could close the opening tag, so it is incomplete.
|
|
2017
|
+
openTagToken.type=4/* TokenType.INCOMPLETE_TAG_OPEN */;}else {// When the start tag is invalid, assume we want a "<" as text.
|
|
1998
2018
|
// Back to back text tokens are merged at the end.
|
|
1999
|
-
this._beginToken(5/* TEXT */,start);this._endToken(['<']);}return;}throw e;}const contentTokenType=this._getTagDefinition(tagName).getContentType(prefix);if(contentTokenType===exports.TagContentType.RAW_TEXT){this._consumeRawTextWithTagClose(prefix,tagName,false);}else if(contentTokenType===exports.TagContentType.ESCAPABLE_RAW_TEXT){this._consumeRawTextWithTagClose(prefix,tagName,true);}}_consumeRawTextWithTagClose(prefix,tagName,consumeEntities){this._consumeRawText(consumeEntities,()=>{if(!this._attemptCharCode($LT))return false;if(!this._attemptCharCode($SLASH))return false;this._attemptCharCodeUntilFn(isNotWhitespace);if(!this._attemptStrCaseInsensitive(tagName))return false;this._attemptCharCodeUntilFn(isNotWhitespace);return this._attemptCharCode($GT);});this._beginToken(3/* TAG_CLOSE */);this._requireCharCodeUntilFn(code=>code===$GT,3);this._cursor.advance();// Consume the `>`
|
|
2000
|
-
this._endToken([prefix,tagName]);}_consumeTagOpenStart(start){this._beginToken(0/* TAG_OPEN_START */,start);const parts=this._consumePrefixAndName();return this._endToken(parts);}_consumeAttributeName(){const attrNameStart=this._cursor.peek();if(attrNameStart===$SQ||attrNameStart===$DQ){throw this._createError(_unexpectedCharacterErrorMsg(attrNameStart),this._cursor.getSpan());}this._beginToken(14/* ATTR_NAME */);const prefixAndName=this._consumePrefixAndName();this._endToken(prefixAndName);}_consumeAttributeValue(){if(this._cursor.peek()===$SQ||this._cursor.peek()===$DQ){const quoteChar=this._cursor.peek();this._consumeQuote(quoteChar);// In an attribute then end of the attribute value and the premature end to an interpolation
|
|
2019
|
+
this._beginToken(5/* TokenType.TEXT */,start);this._endToken(['<']);}return;}throw e;}const contentTokenType=this._getTagDefinition(tagName).getContentType(prefix);if(contentTokenType===exports.TagContentType.RAW_TEXT){this._consumeRawTextWithTagClose(prefix,tagName,false);}else if(contentTokenType===exports.TagContentType.ESCAPABLE_RAW_TEXT){this._consumeRawTextWithTagClose(prefix,tagName,true);}}_consumeRawTextWithTagClose(prefix,tagName,consumeEntities){this._consumeRawText(consumeEntities,()=>{if(!this._attemptCharCode($LT))return false;if(!this._attemptCharCode($SLASH))return false;this._attemptCharCodeUntilFn(isNotWhitespace);if(!this._attemptStrCaseInsensitive(tagName))return false;this._attemptCharCodeUntilFn(isNotWhitespace);return this._attemptCharCode($GT);});this._beginToken(3/* TokenType.TAG_CLOSE */);this._requireCharCodeUntilFn(code=>code===$GT,3);this._cursor.advance();// Consume the `>`
|
|
2020
|
+
this._endToken([prefix,tagName]);}_consumeTagOpenStart(start){this._beginToken(0/* TokenType.TAG_OPEN_START */,start);const parts=this._consumePrefixAndName();return this._endToken(parts);}_consumeAttributeName(){const attrNameStart=this._cursor.peek();if(attrNameStart===$SQ||attrNameStart===$DQ){throw this._createError(_unexpectedCharacterErrorMsg(attrNameStart),this._cursor.getSpan());}this._beginToken(14/* TokenType.ATTR_NAME */);const prefixAndName=this._consumePrefixAndName();this._endToken(prefixAndName);}_consumeAttributeValue(){if(this._cursor.peek()===$SQ||this._cursor.peek()===$DQ){const quoteChar=this._cursor.peek();this._consumeQuote(quoteChar);// In an attribute then end of the attribute value and the premature end to an interpolation
|
|
2001
2021
|
// are both triggered by the `quoteChar`.
|
|
2002
|
-
const endPredicate=()=>this._cursor.peek()===quoteChar;this._consumeWithInterpolation(16/* ATTR_VALUE_TEXT */,17/* ATTR_VALUE_INTERPOLATION */,endPredicate,endPredicate);this._consumeQuote(quoteChar);}else {const endPredicate=()=>isNameEnd(this._cursor.peek());this._consumeWithInterpolation(16/* ATTR_VALUE_TEXT */,17/* ATTR_VALUE_INTERPOLATION */,endPredicate,endPredicate);}}_consumeQuote(quoteChar){this._beginToken(15/* ATTR_QUOTE */);this._requireCharCode(quoteChar);this._endToken([String.fromCodePoint(quoteChar)]);}_consumeTagOpenEnd(){const tokenType=this._attemptCharCode($SLASH)?2/* TAG_OPEN_END_VOID */:1/* TAG_OPEN_END */;this._beginToken(tokenType);this._requireCharCode($GT);this._endToken([]);}_consumeTagClose(start){this._beginToken(3/* TAG_CLOSE */,start);this._attemptCharCodeUntilFn(isNotWhitespace);const prefixAndName=this._consumePrefixAndName();this._attemptCharCodeUntilFn(isNotWhitespace);this._requireCharCode($GT);this._endToken(prefixAndName);}_consumeExpansionFormStart(){this._beginToken(19/* EXPANSION_FORM_START */);this._requireCharCode($LBRACE);this._endToken([]);this._expansionCaseStack.push(19/* EXPANSION_FORM_START */);this._beginToken(7/* RAW_TEXT */);const condition=this._readUntil($COMMA);const normalizedCondition=this._processCarriageReturns(condition);if(this._i18nNormalizeLineEndingsInICUs){// We explicitly want to normalize line endings for this text.
|
|
2022
|
+
const endPredicate=()=>this._cursor.peek()===quoteChar;this._consumeWithInterpolation(16/* TokenType.ATTR_VALUE_TEXT */,17/* TokenType.ATTR_VALUE_INTERPOLATION */,endPredicate,endPredicate);this._consumeQuote(quoteChar);}else {const endPredicate=()=>isNameEnd(this._cursor.peek());this._consumeWithInterpolation(16/* TokenType.ATTR_VALUE_TEXT */,17/* TokenType.ATTR_VALUE_INTERPOLATION */,endPredicate,endPredicate);}}_consumeQuote(quoteChar){this._beginToken(15/* TokenType.ATTR_QUOTE */);this._requireCharCode(quoteChar);this._endToken([String.fromCodePoint(quoteChar)]);}_consumeTagOpenEnd(){const tokenType=this._attemptCharCode($SLASH)?2/* TokenType.TAG_OPEN_END_VOID */:1/* TokenType.TAG_OPEN_END */;this._beginToken(tokenType);this._requireCharCode($GT);this._endToken([]);}_consumeTagClose(start){this._beginToken(3/* TokenType.TAG_CLOSE */,start);this._attemptCharCodeUntilFn(isNotWhitespace);const prefixAndName=this._consumePrefixAndName();this._attemptCharCodeUntilFn(isNotWhitespace);this._requireCharCode($GT);this._endToken(prefixAndName);}_consumeExpansionFormStart(){this._beginToken(19/* TokenType.EXPANSION_FORM_START */);this._requireCharCode($LBRACE);this._endToken([]);this._expansionCaseStack.push(19/* TokenType.EXPANSION_FORM_START */);this._beginToken(7/* TokenType.RAW_TEXT */);const condition=this._readUntil($COMMA);const normalizedCondition=this._processCarriageReturns(condition);if(this._i18nNormalizeLineEndingsInICUs){// We explicitly want to normalize line endings for this text.
|
|
2003
2023
|
this._endToken([normalizedCondition]);}else {// We are not normalizing line endings.
|
|
2004
|
-
const conditionToken=this._endToken([condition]);if(normalizedCondition!==condition){this.nonNormalizedIcuExpressions.push(conditionToken);}}this._requireCharCode($COMMA);this._attemptCharCodeUntilFn(isNotWhitespace);this._beginToken(7/* RAW_TEXT */);const type=this._readUntil($COMMA);this._endToken([type]);this._requireCharCode($COMMA);this._attemptCharCodeUntilFn(isNotWhitespace);}_consumeExpansionCaseStart(){this._beginToken(20/* EXPANSION_CASE_VALUE */);const value=this._readUntil($LBRACE).trim();this._endToken([value]);this._attemptCharCodeUntilFn(isNotWhitespace);this._beginToken(21/* EXPANSION_CASE_EXP_START */);this._requireCharCode($LBRACE);this._endToken([]);this._attemptCharCodeUntilFn(isNotWhitespace);this._expansionCaseStack.push(21/* EXPANSION_CASE_EXP_START */);}_consumeExpansionCaseEnd(){this._beginToken(22/* EXPANSION_CASE_EXP_END */);this._requireCharCode($RBRACE);this._endToken([]);this._attemptCharCodeUntilFn(isNotWhitespace);this._expansionCaseStack.pop();}_consumeExpansionFormEnd(){this._beginToken(23/* EXPANSION_FORM_END */);this._requireCharCode($RBRACE);this._endToken([]);this._expansionCaseStack.pop();}/**
|
|
2024
|
+
const conditionToken=this._endToken([condition]);if(normalizedCondition!==condition){this.nonNormalizedIcuExpressions.push(conditionToken);}}this._requireCharCode($COMMA);this._attemptCharCodeUntilFn(isNotWhitespace);this._beginToken(7/* TokenType.RAW_TEXT */);const type=this._readUntil($COMMA);this._endToken([type]);this._requireCharCode($COMMA);this._attemptCharCodeUntilFn(isNotWhitespace);}_consumeExpansionCaseStart(){this._beginToken(20/* TokenType.EXPANSION_CASE_VALUE */);const value=this._readUntil($LBRACE).trim();this._endToken([value]);this._attemptCharCodeUntilFn(isNotWhitespace);this._beginToken(21/* TokenType.EXPANSION_CASE_EXP_START */);this._requireCharCode($LBRACE);this._endToken([]);this._attemptCharCodeUntilFn(isNotWhitespace);this._expansionCaseStack.push(21/* TokenType.EXPANSION_CASE_EXP_START */);}_consumeExpansionCaseEnd(){this._beginToken(22/* TokenType.EXPANSION_CASE_EXP_END */);this._requireCharCode($RBRACE);this._endToken([]);this._attemptCharCodeUntilFn(isNotWhitespace);this._expansionCaseStack.pop();}_consumeExpansionFormEnd(){this._beginToken(23/* TokenType.EXPANSION_FORM_END */);this._requireCharCode($RBRACE);this._endToken([]);this._expansionCaseStack.pop();}/**
|
|
2005
2025
|
* Consume a string that may contain interpolation expressions.
|
|
2006
2026
|
*
|
|
2007
2027
|
* The first token consumed will be of `tokenType` and then there will be alternating
|
|
@@ -2040,7 +2060,7 @@ return true;}}return false;}/**
|
|
|
2040
2060
|
* (opening/closing/comments/cdata/etc).
|
|
2041
2061
|
*/_isTagStart(){if(this._cursor.peek()===$LT){// We assume that `<` followed by whitespace is not the start of an HTML element.
|
|
2042
2062
|
const tmp=this._cursor.clone();tmp.advance();// If the next character is alphabetic, ! nor / then it is a tag start
|
|
2043
|
-
const code=tmp.peek();if($a<=code&&code<=$z||$A<=code&&code<=$Z||code===$SLASH||code===$BANG){return true;}}return false;}_readUntil(char){const start=this._cursor.clone();this._attemptUntilChar(char);return this._cursor.getChars(start);}_isInExpansionCase(){return this._expansionCaseStack.length>0&&this._expansionCaseStack[this._expansionCaseStack.length-1]===21/* EXPANSION_CASE_EXP_START */;}_isInExpansionForm(){return this._expansionCaseStack.length>0&&this._expansionCaseStack[this._expansionCaseStack.length-1]===19/* EXPANSION_FORM_START */;}isExpansionFormStart(){if(this._cursor.peek()!==$LBRACE){return false;}if(this._interpolationConfig){const start=this._cursor.clone();const isInterpolation=this._attemptStr(this._interpolationConfig.start);this._cursor=start;return !isInterpolation;}return true;}}function isNotWhitespace(code){return !isWhitespace(code)||code===$EOF;}function isNameEnd(code){return isWhitespace(code)||code===$GT||code===$LT||code===$SLASH||code===$SQ||code===$DQ||code===$EQ||code===$EOF;}function isPrefixEnd(code){return (code<$a||$z<code)&&(code<$A||$Z<code)&&(code<$0||code>$9);}function isDigitEntityEnd(code){return code===$SEMICOLON||code===$EOF||!isAsciiHexDigit(code);}function isNamedEntityEnd(code){return code===$SEMICOLON||code===$EOF||!isAsciiLetter(code);}function isExpansionCaseStart(peek){return peek!==$RBRACE;}function compareCharCodeCaseInsensitive(code1,code2){return toUpperCaseCharCode(code1)===toUpperCaseCharCode(code2);}function toUpperCaseCharCode(code){return code>=$a&&code<=$z?code-$a+$A:code;}function mergeTextTokens(srcTokens){const dstTokens=[];let lastDstToken=undefined;for(let i=0;i<srcTokens.length;i++){const token=srcTokens[i];if(lastDstToken&&lastDstToken.type===5/* TEXT */&&token.type===5/* TEXT */||lastDstToken&&lastDstToken.type===16/* ATTR_VALUE_TEXT */&&token.type===16/* ATTR_VALUE_TEXT */){lastDstToken.parts[0]+=token.parts[0];lastDstToken.sourceSpan.end=token.sourceSpan.end;}else {lastDstToken=token;dstTokens.push(lastDstToken);}}return dstTokens;}class PlainCharacterCursor{constructor(fileOrCursor,range){if(fileOrCursor instanceof PlainCharacterCursor){this.file=fileOrCursor.file;this.input=fileOrCursor.input;this.end=fileOrCursor.end;const state=fileOrCursor.state;// Note: avoid using `{...fileOrCursor.state}` here as that has a severe performance penalty.
|
|
2063
|
+
const code=tmp.peek();if($a<=code&&code<=$z||$A<=code&&code<=$Z||code===$SLASH||code===$BANG){return true;}}return false;}_readUntil(char){const start=this._cursor.clone();this._attemptUntilChar(char);return this._cursor.getChars(start);}_isInExpansionCase(){return this._expansionCaseStack.length>0&&this._expansionCaseStack[this._expansionCaseStack.length-1]===21/* TokenType.EXPANSION_CASE_EXP_START */;}_isInExpansionForm(){return this._expansionCaseStack.length>0&&this._expansionCaseStack[this._expansionCaseStack.length-1]===19/* TokenType.EXPANSION_FORM_START */;}isExpansionFormStart(){if(this._cursor.peek()!==$LBRACE){return false;}if(this._interpolationConfig){const start=this._cursor.clone();const isInterpolation=this._attemptStr(this._interpolationConfig.start);this._cursor=start;return !isInterpolation;}return true;}}function isNotWhitespace(code){return !isWhitespace(code)||code===$EOF;}function isNameEnd(code){return isWhitespace(code)||code===$GT||code===$LT||code===$SLASH||code===$SQ||code===$DQ||code===$EQ||code===$EOF;}function isPrefixEnd(code){return (code<$a||$z<code)&&(code<$A||$Z<code)&&(code<$0||code>$9);}function isDigitEntityEnd(code){return code===$SEMICOLON||code===$EOF||!isAsciiHexDigit(code);}function isNamedEntityEnd(code){return code===$SEMICOLON||code===$EOF||!isAsciiLetter(code);}function isExpansionCaseStart(peek){return peek!==$RBRACE;}function compareCharCodeCaseInsensitive(code1,code2){return toUpperCaseCharCode(code1)===toUpperCaseCharCode(code2);}function toUpperCaseCharCode(code){return code>=$a&&code<=$z?code-$a+$A:code;}function mergeTextTokens(srcTokens){const dstTokens=[];let lastDstToken=undefined;for(let i=0;i<srcTokens.length;i++){const token=srcTokens[i];if(lastDstToken&&lastDstToken.type===5/* TokenType.TEXT */&&token.type===5/* TokenType.TEXT */||lastDstToken&&lastDstToken.type===16/* TokenType.ATTR_VALUE_TEXT */&&token.type===16/* TokenType.ATTR_VALUE_TEXT */){lastDstToken.parts[0]+=token.parts[0];lastDstToken.sourceSpan.end=token.sourceSpan.end;}else {lastDstToken=token;dstTokens.push(lastDstToken);}}return dstTokens;}class PlainCharacterCursor{constructor(fileOrCursor,range){if(fileOrCursor instanceof PlainCharacterCursor){this.file=fileOrCursor.file;this.input=fileOrCursor.input;this.end=fileOrCursor.end;const state=fileOrCursor.state;// Note: avoid using `{...fileOrCursor.state}` here as that has a severe performance penalty.
|
|
2044
2064
|
// In ES5 bundles the object spread operator is translated into the `__assign` helper, which
|
|
2045
2065
|
// is not optimized by VMs as efficiently as a raw object literal. Since this constructor is
|
|
2046
2066
|
// called in tight loops, this difference matters.
|
|
@@ -2067,30 +2087,30 @@ this.internalState=previous.internalState;}else if(isNewLine(this.internalState.
|
|
|
2067
2087
|
this.advanceState(this.internalState);// advance over the newline
|
|
2068
2088
|
this.state=this.internalState;}else {// If none of the `if` blocks were executed then we just have an escaped normal character.
|
|
2069
2089
|
// In that case we just, effectively, skip the backslash from the character.
|
|
2070
|
-
this.state.peek=this.internalState.peek;}}}decodeHexDigits(start,length){const hex=this.input.
|
|
2090
|
+
this.state.peek=this.internalState.peek;}}}decodeHexDigits(start,length){const hex=this.input.slice(start.internalState.offset,start.internalState.offset+length);const charCode=parseInt(hex,16);if(!isNaN(charCode)){return charCode;}else {start.state=start.internalState;throw new CursorError('Invalid hexadecimal escape sequence',start);}}}class CursorError{constructor(msg,cursor){this.msg=msg;this.cursor=cursor;}}/**
|
|
2071
2091
|
* @license
|
|
2072
2092
|
* Copyright Google LLC All Rights Reserved.
|
|
2073
2093
|
*
|
|
2074
2094
|
* Use of this source code is governed by an MIT-style license that can be
|
|
2075
2095
|
* found in the LICENSE file at https://angular.io/license
|
|
2076
|
-
*/class TreeError extends ParseError{constructor(elementName,span,msg){super(span,msg);this.elementName=elementName;}static create(elementName,span,msg){return new TreeError(elementName,span,msg);}}class ParseTreeResult{constructor(rootNodes,errors){this.rootNodes=rootNodes;this.errors=errors;}}class Parser{constructor(getTagDefinition){this.getTagDefinition=getTagDefinition;}parse(source,url,options){const tokenizeResult=tokenize(source,url,this.getTagDefinition,options);const parser=new _TreeBuilder(tokenizeResult.tokens,this.getTagDefinition);parser.build();return new ParseTreeResult(parser.rootNodes,tokenizeResult.errors.concat(parser.errors));}}class _TreeBuilder{constructor(tokens,getTagDefinition){this.tokens=tokens;this.getTagDefinition=getTagDefinition;this._index=-1;this._elementStack=[];this.rootNodes=[];this.errors=[];this._advance();}build(){while(this._peek.type!==24/* EOF */){if(this._peek.type===0/* TAG_OPEN_START */||this._peek.type===4/* INCOMPLETE_TAG_OPEN */){this._consumeStartTag(this._advance());}else if(this._peek.type===3/* TAG_CLOSE */){this._consumeEndTag(this._advance());}else if(this._peek.type===12/* CDATA_START */){this._closeVoidElement();this._consumeCdata(this._advance());}else if(this._peek.type===10/* COMMENT_START */){this._closeVoidElement();this._consumeComment(this._advance());}else if(this._peek.type===5/* TEXT */||this._peek.type===7/* RAW_TEXT */||this._peek.type===6/* ESCAPABLE_RAW_TEXT */){this._closeVoidElement();this._consumeText(this._advance());}else if(this._peek.type===19/* EXPANSION_FORM_START */){this._consumeExpansion(this._advance());}else {// Skip all other tokens...
|
|
2096
|
+
*/class TreeError extends ParseError{constructor(elementName,span,msg){super(span,msg);this.elementName=elementName;}static create(elementName,span,msg){return new TreeError(elementName,span,msg);}}class ParseTreeResult{constructor(rootNodes,errors){this.rootNodes=rootNodes;this.errors=errors;}}class Parser{constructor(getTagDefinition){this.getTagDefinition=getTagDefinition;}parse(source,url,options){const tokenizeResult=tokenize(source,url,this.getTagDefinition,options);const parser=new _TreeBuilder(tokenizeResult.tokens,this.getTagDefinition);parser.build();return new ParseTreeResult(parser.rootNodes,tokenizeResult.errors.concat(parser.errors));}}class _TreeBuilder{constructor(tokens,getTagDefinition){this.tokens=tokens;this.getTagDefinition=getTagDefinition;this._index=-1;this._elementStack=[];this.rootNodes=[];this.errors=[];this._advance();}build(){while(this._peek.type!==24/* TokenType.EOF */){if(this._peek.type===0/* TokenType.TAG_OPEN_START */||this._peek.type===4/* TokenType.INCOMPLETE_TAG_OPEN */){this._consumeStartTag(this._advance());}else if(this._peek.type===3/* TokenType.TAG_CLOSE */){this._consumeEndTag(this._advance());}else if(this._peek.type===12/* TokenType.CDATA_START */){this._closeVoidElement();this._consumeCdata(this._advance());}else if(this._peek.type===10/* TokenType.COMMENT_START */){this._closeVoidElement();this._consumeComment(this._advance());}else if(this._peek.type===5/* TokenType.TEXT */||this._peek.type===7/* TokenType.RAW_TEXT */||this._peek.type===6/* TokenType.ESCAPABLE_RAW_TEXT */){this._closeVoidElement();this._consumeText(this._advance());}else if(this._peek.type===19/* TokenType.EXPANSION_FORM_START */){this._consumeExpansion(this._advance());}else {// Skip all other tokens...
|
|
2077
2097
|
this._advance();}}}_advance(){const prev=this._peek;if(this._index<this.tokens.length-1){// Note: there is always an EOF token at the end
|
|
2078
|
-
this._index++;}this._peek=this.tokens[this._index];return prev;}_advanceIf(type){if(this._peek.type===type){return this._advance();}return null;}_consumeCdata(_startToken){this._consumeText(this._advance());this._advanceIf(13/* CDATA_END */);}_consumeComment(token){const text=this._advanceIf(7/* RAW_TEXT */);this._advanceIf(11/* COMMENT_END */);const value=text!=null?text.parts[0].trim():null;this._addToParent(new Comment(value,token.sourceSpan));}_consumeExpansion(token){const switchValue=this._advance();const type=this._advance();const cases=[];// read =
|
|
2079
|
-
while(this._peek.type===20/* EXPANSION_CASE_VALUE */){const expCase=this._parseExpansionCase();if(!expCase)return;// error
|
|
2098
|
+
this._index++;}this._peek=this.tokens[this._index];return prev;}_advanceIf(type){if(this._peek.type===type){return this._advance();}return null;}_consumeCdata(_startToken){this._consumeText(this._advance());this._advanceIf(13/* TokenType.CDATA_END */);}_consumeComment(token){const text=this._advanceIf(7/* TokenType.RAW_TEXT */);this._advanceIf(11/* TokenType.COMMENT_END */);const value=text!=null?text.parts[0].trim():null;this._addToParent(new Comment(value,token.sourceSpan));}_consumeExpansion(token){const switchValue=this._advance();const type=this._advance();const cases=[];// read =
|
|
2099
|
+
while(this._peek.type===20/* TokenType.EXPANSION_CASE_VALUE */){const expCase=this._parseExpansionCase();if(!expCase)return;// error
|
|
2080
2100
|
cases.push(expCase);}// read the final }
|
|
2081
|
-
if(this._peek.type!==23/* EXPANSION_FORM_END */){this.errors.push(TreeError.create(null,this._peek.sourceSpan,`Invalid ICU message. Missing '}'.`));return;}const sourceSpan=new ParseSourceSpan(token.sourceSpan.start,this._peek.sourceSpan.end,token.sourceSpan.fullStart);this._addToParent(new Expansion(switchValue.parts[0],type.parts[0],cases,sourceSpan,switchValue.sourceSpan));this._advance();}_parseExpansionCase(){const value=this._advance();// read {
|
|
2082
|
-
if(this._peek.type!==21/* EXPANSION_CASE_EXP_START */){this.errors.push(TreeError.create(null,this._peek.sourceSpan,`Invalid ICU message. Missing '{'.`));return null;}// read until }
|
|
2083
|
-
const start=this._advance();const exp=this._collectExpansionExpTokens(start);if(!exp)return null;const end=this._advance();exp.push({type:24/* EOF */,parts:[],sourceSpan:end.sourceSpan});// parse everything in between { and }
|
|
2084
|
-
const expansionCaseParser=new _TreeBuilder(exp,this.getTagDefinition);expansionCaseParser.build();if(expansionCaseParser.errors.length>0){this.errors=this.errors.concat(expansionCaseParser.errors);return null;}const sourceSpan=new ParseSourceSpan(value.sourceSpan.start,end.sourceSpan.end,value.sourceSpan.fullStart);const expSourceSpan=new ParseSourceSpan(start.sourceSpan.start,end.sourceSpan.end,start.sourceSpan.fullStart);return new ExpansionCase(value.parts[0],expansionCaseParser.rootNodes,sourceSpan,value.sourceSpan,expSourceSpan);}_collectExpansionExpTokens(start){const exp=[];const expansionFormStack=[21/* EXPANSION_CASE_EXP_START */];while(true){if(this._peek.type===19/* EXPANSION_FORM_START */||this._peek.type===21/* EXPANSION_CASE_EXP_START */){expansionFormStack.push(this._peek.type);}if(this._peek.type===22/* EXPANSION_CASE_EXP_END */){if(lastOnStack(expansionFormStack,21/* EXPANSION_CASE_EXP_START */)){expansionFormStack.pop();if(expansionFormStack.length===0)return exp;}else {this.errors.push(TreeError.create(null,start.sourceSpan,`Invalid ICU message. Missing '}'.`));return null;}}if(this._peek.type===23/* EXPANSION_FORM_END */){if(lastOnStack(expansionFormStack,19/* EXPANSION_FORM_START */)){expansionFormStack.pop();}else {this.errors.push(TreeError.create(null,start.sourceSpan,`Invalid ICU message. Missing '}'.`));return null;}}if(this._peek.type===24/* EOF */){this.errors.push(TreeError.create(null,start.sourceSpan,`Invalid ICU message. Missing '}'.`));return null;}exp.push(this._advance());}}_consumeText(token){const tokens=[token];const startSpan=token.sourceSpan;let text=token.parts[0];if(text.length>0&&text[0]==='\n'){const parent=this._getParentElement();if(parent!=null&&parent.children.length===0&&this.getTagDefinition(parent.name).ignoreFirstLf){text=text.substring(1);tokens[0]={type:token.type,sourceSpan:token.sourceSpan,parts:[text]};}}while(this._peek.type===8/* INTERPOLATION */||this._peek.type===5/* TEXT */||this._peek.type===9/* ENCODED_ENTITY */){token=this._advance();tokens.push(token);if(token.type===8/* INTERPOLATION */){// For backward compatibility we decode HTML entities that appear in interpolation
|
|
2101
|
+
if(this._peek.type!==23/* TokenType.EXPANSION_FORM_END */){this.errors.push(TreeError.create(null,this._peek.sourceSpan,`Invalid ICU message. Missing '}'.`));return;}const sourceSpan=new ParseSourceSpan(token.sourceSpan.start,this._peek.sourceSpan.end,token.sourceSpan.fullStart);this._addToParent(new Expansion(switchValue.parts[0],type.parts[0],cases,sourceSpan,switchValue.sourceSpan));this._advance();}_parseExpansionCase(){const value=this._advance();// read {
|
|
2102
|
+
if(this._peek.type!==21/* TokenType.EXPANSION_CASE_EXP_START */){this.errors.push(TreeError.create(null,this._peek.sourceSpan,`Invalid ICU message. Missing '{'.`));return null;}// read until }
|
|
2103
|
+
const start=this._advance();const exp=this._collectExpansionExpTokens(start);if(!exp)return null;const end=this._advance();exp.push({type:24/* TokenType.EOF */,parts:[],sourceSpan:end.sourceSpan});// parse everything in between { and }
|
|
2104
|
+
const expansionCaseParser=new _TreeBuilder(exp,this.getTagDefinition);expansionCaseParser.build();if(expansionCaseParser.errors.length>0){this.errors=this.errors.concat(expansionCaseParser.errors);return null;}const sourceSpan=new ParseSourceSpan(value.sourceSpan.start,end.sourceSpan.end,value.sourceSpan.fullStart);const expSourceSpan=new ParseSourceSpan(start.sourceSpan.start,end.sourceSpan.end,start.sourceSpan.fullStart);return new ExpansionCase(value.parts[0],expansionCaseParser.rootNodes,sourceSpan,value.sourceSpan,expSourceSpan);}_collectExpansionExpTokens(start){const exp=[];const expansionFormStack=[21/* TokenType.EXPANSION_CASE_EXP_START */];while(true){if(this._peek.type===19/* TokenType.EXPANSION_FORM_START */||this._peek.type===21/* TokenType.EXPANSION_CASE_EXP_START */){expansionFormStack.push(this._peek.type);}if(this._peek.type===22/* TokenType.EXPANSION_CASE_EXP_END */){if(lastOnStack(expansionFormStack,21/* TokenType.EXPANSION_CASE_EXP_START */)){expansionFormStack.pop();if(expansionFormStack.length===0)return exp;}else {this.errors.push(TreeError.create(null,start.sourceSpan,`Invalid ICU message. Missing '}'.`));return null;}}if(this._peek.type===23/* TokenType.EXPANSION_FORM_END */){if(lastOnStack(expansionFormStack,19/* TokenType.EXPANSION_FORM_START */)){expansionFormStack.pop();}else {this.errors.push(TreeError.create(null,start.sourceSpan,`Invalid ICU message. Missing '}'.`));return null;}}if(this._peek.type===24/* TokenType.EOF */){this.errors.push(TreeError.create(null,start.sourceSpan,`Invalid ICU message. Missing '}'.`));return null;}exp.push(this._advance());}}_consumeText(token){const tokens=[token];const startSpan=token.sourceSpan;let text=token.parts[0];if(text.length>0&&text[0]==='\n'){const parent=this._getParentElement();if(parent!=null&&parent.children.length===0&&this.getTagDefinition(parent.name).ignoreFirstLf){text=text.substring(1);tokens[0]={type:token.type,sourceSpan:token.sourceSpan,parts:[text]};}}while(this._peek.type===8/* TokenType.INTERPOLATION */||this._peek.type===5/* TokenType.TEXT */||this._peek.type===9/* TokenType.ENCODED_ENTITY */){token=this._advance();tokens.push(token);if(token.type===8/* TokenType.INTERPOLATION */){// For backward compatibility we decode HTML entities that appear in interpolation
|
|
2085
2105
|
// expressions. This is arguably a bug, but it could be a considerable breaking change to
|
|
2086
2106
|
// fix it. It should be addressed in a larger project to refactor the entire parser/lexer
|
|
2087
2107
|
// chain after View Engine has been removed.
|
|
2088
|
-
text+=token.parts.join('').replace(/&([^;]+);/g,decodeEntity);}else if(token.type===9/* ENCODED_ENTITY */){text+=token.parts[0];}else {text+=token.parts.join('');}}if(text.length>0){const endSpan=token.sourceSpan;this._addToParent(new Text(text,new ParseSourceSpan(startSpan.start,endSpan.end,startSpan.fullStart,startSpan.details),tokens));}}_closeVoidElement(){const el=this._getParentElement();if(el&&this.getTagDefinition(el.name).isVoid){this._elementStack.pop();}}_consumeStartTag(startTagToken){const[prefix,name]=startTagToken.parts;const attrs=[];while(this._peek.type===14/* ATTR_NAME */){attrs.push(this._consumeAttr(this._advance()));}const fullName=this._getElementFullName(prefix,name,this._getParentElement());let selfClosing=false;// Note: There could have been a tokenizer error
|
|
2108
|
+
text+=token.parts.join('').replace(/&([^;]+);/g,decodeEntity);}else if(token.type===9/* TokenType.ENCODED_ENTITY */){text+=token.parts[0];}else {text+=token.parts.join('');}}if(text.length>0){const endSpan=token.sourceSpan;this._addToParent(new Text(text,new ParseSourceSpan(startSpan.start,endSpan.end,startSpan.fullStart,startSpan.details),tokens));}}_closeVoidElement(){const el=this._getParentElement();if(el&&this.getTagDefinition(el.name).isVoid){this._elementStack.pop();}}_consumeStartTag(startTagToken){const[prefix,name]=startTagToken.parts;const attrs=[];while(this._peek.type===14/* TokenType.ATTR_NAME */){attrs.push(this._consumeAttr(this._advance()));}const fullName=this._getElementFullName(prefix,name,this._getParentElement());let selfClosing=false;// Note: There could have been a tokenizer error
|
|
2089
2109
|
// so that we don't get a token for the end tag...
|
|
2090
|
-
if(this._peek.type===2/* TAG_OPEN_END_VOID */){this._advance();selfClosing=true;const tagDef=this.getTagDefinition(fullName);if(!(tagDef.canSelfClose||getNsPrefix(fullName)!==null||tagDef.isVoid)){this.errors.push(TreeError.create(fullName,startTagToken.sourceSpan,`Only void and foreign elements can be self closed "${startTagToken.parts[1]}"`));}}else if(this._peek.type===1/* TAG_OPEN_END */){this._advance();selfClosing=false;}const end=this._peek.sourceSpan.fullStart;const span=new ParseSourceSpan(startTagToken.sourceSpan.start,end,startTagToken.sourceSpan.fullStart);// Create a separate `startSpan` because `span` will be modified when there is an `end` span.
|
|
2110
|
+
if(this._peek.type===2/* TokenType.TAG_OPEN_END_VOID */){this._advance();selfClosing=true;const tagDef=this.getTagDefinition(fullName);if(!(tagDef.canSelfClose||getNsPrefix(fullName)!==null||tagDef.isVoid)){this.errors.push(TreeError.create(fullName,startTagToken.sourceSpan,`Only void and foreign elements can be self closed "${startTagToken.parts[1]}"`));}}else if(this._peek.type===1/* TokenType.TAG_OPEN_END */){this._advance();selfClosing=false;}const end=this._peek.sourceSpan.fullStart;const span=new ParseSourceSpan(startTagToken.sourceSpan.start,end,startTagToken.sourceSpan.fullStart);// Create a separate `startSpan` because `span` will be modified when there is an `end` span.
|
|
2091
2111
|
const startSpan=new ParseSourceSpan(startTagToken.sourceSpan.start,end,startTagToken.sourceSpan.fullStart);const el=new Element(fullName,attrs,[],span,startSpan,undefined);this._pushElement(el);if(selfClosing){// Elements that are self-closed have their `endSourceSpan` set to the full span, as the
|
|
2092
2112
|
// element start tag also represents the end tag.
|
|
2093
|
-
this._popElement(fullName,span);}else if(startTagToken.type===4/* INCOMPLETE_TAG_OPEN */){// We already know the opening tag is not complete, so it is unlikely it has a corresponding
|
|
2113
|
+
this._popElement(fullName,span);}else if(startTagToken.type===4/* TokenType.INCOMPLETE_TAG_OPEN */){// We already know the opening tag is not complete, so it is unlikely it has a corresponding
|
|
2094
2114
|
// close tag. Let's optimistically parse it as a full element and emit an error.
|
|
2095
2115
|
this._popElement(fullName,null);this.errors.push(TreeError.create(fullName,span,`Opening tag "${fullName}" not terminated.`));}}_pushElement(el){const parentEl=this._getParentElement();if(parentEl&&this.getTagDefinition(parentEl.name).isClosedByChild(el.name)){this._elementStack.pop();}this._addToParent(el);this._elementStack.push(el);}_consumeEndTag(endTagToken){const fullName=this._getElementFullName(endTagToken.parts[0],endTagToken.parts[1],this._getParentElement());if(this.getTagDefinition(fullName).isVoid){this.errors.push(TreeError.create(fullName,endTagToken.sourceSpan,`Void elements do not have end tags "${endTagToken.parts[1]}"`));}else if(!this._popElement(fullName,endTagToken.sourceSpan)){const 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`;this.errors.push(TreeError.create(fullName,endTagToken.sourceSpan,errMsg));}}/**
|
|
2096
2116
|
* Closes the nearest element with the tag name `fullName` in the parse tree.
|
|
@@ -2104,17 +2124,17 @@ el.endSourceSpan=endSourceSpan;el.sourceSpan.end=endSourceSpan!==null?endSourceS
|
|
|
2104
2124
|
// stack so we can assign an `endSourceSpan` if there is a corresponding start tag for this
|
|
2105
2125
|
// end tag in the stack.
|
|
2106
2126
|
unexpectedCloseTagDetected=true;}}return false;}_consumeAttr(attrName){const fullName=mergeNsAndName(attrName.parts[0],attrName.parts[1]);let attrEnd=attrName.sourceSpan.end;// Consume any quote
|
|
2107
|
-
if(this._peek.type===15/* ATTR_QUOTE */){this._advance();}// Consume the attribute value
|
|
2127
|
+
if(this._peek.type===15/* TokenType.ATTR_QUOTE */){this._advance();}// Consume the attribute value
|
|
2108
2128
|
let value='';const valueTokens=[];let valueStartSpan=undefined;let valueEnd=undefined;// NOTE: We need to use a new variable `nextTokenType` here to hide the actual type of
|
|
2109
2129
|
// `_peek.type` from TS. Otherwise TS will narrow the type of `_peek.type` preventing it from
|
|
2110
2130
|
// being able to consider `ATTR_VALUE_INTERPOLATION` as an option. This is because TS is not
|
|
2111
2131
|
// able to see that `_advance()` will actually mutate `_peek`.
|
|
2112
|
-
const nextTokenType=this._peek.type;if(nextTokenType===16/* ATTR_VALUE_TEXT */){valueStartSpan=this._peek.sourceSpan;valueEnd=this._peek.sourceSpan.end;while(this._peek.type===16/* ATTR_VALUE_TEXT */||this._peek.type===17/* ATTR_VALUE_INTERPOLATION */||this._peek.type===9/* ENCODED_ENTITY */){const valueToken=this._advance();valueTokens.push(valueToken);if(valueToken.type===17/* ATTR_VALUE_INTERPOLATION */){// For backward compatibility we decode HTML entities that appear in interpolation
|
|
2132
|
+
const nextTokenType=this._peek.type;if(nextTokenType===16/* TokenType.ATTR_VALUE_TEXT */){valueStartSpan=this._peek.sourceSpan;valueEnd=this._peek.sourceSpan.end;while(this._peek.type===16/* TokenType.ATTR_VALUE_TEXT */||this._peek.type===17/* TokenType.ATTR_VALUE_INTERPOLATION */||this._peek.type===9/* TokenType.ENCODED_ENTITY */){const valueToken=this._advance();valueTokens.push(valueToken);if(valueToken.type===17/* TokenType.ATTR_VALUE_INTERPOLATION */){// For backward compatibility we decode HTML entities that appear in interpolation
|
|
2113
2133
|
// expressions. This is arguably a bug, but it could be a considerable breaking change to
|
|
2114
2134
|
// fix it. It should be addressed in a larger project to refactor the entire parser/lexer
|
|
2115
2135
|
// chain after View Engine has been removed.
|
|
2116
|
-
value+=valueToken.parts.join('').replace(/&([^;]+);/g,decodeEntity);}else if(valueToken.type===9/* ENCODED_ENTITY */){value+=valueToken.parts[0];}else {value+=valueToken.parts.join('');}valueEnd=attrEnd=valueToken.sourceSpan.end;}}// Consume any quote
|
|
2117
|
-
if(this._peek.type===15/* ATTR_QUOTE */){const quoteToken=this._advance();attrEnd=quoteToken.sourceSpan.end;}const valueSpan=valueStartSpan&&valueEnd&&new ParseSourceSpan(valueStartSpan.start,valueEnd,valueStartSpan.fullStart);return new Attribute(fullName,value,new ParseSourceSpan(attrName.sourceSpan.start,attrEnd,attrName.sourceSpan.fullStart),attrName.sourceSpan,valueSpan,valueTokens.length>0?valueTokens:undefined,undefined);}_getParentElement(){return this._elementStack.length>0?this._elementStack[this._elementStack.length-1]:null;}_addToParent(node){const parent=this._getParentElement();if(parent!=null){parent.children.push(node);}else {this.rootNodes.push(node);}}_getElementFullName(prefix,localName,parentElement){if(prefix===''){prefix=this.getTagDefinition(localName).implicitNamespacePrefix||'';if(prefix===''&&parentElement!=null){const parentTagName=splitNsName(parentElement.name)[1];const parentTagDefinition=this.getTagDefinition(parentTagName);if(!parentTagDefinition.preventNamespaceInheritance){prefix=getNsPrefix(parentElement.name);}}}return mergeNsAndName(prefix,localName);}}function lastOnStack(stack,element){return stack.length>0&&stack[stack.length-1]===element;}/**
|
|
2136
|
+
value+=valueToken.parts.join('').replace(/&([^;]+);/g,decodeEntity);}else if(valueToken.type===9/* TokenType.ENCODED_ENTITY */){value+=valueToken.parts[0];}else {value+=valueToken.parts.join('');}valueEnd=attrEnd=valueToken.sourceSpan.end;}}// Consume any quote
|
|
2137
|
+
if(this._peek.type===15/* TokenType.ATTR_QUOTE */){const quoteToken=this._advance();attrEnd=quoteToken.sourceSpan.end;}const valueSpan=valueStartSpan&&valueEnd&&new ParseSourceSpan(valueStartSpan.start,valueEnd,valueStartSpan.fullStart);return new Attribute(fullName,value,new ParseSourceSpan(attrName.sourceSpan.start,attrEnd,attrName.sourceSpan.fullStart),attrName.sourceSpan,valueSpan,valueTokens.length>0?valueTokens:undefined,undefined);}_getParentElement(){return this._elementStack.length>0?this._elementStack[this._elementStack.length-1]:null;}_addToParent(node){const parent=this._getParentElement();if(parent!=null){parent.children.push(node);}else {this.rootNodes.push(node);}}_getElementFullName(prefix,localName,parentElement){if(prefix===''){prefix=this.getTagDefinition(localName).implicitNamespacePrefix||'';if(prefix===''&&parentElement!=null){const parentTagName=splitNsName(parentElement.name)[1];const parentTagDefinition=this.getTagDefinition(parentTagName);if(!parentTagDefinition.preventNamespaceInheritance){prefix=getNsPrefix(parentElement.name);}}}return mergeNsAndName(prefix,localName);}}function lastOnStack(stack,element){return stack.length>0&&stack[stack.length-1]===element;}/**
|
|
2118
2138
|
* Decode the `entity` string, which we believe is the contents of an HTML entity.
|
|
2119
2139
|
*
|
|
2120
2140
|
* If the string is not actually a valid/known entity then just return the original `match` string.
|
|
@@ -2154,7 +2174,7 @@ return value.replace(new RegExp(NGSP_UNICODE,'g'),' ');}/**
|
|
|
2154
2174
|
*/class WhitespaceVisitor{visitElement(element,context){if(SKIP_WS_TRIM_TAGS.has(element.name)||hasPreserveWhitespacesAttr(element.attrs)){// don't descent into elements where we need to preserve whitespaces
|
|
2155
2175
|
// but still visit all attributes to eliminate one used as a market to preserve WS
|
|
2156
2176
|
return new Element(element.name,visitAll(this,element.attrs),element.children,element.sourceSpan,element.startSourceSpan,element.endSourceSpan,element.i18n);}return new Element(element.name,element.attrs,visitAllWithSiblings(this,element.children),element.sourceSpan,element.startSourceSpan,element.endSourceSpan,element.i18n);}visitAttribute(attribute,context){return attribute.name!==PRESERVE_WS_ATTR_NAME?attribute:null;}visitText(text,context){const isNotBlank=text.value.match(NO_WS_REGEXP);const hasExpansionSibling=context&&(context.prev instanceof Expansion||context.next instanceof Expansion);if(isNotBlank||hasExpansionSibling){// Process the whitespace in the tokens of this Text node
|
|
2157
|
-
const tokens=text.tokens.map(token=>token.type===5/* TEXT */?createWhitespaceProcessedTextToken(token):token);// Process the whitespace of the value of this Text node
|
|
2177
|
+
const tokens=text.tokens.map(token=>token.type===5/* TokenType.TEXT */?createWhitespaceProcessedTextToken(token):token);// Process the whitespace of the value of this Text node
|
|
2158
2178
|
const value=processWhitespace(text.value);return new Text(value,text.sourceSpan,tokens,text.i18n);}return null;}visitComment(comment,context){return comment;}visitExpansion(expansion,context){return expansion;}visitExpansionCase(expansionCase,context){return expansionCase;}}function createWhitespaceProcessedTextToken({type,parts,sourceSpan}){return {type,parts:[processWhitespace(parts[0])],sourceSpan};}function processWhitespace(text){return replaceNgsp(text).replace(WS_REPLACE_REGEXP,' ');}function visitAllWithSiblings(visitor,nodes){const result=[];nodes.forEach((ast,i)=>{const context={prev:nodes[i-1],next:nodes[i+1]};const astResult=ast.visit(visitor,context);if(astResult){result.push(astResult);}});return result;}function mapLiteral(obj,quoted=false){return literalMap(Object.keys(obj).map(key=>({key,quoted,value:obj[key]})));}/**
|
|
2159
2179
|
* @license
|
|
2160
2180
|
* Copyright Google LLC All Rights Reserved.
|
|
@@ -2328,11 +2348,11 @@ this.parseLiteralAttr(key,null/* value */,keySpan,absoluteValueOffset,undefined/
|
|
|
2328
2348
|
*/_parseTemplateBindings(tplKey,tplValue,sourceSpan,absoluteKeyOffset,absoluteValueOffset){const sourceInfo=sourceSpan.start.toString();try{const bindingsResult=this._exprParser.parseTemplateBindings(tplKey,tplValue,sourceInfo,absoluteKeyOffset,absoluteValueOffset);this._reportExpressionParserErrors(bindingsResult.errors,sourceSpan);bindingsResult.warnings.forEach(warning=>{this._reportError(warning,sourceSpan,exports.ParseErrorLevel.WARNING);});return bindingsResult.templateBindings;}catch(e){this._reportError(`${e}`,sourceSpan);return [];}}parseLiteralAttr(name,value,sourceSpan,absoluteOffset,valueSpan,targetMatchableAttrs,targetProps,keySpan){if(isAnimationLabel(name)){name=name.substring(1);if(keySpan!==undefined){keySpan=moveParseSourceSpan(keySpan,new AbsoluteSourceSpan(keySpan.start.offset+1,keySpan.end.offset));}if(value){this._reportError(`Assigning animation triggers via @prop="exp" attributes with an expression is invalid.`+` Use property bindings (e.g. [@prop]="exp") or use an attribute without a value (e.g. @prop) instead.`,sourceSpan,exports.ParseErrorLevel.ERROR);}this._parseAnimation(name,value,sourceSpan,absoluteOffset,keySpan,valueSpan,targetMatchableAttrs,targetProps);}else {targetProps.push(new ParsedProperty(name,this._exprParser.wrapLiteralPrimitive(value,'',absoluteOffset),exports.ParsedPropertyType.LITERAL_ATTR,sourceSpan,keySpan,valueSpan));}}parsePropertyBinding(name,expression,isHost,sourceSpan,absoluteOffset,valueSpan,targetMatchableAttrs,targetProps,keySpan){if(name.length===0){this._reportError(`Property name is missing in binding`,sourceSpan);}let isAnimationProp=false;if(name.startsWith(ANIMATE_PROP_PREFIX)){isAnimationProp=true;name=name.substring(ANIMATE_PROP_PREFIX.length);if(keySpan!==undefined){keySpan=moveParseSourceSpan(keySpan,new AbsoluteSourceSpan(keySpan.start.offset+ANIMATE_PROP_PREFIX.length,keySpan.end.offset));}}else if(isAnimationLabel(name)){isAnimationProp=true;name=name.substring(1);if(keySpan!==undefined){keySpan=moveParseSourceSpan(keySpan,new AbsoluteSourceSpan(keySpan.start.offset+1,keySpan.end.offset));}}if(isAnimationProp){this._parseAnimation(name,expression,sourceSpan,absoluteOffset,keySpan,valueSpan,targetMatchableAttrs,targetProps);}else {this._parsePropertyAst(name,this._parseBinding(expression,isHost,valueSpan||sourceSpan,absoluteOffset),sourceSpan,keySpan,valueSpan,targetMatchableAttrs,targetProps);}}parsePropertyInterpolation(name,value,sourceSpan,valueSpan,targetMatchableAttrs,targetProps,keySpan,interpolatedTokens){const expr=this.parseInterpolation(value,valueSpan||sourceSpan,interpolatedTokens);if(expr){this._parsePropertyAst(name,expr,sourceSpan,keySpan,valueSpan,targetMatchableAttrs,targetProps);return true;}return false;}_parsePropertyAst(name,ast,sourceSpan,keySpan,valueSpan,targetMatchableAttrs,targetProps){targetMatchableAttrs.push([name,ast.source]);targetProps.push(new ParsedProperty(name,ast,exports.ParsedPropertyType.DEFAULT,sourceSpan,keySpan,valueSpan));}_parseAnimation(name,expression,sourceSpan,absoluteOffset,keySpan,valueSpan,targetMatchableAttrs,targetProps){if(name.length===0){this._reportError('Animation trigger is missing',sourceSpan);}// This will occur when a @trigger is not paired with an expression.
|
|
2329
2349
|
// For animations it is valid to not have an expression since */void
|
|
2330
2350
|
// states will be applied by angular when the element is attached/detached
|
|
2331
|
-
const ast=this._parseBinding(expression||'undefined',false,valueSpan||sourceSpan,absoluteOffset);targetMatchableAttrs.push([name,ast.source]);targetProps.push(new ParsedProperty(name,ast,exports.ParsedPropertyType.ANIMATION,sourceSpan,keySpan,valueSpan));}_parseBinding(value,isHostBinding,sourceSpan,absoluteOffset){const sourceInfo=(sourceSpan&&sourceSpan.start||'(unknown)').toString();try{const ast=isHostBinding?this._exprParser.parseSimpleBinding(value,sourceInfo,absoluteOffset,this._interpolationConfig):this._exprParser.parseBinding(value,sourceInfo,absoluteOffset,this._interpolationConfig);if(ast)this._reportExpressionParserErrors(ast.errors,sourceSpan);return ast;}catch(e){this._reportError(`${e}`,sourceSpan);return this._exprParser.wrapLiteralPrimitive('ERROR',sourceInfo,absoluteOffset);}}createBoundElementProperty(elementSelector,boundProp,skipValidation=false,mapPropertyName=true){if(boundProp.isAnimation){return new BoundElementProperty(boundProp.name,4/* Animation */,SecurityContext.NONE,boundProp.expression,null,boundProp.sourceSpan,boundProp.keySpan,boundProp.valueSpan);}let unit=null;let bindingType=undefined;let boundPropertyName=null;const parts=boundProp.name.split(PROPERTY_PARTS_SEPARATOR);let securityContexts=undefined;// Check for special cases (prefix style, attr, class)
|
|
2332
|
-
if(parts.length>1){if(parts[0]==ATTRIBUTE_PREFIX){boundPropertyName=parts.slice(1).join(PROPERTY_PARTS_SEPARATOR);if(!skipValidation){this._validatePropertyOrAttributeName(boundPropertyName,boundProp.sourceSpan,true);}securityContexts=calcPossibleSecurityContexts(this._schemaRegistry,elementSelector,boundPropertyName,true);const nsSeparatorIdx=boundPropertyName.indexOf(':');if(nsSeparatorIdx>-1){const ns=boundPropertyName.substring(0,nsSeparatorIdx);const name=boundPropertyName.substring(nsSeparatorIdx+1);boundPropertyName=mergeNsAndName(ns,name);}bindingType=1/* Attribute */;}else if(parts[0]==CLASS_PREFIX){boundPropertyName=parts[1];bindingType=2/* Class */;securityContexts=[SecurityContext.NONE];}else if(parts[0]==STYLE_PREFIX){unit=parts.length>2?parts[2]:null;boundPropertyName=parts[1];bindingType=3/* Style */;securityContexts=[SecurityContext.STYLE];}}// If not a special case, use the full property name
|
|
2333
|
-
if(boundPropertyName===null){const mappedPropName=this._schemaRegistry.getMappedPropName(boundProp.name);boundPropertyName=mapPropertyName?mappedPropName:boundProp.name;securityContexts=calcPossibleSecurityContexts(this._schemaRegistry,elementSelector,mappedPropName,false);bindingType=0/* Property */;if(!skipValidation){this._validatePropertyOrAttributeName(mappedPropName,boundProp.sourceSpan,false);}}return new BoundElementProperty(boundPropertyName,bindingType,securityContexts[0],boundProp.expression,unit,boundProp.sourceSpan,boundProp.keySpan,boundProp.valueSpan);}// TODO: keySpan should be required but was made optional to avoid changing VE parser.
|
|
2334
|
-
parseEvent(name,expression,isAssignmentEvent,sourceSpan,handlerSpan,targetMatchableAttrs,targetEvents,keySpan){if(name.length===0){this._reportError(`Event name is missing in binding`,sourceSpan);}if(isAnimationLabel(name)){name=name.
|
|
2335
|
-
const[target,eventName]=splitAtColon(name,[null,name]);const ast=this._parseAction(expression,isAssignmentEvent,handlerSpan);targetMatchableAttrs.push([name,ast.source]);targetEvents.push(new ParsedEvent(eventName,target,0/* Regular */,ast,sourceSpan,handlerSpan,keySpan));// Don't detect directives for event names for now,
|
|
2351
|
+
const ast=this._parseBinding(expression||'undefined',false,valueSpan||sourceSpan,absoluteOffset);targetMatchableAttrs.push([name,ast.source]);targetProps.push(new ParsedProperty(name,ast,exports.ParsedPropertyType.ANIMATION,sourceSpan,keySpan,valueSpan));}_parseBinding(value,isHostBinding,sourceSpan,absoluteOffset){const sourceInfo=(sourceSpan&&sourceSpan.start||'(unknown)').toString();try{const ast=isHostBinding?this._exprParser.parseSimpleBinding(value,sourceInfo,absoluteOffset,this._interpolationConfig):this._exprParser.parseBinding(value,sourceInfo,absoluteOffset,this._interpolationConfig);if(ast)this._reportExpressionParserErrors(ast.errors,sourceSpan);return ast;}catch(e){this._reportError(`${e}`,sourceSpan);return this._exprParser.wrapLiteralPrimitive('ERROR',sourceInfo,absoluteOffset);}}createBoundElementProperty(elementSelector,boundProp,skipValidation=false,mapPropertyName=true){if(boundProp.isAnimation){return new BoundElementProperty(boundProp.name,4/* BindingType.Animation */,SecurityContext.NONE,boundProp.expression,null,boundProp.sourceSpan,boundProp.keySpan,boundProp.valueSpan);}let unit=null;let bindingType=undefined;let boundPropertyName=null;const parts=boundProp.name.split(PROPERTY_PARTS_SEPARATOR);let securityContexts=undefined;// Check for special cases (prefix style, attr, class)
|
|
2352
|
+
if(parts.length>1){if(parts[0]==ATTRIBUTE_PREFIX){boundPropertyName=parts.slice(1).join(PROPERTY_PARTS_SEPARATOR);if(!skipValidation){this._validatePropertyOrAttributeName(boundPropertyName,boundProp.sourceSpan,true);}securityContexts=calcPossibleSecurityContexts(this._schemaRegistry,elementSelector,boundPropertyName,true);const nsSeparatorIdx=boundPropertyName.indexOf(':');if(nsSeparatorIdx>-1){const ns=boundPropertyName.substring(0,nsSeparatorIdx);const name=boundPropertyName.substring(nsSeparatorIdx+1);boundPropertyName=mergeNsAndName(ns,name);}bindingType=1/* BindingType.Attribute */;}else if(parts[0]==CLASS_PREFIX){boundPropertyName=parts[1];bindingType=2/* BindingType.Class */;securityContexts=[SecurityContext.NONE];}else if(parts[0]==STYLE_PREFIX){unit=parts.length>2?parts[2]:null;boundPropertyName=parts[1];bindingType=3/* BindingType.Style */;securityContexts=[SecurityContext.STYLE];}}// If not a special case, use the full property name
|
|
2353
|
+
if(boundPropertyName===null){const mappedPropName=this._schemaRegistry.getMappedPropName(boundProp.name);boundPropertyName=mapPropertyName?mappedPropName:boundProp.name;securityContexts=calcPossibleSecurityContexts(this._schemaRegistry,elementSelector,mappedPropName,false);bindingType=0/* BindingType.Property */;if(!skipValidation){this._validatePropertyOrAttributeName(mappedPropName,boundProp.sourceSpan,false);}}return new BoundElementProperty(boundPropertyName,bindingType,securityContexts[0],boundProp.expression,unit,boundProp.sourceSpan,boundProp.keySpan,boundProp.valueSpan);}// TODO: keySpan should be required but was made optional to avoid changing VE parser.
|
|
2354
|
+
parseEvent(name,expression,isAssignmentEvent,sourceSpan,handlerSpan,targetMatchableAttrs,targetEvents,keySpan){if(name.length===0){this._reportError(`Event name is missing in binding`,sourceSpan);}if(isAnimationLabel(name)){name=name.slice(1);if(keySpan!==undefined){keySpan=moveParseSourceSpan(keySpan,new AbsoluteSourceSpan(keySpan.start.offset+1,keySpan.end.offset));}this._parseAnimationEvent(name,expression,isAssignmentEvent,sourceSpan,handlerSpan,targetEvents,keySpan);}else {this._parseRegularEvent(name,expression,isAssignmentEvent,sourceSpan,handlerSpan,targetMatchableAttrs,targetEvents,keySpan);}}calcPossibleSecurityContexts(selector,propName,isAttribute){const prop=this._schemaRegistry.getMappedPropName(propName);return calcPossibleSecurityContexts(this._schemaRegistry,selector,prop,isAttribute);}_parseAnimationEvent(name,expression,isAssignmentEvent,sourceSpan,handlerSpan,targetEvents,keySpan){const matches=splitAtPeriod(name,[name,'']);const eventName=matches[0];const phase=matches[1].toLowerCase();const ast=this._parseAction(expression,isAssignmentEvent,handlerSpan);targetEvents.push(new ParsedEvent(eventName,phase,1/* ParsedEventType.Animation */,ast,sourceSpan,handlerSpan,keySpan));if(eventName.length===0){this._reportError(`Animation event name is missing in binding`,sourceSpan);}if(phase){if(phase!=='start'&&phase!=='done'){this._reportError(`The provided animation output phase value "${phase}" for "@${eventName}" is not supported (use start or done)`,sourceSpan);}}else {this._reportError(`The animation trigger output event (@${eventName}) is missing its phase value name (start or done are currently supported)`,sourceSpan);}}_parseRegularEvent(name,expression,isAssignmentEvent,sourceSpan,handlerSpan,targetMatchableAttrs,targetEvents,keySpan){// long format: 'target: eventName'
|
|
2355
|
+
const[target,eventName]=splitAtColon(name,[null,name]);const ast=this._parseAction(expression,isAssignmentEvent,handlerSpan);targetMatchableAttrs.push([name,ast.source]);targetEvents.push(new ParsedEvent(eventName,target,0/* ParsedEventType.Regular */,ast,sourceSpan,handlerSpan,keySpan));// Don't detect directives for event names for now,
|
|
2336
2356
|
// so don't add the event name to the matchableAttrs
|
|
2337
2357
|
}_parseAction(value,isAssignmentEvent,sourceSpan){const sourceInfo=(sourceSpan&&sourceSpan.start||'(unknown').toString();const absoluteOffset=sourceSpan&&sourceSpan.start?sourceSpan.start.offset:0;try{const ast=this._exprParser.parseAction(value,isAssignmentEvent,sourceInfo,absoluteOffset,this._interpolationConfig);if(ast){this._reportExpressionParserErrors(ast.errors,sourceSpan);}if(!ast||ast.ast instanceof EmptyExpr){this._reportError(`Empty expressions are not allowed`,sourceSpan);return this._exprParser.wrapLiteralPrimitive('ERROR',sourceInfo,absoluteOffset);}return ast;}catch(e){this._reportError(`${e}`,sourceSpan);return this._exprParser.wrapLiteralPrimitive('ERROR',sourceInfo,absoluteOffset);}}_reportError(message,sourceSpan,level=exports.ParseErrorLevel.ERROR){this.errors.push(new ParseError(sourceSpan,message,level));}_reportExpressionParserErrors(errors,sourceSpan){for(const error of errors){this._reportError(error.message,sourceSpan);}}/**
|
|
2338
2358
|
* @param propName the name of the property / attribute
|
|
@@ -2520,7 +2540,7 @@ const phName=context.placeholderRegistry.getPlaceholderName('ICU',icu.sourceSpan
|
|
|
2520
2540
|
*/_visitTextWithInterpolation(tokens,sourceSpan,context,previousI18n){// Return a sequence of `Text` and `Placeholder` nodes grouped in a `Container`.
|
|
2521
2541
|
const nodes=[];// We will only create a container if there are actually interpolations,
|
|
2522
2542
|
// so this flag tracks that.
|
|
2523
|
-
let hasInterpolation=false;for(const token of tokens){switch(token.type){case 8/* INTERPOLATION */:case 17/* ATTR_VALUE_INTERPOLATION */:hasInterpolation=true;const expression=token.parts[1];const baseName=extractPlaceholderName(expression)||'INTERPOLATION';const phName=context.placeholderRegistry.getPlaceholderName(baseName,expression);context.placeholderToContent[phName]={text:token.parts.join(''),sourceSpan:token.sourceSpan};nodes.push(new Placeholder(expression,phName,token.sourceSpan));break;default:if(token.parts[0].length>0){// This token is text or an encoded entity.
|
|
2543
|
+
let hasInterpolation=false;for(const token of tokens){switch(token.type){case 8/* TokenType.INTERPOLATION */:case 17/* TokenType.ATTR_VALUE_INTERPOLATION */:hasInterpolation=true;const expression=token.parts[1];const baseName=extractPlaceholderName(expression)||'INTERPOLATION';const phName=context.placeholderRegistry.getPlaceholderName(baseName,expression);context.placeholderToContent[phName]={text:token.parts.join(''),sourceSpan:token.sourceSpan};nodes.push(new Placeholder(expression,phName,token.sourceSpan));break;default:if(token.parts[0].length>0){// This token is text or an encoded entity.
|
|
2524
2544
|
// If it is following on from a previous text node then merge it into that node
|
|
2525
2545
|
// Otherwise, if it is following an interpolation, then add a new node.
|
|
2526
2546
|
const previous=nodes[nodes.length-1];if(previous instanceof Text$2){previous.value+=token.parts[0];previous.sourceSpan=new ParseSourceSpan(previous.sourceSpan.start,token.sourceSpan.end,previous.sourceSpan.fullStart,previous.sourceSpan.details);}else {nodes.push(new Text$2(token.parts[0],token.sourceSpan));}}break;}}if(hasInterpolation){// Whitespace removal may have invalidated the interpolation source-spans.
|
|
@@ -2616,8 +2636,48 @@ const previousMessage=meta instanceof Message?meta:meta instanceof IcuPlaceholde
|
|
|
2616
2636
|
* @returns Object with id, meaning and description fields
|
|
2617
2637
|
*/function parseI18nMeta(meta=''){let customId;let meaning;let description;meta=meta.trim();if(meta){const idIndex=meta.indexOf(I18N_ID_SEPARATOR);const descIndex=meta.indexOf(I18N_MEANING_SEPARATOR);let meaningAndDesc;[meaningAndDesc,customId]=idIndex>-1?[meta.slice(0,idIndex),meta.slice(idIndex+2)]:[meta,''];[meaning,description]=descIndex>-1?[meaningAndDesc.slice(0,descIndex),meaningAndDesc.slice(descIndex+1)]:['',meaningAndDesc];}return {customId,meaning,description};}// Converts i18n meta information for a message (id, description, meaning)
|
|
2618
2638
|
// to a JsDoc statement formatted as expected by the Closure compiler.
|
|
2619
|
-
function i18nMetaToJSDoc(meta){const tags=[];if(meta.description){tags.push({tagName:"desc"/* Desc */,text:meta.description});}else {// Suppress the JSCompiler warning that a `@desc` was not given for this message.
|
|
2620
|
-
tags.push({tagName:"suppress"/* Suppress */,text:'{msgDescriptions}'});}if(meta.meaning){tags.push({tagName:"meaning"/* Meaning */,text:meta.meaning});}return jsDocComment(tags);}/** Closure uses `goog.getMsg(message)` to lookup translations */const GOOG_GET_MSG='goog.getMsg'
|
|
2639
|
+
function i18nMetaToJSDoc(meta){const tags=[];if(meta.description){tags.push({tagName:"desc"/* o.JSDocTagName.Desc */,text:meta.description});}else {// Suppress the JSCompiler warning that a `@desc` was not given for this message.
|
|
2640
|
+
tags.push({tagName:"suppress"/* o.JSDocTagName.Suppress */,text:'{msgDescriptions}'});}if(meta.meaning){tags.push({tagName:"meaning"/* o.JSDocTagName.Meaning */,text:meta.meaning});}return jsDocComment(tags);}/** Closure uses `goog.getMsg(message)` to lookup translations */const GOOG_GET_MSG='goog.getMsg';/**
|
|
2641
|
+
* Generates a `goog.getMsg()` statement and reassignment. The template:
|
|
2642
|
+
*
|
|
2643
|
+
* ```html
|
|
2644
|
+
* <div i18n>Sent from {{ sender }} to <span class="receiver">{{ receiver }}</span></div>
|
|
2645
|
+
* ```
|
|
2646
|
+
*
|
|
2647
|
+
* Generates:
|
|
2648
|
+
*
|
|
2649
|
+
* ```typescript
|
|
2650
|
+
* const MSG_FOO = goog.getMsg(
|
|
2651
|
+
* // Message template.
|
|
2652
|
+
* 'Sent from {$interpolation} to {$startTagSpan}{$interpolation_1}{$closeTagSpan}.',
|
|
2653
|
+
* // Placeholder values, set to magic strings which get replaced by the Angular runtime.
|
|
2654
|
+
* {
|
|
2655
|
+
* 'interpolation': '\uFFFD0\uFFFD',
|
|
2656
|
+
* 'startTagSpan': '\uFFFD1\uFFFD',
|
|
2657
|
+
* 'interpolation_1': '\uFFFD2\uFFFD',
|
|
2658
|
+
* 'closeTagSpan': '\uFFFD3\uFFFD',
|
|
2659
|
+
* },
|
|
2660
|
+
* // Options bag.
|
|
2661
|
+
* {
|
|
2662
|
+
* // Maps each placeholder to the original Angular source code which generates it's value.
|
|
2663
|
+
* original_code: {
|
|
2664
|
+
* 'interpolation': '{{ sender }}',
|
|
2665
|
+
* 'startTagSpan': '<span class="receiver">',
|
|
2666
|
+
* 'interploation_1': '{{ receiver }}',
|
|
2667
|
+
* 'closeTagSpan': '</span>',
|
|
2668
|
+
* },
|
|
2669
|
+
* },
|
|
2670
|
+
* );
|
|
2671
|
+
* const I18N_0 = MSG_FOO;
|
|
2672
|
+
* ```
|
|
2673
|
+
*/function createGoogleGetMsgStatements(variable$1,message,closureVar,placeholderValues){const messageString=serializeI18nMessageForGetMsg(message);const args=[literal(messageString)];if(Object.keys(placeholderValues).length){// Message template parameters containing the magic strings replaced by the Angular runtime with
|
|
2674
|
+
// real data, e.g. `{'interpolation': '\uFFFD0\uFFFD'}`.
|
|
2675
|
+
args.push(mapLiteral(formatI18nPlaceholderNamesInMap(placeholderValues,true/* useCamelCase */),true/* quoted */));// Message options object, which contains original source code for placeholders (as they are
|
|
2676
|
+
// present in a template, e.g.
|
|
2677
|
+
// `{original_code: {'interpolation': '{{ name }}', 'startTagSpan': '<span>'}}`.
|
|
2678
|
+
args.push(mapLiteral({original_code:literalMap(Object.keys(placeholderValues).map(param=>({key:formatI18nPlaceholderName(param),quoted:true,value:message.placeholders[param]?// Get source span for typical placeholder if it exists.
|
|
2679
|
+
literal(message.placeholders[param].sourceSpan.toString()):// Otherwise must be an ICU expression, get it's source span.
|
|
2680
|
+
literal(message.placeholderToMessage[param].nodes.map(node=>node.sourceSpan.toString()).join(''))})))}));}// /**
|
|
2621
2681
|
// * @desc description of message
|
|
2622
2682
|
// * @meaning meaning of message
|
|
2623
2683
|
// */
|
|
@@ -2661,9 +2721,12 @@ const NG_PROJECT_AS_ATTR_NAME='ngProjectAs';// Global symbols available only ins
|
|
|
2661
2721
|
const EVENT_BINDING_SCOPE_GLOBALS=new Set(['$event']);// List of supported global targets for event listeners
|
|
2662
2722
|
const GLOBAL_TARGET_RESOLVERS=new Map([['window',Identifiers.resolveWindow],['document',Identifiers.resolveDocument],['body',Identifiers.resolveBody]]);const LEADING_TRIVIA_CHARS=[' ','\n','\r','\t'];// if (rf & flags) { .. }
|
|
2663
2723
|
function renderFlagCheckIfStmt(flags,statements){return ifStmt(variable(RENDER_FLAGS).bitwiseAnd(literal(flags),null,false),statements);}function prepareEventListenerParameters(eventAst,handlerName=null,scope=null){const{type,name,target,phase,handler}=eventAst;if(target&&!GLOBAL_TARGET_RESOLVERS.has(target)){throw new Error(`Unexpected global target '${target}' defined for '${name}' event.
|
|
2664
|
-
Supported list of global targets: ${Array.from(GLOBAL_TARGET_RESOLVERS.keys())}.`);}const eventArgumentName='$event';const implicitReceiverAccesses=new Set();const implicitReceiverExpr=scope===null||scope.bindingLevel===0?variable(CONTEXT_NAME):scope.getOrCreateSharedContextVar(0);const bindingStatements=convertActionBinding(scope,implicitReceiverExpr,handler,'b',eventAst.handlerSpan,implicitReceiverAccesses,EVENT_BINDING_SCOPE_GLOBALS);const statements=[];
|
|
2724
|
+
Supported list of global targets: ${Array.from(GLOBAL_TARGET_RESOLVERS.keys())}.`);}const eventArgumentName='$event';const implicitReceiverAccesses=new Set();const implicitReceiverExpr=scope===null||scope.bindingLevel===0?variable(CONTEXT_NAME):scope.getOrCreateSharedContextVar(0);const bindingStatements=convertActionBinding(scope,implicitReceiverExpr,handler,'b',eventAst.handlerSpan,implicitReceiverAccesses,EVENT_BINDING_SCOPE_GLOBALS);const statements=[];const variableDeclarations=scope===null||scope===void 0?void 0:scope.variableDeclarations();const restoreViewStatement=scope===null||scope===void 0?void 0:scope.restoreViewStatement();if(variableDeclarations){// `variableDeclarations` needs to run first, because
|
|
2665
2725
|
// `restoreViewStatement` depends on the result.
|
|
2666
|
-
statements.push(...
|
|
2726
|
+
statements.push(...variableDeclarations);}statements.push(...bindingStatements);if(restoreViewStatement){statements.unshift(restoreViewStatement);// If there's a `restoreView` call, we need to reset the view at the end of the listener
|
|
2727
|
+
// in order to avoid a leak. If there's a `return` statement already, we wrap it in the
|
|
2728
|
+
// call, e.g. `return resetView(ctx.foo())`. Otherwise we add the call as the last statement.
|
|
2729
|
+
const lastStatement=statements[statements.length-1];if(lastStatement instanceof ReturnStatement){statements[statements.length-1]=new ReturnStatement(invokeInstruction(lastStatement.value.sourceSpan,Identifiers.resetView,[lastStatement.value]));}else {statements.push(new ExpressionStatement(invokeInstruction(null,Identifiers.resetView,[])));}}const eventName=type===1/* ParsedEventType.Animation */?prepareSyntheticListenerName(name,phase):name;const fnName=handlerName&&sanitizeIdentifier(handlerName);const fnArgs=[];if(implicitReceiverAccesses.has(eventArgumentName)){fnArgs.push(new FnParam(eventArgumentName,DYNAMIC_TYPE));}const handlerFn=fn(fnArgs,statements,INFERRED_TYPE,null,fnName);const params=[literal(eventName),handlerFn];if(target){params.push(literal(false),// `useCapture` flag, defaults to `false`
|
|
2667
2730
|
importExpr(GLOBAL_TARGET_RESOLVERS.get(target)));}return params;}function createComponentDefConsts(){return {prepareStatements:[],constExpressions:[],i18nVarRefsCache:new Map()};}class TemplateDefinitionBuilder{constructor(constantPool,parentBindingScope,level=0,contextName,i18nContext,templateIndex,templateName,_namespace,relativeContextFilePath,i18nUseExternalIds,_constants=createComponentDefConsts()){this.constantPool=constantPool;this.level=level;this.contextName=contextName;this.i18nContext=i18nContext;this.templateIndex=templateIndex;this.templateName=templateName;this._namespace=_namespace;this.i18nUseExternalIds=i18nUseExternalIds;this._constants=_constants;this._dataIndex=0;this._bindingContext=0;this._prefixCode=[];/**
|
|
2668
2731
|
* List of callbacks to generate creation mode instructions. We store them here as we process
|
|
2669
2732
|
* the template so bindings in listeners are resolved only once all nodes have been visited.
|
|
@@ -2720,7 +2783,7 @@ const creationStatements=getInstructionStatements(this._creationCodeFns);// Gene
|
|
|
2720
2783
|
const updateStatements=getInstructionStatements(this._updateCodeFns);// Variable declaration must occur after binding resolution so we can generate context
|
|
2721
2784
|
// instructions that build on each other.
|
|
2722
2785
|
// e.g. const b = nextContext().$implicit(); const b = nextContext();
|
|
2723
|
-
const creationVariables=this._bindingScope.viewSnapshotStatements();const updateVariables=this._bindingScope.variableDeclarations().concat(this._tempVariables);const creationBlock=creationStatements.length>0?[renderFlagCheckIfStmt(1/* Create */,creationVariables.concat(creationStatements))]:[];const updateBlock=updateStatements.length>0?[renderFlagCheckIfStmt(2/* Update */,updateVariables.concat(updateStatements))]:[];return fn(// i.e. (rf: RenderFlags, ctx: any)
|
|
2786
|
+
const creationVariables=this._bindingScope.viewSnapshotStatements();const updateVariables=this._bindingScope.variableDeclarations().concat(this._tempVariables);const creationBlock=creationStatements.length>0?[renderFlagCheckIfStmt(1/* core.RenderFlags.Create */,creationVariables.concat(creationStatements))]:[];const updateBlock=updateStatements.length>0?[renderFlagCheckIfStmt(2/* core.RenderFlags.Update */,updateVariables.concat(updateStatements))]:[];return fn(// i.e. (rf: RenderFlags, ctx: any)
|
|
2724
2787
|
[new FnParam(RENDER_FLAGS,NUMBER_TYPE),new FnParam(CONTEXT_NAME,null)],[// Temporary variable declarations for query refresh (i.e. let _t: any;)
|
|
2725
2788
|
...this._prefixCode,// Creating mode (i.e. if (rf & RenderFlags.Create) { ... })
|
|
2726
2789
|
...creationBlock,// Binding and refresh mode (i.e. if (rf & RenderFlags.Update) {...})
|
|
@@ -2729,7 +2792,7 @@ getLocal(name){return this._bindingScope.get(name);}// LocalResolver
|
|
|
2729
2792
|
notifyImplicitReceiverUse(){this._bindingScope.notifyImplicitReceiverUse();}// LocalResolver
|
|
2730
2793
|
maybeRestoreView(){this._bindingScope.maybeRestoreView();}i18nTranslate(message,params={},ref,transformFn){const _ref=ref||this.i18nGenerateMainBlockVar();// Closure Compiler requires const names to start with `MSG_` but disallows any other const to
|
|
2731
2794
|
// start with `MSG_`. We define a variable starting with `MSG_` just for the `goog.getMsg` call
|
|
2732
|
-
const closureVar=this.i18nGenerateClosureVar(message.id);const statements=getTranslationDeclStmts(message,_ref,closureVar,params,transformFn);this._constants.prepareStatements.push(...statements);return _ref;}registerContextVariables(variable$1){const scopedName=this._bindingScope.freshReferenceName();const retrievalLevel=this.level;const lhs=variable(variable$1.name+scopedName);this._bindingScope.set(retrievalLevel,variable$1.name,lhs,1/* CONTEXT */,(scope,relativeLevel)=>{let rhs;if(scope.bindingLevel===retrievalLevel){if(scope.isListenerScope()&&scope.hasRestoreViewVariable()){// e.g. restoredCtx.
|
|
2795
|
+
const closureVar=this.i18nGenerateClosureVar(message.id);const statements=getTranslationDeclStmts(message,_ref,closureVar,params,transformFn);this._constants.prepareStatements.push(...statements);return _ref;}registerContextVariables(variable$1){const scopedName=this._bindingScope.freshReferenceName();const retrievalLevel=this.level;const lhs=variable(variable$1.name+scopedName);this._bindingScope.set(retrievalLevel,variable$1.name,lhs,1/* DeclarationPriority.CONTEXT */,(scope,relativeLevel)=>{let rhs;if(scope.bindingLevel===retrievalLevel){if(scope.isListenerScope()&&scope.hasRestoreViewVariable()){// e.g. restoredCtx.
|
|
2733
2796
|
// We have to get the context from a view reference, if one is available, because
|
|
2734
2797
|
// the context that was passed in during creation may not be correct anymore.
|
|
2735
2798
|
// For more information see: https://github.com/angular/angular/pull/40360.
|
|
@@ -2759,7 +2822,7 @@ this.updateInstructionWithAdvance(this.getConstCount()-1,span,Identifiers.i18nEx
|
|
|
2759
2822
|
*/interpolatedUpdateInstruction(instruction,elementIndex,attrName,input,value,params){this.updateInstructionWithAdvance(elementIndex,input.sourceSpan,instruction,()=>[literal(attrName),...this.getUpdateInstructionArguments(value),...params]);}visitContent(ngContent){const slot=this.allocateDataSlot();const projectionSlotIdx=this._ngContentSelectorsOffset+this._ngContentReservedSlots.length;const parameters=[literal(slot)];this._ngContentReservedSlots.push(ngContent.selector);const nonContentSelectAttributes=ngContent.attributes.filter(attr=>attr.name.toLowerCase()!==NG_CONTENT_SELECT_ATTR);const attributes=this.getAttributeExpressions(ngContent.name,nonContentSelectAttributes,[],[]);if(attributes.length>0){parameters.push(literal(projectionSlotIdx),literalArr(attributes));}else if(projectionSlotIdx!==0){parameters.push(literal(projectionSlotIdx));}this.creationInstruction(ngContent.sourceSpan,Identifiers.projection,parameters);if(this.i18n){this.i18n.appendProjection(ngContent.i18n,slot);}}visitElement(element){var _a,_b;const elementIndex=this.allocateDataSlot();const stylingBuilder=new StylingBuilder(null);let isNonBindableMode=false;const isI18nRootElement=isI18nRootNode(element.i18n)&&!isSingleI18nIcu(element.i18n);const outputAttrs=[];const[namespaceKey,elementName]=splitNsName(element.name);const isNgContainer$1=isNgContainer(element.name);// Handle styling, i18n, ngNonBindable attributes
|
|
2760
2823
|
for(const attr of element.attributes){const{name,value}=attr;if(name===NON_BINDABLE_ATTR){isNonBindableMode=true;}else if(name==='style'){stylingBuilder.registerStyleAttr(value);}else if(name==='class'){stylingBuilder.registerClassAttr(value);}else {outputAttrs.push(attr);}}// Regular element or ng-container creation mode
|
|
2761
2824
|
const parameters=[literal(elementIndex)];if(!isNgContainer$1){parameters.push(literal(elementName));}// Add the attributes
|
|
2762
|
-
const allOtherInputs=[];const boundI18nAttrs=[];element.inputs.forEach(input=>{const stylingInputWasSet=stylingBuilder.registerBoundInput(input);if(!stylingInputWasSet){if(input.type===0/* Property */&&input.i18n){boundI18nAttrs.push(input);}else {allOtherInputs.push(input);}}});// add attributes for directive and projection matching purposes
|
|
2825
|
+
const allOtherInputs=[];const boundI18nAttrs=[];element.inputs.forEach(input=>{const stylingInputWasSet=stylingBuilder.registerBoundInput(input);if(!stylingInputWasSet){if(input.type===0/* BindingType.Property */&&input.i18n){boundI18nAttrs.push(input);}else {allOtherInputs.push(input);}}});// add attributes for directive and projection matching purposes
|
|
2763
2826
|
const attributes=this.getAttributeExpressions(element.name,outputAttrs,allOtherInputs,element.outputs,stylingBuilder,[],boundI18nAttrs);parameters.push(this.addAttrsToConsts(attributes));// local refs (ex.: <div #foo #bar="baz">)
|
|
2764
2827
|
const refs=this.prepareRefsArray(element.references);parameters.push(this.addToConsts(refs));const wasInNamespace=this._namespace;const currentNamespace=this.getNamespaceInstruction(namespaceKey);// If the namespace is changing now, include an instruction to change it
|
|
2765
2828
|
// during element creation.
|
|
@@ -2776,7 +2839,7 @@ const stylingInstructions=stylingBuilder.buildUpdateLevelInstructions(this._valu
|
|
|
2776
2839
|
// special value to symbolize that there is no RHS to this binding
|
|
2777
2840
|
// TODO (matsko): revisit this once FW-959 is approached
|
|
2778
2841
|
const emptyValueBindInstruction=literal(undefined);const propertyBindings=[];const attributeBindings=[];// Generate element input bindings
|
|
2779
|
-
allOtherInputs.forEach(input=>{const inputType=input.type;if(inputType===4/* Animation */){const value=input.value.visit(this._valueConverter);// animation bindings can be presented in the following formats:
|
|
2842
|
+
allOtherInputs.forEach(input=>{const inputType=input.type;if(inputType===4/* BindingType.Animation */){const value=input.value.visit(this._valueConverter);// animation bindings can be presented in the following formats:
|
|
2780
2843
|
// 1. [@binding]="fooExp"
|
|
2781
2844
|
// 2. [@binding]="{value:fooExp, params:{...}}"
|
|
2782
2845
|
// 3. [@binding]
|
|
@@ -2787,12 +2850,12 @@ allOtherInputs.forEach(input=>{const inputType=input.type;if(inputType===4/* Ani
|
|
|
2787
2850
|
// defined in...
|
|
2788
2851
|
const hasValue=value instanceof LiteralPrimitive?!!value.value:true;this.allocateBindingSlots(value);propertyBindings.push({span:input.sourceSpan,paramsOrFn:getBindingFunctionParams(()=>hasValue?this.convertPropertyBinding(value):emptyValueBindInstruction,prepareSyntheticPropertyName(input.name))});}else {// we must skip attributes with associated i18n context, since these attributes are handled
|
|
2789
2852
|
// separately and corresponding `i18nExp` and `i18nApply` instructions will be generated
|
|
2790
|
-
if(input.i18n)return;const value=input.value.visit(this._valueConverter);if(value!==undefined){const params=[];const[attrNamespace,attrName]=splitNsName(input.name);const isAttributeBinding=inputType===1/* Attribute */;const sanitizationRef=resolveSanitizationFn(input.securityContext,isAttributeBinding);if(sanitizationRef)params.push(sanitizationRef);if(attrNamespace){const namespaceLiteral=literal(attrNamespace);if(sanitizationRef){params.push(namespaceLiteral);}else {// If there wasn't a sanitization ref, we need to add
|
|
2853
|
+
if(input.i18n)return;const value=input.value.visit(this._valueConverter);if(value!==undefined){const params=[];const[attrNamespace,attrName]=splitNsName(input.name);const isAttributeBinding=inputType===1/* BindingType.Attribute */;const sanitizationRef=resolveSanitizationFn(input.securityContext,isAttributeBinding);if(sanitizationRef)params.push(sanitizationRef);if(attrNamespace){const namespaceLiteral=literal(attrNamespace);if(sanitizationRef){params.push(namespaceLiteral);}else {// If there wasn't a sanitization ref, we need to add
|
|
2791
2854
|
// an extra param so that we can pass in the namespace.
|
|
2792
|
-
params.push(literal(null),namespaceLiteral);}}this.allocateBindingSlots(value);if(inputType===0/* Property */){if(value instanceof Interpolation){// prop="{{value}}" and friends
|
|
2855
|
+
params.push(literal(null),namespaceLiteral);}}this.allocateBindingSlots(value);if(inputType===0/* BindingType.Property */){if(value instanceof Interpolation){// prop="{{value}}" and friends
|
|
2793
2856
|
this.interpolatedUpdateInstruction(getPropertyInterpolationExpression(value),elementIndex,attrName,input,value,params);}else {// [prop]="value"
|
|
2794
2857
|
// Collect all the properties so that we can chain into a single function at the end.
|
|
2795
|
-
propertyBindings.push({span:input.sourceSpan,paramsOrFn:getBindingFunctionParams(()=>this.convertPropertyBinding(value),attrName,params)});}}else if(inputType===1/* Attribute */){if(value instanceof Interpolation&&getInterpolationArgsLength(value)>1){// attr.name="text{{value}}" and friends
|
|
2858
|
+
propertyBindings.push({span:input.sourceSpan,paramsOrFn:getBindingFunctionParams(()=>this.convertPropertyBinding(value),attrName,params)});}}else if(inputType===1/* BindingType.Attribute */){if(value instanceof Interpolation&&getInterpolationArgsLength(value)>1){// attr.name="text{{value}}" and friends
|
|
2796
2859
|
this.interpolatedUpdateInstruction(getAttributeInterpolationExpression(value),elementIndex,attrName,input,value,params);}else {const boundValue=value instanceof Interpolation?value.expressions[0]:value;// [attr.name]="value" or attr.name="{{value}}"
|
|
2797
2860
|
// Collect the attribute bindings so that they can be chained at the end.
|
|
2798
2861
|
attributeBindings.push({span:input.sourceSpan,paramsOrFn:getBindingFunctionParams(()=>this.convertPropertyBinding(boundValue),attrName,params)});}}else {// class prop
|
|
@@ -2828,7 +2891,7 @@ const message=icu.i18n;// we always need post-processing function for ICUs, to m
|
|
|
2828
2891
|
// `goog.getMsg` does not process ICUs and uses the `{PLACEHOLDER}` format for placeholders
|
|
2829
2892
|
// inside ICUs)
|
|
2830
2893
|
// - all ICU vars (such as `VAR_SELECT` or `VAR_PLURAL`) are replaced with correct values
|
|
2831
|
-
const transformFn=raw=>{const params=Object.assign(Object.assign({},vars),placeholders);const formatted=
|
|
2894
|
+
const transformFn=raw=>{const params=Object.assign(Object.assign({},vars),placeholders);const formatted=formatI18nPlaceholderNamesInMap(params,/* useCamelCase */false);return invokeInstruction(null,Identifiers.i18nPostprocess,[raw,mapLiteral(formatted,true)]);};// in case the whole i18n message is a single ICU - we do not need to
|
|
2832
2895
|
// create a separate top-level translation, we can use the root ref instead
|
|
2833
2896
|
// and make this ICU a top-level translation
|
|
2834
2897
|
// note: ICU placeholders are replaced with actual values in `i18nPostprocess` function
|
|
@@ -2887,15 +2950,15 @@ if(ngProjectAsAttr){attrExprs.push(...getNgProjectAsLiteral(ngProjectAsAttr));}f
|
|
|
2887
2950
|
// as single property value cell by cell.
|
|
2888
2951
|
if(styles){styles.populateInitialStylingAttrs(attrExprs);}if(inputs.length||outputs.length){const attrsLengthBeforeInputs=attrExprs.length;for(let i=0;i<inputs.length;i++){const input=inputs[i];// We don't want the animation and attribute bindings in the
|
|
2889
2952
|
// attributes array since they aren't used for directive matching.
|
|
2890
|
-
if(input.type!==4/* Animation */&&input.type!==1/* Attribute */){addAttrExpr(input.name);}}for(let i=0;i<outputs.length;i++){const output=outputs[i];if(output.type!==1/* Animation */){addAttrExpr(output.name);}}// this is a cheap way of adding the marker only after all the input/output
|
|
2953
|
+
if(input.type!==4/* BindingType.Animation */&&input.type!==1/* BindingType.Attribute */){addAttrExpr(input.name);}}for(let i=0;i<outputs.length;i++){const output=outputs[i];if(output.type!==1/* ParsedEventType.Animation */){addAttrExpr(output.name);}}// this is a cheap way of adding the marker only after all the input/output
|
|
2891
2954
|
// values have been filtered (by not including the animation ones) and added
|
|
2892
2955
|
// to the expressions. The marker is important because it tells the runtime
|
|
2893
2956
|
// code that this is where attributes without values start...
|
|
2894
|
-
if(attrExprs.length!==attrsLengthBeforeInputs){attrExprs.splice(attrsLengthBeforeInputs,0,literal(3/* Bindings */));}}if(templateAttrs.length){attrExprs.push(literal(4/* Template */));templateAttrs.forEach(attr=>addAttrExpr(attr.name));}if(boundI18nAttrs.length){attrExprs.push(literal(6/* I18n */));boundI18nAttrs.forEach(attr=>addAttrExpr(attr.name));}return attrExprs;}addToConsts(expression){if(isNull(expression)){return TYPED_NULL_EXPR;}const consts=this._constants.constExpressions;// Try to reuse a literal that's already in the array, if possible.
|
|
2957
|
+
if(attrExprs.length!==attrsLengthBeforeInputs){attrExprs.splice(attrsLengthBeforeInputs,0,literal(3/* core.AttributeMarker.Bindings */));}}if(templateAttrs.length){attrExprs.push(literal(4/* core.AttributeMarker.Template */));templateAttrs.forEach(attr=>addAttrExpr(attr.name));}if(boundI18nAttrs.length){attrExprs.push(literal(6/* core.AttributeMarker.I18n */));boundI18nAttrs.forEach(attr=>addAttrExpr(attr.name));}return attrExprs;}addToConsts(expression){if(isNull(expression)){return TYPED_NULL_EXPR;}const consts=this._constants.constExpressions;// Try to reuse a literal that's already in the array, if possible.
|
|
2895
2958
|
for(let i=0;i<consts.length;i++){if(consts[i].isEquivalent(expression)){return literal(i);}}return literal(consts.push(expression)-1);}addAttrsToConsts(attrs){return attrs.length>0?this.addToConsts(literalArr(attrs)):TYPED_NULL_EXPR;}prepareRefsArray(references){if(!references||references.length===0){return TYPED_NULL_EXPR;}const refsParam=flatten(references.map(reference=>{const slot=this.allocateDataSlot();// Generate the update temporary.
|
|
2896
|
-
const variableName=this._bindingScope.freshReferenceName();const retrievalLevel=this.level;const lhs=variable(variableName);this._bindingScope.set(retrievalLevel,reference.name,lhs,0/* DEFAULT */,(scope,relativeLevel)=>{// e.g. nextContext(2);
|
|
2959
|
+
const variableName=this._bindingScope.freshReferenceName();const retrievalLevel=this.level;const lhs=variable(variableName);this._bindingScope.set(retrievalLevel,reference.name,lhs,0/* DeclarationPriority.DEFAULT */,(scope,relativeLevel)=>{// e.g. nextContext(2);
|
|
2897
2960
|
const nextContextStmt=relativeLevel>0?[generateNextContextExpr(relativeLevel).toStmt()]:[];// e.g. const $foo$ = reference(1);
|
|
2898
|
-
const refExpr=lhs.set(importExpr(Identifiers.reference).callFn([literal(slot)]));return nextContextStmt.concat(refExpr.toConstDecl());},true);return [reference.name,reference.value];}));return asLiteral(refsParam);}prepareListenerParameter(tagName,outputAst,index){return ()=>{const eventName=outputAst.name;const bindingFnName=outputAst.type===1/* Animation */?// synthetic @listener.foo values are treated the exact same as are standard listeners
|
|
2961
|
+
const refExpr=lhs.set(importExpr(Identifiers.reference).callFn([literal(slot)]));return nextContextStmt.concat(refExpr.toConstDecl());},true);return [reference.name,reference.value];}));return asLiteral(refsParam);}prepareListenerParameter(tagName,outputAst,index){return ()=>{const eventName=outputAst.name;const bindingFnName=outputAst.type===1/* ParsedEventType.Animation */?// synthetic @listener.foo values are treated the exact same as are standard listeners
|
|
2899
2962
|
prepareSyntheticListenerFunctionName(eventName,outputAst.phase):sanitizeIdentifier(eventName);const handlerName=`${this.templateName}_${tagName}_${bindingFnName}_${index}_listener`;const scope=this._bindingScope.nestedScope(this._bindingScope.bindingLevel,EVENT_BINDING_SCOPE_GLOBALS);return prepareEventListenerParameters(outputAst,handlerName,scope);};}}class ValueConverter extends AstMemoryEfficientTransformer{constructor(constantPool,allocateSlot,allocatePureFunctionSlots,definePipe){super();this.constantPool=constantPool;this.allocateSlot=allocateSlot;this.allocatePureFunctionSlots=allocatePureFunctionSlots;this.definePipe=definePipe;this._pipeBindExprs=[];}// AstMemoryEfficientTransformer
|
|
2900
2963
|
visitPipe(pipe,context){// Allocate a slot to create the pipe
|
|
2901
2964
|
const slot=this.allocateSlot();const slotPseudoLocal=`PIPE:${slot}`;// Allocate one slot for the result plus one slot per pipe argument
|
|
@@ -2917,7 +2980,7 @@ const args=[literal(startSlot),literalFactory];if(isVarLength){args.push(literal
|
|
|
2917
2980
|
* `:xlink:href` turns into `[AttributeMarker.NamespaceURI, 'xlink', 'href']`.
|
|
2918
2981
|
*
|
|
2919
2982
|
* @param name Name of the attribute, including the namespace.
|
|
2920
|
-
*/function getAttributeNameLiterals(name){const[attributeNamespace,attributeName]=splitNsName(name);const nameLiteral=literal(attributeName);if(attributeNamespace){return [literal(0/* NamespaceURI */),literal(attributeNamespace),nameLiteral];}return [nameLiteral];}/** The prefix used to get a shared context in BindingScope's map. */const SHARED_CONTEXT_KEY='$$shared_ctx$$';class BindingScope{constructor(bindingLevel=0,parent=null,globals){this.bindingLevel=bindingLevel;this.parent=parent;this.globals=globals;/** Keeps a map from local variables to their BindingData. */this.map=new Map();this.referenceNameIndex=0;this.restoreViewVariable=null;this.usesRestoredViewContext=false;if(globals!==undefined){for(const name of globals){this.set(0,name,variable(name));}}}static createRootScope(){return new BindingScope();}get(name){let current=this;while(current){let value=current.map.get(name);if(value!=null){if(current!==this){// make a local copy and reset the `declare` state
|
|
2983
|
+
*/function getAttributeNameLiterals(name){const[attributeNamespace,attributeName]=splitNsName(name);const nameLiteral=literal(attributeName);if(attributeNamespace){return [literal(0/* core.AttributeMarker.NamespaceURI */),literal(attributeNamespace),nameLiteral];}return [nameLiteral];}/** The prefix used to get a shared context in BindingScope's map. */const SHARED_CONTEXT_KEY='$$shared_ctx$$';class BindingScope{constructor(bindingLevel=0,parent=null,globals){this.bindingLevel=bindingLevel;this.parent=parent;this.globals=globals;/** Keeps a map from local variables to their BindingData. */this.map=new Map();this.referenceNameIndex=0;this.restoreViewVariable=null;this.usesRestoredViewContext=false;if(globals!==undefined){for(const name of globals){this.set(0,name,variable(name));}}}static createRootScope(){return new BindingScope();}get(name){let current=this;while(current){let value=current.map.get(name);if(value!=null){if(current!==this){// make a local copy and reset the `declare` state
|
|
2921
2984
|
value={retrievalLevel:value.retrievalLevel,lhs:value.lhs,declareLocalCallback:value.declareLocalCallback,declare:false,priority:value.priority};// Cache the value locally.
|
|
2922
2985
|
this.map.set(name,value);// Possibly generate a shared context var
|
|
2923
2986
|
this.maybeGenerateSharedContextVar(value);this.maybeRestoreView();}if(value.declareLocalCallback&&!value.declare){value.declare=true;}return value.lhs;}current=current.parent;}// If we get to this point, we are looking for a property on the top level component
|
|
@@ -2933,7 +2996,7 @@ return this.bindingLevel===0?null:this.getComponentProperty(name);}/**
|
|
|
2933
2996
|
* @param priority The sorting priority of this var
|
|
2934
2997
|
* @param declareLocalCallback The callback to invoke when declaring this local var
|
|
2935
2998
|
* @param localRef Whether or not this is a local ref
|
|
2936
|
-
*/set(retrievalLevel,name,lhs,priority=0/* DEFAULT */,declareLocalCallback,localRef){if(this.map.has(name)){if(localRef){// Do not throw an error if it's a local ref and do not update existing value,
|
|
2999
|
+
*/set(retrievalLevel,name,lhs,priority=0/* DeclarationPriority.DEFAULT */,declareLocalCallback,localRef){if(this.map.has(name)){if(localRef){// Do not throw an error if it's a local ref and do not update existing value,
|
|
2937
3000
|
// so the first defined ref is always returned.
|
|
2938
3001
|
return this;}error(`The name ${name} is already defined in scope to be ${this.map.get(name)}`);}this.map.set(name,{retrievalLevel:retrievalLevel,lhs:lhs,declare:false,declareLocalCallback:declareLocalCallback,priority:priority});return this;}// Implemented as part of LocalResolver.
|
|
2939
3002
|
getLocal(name){return this.get(name);}// Implemented as part of LocalResolver.
|
|
@@ -2946,15 +3009,15 @@ this.map.get(SHARED_CONTEXT_KEY+0).declare=true;}}nestedScope(level,globals){con
|
|
|
2946
3009
|
* binding scope will be only declared if they are used.
|
|
2947
3010
|
*/getOrCreateSharedContextVar(retrievalLevel){const bindingKey=SHARED_CONTEXT_KEY+retrievalLevel;if(!this.map.has(bindingKey)){this.generateSharedContextVar(retrievalLevel);}// Shared context variables are always generated as "ReadVarExpr".
|
|
2948
3011
|
return this.map.get(bindingKey).lhs;}getSharedContextName(retrievalLevel){const sharedCtxObj=this.map.get(SHARED_CONTEXT_KEY+retrievalLevel);// Shared context variables are always generated as "ReadVarExpr".
|
|
2949
|
-
return sharedCtxObj&&sharedCtxObj.declare?sharedCtxObj.lhs:null;}maybeGenerateSharedContextVar(value){if(value.priority===1/* CONTEXT */&&value.retrievalLevel<this.bindingLevel){const sharedCtxObj=this.map.get(SHARED_CONTEXT_KEY+value.retrievalLevel);if(sharedCtxObj){sharedCtxObj.declare=true;}else {this.generateSharedContextVar(value.retrievalLevel);}}}generateSharedContextVar(retrievalLevel){const lhs=variable(CONTEXT_NAME+this.freshReferenceName());this.map.set(SHARED_CONTEXT_KEY+retrievalLevel,{retrievalLevel:retrievalLevel,lhs:lhs,declareLocalCallback:(scope,relativeLevel)=>{// const ctx_r0 = nextContext(2);
|
|
2950
|
-
return [lhs.set(generateNextContextExpr(relativeLevel)).toConstDecl()];},declare:false,priority:2/* SHARED_CONTEXT */});}getComponentProperty(name){const componentValue=this.map.get(SHARED_CONTEXT_KEY+0);componentValue.declare=true;this.maybeRestoreView();return componentValue.lhs.prop(name);}maybeRestoreView(){// View restoration is required for listener instructions inside embedded views, because
|
|
3012
|
+
return sharedCtxObj&&sharedCtxObj.declare?sharedCtxObj.lhs:null;}maybeGenerateSharedContextVar(value){if(value.priority===1/* DeclarationPriority.CONTEXT */&&value.retrievalLevel<this.bindingLevel){const sharedCtxObj=this.map.get(SHARED_CONTEXT_KEY+value.retrievalLevel);if(sharedCtxObj){sharedCtxObj.declare=true;}else {this.generateSharedContextVar(value.retrievalLevel);}}}generateSharedContextVar(retrievalLevel){const lhs=variable(CONTEXT_NAME+this.freshReferenceName());this.map.set(SHARED_CONTEXT_KEY+retrievalLevel,{retrievalLevel:retrievalLevel,lhs:lhs,declareLocalCallback:(scope,relativeLevel)=>{// const ctx_r0 = nextContext(2);
|
|
3013
|
+
return [lhs.set(generateNextContextExpr(relativeLevel)).toConstDecl()];},declare:false,priority:2/* DeclarationPriority.SHARED_CONTEXT */});}getComponentProperty(name){const componentValue=this.map.get(SHARED_CONTEXT_KEY+0);componentValue.declare=true;this.maybeRestoreView();return componentValue.lhs.prop(name);}maybeRestoreView(){// View restoration is required for listener instructions inside embedded views, because
|
|
2951
3014
|
// they only run in creation mode and they can have references to the context object.
|
|
2952
3015
|
// If the context object changes in update mode, the reference will be incorrect, because
|
|
2953
3016
|
// it was established during creation.
|
|
2954
3017
|
if(this.isListenerScope()){if(!this.parent.restoreViewVariable){// parent saves variable to generate a shared `const $s$ = getCurrentView();` instruction
|
|
2955
|
-
this.parent.restoreViewVariable=variable(this.parent.freshReferenceName());}this.restoreViewVariable=this.parent.restoreViewVariable;}}restoreViewStatement(){
|
|
3018
|
+
this.parent.restoreViewVariable=variable(this.parent.freshReferenceName());}this.restoreViewVariable=this.parent.restoreViewVariable;}}restoreViewStatement(){if(this.restoreViewVariable){const restoreCall=invokeInstruction(null,Identifiers.restoreView,[this.restoreViewVariable]);// Either `const restoredCtx = restoreView($state$);` or `restoreView($state$);`
|
|
2956
3019
|
// depending on whether it is being used.
|
|
2957
|
-
|
|
3020
|
+
return this.usesRestoredViewContext?variable(RESTORED_VIEW_CONTEXT_NAME).set(restoreCall).toConstDecl():restoreCall.toStmt();}return null;}viewSnapshotStatements(){// const $state$ = getCurrentView();
|
|
2958
3021
|
return this.restoreViewVariable?[this.restoreViewVariable.set(invokeInstruction(null,Identifiers.getCurrentView,[])).toConstDecl()]:[];}isListenerScope(){return this.parent&&this.parent.bindingLevel===this.bindingLevel;}variableDeclarations(){let currentContextLevel=0;return Array.from(this.map.values()).filter(value=>value.declare).sort((a,b)=>b.retrievalLevel-a.retrievalLevel||b.priority-a.priority).reduce((stmts,value)=>{const levelDiff=this.bindingLevel-value.retrievalLevel;const currStmts=value.declareLocalCallback(this,levelDiff-currentContextLevel);currentContextLevel=levelDiff;return stmts.concat(currStmts);},[]);}freshReferenceName(){let current=this;// Find the top scope as it maintains the global reference count
|
|
2959
3022
|
while(current.parent)current=current.parent;const ref=`${REFERENCE_PREFIX}${current.referenceNameIndex++}`;return ref;}hasRestoreViewVariable(){return !!this.restoreViewVariable;}notifyRestoredViewContextUse(){this.usesRestoredViewContext=true;}}/**
|
|
2960
3023
|
* Creates a `CssSelector` given a tag name and a map of attributes
|
|
@@ -2963,7 +3026,7 @@ while(current.parent)current=current.parent;const ref=`${REFERENCE_PREFIX}${curr
|
|
|
2963
3026
|
* which can be added to the instruction parameters.
|
|
2964
3027
|
*/function getNgProjectAsLiteral(attribute){// Parse the attribute value into a CssSelectorList. Note that we only take the
|
|
2965
3028
|
// first selector, because we don't support multiple selectors in ngProjectAs.
|
|
2966
|
-
const parsedR3Selector=parseSelectorToR3Selector(attribute.value)[0];return [literal(5/* ProjectAs */),asLiteral(parsedR3Selector)];}/**
|
|
3029
|
+
const parsedR3Selector=parseSelectorToR3Selector(attribute.value)[0];return [literal(5/* core.AttributeMarker.ProjectAs */),asLiteral(parsedR3Selector)];}/**
|
|
2967
3030
|
* Gets the instruction to generate for an interpolated property
|
|
2968
3031
|
* @param interpolation An Interpolation AST
|
|
2969
3032
|
*/function getPropertyInterpolationExpression(interpolation){switch(getInterpolationArgsLength(interpolation)){case 1:return Identifiers.propertyInterpolate;case 3:return Identifiers.propertyInterpolate1;case 5:return Identifiers.propertyInterpolate2;case 7:return Identifiers.propertyInterpolate3;case 9:return Identifiers.propertyInterpolate4;case 11:return Identifiers.propertyInterpolate5;case 13:return Identifiers.propertyInterpolate6;case 15:return Identifiers.propertyInterpolate7;case 17:return Identifiers.propertyInterpolate8;default:return Identifiers.propertyInterpolateV;}}/**
|
|
@@ -3018,7 +3081,7 @@ fnParams.unshift(literal(name));}return fnParams;};}/** Name of the global varia
|
|
|
3018
3081
|
* @param transformFn Optional transformation function that will be applied to the translation (e.g.
|
|
3019
3082
|
* post-processing).
|
|
3020
3083
|
* @returns An array of statements that defined a given translation.
|
|
3021
|
-
*/function getTranslationDeclStmts(message,variable,closureVar,params={},transformFn){const statements=[declareI18nVariable(variable),ifStmt(createClosureModeGuard(),createGoogleGetMsgStatements(variable,message,closureVar,
|
|
3084
|
+
*/function getTranslationDeclStmts(message,variable,closureVar,params={},transformFn){const statements=[declareI18nVariable(variable),ifStmt(createClosureModeGuard(),createGoogleGetMsgStatements(variable,message,closureVar,params),createLocalizeStatements(variable,message,formatI18nPlaceholderNamesInMap(params,/* useCamelCase */false)))];if(transformFn){statements.push(new ExpressionStatement(variable.set(transformFn(variable))));}return statements;}/**
|
|
3022
3085
|
* Create the expression that will be used to guard the closure mode block
|
|
3023
3086
|
* It is equivalent to:
|
|
3024
3087
|
*
|
|
@@ -3039,10 +3102,11 @@ if(selectors.length>0){definitionMap.set('selectors',asLiteral(selectors));}if(m
|
|
|
3039
3102
|
definitionMap.set('contentQueries',createContentQueriesFunction(meta.queries,constantPool,meta.name));}if(meta.viewQueries.length){definitionMap.set('viewQuery',createViewQueriesFunction(meta.viewQueries,constantPool,meta.name));}// e.g. `hostBindings: (rf, ctx) => { ... }
|
|
3040
3103
|
definitionMap.set('hostBindings',createHostBindingsFunction(meta.host,meta.typeSourceSpan,bindingParser,constantPool,meta.selector||'',meta.name,definitionMap));// e.g 'inputs: {a: 'a'}`
|
|
3041
3104
|
definitionMap.set('inputs',conditionallyCreateMapObjectLiteral(meta.inputs,true));// e.g 'outputs: {a: 'a'}`
|
|
3042
|
-
definitionMap.set('outputs',conditionallyCreateMapObjectLiteral(meta.outputs));if(meta.exportAs!==null){definitionMap.set('exportAs',literalArr(meta.exportAs.map(e=>literal(e))));}return definitionMap;}/**
|
|
3105
|
+
definitionMap.set('outputs',conditionallyCreateMapObjectLiteral(meta.outputs));if(meta.exportAs!==null){definitionMap.set('exportAs',literalArr(meta.exportAs.map(e=>literal(e))));}if(meta.isStandalone){definitionMap.set('standalone',literal(true));}return definitionMap;}/**
|
|
3043
3106
|
* Add features to the definition map.
|
|
3044
3107
|
*/function addFeatures(definitionMap,meta){// e.g. `features: [NgOnChangesFeature]`
|
|
3045
|
-
const features=[];const providers=meta.providers;const viewProviders=meta.viewProviders;if(providers||viewProviders){const args=[providers||new LiteralArrayExpr([])];if(viewProviders){args.push(viewProviders);}features.push(importExpr(Identifiers.ProvidersFeature).callFn(args));}if(meta.usesInheritance){features.push(importExpr(Identifiers.InheritDefinitionFeature));}if(meta.fullInheritance){features.push(importExpr(Identifiers.CopyDefinitionFeature));}if(meta.lifecycle.usesOnChanges){features.push(importExpr(Identifiers.NgOnChangesFeature));}
|
|
3108
|
+
const features=[];const providers=meta.providers;const viewProviders=meta.viewProviders;if(providers||viewProviders){const args=[providers||new LiteralArrayExpr([])];if(viewProviders){args.push(viewProviders);}features.push(importExpr(Identifiers.ProvidersFeature).callFn(args));}if(meta.usesInheritance){features.push(importExpr(Identifiers.InheritDefinitionFeature));}if(meta.fullInheritance){features.push(importExpr(Identifiers.CopyDefinitionFeature));}if(meta.lifecycle.usesOnChanges){features.push(importExpr(Identifiers.NgOnChangesFeature));}// TODO: better way of differentiating component vs directive metadata.
|
|
3109
|
+
if(meta.hasOwnProperty('template')&&meta.isStandalone){features.push(importExpr(Identifiers.StandaloneFeature));}if(features.length){definitionMap.set('features',literalArr(features));}}/**
|
|
3046
3110
|
* Compile a directive for the render3 runtime as defined by the `R3DirectiveMetadata`.
|
|
3047
3111
|
*/function compileDirectiveFromMetadata(meta,constantPool,bindingParser){const definitionMap=baseDirectiveFields(meta,constantPool,bindingParser);addFeatures(definitionMap,meta);const expression=importExpr(Identifiers.defineDirective).callFn([definitionMap.toLiteralMap()],undefined,true);const type=createDirectiveType(meta);return {expression,type,statements:[]};}/**
|
|
3048
3112
|
* Compile a component for the render3 runtime as defined by the `R3ComponentMetadata`.
|
|
@@ -3059,37 +3123,37 @@ definitionMap.set('vars',literal(templateBuilder.getVarCount()));// Generate `co
|
|
|
3059
3123
|
// - or as a factory function in case additional statements are present (to support i18n):
|
|
3060
3124
|
// `consts: function() { var i18n_0; if (ngI18nClosureMode) {...} else {...} return [i18n_0]; }`
|
|
3061
3125
|
const{constExpressions,prepareStatements}=templateBuilder.getConsts();if(constExpressions.length>0){let constsExpr=literalArr(constExpressions);// Prepare statements are present - turn `consts` into a function.
|
|
3062
|
-
if(prepareStatements.length>0){constsExpr=fn([],[...prepareStatements,new ReturnStatement(constsExpr)]);}definitionMap.set('consts',constsExpr);}definitionMap.set('template',templateFunctionExpression)
|
|
3063
|
-
if(meta.
|
|
3064
|
-
if(meta.pipes.size>0){const pipesList=literalArr(Array.from(meta.pipes.values()));const pipesExpr=compileDeclarationList(pipesList,meta.declarationListEmitMode);definitionMap.set('pipes',pipesExpr);}if(meta.encapsulation===null){meta.encapsulation=exports.ViewEncapsulation.Emulated;}// e.g. `styles: [str1, str2]`
|
|
3065
|
-
if(meta.styles&&meta.styles.length){const styleValues=meta.encapsulation==exports.ViewEncapsulation.Emulated?compileStyles(meta.styles,CONTENT_ATTR,HOST_ATTR):meta.styles;const strings=styleValues.map(str=>constantPool.getConstLiteral(literal(str)));definitionMap.set('styles',literalArr(strings));}else if(meta.encapsulation===exports.ViewEncapsulation.Emulated){// If there is no style, don't generate css selectors on elements
|
|
3126
|
+
if(prepareStatements.length>0){constsExpr=fn([],[...prepareStatements,new ReturnStatement(constsExpr)]);}definitionMap.set('consts',constsExpr);}definitionMap.set('template',templateFunctionExpression);if(meta.declarations.length>0){definitionMap.set('dependencies',compileDeclarationList(literalArr(meta.declarations.map(decl=>decl.type)),meta.declarationListEmitMode));}if(meta.encapsulation===null){meta.encapsulation=exports.ViewEncapsulation.Emulated;}// e.g. `styles: [str1, str2]`
|
|
3127
|
+
if(meta.styles&&meta.styles.length){const styleValues=meta.encapsulation==exports.ViewEncapsulation.Emulated?compileStyles(meta.styles,CONTENT_ATTR,HOST_ATTR):meta.styles;const styleNodes=styleValues.reduce((result,style)=>{if(style.trim().length>0){result.push(constantPool.getConstLiteral(literal(style)));}return result;},[]);if(styleNodes.length>0){definitionMap.set('styles',literalArr(styleNodes));}}else if(meta.encapsulation===exports.ViewEncapsulation.Emulated){// If there is no style, don't generate css selectors on elements
|
|
3066
3128
|
meta.encapsulation=exports.ViewEncapsulation.None;}// Only set view encapsulation if it's not the default value
|
|
3067
3129
|
if(meta.encapsulation!==exports.ViewEncapsulation.Emulated){definitionMap.set('encapsulation',literal(meta.encapsulation));}// e.g. `animation: [trigger('123', [])]`
|
|
3068
3130
|
if(meta.animations!==null){definitionMap.set('data',literalMap([{key:'animation',value:meta.animations,quoted:false}]));}// Only set the change detection flag if it's defined and it's not the default.
|
|
3069
3131
|
if(changeDetection!=null&&changeDetection!==exports.ChangeDetectionStrategy.Default){definitionMap.set('changeDetection',literal(changeDetection));}const expression=importExpr(Identifiers.defineComponent).callFn([definitionMap.toLiteralMap()],undefined,true);const type=createComponentType(meta);return {expression,type,statements:[]};}/**
|
|
3070
3132
|
* Creates the type specification from the component meta. This type is inserted into .d.ts files
|
|
3071
3133
|
* to be consumed by upstream compilations.
|
|
3072
|
-
*/function createComponentType(meta){const typeParams=
|
|
3134
|
+
*/function createComponentType(meta){const typeParams=createBaseDirectiveTypeParams(meta);typeParams.push(stringArrayAsType(meta.template.ngContentSelectors));typeParams.push(expressionType(literal(meta.isStandalone)));return expressionType(importExpr(Identifiers.ComponentDeclaration,typeParams));}/**
|
|
3073
3135
|
* Compiles the array literal of declarations into an expression according to the provided emit
|
|
3074
3136
|
* mode.
|
|
3075
|
-
*/function compileDeclarationList(list,mode){switch(mode){case 0/* Direct */:// directives: [MyDir],
|
|
3076
|
-
return list;case 1/* Closure */:// directives: function () { return [MyDir]; }
|
|
3077
|
-
return fn([],[new ReturnStatement(list)]);case 2/* ClosureResolved */:// directives: function () { return [MyDir].map(ng.resolveForwardRef); }
|
|
3137
|
+
*/function compileDeclarationList(list,mode){switch(mode){case 0/* DeclarationListEmitMode.Direct */:// directives: [MyDir],
|
|
3138
|
+
return list;case 1/* DeclarationListEmitMode.Closure */:// directives: function () { return [MyDir]; }
|
|
3139
|
+
return fn([],[new ReturnStatement(list)]);case 2/* DeclarationListEmitMode.ClosureResolved */:// directives: function () { return [MyDir].map(ng.resolveForwardRef); }
|
|
3078
3140
|
const resolvedList=list.prop('map').callFn([importExpr(Identifiers.resolveForwardRef)]);return fn([],[new ReturnStatement(resolvedList)]);}}function prepareQueryParams(query,constantPool){const parameters=[getQueryPredicate(query,constantPool),literal(toQueryFlags(query))];if(query.read){parameters.push(query.read);}return parameters;}/**
|
|
3079
3141
|
* Translates query flags into `TQueryFlags` type in packages/core/src/render3/interfaces/query.ts
|
|
3080
3142
|
* @param query
|
|
3081
|
-
*/function toQueryFlags(query){return (query.descendants?1/* descendants */:0/* none */)|(query.static?2/* isStatic */:0/* none */)|(query.emitDistinctChangesOnly?4/* emitDistinctChangesOnly */:0/* none */);}function convertAttributesToExpressions(attributes){const values=[];for(let key of Object.getOwnPropertyNames(attributes)){const value=attributes[key];values.push(literal(key),value);}return values;}// Define and update any content queries
|
|
3143
|
+
*/function toQueryFlags(query){return (query.descendants?1/* QueryFlags.descendants */:0/* QueryFlags.none */)|(query.static?2/* QueryFlags.isStatic */:0/* QueryFlags.none */)|(query.emitDistinctChangesOnly?4/* QueryFlags.emitDistinctChangesOnly */:0/* QueryFlags.none */);}function convertAttributesToExpressions(attributes){const values=[];for(let key of Object.getOwnPropertyNames(attributes)){const value=attributes[key];values.push(literal(key),value);}return values;}// Define and update any content queries
|
|
3082
3144
|
function createContentQueriesFunction(queries,constantPool,name){const createStatements=[];const updateStatements=[];const tempAllocator=temporaryAllocator(updateStatements,TEMPORARY_NAME);for(const query of queries){// creation, e.g. r3.contentQuery(dirIndex, somePredicate, true, null);
|
|
3083
3145
|
createStatements.push(importExpr(Identifiers.contentQuery).callFn([variable('dirIndex'),...prepareQueryParams(query,constantPool)]).toStmt());// update, e.g. (r3.queryRefresh(tmp = r3.loadQuery()) && (ctx.someDir = tmp));
|
|
3084
|
-
const temporary=tempAllocator();const getQueryList=importExpr(Identifiers.loadQuery).callFn([]);const refresh=importExpr(Identifiers.queryRefresh).callFn([temporary.set(getQueryList)]);const updateDirective=variable(CONTEXT_NAME).prop(query.propertyName).set(query.first?temporary.prop('first'):temporary);updateStatements.push(refresh.and(updateDirective).toStmt());}const contentQueriesFnName=name?`${name}_ContentQueries`:null;return fn([new FnParam(RENDER_FLAGS,NUMBER_TYPE),new FnParam(CONTEXT_NAME,null),new FnParam('dirIndex',null)],[renderFlagCheckIfStmt(1/* Create */,createStatements),renderFlagCheckIfStmt(2/* Update */,updateStatements)],INFERRED_TYPE,null,contentQueriesFnName);}function stringAsType(str){return expressionType(literal(str));}function stringMapAsType(map){const mapValues=Object.keys(map).map(key=>{const value=Array.isArray(map[key])?map[key][0]:map[key];return {key,value:literal(value),quoted:true};});return expressionType(literalMap(mapValues));}function stringArrayAsType(arr){return arr.length>0?expressionType(literalArr(arr.map(value=>literal(value)))):NONE_TYPE;}function
|
|
3146
|
+
const temporary=tempAllocator();const getQueryList=importExpr(Identifiers.loadQuery).callFn([]);const refresh=importExpr(Identifiers.queryRefresh).callFn([temporary.set(getQueryList)]);const updateDirective=variable(CONTEXT_NAME).prop(query.propertyName).set(query.first?temporary.prop('first'):temporary);updateStatements.push(refresh.and(updateDirective).toStmt());}const contentQueriesFnName=name?`${name}_ContentQueries`:null;return fn([new FnParam(RENDER_FLAGS,NUMBER_TYPE),new FnParam(CONTEXT_NAME,null),new FnParam('dirIndex',null)],[renderFlagCheckIfStmt(1/* core.RenderFlags.Create */,createStatements),renderFlagCheckIfStmt(2/* core.RenderFlags.Update */,updateStatements)],INFERRED_TYPE,null,contentQueriesFnName);}function stringAsType(str){return expressionType(literal(str));}function stringMapAsType(map){const mapValues=Object.keys(map).map(key=>{const value=Array.isArray(map[key])?map[key][0]:map[key];return {key,value:literal(value),quoted:true};});return expressionType(literalMap(mapValues));}function stringArrayAsType(arr){return arr.length>0?expressionType(literalArr(arr.map(value=>literal(value)))):NONE_TYPE;}function createBaseDirectiveTypeParams(meta){// On the type side, remove newlines from the selector as it will need to fit into a TypeScript
|
|
3085
3147
|
// string literal, which must be on one line.
|
|
3086
3148
|
const selectorForType=meta.selector!==null?meta.selector.replace(/\n/g,''):null;return [typeWithParameters(meta.type.type,meta.typeArgumentCount),selectorForType!==null?stringAsType(selectorForType):NONE_TYPE,meta.exportAs!==null?stringArrayAsType(meta.exportAs):NONE_TYPE,stringMapAsType(meta.inputs),stringMapAsType(meta.outputs),stringArrayAsType(meta.queries.map(q=>q.propertyName))];}/**
|
|
3087
3149
|
* Creates the type specification from the directive meta. This type is inserted into .d.ts files
|
|
3088
3150
|
* to be consumed by upstream compilations.
|
|
3089
|
-
*/function createDirectiveType(meta){const typeParams=
|
|
3151
|
+
*/function createDirectiveType(meta){const typeParams=createBaseDirectiveTypeParams(meta);// Directives have no NgContentSelectors slot, but instead express a `never` type
|
|
3152
|
+
// so that future fields align.
|
|
3153
|
+
typeParams.push(NONE_TYPE);typeParams.push(expressionType(literal(meta.isStandalone)));return expressionType(importExpr(Identifiers.DirectiveDeclaration,typeParams));}// Define and update any view queries
|
|
3090
3154
|
function createViewQueriesFunction(viewQueries,constantPool,name){const createStatements=[];const updateStatements=[];const tempAllocator=temporaryAllocator(updateStatements,TEMPORARY_NAME);viewQueries.forEach(query=>{// creation, e.g. r3.viewQuery(somePredicate, true);
|
|
3091
3155
|
const queryDefinition=importExpr(Identifiers.viewQuery).callFn(prepareQueryParams(query,constantPool));createStatements.push(queryDefinition.toStmt());// update, e.g. (r3.queryRefresh(tmp = r3.loadQuery()) && (ctx.someDir = tmp));
|
|
3092
|
-
const temporary=tempAllocator();const getQueryList=importExpr(Identifiers.loadQuery).callFn([]);const refresh=importExpr(Identifiers.queryRefresh).callFn([temporary.set(getQueryList)]);const updateDirective=variable(CONTEXT_NAME).prop(query.propertyName).set(query.first?temporary.prop('first'):temporary);updateStatements.push(refresh.and(updateDirective).toStmt());});const viewQueryFnName=name?`${name}_Query`:null;return fn([new FnParam(RENDER_FLAGS,NUMBER_TYPE),new FnParam(CONTEXT_NAME,null)],[renderFlagCheckIfStmt(1/* Create */,createStatements),renderFlagCheckIfStmt(2/* Update */,updateStatements)],INFERRED_TYPE,null,viewQueryFnName);}// Return a host binding function or null if one is not necessary.
|
|
3156
|
+
const temporary=tempAllocator();const getQueryList=importExpr(Identifiers.loadQuery).callFn([]);const refresh=importExpr(Identifiers.queryRefresh).callFn([temporary.set(getQueryList)]);const updateDirective=variable(CONTEXT_NAME).prop(query.propertyName).set(query.first?temporary.prop('first'):temporary);updateStatements.push(refresh.and(updateDirective).toStmt());});const viewQueryFnName=name?`${name}_Query`:null;return fn([new FnParam(RENDER_FLAGS,NUMBER_TYPE),new FnParam(CONTEXT_NAME,null)],[renderFlagCheckIfStmt(1/* core.RenderFlags.Create */,createStatements),renderFlagCheckIfStmt(2/* core.RenderFlags.Update */,updateStatements)],INFERRED_TYPE,null,viewQueryFnName);}// Return a host binding function or null if one is not necessary.
|
|
3093
3157
|
function createHostBindingsFunction(hostBindingsMetadata,typeSourceSpan,bindingParser,constantPool,selector,name,definitionMap){const bindingContext=variable(CONTEXT_NAME);const styleBuilder=new StylingBuilder(bindingContext);const{styleAttr,classAttr}=hostBindingsMetadata.specialAttributes;if(styleAttr!==undefined){styleBuilder.registerStyleAttr(styleAttr);}if(classAttr!==undefined){styleBuilder.registerClassAttr(classAttr);}const createInstructions=[];const updateInstructions=[];const updateVariables=[];const hostBindingSourceSpan=typeSourceSpan;// Calculate host event bindings
|
|
3094
3158
|
const eventBindings=bindingParser.createDirectiveHostEventAsts(hostBindingsMetadata.listeners,hostBindingSourceSpan);if(eventBindings&&eventBindings.length){createInstructions.push(...createHostListeners(eventBindings,name));}// Calculate the host property bindings
|
|
3095
3159
|
const bindings=bindingParser.createBoundHostProperties(hostBindingsMetadata.properties,hostBindingSourceSpan);const allOtherBindings=[];// We need to calculate the total amount of binding slots required by
|
|
@@ -3115,18 +3179,18 @@ const hostAttrs=convertAttributesToExpressions(hostBindingsMetadata.attributes);
|
|
|
3115
3179
|
// are evaluated and updated for the element.
|
|
3116
3180
|
styleBuilder.buildUpdateLevelInstructions(getValueConverter()).forEach(instruction=>{for(const call of instruction.calls){// we subtract a value of `1` here because the binding slot was already allocated
|
|
3117
3181
|
// at the top of this method when all the input bindings were counted.
|
|
3118
|
-
totalHostVarsCount+=Math.max(call.allocateBindingSlots-MIN_STYLING_BINDING_SLOTS_REQUIRED,0);updateInstructions.push({reference:instruction.reference,paramsOrFn:convertStylingCall(call,bindingContext,bindingFn),span:null});}});}if(totalHostVarsCount){definitionMap.set('hostVars',literal(totalHostVarsCount));}if(createInstructions.length>0||updateInstructions.length>0){const hostBindingsFnName=name?`${name}_HostBindings`:null;const statements=[];if(createInstructions.length>0){statements.push(renderFlagCheckIfStmt(1/* Create */,getInstructionStatements(createInstructions)));}if(updateInstructions.length>0){statements.push(renderFlagCheckIfStmt(2/* Update */,updateVariables.concat(getInstructionStatements(updateInstructions))));}return fn([new FnParam(RENDER_FLAGS,NUMBER_TYPE),new FnParam(CONTEXT_NAME,null)],statements,INFERRED_TYPE,null,hostBindingsFnName);}return null;}function bindingFn(implicit,value){return convertPropertyBinding(null,implicit,value,'b');}function convertStylingCall(call,bindingContext,bindingFn){return call.params(value=>bindingFn(bindingContext,value).currValExpr);}function getBindingNameAndInstruction(binding){let bindingName=binding.name;let instruction;// Check to see if this is an attr binding or a property binding
|
|
3182
|
+
totalHostVarsCount+=Math.max(call.allocateBindingSlots-MIN_STYLING_BINDING_SLOTS_REQUIRED,0);updateInstructions.push({reference:instruction.reference,paramsOrFn:convertStylingCall(call,bindingContext,bindingFn),span:null});}});}if(totalHostVarsCount){definitionMap.set('hostVars',literal(totalHostVarsCount));}if(createInstructions.length>0||updateInstructions.length>0){const hostBindingsFnName=name?`${name}_HostBindings`:null;const statements=[];if(createInstructions.length>0){statements.push(renderFlagCheckIfStmt(1/* core.RenderFlags.Create */,getInstructionStatements(createInstructions)));}if(updateInstructions.length>0){statements.push(renderFlagCheckIfStmt(2/* core.RenderFlags.Update */,updateVariables.concat(getInstructionStatements(updateInstructions))));}return fn([new FnParam(RENDER_FLAGS,NUMBER_TYPE),new FnParam(CONTEXT_NAME,null)],statements,INFERRED_TYPE,null,hostBindingsFnName);}return null;}function bindingFn(implicit,value){return convertPropertyBinding(null,implicit,value,'b');}function convertStylingCall(call,bindingContext,bindingFn){return call.params(value=>bindingFn(bindingContext,value).currValExpr);}function getBindingNameAndInstruction(binding){let bindingName=binding.name;let instruction;// Check to see if this is an attr binding or a property binding
|
|
3119
3183
|
const attrMatches=bindingName.match(ATTR_REGEX);if(attrMatches){bindingName=attrMatches[1];instruction=Identifiers.attribute;}else {if(binding.isAnimation){bindingName=prepareSyntheticPropertyName(bindingName);// host bindings that have a synthetic property (e.g. @foo) should always be rendered
|
|
3120
3184
|
// in the context of the component and not the parent. Therefore there is a special
|
|
3121
3185
|
// compatibility instruction available for this purpose.
|
|
3122
|
-
instruction=Identifiers.syntheticHostProperty;}else {instruction=Identifiers.hostProperty;}}return {bindingName,instruction,isAttribute:!!attrMatches};}function createHostListeners(eventBindings,name){const listenerParams=[];const syntheticListenerParams=[];const instructions=[];for(const binding of eventBindings){let bindingName=binding.name&&sanitizeIdentifier(binding.name);const bindingFnName=binding.type===1/* Animation */?prepareSyntheticListenerFunctionName(bindingName,binding.targetOrPhase):bindingName;const handlerName=name&&bindingName?`${name}_${bindingFnName}_HostBindingHandler`:null;const params=prepareEventListenerParameters(BoundEvent.fromParsedEvent(binding),handlerName);if(binding.type==1/* Animation */){syntheticListenerParams.push(params);}else {listenerParams.push(params);}}for(const params of syntheticListenerParams){instructions.push({reference:Identifiers.syntheticHostListener,paramsOrFn:params,span:null});}for(const params of listenerParams){instructions.push({reference:Identifiers.listener,paramsOrFn:params,span:null});}return instructions;}const HOST_REG_EXP=/^(?:\[([^\]]+)\])|(?:\(([^\)]+)\))$/;function parseHostBindings(host){const attributes={};const listeners={};const properties={};const specialAttributes={};for(const key of Object.keys(host)){const value=host[key];const matches=key.match(HOST_REG_EXP);if(matches===null){switch(key){case'class':if(typeof value!=='string'){// TODO(alxhub): make this a diagnostic.
|
|
3186
|
+
instruction=Identifiers.syntheticHostProperty;}else {instruction=Identifiers.hostProperty;}}return {bindingName,instruction,isAttribute:!!attrMatches};}function createHostListeners(eventBindings,name){const listenerParams=[];const syntheticListenerParams=[];const instructions=[];for(const binding of eventBindings){let bindingName=binding.name&&sanitizeIdentifier(binding.name);const bindingFnName=binding.type===1/* ParsedEventType.Animation */?prepareSyntheticListenerFunctionName(bindingName,binding.targetOrPhase):bindingName;const handlerName=name&&bindingName?`${name}_${bindingFnName}_HostBindingHandler`:null;const params=prepareEventListenerParameters(BoundEvent.fromParsedEvent(binding),handlerName);if(binding.type==1/* ParsedEventType.Animation */){syntheticListenerParams.push(params);}else {listenerParams.push(params);}}for(const params of syntheticListenerParams){instructions.push({reference:Identifiers.syntheticHostListener,paramsOrFn:params,span:null});}for(const params of listenerParams){instructions.push({reference:Identifiers.listener,paramsOrFn:params,span:null});}return instructions;}const HOST_REG_EXP=/^(?:\[([^\]]+)\])|(?:\(([^\)]+)\))$/;function parseHostBindings(host){const attributes={};const listeners={};const properties={};const specialAttributes={};for(const key of Object.keys(host)){const value=host[key];const matches=key.match(HOST_REG_EXP);if(matches===null){switch(key){case'class':if(typeof value!=='string'){// TODO(alxhub): make this a diagnostic.
|
|
3123
3187
|
throw new Error(`Class binding must be string`);}specialAttributes.classAttr=value;break;case'style':if(typeof value!=='string'){// TODO(alxhub): make this a diagnostic.
|
|
3124
|
-
throw new Error(`Style binding must be string`);}specialAttributes.styleAttr=value;break;default:if(typeof value==='string'){attributes[key]=literal(value);}else {attributes[key]=value;}}}else if(matches[1/* Binding */]!=null){if(typeof value!=='string'){// TODO(alxhub): make this a diagnostic.
|
|
3188
|
+
throw new Error(`Style binding must be string`);}specialAttributes.styleAttr=value;break;default:if(typeof value==='string'){attributes[key]=literal(value);}else {attributes[key]=value;}}}else if(matches[1/* HostBindingGroup.Binding */]!=null){if(typeof value!=='string'){// TODO(alxhub): make this a diagnostic.
|
|
3125
3189
|
throw new Error(`Property binding must be string`);}// synthetic properties (the ones that have a `@` as a prefix)
|
|
3126
3190
|
// are still treated the same as regular properties. Therefore
|
|
3127
3191
|
// there is no point in storing them in a separate map.
|
|
3128
|
-
properties[matches[1/* Binding */]]=value;}else if(matches[2/* Event */]!=null){if(typeof value!=='string'){// TODO(alxhub): make this a diagnostic.
|
|
3129
|
-
throw new Error(`Event binding must be string`);}listeners[matches[2/* Event */]]=value;}}return {attributes,listeners,properties,specialAttributes};}/**
|
|
3192
|
+
properties[matches[1/* HostBindingGroup.Binding */]]=value;}else if(matches[2/* HostBindingGroup.Event */]!=null){if(typeof value!=='string'){// TODO(alxhub): make this a diagnostic.
|
|
3193
|
+
throw new Error(`Event binding must be string`);}listeners[matches[2/* HostBindingGroup.Event */]]=value;}}return {attributes,listeners,properties,specialAttributes};}/**
|
|
3130
3194
|
* Verifies host bindings and returns the list of errors (if any). Empty array indicates that a
|
|
3131
3195
|
* given set of host bindings has no errors.
|
|
3132
3196
|
*
|
|
@@ -3153,9 +3217,9 @@ const bindingParser=makeBindingParser();bindingParser.createDirectiveHostEventAs
|
|
|
3153
3217
|
*
|
|
3154
3218
|
* Use of this source code is governed by an MIT-style license that can be
|
|
3155
3219
|
* found in the LICENSE file at https://angular.io/license
|
|
3156
|
-
*/class CompilerFacadeImpl{constructor(jitEvaluator=new JitEvaluator()){this.jitEvaluator=jitEvaluator;this.FactoryTarget=exports.FactoryTarget;this.ResourceLoader=ResourceLoader;this.elementSchemaRegistry=new DomElementSchemaRegistry();}compilePipe(angularCoreEnv,sourceMapUrl,facade){const metadata={name:facade.name,type:wrapReference(facade.type),internalType:new WrappedNodeExpr(facade.type),typeArgumentCount:0,deps:null,pipeName:facade.pipeName,pure:facade.pure};const res=compilePipeFromMetadata(metadata);return this.jitExpression(res.expression,angularCoreEnv,sourceMapUrl,[]);}compilePipeDeclaration(angularCoreEnv,sourceMapUrl,declaration){const meta=convertDeclarePipeFacadeToMetadata(declaration);const res=compilePipeFromMetadata(meta);return this.jitExpression(res.expression,angularCoreEnv,sourceMapUrl,[]);}compileInjectable(angularCoreEnv,sourceMapUrl,facade){var _a;const{expression,statements}=compileInjectable({name:facade.name,type:wrapReference(facade.type),internalType:new WrappedNodeExpr(facade.type),typeArgumentCount:facade.typeArgumentCount,providedIn:computeProvidedIn(facade.providedIn),useClass:convertToProviderExpression(facade,
|
|
3220
|
+
*/class CompilerFacadeImpl{constructor(jitEvaluator=new JitEvaluator()){this.jitEvaluator=jitEvaluator;this.FactoryTarget=exports.FactoryTarget;this.ResourceLoader=ResourceLoader;this.elementSchemaRegistry=new DomElementSchemaRegistry();}compilePipe(angularCoreEnv,sourceMapUrl,facade){const metadata={name:facade.name,type:wrapReference(facade.type),internalType:new WrappedNodeExpr(facade.type),typeArgumentCount:0,deps:null,pipeName:facade.pipeName,pure:facade.pure,isStandalone:facade.isStandalone};const res=compilePipeFromMetadata(metadata);return this.jitExpression(res.expression,angularCoreEnv,sourceMapUrl,[]);}compilePipeDeclaration(angularCoreEnv,sourceMapUrl,declaration){const meta=convertDeclarePipeFacadeToMetadata(declaration);const res=compilePipeFromMetadata(meta);return this.jitExpression(res.expression,angularCoreEnv,sourceMapUrl,[]);}compileInjectable(angularCoreEnv,sourceMapUrl,facade){var _a;const{expression,statements}=compileInjectable({name:facade.name,type:wrapReference(facade.type),internalType:new WrappedNodeExpr(facade.type),typeArgumentCount:facade.typeArgumentCount,providedIn:computeProvidedIn(facade.providedIn),useClass:convertToProviderExpression(facade,'useClass'),useFactory:wrapExpression(facade,'useFactory'),useValue:convertToProviderExpression(facade,'useValue'),useExisting:convertToProviderExpression(facade,'useExisting'),deps:(_a=facade.deps)===null||_a===void 0?void 0:_a.map(convertR3DependencyMetadata)},/* resolveForwardRefs */true);return this.jitExpression(expression,angularCoreEnv,sourceMapUrl,statements);}compileInjectableDeclaration(angularCoreEnv,sourceMapUrl,facade){var _a;const{expression,statements}=compileInjectable({name:facade.type.name,type:wrapReference(facade.type),internalType:new WrappedNodeExpr(facade.type),typeArgumentCount:0,providedIn:computeProvidedIn(facade.providedIn),useClass:convertToProviderExpression(facade,'useClass'),useFactory:wrapExpression(facade,'useFactory'),useValue:convertToProviderExpression(facade,'useValue'),useExisting:convertToProviderExpression(facade,'useExisting'),deps:(_a=facade.deps)===null||_a===void 0?void 0:_a.map(convertR3DeclareDependencyMetadata)},/* resolveForwardRefs */true);return this.jitExpression(expression,angularCoreEnv,sourceMapUrl,statements);}compileInjector(angularCoreEnv,sourceMapUrl,facade){const meta={name:facade.name,type:wrapReference(facade.type),internalType:new WrappedNodeExpr(facade.type),providers:new WrappedNodeExpr(facade.providers),imports:facade.imports.map(i=>new WrappedNodeExpr(i))};const res=compileInjector(meta);return this.jitExpression(res.expression,angularCoreEnv,sourceMapUrl,[]);}compileInjectorDeclaration(angularCoreEnv,sourceMapUrl,declaration){const meta=convertDeclareInjectorFacadeToMetadata(declaration);const res=compileInjector(meta);return this.jitExpression(res.expression,angularCoreEnv,sourceMapUrl,[]);}compileNgModule(angularCoreEnv,sourceMapUrl,facade){const meta={type:wrapReference(facade.type),internalType:new WrappedNodeExpr(facade.type),adjacentType:new WrappedNodeExpr(facade.type),bootstrap:facade.bootstrap.map(wrapReference),declarations:facade.declarations.map(wrapReference),imports:facade.imports.map(wrapReference),exports:facade.exports.map(wrapReference),selectorScopeMode:exports.R3SelectorScopeMode.Inline,containsForwardDecls:false,schemas:facade.schemas?facade.schemas.map(wrapReference):null,id:facade.id?new WrappedNodeExpr(facade.id):null};const res=compileNgModule(meta);return this.jitExpression(res.expression,angularCoreEnv,sourceMapUrl,[]);}compileNgModuleDeclaration(angularCoreEnv,sourceMapUrl,declaration){const expression=compileNgModuleDeclarationExpression(declaration);return this.jitExpression(expression,angularCoreEnv,sourceMapUrl,[]);}compileDirective(angularCoreEnv,sourceMapUrl,facade){const meta=convertDirectiveFacadeToMetadata(facade);return this.compileDirectiveFromMeta(angularCoreEnv,sourceMapUrl,meta);}compileDirectiveDeclaration(angularCoreEnv,sourceMapUrl,declaration){const typeSourceSpan=this.createParseSourceSpan('Directive',declaration.type.name,sourceMapUrl);const meta=convertDeclareDirectiveFacadeToMetadata(declaration,typeSourceSpan);return this.compileDirectiveFromMeta(angularCoreEnv,sourceMapUrl,meta);}compileDirectiveFromMeta(angularCoreEnv,sourceMapUrl,meta){const constantPool=new ConstantPool();const bindingParser=makeBindingParser();const res=compileDirectiveFromMetadata(meta,constantPool,bindingParser);return this.jitExpression(res.expression,angularCoreEnv,sourceMapUrl,constantPool.statements);}compileComponent(angularCoreEnv,sourceMapUrl,facade){// Parse the template and check for errors.
|
|
3157
3221
|
const{template,interpolation}=parseJitTemplate(facade.template,facade.name,sourceMapUrl,facade.preserveWhitespaces,facade.interpolation);// Compile the component metadata, including template, into an expression.
|
|
3158
|
-
const meta=Object.assign(Object.assign(Object.assign({},facade),convertDirectiveFacadeToMetadata(facade)),{selector:facade.selector||this.elementSchemaRegistry.getDefaultComponentElementName(),template,declarationListEmitMode:0/* Direct */,styles:[...facade.styles,...template.styles],encapsulation:facade.encapsulation,interpolation,changeDetection:facade.changeDetection,animations:facade.animations!=null?new WrappedNodeExpr(facade.animations):null,viewProviders:facade.viewProviders!=null?new WrappedNodeExpr(facade.viewProviders):null,relativeContextFilePath:'',i18nUseExternalIds:true});const jitExpressionSourceMap=`ng:///${facade.name}.js`;return this.compileComponentFromMeta(angularCoreEnv,jitExpressionSourceMap,meta);}compileComponentDeclaration(angularCoreEnv,sourceMapUrl,declaration){const typeSourceSpan=this.createParseSourceSpan('Component',declaration.type.name,sourceMapUrl);const meta=convertDeclareComponentFacadeToMetadata(declaration,typeSourceSpan,sourceMapUrl);return this.compileComponentFromMeta(angularCoreEnv,sourceMapUrl,meta);}compileComponentFromMeta(angularCoreEnv,sourceMapUrl,meta){const constantPool=new ConstantPool();const bindingParser=makeBindingParser(meta.interpolation);const res=compileComponentFromMetadata(meta,constantPool,bindingParser);return this.jitExpression(res.expression,angularCoreEnv,sourceMapUrl,constantPool.statements);}compileFactory(angularCoreEnv,sourceMapUrl,meta){const factoryRes=compileFactoryFunction({name:meta.name,type:wrapReference(meta.type),internalType:new WrappedNodeExpr(meta.type),typeArgumentCount:meta.typeArgumentCount,deps:convertR3DependencyMetadataArray(meta.deps),target:meta.target});return this.jitExpression(factoryRes.expression,angularCoreEnv,sourceMapUrl,factoryRes.statements);}compileFactoryDeclaration(angularCoreEnv,sourceMapUrl,meta){const factoryRes=compileFactoryFunction({name:meta.type.name,type:wrapReference(meta.type),internalType:new WrappedNodeExpr(meta.type),typeArgumentCount:0,deps:Array.isArray(meta.deps)?meta.deps.map(convertR3DeclareDependencyMetadata):meta.deps,target:meta.target});return this.jitExpression(factoryRes.expression,angularCoreEnv,sourceMapUrl,factoryRes.statements);}createParseSourceSpan(kind,typeName,sourceUrl){return r3JitTypeSourceSpan(kind,typeName,sourceUrl);}/**
|
|
3222
|
+
const meta=Object.assign(Object.assign(Object.assign({},facade),convertDirectiveFacadeToMetadata(facade)),{selector:facade.selector||this.elementSchemaRegistry.getDefaultComponentElementName(),template,declarations:facade.declarations.map(convertDeclarationFacadeToMetadata),declarationListEmitMode:0/* DeclarationListEmitMode.Direct */,styles:[...facade.styles,...template.styles],encapsulation:facade.encapsulation,interpolation,changeDetection:facade.changeDetection,animations:facade.animations!=null?new WrappedNodeExpr(facade.animations):null,viewProviders:facade.viewProviders!=null?new WrappedNodeExpr(facade.viewProviders):null,relativeContextFilePath:'',i18nUseExternalIds:true});const jitExpressionSourceMap=`ng:///${facade.name}.js`;return this.compileComponentFromMeta(angularCoreEnv,jitExpressionSourceMap,meta);}compileComponentDeclaration(angularCoreEnv,sourceMapUrl,declaration){const typeSourceSpan=this.createParseSourceSpan('Component',declaration.type.name,sourceMapUrl);const meta=convertDeclareComponentFacadeToMetadata(declaration,typeSourceSpan,sourceMapUrl);return this.compileComponentFromMeta(angularCoreEnv,sourceMapUrl,meta);}compileComponentFromMeta(angularCoreEnv,sourceMapUrl,meta){const constantPool=new ConstantPool();const bindingParser=makeBindingParser(meta.interpolation);const res=compileComponentFromMetadata(meta,constantPool,bindingParser);return this.jitExpression(res.expression,angularCoreEnv,sourceMapUrl,constantPool.statements);}compileFactory(angularCoreEnv,sourceMapUrl,meta){const factoryRes=compileFactoryFunction({name:meta.name,type:wrapReference(meta.type),internalType:new WrappedNodeExpr(meta.type),typeArgumentCount:meta.typeArgumentCount,deps:convertR3DependencyMetadataArray(meta.deps),target:meta.target});return this.jitExpression(factoryRes.expression,angularCoreEnv,sourceMapUrl,factoryRes.statements);}compileFactoryDeclaration(angularCoreEnv,sourceMapUrl,meta){const factoryRes=compileFactoryFunction({name:meta.type.name,type:wrapReference(meta.type),internalType:new WrappedNodeExpr(meta.type),typeArgumentCount:0,deps:Array.isArray(meta.deps)?meta.deps.map(convertR3DeclareDependencyMetadata):meta.deps,target:meta.target});return this.jitExpression(factoryRes.expression,angularCoreEnv,sourceMapUrl,factoryRes.statements);}createParseSourceSpan(kind,typeName,sourceUrl){return r3JitTypeSourceSpan(kind,typeName,sourceUrl);}/**
|
|
3159
3223
|
* JIT compiles an expression and returns the result of executing that expression.
|
|
3160
3224
|
*
|
|
3161
3225
|
* @param def the definition which will be compiled and executed to get the value to patch
|
|
@@ -3166,9 +3230,11 @@ const meta=Object.assign(Object.assign(Object.assign({},facade),convertDirective
|
|
|
3166
3230
|
*/jitExpression(def,context,sourceUrl,preStatements){// The ConstantPool may contain Statements which declare variables used in the final expression.
|
|
3167
3231
|
// Therefore, its statements need to precede the actual JIT operation. The final statement is a
|
|
3168
3232
|
// declaration of $def which is set to the expression being compiled.
|
|
3169
|
-
const statements=[...preStatements,new DeclareVarStmt('$def',def,undefined,exports.StmtModifier.Exported)];const res=this.jitEvaluator.evaluateStatements(sourceUrl,statements,new R3JitReflector(context),/* enableSourceMaps */true);return res['$def'];}}
|
|
3233
|
+
const statements=[...preStatements,new DeclareVarStmt('$def',def,undefined,exports.StmtModifier.Exported)];const res=this.jitEvaluator.evaluateStatements(sourceUrl,statements,new R3JitReflector(context),/* enableSourceMaps */true);return res['$def'];}}function convertToR3QueryMetadata(facade){return Object.assign(Object.assign({},facade),{predicate:convertQueryPredicate(facade.predicate),read:facade.read?new WrappedNodeExpr(facade.read):null,static:facade.static,emitDistinctChangesOnly:facade.emitDistinctChangesOnly});}function convertQueryDeclarationToMetadata(declaration){var _a,_b,_c,_d;return {propertyName:declaration.propertyName,first:(_a=declaration.first)!==null&&_a!==void 0?_a:false,predicate:convertQueryPredicate(declaration.predicate),descendants:(_b=declaration.descendants)!==null&&_b!==void 0?_b:false,read:declaration.read?new WrappedNodeExpr(declaration.read):null,static:(_c=declaration.static)!==null&&_c!==void 0?_c:false,emitDistinctChangesOnly:(_d=declaration.emitDistinctChangesOnly)!==null&&_d!==void 0?_d:true};}function convertQueryPredicate(predicate){return Array.isArray(predicate)?// The predicate is an array of strings so pass it through.
|
|
3170
3234
|
predicate:// The predicate is a type - assume that we will need to unwrap any `forwardRef()` calls.
|
|
3171
|
-
createMayBeForwardRefExpression(new WrappedNodeExpr(predicate),1/* Wrapped */);}function convertDirectiveFacadeToMetadata(facade){const inputsFromMetadata=parseInputOutputs(facade.inputs||[]);const outputsFromMetadata=parseInputOutputs(facade.outputs||[]);const propMetadata=facade.propMetadata;const inputsFromType={};const outputsFromType={};for(const field in propMetadata){if(propMetadata.hasOwnProperty(field)){propMetadata[field].forEach(ann=>{if(isInput(ann)){inputsFromType[field]=ann.bindingPropertyName?[ann.bindingPropertyName,field]:field;}else if(isOutput(ann)){outputsFromType[field]=ann.bindingPropertyName||field;}});}}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});}function convertDeclareDirectiveFacadeToMetadata(declaration,typeSourceSpan){var _a,_b,_c,_d,_e,_f,_g,_h;return {name:declaration.type.name,type:wrapReference(declaration.type),typeSourceSpan,internalType:new WrappedNodeExpr(declaration.type),selector:(_a=declaration.selector)!==null&&_a!==void 0?_a:null,inputs:(_b=declaration.inputs)!==null&&_b!==void 0?_b:{},outputs:(_c=declaration.outputs)!==null&&_c!==void 0?_c:{},host:convertHostDeclarationToMetadata(declaration.host),queries:((_d=declaration.queries)!==null&&_d!==void 0?_d:[]).map(convertQueryDeclarationToMetadata),viewQueries:((_e=declaration.viewQueries)!==null&&_e!==void 0?_e:[]).map(convertQueryDeclarationToMetadata),providers:declaration.providers!==undefined?new WrappedNodeExpr(declaration.providers):null,exportAs:(_f=declaration.exportAs)!==null&&_f!==void 0?_f:null,usesInheritance:(_g=declaration.usesInheritance)!==null&&_g!==void 0?_g:false,lifecycle:{usesOnChanges:(_h=declaration.usesOnChanges)!==null&&_h!==void 0?_h:false},deps:null,typeArgumentCount:0,fullInheritance:false};}function convertHostDeclarationToMetadata(host={}){var _a,_b,_c;return {attributes:convertOpaqueValuesToExpressions((_a=host.attributes)!==null&&_a!==void 0?_a:{}),listeners:(_b=host.listeners)!==null&&_b!==void 0?_b:{},properties:(_c=host.properties)!==null&&_c!==void 0?_c:{},specialAttributes:{classAttr:host.classAttribute,styleAttr:host.styleAttribute}};}function convertOpaqueValuesToExpressions(obj){const result={};for(const key of Object.keys(obj)){result[key]=new WrappedNodeExpr(obj[key]);}return result;}function convertDeclareComponentFacadeToMetadata(
|
|
3235
|
+
createMayBeForwardRefExpression(new WrappedNodeExpr(predicate),1/* ForwardRefHandling.Wrapped */);}function convertDirectiveFacadeToMetadata(facade){const inputsFromMetadata=parseInputOutputs(facade.inputs||[]);const outputsFromMetadata=parseInputOutputs(facade.outputs||[]);const propMetadata=facade.propMetadata;const inputsFromType={};const outputsFromType={};for(const field in propMetadata){if(propMetadata.hasOwnProperty(field)){propMetadata[field].forEach(ann=>{if(isInput(ann)){inputsFromType[field]=ann.bindingPropertyName?[ann.bindingPropertyName,field]:field;}else if(isOutput(ann)){outputsFromType[field]=ann.bindingPropertyName||field;}});}}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});}function convertDeclareDirectiveFacadeToMetadata(declaration,typeSourceSpan){var _a,_b,_c,_d,_e,_f,_g,_h,_j;return {name:declaration.type.name,type:wrapReference(declaration.type),typeSourceSpan,internalType:new WrappedNodeExpr(declaration.type),selector:(_a=declaration.selector)!==null&&_a!==void 0?_a:null,inputs:(_b=declaration.inputs)!==null&&_b!==void 0?_b:{},outputs:(_c=declaration.outputs)!==null&&_c!==void 0?_c:{},host:convertHostDeclarationToMetadata(declaration.host),queries:((_d=declaration.queries)!==null&&_d!==void 0?_d:[]).map(convertQueryDeclarationToMetadata),viewQueries:((_e=declaration.viewQueries)!==null&&_e!==void 0?_e:[]).map(convertQueryDeclarationToMetadata),providers:declaration.providers!==undefined?new WrappedNodeExpr(declaration.providers):null,exportAs:(_f=declaration.exportAs)!==null&&_f!==void 0?_f:null,usesInheritance:(_g=declaration.usesInheritance)!==null&&_g!==void 0?_g:false,lifecycle:{usesOnChanges:(_h=declaration.usesOnChanges)!==null&&_h!==void 0?_h:false},deps:null,typeArgumentCount:0,fullInheritance:false,isStandalone:(_j=declaration.isStandalone)!==null&&_j!==void 0?_j:false};}function convertHostDeclarationToMetadata(host={}){var _a,_b,_c;return {attributes:convertOpaqueValuesToExpressions((_a=host.attributes)!==null&&_a!==void 0?_a:{}),listeners:(_b=host.listeners)!==null&&_b!==void 0?_b:{},properties:(_c=host.properties)!==null&&_c!==void 0?_c:{},specialAttributes:{classAttr:host.classAttribute,styleAttr:host.styleAttribute}};}function convertOpaqueValuesToExpressions(obj){const result={};for(const key of Object.keys(obj)){result[key]=new WrappedNodeExpr(obj[key]);}return result;}function convertDeclareComponentFacadeToMetadata(decl,typeSourceSpan,sourceMapUrl){var _a,_b,_c,_d;const{template,interpolation}=parseJitTemplate(decl.template,decl.type.name,sourceMapUrl,(_a=decl.preserveWhitespaces)!==null&&_a!==void 0?_a:false,decl.interpolation);const declarations=[];if(decl.dependencies){for(const innerDep of decl.dependencies){switch(innerDep.kind){case'directive':case'component':declarations.push(convertDirectiveDeclarationToMetadata(innerDep));break;case'pipe':declarations.push(convertPipeDeclarationToMetadata(innerDep));break;}}}else if(decl.components||decl.directives||decl.pipes){// Existing declarations on NPM may not be using the new `dependencies` merged field, and may
|
|
3236
|
+
// have separate fields for dependencies instead. Unify them for JIT compilation.
|
|
3237
|
+
decl.components&&declarations.push(...decl.components.map(dir=>convertDirectiveDeclarationToMetadata(dir,/* isComponent */true)));decl.directives&&declarations.push(...decl.directives.map(dir=>convertDirectiveDeclarationToMetadata(dir)));decl.pipes&&declarations.push(...convertPipeMapToMetadata(decl.pipes));}return Object.assign(Object.assign({},convertDeclareDirectiveFacadeToMetadata(decl,typeSourceSpan)),{template,styles:(_b=decl.styles)!==null&&_b!==void 0?_b:[],declarations,viewProviders:decl.viewProviders!==undefined?new WrappedNodeExpr(decl.viewProviders):null,animations:decl.animations!==undefined?new WrappedNodeExpr(decl.animations):null,changeDetection:(_c=decl.changeDetection)!==null&&_c!==void 0?_c:exports.ChangeDetectionStrategy.Default,encapsulation:(_d=decl.encapsulation)!==null&&_d!==void 0?_d:exports.ViewEncapsulation.Emulated,interpolation,declarationListEmitMode:2/* DeclarationListEmitMode.ClosureResolved */,relativeContextFilePath:'',i18nUseExternalIds:true});}function convertDeclarationFacadeToMetadata(declaration){return Object.assign(Object.assign({},declaration),{type:new WrappedNodeExpr(declaration.type)});}function convertDirectiveDeclarationToMetadata(declaration,isComponent=null){var _a,_b,_c;return {kind:exports.R3TemplateDependencyKind.Directive,isComponent:isComponent||declaration.kind==='component',selector:declaration.selector,type:new WrappedNodeExpr(declaration.type),inputs:(_a=declaration.inputs)!==null&&_a!==void 0?_a:[],outputs:(_b=declaration.outputs)!==null&&_b!==void 0?_b:[],exportAs:(_c=declaration.exportAs)!==null&&_c!==void 0?_c:null};}function convertPipeMapToMetadata(pipes){if(!pipes){return [];}return Object.keys(pipes).map(name=>{return {kind:exports.R3TemplateDependencyKind.Pipe,name,type:new WrappedNodeExpr(pipes[name])};});}function convertPipeDeclarationToMetadata(pipe){return {kind:exports.R3TemplateDependencyKind.Pipe,name:pipe.name,type:new WrappedNodeExpr(pipe.type)};}function parseJitTemplate(template,typeName,sourceMapUrl,preserveWhitespaces,interpolation){const interpolationConfig=interpolation?InterpolationConfig.fromArray(interpolation):DEFAULT_INTERPOLATION_CONFIG;// Parse the template and check for errors.
|
|
3172
3238
|
const parsed=parseTemplate(template,sourceMapUrl,{preserveWhitespaces,interpolationConfig});if(parsed.errors!==null){const errors=parsed.errors.map(err=>err.toString()).join(', ');throw new Error(`Errors during JIT compilation of template for ${typeName}: ${errors}`);}return {template:parsed,interpolation:interpolationConfig};}/**
|
|
3173
3239
|
* Convert the expression, if present to an `R3ProviderExpression`.
|
|
3174
3240
|
*
|
|
@@ -3176,8 +3242,8 @@ const parsed=parseTemplate(template,sourceMapUrl,{preserveWhitespaces,interpolat
|
|
|
3176
3242
|
* if it is referencing a type that has not yet been defined, it will have already been wrapped in
|
|
3177
3243
|
* a `forwardRef()` - either by the application developer or during partial-compilation. Thus we can
|
|
3178
3244
|
* use `ForwardRefHandling.None`.
|
|
3179
|
-
*/function convertToProviderExpression(obj,property){if(obj.hasOwnProperty(property)){return createMayBeForwardRefExpression(new WrappedNodeExpr(obj[property]),0/* None */);}else {return undefined;}}function wrapExpression(obj,property){if(obj.hasOwnProperty(property)){return new WrappedNodeExpr(obj[property]);}else {return undefined;}}function computeProvidedIn(providedIn){const expression=typeof providedIn==='function'?new WrappedNodeExpr(providedIn):new LiteralExpr(providedIn!==null&&providedIn!==void 0?providedIn:null);// See `convertToProviderExpression()` for why this uses `ForwardRefHandling.None`.
|
|
3180
|
-
return createMayBeForwardRefExpression(expression,0/* None */);}function convertR3DependencyMetadataArray(facades){return facades==null?null:facades.map(convertR3DependencyMetadata);}function convertR3DependencyMetadata(facade){const isAttributeDep=facade.attribute!=null;// both `null` and `undefined`
|
|
3245
|
+
*/function convertToProviderExpression(obj,property){if(obj.hasOwnProperty(property)){return createMayBeForwardRefExpression(new WrappedNodeExpr(obj[property]),0/* ForwardRefHandling.None */);}else {return undefined;}}function wrapExpression(obj,property){if(obj.hasOwnProperty(property)){return new WrappedNodeExpr(obj[property]);}else {return undefined;}}function computeProvidedIn(providedIn){const expression=typeof providedIn==='function'?new WrappedNodeExpr(providedIn):new LiteralExpr(providedIn!==null&&providedIn!==void 0?providedIn:null);// See `convertToProviderExpression()` for why this uses `ForwardRefHandling.None`.
|
|
3246
|
+
return createMayBeForwardRefExpression(expression,0/* ForwardRefHandling.None */);}function convertR3DependencyMetadataArray(facades){return facades==null?null:facades.map(convertR3DependencyMetadata);}function convertR3DependencyMetadata(facade){const isAttributeDep=facade.attribute!=null;// both `null` and `undefined`
|
|
3181
3247
|
const rawToken=facade.token===null?null:new WrappedNodeExpr(facade.token);// In JIT mode, if the dep is an `@Attribute()` then we use the attribute name given in
|
|
3182
3248
|
// `attribute` rather than the `token`.
|
|
3183
3249
|
const token=isAttributeDep?new WrappedNodeExpr(facade.attribute):rawToken;return createR3DependencyMetadata(token,isAttributeDep,facade.host,facade.optional,facade.self,facade.skipSelf);}function convertR3DeclareDependencyMetadata(facade){var _a,_b,_c,_d,_e;const isAttributeDep=(_a=facade.attribute)!==null&&_a!==void 0?_a:false;const token=facade.token===null?null:new WrappedNodeExpr(facade.token);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);}function createR3DependencyMetadata(token,isAttributeDep,host,optional,self,skipSelf){// If the dep is an `@Attribute()` the `attributeNameType` ought to be the `unknown` type.
|
|
@@ -3189,13 +3255,13 @@ const errors=verifyHostBindings(bindings,sourceSpan);if(errors.length){throw new
|
|
|
3189
3255
|
for(const field in propMetadata){if(propMetadata.hasOwnProperty(field)){propMetadata[field].forEach(ann=>{if(isHostBinding(ann)){// Since this is a decorator, we know that the value is a class member. Always access it
|
|
3190
3256
|
// through `this` so that further down the line it can't be confused for a literal value
|
|
3191
3257
|
// (e.g. if there's a property called `true`).
|
|
3192
|
-
bindings.properties[ann.hostPropertyName||field]=getSafePropertyAccessString('this',field);}else if(isHostListener(ann)){bindings.listeners[ann.eventName||field]=`${field}(${(ann.args||[]).join(',')})`;}});}}return bindings;}function isHostBinding(value){return value.ngMetadataName==='HostBinding';}function isHostListener(value){return value.ngMetadataName==='HostListener';}function isInput(value){return value.ngMetadataName==='Input';}function isOutput(value){return value.ngMetadataName==='Output';}function parseInputOutputs(values){return values.reduce((map,value)=>{const[field,property]=value.split(',').map(piece=>piece.trim());map[field]=property||field;return map;},{});}function convertDeclarePipeFacadeToMetadata(declaration){var _a;return {name:declaration.type.name,type:wrapReference(declaration.type),internalType:new WrappedNodeExpr(declaration.type),typeArgumentCount:0,pipeName:declaration.name,deps:null,pure:(_a=declaration.pure)!==null&&_a!==void 0?_a:true};}function convertDeclareInjectorFacadeToMetadata(declaration){return {name:declaration.type.name,type:wrapReference(declaration.type),internalType:new WrappedNodeExpr(declaration.type),providers:declaration.providers!==undefined?new WrappedNodeExpr(declaration.providers):null,imports:declaration.imports!==undefined?declaration.imports.map(i=>new WrappedNodeExpr(i)):[]};}function publishFacade(global){const ng=global.ng||(global.ng={});ng.ɵcompilerFacade=new CompilerFacadeImpl();}/**
|
|
3258
|
+
bindings.properties[ann.hostPropertyName||field]=getSafePropertyAccessString('this',field);}else if(isHostListener(ann)){bindings.listeners[ann.eventName||field]=`${field}(${(ann.args||[]).join(',')})`;}});}}return bindings;}function isHostBinding(value){return value.ngMetadataName==='HostBinding';}function isHostListener(value){return value.ngMetadataName==='HostListener';}function isInput(value){return value.ngMetadataName==='Input';}function isOutput(value){return value.ngMetadataName==='Output';}function parseInputOutputs(values){return values.reduce((map,value)=>{const[field,property]=value.split(',').map(piece=>piece.trim());map[field]=property||field;return map;},{});}function convertDeclarePipeFacadeToMetadata(declaration){var _a,_b;return {name:declaration.type.name,type:wrapReference(declaration.type),internalType:new WrappedNodeExpr(declaration.type),typeArgumentCount:0,pipeName:declaration.name,deps:null,pure:(_a=declaration.pure)!==null&&_a!==void 0?_a:true,isStandalone:(_b=declaration.isStandalone)!==null&&_b!==void 0?_b:false};}function convertDeclareInjectorFacadeToMetadata(declaration){return {name:declaration.type.name,type:wrapReference(declaration.type),internalType:new WrappedNodeExpr(declaration.type),providers:declaration.providers!==undefined?new WrappedNodeExpr(declaration.providers):null,imports:declaration.imports!==undefined?declaration.imports.map(i=>new WrappedNodeExpr(i)):[]};}function publishFacade(global){const ng=global.ng||(global.ng={});ng.ɵcompilerFacade=new CompilerFacadeImpl();}/**
|
|
3193
3259
|
* @license
|
|
3194
3260
|
* Copyright Google LLC All Rights Reserved.
|
|
3195
3261
|
*
|
|
3196
3262
|
* Use of this source code is governed by an MIT-style license that can be
|
|
3197
3263
|
* found in the LICENSE file at https://angular.io/license
|
|
3198
|
-
*/const VERSION=new Version('
|
|
3264
|
+
*/const VERSION=new Version('14.0.0-rc.2');/**
|
|
3199
3265
|
* @license
|
|
3200
3266
|
* Copyright Google LLC All Rights Reserved.
|
|
3201
3267
|
*
|
|
@@ -3544,7 +3610,7 @@ const fnCall=importExpr(Identifiers.setClassMetadata).callFn([metadata.type,meta
|
|
|
3544
3610
|
* declaration.
|
|
3545
3611
|
*
|
|
3546
3612
|
* Do not include any prerelease in these versions as they are ignored.
|
|
3547
|
-
*/const MINIMUM_PARTIAL_LINKER_VERSION$6='12.0.0';function compileDeclareClassMetadata(metadata){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION$6));definitionMap.set('version',literal('
|
|
3613
|
+
*/const MINIMUM_PARTIAL_LINKER_VERSION$6='12.0.0';function compileDeclareClassMetadata(metadata){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION$6));definitionMap.set('version',literal('14.0.0-rc.2'));definitionMap.set('ngImport',importExpr(Identifiers.core));definitionMap.set('type',metadata.type);definitionMap.set('decorators',metadata.decorators);definitionMap.set('ctorParameters',metadata.ctorParameters);definitionMap.set('propDecorators',metadata.propDecorators);return importExpr(Identifiers.declareClassMetadata).callFn([definitionMap.toLiteralMap()]);}/**
|
|
3548
3614
|
* @license
|
|
3549
3615
|
* Copyright Google LLC All Rights Reserved.
|
|
3550
3616
|
*
|
|
@@ -3580,13 +3646,13 @@ return literal('invalid');}else if(deps===null){return literal(null);}else {retu
|
|
|
3580
3646
|
* declaration.
|
|
3581
3647
|
*
|
|
3582
3648
|
* Do not include any prerelease in these versions as they are ignored.
|
|
3583
|
-
*/const MINIMUM_PARTIAL_LINKER_VERSION$5='
|
|
3649
|
+
*/const MINIMUM_PARTIAL_LINKER_VERSION$5='14.0.0';/**
|
|
3584
3650
|
* Compile a directive declaration defined by the `R3DirectiveMetadata`.
|
|
3585
3651
|
*/function compileDeclareDirectiveFromMetadata(meta){const definitionMap=createDirectiveDefinitionMap(meta);const expression=importExpr(Identifiers.declareDirective).callFn([definitionMap.toLiteralMap()]);const type=createDirectiveType(meta);return {expression,type,statements:[]};}/**
|
|
3586
3652
|
* Gathers the declaration fields for a directive into a `DefinitionMap`. This allows for reusing
|
|
3587
3653
|
* this logic for components, as they extend the directive metadata.
|
|
3588
|
-
*/function createDirectiveDefinitionMap(meta){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION$5));definitionMap.set('version',literal('
|
|
3589
|
-
definitionMap.set('type',meta.internalType)
|
|
3654
|
+
*/function createDirectiveDefinitionMap(meta){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION$5));definitionMap.set('version',literal('14.0.0-rc.2'));// e.g. `type: MyDirective`
|
|
3655
|
+
definitionMap.set('type',meta.internalType);if(meta.isStandalone){definitionMap.set('isStandalone',literal(meta.isStandalone));}// e.g. `selector: 'some-dir'`
|
|
3590
3656
|
if(meta.selector!==null){definitionMap.set('selector',literal(meta.selector));}definitionMap.set('inputs',conditionallyCreateMapObjectLiteral(meta.inputs,true));definitionMap.set('outputs',conditionallyCreateMapObjectLiteral(meta.outputs));definitionMap.set('host',compileHostMetadata(meta.host));definitionMap.set('providers',meta.providers);if(meta.queries.length>0){definitionMap.set('queries',literalArr(meta.queries.map(compileQuery)));}if(meta.viewQueries.length>0){definitionMap.set('viewQueries',literalArr(meta.viewQueries.map(compileQuery)));}if(meta.exportAs!==null){definitionMap.set('exportAs',asLiteral(meta.exportAs));}if(meta.usesInheritance){definitionMap.set('usesInheritance',literal(true));}if(meta.lifecycle.usesOnChanges){definitionMap.set('usesOnChanges',literal(true));}definitionMap.set('ngImport',importExpr(Identifiers.core));return definitionMap;}/**
|
|
3591
3657
|
* Compiles the metadata of a single query into its partial declaration form as declared
|
|
3592
3658
|
* by `R3DeclareQueryMetadata`.
|
|
@@ -3605,7 +3671,7 @@ meta.set('emitDistinctChangesOnly',literal(false));}if(query.descendants){meta.s
|
|
|
3605
3671
|
* Compile a component declaration defined by the `R3ComponentMetadata`.
|
|
3606
3672
|
*/function compileDeclareComponentFromMetadata(meta,template,additionalTemplateInfo){const definitionMap=createComponentDefinitionMap(meta,template,additionalTemplateInfo);const expression=importExpr(Identifiers.declareComponent).callFn([definitionMap.toLiteralMap()]);const type=createComponentType(meta);return {expression,type,statements:[]};}/**
|
|
3607
3673
|
* Gathers the declaration fields for a component into a `DefinitionMap`.
|
|
3608
|
-
*/function createComponentDefinitionMap(meta,template,templateInfo){const definitionMap=createDirectiveDefinitionMap(meta);definitionMap.set('template',getTemplateExpression(template,templateInfo));if(templateInfo.isInline){definitionMap.set('isInline',literal(true));}definitionMap.set('styles',toOptionalLiteralArray(meta.styles,literal));definitionMap.set('
|
|
3674
|
+
*/function createComponentDefinitionMap(meta,template,templateInfo){const definitionMap=createDirectiveDefinitionMap(meta);definitionMap.set('template',getTemplateExpression(template,templateInfo));if(templateInfo.isInline){definitionMap.set('isInline',literal(true));}definitionMap.set('styles',toOptionalLiteralArray(meta.styles,literal));definitionMap.set('dependencies',compileUsedDependenciesMetadata(meta));definitionMap.set('viewProviders',meta.viewProviders);definitionMap.set('animations',meta.animations);if(meta.changeDetection!==undefined){definitionMap.set('changeDetection',importExpr(Identifiers.ChangeDetectionStrategy).prop(exports.ChangeDetectionStrategy[meta.changeDetection]));}if(meta.encapsulation!==exports.ViewEncapsulation.Emulated){definitionMap.set('encapsulation',importExpr(Identifiers.ViewEncapsulation).prop(exports.ViewEncapsulation[meta.encapsulation]));}if(meta.interpolation!==DEFAULT_INTERPOLATION_CONFIG){definitionMap.set('interpolation',literalArr([literal(meta.interpolation.start),literal(meta.interpolation.end)]));}if(template.preserveWhitespaces===true){definitionMap.set('preserveWhitespaces',literal(true));}return definitionMap;}function getTemplateExpression(template,templateInfo){// If the template has been defined using a direct literal, we use that expression directly
|
|
3609
3675
|
// without any modifications. This is ensures proper source mapping from the partially
|
|
3610
3676
|
// compiled code to the source file declaring the template. Note that this does not capture
|
|
3611
3677
|
// template literals referenced indirectly through an identifier.
|
|
@@ -3615,14 +3681,7 @@ if(templateInfo.inlineTemplateLiteralExpression!==null){return templateInfo.inli
|
|
|
3615
3681
|
// to be defined as a literal in the declaration.
|
|
3616
3682
|
if(templateInfo.isInline){return literal(templateInfo.content,null,null);}// The template is external so we must synthesize an expression node with
|
|
3617
3683
|
// the appropriate source-span.
|
|
3618
|
-
const contents=templateInfo.content;const file=new ParseSourceFile(contents,templateInfo.sourceUrl);const start=new ParseLocation(file,0,0,0);const end=computeEndLocation(file,contents);const span=new ParseSourceSpan(start,end);return literal(contents,null,span);}function computeEndLocation(file,contents){const length=contents.length;let lineStart=0;let lastLineStart=0;let line=0;do{lineStart=contents.indexOf('\n',lastLineStart);if(lineStart!==-1){lastLineStart=lineStart+1;line++;}}while(lineStart!==-1);return new ParseLocation(file,length,line,length-lastLineStart);}/**
|
|
3619
|
-
* Compiles the directives as registered in the component metadata into an array literal of the
|
|
3620
|
-
* individual directives. If the component does not use any directives, then null is returned.
|
|
3621
|
-
*/function compileUsedDirectiveMetadata(meta,predicate){const wrapType=meta.declarationListEmitMode!==0/* Direct */?generateForwardRef:expr=>expr;const directives=meta.directives.filter(predicate);return toOptionalLiteralArray(directives,directive=>{const dirMeta=new DefinitionMap();dirMeta.set('type',wrapType(directive.type));dirMeta.set('selector',literal(directive.selector));dirMeta.set('inputs',toOptionalLiteralArray(directive.inputs,literal));dirMeta.set('outputs',toOptionalLiteralArray(directive.outputs,literal));dirMeta.set('exportAs',toOptionalLiteralArray(directive.exportAs,literal));return dirMeta.toLiteralMap();});}/**
|
|
3622
|
-
* Compiles the pipes as registered in the component metadata into an object literal, where the
|
|
3623
|
-
* pipe's name is used as key and a reference to its type as value. If the component does not use
|
|
3624
|
-
* any pipes, then null is returned.
|
|
3625
|
-
*/function compileUsedPipeMetadata(meta){if(meta.pipes.size===0){return null;}const wrapType=meta.declarationListEmitMode!==0/* Direct */?generateForwardRef:expr=>expr;const entries=[];for(const[name,pipe]of meta.pipes){entries.push({key:name,value:wrapType(pipe),quoted:true});}return literalMap(entries);}/**
|
|
3684
|
+
const contents=templateInfo.content;const file=new ParseSourceFile(contents,templateInfo.sourceUrl);const start=new ParseLocation(file,0,0,0);const end=computeEndLocation(file,contents);const span=new ParseSourceSpan(start,end);return literal(contents,null,span);}function computeEndLocation(file,contents){const length=contents.length;let lineStart=0;let lastLineStart=0;let line=0;do{lineStart=contents.indexOf('\n',lastLineStart);if(lineStart!==-1){lastLineStart=lineStart+1;line++;}}while(lineStart!==-1);return new ParseLocation(file,length,line,length-lastLineStart);}function compileUsedDependenciesMetadata(meta){const wrapType=meta.declarationListEmitMode!==0/* DeclarationListEmitMode.Direct */?generateForwardRef:expr=>expr;return toOptionalLiteralArray(meta.declarations,decl=>{switch(decl.kind){case exports.R3TemplateDependencyKind.Directive:const dirMeta=new DefinitionMap();dirMeta.set('kind',literal(decl.isComponent?'component':'directive'));dirMeta.set('type',wrapType(decl.type));dirMeta.set('selector',literal(decl.selector));dirMeta.set('inputs',toOptionalLiteralArray(decl.inputs,literal));dirMeta.set('outputs',toOptionalLiteralArray(decl.outputs,literal));dirMeta.set('exportAs',toOptionalLiteralArray(decl.exportAs,literal));return dirMeta.toLiteralMap();case exports.R3TemplateDependencyKind.Pipe:const pipeMeta=new DefinitionMap();pipeMeta.set('kind',literal('pipe'));pipeMeta.set('type',wrapType(decl.type));pipeMeta.set('name',literal(decl.name));return pipeMeta.toLiteralMap();case exports.R3TemplateDependencyKind.NgModule:const ngModuleMeta=new DefinitionMap();ngModuleMeta.set('kind',literal('ngmodule'));ngModuleMeta.set('type',wrapType(decl.type));return ngModuleMeta.toLiteralMap();}});}/**
|
|
3626
3685
|
* @license
|
|
3627
3686
|
* Copyright Google LLC All Rights Reserved.
|
|
3628
3687
|
*
|
|
@@ -3634,7 +3693,7 @@ const contents=templateInfo.content;const file=new ParseSourceFile(contents,temp
|
|
|
3634
3693
|
* declaration.
|
|
3635
3694
|
*
|
|
3636
3695
|
* Do not include any prerelease in these versions as they are ignored.
|
|
3637
|
-
*/const MINIMUM_PARTIAL_LINKER_VERSION$4='12.0.0';function compileDeclareFactoryFunction(meta){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION$4));definitionMap.set('version',literal('
|
|
3696
|
+
*/const MINIMUM_PARTIAL_LINKER_VERSION$4='12.0.0';function compileDeclareFactoryFunction(meta){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION$4));definitionMap.set('version',literal('14.0.0-rc.2'));definitionMap.set('ngImport',importExpr(Identifiers.core));definitionMap.set('type',meta.internalType);definitionMap.set('deps',compileDependencies(meta.deps));definitionMap.set('target',importExpr(Identifiers.FactoryTarget).prop(exports.FactoryTarget[meta.target]));return {expression:importExpr(Identifiers.declareFactory).callFn([definitionMap.toLiteralMap()]),statements:[],type:createFactoryType(meta)};}/**
|
|
3638
3697
|
* @license
|
|
3639
3698
|
* Copyright Google LLC All Rights Reserved.
|
|
3640
3699
|
*
|
|
@@ -3650,7 +3709,7 @@ const contents=templateInfo.content;const file=new ParseSourceFile(contents,temp
|
|
|
3650
3709
|
* Compile a Injectable declaration defined by the `R3InjectableMetadata`.
|
|
3651
3710
|
*/function compileDeclareInjectableFromMetadata(meta){const definitionMap=createInjectableDefinitionMap(meta);const expression=importExpr(Identifiers.declareInjectable).callFn([definitionMap.toLiteralMap()]);const type=createInjectableType(meta);return {expression,type,statements:[]};}/**
|
|
3652
3711
|
* Gathers the declaration fields for a Injectable into a `DefinitionMap`.
|
|
3653
|
-
*/function createInjectableDefinitionMap(meta){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION$3));definitionMap.set('version',literal('
|
|
3712
|
+
*/function createInjectableDefinitionMap(meta){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION$3));definitionMap.set('version',literal('14.0.0-rc.2'));definitionMap.set('ngImport',importExpr(Identifiers.core));definitionMap.set('type',meta.internalType);// Only generate providedIn property if it has a non-null value
|
|
3654
3713
|
if(meta.providedIn!==undefined){const providedIn=convertFromMaybeForwardRefExpression(meta.providedIn);if(providedIn.value!==null){definitionMap.set('providedIn',providedIn);}}if(meta.useClass!==undefined){definitionMap.set('useClass',convertFromMaybeForwardRefExpression(meta.useClass));}if(meta.useExisting!==undefined){definitionMap.set('useExisting',convertFromMaybeForwardRefExpression(meta.useExisting));}if(meta.useValue!==undefined){definitionMap.set('useValue',convertFromMaybeForwardRefExpression(meta.useValue));}// Factories do not contain `ForwardRef`s since any types are already wrapped in a function call
|
|
3655
3714
|
// so the types will not be eagerly evaluated. Therefore we do not need to process this expression
|
|
3656
3715
|
// with `convertFromProviderExpression()`.
|
|
@@ -3668,7 +3727,7 @@ if(meta.useFactory!==undefined){definitionMap.set('useFactory',meta.useFactory);
|
|
|
3668
3727
|
* Do not include any prerelease in these versions as they are ignored.
|
|
3669
3728
|
*/const MINIMUM_PARTIAL_LINKER_VERSION$2='12.0.0';function compileDeclareInjectorFromMetadata(meta){const definitionMap=createInjectorDefinitionMap(meta);const expression=importExpr(Identifiers.declareInjector).callFn([definitionMap.toLiteralMap()]);const type=createInjectorType(meta);return {expression,type,statements:[]};}/**
|
|
3670
3729
|
* Gathers the declaration fields for an Injector into a `DefinitionMap`.
|
|
3671
|
-
*/function createInjectorDefinitionMap(meta){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION$2));definitionMap.set('version',literal('
|
|
3730
|
+
*/function createInjectorDefinitionMap(meta){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION$2));definitionMap.set('version',literal('14.0.0-rc.2'));definitionMap.set('ngImport',importExpr(Identifiers.core));definitionMap.set('type',meta.internalType);definitionMap.set('providers',meta.providers);if(meta.imports.length>0){definitionMap.set('imports',literalArr(meta.imports));}return definitionMap;}/**
|
|
3672
3731
|
* @license
|
|
3673
3732
|
* Copyright Google LLC All Rights Reserved.
|
|
3674
3733
|
*
|
|
@@ -3680,9 +3739,9 @@ if(meta.useFactory!==undefined){definitionMap.set('useFactory',meta.useFactory);
|
|
|
3680
3739
|
* declaration.
|
|
3681
3740
|
*
|
|
3682
3741
|
* Do not include any prerelease in these versions as they are ignored.
|
|
3683
|
-
*/const MINIMUM_PARTIAL_LINKER_VERSION$1='
|
|
3742
|
+
*/const MINIMUM_PARTIAL_LINKER_VERSION$1='14.0.0';function compileDeclareNgModuleFromMetadata(meta){const definitionMap=createNgModuleDefinitionMap(meta);const expression=importExpr(Identifiers.declareNgModule).callFn([definitionMap.toLiteralMap()]);const type=createNgModuleType(meta);return {expression,type,statements:[]};}/**
|
|
3684
3743
|
* Gathers the declaration fields for an NgModule into a `DefinitionMap`.
|
|
3685
|
-
*/function createNgModuleDefinitionMap(meta){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION$1));definitionMap.set('version',literal('
|
|
3744
|
+
*/function createNgModuleDefinitionMap(meta){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION$1));definitionMap.set('version',literal('14.0.0-rc.2'));definitionMap.set('ngImport',importExpr(Identifiers.core));definitionMap.set('type',meta.internalType);// We only generate the keys in the metadata if the arrays contain values.
|
|
3686
3745
|
// We must wrap the arrays inside a function if any of the values are a forward reference to a
|
|
3687
3746
|
// not-yet-declared class. This is to support JIT execution of the `ɵɵngDeclareNgModule()` call.
|
|
3688
3747
|
// In the linker these wrappers are stripped and then reapplied for the `ɵɵdefineNgModule()` call.
|
|
@@ -3698,12 +3757,12 @@ if(meta.bootstrap.length>0){definitionMap.set('bootstrap',refsToArray(meta.boots
|
|
|
3698
3757
|
* declaration.
|
|
3699
3758
|
*
|
|
3700
3759
|
* Do not include any prerelease in these versions as they are ignored.
|
|
3701
|
-
*/const MINIMUM_PARTIAL_LINKER_VERSION='
|
|
3760
|
+
*/const MINIMUM_PARTIAL_LINKER_VERSION='14.0.0';/**
|
|
3702
3761
|
* Compile a Pipe declaration defined by the `R3PipeMetadata`.
|
|
3703
3762
|
*/function compileDeclarePipeFromMetadata(meta){const definitionMap=createPipeDefinitionMap(meta);const expression=importExpr(Identifiers.declarePipe).callFn([definitionMap.toLiteralMap()]);const type=createPipeType(meta);return {expression,type,statements:[]};}/**
|
|
3704
3763
|
* Gathers the declaration fields for a Pipe into a `DefinitionMap`.
|
|
3705
|
-
*/function createPipeDefinitionMap(meta){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION));definitionMap.set('version',literal('
|
|
3706
|
-
definitionMap.set('type',meta.internalType)
|
|
3764
|
+
*/function createPipeDefinitionMap(meta){const definitionMap=new DefinitionMap();definitionMap.set('minVersion',literal(MINIMUM_PARTIAL_LINKER_VERSION));definitionMap.set('version',literal('14.0.0-rc.2'));definitionMap.set('ngImport',importExpr(Identifiers.core));// e.g. `type: MyPipe`
|
|
3765
|
+
definitionMap.set('type',meta.internalType);if(meta.isStandalone){definitionMap.set('isStandalone',literal(meta.isStandalone));}// e.g. `name: "myPipe"`
|
|
3707
3766
|
definitionMap.set('name',literal(meta.pipeName));if(meta.pure===false){// e.g. `pure: false`
|
|
3708
3767
|
definitionMap.set('pure',literal(meta.pure));}return definitionMap;}/**
|
|
3709
3768
|
* @license
|
|
@@ -3807,7 +3866,6 @@ exports.ParserError = ParserError;
|
|
|
3807
3866
|
exports.PrefixNot = PrefixNot;
|
|
3808
3867
|
exports.PropertyRead = PropertyRead;
|
|
3809
3868
|
exports.PropertyWrite = PropertyWrite;
|
|
3810
|
-
exports.Quote = Quote;
|
|
3811
3869
|
exports.R3BoundTarget = R3BoundTarget;
|
|
3812
3870
|
exports.R3Identifiers = Identifiers;
|
|
3813
3871
|
exports.R3TargetBinder = R3TargetBinder;
|