@economic/taco-rules 2.0.0 → 2.1.0-EC-87491-formatting-config.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -402,6 +402,48 @@ escape sequences are regenerated for the new quote style. The chosen quote
402
402
  never introduces an escape: double quotes when the content contains a single
403
403
  quote, single quotes otherwise.
404
404
 
405
+ ### `taco/require-timer-cleanup`
406
+
407
+ Part of the `recommended` config. Flags `setTimeout`/`setInterval` calls
408
+ started directly by a `useEffect` or `useLayoutEffect` callback (or a custom
409
+ effect hook listed in `additionalHooks`, see below) when the
410
+ effect's cleanup does not clear them with the matching function
411
+ (`clearTimeout` for `setTimeout`, `clearInterval` for `setInterval` and `cancelAnimationFrame` for `requestAnimationFrame`):
412
+
413
+ ```tsx
414
+ useEffect(() => {
415
+ setTimeout(() => setReady(true), 1); // ✗ fires after unmount / stale deps
416
+ }, [ready]);
417
+
418
+ useEffect(() => {
419
+ const id = setTimeout(() => setReady(true), 1); // ✓
420
+ return () => clearTimeout(id);
421
+ }, [ready]);
422
+ ```
423
+
424
+ Each timer must be stored in a handle (`const id = …`, `ref.current = …`) and
425
+ that same handle passed to the matching clear call inside the cleanup function
426
+ the effect returns (inline, or a local function returned by name); clearing one
427
+ handle does not satisfy another timer, a clear inside an event handler or
428
+ promise callback does not count — it never runs on unmount — and a handle
429
+ reassigned to a second timer without a synchronous clear in between orphans
430
+ that timer (a clear inside a timer callback is deferred and does not count).
431
+
432
+ When an effect returns different cleanup functions from different branches,
433
+ their clears are pooled rather than checked per branch. Timers chained from another
434
+ timer's callback count as owned by the effect, so a nested
435
+ `setTimeout` needs its own handle and its own `clearTimeout`. Timers started
436
+ from nested handlers (event listeners, promise callbacks) are not flagged —
437
+ clearing them is the handler's concern.
438
+
439
+ Custom hooks that take an effect callback with the same contract as
440
+ `useEffect` (returns an optional cleanup) can be checked too via
441
+ `additionalHooks`. These are added to the built-in hooks, not substituted for them:
442
+
443
+ ```json
444
+ "taco/require-timer-cleanup": ["error", { "additionalHooks": ["useLazyEffect"] }]
445
+ ```
446
+
405
447
  ## Why string-literal-wide rather than className-only?
406
448
 
407
449
  The rules visit every string literal and every template element in the file
@@ -12,6 +12,7 @@ import noLeakedRender from "./no-leaked-render/no-leaked-render.js";
12
12
  import noReactUseId from "./no-react-useid/no-react-useid.js";
13
13
  import noSeparateSizeClasses from "./no-separate-size-classes/no-separate-size-classes.js";
14
14
  import noUnnecessaryTemplateLiteral from "./no-unnecessary-template-literal/no-unnecessary-template-literal.js";
