22
33import { dirRE } from './parser/index'
44
5- const keywordRE = new RegExp ( '\\b' + (
6- 'do,if,in,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
7- 'super,throw,while,yield,delete,export,import,return,switch,typeof,default,' +
8- 'extends,finally,continue,debugger,function,arguments,instanceof'
5+ // operators like typeof, instanceof and in are allowed
6+ const prohibitedKeywordRE = new RegExp ( '\\b' + (
7+ 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
8+ 'super,throw,while,yield,delete,export,import,return,switch,default,' +
9+ 'extends,finally,continue,debugger,function,arguments'
910) . split ( ',' ) . join ( '\\b|\\b' ) + '\\b' )
11+ // check valid identifier for v-for
12+ const identRE = / [ ^ \w $ \. ] (?: [ A - Z a - z _ $ ] [ \w $ ] * ) /
1013
1114// detect problematic expressions in a template
1215export function detectErrors ( ast : ?ASTNode ) : Array < string > {
@@ -23,7 +26,11 @@ function checkNode (node: ASTNode, errors: Array<string>) {
2326 if ( dirRE . test ( name ) ) {
2427 const value = node . attrsMap [ name ]
2528 if ( value ) {
26- checkExpression ( value , `${ name } ="${ value } "` , errors )
29+ if ( name === 'v-for' ) {
30+ checkFor ( node , `v-for="${ value } "` , errors )
31+ } else {
32+ checkExpression ( value , `${ name } ="${ value } "` , errors )
33+ }
2734 }
2835 }
2936 }
@@ -37,17 +44,30 @@ function checkNode (node: ASTNode, errors: Array<string>) {
3744 }
3845}
3946
47+ function checkFor ( node : ASTElement , text : string , errors : Array < string > ) {
48+ checkExpression ( node . for || '' , text , errors )
49+ checkIdentifier ( node . alias , 'v-for alias' , text , errors )
50+ checkIdentifier ( node . iterator1 , 'v-for iterator' , text , errors )
51+ checkIdentifier ( node . iterator2 , 'v-for iterator' , text , errors )
52+ }
53+
54+ function checkIdentifier ( ident : ?string , type : string , text : string , errors : Array < string > ) {
55+ if ( typeof ident === 'string' && ! identRE . test ( ident ) ) {
56+ errors . push ( `- invalid ${ type } "${ ident } " in expression: ${ text } ` )
57+ }
58+ }
59+
4060function checkExpression ( exp : string , text : string , errors : Array < string > ) {
4161 exp = stripToString ( exp )
42- const keywordMatch = exp . match ( keywordRE )
62+ const keywordMatch = exp . match ( prohibitedKeywordRE )
4363 if ( keywordMatch ) {
4464 errors . push (
4565 `- avoid using JavaScript keyword as property name: ` +
4666 `"${ keywordMatch [ 0 ] } " in expression ${ text } `
4767 )
4868 } else {
4969 try {
50- new Function ( exp )
70+ new Function ( `return ${ exp } ` )
5171 } catch ( e ) {
5272 errors . push ( `- invalid expression: ${ text } ` )
5373 }
0 commit comments