|
| 1 | +import * as ts from 'typescript'; |
| 2 | +import { Replacement, RuleFailure, Rules } from 'tslint'; |
| 3 | +import { tsquery } from '@phenomnomnominal/tsquery'; |
| 4 | + |
| 5 | +const IS_COMPONENT_PROPERTY_QUERY = |
| 6 | + 'CallExpression:has(Identifier[name="render"]) > ObjectLiteralExpression:first-child'; |
| 7 | +const RENDER_OPTIONS_QUERY = 'CallExpression:has(Identifier[name="render"]) > ObjectLiteralExpression:last-child'; |
| 8 | +const COMPONENT_PARAMETERS_PROPERTY_VALUE_QUERY = 'PropertyAssignment:has(Identifier[name="parameters"]) :last-child'; |
| 9 | + |
| 10 | +const FAILURE_MESSAGE = 'Found `parameters` parameter, use `componentProperties` instead.'; |
| 11 | + |
| 12 | +export class Rule extends Rules.AbstractRule { |
| 13 | + public apply(ast: ts.SourceFile): Array<RuleFailure> { |
| 14 | + return tsquery(ast, IS_COMPONENT_PROPERTY_QUERY) |
| 15 | + .map(result => { |
| 16 | + const [parameterNode] = tsquery(result, COMPONENT_PARAMETERS_PROPERTY_VALUE_QUERY); |
| 17 | + if (!parameterNode) { |
| 18 | + return []; |
| 19 | + } |
| 20 | + const [renderOptionsNode] = tsquery(ast, RENDER_OPTIONS_QUERY); |
| 21 | + |
| 22 | + const renderOptionsText = renderOptionsNode.getFullText(); |
| 23 | + const bracketIndex = renderOptionsText.indexOf('{'); |
| 24 | + const renderOptions = |
| 25 | + renderOptionsText.substring(0, bracketIndex + 1) + |
| 26 | + `componentProperties:${parameterNode.getFullText()},` + |
| 27 | + renderOptionsText.substr(bracketIndex + 1); |
| 28 | + |
| 29 | + const replacement = new Replacement(renderOptionsNode.getStart(), renderOptionsNode.getWidth(), renderOptions); |
| 30 | + const start = renderOptionsNode.getStart(); |
| 31 | + const end = renderOptionsNode.getEnd(); |
| 32 | + |
| 33 | + const replacementOriginal = new Replacement(parameterNode.getStart(), parameterNode.getWidth(), ''); |
| 34 | + const startOriginal = renderOptionsNode.getStart(); |
| 35 | + const endOriginal = renderOptionsNode.getEnd(); |
| 36 | + |
| 37 | + return [ |
| 38 | + new RuleFailure(ast, startOriginal, endOriginal, FAILURE_MESSAGE, this.ruleName, replacementOriginal), |
| 39 | + new RuleFailure(ast, start, end, FAILURE_MESSAGE, this.ruleName, replacement), |
| 40 | + ]; |
| 41 | + }) |
| 42 | + .reduce((rules, rule) => rules.concat(rule), []); |
| 43 | + } |
| 44 | +} |
0 commit comments