We are going to create a linter that checks for common patterns in async code that may lead to cancellation safety issues.
We'll focus on:
Timeouts: ensuring that timeouts are properly handled and do not leave resources hanging.
Abort propagation: ensuring that cancellation signals (like AbortController) are propagated to all async operations.
Leak checks: ensuring that resources (like event listeners, intervals, timeouts) are cleaned up when no longer needed.
We assume the codebase is in JavaScript/TypeScript and uses common async patterns (Promises, async/await, AbortController, etc.)
We'll design rules that can be implemented in a linter (like ESLint) but for simplicity, we'll describe the rules and how to check for them.
Steps:
Timeouts:
Rule: Every setTimeout/setInterval should have a corresponding clearTimeout/clearInterval in every code path, especially when cancellation occurs.
How to check: We can track the assignment of timer IDs and then check if they are cleared in the same function/block, especially when an AbortController is used or when an error occurs.
Abort propagation:
Rule: When an AbortController is used, its signal should be passed to all async operations that support it (fetch, timers, etc.) and the abort event should be handled to clean up resources.
How to check: Look for AbortController creation and then check that:
a. The signal is passed to functions that accept a signal (like fetch, some DOM APIs, etc.).
b. There is an event listener for 'abort' on the signal that cleans up resources (clears timers, removes event listeners, etc.).
Leak checks:
Rule: Resources (event listeners, intervals, timeouts, etc.) must be released when they are no longer needed, especially when the component/function is cleaned up (like in React useEffect cleanup).
How to check: Track the registration of resources and then check for their release in the same scope or in a cleanup function.
Implementation approach:
We can use a static analysis tool that has an AST (Abstract Syntax Tree) for JavaScript/TypeScript. We'll write rules that traverse the AST and look for patterns.
Let's break down each rule with examples and how we might check for them.
Example code patterns and what we want to flag:
Timeouts:
Bad:
const controller = new AbortController();
const timeoutId = setTimeout(() => { ... }, 1000);
// No clearTimeout anywhere, especially if controller aborts.
We want to flag: a setTimeout/setInterval that is not cleared in the same function/block when an AbortController is present and the abort event is not handled to clear it.
How:
Find all setTimeout/setInterval calls and store their return value (the timer ID).
Check if that timer ID is passed to a clearTimeout/clearInterval in every possible code path (especially in a finally block or an abort event handler).
This is complex because we have to track the flow. Alternatively, we can require that when an AbortController is used, all timers are cleared in the abort event handler.
Simplified rule: If there's an AbortController in the same function and a timer is set, then there must be an abort event handler that clears the timer.
Abort propagation:
Bad:
const controller = new AbortController();
fetch(url, { signal: controller.signal }); // Good, but what about other async operations?
// But if we also have:
someAsyncFunctionThatDoesntSupportSignal(controller.signal); // This might be a mistake if the function does not support abort.
We want to flag:
a. Passing controller.signal to a function that doesn't accept a signal (if we can determine that).
b. Not passing the signal to functions that do support it (if we know they support it and the signal is available).
How:
We need a list of functions that support AbortSignal (like fetch, DOM methods, some libraries). This can be configureable.
For each function call that we know supports signal, if there's an AbortController in the same scope and we don't pass the signal, flag it.
Conversely, if we pass a signal to a function that doesn't support it, flag it (if we can determine that the function doesn't support signal).
Leak checks:
Bad:
useEffect(() => {
const listener = () => { ... };
element.addEventListener('click', listener);
// No cleanup function that removes the listener.
}, []);
Track all addEventListener calls and their event names and listener functions.
Check that there's a corresponding removeEventListener in the same scope (or in a cleanup function if in a React component) for every added listener.
Similarly for setInterval, setTimeout, etc.
Given the complexity, we might break the linter into multiple rules.
Proposed rules:
Rule 1: no-uncancelled-timers
When an AbortController is present in the same scope, every timer (setTimeout, setInterval) must be cleared in an event handler for the controller's 'abort' event or in a cleanup function (like in useEffect).
Rule 2: no-missing-signal-propagation
For known functions that accept an AbortSignal (configurable list), if an AbortController is available in the same scope, the signal must be passed.
Rule 3: no-missing-signal-usage
For known functions that do not accept an AbortSignal (configurable list), do not pass a signal.
Rule 4: no-unremoved-event-listeners
Every event listener added must be removed in the same scope or in a cleanup function (like in React's useEffect return).
Rule 5: no-unremoved-timers
Every timer set must be cleared in the same scope or in a cleanup function.
However, note that sometimes we intentionally don't clear a timer (like a one-off setTimeout that runs once and then we don't care). So we might need to be cautious.
Given the complexity of static analysis, we might have to rely on heuristics and configuration.
How to implement:
We can use ESLint and write custom rules. But since the question is about creating a linter, we can design the rules and then perhaps implement a prototype.
Alternatively, we can use an existing linter and extend it.
Since this is a complex task, we'll outline the steps for one rule as an example.
Example: Rule 1: no-uncancelled-timers
Steps:
Traverse the AST and find all AbortController instantiations (new AbortController()).
For each AbortController, look in the same scope (function block, module, etc.) for:
a. setTimeout/setInterval calls.
b. Event listeners added with addEventListener (if we consider them as resources that should be cleaned on abort? Actually, event listeners are not automatically removed on AbortController abort, so we might not require that. But we might require that if the event listener is added in the same scope as the AbortController, then it should be removed in the abort handler? Not necessarily. So maybe we don't mix event listeners with AbortController. But note: some event listeners might be set on an AbortSignal? Actually, AbortSignal has an 'abort' event, but other events are separate.)
Actually, the AbortController's signal's 'abort' event is for when the controller aborts. We want to clear timers when that happens.
So for each timer, we want to see if there's an event listener on the same AbortController's signal for 'abort' that clears that timer.
How to track:
- When we find an AbortController, note its variable name (if assigned to a variable) and the signal property.
- Then, find all timerId = setTimeout(...) or timerId = setInterval(...).
- Then, look for an event listener on controller.signal for the event 'abort' that calls clearTimeout(timerId) or clearInterval(timerId).
But note: the timerId might be a variable that is used in multiple places. We have to track the variable that holds the timer ID.
We can do:
- For each timer, record the variable that holds the timer ID (if it's assigned to a variable) and the scope.
- Then, in the abort event handler (which is added via signal.addEventListener('abort', ...) or signal.onabort = ...), check if that variable is passed to clearTimeout/clearInterval.
This is very complex because of variable scoping and multiple assignments.
Alternatively, we can enforce a pattern:
Rule: When using an AbortController, all timers must be cleared in the same function that aborts the controller, and we must have a mapping from timer IDs to clear functions.
But that's too restrictive.
Given the complexity, maybe we should focus on a simpler pattern:
Pattern 1: Using AbortController with timers in a try/finally:
So we can require that for every timer set, there must be an event listener on the controller's signal (if the controller is in the same scope) that clears it.
How to check:
code
Step 1: Find all AbortController instances (by `new AbortController()`).
Step 2: For each AbortController, get the variable name (if any) and the signal expression (usually `controller.signal`).
Step 3: For each timer set (setTimeout/setInterval) in the same scope, check if there is an event listener added to that signal for the event 'abort' that, when called, clears that timer.
But note: the timer might be stored in a variable that is used in multiple places. We have to track the variable that holds the timer ID and see if it is used in the abort handler.
But what if the timer is set conditionally? Then the abort handler must conditionally clear it? That's getting too complex.
Given the complexity, maybe we should not try to track variable usage across the entire scope but instead require that every timer set in a scope with an AbortController must be cleared in a specific way:
code
- Either in a finally block (but then we clear even on success, which might be acceptable for some timers but not all) or
- In an abort event handler that is attached to the same AbortController's signal.
And we can require that the timer ID is directly used in the clearTimeout call without any indirection? That's not always possible.
Alternatively, we can require that the timer is set and cleared in the same block and that the clear is in the abort handler.
Given the difficulty, we might have to leave this as a manual check or use a runtime approach.
However, the problem asks for a linter, so we try to catch the obvious cases.
Let's define:
Rule no-uncancelled-timers:
code
In a function that has an AbortController (either as a parameter or local variable), every call to setTimeout or setInterval must be followed by an event listener on the same AbortController's signal that calls clearTimeout or clearInterval with the same timer ID.
How to check:
code
We can look for:
const controller = ...;
const id = setTimeout(...);
controller.signal.addEventListener('abort', () => clearTimeout(id));
But note: the variable name for the controller might be different, and the timer ID variable might be used in multiple places.
We can do:
code
- For each AbortController variable (or expression) in the current scope, let's call it `abortControllerVar`.
- Then, for each timer call in the same scope, we record the variable that holds the timer ID (if it's assigned to a variable) or the expression of the timer call if not.
- Then, we look for an event listener added to `abortControllerVar.signal` (or the signal expression) for the event 'abort'. In the callback of that event listener, we check if there's a call to clearTimeout or clearInterval with the timer ID (or an expression that we can match).
This is a very hard static analysis problem.
Given the constraints, we might have to settle for a simpler rule:
code
Rule: In a function that uses an AbortController, do not use setTimeout or setInterval without also adding an abort event listener that clears it.
And we can flag:
code
if (there's an AbortController in the same scope) {
if (there's a setTimeout/setInterval that is not in the same statement as adding an abort event listener that clears it) {
flag the timer;
}
}
But that would flag:
code
const id = setTimeout(...);
// ... some code ...
controller.signal.addEventListener('abort', () => clearTimeout(id));
because the timer and the event listener are not in the same statement? That's too strict.
Alternatively, we can require that the timer and the event listener are in the same block (like the same function) and that the event listener is added before the timer? Not necessarily.
Given the complexity, I think we need to step back and consider that static analysis for cancellation safety is very hard and might require a more sophisticated approach (like data flow analysis).
However, for the purpose of this exercise, we can define a set of patterns that are safe and flag deviations.
const controller = new AbortController();
setTimeout(...); // without using the cancellableTimeout and without adding an abort listener.
So we can have two rules:
code
Rule A: Do not use setTimeout/setInterval without a corresponding clear in the abort event handler (if an AbortController is in scope).
Rule B: Use a helper function (like cancellableTimeout) that automatically sets up the abort listener.
But Rule A is hard to check, so we might only check for the helper function.
Given the complexity, maybe we should focus on React components and useEffect cleanup.
But if we are using AbortController for other async operations, we might want to clear the timer when the component unmounts or when the effect re-runs.
So in React, we can require that every timer set in useEffect is cleared in the cleanup function.
Then, for non-React code, we require the abort event listener.
Given the time, I think we have to define a set of patterns that we can reasonably check and flag the rest.
Let's define:
For any function (or React component effect) that creates an AbortController, every timer set must be cleared in one of:
code
1. The abort event handler of that AbortController's signal.
2. The cleanup function (in React) or finally block (for non-React) that runs when the function exits.
And we can also require that the same timer ID is used in the clear.
But again, tracking the same variable is hard.
Alternatively, we can require that the timer is cleared by a function that is provided by a utility (like a cancellable promise or cancellable timeout) and then we only check that the utility is used.
Given the complexity, I think for a real linter we would need to use a framework that supports data flow analysis (like TypeScript with type checking and maybe a custom type for timer IDs that are "cancellable").
But for the purpose of this response, we'll outline the rules and note that they are complex to implement.
We can instead provide a checklist for developers:
Every timer must have a clear.
When using AbortController, pass the signal to every async operation that supports it.
Every event listener must be removed.
In React, every effect that adds a listener or timer must return a cleanup function.
And we can write a linter that enforces the React patterns and the AbortController pattern for known functions.
Given the time, I'll write a simple ESLint rule for React useEffect cleanup for event listeners and timers.
Rule: react-hooks/exhaustive-deps already does some of this for dependencies, but we want to check for cleanup.
We can write a rule that checks:
code
In a useEffect, if we call addEventListener, then the return function must call removeEventListener with the same arguments.
Similarly for setTimeout/setInterval.
We can check that the arguments to addEventListener and removeEventListener match.
This is more feasible.
So let's design:
Rule: no-unremoved-event-listeners-in-effect
code
In a useEffect, for every call to addEventListener, there must be a call to removeEventListener in the return function with the same event type and the same listener (or at least the same variable for the listener).
We can do:
code
- Traverse the useEffect callback.
- Find all addEventListener calls and record the event type and the listener (if it's a variable or function expression).
- Then, in the return function, find all removeEventListener calls and check if they match.
But note: the listener might be an anonymous function, then we cannot match by reference. So we might require that the listener is assigned to a variable.
1. For React useEffect: every addEventListener must have a corresponding removeEventListener in the cleanup, and the listener must be the same variable.
2. For React useEffect: every setTimeout/setInterval must have a corresponding clearTimeout/clearInterval in the cleanup with the same timer ID.
And for non-React code with AbortController:
code
3. Every setTimer must have a corresponding clearTimer in an abort event handler of the same AbortController, and the timer ID must be the same variable.
But note: in non-React code, we might have multiple AbortControllers. We have to link the timer to the correct AbortController.
Given the complexity, we might have to limit the scope.
Given the time, I think we have to conclude that building a full cancellation safety linter is a massive undertaking and would require a sophisticated static analysis engine.
However, we can write a set of ESLint rules that cover the common patterns and flag the obvious mistakes.
Let's write one rule for React useEffect cleanup for event listeners as an example.
We'll assume we are writing an ESLint rule for React.
1. We look for CallExpressions with callee name 'useEffect'.
2. We get the first argument (the effect function) and the second argument (dependencies) but we don't care about the second.
3. We traverse the effect function body.
4. We collect all addEventListener calls and record:
- The target (object on which addEventListener is called, e.g., window, document, or a variable)
- The event type (string or variable)
- The listener (the function or variable)
We require the listener to be a variable (so we can match in the cleanup). If it's an anonymous function, we flag it.
5. Then we look at the return statement of the effect function (if it returns a function). We traverse that cleanup function.
6. In the cleanup function, we look for removeEventListener calls and check if they match one of the addEventListeners we recorded.
Matching criteria:
- Same target (or at least same variable name? We might not be able to compare objects, so we compare variable names if they are identifiers).
- Same event type (identifier or string literal).
- Same listener (identifier).
7. If we find an addEventListener that doesn't have a matching removeEventListener in the cleanup, we report an error.
Similarly for timers.
This is a simplified version.
Given the complexity of the full problem, I think we have to be pragmatic and start with these simpler rules.
We can also write a rule for AbortController and timers in non-React code, but it would be similar: we require an abort event listener that clears the timer.
- Find AbortController and the variable name (say `controller`).
- Find setTimeout and the variable that holds the timer ID (say `timerId`).
- Find an event listener on `controller.signal` for 'abort' that calls `clearTimeout(timerId)`.
But again, matching the variable timerId in the abort handler is tricky because it might be captured in a closure and we have to check that the variable in the closure is the same.
We can require that the abort handler is defined in the same scope and uses the same variable name? That's too restrictive.
Given the time, I think we have to leave the full implementation as an exercise and note that it's a research-level problem.
Instead, we can provide a set of best practices and a linter that enforces the ones that are easy to check.
Proposed set of rules:
For React:
code
- rule1: In useEffect, every addEventListener must have a matching removeEventListener in the cleanup, and the listener must be a variable (not an anonymous function).
- rule2: In useEffect, every setTimeout/setInterval must have a matching clearTimeout/clearInterval in the cleanup, and the timer ID must be a variable.
For non-React with AbortController:
code
- rule3: Every setTimeout/setInterval must be cleared in an abort event handler of an AbortController that is in the same scope, and the timer ID must be the same variable? (We might relax this to: the timer must be cleared in the same function and the clear must use the same variable that was assigned from the timer call.)
But without data flow, we can't be sure.
Given the complexity, I think we have to accept that a linter for cancellation safety will have false positives and negatives.
We might instead provide a runtime helper that does the cancellation safely and then require that developers use that helper.
Then we can write a rule that says: "Do not use setTimeout directly; use useCancellableTimeout."
That's easier to enforce.
So the linter could enforce the use of these helper functions.
Given the time, I think the best approach is to define a set of helper functions and then write a linter that requires their use.
But the problem asks for a linter that checks for timeouts, abort propagation, and leak checks.
Given the complexity, I will outline a plan for a simple linter that checks for the following:
In any function:
code
If there's an AbortController (local variable or parameter) then:
1. Every call to fetch must pass the signal (if we can determine that the function is fetch and it's in the same scope as the AbortController).
2. Every setTimeout/setInterval must be followed by an event listener on the AbortController's signal that clears it, and the clear must use the same variable that was assigned from the timer call.
But again, step 2 is very hard.
Given the time, I think we have to conclude that this is a very hard problem and we cannot provide a complete solution in this format.
Instead, we can provide a set of rules that are easy to implement and then note the limitations.
Let's write two simple rules for React and one for AbortController and fetch.
Rule 1 (React): useEffect cleanup for event listeners and timers.
Rule 2 (AbortController and fetch): In a function with an AbortController, every fetch call must include the signal.
Rule 3 (AbortController and timers): In a function with an AbortController, every setTimeout/setInterval must be cleared in an abort event handler (we'll just check that there's at least one abort event handler that clears a timer, but we won't match specific timers).
This is still hard.
Given the time, I think we should stop here and note that a complete solution requires a lot of work.
However, for the purpose of the interview, we can describe the rules and how we might implement them in a simplified manner.
Let's write a simple ESLint rule for Rule 2:
code
In a function (or block) that has an AbortController, every call to fetch must have an option with a signal property that is the AbortController's signal.
Steps:
code
- Find all AbortController instantiations and note the variable name (if any) and the signal expression (usually `controller.signal`).
- Then, for every fetch call in the same scope, check the options argument. If it's an object, check if it has a property `signal` that matches the AbortController's signal expression.
But note: the fetch might be called multiple times and the AbortController might be passed as an argument to a function that then does the fetch.
We can only check direct fetch calls.
Example:
code
const controller = new AbortController();
fetch(url, { signal: controller.signal }); // Good
const opts = { signal: controller.signal };
fetch(url, opts); // Good? We can't track `opts` easily.
So we might have to require that the signal is passed directly in the options object.
We can flag:
code
const controller = new AbortController();
const opts = { signal: controller.signal };
fetch(url, opts); // We might not flag because we can't track opts? But we could if we do a simple check: if the second argument is a variable, we check if that variable was assigned an object with a signal property that is the controller.signal. That's data flow again.
Given the complexity, we might only check the direct pattern.
So we flag:
code
fetch(url); // if there's an AbortController in the same scope and we don't see a signal option.
But that's too strict because sometimes we don't want to cancel the fetch.
So we have to be cautious.
Given the time, I think we have to accept that we cannot build a perfect linter.
Instead, we can provide a set of rules that are safe to enforce and then let the developer decide.
Proposed:
Rule: require-abortcontroller-signal-for-fetch
code
If a function has an AbortController (local variable or parameter) and it calls fetch, then the fetch must be called with an options object that has a signal property set to that AbortController's signal.
We can implement by:
code
- In the function scope, record the AbortController variable and its signal expression (if it's a simple `controller.signal`).
- Then, for each fetch call, check the second argument. If it's an object literal, check if it has a property `signal` that equals the recorded signal expression.
- If the second argument is a variable, we can try to track the variable assignment (if it's assigned in the same function and the assignment is an object literal with the signal property). But that's limited.
We can start with the direct pattern.
Given the time, I think we have to stop here.
In summary, we can build a linter that enforces:
For React:
- useEffect cleanup for event listeners and timers.
For non-React with AbortController:
- fetch must be called with the AbortController's signal (if we can determine the signal expression).
- timers must be cleared in an abort event handler (but we might not be able to link the specific timer, so we just check that there is an abort event handler that clears some timer? That's not safe.)
Given the complexity, I think the answer is that it's a hard problem and we can only provide partial solutions.
We might instead focus on runtime checks:
code
- Use a wrapper for setTimeout that returns a function that also registers an abort listener if a signal is provided.
But the question asks for a linter.
I think we have to be honest and say that building a complete cancellation safety linter is beyond the scope of a simple response and would require a team and a lot of time.
However, we can provide a set of rules that are easy to implement and then note the limitations.
Let's write one simple rule for React useEffect cleanup for event listeners.
We'll write an ESLint rule in JavaScript:
We'll use the ESLint rule template.
But note: the question doesn't specify the language for the linter, so we can describe the rule in words.
Given the time, I'll write one rule in pseudocode:
This is a very simplified version and will have many false negatives and positives.
Given the time, I think we have to stop here.
In conclusion, building a cancellation safety linter is a complex task that requires deep static analysis. We can start with simple rules for React effects and then expand to other patterns, but it will be an ongoing effort.
We might also consider using a type system (like TypeScript) to track the cancellation tokens and enforce their usage.
But for now, we'll leave it at that.
I'll help you design an async cancellation safety linter that detects common pitfalls in JavaScript/TypeScript async code. This is a complex static analysis problem, so I'll provide both conceptual rules and practical implementation strategies.
Cancellation Safety Linter: Core Rules
1. Timeout Leaks
Detects setTimeout/setInterval without proper cleanup.
javascript
// ❌ BAD - No cleanup
function badTimeout() {
const timer = setTimeout(() => console.log('hi'), 1000);
// timer never cleared
}
// ✅ GOOD - Proper cleanup
function goodTimeout(controller) {
const timer = setTimeout(() => console.log('hi'), 1000);
controller.signal.addEventListener('abort', () => clearTimeout(timer));
return () => clearTimeout(timer); // Also cleanup on return
}
Detection Strategy:
Track timer IDs from setTimeout/setInterval
Ensure every path has matching clearTimeout/clearInterval
Check for AbortController integration when present
2. Abort Signal Propagation
Ensures cancellation signals reach all async operations.
javascript
// ❌ BAD - Signal not propagated
async function badFetch(controller) {
const data = fetch('/api/data'); // Missing { signal: controller.signal }
// ...
}
// ✅ GOOD - Signal propagated
async function goodFetch(controller) {
const data = fetch('/api/data', { signal: controller.signal });
// ...
}
// ❌ BAD - Async function doesn't accept signal
async function badOperation() {
// Should accept signal parameter if doing async work
}
// ✅ GOOD - Accept and propagate signal
async function goodOperation(controller) {
await someApiCall({ signal: controller.signal });
}
Detection Strategy:
Identify functions creating AbortController
Check all fetch/XMLHttpRequest/WebSocket calls for signal
Flag async functions that should accept signal but don't
function withTimerTracking(visitor) {
return {
...visitor,
CallExpression(node) {
if (isSetTimeout(node)) trackTimer(node, context);
if (isClearTimeout(node)) markTimerCleared(node, context);
},
};
}
This linter would significantly improve reliability of async code by catching cancellation safety issues at compile time rather than runtime. The key is starting with high-value, low-false-positive rules and gradually increasing sophistication.
// We'll use the ESLint API.
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Ensure event listeners added in useEffect are removed in the cleanup function',
},
schema: [], // no options
},
create(context) {
// We'll look for useEffect calls.
return {
CallExpression(node) {
if (node.callee.name !== 'useEffect') {
return;
}
// We expect the first argument to be a function (the effect) and the second to be an array (dependencies) but we don't care.
const effectFunction = node.arguments[0];
if (!effectFunction || effectFunction.type !== 'FunctionExpression' && effectFunction.type !== 'ArrowFunctionExpression') {
return;
}
// We'll collect all addEventListener calls in the effect function body.
const addEventListeners = [];
const cleanupFunction = null;
// Traverse the effect function body.
traverse(effectFunction.body, {
CallExpression(innerNode) {
if (innerNode.callee.property && innerNode.callee.property.name === 'addEventListener') {
// We record the target, event type, and listener.
// We require that the listener is an identifier (so we can match in cleanup).
const [target, eventType, listener, options] = innerNode.arguments;
if (listener.type === 'Identifier') {
addEventListeners.push({
target: target,
eventType: eventType,
listener: listener,
node: innerNode,
});
} else {
// Flag: listener should be an identifier to be removable.
context.report({
node: listener,
message: 'Event listener must be assigned to a variable to be removable in cleanup.',
});
}
}
},
});
// Now, look for the return statement in the effect function that returns a cleanup function.
// We assume the effect function returns a function (the cleanup).
// We look for a ReturnStatement in the effect function body that returns a FunctionExpression.
// This is a simplified version: we look for a return statement that returns a function and then traverse that function for removeEventListener.
// We'll do a second traversal of the effect function body to find the return statement.
let cleanupFunctionNode = null;
traverse(effectFunction.body, {
ReturnStatement(returnNode) {
if (returnNode.argument && (returnNode.argument.type === 'FunctionExpression' || returnNode.argument.type === 'ArrowFunctionExpression')) {
cleanupFunctionNode = returnNode.argument;
}
},
});
if (!cleanupFunctionNode) {
// If there's no cleanup function and we have event listeners, flag.
if (addEventListeners.length > 0) {
context.report({
node: effectFunction,
message: 'Effect has event listeners but no cleanup function.',
});
}
return;
}
// Now, traverse the cleanup function and collect removeEventListener calls.
const removeEventListeners = [];
traverse(cleanupFunctionNode.body, {
CallExpression(innerNode) {
if (innerNode.callee.property && innerNode.callee.property.name === 'removeEventListener') {
const [target, eventType, listener, options] = innerNode.arguments;
if (listener.type === 'Identifier') {
removeEventListeners.push({
target: target,
eventType: eventType,
listener: listener,
node: innerNode,
});
}
}
},
});
// Now, for each addEventListener, check if there's a matching removeEventListener.
for (const add of addEventListeners) {
const match = removeEventListeners.find(remove =>
// Compare target, eventType, and listener.
// We compare by code (string representation) or by node identity? We can compare the code of the expression.
// This is not perfect but works for simple cases.
remove.target.toString() === add.target.toString() &&
remove.eventType.toString() === add.eventType.toString() &&
remove.listener.name === add.listener.name
);
if (!match) {
context.report({
node: add.node,
message: 'Event listener added but not removed in cleanup.',
});
}
}
},
};
},
};