From 1df69cb4d2f6ae23c7c534156d292a5d29fbd649 Mon Sep 17 00:00:00 2001 From: Victor Berchet Date: Tue, 23 Aug 2016 10:52:40 -0700 Subject: [PATCH] fix(DomSchemaRegistry): detect invalid elements --- .../common/test/directives/ng_for_spec.ts | 12 +- .../common/test/directives/ng_if_spec.ts | 52 ++-- .../directives/ng_template_outlet_spec.ts | 41 +-- .../src/schema/dom_element_schema_registry.ts | 244 ++++++++++-------- .../src/schema/element_schema_registry.ts | 1 + modules/@angular/compiler/src/selector.ts | 6 +- .../src/template_parser/template_parser.ts | 125 ++++++--- .../dom_element_schema_registry_spec.ts | 17 +- .../compiler/test/schema/schema_extractor.ts | 237 +++++++++++------ .../template_parser/template_parser_spec.ts | 23 +- .../compiler/testing/schema_registry_mock.ts | 20 +- .../compiler/testing/test_bindings.ts | 2 +- .../@angular/core/src/metadata/ng_module.ts | 18 +- .../core/test/debug/debug_node_spec.ts | 7 +- .../core/test/forward_ref_integration_spec.ts | 4 +- .../core/test/linker/integration_spec.ts | 86 ++++-- .../linker/projection_integration_spec.ts | 13 +- .../@angular/core/test/metadata/di_spec.ts | 11 +- .../@angular/router/test/integration.spec.ts | 8 +- modules/@angular/upgrade/test/upgrade_spec.ts | 90 ++++--- .../playground/src/routing/app/inbox-app.html | 4 +- modules/playground/src/routing/css/app.css | 12 +- 22 files changed, 638 insertions(+), 395 deletions(-) diff --git a/modules/@angular/common/test/directives/ng_for_spec.ts b/modules/@angular/common/test/directives/ng_for_spec.ts index c9997388e0..8064f5952f 100644 --- a/modules/@angular/common/test/directives/ng_for_spec.ts +++ b/modules/@angular/common/test/directives/ng_for_spec.ts @@ -19,7 +19,7 @@ let thisArg: any; export function main() { describe('ngFor', () => { const TEMPLATE = - '
{{item.toString()}};
'; + '
{{item.toString()}};
'; beforeEach(() => { TestBed.configureTestingModule( @@ -218,7 +218,7 @@ export function main() { it('should display indices correctly', async(() => { const template = - '
{{i.toString()}}
'; + '
{{i.toString()}}
'; TestBed.overrideComponent(TestComponent, {set: {template: template}}); let fixture = TestBed.createComponent(TestComponent); @@ -233,7 +233,7 @@ export function main() { it('should display first item correctly', async(() => { const template = - '
{{isFirst.toString()}}
'; + '
{{isFirst.toString()}}
'; TestBed.overrideComponent(TestComponent, {set: {template: template}}); let fixture = TestBed.createComponent(TestComponent); @@ -248,7 +248,7 @@ export function main() { it('should display last item correctly', async(() => { const template = - '
{{isLast.toString()}}
'; + '
{{isLast.toString()}}
'; TestBed.overrideComponent(TestComponent, {set: {template: template}}); let fixture = TestBed.createComponent(TestComponent); @@ -263,7 +263,7 @@ export function main() { it('should display even items correctly', async(() => { const template = - '
{{isEven.toString()}}
'; + '
{{isEven.toString()}}
'; TestBed.overrideComponent(TestComponent, {set: {template: template}}); let fixture = TestBed.createComponent(TestComponent); @@ -278,7 +278,7 @@ export function main() { it('should display odd items correctly', async(() => { const template = - '
{{isOdd.toString()}}
'; + '
{{isOdd.toString()}}
'; TestBed.overrideComponent(TestComponent, {set: {template: template}}); let fixture = TestBed.createComponent(TestComponent); diff --git a/modules/@angular/common/test/directives/ng_if_spec.ts b/modules/@angular/common/test/directives/ng_if_spec.ts index 79b5b2428a..9df2a71dc9 100644 --- a/modules/@angular/common/test/directives/ng_if_spec.ts +++ b/modules/@angular/common/test/directives/ng_if_spec.ts @@ -20,149 +20,149 @@ export function main() { }); it('should work in a template attribute', async(() => { - const template = '
hello
'; + const template = '
hello
'; TestBed.overrideComponent(TestComponent, {set: {template: template}}); let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(1); expect(fixture.debugElement.nativeElement).toHaveText('hello'); })); it('should work in a template element', async(() => { const template = - '
'; + '
'; TestBed.overrideComponent(TestComponent, {set: {template: template}}); let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(1); expect(fixture.debugElement.nativeElement).toHaveText('hello2'); })); it('should toggle node when condition changes', async(() => { - const template = '
hello
'; + const template = '
hello
'; TestBed.overrideComponent(TestComponent, {set: {template: template}}); let fixture = TestBed.createComponent(TestComponent); fixture.debugElement.componentInstance.booleanCondition = false; fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(0); expect(fixture.debugElement.nativeElement).toHaveText(''); fixture.debugElement.componentInstance.booleanCondition = true; fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(1); expect(fixture.debugElement.nativeElement).toHaveText('hello'); fixture.debugElement.componentInstance.booleanCondition = false; fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(0); expect(fixture.debugElement.nativeElement).toHaveText(''); })); it('should handle nested if correctly', async(() => { const template = - '
'; + '
'; TestBed.overrideComponent(TestComponent, {set: {template: template}}); let fixture = TestBed.createComponent(TestComponent); fixture.debugElement.componentInstance.booleanCondition = false; fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(0); expect(fixture.debugElement.nativeElement).toHaveText(''); fixture.debugElement.componentInstance.booleanCondition = true; fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(1); expect(fixture.debugElement.nativeElement).toHaveText('hello'); fixture.debugElement.componentInstance.nestedBooleanCondition = false; fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(0); expect(fixture.debugElement.nativeElement).toHaveText(''); fixture.debugElement.componentInstance.nestedBooleanCondition = true; fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(1); expect(fixture.debugElement.nativeElement).toHaveText('hello'); fixture.debugElement.componentInstance.booleanCondition = false; fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(0); expect(fixture.debugElement.nativeElement).toHaveText(''); })); it('should update several nodes with if', async(() => { const template = '
' + - 'helloNumber' + - 'helloString' + - 'helloFunction' + + 'helloNumber' + + 'helloString' + + 'helloFunction' + '
'; TestBed.overrideComponent(TestComponent, {set: {template: template}}); let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(3); expect(getDOM().getText(fixture.debugElement.nativeElement)) .toEqual('helloNumberhelloStringhelloFunction'); fixture.debugElement.componentInstance.numberCondition = 0; fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(1); expect(fixture.debugElement.nativeElement).toHaveText('helloString'); fixture.debugElement.componentInstance.numberCondition = 1; fixture.debugElement.componentInstance.stringCondition = 'bar'; fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(1); expect(fixture.debugElement.nativeElement).toHaveText('helloNumber'); })); it('should not add the element twice if the condition goes from true to true (JS)', async(() => { - const template = '
hello
'; + const template = '
hello
'; TestBed.overrideComponent(TestComponent, {set: {template: template}}); let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(1); expect(fixture.debugElement.nativeElement).toHaveText('hello'); fixture.debugElement.componentInstance.numberCondition = 2; fixture.detectChanges(); - expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length) + expect(getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'span').length) .toEqual(1); expect(fixture.debugElement.nativeElement).toHaveText('hello'); })); it('should not recreate the element if the condition goes from true to true (JS)', async(() => { - const template = '
hello
'; + const template = '
hello
'; TestBed.overrideComponent(TestComponent, {set: {template: template}}); let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); getDOM().addClass( - getDOM().querySelector(fixture.debugElement.nativeElement, 'copy-me'), 'foo'); + getDOM().querySelector(fixture.debugElement.nativeElement, 'span'), 'foo'); fixture.debugElement.componentInstance.numberCondition = 2; fixture.detectChanges(); expect(getDOM().hasClass( - getDOM().querySelector(fixture.debugElement.nativeElement, 'copy-me'), 'foo')) + getDOM().querySelector(fixture.debugElement.nativeElement, 'span'), 'foo')) .toBe(true); })); }); diff --git a/modules/@angular/common/test/directives/ng_template_outlet_spec.ts b/modules/@angular/common/test/directives/ng_template_outlet_spec.ts index f38eb9c8be..a5a8f17d25 100644 --- a/modules/@angular/common/test/directives/ng_template_outlet_spec.ts +++ b/modules/@angular/common/test/directives/ng_template_outlet_spec.ts @@ -7,7 +7,7 @@ */ import {CommonModule} from '@angular/common'; -import {Component, ContentChildren, Directive, QueryList, TemplateRef} from '@angular/core'; +import {Component, ContentChildren, Directive, NO_ERRORS_SCHEMA, QueryList, TemplateRef} from '@angular/core'; import {TestBed, async} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/matchers'; @@ -20,7 +20,7 @@ export function main() { }); it('should do nothing if templateRef is null', async(() => { - var template = ``; + const template = ``; TestBed.overrideComponent(TestComponent, {set: {template: template}}); let fixture = TestBed.createComponent(TestComponent); @@ -29,9 +29,11 @@ export function main() { })); it('should insert content specified by TemplateRef', async(() => { - var template = + const template = ``; - TestBed.overrideComponent(TestComponent, {set: {template: template}}); + TestBed.overrideComponent(TestComponent, {set: {template: template}}) + .configureTestingModule({schemas: [NO_ERRORS_SCHEMA]}); + let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); @@ -45,9 +47,10 @@ export function main() { })); it('should clear content if TemplateRef becomes null', async(() => { - var template = + const template = ``; - TestBed.overrideComponent(TestComponent, {set: {template: template}}); + TestBed.overrideComponent(TestComponent, {set: {template: template}}) + .configureTestingModule({schemas: [NO_ERRORS_SCHEMA]}); let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); @@ -63,9 +66,10 @@ export function main() { })); it('should swap content if TemplateRef changes', async(() => { - var template = + const template = ``; - TestBed.overrideComponent(TestComponent, {set: {template: template}}); + TestBed.overrideComponent(TestComponent, {set: {template: template}}) + .configureTestingModule({schemas: [NO_ERRORS_SCHEMA]}); let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); @@ -81,9 +85,10 @@ export function main() { })); it('should display template if context is null', async(() => { - var template = + const template = ``; - TestBed.overrideComponent(TestComponent, {set: {template: template}}); + TestBed.overrideComponent(TestComponent, {set: {template: template}}) + .configureTestingModule({schemas: [NO_ERRORS_SCHEMA]}); let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); @@ -97,9 +102,10 @@ export function main() { })); it('should reflect initial context and changes', async(() => { - var template = + const template = ``; - TestBed.overrideComponent(TestComponent, {set: {template: template}}); + TestBed.overrideComponent(TestComponent, {set: {template: template}}) + .configureTestingModule({schemas: [NO_ERRORS_SCHEMA]}); let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); @@ -116,9 +122,10 @@ export function main() { })); it('should reflect user defined $implicit property in the context', async(() => { - var template = + const template = ``; - TestBed.overrideComponent(TestComponent, {set: {template: template}}); + TestBed.overrideComponent(TestComponent, {set: {template: template}}) + .configureTestingModule({schemas: [NO_ERRORS_SCHEMA]}); let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); @@ -131,9 +138,11 @@ export function main() { })); it('should reflect context re-binding', async(() => { - var template = + const template = ``; - TestBed.overrideComponent(TestComponent, {set: {template: template}}); + TestBed.overrideComponent(TestComponent, {set: {template: template}}) + .configureTestingModule({schemas: [NO_ERRORS_SCHEMA]}); + let fixture = TestBed.createComponent(TestComponent); fixture.detectChanges(); diff --git a/modules/@angular/compiler/src/schema/dom_element_schema_registry.ts b/modules/@angular/compiler/src/schema/dom_element_schema_registry.ts index 97982ead63..3c64a61a80 100644 --- a/modules/@angular/compiler/src/schema/dom_element_schema_registry.ts +++ b/modules/@angular/compiler/src/schema/dom_element_schema_registry.ts @@ -8,13 +8,9 @@ import {CUSTOM_ELEMENTS_SCHEMA, Injectable, NO_ERRORS_SCHEMA, SchemaMetadata, SecurityContext} from '@angular/core'; -import {StringMapWrapper} from '../facade/collection'; -import {isPresent} from '../facade/lang'; - import {SECURITY_SCHEMA} from './dom_security_schema'; import {ElementSchemaRegistry} from './element_schema_registry'; -const EVENT = 'event'; const BOOLEAN = 'boolean'; const NUMBER = 'number'; const STRING = 'string'; @@ -26,7 +22,7 @@ const OBJECT = 'object'; * ## Overview * * Each line represents one kind of element. The `element_inheritance` and properties are joined - * using `element_inheritance|preperties` syntax. + * using `element_inheritance|properties` syntax. * * ## Element Inheritance * @@ -54,7 +50,7 @@ const OBJECT = 'object'; * * ## Query * - * The class creates an internal squas representaino which allows to easily answer the query of + * The class creates an internal squas representation which allows to easily answer the query of * if a given property exist on a given element. * * NOTE: We don't yet support querying for types or events. @@ -77,9 +73,9 @@ const OBJECT = 'object'; const SCHEMA: string[] = ([ '*|textContent,%classList,className,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*copy,*cut,*paste,*search,*selectstart,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerHTML,#scrollLeft,#scrollTop', - '^*|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*autocomplete,*autocompleteerror,*beforecopy,*beforecut,*beforepaste,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*message,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*paste,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*search,*seeked,*seeking,*select,*selectstart,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate', - 'media|!autoplay,!controls,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,#playbackRate,preload,src,#volume', - ':svg:^*|*abort,*autocomplete,*autocompleteerror,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,%style,#tabIndex', + 'abbr,address,article,aside,b,bdi,bdo,cite,code,dd,dfn,dt,em,figcaption,figure,footer,header,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr^*|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*beforecopy,*beforecut,*beforepaste,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*message,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*paste,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*search,*seeked,*seeking,*select,*selectstart,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate', + 'media^abbr|!autoplay,!controls,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,#playbackRate,preload,src,%srcObject,#volume', + ':svg:^abbr|*abort,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,%style,#tabIndex', ':svg:graphics^:svg:|', ':svg:animation^:svg:|*begin,*end,*repeat', ':svg:geometry^:svg:|', @@ -87,74 +83,75 @@ const SCHEMA: string[] = ([ ':svg:gradient^:svg:|', ':svg:textContent^:svg:graphics|', ':svg:textPositioning^:svg:textContent|', - 'a|charset,coords,download,hash,host,hostname,href,hreflang,name,password,pathname,ping,port,protocol,referrerpolicy,rel,rev,search,shape,target,text,type,username', - 'area|alt,coords,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerpolicy,search,shape,target,username', + 'abbr^*|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*beforecopy,*beforecut,*beforepaste,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*copy,*cuechange,*cut,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*message,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*paste,*pause,*play,*playing,*progress,*ratechange,*reset,*resize,*scroll,*search,*seeked,*seeking,*select,*selectstart,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerText,!spellcheck,%style,#tabIndex,title,!translate', + 'a^abbr|charset,coords,download,hash,host,hostname,href,hreflang,name,password,pathname,ping,port,protocol,referrerPolicy,rel,rev,search,shape,target,text,type,username', + 'area^abbr|alt,coords,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,search,shape,target,username', 'audio^media|', - 'br|clear', - 'base|href,target', - 'body|aLink,background,bgColor,link,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,text,vLink', - 'button|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value', - 'canvas|#height,#width', - 'content|select', - 'dl|!compact', - 'datalist|', - 'details|!open', - 'dialog|!open,returnValue', - 'dir|!compact', - 'div|align', - 'embed|align,height,name,src,type,width', - 'fieldset|!disabled,name', - 'font|color,face,size', - 'form|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target', - 'frame|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src', - 'frameset|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows', - 'hr|align,color,!noShade,size,width', - 'head|', - 'h1,h2,h3,h4,h5,h6|align', - 'html|version', - 'iframe|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerpolicy,%sandbox,scrolling,src,srcdoc,width', - 'img|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerpolicy,sizes,src,srcset,useMap,#vspace,#width', - 'input|accept,align,alt,autocapitalize,autocomplete,!autofocus,!checked,!defaultChecked,defaultValue,dirName,!disabled,%files,formAction,formEnctype,formMethod,!formNoValidate,formTarget,#height,!incremental,!indeterminate,max,#maxLength,min,#minLength,!multiple,name,pattern,placeholder,!readOnly,!required,selectionDirection,#selectionEnd,#selectionStart,#size,src,step,type,useMap,value,%valueAsDate,#valueAsNumber,#width', - 'keygen|!autofocus,challenge,!disabled,keytype,name', - 'li|type,#value', - 'label|htmlFor', - 'legend|align', - 'link|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,rel,%relList,rev,%sizes,target,type', - 'map|name', - 'marquee|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width', - 'menu|!compact', - 'meta|content,httpEquiv,name,scheme', - 'meter|#high,#low,#max,#min,#optimum,#value', - 'ins,del|cite,dateTime', - 'ol|!compact,!reversed,#start,type', - 'object|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width', - 'optgroup|!disabled,label', - 'option|!defaultSelected,!disabled,label,!selected,text,value', - 'output|defaultValue,%htmlFor,name,value', - 'p|align', - 'param|name,type,value,valueType', - 'picture|', - 'pre|#width', - 'progress|#max,#value', - 'q,blockquote,cite|', - 'script|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type', - 'select|!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value', - 'shadow|', - 'source|media,sizes,src,srcset,type', - 'span|', - 'style|!disabled,media,type', - 'caption|align', - 'th,td|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width', - 'col,colgroup|align,ch,chOff,#span,vAlign,width', - 'table|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width', - 'tr|align,bgColor,ch,chOff,vAlign', - 'tfoot,thead,tbody|align,ch,chOff,vAlign', - 'template|', - 'textarea|autocapitalize,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap', - 'title|text', - 'track|!default,kind,label,src,srclang', - 'ul|!compact,type', - 'unknown|', + 'br^abbr|clear', + 'base^abbr|href,target', + 'body^abbr|aLink,background,bgColor,link,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,text,vLink', + 'button^abbr|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value', + 'canvas^abbr|#height,#width', + 'content^abbr|select', + 'dl^abbr|!compact', + 'datalist^abbr|', + 'details^abbr|!open', + 'dialog^abbr|!open,returnValue', + 'dir^abbr|!compact', + 'div^abbr|align', + 'embed^abbr|align,height,name,src,type,width', + 'fieldset^abbr|!disabled,name', + 'font^abbr|color,face,size', + 'form^abbr|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target', + 'frame^abbr|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src', + 'frameset^abbr|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows', + 'hr^abbr|align,color,!noShade,size,width', + 'head^abbr|', + 'h1,h2,h3,h4,h5,h6^abbr|align', + 'html^abbr|version', + 'iframe^abbr|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width', + 'img^abbr|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width', + 'input^abbr|accept,align,alt,autocapitalize,autocomplete,!autofocus,!checked,!defaultChecked,defaultValue,dirName,!disabled,%files,formAction,formEnctype,formMethod,!formNoValidate,formTarget,#height,!incremental,!indeterminate,max,#maxLength,min,#minLength,!multiple,name,pattern,placeholder,!readOnly,!required,selectionDirection,#selectionEnd,#selectionStart,#size,src,step,type,useMap,value,%valueAsDate,#valueAsNumber,#width', + 'keygen^abbr|!autofocus,challenge,!disabled,keytype,name', + 'li^abbr|type,#value', + 'label^abbr|htmlFor', + 'legend^abbr|align', + 'link^abbr|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,rel,%relList,rev,%sizes,target,type', + 'map^abbr|name', + 'marquee^abbr|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width', + 'menu^abbr|!compact', + 'meta^abbr|content,httpEquiv,name,scheme', + 'meter^abbr|#high,#low,#max,#min,#optimum,#value', + 'ins,del^abbr|cite,dateTime', + 'ol^abbr|!compact,!reversed,#start,type', + 'object^abbr|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width', + 'optgroup^abbr|!disabled,label', + 'option^abbr|!defaultSelected,!disabled,label,!selected,text,value', + 'output^abbr|defaultValue,%htmlFor,name,value', + 'p^abbr|align', + 'param^abbr|name,type,value,valueType', + 'picture^abbr|', + 'pre^abbr|#width', + 'progress^abbr|#max,#value', + 'q,blockquote,cite^abbr|', + 'script^abbr|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type', + 'select^abbr|!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value', + 'shadow^abbr|', + 'source^abbr|media,sizes,src,srcset,type', + 'span^abbr|', + 'style^abbr|!disabled,media,type', + 'caption^abbr|align', + 'th,td^abbr|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width', + 'col,colgroup^abbr|align,ch,chOff,#span,vAlign,width', + 'table^abbr|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width', + 'tr^abbr|align,bgColor,ch,chOff,vAlign', + 'tfoot,thead,tbody^abbr|align,ch,chOff,vAlign', + 'template^abbr|', + 'textarea^abbr|autocapitalize,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap', + 'title^abbr|text', + 'track^abbr|!default,kind,label,src,srclang', + 'ul^abbr|!compact,type', + 'unknown^abbr|', 'video^media|#height,poster,#width', ':svg:a^:svg:graphics|', ':svg:animate^:svg:animation|', @@ -223,7 +220,7 @@ const SCHEMA: string[] = ([ ':svg:view^:svg:|#zoomAndPan', ]); -var attrToPropMap: {[name: string]: string} = { +const _ATTR_TO_PROP: {[name: string]: string} = { 'class': 'className', 'formaction': 'formAction', 'innerHtml': 'innerHTML', @@ -233,37 +230,42 @@ var attrToPropMap: {[name: string]: string} = { @Injectable() export class DomElementSchemaRegistry extends ElementSchemaRegistry { - schema = <{[element: string]: {[property: string]: string}}>{}; + private _schema: {[element: string]: {[property: string]: string}} = {}; constructor() { super(); SCHEMA.forEach(encodedType => { - var parts = encodedType.split('|'); - var properties = parts[1].split(','); - var typeParts = (parts[0] + '^').split('^'); - var typeName = typeParts[0]; - var type = <{[property: string]: string}>{}; - typeName.split(',').forEach(tag => this.schema[tag] = type); - var superType = this.schema[typeParts[1]]; - if (isPresent(superType)) { - StringMapWrapper.forEach( - superType, (v: any /** TODO #9100 */, k: any /** TODO #9100 */) => type[k] = v); + const [strType, strProperties] = encodedType.split('|'); + const properties = strProperties.split(','); + const [typeNames, superName] = strType.split('^'); + const type: {[property: string]: string} = {}; + typeNames.split(',').forEach(tag => this._schema[tag.toLowerCase()] = type); + const superType = this._schema[superName]; + if (superType) { + Object.keys(superType).forEach((prop: string) => { type[prop] = superType[prop]; }); } properties.forEach((property: string) => { - if (property == '') { - } else if (property.startsWith('*')) { - // We don't yet support events. - // If ever allowing to bind to events, GO THROUGH A SECURITY REVIEW, allowing events will - // almost certainly introduce bad XSS vulnerabilities. - // type[property.substring(1)] = EVENT; - } else if (property.startsWith('!')) { - type[property.substring(1)] = BOOLEAN; - } else if (property.startsWith('#')) { - type[property.substring(1)] = NUMBER; - } else if (property.startsWith('%')) { - type[property.substring(1)] = OBJECT; - } else { - type[property] = STRING; + if (property.length > 0) { + switch (property[0]) { + case '*': + // We don't yet support events. + // If ever allowing to bind to events, GO THROUGH A SECURITY REVIEW, allowing events + // will + // almost certainly introduce bad XSS vulnerabilities. + // type[property.substring(1)] = EVENT; + break; + case '!': + type[property.substring(1)] = BOOLEAN; + break; + case '#': + type[property.substring(1)] = NUMBER; + break; + case '%': + type[property.substring(1)] = OBJECT; + break; + default: + type[property] = STRING; + } } }); }); @@ -274,10 +276,11 @@ export class DomElementSchemaRegistry extends ElementSchemaRegistry { return true; } - if (tagName.indexOf('-') !== -1) { + if (tagName.indexOf('-') > -1) { if (tagName === 'ng-container' || tagName === 'ng-content') { return false; } + if (schemaMetas.some((schema) => schema.name === CUSTOM_ELEMENTS_SCHEMA.name)) { // Can't tell now as we don't know which properties a custom element will get // once it is instantiated @@ -285,11 +288,27 @@ export class DomElementSchemaRegistry extends ElementSchemaRegistry { } } - var elementProperties = this.schema[tagName.toLowerCase()]; - if (!isPresent(elementProperties)) { - elementProperties = this.schema['unknown']; + const elementProperties = this._schema[tagName.toLowerCase()] || this._schema['unknown']; + return !!elementProperties[propName]; + } + + hasElement(tagName: string, schemaMetas: SchemaMetadata[]): boolean { + if (schemaMetas.some((schema) => schema.name === NO_ERRORS_SCHEMA.name)) { + return true; } - return isPresent(elementProperties[propName]); + + if (tagName.indexOf('-') > -1) { + if (tagName === 'ng-container' || tagName === 'ng-content') { + return true; + } + + if (schemaMetas.some((schema) => schema.name === CUSTOM_ELEMENTS_SCHEMA.name)) { + // Allow any custom elements + return true; + } + } + + return !!this._schema[tagName.toLowerCase()]; } /** @@ -308,15 +327,14 @@ export class DomElementSchemaRegistry extends ElementSchemaRegistry { tagName = tagName.toLowerCase(); propName = propName.toLowerCase(); let ctx = SECURITY_SCHEMA[tagName + '|' + propName]; - if (ctx !== undefined) return ctx; + if (ctx) { + return ctx; + } ctx = SECURITY_SCHEMA['*|' + propName]; - return ctx !== undefined ? ctx : SecurityContext.NONE; + return ctx ? ctx : SecurityContext.NONE; } - getMappedPropName(propName: string): string { - var mappedPropName = StringMapWrapper.get(attrToPropMap, propName); - return isPresent(mappedPropName) ? mappedPropName : propName; - } + getMappedPropName(propName: string): string { return _ATTR_TO_PROP[propName] || propName; } getDefaultComponentElementName(): string { return 'ng-component'; } } diff --git a/modules/@angular/compiler/src/schema/element_schema_registry.ts b/modules/@angular/compiler/src/schema/element_schema_registry.ts index 88bfa1794d..b16428f9e3 100644 --- a/modules/@angular/compiler/src/schema/element_schema_registry.ts +++ b/modules/@angular/compiler/src/schema/element_schema_registry.ts @@ -10,6 +10,7 @@ import {SchemaMetadata} from '@angular/core'; export abstract class ElementSchemaRegistry { abstract hasProperty(tagName: string, propName: string, schemaMetas: SchemaMetadata[]): boolean; + abstract hasElement(tagName: string, schemaMetas: SchemaMetadata[]): boolean; abstract securityContext(tagName: string, propName: string): any; abstract getMappedPropName(propName: string): string; abstract getDefaultComponentElementName(): string; diff --git a/modules/@angular/compiler/src/selector.ts b/modules/@angular/compiler/src/selector.ts index f64620a2d9..2c323754cb 100644 --- a/modules/@angular/compiler/src/selector.ts +++ b/modules/@angular/compiler/src/selector.ts @@ -81,10 +81,12 @@ export class CssSelector { } isElementSelector(): boolean { - return isPresent(this.element) && ListWrapper.isEmpty(this.classNames) && - ListWrapper.isEmpty(this.attrs) && this.notSelectors.length === 0; + return this.hasElementSelector() && this.classNames.length == 0 && this.attrs.length == 0 && + this.notSelectors.length === 0; } + hasElementSelector(): boolean { return !!this.element; } + setElement(element: string = null) { this.element = element; } /** Gets a template string for an element that matches the selector. */ diff --git a/modules/@angular/compiler/src/template_parser/template_parser.ts b/modules/@angular/compiler/src/template_parser/template_parser.ts index 1c5d9a3b82..c7974a7e18 100644 --- a/modules/@angular/compiler/src/template_parser/template_parser.ts +++ b/modules/@angular/compiler/src/template_parser/template_parser.ts @@ -11,7 +11,7 @@ import {Inject, Injectable, OpaqueToken, Optional, SchemaMetadata, SecurityConte import {CompileDirectiveMetadata, CompilePipeMetadata, CompileTokenMetadata, removeIdentifierDuplicates} from '../compile_metadata'; import {AST, ASTWithSource, BindingPipe, EmptyExpr, Interpolation, ParserError, RecursiveAstVisitor, TemplateBinding} from '../expression_parser/ast'; import {Parser} from '../expression_parser/parser'; -import {ListWrapper, SetWrapper, StringMapWrapper} from '../facade/collection'; +import {StringMapWrapper} from '../facade/collection'; import {isBlank, isPresent, isString} from '../facade/lang'; import {I18NHtmlParser} from '../i18n/i18n_html_parser'; import {Identifiers, identifierToken, resolveIdentifierToken} from '../identifiers'; @@ -32,7 +32,6 @@ import {AttrAst, BoundDirectivePropertyAst, BoundElementPropertyAst, BoundEventA import {PreparsedElementType, preparseElement} from './template_preparser'; - // Group 1 = "bind-" // Group 2 = "let-" // Group 3 = "ref-/#" @@ -102,9 +101,11 @@ export class TemplateParser { const result = this.tryParse(component, template, directives, pipes, schemas, templateUrl); const warnings = result.errors.filter(error => error.level === ParseErrorLevel.WARNING); const errors = result.errors.filter(error => error.level === ParseErrorLevel.FATAL); + if (warnings.length > 0) { this._console.warn(`Template parse warnings:\n${warnings.join('\n')}`); } + if (errors.length > 0) { const errorString = errors.join('\n'); throw new Error(`Template parse errors:\n${errorString}`); @@ -183,36 +184,33 @@ export class TemplateParser { } class TemplateParseVisitor implements html.Visitor { - selectorMatcher: SelectorMatcher; + selectorMatcher = new SelectorMatcher(); errors: TemplateParseError[] = []; directivesIndex = new Map(); ngContentCount: number = 0; - pipesByName: Map; + pipesByName: Map = new Map(); + private _interpolationConfig: InterpolationConfig; constructor( public providerViewContext: ProviderViewContext, directives: CompileDirectiveMetadata[], pipes: CompilePipeMetadata[], private _schemas: SchemaMetadata[], private _exprParser: Parser, private _schemaRegistry: ElementSchemaRegistry) { - this.selectorMatcher = new SelectorMatcher(); - const tempMeta = providerViewContext.component.template; - if (isPresent(tempMeta) && isPresent(tempMeta.interpolation)) { + if (tempMeta && tempMeta.interpolation) { this._interpolationConfig = { start: tempMeta.interpolation[0], end: tempMeta.interpolation[1] }; } - ListWrapper.forEachWithIndex( - directives, (directive: CompileDirectiveMetadata, index: number) => { - const selector = CssSelector.parse(directive.selector); - this.selectorMatcher.addSelectables(selector, directive); - this.directivesIndex.set(directive, index); - }); + directives.forEach((directive: CompileDirectiveMetadata, index: number) => { + const selector = CssSelector.parse(directive.selector); + this.selectorMatcher.addSelectables(selector, directive); + this.directivesIndex.set(directive, index); + }); - this.pipesByName = new Map(); pipes.forEach(pipe => this.pipesByName.set(pipe.name, pipe)); } @@ -222,7 +220,7 @@ class TemplateParseVisitor implements html.Visitor { this.errors.push(new TemplateParseError(message, sourceSpan, level)); } - private _reportParserErors(errors: ParserError[], sourceSpan: ParseSourceSpan) { + private _reportParserErrors(errors: ParserError[], sourceSpan: ParseSourceSpan) { for (const error of errors) { this._reportError(error.message, sourceSpan); } @@ -230,9 +228,10 @@ class TemplateParseVisitor implements html.Visitor { private _parseInterpolation(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); + try { const ast = this._exprParser.parseInterpolation(value, sourceInfo, this._interpolationConfig); - if (ast) this._reportParserErors(ast.errors, sourceSpan); + if (ast) this._reportParserErrors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); if (isPresent(ast) && (ast.ast).expressions.length > MAX_INTERPOLATION_VALUES) { @@ -251,7 +250,7 @@ class TemplateParseVisitor implements html.Visitor { try { const ast = this._exprParser.parseAction(value, sourceInfo, this._interpolationConfig); if (ast) { - this._reportParserErors(ast.errors, sourceSpan); + this._reportParserErrors(ast.errors, sourceSpan); } if (!ast || ast.ast instanceof EmptyExpr) { this._reportError(`Empty expressions are not allowed`, sourceSpan); @@ -267,9 +266,10 @@ class TemplateParseVisitor implements html.Visitor { private _parseBinding(value: string, sourceSpan: ParseSourceSpan): ASTWithSource { const sourceInfo = sourceSpan.start.toString(); + try { const ast = this._exprParser.parseBinding(value, sourceInfo, this._interpolationConfig); - if (ast) this._reportParserErors(ast.errors, sourceSpan); + if (ast) this._reportParserErrors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); return ast; } catch (e) { @@ -280,9 +280,10 @@ class TemplateParseVisitor implements html.Visitor { private _parseTemplateBindings(value: string, sourceSpan: ParseSourceSpan): TemplateBinding[] { const sourceInfo = sourceSpan.start.toString(); + try { const bindingsResult = this._exprParser.parseTemplateBindings(value, sourceInfo); - this._reportParserErors(bindingsResult.errors, sourceSpan); + this._reportParserErrors(bindingsResult.errors, sourceSpan); bindingsResult.templateBindings.forEach((binding) => { if (isPresent(binding.expression)) { this._checkPipes(binding.expression, sourceSpan); @@ -323,7 +324,7 @@ class TemplateParseVisitor implements html.Visitor { } } - visitAttribute(attribute: html.Attribute, contex: any): any { + visitAttribute(attribute: html.Attribute, context: any): any { return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan); } @@ -366,6 +367,7 @@ class TemplateParseVisitor implements html.Visitor { const hasBinding = this._parseAttr( isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, animationProps, events, elementOrDirectiveRefs, elementVars); + const hasTemplateBinding = this._parseInlineTemplateBinding( attr, templateMatchableAttrs, templateElementOrDirectiveProps, templateElementVars); @@ -380,13 +382,15 @@ class TemplateParseVisitor implements html.Visitor { attrs.push(this.visitAttribute(attr, null)); matchableAttrs.push([attr.name, attr.value]); } + if (hasTemplateBinding) { hasInlineTemplates = true; } }); const elementCssSelector = createElementCssSelector(nodeName, matchableAttrs); - const directiveMetas = this._parseDirectives(this.selectorMatcher, elementCssSelector); + const {directives: directiveMetas, matchElement} = + this._parseDirectives(this.selectorMatcher, elementCssSelector); const references: ReferenceAst[] = []; const directiveAsts = this._createDirectiveAsts( isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps, @@ -430,7 +434,9 @@ class TemplateParseVisitor implements html.Visitor { providerContext.transformProviders, providerContext.transformedHasViewContainer, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } else { + this._assertElementExists(matchElement, element); this._assertOnlyOneComponent(directiveAsts, element.sourceSpan); + const ngContentIndex = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector); parsedElement = new ElementAst( @@ -439,10 +445,11 @@ class TemplateParseVisitor implements html.Visitor { providerContext.transformedHasViewContainer, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan); } + if (hasInlineTemplates) { const templateCssSelector = createElementCssSelector(TEMPLATE_ELEMENT, templateMatchableAttrs); - const templateDirectiveMetas = + const {directives: templateDirectiveMetas} = this._parseDirectives(this.selectorMatcher, templateCssSelector); const templateDirectiveAsts = this._createDirectiveAsts( true, element.name, templateDirectiveMetas, templateElementOrDirectiveProps, [], @@ -681,15 +688,23 @@ class TemplateParseVisitor implements html.Visitor { } private _parseDirectives(selectorMatcher: SelectorMatcher, elementCssSelector: CssSelector): - CompileDirectiveMetadata[] { + {directives: CompileDirectiveMetadata[], matchElement: boolean} { // Need to sort the directives so that we get consistent results throughout, // as selectorMatcher uses Maps inside. - // Also dedupe directives as they might match more than one time! - const directives = ListWrapper.createFixedSize(this.directivesIndex.size); + // Also deduplicate directives as they might match more than one time! + const directives = new Array(this.directivesIndex.size); + // Whether any directive selector matches on the element name + let matchElement = false; + selectorMatcher.match(elementCssSelector, (selector, directive) => { directives[this.directivesIndex.get(directive)] = directive; + matchElement = matchElement || selector.hasElementSelector(); }); - return directives.filter(dir => isPresent(dir)); + + return { + directives: directives.filter(dir => !!dir), + matchElement, + }; } private _createDirectiveAsts( @@ -724,12 +739,12 @@ class TemplateParseVisitor implements html.Visitor { }); elementOrDirectiveRefs.forEach((elOrDirRef) => { if (elOrDirRef.value.length > 0) { - if (!SetWrapper.has(matchedReferences, elOrDirRef.name)) { + if (!matchedReferences.has(elOrDirRef.name)) { this._reportError( `There is no directive with "exportAs" set to "${elOrDirRef.value}"`, elOrDirRef.sourceSpan); } - } else if (isBlank(component)) { + } else if (!component) { let refToken: CompileTokenMetadata = null; if (isTemplateElement) { refToken = resolveIdentifierToken(Identifiers.TemplateRef); @@ -743,7 +758,7 @@ class TemplateParseVisitor implements html.Visitor { private _createDirectiveHostPropertyAsts( elementName: string, hostProps: {[key: string]: string}, sourceSpan: ParseSourceSpan, targetPropertyAsts: BoundElementPropertyAst[]) { - if (isPresent(hostProps)) { + if (hostProps) { StringMapWrapper.forEach(hostProps, (expression: string, propName: string) => { if (isString(expression)) { const exprAst = this._parseBinding(expression, sourceSpan); @@ -761,7 +776,7 @@ class TemplateParseVisitor implements html.Visitor { private _createDirectiveHostEventAsts( hostListeners: {[key: string]: string}, sourceSpan: ParseSourceSpan, targetEventAsts: BoundEventAst[]) { - if (isPresent(hostListeners)) { + if (hostListeners) { StringMapWrapper.forEach(hostListeners, (expression: string, propName: string) => { if (isString(expression)) { this._parseEvent(propName, expression, sourceSpan, [], targetEventAsts); @@ -777,7 +792,7 @@ class TemplateParseVisitor implements html.Visitor { private _createDirectivePropertyAsts( directiveProperties: {[key: string]: string}, boundProps: BoundElementOrDirectiveProperty[], targetBoundDirectiveProps: BoundDirectivePropertyAst[]) { - if (isPresent(directiveProperties)) { + if (directiveProperties) { const boundPropsByName = new Map(); boundProps.forEach(boundProp => { const prevValue = boundPropsByName.get(boundProp.name); @@ -791,7 +806,7 @@ class TemplateParseVisitor implements html.Visitor { const boundProp = boundPropsByName.get(elProp); // Bindings are optional, so this binding only needs to be set up if an expression is given. - if (isPresent(boundProp)) { + if (boundProp) { targetBoundDirectiveProps.push(new BoundDirectivePropertyAst( dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan)); } @@ -804,11 +819,13 @@ class TemplateParseVisitor implements html.Visitor { directives: DirectiveAst[]): BoundElementPropertyAst[] { const boundElementProps: BoundElementPropertyAst[] = []; const boundDirectivePropsIndex = new Map(); + directives.forEach((directive: DirectiveAst) => { directive.inputs.forEach((prop: BoundDirectivePropertyAst) => { boundDirectivePropsIndex.set(prop.templateName, prop); }); }); + props.forEach((prop: BoundElementOrDirectiveProperty) => { if (!prop.isLiteral && isBlank(boundDirectivePropsIndex.get(prop.name))) { boundElementProps.push(this._createElementPropertyAst( @@ -826,6 +843,7 @@ class TemplateParseVisitor implements html.Visitor { let boundPropertyName: string; const parts = name.split(PROPERTY_PARTS_SEPARATOR); let securityContext: SecurityContext; + if (parts.length === 1) { var partValue = parts[0]; if (partValue[0] == '@') { @@ -839,7 +857,7 @@ class TemplateParseVisitor implements html.Visitor { if (!this._schemaRegistry.hasProperty(elementName, boundPropertyName, this._schemas)) { let errorMsg = `Can't bind to '${boundPropertyName}' since it isn't a known property of '${elementName}'.`; - if (elementName.indexOf('-') !== -1) { + if (elementName.indexOf('-') > -1) { errorMsg += `\n1. If '${elementName}' is an Angular component and it has '${boundPropertyName}' input, then verify that it is part of this module.` + `\n2. If '${elementName}' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.\n`; @@ -857,12 +875,13 @@ class TemplateParseVisitor implements html.Visitor { sourceSpan); } // NB: For security purposes, use the mapped property name, not the attribute name. - securityContext = this._schemaRegistry.securityContext( - elementName, this._schemaRegistry.getMappedPropName(boundPropertyName)); - let nsSeparatorIdx = boundPropertyName.indexOf(':'); + const mapPropName = this._schemaRegistry.getMappedPropName(boundPropertyName); + securityContext = this._schemaRegistry.securityContext(elementName, mapPropName); + + const nsSeparatorIdx = boundPropertyName.indexOf(':'); if (nsSeparatorIdx > -1) { - let ns = boundPropertyName.substring(0, nsSeparatorIdx); - let name = boundPropertyName.substring(nsSeparatorIdx + 1); + const ns = boundPropertyName.substring(0, nsSeparatorIdx); + const name = boundPropertyName.substring(nsSeparatorIdx + 1); boundPropertyName = mergeNsAndName(ns, name); } @@ -906,6 +925,26 @@ class TemplateParseVisitor implements html.Visitor { } } + /** + * Make sure that non-angular tags conform to the schemas. + * + * Note: An element is considered an angular tag when at least one directive selector matches the + * tag name. + * + * @param matchElement Whether any directive has matched on the tag name + * @param element the html element + */ + private _assertElementExists(matchElement: boolean, element: html.Element) { + const elName = element.name.replace(/^:xhtml:/, ''); + + if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) { + const errorMsg = `'${elName}' is not a known element:\n` + + `1. If '${elName}' is an Angular component, then verify that it is part of this module.\n` + + `2. If '${elName}' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message.`; + this._reportError(errorMsg, element.sourceSpan); + } + } + private _assertNoComponentsNorElementBindingsOnTemplate( directives: DirectiveAst[], elementProps: BoundElementPropertyAst[], sourceSpan: ParseSourceSpan) { @@ -924,13 +963,15 @@ class TemplateParseVisitor implements html.Visitor { private _assertAllEventsPublishedByDirectives( directives: DirectiveAst[], events: BoundEventAst[]) { const allDirectiveEvents = new Set(); + directives.forEach(directive => { StringMapWrapper.forEach(directive.directive.outputs, (eventName: string) => { allDirectiveEvents.add(eventName); }); }); + events.forEach(event => { - if (isPresent(event.target) || !SetWrapper.has(allDirectiveEvents, event.name)) { + if (isPresent(event.target) || !allDirectiveEvents.has(event.name)) { this._reportError( `Event binding ${event.fullName} not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the "directives" section.`, event.sourceSpan); @@ -996,7 +1037,7 @@ class ElementContext { const matcher = new SelectorMatcher(); let wildcardNgContentIndex: number = null; const component = directives.find(directive => directive.directive.isComponent); - if (isPresent(component)) { + if (component) { const ngContentSelectors = component.directive.template.ngContentSelectors; for (let i = 0; i < ngContentSelectors.length; i++) { const selector = ngContentSelectors[i]; @@ -1017,7 +1058,7 @@ class ElementContext { const ngContentIndices: number[] = []; this._ngContentIndexMatcher.match( selector, (selector, ngContentIndex) => { ngContentIndices.push(ngContentIndex); }); - ListWrapper.sort(ngContentIndices); + ngContentIndices.sort(); if (isPresent(this._wildcardNgContentIndex)) { ngContentIndices.push(this._wildcardNgContentIndex); } @@ -1027,7 +1068,7 @@ class ElementContext { function createElementCssSelector(elementName: string, matchableAttrs: string[][]): CssSelector { const cssSelector = new CssSelector(); - let elNameNoNs = splitNsName(elementName)[1]; + const elNameNoNs = splitNsName(elementName)[1]; cssSelector.setElement(elNameNoNs); diff --git a/modules/@angular/compiler/test/schema/dom_element_schema_registry_spec.ts b/modules/@angular/compiler/test/schema/dom_element_schema_registry_spec.ts index 968a391d06..e3bea7f09b 100644 --- a/modules/@angular/compiler/test/schema/dom_element_schema_registry_spec.ts +++ b/modules/@angular/compiler/test/schema/dom_element_schema_registry_spec.ts @@ -21,6 +21,16 @@ export function main() { let registry: DomElementSchemaRegistry; beforeEach(() => { registry = new DomElementSchemaRegistry(); }); + it('should detect elements', () => { + expect(registry.hasElement('div', [])).toBeTruthy(); + expect(registry.hasElement('b', [])).toBeTruthy(); + expect(registry.hasElement('ng-container', [])).toBeTruthy(); + expect(registry.hasElement('ng-content', [])).toBeTruthy(); + + expect(registry.hasElement('my-cmp', [])).toBeFalsy(); + expect(registry.hasElement('abc', [])).toBeFalsy(); + }); + it('should detect properties on regular elements', () => { expect(registry.hasProperty('div', 'id', [])).toBeTruthy(); expect(registry.hasProperty('div', 'title', [])).toBeTruthy(); @@ -37,7 +47,7 @@ export function main() { }); it('should detect different kinds of types', () => { - // inheritance: video => media => * + // inheritance: video => media => HTMLElement expect(registry.hasProperty('video', 'className', [])).toBeTruthy(); // from * expect(registry.hasProperty('video', 'id', [])).toBeTruthy(); // string expect(registry.hasProperty('video', 'scrollLeft', [])).toBeTruthy(); // number @@ -57,11 +67,16 @@ export function main() { it('should return true for custom-like elements if the CUSTOM_ELEMENTS_SCHEMA was used', () => { expect(registry.hasProperty('custom-like', 'unknown', [CUSTOM_ELEMENTS_SCHEMA])).toBeTruthy(); + + expect(registry.hasElement('custom-like', [CUSTOM_ELEMENTS_SCHEMA])).toBeTruthy(); }); it('should return true for all elements if the NO_ERRORS_SCHEMA was used', () => { expect(registry.hasProperty('custom-like', 'unknown', [NO_ERRORS_SCHEMA])).toBeTruthy(); expect(registry.hasProperty('a', 'unknown', [NO_ERRORS_SCHEMA])).toBeTruthy(); + + expect(registry.hasElement('custom-like', [NO_ERRORS_SCHEMA])).toBeTruthy(); + expect(registry.hasElement('unknown', [NO_ERRORS_SCHEMA])).toBeTruthy(); }); it('should re-map property names that are specified in DOM facade', diff --git a/modules/@angular/compiler/test/schema/schema_extractor.ts b/modules/@angular/compiler/test/schema/schema_extractor.ts index 07d79ff75e..d8b1847f14 100644 --- a/modules/@angular/compiler/test/schema/schema_extractor.ts +++ b/modules/@angular/compiler/test/schema/schema_extractor.ts @@ -6,38 +6,43 @@ * found in the LICENSE file at https://angular.io/license */ -import {isPresent, isString} from '../../src/facade/lang'; - const SVG_PREFIX = ':svg:'; +const HTMLELEMENT_NAMES = + 'abbr,address,article,aside,b,bdi,bdo,cite,code,dd,dfn,dt,em,figcaption,figure,footer,header,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr'; +const HTMLELEMENT_NAME = 'abbr'; -var document = typeof(global as any /** TODO #???? */)['document'] == 'object' ? - (global as any /** TODO #???? */)['document'] : - null; +const _G: any = global; +const document: any = typeof _G['document'] == 'object' ? _G['document'] : null; export function extractSchema(): Map { - var SVGGraphicsElement = (global as any /** TODO #???? */)['SVGGraphicsElement']; - var SVGAnimationElement = (global as any /** TODO #???? */)['SVGAnimationElement']; - var SVGGeometryElement = (global as any /** TODO #???? */)['SVGGeometryElement']; - var SVGComponentTransferFunctionElement = - (global as any /** TODO #???? */)['SVGComponentTransferFunctionElement']; - var SVGGradientElement = (global as any /** TODO #???? */)['SVGGradientElement']; - var SVGTextContentElement = (global as any /** TODO #???? */)['SVGTextContentElement']; - var SVGTextPositioningElement = (global as any /** TODO #???? */)['SVGTextPositioningElement']; - if (!document || !SVGGraphicsElement) return null; - var descMap: Map = new Map(); - var visited: {[name: string]: boolean} = {}; - var element = document.createElement('video'); - var svgAnimation = document.createElementNS('http://www.w3.org/2000/svg', 'set'); - var svgPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); - var svgFeFuncA = document.createElementNS('http://www.w3.org/2000/svg', 'feFuncA'); - var svgGradient = document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient'); - var svgText = document.createElementNS('http://www.w3.org/2000/svg', 'text'); + if (!document) return null; + const SVGGraphicsElement = _G['SVGGraphicsElement']; + if (!SVGGraphicsElement) return null; + const SVGAnimationElement = _G['SVGAnimationElement']; + const SVGGeometryElement = _G['SVGGeometryElement']; + const SVGComponentTransferFunctionElement = _G['SVGComponentTransferFunctionElement']; + const SVGGradientElement = _G['SVGGradientElement']; + const SVGTextContentElement = _G['SVGTextContentElement']; + const SVGTextPositioningElement = _G['SVGTextPositioningElement']; + const element = document.createElement('video'); + const svgAnimation = document.createElementNS('http://www.w3.org/2000/svg', 'set'); + const svgPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + const svgFeFuncA = document.createElementNS('http://www.w3.org/2000/svg', 'feFuncA'); + const svgGradient = document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient'); + const svgText = document.createElementNS('http://www.w3.org/2000/svg', 'text'); + + const descMap: Map = new Map(); + let visited: {[name: string]: boolean} = {}; + + // HTML top level extractProperties(Node, element, visited, descMap, '*', ''); extractProperties(Element, element, visited, descMap, '*', ''); - extractProperties(HTMLElement, element, visited, descMap, '', '*'); - extractProperties(HTMLMediaElement, element, visited, descMap, 'media', ''); - extractProperties(SVGElement, svgText, visited, descMap, SVG_PREFIX, '*'); + extractProperties(HTMLElement, element, visited, descMap, HTMLELEMENT_NAMES, '*'); + extractProperties(HTMLMediaElement, element, visited, descMap, 'media', HTMLELEMENT_NAME); + + // SVG top level + extractProperties(SVGElement, svgText, visited, descMap, SVG_PREFIX, HTMLELEMENT_NAME); extractProperties( SVGGraphicsElement, svgText, visited, descMap, SVG_PREFIX + 'graphics', SVG_PREFIX); extractProperties( @@ -55,37 +60,64 @@ export function extractSchema(): Map { extractProperties( SVGTextPositioningElement, svgText, visited, descMap, SVG_PREFIX + 'textPositioning', SVG_PREFIX + 'textContent'); - var keys = Object.keys(window).filter( - k => k.endsWith('Element') && (k.startsWith('HTML') || k.startsWith('SVG'))); - keys.sort(); - keys.forEach( - name => - extractRecursiveProperties(visited, descMap, (window as any /** TODO #???? */)[name])); + + // Get all element types + const types = Object.getOwnPropertyNames(window).filter(k => /^(HTML|SVG).*?Element$/.test(k)); + + types.sort(); + + types.forEach(type => { extractRecursiveProperties(visited, descMap, (window as any)[type]); }); return descMap; } function extractRecursiveProperties( visited: {[name: string]: boolean}, descMap: Map, type: Function): string { - var name = extractName(type); - if (visited[name]) return name; // already been here - var superName = ''; - if (name != '*') { - superName = extractRecursiveProperties(visited, descMap, type.prototype.__proto__.constructor); + const name = extractName(type); + + if (visited[name]) { + return name; } - var instance: HTMLElement = null; + let superName: string; + switch (name) { + case '*': + superName = ''; + break; + case HTMLELEMENT_NAME: + superName = '*'; + break; + default: + superName = + extractRecursiveProperties(visited, descMap, type.prototype.__proto__.constructor); + } + + // If the ancestor is an HTMLElement, use one of the multiple implememtation + superName = superName.split(',')[0]; + + let instance: HTMLElement = null; name.split(',').forEach(tagName => { instance = isSVG(type) ? document.createElementNS('http://www.w3.org/2000/svg', tagName.replace(SVG_PREFIX, '')) : document.createElement(tagName); - var htmlType = type; - if (tagName == 'cite') htmlType = HTMLElement; + + let htmlType: Function; + + switch (tagName) { + case 'cite': + htmlType = HTMLElement; + break; + default: + htmlType = type; + } + if (!(instance instanceof htmlType)) { throw new Error(`Tag <${tagName}> is not an instance of ${htmlType['name']}`); } }); + extractProperties(type, instance, visited, descMap, name, superName); + return name; } @@ -93,21 +125,26 @@ function extractProperties( type: Function, instance: any, visited: {[name: string]: boolean}, descMap: Map, name: string, superName: string) { if (!type) return; + visited[name] = true; + const fullName = name + (superName ? '^' + superName : ''); - let props: string[] = descMap.has(fullName) ? descMap.get(fullName) : []; - var prototype = type.prototype; - var keys = Object.keys(prototype); + + const props: string[] = descMap.has(fullName) ? descMap.get(fullName) : []; + + const prototype = type.prototype; + let keys = Object.getOwnPropertyNames(prototype); + keys.sort(); - keys.forEach((n) => { - if (n.startsWith('on')) { - props.push('*' + n.substr(2)); + keys.forEach((name) => { + if (name.startsWith('on')) { + props.push('*' + name.substr(2)); } else { - var typeCh = typeMap[typeof instance[n]]; - var descriptor = Object.getOwnPropertyDescriptor(prototype, n); - var isSetter = descriptor && isPresent(descriptor.set); - if (isString(typeCh) && !n.startsWith('webkit') && isSetter) { - props.push(typeCh + n); + const typeCh = _TYPE_MNEMONICS[typeof instance[name]]; + const descriptor = Object.getOwnPropertyDescriptor(prototype, name); + const isSetter = descriptor && descriptor.set; + if (typeCh !== void 0 && !name.startsWith('webkit') && isSetter) { + props.push(typeCh + name); } } }); @@ -117,44 +154,76 @@ function extractProperties( } function extractName(type: Function): string { - var name = type['name']; - if (name == 'Element') return '*'; - if (name == 'HTMLImageElement') return 'img'; - if (name == 'HTMLAnchorElement') return 'a'; - if (name == 'HTMLDListElement') return 'dl'; - if (name == 'HTMLDirectoryElement') return 'dir'; - if (name == 'HTMLHeadingElement') return 'h1,h2,h3,h4,h5,h6'; - if (name == 'HTMLModElement') return 'ins,del'; - if (name == 'HTMLOListElement') return 'ol'; - if (name == 'HTMLParagraphElement') return 'p'; - if (name == 'HTMLQuoteElement') return 'q,blockquote,cite'; - if (name == 'HTMLTableCaptionElement') return 'caption'; - if (name == 'HTMLTableCellElement') return 'th,td'; - if (name == 'HTMLTableColElement') return 'col,colgroup'; - if (name == 'HTMLTableRowElement') return 'tr'; - if (name == 'HTMLTableSectionElement') return 'tfoot,thead,tbody'; - if (name == 'HTMLUListElement') return 'ul'; - if (name == 'SVGGraphicsElement') return SVG_PREFIX + 'graphics'; - if (name == 'SVGMPathElement') return SVG_PREFIX + 'mpath'; - if (name == 'SVGSVGElement') return SVG_PREFIX + 'svg'; - if (name == 'SVGTSpanElement') return SVG_PREFIX + 'tspan'; - var isSVG = name.startsWith('SVG'); - if (name.startsWith('HTML') || isSVG) { - name = name.replace('HTML', '').replace('SVG', '').replace('Element', ''); - if (isSVG && name.startsWith('FE')) { - name = 'fe' + name.substring(2); - } else if (name) { - name = name.charAt(0).toLowerCase() + name.substring(1); - } - return isSVG ? SVG_PREFIX + name : name.toLowerCase(); - } else { - return null; + let name = type['name']; + + switch (name) { + // see https://www.w3.org/TR/html5/index.html + // TODO(vicb): generate this map from all the element types + case 'Element': + return '*'; + case 'HTMLElement': + return HTMLELEMENT_NAME; + case 'HTMLImageElement': + return 'img'; + case 'HTMLAnchorElement': + return 'a'; + case 'HTMLDListElement': + return 'dl'; + case 'HTMLDirectoryElement': + return 'dir'; + case 'HTMLHeadingElement': + return 'h1,h2,h3,h4,h5,h6'; + case 'HTMLModElement': + return 'ins,del'; + case 'HTMLOListElement': + return 'ol'; + case 'HTMLParagraphElement': + return 'p'; + case 'HTMLQuoteElement': + return 'q,blockquote,cite'; + case 'HTMLTableCaptionElement': + return 'caption'; + case 'HTMLTableCellElement': + return 'th,td'; + case 'HTMLTableColElement': + return 'col,colgroup'; + case 'HTMLTableRowElement': + return 'tr'; + case 'HTMLTableSectionElement': + return 'tfoot,thead,tbody'; + case 'HTMLUListElement': + return 'ul'; + case 'SVGGraphicsElement': + return SVG_PREFIX + 'graphics'; + case 'SVGMPathElement': + return SVG_PREFIX + 'mpath'; + case 'SVGSVGElement': + return SVG_PREFIX + 'svg'; + case 'SVGTSpanElement': + return SVG_PREFIX + 'tspan'; + default: + const isSVG = name.startsWith('SVG'); + if (name.startsWith('HTML') || isSVG) { + name = name.replace('HTML', '').replace('SVG', '').replace('Element', ''); + if (isSVG && name.startsWith('FE')) { + name = 'fe' + name.substring(2); + } else if (name) { + name = name.charAt(0).toLowerCase() + name.substring(1); + } + return isSVG ? SVG_PREFIX + name : name.toLowerCase(); + } } + + return null; } function isSVG(type: Function): boolean { return type['name'].startsWith('SVG'); } -const typeMap = - <{[type: string]: string}>{'string': '', 'number': '#', 'boolean': '!', 'object': '%'}; +const _TYPE_MNEMONICS: {[type: string]: string} = { + 'string': '', + 'number': '#', + 'boolean': '!', + 'object': '%', +}; \ No newline at end of file diff --git a/modules/@angular/compiler/test/template_parser/template_parser_spec.ts b/modules/@angular/compiler/test/template_parser/template_parser_spec.ts index f4ecdb77b9..bc36e10fc0 100644 --- a/modules/@angular/compiler/test/template_parser/template_parser_spec.ts +++ b/modules/@angular/compiler/test/template_parser/template_parser_spec.ts @@ -22,11 +22,12 @@ import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../../src/ml_pa import {MockSchemaRegistry} from '../../testing/index'; import {unparse} from '../expression_parser/unparser'; -var someModuleUrl = 'package:someModule'; +const someModuleUrl = 'package:someModule'; -var MOCK_SCHEMA_REGISTRY = [{ +const MOCK_SCHEMA_REGISTRY = [{ provide: ElementSchemaRegistry, - useValue: new MockSchemaRegistry({'invalidProp': false}, {'mappedAttr': 'mappedProp'}) + useValue: new MockSchemaRegistry( + {'invalidProp': false}, {'mappedAttr': 'mappedProp'}, {'unknown': false, 'un-known': false}), }]; export function main() { @@ -256,7 +257,7 @@ export function main() { }); describe('errors', () => { - it('should throw error when binding to an unkonown property', () => { + it('should throw error when binding to an unknown property', () => { expect(() => parse('', [])) .toThrowError(`Template parse errors: Can't bind to 'invalidProp' since it isn't a known property of 'my-component'. @@ -264,6 +265,20 @@ Can't bind to 'invalidProp' since it isn't a known property of 'my-component'. 2. If 'my-component' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message. ("][invalidProp]="bar">"): TestComp@0:14`); }); + + it('should throw error when binding to an unknown element w/o bindings', () => { + expect(() => parse('', [])).toThrowError(`Template parse errors: +'unknown' is not a known element: +1. If 'unknown' is an Angular component, then verify that it is part of this module. +2. If 'unknown' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message. ("[ERROR ->]"): TestComp@0:0`); + }); + + it('should throw error when binding to an unknown custom element w/o bindings', () => { + expect(() => parse('', [])).toThrowError(`Template parse errors: +'un-known' is not a known element: +1. If 'un-known' is an Angular component, then verify that it is part of this module. +2. If 'un-known' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message. ("[ERROR ->]"): TestComp@0:0`); + }); }); it('should parse bound properties via [...] and not report them as attributes', () => { diff --git a/modules/@angular/compiler/testing/schema_registry_mock.ts b/modules/@angular/compiler/testing/schema_registry_mock.ts index 7d20e90887..3dc7488a6c 100644 --- a/modules/@angular/compiler/testing/schema_registry_mock.ts +++ b/modules/@angular/compiler/testing/schema_registry_mock.ts @@ -8,27 +8,29 @@ import {ElementSchemaRegistry} from '@angular/compiler'; import {SchemaMetadata, SecurityContext} from '@angular/core'; - -import {isPresent} from './facade/lang'; +import {ElementSchemaRegistry} from '../index'; export class MockSchemaRegistry implements ElementSchemaRegistry { constructor( public existingProperties: {[key: string]: boolean}, - public attrPropMapping: {[key: string]: string}) {} + public attrPropMapping: {[key: string]: string}, + public existingElements: {[key: string]: boolean}) {} hasProperty(tagName: string, property: string, schemas: SchemaMetadata[]): boolean { - var result = this.existingProperties[property]; - return isPresent(result) ? result : true; + const value = this.existingProperties[property]; + return value === void 0 ? true : value; + } + + hasElement(tagName: string, schemaMetas: SchemaMetadata[]): boolean { + const value = this.existingElements[tagName.toLowerCase()]; + return value === void 0 ? true : value; } securityContext(tagName: string, property: string): SecurityContext { return SecurityContext.NONE; } - getMappedPropName(attrName: string): string { - var result = this.attrPropMapping[attrName]; - return isPresent(result) ? result : attrName; - } + getMappedPropName(attrName: string): string { return this.attrPropMapping[attrName] || attrName; } getDefaultComponentElementName(): string { return 'ng-component'; } } diff --git a/modules/@angular/compiler/testing/test_bindings.ts b/modules/@angular/compiler/testing/test_bindings.ts index 33b79ee2b9..6f6ef6974c 100644 --- a/modules/@angular/compiler/testing/test_bindings.ts +++ b/modules/@angular/compiler/testing/test_bindings.ts @@ -19,7 +19,7 @@ export function createUrlResolverWithoutPackagePrefix(): UrlResolver { // internal test packages. // TODO: get rid of it or move to a separate @angular/internal_testing package export var TEST_COMPILER_PROVIDERS: Provider[] = [ - {provide: ElementSchemaRegistry, useValue: new MockSchemaRegistry({}, {})}, + {provide: ElementSchemaRegistry, useValue: new MockSchemaRegistry({}, {}, {})}, {provide: ResourceLoader, useClass: MockResourceLoader}, {provide: UrlResolver, useFactory: createUrlResolverWithoutPackagePrefix} ]; diff --git a/modules/@angular/core/src/metadata/ng_module.ts b/modules/@angular/core/src/metadata/ng_module.ts index df2e7d7404..165e7ceb17 100644 --- a/modules/@angular/core/src/metadata/ng_module.ts +++ b/modules/@angular/core/src/metadata/ng_module.ts @@ -27,8 +27,10 @@ export interface ModuleWithProviders { export interface SchemaMetadata { name: string; } /** - * Defines a schema that will allow any property on elements with a `-` in their name, - * which is the common rule for custom elements. + * Defines a schema that will allow: + * - any non-angular elements with a `-` in their name, + * - any properties on elements with a `-` in their name which is the common rule for custom + * elements. * * @stable */ @@ -161,6 +163,18 @@ export class NgModuleMetadata extends InjectableMetadata implements NgModuleMeta */ bootstrap: Array|any[]>; + /** + * Elements and properties that are not angular Components nor Directives have to be declared in + * the schema. + * + * Available schemas: + * - `NO_ERRORS_SCHEMA`: any elements and properties are allowed, + * - `CUSTOM_ELEMENTS_SCHEMA`: any custom elements (tag name has "-") with any properties are + * allowed. + * + * @security When using one of `NO_ERRORS_SCHEMA` or `CUSTOM_ELEMENTS_SCHEMA` we're trusting that + * allowed elements (and its properties) securely escape inputs. + */ schemas: Array; constructor(options: NgModuleMetadataType = {}) { diff --git a/modules/@angular/core/test/debug/debug_node_spec.ts b/modules/@angular/core/test/debug/debug_node_spec.ts index 02e7adf886..04fb637fbb 100644 --- a/modules/@angular/core/test/debug/debug_node_spec.ts +++ b/modules/@angular/core/test/debug/debug_node_spec.ts @@ -7,7 +7,7 @@ */ import {NgFor, NgIf} from '@angular/common'; -import {Injectable} from '@angular/core'; +import {Injectable, NO_ERRORS_SCHEMA} from '@angular/core'; import {Component, Directive, Input} from '@angular/core/src/metadata'; import {ComponentFixture, TestBed, async} from '@angular/core/testing'; import {By} from '@angular/platform-browser/src/dom/debug/by'; @@ -185,9 +185,8 @@ export function main() { TestApp, UsingFor, ], - providers: [ - Logger, - ] + providers: [Logger], + schemas: [NO_ERRORS_SCHEMA], }); })); diff --git a/modules/@angular/core/test/forward_ref_integration_spec.ts b/modules/@angular/core/test/forward_ref_integration_spec.ts index 97d6c36404..51d137ca18 100644 --- a/modules/@angular/core/test/forward_ref_integration_spec.ts +++ b/modules/@angular/core/test/forward_ref_integration_spec.ts @@ -7,7 +7,7 @@ */ import {CommonModule} from '@angular/common'; -import {Component, ContentChildren, Directive, Inject, NgModule, QueryList, asNativeElements, forwardRef} from '@angular/core'; +import {Component, ContentChildren, Directive, Inject, NO_ERRORS_SCHEMA, NgModule, QueryList, asNativeElements, forwardRef} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {expect} from '@angular/platform-browser/testing/matchers'; @@ -16,7 +16,7 @@ export function main() { beforeEach(() => { TestBed.configureTestingModule({imports: [Module], declarations: [App]}); }); it('should instantiate components which are declared using forwardRef', () => { - const a = TestBed.createComponent(App); + const a = TestBed.configureTestingModule({schemas: [NO_ERRORS_SCHEMA]}).createComponent(App); a.detectChanges(); expect(asNativeElements(a.debugElement.children)).toHaveText('frame(lock)'); expect(TestBed.get(ModuleFrame)).toBeDefined(); diff --git a/modules/@angular/core/test/linker/integration_spec.ts b/modules/@angular/core/test/linker/integration_spec.ts index cd36841e15..a0e795f2ef 100644 --- a/modules/@angular/core/test/linker/integration_spec.ts +++ b/modules/@angular/core/test/linker/integration_spec.ts @@ -7,7 +7,7 @@ */ import {CommonModule} from '@angular/common'; -import {ComponentFactory, Host, Inject, Injectable, Injector, NgModule, OnDestroy, OpaqueToken, ReflectiveInjector, SkipSelf, SkipSelfMetadata, forwardRef} from '@angular/core'; +import {ComponentFactory, Host, Inject, Injectable, Injector, NO_ERRORS_SCHEMA, NgModule, OnDestroy, OpaqueToken, ReflectiveInjector, SkipSelf, SkipSelfMetadata} from '@angular/core'; import {ChangeDetectionStrategy, ChangeDetectorRef, PipeTransform} from '@angular/core/src/change_detection/change_detection'; import {ComponentFactoryResolver} from '@angular/core/src/linker/component_factory_resolver'; import {ElementRef} from '@angular/core/src/linker/element_ref'; @@ -304,7 +304,7 @@ function declareTests({useJit}: {useJit: boolean}) { it('should support template directives via `