@virmator/lint 14.33.0 → 14.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,262 @@
1
+ import {type Rule, type SourceCode} from 'eslint';
2
+ import type {
3
+ ArrowFunctionExpression,
4
+ Identifier,
5
+ Node,
6
+ Property,
7
+ VariableDeclaration,
8
+ VariableDeclarator,
9
+ } from 'estree';
10
+
11
+ type TypescriptArrowFunctionExpression = ArrowFunctionExpression & {
12
+ returnType?: Rule.Node;
13
+ typeParameters?: Rule.Node;
14
+ };
15
+
16
+ type RuleArrowFunctionExpression = TypescriptArrowFunctionExpression & Rule.NodeParentExtension;
17
+
18
+ type IdentifierVariableDeclarator = VariableDeclarator &
19
+ Rule.NodeParentExtension & {
20
+ id: Identifier;
21
+ };
22
+
23
+ type TypescriptIdentifier = Identifier & {
24
+ typeAnnotation?: Rule.Node;
25
+ };
26
+
27
+ function isArrowFunctionExpression(
28
+ node: Readonly<Node>,
29
+ ): node is TypescriptArrowFunctionExpression {
30
+ return node.type === 'ArrowFunctionExpression';
31
+ }
32
+
33
+ function isIdentifierVariableDeclarator(
34
+ node: Readonly<Rule.Node>,
35
+ ): node is IdentifierVariableDeclarator {
36
+ return node.type === 'VariableDeclarator' && node.id.type === 'Identifier';
37
+ }
38
+
39
+ function hasTypeAnnotation({id}: Readonly<{id: Identifier}>) {
40
+ const typescriptId: TypescriptIdentifier = id;
41
+ return typescriptId.typeAnnotation != undefined;
42
+ }
43
+
44
+ function getParameterText({
45
+ node,
46
+ sourceCode,
47
+ }: Readonly<{
48
+ node: RuleArrowFunctionExpression;
49
+ sourceCode: SourceCode;
50
+ }>) {
51
+ const firstParam = node.params.at(0);
52
+ const lastParam = node.params.at(-1);
53
+
54
+ if (!firstParam || !lastParam) {
55
+ return '()';
56
+ }
57
+
58
+ const openParen = sourceCode.getTokenBefore(firstParam);
59
+ const closeParen = sourceCode.getTokenAfter(lastParam);
60
+
61
+ if (openParen?.value === '(' && closeParen?.value === ')') {
62
+ return sourceCode.text.slice(openParen.range[0], closeParen.range[1]);
63
+ } else if (node.params.length > 1) {
64
+ return undefined;
65
+ } else {
66
+ return `(${sourceCode.getText(firstParam)})`;
67
+ }
68
+ }
69
+
70
+ function getFunctionText({
71
+ node,
72
+ name,
73
+ sourceCode,
74
+ useFunctionKeyword,
75
+ }: Readonly<{
76
+ node: RuleArrowFunctionExpression;
77
+ name: string;
78
+ sourceCode: SourceCode;
79
+ useFunctionKeyword: boolean;
80
+ }>) {
81
+ const parameterText = getParameterText({
82
+ node,
83
+ sourceCode,
84
+ });
85
+
86
+ if (!parameterText) {
87
+ return undefined;
88
+ }
89
+
90
+ const typeParameterText = node.typeParameters ? sourceCode.getText(node.typeParameters) : '';
91
+ const returnTypeText = node.returnType ? sourceCode.getText(node.returnType) : '';
92
+ const bodyText =
93
+ node.body.type === 'BlockStatement'
94
+ ? sourceCode.getText(node.body)
95
+ : `{ return ${sourceCode.getText(node.body)}; }`;
96
+ const asyncText = node.async ? 'async ' : '';
97
+ const functionKeywordText = useFunctionKeyword ? 'function ' : '';
98
+
99
+ return `${asyncText}${functionKeywordText}${name}${typeParameterText}${parameterText}${returnTypeText} ${bodyText}`;
100
+ }
101
+
102
+ function isPrototypeSetter({property}: Readonly<{property: Property}>) {
103
+ return (
104
+ !property.computed &&
105
+ ((property.key.type === 'Identifier' && property.key.name === '__proto__') ||
106
+ (property.key.type === 'Literal' && property.key.value === '__proto__'))
107
+ );
108
+ }
109
+
110
+ function getConstVariable({
111
+ node,
112
+ }: Readonly<{
113
+ node: RuleArrowFunctionExpression;
114
+ }>) {
115
+ const declarator = node.parent;
116
+
117
+ if (
118
+ !isIdentifierVariableDeclarator(declarator) ||
119
+ declarator.init !== node ||
120
+ hasTypeAnnotation({
121
+ id: declarator.id,
122
+ })
123
+ ) {
124
+ return undefined;
125
+ }
126
+
127
+ const declaration = declarator.parent;
128
+
129
+ if (declaration.type !== 'VariableDeclaration' || declaration.kind !== 'const') {
130
+ return undefined;
131
+ }
132
+
133
+ return {
134
+ declarator,
135
+ declaration,
136
+ };
137
+ }
138
+
139
+ function canUseFunctionDeclaration({
140
+ declaration,
141
+ }: Readonly<{
142
+ declaration: VariableDeclaration & Rule.NodeParentExtension;
143
+ }>) {
144
+ return (
145
+ declaration.declarations.length === 1 &&
146
+ (declaration.parent.type === 'BlockStatement' ||
147
+ declaration.parent.type === 'ExportNamedDeclaration' ||
148
+ declaration.parent.type === 'Program')
149
+ );
150
+ }
151
+
152
+ const rule: Rule.RuleModule = {
153
+ meta: {
154
+ type: 'suggestion',
155
+ fixable: 'code',
156
+ messages: {
157
+ useFunctionDeclaration:
158
+ 'Use a `function` keyword function instead of storing an arrow function in a `const`.',
159
+ usePropertyMethod:
160
+ 'Use object property method shorthand instead of storing an arrow function in a property.',
161
+ },
162
+ schema: [],
163
+ },
164
+ create(context) {
165
+ const sourceCode = context.sourceCode;
166
+ const arrowsThatCaptureThis = new Set<TypescriptArrowFunctionExpression>();
167
+
168
+ function markArrowsThatCaptureThis(node: Rule.Node & Rule.NodeParentExtension) {
169
+ sourceCode
170
+ .getAncestors(node)
171
+ .toReversed()
172
+ .some((ancestor) => {
173
+ if (
174
+ ancestor.type === 'ClassDeclaration' ||
175
+ ancestor.type === 'ClassExpression' ||
176
+ ancestor.type === 'FunctionDeclaration' ||
177
+ ancestor.type === 'FunctionExpression'
178
+ ) {
179
+ return true;
180
+ }
181
+
182
+ if (isArrowFunctionExpression(ancestor)) {
183
+ arrowsThatCaptureThis.add(ancestor);
184
+ }
185
+
186
+ return false;
187
+ });
188
+ }
189
+
190
+ function checkArrowFunction(node: RuleArrowFunctionExpression) {
191
+ if (arrowsThatCaptureThis.has(node)) {
192
+ return;
193
+ }
194
+
195
+ const constVariable = getConstVariable({
196
+ node,
197
+ });
198
+
199
+ if (constVariable) {
200
+ const functionText = getFunctionText({
201
+ node,
202
+ name: constVariable.declarator.id.name,
203
+ sourceCode,
204
+ useFunctionKeyword: true,
205
+ });
206
+
207
+ context.report({
208
+ node,
209
+ messageId: 'useFunctionDeclaration',
210
+ fix: functionText
211
+ ? (fixer) => {
212
+ return canUseFunctionDeclaration({
213
+ declaration: constVariable.declaration,
214
+ })
215
+ ? fixer.replaceText(constVariable.declaration, functionText)
216
+ : fixer.replaceText(node, functionText);
217
+ }
218
+ : undefined,
219
+ });
220
+ return;
221
+ }
222
+
223
+ const property = node.parent;
224
+
225
+ if (
226
+ property.type !== 'Property' ||
227
+ property.value !== node ||
228
+ property.kind !== 'init' ||
229
+ isPrototypeSetter({
230
+ property,
231
+ })
232
+ ) {
233
+ return;
234
+ }
235
+
236
+ const propertyName = property.computed
237
+ ? `[${sourceCode.getText(property.key)}]`
238
+ : sourceCode.getText(property.key);
239
+ const functionText = getFunctionText({
240
+ node,
241
+ name: propertyName,
242
+ sourceCode,
243
+ useFunctionKeyword: false,
244
+ });
245
+
246
+ context.report({
247
+ node,
248
+ messageId: 'usePropertyMethod',
249
+ fix: functionText
250
+ ? (fixer) => fixer.replaceText(property, functionText)
251
+ : undefined,
252
+ });
253
+ }
254
+
255
+ return {
256
+ ThisExpression: markArrowsThatCaptureThis,
257
+ 'ArrowFunctionExpression:exit': checkArrowFunction,
258
+ };
259
+ },
260
+ };
261
+
262
+ export default rule;
@@ -0,0 +1,151 @@
1
+ import {type Rule} from 'eslint';
2
+ import type {Node} from 'estree';
3
+
4
+ const looseOperatorByStrictOperator = {
5
+ '===': '==',
6
+ '!==': '!=',
7
+ };
8
+
9
+ type NullishKind = 'null' | 'undefined';
10
+
11
+ function getComparedNullishKind(node: Readonly<Node>): NullishKind | undefined {
12
+ if (node.type === 'Identifier' && node.name === 'undefined') {
13
+ return 'undefined';
14
+ } else if (node.type === 'Literal' && node.raw === 'null') {
15
+ return 'null';
16
+ } else {
17
+ return undefined;
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Which nullish members the given node's type includes. `undefined` is returned when the type
23
+ * cannot be determined at all, or when it is `any` or `unknown` (both of which could be either
24
+ * nullish value at run time).
25
+ *
26
+ * ESLint types `sourceCode.parserServices` as `any`, so the TypeScript program behind the
27
+ * typescript-eslint parser is necessarily reached without types here.
28
+ */
29
+ function getNullishMembers({
30
+ node,
31
+ parserServices,
32
+ }: Readonly<{
33
+ node: Readonly<Node>;
34
+ parserServices: any;
35
+ }>) {
36
+ const program = parserServices?.program;
37
+ const tsNode = parserServices?.esTreeNodeToTSNodeMap?.get(node);
38
+
39
+ if (!program || !tsNode) {
40
+ return undefined;
41
+ }
42
+
43
+ const checker = program.getTypeChecker();
44
+ const type = checker.getTypeAtLocation(tsNode);
45
+ /**
46
+ * `TypeFlags` values are compared through `typeToString` rather than the numeric enum because
47
+ * TypeScript renumbers those flags between major versions.
48
+ */
49
+ const typeNames: string[] = (type.isUnion() ? type.types : [type]).map((typePart: unknown) => {
50
+ return checker.typeToString(typePart);
51
+ });
52
+
53
+ if (typeNames.includes('any') || typeNames.includes('unknown')) {
54
+ return undefined;
55
+ }
56
+
57
+ return {
58
+ hasNull: typeNames.includes('null'),
59
+ /** A `void` value can only ever be `undefined` at run time. */
60
+ hasUndefined: typeNames.includes('undefined') || typeNames.includes('void'),
61
+ };
62
+ }
63
+
64
+ const rule: Rule.RuleModule = {
65
+ meta: {
66
+ type: 'suggestion',
67
+ fixable: 'code',
68
+ docs: {
69
+ description:
70
+ 'Require loose equality when comparing against `null` or `undefined` and strict equality cannot distinguish them.',
71
+ },
72
+ messages: {
73
+ preferLooseEquality:
74
+ 'Use `{{looseOperator}}` instead of `{{strictOperator}}` here: this value cannot be `{{otherNullish}}`, so the two behave identically.',
75
+ },
76
+ schema: [],
77
+ },
78
+ create(context) {
79
+ const sourceCode = context.sourceCode;
80
+
81
+ return {
82
+ BinaryExpression(node) {
83
+ const looseOperator =
84
+ looseOperatorByStrictOperator[
85
+ node.operator as keyof typeof looseOperatorByStrictOperator
86
+ ];
87
+
88
+ if (!looseOperator) {
89
+ return;
90
+ }
91
+
92
+ const leftNullishKind = getComparedNullishKind(node.left);
93
+ const rightNullishKind = getComparedNullishKind(node.right);
94
+
95
+ /**
96
+ * A comparison between two nullish literals has no value side to check, and a
97
+ * comparison between two non-nullish sides is not this rule's business.
98
+ */
99
+ if (!!leftNullishKind === !!rightNullishKind) {
100
+ return;
101
+ }
102
+
103
+ const comparedNullishKind = leftNullishKind ?? rightNullishKind;
104
+ const valueNode = leftNullishKind ? node.right : node.left;
105
+ const nullishMembers = getNullishMembers({
106
+ node: valueNode,
107
+ parserServices: sourceCode.parserServices,
108
+ });
109
+
110
+ if (!nullishMembers) {
111
+ return;
112
+ }
113
+
114
+ /**
115
+ * Loose equality only matches strict equality when the value cannot hold the
116
+ * _other_ nullish value. A value that can be both `null` and `undefined` is the
117
+ * rare case where strict equality is load bearing, so it is left alone.
118
+ */
119
+ const isEquivalentToStrictEquality =
120
+ comparedNullishKind === 'undefined'
121
+ ? nullishMembers.hasUndefined && !nullishMembers.hasNull
122
+ : nullishMembers.hasNull && !nullishMembers.hasUndefined;
123
+
124
+ if (!isEquivalentToStrictEquality) {
125
+ return;
126
+ }
127
+
128
+ const operatorToken = sourceCode.getTokenAfter(node.left, {
129
+ filter(token) {
130
+ return token.type === 'Punctuator' && token.value === node.operator;
131
+ },
132
+ });
133
+
134
+ context.report({
135
+ node,
136
+ messageId: 'preferLooseEquality',
137
+ data: {
138
+ looseOperator,
139
+ strictOperator: node.operator,
140
+ otherNullish: comparedNullishKind === 'undefined' ? 'null' : 'undefined',
141
+ },
142
+ fix: operatorToken
143
+ ? (fixer) => fixer.replaceText(operatorToken, looseOperator)
144
+ : undefined,
145
+ });
146
+ },
147
+ };
148
+ },
149
+ };
150
+
151
+ export default rule;
@@ -19,10 +19,14 @@ function findPrivateToken(node: AccessibilityNode, sourceCode: Readonly<SourceCo
19
19
  */
20
20
  return lastDecorator
21
21
  ? sourceCode.getTokenAfter(lastDecorator, {
22
- filter: (token) => token.value === 'private',
22
+ filter(token) {
23
+ return token.value === 'private';
24
+ },
23
25
  })
24
26
  : sourceCode.getFirstToken(node, {
25
- filter: (token) => token.value === 'private',
27
+ filter(token) {
28
+ return token.value === 'private';
29
+ },
26
30
  });
27
31
  }
28
32
 
@@ -0,0 +1,167 @@
1
+ import {type Rule} from 'eslint';
2
+ import type {Comment} from 'estree';
3
+
4
+ /**
5
+ * Matches a cspell word allow-list directive and captures everything after it. Only `word` and
6
+ * `words` directives are matched: other cspell directives (`ignore`, `disable`, `locale`, etc.) are
7
+ * position sensitive within a file and cannot be combined.
8
+ */
9
+ const wordsDirectiveRegExp = /\bcspell:words?\b[\t :]*(.*)/i;
10
+
11
+ type WordsComment = {
12
+ comment: Comment;
13
+ range: [
14
+ number,
15
+ number,
16
+ ];
17
+ words: string[];
18
+ };
19
+
20
+ function parseWordsComment(comment: Comment): WordsComment | undefined {
21
+ const range = comment.range;
22
+ const directiveMatch = wordsDirectiveRegExp.exec(comment.value);
23
+
24
+ if (!range || !directiveMatch) {
25
+ return undefined;
26
+ }
27
+
28
+ const words = (directiveMatch[1] ?? '')
29
+ .trim()
30
+ .split(/[\s,]+/)
31
+ .filter((word) => word !== '');
32
+
33
+ return {
34
+ comment,
35
+ range,
36
+ words,
37
+ };
38
+ }
39
+
40
+ function createCombinedCommentText({
41
+ comment,
42
+ words,
43
+ }: Readonly<{
44
+ comment: Comment;
45
+ words: ReadonlyArray<string>;
46
+ }>) {
47
+ const directiveText = `cspell:words ${words.join(' ')}`;
48
+
49
+ return comment.type === 'Line' ? `// ${directiveText}` : `/* ${directiveText} */`;
50
+ }
51
+
52
+ /**
53
+ * The range covering the whole line that the given comment sits on, including its trailing new
54
+ * line, or `undefined` when anything else shares the line and only the comment itself can be
55
+ * removed.
56
+ */
57
+ function getRemovalRange({
58
+ range,
59
+ sourceCode,
60
+ }: Readonly<{
61
+ range: readonly [
62
+ number,
63
+ number,
64
+ ];
65
+ sourceCode: Rule.RuleContext['sourceCode'];
66
+ }>): [
67
+ number,
68
+ number,
69
+ ] {
70
+ const lineStart = sourceCode.text.lastIndexOf('\n', range[0]) + 1;
71
+ const nextNewLine = sourceCode.text.indexOf('\n', range[1]);
72
+ const lineEnd = nextNewLine === -1 ? sourceCode.text.length : nextNewLine + 1;
73
+ const isAloneOnItsLine =
74
+ sourceCode.text.slice(lineStart, range[0]).trim() === '' &&
75
+ sourceCode.text.slice(range[1], lineEnd).trim() === '';
76
+
77
+ return isAloneOnItsLine
78
+ ? [
79
+ lineStart,
80
+ lineEnd,
81
+ ]
82
+ : [
83
+ range[0],
84
+ range[1],
85
+ ];
86
+ }
87
+
88
+ const rule: Rule.RuleModule = {
89
+ meta: {
90
+ type: 'suggestion',
91
+ fixable: 'code',
92
+ docs: {
93
+ description: 'Require all cspell word allow-list comments in a file to be combined.',
94
+ },
95
+ messages: {
96
+ singleWordsComment:
97
+ 'Combine all `cspell:words` comments in a file into a single comment.',
98
+ },
99
+ schema: [],
100
+ },
101
+ create(context) {
102
+ const sourceCode = context.sourceCode;
103
+
104
+ return {
105
+ Program() {
106
+ const wordsComments = sourceCode
107
+ .getAllComments()
108
+ .map((comment) => parseWordsComment(comment))
109
+ .filter((wordsComment) => wordsComment != undefined);
110
+ const [
111
+ firstWordsComment,
112
+ ...extraWordsComments
113
+ ] = wordsComments;
114
+
115
+ if (!firstWordsComment || !extraWordsComments.length) {
116
+ return;
117
+ }
118
+
119
+ const combinedWords = wordsComments.flatMap((wordsComment) => {
120
+ return wordsComment.words;
121
+ });
122
+ const uniqueWords = combinedWords.filter((word, wordIndex) => {
123
+ return combinedWords.indexOf(word) === wordIndex;
124
+ });
125
+
126
+ extraWordsComments.forEach((extraWordsComment, extraIndex) => {
127
+ context.report({
128
+ loc: extraWordsComment.comment.loc ?? {
129
+ start: sourceCode.getLocFromIndex(extraWordsComment.range[0]),
130
+ end: sourceCode.getLocFromIndex(extraWordsComment.range[1]),
131
+ },
132
+ messageId: 'singleWordsComment',
133
+ /**
134
+ * Only the first extra comment carries the fix: it rewrites the kept
135
+ * comment and removes every extra comment at once, so a single pass
136
+ * combines them all without overlapping fixes.
137
+ */
138
+ fix:
139
+ extraIndex === 0
140
+ ? (fixer) => {
141
+ return [
142
+ fixer.replaceTextRange(
143
+ firstWordsComment.range,
144
+ createCombinedCommentText({
145
+ comment: firstWordsComment.comment,
146
+ words: uniqueWords,
147
+ }),
148
+ ),
149
+ ...extraWordsComments.map((removedWordsComment) => {
150
+ return fixer.removeRange(
151
+ getRemovalRange({
152
+ range: removedWordsComment.range,
153
+ sourceCode,
154
+ }),
155
+ );
156
+ }),
157
+ ];
158
+ }
159
+ : undefined,
160
+ });
161
+ });
162
+ },
163
+ };
164
+ },
165
+ };
166
+
167
+ export default rule;