15
+ import requireTimerCleanup from "./require-timer-cleanup/require-timer-cleanup.js";
15
16
  export const rules = {
16
17
  'consistent-clsx-import': consistentClsxImport,
17
18
  'data-taco-kebab-case': dataTacoKebabCase,
@@ -27,4 +28,5 @@ export const rules = {
27
28
  'no-react-useid': noReactUseId,
28
29
  'no-separate-size-classes': noSeparateSizeClasses,
29
30
  'no-unnecessary-template-literal': noUnnecessaryTemplateLiteral,
31
+ 'require-timer-cleanup': requireTimerCleanup,
30
32
  };
@@ -0,0 +1,2 @@
1
+ declare const _default: import("@oxlint/plugins").Rule;
2
+ export default _default;
@@ -0,0 +1,370 @@
1
+ import { defineRule } from '@oxlint/plugins';
2
+ // Requires timers started inside an effect to be cleared by that effect's cleanup. A `setTimeout`
3
+ // that fires after the deps change or the component unmounts calls stale setters and touches
4
+ // detached refs; the fix is always `const id = setTimeout(…); return () => clearTimeout(id)`.
5
+ //
6
+ // Detection is syntactic. A timer is "owned" by the effect when its nearest enclosing function is
7
+ // the effect callback itself (or a timer callback chained from it); timers started from nested
8
+ // handlers (event listeners, promise callbacks) are the handler's responsibility and are skipped.
9
+ // An owned timer passes only when it is stored in a handle and that same handle is passed to the
10
+ // matching clear function synchronously inside the cleanup the effect returns (inline, or a local
11
+ // function returned by name). A handle reassigned to a second timer without a synchronous clear in
12
+ // between orphans the first timer and is reported as well. Alternative cleanups returned from
13
+ // different branches are merged rather than checked per path. A clear under a conditional in the
14
+ // cleanup does not satisfy a timer started under the opposite arm of a condition with the same
15
+ // source text (`immediate ? raf() : setTimeout()` vs `immediate ? clearTimeout() : cancel…()`).
16
+ const BUILTIN_EFFECT_HOOKS = ['useEffect', 'useLayoutEffect'];
17
+ const TIMER_TO_CLEAR = new Map([
18
+ ['setTimeout', 'clearTimeout'],
19
+ ['setInterval', 'clearInterval'],
20
+ ['requestAnimationFrame', 'cancelAnimationFrame'],
21
+ ]);
22
+ const CLEAR_NAMES = new Set(TIMER_TO_CLEAR.values());
23
+ const NESTED_FUNCTION_TYPES = new Set(['ArrowFunctionExpression', 'FunctionExpression', 'FunctionDeclaration']);
24
+ const REASSIGNED_HANDLE_MESSAGE = (handle, timerName) => `\`${handle}\` is reassigned to another \`${timerName}\` before this one is cleared; the cleanup only clears the last timer stored in it.`;
25
+ const UNCLEARED_TIMER_MESSAGE = (timerName, clearName) => `\`${timerName}\` started in an effect must be stored in a handle and cleared with \`${clearName}\` in the effect's cleanup function.`;
26
+ function isNode(value) {
27
+ return typeof value === 'object' && value !== null && typeof value.type === 'string';
28
+ }
29
+ function isFunction(node) {
30
+ return isNode(node) && (node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression');
31
+ }
32
+ // `setTimeout`, `window.setTimeout`, `globalThis.setTimeout`
33
+ function getGlobalCalleeName(callee) {
34
+ if (callee.type === 'Identifier') {
35
+ return callee.name;
36
+ }
37
+ if (callee.type === 'MemberExpression' &&
38
+ !callee.computed &&
39
+ callee.object.type === 'Identifier' &&
40
+ (callee.object.name === 'window' || callee.object.name === 'globalThis') &&
41
+ callee.property.type === 'Identifier') {
42
+ return callee.property.name;
43
+ }
44
+ return undefined;
45
+ }
46
+ // `useEffect`, `React.useEffect`
47
+ function isEffectHookCall(node, effectHooks) {
48
+ const { callee } = node;
49
+ if (callee.type === 'Identifier') {
50
+ return effectHooks.has(callee.name);
51
+ }
52
+ return (callee.type === 'MemberExpression' &&
53
+ !callee.computed &&
54
+ callee.property.type === 'Identifier' &&
55
+ effectHooks.has(callee.property.name));
56
+ }
57
+ function forEachChild(node, visit) {
58
+ for (const [key, value] of Object.entries(node)) {
59
+ if (key === 'parent') {
60
+ continue;
61
+ }
62
+ if (Array.isArray(value)) {
63
+ for (const item of value) {
64
+ if (isNode(item)) {
65
+ visit(item);
66
+ }
67
+ }
68
+ }
69
+ else if (isNode(value)) {
70
+ visit(value);
71
+ }
72
+ }
73
+ }
74
+ function unwrapExpression(node) {
75
+ return node.type === 'TSNonNullExpression' ||
76
+ node.type === 'TSAsExpression' ||
77
+ node.type === 'TSSatisfiesExpression' ||
78
+ node.type === 'ParenthesizedExpression'
79
+ ? unwrapExpression(node.expression)
80
+ : node;
81
+ }
82
+ // Stable key for the expression a timer handle is stored in: `id`, `timers.current`, …
83
+ function getHandleKey(rawNode) {
84
+ const node = unwrapExpression(rawNode);
85
+ if (node.type === 'Identifier') {
86
+ return node.name;
87
+ }
88
+ if (node.type === 'MemberExpression' && !node.computed && node.property.type === 'Identifier') {
89
+ const objectKey = getHandleKey(node.object);
90
+ return objectKey === undefined ? undefined : `${objectKey}.${node.property.name}`;
91
+ }
92
+ return undefined;
93
+ }
94
+ function getTimerName(node) {
95
+ if (node.type !== 'CallExpression') {
96
+ return undefined;
97
+ }
98
+ const name = getGlobalCalleeName(node.callee);
99
+ return name !== undefined && TIMER_TO_CLEAR.has(name) ? name : undefined;
100
+ }
101
+ // `setTimeout(…)`, a ternary with a timer in either arm, or `cond && setTimeout(…)` — expressions
102
+ // whose result lands in the handle.
103
+ function isTimerInitializer(rawNode) {
104
+ const node = unwrapExpression(rawNode);
105
+ if (node.type === 'ConditionalExpression') {
106
+ return isTimerInitializer(node.consequent) || isTimerInitializer(node.alternate);
107
+ }
108
+ if (node.type === 'LogicalExpression' && node.operator === '&&') {
109
+ return isTimerInitializer(node.right);
110
+ }
111
+ return getTimerName(node) !== undefined;
112
+ }
113
+ // Every `clearTimeout(x)`/`clearInterval(x)` reached synchronously from `node` — nested functions
114
+ // are not entered, since a clear inside a deferred callback does not run when the cleanup does.
115
+ // Keyed as `clearTimeout:x` so a clear only satisfies the timer whose handle it receives, and
116
+ // recorded with its enclosing conditional arms so it can be matched against the timer's.
117
+ function collectClearCalls(node, into, branches) {
118
+ if (node.type === 'CallExpression') {
119
+ const name = getGlobalCalleeName(node.callee);
120
+ if (name !== undefined && CLEAR_NAMES.has(name)) {
121
+ const argument = node.arguments[0];
122
+ const handle = isNode(argument) ? getHandleKey(argument) : undefined;
123
+ if (handle !== undefined) {
124
+ into.push({ key: `${name}:${handle}`, branches });
125
+ }
126
+ }
127
+ }
128
+ if (NESTED_FUNCTION_TYPES.has(node.type)) {
129
+ return;
130
+ }
131
+ if (node.type === 'IfStatement' || node.type === 'ConditionalExpression') {
132
+ collectClearCalls(node.test, into, branches);
133
+ collectClearCalls(node.consequent, into, [...branches, { node, arm: 'consequent' }]);
134
+ if (node.alternate) {
135
+ collectClearCalls(node.alternate, into, [...branches, { node, arm: 'alternate' }]);
136
+ }
137
+ return;
138
+ }
139
+ forEachChild(node, child => collectClearCalls(child, into, branches));
140
+ }
141
+ function collectClearCallsInFunction(fn, into) {
142
+ forEachChild(fn, child => collectClearCalls(child, into, []));
143
+ }
144
+ // `return` statements belonging to the effect callback itself (not to nested functions).
145
+ function collectOwnReturns(node, into) {
146
+ if (node.type === 'ReturnStatement') {
147
+ into.push(node);
148
+ return;
149
+ }
150
+ if (NESTED_FUNCTION_TYPES.has(node.type)) {
151
+ return;
152
+ }
153
+ forEachChild(node, child => collectOwnReturns(child, into));
154
+ }
155
+ // Local functions declared in the effect body, by name, so `return cleanup` can be resolved.
156
+ function collectLocalFunctions(node, into) {
157
+ if (node.type === 'FunctionDeclaration' && node.id) {
158
+ into.set(node.id.name, node);
159
+ return;
160
+ }
161
+ if (node.type === 'VariableDeclarator' && node.id.type === 'Identifier' && isFunction(node.init)) {
162
+ into.set(node.id.name, node.init);
163
+ return;
164
+ }
165
+ if (NESTED_FUNCTION_TYPES.has(node.type)) {
166
+ return;
167
+ }
168
+ forEachChild(node, child => collectLocalFunctions(child, into));
169
+ }
170
+ // The cleanup function(s) the effect returns — either inline or a local function returned by name.
171
+ // Only clears inside these count: a clear in an event handler or promise callback does not run on unmount.
172
+ function collectCleanupFunctions(effectBody) {
173
+ const returns = [];
174
+ collectOwnReturns(effectBody, returns);
175
+ const localFunctions = new Map();
176
+ collectLocalFunctions(effectBody, localFunctions);
177
+ const cleanups = [];
178
+ for (const { argument } of returns) {
179
+ if (!argument) {
180
+ continue;
181
+ }
182
+ if (isFunction(argument)) {
183
+ cleanups.push(argument);
184
+ }
185
+ else if (argument.type === 'Identifier') {
186
+ const local = localFunctions.get(argument.name);
187
+ if (local) {
188
+ cleanups.push(local);
189
+ }
190
+ }
191
+ }
192
+ return cleanups;
193
+ }
194
+ // Timer calls owned by the effect, and the clears the effect body performs synchronously, in
195
+ // source order. Owned means reached without crossing into a nested function, except for callbacks
196
+ // passed directly to another timer (`setTimeout(() => { setTimeout(…) })`); clears inside those
197
+ // callbacks run later, not as part of the body, so they are not recorded. Each timer is recorded
198
+ // with the handle it is stored in, if any.
199
+ function collectTimerEvents(node, into, options) {
200
+ const unwrapped = unwrapExpression(node);
201
+ if (unwrapped !== node) {
202
+ collectTimerEvents(unwrapped, into, options);
203
+ return;
204
+ }
205
+ const { deferred, branches } = options;
206
+ const timerName = getTimerName(node);
207
+ if (timerName !== undefined && node.type === 'CallExpression') {
208
+ into.push({ kind: 'timer', call: node, timerName, handle: options.handle, deferred, branches });
209
+ const callback = node.arguments[0];
210
+ if (isFunction(callback) && callback.body) {
211
+ collectTimerEvents(callback.body, into, { deferred: true, branches: [] });
212
+ }
213
+ return;
214
+ }
215
+ if (node.type === 'IfStatement' || node.type === 'ConditionalExpression') {
216
+ // A ternary's arms are its value, so they inherit the handle it is stored in; an `if`'s are statements.
217
+ const handle = node.type === 'ConditionalExpression' ? options.handle : undefined;
218
+ collectTimerEvents(node.test, into, { deferred, branches });
219
+ collectTimerEvents(node.consequent, into, {
220
+ handle,
221
+ deferred,
222
+ branches: [...branches, { node, arm: 'consequent' }],
223
+ });
224
+ if (node.alternate) {
225
+ collectTimerEvents(node.alternate, into, {
226
+ handle,
227
+ deferred,
228
+ branches: [...branches, { node, arm: 'alternate' }],
229
+ });
230
+ }
231
+ return;
232
+ }
233
+ if (node.type === 'LogicalExpression' && node.operator === '&&' && options.handle !== undefined) {
234
+ collectTimerEvents(node.left, into, { deferred, branches });
235
+ collectTimerEvents(node.right, into, { handle: options.handle, deferred, branches });
236
+ return;
237
+ }
238
+ if (node.type === 'CallExpression' && !options.deferred) {
239
+ const name = getGlobalCalleeName(node.callee);
240
+ if (name !== undefined && CLEAR_NAMES.has(name)) {
241
+ const argument = node.arguments[0];
242
+ const cleared = isNode(argument) ? getHandleKey(argument) : undefined;
243
+ if (cleared !== undefined) {
244
+ into.push({ kind: 'clear', key: `${name}:${cleared}` });
245
+ }
246
+ }
247
+ }
248
+ if (node.type === 'VariableDeclarator' && node.init && isTimerInitializer(node.init)) {
249
+ collectTimerEvents(node.init, into, { handle: getHandleKey(node.id), deferred, branches });
250
+ return;
251
+ }
252
+ if (node.type === 'AssignmentExpression' && node.operator === '=' && isTimerInitializer(node.right)) {
253
+ collectTimerEvents(node.right, into, { handle: getHandleKey(node.left), deferred, branches });
254
+ return;
255
+ }
256
+ if (NESTED_FUNCTION_TYPES.has(node.type)) {
257
+ return;
258
+ }
259
+ forEachChild(node, child => collectTimerEvents(child, into, { deferred, branches }));
260
+ }
261
+ function inExclusiveBranches(a, b) {
262
+ return a.branches.some(x => b.branches.some(y => x.node === y.node && x.arm !== y.arm));
263
+ }
264
+ // The cleanup's conditionals are different nodes from the body's, so arms are paired by the source
265
+ // text of their test: the cleanup closure sees the same values the body branched on. Conditions the
266
+ // timer was not started under (e.g. an `if (id)` guard) don't constrain the match.
267
+ function clearReachesTimer(context, clear, timer) {
268
+ return !clear.branches.some(x => {
269
+ const clearTest = context.sourceCode.getText(x.node.test);
270
+ return timer.branches.some(y => y.arm !== x.arm && context.sourceCode.getText(y.node.test) === clearTest);
271
+ });
272
+ }
273
+ function checkEffect(context, effectCallback) {
274
+ if (!effectCallback.body) {
275
+ return;
276
+ }
277
+ const events = [];
278
+ collectTimerEvents(effectCallback.body, events, { deferred: false, branches: [] });
279
+ const timerCalls = events.filter((event) => event.kind === 'timer');
280
+ if (timerCalls.length === 0) {
281
+ return;
282
+ }
283
+ // Clears performed by any cleanup the effect returns. Alternative cleanups (one per return
284
+ // path) are merged: checking that every path clears every handle would need control-flow
285
+ // analysis and would flag branches that legitimately own different timers.
286
+ const cleanupClears = [];
287
+ for (const cleanup of collectCleanupFunctions(effectCallback.body)) {
288
+ collectClearCallsInFunction(cleanup, cleanupClears);
289
+ }
290
+ // Replay the effect body in source order: a handle may only hold one outstanding timer, so
291
+ // storing a second timer in it before a synchronous clear orphans the first. Deferred timers
292
+ // (started inside another timer's callback) are excluded: their assignments run only after the
293
+ // outer timer fired, so a self-rescheduling loop like
294
+ // `id = requestAnimationFrame(function loop() { id = requestAnimationFrame(loop) })`
295
+ // never holds two outstanding timers in the handle.
296
+ const outstanding = new Map();
297
+ for (const event of events) {
298
+ if (event.kind === 'clear') {
299
+ for (const [handle, timer] of outstanding) {
300
+ if (event.key === `${TIMER_TO_CLEAR.get(timer.timerName)}:${handle}`) {
301
+ outstanding.delete(handle);
302
+ }
303
+ }
304
+ continue;
305
+ }
306
+ if (event.handle === undefined || event.deferred) {
307
+ continue;
308
+ }
309
+ const previous = outstanding.get(event.handle);
310
+ if (previous && !inExclusiveBranches(previous, event)) {
311
+ context.report({
312
+ node: previous.call,
313
+ message: REASSIGNED_HANDLE_MESSAGE(event.handle, event.timerName),
314
+ });
315
+ }
316
+ outstanding.set(event.handle, event);
317
+ }
318
+ for (const timer of timerCalls) {
319
+ const { call, timerName, handle } = timer;
320
+ const clearName = TIMER_TO_CLEAR.get(timerName);
321
+ if (clearName === undefined) {
322
+ continue;
323
+ }
324
+ const key = `${clearName}:${handle}`;
325
+ const cleared = handle !== undefined && cleanupClears.some(clear => clear.key === key && clearReachesTimer(context, clear, timer));
326
+ if (!cleared) {
327
+ context.report({
328
+ node: call,
329
+ message: UNCLEARED_TIMER_MESSAGE(timerName, clearName),
330
+ });
331
+ }
332
+ }
333
+ }
334
+ export default defineRule({
335
+ meta: {
336
+ type: 'problem',
337
+ docs: {
338
+ description: 'Require timers and animation frames started in useEffect/useLayoutEffect to be cleared in the cleanup function.',
339
+ recommended: true,
340
+ },
341
+ schema: [
342
+ {
343
+ type: 'object',
344
+ properties: {
345
+ additionalHooks: { type: 'array', items: { type: 'string' }, uniqueItems: true },
346
+ },
347
+ additionalProperties: false,
348
+ },
349
+ ],
350
+ },
351
+ createOnce(context) {
352
+ // Options are per file, so they can only be read once linting of a file starts.
353
+ let effectHooks = new Set(BUILTIN_EFFECT_HOOKS);
354
+ return {
355
+ before() {
356
+ const [{ additionalHooks = [] } = {}] = context.options;
357
+ effectHooks = new Set([...BUILTIN_EFFECT_HOOKS, ...additionalHooks]);
358
+ },
359
+ CallExpression(node) {
360
+ if (!isEffectHookCall(node, effectHooks)) {
361
+ return;
362
+ }
363
+ const effectCallback = node.arguments[0];
364
+ if (isFunction(effectCallback)) {
365
+ checkEffect(context, effectCallback);
366
+ }
367
+ },
368
+ };
369
+ },
370
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@economic/taco-rules",
3
- "version": "2.0.0",
3
+ "version": "2.1.0-EC-87491-formatting-config.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -64,5 +64,5 @@
64
64
  "typescript": "^5.9.3",
65
65
  "vitest": "^4.1.12"
66
66
  },
67
- "gitHead": "c998df158f2898eee1e3abb38594110e4923b055"
67
+ "gitHead": "a6631be49b1c76f50308f514179d1402cf221117"
68
68
  }