Skip to content

feat(eslint-plugin): [no-floating-promises] add an 'allowForKnownSafePromises' option #8502

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 38 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
476f867
feat: [no-floating-promises] add an
arkapratimc Feb 17, 2024
7bbba26
chore: snapshot errors
arkapratimc Feb 18, 2024
38ea99f
chore: add a test
arkapratimc Feb 19, 2024
f15a0bb
chore: add another test
arkapratimc Feb 19, 2024
0019678
chore: rewrite
arkapratimc Feb 21, 2024
d231660
Merge branch 'main' into issue-7008
arkapratimc Mar 19, 2024
379a2d0
chore: docs & test
arkapratimc Mar 19, 2024
035484b
chore: add jsdoc comment
arkapratimc Mar 19, 2024
6fe2efa
chore: cspell
arkapratimc Mar 19, 2024
2269319
chore: lint
arkapratimc Mar 19, 2024
2f7ed24
Merge branch 'main' into issue-7008
arkapratimc Apr 4, 2024
27b463f
chore: address reviews
arkapratimc Apr 4, 2024
6e221be
chore: lint errors
arkapratimc Apr 4, 2024
4400e3b
chore: remove invalid js/ts code
arkapratimc Apr 5, 2024
856a1a0
chore: add thenables
arkapratimc Apr 5, 2024
9bd2105
Merge branch 'main' into issue-7008
arkapratimc Apr 5, 2024
b7ac1fd
chore: fix failures
arkapratimc Apr 5, 2024
0fbc581
chore: re-write tests
arkapratimc Apr 8, 2024
c50ae5b
chore: more tests
arkapratimc Apr 8, 2024
af882dd
chore: fix schemas
arkapratimc Apr 8, 2024
4c51ce3
chore: typo
arkapratimc Apr 8, 2024
52019b2
fix: docs
arkapratimc Apr 9, 2024
e5ffd3d
chore: nits
arkapratimc Apr 9, 2024
345a65d
snapshots
arkapratimc Apr 9, 2024
304a53c
chore: address reviews
arkapratimc Apr 24, 2024
497e8f7
chore: reduce tests
arkapratimc Apr 24, 2024
842bd2d
chore: line numbers
arkapratimc Apr 24, 2024
6b01c41
chore: docs
arkapratimc Apr 25, 2024
f10ae89
chore: typos
arkapratimc Apr 25, 2024
4a7d516
chore: address reviews
arkapratimc Apr 27, 2024
aa94a28
fix: condition issues
arkapratimc Apr 27, 2024
171701b
chore: update docs
arkapratimc Apr 29, 2024
ecd31e3
chore: tag function
arkapratimc Apr 29, 2024
a7fc9a2
chore: address reviews
arkapratimc May 1, 2024
0ab7060
chore: revert var name
arkapratimc May 1, 2024
441e467
chore: address reviews
arkapratimc May 11, 2024
7422cf5
chore: lint & tests
arkapratimc May 11, 2024
cbbda8a
chore: comments
arkapratimc May 26, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions packages/eslint-plugin/docs/rules/no-floating-promises.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,51 @@ await (async function () {
})();
```

### `allowForKnownSafePromises`

This option allows marking specific types as "safe" to be floating. For example, you may need to do this in the case of libraries whose APIs return Promises whose rejections are safely handled by the library.

Each item must be one of:

- A type defined in a file (`{from: "file", name: "Foo", path: "src/foo-file.ts"}` with `path` being an optional path relative to the project root directory)
- A type from the default library (`{from: "lib", name: "PromiseLike"}`)
- A type from a package (`{from: "package", name: "Foo", package: "foo-lib"}`, this also works for types defined in a typings package).

Examples of code for this rule with:

```json
{
"allowForKnownSafePromises": [
{ "from": "file", "name": "SafePromise" },
{ "from": "lib", "name": "PromiseLike" },
{ "from": "package", "name": "Bar", "package": "bar-lib" }
]
}
```

<Tabs>
<TabItem value="❌ Incorrect">

```ts option='{"allowForKnownSafePromises":[{"from":"file","name":"SafePromise"},{"from":"lib","name":"PromiseLike"},{"from":"package","name":"Bar","package":"bar-lib"}]}'
type UnsafePromise = Promise<number> & { __linterBrands?: string };
let promise: UnsafePromise = Promise.resolve(2);
promise;
promise.finally();
```

</TabItem>
<TabItem value="✅ Correct">

```ts option='{"allowForKnownSafePromises":[{"from":"file","name":"SafePromise"},{"from":"lib","name":"PromiseLike"},{"from":"package","name":"Bar","package":"bar-lib"}]}'
type SafePromise = Promise<number> & { __linterBrands?: string }; // promises can be marked as safe by using branded types
let promise: SafePromise = Promise.resolve(2);
promise;
promise.finally();
```

</TabItem>
</Tabs>

## When Not To Use It

This rule can be difficult to enable on large existing projects that set up many floating Promises.
Expand Down
88 changes: 85 additions & 3 deletions packages/eslint-plugin/src/rules/no-floating-promises.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,28 @@
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import type {
ParserServicesWithTypeInformation,
TSESLint,
TSESTree,
} from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import * as tsutils from 'ts-api-utils';
import * as ts from 'typescript';

import type { TypeOrValueSpecifier } from '../util';
import {
createRule,
getOperatorPrecedence,
getParserServices,
OperatorPrecedence,
readonlynessOptionsDefaults,
readonlynessOptionsSchema,
typeMatchesSpecifier,
} from '../util';

type Options = [
{
ignoreVoid?: boolean;
ignoreIIFE?: boolean;
allowForKnownSafePromises?: TypeOrValueSpecifier[];
},
];

Expand Down Expand Up @@ -79,6 +88,7 @@ export default createRule<Options, MessageId>({
'Whether to ignore async IIFEs (Immediately Invoked Function Expressions).',
type: 'boolean',
},
allowForKnownSafePromises: readonlynessOptionsSchema.properties.allow,
},
additionalProperties: false,
},
Expand All @@ -89,12 +99,16 @@ export default createRule<Options, MessageId>({
{
ignoreVoid: true,
ignoreIIFE: false,
allowForKnownSafePromises: readonlynessOptionsDefaults.allow,
},
],

create(context, [options]) {
const services = getParserServices(context);
const checker = services.program.getTypeChecker();
// TODO: #5439
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const allowForKnownSafePromises = options.allowForKnownSafePromises!;

return {
ExpressionStatement(node): void {
Expand Down Expand Up @@ -253,7 +267,9 @@ export default createRule<Options, MessageId>({
// Check the type. At this point it can't be unhandled if it isn't a promise
// or array thereof.

if (isPromiseArray(checker, tsNode)) {
if (
isPromiseArray(services, allowForKnownSafePromises, checker, tsNode)
) {
return { isUnhandled: true, promiseArray: true };
}

Expand All @@ -262,6 +278,28 @@ export default createRule<Options, MessageId>({
}

if (node.type === AST_NODE_TYPES.CallExpression) {
const member =
node.callee.type === AST_NODE_TYPES.MemberExpression
? node.callee.object
: node;
const calledByThenOrCatch =
(node.callee.type === AST_NODE_TYPES.MemberExpression &&
node.callee.property.type === AST_NODE_TYPES.Identifier &&
node.callee.property.name === 'catch') ||
(node.callee.type === AST_NODE_TYPES.MemberExpression &&
node.callee.property.type === AST_NODE_TYPES.Identifier &&
node.callee.property.name === 'then');
if (
!calledByThenOrCatch &&
doesTypeMatchSpecifier(
services,
allowForKnownSafePromises,
services.getTypeAtLocation(member),
)
) {
return { isUnhandled: false };
}

// If the outer expression is a call, a `.catch()` or `.then()` with
// rejection handler handles the promise.

Expand Down Expand Up @@ -291,6 +329,15 @@ export default createRule<Options, MessageId>({
// All other cases are unhandled.
return { isUnhandled: true };
} else if (node.type === AST_NODE_TYPES.TaggedTemplateExpression) {
if (
doesTypeMatchSpecifier(
services,
allowForKnownSafePromises,
services.getTypeAtLocation(node),
)
) {
return { isUnhandled: false };
}
return { isUnhandled: true };
} else if (node.type === AST_NODE_TYPES.ConditionalExpression) {
// We must be getting the promise-like value from one of the branches of the
Expand All @@ -305,6 +352,15 @@ export default createRule<Options, MessageId>({
node.type === AST_NODE_TYPES.Identifier ||
node.type === AST_NODE_TYPES.NewExpression
) {
if (
doesTypeMatchSpecifier(
services,
allowForKnownSafePromises,
services.getTypeAtLocation(node),
)
) {
return { isUnhandled: false };
}
// 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.
Expand All @@ -325,20 +381,46 @@ export default createRule<Options, MessageId>({
},
});

function isPromiseArray(checker: ts.TypeChecker, node: ts.Node): boolean {
function doesTypeMatchSpecifier(
services: ParserServicesWithTypeInformation,
options: TypeOrValueSpecifier[],
type: ts.Type,
): boolean {
return options.some(specifier =>
typeMatchesSpecifier(type, specifier, services.program),
);
}

function isPromiseArray(
services: ParserServicesWithTypeInformation,
options: TypeOrValueSpecifier[],
checker: ts.TypeChecker,
node: ts.Node,
): boolean {
const type = checker.getTypeAtLocation(node);
for (const ty of tsutils
.unionTypeParts(type)
.map(t => checker.getApparentType(t))) {
if (checker.isArrayType(ty)) {
const arrayType = checker.getTypeArguments(ty)[0];
if (
options.length > 0 &&
tsutils
.unionTypeParts(arrayType)
.some(type => doesTypeMatchSpecifier(services, options, type))
) {
return false;
}
if (isPromiseLike(checker, node, arrayType)) {
return true;
}
}

if (checker.isTupleType(ty)) {
for (const tupleElementType of checker.getTypeArguments(ty)) {
if (doesTypeMatchSpecifier(services, options, tupleElementType)) {
return false;
}
if (isPromiseLike(checker, node, tupleElementType)) {
return true;
}
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading