Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions test/eslint.config_partial.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ export default [
'node-core/require-common-first': 'error',
'node-core/no-duplicate-requires': 'off',
'node-core/must-call-assert': 'error',
'node-core/prefer-abort-signal-abort': 'error',
},
},
{
Expand Down
5 changes: 2 additions & 3 deletions test/parallel/test-abortcontroller.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,8 @@ test('AbortController inspection depth 1 or null works', () => {

test('AbortSignal reason is set correctly', () => {
// Test AbortSignal.reason
const ac = new AbortController();
ac.abort('reason');
assert.strictEqual(ac.signal.reason, 'reason');
const signal = AbortSignal.abort('reason');
assert.strictEqual(signal.reason, 'reason');
Comment on lines +164 to +165
Copy link
Copy Markdown
Contributor

@aduh95 aduh95 May 25, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is testing AbortController (see the file name), not AbortSignal; it should be reverted and excluded via a // eslint-disable-next-line comment

});

test('AbortSignal reasonable is set correctly with AbortSignal.abort()', () => {
Expand Down
91 changes: 91 additions & 0 deletions test/parallel/test-eslint-prefer-abort-signal-abort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
'use strict';

const common = require('../common');
if ((!common.hasCrypto) || (!common.hasIntl)) {
common.skip('ESLint tests require crypto and Intl');
}

common.skipIfEslintMissing();

const RuleTester = require('../../tools/eslint/node_modules/eslint').RuleTester;
const rule = require('../../tools/eslint-rules/prefer-abort-signal-abort');

const message = 'Use AbortSignal.abort() instead of creating and aborting an AbortController.';

new RuleTester().run('prefer-abort-signal-abort', rule, {
valid: [
'const signal = AbortSignal.abort();',
`
const controller = new AbortController();
controller.abort();
controller.abort();
fn(controller.signal);
`,
Comment on lines +18 to +23
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For readability sake, let's indent

Suggested change
`
const controller = new AbortController();
controller.abort();
controller.abort();
fn(controller.signal);
`,
`
const controller = new AbortController();
controller.abort();
controller.abort();
fn(controller.signal);
`,

`
const controller = new AbortController();
controller.abort();
fn(controller.signal, controller.signal);
Comment on lines +25 to +27
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ditto, and why is this a valid case?

`,
`
const controller = new AbortController();
controller.abort();
console.log(controller);
fn(controller.signal);
`,
`
const controller = new AbortController();
// This comment should not be removed.
controller.abort();
fn(controller.signal);
`,
`
const controller = new AbortController();
setImmediate(() => controller.abort());
fn(controller.signal);
`,
`
const controller = new AbortController();
controller.abort('reason', 'extra');
fn(controller.signal);
`,
],
invalid: [
{
code: `
const controller = new AbortController();
controller.abort();
fn(controller.signal);
`,
errors: [{ message }],
output: `
fn(AbortSignal.abort());
`,
},
{
code: `
const abortController = new AbortController();
abortController.abort(new Error('aborted'));
fn({ signal: abortController.signal });
`,
errors: [{ message }],
output: `
fn({ signal: AbortSignal.abort(new Error('aborted')) });
`,
},
{
code: `
{
const ac = new AbortController();
ac.abort();
await wait({ signal: ac.signal });
}
`,
errors: [{ message }],
output: `
{
await wait({ signal: AbortSignal.abort() });
}
`,
},
]
});
5 changes: 2 additions & 3 deletions test/parallel/test-quic-writer-abort-signal.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,11 @@ const stream = await clientSession.createBidirectionalStream();
const w = stream.writer;

// Create an already-aborted signal.
const ac = new AbortController();
ac.abort(new Error('already aborted'));
const signal = AbortSignal.abort(new Error('already aborted'));

// write() with an already-aborted signal should reject immediately.
await rejects(
w.write(encoder.encode('data'), { signal: ac.signal }),
w.write(encoder.encode('data'), { signal }),
{ message: 'already aborted' },
);

Expand Down
147 changes: 147 additions & 0 deletions tools/eslint-rules/prefer-abort-signal-abort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/**
* @file Prefer AbortSignal.abort() for already-aborted signals.
*/
'use strict';

const message = 'Use AbortSignal.abort() instead of creating and aborting an AbortController.';

function isAbortControllerConstruction(node) {
return node?.type === 'NewExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'AbortController' &&
node.arguments.length === 0;
}

function isIdentifier(node, name) {
return node?.type === 'Identifier' && node.name === name;
}

function isProperty(node, name) {
return !node.computed && isIdentifier(node.property, name);
}

function isAbortCallStatement(node, name) {
const expression = node?.expression;
const callee = expression?.callee;
return node?.type === 'ExpressionStatement' &&
expression.type === 'CallExpression' &&
callee.type === 'MemberExpression' &&
isIdentifier(callee.object, name) &&
isProperty(callee, 'abort') &&
expression.arguments.length <= 1;
}

function isSignalReference(reference, name) {
const { identifier } = reference;
const parent = identifier.parent;
return isIdentifier(identifier, name) &&
parent?.type === 'MemberExpression' &&
parent.object === identifier &&
isProperty(parent, 'signal');
}

function isAbortReference(reference, abortStatement, name) {
const { identifier } = reference;
const parent = identifier.parent;
return isIdentifier(identifier, name) &&
parent?.type === 'MemberExpression' &&
parent.object === identifier &&
isProperty(parent, 'abort') &&
parent.parent === abortStatement.expression;
}

module.exports = {
meta: {
fixable: 'code',
},

create(context) {
const sourceCode = context.sourceCode;
const candidates = [];

function hasCommentsBetween(left, right) {
return sourceCode.getCommentsBefore(right)
.some((comment) => comment.range[0] > left.range[1]);
}

function rangeIncludingTrailingLine(statement) {
const tokenAfter = sourceCode.getTokenAfter(statement, { includeComments: true });
if (tokenAfter && tokenAfter.loc.start.line > statement.loc.end.line) {
return [statement.range[0], tokenAfter.range[0]];
}
return statement.range;
}

return {
VariableDeclarator(node) {
if (node.id.type !== 'Identifier' ||
!isAbortControllerConstruction(node.init) ||
node.parent.declarations.length !== 1) {
return;
}

const variableDeclaration = node.parent;
const parent = variableDeclaration.parent;
if (parent.type !== 'BlockStatement' && parent.type !== 'Program') {
return;
}

const index = parent.body.indexOf(variableDeclaration);
const abortStatement = parent.body[index + 1];
if (!isAbortCallStatement(abortStatement, node.id.name) ||
hasCommentsBetween(variableDeclaration, abortStatement)) {
return;
}

candidates.push({
abortStatement,
declarator: node,
variableDeclaration,
});
},

'Program:exit'() {
for (const { abortStatement, declarator, variableDeclaration } of candidates) {
const [variable] = sourceCode.scopeManager.getDeclaredVariables(declarator);
if (!variable) {
continue;
}

const name = declarator.id.name;
const references = variable.references.filter((reference) => {
return reference.identifier !== declarator.id;
});
const signalReferences = references.filter((reference) => {
return isSignalReference(reference, name);
});
const abortReferences = references.filter((reference) => {
return isAbortReference(reference, abortStatement, name);
});

if (references.length !== 2 ||
signalReferences.length !== 1 ||
Comment on lines +121 to +122
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (references.length !== 2 ||
signalReferences.length !== 1 ||
if (references.length !== (1 + signalReferences.length) ||

abortReferences.length !== 1) {
continue;
}

const signalNode = signalReferences[0].identifier.parent;
const abortArguments = abortStatement.expression.arguments;
const abortReason = abortArguments.length === 0 ?
'' : sourceCode.getText(abortArguments[0]);

context.report({
node: signalNode,
message,
fix(fixer) {
return [
fixer.removeRange(rangeIncludingTrailingLine(variableDeclaration)),
fixer.removeRange(rangeIncludingTrailingLine(abortStatement)),
fixer.replaceText(signalNode, `AbortSignal.abort(${abortReason})`),
];
},
});
}
},
};
},
};
Loading