/
validationHelpers.ts
182 lines (168 loc) · 5.36 KB
/
validationHelpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import { simpleTraverse } from '@typescript-eslint/typescript-estree';
import type { TSESTree } from '@typescript-eslint/utils';
import type { Parser, SourceCode } from '@typescript-eslint/utils/ts-eslint';
/*
* List every parameters possible on a test case that are not related to eslint
* configuration
*/
export const RULE_TESTER_PARAMETERS = [
'code',
'defaultFilenames',
'dependencyConstraints',
'errors',
'filename',
'name',
'only',
'options',
'output',
'skip',
] as const;
/*
* All allowed property names in error objects.
*/
export const ERROR_OBJECT_PARAMETERS: ReadonlySet<string> = new Set([
'column',
'data',
'endColumn',
'endLine',
'line',
'message',
'messageId',
'suggestions',
'type',
]);
export const FRIENDLY_ERROR_OBJECT_PARAMETER_LIST = `[${[
...ERROR_OBJECT_PARAMETERS,
]
.map(key => `'${key}'`)
.join(', ')}]`;
/*
* All allowed property names in suggestion objects.
*/
export const SUGGESTION_OBJECT_PARAMETERS: ReadonlySet<string> = new Set([
'data',
'desc',
'messageId',
'output',
]);
export const FRIENDLY_SUGGESTION_OBJECT_PARAMETER_LIST = `[${[
...SUGGESTION_OBJECT_PARAMETERS,
]
.map(key => `'${key}'`)
.join(', ')}]`;
/**
* Replace control characters by `\u00xx` form.
*/
export function sanitize(text: string): string {
if (typeof text !== 'string') {
return '';
}
return text.replace(
// eslint-disable-next-line no-control-regex
/[\u0000-\u0009\u000b-\u001a]/gu,
c => `\\u${c.codePointAt(0)!.toString(16).padStart(4, '0')}`,
);
}
// this symbol is used internally by ESLint to unwrap the wrapped parser
// https://github.com/eslint/eslint/blob/129e252132c7c476d7de17f40b54a333ddb2e6bb/lib/linter/linter.js#L139-L146
const parserSymbol = Symbol.for('eslint.RuleTester.parser');
/**
* Wraps the given parser in order to intercept and modify return values from the `parse` and `parseForESLint` methods, for test purposes.
* In particular, to modify ast nodes, tokens and comments to throw on access to their `start` and `end` properties.
*/
export function wrapParser(parser: Parser.ParserModule): Parser.ParserModule {
/**
* Define `start`/`end` properties of all nodes of the given AST as throwing error.
*/
function defineStartEndAsErrorInTree(
ast: TSESTree.Program,
visitorKeys?: Readonly<SourceCode.VisitorKeys>,
): void {
/**
* Define `start`/`end` properties as throwing error.
*/
function defineStartEndAsError(objName: string, node: unknown): void {
Object.defineProperties(node, {
start: {
get() {
throw new Error(
`Use ${objName}.range[0] instead of ${objName}.start`,
);
},
configurable: true,
enumerable: false,
},
end: {
get() {
throw new Error(
`Use ${objName}.range[1] instead of ${objName}.end`,
);
},
configurable: true,
enumerable: false,
},
});
}
simpleTraverse(ast, {
visitorKeys: visitorKeys,
enter: node => defineStartEndAsError('node', node),
});
ast.tokens?.forEach(token => defineStartEndAsError('token', token));
ast.comments?.forEach(comment => defineStartEndAsError('token', comment));
}
if ('parseForESLint' in parser) {
return {
// @ts-expect-error -- see above
[parserSymbol]: parser,
parseForESLint(...args): Parser.ParseResult {
const ret = parser.parseForESLint(...args);
defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys);
return ret;
},
};
}
return {
// @ts-expect-error -- see above
[parserSymbol]: parser,
parse(...args): TSESTree.Program {
const ast = parser.parse(...args);
defineStartEndAsErrorInTree(ast);
return ast;
},
};
}
/**
* Function to replace `SourceCode.prototype.getComments`.
*/
export function getCommentsDeprecation(): never {
throw new Error(
'`SourceCode#getComments()` is deprecated and will be removed in a future major version. Use `getCommentsBefore()`, `getCommentsAfter()`, and `getCommentsInside()` instead.',
);
}
const EMIT_LEGACY_RULE_API_WARNING: Record<string, boolean> = {};
/**
* Emit a deprecation warning if function-style format is being used.
*/
export function emitLegacyRuleAPIWarning(ruleName: string): void {
if (!EMIT_LEGACY_RULE_API_WARNING[`warned-${ruleName}`]) {
EMIT_LEGACY_RULE_API_WARNING[`warned-${ruleName}`] = true;
process.emitWarning(
`"${ruleName}" rule is using the deprecated function-style format and will stop working in ESLint v9. Please use object-style format: https://eslint.org/docs/latest/extend/custom-rules`,
'DeprecationWarning',
);
}
}
const EMIT_MISSING_SCHEMA_WARNING: Record<string, boolean> = {};
/**
* Emit a deprecation warning if rule has options but is missing the "meta.schema" property
*/
export function emitMissingSchemaWarning(ruleName: string): void {
if (!EMIT_MISSING_SCHEMA_WARNING[`warned-${ruleName}`]) {
EMIT_MISSING_SCHEMA_WARNING[`warned-${ruleName}`] = true;
process.emitWarning(
`"${ruleName}" rule has options but is missing the "meta.schema" property and will stop working in ESLint v9. Please add a schema: https://eslint.org/docs/latest/extend/custom-rules#options-schemas`,
'DeprecationWarning',
);
}
}
export const REQUIRED_SCENARIOS = ['valid', 'invalid'] as const;