-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
no-floating-promises.ts
264 lines (240 loc) · 7.96 KB
/
no-floating-promises.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import * as tsutils from 'tsutils';
import * as ts from 'typescript';
import {
TSESLint,
AST_NODE_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import * as util from '../util';
type Options = [
{
ignoreVoid?: boolean;
ignoreIIFE?: boolean;
},
];
type MessageId = 'floating' | 'floatingVoid' | 'floatingFixVoid';
export default util.createRule<Options, MessageId>({
name: 'no-floating-promises',
meta: {
docs: {
description: 'Requires Promise-like values to be handled appropriately',
recommended: 'error',
suggestion: true,
requiresTypeChecking: true,
},
hasSuggestions: true,
messages: {
floating:
'Promises must be awaited, end with a call to .catch, or end with a call to .then with a rejection handler.',
floatingVoid:
'Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler' +
' or be explicitly marked as ignored with the `void` operator.',
floatingFixVoid: 'Add void operator to ignore.',
},
schema: [
{
type: 'object',
properties: {
ignoreVoid: { type: 'boolean' },
ignoreIIFE: { type: 'boolean' },
},
additionalProperties: false,
},
],
type: 'problem',
},
defaultOptions: [
{
ignoreVoid: true,
ignoreIIFE: false,
},
],
create(context, [options]) {
const parserServices = util.getParserServices(context);
const checker = parserServices.program.getTypeChecker();
const sourceCode = context.getSourceCode();
return {
ExpressionStatement(node): void {
if (options.ignoreIIFE && isAsyncIife(node)) {
return;
}
let expression = node.expression;
if (expression.type === AST_NODE_TYPES.ChainExpression) {
expression = expression.expression;
}
if (isUnhandledPromise(checker, expression)) {
if (options.ignoreVoid) {
context.report({
node,
messageId: 'floatingVoid',
suggest: [
{
messageId: 'floatingFixVoid',
fix(fixer): TSESLint.RuleFix {
let code = sourceCode.getText(node);
code = `void ${code}`;
return fixer.replaceText(node, code);
},
},
],
});
} else {
context.report({
node,
messageId: 'floating',
});
}
}
},
};
function isAsyncIife(node: TSESTree.ExpressionStatement): boolean {
if (node.expression.type !== AST_NODE_TYPES.CallExpression) {
return false;
}
return (
node.expression.type === AST_NODE_TYPES.CallExpression &&
(node.expression.callee.type ===
AST_NODE_TYPES.ArrowFunctionExpression ||
node.expression.callee.type === AST_NODE_TYPES.FunctionExpression)
);
}
function isUnhandledPromise(
checker: ts.TypeChecker,
node: TSESTree.Node,
): boolean {
// First, check expressions whose resulting types may not be promise-like
if (node.type === AST_NODE_TYPES.SequenceExpression) {
// Any child in a comma expression could return a potentially unhandled
// promise, so we check them all regardless of whether the final returned
// value is promise-like.
return node.expressions.some(item => isUnhandledPromise(checker, item));
}
if (
!options.ignoreVoid &&
node.type === AST_NODE_TYPES.UnaryExpression &&
node.operator === 'void'
) {
// Similarly, a `void` expression always returns undefined, so we need to
// see what's inside it without checking the type of the overall expression.
return isUnhandledPromise(checker, node.argument);
}
// Check the type. At this point it can't be unhandled if it isn't a promise
if (
!isPromiseLike(checker, parserServices.esTreeNodeToTSNodeMap.get(node))
) {
return false;
}
if (node.type === AST_NODE_TYPES.CallExpression) {
// If the outer expression is a call, it must be either a `.then()` or
// `.catch()` that handles the promise.
return (
!isPromiseCatchCallWithHandler(node) &&
!isPromiseThenCallWithRejectionHandler(node) &&
!isPromiseFinallyCallWithHandler(node)
);
} else if (node.type === AST_NODE_TYPES.ConditionalExpression) {
// We must be getting the promise-like value from one of the branches of the
// ternary. Check them directly.
return (
isUnhandledPromise(checker, node.alternate) ||
isUnhandledPromise(checker, node.consequent)
);
} else if (
node.type === AST_NODE_TYPES.MemberExpression ||
node.type === AST_NODE_TYPES.Identifier ||
node.type === AST_NODE_TYPES.NewExpression
) {
// If it is just a property access chain or a `new` call (e.g. `foo.bar` or
// `new Promise()`), the promise is not handled because it doesn't have the
// necessary then/catch call at the end of the chain.
return true;
}
// We conservatively return false for all other types of expressions because
// we don't want to accidentally fail if the promise is handled internally but
// we just can't tell.
return false;
}
},
});
// Modified from tsutils.isThenable() to only consider thenables which can be
// rejected/caught via a second parameter. Original source (MIT licensed):
//
// https://github.com/ajafff/tsutils/blob/49d0d31050b44b81e918eae4fbaf1dfe7b7286af/util/type.ts#L95-L125
function isPromiseLike(checker: ts.TypeChecker, node: ts.Node): boolean {
const type = checker.getTypeAtLocation(node);
for (const ty of tsutils.unionTypeParts(checker.getApparentType(type))) {
const then = ty.getProperty('then');
if (then === undefined) {
continue;
}
const thenType = checker.getTypeOfSymbolAtLocation(then, node);
if (
hasMatchingSignature(
thenType,
signature =>
signature.parameters.length >= 2 &&
isFunctionParam(checker, signature.parameters[0], node) &&
isFunctionParam(checker, signature.parameters[1], node),
)
) {
return true;
}
}
return false;
}
function hasMatchingSignature(
type: ts.Type,
matcher: (signature: ts.Signature) => boolean,
): boolean {
for (const t of tsutils.unionTypeParts(type)) {
if (t.getCallSignatures().some(matcher)) {
return true;
}
}
return false;
}
function isFunctionParam(
checker: ts.TypeChecker,
param: ts.Symbol,
node: ts.Node,
): boolean {
const type: ts.Type | undefined = checker.getApparentType(
checker.getTypeOfSymbolAtLocation(param, node),
);
for (const t of tsutils.unionTypeParts(type)) {
if (t.getCallSignatures().length !== 0) {
return true;
}
}
return false;
}
function isPromiseCatchCallWithHandler(
expression: TSESTree.CallExpression,
): boolean {
return (
expression.callee.type === AST_NODE_TYPES.MemberExpression &&
expression.callee.property.type === AST_NODE_TYPES.Identifier &&
expression.callee.property.name === 'catch' &&
expression.arguments.length >= 1
);
}
function isPromiseThenCallWithRejectionHandler(
expression: TSESTree.CallExpression,
): boolean {
return (
expression.callee.type === AST_NODE_TYPES.MemberExpression &&
expression.callee.property.type === AST_NODE_TYPES.Identifier &&
expression.callee.property.name === 'then' &&
expression.arguments.length >= 2
);
}
function isPromiseFinallyCallWithHandler(
expression: TSESTree.CallExpression,
): boolean {
return (
expression.callee.type === AST_NODE_TYPES.MemberExpression &&
expression.callee.property.type === AST_NODE_TYPES.Identifier &&
expression.callee.property.name === 'finally' &&
expression.arguments.length >= 1
);
}