eslint-plugin-react-hooks 5.1.0-rc.0 → 5.1.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.
@@ -8,2627 +8,2031 @@
8
8
  * LICENSE file in the root directory of this source tree.
9
9
  */
10
10
 
11
- 'use strict';
12
-
13
- if (process.env.NODE_ENV !== "production") {
14
- (function() {
15
- 'use strict';
16
-
17
- function _unsupportedIterableToArray(o, minLen) {
18
- if (!o) return;
19
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
20
- var n = Object.prototype.toString.call(o).slice(8, -1);
21
- if (n === "Object" && o.constructor) n = o.constructor.name;
22
- if (n === "Map" || n === "Set") return Array.from(o);
23
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
24
- }
25
-
26
- function _arrayLikeToArray(arr, len) {
27
- if (len == null || len > arr.length) len = arr.length;
28
-
29
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
30
-
31
- return arr2;
32
- }
33
-
34
- function _createForOfIteratorHelper(o, allowArrayLike) {
35
- var it;
36
-
37
- if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
38
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
39
- if (it) o = it;
40
- var i = 0;
41
-
42
- var F = function () {};
43
-
44
- return {
45
- s: F,
46
- n: function () {
47
- if (i >= o.length) return {
48
- done: true
49
- };
11
+ "use strict";
12
+ "production" !== process.env.NODE_ENV &&
13
+ (function () {
14
+ function _unsupportedIterableToArray(o, minLen) {
15
+ if (o) {
16
+ if ("string" === typeof o) return _arrayLikeToArray(o, minLen);
17
+ var n = Object.prototype.toString.call(o).slice(8, -1);
18
+ "Object" === n && o.constructor && (n = o.constructor.name);
19
+ if ("Map" === n || "Set" === n) return Array.from(o);
20
+ if (
21
+ "Arguments" === n ||
22
+ /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)
23
+ )
24
+ return _arrayLikeToArray(o, minLen);
25
+ }
26
+ }
27
+ function _arrayLikeToArray(arr, len) {
28
+ if (null == len || len > arr.length) len = arr.length;
29
+ for (var i = 0, arr2 = Array(len); i < len; i++) arr2[i] = arr[i];
30
+ return arr2;
31
+ }
32
+ function _createForOfIteratorHelper(o, allowArrayLike) {
33
+ var it;
34
+ if ("undefined" === typeof Symbol || null == o[Symbol.iterator]) {
35
+ if (
36
+ Array.isArray(o) ||
37
+ (it = _unsupportedIterableToArray(o)) ||
38
+ (allowArrayLike && o && "number" === typeof o.length)
39
+ ) {
40
+ it && (o = it);
41
+ var i = 0;
42
+ allowArrayLike = function () {};
50
43
  return {
51
- done: false,
52
- value: o[i++]
44
+ s: allowArrayLike,
45
+ n: function () {
46
+ return i >= o.length ? { done: !0 } : { done: !1, value: o[i++] };
47
+ },
48
+ e: function (e) {
49
+ throw e;
50
+ },
51
+ f: allowArrayLike
53
52
  };
53
+ }
54
+ throw new TypeError(
55
+ "Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
56
+ );
57
+ }
58
+ var normalCompletion = !0,
59
+ didErr = !1,
60
+ err;
61
+ return {
62
+ s: function () {
63
+ it = o[Symbol.iterator]();
64
+ },
65
+ n: function () {
66
+ var step = it.next();
67
+ normalCompletion = step.done;
68
+ return step;
54
69
  },
55
70
  e: function (e) {
56
- throw e;
71
+ didErr = !0;
72
+ err = e;
57
73
  },
58
- f: F
74
+ f: function () {
75
+ try {
76
+ normalCompletion || null == it.return || it.return();
77
+ } finally {
78
+ if (didErr) throw err;
79
+ }
80
+ }
59
81
  };
60
82
  }
61
-
62
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
63
- }
64
-
65
- var normalCompletion = true,
66
- didErr = false,
67
- err;
68
- return {
69
- s: function () {
70
- it = o[Symbol.iterator]();
71
- },
72
- n: function () {
73
- var step = it.next();
74
- normalCompletion = step.done;
75
- return step;
76
- },
77
- e: function (e) {
78
- didErr = true;
79
- err = e;
80
- },
81
- f: function () {
82
- try {
83
- if (!normalCompletion && it.return != null) it.return();
84
- } finally {
85
- if (didErr) throw err;
83
+ function isHook(node) {
84
+ if ("Identifier" === node.type)
85
+ return (node = node.name), "use" === node || /^use[A-Z0-9]/.test(node);
86
+ if (
87
+ "MemberExpression" === node.type &&
88
+ !node.computed &&
89
+ isHook(node.property)
90
+ ) {
91
+ node = node.object;
92
+ var isPascalCaseNameSpace = /^[A-Z].*/;
93
+ return (
94
+ "Identifier" === node.type && isPascalCaseNameSpace.test(node.name)
95
+ );
86
96
  }
97
+ return !1;
87
98
  }
88
- };
89
- }
90
-
91
- /* global BigInt */
92
-
93
- function isHookName(s) {
94
- return s === 'use' || /^use[A-Z0-9]/.test(s);
95
- }
96
- /**
97
- * We consider hooks to be a hook name identifier or a member expression
98
- * containing a hook name.
99
- */
100
-
101
-
102
- function isHook(node) {
103
- if (node.type === 'Identifier') {
104
- return isHookName(node.name);
105
- } else if (node.type === 'MemberExpression' && !node.computed && isHook(node.property)) {
106
- var obj = node.object;
107
- var isPascalCaseNameSpace = /^[A-Z].*/;
108
- return obj.type === 'Identifier' && isPascalCaseNameSpace.test(obj.name);
109
- } else {
110
- return false;
111
- }
112
- }
113
- /**
114
- * Checks if the node is a React component name. React component names must
115
- * always start with an uppercase letter.
116
- */
117
-
118
-
119
- function isComponentName(node) {
120
- return node.type === 'Identifier' && /^[A-Z]/.test(node.name);
121
- }
122
-
123
- function isReactFunction(node, functionName) {
124
- return node.name === functionName || node.type === 'MemberExpression' && node.object.name === 'React' && node.property.name === functionName;
125
- }
126
- /**
127
- * Checks if the node is a callback argument of forwardRef. This render function
128
- * should follow the rules of hooks.
129
- */
130
-
131
-
132
- function isForwardRefCallback(node) {
133
- return !!(node.parent && node.parent.callee && isReactFunction(node.parent.callee, 'forwardRef'));
134
- }
135
- /**
136
- * Checks if the node is a callback argument of React.memo. This anonymous
137
- * functional component should follow the rules of hooks.
138
- */
139
-
140
-
141
- function isMemoCallback(node) {
142
- return !!(node.parent && node.parent.callee && isReactFunction(node.parent.callee, 'memo'));
143
- }
144
-
145
- function isInsideComponentOrHook(node) {
146
- while (node) {
147
- var functionName = getFunctionName(node);
148
-
149
- if (functionName) {
150
- if (isComponentName(functionName) || isHook(functionName)) {
151
- return true;
99
+ function isComponentName(node) {
100
+ return "Identifier" === node.type && /^[A-Z]/.test(node.name);
101
+ }
102
+ function isReactFunction(node, functionName) {
103
+ return (
104
+ node.name === functionName ||
105
+ ("MemberExpression" === node.type &&
106
+ "React" === node.object.name &&
107
+ node.property.name === functionName)
108
+ );
109
+ }
110
+ function isForwardRefCallback(node) {
111
+ return !!(
112
+ node.parent &&
113
+ node.parent.callee &&
114
+ isReactFunction(node.parent.callee, "forwardRef")
115
+ );
116
+ }
117
+ function isMemoCallback(node) {
118
+ return !!(
119
+ node.parent &&
120
+ node.parent.callee &&
121
+ isReactFunction(node.parent.callee, "memo")
122
+ );
123
+ }
124
+ function isInsideComponentOrHook(node) {
125
+ for (; node; ) {
126
+ var functionName = getFunctionName(node);
127
+ if (
128
+ (functionName &&
129
+ (isComponentName(functionName) || isHook(functionName))) ||
130
+ isForwardRefCallback(node) ||
131
+ isMemoCallback(node)
132
+ )
133
+ return !0;
134
+ node = node.parent;
152
135
  }
136
+ return !1;
153
137
  }
154
-
155
- if (isForwardRefCallback(node) || isMemoCallback(node)) {
156
- return true;
138
+ function getFunctionName(node) {
139
+ if (
140
+ "FunctionDeclaration" === node.type ||
141
+ ("FunctionExpression" === node.type && node.id)
142
+ )
143
+ return node.id;
144
+ if (
145
+ "FunctionExpression" === node.type ||
146
+ "ArrowFunctionExpression" === node.type
147
+ )
148
+ return "VariableDeclarator" === node.parent.type &&
149
+ node.parent.init === node
150
+ ? node.parent.id
151
+ : "AssignmentExpression" === node.parent.type &&
152
+ node.parent.right === node &&
153
+ "=" === node.parent.operator
154
+ ? node.parent.left
155
+ : "Property" !== node.parent.type ||
156
+ node.parent.value !== node ||
157
+ node.parent.computed
158
+ ? "AssignmentPattern" !== node.parent.type ||
159
+ node.parent.right !== node ||
160
+ node.parent.computed
161
+ ? void 0
162
+ : node.parent.left
163
+ : node.parent.key;
157
164
  }
158
-
159
- node = node.parent;
160
- }
161
-
162
- return false;
163
- }
164
-
165
- function isUseEffectEventIdentifier$1(node) {
166
-
167
- return false;
168
- }
169
-
170
- function isUseIdentifier(node) {
171
- return isReactFunction(node, 'use');
172
- }
173
-
174
- var RulesOfHooks = {
175
- meta: {
176
- type: 'problem',
177
- docs: {
178
- description: 'enforces the Rules of Hooks',
179
- recommended: true,
180
- url: 'https://reactjs.org/docs/hooks-rules.html'
165
+ function collectRecommendations(_ref6) {
166
+ function createDepTree() {
167
+ return {
168
+ isUsed: !1,
169
+ isSatisfiedRecursively: !1,
170
+ isSubtreeUsed: !1,
171
+ children: new Map()
172
+ };
173
+ }
174
+ function getOrCreateNodeByPath(rootNode, path) {
175
+ path = path.split(".");
176
+ path = _createForOfIteratorHelper(path);
177
+ var _step4;
178
+ try {
179
+ for (path.s(); !(_step4 = path.n()).done; ) {
180
+ var key = _step4.value,
181
+ child = rootNode.children.get(key);
182
+ child ||
183
+ ((child = createDepTree()), rootNode.children.set(key, child));
184
+ rootNode = child;
185
+ }
186
+ } catch (err) {
187
+ path.e(err);
188
+ } finally {
189
+ path.f();
190
+ }
191
+ return rootNode;
192
+ }
193
+ function markAllParentsByPath(rootNode, path, fn) {
194
+ path = path.split(".");
195
+ path = _createForOfIteratorHelper(path);
196
+ var _step5;
197
+ try {
198
+ for (path.s(); !(_step5 = path.n()).done; ) {
199
+ var child = rootNode.children.get(_step5.value);
200
+ if (!child) break;
201
+ fn(child);
202
+ rootNode = child;
203
+ }
204
+ } catch (err) {
205
+ path.e(err);
206
+ } finally {
207
+ path.f();
208
+ }
209
+ }
210
+ function scanTreeRecursively(
211
+ node,
212
+ missingPaths,
213
+ satisfyingPaths,
214
+ keyToPath
215
+ ) {
216
+ node.children.forEach(function (child, key) {
217
+ var path = keyToPath(key);
218
+ child.isSatisfiedRecursively
219
+ ? child.isSubtreeUsed && satisfyingPaths.add(path)
220
+ : child.isUsed
221
+ ? missingPaths.add(path)
222
+ : scanTreeRecursively(
223
+ child,
224
+ missingPaths,
225
+ satisfyingPaths,
226
+ function (childKey) {
227
+ return path + "." + childKey;
228
+ }
229
+ );
230
+ });
231
+ }
232
+ var dependencies = _ref6.dependencies,
233
+ declaredDependencies = _ref6.declaredDependencies,
234
+ stableDependencies = _ref6.stableDependencies,
235
+ externalDependencies = _ref6.externalDependencies,
236
+ isEffect = _ref6.isEffect,
237
+ depTree = createDepTree();
238
+ dependencies.forEach(function (_, key) {
239
+ getOrCreateNodeByPath(depTree, key).isUsed = !0;
240
+ markAllParentsByPath(depTree, key, function (parent) {
241
+ parent.isSubtreeUsed = !0;
242
+ });
243
+ });
244
+ declaredDependencies.forEach(function (_ref7) {
245
+ getOrCreateNodeByPath(depTree, _ref7.key).isSatisfiedRecursively = !0;
246
+ });
247
+ stableDependencies.forEach(function (key) {
248
+ getOrCreateNodeByPath(depTree, key).isSatisfiedRecursively = !0;
249
+ });
250
+ _ref6 = new Set();
251
+ var satisfyingDependencies = new Set();
252
+ scanTreeRecursively(
253
+ depTree,
254
+ _ref6,
255
+ satisfyingDependencies,
256
+ function (key) {
257
+ return key;
258
+ }
259
+ );
260
+ var suggestedDependencies = [],
261
+ unnecessaryDependencies = new Set(),
262
+ duplicateDependencies = new Set();
263
+ declaredDependencies.forEach(function (_ref8) {
264
+ _ref8 = _ref8.key;
265
+ satisfyingDependencies.has(_ref8)
266
+ ? -1 === suggestedDependencies.indexOf(_ref8)
267
+ ? suggestedDependencies.push(_ref8)
268
+ : duplicateDependencies.add(_ref8)
269
+ : !isEffect ||
270
+ _ref8.endsWith(".current") ||
271
+ externalDependencies.has(_ref8)
272
+ ? unnecessaryDependencies.add(_ref8)
273
+ : -1 === suggestedDependencies.indexOf(_ref8) &&
274
+ suggestedDependencies.push(_ref8);
275
+ });
276
+ _ref6.forEach(function (key) {
277
+ suggestedDependencies.push(key);
278
+ });
279
+ return {
280
+ suggestedDependencies: suggestedDependencies,
281
+ unnecessaryDependencies: unnecessaryDependencies,
282
+ duplicateDependencies: duplicateDependencies,
283
+ missingDependencies: _ref6
284
+ };
181
285
  }
182
- },
183
- create: function (context) {
184
- var lastEffect = null;
185
- var codePathReactHooksMapStack = [];
186
- var codePathSegmentStack = [];
187
- var useEffectEventFunctions = new WeakSet(); // For a given scope, iterate through the references and add all useEffectEvent definitions. We can
188
- // do this in non-Program nodes because we can rely on the assumption that useEffectEvent functions
189
- // can only be declared within a component or hook at its top level.
190
-
191
- function recordAllUseEffectEventFunctions(scope) {
192
- var _iterator = _createForOfIteratorHelper(scope.references),
193
- _step;
194
-
195
- try {
196
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
197
- var reference = _step.value;
198
- var parent = reference.identifier.parent;
199
-
200
- if (parent.type === 'VariableDeclarator' && parent.init && parent.init.type === 'CallExpression' && parent.init.callee && isUseEffectEventIdentifier$1(parent.init.callee)) {
201
- var _iterator2 = _createForOfIteratorHelper(reference.resolved.references),
202
- _step2;
203
-
204
- try {
205
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
206
- var ref = _step2.value;
207
-
208
- if (ref !== reference) {
209
- useEffectEventFunctions.add(ref.identifier);
286
+ function getConstructionExpressionType(node) {
287
+ switch (node.type) {
288
+ case "ObjectExpression":
289
+ return "object";
290
+ case "ArrayExpression":
291
+ return "array";
292
+ case "ArrowFunctionExpression":
293
+ case "FunctionExpression":
294
+ return "function";
295
+ case "ClassExpression":
296
+ return "class";
297
+ case "ConditionalExpression":
298
+ if (
299
+ null != getConstructionExpressionType(node.consequent) ||
300
+ null != getConstructionExpressionType(node.alternate)
301
+ )
302
+ return "conditional";
303
+ break;
304
+ case "LogicalExpression":
305
+ if (
306
+ null != getConstructionExpressionType(node.left) ||
307
+ null != getConstructionExpressionType(node.right)
308
+ )
309
+ return "logical expression";
310
+ break;
311
+ case "JSXFragment":
312
+ return "JSX fragment";
313
+ case "JSXElement":
314
+ return "JSX element";
315
+ case "AssignmentExpression":
316
+ if (null != getConstructionExpressionType(node.right))
317
+ return "assignment expression";
318
+ break;
319
+ case "NewExpression":
320
+ return "object construction";
321
+ case "Literal":
322
+ if (node.value instanceof RegExp) return "regular expression";
323
+ break;
324
+ case "TypeCastExpression":
325
+ case "AsExpression":
326
+ case "TSAsExpression":
327
+ return getConstructionExpressionType(node.expression);
328
+ }
329
+ return null;
330
+ }
331
+ function scanForConstructions(_ref9) {
332
+ var declaredDependenciesNode = _ref9.declaredDependenciesNode,
333
+ componentScope = _ref9.componentScope,
334
+ scope = _ref9.scope;
335
+ return _ref9.declaredDependencies
336
+ .map(function (_ref10) {
337
+ var key = _ref10.key;
338
+ _ref10 = componentScope.variables.find(function (v) {
339
+ return v.name === key;
340
+ });
341
+ if (null == _ref10) return null;
342
+ var node = _ref10.defs[0];
343
+ if (null == node) return null;
344
+ if (
345
+ "Variable" === node.type &&
346
+ "VariableDeclarator" === node.node.type &&
347
+ "Identifier" === node.node.id.type &&
348
+ null != node.node.init
349
+ ) {
350
+ var constantExpressionType = getConstructionExpressionType(
351
+ node.node.init
352
+ );
353
+ if (null != constantExpressionType)
354
+ return [_ref10, constantExpressionType];
355
+ }
356
+ return "FunctionName" === node.type &&
357
+ "FunctionDeclaration" === node.node.type
358
+ ? [_ref10, "function"]
359
+ : "ClassName" === node.type && "ClassDeclaration" === node.node.type
360
+ ? [_ref10, "class"]
361
+ : null;
362
+ })
363
+ .filter(Boolean)
364
+ .map(function (_ref11) {
365
+ var ref = _ref11[0];
366
+ _ref11 = _ref11[1];
367
+ var JSCompiler_temp_const = ref.defs[0];
368
+ a: {
369
+ for (
370
+ var foundWriteExpr = !1, i = 0;
371
+ i < ref.references.length;
372
+ i++
373
+ ) {
374
+ var reference = ref.references[i];
375
+ if (reference.writeExpr)
376
+ if (foundWriteExpr) {
377
+ ref = !0;
378
+ break a;
379
+ } else {
380
+ foundWriteExpr = !0;
381
+ continue;
210
382
  }
383
+ for (
384
+ var currentScope = reference.from;
385
+ currentScope !== scope && null != currentScope;
386
+
387
+ )
388
+ currentScope = currentScope.upper;
389
+ if (
390
+ currentScope !== scope &&
391
+ !isAncestorNodeOf(
392
+ declaredDependenciesNode,
393
+ reference.identifier
394
+ )
395
+ ) {
396
+ ref = !0;
397
+ break a;
211
398
  }
212
- } catch (err) {
213
- _iterator2.e(err);
214
- } finally {
215
- _iterator2.f();
216
399
  }
400
+ ref = !1;
217
401
  }
402
+ return {
403
+ construction: JSCompiler_temp_const,
404
+ depType: _ref11,
405
+ isUsedOutsideOfHook: ref
406
+ };
407
+ });
408
+ }
409
+ function getDependency(node) {
410
+ return ("MemberExpression" !== node.parent.type &&
411
+ "OptionalMemberExpression" !== node.parent.type) ||
412
+ node.parent.object !== node ||
413
+ "current" === node.parent.property.name ||
414
+ node.parent.computed ||
415
+ (null != node.parent.parent &&
416
+ ("CallExpression" === node.parent.parent.type ||
417
+ "OptionalCallExpression" === node.parent.parent.type) &&
418
+ node.parent.parent.callee === node.parent)
419
+ ? "MemberExpression" === node.type &&
420
+ node.parent &&
421
+ "AssignmentExpression" === node.parent.type &&
422
+ node.parent.left === node
423
+ ? node.object
424
+ : node
425
+ : getDependency(node.parent);
426
+ }
427
+ function markNode(node, optionalChains, result) {
428
+ optionalChains &&
429
+ (node.optional
430
+ ? optionalChains.has(result) || optionalChains.set(result, !0)
431
+ : optionalChains.set(result, !1));
432
+ }
433
+ function analyzePropertyChain(node, optionalChains) {
434
+ if ("Identifier" === node.type || "JSXIdentifier" === node.type)
435
+ return (
436
+ (node = node.name),
437
+ optionalChains && optionalChains.set(node, !1),
438
+ node
439
+ );
440
+ if ("MemberExpression" !== node.type || node.computed) {
441
+ if ("OptionalMemberExpression" !== node.type || node.computed) {
442
+ if ("ChainExpression" !== node.type || node.computed)
443
+ throw Error("Unsupported node type: " + node.type);
444
+ node = node.expression;
445
+ if ("CallExpression" === node.type)
446
+ throw Error("Unsupported node type: " + node.type);
447
+ var _object2 = analyzePropertyChain(node.object, optionalChains),
448
+ _property2 = analyzePropertyChain(node.property, null);
449
+ _object2 = _object2 + "." + _property2;
450
+ markNode(node, optionalChains, _object2);
451
+ return _object2;
218
452
  }
219
- } catch (err) {
220
- _iterator.e(err);
221
- } finally {
222
- _iterator.f();
453
+ _object2 = analyzePropertyChain(node.object, optionalChains);
454
+ _property2 = analyzePropertyChain(node.property, null);
455
+ _object2 = _object2 + "." + _property2;
456
+ markNode(node, optionalChains, _object2);
457
+ return _object2;
223
458
  }
459
+ _object2 = analyzePropertyChain(node.object, optionalChains);
460
+ _property2 = analyzePropertyChain(node.property, null);
461
+ _object2 = _object2 + "." + _property2;
462
+ markNode(node, optionalChains, _object2);
463
+ return _object2;
224
464
  }
225
- /**
226
- * SourceCode#getText that also works down to ESLint 3.0.0
227
- */
228
-
229
-
230
- var getSource = typeof context.getSource === 'function' ? function (node) {
231
- return context.getSource(node);
232
- } : function (node) {
233
- return context.sourceCode.getText(node);
234
- };
235
- /**
236
- * SourceCode#getScope that also works down to ESLint 3.0.0
237
- */
238
-
239
- var getScope = typeof context.getScope === 'function' ? function () {
240
- return context.getScope();
241
- } : function (node) {
242
- return context.sourceCode.getScope(node);
243
- };
244
- return {
245
- // Maintain code segment path stack as we traverse.
246
- onCodePathSegmentStart: function (segment) {
247
- return codePathSegmentStack.push(segment);
248
- },
249
- onCodePathSegmentEnd: function () {
250
- return codePathSegmentStack.pop();
251
- },
252
- // Maintain code path stack as we traverse.
253
- onCodePathStart: function () {
254
- return codePathReactHooksMapStack.push(new Map());
255
- },
256
- // Process our code path.
257
- //
258
- // Everything is ok if all React Hooks are both reachable from the initial
259
- // segment and reachable from every final segment.
260
- onCodePathEnd: function (codePath, codePathNode) {
261
- var reactHooksMap = codePathReactHooksMapStack.pop();
262
-
263
- if (reactHooksMap.size === 0) {
264
- return;
265
- } // All of the segments which are cyclic are recorded in this set.
266
-
267
-
268
- var cyclic = new Set();
269
- /**
270
- * Count the number of code paths from the start of the function to this
271
- * segment. For example:
272
- *
273
- * ```js
274
- * function MyComponent() {
275
- * if (condition) {
276
- * // Segment 1
277
- * } else {
278
- * // Segment 2
279
- * }
280
- * // Segment 3
281
- * }
282
- * ```
283
- *
284
- * Segments 1 and 2 have one path to the beginning of `MyComponent` and
285
- * segment 3 has two paths to the beginning of `MyComponent` since we
286
- * could have either taken the path of segment 1 or segment 2.
287
- *
288
- * Populates `cyclic` with cyclic segments.
289
- */
290
-
291
- function countPathsFromStart(segment, pathHistory) {
292
- var cache = countPathsFromStart.cache;
293
- var paths = cache.get(segment.id);
294
- var pathList = new Set(pathHistory); // If `pathList` includes the current segment then we've found a cycle!
295
- // We need to fill `cyclic` with all segments inside cycle
296
-
297
- if (pathList.has(segment.id)) {
298
- var pathArray = [].concat(pathList);
299
- var cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1);
300
-
301
- var _iterator3 = _createForOfIteratorHelper(cyclicSegments),
302
- _step3;
303
-
465
+ function getNodeWithoutReactNamespace(node) {
466
+ return "MemberExpression" !== node.type ||
467
+ "Identifier" !== node.object.type ||
468
+ "React" !== node.object.name ||
469
+ "Identifier" !== node.property.type ||
470
+ node.computed
471
+ ? node
472
+ : node.property;
473
+ }
474
+ function getReactiveHookCallbackIndex(calleeNode, options) {
475
+ var node = getNodeWithoutReactNamespace(calleeNode);
476
+ if ("Identifier" !== node.type) return -1;
477
+ switch (node.name) {
478
+ case "useEffect":
479
+ case "useLayoutEffect":
480
+ case "useCallback":
481
+ case "useMemo":
482
+ return 0;
483
+ case "useImperativeHandle":
484
+ return 1;
485
+ default:
486
+ if (node === calleeNode && options && options.additionalHooks) {
304
487
  try {
305
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
306
- var cyclicSegment = _step3.value;
307
- cyclic.add(cyclicSegment);
308
- }
309
- } catch (err) {
310
- _iterator3.e(err);
311
- } finally {
312
- _iterator3.f();
488
+ var name = analyzePropertyChain(node, null);
489
+ } catch (error) {
490
+ if (/Unsupported node type/.test(error.message)) return 0;
491
+ throw error;
313
492
  }
314
-
315
- return BigInt('0');
316
- } // add the current segment to pathList
317
-
318
-
319
- pathList.add(segment.id); // We have a cached `paths`. Return it.
320
-
321
- if (paths !== undefined) {
322
- return paths;
493
+ return options.additionalHooks.test(name) ? 0 : -1;
323
494
  }
324
-
325
- if (codePath.thrownSegments.includes(segment)) {
326
- paths = BigInt('0');
327
- } else if (segment.prevSegments.length === 0) {
328
- paths = BigInt('1');
329
- } else {
330
- paths = BigInt('0');
331
-
332
- var _iterator4 = _createForOfIteratorHelper(segment.prevSegments),
333
- _step4;
334
-
335
- try {
336
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
337
- var prevSegment = _step4.value;
338
- paths += countPathsFromStart(prevSegment, pathList);
339
- }
340
- } catch (err) {
341
- _iterator4.e(err);
342
- } finally {
343
- _iterator4.f();
344
- }
345
- } // If our segment is reachable then there should be at least one path
346
- // to it from the start of our code path.
347
-
348
-
349
- if (segment.reachable && paths === BigInt('0')) {
350
- cache.delete(segment.id);
351
- } else {
352
- cache.set(segment.id, paths);
495
+ return -1;
496
+ }
497
+ }
498
+ function fastFindReferenceWithParent(start, target) {
499
+ for (var queue = [start], item = null; queue.length; ) {
500
+ item = queue.shift();
501
+ if (
502
+ ("Identifier" === item.type || "JSXIdentifier" === item.type) &&
503
+ item.type === target.type &&
504
+ item.name === target.name &&
505
+ item.range[0] === target.range[0] &&
506
+ item.range[1] === target.range[1]
507
+ )
508
+ return item;
509
+ if (isAncestorNodeOf(item, target)) {
510
+ start = 0;
511
+ for (
512
+ var _Object$entries = Object.entries(item);
513
+ start < _Object$entries.length;
514
+ start++
515
+ ) {
516
+ var _Object$entries$_i = _Object$entries[start],
517
+ value = _Object$entries$_i[1];
518
+ "parent" !== _Object$entries$_i[0] &&
519
+ (isNodeLike(value)
520
+ ? ((value.parent = item), queue.push(value))
521
+ : Array.isArray(value) &&
522
+ value.forEach(function (val) {
523
+ isNodeLike(val) && ((val.parent = item), queue.push(val));
524
+ }));
353
525
  }
354
-
355
- return paths;
356
526
  }
357
- /**
358
- * Count the number of code paths from this segment to the end of the
359
- * function. For example:
360
- *
361
- * ```js
362
- * function MyComponent() {
363
- * // Segment 1
364
- * if (condition) {
365
- * // Segment 2
366
- * } else {
367
- * // Segment 3
368
- * }
369
- * }
370
- * ```
371
- *
372
- * Segments 2 and 3 have one path to the end of `MyComponent` and
373
- * segment 1 has two paths to the end of `MyComponent` since we could
374
- * either take the path of segment 1 or segment 2.
375
- *
376
- * Populates `cyclic` with cyclic segments.
377
- */
378
-
379
-
380
- function countPathsToEnd(segment, pathHistory) {
381
- var cache = countPathsToEnd.cache;
382
- var paths = cache.get(segment.id);
383
- var pathList = new Set(pathHistory); // If `pathList` includes the current segment then we've found a cycle!
384
- // We need to fill `cyclic` with all segments inside cycle
385
-
386
- if (pathList.has(segment.id)) {
387
- var pathArray = Array.from(pathList);
388
- var cyclicSegments = pathArray.slice(pathArray.indexOf(segment.id) + 1);
389
-
390
- var _iterator5 = _createForOfIteratorHelper(cyclicSegments),
391
- _step5;
392
-
527
+ }
528
+ return null;
529
+ }
530
+ function joinEnglish(arr) {
531
+ for (var s = "", i = 0; i < arr.length; i++)
532
+ (s += arr[i]),
533
+ 0 === i && 2 === arr.length
534
+ ? (s += " and ")
535
+ : i === arr.length - 2 && 2 < arr.length
536
+ ? (s += ", and ")
537
+ : i < arr.length - 1 && (s += ", ");
538
+ return s;
539
+ }
540
+ function isNodeLike(val) {
541
+ return (
542
+ "object" === typeof val &&
543
+ null !== val &&
544
+ !Array.isArray(val) &&
545
+ "string" === typeof val.type
546
+ );
547
+ }
548
+ function isAncestorNodeOf(a, b) {
549
+ return a.range[0] <= b.range[0] && a.range[1] >= b.range[1];
550
+ }
551
+ exports.configs = {
552
+ recommended: {
553
+ plugins: ["react-hooks"],
554
+ rules: {
555
+ "react-hooks/rules-of-hooks": "error",
556
+ "react-hooks/exhaustive-deps": "warn"
557
+ }
558
+ }
559
+ };
560
+ exports.rules = {
561
+ "rules-of-hooks": {
562
+ meta: {
563
+ type: "problem",
564
+ docs: {
565
+ description: "enforces the Rules of Hooks",
566
+ recommended: !0,
567
+ url: "https://reactjs.org/docs/hooks-rules.html"
568
+ }
569
+ },
570
+ create: function (context) {
571
+ function recordAllUseEffectEventFunctions(scope) {
572
+ scope = _createForOfIteratorHelper(scope.references);
393
573
  try {
394
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
395
- var cyclicSegment = _step5.value;
396
- cyclic.add(cyclicSegment);
397
- }
398
- } catch (err) {
399
- _iterator5.e(err);
574
+ for (scope.s(); !scope.n().done; );
575
+ } catch (err$0) {
576
+ scope.e(err$0);
400
577
  } finally {
401
- _iterator5.f();
578
+ scope.f();
402
579
  }
403
-
404
- return BigInt('0');
405
- } // add the current segment to pathList
406
-
407
-
408
- pathList.add(segment.id); // We have a cached `paths`. Return it.
409
-
410
- if (paths !== undefined) {
411
- return paths;
412
580
  }
581
+ var lastEffect = null,
582
+ codePathReactHooksMapStack = [],
583
+ codePathSegmentStack = [],
584
+ useEffectEventFunctions = new WeakSet(),
585
+ getSource =
586
+ "function" === typeof context.getSource
587
+ ? function (node) {
588
+ return context.getSource(node);
589
+ }
590
+ : function (node) {
591
+ return context.sourceCode.getText(node);
592
+ },
593
+ getScope =
594
+ "function" === typeof context.getScope
595
+ ? function () {
596
+ return context.getScope();
597
+ }
598
+ : function (node) {
599
+ return context.sourceCode.getScope(node);
600
+ };
601
+ return {
602
+ onCodePathSegmentStart: function (segment) {
603
+ return codePathSegmentStack.push(segment);
604
+ },
605
+ onCodePathSegmentEnd: function () {
606
+ return codePathSegmentStack.pop();
607
+ },
608
+ onCodePathStart: function () {
609
+ return codePathReactHooksMapStack.push(new Map());
610
+ },
611
+ onCodePathEnd: function (codePath, codePathNode) {
612
+ function countPathsFromStart(segment, pathHistory) {
613
+ var cache = countPathsFromStart.cache,
614
+ paths = cache.get(segment.id);
615
+ pathHistory = new Set(pathHistory);
616
+ if (pathHistory.has(segment.id)) {
617
+ cache = [].concat(pathHistory);
618
+ segment = cache.slice(cache.indexOf(segment.id) + 1);
619
+ segment = _createForOfIteratorHelper(segment);
620
+ var _step3;
621
+ try {
622
+ for (segment.s(); !(_step3 = segment.n()).done; )
623
+ cyclic.add(_step3.value);
624
+ } catch (err) {
625
+ segment.e(err);
626
+ } finally {
627
+ segment.f();
628
+ }
629
+ return BigInt("0");
630
+ }
631
+ pathHistory.add(segment.id);
632
+ if (void 0 !== paths) return paths;
633
+ if (codePath.thrownSegments.includes(segment))
634
+ paths = BigInt("0");
635
+ else if (0 === segment.prevSegments.length) paths = BigInt("1");
636
+ else {
637
+ paths = BigInt("0");
638
+ _step3 = _createForOfIteratorHelper(segment.prevSegments);
639
+ var _step4;
640
+ try {
641
+ for (_step3.s(); !(_step4 = _step3.n()).done; )
642
+ paths += countPathsFromStart(_step4.value, pathHistory);
643
+ } catch (err$1) {
644
+ _step3.e(err$1);
645
+ } finally {
646
+ _step3.f();
647
+ }
648
+ }
649
+ segment.reachable && paths === BigInt("0")
650
+ ? cache.delete(segment.id)
651
+ : cache.set(segment.id, paths);
652
+ return paths;
653
+ }
654
+ function countPathsToEnd(segment, pathHistory) {
655
+ var cache = countPathsToEnd.cache,
656
+ paths = cache.get(segment.id);
657
+ pathHistory = new Set(pathHistory);
658
+ if (pathHistory.has(segment.id)) {
659
+ cache = Array.from(pathHistory);
660
+ segment = cache.slice(cache.indexOf(segment.id) - 1);
661
+ segment = _createForOfIteratorHelper(segment);
662
+ var _step5;
663
+ try {
664
+ for (segment.s(); !(_step5 = segment.n()).done; )
665
+ cyclic.add(_step5.value);
666
+ } catch (err) {
667
+ segment.e(err);
668
+ } finally {
669
+ segment.f();
670
+ }
671
+ return BigInt("0");
672
+ }
673
+ pathHistory.add(segment.id);
674
+ if (void 0 !== paths) return paths;
675
+ if (codePath.thrownSegments.includes(segment))
676
+ paths = BigInt("0");
677
+ else if (0 === segment.nextSegments.length) paths = BigInt("1");
678
+ else {
679
+ paths = BigInt("0");
680
+ _step5 = _createForOfIteratorHelper(segment.nextSegments);
681
+ var _step6;
682
+ try {
683
+ for (_step5.s(); !(_step6 = _step5.n()).done; )
684
+ paths += countPathsToEnd(_step6.value, pathHistory);
685
+ } catch (err$2) {
686
+ _step5.e(err$2);
687
+ } finally {
688
+ _step5.f();
689
+ }
690
+ }
691
+ cache.set(segment.id, paths);
692
+ return paths;
693
+ }
694
+ function shortestPathLengthToStart(segment) {
695
+ var cache = shortestPathLengthToStart.cache,
696
+ length = cache.get(segment.id);
697
+ if (null === length) return Infinity;
698
+ if (void 0 !== length) return length;
699
+ cache.set(segment.id, null);
700
+ if (0 === segment.prevSegments.length) length = 1;
701
+ else {
702
+ length = Infinity;
703
+ var _iterator7 = _createForOfIteratorHelper(
704
+ segment.prevSegments
705
+ ),
706
+ _step7;
707
+ try {
708
+ for (_iterator7.s(); !(_step7 = _iterator7.n()).done; ) {
709
+ var prevLength = shortestPathLengthToStart(_step7.value);
710
+ prevLength < length && (length = prevLength);
711
+ }
712
+ } catch (err) {
713
+ _iterator7.e(err);
714
+ } finally {
715
+ _iterator7.f();
716
+ }
717
+ length += 1;
718
+ }
719
+ cache.set(segment.id, length);
720
+ return length;
721
+ }
722
+ var reactHooksMap = codePathReactHooksMapStack.pop();
723
+ if (0 !== reactHooksMap.size) {
724
+ var cyclic = new Set();
725
+ countPathsFromStart.cache = new Map();
726
+ countPathsToEnd.cache = new Map();
727
+ shortestPathLengthToStart.cache = new Map();
728
+ var allPathsFromStartToEnd = countPathsToEnd(
729
+ codePath.initialSegment
730
+ ),
731
+ codePathFunctionName = getFunctionName(codePathNode),
732
+ isSomewhereInsideComponentOrHook =
733
+ isInsideComponentOrHook(codePathNode),
734
+ isDirectlyInsideComponentOrHook = codePathFunctionName
735
+ ? isComponentName(codePathFunctionName) ||
736
+ isHook(codePathFunctionName)
737
+ : isForwardRefCallback(codePathNode) ||
738
+ isMemoCallback(codePathNode),
739
+ shortestFinalPathLength = Infinity,
740
+ _iterator8 = _createForOfIteratorHelper(
741
+ codePath.finalSegments
742
+ ),
743
+ _step8;
744
+ try {
745
+ for (_iterator8.s(); !(_step8 = _iterator8.n()).done; ) {
746
+ var finalSegment = _step8.value;
747
+ if (finalSegment.reachable) {
748
+ var length$jscomp$0 =
749
+ shortestPathLengthToStart(finalSegment);
750
+ length$jscomp$0 < shortestFinalPathLength &&
751
+ (shortestFinalPathLength = length$jscomp$0);
752
+ }
753
+ }
754
+ } catch (err) {
755
+ _iterator8.e(err);
756
+ } finally {
757
+ _iterator8.f();
758
+ }
759
+ reactHooksMap = _createForOfIteratorHelper(reactHooksMap);
760
+ var _step9;
761
+ try {
762
+ for (
763
+ reactHooksMap.s();
764
+ !(_step9 = reactHooksMap.n()).done;
413
765
 
414
- if (codePath.thrownSegments.includes(segment)) {
415
- paths = BigInt('0');
416
- } else if (segment.nextSegments.length === 0) {
417
- paths = BigInt('1');
418
- } else {
419
- paths = BigInt('0');
420
-
421
- var _iterator6 = _createForOfIteratorHelper(segment.nextSegments),
422
- _step6;
423
-
424
- try {
425
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
426
- var nextSegment = _step6.value;
427
- paths += countPathsToEnd(nextSegment, pathList);
766
+ ) {
767
+ var _step9$value = _step9.value,
768
+ segment$jscomp$0 = _step9$value[0],
769
+ reactHooks = _step9$value[1];
770
+ if (segment$jscomp$0.reachable) {
771
+ var possiblyHasEarlyReturn =
772
+ 0 === segment$jscomp$0.nextSegments.length
773
+ ? shortestFinalPathLength <=
774
+ shortestPathLengthToStart(segment$jscomp$0)
775
+ : shortestFinalPathLength <
776
+ shortestPathLengthToStart(segment$jscomp$0),
777
+ pathsFromStartToEnd =
778
+ countPathsFromStart(segment$jscomp$0) *
779
+ countPathsToEnd(segment$jscomp$0),
780
+ cycled = cyclic.has(segment$jscomp$0.id),
781
+ _iterator10 = _createForOfIteratorHelper(reactHooks),
782
+ _step10;
783
+ try {
784
+ for (
785
+ _iterator10.s();
786
+ !(_step10 = _iterator10.n()).done;
787
+
788
+ ) {
789
+ var hook = _step10.value;
790
+ cycled &&
791
+ !isReactFunction(hook, "use") &&
792
+ context.report({
793
+ node: hook,
794
+ message:
795
+ 'React Hook "' +
796
+ getSource(hook) +
797
+ '" may be executed more than once. Possibly because it is called in a loop. React Hooks must be called in the exact same order in every component render.'
798
+ });
799
+ if (isDirectlyInsideComponentOrHook) {
800
+ if (
801
+ (codePathNode.async &&
802
+ context.report({
803
+ node: hook,
804
+ message:
805
+ 'React Hook "' +
806
+ getSource(hook) +
807
+ '" cannot be called in an async function.'
808
+ }),
809
+ !cycled &&
810
+ pathsFromStartToEnd !==
811
+ allPathsFromStartToEnd &&
812
+ !isReactFunction(hook, "use"))
813
+ ) {
814
+ var message =
815
+ 'React Hook "' +
816
+ getSource(hook) +
817
+ '" is called conditionally. React Hooks must be called in the exact same order in every component render.' +
818
+ (possiblyHasEarlyReturn
819
+ ? " Did you accidentally call a React Hook after an early return?"
820
+ : "");
821
+ context.report({ node: hook, message: message });
822
+ }
823
+ } else if (
824
+ codePathNode.parent &&
825
+ ("MethodDefinition" === codePathNode.parent.type ||
826
+ "ClassProperty" === codePathNode.parent.type) &&
827
+ codePathNode.parent.value === codePathNode
828
+ ) {
829
+ var _message =
830
+ 'React Hook "' +
831
+ getSource(hook) +
832
+ '" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function.';
833
+ context.report({ node: hook, message: _message });
834
+ } else if (codePathFunctionName) {
835
+ var _message2 =
836
+ 'React Hook "' +
837
+ getSource(hook) +
838
+ '" is called in function "' +
839
+ (getSource(codePathFunctionName) +
840
+ '" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use".');
841
+ context.report({ node: hook, message: _message2 });
842
+ } else if ("Program" === codePathNode.type) {
843
+ var _message3 =
844
+ 'React Hook "' +
845
+ getSource(hook) +
846
+ '" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function.';
847
+ context.report({ node: hook, message: _message3 });
848
+ } else if (
849
+ isSomewhereInsideComponentOrHook &&
850
+ !isReactFunction(hook, "use")
851
+ ) {
852
+ var _message4 =
853
+ 'React Hook "' +
854
+ getSource(hook) +
855
+ '" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function.';
856
+ context.report({ node: hook, message: _message4 });
857
+ }
858
+ }
859
+ } catch (err$3) {
860
+ _iterator10.e(err$3);
861
+ } finally {
862
+ _iterator10.f();
863
+ }
864
+ }
865
+ }
866
+ } catch (err$4) {
867
+ reactHooksMap.e(err$4);
868
+ } finally {
869
+ reactHooksMap.f();
870
+ }
428
871
  }
429
- } catch (err) {
430
- _iterator6.e(err);
431
- } finally {
432
- _iterator6.f();
872
+ },
873
+ CallExpression: function (node) {
874
+ if (isHook(node.callee)) {
875
+ var reactHooksMap =
876
+ codePathReactHooksMapStack[
877
+ codePathReactHooksMapStack.length - 1
878
+ ],
879
+ codePathSegment =
880
+ codePathSegmentStack[codePathSegmentStack.length - 1],
881
+ reactHooks = reactHooksMap.get(codePathSegment);
882
+ reactHooks ||
883
+ ((reactHooks = []),
884
+ reactHooksMap.set(codePathSegment, reactHooks));
885
+ reactHooks.push(node.callee);
886
+ }
887
+ "Identifier" === node.callee.type &&
888
+ "useEffect" === node.callee.name &&
889
+ 0 < node.arguments.length &&
890
+ (lastEffect = node);
891
+ },
892
+ Identifier: function (node) {
893
+ null == lastEffect &&
894
+ useEffectEventFunctions.has(node) &&
895
+ "CallExpression" !== node.parent.type &&
896
+ context.report({
897
+ node: node,
898
+ message:
899
+ "`" +
900
+ getSource(node) +
901
+ '` is a function created with React Hook "useEffectEvent", and can only be called from the same component. They cannot be assigned to variables or passed down.'
902
+ });
903
+ },
904
+ "CallExpression:exit": function (node) {
905
+ node === lastEffect && (lastEffect = null);
906
+ },
907
+ FunctionDeclaration: function (node) {
908
+ isInsideComponentOrHook(node) &&
909
+ recordAllUseEffectEventFunctions(getScope(node));
910
+ },
911
+ ArrowFunctionExpression: function (node) {
912
+ isInsideComponentOrHook(node) &&
913
+ recordAllUseEffectEventFunctions(getScope(node));
433
914
  }
434
- }
435
-
436
- cache.set(segment.id, paths);
437
- return paths;
915
+ };
438
916
  }
439
- /**
440
- * Gets the shortest path length to the start of a code path.
441
- * For example:
442
- *
443
- * ```js
444
- * function MyComponent() {
445
- * if (condition) {
446
- * // Segment 1
447
- * }
448
- * // Segment 2
449
- * }
450
- * ```
451
- *
452
- * There is only one path from segment 1 to the code path start. Its
453
- * length is one so that is the shortest path.
454
- *
455
- * There are two paths from segment 2 to the code path start. One
456
- * through segment 1 with a length of two and another directly to the
457
- * start with a length of one. The shortest path has a length of one
458
- * so we would return that.
459
- */
460
-
461
-
462
- function shortestPathLengthToStart(segment) {
463
- var cache = shortestPathLengthToStart.cache;
464
- var length = cache.get(segment.id); // If `length` is null then we found a cycle! Return infinity since
465
- // the shortest path is definitely not the one where we looped.
466
-
467
- if (length === null) {
468
- return Infinity;
469
- } // We have a cached `length`. Return it.
470
-
471
-
472
- if (length !== undefined) {
473
- return length;
474
- } // Compute `length` and cache it. Guarding against cycles.
475
-
476
-
477
- cache.set(segment.id, null);
478
-
479
- if (segment.prevSegments.length === 0) {
480
- length = 1;
481
- } else {
482
- length = Infinity;
483
-
484
- var _iterator7 = _createForOfIteratorHelper(segment.prevSegments),
485
- _step7;
486
-
487
- try {
488
- for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
489
- var prevSegment = _step7.value;
490
- var prevLength = shortestPathLengthToStart(prevSegment);
491
-
492
- if (prevLength < length) {
493
- length = prevLength;
917
+ },
918
+ "exhaustive-deps": {
919
+ meta: {
920
+ type: "suggestion",
921
+ docs: {
922
+ description:
923
+ "verifies the list of dependencies for Hooks like useEffect and similar",
924
+ recommended: !0,
925
+ url: "https://github.com/facebook/react/issues/14920"
926
+ },
927
+ fixable: "code",
928
+ hasSuggestions: !0,
929
+ schema: [
930
+ {
931
+ type: "object",
932
+ additionalProperties: !1,
933
+ enableDangerousAutofixThisMayCauseInfiniteLoops: !1,
934
+ properties: {
935
+ additionalHooks: { type: "string" },
936
+ enableDangerousAutofixThisMayCauseInfiniteLoops: {
937
+ type: "boolean"
494
938
  }
495
939
  }
496
- } catch (err) {
497
- _iterator7.e(err);
498
- } finally {
499
- _iterator7.f();
500
940
  }
501
-
502
- length += 1;
941
+ ]
942
+ },
943
+ create: function (context) {
944
+ function reportProblem(problem) {
945
+ enableDangerousAutofixThisMayCauseInfiniteLoops &&
946
+ Array.isArray(problem.suggest) &&
947
+ 0 < problem.suggest.length &&
948
+ (problem.fix = problem.suggest[0].fix);
949
+ context.report(problem);
503
950
  }
504
-
505
- cache.set(segment.id, length);
506
- return length;
507
- }
508
-
509
- countPathsFromStart.cache = new Map();
510
- countPathsToEnd.cache = new Map();
511
- shortestPathLengthToStart.cache = new Map(); // Count all code paths to the end of our component/hook. Also primes
512
- // the `countPathsToEnd` cache.
513
-
514
- var allPathsFromStartToEnd = countPathsToEnd(codePath.initialSegment); // Gets the function name for our code path. If the function name is
515
- // `undefined` then we know either that we have an anonymous function
516
- // expression or our code path is not in a function. In both cases we
517
- // will want to error since neither are React function components or
518
- // hook functions - unless it is an anonymous function argument to
519
- // forwardRef or memo.
520
-
521
- var codePathFunctionName = getFunctionName(codePathNode); // This is a valid code path for React hooks if we are directly in a React
522
- // function component or we are in a hook function.
523
-
524
- var isSomewhereInsideComponentOrHook = isInsideComponentOrHook(codePathNode);
525
- var isDirectlyInsideComponentOrHook = codePathFunctionName ? isComponentName(codePathFunctionName) || isHook(codePathFunctionName) : isForwardRefCallback(codePathNode) || isMemoCallback(codePathNode); // Compute the earliest finalizer level using information from the
526
- // cache. We expect all reachable final segments to have a cache entry
527
- // after calling `visitSegment()`.
528
-
529
- var shortestFinalPathLength = Infinity;
530
-
531
- var _iterator8 = _createForOfIteratorHelper(codePath.finalSegments),
532
- _step8;
533
-
534
- try {
535
- for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
536
- var finalSegment = _step8.value;
537
-
538
- if (!finalSegment.reachable) {
539
- continue;
540
- }
541
-
542
- var length = shortestPathLengthToStart(finalSegment);
543
-
544
- if (length < shortestFinalPathLength) {
545
- shortestFinalPathLength = length;
546
- }
547
- } // Make sure all React Hooks pass our lint invariants. Log warnings
548
- // if not.
549
-
550
- } catch (err) {
551
- _iterator8.e(err);
552
- } finally {
553
- _iterator8.f();
554
- }
555
-
556
- var _iterator9 = _createForOfIteratorHelper(reactHooksMap),
557
- _step9;
558
-
559
- try {
560
- for (_iterator9.s(); !(_step9 = _iterator9.n()).done;) {
561
- var _step9$value = _step9.value,
562
- segment = _step9$value[0],
563
- reactHooks = _step9$value[1];
564
-
565
- // NOTE: We could report here that the hook is not reachable, but
566
- // that would be redundant with more general "no unreachable"
567
- // lint rules.
568
- if (!segment.reachable) {
569
- continue;
570
- } // If there are any final segments with a shorter path to start then
571
- // we possibly have an early return.
572
- //
573
- // If our segment is a final segment itself then siblings could
574
- // possibly be early returns.
575
-
576
-
577
- var possiblyHasEarlyReturn = segment.nextSegments.length === 0 ? shortestFinalPathLength <= shortestPathLengthToStart(segment) : shortestFinalPathLength < shortestPathLengthToStart(segment); // Count all the paths from the start of our code path to the end of
578
- // our code path that go _through_ this segment. The critical piece
579
- // of this is _through_. If we just call `countPathsToEnd(segment)`
580
- // then we neglect that we may have gone through multiple paths to get
581
- // to this point! Consider:
582
- //
583
- // ```js
584
- // function MyComponent() {
585
- // if (a) {
586
- // // Segment 1
587
- // } else {
588
- // // Segment 2
589
- // }
590
- // // Segment 3
591
- // if (b) {
592
- // // Segment 4
593
- // } else {
594
- // // Segment 5
595
- // }
596
- // }
597
- // ```
598
- //
599
- // In this component we have four code paths:
600
- //
601
- // 1. `a = true; b = true`
602
- // 2. `a = true; b = false`
603
- // 3. `a = false; b = true`
604
- // 4. `a = false; b = false`
605
- //
606
- // From segment 3 there are two code paths to the end through segment
607
- // 4 and segment 5. However, we took two paths to get here through
608
- // segment 1 and segment 2.
609
- //
610
- // If we multiply the paths from start (two) by the paths to end (two)
611
- // for segment 3 we get four. Which is our desired count.
612
-
613
- var pathsFromStartToEnd = countPathsFromStart(segment) * countPathsToEnd(segment); // Is this hook a part of a cyclic segment?
614
-
615
- var cycled = cyclic.has(segment.id);
616
-
617
- var _iterator10 = _createForOfIteratorHelper(reactHooks),
618
- _step10;
619
-
620
- try {
621
- for (_iterator10.s(); !(_step10 = _iterator10.n()).done;) {
622
- var hook = _step10.value;
623
-
624
- // Report an error if a hook may be called more then once.
625
- // `use(...)` can be called in loops.
626
- if (cycled && !isUseIdentifier(hook)) {
627
- context.report({
628
- node: hook,
629
- message: "React Hook \"" + getSource(hook) + "\" may be executed " + 'more than once. Possibly because it is called in a loop. ' + 'React Hooks must be called in the exact same order in ' + 'every component render.'
630
- });
631
- } // If this is not a valid code path for React hooks then we need to
632
- // log a warning for every hook in this code path.
633
- //
634
- // Pick a special message depending on the scope this hook was
635
- // called in.
636
-
637
-
638
- if (isDirectlyInsideComponentOrHook) {
639
- // Report an error if the hook is called inside an async function.
640
- var isAsyncFunction = codePathNode.async;
641
-
642
- if (isAsyncFunction) {
643
- context.report({
644
- node: hook,
645
- message: "React Hook \"" + getSource(hook) + "\" cannot be " + 'called in an async function.'
646
- });
647
- } // Report an error if a hook does not reach all finalizing code
648
- // path segments.
649
- //
650
- // Special case when we think there might be an early return.
651
-
652
-
653
- if (!cycled && pathsFromStartToEnd !== allPathsFromStartToEnd && !isUseIdentifier(hook) // `use(...)` can be called conditionally.
951
+ function memoizeWithWeakMap(fn, map) {
952
+ return function (arg) {
953
+ if (map.has(arg)) return map.get(arg);
954
+ var result = fn(arg);
955
+ map.set(arg, result);
956
+ return result;
957
+ };
958
+ }
959
+ function visitFunctionWithDependencies(
960
+ node,
961
+ declaredDependenciesNode,
962
+ reactiveHook,
963
+ reactiveHookName,
964
+ isEffect
965
+ ) {
966
+ function gatherDependenciesRecursively(currentScope) {
967
+ var _iterator2 = _createForOfIteratorHelper(
968
+ currentScope.references
969
+ ),
970
+ _step2;
971
+ try {
972
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done; ) {
973
+ var reference = _step2.value;
974
+ if (
975
+ reference.resolved &&
976
+ pureScopes.has(reference.resolved.scope)
654
977
  ) {
655
- var message = "React Hook \"" + getSource(hook) + "\" is called " + 'conditionally. React Hooks must be called in the exact ' + 'same order in every component render.' + (possiblyHasEarlyReturn ? ' Did you accidentally call a React Hook after an' + ' early return?' : '');
656
- context.report({
657
- node: hook,
658
- message: message
978
+ var referenceNode = fastFindReferenceWithParent(
979
+ node,
980
+ reference.identifier
981
+ ),
982
+ dependencyNode = getDependency(referenceNode),
983
+ dependency = analyzePropertyChain(
984
+ dependencyNode,
985
+ optionalChains
986
+ ),
987
+ JSCompiler_temp;
988
+ if (
989
+ (JSCompiler_temp =
990
+ isEffect &&
991
+ "Identifier" === dependencyNode.type &&
992
+ ("MemberExpression" === dependencyNode.parent.type ||
993
+ "OptionalMemberExpression" ===
994
+ dependencyNode.parent.type) &&
995
+ !dependencyNode.parent.computed &&
996
+ "Identifier" === dependencyNode.parent.property.type &&
997
+ "current" === dependencyNode.parent.property.name)
998
+ ) {
999
+ for (
1000
+ var curScope = reference.from,
1001
+ isInReturnedFunction = !1;
1002
+ curScope.block !== node;
1003
+
1004
+ )
1005
+ "function" === curScope.type &&
1006
+ (isInReturnedFunction =
1007
+ null != curScope.block.parent &&
1008
+ "ReturnStatement" === curScope.block.parent.type),
1009
+ (curScope = curScope.upper);
1010
+ JSCompiler_temp = isInReturnedFunction;
1011
+ }
1012
+ JSCompiler_temp &&
1013
+ currentRefsInEffectCleanup.set(dependency, {
1014
+ reference: reference,
1015
+ dependencyNode: dependencyNode
659
1016
  });
1017
+ if (
1018
+ "TSTypeQuery" !== dependencyNode.parent.type &&
1019
+ "TSTypeReference" !== dependencyNode.parent.type
1020
+ ) {
1021
+ var def = reference.resolved.defs[0];
1022
+ if (
1023
+ null != def &&
1024
+ (null == def.node || def.node.init !== node.parent) &&
1025
+ "TypeParameter" !== def.type
1026
+ )
1027
+ if (dependencies.has(dependency))
1028
+ dependencies
1029
+ .get(dependency)
1030
+ .references.push(reference);
1031
+ else {
1032
+ var resolved = reference.resolved,
1033
+ isStable =
1034
+ memoizedIsStableKnownHookValue(resolved) ||
1035
+ memoizedIsFunctionWithoutCapturedValues(resolved);
1036
+ dependencies.set(dependency, {
1037
+ isStable: isStable,
1038
+ references: [reference]
1039
+ });
1040
+ }
660
1041
  }
661
- } else if (codePathNode.parent && (codePathNode.parent.type === 'MethodDefinition' || codePathNode.parent.type === 'ClassProperty') && codePathNode.parent.value === codePathNode) {
662
- // Custom message for hooks inside a class
663
- var _message = "React Hook \"" + getSource(hook) + "\" cannot be called " + 'in a class component. React Hooks must be called in a ' + 'React function component or a custom React Hook function.';
664
-
665
- context.report({
666
- node: hook,
667
- message: _message
668
- });
669
- } else if (codePathFunctionName) {
670
- // Custom message if we found an invalid function name.
671
- var _message2 = "React Hook \"" + getSource(hook) + "\" is called in " + ("function \"" + getSource(codePathFunctionName) + "\" ") + 'that is neither a React function component nor a custom ' + 'React Hook function.' + ' React component names must start with an uppercase letter.' + ' React Hook names must start with the word "use".';
672
-
673
- context.report({
674
- node: hook,
675
- message: _message2
676
- });
677
- } else if (codePathNode.type === 'Program') {
678
- // These are dangerous if you have inline requires enabled.
679
- var _message3 = "React Hook \"" + getSource(hook) + "\" cannot be called " + 'at the top level. React Hooks must be called in a ' + 'React function component or a custom React Hook function.';
680
-
681
- context.report({
682
- node: hook,
683
- message: _message3
684
- });
685
- } else {
686
- // Assume in all other cases the user called a hook in some
687
- // random function callback. This should usually be true for
688
- // anonymous function expressions. Hopefully this is clarifying
689
- // enough in the common case that the incorrect message in
690
- // uncommon cases doesn't matter.
691
- // `use(...)` can be called in callbacks.
692
- if (isSomewhereInsideComponentOrHook && !isUseIdentifier(hook)) {
693
- var _message4 = "React Hook \"" + getSource(hook) + "\" cannot be called " + 'inside a callback. React Hooks must be called in a ' + 'React function component or a custom React Hook function.';
694
-
695
- context.report({
696
- node: hook,
697
- message: _message4
698
- });
699
1042
  }
700
1043
  }
1044
+ } catch (err) {
1045
+ _iterator2.e(err);
1046
+ } finally {
1047
+ _iterator2.f();
701
1048
  }
702
- } catch (err) {
703
- _iterator10.e(err);
704
- } finally {
705
- _iterator10.f();
706
- }
707
- }
708
- } catch (err) {
709
- _iterator9.e(err);
710
- } finally {
711
- _iterator9.f();
712
- }
713
- },
714
- // Missed opportunity...We could visit all `Identifier`s instead of all
715
- // `CallExpression`s and check that _every use_ of a hook name is valid.
716
- // But that gets complicated and enters type-system territory, so we're
717
- // only being strict about hook calls for now.
718
- CallExpression: function (node) {
719
- if (isHook(node.callee)) {
720
- // Add the hook node to a map keyed by the code path segment. We will
721
- // do full code path analysis at the end of our code path.
722
- var reactHooksMap = last(codePathReactHooksMapStack);
723
- var codePathSegment = last(codePathSegmentStack);
724
- var reactHooks = reactHooksMap.get(codePathSegment);
725
-
726
- if (!reactHooks) {
727
- reactHooks = [];
728
- reactHooksMap.set(codePathSegment, reactHooks);
729
- }
730
-
731
- reactHooks.push(node.callee);
732
- } // useEffectEvent: useEffectEvent functions can be passed by reference within useEffect as well as in
733
- // another useEffectEvent
734
-
735
-
736
- if (node.callee.type === 'Identifier' && (node.callee.name === 'useEffect' || isUseEffectEventIdentifier$1()) && node.arguments.length > 0) {
737
- // Denote that we have traversed into a useEffect call, and stash the CallExpr for
738
- // comparison later when we exit
739
- lastEffect = node;
740
- }
741
- },
742
- Identifier: function (node) {
743
- // This identifier resolves to a useEffectEvent function, but isn't being referenced in an
744
- // effect or another event function. It isn't being called either.
745
- if (lastEffect == null && useEffectEventFunctions.has(node) && node.parent.type !== 'CallExpression') {
746
- context.report({
747
- node: node,
748
- message: "`" + getSource(node) + "` is a function created with React Hook \"useEffectEvent\", and can only be called from " + 'the same component. They cannot be assigned to variables or passed down.'
749
- });
750
- }
751
- },
752
- 'CallExpression:exit': function (node) {
753
- if (node === lastEffect) {
754
- lastEffect = null;
755
- }
756
- },
757
- FunctionDeclaration: function (node) {
758
- // function MyComponent() { const onClick = useEffectEvent(...) }
759
- if (isInsideComponentOrHook(node)) {
760
- recordAllUseEffectEventFunctions(getScope(node));
761
- }
762
- },
763
- ArrowFunctionExpression: function (node) {
764
- // const MyComponent = () => { const onClick = useEffectEvent(...) }
765
- if (isInsideComponentOrHook(node)) {
766
- recordAllUseEffectEventFunctions(getScope(node));
767
- }
768
- }
769
- };
770
- }
771
- };
772
- /**
773
- * Gets the static name of a function AST node. For function declarations it is
774
- * easy. For anonymous function expressions it is much harder. If you search for
775
- * `IsAnonymousFunctionDefinition()` in the ECMAScript spec you'll find places
776
- * where JS gives anonymous function expressions names. We roughly detect the
777
- * same AST nodes with some exceptions to better fit our use case.
778
- */
779
-
780
- function getFunctionName(node) {
781
- if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' && node.id) {
782
- // function useHook() {}
783
- // const whatever = function useHook() {};
784
- //
785
- // Function declaration or function expression names win over any
786
- // assignment statements or other renames.
787
- return node.id;
788
- } else if (node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
789
- if (node.parent.type === 'VariableDeclarator' && node.parent.init === node) {
790
- // const useHook = () => {};
791
- return node.parent.id;
792
- } else if (node.parent.type === 'AssignmentExpression' && node.parent.right === node && node.parent.operator === '=') {
793
- // useHook = () => {};
794
- return node.parent.left;
795
- } else if (node.parent.type === 'Property' && node.parent.value === node && !node.parent.computed) {
796
- // {useHook: () => {}}
797
- // {useHook() {}}
798
- return node.parent.key; // NOTE: We could also support `ClassProperty` and `MethodDefinition`
799
- // here to be pedantic. However, hooks in a class are an anti-pattern. So
800
- // we don't allow it to error early.
801
- //
802
- // class {useHook = () => {}}
803
- // class {useHook() {}}
804
- } else if (node.parent.type === 'AssignmentPattern' && node.parent.right === node && !node.parent.computed) {
805
- // const {useHook = () => {}} = {};
806
- // ({useHook = () => {}} = {});
807
- //
808
- // Kinda clowny, but we'd said we'd follow spec convention for
809
- // `IsAnonymousFunctionDefinition()` usage.
810
- return node.parent.left;
811
- } else {
812
- return undefined;
813
- }
814
- } else {
815
- return undefined;
816
- }
817
- }
818
- /**
819
- * Convenience function for peeking the last item in a stack.
820
- */
821
-
822
-
823
- function last(array) {
824
- return array[array.length - 1];
825
- }
826
-
827
- /* eslint-disable no-for-of-loops/no-for-of-loops */
828
- var ExhaustiveDeps = {
829
- meta: {
830
- type: 'suggestion',
831
- docs: {
832
- description: 'verifies the list of dependencies for Hooks like useEffect and similar',
833
- recommended: true,
834
- url: 'https://github.com/facebook/react/issues/14920'
835
- },
836
- fixable: 'code',
837
- hasSuggestions: true,
838
- schema: [{
839
- type: 'object',
840
- additionalProperties: false,
841
- enableDangerousAutofixThisMayCauseInfiniteLoops: false,
842
- properties: {
843
- additionalHooks: {
844
- type: 'string'
845
- },
846
- enableDangerousAutofixThisMayCauseInfiniteLoops: {
847
- type: 'boolean'
848
- }
849
- }
850
- }]
851
- },
852
- create: function (context) {
853
- // Parse the `additionalHooks` regex.
854
- var additionalHooks = context.options && context.options[0] && context.options[0].additionalHooks ? new RegExp(context.options[0].additionalHooks) : undefined;
855
- var enableDangerousAutofixThisMayCauseInfiniteLoops = context.options && context.options[0] && context.options[0].enableDangerousAutofixThisMayCauseInfiniteLoops || false;
856
- var options = {
857
- additionalHooks: additionalHooks,
858
- enableDangerousAutofixThisMayCauseInfiniteLoops: enableDangerousAutofixThisMayCauseInfiniteLoops
859
- };
860
-
861
- function reportProblem(problem) {
862
- if (enableDangerousAutofixThisMayCauseInfiniteLoops) {
863
- // Used to enable legacy behavior. Dangerous.
864
- // Keep this as an option until major IDEs upgrade (including VSCode FB ESLint extension).
865
- if (Array.isArray(problem.suggest) && problem.suggest.length > 0) {
866
- problem.fix = problem.suggest[0].fix;
867
- }
868
- }
869
-
870
- context.report(problem);
871
- }
872
- /**
873
- * SourceCode#getText that also works down to ESLint 3.0.0
874
- */
875
-
876
-
877
- var getSource = typeof context.getSource === 'function' ? function (node) {
878
- return context.getSource(node);
879
- } : function (node) {
880
- return context.sourceCode.getText(node);
881
- };
882
- /**
883
- * SourceCode#getScope that also works down to ESLint 3.0.0
884
- */
885
-
886
- var getScope = typeof context.getScope === 'function' ? function () {
887
- return context.getScope();
888
- } : function (node) {
889
- return context.sourceCode.getScope(node);
890
- };
891
- var scopeManager = context.getSourceCode().scopeManager; // Should be shared between visitors.
892
-
893
- var setStateCallSites = new WeakMap();
894
- var stateVariables = new WeakSet();
895
- var stableKnownValueCache = new WeakMap();
896
- var functionWithoutCapturedValueCache = new WeakMap();
897
- var useEffectEventVariables = new WeakSet();
898
-
899
- function memoizeWithWeakMap(fn, map) {
900
- return function (arg) {
901
- if (map.has(arg)) {
902
- // to verify cache hits:
903
- // console.log(arg.name)
904
- return map.get(arg);
905
- }
906
-
907
- var result = fn(arg);
908
- map.set(arg, result);
909
- return result;
910
- };
911
- }
912
- /**
913
- * Visitor for both function expressions and arrow function expressions.
914
- */
915
-
916
-
917
- function visitFunctionWithDependencies(node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect) {
918
- if (isEffect && node.async) {
919
- reportProblem({
920
- node: node,
921
- message: "Effect callbacks are synchronous to prevent race conditions. " + "Put the async function inside:\n\n" + 'useEffect(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching'
922
- });
923
- } // Get the current scope.
924
-
925
-
926
- var scope = scopeManager.acquire(node); // Find all our "pure scopes". On every re-render of a component these
927
- // pure scopes may have changes to the variables declared within. So all
928
- // variables used in our reactive hook callback but declared in a pure
929
- // scope need to be listed as dependencies of our reactive hook callback.
930
- //
931
- // According to the rules of React you can't read a mutable value in pure
932
- // scope. We can't enforce this in a lint so we trust that all variables
933
- // declared outside of pure scope are indeed frozen.
934
-
935
- var pureScopes = new Set();
936
- var componentScope = null;
937
- {
938
- var currentScope = scope.upper;
939
-
940
- while (currentScope) {
941
- pureScopes.add(currentScope);
942
-
943
- if (currentScope.type === 'function') {
944
- break;
945
- }
946
-
947
- currentScope = currentScope.upper;
948
- } // If there is no parent function scope then there are no pure scopes.
949
- // The ones we've collected so far are incorrect. So don't continue with
950
- // the lint.
951
-
952
-
953
- if (!currentScope) {
954
- return;
955
- }
956
-
957
- componentScope = currentScope;
958
- }
959
- var isArray = Array.isArray; // Next we'll define a few helpers that helps us
960
- // tell if some values don't have to be declared as deps.
961
- // Some are known to be stable based on Hook calls.
962
- // const [state, setState] = useState() / React.useState()
963
- // ^^^ true for this reference
964
- // const [state, dispatch] = useReducer() / React.useReducer()
965
- // ^^^ true for this reference
966
- // const ref = useRef()
967
- // ^^^ true for this reference
968
- // const onStuff = useEffectEvent(() => {})
969
- // ^^^ true for this reference
970
- // False for everything else.
971
-
972
- function isStableKnownHookValue(resolved) {
973
- if (!isArray(resolved.defs)) {
974
- return false;
975
- }
976
-
977
- var def = resolved.defs[0];
978
-
979
- if (def == null) {
980
- return false;
981
- } // Look for `let stuff = ...`
982
-
983
-
984
- if (def.node.type !== 'VariableDeclarator') {
985
- return false;
986
- }
987
-
988
- var init = def.node.init;
989
-
990
- if (init == null) {
991
- return false;
992
- }
993
-
994
- while (init.type === 'TSAsExpression' || init.type === 'AsExpression') {
995
- init = init.expression;
996
- } // Detect primitive constants
997
- // const foo = 42
998
-
999
-
1000
- var declaration = def.node.parent;
1001
-
1002
- if (declaration == null) {
1003
- // This might happen if variable is declared after the callback.
1004
- // In that case ESLint won't set up .parent refs.
1005
- // So we'll set them up manually.
1006
- fastFindReferenceWithParent(componentScope.block, def.node.id);
1007
- declaration = def.node.parent;
1008
-
1009
- if (declaration == null) {
1010
- return false;
1011
- }
1012
- }
1013
-
1014
- if (declaration.kind === 'const' && init.type === 'Literal' && (typeof init.value === 'string' || typeof init.value === 'number' || init.value === null)) {
1015
- // Definitely stable
1016
- return true;
1017
- } // Detect known Hook calls
1018
- // const [_, setState] = useState()
1019
-
1020
-
1021
- if (init.type !== 'CallExpression') {
1022
- return false;
1023
- }
1024
-
1025
- var callee = init.callee; // Step into `= React.something` initializer.
1026
-
1027
- if (callee.type === 'MemberExpression' && callee.object.name === 'React' && callee.property != null && !callee.computed) {
1028
- callee = callee.property;
1029
- }
1030
-
1031
- if (callee.type !== 'Identifier') {
1032
- return false;
1033
- }
1034
-
1035
- var id = def.node.id;
1036
- var _callee = callee,
1037
- name = _callee.name;
1038
-
1039
- if (name === 'useRef' && id.type === 'Identifier') {
1040
- // useRef() return value is stable.
1041
- return true;
1042
- } else if (isUseEffectEventIdentifier() && id.type === 'Identifier') {
1043
- var _iterator = _createForOfIteratorHelper(resolved.references),
1044
- _step;
1045
-
1046
- try {
1047
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1048
- var ref = _step.value;
1049
-
1050
- if (ref !== id) {
1051
- useEffectEventVariables.add(ref.identifier);
1049
+ currentScope = _createForOfIteratorHelper(
1050
+ currentScope.childScopes
1051
+ );
1052
+ var _step3;
1053
+ try {
1054
+ for (currentScope.s(); !(_step3 = currentScope.n()).done; )
1055
+ gatherDependenciesRecursively(_step3.value);
1056
+ } catch (err$5) {
1057
+ currentScope.e(err$5);
1058
+ } finally {
1059
+ currentScope.f();
1052
1060
  }
1053
- } // useEffectEvent() return value is always unstable.
1054
-
1055
- } catch (err) {
1056
- _iterator.e(err);
1057
- } finally {
1058
- _iterator.f();
1059
- }
1060
-
1061
- return true;
1062
- } else if (name === 'useState' || name === 'useReducer') {
1063
- // Only consider second value in initializing tuple stable.
1064
- if (id.type === 'ArrayPattern' && id.elements.length === 2 && isArray(resolved.identifiers)) {
1065
- // Is second tuple value the same reference we're checking?
1066
- if (id.elements[1] === resolved.identifiers[0]) {
1067
- if (name === 'useState') {
1068
- var references = resolved.references;
1069
- var writeCount = 0;
1070
-
1071
- for (var i = 0; i < references.length; i++) {
1072
- if (references[i].isWrite()) {
1073
- writeCount++;
1074
- }
1075
-
1076
- if (writeCount > 1) {
1077
- return false;
1078
- }
1079
-
1080
- setStateCallSites.set(references[i].identifier, id.elements[0]);
1081
- }
1082
- } // Setter is stable.
1083
-
1084
-
1085
- return true;
1086
- } else if (id.elements[0] === resolved.identifiers[0]) {
1087
- if (name === 'useState') {
1088
- var _references = resolved.references;
1089
-
1090
- for (var _i = 0; _i < _references.length; _i++) {
1091
- stateVariables.add(_references[_i].identifier);
1092
- }
1093
- } // State variable itself is dynamic.
1094
-
1095
-
1096
- return false;
1097
1061
  }
1098
- }
1099
- } else if (name === 'useTransition') {
1100
- // Only consider second value in initializing tuple stable.
1101
- if (id.type === 'ArrayPattern' && id.elements.length === 2 && Array.isArray(resolved.identifiers)) {
1102
- // Is second tuple value the same reference we're checking?
1103
- if (id.elements[1] === resolved.identifiers[0]) {
1104
- // Setter is stable.
1105
- return true;
1062
+ function formatDependency(path) {
1063
+ path = path.split(".");
1064
+ for (var finalPath = "", i = 0; i < path.length; i++) {
1065
+ if (0 !== i) {
1066
+ var pathSoFar = path.slice(0, i + 1).join(".");
1067
+ pathSoFar = !0 === optionalChains.get(pathSoFar);
1068
+ finalPath += pathSoFar ? "?." : ".";
1069
+ }
1070
+ finalPath += path[i];
1071
+ }
1072
+ return finalPath;
1106
1073
  }
1107
- }
1108
- } // By default assume it's dynamic.
1109
-
1110
-
1111
- return false;
1112
- } // Some are just functions that don't reference anything dynamic.
1113
-
1114
-
1115
- function isFunctionWithoutCapturedValues(resolved) {
1116
- if (!isArray(resolved.defs)) {
1117
- return false;
1118
- }
1119
-
1120
- var def = resolved.defs[0];
1121
-
1122
- if (def == null) {
1123
- return false;
1124
- }
1125
-
1126
- if (def.node == null || def.node.id == null) {
1127
- return false;
1128
- } // Search the direct component subscopes for
1129
- // top-level function definitions matching this reference.
1130
-
1131
-
1132
- var fnNode = def.node;
1133
- var childScopes = componentScope.childScopes;
1134
- var fnScope = null;
1135
- var i;
1136
-
1137
- for (i = 0; i < childScopes.length; i++) {
1138
- var childScope = childScopes[i];
1139
- var childScopeBlock = childScope.block;
1140
-
1141
- if ( // function handleChange() {}
1142
- fnNode.type === 'FunctionDeclaration' && childScopeBlock === fnNode || // const handleChange = () => {}
1143
- // const handleChange = function() {}
1144
- fnNode.type === 'VariableDeclarator' && childScopeBlock.parent === fnNode) {
1145
- // Found it!
1146
- fnScope = childScope;
1147
- break;
1148
- }
1149
- }
1150
-
1151
- if (fnScope == null) {
1152
- return false;
1153
- } // Does this function capture any values
1154
- // that are in pure scopes (aka render)?
1155
-
1156
-
1157
- for (i = 0; i < fnScope.through.length; i++) {
1158
- var ref = fnScope.through[i];
1159
-
1160
- if (ref.resolved == null) {
1161
- continue;
1162
- }
1163
-
1164
- if (pureScopes.has(ref.resolved.scope) && // Stable values are fine though,
1165
- // although we won't check functions deeper.
1166
- !memoizedIsStableKnownHookValue(ref.resolved)) {
1167
- return false;
1168
- }
1169
- } // If we got here, this function doesn't capture anything
1170
- // from render--or everything it captures is known stable.
1171
-
1172
-
1173
- return true;
1174
- } // Remember such values. Avoid re-running extra checks on them.
1175
-
1176
-
1177
- var memoizedIsStableKnownHookValue = memoizeWithWeakMap(isStableKnownHookValue, stableKnownValueCache);
1178
- var memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(isFunctionWithoutCapturedValues, functionWithoutCapturedValueCache); // These are usually mistaken. Collect them.
1179
-
1180
- var currentRefsInEffectCleanup = new Map(); // Is this reference inside a cleanup function for this effect node?
1181
- // We can check by traversing scopes upwards from the reference, and checking
1182
- // if the last "return () => " we encounter is located directly inside the effect.
1183
-
1184
- function isInsideEffectCleanup(reference) {
1185
- var curScope = reference.from;
1186
- var isInReturnedFunction = false;
1187
-
1188
- while (curScope.block !== node) {
1189
- if (curScope.type === 'function') {
1190
- isInReturnedFunction = curScope.block.parent != null && curScope.block.parent.type === 'ReturnStatement';
1191
- }
1192
-
1193
- curScope = curScope.upper;
1194
- }
1195
-
1196
- return isInReturnedFunction;
1197
- } // Get dependencies from all our resolved references in pure scopes.
1198
- // Key is dependency string, value is whether it's stable.
1199
-
1200
-
1201
- var dependencies = new Map();
1202
- var optionalChains = new Map();
1203
- gatherDependenciesRecursively(scope);
1204
-
1205
- function gatherDependenciesRecursively(currentScope) {
1206
- var _iterator2 = _createForOfIteratorHelper(currentScope.references),
1207
- _step2;
1208
-
1209
- try {
1210
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
1211
- var reference = _step2.value;
1212
-
1213
- // If this reference is not resolved or it is not declared in a pure
1214
- // scope then we don't care about this reference.
1215
- if (!reference.resolved) {
1216
- continue;
1074
+ function getWarningMessage(deps, singlePrefix, label, fixVerb) {
1075
+ return 0 === deps.size
1076
+ ? null
1077
+ : (1 < deps.size ? "" : singlePrefix + " ") +
1078
+ label +
1079
+ " " +
1080
+ (1 < deps.size ? "dependencies" : "dependency") +
1081
+ ": " +
1082
+ joinEnglish(
1083
+ Array.from(deps)
1084
+ .sort()
1085
+ .map(function (name) {
1086
+ return "'" + formatDependency(name) + "'";
1087
+ })
1088
+ ) +
1089
+ (". Either " +
1090
+ fixVerb +
1091
+ " " +
1092
+ (1 < deps.size ? "them" : "it") +
1093
+ " or remove the dependency array.");
1217
1094
  }
1218
-
1219
- if (!pureScopes.has(reference.resolved.scope)) {
1220
- continue;
1221
- } // Narrow the scope of a dependency if it is, say, a member expression.
1222
- // Then normalize the narrowed dependency.
1223
-
1224
-
1225
- var referenceNode = fastFindReferenceWithParent(node, reference.identifier);
1226
- var dependencyNode = getDependency(referenceNode);
1227
- var dependency = analyzePropertyChain(dependencyNode, optionalChains); // Accessing ref.current inside effect cleanup is bad.
1228
-
1229
- if ( // We're in an effect...
1230
- isEffect && // ... and this look like accessing .current...
1231
- dependencyNode.type === 'Identifier' && (dependencyNode.parent.type === 'MemberExpression' || dependencyNode.parent.type === 'OptionalMemberExpression') && !dependencyNode.parent.computed && dependencyNode.parent.property.type === 'Identifier' && dependencyNode.parent.property.name === 'current' && // ...in a cleanup function or below...
1232
- isInsideEffectCleanup(reference)) {
1233
- currentRefsInEffectCleanup.set(dependency, {
1234
- reference: reference,
1235
- dependencyNode: dependencyNode
1095
+ isEffect &&
1096
+ node.async &&
1097
+ reportProblem({
1098
+ node: node,
1099
+ message:
1100
+ "Effect callbacks are synchronous to prevent race conditions. Put the async function inside:\n\nuseEffect(() => {\n async function fetchData() {\n // You can await here\n const response = await MyAPI.getData(someId);\n // ...\n }\n fetchData();\n}, [someId]); // Or [] if effect doesn't need props or state\n\nLearn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching"
1236
1101
  });
1102
+ for (
1103
+ var scope = scopeManager.acquire(node),
1104
+ pureScopes = new Set(),
1105
+ componentScope = null,
1106
+ currentScope = scope.upper;
1107
+ currentScope;
1108
+
1109
+ ) {
1110
+ pureScopes.add(currentScope);
1111
+ if ("function" === currentScope.type) break;
1112
+ currentScope = currentScope.upper;
1237
1113
  }
1238
-
1239
- if (dependencyNode.parent.type === 'TSTypeQuery' || dependencyNode.parent.type === 'TSTypeReference') {
1240
- continue;
1241
- }
1242
-
1243
- var def = reference.resolved.defs[0];
1244
-
1245
- if (def == null) {
1246
- continue;
1247
- } // Ignore references to the function itself as it's not defined yet.
1248
-
1249
-
1250
- if (def.node != null && def.node.init === node.parent) {
1251
- continue;
1252
- } // Ignore Flow type parameters
1253
-
1254
-
1255
- if (def.type === 'TypeParameter') {
1256
- continue;
1257
- } // Add the dependency to a map so we can make sure it is referenced
1258
- // again in our dependencies array. Remember whether it's stable.
1259
-
1260
-
1261
- if (!dependencies.has(dependency)) {
1262
- var resolved = reference.resolved;
1263
- var isStable = memoizedIsStableKnownHookValue(resolved) || memoizedIsFunctionWithoutCapturedValues(resolved);
1264
- dependencies.set(dependency, {
1265
- isStable: isStable,
1266
- references: [reference]
1114
+ if (currentScope) {
1115
+ componentScope = currentScope;
1116
+ var isArray = Array.isArray,
1117
+ memoizedIsStableKnownHookValue = memoizeWithWeakMap(function (
1118
+ resolved
1119
+ ) {
1120
+ if (!isArray(resolved.defs)) return !1;
1121
+ var def = resolved.defs[0];
1122
+ if (null == def || "VariableDeclarator" !== def.node.type)
1123
+ return !1;
1124
+ var init = def.node.init;
1125
+ if (null == init) return !1;
1126
+ for (
1127
+ ;
1128
+ "TSAsExpression" === init.type ||
1129
+ "AsExpression" === init.type;
1130
+
1131
+ )
1132
+ init = init.expression;
1133
+ var declaration = def.node.parent;
1134
+ if (
1135
+ null == declaration &&
1136
+ (fastFindReferenceWithParent(
1137
+ componentScope.block,
1138
+ def.node.id
1139
+ ),
1140
+ (declaration = def.node.parent),
1141
+ null == declaration)
1142
+ )
1143
+ return !1;
1144
+ if (
1145
+ "const" === declaration.kind &&
1146
+ "Literal" === init.type &&
1147
+ ("string" === typeof init.value ||
1148
+ "number" === typeof init.value ||
1149
+ null === init.value)
1150
+ )
1151
+ return !0;
1152
+ if ("CallExpression" !== init.type) return !1;
1153
+ init = init.callee;
1154
+ "MemberExpression" !== init.type ||
1155
+ "React" !== init.object.name ||
1156
+ null == init.property ||
1157
+ init.computed ||
1158
+ (init = init.property);
1159
+ if ("Identifier" !== init.type) return !1;
1160
+ def = def.node.id;
1161
+ init = init.name;
1162
+ if ("useRef" === init && "Identifier" === def.type) return !0;
1163
+ if (
1164
+ "useState" === init ||
1165
+ "useReducer" === init ||
1166
+ "useActionState" === init
1167
+ ) {
1168
+ if (
1169
+ "ArrayPattern" === def.type &&
1170
+ 2 === def.elements.length &&
1171
+ isArray(resolved.identifiers)
1172
+ ) {
1173
+ if (def.elements[1] === resolved.identifiers[0]) {
1174
+ if ("useState" === init)
1175
+ for (
1176
+ resolved = resolved.references,
1177
+ declaration = init = 0;
1178
+ declaration < resolved.length;
1179
+ declaration++
1180
+ ) {
1181
+ resolved[declaration].isWrite() && init++;
1182
+ if (1 < init) return !1;
1183
+ setStateCallSites.set(
1184
+ resolved[declaration].identifier,
1185
+ def.elements[0]
1186
+ );
1187
+ }
1188
+ return !0;
1189
+ }
1190
+ if (
1191
+ def.elements[0] === resolved.identifiers[0] &&
1192
+ "useState" === init
1193
+ )
1194
+ for (
1195
+ resolved = resolved.references, def = 0;
1196
+ def < resolved.length;
1197
+ def++
1198
+ )
1199
+ stateVariables.add(resolved[def].identifier);
1200
+ }
1201
+ } else if (
1202
+ "useTransition" === init &&
1203
+ "ArrayPattern" === def.type &&
1204
+ 2 === def.elements.length &&
1205
+ Array.isArray(resolved.identifiers) &&
1206
+ def.elements[1] === resolved.identifiers[0]
1207
+ )
1208
+ return !0;
1209
+ return !1;
1210
+ }, stableKnownValueCache),
1211
+ memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(
1212
+ function (resolved) {
1213
+ if (!isArray(resolved.defs)) return !1;
1214
+ resolved = resolved.defs[0];
1215
+ if (
1216
+ null == resolved ||
1217
+ null == resolved.node ||
1218
+ null == resolved.node.id
1219
+ )
1220
+ return !1;
1221
+ var fnNode = resolved.node,
1222
+ childScopes = componentScope.childScopes;
1223
+ resolved = null;
1224
+ var i;
1225
+ for (i = 0; i < childScopes.length; i++) {
1226
+ var childScope = childScopes[i],
1227
+ childScopeBlock = childScope.block;
1228
+ if (
1229
+ ("FunctionDeclaration" === fnNode.type &&
1230
+ childScopeBlock === fnNode) ||
1231
+ ("VariableDeclarator" === fnNode.type &&
1232
+ childScopeBlock.parent === fnNode)
1233
+ ) {
1234
+ resolved = childScope;
1235
+ break;
1236
+ }
1237
+ }
1238
+ if (null == resolved) return !1;
1239
+ for (i = 0; i < resolved.through.length; i++)
1240
+ if (
1241
+ ((fnNode = resolved.through[i]),
1242
+ null != fnNode.resolved &&
1243
+ pureScopes.has(fnNode.resolved.scope) &&
1244
+ !memoizedIsStableKnownHookValue(fnNode.resolved))
1245
+ )
1246
+ return !1;
1247
+ return !0;
1248
+ },
1249
+ functionWithoutCapturedValueCache
1250
+ ),
1251
+ currentRefsInEffectCleanup = new Map(),
1252
+ dependencies = new Map(),
1253
+ optionalChains = new Map();
1254
+ gatherDependenciesRecursively(scope);
1255
+ currentRefsInEffectCleanup.forEach(function (_ref, dependency) {
1256
+ var dependencyNode = _ref.dependencyNode;
1257
+ _ref = _ref.reference.resolved.references;
1258
+ for (
1259
+ var foundCurrentAssignment = !1, i = 0;
1260
+ i < _ref.length;
1261
+ i++
1262
+ ) {
1263
+ var parent = _ref[i].identifier.parent;
1264
+ if (
1265
+ null != parent &&
1266
+ "MemberExpression" === parent.type &&
1267
+ !parent.computed &&
1268
+ "Identifier" === parent.property.type &&
1269
+ "current" === parent.property.name &&
1270
+ "AssignmentExpression" === parent.parent.type &&
1271
+ parent.parent.left === parent
1272
+ ) {
1273
+ foundCurrentAssignment = !0;
1274
+ break;
1275
+ }
1276
+ }
1277
+ foundCurrentAssignment ||
1278
+ reportProblem({
1279
+ node: dependencyNode.parent.property,
1280
+ message:
1281
+ "The ref value '" +
1282
+ dependency +
1283
+ ".current' will likely have changed by the time this effect cleanup function runs. If this ref points to a node rendered by React, copy '" +
1284
+ (dependency +
1285
+ ".current' to a variable inside the effect, and use that variable in the cleanup function.")
1286
+ });
1287
+ });
1288
+ var staleAssignments = new Set(),
1289
+ stableDependencies = new Set();
1290
+ dependencies.forEach(function (_ref2, key) {
1291
+ var references = _ref2.references;
1292
+ _ref2.isStable && stableDependencies.add(key);
1293
+ references.forEach(function (reference) {
1294
+ reference.writeExpr &&
1295
+ ((reference = reference.writeExpr),
1296
+ staleAssignments.has(key) ||
1297
+ (staleAssignments.add(key),
1298
+ reportProblem({
1299
+ node: reference,
1300
+ message:
1301
+ "Assignments to the '" +
1302
+ key +
1303
+ "' variable from inside React Hook " +
1304
+ (getSource(reactiveHook) +
1305
+ " will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside ") +
1306
+ (getSource(reactiveHook) + ".")
1307
+ })));
1308
+ });
1267
1309
  });
1268
- } else {
1269
- dependencies.get(dependency).references.push(reference);
1310
+ if (!(0 < staleAssignments.size))
1311
+ if (declaredDependenciesNode) {
1312
+ var declaredDependencies = [],
1313
+ externalDependencies = new Set();
1314
+ currentScope =
1315
+ "TSAsExpression" === declaredDependenciesNode.type &&
1316
+ "ArrayExpression" ===
1317
+ declaredDependenciesNode.expression.type;
1318
+ "ArrayExpression" === declaredDependenciesNode.type ||
1319
+ currentScope
1320
+ ? (currentScope
1321
+ ? declaredDependenciesNode.expression
1322
+ : declaredDependenciesNode
1323
+ ).elements.forEach(function (declaredDependencyNode) {
1324
+ if (null !== declaredDependencyNode)
1325
+ if ("SpreadElement" === declaredDependencyNode.type)
1326
+ reportProblem({
1327
+ node: declaredDependencyNode,
1328
+ message:
1329
+ "React Hook " +
1330
+ getSource(reactiveHook) +
1331
+ " has a spread element in its dependency array. This means we can't statically verify whether you've passed the correct dependencies."
1332
+ });
1333
+ else {
1334
+ useEffectEventVariables.has(
1335
+ declaredDependencyNode
1336
+ ) &&
1337
+ reportProblem({
1338
+ node: declaredDependencyNode,
1339
+ message:
1340
+ "Functions returned from `useEffectEvent` must not be included in the dependency array. Remove `" +
1341
+ (getSource(declaredDependencyNode) +
1342
+ "` from the list."),
1343
+ suggest: [
1344
+ {
1345
+ desc:
1346
+ "Remove the dependency `" +
1347
+ getSource(declaredDependencyNode) +
1348
+ "`",
1349
+ fix: function (fixer) {
1350
+ return fixer.removeRange(
1351
+ declaredDependencyNode.range
1352
+ );
1353
+ }
1354
+ }
1355
+ ]
1356
+ });
1357
+ try {
1358
+ var declaredDependency = analyzePropertyChain(
1359
+ declaredDependencyNode,
1360
+ null
1361
+ );
1362
+ } catch (error) {
1363
+ if (/Unsupported node type/.test(error.message)) {
1364
+ "Literal" === declaredDependencyNode.type
1365
+ ? dependencies.has(
1366
+ declaredDependencyNode.value
1367
+ )
1368
+ ? reportProblem({
1369
+ node: declaredDependencyNode,
1370
+ message:
1371
+ "The " +
1372
+ declaredDependencyNode.raw +
1373
+ " literal is not a valid dependency because it never changes. Did you mean to include " +
1374
+ (declaredDependencyNode.value +
1375
+ " in the array instead?")
1376
+ })
1377
+ : reportProblem({
1378
+ node: declaredDependencyNode,
1379
+ message:
1380
+ "The " +
1381
+ declaredDependencyNode.raw +
1382
+ " literal is not a valid dependency because it never changes. You can safely remove it."
1383
+ })
1384
+ : reportProblem({
1385
+ node: declaredDependencyNode,
1386
+ message:
1387
+ "React Hook " +
1388
+ getSource(reactiveHook) +
1389
+ " has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked."
1390
+ });
1391
+ return;
1392
+ }
1393
+ throw error;
1394
+ }
1395
+ for (
1396
+ var maybeID = declaredDependencyNode;
1397
+ "MemberExpression" === maybeID.type ||
1398
+ "OptionalMemberExpression" === maybeID.type ||
1399
+ "ChainExpression" === maybeID.type;
1400
+
1401
+ )
1402
+ maybeID =
1403
+ maybeID.object || maybeID.expression.object;
1404
+ var isDeclaredInComponent =
1405
+ !componentScope.through.some(function (ref) {
1406
+ return ref.identifier === maybeID;
1407
+ });
1408
+ declaredDependencies.push({
1409
+ key: declaredDependency,
1410
+ node: declaredDependencyNode
1411
+ });
1412
+ isDeclaredInComponent ||
1413
+ externalDependencies.add(declaredDependency);
1414
+ }
1415
+ })
1416
+ : reportProblem({
1417
+ node: declaredDependenciesNode,
1418
+ message:
1419
+ "React Hook " +
1420
+ getSource(reactiveHook) +
1421
+ " was passed a dependency list that is not an array literal. This means we can't statically verify whether you've passed the correct dependencies."
1422
+ });
1423
+ var _collectRecommendatio2 = collectRecommendations({
1424
+ dependencies: dependencies,
1425
+ declaredDependencies: declaredDependencies,
1426
+ stableDependencies: stableDependencies,
1427
+ externalDependencies: externalDependencies,
1428
+ isEffect: isEffect
1429
+ });
1430
+ currentScope = _collectRecommendatio2.unnecessaryDependencies;
1431
+ var missingDependencies =
1432
+ _collectRecommendatio2.missingDependencies,
1433
+ duplicateDependencies =
1434
+ _collectRecommendatio2.duplicateDependencies,
1435
+ suggestedDeps =
1436
+ _collectRecommendatio2.suggestedDependencies;
1437
+ if (
1438
+ 0 ===
1439
+ duplicateDependencies.size +
1440
+ missingDependencies.size +
1441
+ currentScope.size
1442
+ )
1443
+ scanForConstructions({
1444
+ declaredDependencies: declaredDependencies,
1445
+ declaredDependenciesNode: declaredDependenciesNode,
1446
+ componentScope: componentScope,
1447
+ scope: scope
1448
+ }).forEach(function (_ref4) {
1449
+ var construction = _ref4.construction,
1450
+ isUsedOutsideOfHook = _ref4.isUsedOutsideOfHook;
1451
+ _ref4 = _ref4.depType;
1452
+ var wrapperHook =
1453
+ "function" === _ref4 ? "useCallback" : "useMemo",
1454
+ constructionType =
1455
+ "function" === _ref4
1456
+ ? "definition"
1457
+ : "initialization",
1458
+ defaultAdvice =
1459
+ "wrap the " +
1460
+ constructionType +
1461
+ " of '" +
1462
+ construction.name.name +
1463
+ "' in its own " +
1464
+ wrapperHook +
1465
+ "() Hook.";
1466
+ defaultAdvice =
1467
+ "The '" +
1468
+ construction.name.name +
1469
+ "' " +
1470
+ _ref4 +
1471
+ " " +
1472
+ ("conditional" === _ref4 ||
1473
+ "logical expression" === _ref4
1474
+ ? "could make"
1475
+ : "makes") +
1476
+ " the dependencies of " +
1477
+ (reactiveHookName +
1478
+ " Hook (at line " +
1479
+ declaredDependenciesNode.loc.start.line +
1480
+ ") change on every render. ") +
1481
+ (isUsedOutsideOfHook
1482
+ ? "To fix this, " + defaultAdvice
1483
+ : "Move it inside the " +
1484
+ reactiveHookName +
1485
+ " callback. Alternatively, " +
1486
+ defaultAdvice);
1487
+ var suggest;
1488
+ isUsedOutsideOfHook &&
1489
+ "Variable" === construction.type &&
1490
+ "function" === _ref4 &&
1491
+ (suggest = [
1492
+ {
1493
+ desc:
1494
+ "Wrap the " +
1495
+ constructionType +
1496
+ " of '" +
1497
+ construction.name.name +
1498
+ "' in its own " +
1499
+ wrapperHook +
1500
+ "() Hook.",
1501
+ fix: function (fixer) {
1502
+ var _ref5 =
1503
+ "useMemo" === wrapperHook
1504
+ ? ["useMemo(() => { return ", "; })"]
1505
+ : ["useCallback(", ")"],
1506
+ after = _ref5[1];
1507
+ return [
1508
+ fixer.insertTextBefore(
1509
+ construction.node.init,
1510
+ _ref5[0]
1511
+ ),
1512
+ fixer.insertTextAfter(
1513
+ construction.node.init,
1514
+ after
1515
+ )
1516
+ ];
1517
+ }
1518
+ }
1519
+ ]);
1520
+ reportProblem({
1521
+ node: construction.node,
1522
+ message: defaultAdvice,
1523
+ suggest: suggest
1524
+ });
1525
+ });
1526
+ else {
1527
+ !isEffect &&
1528
+ 0 < missingDependencies.size &&
1529
+ (suggestedDeps = collectRecommendations({
1530
+ dependencies: dependencies,
1531
+ declaredDependencies: [],
1532
+ stableDependencies: stableDependencies,
1533
+ externalDependencies: externalDependencies,
1534
+ isEffect: isEffect
1535
+ }).suggestedDependencies);
1536
+ (function () {
1537
+ if (0 === declaredDependencies.length) return !0;
1538
+ var declaredDepKeys = declaredDependencies.map(
1539
+ function (dep) {
1540
+ return dep.key;
1541
+ }
1542
+ ),
1543
+ sortedDeclaredDepKeys = declaredDepKeys.slice().sort();
1544
+ return (
1545
+ declaredDepKeys.join(",") ===
1546
+ sortedDeclaredDepKeys.join(",")
1547
+ );
1548
+ })() && suggestedDeps.sort();
1549
+ _collectRecommendatio2 = "";
1550
+ if (0 < currentScope.size) {
1551
+ var badRef = null;
1552
+ Array.from(currentScope.keys()).forEach(function (key) {
1553
+ null === badRef &&
1554
+ key.endsWith(".current") &&
1555
+ (badRef = key);
1556
+ });
1557
+ if (null !== badRef)
1558
+ _collectRecommendatio2 =
1559
+ " Mutable values like '" +
1560
+ badRef +
1561
+ "' aren't valid dependencies because mutating them doesn't re-render the component.";
1562
+ else if (0 < externalDependencies.size) {
1563
+ var dep = Array.from(externalDependencies)[0];
1564
+ scope.set.has(dep) ||
1565
+ (_collectRecommendatio2 =
1566
+ " Outer scope values like '" +
1567
+ dep +
1568
+ "' aren't valid dependencies because mutating them doesn't re-render the component.");
1569
+ }
1570
+ }
1571
+ if (
1572
+ !_collectRecommendatio2 &&
1573
+ missingDependencies.has("props")
1574
+ ) {
1575
+ scope = dependencies.get("props");
1576
+ if (null == scope) return;
1577
+ scope = scope.references;
1578
+ if (!Array.isArray(scope)) return;
1579
+ dep = !0;
1580
+ for (
1581
+ var i$jscomp$0 = 0;
1582
+ i$jscomp$0 < scope.length;
1583
+ i$jscomp$0++
1584
+ ) {
1585
+ var id = fastFindReferenceWithParent(
1586
+ componentScope.block,
1587
+ scope[i$jscomp$0].identifier
1588
+ );
1589
+ if (!id) {
1590
+ dep = !1;
1591
+ break;
1592
+ }
1593
+ id = id.parent;
1594
+ if (null == id) {
1595
+ dep = !1;
1596
+ break;
1597
+ }
1598
+ if (
1599
+ "MemberExpression" !== id.type &&
1600
+ "OptionalMemberExpression" !== id.type
1601
+ ) {
1602
+ dep = !1;
1603
+ break;
1604
+ }
1605
+ }
1606
+ dep &&
1607
+ (_collectRecommendatio2 =
1608
+ " However, 'props' will change when *any* prop changes, so the preferred fix is to destructure the 'props' object outside of the " +
1609
+ (reactiveHookName +
1610
+ " call and refer to those specific props inside ") +
1611
+ (getSource(reactiveHook) + "."));
1612
+ }
1613
+ if (
1614
+ !_collectRecommendatio2 &&
1615
+ 0 < missingDependencies.size
1616
+ ) {
1617
+ var missingCallbackDep = null;
1618
+ missingDependencies.forEach(function (missingDep) {
1619
+ if (!missingCallbackDep) {
1620
+ var topScopeRef = componentScope.set.get(missingDep),
1621
+ usedDep = dependencies.get(missingDep);
1622
+ if (
1623
+ usedDep.references[0].resolved === topScopeRef &&
1624
+ ((topScopeRef = topScopeRef.defs[0]),
1625
+ null != topScopeRef &&
1626
+ null != topScopeRef.name &&
1627
+ "Parameter" === topScopeRef.type)
1628
+ ) {
1629
+ topScopeRef = !1;
1630
+ for (
1631
+ var id, _i2 = 0;
1632
+ _i2 < usedDep.references.length;
1633
+ _i2++
1634
+ )
1635
+ if (
1636
+ ((id = usedDep.references[_i2].identifier),
1637
+ null != id &&
1638
+ null != id.parent &&
1639
+ ("CallExpression" === id.parent.type ||
1640
+ "OptionalCallExpression" ===
1641
+ id.parent.type) &&
1642
+ id.parent.callee === id)
1643
+ ) {
1644
+ topScopeRef = !0;
1645
+ break;
1646
+ }
1647
+ topScopeRef && (missingCallbackDep = missingDep);
1648
+ }
1649
+ }
1650
+ });
1651
+ null !== missingCallbackDep &&
1652
+ (_collectRecommendatio2 =
1653
+ " If '" +
1654
+ missingCallbackDep +
1655
+ "' changes too often, find the parent component that defines it and wrap that definition in useCallback.");
1656
+ }
1657
+ if (
1658
+ !_collectRecommendatio2 &&
1659
+ 0 < missingDependencies.size
1660
+ ) {
1661
+ var setStateRecommendation = null;
1662
+ missingDependencies.forEach(function (missingDep) {
1663
+ if (null === setStateRecommendation)
1664
+ for (
1665
+ var references =
1666
+ dependencies.get(missingDep).references,
1667
+ id,
1668
+ maybeCall,
1669
+ _i3 = 0;
1670
+ _i3 < references.length;
1671
+ _i3++
1672
+ ) {
1673
+ id = references[_i3].identifier;
1674
+ for (
1675
+ maybeCall = id.parent;
1676
+ null != maybeCall &&
1677
+ maybeCall !== componentScope.block;
1678
+
1679
+ ) {
1680
+ if ("CallExpression" === maybeCall.type) {
1681
+ var correspondingStateVariable =
1682
+ setStateCallSites.get(maybeCall.callee);
1683
+ if (null != correspondingStateVariable) {
1684
+ correspondingStateVariable.name === missingDep
1685
+ ? (setStateRecommendation = {
1686
+ missingDep: missingDep,
1687
+ setter: maybeCall.callee.name,
1688
+ form: "updater"
1689
+ })
1690
+ : stateVariables.has(id)
1691
+ ? (setStateRecommendation = {
1692
+ missingDep: missingDep,
1693
+ setter: maybeCall.callee.name,
1694
+ form: "reducer"
1695
+ })
1696
+ : ((id = references[_i3].resolved),
1697
+ null != id &&
1698
+ ((id = id.defs[0]),
1699
+ null != id &&
1700
+ "Parameter" === id.type &&
1701
+ (setStateRecommendation = {
1702
+ missingDep: missingDep,
1703
+ setter: maybeCall.callee.name,
1704
+ form: "inlineReducer"
1705
+ })));
1706
+ break;
1707
+ }
1708
+ }
1709
+ maybeCall = maybeCall.parent;
1710
+ }
1711
+ if (null !== setStateRecommendation) break;
1712
+ }
1713
+ });
1714
+ if (null !== setStateRecommendation)
1715
+ switch (setStateRecommendation.form) {
1716
+ case "reducer":
1717
+ _collectRecommendatio2 =
1718
+ " You can also replace multiple useState variables with useReducer if '" +
1719
+ (setStateRecommendation.setter +
1720
+ "' needs the current value of '") +
1721
+ (setStateRecommendation.missingDep + "'.");
1722
+ break;
1723
+ case "inlineReducer":
1724
+ _collectRecommendatio2 =
1725
+ " If '" +
1726
+ setStateRecommendation.setter +
1727
+ "' needs the current value of '" +
1728
+ (setStateRecommendation.missingDep +
1729
+ "', you can also switch to useReducer instead of useState and read '") +
1730
+ (setStateRecommendation.missingDep +
1731
+ "' in the reducer.");
1732
+ break;
1733
+ case "updater":
1734
+ _collectRecommendatio2 =
1735
+ " You can also do a functional update '" +
1736
+ setStateRecommendation.setter +
1737
+ "(" +
1738
+ setStateRecommendation.missingDep.slice(0, 1) +
1739
+ " => ...)' if you only need '" +
1740
+ setStateRecommendation.missingDep +
1741
+ "' in the '" +
1742
+ (setStateRecommendation.setter + "' call.");
1743
+ break;
1744
+ default:
1745
+ throw Error("Unknown case.");
1746
+ }
1747
+ }
1748
+ reportProblem({
1749
+ node: declaredDependenciesNode,
1750
+ message:
1751
+ "React Hook " +
1752
+ getSource(reactiveHook) +
1753
+ " has " +
1754
+ (getWarningMessage(
1755
+ missingDependencies,
1756
+ "a",
1757
+ "missing",
1758
+ "include"
1759
+ ) ||
1760
+ getWarningMessage(
1761
+ currentScope,
1762
+ "an",
1763
+ "unnecessary",
1764
+ "exclude"
1765
+ ) ||
1766
+ getWarningMessage(
1767
+ duplicateDependencies,
1768
+ "a",
1769
+ "duplicate",
1770
+ "omit"
1771
+ )) +
1772
+ _collectRecommendatio2,
1773
+ suggest: [
1774
+ {
1775
+ desc:
1776
+ "Update the dependencies array to be: [" +
1777
+ suggestedDeps.map(formatDependency).join(", ") +
1778
+ "]",
1779
+ fix: function (fixer) {
1780
+ return fixer.replaceText(
1781
+ declaredDependenciesNode,
1782
+ "[" +
1783
+ suggestedDeps.map(formatDependency).join(", ") +
1784
+ "]"
1785
+ );
1786
+ }
1787
+ }
1788
+ ]
1789
+ });
1790
+ }
1791
+ } else {
1792
+ var setStateInsideEffectWithoutDeps = null;
1793
+ dependencies.forEach(function (_ref3, key) {
1794
+ setStateInsideEffectWithoutDeps ||
1795
+ _ref3.references.forEach(function (reference) {
1796
+ if (
1797
+ !setStateInsideEffectWithoutDeps &&
1798
+ setStateCallSites.has(reference.identifier)
1799
+ ) {
1800
+ for (
1801
+ reference = reference.from;
1802
+ "function" !== reference.type;
1803
+
1804
+ )
1805
+ reference = reference.upper;
1806
+ reference.block === node &&
1807
+ (setStateInsideEffectWithoutDeps = key);
1808
+ }
1809
+ });
1810
+ });
1811
+ if (setStateInsideEffectWithoutDeps) {
1812
+ var _suggestedDependencies = collectRecommendations({
1813
+ dependencies: dependencies,
1814
+ declaredDependencies: [],
1815
+ stableDependencies: stableDependencies,
1816
+ externalDependencies: new Set(),
1817
+ isEffect: !0
1818
+ }).suggestedDependencies;
1819
+ reportProblem({
1820
+ node: reactiveHook,
1821
+ message:
1822
+ "React Hook " +
1823
+ reactiveHookName +
1824
+ " contains a call to '" +
1825
+ setStateInsideEffectWithoutDeps +
1826
+ "'. Without a list of dependencies, this can lead to an infinite chain of updates. To fix this, pass [" +
1827
+ _suggestedDependencies.join(", ") +
1828
+ ("] as a second argument to the " +
1829
+ reactiveHookName +
1830
+ " Hook."),
1831
+ suggest: [
1832
+ {
1833
+ desc:
1834
+ "Add dependencies array: [" +
1835
+ _suggestedDependencies.join(", ") +
1836
+ "]",
1837
+ fix: function (fixer) {
1838
+ return fixer.insertTextAfter(
1839
+ node,
1840
+ ", [" + _suggestedDependencies.join(", ") + "]"
1841
+ );
1842
+ }
1843
+ }
1844
+ ]
1845
+ });
1846
+ }
1847
+ }
1270
1848
  }
1271
1849
  }
1272
- } catch (err) {
1273
- _iterator2.e(err);
1274
- } finally {
1275
- _iterator2.f();
1276
- }
1277
-
1278
- var _iterator3 = _createForOfIteratorHelper(currentScope.childScopes),
1279
- _step3;
1280
-
1281
- try {
1282
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
1283
- var childScope = _step3.value;
1284
- gatherDependenciesRecursively(childScope);
1285
- }
1286
- } catch (err) {
1287
- _iterator3.e(err);
1288
- } finally {
1289
- _iterator3.f();
1290
- }
1291
- } // Warn about accessing .current in cleanup effects.
1292
-
1293
-
1294
- currentRefsInEffectCleanup.forEach(function (_ref, dependency) {
1295
- var reference = _ref.reference,
1296
- dependencyNode = _ref.dependencyNode;
1297
- var references = reference.resolved.references; // Is React managing this ref or us?
1298
- // Let's see if we can find a .current assignment.
1299
-
1300
- var foundCurrentAssignment = false;
1301
-
1302
- for (var i = 0; i < references.length; i++) {
1303
- var identifier = references[i].identifier;
1304
- var parent = identifier.parent;
1305
-
1306
- if (parent != null && // ref.current
1307
- // Note: no need to handle OptionalMemberExpression because it can't be LHS.
1308
- parent.type === 'MemberExpression' && !parent.computed && parent.property.type === 'Identifier' && parent.property.name === 'current' && // ref.current = <something>
1309
- parent.parent.type === 'AssignmentExpression' && parent.parent.left === parent) {
1310
- foundCurrentAssignment = true;
1311
- break;
1312
- }
1313
- } // We only want to warn about React-managed refs.
1314
-
1315
-
1316
- if (foundCurrentAssignment) {
1317
- return;
1318
- }
1319
-
1320
- reportProblem({
1321
- node: dependencyNode.parent.property,
1322
- message: "The ref value '" + dependency + ".current' will likely have " + "changed by the time this effect cleanup function runs. If " + "this ref points to a node rendered by React, copy " + ("'" + dependency + ".current' to a variable inside the effect, and ") + "use that variable in the cleanup function."
1323
- });
1324
- }); // Warn about assigning to variables in the outer scope.
1325
- // Those are usually bugs.
1326
-
1327
- var staleAssignments = new Set();
1328
-
1329
- function reportStaleAssignment(writeExpr, key) {
1330
- if (staleAssignments.has(key)) {
1331
- return;
1332
- }
1333
-
1334
- staleAssignments.add(key);
1335
- reportProblem({
1336
- node: writeExpr,
1337
- message: "Assignments to the '" + key + "' variable from inside React Hook " + (getSource(reactiveHook) + " will be lost after each ") + "render. To preserve the value over time, store it in a useRef " + "Hook and keep the mutable value in the '.current' property. " + "Otherwise, you can move this variable directly inside " + (getSource(reactiveHook) + ".")
1338
- });
1339
- } // Remember which deps are stable and report bad usage first.
1340
-
1341
-
1342
- var stableDependencies = new Set();
1343
- dependencies.forEach(function (_ref2, key) {
1344
- var isStable = _ref2.isStable,
1345
- references = _ref2.references;
1346
-
1347
- if (isStable) {
1348
- stableDependencies.add(key);
1850
+ var enableDangerousAutofixThisMayCauseInfiniteLoops =
1851
+ (context.options &&
1852
+ context.options[0] &&
1853
+ context.options[0]
1854
+ .enableDangerousAutofixThisMayCauseInfiniteLoops) ||
1855
+ !1,
1856
+ options = {
1857
+ additionalHooks:
1858
+ context.options &&
1859
+ context.options[0] &&
1860
+ context.options[0].additionalHooks
1861
+ ? new RegExp(context.options[0].additionalHooks)
1862
+ : void 0,
1863
+ enableDangerousAutofixThisMayCauseInfiniteLoops:
1864
+ enableDangerousAutofixThisMayCauseInfiniteLoops
1865
+ },
1866
+ getSource =
1867
+ "function" === typeof context.getSource
1868
+ ? function (node) {
1869
+ return context.getSource(node);
1870
+ }
1871
+ : function (node) {
1872
+ return context.sourceCode.getText(node);
1873
+ },
1874
+ getScope =
1875
+ "function" === typeof context.getScope
1876
+ ? function () {
1877
+ return context.getScope();
1878
+ }
1879
+ : function (node) {
1880
+ return context.sourceCode.getScope(node);
1881
+ },
1882
+ scopeManager = context.getSourceCode().scopeManager,
1883
+ setStateCallSites = new WeakMap(),
1884
+ stateVariables = new WeakSet(),
1885
+ stableKnownValueCache = new WeakMap(),
1886
+ functionWithoutCapturedValueCache = new WeakMap(),
1887
+ useEffectEventVariables = new WeakSet();
1888
+ return {
1889
+ CallExpression: function (node) {
1890
+ var callbackIndex = getReactiveHookCallbackIndex(
1891
+ node.callee,
1892
+ options
1893
+ );
1894
+ if (-1 !== callbackIndex) {
1895
+ var callback = node.arguments[callbackIndex],
1896
+ reactiveHook = node.callee,
1897
+ reactiveHookName =
1898
+ getNodeWithoutReactNamespace(reactiveHook).name;
1899
+ node = node.arguments[callbackIndex + 1];
1900
+ var declaredDependenciesNode =
1901
+ !node ||
1902
+ ("Identifier" === node.type && "undefined" === node.name)
1903
+ ? void 0
1904
+ : node;
1905
+ node = /Effect($|[^a-z])/g.test(reactiveHookName);
1906
+ if (callback)
1907
+ if (declaredDependenciesNode || node) {
1908
+ switch (callback.type) {
1909
+ case "FunctionExpression":
1910
+ case "ArrowFunctionExpression":
1911
+ visitFunctionWithDependencies(
1912
+ callback,
1913
+ declaredDependenciesNode,
1914
+ reactiveHook,
1915
+ reactiveHookName,
1916
+ node
1917
+ );
1918
+ return;
1919
+ case "TSAsExpression":
1920
+ visitFunctionWithDependencies(
1921
+ callback.expression,
1922
+ declaredDependenciesNode,
1923
+ reactiveHook,
1924
+ reactiveHookName,
1925
+ node
1926
+ );
1927
+ return;
1928
+ case "Identifier":
1929
+ if (
1930
+ !declaredDependenciesNode ||
1931
+ (declaredDependenciesNode.elements &&
1932
+ declaredDependenciesNode.elements.some(
1933
+ function (el) {
1934
+ return (
1935
+ el &&
1936
+ "Identifier" === el.type &&
1937
+ el.name === callback.name
1938
+ );
1939
+ }
1940
+ ))
1941
+ )
1942
+ return;
1943
+ callbackIndex = getScope(callback).set.get(
1944
+ callback.name
1945
+ );
1946
+ if (null == callbackIndex || null == callbackIndex.defs)
1947
+ return;
1948
+ callbackIndex = callbackIndex.defs[0];
1949
+ if (!callbackIndex || !callbackIndex.node) break;
1950
+ if (
1951
+ "Variable" !== callbackIndex.type &&
1952
+ "FunctionName" !== callbackIndex.type
1953
+ )
1954
+ break;
1955
+ switch (callbackIndex.node.type) {
1956
+ case "FunctionDeclaration":
1957
+ visitFunctionWithDependencies(
1958
+ callbackIndex.node,
1959
+ declaredDependenciesNode,
1960
+ reactiveHook,
1961
+ reactiveHookName,
1962
+ node
1963
+ );
1964
+ return;
1965
+ case "VariableDeclarator":
1966
+ if ((callbackIndex = callbackIndex.node.init))
1967
+ switch (callbackIndex.type) {
1968
+ case "ArrowFunctionExpression":
1969
+ case "FunctionExpression":
1970
+ visitFunctionWithDependencies(
1971
+ callbackIndex,
1972
+ declaredDependenciesNode,
1973
+ reactiveHook,
1974
+ reactiveHookName,
1975
+ node
1976
+ );
1977
+ return;
1978
+ }
1979
+ }
1980
+ break;
1981
+ default:
1982
+ reportProblem({
1983
+ node: reactiveHook,
1984
+ message:
1985
+ "React Hook " +
1986
+ reactiveHookName +
1987
+ " received a function whose dependencies are unknown. Pass an inline function instead."
1988
+ });
1989
+ return;
1990
+ }
1991
+ reportProblem({
1992
+ node: reactiveHook,
1993
+ message:
1994
+ "React Hook " +
1995
+ reactiveHookName +
1996
+ " has a missing dependency: '" +
1997
+ callback.name +
1998
+ "'. Either include it or remove the dependency array.",
1999
+ suggest: [
2000
+ {
2001
+ desc:
2002
+ "Update the dependencies array to be: [" +
2003
+ callback.name +
2004
+ "]",
2005
+ fix: function (fixer) {
2006
+ return fixer.replaceText(
2007
+ declaredDependenciesNode,
2008
+ "[" + callback.name + "]"
2009
+ );
2010
+ }
2011
+ }
2012
+ ]
2013
+ });
2014
+ } else
2015
+ ("useMemo" !== reactiveHookName &&
2016
+ "useCallback" !== reactiveHookName) ||
2017
+ reportProblem({
2018
+ node: reactiveHook,
2019
+ message:
2020
+ "React Hook " +
2021
+ reactiveHookName +
2022
+ " does nothing when called with only one argument. Did you forget to pass an array of dependencies?"
2023
+ });
2024
+ else
2025
+ reportProblem({
2026
+ node: reactiveHook,
2027
+ message:
2028
+ "React Hook " +
2029
+ reactiveHookName +
2030
+ " requires an effect callback. Did you forget to pass a callback to the hook?"
2031
+ });
2032
+ }
2033
+ }
2034
+ };
1349
2035
  }
1350
-
1351
- references.forEach(function (reference) {
1352
- if (reference.writeExpr) {
1353
- reportStaleAssignment(reference.writeExpr, key);
1354
- }
1355
- });
1356
- });
1357
-
1358
- if (staleAssignments.size > 0) {
1359
- // The intent isn't clear so we'll wait until you fix those first.
1360
- return;
1361
- }
1362
-
1363
- if (!declaredDependenciesNode) {
1364
- // Check if there are any top-level setState() calls.
1365
- // Those tend to lead to infinite loops.
1366
- var setStateInsideEffectWithoutDeps = null;
1367
- dependencies.forEach(function (_ref3, key) {
1368
- var references = _ref3.references;
1369
-
1370
- if (setStateInsideEffectWithoutDeps) {
1371
- return;
1372
- }
1373
-
1374
- references.forEach(function (reference) {
1375
- if (setStateInsideEffectWithoutDeps) {
1376
- return;
1377
- }
1378
-
1379
- var id = reference.identifier;
1380
- var isSetState = setStateCallSites.has(id);
1381
-
1382
- if (!isSetState) {
1383
- return;
1384
- }
1385
-
1386
- var fnScope = reference.from;
1387
-
1388
- while (fnScope.type !== 'function') {
1389
- fnScope = fnScope.upper;
1390
- }
1391
-
1392
- var isDirectlyInsideEffect = fnScope.block === node;
1393
-
1394
- if (isDirectlyInsideEffect) {
1395
- // TODO: we could potentially ignore early returns.
1396
- setStateInsideEffectWithoutDeps = key;
1397
- }
1398
- });
1399
- });
1400
-
1401
- if (setStateInsideEffectWithoutDeps) {
1402
- var _collectRecommendatio = collectRecommendations({
1403
- dependencies: dependencies,
1404
- declaredDependencies: [],
1405
- stableDependencies: stableDependencies,
1406
- externalDependencies: new Set(),
1407
- isEffect: true
1408
- }),
1409
- _suggestedDependencies = _collectRecommendatio.suggestedDependencies;
1410
-
1411
- reportProblem({
1412
- node: reactiveHook,
1413
- message: "React Hook " + reactiveHookName + " contains a call to '" + setStateInsideEffectWithoutDeps + "'. " + "Without a list of dependencies, this can lead to an infinite chain of updates. " + "To fix this, pass [" + _suggestedDependencies.join(', ') + ("] as a second argument to the " + reactiveHookName + " Hook."),
1414
- suggest: [{
1415
- desc: "Add dependencies array: [" + _suggestedDependencies.join(', ') + "]",
1416
- fix: function (fixer) {
1417
- return fixer.insertTextAfter(node, ", [" + _suggestedDependencies.join(', ') + "]");
1418
- }
1419
- }]
1420
- });
1421
- }
1422
-
1423
- return;
1424
- }
1425
-
1426
- var declaredDependencies = [];
1427
- var externalDependencies = new Set();
1428
- var isArrayExpression = declaredDependenciesNode.type === 'ArrayExpression';
1429
- var isTSAsArrayExpression = declaredDependenciesNode.type === 'TSAsExpression' && declaredDependenciesNode.expression.type === 'ArrayExpression';
1430
-
1431
- if (!isArrayExpression && !isTSAsArrayExpression) {
1432
- // If the declared dependencies are not an array expression then we
1433
- // can't verify that the user provided the correct dependencies. Tell
1434
- // the user this in an error.
1435
- reportProblem({
1436
- node: declaredDependenciesNode,
1437
- message: "React Hook " + getSource(reactiveHook) + " was passed a " + 'dependency list that is not an array literal. This means we ' + "can't statically verify whether you've passed the correct " + 'dependencies.'
1438
- });
1439
- } else {
1440
- var arrayExpression = isTSAsArrayExpression ? declaredDependenciesNode.expression : declaredDependenciesNode;
1441
- arrayExpression.elements.forEach(function (declaredDependencyNode) {
1442
- // Skip elided elements.
1443
- if (declaredDependencyNode === null) {
1444
- return;
1445
- } // If we see a spread element then add a special warning.
1446
-
1447
-
1448
- if (declaredDependencyNode.type === 'SpreadElement') {
1449
- reportProblem({
1450
- node: declaredDependencyNode,
1451
- message: "React Hook " + getSource(reactiveHook) + " has a spread " + "element in its dependency array. This means we can't " + "statically verify whether you've passed the " + 'correct dependencies.'
1452
- });
1453
- return;
1454
- }
1455
-
1456
- if (useEffectEventVariables.has(declaredDependencyNode)) {
1457
- reportProblem({
1458
- node: declaredDependencyNode,
1459
- message: 'Functions returned from `useEffectEvent` must not be included in the dependency array. ' + ("Remove `" + getSource(declaredDependencyNode) + "` from the list."),
1460
- suggest: [{
1461
- desc: "Remove the dependency `" + getSource(declaredDependencyNode) + "`",
1462
- fix: function (fixer) {
1463
- return fixer.removeRange(declaredDependencyNode.range);
1464
- }
1465
- }]
1466
- });
1467
- } // Try to normalize the declared dependency. If we can't then an error
1468
- // will be thrown. We will catch that error and report an error.
1469
-
1470
-
1471
- var declaredDependency;
1472
-
1473
- try {
1474
- declaredDependency = analyzePropertyChain(declaredDependencyNode, null);
1475
- } catch (error) {
1476
- if (/Unsupported node type/.test(error.message)) {
1477
- if (declaredDependencyNode.type === 'Literal') {
1478
- if (dependencies.has(declaredDependencyNode.value)) {
1479
- reportProblem({
1480
- node: declaredDependencyNode,
1481
- message: "The " + declaredDependencyNode.raw + " literal is not a valid dependency " + "because it never changes. " + ("Did you mean to include " + declaredDependencyNode.value + " in the array instead?")
1482
- });
1483
- } else {
1484
- reportProblem({
1485
- node: declaredDependencyNode,
1486
- message: "The " + declaredDependencyNode.raw + " literal is not a valid dependency " + 'because it never changes. You can safely remove it.'
1487
- });
1488
- }
1489
- } else {
1490
- reportProblem({
1491
- node: declaredDependencyNode,
1492
- message: "React Hook " + getSource(reactiveHook) + " has a " + "complex expression in the dependency array. " + 'Extract it to a separate variable so it can be statically checked.'
1493
- });
1494
- }
1495
-
1496
- return;
1497
- } else {
1498
- throw error;
1499
- }
1500
- }
1501
-
1502
- var maybeID = declaredDependencyNode;
1503
-
1504
- while (maybeID.type === 'MemberExpression' || maybeID.type === 'OptionalMemberExpression' || maybeID.type === 'ChainExpression') {
1505
- maybeID = maybeID.object || maybeID.expression.object;
1506
- }
1507
-
1508
- var isDeclaredInComponent = !componentScope.through.some(function (ref) {
1509
- return ref.identifier === maybeID;
1510
- }); // Add the dependency to our declared dependency map.
1511
-
1512
- declaredDependencies.push({
1513
- key: declaredDependency,
1514
- node: declaredDependencyNode
1515
- });
1516
-
1517
- if (!isDeclaredInComponent) {
1518
- externalDependencies.add(declaredDependency);
1519
- }
1520
- });
1521
- }
1522
-
1523
- var _collectRecommendatio2 = collectRecommendations({
1524
- dependencies: dependencies,
1525
- declaredDependencies: declaredDependencies,
1526
- stableDependencies: stableDependencies,
1527
- externalDependencies: externalDependencies,
1528
- isEffect: isEffect
1529
- }),
1530
- suggestedDependencies = _collectRecommendatio2.suggestedDependencies,
1531
- unnecessaryDependencies = _collectRecommendatio2.unnecessaryDependencies,
1532
- missingDependencies = _collectRecommendatio2.missingDependencies,
1533
- duplicateDependencies = _collectRecommendatio2.duplicateDependencies;
1534
-
1535
- var suggestedDeps = suggestedDependencies;
1536
- var problemCount = duplicateDependencies.size + missingDependencies.size + unnecessaryDependencies.size;
1537
-
1538
- if (problemCount === 0) {
1539
- // If nothing else to report, check if some dependencies would
1540
- // invalidate on every render.
1541
- var constructions = scanForConstructions({
1542
- declaredDependencies: declaredDependencies,
1543
- declaredDependenciesNode: declaredDependenciesNode,
1544
- componentScope: componentScope,
1545
- scope: scope
1546
- });
1547
- constructions.forEach(function (_ref4) {
1548
- var construction = _ref4.construction,
1549
- isUsedOutsideOfHook = _ref4.isUsedOutsideOfHook,
1550
- depType = _ref4.depType;
1551
- var wrapperHook = depType === 'function' ? 'useCallback' : 'useMemo';
1552
- var constructionType = depType === 'function' ? 'definition' : 'initialization';
1553
- var defaultAdvice = "wrap the " + constructionType + " of '" + construction.name.name + "' in its own " + wrapperHook + "() Hook.";
1554
- var advice = isUsedOutsideOfHook ? "To fix this, " + defaultAdvice : "Move it inside the " + reactiveHookName + " callback. Alternatively, " + defaultAdvice;
1555
- var causation = depType === 'conditional' || depType === 'logical expression' ? 'could make' : 'makes';
1556
- var message = "The '" + construction.name.name + "' " + depType + " " + causation + " the dependencies of " + (reactiveHookName + " Hook (at line " + declaredDependenciesNode.loc.start.line + ") ") + ("change on every render. " + advice);
1557
- var suggest; // Only handle the simple case of variable assignments.
1558
- // Wrapping function declarations can mess up hoisting.
1559
-
1560
- if (isUsedOutsideOfHook && construction.type === 'Variable' && // Objects may be mutated after construction, which would make this
1561
- // fix unsafe. Functions _probably_ won't be mutated, so we'll
1562
- // allow this fix for them.
1563
- depType === 'function') {
1564
- suggest = [{
1565
- desc: "Wrap the " + constructionType + " of '" + construction.name.name + "' in its own " + wrapperHook + "() Hook.",
1566
- fix: function (fixer) {
1567
- var _ref5 = wrapperHook === 'useMemo' ? ["useMemo(() => { return ", '; })'] : ['useCallback(', ')'],
1568
- before = _ref5[0],
1569
- after = _ref5[1];
1570
-
1571
- return [// TODO: also add an import?
1572
- fixer.insertTextBefore(construction.node.init, before), // TODO: ideally we'd gather deps here but it would require
1573
- // restructuring the rule code. This will cause a new lint
1574
- // error to appear immediately for useCallback. Note we're
1575
- // not adding [] because would that changes semantics.
1576
- fixer.insertTextAfter(construction.node.init, after)];
1577
- }
1578
- }];
1579
- } // TODO: What if the function needs to change on every render anyway?
1580
- // Should we suggest removing effect deps as an appropriate fix too?
1581
-
1582
-
1583
- reportProblem({
1584
- // TODO: Why not report this at the dependency site?
1585
- node: construction.node,
1586
- message: message,
1587
- suggest: suggest
1588
- });
1589
- });
1590
- return;
1591
- } // If we're going to report a missing dependency,
1592
- // we might as well recalculate the list ignoring
1593
- // the currently specified deps. This can result
1594
- // in some extra deduplication. We can't do this
1595
- // for effects though because those have legit
1596
- // use cases for over-specifying deps.
1597
-
1598
-
1599
- if (!isEffect && missingDependencies.size > 0) {
1600
- suggestedDeps = collectRecommendations({
1601
- dependencies: dependencies,
1602
- declaredDependencies: [],
1603
- // Pretend we don't know
1604
- stableDependencies: stableDependencies,
1605
- externalDependencies: externalDependencies,
1606
- isEffect: isEffect
1607
- }).suggestedDependencies;
1608
- } // Alphabetize the suggestions, but only if deps were already alphabetized.
1609
-
1610
-
1611
- function areDeclaredDepsAlphabetized() {
1612
- if (declaredDependencies.length === 0) {
1613
- return true;
1614
- }
1615
-
1616
- var declaredDepKeys = declaredDependencies.map(function (dep) {
1617
- return dep.key;
1618
- });
1619
- var sortedDeclaredDepKeys = declaredDepKeys.slice().sort();
1620
- return declaredDepKeys.join(',') === sortedDeclaredDepKeys.join(',');
1621
- }
1622
-
1623
- if (areDeclaredDepsAlphabetized()) {
1624
- suggestedDeps.sort();
1625
- } // Most of our algorithm deals with dependency paths with optional chaining stripped.
1626
- // This function is the last step before printing a dependency, so now is a good time to
1627
- // check whether any members in our path are always used as optional-only. In that case,
1628
- // we will use ?. instead of . to concatenate those parts of the path.
1629
-
1630
-
1631
- function formatDependency(path) {
1632
- var members = path.split('.');
1633
- var finalPath = '';
1634
-
1635
- for (var i = 0; i < members.length; i++) {
1636
- if (i !== 0) {
1637
- var pathSoFar = members.slice(0, i + 1).join('.');
1638
- var isOptional = optionalChains.get(pathSoFar) === true;
1639
- finalPath += isOptional ? '?.' : '.';
1640
- }
1641
-
1642
- finalPath += members[i];
1643
- }
1644
-
1645
- return finalPath;
1646
- }
1647
-
1648
- function getWarningMessage(deps, singlePrefix, label, fixVerb) {
1649
- if (deps.size === 0) {
1650
- return null;
1651
- }
1652
-
1653
- return (deps.size > 1 ? '' : singlePrefix + ' ') + label + ' ' + (deps.size > 1 ? 'dependencies' : 'dependency') + ': ' + joinEnglish(Array.from(deps).sort().map(function (name) {
1654
- return "'" + formatDependency(name) + "'";
1655
- })) + (". Either " + fixVerb + " " + (deps.size > 1 ? 'them' : 'it') + " or remove the dependency array.");
1656
- }
1657
-
1658
- var extraWarning = '';
1659
-
1660
- if (unnecessaryDependencies.size > 0) {
1661
- var badRef = null;
1662
- Array.from(unnecessaryDependencies.keys()).forEach(function (key) {
1663
- if (badRef !== null) {
1664
- return;
1665
- }
1666
-
1667
- if (key.endsWith('.current')) {
1668
- badRef = key;
1669
- }
1670
- });
1671
-
1672
- if (badRef !== null) {
1673
- extraWarning = " Mutable values like '" + badRef + "' aren't valid dependencies " + "because mutating them doesn't re-render the component.";
1674
- } else if (externalDependencies.size > 0) {
1675
- var dep = Array.from(externalDependencies)[0]; // Don't show this warning for things that likely just got moved *inside* the callback
1676
- // because in that case they're clearly not referring to globals.
1677
-
1678
- if (!scope.set.has(dep)) {
1679
- extraWarning = " Outer scope values like '" + dep + "' aren't valid dependencies " + "because mutating them doesn't re-render the component.";
1680
- }
1681
- }
1682
- } // `props.foo()` marks `props` as a dependency because it has
1683
- // a `this` value. This warning can be confusing.
1684
- // So if we're going to show it, append a clarification.
1685
-
1686
-
1687
- if (!extraWarning && missingDependencies.has('props')) {
1688
- var propDep = dependencies.get('props');
1689
-
1690
- if (propDep == null) {
1691
- return;
1692
- }
1693
-
1694
- var refs = propDep.references;
1695
-
1696
- if (!Array.isArray(refs)) {
1697
- return;
1698
- }
1699
-
1700
- var isPropsOnlyUsedInMembers = true;
1701
-
1702
- for (var i = 0; i < refs.length; i++) {
1703
- var ref = refs[i];
1704
- var id = fastFindReferenceWithParent(componentScope.block, ref.identifier);
1705
-
1706
- if (!id) {
1707
- isPropsOnlyUsedInMembers = false;
1708
- break;
1709
- }
1710
-
1711
- var parent = id.parent;
1712
-
1713
- if (parent == null) {
1714
- isPropsOnlyUsedInMembers = false;
1715
- break;
1716
- }
1717
-
1718
- if (parent.type !== 'MemberExpression' && parent.type !== 'OptionalMemberExpression') {
1719
- isPropsOnlyUsedInMembers = false;
1720
- break;
1721
- }
1722
- }
1723
-
1724
- if (isPropsOnlyUsedInMembers) {
1725
- extraWarning = " However, 'props' will change when *any* prop changes, so the " + "preferred fix is to destructure the 'props' object outside of " + ("the " + reactiveHookName + " call and refer to those specific props ") + ("inside " + getSource(reactiveHook) + ".");
1726
- }
1727
- }
1728
-
1729
- if (!extraWarning && missingDependencies.size > 0) {
1730
- // See if the user is trying to avoid specifying a callable prop.
1731
- // This usually means they're unaware of useCallback.
1732
- var missingCallbackDep = null;
1733
- missingDependencies.forEach(function (missingDep) {
1734
- if (missingCallbackDep) {
1735
- return;
1736
- } // Is this a variable from top scope?
1737
-
1738
-
1739
- var topScopeRef = componentScope.set.get(missingDep);
1740
- var usedDep = dependencies.get(missingDep);
1741
-
1742
- if (usedDep.references[0].resolved !== topScopeRef) {
1743
- return;
1744
- } // Is this a destructured prop?
1745
-
1746
-
1747
- var def = topScopeRef.defs[0];
1748
-
1749
- if (def == null || def.name == null || def.type !== 'Parameter') {
1750
- return;
1751
- } // Was it called in at least one case? Then it's a function.
1752
-
1753
-
1754
- var isFunctionCall = false;
1755
- var id;
1756
-
1757
- for (var _i2 = 0; _i2 < usedDep.references.length; _i2++) {
1758
- id = usedDep.references[_i2].identifier;
1759
-
1760
- if (id != null && id.parent != null && (id.parent.type === 'CallExpression' || id.parent.type === 'OptionalCallExpression') && id.parent.callee === id) {
1761
- isFunctionCall = true;
1762
- break;
1763
- }
1764
- }
1765
-
1766
- if (!isFunctionCall) {
1767
- return;
1768
- } // If it's missing (i.e. in component scope) *and* it's a parameter
1769
- // then it is definitely coming from props destructuring.
1770
- // (It could also be props itself but we wouldn't be calling it then.)
1771
-
1772
-
1773
- missingCallbackDep = missingDep;
1774
- });
1775
-
1776
- if (missingCallbackDep !== null) {
1777
- extraWarning = " If '" + missingCallbackDep + "' changes too often, " + "find the parent component that defines it " + "and wrap that definition in useCallback.";
1778
- }
1779
- }
1780
-
1781
- if (!extraWarning && missingDependencies.size > 0) {
1782
- var setStateRecommendation = null;
1783
- missingDependencies.forEach(function (missingDep) {
1784
- if (setStateRecommendation !== null) {
1785
- return;
1786
- }
1787
-
1788
- var usedDep = dependencies.get(missingDep);
1789
- var references = usedDep.references;
1790
- var id;
1791
- var maybeCall;
1792
-
1793
- for (var _i3 = 0; _i3 < references.length; _i3++) {
1794
- id = references[_i3].identifier;
1795
- maybeCall = id.parent; // Try to see if we have setState(someExpr(missingDep)).
1796
-
1797
- while (maybeCall != null && maybeCall !== componentScope.block) {
1798
- if (maybeCall.type === 'CallExpression') {
1799
- var correspondingStateVariable = setStateCallSites.get(maybeCall.callee);
1800
-
1801
- if (correspondingStateVariable != null) {
1802
- if (correspondingStateVariable.name === missingDep) {
1803
- // setCount(count + 1)
1804
- setStateRecommendation = {
1805
- missingDep: missingDep,
1806
- setter: maybeCall.callee.name,
1807
- form: 'updater'
1808
- };
1809
- } else if (stateVariables.has(id)) {
1810
- // setCount(count + increment)
1811
- setStateRecommendation = {
1812
- missingDep: missingDep,
1813
- setter: maybeCall.callee.name,
1814
- form: 'reducer'
1815
- };
1816
- } else {
1817
- var resolved = references[_i3].resolved;
1818
-
1819
- if (resolved != null) {
1820
- // If it's a parameter *and* a missing dep,
1821
- // it must be a prop or something inside a prop.
1822
- // Therefore, recommend an inline reducer.
1823
- var def = resolved.defs[0];
1824
-
1825
- if (def != null && def.type === 'Parameter') {
1826
- setStateRecommendation = {
1827
- missingDep: missingDep,
1828
- setter: maybeCall.callee.name,
1829
- form: 'inlineReducer'
1830
- };
1831
- }
1832
- }
1833
- }
1834
-
1835
- break;
1836
- }
1837
- }
1838
-
1839
- maybeCall = maybeCall.parent;
1840
- }
1841
-
1842
- if (setStateRecommendation !== null) {
1843
- break;
1844
- }
1845
- }
1846
- });
1847
-
1848
- if (setStateRecommendation !== null) {
1849
- switch (setStateRecommendation.form) {
1850
- case 'reducer':
1851
- extraWarning = " You can also replace multiple useState variables with useReducer " + ("if '" + setStateRecommendation.setter + "' needs the ") + ("current value of '" + setStateRecommendation.missingDep + "'.");
1852
- break;
1853
-
1854
- case 'inlineReducer':
1855
- extraWarning = " If '" + setStateRecommendation.setter + "' needs the " + ("current value of '" + setStateRecommendation.missingDep + "', ") + "you can also switch to useReducer instead of useState and " + ("read '" + setStateRecommendation.missingDep + "' in the reducer.");
1856
- break;
1857
-
1858
- case 'updater':
1859
- extraWarning = " You can also do a functional update '" + setStateRecommendation.setter + "(" + setStateRecommendation.missingDep.slice(0, 1) + " => ...)' if you only need '" + setStateRecommendation.missingDep + "'" + (" in the '" + setStateRecommendation.setter + "' call.");
1860
- break;
1861
-
1862
- default:
1863
- throw new Error('Unknown case.');
1864
- }
1865
- }
1866
- }
1867
-
1868
- reportProblem({
1869
- node: declaredDependenciesNode,
1870
- message: "React Hook " + getSource(reactiveHook) + " has " + ( // To avoid a long message, show the next actionable item.
1871
- getWarningMessage(missingDependencies, 'a', 'missing', 'include') || getWarningMessage(unnecessaryDependencies, 'an', 'unnecessary', 'exclude') || getWarningMessage(duplicateDependencies, 'a', 'duplicate', 'omit')) + extraWarning,
1872
- suggest: [{
1873
- desc: "Update the dependencies array to be: [" + suggestedDeps.map(formatDependency).join(', ') + "]",
1874
- fix: function (fixer) {
1875
- // TODO: consider preserving the comments or formatting?
1876
- return fixer.replaceText(declaredDependenciesNode, "[" + suggestedDeps.map(formatDependency).join(', ') + "]");
1877
- }
1878
- }]
1879
- });
1880
- }
1881
-
1882
- function visitCallExpression(node) {
1883
- var callbackIndex = getReactiveHookCallbackIndex(node.callee, options);
1884
-
1885
- if (callbackIndex === -1) {
1886
- // Not a React Hook call that needs deps.
1887
- return;
1888
- }
1889
-
1890
- var callback = node.arguments[callbackIndex];
1891
- var reactiveHook = node.callee;
1892
- var reactiveHookName = getNodeWithoutReactNamespace(reactiveHook).name;
1893
- var maybeNode = node.arguments[callbackIndex + 1];
1894
- var declaredDependenciesNode = maybeNode && !(maybeNode.type === 'Identifier' && maybeNode.name === 'undefined') ? maybeNode : undefined;
1895
- var isEffect = /Effect($|[^a-z])/g.test(reactiveHookName); // Check whether a callback is supplied. If there is no callback supplied
1896
- // then the hook will not work and React will throw a TypeError.
1897
- // So no need to check for dependency inclusion.
1898
-
1899
- if (!callback) {
1900
- reportProblem({
1901
- node: reactiveHook,
1902
- message: "React Hook " + reactiveHookName + " requires an effect callback. " + "Did you forget to pass a callback to the hook?"
1903
- });
1904
- return;
1905
- } // Check the declared dependencies for this reactive hook. If there is no
1906
- // second argument then the reactive callback will re-run on every render.
1907
- // So no need to check for dependency inclusion.
1908
-
1909
-
1910
- if (!declaredDependenciesNode && !isEffect) {
1911
- // These are only used for optimization.
1912
- if (reactiveHookName === 'useMemo' || reactiveHookName === 'useCallback') {
1913
- // TODO: Can this have a suggestion?
1914
- reportProblem({
1915
- node: reactiveHook,
1916
- message: "React Hook " + reactiveHookName + " does nothing when called with " + "only one argument. Did you forget to pass an array of " + "dependencies?"
1917
- });
1918
- }
1919
-
1920
- return;
1921
- }
1922
-
1923
- switch (callback.type) {
1924
- case 'FunctionExpression':
1925
- case 'ArrowFunctionExpression':
1926
- visitFunctionWithDependencies(callback, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect);
1927
- return;
1928
- // Handled
1929
-
1930
- case 'TSAsExpression':
1931
- visitFunctionWithDependencies(callback.expression, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect);
1932
- return;
1933
- // Handled
1934
-
1935
- case 'Identifier':
1936
- if (!declaredDependenciesNode) {
1937
- // No deps, no problems.
1938
- return; // Handled
1939
- } // The function passed as a callback is not written inline.
1940
- // But perhaps it's in the dependencies array?
1941
-
1942
-
1943
- if (declaredDependenciesNode.elements && declaredDependenciesNode.elements.some(function (el) {
1944
- return el && el.type === 'Identifier' && el.name === callback.name;
1945
- })) {
1946
- // If it's already in the list of deps, we don't care because
1947
- // this is valid regardless.
1948
- return; // Handled
1949
- } // We'll do our best effort to find it, complain otherwise.
1950
-
1951
-
1952
- var variable = getScope(callback).set.get(callback.name);
1953
-
1954
- if (variable == null || variable.defs == null) {
1955
- // If it's not in scope, we don't care.
1956
- return; // Handled
1957
- } // The function passed as a callback is not written inline.
1958
- // But it's defined somewhere in the render scope.
1959
- // We'll do our best effort to find and check it, complain otherwise.
1960
-
1961
-
1962
- var def = variable.defs[0];
1963
-
1964
- if (!def || !def.node) {
1965
- break; // Unhandled
1966
- }
1967
-
1968
- if (def.type !== 'Variable' && def.type !== 'FunctionName') {
1969
- // Parameter or an unusual pattern. Bail out.
1970
- break; // Unhandled
1971
- }
1972
-
1973
- switch (def.node.type) {
1974
- case 'FunctionDeclaration':
1975
- // useEffect(() => { ... }, []);
1976
- visitFunctionWithDependencies(def.node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect);
1977
- return;
1978
- // Handled
1979
-
1980
- case 'VariableDeclarator':
1981
- var init = def.node.init;
1982
-
1983
- if (!init) {
1984
- break; // Unhandled
1985
- }
1986
-
1987
- switch (init.type) {
1988
- // const effectBody = () => {...};
1989
- // useEffect(effectBody, []);
1990
- case 'ArrowFunctionExpression':
1991
- case 'FunctionExpression':
1992
- // We can inspect this function as if it were inline.
1993
- visitFunctionWithDependencies(init, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect);
1994
- return;
1995
- // Handled
1996
- }
1997
-
1998
- break;
1999
- // Unhandled
2000
- }
2001
-
2002
- break;
2003
- // Unhandled
2004
-
2005
- default:
2006
- // useEffect(generateEffectBody(), []);
2007
- reportProblem({
2008
- node: reactiveHook,
2009
- message: "React Hook " + reactiveHookName + " received a function whose dependencies " + "are unknown. Pass an inline function instead."
2010
- });
2011
- return;
2012
- // Handled
2013
- } // Something unusual. Fall back to suggesting to add the body itself as a dep.
2014
-
2015
-
2016
- reportProblem({
2017
- node: reactiveHook,
2018
- message: "React Hook " + reactiveHookName + " has a missing dependency: '" + callback.name + "'. " + "Either include it or remove the dependency array.",
2019
- suggest: [{
2020
- desc: "Update the dependencies array to be: [" + callback.name + "]",
2021
- fix: function (fixer) {
2022
- return fixer.replaceText(declaredDependenciesNode, "[" + callback.name + "]");
2023
- }
2024
- }]
2025
- });
2026
- }
2027
-
2028
- return {
2029
- CallExpression: visitCallExpression
2030
- };
2031
- }
2032
- }; // The meat of the logic.
2033
-
2034
- function collectRecommendations(_ref6) {
2035
- var dependencies = _ref6.dependencies,
2036
- declaredDependencies = _ref6.declaredDependencies,
2037
- stableDependencies = _ref6.stableDependencies,
2038
- externalDependencies = _ref6.externalDependencies,
2039
- isEffect = _ref6.isEffect;
2040
- // Our primary data structure.
2041
- // It is a logical representation of property chains:
2042
- // `props` -> `props.foo` -> `props.foo.bar` -> `props.foo.bar.baz`
2043
- // -> `props.lol`
2044
- // -> `props.huh` -> `props.huh.okay`
2045
- // -> `props.wow`
2046
- // We'll use it to mark nodes that are *used* by the programmer,
2047
- // and the nodes that were *declared* as deps. Then we will
2048
- // traverse it to learn which deps are missing or unnecessary.
2049
- var depTree = createDepTree();
2050
-
2051
- function createDepTree() {
2052
- return {
2053
- isUsed: false,
2054
- // True if used in code
2055
- isSatisfiedRecursively: false,
2056
- // True if specified in deps
2057
- isSubtreeUsed: false,
2058
- // True if something deeper is used by code
2059
- children: new Map() // Nodes for properties
2060
-
2061
- };
2062
- } // Mark all required nodes first.
2063
- // Imagine exclamation marks next to each used deep property.
2064
-
2065
-
2066
- dependencies.forEach(function (_, key) {
2067
- var node = getOrCreateNodeByPath(depTree, key);
2068
- node.isUsed = true;
2069
- markAllParentsByPath(depTree, key, function (parent) {
2070
- parent.isSubtreeUsed = true;
2071
- });
2072
- }); // Mark all satisfied nodes.
2073
- // Imagine checkmarks next to each declared dependency.
2074
-
2075
- declaredDependencies.forEach(function (_ref7) {
2076
- var key = _ref7.key;
2077
- var node = getOrCreateNodeByPath(depTree, key);
2078
- node.isSatisfiedRecursively = true;
2079
- });
2080
- stableDependencies.forEach(function (key) {
2081
- var node = getOrCreateNodeByPath(depTree, key);
2082
- node.isSatisfiedRecursively = true;
2083
- }); // Tree manipulation helpers.
2084
-
2085
- function getOrCreateNodeByPath(rootNode, path) {
2086
- var keys = path.split('.');
2087
- var node = rootNode;
2088
-
2089
- var _iterator4 = _createForOfIteratorHelper(keys),
2090
- _step4;
2091
-
2092
- try {
2093
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
2094
- var key = _step4.value;
2095
- var child = node.children.get(key);
2096
-
2097
- if (!child) {
2098
- child = createDepTree();
2099
- node.children.set(key, child);
2100
- }
2101
-
2102
- node = child;
2103
- }
2104
- } catch (err) {
2105
- _iterator4.e(err);
2106
- } finally {
2107
- _iterator4.f();
2108
- }
2109
-
2110
- return node;
2111
- }
2112
-
2113
- function markAllParentsByPath(rootNode, path, fn) {
2114
- var keys = path.split('.');
2115
- var node = rootNode;
2116
-
2117
- var _iterator5 = _createForOfIteratorHelper(keys),
2118
- _step5;
2119
-
2120
- try {
2121
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
2122
- var key = _step5.value;
2123
- var child = node.children.get(key);
2124
-
2125
- if (!child) {
2126
- return;
2127
- }
2128
-
2129
- fn(child);
2130
- node = child;
2131
- }
2132
- } catch (err) {
2133
- _iterator5.e(err);
2134
- } finally {
2135
- _iterator5.f();
2136
- }
2137
- } // Now we can learn which dependencies are missing or necessary.
2138
-
2139
-
2140
- var missingDependencies = new Set();
2141
- var satisfyingDependencies = new Set();
2142
- scanTreeRecursively(depTree, missingDependencies, satisfyingDependencies, function (key) {
2143
- return key;
2144
- });
2145
-
2146
- function scanTreeRecursively(node, missingPaths, satisfyingPaths, keyToPath) {
2147
- node.children.forEach(function (child, key) {
2148
- var path = keyToPath(key);
2149
-
2150
- if (child.isSatisfiedRecursively) {
2151
- if (child.isSubtreeUsed) {
2152
- // Remember this dep actually satisfied something.
2153
- satisfyingPaths.add(path);
2154
- } // It doesn't matter if there's something deeper.
2155
- // It would be transitively satisfied since we assume immutability.
2156
- // `props.foo` is enough if you read `props.foo.id`.
2157
-
2158
-
2159
- return;
2160
- }
2161
-
2162
- if (child.isUsed) {
2163
- // Remember that no declared deps satisfied this node.
2164
- missingPaths.add(path); // If we got here, nothing in its subtree was satisfied.
2165
- // No need to search further.
2166
-
2167
- return;
2168
- }
2169
-
2170
- scanTreeRecursively(child, missingPaths, satisfyingPaths, function (childKey) {
2171
- return path + '.' + childKey;
2172
- });
2173
- });
2174
- } // Collect suggestions in the order they were originally specified.
2175
-
2176
-
2177
- var suggestedDependencies = [];
2178
- var unnecessaryDependencies = new Set();
2179
- var duplicateDependencies = new Set();
2180
- declaredDependencies.forEach(function (_ref8) {
2181
- var key = _ref8.key;
2182
-
2183
- // Does this declared dep satisfy a real need?
2184
- if (satisfyingDependencies.has(key)) {
2185
- if (suggestedDependencies.indexOf(key) === -1) {
2186
- // Good one.
2187
- suggestedDependencies.push(key);
2188
- } else {
2189
- // Duplicate.
2190
- duplicateDependencies.add(key);
2191
- }
2192
- } else {
2193
- if (isEffect && !key.endsWith('.current') && !externalDependencies.has(key)) {
2194
- // Effects are allowed extra "unnecessary" deps.
2195
- // Such as resetting scroll when ID changes.
2196
- // Consider them legit.
2197
- // The exception is ref.current which is always wrong.
2198
- if (suggestedDependencies.indexOf(key) === -1) {
2199
- suggestedDependencies.push(key);
2200
- }
2201
- } else {
2202
- // It's definitely not needed.
2203
- unnecessaryDependencies.add(key);
2204
- }
2205
- }
2206
- }); // Then add the missing ones at the end.
2207
-
2208
- missingDependencies.forEach(function (key) {
2209
- suggestedDependencies.push(key);
2210
- });
2211
- return {
2212
- suggestedDependencies: suggestedDependencies,
2213
- unnecessaryDependencies: unnecessaryDependencies,
2214
- duplicateDependencies: duplicateDependencies,
2215
- missingDependencies: missingDependencies
2216
- };
2217
- } // If the node will result in constructing a referentially unique value, return
2218
- // its human readable type name, else return null.
2219
-
2220
-
2221
- function getConstructionExpressionType(node) {
2222
- switch (node.type) {
2223
- case 'ObjectExpression':
2224
- return 'object';
2225
-
2226
- case 'ArrayExpression':
2227
- return 'array';
2228
-
2229
- case 'ArrowFunctionExpression':
2230
- case 'FunctionExpression':
2231
- return 'function';
2232
-
2233
- case 'ClassExpression':
2234
- return 'class';
2235
-
2236
- case 'ConditionalExpression':
2237
- if (getConstructionExpressionType(node.consequent) != null || getConstructionExpressionType(node.alternate) != null) {
2238
- return 'conditional';
2239
- }
2240
-
2241
- return null;
2242
-
2243
- case 'LogicalExpression':
2244
- if (getConstructionExpressionType(node.left) != null || getConstructionExpressionType(node.right) != null) {
2245
- return 'logical expression';
2246
- }
2247
-
2248
- return null;
2249
-
2250
- case 'JSXFragment':
2251
- return 'JSX fragment';
2252
-
2253
- case 'JSXElement':
2254
- return 'JSX element';
2255
-
2256
- case 'AssignmentExpression':
2257
- if (getConstructionExpressionType(node.right) != null) {
2258
- return 'assignment expression';
2259
2036
  }
2260
-
2261
- return null;
2262
-
2263
- case 'NewExpression':
2264
- return 'object construction';
2265
-
2266
- case 'Literal':
2267
- if (node.value instanceof RegExp) {
2268
- return 'regular expression';
2269
- }
2270
-
2271
- return null;
2272
-
2273
- case 'TypeCastExpression':
2274
- case 'AsExpression':
2275
- case 'TSAsExpression':
2276
- return getConstructionExpressionType(node.expression);
2277
- }
2278
-
2279
- return null;
2280
- } // Finds variables declared as dependencies
2281
- // that would invalidate on every render.
2282
-
2283
-
2284
- function scanForConstructions(_ref9) {
2285
- var declaredDependencies = _ref9.declaredDependencies,
2286
- declaredDependenciesNode = _ref9.declaredDependenciesNode,
2287
- componentScope = _ref9.componentScope,
2288
- scope = _ref9.scope;
2289
- var constructions = declaredDependencies.map(function (_ref10) {
2290
- var key = _ref10.key;
2291
- var ref = componentScope.variables.find(function (v) {
2292
- return v.name === key;
2293
- });
2294
-
2295
- if (ref == null) {
2296
- return null;
2297
- }
2298
-
2299
- var node = ref.defs[0];
2300
-
2301
- if (node == null) {
2302
- return null;
2303
- } // const handleChange = function () {}
2304
- // const handleChange = () => {}
2305
- // const foo = {}
2306
- // const foo = []
2307
- // etc.
2308
-
2309
-
2310
- if (node.type === 'Variable' && node.node.type === 'VariableDeclarator' && node.node.id.type === 'Identifier' && // Ensure this is not destructed assignment
2311
- node.node.init != null) {
2312
- var constantExpressionType = getConstructionExpressionType(node.node.init);
2313
-
2314
- if (constantExpressionType != null) {
2315
- return [ref, constantExpressionType];
2316
- }
2317
- } // function handleChange() {}
2318
-
2319
-
2320
- if (node.type === 'FunctionName' && node.node.type === 'FunctionDeclaration') {
2321
- return [ref, 'function'];
2322
- } // class Foo {}
2323
-
2324
-
2325
- if (node.type === 'ClassName' && node.node.type === 'ClassDeclaration') {
2326
- return [ref, 'class'];
2327
- }
2328
-
2329
- return null;
2330
- }).filter(Boolean);
2331
-
2332
- function isUsedOutsideOfHook(ref) {
2333
- var foundWriteExpr = false;
2334
-
2335
- for (var i = 0; i < ref.references.length; i++) {
2336
- var reference = ref.references[i];
2337
-
2338
- if (reference.writeExpr) {
2339
- if (foundWriteExpr) {
2340
- // Two writes to the same function.
2341
- return true;
2342
- } else {
2343
- // Ignore first write as it's not usage.
2344
- foundWriteExpr = true;
2345
- continue;
2346
- }
2347
- }
2348
-
2349
- var currentScope = reference.from;
2350
-
2351
- while (currentScope !== scope && currentScope != null) {
2352
- currentScope = currentScope.upper;
2353
- }
2354
-
2355
- if (currentScope !== scope) {
2356
- // This reference is outside the Hook callback.
2357
- // It can only be legit if it's the deps array.
2358
- if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) {
2359
- return true;
2360
- }
2361
- }
2362
- }
2363
-
2364
- return false;
2365
- }
2366
-
2367
- return constructions.map(function (_ref11) {
2368
- var ref = _ref11[0],
2369
- depType = _ref11[1];
2370
- return {
2371
- construction: ref.defs[0],
2372
- depType: depType,
2373
- isUsedOutsideOfHook: isUsedOutsideOfHook(ref)
2374
2037
  };
2375
- });
2376
- }
2377
- /**
2378
- * Assuming () means the passed/returned node:
2379
- * (props) => (props)
2380
- * props.(foo) => (props.foo)
2381
- * props.foo.(bar) => (props).foo.bar
2382
- * props.foo.bar.(baz) => (props).foo.bar.baz
2383
- */
2384
-
2385
-
2386
- function getDependency(node) {
2387
- if ((node.parent.type === 'MemberExpression' || node.parent.type === 'OptionalMemberExpression') && node.parent.object === node && node.parent.property.name !== 'current' && !node.parent.computed && !(node.parent.parent != null && (node.parent.parent.type === 'CallExpression' || node.parent.parent.type === 'OptionalCallExpression') && node.parent.parent.callee === node.parent)) {
2388
- return getDependency(node.parent);
2389
- } else if ( // Note: we don't check OptionalMemberExpression because it can't be LHS.
2390
- node.type === 'MemberExpression' && node.parent && node.parent.type === 'AssignmentExpression' && node.parent.left === node) {
2391
- return node.object;
2392
- } else {
2393
- return node;
2394
- }
2395
- }
2396
- /**
2397
- * Mark a node as either optional or required.
2398
- * Note: If the node argument is an OptionalMemberExpression, it doesn't necessarily mean it is optional.
2399
- * It just means there is an optional member somewhere inside.
2400
- * This particular node might still represent a required member, so check .optional field.
2401
- */
2402
-
2403
-
2404
- function markNode(node, optionalChains, result) {
2405
- if (optionalChains) {
2406
- if (node.optional) {
2407
- // We only want to consider it optional if *all* usages were optional.
2408
- if (!optionalChains.has(result)) {
2409
- // Mark as (maybe) optional. If there's a required usage, this will be overridden.
2410
- optionalChains.set(result, true);
2411
- }
2412
- } else {
2413
- // Mark as required.
2414
- optionalChains.set(result, false);
2415
- }
2416
- }
2417
- }
2418
- /**
2419
- * Assuming () means the passed node.
2420
- * (foo) -> 'foo'
2421
- * foo(.)bar -> 'foo.bar'
2422
- * foo.bar(.)baz -> 'foo.bar.baz'
2423
- * Otherwise throw.
2424
- */
2425
-
2426
-
2427
- function analyzePropertyChain(node, optionalChains) {
2428
- if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {
2429
- var result = node.name;
2430
-
2431
- if (optionalChains) {
2432
- // Mark as required.
2433
- optionalChains.set(result, false);
2434
- }
2435
-
2436
- return result;
2437
- } else if (node.type === 'MemberExpression' && !node.computed) {
2438
- var object = analyzePropertyChain(node.object, optionalChains);
2439
- var property = analyzePropertyChain(node.property, null);
2440
-
2441
- var _result = object + "." + property;
2442
-
2443
- markNode(node, optionalChains, _result);
2444
- return _result;
2445
- } else if (node.type === 'OptionalMemberExpression' && !node.computed) {
2446
- var _object = analyzePropertyChain(node.object, optionalChains);
2447
-
2448
- var _property = analyzePropertyChain(node.property, null);
2449
-
2450
- var _result2 = _object + "." + _property;
2451
-
2452
- markNode(node, optionalChains, _result2);
2453
- return _result2;
2454
- } else if (node.type === 'ChainExpression' && !node.computed) {
2455
- var expression = node.expression;
2456
-
2457
- if (expression.type === 'CallExpression') {
2458
- throw new Error("Unsupported node type: " + expression.type);
2459
- }
2460
-
2461
- var _object2 = analyzePropertyChain(expression.object, optionalChains);
2462
-
2463
- var _property2 = analyzePropertyChain(expression.property, null);
2464
-
2465
- var _result3 = _object2 + "." + _property2;
2466
-
2467
- markNode(expression, optionalChains, _result3);
2468
- return _result3;
2469
- } else {
2470
- throw new Error("Unsupported node type: " + node.type);
2471
- }
2472
- }
2473
-
2474
- function getNodeWithoutReactNamespace(node, options) {
2475
- if (node.type === 'MemberExpression' && node.object.type === 'Identifier' && node.object.name === 'React' && node.property.type === 'Identifier' && !node.computed) {
2476
- return node.property;
2477
- }
2478
-
2479
- return node;
2480
- } // What's the index of callback that needs to be analyzed for a given Hook?
2481
- // -1 if it's not a Hook we care about (e.g. useState).
2482
- // 0 for useEffect/useMemo/useCallback(fn).
2483
- // 1 for useImperativeHandle(ref, fn).
2484
- // For additionally configured Hooks, assume that they're like useEffect (0).
2485
-
2486
-
2487
- function getReactiveHookCallbackIndex(calleeNode, options) {
2488
- var node = getNodeWithoutReactNamespace(calleeNode);
2489
-
2490
- if (node.type !== 'Identifier') {
2491
- return -1;
2492
- }
2493
-
2494
- switch (node.name) {
2495
- case 'useEffect':
2496
- case 'useLayoutEffect':
2497
- case 'useCallback':
2498
- case 'useMemo':
2499
- // useEffect(fn)
2500
- return 0;
2501
-
2502
- case 'useImperativeHandle':
2503
- // useImperativeHandle(ref, fn)
2504
- return 1;
2505
-
2506
- default:
2507
- if (node === calleeNode && options && options.additionalHooks) {
2508
- // Allow the user to provide a regular expression which enables the lint to
2509
- // target custom reactive hooks.
2510
- var name;
2511
-
2512
- try {
2513
- name = analyzePropertyChain(node, null);
2514
- } catch (error) {
2515
- if (/Unsupported node type/.test(error.message)) {
2516
- return 0;
2517
- } else {
2518
- throw error;
2519
- }
2520
- }
2521
-
2522
- return options.additionalHooks.test(name) ? 0 : -1;
2523
- } else {
2524
- return -1;
2525
- }
2526
-
2527
- }
2528
- }
2529
- /**
2530
- * ESLint won't assign node.parent to references from context.getScope()
2531
- *
2532
- * So instead we search for the node from an ancestor assigning node.parent
2533
- * as we go. This mutates the AST.
2534
- *
2535
- * This traversal is:
2536
- * - optimized by only searching nodes with a range surrounding our target node
2537
- * - agnostic to AST node types, it looks for `{ type: string, ... }`
2538
- */
2539
-
2540
-
2541
- function fastFindReferenceWithParent(start, target) {
2542
- var queue = [start];
2543
- var item = null;
2544
-
2545
- while (queue.length) {
2546
- item = queue.shift();
2547
-
2548
- if (isSameIdentifier(item, target)) {
2549
- return item;
2550
- }
2551
-
2552
- if (!isAncestorNodeOf(item, target)) {
2553
- continue;
2554
- }
2555
-
2556
- for (var _i4 = 0, _Object$entries = Object.entries(item); _i4 < _Object$entries.length; _i4++) {
2557
- var _Object$entries$_i = _Object$entries[_i4],
2558
- key = _Object$entries$_i[0],
2559
- value = _Object$entries$_i[1];
2560
-
2561
- if (key === 'parent') {
2562
- continue;
2563
- }
2564
-
2565
- if (isNodeLike(value)) {
2566
- value.parent = item;
2567
- queue.push(value);
2568
- } else if (Array.isArray(value)) {
2569
- value.forEach(function (val) {
2570
- if (isNodeLike(val)) {
2571
- val.parent = item;
2572
- queue.push(val);
2573
- }
2574
- });
2575
- }
2576
- }
2577
- }
2578
-
2579
- return null;
2580
- }
2581
-
2582
- function joinEnglish(arr) {
2583
- var s = '';
2584
-
2585
- for (var i = 0; i < arr.length; i++) {
2586
- s += arr[i];
2587
-
2588
- if (i === 0 && arr.length === 2) {
2589
- s += ' and ';
2590
- } else if (i === arr.length - 2 && arr.length > 2) {
2591
- s += ', and ';
2592
- } else if (i < arr.length - 1) {
2593
- s += ', ';
2594
- }
2595
- }
2596
-
2597
- return s;
2598
- }
2599
-
2600
- function isNodeLike(val) {
2601
- return typeof val === 'object' && val !== null && !Array.isArray(val) && typeof val.type === 'string';
2602
- }
2603
-
2604
- function isSameIdentifier(a, b) {
2605
- return (a.type === 'Identifier' || a.type === 'JSXIdentifier') && a.type === b.type && a.name === b.name && a.range[0] === b.range[0] && a.range[1] === b.range[1];
2606
- }
2607
-
2608
- function isAncestorNodeOf(a, b) {
2609
- return a.range[0] <= b.range[0] && a.range[1] >= b.range[1];
2610
- }
2611
-
2612
- function isUseEffectEventIdentifier(node) {
2613
-
2614
- return false;
2615
- }
2616
-
2617
- var configs = {
2618
- recommended: {
2619
- plugins: ['react-hooks'],
2620
- rules: {
2621
- 'react-hooks/rules-of-hooks': 'error',
2622
- 'react-hooks/exhaustive-deps': 'warn'
2623
- }
2624
- }
2625
- };
2626
- var rules = {
2627
- 'rules-of-hooks': RulesOfHooks,
2628
- 'exhaustive-deps': ExhaustiveDeps
2629
- };
2630
-
2631
- exports.configs = configs;
2632
- exports.rules = rules;
2633
2038
  })();
2634
- }