Skip to content

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

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 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
b1ce3f3
new logic
kirkwaiblinger May 28, 2024
597f3bf
make use of closure
kirkwaiblinger May 28, 2024
9a6ced2
rename variable
kirkwaiblinger May 30, 2024
e0355d8
Merge branch 'main' into kirk-safe-promises
kirkwaiblinger May 30, 2024
049230f
wording
kirkwaiblinger May 30, 2024
963c806
whoops, copypasta mistake
kirkwaiblinger May 30, 2024
0bdd2ef
remove test comment
kirkwaiblinger May 31, 2024
98e3120
simplify comments
kirkwaiblinger May 31, 2024
47b2661
remove bare string specifier
kirkwaiblinger May 31, 2024
d391a04
docs
kirkwaiblinger May 31, 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
57 changes: 57 additions & 0 deletions packages/eslint-plugin/docs/rules/no-floating-promises.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,63 @@ 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.

This option takes an array of type specifiers to consider safe.
Each item in the array must have one of the following forms:

- 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"}]}'
let promise: Promise<number> = Promise.resolve(2);
promise;

function returnsPromise(): Promise<number> {
return Promise.resolve(42);
}

returnsPromise();
```

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

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

let promise: SafePromise = Promise.resolve(2);
promise;

function returnsSafePromise(): SafePromise {
return Promise.resolve(42);
}

returnsSafePromise();
```

</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
Original file line number Diff line number Diff line change
Expand Up @@ -142,11 +142,12 @@ interface Foo {

Some complex types cannot easily be made readonly, for example the `HTMLElement` type or the `JQueryStatic` type from `@types/jquery`. This option allows you to globally disable reporting of such types.

Each item must be one of:
This option takes an array of type specifiers to ignore.
Each item in the array must have one of the following forms:

- 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: "Foo"}`)
- A type from a package (`{from: "package", name: "Foo", package: "foo-lib"}`, this also works for types defined in a typings package).
- 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: "Foo" }`)
- A type from a package (`{ from: "package", name: "Foo", package: "foo-lib" }`, this also works for types defined in a typings package).

Additionally, a type may be defined just as a simple string, which then matches the type independently of its origin.

Expand Down
118 changes: 67 additions & 51 deletions packages/eslint-plugin/src/rules/no-floating-promises.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,22 @@ 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 +84,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 +95,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,11 +263,11 @@ 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(tsNode)) {
return { isUnhandled: true, promiseArray: true };
}

if (!isPromiseLike(checker, tsNode)) {
if (!isPromiseLike(tsNode)) {
return { isUnhandled: false };
}

Expand Down Expand Up @@ -322,63 +332,69 @@ export default createRule<Options, MessageId>({
// we just can't tell.
return { isUnhandled: false };
}
},
});

function isPromiseArray(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 (isPromiseLike(checker, node, arrayType)) {
return true;
}
}
function isPromiseArray(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 (isPromiseLike(node, arrayType)) {
return true;
}
}

if (checker.isTupleType(ty)) {
for (const tupleElementType of checker.getTypeArguments(ty)) {
if (isPromiseLike(checker, node, tupleElementType)) {
return true;
if (checker.isTupleType(ty)) {
for (const tupleElementType of checker.getTypeArguments(ty)) {
if (isPromiseLike(node, tupleElementType)) {
return true;
}
}
}
}
return false;
}
}
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,
type?: ts.Type,
): boolean {
type ??= checker.getTypeAtLocation(node);
for (const ty of tsutils.unionTypeParts(checker.getApparentType(type))) {
const then = ty.getProperty('then');
if (then === undefined) {
continue;
}
// 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(node: ts.Node, type?: ts.Type): boolean {
type ??= checker.getTypeAtLocation(node);

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;
// Ignore anything specified by `allowForKnownSafePromises` option.
if (
allowForKnownSafePromises.some(allowedType =>
typeMatchesSpecifier(type, allowedType, services.program),
)
) {
return false;
}

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;
}
}
return false;
}
},
});

function hasMatchingSignature(
type: ts.Type,
Expand Down

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

Loading
Loading