eslint-plugin-react-x 5.30.0-beta.2 → 5.30.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1171 -106
- package/package.json +7 -7
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DEFAULT_ESLINT_REACT_SETTINGS, getSettingsFromContext, toRegExp } from "@eslint-react/shared";
|
|
2
2
|
import * as ESLintUtils from "@typescript-eslint/utils/eslint-utils";
|
|
3
|
-
import { Check, Collect, Compare, Extract, Traverse } from "@eslint-react/ast";
|
|
3
|
+
import { Analyze, Check, Collect, Compare, Extract, Traverse } from "@eslint-react/ast";
|
|
4
4
|
import * as core from "@eslint-react/core";
|
|
5
5
|
import { getConstrainedTypeAtLocation, getText, merge, report } from "@eslint-react/eslint";
|
|
6
6
|
import { AST_NODE_TYPES } from "@typescript-eslint/types";
|
|
@@ -112,7 +112,8 @@ const rules$7 = {
|
|
|
112
112
|
"react-x/no-unused-state": "off",
|
|
113
113
|
"react-x/refs": "off",
|
|
114
114
|
"react-x/set-state-in-render": "off",
|
|
115
|
-
"react-x/static-components": "off"
|
|
115
|
+
"react-x/static-components": "off",
|
|
116
|
+
"react-x/unstable-exhaustive-deps": "off"
|
|
116
117
|
};
|
|
117
118
|
// src/configs/disable-type-checked.ts
|
|
118
119
|
var disable_type_checked_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -129,7 +130,7 @@ const rules$6 = {
|
|
|
129
130
|
};
|
|
130
131
|
// package.json
|
|
131
132
|
var name$6 = "eslint-plugin-react-x";
|
|
132
|
-
var version = "5.30.0-beta.
|
|
133
|
+
var version = "5.30.0-beta.4";
|
|
133
134
|
// src/utils/create-rule.ts
|
|
134
135
|
function getDocsUrl(ruleName) {
|
|
135
136
|
return `https://eslint-react.xyz/docs/rules/${ruleName}`;
|
|
@@ -191,7 +192,7 @@ function create$50(context) {
|
|
|
191
192
|
});
|
|
192
193
|
}
|
|
193
194
|
// src/rules/exhaustive-deps/exhaustive-deps.ts
|
|
194
|
-
const rule$
|
|
195
|
+
const rule$2 = {
|
|
195
196
|
meta: {
|
|
196
197
|
type: "suggestion",
|
|
197
198
|
docs: {
|
|
@@ -287,7 +288,7 @@ const rule$1 = {
|
|
|
287
288
|
while (init.type === "TSAsExpression" || init.type === "AsExpression") init = init.expression;
|
|
288
289
|
let declaration = defNode.parent;
|
|
289
290
|
if (declaration == null && componentScope != null) {
|
|
290
|
-
fastFindReferenceWithParent(componentScope.block, def.node.id);
|
|
291
|
+
fastFindReferenceWithParent$1(componentScope.block, def.node.id);
|
|
291
292
|
declaration = def.node.parent;
|
|
292
293
|
if (declaration == null) return false;
|
|
293
294
|
}
|
|
@@ -299,7 +300,7 @@ const rule$1 = {
|
|
|
299
300
|
const id = def.node.id;
|
|
300
301
|
const { name } = callee;
|
|
301
302
|
if (name === "useRef" && id.type === "Identifier") return true;
|
|
302
|
-
else if (isUseEffectEventIdentifier$
|
|
303
|
+
else if (isUseEffectEventIdentifier$2(callee) && id.type === "Identifier") {
|
|
303
304
|
for (const ref of resolved.references) if (ref !== id) useEffectEventVariables.add(ref.identifier);
|
|
304
305
|
return true;
|
|
305
306
|
} else if (name === "useState" || name === "useReducer" || name === "useActionState") {
|
|
@@ -371,10 +372,10 @@ const rule$1 = {
|
|
|
371
372
|
for (const reference of currentScope.references) {
|
|
372
373
|
if (!reference.resolved) continue;
|
|
373
374
|
if (!pureScopes.has(reference.resolved.scope)) continue;
|
|
374
|
-
const referenceNode = fastFindReferenceWithParent(node, reference.identifier);
|
|
375
|
+
const referenceNode = fastFindReferenceWithParent$1(node, reference.identifier);
|
|
375
376
|
if (referenceNode == null) continue;
|
|
376
|
-
const dependencyNode = getDependency(referenceNode);
|
|
377
|
-
const dependency = analyzePropertyChain(dependencyNode, optionalChains);
|
|
377
|
+
const dependencyNode = getDependency$1(referenceNode);
|
|
378
|
+
const dependency = analyzePropertyChain$1(dependencyNode, optionalChains);
|
|
378
379
|
if (isEffect && dependencyNode.type === "Identifier" && (dependencyNode.parent?.type === "MemberExpression" || dependencyNode.parent?.type === "OptionalMemberExpression") && !dependencyNode.parent.computed && dependencyNode.parent.property.type === "Identifier" && dependencyNode.parent.property.name === "current" && isInsideEffectCleanup(reference)) currentRefsInEffectCleanup.set(dependency, {
|
|
379
380
|
reference,
|
|
380
381
|
dependencyNode
|
|
@@ -444,7 +445,7 @@ const rule$1 = {
|
|
|
444
445
|
});
|
|
445
446
|
});
|
|
446
447
|
if (setStateInsideEffectWithoutDeps) {
|
|
447
|
-
const { suggestedDependencies } = collectRecommendations({
|
|
448
|
+
const { suggestedDependencies } = collectRecommendations$1({
|
|
448
449
|
dependencies,
|
|
449
450
|
declaredDependencies: [],
|
|
450
451
|
stableDependencies,
|
|
@@ -494,7 +495,7 @@ const rule$1 = {
|
|
|
494
495
|
});
|
|
495
496
|
let declaredDependency;
|
|
496
497
|
try {
|
|
497
|
-
declaredDependency = analyzePropertyChain(declaredDependencyNode, null);
|
|
498
|
+
declaredDependency = analyzePropertyChain$1(declaredDependencyNode, null);
|
|
498
499
|
} catch (error) {
|
|
499
500
|
if (error instanceof Error && /Unsupported node type/.test(error.message)) {
|
|
500
501
|
if (declaredDependencyNode.type === "Literal") {
|
|
@@ -522,7 +523,7 @@ const rule$1 = {
|
|
|
522
523
|
});
|
|
523
524
|
if (!isDeclaredInComponent) externalDependencies.add(declaredDependency);
|
|
524
525
|
});
|
|
525
|
-
const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies } = collectRecommendations({
|
|
526
|
+
const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies } = collectRecommendations$1({
|
|
526
527
|
dependencies,
|
|
527
528
|
declaredDependencies,
|
|
528
529
|
stableDependencies,
|
|
@@ -531,7 +532,7 @@ const rule$1 = {
|
|
|
531
532
|
});
|
|
532
533
|
let suggestedDeps = suggestedDependencies;
|
|
533
534
|
if (duplicateDependencies.size + missingDependencies.size + unnecessaryDependencies.size === 0) {
|
|
534
|
-
scanForConstructions({
|
|
535
|
+
scanForConstructions$1({
|
|
535
536
|
declaredDependencies,
|
|
536
537
|
declaredDependenciesNode,
|
|
537
538
|
componentScope,
|
|
@@ -559,7 +560,7 @@ const rule$1 = {
|
|
|
559
560
|
});
|
|
560
561
|
return;
|
|
561
562
|
}
|
|
562
|
-
if (!isEffect && missingDependencies.size > 0) suggestedDeps = collectRecommendations({
|
|
563
|
+
if (!isEffect && missingDependencies.size > 0) suggestedDeps = collectRecommendations$1({
|
|
563
564
|
dependencies,
|
|
564
565
|
declaredDependencies: [],
|
|
565
566
|
stableDependencies,
|
|
@@ -588,7 +589,7 @@ const rule$1 = {
|
|
|
588
589
|
}
|
|
589
590
|
function getWarningMessage(deps, singlePrefix, label, fixVerb) {
|
|
590
591
|
if (deps.size === 0) return null;
|
|
591
|
-
return (deps.size > 1 ? "" : singlePrefix + " ") + label + " " + (deps.size > 1 ? "dependencies" : "dependency") + ": " + joinEnglish(Array.from(deps).sort().map((name) => "'" + formatDependency(name) + "'")) + `. Either ${fixVerb} ${deps.size > 1 ? "them" : "it"} or remove the dependency array.`;
|
|
592
|
+
return (deps.size > 1 ? "" : singlePrefix + " ") + label + " " + (deps.size > 1 ? "dependencies" : "dependency") + ": " + joinEnglish$1(Array.from(deps).sort().map((name) => "'" + formatDependency(name) + "'")) + `. Either ${fixVerb} ${deps.size > 1 ? "them" : "it"} or remove the dependency array.`;
|
|
592
593
|
}
|
|
593
594
|
let extraWarning = "";
|
|
594
595
|
if (unnecessaryDependencies.size > 0) {
|
|
@@ -610,7 +611,7 @@ const rule$1 = {
|
|
|
610
611
|
if (!Array.isArray(refs)) return;
|
|
611
612
|
let isPropsOnlyUsedInMembers = true;
|
|
612
613
|
for (const ref of refs) {
|
|
613
|
-
const id = fastFindReferenceWithParent(componentScope.block, ref.identifier);
|
|
614
|
+
const id = fastFindReferenceWithParent$1(componentScope.block, ref.identifier);
|
|
614
615
|
if (!id) {
|
|
615
616
|
isPropsOnlyUsedInMembers = false;
|
|
616
617
|
break;
|
|
@@ -718,11 +719,11 @@ const rule$1 = {
|
|
|
718
719
|
});
|
|
719
720
|
}
|
|
720
721
|
function visitCallExpression(node) {
|
|
721
|
-
const callbackIndex = getReactiveHookCallbackIndex(node.callee, options);
|
|
722
|
+
const callbackIndex = getReactiveHookCallbackIndex$1(node.callee, options);
|
|
722
723
|
if (callbackIndex === -1) return;
|
|
723
724
|
let callback = node.arguments[callbackIndex];
|
|
724
725
|
const reactiveHook = node.callee;
|
|
725
|
-
const nodeWithoutNamespace = getNodeWithoutReactNamespace$
|
|
726
|
+
const nodeWithoutNamespace = getNodeWithoutReactNamespace$2(reactiveHook);
|
|
726
727
|
const reactiveHookName = "name" in nodeWithoutNamespace ? nodeWithoutNamespace.name : "";
|
|
727
728
|
const maybeNode = node.arguments[callbackIndex + 1];
|
|
728
729
|
const declaredDependenciesNode = maybeNode && !(maybeNode.type === "Identifier" && maybeNode.name === "undefined") ? maybeNode : void 0;
|
|
@@ -762,7 +763,7 @@ const rule$1 = {
|
|
|
762
763
|
if (def.type === "Parameter") {
|
|
763
764
|
reportProblem({
|
|
764
765
|
node: reactiveHook,
|
|
765
|
-
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
766
|
+
message: getUnknownDependenciesMessage$1(reactiveHookName)
|
|
766
767
|
});
|
|
767
768
|
return;
|
|
768
769
|
}
|
|
@@ -785,7 +786,7 @@ const rule$1 = {
|
|
|
785
786
|
default:
|
|
786
787
|
reportProblem({
|
|
787
788
|
node: reactiveHook,
|
|
788
|
-
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
789
|
+
message: getUnknownDependenciesMessage$1(reactiveHookName)
|
|
789
790
|
});
|
|
790
791
|
return;
|
|
791
792
|
}
|
|
@@ -803,7 +804,7 @@ const rule$1 = {
|
|
|
803
804
|
return { CallExpression: visitCallExpression };
|
|
804
805
|
}
|
|
805
806
|
};
|
|
806
|
-
function collectRecommendations({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect }) {
|
|
807
|
+
function collectRecommendations$1({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect }) {
|
|
807
808
|
const depTree = createDepTree();
|
|
808
809
|
function createDepTree() {
|
|
809
810
|
return {
|
|
@@ -889,7 +890,7 @@ function collectRecommendations({ dependencies, declaredDependencies, stableDepe
|
|
|
889
890
|
missingDependencies
|
|
890
891
|
};
|
|
891
892
|
}
|
|
892
|
-
function getConstructionExpressionType(node) {
|
|
893
|
+
function getConstructionExpressionType$1(node) {
|
|
893
894
|
switch (node.type) {
|
|
894
895
|
case "ObjectExpression": return "object";
|
|
895
896
|
case "ArrayExpression": return "array";
|
|
@@ -897,15 +898,15 @@ function getConstructionExpressionType(node) {
|
|
|
897
898
|
case "FunctionExpression": return "function";
|
|
898
899
|
case "ClassExpression": return "class";
|
|
899
900
|
case "ConditionalExpression":
|
|
900
|
-
if (getConstructionExpressionType(node.consequent) != null || getConstructionExpressionType(node.alternate) != null) return "conditional";
|
|
901
|
+
if (getConstructionExpressionType$1(node.consequent) != null || getConstructionExpressionType$1(node.alternate) != null) return "conditional";
|
|
901
902
|
return null;
|
|
902
903
|
case "LogicalExpression":
|
|
903
|
-
if (getConstructionExpressionType(node.left) != null || getConstructionExpressionType(node.right) != null) return "logical expression";
|
|
904
|
+
if (getConstructionExpressionType$1(node.left) != null || getConstructionExpressionType$1(node.right) != null) return "logical expression";
|
|
904
905
|
return null;
|
|
905
906
|
case "JSXFragment": return "JSX fragment";
|
|
906
907
|
case "JSXElement": return "JSX element";
|
|
907
908
|
case "AssignmentExpression":
|
|
908
|
-
if (getConstructionExpressionType(node.right) != null) return "assignment expression";
|
|
909
|
+
if (getConstructionExpressionType$1(node.right) != null) return "assignment expression";
|
|
909
910
|
return null;
|
|
910
911
|
case "NewExpression": return "object construction";
|
|
911
912
|
case "Literal":
|
|
@@ -913,18 +914,18 @@ function getConstructionExpressionType(node) {
|
|
|
913
914
|
return null;
|
|
914
915
|
case "TypeCastExpression":
|
|
915
916
|
case "AsExpression":
|
|
916
|
-
case "TSAsExpression": return getConstructionExpressionType(node.expression);
|
|
917
|
+
case "TSAsExpression": return getConstructionExpressionType$1(node.expression);
|
|
917
918
|
}
|
|
918
919
|
return null;
|
|
919
920
|
}
|
|
920
|
-
function scanForConstructions({ declaredDependencies, declaredDependenciesNode, componentScope, scope }) {
|
|
921
|
+
function scanForConstructions$1({ declaredDependencies, declaredDependenciesNode, componentScope, scope }) {
|
|
921
922
|
const constructions = declaredDependencies.map(({ key }) => {
|
|
922
923
|
const ref = componentScope.variables.find((v) => v.name === key);
|
|
923
924
|
if (ref == null) return null;
|
|
924
925
|
const node = ref.defs[0];
|
|
925
926
|
if (node == null) return null;
|
|
926
927
|
if (node.type === "Variable" && node.node.type === "VariableDeclarator" && node.node.id.type === "Identifier" && node.node.init != null) {
|
|
927
|
-
const constantExpressionType = getConstructionExpressionType(node.node.init);
|
|
928
|
+
const constantExpressionType = getConstructionExpressionType$1(node.node.init);
|
|
928
929
|
if (constantExpressionType) return [ref, constantExpressionType];
|
|
929
930
|
}
|
|
930
931
|
if (node.type === "FunctionName" && node.node.type === "FunctionDeclaration") return [ref, "function"];
|
|
@@ -944,7 +945,7 @@ function scanForConstructions({ declaredDependencies, declaredDependenciesNode,
|
|
|
944
945
|
let currentScope = reference.from;
|
|
945
946
|
while (currentScope !== scope && currentScope != null) currentScope = currentScope.upper;
|
|
946
947
|
if (currentScope !== scope) {
|
|
947
|
-
if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) return true;
|
|
948
|
+
if (!isAncestorNodeOf$1(declaredDependenciesNode, reference.identifier)) return true;
|
|
948
949
|
}
|
|
949
950
|
}
|
|
950
951
|
return false;
|
|
@@ -955,45 +956,45 @@ function scanForConstructions({ declaredDependencies, declaredDependenciesNode,
|
|
|
955
956
|
isUsedOutsideOfHook: isUsedOutsideOfHook(ref)
|
|
956
957
|
}));
|
|
957
958
|
}
|
|
958
|
-
function getDependency(node) {
|
|
959
|
-
if (node.parent && (node.parent.type === "MemberExpression" || node.parent.type === "OptionalMemberExpression") && node.parent.object === node && "name" in node.parent.property && 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)) return getDependency(node.parent);
|
|
959
|
+
function getDependency$1(node) {
|
|
960
|
+
if (node.parent && (node.parent.type === "MemberExpression" || node.parent.type === "OptionalMemberExpression") && node.parent.object === node && "name" in node.parent.property && 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)) return getDependency$1(node.parent);
|
|
960
961
|
else if (node.type === "MemberExpression" && node.parent && node.parent.type === "AssignmentExpression" && node.parent.left === node) return node.object;
|
|
961
962
|
else return node;
|
|
962
963
|
}
|
|
963
|
-
function markNode(node, optionalChains, result) {
|
|
964
|
+
function markNode$1(node, optionalChains, result) {
|
|
964
965
|
if (optionalChains) {
|
|
965
966
|
if ("optional" in node && node.optional) {
|
|
966
967
|
if (!optionalChains.has(result)) optionalChains.set(result, true);
|
|
967
968
|
} else optionalChains.set(result, false);
|
|
968
969
|
}
|
|
969
970
|
}
|
|
970
|
-
function analyzePropertyChain(node, optionalChains) {
|
|
971
|
+
function analyzePropertyChain$1(node, optionalChains) {
|
|
971
972
|
if (node.type === "Identifier" || node.type === "JSXIdentifier") {
|
|
972
973
|
const result = node.name;
|
|
973
974
|
if (optionalChains) optionalChains.set(result, false);
|
|
974
975
|
return result;
|
|
975
976
|
} else if (node.type === "MemberExpression" && !node.computed) {
|
|
976
|
-
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
977
|
-
markNode(node, optionalChains, result);
|
|
977
|
+
const result = `${analyzePropertyChain$1(node.object, optionalChains)}.${analyzePropertyChain$1(node.property, null)}`;
|
|
978
|
+
markNode$1(node, optionalChains, result);
|
|
978
979
|
return result;
|
|
979
980
|
} else if (node.type === "OptionalMemberExpression" && !node.computed) {
|
|
980
|
-
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
981
|
-
markNode(node, optionalChains, result);
|
|
981
|
+
const result = `${analyzePropertyChain$1(node.object, optionalChains)}.${analyzePropertyChain$1(node.property, null)}`;
|
|
982
|
+
markNode$1(node, optionalChains, result);
|
|
982
983
|
return result;
|
|
983
984
|
} else if (node.type === "ChainExpression" && (!("computed" in node) || !node.computed)) {
|
|
984
985
|
const expression = node.expression;
|
|
985
986
|
if (expression.type === "CallExpression") throw new Error(`Unsupported node type: ${expression.type}`);
|
|
986
|
-
const result = `${analyzePropertyChain(expression.object, optionalChains)}.${analyzePropertyChain(expression.property, null)}`;
|
|
987
|
-
markNode(expression, optionalChains, result);
|
|
987
|
+
const result = `${analyzePropertyChain$1(expression.object, optionalChains)}.${analyzePropertyChain$1(expression.property, null)}`;
|
|
988
|
+
markNode$1(expression, optionalChains, result);
|
|
988
989
|
return result;
|
|
989
990
|
} else throw new Error(`Unsupported node type: ${node.type}`);
|
|
990
991
|
}
|
|
991
|
-
function getNodeWithoutReactNamespace$
|
|
992
|
+
function getNodeWithoutReactNamespace$2(node) {
|
|
992
993
|
if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "React" && node.property.type === "Identifier" && !node.computed) return node.property;
|
|
993
994
|
return node;
|
|
994
995
|
}
|
|
995
|
-
function getReactiveHookCallbackIndex(calleeNode, options) {
|
|
996
|
-
const node = getNodeWithoutReactNamespace$
|
|
996
|
+
function getReactiveHookCallbackIndex$1(calleeNode, options) {
|
|
997
|
+
const node = getNodeWithoutReactNamespace$2(calleeNode);
|
|
997
998
|
if (node.type !== "Identifier") return -1;
|
|
998
999
|
switch (node.name) {
|
|
999
1000
|
case "useEffect":
|
|
@@ -1004,7 +1005,7 @@ function getReactiveHookCallbackIndex(calleeNode, options) {
|
|
|
1004
1005
|
default: if (node === calleeNode && options && options.additionalHooks) {
|
|
1005
1006
|
let name;
|
|
1006
1007
|
try {
|
|
1007
|
-
name = analyzePropertyChain(node, null);
|
|
1008
|
+
name = analyzePropertyChain$1(node, null);
|
|
1008
1009
|
} catch (error) {
|
|
1009
1010
|
if (error instanceof Error && /Unsupported node type/.test(error.message)) return 0;
|
|
1010
1011
|
else throw error;
|
|
@@ -1013,20 +1014,20 @@ function getReactiveHookCallbackIndex(calleeNode, options) {
|
|
|
1013
1014
|
} else return -1;
|
|
1014
1015
|
}
|
|
1015
1016
|
}
|
|
1016
|
-
function fastFindReferenceWithParent(start, target) {
|
|
1017
|
+
function fastFindReferenceWithParent$1(start, target) {
|
|
1017
1018
|
const queue = [start];
|
|
1018
1019
|
let item;
|
|
1019
1020
|
while (queue.length) {
|
|
1020
1021
|
item = queue.shift();
|
|
1021
|
-
if (isSameIdentifier(item, target)) return item;
|
|
1022
|
-
if (!isAncestorNodeOf(item, target)) continue;
|
|
1022
|
+
if (isSameIdentifier$1(item, target)) return item;
|
|
1023
|
+
if (!isAncestorNodeOf$1(item, target)) continue;
|
|
1023
1024
|
for (const [key, value] of Object.entries(item)) {
|
|
1024
1025
|
if (key === "parent") continue;
|
|
1025
|
-
if (isNodeLike(value)) {
|
|
1026
|
+
if (isNodeLike$1(value)) {
|
|
1026
1027
|
value.parent = item;
|
|
1027
1028
|
queue.push(value);
|
|
1028
1029
|
} else if (Array.isArray(value)) value.forEach((val) => {
|
|
1029
|
-
if (isNodeLike(val)) {
|
|
1030
|
+
if (isNodeLike$1(val)) {
|
|
1030
1031
|
val.parent = item;
|
|
1031
1032
|
queue.push(val);
|
|
1032
1033
|
}
|
|
@@ -1035,7 +1036,7 @@ function fastFindReferenceWithParent(start, target) {
|
|
|
1035
1036
|
}
|
|
1036
1037
|
return null;
|
|
1037
1038
|
}
|
|
1038
|
-
function joinEnglish(arr) {
|
|
1039
|
+
function joinEnglish$1(arr) {
|
|
1039
1040
|
let s = "";
|
|
1040
1041
|
for (let i = 0; i < arr.length; i++) {
|
|
1041
1042
|
s += arr[i];
|
|
@@ -1045,19 +1046,19 @@ function joinEnglish(arr) {
|
|
|
1045
1046
|
}
|
|
1046
1047
|
return s;
|
|
1047
1048
|
}
|
|
1048
|
-
function isNodeLike(val) {
|
|
1049
|
+
function isNodeLike$1(val) {
|
|
1049
1050
|
return typeof val === "object" && val !== null && !Array.isArray(val) && "type" in val && typeof val.type === "string";
|
|
1050
1051
|
}
|
|
1051
|
-
function isSameIdentifier(a, b) {
|
|
1052
|
+
function isSameIdentifier$1(a, b) {
|
|
1052
1053
|
return (a.type === "Identifier" || a.type === "JSXIdentifier") && a.type === b.type && a.name === b.name && !!a.range && !!b.range && a.range[0] === b.range[0] && a.range[1] === b.range[1];
|
|
1053
1054
|
}
|
|
1054
|
-
function isAncestorNodeOf(a, b) {
|
|
1055
|
+
function isAncestorNodeOf$1(a, b) {
|
|
1055
1056
|
return !!a.range && !!b.range && a.range[0] <= b.range[0] && a.range[1] >= b.range[1];
|
|
1056
1057
|
}
|
|
1057
|
-
function isUseEffectEventIdentifier$
|
|
1058
|
+
function isUseEffectEventIdentifier$2(node) {
|
|
1058
1059
|
return node.type === "Identifier" && node.name === "useEffectEvent";
|
|
1059
1060
|
}
|
|
1060
|
-
function getUnknownDependenciesMessage(reactiveHookName) {
|
|
1061
|
+
function getUnknownDependenciesMessage$1(reactiveHookName) {
|
|
1061
1062
|
return `React Hook ${reactiveHookName} received a function whose dependencies are unknown. Pass an inline function instead.`;
|
|
1062
1063
|
}
|
|
1063
1064
|
// src/rules/globals/helpers.ts
|
|
@@ -1996,7 +1997,7 @@ function memoize(f) {
|
|
|
1996
1997
|
function not(predicate) {
|
|
1997
1998
|
return (data) => !predicate(data);
|
|
1998
1999
|
}
|
|
1999
|
-
|
|
2000
|
+
dual(2, (a, b) => (data) => a(data) && b(data));
|
|
2000
2001
|
const or = dual(2, (a, b) => (data) => a(data) || b(data));
|
|
2001
2002
|
dual(2, (a, b) => (data) => a(data) !== b(data));
|
|
2002
2003
|
dual(2, (a, b) => (data) => a(data) === b(data));
|
|
@@ -4291,18 +4292,6 @@ function getGuardDisposition(node, getNullBranch) {
|
|
|
4291
4292
|
}
|
|
4292
4293
|
return null;
|
|
4293
4294
|
}
|
|
4294
|
-
function isUnconditionallyTerminating(statement) {
|
|
4295
|
-
switch (statement.type) {
|
|
4296
|
-
case AST_NODE_TYPES.ReturnStatement:
|
|
4297
|
-
case AST_NODE_TYPES.ThrowStatement: return true;
|
|
4298
|
-
case AST_NODE_TYPES.BlockStatement: {
|
|
4299
|
-
const last = statement.body.at(-1);
|
|
4300
|
-
return last != null && isUnconditionallyTerminating(last);
|
|
4301
|
-
}
|
|
4302
|
-
case AST_NODE_TYPES.IfStatement: return statement.alternate != null && isUnconditionallyTerminating(statement.consequent) && isUnconditionallyTerminating(statement.alternate);
|
|
4303
|
-
default: return false;
|
|
4304
|
-
}
|
|
4305
|
-
}
|
|
4306
4295
|
function isAfterTerminatingNonNullGuard(node, getNullBranch) {
|
|
4307
4296
|
let statement = node;
|
|
4308
4297
|
while (statement.parent?.type !== AST_NODE_TYPES.BlockStatement) {
|
|
@@ -4317,7 +4306,7 @@ function isAfterTerminatingNonNullGuard(node, getNullBranch) {
|
|
|
4317
4306
|
const nullBranch = getNullBranch(sibling.test);
|
|
4318
4307
|
if (nullBranch == null) continue;
|
|
4319
4308
|
const nonNullBranch = nullBranch === "alternate" ? sibling.consequent : sibling.alternate;
|
|
4320
|
-
return nonNullBranch != null && isUnconditionallyTerminating(nonNullBranch);
|
|
4309
|
+
return nonNullBranch != null && Analyze.isUnconditionallyTerminating(nonNullBranch);
|
|
4321
4310
|
}
|
|
4322
4311
|
return false;
|
|
4323
4312
|
}
|
|
@@ -6055,7 +6044,7 @@ function isInsideTryCatch(node) {
|
|
|
6055
6044
|
}
|
|
6056
6045
|
return false;
|
|
6057
6046
|
}
|
|
6058
|
-
function getNodeWithoutReactNamespace(node) {
|
|
6047
|
+
function getNodeWithoutReactNamespace$1(node) {
|
|
6059
6048
|
if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "React" && node.property.type === "Identifier" && !node.computed) return node.property;
|
|
6060
6049
|
return node;
|
|
6061
6050
|
}
|
|
@@ -6064,7 +6053,7 @@ function isEffectIdentifier(node, additionalHooks) {
|
|
|
6064
6053
|
if (additionalHooks && node.type === "Identifier") return additionalHooks.test(node.name);
|
|
6065
6054
|
return false;
|
|
6066
6055
|
}
|
|
6067
|
-
function isUseEffectEventIdentifier(node) {
|
|
6056
|
+
function isUseEffectEventIdentifier$1(node) {
|
|
6068
6057
|
return node.type === "Identifier" && node.name === "useEffectEvent";
|
|
6069
6058
|
}
|
|
6070
6059
|
function useEffectEventError(fn, called) {
|
|
@@ -6074,7 +6063,7 @@ function useEffectEventError(fn, called) {
|
|
|
6074
6063
|
function isUseIdentifier(node) {
|
|
6075
6064
|
return isReactFunction(node, "use");
|
|
6076
6065
|
}
|
|
6077
|
-
const rule = {
|
|
6066
|
+
const rule$1 = {
|
|
6078
6067
|
meta: {
|
|
6079
6068
|
type: "problem",
|
|
6080
6069
|
docs: {
|
|
@@ -6099,7 +6088,7 @@ const rule = {
|
|
|
6099
6088
|
function recordAllUseEffectEventFunctions(scope) {
|
|
6100
6089
|
for (const reference of scope.references) {
|
|
6101
6090
|
const parent = reference.identifier.parent;
|
|
6102
|
-
if (parent?.type === "VariableDeclarator" && parent.init && parent.init.type === "CallExpression" && parent.init.callee && isUseEffectEventIdentifier(parent.init.callee)) {
|
|
6091
|
+
if (parent?.type === "VariableDeclarator" && parent.init && parent.init.type === "CallExpression" && parent.init.callee && isUseEffectEventIdentifier$1(parent.init.callee)) {
|
|
6103
6092
|
if (reference.resolved === null) throw new Error("Unexpected null reference.resolved");
|
|
6104
6093
|
for (const ref of reference.resolved.references) if (ref !== reference) useEffectEventFunctions.add(ref.identifier);
|
|
6105
6094
|
}
|
|
@@ -6278,9 +6267,9 @@ const rule = {
|
|
|
6278
6267
|
}
|
|
6279
6268
|
reactHooks.push(callee);
|
|
6280
6269
|
}
|
|
6281
|
-
const nodeWithoutNamespace = getNodeWithoutReactNamespace(node.callee);
|
|
6282
|
-
if ((isEffectIdentifier(nodeWithoutNamespace, additionalEffectHooks) || isUseEffectEventIdentifier(nodeWithoutNamespace)) && node.arguments.length > 0) lastEffect = node;
|
|
6283
|
-
if (isUseEffectEventIdentifier(nodeWithoutNamespace) && node.parent?.type !== "VariableDeclarator" && node.parent?.type !== "ExpressionStatement") {
|
|
6270
|
+
const nodeWithoutNamespace = getNodeWithoutReactNamespace$1(node.callee);
|
|
6271
|
+
if ((isEffectIdentifier(nodeWithoutNamespace, additionalEffectHooks) || isUseEffectEventIdentifier$1(nodeWithoutNamespace)) && node.arguments.length > 0) lastEffect = node;
|
|
6272
|
+
if (isUseEffectEventIdentifier$1(nodeWithoutNamespace) && node.parent?.type !== "VariableDeclarator" && node.parent?.type !== "ExpressionStatement") {
|
|
6284
6273
|
const message = useEffectEventError(null, false);
|
|
6285
6274
|
context.report({
|
|
6286
6275
|
node,
|
|
@@ -6373,10 +6362,11 @@ function createFactCollector$3(additionalStateHooks, additionalEffectHooks) {
|
|
|
6373
6362
|
};
|
|
6374
6363
|
}
|
|
6375
6364
|
// src/rules/set-state-in-effect/helpers.ts
|
|
6376
|
-
function
|
|
6377
|
-
|
|
6378
|
-
|
|
6379
|
-
return
|
|
6365
|
+
function getImmediateInvocation(fn) {
|
|
6366
|
+
let parent = fn.parent;
|
|
6367
|
+
while (Check.isTypeOrChainExpression(parent)) parent = parent.parent;
|
|
6368
|
+
if (parent.type !== AST_NODE_TYPES.CallExpression) return null;
|
|
6369
|
+
return Extract.unwrap(parent.callee) === fn ? parent : null;
|
|
6380
6370
|
}
|
|
6381
6371
|
function getConditionalBranch(node) {
|
|
6382
6372
|
let child = node;
|
|
@@ -6540,6 +6530,47 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6540
6530
|
}
|
|
6541
6531
|
return refParams;
|
|
6542
6532
|
}
|
|
6533
|
+
function isDeferredInvocation(invocation) {
|
|
6534
|
+
let current = invocation.parent;
|
|
6535
|
+
while (current != null) {
|
|
6536
|
+
if (Check.isFunction(current)) return false;
|
|
6537
|
+
switch (current.type) {
|
|
6538
|
+
case AST_NODE_TYPES.AssignmentPattern: return true;
|
|
6539
|
+
case AST_NODE_TYPES.PropertyDefinition: {
|
|
6540
|
+
if (current.static) return false;
|
|
6541
|
+
const value = current.value;
|
|
6542
|
+
return value != null && (value === invocation || Traverse.hasParent(invocation, (n) => n === value));
|
|
6543
|
+
}
|
|
6544
|
+
default: current = current.parent;
|
|
6545
|
+
}
|
|
6546
|
+
}
|
|
6547
|
+
return false;
|
|
6548
|
+
}
|
|
6549
|
+
function getVisibleWriteLocation(value, id) {
|
|
6550
|
+
let branch = getConditionalBranch(value);
|
|
6551
|
+
let node = value;
|
|
6552
|
+
let order = 1;
|
|
6553
|
+
let boundary = Traverse.findParent(value, Check.isFunction);
|
|
6554
|
+
while (boundary != null) {
|
|
6555
|
+
if (Traverse.hasParent(id, (n) => n === boundary)) return {
|
|
6556
|
+
branch,
|
|
6557
|
+
node,
|
|
6558
|
+
order
|
|
6559
|
+
};
|
|
6560
|
+
if (boundary.async || boundary.generator) return null;
|
|
6561
|
+
const invocation = getImmediateInvocation(boundary);
|
|
6562
|
+
if (invocation == null || isDeferredInvocation(invocation)) return null;
|
|
6563
|
+
branch ??= getConditionalBranch(invocation);
|
|
6564
|
+
node = invocation;
|
|
6565
|
+
order = 0;
|
|
6566
|
+
boundary = Traverse.findParent(invocation, Check.isFunction);
|
|
6567
|
+
}
|
|
6568
|
+
return {
|
|
6569
|
+
branch,
|
|
6570
|
+
node,
|
|
6571
|
+
order
|
|
6572
|
+
};
|
|
6573
|
+
}
|
|
6543
6574
|
function isInitializedFromRef(id, refParams, seen = /* @__PURE__ */ new Set()) {
|
|
6544
6575
|
const variable = findVariable(context.sourceCode.getScope(id), id);
|
|
6545
6576
|
if (variable == null) return false;
|
|
@@ -6548,11 +6579,16 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6548
6579
|
seen.add(key);
|
|
6549
6580
|
if (isStateHeldDomNode(variable)) return true;
|
|
6550
6581
|
const candidates = [];
|
|
6551
|
-
const addCandidate = (value,
|
|
6552
|
-
|
|
6582
|
+
const addCandidate = (value, visibility = {
|
|
6583
|
+
branch: getConditionalBranch(value),
|
|
6584
|
+
node: value,
|
|
6585
|
+
order: 1
|
|
6586
|
+
}, previous) => {
|
|
6587
|
+
if (visibility.node.range[1] > id.range[0] || candidates.some((c) => c.value === value)) return;
|
|
6553
6588
|
candidates.push({
|
|
6554
|
-
branch:
|
|
6555
|
-
|
|
6589
|
+
branch: visibility.branch,
|
|
6590
|
+
order: visibility.order,
|
|
6591
|
+
position: visibility.node.range[1],
|
|
6556
6592
|
previous,
|
|
6557
6593
|
value
|
|
6558
6594
|
});
|
|
@@ -6565,12 +6601,13 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6565
6601
|
if (!reference.isWrite() || reference.writeExpr == null) continue;
|
|
6566
6602
|
if (reference.init === true && variable.defs.some((d) => d.type === DefinitionType.Parameter && refParams?.has(d.name) === true)) continue;
|
|
6567
6603
|
const writeExpr = reference.writeExpr;
|
|
6568
|
-
|
|
6604
|
+
const visibility = getVisibleWriteLocation(writeExpr, id);
|
|
6605
|
+
if (visibility == null) continue;
|
|
6569
6606
|
const parent = reference.identifier.parent;
|
|
6570
|
-
addCandidate(writeExpr, parent.type === AST_NODE_TYPES.AssignmentExpression && parent.operator !== "=" && Extract.unwrap(parent.left) === reference.identifier ? reference.identifier : void 0);
|
|
6607
|
+
addCandidate(writeExpr, visibility, parent.type === AST_NODE_TYPES.AssignmentExpression && parent.operator !== "=" && Extract.unwrap(parent.left) === reference.identifier ? reference.identifier : void 0);
|
|
6571
6608
|
}
|
|
6572
6609
|
const survivingCandidates = [];
|
|
6573
|
-
for (const candidate of [...candidates].sort((a, b) => a.position - b.position)) {
|
|
6610
|
+
for (const candidate of [...candidates].sort((a, b) => a.position - b.position || a.order - b.order)) {
|
|
6574
6611
|
if (candidate.branch == null) survivingCandidates.length = 0;
|
|
6575
6612
|
else {
|
|
6576
6613
|
const previousIndex = survivingCandidates.findIndex((o) => o.branch === candidate.branch);
|
|
@@ -6620,7 +6657,11 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6620
6657
|
case AST_NODE_TYPES.LogicalExpression: return isRefValue(expression.left, refParams, seen, mode) || isRefValue(expression.right, refParams, seen, mode);
|
|
6621
6658
|
case AST_NODE_TYPES.UnaryExpression:
|
|
6622
6659
|
case AST_NODE_TYPES.UpdateExpression: return isRefValue(expression.argument, refParams, seen, mode);
|
|
6623
|
-
case AST_NODE_TYPES.ConditionalExpression: return
|
|
6660
|
+
case AST_NODE_TYPES.ConditionalExpression: return [
|
|
6661
|
+
mode === "initializer" ? expression.test : null,
|
|
6662
|
+
expression.consequent,
|
|
6663
|
+
expression.alternate
|
|
6664
|
+
].some((e) => e != null && isRefValue(e, refParams, seen, mode));
|
|
6624
6665
|
case AST_NODE_TYPES.SequenceExpression: return expression.expressions.some((p) => isRefValue(p, refParams, seen, mode));
|
|
6625
6666
|
case AST_NODE_TYPES.TemplateLiteral: return expression.expressions.some((p) => isRefValue(p, refParams, seen, mode));
|
|
6626
6667
|
case AST_NODE_TYPES.TaggedTemplateExpression: return isRefValue(expression.tag, refParams, seen, mode) || isRefValue(expression.quasi, refParams, seen, mode);
|
|
@@ -6643,6 +6684,29 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6643
6684
|
function isRefInExpression(node, refParams) {
|
|
6644
6685
|
return Collect.getIdentifiers(node).some((id) => isInitializedFromRef(id, refParams));
|
|
6645
6686
|
}
|
|
6687
|
+
function hasRefGatedTerminator(statements, refParams) {
|
|
6688
|
+
return statements.some((statement) => isRefGatedTerminator(statement, refParams));
|
|
6689
|
+
}
|
|
6690
|
+
function isRefGatedTerminator(statement, refParams) {
|
|
6691
|
+
switch (statement.type) {
|
|
6692
|
+
case AST_NODE_TYPES.IfStatement: return isRefInExpression(statement.test, refParams) && (Analyze.isTerminatingStatement(statement.consequent) || statement.alternate != null && Analyze.isTerminatingStatement(statement.alternate));
|
|
6693
|
+
case AST_NODE_TYPES.BlockStatement: return hasRefGatedTerminator(statement.body, refParams);
|
|
6694
|
+
case AST_NODE_TYPES.TryStatement:
|
|
6695
|
+
if (statement.finalizer != null && hasRefGatedTerminator(statement.finalizer.body, refParams)) return true;
|
|
6696
|
+
if (statement.handler != null && !Analyze.isTerminatingStatement(statement.handler.body)) return false;
|
|
6697
|
+
return hasRefGatedTerminator(statement.block.body, refParams);
|
|
6698
|
+
default: return false;
|
|
6699
|
+
}
|
|
6700
|
+
}
|
|
6701
|
+
function hasRefGatedEarlyExit(statements, child, refParams) {
|
|
6702
|
+
const index = statements.findIndex((statement) => statement === child);
|
|
6703
|
+
if (index < 0) return false;
|
|
6704
|
+
for (let i = 0; i < index; i++) {
|
|
6705
|
+
const statement = statements[i];
|
|
6706
|
+
if (statement != null && isRefGatedTerminator(statement, refParams)) return true;
|
|
6707
|
+
}
|
|
6708
|
+
return false;
|
|
6709
|
+
}
|
|
6646
6710
|
function isRefGatedContext(node, refParams) {
|
|
6647
6711
|
let child = node;
|
|
6648
6712
|
let current = node.parent;
|
|
@@ -6656,15 +6720,16 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6656
6720
|
case AST_NODE_TYPES.LogicalExpression:
|
|
6657
6721
|
if (child === current.right && isRefInExpression(current.left, refParams)) return true;
|
|
6658
6722
|
break;
|
|
6659
|
-
case AST_NODE_TYPES.
|
|
6660
|
-
|
|
6661
|
-
for (const statement of current.body.slice(0, Math.max(0, index))) {
|
|
6662
|
-
if (statement.type !== AST_NODE_TYPES.IfStatement) continue;
|
|
6663
|
-
if (!isRefInExpression(statement.test, refParams)) continue;
|
|
6664
|
-
if (isTerminatingStatement(statement.consequent)) return true;
|
|
6665
|
-
}
|
|
6723
|
+
case AST_NODE_TYPES.WhileStatement:
|
|
6724
|
+
if (child === current.body && isRefInExpression(current.test, refParams)) return true;
|
|
6666
6725
|
break;
|
|
6667
|
-
|
|
6726
|
+
case AST_NODE_TYPES.ForStatement:
|
|
6727
|
+
if ((child === current.body || child === current.update) && current.test != null && isRefInExpression(current.test, refParams)) return true;
|
|
6728
|
+
break;
|
|
6729
|
+
case AST_NODE_TYPES.BlockStatement:
|
|
6730
|
+
if (hasRefGatedEarlyExit(current.body, child, refParams)) return true;
|
|
6731
|
+
break;
|
|
6732
|
+
case AST_NODE_TYPES.SwitchCase: if (hasRefGatedEarlyExit(current.consequent, child, refParams)) return true;
|
|
6668
6733
|
}
|
|
6669
6734
|
child = current;
|
|
6670
6735
|
current = current.parent;
|
|
@@ -6703,24 +6768,24 @@ function inferViolations$2(context, facts) {
|
|
|
6703
6768
|
visited.add(key);
|
|
6704
6769
|
queue.push(state);
|
|
6705
6770
|
};
|
|
6706
|
-
const report = (
|
|
6707
|
-
|
|
6708
|
-
|
|
6709
|
-
|
|
6771
|
+
const report = (setter, reportNode) => {
|
|
6772
|
+
const name = resolver.getSetterName(setter.node);
|
|
6773
|
+
const key = `${String(reportNode.range[0])}:${String(reportNode.range[1])}:${name}`;
|
|
6774
|
+
getOrInsertComputed(violations, key, () => ({
|
|
6775
|
+
name,
|
|
6710
6776
|
node: reportNode
|
|
6711
|
-
});
|
|
6777
|
+
}));
|
|
6712
6778
|
};
|
|
6713
6779
|
const isExemptCall = (call, state) => {
|
|
6714
6780
|
if (state.inheritedRefGate || resolver.isRefGatedContext(call, state.refParams)) return true;
|
|
6715
|
-
|
|
6716
|
-
return argument != null && resolver.isArgumentUsingRefValue(argument, state.refParams);
|
|
6781
|
+
return call.arguments.some((argument) => resolver.isArgumentUsingRefValue(argument, state.refParams));
|
|
6717
6782
|
};
|
|
6718
6783
|
for (const root of [...facts.effectRoots].sort((a, b) => a.node.range[0] - b.node.range[0])) {
|
|
6719
6784
|
const setup = root.setup;
|
|
6720
6785
|
const unwrappedSetup = Extract.unwrap(setup);
|
|
6721
6786
|
for (const target of resolver.resolveValues(setup)) {
|
|
6722
6787
|
if (target.kind === "setter") {
|
|
6723
|
-
if (!resolver.isRefGatedContext(setup)) report(target
|
|
6788
|
+
if (!resolver.isRefGatedContext(setup)) report(target, setup);
|
|
6724
6789
|
continue;
|
|
6725
6790
|
}
|
|
6726
6791
|
const reportNode = unwrappedSetup === target.node ? null : setup;
|
|
@@ -6738,7 +6803,7 @@ function inferViolations$2(context, facts) {
|
|
|
6738
6803
|
const calls = callsByFunction.get(state.fn) ?? [];
|
|
6739
6804
|
for (const call of calls) for (const target of resolver.resolveValues(call.callee)) {
|
|
6740
6805
|
if (target.kind === "setter") {
|
|
6741
|
-
if (!isExemptCall(call, state)) report(
|
|
6806
|
+
if (!isExemptCall(call, state)) report(target, state.reportNode ?? call);
|
|
6742
6807
|
continue;
|
|
6743
6808
|
}
|
|
6744
6809
|
enqueue({
|
|
@@ -7070,6 +7135,1005 @@ function create$3(context) {
|
|
|
7070
7135
|
}
|
|
7071
7136
|
} });
|
|
7072
7137
|
}
|
|
7138
|
+
// src/rules/unstable-exhaustive-deps/lib.ts
|
|
7139
|
+
function getHookConfigs(hooks = []) {
|
|
7140
|
+
const reactive = /* @__PURE__ */ new Map();
|
|
7141
|
+
const stable = /* @__PURE__ */ new Map();
|
|
7142
|
+
for (const { name, closureIndex, dependenciesIndex, stableResult } of hooks) {
|
|
7143
|
+
if (closureIndex != null && dependenciesIndex != null && closureIndex !== dependenciesIndex) reactive.set(name, {
|
|
7144
|
+
closureIndex,
|
|
7145
|
+
dependenciesIndex
|
|
7146
|
+
});
|
|
7147
|
+
if (stableResult === true) stable.set(name, true);
|
|
7148
|
+
else if (typeof stableResult === "number") stable.set(name, /* @__PURE__ */ new Set([stableResult]));
|
|
7149
|
+
else if (Array.isArray(stableResult)) stable.set(name, new Set(stableResult));
|
|
7150
|
+
}
|
|
7151
|
+
return {
|
|
7152
|
+
reactive,
|
|
7153
|
+
stable
|
|
7154
|
+
};
|
|
7155
|
+
}
|
|
7156
|
+
function getReactiveHookConfig(node, configs) {
|
|
7157
|
+
if (configs.reactive.size === 0) return null;
|
|
7158
|
+
const name = Extract.getCalleeName(node);
|
|
7159
|
+
if (name == null) return null;
|
|
7160
|
+
const config = configs.reactive.get(name);
|
|
7161
|
+
if (config == null) return null;
|
|
7162
|
+
return {
|
|
7163
|
+
name,
|
|
7164
|
+
...config
|
|
7165
|
+
};
|
|
7166
|
+
}
|
|
7167
|
+
function isConfiguredStableHookValue(variable, configs) {
|
|
7168
|
+
if (configs.stable.size === 0) return false;
|
|
7169
|
+
let matchedNode = null;
|
|
7170
|
+
let stableResult = null;
|
|
7171
|
+
let initializerCount = 0;
|
|
7172
|
+
for (const def of variable.defs) {
|
|
7173
|
+
if (def.type !== DefinitionType.Variable || def.node.init == null) continue;
|
|
7174
|
+
initializerCount++;
|
|
7175
|
+
const init = Extract.unwrap(def.node.init);
|
|
7176
|
+
if (init.type !== AST_NODE_TYPES.CallExpression) continue;
|
|
7177
|
+
const name = Extract.getCalleeName(init);
|
|
7178
|
+
if (name == null) continue;
|
|
7179
|
+
const config = configs.stable.get(name);
|
|
7180
|
+
if (config == null) continue;
|
|
7181
|
+
if (matchedNode != null) return false;
|
|
7182
|
+
matchedNode = def.node;
|
|
7183
|
+
stableResult = config;
|
|
7184
|
+
}
|
|
7185
|
+
if (initializerCount !== 1) return false;
|
|
7186
|
+
if (matchedNode == null || stableResult == null) return false;
|
|
7187
|
+
if (variable.references.some((reference) => reference.isWrite() && reference.init !== true)) return false;
|
|
7188
|
+
const { id } = matchedNode;
|
|
7189
|
+
if (stableResult === true) return id.type === AST_NODE_TYPES.Identifier;
|
|
7190
|
+
if (id.type !== AST_NODE_TYPES.ArrayPattern) return false;
|
|
7191
|
+
const index = id.elements.findIndex((element) => {
|
|
7192
|
+
if (element == null) return false;
|
|
7193
|
+
const binding = element.type === AST_NODE_TYPES.AssignmentPattern ? element.left : element;
|
|
7194
|
+
return variable.identifiers.some((identifier) => identifier === binding);
|
|
7195
|
+
});
|
|
7196
|
+
return index !== -1 && stableResult.has(index);
|
|
7197
|
+
}
|
|
7198
|
+
// src/rules/unstable-exhaustive-deps/unstable-exhaustive-deps.ts
|
|
7199
|
+
const rule = {
|
|
7200
|
+
meta: {
|
|
7201
|
+
type: "suggestion",
|
|
7202
|
+
docs: {
|
|
7203
|
+
description: "Verifies the list of dependencies for Hooks like 'useEffect' and similar, with support for custom Hooks and stable Hook results.",
|
|
7204
|
+
url: "https://eslint-react.xyz/docs/rules/unstable-exhaustive-deps"
|
|
7205
|
+
},
|
|
7206
|
+
fixable: "code",
|
|
7207
|
+
hasSuggestions: true,
|
|
7208
|
+
schema: [{
|
|
7209
|
+
type: "object",
|
|
7210
|
+
additionalProperties: false,
|
|
7211
|
+
enableDangerousAutofixThisMayCauseInfiniteLoops: false,
|
|
7212
|
+
properties: {
|
|
7213
|
+
additionalHooks: { type: "string" },
|
|
7214
|
+
enableDangerousAutofixThisMayCauseInfiniteLoops: { type: "boolean" },
|
|
7215
|
+
experimental_autoDependenciesHooks: {
|
|
7216
|
+
type: "array",
|
|
7217
|
+
items: { type: "string" }
|
|
7218
|
+
},
|
|
7219
|
+
hooks: {
|
|
7220
|
+
type: "array",
|
|
7221
|
+
items: {
|
|
7222
|
+
type: "object",
|
|
7223
|
+
additionalProperties: false,
|
|
7224
|
+
dependencies: {
|
|
7225
|
+
closureIndex: ["dependenciesIndex"],
|
|
7226
|
+
dependenciesIndex: ["closureIndex"]
|
|
7227
|
+
},
|
|
7228
|
+
properties: {
|
|
7229
|
+
name: {
|
|
7230
|
+
type: "string",
|
|
7231
|
+
minLength: 1
|
|
7232
|
+
},
|
|
7233
|
+
closureIndex: {
|
|
7234
|
+
type: "integer",
|
|
7235
|
+
minimum: 0
|
|
7236
|
+
},
|
|
7237
|
+
dependenciesIndex: {
|
|
7238
|
+
type: "integer",
|
|
7239
|
+
minimum: 0
|
|
7240
|
+
},
|
|
7241
|
+
stableResult: { oneOf: [
|
|
7242
|
+
{ type: "boolean" },
|
|
7243
|
+
{
|
|
7244
|
+
type: "integer",
|
|
7245
|
+
minimum: 0
|
|
7246
|
+
},
|
|
7247
|
+
{
|
|
7248
|
+
type: "array",
|
|
7249
|
+
items: {
|
|
7250
|
+
type: "integer",
|
|
7251
|
+
minimum: 0
|
|
7252
|
+
},
|
|
7253
|
+
minItems: 1
|
|
7254
|
+
}
|
|
7255
|
+
] }
|
|
7256
|
+
},
|
|
7257
|
+
required: ["name"]
|
|
7258
|
+
}
|
|
7259
|
+
},
|
|
7260
|
+
requireExplicitEffectDeps: { type: "boolean" }
|
|
7261
|
+
}
|
|
7262
|
+
}]
|
|
7263
|
+
},
|
|
7264
|
+
create(context) {
|
|
7265
|
+
const rawOptions = context.options && context.options[0];
|
|
7266
|
+
const additionalHooks = rawOptions && rawOptions.additionalHooks ? new RegExp(rawOptions.additionalHooks) : getSettingsFromContext(context).additionalEffectHooks;
|
|
7267
|
+
const enableDangerousAutofixThisMayCauseInfiniteLoops = rawOptions && rawOptions.enableDangerousAutofixThisMayCauseInfiniteLoops || false;
|
|
7268
|
+
const experimental_autoDependenciesHooks = rawOptions && Array.isArray(rawOptions.experimental_autoDependenciesHooks) ? rawOptions.experimental_autoDependenciesHooks : [];
|
|
7269
|
+
const requireExplicitEffectDeps = rawOptions && rawOptions.requireExplicitEffectDeps || false;
|
|
7270
|
+
const options = {
|
|
7271
|
+
additionalHooks,
|
|
7272
|
+
experimental_autoDependenciesHooks,
|
|
7273
|
+
enableDangerousAutofixThisMayCauseInfiniteLoops,
|
|
7274
|
+
hooks: getHookConfigs(rawOptions && rawOptions.hooks),
|
|
7275
|
+
requireExplicitEffectDeps
|
|
7276
|
+
};
|
|
7277
|
+
function reportProblem(problem) {
|
|
7278
|
+
if (enableDangerousAutofixThisMayCauseInfiniteLoops) {
|
|
7279
|
+
if (Array.isArray(problem.suggest) && problem.suggest.length > 0 && problem.suggest[0]) problem.fix = problem.suggest[0].fix;
|
|
7280
|
+
}
|
|
7281
|
+
context.report(problem);
|
|
7282
|
+
}
|
|
7283
|
+
const getSourceCode = typeof context.getSourceCode === "function" ? () => {
|
|
7284
|
+
return context.getSourceCode();
|
|
7285
|
+
} : () => {
|
|
7286
|
+
return context.sourceCode;
|
|
7287
|
+
};
|
|
7288
|
+
const getScope = typeof context.getScope === "function" ? () => {
|
|
7289
|
+
return context.getScope();
|
|
7290
|
+
} : (node) => {
|
|
7291
|
+
return context.sourceCode.getScope(node);
|
|
7292
|
+
};
|
|
7293
|
+
const scopeManager = getSourceCode().scopeManager;
|
|
7294
|
+
const setStateCallSites = /* @__PURE__ */ new WeakMap();
|
|
7295
|
+
const stateVariables = /* @__PURE__ */ new WeakSet();
|
|
7296
|
+
const stableKnownValueCache = /* @__PURE__ */ new WeakMap();
|
|
7297
|
+
const functionWithoutCapturedValueCache = /* @__PURE__ */ new WeakMap();
|
|
7298
|
+
const useEffectEventVariables = /* @__PURE__ */ new WeakSet();
|
|
7299
|
+
function memoizeWithWeakMap(fn, map) {
|
|
7300
|
+
return function(arg) {
|
|
7301
|
+
if (map.has(arg)) return map.get(arg);
|
|
7302
|
+
const result = fn(arg);
|
|
7303
|
+
map.set(arg, result);
|
|
7304
|
+
return result;
|
|
7305
|
+
};
|
|
7306
|
+
}
|
|
7307
|
+
function visitFunctionWithDependencies(node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, callExpression, dependenciesIndex) {
|
|
7308
|
+
if (isEffect && node.async) reportProblem({
|
|
7309
|
+
node,
|
|
7310
|
+
message: "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"
|
|
7311
|
+
});
|
|
7312
|
+
const scope = scopeManager.acquire(node);
|
|
7313
|
+
if (!scope) throw new Error("Unable to acquire scope for the current node. This is a bug in eslint-plugin-react-hooks, please file an issue.");
|
|
7314
|
+
const pureScopes = /* @__PURE__ */ new Set();
|
|
7315
|
+
let componentScope = null;
|
|
7316
|
+
{
|
|
7317
|
+
let currentScope = scope.upper;
|
|
7318
|
+
while (currentScope) {
|
|
7319
|
+
pureScopes.add(currentScope);
|
|
7320
|
+
if (currentScope.type === "function" || currentScope.type === "hook" || currentScope.type === "component") break;
|
|
7321
|
+
currentScope = currentScope.upper;
|
|
7322
|
+
}
|
|
7323
|
+
if (!currentScope) return;
|
|
7324
|
+
componentScope = currentScope;
|
|
7325
|
+
}
|
|
7326
|
+
const isArray = Array.isArray;
|
|
7327
|
+
function isStableKnownHookValue(resolved) {
|
|
7328
|
+
if (!isArray(resolved.defs)) return false;
|
|
7329
|
+
const initializers = resolved.defs.filter((definition) => definition.type === "Variable" && definition.node.type === "VariableDeclarator" && definition.node.init != null);
|
|
7330
|
+
if (initializers.length !== 1) return false;
|
|
7331
|
+
const def = initializers[0];
|
|
7332
|
+
const defNode = def.node;
|
|
7333
|
+
if (defNode.type !== "VariableDeclarator") return false;
|
|
7334
|
+
let init = defNode.init;
|
|
7335
|
+
if (init == null) return false;
|
|
7336
|
+
while (init.type === "TSAsExpression" || init.type === "AsExpression") init = init.expression;
|
|
7337
|
+
let declaration = defNode.parent;
|
|
7338
|
+
if (declaration == null && componentScope != null) {
|
|
7339
|
+
fastFindReferenceWithParent(componentScope.block, def.node.id);
|
|
7340
|
+
declaration = def.node.parent;
|
|
7341
|
+
if (declaration == null) return false;
|
|
7342
|
+
}
|
|
7343
|
+
if (declaration != null && "kind" in declaration && declaration.kind === "const" && init.type === "Literal" && (typeof init.value === "string" || typeof init.value === "number" || init.value === null)) return true;
|
|
7344
|
+
if (init.type !== "CallExpression") return false;
|
|
7345
|
+
let callee = init.callee;
|
|
7346
|
+
if (callee.type === "MemberExpression" && "name" in callee.object && callee.object.name === "React" && callee.property != null && !callee.computed) callee = callee.property;
|
|
7347
|
+
if (callee.type !== "Identifier") return false;
|
|
7348
|
+
const id = def.node.id;
|
|
7349
|
+
const { name } = callee;
|
|
7350
|
+
if (name === "useRef" && id.type === "Identifier") return true;
|
|
7351
|
+
else if (isUseEffectEventIdentifier(callee) && id.type === "Identifier") {
|
|
7352
|
+
for (const ref of resolved.references) if (ref !== id) useEffectEventVariables.add(ref.identifier);
|
|
7353
|
+
return true;
|
|
7354
|
+
} else if (name === "useState" || name === "useReducer" || name === "useActionState") {
|
|
7355
|
+
const isActionState = name === "useActionState";
|
|
7356
|
+
if (id.type === "ArrayPattern" && (isActionState ? id.elements.length >= 2 : id.elements.length === 2) && isArray(resolved.identifiers)) {
|
|
7357
|
+
const firstElement = id.elements[0]?.type === "AssignmentPattern" ? id.elements[0].left : id.elements[0];
|
|
7358
|
+
const secondElement = id.elements[1]?.type === "AssignmentPattern" ? id.elements[1].left : id.elements[1];
|
|
7359
|
+
if (resolved.identifiers.some((identifier) => identifier === secondElement)) {
|
|
7360
|
+
if (name === "useState") {
|
|
7361
|
+
const references = resolved.references;
|
|
7362
|
+
for (const reference of references) {
|
|
7363
|
+
if (reference.isWrite() && reference.init !== true) return false;
|
|
7364
|
+
setStateCallSites.set(reference.identifier, firstElement);
|
|
7365
|
+
}
|
|
7366
|
+
}
|
|
7367
|
+
return true;
|
|
7368
|
+
} else if (resolved.identifiers.some((identifier) => identifier === firstElement)) {
|
|
7369
|
+
if (name === "useState") {
|
|
7370
|
+
const references = resolved.references;
|
|
7371
|
+
for (const reference of references) stateVariables.add(reference.identifier);
|
|
7372
|
+
}
|
|
7373
|
+
return false;
|
|
7374
|
+
}
|
|
7375
|
+
}
|
|
7376
|
+
} else if (name === "useTransition") {
|
|
7377
|
+
if (id.type === "ArrayPattern" && id.elements.length === 2 && Array.isArray(resolved.identifiers)) {
|
|
7378
|
+
const secondElement = id.elements[1]?.type === "AssignmentPattern" ? id.elements[1].left : id.elements[1];
|
|
7379
|
+
if (resolved.identifiers.some((identifier) => identifier === secondElement)) return true;
|
|
7380
|
+
}
|
|
7381
|
+
}
|
|
7382
|
+
return false;
|
|
7383
|
+
}
|
|
7384
|
+
function isFunctionWithoutCapturedValues(resolved) {
|
|
7385
|
+
if (!isArray(resolved.defs)) return false;
|
|
7386
|
+
const def = resolved.defs[0];
|
|
7387
|
+
if (def == null) return false;
|
|
7388
|
+
if (def.node == null || def.node.id == null) return false;
|
|
7389
|
+
const fnNode = def.node;
|
|
7390
|
+
const childScopes = componentScope?.childScopes || [];
|
|
7391
|
+
let fnScope = null;
|
|
7392
|
+
for (const childScope of childScopes) {
|
|
7393
|
+
const childScopeBlock = childScope.block;
|
|
7394
|
+
if (fnNode.type === "FunctionDeclaration" && childScopeBlock === fnNode || fnNode.type === "VariableDeclarator" && childScopeBlock.parent === fnNode) {
|
|
7395
|
+
fnScope = childScope;
|
|
7396
|
+
break;
|
|
7397
|
+
}
|
|
7398
|
+
}
|
|
7399
|
+
if (fnScope == null) return false;
|
|
7400
|
+
for (const ref of fnScope.through) {
|
|
7401
|
+
if (ref.resolved == null) continue;
|
|
7402
|
+
if (pureScopes.has(ref.resolved.scope) && !memoizedIsStableKnownHookValue(ref.resolved)) return false;
|
|
7403
|
+
}
|
|
7404
|
+
return true;
|
|
7405
|
+
}
|
|
7406
|
+
const memoizedIsStableKnownHookValue = memoizeWithWeakMap((resolved) => isStableKnownHookValue(resolved) || isConfiguredStableHookValue(resolved, options.hooks), stableKnownValueCache);
|
|
7407
|
+
const memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(isFunctionWithoutCapturedValues, functionWithoutCapturedValueCache);
|
|
7408
|
+
const currentRefsInEffectCleanup = /* @__PURE__ */ new Map();
|
|
7409
|
+
function isInsideEffectCleanup(reference) {
|
|
7410
|
+
let curScope = reference.from;
|
|
7411
|
+
let isInReturnedFunction = false;
|
|
7412
|
+
while (curScope != null && curScope.block !== node) {
|
|
7413
|
+
if (curScope.type === "function") isInReturnedFunction = curScope.block.parent != null && curScope.block.parent.type === "ReturnStatement";
|
|
7414
|
+
curScope = curScope.upper;
|
|
7415
|
+
}
|
|
7416
|
+
return isInReturnedFunction;
|
|
7417
|
+
}
|
|
7418
|
+
const dependencies = /* @__PURE__ */ new Map();
|
|
7419
|
+
const optionalChains = /* @__PURE__ */ new Map();
|
|
7420
|
+
gatherDependenciesRecursively(scope);
|
|
7421
|
+
function gatherDependenciesRecursively(currentScope) {
|
|
7422
|
+
for (const reference of currentScope.references) {
|
|
7423
|
+
if (!reference.resolved) continue;
|
|
7424
|
+
if (!pureScopes.has(reference.resolved.scope)) continue;
|
|
7425
|
+
const referenceNode = fastFindReferenceWithParent(node, reference.identifier);
|
|
7426
|
+
if (referenceNode == null) continue;
|
|
7427
|
+
const dependencyNode = getDependency(referenceNode);
|
|
7428
|
+
const dependency = analyzePropertyChain(dependencyNode, optionalChains);
|
|
7429
|
+
if (isEffect && dependencyNode.type === "Identifier" && (dependencyNode.parent?.type === "MemberExpression" || dependencyNode.parent?.type === "OptionalMemberExpression") && !dependencyNode.parent.computed && dependencyNode.parent.property.type === "Identifier" && dependencyNode.parent.property.name === "current" && isInsideEffectCleanup(reference)) currentRefsInEffectCleanup.set(dependency, {
|
|
7430
|
+
reference,
|
|
7431
|
+
dependencyNode
|
|
7432
|
+
});
|
|
7433
|
+
if (dependencyNode.parent?.type === "TSTypeQuery" || dependencyNode.parent?.type === "TSTypeReference") continue;
|
|
7434
|
+
const def = reference.resolved.defs[0];
|
|
7435
|
+
if (def == null) continue;
|
|
7436
|
+
if (def.node != null && def.node.init === node.parent) continue;
|
|
7437
|
+
if (def.type === "TypeParameter" || dependencyNode.parent?.type === "GenericTypeAnnotation") continue;
|
|
7438
|
+
if (!dependencies.has(dependency)) {
|
|
7439
|
+
const resolved = reference.resolved;
|
|
7440
|
+
const isStable = memoizedIsStableKnownHookValue(resolved) || memoizedIsFunctionWithoutCapturedValues(resolved);
|
|
7441
|
+
dependencies.set(dependency, {
|
|
7442
|
+
isStable,
|
|
7443
|
+
references: [reference]
|
|
7444
|
+
});
|
|
7445
|
+
} else dependencies.get(dependency)?.references.push(reference);
|
|
7446
|
+
}
|
|
7447
|
+
for (const childScope of currentScope.childScopes) gatherDependenciesRecursively(childScope);
|
|
7448
|
+
}
|
|
7449
|
+
currentRefsInEffectCleanup.forEach(({ reference, dependencyNode }, dependency) => {
|
|
7450
|
+
const references = reference.resolved?.references || [];
|
|
7451
|
+
let foundCurrentAssignment = false;
|
|
7452
|
+
for (const ref of references) {
|
|
7453
|
+
const { identifier } = ref;
|
|
7454
|
+
const { parent } = identifier;
|
|
7455
|
+
if (parent != null && parent.type === "MemberExpression" && !parent.computed && parent.property.type === "Identifier" && parent.property.name === "current" && parent.parent?.type === "AssignmentExpression" && parent.parent.left === parent) {
|
|
7456
|
+
foundCurrentAssignment = true;
|
|
7457
|
+
break;
|
|
7458
|
+
}
|
|
7459
|
+
}
|
|
7460
|
+
if (foundCurrentAssignment) return;
|
|
7461
|
+
reportProblem({
|
|
7462
|
+
node: dependencyNode.parent.property,
|
|
7463
|
+
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.`
|
|
7464
|
+
});
|
|
7465
|
+
});
|
|
7466
|
+
const staleAssignments = /* @__PURE__ */ new Set();
|
|
7467
|
+
function reportStaleAssignment(writeExpr, key) {
|
|
7468
|
+
if (staleAssignments.has(key)) return;
|
|
7469
|
+
staleAssignments.add(key);
|
|
7470
|
+
reportProblem({
|
|
7471
|
+
node: writeExpr,
|
|
7472
|
+
message: `Assignments to the '${key}' variable from inside React Hook ${getSourceCode().getText(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 ${getSourceCode().getText(reactiveHook)}.`
|
|
7473
|
+
});
|
|
7474
|
+
}
|
|
7475
|
+
const stableDependencies = /* @__PURE__ */ new Set();
|
|
7476
|
+
dependencies.forEach(({ isStable, references }, key) => {
|
|
7477
|
+
if (isStable) stableDependencies.add(key);
|
|
7478
|
+
references.forEach((reference) => {
|
|
7479
|
+
if (reference.writeExpr) reportStaleAssignment(reference.writeExpr, key);
|
|
7480
|
+
});
|
|
7481
|
+
});
|
|
7482
|
+
if (staleAssignments.size > 0) return;
|
|
7483
|
+
if (!declaredDependenciesNode) {
|
|
7484
|
+
if (isAutoDepsHook) return;
|
|
7485
|
+
let setStateInsideEffectWithoutDeps = null;
|
|
7486
|
+
dependencies.forEach(({ references }, key) => {
|
|
7487
|
+
if (setStateInsideEffectWithoutDeps) return;
|
|
7488
|
+
references.forEach((reference) => {
|
|
7489
|
+
if (setStateInsideEffectWithoutDeps) return;
|
|
7490
|
+
const id = reference.identifier;
|
|
7491
|
+
if (!setStateCallSites.has(id)) return;
|
|
7492
|
+
let fnScope = reference.from;
|
|
7493
|
+
while (fnScope != null && fnScope.type !== "function") fnScope = fnScope.upper;
|
|
7494
|
+
if (fnScope?.block === node) setStateInsideEffectWithoutDeps = key;
|
|
7495
|
+
});
|
|
7496
|
+
});
|
|
7497
|
+
if (setStateInsideEffectWithoutDeps) {
|
|
7498
|
+
const { suggestedDependencies } = collectRecommendations({
|
|
7499
|
+
dependencies,
|
|
7500
|
+
declaredDependencies: [],
|
|
7501
|
+
stableDependencies,
|
|
7502
|
+
externalDependencies: /* @__PURE__ */ new Set(),
|
|
7503
|
+
isEffect: true
|
|
7504
|
+
});
|
|
7505
|
+
const suggestedDependenciesText = `[${suggestedDependencies.join(", ")}]`;
|
|
7506
|
+
const dependenciesArgument = callExpression.arguments[dependenciesIndex];
|
|
7507
|
+
const hasSpreadArgumentBeforeOrAtDependencies = callExpression.arguments.slice(0, dependenciesIndex + 1).some((argument) => argument?.type === "SpreadElement");
|
|
7508
|
+
let fix = null;
|
|
7509
|
+
if (!hasSpreadArgumentBeforeOrAtDependencies) {
|
|
7510
|
+
if (dependenciesArgument?.type === "Identifier" && dependenciesArgument.name === "undefined") fix = (fixer) => fixer.replaceText(dependenciesArgument, suggestedDependenciesText);
|
|
7511
|
+
else if (dependenciesArgument == null && dependenciesIndex === callExpression.arguments.length) {
|
|
7512
|
+
const closeParen = getSourceCode().getLastToken(callExpression);
|
|
7513
|
+
if (closeParen != null && closeParen.value === ")") {
|
|
7514
|
+
const tokenBeforeCloseParen = getSourceCode().getTokenBefore(closeParen);
|
|
7515
|
+
fix = tokenBeforeCloseParen?.value === "," ? (fixer) => fixer.insertTextAfter(tokenBeforeCloseParen, ` ${suggestedDependenciesText}`) : (fixer) => fixer.insertTextBefore(closeParen, `, ${suggestedDependenciesText}`);
|
|
7516
|
+
}
|
|
7517
|
+
}
|
|
7518
|
+
}
|
|
7519
|
+
const dependenciesArgumentText = dependenciesIndex === 1 ? "as a second argument" : `as the dependencies argument (index ${dependenciesIndex})`;
|
|
7520
|
+
const problem = {
|
|
7521
|
+
node: reactiveHook,
|
|
7522
|
+
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 ${suggestedDependenciesText} ${dependenciesArgumentText} to the ${reactiveHookName} Hook.`
|
|
7523
|
+
};
|
|
7524
|
+
if (fix != null) problem.suggest = [{
|
|
7525
|
+
desc: `Add dependencies array: ${suggestedDependenciesText}`,
|
|
7526
|
+
fix
|
|
7527
|
+
}];
|
|
7528
|
+
reportProblem(problem);
|
|
7529
|
+
}
|
|
7530
|
+
return;
|
|
7531
|
+
}
|
|
7532
|
+
if (isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) return;
|
|
7533
|
+
const declaredDependencies = [];
|
|
7534
|
+
const externalDependencies = /* @__PURE__ */ new Set();
|
|
7535
|
+
const isArrayExpression = declaredDependenciesNode.type === "ArrayExpression";
|
|
7536
|
+
const isTSAsArrayExpression = declaredDependenciesNode.type === "TSAsExpression" && declaredDependenciesNode.expression.type === "ArrayExpression";
|
|
7537
|
+
if (!isArrayExpression && !isTSAsArrayExpression) reportProblem({
|
|
7538
|
+
node: declaredDependenciesNode,
|
|
7539
|
+
message: `React Hook ${getSourceCode().getText(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.`
|
|
7540
|
+
});
|
|
7541
|
+
else (isTSAsArrayExpression ? declaredDependenciesNode.expression : declaredDependenciesNode).elements.forEach((declaredDependencyNode) => {
|
|
7542
|
+
if (declaredDependencyNode === null) return;
|
|
7543
|
+
if (declaredDependencyNode.type === "SpreadElement") {
|
|
7544
|
+
reportProblem({
|
|
7545
|
+
node: declaredDependencyNode,
|
|
7546
|
+
message: `React Hook ${getSourceCode().getText(reactiveHook)} has a spread element in its dependency array. This means we can't statically verify whether you've passed the correct dependencies.`
|
|
7547
|
+
});
|
|
7548
|
+
return;
|
|
7549
|
+
}
|
|
7550
|
+
if (useEffectEventVariables.has(declaredDependencyNode)) reportProblem({
|
|
7551
|
+
node: declaredDependencyNode,
|
|
7552
|
+
message: `Functions returned from \`useEffectEvent\` must not be included in the dependency array. Remove \`${getSourceCode().getText(declaredDependencyNode)}\` from the list.`,
|
|
7553
|
+
suggest: [{
|
|
7554
|
+
desc: `Remove the dependency \`${getSourceCode().getText(declaredDependencyNode)}\``,
|
|
7555
|
+
fix(fixer) {
|
|
7556
|
+
return fixer.removeRange(declaredDependencyNode.range);
|
|
7557
|
+
}
|
|
7558
|
+
}]
|
|
7559
|
+
});
|
|
7560
|
+
let declaredDependency;
|
|
7561
|
+
try {
|
|
7562
|
+
declaredDependency = analyzePropertyChain(declaredDependencyNode, null);
|
|
7563
|
+
} catch (error) {
|
|
7564
|
+
if (error instanceof Error && /Unsupported node type/.test(error.message)) {
|
|
7565
|
+
if (declaredDependencyNode.type === "Literal") {
|
|
7566
|
+
if (declaredDependencyNode.value && dependencies.has(declaredDependencyNode.value)) reportProblem({
|
|
7567
|
+
node: declaredDependencyNode,
|
|
7568
|
+
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?`
|
|
7569
|
+
});
|
|
7570
|
+
else reportProblem({
|
|
7571
|
+
node: declaredDependencyNode,
|
|
7572
|
+
message: `The ${declaredDependencyNode.raw} literal is not a valid dependency because it never changes. You can safely remove it.`
|
|
7573
|
+
});
|
|
7574
|
+
} else reportProblem({
|
|
7575
|
+
node: declaredDependencyNode,
|
|
7576
|
+
message: `React Hook ${getSourceCode().getText(reactiveHook)} has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked.`
|
|
7577
|
+
});
|
|
7578
|
+
return;
|
|
7579
|
+
} else throw error;
|
|
7580
|
+
}
|
|
7581
|
+
let maybeID = declaredDependencyNode;
|
|
7582
|
+
while (maybeID.type === "MemberExpression" || maybeID.type === "OptionalMemberExpression" || maybeID.type === "ChainExpression") maybeID = maybeID.object || maybeID.expression.object;
|
|
7583
|
+
const isDeclaredInComponent = !componentScope.through.some((ref) => ref.identifier === maybeID);
|
|
7584
|
+
declaredDependencies.push({
|
|
7585
|
+
key: declaredDependency,
|
|
7586
|
+
node: declaredDependencyNode
|
|
7587
|
+
});
|
|
7588
|
+
if (!isDeclaredInComponent) externalDependencies.add(declaredDependency);
|
|
7589
|
+
});
|
|
7590
|
+
const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies } = collectRecommendations({
|
|
7591
|
+
dependencies,
|
|
7592
|
+
declaredDependencies,
|
|
7593
|
+
stableDependencies,
|
|
7594
|
+
externalDependencies,
|
|
7595
|
+
isEffect
|
|
7596
|
+
});
|
|
7597
|
+
let suggestedDeps = suggestedDependencies;
|
|
7598
|
+
if (duplicateDependencies.size + missingDependencies.size + unnecessaryDependencies.size === 0) {
|
|
7599
|
+
scanForConstructions({
|
|
7600
|
+
declaredDependencies,
|
|
7601
|
+
declaredDependenciesNode,
|
|
7602
|
+
componentScope,
|
|
7603
|
+
scope
|
|
7604
|
+
}).forEach(({ construction, isUsedOutsideOfHook, depType }) => {
|
|
7605
|
+
const wrapperHook = depType === "function" ? "useCallback" : "useMemo";
|
|
7606
|
+
const constructionType = depType === "function" ? "definition" : "initialization";
|
|
7607
|
+
const defaultAdvice = `wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`;
|
|
7608
|
+
const advice = isUsedOutsideOfHook ? `To fix this, ${defaultAdvice}` : `Move it inside the ${reactiveHookName} callback. Alternatively, ${defaultAdvice}`;
|
|
7609
|
+
const causation = depType === "conditional" || depType === "logical expression" ? "could make" : "makes";
|
|
7610
|
+
const message = `The '${construction.name.name}' ${depType} ${causation} the dependencies of ${reactiveHookName} Hook (at line ${declaredDependenciesNode.loc?.start.line}) change on every render. ${advice}`;
|
|
7611
|
+
let suggest;
|
|
7612
|
+
if (isUsedOutsideOfHook && construction.type === "Variable" && depType === "function") suggest = [{
|
|
7613
|
+
desc: `Wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`,
|
|
7614
|
+
fix(fixer) {
|
|
7615
|
+
const [before, after] = wrapperHook === "useMemo" ? [`useMemo(() => { return `, "; })"] : ["useCallback(", ")"];
|
|
7616
|
+
return [fixer.insertTextBefore(construction.node.init, before), fixer.insertTextAfter(construction.node.init, after)];
|
|
7617
|
+
}
|
|
7618
|
+
}];
|
|
7619
|
+
reportProblem({
|
|
7620
|
+
node: construction.node,
|
|
7621
|
+
message,
|
|
7622
|
+
suggest
|
|
7623
|
+
});
|
|
7624
|
+
});
|
|
7625
|
+
return;
|
|
7626
|
+
}
|
|
7627
|
+
if (!isEffect && missingDependencies.size > 0) suggestedDeps = collectRecommendations({
|
|
7628
|
+
dependencies,
|
|
7629
|
+
declaredDependencies: [],
|
|
7630
|
+
stableDependencies,
|
|
7631
|
+
externalDependencies,
|
|
7632
|
+
isEffect
|
|
7633
|
+
}).suggestedDependencies;
|
|
7634
|
+
function areDeclaredDepsAlphabetized() {
|
|
7635
|
+
if (declaredDependencies.length === 0) return true;
|
|
7636
|
+
const declaredDepKeys = declaredDependencies.map((dep) => dep.key);
|
|
7637
|
+
const sortedDeclaredDepKeys = declaredDepKeys.slice().sort();
|
|
7638
|
+
return declaredDepKeys.join(",") === sortedDeclaredDepKeys.join(",");
|
|
7639
|
+
}
|
|
7640
|
+
if (areDeclaredDepsAlphabetized()) suggestedDeps.sort();
|
|
7641
|
+
function formatDependency(path) {
|
|
7642
|
+
const members = path.split(".");
|
|
7643
|
+
let finalPath = "";
|
|
7644
|
+
for (let i = 0; i < members.length; i++) {
|
|
7645
|
+
if (i !== 0) {
|
|
7646
|
+
const pathSoFar = members.slice(0, i + 1).join(".");
|
|
7647
|
+
const isOptional = optionalChains.get(pathSoFar) === true;
|
|
7648
|
+
finalPath += isOptional ? "?." : ".";
|
|
7649
|
+
}
|
|
7650
|
+
finalPath += members[i];
|
|
7651
|
+
}
|
|
7652
|
+
return finalPath;
|
|
7653
|
+
}
|
|
7654
|
+
function getWarningMessage(deps, singlePrefix, label, fixVerb) {
|
|
7655
|
+
if (deps.size === 0) return null;
|
|
7656
|
+
return (deps.size > 1 ? "" : singlePrefix + " ") + label + " " + (deps.size > 1 ? "dependencies" : "dependency") + ": " + joinEnglish(Array.from(deps).sort().map((name) => "'" + formatDependency(name) + "'")) + `. Either ${fixVerb} ${deps.size > 1 ? "them" : "it"} or remove the dependency array.`;
|
|
7657
|
+
}
|
|
7658
|
+
let extraWarning = "";
|
|
7659
|
+
if (unnecessaryDependencies.size > 0) {
|
|
7660
|
+
let badRef = null;
|
|
7661
|
+
Array.from(unnecessaryDependencies.keys()).forEach((key) => {
|
|
7662
|
+
if (badRef !== null) return;
|
|
7663
|
+
if (key.endsWith(".current")) badRef = key;
|
|
7664
|
+
});
|
|
7665
|
+
if (badRef !== null) extraWarning = ` Mutable values like '${badRef}' aren't valid dependencies because mutating them doesn't re-render the component.`;
|
|
7666
|
+
else if (externalDependencies.size > 0) {
|
|
7667
|
+
const dep = Array.from(externalDependencies)[0];
|
|
7668
|
+
if (!scope.set.has(dep)) extraWarning = ` Outer scope values like '${dep}' aren't valid dependencies because mutating them doesn't re-render the component.`;
|
|
7669
|
+
}
|
|
7670
|
+
}
|
|
7671
|
+
if (!extraWarning && missingDependencies.has("props")) {
|
|
7672
|
+
const propDep = dependencies.get("props");
|
|
7673
|
+
if (propDep == null) return;
|
|
7674
|
+
const refs = propDep.references;
|
|
7675
|
+
if (!Array.isArray(refs)) return;
|
|
7676
|
+
let isPropsOnlyUsedInMembers = true;
|
|
7677
|
+
for (const ref of refs) {
|
|
7678
|
+
const id = fastFindReferenceWithParent(componentScope.block, ref.identifier);
|
|
7679
|
+
if (!id) {
|
|
7680
|
+
isPropsOnlyUsedInMembers = false;
|
|
7681
|
+
break;
|
|
7682
|
+
}
|
|
7683
|
+
const parent = id.parent;
|
|
7684
|
+
if (parent == null) {
|
|
7685
|
+
isPropsOnlyUsedInMembers = false;
|
|
7686
|
+
break;
|
|
7687
|
+
}
|
|
7688
|
+
if (parent.type !== "MemberExpression" && parent.type !== "OptionalMemberExpression") {
|
|
7689
|
+
isPropsOnlyUsedInMembers = false;
|
|
7690
|
+
break;
|
|
7691
|
+
}
|
|
7692
|
+
}
|
|
7693
|
+
if (isPropsOnlyUsedInMembers) 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 ${getSourceCode().getText(reactiveHook)}.`;
|
|
7694
|
+
}
|
|
7695
|
+
if (!extraWarning && missingDependencies.size > 0) {
|
|
7696
|
+
let missingCallbackDep = null;
|
|
7697
|
+
missingDependencies.forEach((missingDep) => {
|
|
7698
|
+
if (missingCallbackDep) return;
|
|
7699
|
+
const topScopeRef = componentScope.set.get(missingDep);
|
|
7700
|
+
const usedDep = dependencies.get(missingDep);
|
|
7701
|
+
if (!usedDep?.references || usedDep?.references[0]?.resolved !== topScopeRef) return;
|
|
7702
|
+
const def = topScopeRef?.defs[0];
|
|
7703
|
+
if (def == null || def.name == null || def.type !== "Parameter") return;
|
|
7704
|
+
let isFunctionCall = false;
|
|
7705
|
+
let id;
|
|
7706
|
+
for (const reference of usedDep.references) {
|
|
7707
|
+
id = reference.identifier;
|
|
7708
|
+
if (id != null && id.parent != null && (id.parent.type === "CallExpression" || id.parent.type === "OptionalCallExpression") && id.parent.callee === id) {
|
|
7709
|
+
isFunctionCall = true;
|
|
7710
|
+
break;
|
|
7711
|
+
}
|
|
7712
|
+
}
|
|
7713
|
+
if (!isFunctionCall) return;
|
|
7714
|
+
missingCallbackDep = missingDep;
|
|
7715
|
+
});
|
|
7716
|
+
if (missingCallbackDep !== null) extraWarning = ` If '${missingCallbackDep}' changes too often, find the parent component that defines it and wrap that definition in useCallback.`;
|
|
7717
|
+
}
|
|
7718
|
+
if (!extraWarning && missingDependencies.size > 0) {
|
|
7719
|
+
let setStateRecommendation = null;
|
|
7720
|
+
for (const missingDep of missingDependencies) {
|
|
7721
|
+
if (setStateRecommendation !== null) break;
|
|
7722
|
+
const references = dependencies.get(missingDep).references;
|
|
7723
|
+
let id;
|
|
7724
|
+
let maybeCall;
|
|
7725
|
+
for (const reference of references) {
|
|
7726
|
+
id = reference.identifier;
|
|
7727
|
+
maybeCall = id.parent;
|
|
7728
|
+
while (maybeCall != null && maybeCall !== componentScope.block) {
|
|
7729
|
+
if (maybeCall.type === "CallExpression") {
|
|
7730
|
+
const correspondingStateVariable = setStateCallSites.get(maybeCall.callee);
|
|
7731
|
+
if (correspondingStateVariable != null) {
|
|
7732
|
+
if ("name" in correspondingStateVariable && correspondingStateVariable.name === missingDep) setStateRecommendation = {
|
|
7733
|
+
missingDep,
|
|
7734
|
+
setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
|
|
7735
|
+
form: "updater"
|
|
7736
|
+
};
|
|
7737
|
+
else if (stateVariables.has(id)) setStateRecommendation = {
|
|
7738
|
+
missingDep,
|
|
7739
|
+
setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
|
|
7740
|
+
form: "reducer"
|
|
7741
|
+
};
|
|
7742
|
+
else {
|
|
7743
|
+
const resolved = reference.resolved;
|
|
7744
|
+
if (resolved != null) {
|
|
7745
|
+
const def = resolved.defs[0];
|
|
7746
|
+
if (def != null && def.type === "Parameter") setStateRecommendation = {
|
|
7747
|
+
missingDep,
|
|
7748
|
+
setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
|
|
7749
|
+
form: "inlineReducer"
|
|
7750
|
+
};
|
|
7751
|
+
}
|
|
7752
|
+
}
|
|
7753
|
+
break;
|
|
7754
|
+
}
|
|
7755
|
+
}
|
|
7756
|
+
maybeCall = maybeCall.parent;
|
|
7757
|
+
}
|
|
7758
|
+
if (setStateRecommendation !== null) break;
|
|
7759
|
+
}
|
|
7760
|
+
}
|
|
7761
|
+
if (setStateRecommendation !== null) switch (setStateRecommendation.form) {
|
|
7762
|
+
case "reducer":
|
|
7763
|
+
extraWarning = ` You can also replace multiple useState variables with useReducer if '${setStateRecommendation.setter}' needs the current value of '${setStateRecommendation.missingDep}'.`;
|
|
7764
|
+
break;
|
|
7765
|
+
case "inlineReducer":
|
|
7766
|
+
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.`;
|
|
7767
|
+
break;
|
|
7768
|
+
case "updater":
|
|
7769
|
+
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.`;
|
|
7770
|
+
break;
|
|
7771
|
+
default: throw new Error("Unknown case.");
|
|
7772
|
+
}
|
|
7773
|
+
}
|
|
7774
|
+
reportProblem({
|
|
7775
|
+
node: declaredDependenciesNode,
|
|
7776
|
+
message: `React Hook ${getSourceCode().getText(reactiveHook)} has ` + (getWarningMessage(missingDependencies, "a", "missing", "include") || getWarningMessage(unnecessaryDependencies, "an", "unnecessary", "exclude") || getWarningMessage(duplicateDependencies, "a", "duplicate", "omit")) + extraWarning,
|
|
7777
|
+
suggest: [{
|
|
7778
|
+
desc: `Update the dependencies array to be: [${suggestedDeps.map(formatDependency).join(", ")}]`,
|
|
7779
|
+
fix(fixer) {
|
|
7780
|
+
return fixer.replaceText(declaredDependenciesNode, `[${suggestedDeps.map(formatDependency).join(", ")}]`);
|
|
7781
|
+
}
|
|
7782
|
+
}]
|
|
7783
|
+
});
|
|
7784
|
+
}
|
|
7785
|
+
function visitCallExpression(node) {
|
|
7786
|
+
const configuredHook = getReactiveHookConfig(node, options.hooks);
|
|
7787
|
+
const callbackIndex = configuredHook ? configuredHook.closureIndex : getReactiveHookCallbackIndex(node.callee, options);
|
|
7788
|
+
if (callbackIndex === -1) return;
|
|
7789
|
+
let callback = node.arguments[callbackIndex];
|
|
7790
|
+
const reactiveHook = node.callee;
|
|
7791
|
+
const nodeWithoutNamespace = getNodeWithoutReactNamespace(reactiveHook);
|
|
7792
|
+
const reactiveHookName = configuredHook?.name ?? ("name" in nodeWithoutNamespace ? nodeWithoutNamespace.name : "");
|
|
7793
|
+
const dependenciesIndex = configuredHook ? configuredHook.dependenciesIndex : callbackIndex + 1;
|
|
7794
|
+
const maybeNode = node.arguments[dependenciesIndex];
|
|
7795
|
+
const declaredDependenciesNode = maybeNode && !(maybeNode.type === "Identifier" && maybeNode.name === "undefined") ? maybeNode : void 0;
|
|
7796
|
+
const isEffect = /Effect($|[^a-z])/g.test(reactiveHookName);
|
|
7797
|
+
if (!callback) {
|
|
7798
|
+
if (configuredHook) {
|
|
7799
|
+
const builtInCallbackIndex = getReactiveHookCallbackIndex(reactiveHook, { additionalHooks: void 0 });
|
|
7800
|
+
const builtInCallback = builtInCallbackIndex === -1 ? null : node.arguments[builtInCallbackIndex];
|
|
7801
|
+
if (builtInCallbackIndex === -1 || builtInCallback != null) return;
|
|
7802
|
+
}
|
|
7803
|
+
reportProblem({
|
|
7804
|
+
node: reactiveHook,
|
|
7805
|
+
message: `React Hook ${reactiveHookName} requires an effect callback. Did you forget to pass a callback to the hook?`
|
|
7806
|
+
});
|
|
7807
|
+
return;
|
|
7808
|
+
}
|
|
7809
|
+
if (!maybeNode && isEffect && options.requireExplicitEffectDeps) reportProblem({
|
|
7810
|
+
node: reactiveHook,
|
|
7811
|
+
message: `React Hook ${reactiveHookName} always requires dependencies. Please add a dependency array or an explicit \`undefined\``
|
|
7812
|
+
});
|
|
7813
|
+
const isAutoDepsHook = options.experimental_autoDependenciesHooks.includes(reactiveHookName);
|
|
7814
|
+
if ((!declaredDependenciesNode || isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) && !isEffect) {
|
|
7815
|
+
if (reactiveHookName === "useMemo" || reactiveHookName === "useCallback") reportProblem({
|
|
7816
|
+
node: reactiveHook,
|
|
7817
|
+
message: `React Hook ${reactiveHookName} does nothing when called with only one argument. Did you forget to pass an array of dependencies?`
|
|
7818
|
+
});
|
|
7819
|
+
return;
|
|
7820
|
+
}
|
|
7821
|
+
while (callback.type === "TSAsExpression" || callback.type === "AsExpression") callback = callback.expression;
|
|
7822
|
+
switch (callback.type) {
|
|
7823
|
+
case "FunctionExpression":
|
|
7824
|
+
case "ArrowFunctionExpression":
|
|
7825
|
+
visitFunctionWithDependencies(callback, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
|
|
7826
|
+
return;
|
|
7827
|
+
case "Identifier":
|
|
7828
|
+
if (!declaredDependenciesNode || isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) return;
|
|
7829
|
+
if ("elements" in declaredDependenciesNode && declaredDependenciesNode.elements && declaredDependenciesNode.elements.some((el) => el && el.type === "Identifier" && el.name === callback.name)) return;
|
|
7830
|
+
const variable = getScope(callback).set.get(callback.name);
|
|
7831
|
+
if (variable == null || variable.defs == null) return;
|
|
7832
|
+
const def = variable.defs[0];
|
|
7833
|
+
if (!def || !def.node) break;
|
|
7834
|
+
if (def.type === "Parameter") {
|
|
7835
|
+
reportProblem({
|
|
7836
|
+
node: reactiveHook,
|
|
7837
|
+
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
7838
|
+
});
|
|
7839
|
+
return;
|
|
7840
|
+
}
|
|
7841
|
+
if (def.type !== "Variable" && def.type !== "FunctionName") break;
|
|
7842
|
+
switch (def.node.type) {
|
|
7843
|
+
case "FunctionDeclaration":
|
|
7844
|
+
visitFunctionWithDependencies(def.node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
|
|
7845
|
+
return;
|
|
7846
|
+
case "VariableDeclarator":
|
|
7847
|
+
const init = def.node.init;
|
|
7848
|
+
if (!init) break;
|
|
7849
|
+
switch (init.type) {
|
|
7850
|
+
case "ArrowFunctionExpression":
|
|
7851
|
+
case "FunctionExpression":
|
|
7852
|
+
visitFunctionWithDependencies(init, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
|
|
7853
|
+
return;
|
|
7854
|
+
}
|
|
7855
|
+
}
|
|
7856
|
+
break;
|
|
7857
|
+
default:
|
|
7858
|
+
if (configuredHook) return;
|
|
7859
|
+
reportProblem({
|
|
7860
|
+
node: reactiveHook,
|
|
7861
|
+
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
7862
|
+
});
|
|
7863
|
+
return;
|
|
7864
|
+
}
|
|
7865
|
+
reportProblem({
|
|
7866
|
+
node: reactiveHook,
|
|
7867
|
+
message: `React Hook ${reactiveHookName} has a missing dependency: '${callback.name}'. Either include it or remove the dependency array.`,
|
|
7868
|
+
suggest: [{
|
|
7869
|
+
desc: `Update the dependencies array to be: [${callback.name}]`,
|
|
7870
|
+
fix(fixer) {
|
|
7871
|
+
return fixer.replaceText(declaredDependenciesNode, `[${callback.name}]`);
|
|
7872
|
+
}
|
|
7873
|
+
}]
|
|
7874
|
+
});
|
|
7875
|
+
}
|
|
7876
|
+
return { CallExpression: visitCallExpression };
|
|
7877
|
+
}
|
|
7878
|
+
};
|
|
7879
|
+
function collectRecommendations({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect }) {
|
|
7880
|
+
const depTree = createDepTree();
|
|
7881
|
+
function createDepTree() {
|
|
7882
|
+
return {
|
|
7883
|
+
isUsed: false,
|
|
7884
|
+
isSatisfiedRecursively: false,
|
|
7885
|
+
isSubtreeUsed: false,
|
|
7886
|
+
children: /* @__PURE__ */ new Map()
|
|
7887
|
+
};
|
|
7888
|
+
}
|
|
7889
|
+
dependencies.forEach((_, key) => {
|
|
7890
|
+
const node = getOrCreateNodeByPath(depTree, key);
|
|
7891
|
+
node.isUsed = true;
|
|
7892
|
+
markAllParentsByPath(depTree, key, (parent) => {
|
|
7893
|
+
parent.isSubtreeUsed = true;
|
|
7894
|
+
});
|
|
7895
|
+
});
|
|
7896
|
+
declaredDependencies.forEach(({ key }) => {
|
|
7897
|
+
const node = getOrCreateNodeByPath(depTree, key);
|
|
7898
|
+
node.isSatisfiedRecursively = true;
|
|
7899
|
+
});
|
|
7900
|
+
stableDependencies.forEach((key) => {
|
|
7901
|
+
const node = getOrCreateNodeByPath(depTree, key);
|
|
7902
|
+
node.isSatisfiedRecursively = true;
|
|
7903
|
+
});
|
|
7904
|
+
function getOrCreateNodeByPath(rootNode, path) {
|
|
7905
|
+
const keys = path.split(".");
|
|
7906
|
+
let node = rootNode;
|
|
7907
|
+
for (const key of keys) {
|
|
7908
|
+
let child = node.children.get(key);
|
|
7909
|
+
if (!child) {
|
|
7910
|
+
child = createDepTree();
|
|
7911
|
+
node.children.set(key, child);
|
|
7912
|
+
}
|
|
7913
|
+
node = child;
|
|
7914
|
+
}
|
|
7915
|
+
return node;
|
|
7916
|
+
}
|
|
7917
|
+
function markAllParentsByPath(rootNode, path, fn) {
|
|
7918
|
+
const keys = path.split(".");
|
|
7919
|
+
let node = rootNode;
|
|
7920
|
+
for (const key of keys) {
|
|
7921
|
+
const child = node.children.get(key);
|
|
7922
|
+
if (!child) return;
|
|
7923
|
+
fn(child);
|
|
7924
|
+
node = child;
|
|
7925
|
+
}
|
|
7926
|
+
}
|
|
7927
|
+
const missingDependencies = /* @__PURE__ */ new Set();
|
|
7928
|
+
const satisfyingDependencies = /* @__PURE__ */ new Set();
|
|
7929
|
+
scanTreeRecursively(depTree, missingDependencies, satisfyingDependencies, (key) => key);
|
|
7930
|
+
function scanTreeRecursively(node, missingPaths, satisfyingPaths, keyToPath) {
|
|
7931
|
+
node.children.forEach((child, key) => {
|
|
7932
|
+
const path = keyToPath(key);
|
|
7933
|
+
if (child.isSatisfiedRecursively) {
|
|
7934
|
+
if (child.isSubtreeUsed) satisfyingPaths.add(path);
|
|
7935
|
+
return;
|
|
7936
|
+
}
|
|
7937
|
+
if (child.isUsed) {
|
|
7938
|
+
missingPaths.add(path);
|
|
7939
|
+
return;
|
|
7940
|
+
}
|
|
7941
|
+
scanTreeRecursively(child, missingPaths, satisfyingPaths, (childKey) => path + "." + childKey);
|
|
7942
|
+
});
|
|
7943
|
+
}
|
|
7944
|
+
const suggestedDependencies = [];
|
|
7945
|
+
const unnecessaryDependencies = /* @__PURE__ */ new Set();
|
|
7946
|
+
const duplicateDependencies = /* @__PURE__ */ new Set();
|
|
7947
|
+
declaredDependencies.forEach(({ key }) => {
|
|
7948
|
+
if (satisfyingDependencies.has(key)) {
|
|
7949
|
+
if (suggestedDependencies.indexOf(key) === -1) suggestedDependencies.push(key);
|
|
7950
|
+
else duplicateDependencies.add(key);
|
|
7951
|
+
} else if (isEffect && !key.endsWith(".current") && !externalDependencies.has(key)) {
|
|
7952
|
+
if (suggestedDependencies.indexOf(key) === -1) suggestedDependencies.push(key);
|
|
7953
|
+
} else unnecessaryDependencies.add(key);
|
|
7954
|
+
});
|
|
7955
|
+
missingDependencies.forEach((key) => {
|
|
7956
|
+
suggestedDependencies.push(key);
|
|
7957
|
+
});
|
|
7958
|
+
return {
|
|
7959
|
+
suggestedDependencies,
|
|
7960
|
+
unnecessaryDependencies,
|
|
7961
|
+
duplicateDependencies,
|
|
7962
|
+
missingDependencies
|
|
7963
|
+
};
|
|
7964
|
+
}
|
|
7965
|
+
function getConstructionExpressionType(node) {
|
|
7966
|
+
switch (node.type) {
|
|
7967
|
+
case "ObjectExpression": return "object";
|
|
7968
|
+
case "ArrayExpression": return "array";
|
|
7969
|
+
case "ArrowFunctionExpression":
|
|
7970
|
+
case "FunctionExpression": return "function";
|
|
7971
|
+
case "ClassExpression": return "class";
|
|
7972
|
+
case "ConditionalExpression":
|
|
7973
|
+
if (getConstructionExpressionType(node.consequent) != null || getConstructionExpressionType(node.alternate) != null) return "conditional";
|
|
7974
|
+
return null;
|
|
7975
|
+
case "LogicalExpression":
|
|
7976
|
+
if (getConstructionExpressionType(node.left) != null || getConstructionExpressionType(node.right) != null) return "logical expression";
|
|
7977
|
+
return null;
|
|
7978
|
+
case "JSXFragment": return "JSX fragment";
|
|
7979
|
+
case "JSXElement": return "JSX element";
|
|
7980
|
+
case "AssignmentExpression":
|
|
7981
|
+
if (getConstructionExpressionType(node.right) != null) return "assignment expression";
|
|
7982
|
+
return null;
|
|
7983
|
+
case "NewExpression": return "object construction";
|
|
7984
|
+
case "Literal":
|
|
7985
|
+
if (node.value instanceof RegExp) return "regular expression";
|
|
7986
|
+
return null;
|
|
7987
|
+
case "TypeCastExpression":
|
|
7988
|
+
case "AsExpression":
|
|
7989
|
+
case "TSAsExpression": return getConstructionExpressionType(node.expression);
|
|
7990
|
+
}
|
|
7991
|
+
return null;
|
|
7992
|
+
}
|
|
7993
|
+
function scanForConstructions({ declaredDependencies, declaredDependenciesNode, componentScope, scope }) {
|
|
7994
|
+
const constructions = declaredDependencies.map(({ key }) => {
|
|
7995
|
+
const ref = componentScope.variables.find((v) => v.name === key);
|
|
7996
|
+
if (ref == null) return null;
|
|
7997
|
+
const node = ref.defs[0];
|
|
7998
|
+
if (node == null) return null;
|
|
7999
|
+
if (node.type === "Variable" && node.node.type === "VariableDeclarator" && node.node.id.type === "Identifier" && node.node.init != null) {
|
|
8000
|
+
const constantExpressionType = getConstructionExpressionType(node.node.init);
|
|
8001
|
+
if (constantExpressionType) return [ref, constantExpressionType];
|
|
8002
|
+
}
|
|
8003
|
+
if (node.type === "FunctionName" && node.node.type === "FunctionDeclaration") return [ref, "function"];
|
|
8004
|
+
if (node.type === "ClassName" && node.node.type === "ClassDeclaration") return [ref, "class"];
|
|
8005
|
+
return null;
|
|
8006
|
+
}).filter(Boolean);
|
|
8007
|
+
function isUsedOutsideOfHook(ref) {
|
|
8008
|
+
let foundWriteExpr = false;
|
|
8009
|
+
for (const reference of ref.references) {
|
|
8010
|
+
if (reference.writeExpr) {
|
|
8011
|
+
if (foundWriteExpr) return true;
|
|
8012
|
+
else {
|
|
8013
|
+
foundWriteExpr = true;
|
|
8014
|
+
continue;
|
|
8015
|
+
}
|
|
8016
|
+
}
|
|
8017
|
+
let currentScope = reference.from;
|
|
8018
|
+
while (currentScope !== scope && currentScope != null) currentScope = currentScope.upper;
|
|
8019
|
+
if (currentScope !== scope) {
|
|
8020
|
+
if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) return true;
|
|
8021
|
+
}
|
|
8022
|
+
}
|
|
8023
|
+
return false;
|
|
8024
|
+
}
|
|
8025
|
+
return constructions.map(([ref, depType]) => ({
|
|
8026
|
+
construction: ref.defs[0],
|
|
8027
|
+
depType,
|
|
8028
|
+
isUsedOutsideOfHook: isUsedOutsideOfHook(ref)
|
|
8029
|
+
}));
|
|
8030
|
+
}
|
|
8031
|
+
function getDependency(node) {
|
|
8032
|
+
if (node.parent && (node.parent.type === "MemberExpression" || node.parent.type === "OptionalMemberExpression") && node.parent.object === node && "name" in node.parent.property && 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)) return getDependency(node.parent);
|
|
8033
|
+
else if (node.type === "MemberExpression" && node.parent && node.parent.type === "AssignmentExpression" && node.parent.left === node) return node.object;
|
|
8034
|
+
else return node;
|
|
8035
|
+
}
|
|
8036
|
+
function markNode(node, optionalChains, result) {
|
|
8037
|
+
if (optionalChains) {
|
|
8038
|
+
if ("optional" in node && node.optional) {
|
|
8039
|
+
if (!optionalChains.has(result)) optionalChains.set(result, true);
|
|
8040
|
+
} else optionalChains.set(result, false);
|
|
8041
|
+
}
|
|
8042
|
+
}
|
|
8043
|
+
function analyzePropertyChain(node, optionalChains) {
|
|
8044
|
+
if (node.type === "Identifier" || node.type === "JSXIdentifier") {
|
|
8045
|
+
const result = node.name;
|
|
8046
|
+
if (optionalChains) optionalChains.set(result, false);
|
|
8047
|
+
return result;
|
|
8048
|
+
} else if (node.type === "MemberExpression" && !node.computed) {
|
|
8049
|
+
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
8050
|
+
markNode(node, optionalChains, result);
|
|
8051
|
+
return result;
|
|
8052
|
+
} else if (node.type === "OptionalMemberExpression" && !node.computed) {
|
|
8053
|
+
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
8054
|
+
markNode(node, optionalChains, result);
|
|
8055
|
+
return result;
|
|
8056
|
+
} else if (node.type === "ChainExpression" && (!("computed" in node) || !node.computed)) {
|
|
8057
|
+
const expression = node.expression;
|
|
8058
|
+
if (expression.type === "CallExpression") throw new Error(`Unsupported node type: ${expression.type}`);
|
|
8059
|
+
const result = `${analyzePropertyChain(expression.object, optionalChains)}.${analyzePropertyChain(expression.property, null)}`;
|
|
8060
|
+
markNode(expression, optionalChains, result);
|
|
8061
|
+
return result;
|
|
8062
|
+
} else throw new Error(`Unsupported node type: ${node.type}`);
|
|
8063
|
+
}
|
|
8064
|
+
function getNodeWithoutReactNamespace(node) {
|
|
8065
|
+
if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "React" && node.property.type === "Identifier" && !node.computed) return node.property;
|
|
8066
|
+
return node;
|
|
8067
|
+
}
|
|
8068
|
+
function getReactiveHookCallbackIndex(calleeNode, options) {
|
|
8069
|
+
const node = getNodeWithoutReactNamespace(calleeNode);
|
|
8070
|
+
if (node.type !== "Identifier") return -1;
|
|
8071
|
+
switch (node.name) {
|
|
8072
|
+
case "useEffect":
|
|
8073
|
+
case "useLayoutEffect":
|
|
8074
|
+
case "useCallback":
|
|
8075
|
+
case "useMemo": return 0;
|
|
8076
|
+
case "useImperativeHandle": return 1;
|
|
8077
|
+
default: if (node === calleeNode && options && options.additionalHooks) {
|
|
8078
|
+
let name;
|
|
8079
|
+
try {
|
|
8080
|
+
name = analyzePropertyChain(node, null);
|
|
8081
|
+
} catch (error) {
|
|
8082
|
+
if (error instanceof Error && /Unsupported node type/.test(error.message)) return 0;
|
|
8083
|
+
else throw error;
|
|
8084
|
+
}
|
|
8085
|
+
if (options.additionalHooks instanceof RegExp) options.additionalHooks.lastIndex = 0;
|
|
8086
|
+
return options.additionalHooks.test(name) ? 0 : -1;
|
|
8087
|
+
} else return -1;
|
|
8088
|
+
}
|
|
8089
|
+
}
|
|
8090
|
+
function fastFindReferenceWithParent(start, target) {
|
|
8091
|
+
const queue = [start];
|
|
8092
|
+
let item;
|
|
8093
|
+
while (queue.length) {
|
|
8094
|
+
item = queue.shift();
|
|
8095
|
+
if (isSameIdentifier(item, target)) return item;
|
|
8096
|
+
if (!isAncestorNodeOf(item, target)) continue;
|
|
8097
|
+
for (const [key, value] of Object.entries(item)) {
|
|
8098
|
+
if (key === "parent") continue;
|
|
8099
|
+
if (isNodeLike(value)) {
|
|
8100
|
+
value.parent = item;
|
|
8101
|
+
queue.push(value);
|
|
8102
|
+
} else if (Array.isArray(value)) value.forEach((val) => {
|
|
8103
|
+
if (isNodeLike(val)) {
|
|
8104
|
+
val.parent = item;
|
|
8105
|
+
queue.push(val);
|
|
8106
|
+
}
|
|
8107
|
+
});
|
|
8108
|
+
}
|
|
8109
|
+
}
|
|
8110
|
+
return null;
|
|
8111
|
+
}
|
|
8112
|
+
function joinEnglish(arr) {
|
|
8113
|
+
let s = "";
|
|
8114
|
+
for (let i = 0; i < arr.length; i++) {
|
|
8115
|
+
s += arr[i];
|
|
8116
|
+
if (i === 0 && arr.length === 2) s += " and ";
|
|
8117
|
+
else if (i === arr.length - 2 && arr.length > 2) s += ", and ";
|
|
8118
|
+
else if (i < arr.length - 1) s += ", ";
|
|
8119
|
+
}
|
|
8120
|
+
return s;
|
|
8121
|
+
}
|
|
8122
|
+
function isNodeLike(val) {
|
|
8123
|
+
return typeof val === "object" && val !== null && !Array.isArray(val) && "type" in val && typeof val.type === "string";
|
|
8124
|
+
}
|
|
8125
|
+
function isSameIdentifier(a, b) {
|
|
8126
|
+
return (a.type === "Identifier" || a.type === "JSXIdentifier") && a.type === b.type && a.name === b.name && !!a.range && !!b.range && a.range[0] === b.range[0] && a.range[1] === b.range[1];
|
|
8127
|
+
}
|
|
8128
|
+
function isAncestorNodeOf(a, b) {
|
|
8129
|
+
return !!a.range && !!b.range && a.range[0] <= b.range[0] && a.range[1] >= b.range[1];
|
|
8130
|
+
}
|
|
8131
|
+
function isUseEffectEventIdentifier(node) {
|
|
8132
|
+
return node.type === "Identifier" && node.name === "useEffectEvent";
|
|
8133
|
+
}
|
|
8134
|
+
function getUnknownDependenciesMessage(reactiveHookName) {
|
|
8135
|
+
return `React Hook ${reactiveHookName} received a function whose dependencies are unknown. Pass an inline function instead.`;
|
|
8136
|
+
}
|
|
7073
8137
|
// src/rules/unsupported-syntax/lib.ts
|
|
7074
8138
|
function isEvalCall(node) {
|
|
7075
8139
|
const callee = Extract.unwrap(node.callee);
|
|
@@ -7405,7 +8469,7 @@ const plugin = {
|
|
|
7405
8469
|
},
|
|
7406
8470
|
rules: {
|
|
7407
8471
|
"error-boundaries": error_boundaries_default,
|
|
7408
|
-
"exhaustive-deps": rule$
|
|
8472
|
+
"exhaustive-deps": rule$2,
|
|
7409
8473
|
globals: globals_default,
|
|
7410
8474
|
immutability: immutability_default,
|
|
7411
8475
|
"no-access-state-in-setstate": no_access_state_in_setstate_default,
|
|
@@ -7450,10 +8514,11 @@ const plugin = {
|
|
|
7450
8514
|
"no-use-context": no_use_context_default,
|
|
7451
8515
|
purity: purity_default,
|
|
7452
8516
|
refs: refs_default,
|
|
7453
|
-
"rules-of-hooks": rule,
|
|
8517
|
+
"rules-of-hooks": rule$1,
|
|
7454
8518
|
"set-state-in-effect": set_state_in_effect_default,
|
|
7455
8519
|
"set-state-in-render": set_state_in_render_default,
|
|
7456
8520
|
"static-components": static_components_default,
|
|
8521
|
+
"unstable-exhaustive-deps": rule,
|
|
7457
8522
|
"unsupported-syntax": unsupported_syntax_default,
|
|
7458
8523
|
"use-memo": use_memo_default,
|
|
7459
8524
|
"use-state": use_state_default
|