|
| 1 | +import * as Lint from 'tslint'; |
| 2 | +import ts from 'typescript'; |
| 3 | +import minimatch from 'minimatch'; |
| 4 | + |
| 5 | +/** |
| 6 | + * NgZone properties that are ok to access. |
| 7 | + */ |
| 8 | +const allowedNgZoneProperties = new Set<string>(['run', 'runOutsideAngular']); |
| 9 | + |
| 10 | +/** Rule to prevent adding code that depends on using zones. */ |
| 11 | +export class Rule extends Lint.Rules.TypedRule { |
| 12 | + applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] { |
| 13 | + return this.applyWithWalker( |
| 14 | + new Walker(sourceFile, this.getOptions(), program.getTypeChecker()), |
| 15 | + ); |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +class Walker extends Lint.RuleWalker { |
| 20 | + /** Whether the walker should check the current source file. */ |
| 21 | + private _enabled: boolean; |
| 22 | + |
| 23 | + constructor( |
| 24 | + sourceFile: ts.SourceFile, |
| 25 | + options: Lint.IOptions, |
| 26 | + private _typeChecker: ts.TypeChecker, |
| 27 | + ) { |
| 28 | + super(sourceFile, options); |
| 29 | + |
| 30 | + // Globs that are used to determine which files to lint. |
| 31 | + const fileGlobs: string[] = options.ruleArguments[0]; |
| 32 | + |
| 33 | + // Whether the file should be checked at all. |
| 34 | + this._enabled = !fileGlobs.some(p => minimatch(sourceFile.fileName, p)); |
| 35 | + } |
| 36 | + |
| 37 | + override visitPropertyAccessExpression(node: ts.PropertyAccessExpression) { |
| 38 | + if (!this._enabled) { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + const classType = this._typeChecker.getTypeAtLocation(node.expression); |
| 43 | + const className = classType.symbol && classType.symbol.name; |
| 44 | + const propertyName = node.name.text; |
| 45 | + |
| 46 | + if (className === 'NgZone' && !allowedNgZoneProperties.has(propertyName)) { |
| 47 | + this.addFailureAtNode(node, `Using NgZone.${propertyName} is not allowed.`); |
| 48 | + } |
| 49 | + |
| 50 | + return super.visitPropertyAccessExpression(node); |
| 51 | + } |
| 52 | +} |
0 commit comments