eslint-plugin-react-x 5.30.0-beta.1 → 5.30.0-beta.10
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 +1415 -483
- package/package.json +10 -11
package/dist/index.js
CHANGED
|
@@ -1,18 +1,17 @@
|
|
|
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, 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";
|
|
7
7
|
import { P, isMatching, match } from "ts-pattern";
|
|
8
|
-
import { isAssignmentTargetEqual, isInitializedFromReact, resolveEnclosingAssignmentTarget, resolveObjectType, resolveOrigin } from "@eslint-react/var";
|
|
8
|
+
import { isAssignmentTargetEqual, isInitializedFromReact, resolveEnclosingAssignmentTarget, resolveObjectType, resolveOrigin, resolveOriginChain } from "@eslint-react/var";
|
|
9
9
|
import { DefinitionType, ScopeType } from "@typescript-eslint/scope-manager";
|
|
10
10
|
import { findVariable, getStaticValue } from "@typescript-eslint/utils/ast-utils";
|
|
11
|
-
import { findParentAttribute,
|
|
11
|
+
import { findParentAttribute, getElementFullType, getElementSelfType, hasAttribute, isInsideCreateElementProps, isPlainAttribute, parseCreateElementCall } from "@eslint-react/jsx";
|
|
12
12
|
import { compare } from "compare-versions";
|
|
13
13
|
import { unionConstituents } from "ts-api-utils";
|
|
14
14
|
import "typescript";
|
|
15
|
-
import { simpleTraverse } from "@typescript-eslint/typescript-estree";
|
|
16
15
|
import { delimiterCase, snakeCase, toLowerCase } from "string-ts";
|
|
17
16
|
// \0rolldown/runtime.js
|
|
18
17
|
var __defProp = Object.defineProperty;
|
|
@@ -113,7 +112,8 @@ const rules$7 = {
|
|
|
113
112
|
"react-x/no-unused-state": "off",
|
|
114
113
|
"react-x/refs": "off",
|
|
115
114
|
"react-x/set-state-in-render": "off",
|
|
116
|
-
"react-x/static-components": "off"
|
|
115
|
+
"react-x/static-components": "off",
|
|
116
|
+
"react-x/unstable-exhaustive-deps": "off"
|
|
117
117
|
};
|
|
118
118
|
// src/configs/disable-type-checked.ts
|
|
119
119
|
var disable_type_checked_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -130,7 +130,7 @@ const rules$6 = {
|
|
|
130
130
|
};
|
|
131
131
|
// package.json
|
|
132
132
|
var name$6 = "eslint-plugin-react-x";
|
|
133
|
-
var version = "5.30.0-beta.
|
|
133
|
+
var version = "5.30.0-beta.10";
|
|
134
134
|
// src/utils/create-rule.ts
|
|
135
135
|
function getDocsUrl(ruleName) {
|
|
136
136
|
return `https://eslint-react.xyz/docs/rules/${ruleName}`;
|
|
@@ -192,7 +192,7 @@ function create$50(context) {
|
|
|
192
192
|
});
|
|
193
193
|
}
|
|
194
194
|
// src/rules/exhaustive-deps/exhaustive-deps.ts
|
|
195
|
-
const rule$
|
|
195
|
+
const rule$2 = {
|
|
196
196
|
meta: {
|
|
197
197
|
type: "suggestion",
|
|
198
198
|
docs: {
|
|
@@ -288,7 +288,7 @@ const rule$1 = {
|
|
|
288
288
|
while (init.type === "TSAsExpression" || init.type === "AsExpression") init = init.expression;
|
|
289
289
|
let declaration = defNode.parent;
|
|
290
290
|
if (declaration == null && componentScope != null) {
|
|
291
|
-
fastFindReferenceWithParent(componentScope.block, def.node.id);
|
|
291
|
+
fastFindReferenceWithParent$1(componentScope.block, def.node.id);
|
|
292
292
|
declaration = def.node.parent;
|
|
293
293
|
if (declaration == null) return false;
|
|
294
294
|
}
|
|
@@ -300,7 +300,7 @@ const rule$1 = {
|
|
|
300
300
|
const id = def.node.id;
|
|
301
301
|
const { name } = callee;
|
|
302
302
|
if (name === "useRef" && id.type === "Identifier") return true;
|
|
303
|
-
else if (isUseEffectEventIdentifier$
|
|
303
|
+
else if (isUseEffectEventIdentifier$2(callee) && id.type === "Identifier") {
|
|
304
304
|
for (const ref of resolved.references) if (ref !== id) useEffectEventVariables.add(ref.identifier);
|
|
305
305
|
return true;
|
|
306
306
|
} else if (name === "useState" || name === "useReducer" || name === "useActionState") {
|
|
@@ -372,10 +372,10 @@ const rule$1 = {
|
|
|
372
372
|
for (const reference of currentScope.references) {
|
|
373
373
|
if (!reference.resolved) continue;
|
|
374
374
|
if (!pureScopes.has(reference.resolved.scope)) continue;
|
|
375
|
-
const referenceNode = fastFindReferenceWithParent(node, reference.identifier);
|
|
375
|
+
const referenceNode = fastFindReferenceWithParent$1(node, reference.identifier);
|
|
376
376
|
if (referenceNode == null) continue;
|
|
377
|
-
const dependencyNode = getDependency(referenceNode);
|
|
378
|
-
const dependency = analyzePropertyChain(dependencyNode, optionalChains);
|
|
377
|
+
const dependencyNode = getDependency$1(referenceNode);
|
|
378
|
+
const dependency = analyzePropertyChain$1(dependencyNode, optionalChains);
|
|
379
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, {
|
|
380
380
|
reference,
|
|
381
381
|
dependencyNode
|
|
@@ -445,7 +445,7 @@ const rule$1 = {
|
|
|
445
445
|
});
|
|
446
446
|
});
|
|
447
447
|
if (setStateInsideEffectWithoutDeps) {
|
|
448
|
-
const { suggestedDependencies } = collectRecommendations({
|
|
448
|
+
const { suggestedDependencies } = collectRecommendations$1({
|
|
449
449
|
dependencies,
|
|
450
450
|
declaredDependencies: [],
|
|
451
451
|
stableDependencies,
|
|
@@ -495,7 +495,7 @@ const rule$1 = {
|
|
|
495
495
|
});
|
|
496
496
|
let declaredDependency;
|
|
497
497
|
try {
|
|
498
|
-
declaredDependency = analyzePropertyChain(declaredDependencyNode, null);
|
|
498
|
+
declaredDependency = analyzePropertyChain$1(declaredDependencyNode, null);
|
|
499
499
|
} catch (error) {
|
|
500
500
|
if (error instanceof Error && /Unsupported node type/.test(error.message)) {
|
|
501
501
|
if (declaredDependencyNode.type === "Literal") {
|
|
@@ -523,7 +523,7 @@ const rule$1 = {
|
|
|
523
523
|
});
|
|
524
524
|
if (!isDeclaredInComponent) externalDependencies.add(declaredDependency);
|
|
525
525
|
});
|
|
526
|
-
const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies } = collectRecommendations({
|
|
526
|
+
const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies } = collectRecommendations$1({
|
|
527
527
|
dependencies,
|
|
528
528
|
declaredDependencies,
|
|
529
529
|
stableDependencies,
|
|
@@ -532,7 +532,7 @@ const rule$1 = {
|
|
|
532
532
|
});
|
|
533
533
|
let suggestedDeps = suggestedDependencies;
|
|
534
534
|
if (duplicateDependencies.size + missingDependencies.size + unnecessaryDependencies.size === 0) {
|
|
535
|
-
scanForConstructions({
|
|
535
|
+
scanForConstructions$1({
|
|
536
536
|
declaredDependencies,
|
|
537
537
|
declaredDependenciesNode,
|
|
538
538
|
componentScope,
|
|
@@ -560,7 +560,7 @@ const rule$1 = {
|
|
|
560
560
|
});
|
|
561
561
|
return;
|
|
562
562
|
}
|
|
563
|
-
if (!isEffect && missingDependencies.size > 0) suggestedDeps = collectRecommendations({
|
|
563
|
+
if (!isEffect && missingDependencies.size > 0) suggestedDeps = collectRecommendations$1({
|
|
564
564
|
dependencies,
|
|
565
565
|
declaredDependencies: [],
|
|
566
566
|
stableDependencies,
|
|
@@ -589,7 +589,7 @@ const rule$1 = {
|
|
|
589
589
|
}
|
|
590
590
|
function getWarningMessage(deps, singlePrefix, label, fixVerb) {
|
|
591
591
|
if (deps.size === 0) return null;
|
|
592
|
-
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.`;
|
|
593
593
|
}
|
|
594
594
|
let extraWarning = "";
|
|
595
595
|
if (unnecessaryDependencies.size > 0) {
|
|
@@ -611,7 +611,7 @@ const rule$1 = {
|
|
|
611
611
|
if (!Array.isArray(refs)) return;
|
|
612
612
|
let isPropsOnlyUsedInMembers = true;
|
|
613
613
|
for (const ref of refs) {
|
|
614
|
-
const id = fastFindReferenceWithParent(componentScope.block, ref.identifier);
|
|
614
|
+
const id = fastFindReferenceWithParent$1(componentScope.block, ref.identifier);
|
|
615
615
|
if (!id) {
|
|
616
616
|
isPropsOnlyUsedInMembers = false;
|
|
617
617
|
break;
|
|
@@ -719,11 +719,11 @@ const rule$1 = {
|
|
|
719
719
|
});
|
|
720
720
|
}
|
|
721
721
|
function visitCallExpression(node) {
|
|
722
|
-
const callbackIndex = getReactiveHookCallbackIndex(node.callee, options);
|
|
722
|
+
const callbackIndex = getReactiveHookCallbackIndex$1(node.callee, options);
|
|
723
723
|
if (callbackIndex === -1) return;
|
|
724
724
|
let callback = node.arguments[callbackIndex];
|
|
725
725
|
const reactiveHook = node.callee;
|
|
726
|
-
const nodeWithoutNamespace = getNodeWithoutReactNamespace$
|
|
726
|
+
const nodeWithoutNamespace = getNodeWithoutReactNamespace$2(reactiveHook);
|
|
727
727
|
const reactiveHookName = "name" in nodeWithoutNamespace ? nodeWithoutNamespace.name : "";
|
|
728
728
|
const maybeNode = node.arguments[callbackIndex + 1];
|
|
729
729
|
const declaredDependenciesNode = maybeNode && !(maybeNode.type === "Identifier" && maybeNode.name === "undefined") ? maybeNode : void 0;
|
|
@@ -763,7 +763,7 @@ const rule$1 = {
|
|
|
763
763
|
if (def.type === "Parameter") {
|
|
764
764
|
reportProblem({
|
|
765
765
|
node: reactiveHook,
|
|
766
|
-
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
766
|
+
message: getUnknownDependenciesMessage$1(reactiveHookName)
|
|
767
767
|
});
|
|
768
768
|
return;
|
|
769
769
|
}
|
|
@@ -786,7 +786,7 @@ const rule$1 = {
|
|
|
786
786
|
default:
|
|
787
787
|
reportProblem({
|
|
788
788
|
node: reactiveHook,
|
|
789
|
-
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
789
|
+
message: getUnknownDependenciesMessage$1(reactiveHookName)
|
|
790
790
|
});
|
|
791
791
|
return;
|
|
792
792
|
}
|
|
@@ -804,7 +804,7 @@ const rule$1 = {
|
|
|
804
804
|
return { CallExpression: visitCallExpression };
|
|
805
805
|
}
|
|
806
806
|
};
|
|
807
|
-
function collectRecommendations({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect }) {
|
|
807
|
+
function collectRecommendations$1({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect }) {
|
|
808
808
|
const depTree = createDepTree();
|
|
809
809
|
function createDepTree() {
|
|
810
810
|
return {
|
|
@@ -890,7 +890,7 @@ function collectRecommendations({ dependencies, declaredDependencies, stableDepe
|
|
|
890
890
|
missingDependencies
|
|
891
891
|
};
|
|
892
892
|
}
|
|
893
|
-
function getConstructionExpressionType(node) {
|
|
893
|
+
function getConstructionExpressionType$1(node) {
|
|
894
894
|
switch (node.type) {
|
|
895
895
|
case "ObjectExpression": return "object";
|
|
896
896
|
case "ArrayExpression": return "array";
|
|
@@ -898,15 +898,15 @@ function getConstructionExpressionType(node) {
|
|
|
898
898
|
case "FunctionExpression": return "function";
|
|
899
899
|
case "ClassExpression": return "class";
|
|
900
900
|
case "ConditionalExpression":
|
|
901
|
-
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";
|
|
902
902
|
return null;
|
|
903
903
|
case "LogicalExpression":
|
|
904
|
-
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";
|
|
905
905
|
return null;
|
|
906
906
|
case "JSXFragment": return "JSX fragment";
|
|
907
907
|
case "JSXElement": return "JSX element";
|
|
908
908
|
case "AssignmentExpression":
|
|
909
|
-
if (getConstructionExpressionType(node.right) != null) return "assignment expression";
|
|
909
|
+
if (getConstructionExpressionType$1(node.right) != null) return "assignment expression";
|
|
910
910
|
return null;
|
|
911
911
|
case "NewExpression": return "object construction";
|
|
912
912
|
case "Literal":
|
|
@@ -914,18 +914,18 @@ function getConstructionExpressionType(node) {
|
|
|
914
914
|
return null;
|
|
915
915
|
case "TypeCastExpression":
|
|
916
916
|
case "AsExpression":
|
|
917
|
-
case "TSAsExpression": return getConstructionExpressionType(node.expression);
|
|
917
|
+
case "TSAsExpression": return getConstructionExpressionType$1(node.expression);
|
|
918
918
|
}
|
|
919
919
|
return null;
|
|
920
920
|
}
|
|
921
|
-
function scanForConstructions({ declaredDependencies, declaredDependenciesNode, componentScope, scope }) {
|
|
921
|
+
function scanForConstructions$1({ declaredDependencies, declaredDependenciesNode, componentScope, scope }) {
|
|
922
922
|
const constructions = declaredDependencies.map(({ key }) => {
|
|
923
923
|
const ref = componentScope.variables.find((v) => v.name === key);
|
|
924
924
|
if (ref == null) return null;
|
|
925
925
|
const node = ref.defs[0];
|
|
926
926
|
if (node == null) return null;
|
|
927
927
|
if (node.type === "Variable" && node.node.type === "VariableDeclarator" && node.node.id.type === "Identifier" && node.node.init != null) {
|
|
928
|
-
const constantExpressionType = getConstructionExpressionType(node.node.init);
|
|
928
|
+
const constantExpressionType = getConstructionExpressionType$1(node.node.init);
|
|
929
929
|
if (constantExpressionType) return [ref, constantExpressionType];
|
|
930
930
|
}
|
|
931
931
|
if (node.type === "FunctionName" && node.node.type === "FunctionDeclaration") return [ref, "function"];
|
|
@@ -945,7 +945,7 @@ function scanForConstructions({ declaredDependencies, declaredDependenciesNode,
|
|
|
945
945
|
let currentScope = reference.from;
|
|
946
946
|
while (currentScope !== scope && currentScope != null) currentScope = currentScope.upper;
|
|
947
947
|
if (currentScope !== scope) {
|
|
948
|
-
if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) return true;
|
|
948
|
+
if (!isAncestorNodeOf$1(declaredDependenciesNode, reference.identifier)) return true;
|
|
949
949
|
}
|
|
950
950
|
}
|
|
951
951
|
return false;
|
|
@@ -956,45 +956,45 @@ function scanForConstructions({ declaredDependencies, declaredDependenciesNode,
|
|
|
956
956
|
isUsedOutsideOfHook: isUsedOutsideOfHook(ref)
|
|
957
957
|
}));
|
|
958
958
|
}
|
|
959
|
-
function getDependency(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(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);
|
|
961
961
|
else if (node.type === "MemberExpression" && node.parent && node.parent.type === "AssignmentExpression" && node.parent.left === node) return node.object;
|
|
962
962
|
else return node;
|
|
963
963
|
}
|
|
964
|
-
function markNode(node, optionalChains, result) {
|
|
964
|
+
function markNode$1(node, optionalChains, result) {
|
|
965
965
|
if (optionalChains) {
|
|
966
966
|
if ("optional" in node && node.optional) {
|
|
967
967
|
if (!optionalChains.has(result)) optionalChains.set(result, true);
|
|
968
968
|
} else optionalChains.set(result, false);
|
|
969
969
|
}
|
|
970
970
|
}
|
|
971
|
-
function analyzePropertyChain(node, optionalChains) {
|
|
971
|
+
function analyzePropertyChain$1(node, optionalChains) {
|
|
972
972
|
if (node.type === "Identifier" || node.type === "JSXIdentifier") {
|
|
973
973
|
const result = node.name;
|
|
974
974
|
if (optionalChains) optionalChains.set(result, false);
|
|
975
975
|
return result;
|
|
976
976
|
} else if (node.type === "MemberExpression" && !node.computed) {
|
|
977
|
-
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
978
|
-
markNode(node, optionalChains, result);
|
|
977
|
+
const result = `${analyzePropertyChain$1(node.object, optionalChains)}.${analyzePropertyChain$1(node.property, null)}`;
|
|
978
|
+
markNode$1(node, optionalChains, result);
|
|
979
979
|
return result;
|
|
980
980
|
} else if (node.type === "OptionalMemberExpression" && !node.computed) {
|
|
981
|
-
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
982
|
-
markNode(node, optionalChains, result);
|
|
981
|
+
const result = `${analyzePropertyChain$1(node.object, optionalChains)}.${analyzePropertyChain$1(node.property, null)}`;
|
|
982
|
+
markNode$1(node, optionalChains, result);
|
|
983
983
|
return result;
|
|
984
984
|
} else if (node.type === "ChainExpression" && (!("computed" in node) || !node.computed)) {
|
|
985
985
|
const expression = node.expression;
|
|
986
986
|
if (expression.type === "CallExpression") throw new Error(`Unsupported node type: ${expression.type}`);
|
|
987
|
-
const result = `${analyzePropertyChain(expression.object, optionalChains)}.${analyzePropertyChain(expression.property, null)}`;
|
|
988
|
-
markNode(expression, optionalChains, result);
|
|
987
|
+
const result = `${analyzePropertyChain$1(expression.object, optionalChains)}.${analyzePropertyChain$1(expression.property, null)}`;
|
|
988
|
+
markNode$1(expression, optionalChains, result);
|
|
989
989
|
return result;
|
|
990
990
|
} else throw new Error(`Unsupported node type: ${node.type}`);
|
|
991
991
|
}
|
|
992
|
-
function getNodeWithoutReactNamespace$
|
|
992
|
+
function getNodeWithoutReactNamespace$2(node) {
|
|
993
993
|
if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "React" && node.property.type === "Identifier" && !node.computed) return node.property;
|
|
994
994
|
return node;
|
|
995
995
|
}
|
|
996
|
-
function getReactiveHookCallbackIndex(calleeNode, options) {
|
|
997
|
-
const node = getNodeWithoutReactNamespace$
|
|
996
|
+
function getReactiveHookCallbackIndex$1(calleeNode, options) {
|
|
997
|
+
const node = getNodeWithoutReactNamespace$2(calleeNode);
|
|
998
998
|
if (node.type !== "Identifier") return -1;
|
|
999
999
|
switch (node.name) {
|
|
1000
1000
|
case "useEffect":
|
|
@@ -1005,7 +1005,7 @@ function getReactiveHookCallbackIndex(calleeNode, options) {
|
|
|
1005
1005
|
default: if (node === calleeNode && options && options.additionalHooks) {
|
|
1006
1006
|
let name;
|
|
1007
1007
|
try {
|
|
1008
|
-
name = analyzePropertyChain(node, null);
|
|
1008
|
+
name = analyzePropertyChain$1(node, null);
|
|
1009
1009
|
} catch (error) {
|
|
1010
1010
|
if (error instanceof Error && /Unsupported node type/.test(error.message)) return 0;
|
|
1011
1011
|
else throw error;
|
|
@@ -1014,20 +1014,20 @@ function getReactiveHookCallbackIndex(calleeNode, options) {
|
|
|
1014
1014
|
} else return -1;
|
|
1015
1015
|
}
|
|
1016
1016
|
}
|
|
1017
|
-
function fastFindReferenceWithParent(start, target) {
|
|
1017
|
+
function fastFindReferenceWithParent$1(start, target) {
|
|
1018
1018
|
const queue = [start];
|
|
1019
1019
|
let item;
|
|
1020
1020
|
while (queue.length) {
|
|
1021
1021
|
item = queue.shift();
|
|
1022
|
-
if (isSameIdentifier(item, target)) return item;
|
|
1023
|
-
if (!isAncestorNodeOf(item, target)) continue;
|
|
1022
|
+
if (isSameIdentifier$1(item, target)) return item;
|
|
1023
|
+
if (!isAncestorNodeOf$1(item, target)) continue;
|
|
1024
1024
|
for (const [key, value] of Object.entries(item)) {
|
|
1025
1025
|
if (key === "parent") continue;
|
|
1026
|
-
if (isNodeLike(value)) {
|
|
1026
|
+
if (isNodeLike$1(value)) {
|
|
1027
1027
|
value.parent = item;
|
|
1028
1028
|
queue.push(value);
|
|
1029
1029
|
} else if (Array.isArray(value)) value.forEach((val) => {
|
|
1030
|
-
if (isNodeLike(val)) {
|
|
1030
|
+
if (isNodeLike$1(val)) {
|
|
1031
1031
|
val.parent = item;
|
|
1032
1032
|
queue.push(val);
|
|
1033
1033
|
}
|
|
@@ -1036,7 +1036,7 @@ function fastFindReferenceWithParent(start, target) {
|
|
|
1036
1036
|
}
|
|
1037
1037
|
return null;
|
|
1038
1038
|
}
|
|
1039
|
-
function joinEnglish(arr) {
|
|
1039
|
+
function joinEnglish$1(arr) {
|
|
1040
1040
|
let s = "";
|
|
1041
1041
|
for (let i = 0; i < arr.length; i++) {
|
|
1042
1042
|
s += arr[i];
|
|
@@ -1046,19 +1046,19 @@ function joinEnglish(arr) {
|
|
|
1046
1046
|
}
|
|
1047
1047
|
return s;
|
|
1048
1048
|
}
|
|
1049
|
-
function isNodeLike(val) {
|
|
1049
|
+
function isNodeLike$1(val) {
|
|
1050
1050
|
return typeof val === "object" && val !== null && !Array.isArray(val) && "type" in val && typeof val.type === "string";
|
|
1051
1051
|
}
|
|
1052
|
-
function isSameIdentifier(a, b) {
|
|
1052
|
+
function isSameIdentifier$1(a, b) {
|
|
1053
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];
|
|
1054
1054
|
}
|
|
1055
|
-
function isAncestorNodeOf(a, b) {
|
|
1055
|
+
function isAncestorNodeOf$1(a, b) {
|
|
1056
1056
|
return !!a.range && !!b.range && a.range[0] <= b.range[0] && a.range[1] >= b.range[1];
|
|
1057
1057
|
}
|
|
1058
|
-
function isUseEffectEventIdentifier$
|
|
1058
|
+
function isUseEffectEventIdentifier$2(node) {
|
|
1059
1059
|
return node.type === "Identifier" && node.name === "useEffectEvent";
|
|
1060
1060
|
}
|
|
1061
|
-
function getUnknownDependenciesMessage(reactiveHookName) {
|
|
1061
|
+
function getUnknownDependenciesMessage$1(reactiveHookName) {
|
|
1062
1062
|
return `React Hook ${reactiveHookName} received a function whose dependencies are unknown. Pass an inline function instead.`;
|
|
1063
1063
|
}
|
|
1064
1064
|
// src/rules/globals/helpers.ts
|
|
@@ -1160,14 +1160,13 @@ function resolveGlobalOrigin(context, node, seen = /* @__PURE__ */ new Set()) {
|
|
|
1160
1160
|
if (initializer.type !== AST_NODE_TYPES.Identifier && initializer.type !== AST_NODE_TYPES.MemberExpression) return null;
|
|
1161
1161
|
return resolveGlobalOrigin(context, initializer, seen);
|
|
1162
1162
|
}
|
|
1163
|
-
function resolveToFunction(context, node
|
|
1163
|
+
function resolveToFunction(context, node) {
|
|
1164
1164
|
const expression = Extract.unwrap(node);
|
|
1165
1165
|
if (Check.isFunction(expression)) return expression;
|
|
1166
|
-
if (!Check.isIdentifier(expression)
|
|
1167
|
-
|
|
1168
|
-
const
|
|
1169
|
-
|
|
1170
|
-
return resolveToFunction(context, resolved, seen);
|
|
1166
|
+
if (!Check.isIdentifier(expression)) return null;
|
|
1167
|
+
const origin = resolveOriginChain(context, expression);
|
|
1168
|
+
const unwrapped = origin == null ? null : Extract.unwrap(origin);
|
|
1169
|
+
return unwrapped != null && Check.isFunction(unwrapped) ? unwrapped : null;
|
|
1171
1170
|
}
|
|
1172
1171
|
// src/rules/globals/effects.ts
|
|
1173
1172
|
function inferGlobalMutations(context, facts) {
|
|
@@ -1255,10 +1254,10 @@ function create$49(context) {
|
|
|
1255
1254
|
const comps = core.getFunctionComponentCollector(context);
|
|
1256
1255
|
const facts = createFactCollector$6();
|
|
1257
1256
|
return merge(hooks.visitor, comps.visitor, facts.visitor, { "Program:exit"(program) {
|
|
1258
|
-
const
|
|
1257
|
+
const funcs = [...comps.api.getAllComponents(program), ...hooks.api.getAllHooks(program)].map(({ node }) => node);
|
|
1259
1258
|
const directEffects = inferGlobalMutations(context, facts.facts);
|
|
1260
1259
|
const callGraph = inferCallGraph$1(context, facts.facts.callEdges);
|
|
1261
|
-
for (const effect of collectReachableEffects(
|
|
1260
|
+
for (const effect of collectReachableEffects(funcs, directEffects, callGraph)) {
|
|
1262
1261
|
const data = effect.method == null ? { name: effect.name } : {
|
|
1263
1262
|
name: effect.name,
|
|
1264
1263
|
method: effect.method
|
|
@@ -1408,13 +1407,13 @@ function resolveVariableOrigin(context, variable, mode = "alias", seen = /* @__P
|
|
|
1408
1407
|
const source = findVariable(context.sourceCode.getScope(init), init);
|
|
1409
1408
|
return source == null ? variable : resolveVariableOrigin(context, source, mode, seen);
|
|
1410
1409
|
}
|
|
1411
|
-
function resolveToFunctionNode(context, node
|
|
1410
|
+
function resolveToFunctionNode(context, node) {
|
|
1412
1411
|
const expr = Extract.unwrap(node);
|
|
1413
1412
|
if (Check.isFunction(expr)) return expr;
|
|
1414
|
-
if (!Check.isIdentifier(expr)
|
|
1415
|
-
|
|
1416
|
-
const
|
|
1417
|
-
return
|
|
1413
|
+
if (!Check.isIdentifier(expr)) return null;
|
|
1414
|
+
const origin = resolveOriginChain(context, expr);
|
|
1415
|
+
const unwrapped = origin == null ? null : Extract.unwrap(origin);
|
|
1416
|
+
return unwrapped != null && Check.isFunction(unwrapped) ? unwrapped : null;
|
|
1418
1417
|
}
|
|
1419
1418
|
function isComponentPropsDefinition(def, components) {
|
|
1420
1419
|
if (def.type !== DefinitionType.Parameter) return false;
|
|
@@ -1727,7 +1726,7 @@ function isArrayIndexReference(context, node) {
|
|
|
1727
1726
|
if (call.arguments[callbackPosition] !== argument) return false;
|
|
1728
1727
|
const param = callback.params[indexPosition];
|
|
1729
1728
|
if (param == null) return false;
|
|
1730
|
-
return param
|
|
1729
|
+
return (param.type === AST_NODE_TYPES.AssignmentPattern ? param.left : param) === def.name;
|
|
1731
1730
|
}
|
|
1732
1731
|
function getIdentifiersFromBinaryExpression(side) {
|
|
1733
1732
|
if (Check.isIdentifier(side)) return [side];
|
|
@@ -1749,9 +1748,10 @@ function create$46(context) {
|
|
|
1749
1748
|
return node != null && Check.isIdentifier(node) && isArrayIndexReference(context, node);
|
|
1750
1749
|
}
|
|
1751
1750
|
function getPropsObject(node) {
|
|
1752
|
-
const
|
|
1753
|
-
if (
|
|
1751
|
+
const call = parseCreateElementCall(context, node);
|
|
1752
|
+
if (call != null) return call.propsObject;
|
|
1754
1753
|
if (!core.isCloneElementCall(context, node)) return null;
|
|
1754
|
+
const props = node.arguments[1];
|
|
1755
1755
|
return props?.type === AST_NODE_TYPES.ObjectExpression ? props : null;
|
|
1756
1756
|
}
|
|
1757
1757
|
function visitKeyExpression(node) {
|
|
@@ -1815,6 +1815,7 @@ var no_children_count_default = createRule({
|
|
|
1815
1815
|
create: create$45
|
|
1816
1816
|
});
|
|
1817
1817
|
function create$45(context) {
|
|
1818
|
+
if (!context.sourceCode.text.includes("Children")) return {};
|
|
1818
1819
|
return { MemberExpression(node) {
|
|
1819
1820
|
if (core.isChildrenCount(context, node)) context.report({
|
|
1820
1821
|
messageId: "default",
|
|
@@ -1833,6 +1834,7 @@ var no_children_for_each_default = createRule({
|
|
|
1833
1834
|
create: create$44
|
|
1834
1835
|
});
|
|
1835
1836
|
function create$44(context) {
|
|
1837
|
+
if (!context.sourceCode.text.includes("Children")) return {};
|
|
1836
1838
|
return { MemberExpression(node) {
|
|
1837
1839
|
if (core.isChildrenForEach(context, node)) context.report({
|
|
1838
1840
|
messageId: "default",
|
|
@@ -1851,6 +1853,7 @@ var no_children_map_default = createRule({
|
|
|
1851
1853
|
create: create$43
|
|
1852
1854
|
});
|
|
1853
1855
|
function create$43(context) {
|
|
1856
|
+
if (!context.sourceCode.text.includes("Children")) return {};
|
|
1854
1857
|
return { MemberExpression(node) {
|
|
1855
1858
|
if (core.isChildrenMap(context, node)) context.report({
|
|
1856
1859
|
messageId: "default",
|
|
@@ -1869,6 +1872,7 @@ var no_children_only_default = createRule({
|
|
|
1869
1872
|
create: create$42
|
|
1870
1873
|
});
|
|
1871
1874
|
function create$42(context) {
|
|
1875
|
+
if (!context.sourceCode.text.includes("Children")) return {};
|
|
1872
1876
|
return { MemberExpression(node) {
|
|
1873
1877
|
if (core.isChildrenOnly(context, node)) context.report({
|
|
1874
1878
|
messageId: "default",
|
|
@@ -1887,6 +1891,7 @@ var no_children_to_array_default = createRule({
|
|
|
1887
1891
|
create: create$41
|
|
1888
1892
|
});
|
|
1889
1893
|
function create$41(context) {
|
|
1894
|
+
if (!context.sourceCode.text.includes("Children")) return {};
|
|
1890
1895
|
return { MemberExpression(node) {
|
|
1891
1896
|
if (core.isChildrenToArray(context, node)) context.report({
|
|
1892
1897
|
messageId: "default",
|
|
@@ -1997,7 +2002,7 @@ function memoize(f) {
|
|
|
1997
2002
|
function not(predicate) {
|
|
1998
2003
|
return (data) => !predicate(data);
|
|
1999
2004
|
}
|
|
2000
|
-
|
|
2005
|
+
dual(2, (a, b) => (data) => a(data) && b(data));
|
|
2001
2006
|
const or = dual(2, (a, b) => (data) => a(data) || b(data));
|
|
2002
2007
|
dual(2, (a, b) => (data) => a(data) !== b(data));
|
|
2003
2008
|
dual(2, (a, b) => (data) => a(data) === b(data));
|
|
@@ -2070,6 +2075,7 @@ var no_clone_element_default = createRule({
|
|
|
2070
2075
|
create: create$39
|
|
2071
2076
|
});
|
|
2072
2077
|
function create$39(context) {
|
|
2078
|
+
if (!context.sourceCode.text.includes("cloneElement")) return {};
|
|
2073
2079
|
return { CallExpression(node) {
|
|
2074
2080
|
if (core.isCloneElementCall(context, node)) context.report({
|
|
2075
2081
|
messageId: "default",
|
|
@@ -2247,6 +2253,20 @@ var no_direct_mutation_state_default = createRule({
|
|
|
2247
2253
|
name: "no-direct-mutation-state",
|
|
2248
2254
|
create: create$33
|
|
2249
2255
|
});
|
|
2256
|
+
function create$33(context) {
|
|
2257
|
+
if (!context.sourceCode.text.includes("Component")) return {};
|
|
2258
|
+
return { AssignmentExpression(node) {
|
|
2259
|
+
if (!isAssignmentToThisState(node)) return;
|
|
2260
|
+
const fact = Traverse.findParent(node, Check.isClass);
|
|
2261
|
+
if (fact == null || !core.isClassComponent(fact)) return;
|
|
2262
|
+
const constructor = Traverse.findParent(node, isConstructorFunction);
|
|
2263
|
+
if (Traverse.findParent(node, Check.isFunctionOrClass) === constructor) return;
|
|
2264
|
+
context.report({
|
|
2265
|
+
messageId: "default",
|
|
2266
|
+
node
|
|
2267
|
+
});
|
|
2268
|
+
} };
|
|
2269
|
+
}
|
|
2250
2270
|
function isConstructorFunction(node) {
|
|
2251
2271
|
return Check.isOneOf([AST_NODE_TYPES.FunctionDeclaration, AST_NODE_TYPES.FunctionExpression])(node) && Check.isPropertyOrMethod(node.parent) && Check.isIdentifier(node.parent.key, "constructor");
|
|
2252
2272
|
}
|
|
@@ -2261,17 +2281,6 @@ function isAssignmentToThisState(node) {
|
|
|
2261
2281
|
}
|
|
2262
2282
|
return false;
|
|
2263
2283
|
}
|
|
2264
|
-
function create$33(context) {
|
|
2265
|
-
return { AssignmentExpression(node) {
|
|
2266
|
-
if (!isAssignmentToThisState(node)) return;
|
|
2267
|
-
const fact = Traverse.findParent(node, Check.isClass);
|
|
2268
|
-
if (fact == null) return;
|
|
2269
|
-
if (core.isClassComponent(fact) && context.sourceCode.getScope(node).block !== Traverse.findParent(node, isConstructorFunction)) context.report({
|
|
2270
|
-
messageId: "default",
|
|
2271
|
-
node
|
|
2272
|
-
});
|
|
2273
|
-
} };
|
|
2274
|
-
}
|
|
2275
2284
|
var no_duplicate_key_default = createRule({
|
|
2276
2285
|
meta: {
|
|
2277
2286
|
type: "problem",
|
|
@@ -2283,13 +2292,20 @@ var no_duplicate_key_default = createRule({
|
|
|
2283
2292
|
create: create$32
|
|
2284
2293
|
});
|
|
2285
2294
|
function create$32(context) {
|
|
2286
|
-
if (
|
|
2287
|
-
const
|
|
2288
|
-
function
|
|
2289
|
-
const
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2295
|
+
if (!/\bkey\b/u.test(context.sourceCode.text)) return {};
|
|
2296
|
+
const keyGroups = /* @__PURE__ */ new Map();
|
|
2297
|
+
function recordSiblingKey(root, key) {
|
|
2298
|
+
const prevKeys = keyGroups.get(root)?.keys ?? [];
|
|
2299
|
+
keyGroups.set(root, {
|
|
2300
|
+
hasDuplicate: prevKeys.some((prevKey) => isKeyValueEqual(prevKey, key)),
|
|
2301
|
+
keys: [...prevKeys, key]
|
|
2302
|
+
});
|
|
2303
|
+
}
|
|
2304
|
+
function recordMapCallbackKey(call, key) {
|
|
2305
|
+
keyGroups.set(call, {
|
|
2306
|
+
hasDuplicate: key.value?.type === AST_NODE_TYPES.Literal,
|
|
2307
|
+
keys: [key]
|
|
2308
|
+
});
|
|
2293
2309
|
}
|
|
2294
2310
|
return {
|
|
2295
2311
|
"JSXAttribute[name.name='key']"(node) {
|
|
@@ -2297,16 +2313,9 @@ function create$32(context) {
|
|
|
2297
2313
|
switch (jsxElement.parent.type) {
|
|
2298
2314
|
case AST_NODE_TYPES.ArrayExpression:
|
|
2299
2315
|
case AST_NODE_TYPES.JSXElement:
|
|
2300
|
-
case AST_NODE_TYPES.JSXFragment:
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
keyedEntries.set(root, {
|
|
2304
|
-
hasDuplicate: prevKeys.some((prevKey) => isKeyValueEqual(prevKey, node)),
|
|
2305
|
-
keys: [...prevKeys, node],
|
|
2306
|
-
root: jsxElement.parent
|
|
2307
|
-
});
|
|
2308
|
-
break;
|
|
2309
|
-
}
|
|
2316
|
+
case AST_NODE_TYPES.JSXFragment:
|
|
2317
|
+
recordSiblingKey(jsxElement.parent, node);
|
|
2318
|
+
return;
|
|
2310
2319
|
default: {
|
|
2311
2320
|
const call = Traverse.findParent(jsxElement, (n) => {
|
|
2312
2321
|
if (n.type !== AST_NODE_TYPES.CallExpression) return false;
|
|
@@ -2315,21 +2324,15 @@ function create$32(context) {
|
|
|
2315
2324
|
return Check.isIdentifier(callee.property, "map");
|
|
2316
2325
|
});
|
|
2317
2326
|
if (call == null) return;
|
|
2318
|
-
const
|
|
2319
|
-
if (
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
if (Extract.unwrap(arg0) !== iter) return;
|
|
2323
|
-
keyedEntries.set(call, {
|
|
2324
|
-
hasDuplicate: node.value?.type === AST_NODE_TYPES.Literal,
|
|
2325
|
-
keys: [node],
|
|
2326
|
-
root: call
|
|
2327
|
-
});
|
|
2327
|
+
const callback = call.arguments[0];
|
|
2328
|
+
if (callback == null) return;
|
|
2329
|
+
if (Traverse.findParent(jsxElement, Check.isFunction, (n) => n === call) !== Extract.unwrap(callback)) return;
|
|
2330
|
+
recordMapCallbackKey(call, node);
|
|
2328
2331
|
}
|
|
2329
2332
|
}
|
|
2330
2333
|
},
|
|
2331
2334
|
"Program:exit"() {
|
|
2332
|
-
for (const { hasDuplicate, keys } of
|
|
2335
|
+
for (const { hasDuplicate, keys } of keyGroups.values()) {
|
|
2333
2336
|
if (!hasDuplicate) continue;
|
|
2334
2337
|
for (const key of keys) context.report({
|
|
2335
2338
|
messageId: "default",
|
|
@@ -2339,6 +2342,12 @@ function create$32(context) {
|
|
|
2339
2342
|
}
|
|
2340
2343
|
};
|
|
2341
2344
|
}
|
|
2345
|
+
function isKeyValueEqual(a, b) {
|
|
2346
|
+
const aValue = a.value;
|
|
2347
|
+
const bValue = b.value;
|
|
2348
|
+
if (aValue == null || bValue == null) return false;
|
|
2349
|
+
return Compare.isEqual(aValue, bValue);
|
|
2350
|
+
}
|
|
2342
2351
|
var no_forward_ref_default = createRule({
|
|
2343
2352
|
meta: {
|
|
2344
2353
|
type: "suggestion",
|
|
@@ -2466,6 +2475,7 @@ var no_implicit_children_default = createRule({
|
|
|
2466
2475
|
create: create$30
|
|
2467
2476
|
});
|
|
2468
2477
|
function create$30(context) {
|
|
2478
|
+
if (!context.sourceCode.text.includes("...")) return {};
|
|
2469
2479
|
return createImplicitPropListener(context, {
|
|
2470
2480
|
name: "children",
|
|
2471
2481
|
isAllowedProp: (fqn) => fqn.endsWith("attributes.children") || fqn.endsWith("propswithchildren.children"),
|
|
@@ -2489,6 +2499,7 @@ var no_implicit_key_default = createRule({
|
|
|
2489
2499
|
create: create$29
|
|
2490
2500
|
});
|
|
2491
2501
|
function create$29(context) {
|
|
2502
|
+
if (!context.sourceCode.text.includes("...")) return {};
|
|
2492
2503
|
return createImplicitPropListener(context, {
|
|
2493
2504
|
name: "key",
|
|
2494
2505
|
isAllowedProp: (fqn) => fqn.endsWith("react.attributes.key"),
|
|
@@ -2515,6 +2526,7 @@ var no_implicit_ref_default = createRule({
|
|
|
2515
2526
|
create: create$28
|
|
2516
2527
|
});
|
|
2517
2528
|
function create$28(context) {
|
|
2529
|
+
if (!context.sourceCode.text.includes("...")) return {};
|
|
2518
2530
|
return createImplicitPropListener(context, {
|
|
2519
2531
|
name: "ref",
|
|
2520
2532
|
isAllowedProp: (fqn) => fqn.endsWith("attributes.ref"),
|
|
@@ -2659,7 +2671,20 @@ function create$25(context) {
|
|
|
2659
2671
|
})) context.report({
|
|
2660
2672
|
fix(fixer) {
|
|
2661
2673
|
if (id.type !== AST_NODE_TYPES.Identifier || id.parent !== call.parent) return [];
|
|
2662
|
-
|
|
2674
|
+
const declaration = id.parent.parent;
|
|
2675
|
+
if (declaration == null || declaration.type !== AST_NODE_TYPES.VariableDeclaration) return [];
|
|
2676
|
+
switch (declaration.parent.type) {
|
|
2677
|
+
case AST_NODE_TYPES.BlockStatement:
|
|
2678
|
+
case AST_NODE_TYPES.ExportNamedDeclaration:
|
|
2679
|
+
case AST_NODE_TYPES.Program:
|
|
2680
|
+
case AST_NODE_TYPES.StaticBlock:
|
|
2681
|
+
case AST_NODE_TYPES.SwitchCase:
|
|
2682
|
+
case AST_NODE_TYPES.TSModuleBlock: break;
|
|
2683
|
+
default: return [];
|
|
2684
|
+
}
|
|
2685
|
+
const lastToken = context.sourceCode.getLastToken(declaration);
|
|
2686
|
+
if (lastToken == null) return [];
|
|
2687
|
+
return fixer.insertTextAfter(lastToken, [
|
|
2663
2688
|
"\n",
|
|
2664
2689
|
id.name,
|
|
2665
2690
|
".",
|
|
@@ -2678,21 +2703,23 @@ function create$25(context) {
|
|
|
2678
2703
|
}
|
|
2679
2704
|
};
|
|
2680
2705
|
}
|
|
2681
|
-
// src/
|
|
2706
|
+
// src/utils/jsx-iterator.ts
|
|
2682
2707
|
const KNOWN_CALLBACK_POSITIONS = /* @__PURE__ */ new Map([
|
|
2683
2708
|
["flatMap", 0],
|
|
2684
2709
|
["from", 1],
|
|
2685
2710
|
["map", 0]
|
|
2686
2711
|
]);
|
|
2687
|
-
function
|
|
2688
|
-
const
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2712
|
+
function getIteratorCallback(node) {
|
|
2713
|
+
const callee = Extract.unwrap(node.callee);
|
|
2714
|
+
if (callee.type !== AST_NODE_TYPES.MemberExpression) return null;
|
|
2715
|
+
if (!Check.isIdentifier(callee.property)) return null;
|
|
2716
|
+
const position = KNOWN_CALLBACK_POSITIONS.get(callee.property.name);
|
|
2717
|
+
if (position == null) return null;
|
|
2718
|
+
const argument = node.arguments[position];
|
|
2719
|
+
if (argument == null) return null;
|
|
2720
|
+
const callback = Extract.unwrap(argument);
|
|
2721
|
+
if (!Check.isFunction(callback)) return null;
|
|
2722
|
+
return callback;
|
|
2696
2723
|
}
|
|
2697
2724
|
var no_missing_key_default = createRule({
|
|
2698
2725
|
meta: {
|
|
@@ -2707,16 +2734,6 @@ var no_missing_key_default = createRule({
|
|
|
2707
2734
|
name: "no-missing-key",
|
|
2708
2735
|
create: create$24
|
|
2709
2736
|
});
|
|
2710
|
-
function getIteratorCallback(node) {
|
|
2711
|
-
const callee = Extract.unwrap(node.callee);
|
|
2712
|
-
if (callee.type !== AST_NODE_TYPES.MemberExpression) return null;
|
|
2713
|
-
if (!Check.isIdentifier(callee.property)) return null;
|
|
2714
|
-
const position = KNOWN_CALLBACK_POSITIONS.get(callee.property.name);
|
|
2715
|
-
if (position == null) return null;
|
|
2716
|
-
const callback = node.arguments[position];
|
|
2717
|
-
if (callback == null || !Check.isFunction(callback)) return null;
|
|
2718
|
-
return callback;
|
|
2719
|
-
}
|
|
2720
2737
|
function create$24(context) {
|
|
2721
2738
|
let childrenToArrayDepth = 0;
|
|
2722
2739
|
function visitItemExpression(node) {
|
|
@@ -2727,10 +2744,13 @@ function create$24(context) {
|
|
|
2727
2744
|
case AST_NODE_TYPES.TSNonNullExpression:
|
|
2728
2745
|
case AST_NODE_TYPES.TSSatisfiesExpression:
|
|
2729
2746
|
case AST_NODE_TYPES.TSInstantiationExpression: return visitItemExpression(node.expression);
|
|
2730
|
-
case AST_NODE_TYPES.JSXElement:
|
|
2731
|
-
|
|
2732
|
-
node
|
|
2733
|
-
|
|
2747
|
+
case AST_NODE_TYPES.JSXElement:
|
|
2748
|
+
if (hasAttribute(node, "key")) return [];
|
|
2749
|
+
if (node.openingElement.attributes.some((a) => a.type === AST_NODE_TYPES.JSXSpreadAttribute)) return [];
|
|
2750
|
+
return [{
|
|
2751
|
+
messageId: "default",
|
|
2752
|
+
node
|
|
2753
|
+
}];
|
|
2734
2754
|
case AST_NODE_TYPES.JSXFragment: return [{
|
|
2735
2755
|
messageId: "unexpected-fragment-syntax",
|
|
2736
2756
|
node
|
|
@@ -2741,8 +2761,7 @@ function create$24(context) {
|
|
|
2741
2761
|
}
|
|
2742
2762
|
}
|
|
2743
2763
|
function visitIteratorCallback(node) {
|
|
2744
|
-
|
|
2745
|
-
return getReturnStatements$1(node.body).flatMap((stmt) => stmt.argument == null ? [] : visitItemExpression(stmt.argument));
|
|
2764
|
+
return Collect.getReturnExpressions(node).flatMap(visitItemExpression);
|
|
2746
2765
|
}
|
|
2747
2766
|
return {
|
|
2748
2767
|
ArrayExpression(node) {
|
|
@@ -2973,6 +2992,7 @@ var no_nested_lazy_component_declarations_default = createRule({
|
|
|
2973
2992
|
create: create$21
|
|
2974
2993
|
});
|
|
2975
2994
|
function create$21(context) {
|
|
2995
|
+
if (!context.sourceCode.text.includes("lazy")) return {};
|
|
2976
2996
|
const fc = core.getFunctionComponentCollector(context);
|
|
2977
2997
|
const cc = core.getClassComponentCollector(context);
|
|
2978
2998
|
const hc = core.getHookCollector(context);
|
|
@@ -3217,14 +3237,15 @@ function create$13(context) {
|
|
|
3217
3237
|
const constructions = /* @__PURE__ */ new WeakMap();
|
|
3218
3238
|
return merge(visitor, {
|
|
3219
3239
|
JSXOpeningElement(node) {
|
|
3220
|
-
const selfName =
|
|
3221
|
-
if (selfName
|
|
3240
|
+
const selfName = getElementSelfType(node.parent);
|
|
3241
|
+
if (selfName === "") return;
|
|
3222
3242
|
if (!isContextName(selfName, isReact18OrBelow)) return;
|
|
3223
3243
|
const enclosingFunction = Traverse.findParent(node, Check.isFunction);
|
|
3224
3244
|
if (enclosingFunction == null) return;
|
|
3225
3245
|
if (compilationMode === "annotation" && core.isFunctionHasDirective(enclosingFunction, "use memo")) return;
|
|
3226
|
-
const attribute = node.attributes.findLast(
|
|
3227
|
-
if (attribute?.
|
|
3246
|
+
const attribute = node.attributes.findLast(isPlainAttribute("value"));
|
|
3247
|
+
if (attribute?.type !== AST_NODE_TYPES.JSXAttribute) return;
|
|
3248
|
+
if (attribute.value?.type !== AST_NODE_TYPES.JSXExpressionContainer) return;
|
|
3228
3249
|
const valueExpression = attribute.value.expression;
|
|
3229
3250
|
const construction = resolveObjectType(context, valueExpression);
|
|
3230
3251
|
if (construction == null) return;
|
|
@@ -3264,35 +3285,32 @@ function getHumanReadableKind(node) {
|
|
|
3264
3285
|
}
|
|
3265
3286
|
return toLowerCase(delimiterCase(node.type, " "));
|
|
3266
3287
|
}
|
|
3267
|
-
// src/rules/no-unstable-default-props/no-unstable-default-props.ts
|
|
3268
|
-
const RULE_NAME$12 = "no-unstable-default-props";
|
|
3269
|
-
const defaultOptions$1 = [{ safeDefaultProps: [] }];
|
|
3270
|
-
const schema$1 = [{
|
|
3271
|
-
type: "object",
|
|
3272
|
-
additionalProperties: false,
|
|
3273
|
-
properties: { safeDefaultProps: {
|
|
3274
|
-
type: "array",
|
|
3275
|
-
items: { type: "string" }
|
|
3276
|
-
} }
|
|
3277
|
-
}];
|
|
3278
3288
|
var no_unstable_default_props_default = createRule({
|
|
3279
3289
|
meta: {
|
|
3280
3290
|
type: "problem",
|
|
3281
|
-
defaultOptions: [
|
|
3291
|
+
defaultOptions: [{}],
|
|
3282
3292
|
docs: { description: "Prevents using referential-type values as default props in object destructuring." },
|
|
3283
3293
|
messages: { default: "A/an '{{kind}}' as default prop. This could lead to potential infinite render loop in React. Use a variable instead of '{{kind}}'." },
|
|
3284
|
-
schema:
|
|
3294
|
+
schema: [{
|
|
3295
|
+
type: "object",
|
|
3296
|
+
additionalProperties: false,
|
|
3297
|
+
properties: { safeDefaultProps: {
|
|
3298
|
+
type: "array",
|
|
3299
|
+
description: "Property names or patterns that are safe to use as default props.",
|
|
3300
|
+
items: { type: "string" }
|
|
3301
|
+
} }
|
|
3302
|
+
}]
|
|
3285
3303
|
},
|
|
3286
|
-
name:
|
|
3304
|
+
name: "no-unstable-default-props",
|
|
3287
3305
|
create: create$12
|
|
3288
3306
|
});
|
|
3289
|
-
function create$12(context
|
|
3307
|
+
function create$12(context) {
|
|
3308
|
+
const safeDefaultProps = (context.options[0] ?? {}).safeDefaultProps ?? [];
|
|
3290
3309
|
const { compilationMode } = getSettingsFromContext(context);
|
|
3291
3310
|
if (compilationMode === "infer" || compilationMode === "all") return {};
|
|
3292
3311
|
if (compilationMode === "annotation" && context.sourceCode.ast.body.some((stmt) => Check.isDirective(stmt, "use memo"))) return {};
|
|
3293
3312
|
const { api, visitor } = core.getFunctionComponentCollector(context);
|
|
3294
3313
|
const declarators = /* @__PURE__ */ new WeakMap();
|
|
3295
|
-
const { safeDefaultProps = [] } = options;
|
|
3296
3314
|
const safePatterns = safeDefaultProps.map((s) => toRegExp(s));
|
|
3297
3315
|
return merge(visitor, {
|
|
3298
3316
|
[SEL_OBJECT_DESTRUCTURING_VARIABLE_DECLARATOR](node) {
|
|
@@ -3309,7 +3327,7 @@ function create$12(context, [options]) {
|
|
|
3309
3327
|
return declarators.get(component)?.filter((d) => d.init.name === name).flatMap((d) => d.id.properties) ?? [];
|
|
3310
3328
|
}).otherwise(() => []);
|
|
3311
3329
|
for (const prop of properties) {
|
|
3312
|
-
if (prop.type !== AST_NODE_TYPES.Property || prop.value
|
|
3330
|
+
if (prop.type !== AST_NODE_TYPES.Property || !Check.isObjectPatternElementDefault(prop.value)) continue;
|
|
3313
3331
|
const { value } = prop;
|
|
3314
3332
|
const { right } = value;
|
|
3315
3333
|
const construction = resolveObjectType(context, value);
|
|
@@ -3366,8 +3384,7 @@ function isExportedClass(node) {
|
|
|
3366
3384
|
default: return false;
|
|
3367
3385
|
}
|
|
3368
3386
|
}
|
|
3369
|
-
function isPublicMethod(
|
|
3370
|
-
const member = def.parent;
|
|
3387
|
+
function isPublicMethod(member) {
|
|
3371
3388
|
switch (member.type) {
|
|
3372
3389
|
case AST_NODE_TYPES.MethodDefinition: return member.accessibility == null || member.accessibility === "public";
|
|
3373
3390
|
case AST_NODE_TYPES.PropertyDefinition: return (member.accessibility == null || member.accessibility === "public") && (member.value?.type === AST_NODE_TYPES.ArrowFunctionExpression || member.value?.type === AST_NODE_TYPES.FunctionExpression);
|
|
@@ -3385,8 +3402,17 @@ var no_unused_class_component_members_default = createRule({
|
|
|
3385
3402
|
create: create$11
|
|
3386
3403
|
});
|
|
3387
3404
|
function create$11(context) {
|
|
3405
|
+
if (!context.sourceCode.text.includes("Component")) return {};
|
|
3388
3406
|
const propertyDefs = /* @__PURE__ */ new WeakMap();
|
|
3407
|
+
const publicMethods = /* @__PURE__ */ new WeakMap();
|
|
3389
3408
|
const propertyUsages = /* @__PURE__ */ new WeakMap();
|
|
3409
|
+
function getStaticName(key, computed) {
|
|
3410
|
+
const unwrapped = Extract.unwrap(key);
|
|
3411
|
+
if (!computed && Check.isIdentifier(unwrapped)) return unwrapped.name;
|
|
3412
|
+
if (unwrapped.type === AST_NODE_TYPES.Literal && typeof unwrapped.value === "string") return unwrapped.value;
|
|
3413
|
+
if (unwrapped.type === AST_NODE_TYPES.TemplateLiteral && unwrapped.expressions.length === 0) return unwrapped.quasis[0]?.value.cooked ?? unwrapped.quasis[0]?.value.raw ?? null;
|
|
3414
|
+
return null;
|
|
3415
|
+
}
|
|
3390
3416
|
function classExit(node) {
|
|
3391
3417
|
if (!core.isClassComponent(node)) return;
|
|
3392
3418
|
const id = core.getClassId(node);
|
|
@@ -3394,21 +3420,20 @@ function create$11(context) {
|
|
|
3394
3420
|
if (defs == null) return;
|
|
3395
3421
|
const usages = propertyUsages.get(node);
|
|
3396
3422
|
const exported = isExportedClass(node);
|
|
3397
|
-
|
|
3398
|
-
|
|
3423
|
+
const publicMembers = publicMethods.get(node);
|
|
3424
|
+
for (const [methodName, defNode] of defs) {
|
|
3399
3425
|
if (usages?.has(methodName) ?? false) continue;
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
}
|
|
3426
|
+
const isPureComponentShouldUpdate = methodName === "shouldComponentUpdate" && core.isPureComponent(node);
|
|
3427
|
+
if (LIFECYCLE_METHODS.has(methodName) && !isPureComponentShouldUpdate) continue;
|
|
3403
3428
|
if (KNOWN_HOST_CONVENTION_METHODS.has(methodName)) continue;
|
|
3404
|
-
if (exported &&
|
|
3429
|
+
if (exported && (publicMembers?.has(methodName) ?? false)) continue;
|
|
3405
3430
|
context.report({
|
|
3406
3431
|
data: {
|
|
3407
3432
|
className: id != null ? getText(context, id) : "Component",
|
|
3408
3433
|
methodName
|
|
3409
3434
|
},
|
|
3410
3435
|
messageId: "default",
|
|
3411
|
-
node:
|
|
3436
|
+
node: defNode
|
|
3412
3437
|
});
|
|
3413
3438
|
}
|
|
3414
3439
|
}
|
|
@@ -3416,7 +3441,11 @@ function create$11(context) {
|
|
|
3416
3441
|
const currentClass = Traverse.findParent(node, Check.isClass);
|
|
3417
3442
|
if (currentClass == null || !core.isClassComponent(currentClass)) return;
|
|
3418
3443
|
if (node.static) return;
|
|
3419
|
-
if (
|
|
3444
|
+
if (node.computed || !Check.isIdentifier(node.key)) return;
|
|
3445
|
+
const methodName = node.key.name;
|
|
3446
|
+
const defs = getOrInsertComputed(propertyDefs, currentClass, () => /* @__PURE__ */ new Map());
|
|
3447
|
+
if (!defs.has(methodName)) defs.set(methodName, node.key);
|
|
3448
|
+
if (isPublicMethod(node)) getOrInsertComputed(publicMethods, currentClass, () => /* @__PURE__ */ new Set()).add(methodName);
|
|
3420
3449
|
}
|
|
3421
3450
|
return {
|
|
3422
3451
|
"ClassDeclaration:exit": classExit,
|
|
@@ -3426,12 +3455,17 @@ function create$11(context) {
|
|
|
3426
3455
|
const currentMethod = Traverse.findParent(node, Check.isPropertyOrMethod);
|
|
3427
3456
|
if (currentClass == null || currentMethod == null) return;
|
|
3428
3457
|
if (!core.isClassComponent(currentClass) || currentMethod.static) return;
|
|
3429
|
-
if (node.object.type !== AST_NODE_TYPES.ThisExpression
|
|
3458
|
+
if (node.object.type !== AST_NODE_TYPES.ThisExpression) return;
|
|
3430
3459
|
if (node.parent.type === AST_NODE_TYPES.AssignmentExpression && node.parent.left === node) {
|
|
3431
|
-
|
|
3460
|
+
if (!node.computed && Check.isIdentifier(node.property)) {
|
|
3461
|
+
const defs = getOrInsertComputed(propertyDefs, currentClass, () => /* @__PURE__ */ new Map());
|
|
3462
|
+
if (!defs.has(node.property.name)) defs.set(node.property.name, node.property);
|
|
3463
|
+
}
|
|
3432
3464
|
return;
|
|
3433
3465
|
}
|
|
3434
|
-
|
|
3466
|
+
const propertyName = getStaticName(node.property, node.computed);
|
|
3467
|
+
if (propertyName == null) return;
|
|
3468
|
+
getOrInsertComputed(propertyUsages, currentClass, () => /* @__PURE__ */ new Set()).add(propertyName);
|
|
3435
3469
|
},
|
|
3436
3470
|
MethodDefinition: methodEnter,
|
|
3437
3471
|
PropertyDefinition: methodEnter,
|
|
@@ -3440,8 +3474,11 @@ function create$11(context) {
|
|
|
3440
3474
|
const currentMethod = Traverse.findParent(node, Check.isPropertyOrMethod);
|
|
3441
3475
|
if (currentClass == null || currentMethod == null) return;
|
|
3442
3476
|
if (!core.isClassComponent(currentClass) || currentMethod.static) return;
|
|
3443
|
-
if (node.init != null && node.init.type === AST_NODE_TYPES.ThisExpression && node.id.type === AST_NODE_TYPES.ObjectPattern) {
|
|
3444
|
-
|
|
3477
|
+
if (node.init != null && node.init.type === AST_NODE_TYPES.ThisExpression && node.id.type === AST_NODE_TYPES.ObjectPattern) for (const prop of node.id.properties) {
|
|
3478
|
+
if (prop.type !== AST_NODE_TYPES.Property) continue;
|
|
3479
|
+
const name = getStaticName(prop.key, prop.computed);
|
|
3480
|
+
if (name == null) continue;
|
|
3481
|
+
getOrInsertComputed(propertyUsages, currentClass, () => /* @__PURE__ */ new Set()).add(name);
|
|
3445
3482
|
}
|
|
3446
3483
|
}
|
|
3447
3484
|
};
|
|
@@ -4303,18 +4340,6 @@ function getGuardDisposition(node, getNullBranch) {
|
|
|
4303
4340
|
}
|
|
4304
4341
|
return null;
|
|
4305
4342
|
}
|
|
4306
|
-
function isUnconditionallyTerminating(statement) {
|
|
4307
|
-
switch (statement.type) {
|
|
4308
|
-
case AST_NODE_TYPES.ReturnStatement:
|
|
4309
|
-
case AST_NODE_TYPES.ThrowStatement: return true;
|
|
4310
|
-
case AST_NODE_TYPES.BlockStatement: {
|
|
4311
|
-
const last = statement.body.at(-1);
|
|
4312
|
-
return last != null && isUnconditionallyTerminating(last);
|
|
4313
|
-
}
|
|
4314
|
-
case AST_NODE_TYPES.IfStatement: return statement.alternate != null && isUnconditionallyTerminating(statement.consequent) && isUnconditionallyTerminating(statement.alternate);
|
|
4315
|
-
default: return false;
|
|
4316
|
-
}
|
|
4317
|
-
}
|
|
4318
4343
|
function isAfterTerminatingNonNullGuard(node, getNullBranch) {
|
|
4319
4344
|
let statement = node;
|
|
4320
4345
|
while (statement.parent?.type !== AST_NODE_TYPES.BlockStatement) {
|
|
@@ -4329,7 +4354,7 @@ function isAfterTerminatingNonNullGuard(node, getNullBranch) {
|
|
|
4329
4354
|
const nullBranch = getNullBranch(sibling.test);
|
|
4330
4355
|
if (nullBranch == null) continue;
|
|
4331
4356
|
const nonNullBranch = nullBranch === "alternate" ? sibling.consequent : sibling.alternate;
|
|
4332
|
-
return nonNullBranch != null && isUnconditionallyTerminating(nonNullBranch);
|
|
4357
|
+
return nonNullBranch != null && Analyze.isUnconditionallyTerminating(nonNullBranch);
|
|
4333
4358
|
}
|
|
4334
4359
|
return false;
|
|
4335
4360
|
}
|
|
@@ -6067,7 +6092,7 @@ function isInsideTryCatch(node) {
|
|
|
6067
6092
|
}
|
|
6068
6093
|
return false;
|
|
6069
6094
|
}
|
|
6070
|
-
function getNodeWithoutReactNamespace(node) {
|
|
6095
|
+
function getNodeWithoutReactNamespace$1(node) {
|
|
6071
6096
|
if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "React" && node.property.type === "Identifier" && !node.computed) return node.property;
|
|
6072
6097
|
return node;
|
|
6073
6098
|
}
|
|
@@ -6076,7 +6101,7 @@ function isEffectIdentifier(node, additionalHooks) {
|
|
|
6076
6101
|
if (additionalHooks && node.type === "Identifier") return additionalHooks.test(node.name);
|
|
6077
6102
|
return false;
|
|
6078
6103
|
}
|
|
6079
|
-
function isUseEffectEventIdentifier(node) {
|
|
6104
|
+
function isUseEffectEventIdentifier$1(node) {
|
|
6080
6105
|
return node.type === "Identifier" && node.name === "useEffectEvent";
|
|
6081
6106
|
}
|
|
6082
6107
|
function useEffectEventError(fn, called) {
|
|
@@ -6086,7 +6111,7 @@ function useEffectEventError(fn, called) {
|
|
|
6086
6111
|
function isUseIdentifier(node) {
|
|
6087
6112
|
return isReactFunction(node, "use");
|
|
6088
6113
|
}
|
|
6089
|
-
const rule = {
|
|
6114
|
+
const rule$1 = {
|
|
6090
6115
|
meta: {
|
|
6091
6116
|
type: "problem",
|
|
6092
6117
|
docs: {
|
|
@@ -6111,7 +6136,7 @@ const rule = {
|
|
|
6111
6136
|
function recordAllUseEffectEventFunctions(scope) {
|
|
6112
6137
|
for (const reference of scope.references) {
|
|
6113
6138
|
const parent = reference.identifier.parent;
|
|
6114
|
-
if (parent?.type === "VariableDeclarator" && parent.init && parent.init.type === "CallExpression" && parent.init.callee && isUseEffectEventIdentifier(parent.init.callee)) {
|
|
6139
|
+
if (parent?.type === "VariableDeclarator" && parent.init && parent.init.type === "CallExpression" && parent.init.callee && isUseEffectEventIdentifier$1(parent.init.callee)) {
|
|
6115
6140
|
if (reference.resolved === null) throw new Error("Unexpected null reference.resolved");
|
|
6116
6141
|
for (const ref of reference.resolved.references) if (ref !== reference) useEffectEventFunctions.add(ref.identifier);
|
|
6117
6142
|
}
|
|
@@ -6290,9 +6315,9 @@ const rule = {
|
|
|
6290
6315
|
}
|
|
6291
6316
|
reactHooks.push(callee);
|
|
6292
6317
|
}
|
|
6293
|
-
const nodeWithoutNamespace = getNodeWithoutReactNamespace(node.callee);
|
|
6294
|
-
if ((isEffectIdentifier(nodeWithoutNamespace, additionalEffectHooks) || isUseEffectEventIdentifier(nodeWithoutNamespace)) && node.arguments.length > 0) lastEffect = node;
|
|
6295
|
-
if (isUseEffectEventIdentifier(nodeWithoutNamespace) && node.parent?.type !== "VariableDeclarator" && node.parent?.type !== "ExpressionStatement") {
|
|
6318
|
+
const nodeWithoutNamespace = getNodeWithoutReactNamespace$1(node.callee);
|
|
6319
|
+
if ((isEffectIdentifier(nodeWithoutNamespace, additionalEffectHooks) || isUseEffectEventIdentifier$1(nodeWithoutNamespace)) && node.arguments.length > 0) lastEffect = node;
|
|
6320
|
+
if (isUseEffectEventIdentifier$1(nodeWithoutNamespace) && node.parent?.type !== "VariableDeclarator" && node.parent?.type !== "ExpressionStatement") {
|
|
6296
6321
|
const message = useEffectEventError(null, false);
|
|
6297
6322
|
context.report({
|
|
6298
6323
|
node,
|
|
@@ -6385,94 +6410,11 @@ function createFactCollector$3(additionalStateHooks, additionalEffectHooks) {
|
|
|
6385
6410
|
};
|
|
6386
6411
|
}
|
|
6387
6412
|
// src/rules/set-state-in-effect/helpers.ts
|
|
6388
|
-
|
|
6389
|
-
|
|
6390
|
-
|
|
6391
|
-
|
|
6392
|
-
|
|
6393
|
-
[AST_NODE_TYPES.AwaitExpression]: ["argument"],
|
|
6394
|
-
[AST_NODE_TYPES.BinaryExpression]: ["left", "right"],
|
|
6395
|
-
[AST_NODE_TYPES.CallExpression]: ["callee", "arguments"],
|
|
6396
|
-
[AST_NODE_TYPES.ChainExpression]: ["expression"],
|
|
6397
|
-
[AST_NODE_TYPES.ConditionalExpression]: [
|
|
6398
|
-
"test",
|
|
6399
|
-
"consequent",
|
|
6400
|
-
"alternate"
|
|
6401
|
-
],
|
|
6402
|
-
[AST_NODE_TYPES.ForInStatement]: ["left", "right"],
|
|
6403
|
-
[AST_NODE_TYPES.ForOfStatement]: ["left", "right"],
|
|
6404
|
-
[AST_NODE_TYPES.ImportExpression]: ["source"],
|
|
6405
|
-
[AST_NODE_TYPES.LogicalExpression]: ["left", "right"],
|
|
6406
|
-
[AST_NODE_TYPES.MemberExpression]: ["object", "property"],
|
|
6407
|
-
[AST_NODE_TYPES.NewExpression]: ["callee", "arguments"],
|
|
6408
|
-
[AST_NODE_TYPES.ObjectExpression]: ["properties"],
|
|
6409
|
-
[AST_NODE_TYPES.ObjectPattern]: ["properties"],
|
|
6410
|
-
[AST_NODE_TYPES.Property]: ["value"],
|
|
6411
|
-
[AST_NODE_TYPES.SequenceExpression]: ["expressions"],
|
|
6412
|
-
[AST_NODE_TYPES.SpreadElement]: ["argument"],
|
|
6413
|
-
[AST_NODE_TYPES.TaggedTemplateExpression]: ["tag", "quasi"],
|
|
6414
|
-
[AST_NODE_TYPES.TemplateLiteral]: ["expressions"],
|
|
6415
|
-
[AST_NODE_TYPES.TSAsExpression]: ["expression"],
|
|
6416
|
-
[AST_NODE_TYPES.TSInstantiationExpression]: ["expression"],
|
|
6417
|
-
[AST_NODE_TYPES.TSNonNullExpression]: ["expression"],
|
|
6418
|
-
[AST_NODE_TYPES.TSSatisfiesExpression]: ["expression"],
|
|
6419
|
-
[AST_NODE_TYPES.TSTypeAssertion]: ["expression"],
|
|
6420
|
-
[AST_NODE_TYPES.UnaryExpression]: ["argument"],
|
|
6421
|
-
[AST_NODE_TYPES.UpdateExpression]: ["argument"],
|
|
6422
|
-
[AST_NODE_TYPES.YieldExpression]: ["argument"]
|
|
6423
|
-
};
|
|
6424
|
-
function getIdentifiers(node) {
|
|
6425
|
-
const identifiers = [];
|
|
6426
|
-
simpleTraverse(node, {
|
|
6427
|
-
enter(node, parent) {
|
|
6428
|
-
if (node.type !== AST_NODE_TYPES.Identifier) return;
|
|
6429
|
-
if (parent?.type === AST_NODE_TYPES.MemberExpression && !parent.computed && parent.property === node) return;
|
|
6430
|
-
identifiers.push(node);
|
|
6431
|
-
},
|
|
6432
|
-
visitorKeys: IDENTIFIER_VISITOR_KEYS
|
|
6433
|
-
});
|
|
6434
|
-
return identifiers;
|
|
6435
|
-
}
|
|
6436
|
-
function isTerminatingStatement(node) {
|
|
6437
|
-
if (node.type === AST_NODE_TYPES.ReturnStatement || node.type === AST_NODE_TYPES.ThrowStatement) return true;
|
|
6438
|
-
if (node.type === AST_NODE_TYPES.BlockStatement) return node.body.some(isTerminatingStatement);
|
|
6439
|
-
return false;
|
|
6440
|
-
}
|
|
6441
|
-
function getReturnExpressions(fn) {
|
|
6442
|
-
if (fn.type === AST_NODE_TYPES.ArrowFunctionExpression && fn.body.type !== AST_NODE_TYPES.BlockStatement) return [fn.body];
|
|
6443
|
-
const returns = [];
|
|
6444
|
-
const visitStatements = (statements) => {
|
|
6445
|
-
for (const statement of statements) switch (statement.type) {
|
|
6446
|
-
case AST_NODE_TYPES.ReturnStatement:
|
|
6447
|
-
if (statement.argument != null) returns.push(statement.argument);
|
|
6448
|
-
break;
|
|
6449
|
-
case AST_NODE_TYPES.BlockStatement:
|
|
6450
|
-
visitStatements(statement.body);
|
|
6451
|
-
break;
|
|
6452
|
-
case AST_NODE_TYPES.IfStatement:
|
|
6453
|
-
visitStatements([statement.consequent]);
|
|
6454
|
-
if (statement.alternate != null) visitStatements([statement.alternate]);
|
|
6455
|
-
break;
|
|
6456
|
-
case AST_NODE_TYPES.SwitchStatement:
|
|
6457
|
-
for (const switchCase of statement.cases) visitStatements(switchCase.consequent);
|
|
6458
|
-
break;
|
|
6459
|
-
case AST_NODE_TYPES.TryStatement:
|
|
6460
|
-
visitStatements([statement.block]);
|
|
6461
|
-
if (statement.handler != null) visitStatements([statement.handler.body]);
|
|
6462
|
-
if (statement.finalizer != null) visitStatements([statement.finalizer]);
|
|
6463
|
-
break;
|
|
6464
|
-
case AST_NODE_TYPES.DoWhileStatement:
|
|
6465
|
-
case AST_NODE_TYPES.ForInStatement:
|
|
6466
|
-
case AST_NODE_TYPES.ForOfStatement:
|
|
6467
|
-
case AST_NODE_TYPES.ForStatement:
|
|
6468
|
-
case AST_NODE_TYPES.LabeledStatement:
|
|
6469
|
-
case AST_NODE_TYPES.WhileStatement:
|
|
6470
|
-
case AST_NODE_TYPES.WithStatement: visitStatements([statement.body]);
|
|
6471
|
-
}
|
|
6472
|
-
};
|
|
6473
|
-
if (fn.body.type !== AST_NODE_TYPES.BlockStatement) return [];
|
|
6474
|
-
visitStatements(fn.body.body);
|
|
6475
|
-
return returns;
|
|
6413
|
+
function getImmediateInvocation(fn) {
|
|
6414
|
+
let parent = fn.parent;
|
|
6415
|
+
while (Check.isTypeOrChainExpression(parent)) parent = parent.parent;
|
|
6416
|
+
if (parent.type !== AST_NODE_TYPES.CallExpression) return null;
|
|
6417
|
+
return Extract.unwrap(parent.callee) === fn ? parent : null;
|
|
6476
6418
|
}
|
|
6477
6419
|
function getConditionalBranch(node) {
|
|
6478
6420
|
let child = node;
|
|
@@ -6507,11 +6449,8 @@ function isRefLikeName(name) {
|
|
|
6507
6449
|
return name === "ref" || name.endsWith("Ref");
|
|
6508
6450
|
}
|
|
6509
6451
|
function getParameterId(param) {
|
|
6510
|
-
|
|
6511
|
-
|
|
6512
|
-
case AST_NODE_TYPES.AssignmentPattern: return param.left.type === AST_NODE_TYPES.Identifier ? param.left : null;
|
|
6513
|
-
default: return null;
|
|
6514
|
-
}
|
|
6452
|
+
const target = param.type === AST_NODE_TYPES.AssignmentPattern ? param.left : param;
|
|
6453
|
+
return target.type === AST_NODE_TYPES.Identifier ? target : null;
|
|
6515
6454
|
}
|
|
6516
6455
|
function getRefSourceName(node) {
|
|
6517
6456
|
switch (node.type) {
|
|
@@ -6531,7 +6470,7 @@ const EMPTY_FACTS = {
|
|
|
6531
6470
|
};
|
|
6532
6471
|
function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
6533
6472
|
const { additionalRefHooks, additionalStateHooks } = getSettingsFromContext(context);
|
|
6534
|
-
const getReturnExpressions
|
|
6473
|
+
const getReturnExpressions = memoize(Collect.getReturnExpressions);
|
|
6535
6474
|
function isUseRefCall(node) {
|
|
6536
6475
|
return node.type === AST_NODE_TYPES.CallExpression && core.isUseRefLikeCall(node, additionalRefHooks);
|
|
6537
6476
|
}
|
|
@@ -6617,7 +6556,7 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6617
6556
|
const targets = [];
|
|
6618
6557
|
for (const factory of factories) {
|
|
6619
6558
|
if (factory.kind !== "function" || factory.node.async) continue;
|
|
6620
|
-
for (const returnExpression of getReturnExpressions
|
|
6559
|
+
for (const returnExpression of getReturnExpressions(factory.node)) targets.push(...resolveValues(returnExpression, new Set(seen)));
|
|
6621
6560
|
}
|
|
6622
6561
|
return uniqueTargets(targets);
|
|
6623
6562
|
}
|
|
@@ -6636,6 +6575,47 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6636
6575
|
}
|
|
6637
6576
|
return refParams;
|
|
6638
6577
|
}
|
|
6578
|
+
function isDeferredInvocation(invocation) {
|
|
6579
|
+
let current = invocation.parent;
|
|
6580
|
+
while (current != null) {
|
|
6581
|
+
if (Check.isFunction(current)) return false;
|
|
6582
|
+
switch (current.type) {
|
|
6583
|
+
case AST_NODE_TYPES.AssignmentPattern: return true;
|
|
6584
|
+
case AST_NODE_TYPES.PropertyDefinition: {
|
|
6585
|
+
if (current.static) return false;
|
|
6586
|
+
const value = current.value;
|
|
6587
|
+
return value != null && (value === invocation || Traverse.hasParent(invocation, (n) => n === value));
|
|
6588
|
+
}
|
|
6589
|
+
default: current = current.parent;
|
|
6590
|
+
}
|
|
6591
|
+
}
|
|
6592
|
+
return false;
|
|
6593
|
+
}
|
|
6594
|
+
function getVisibleWriteLocation(value, id) {
|
|
6595
|
+
let branch = getConditionalBranch(value);
|
|
6596
|
+
let node = value;
|
|
6597
|
+
let order = 1;
|
|
6598
|
+
let boundary = Traverse.findParent(value, Check.isFunction);
|
|
6599
|
+
while (boundary != null) {
|
|
6600
|
+
if (Traverse.hasParent(id, (n) => n === boundary)) return {
|
|
6601
|
+
branch,
|
|
6602
|
+
node,
|
|
6603
|
+
order
|
|
6604
|
+
};
|
|
6605
|
+
if (boundary.async || boundary.generator) return null;
|
|
6606
|
+
const invocation = getImmediateInvocation(boundary);
|
|
6607
|
+
if (invocation == null || isDeferredInvocation(invocation)) return null;
|
|
6608
|
+
branch ??= getConditionalBranch(invocation);
|
|
6609
|
+
node = invocation;
|
|
6610
|
+
order = 0;
|
|
6611
|
+
boundary = Traverse.findParent(invocation, Check.isFunction);
|
|
6612
|
+
}
|
|
6613
|
+
return {
|
|
6614
|
+
branch,
|
|
6615
|
+
node,
|
|
6616
|
+
order
|
|
6617
|
+
};
|
|
6618
|
+
}
|
|
6639
6619
|
function isInitializedFromRef(id, refParams, seen = /* @__PURE__ */ new Set()) {
|
|
6640
6620
|
const variable = findVariable(context.sourceCode.getScope(id), id);
|
|
6641
6621
|
if (variable == null) return false;
|
|
@@ -6644,11 +6624,16 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6644
6624
|
seen.add(key);
|
|
6645
6625
|
if (isStateHeldDomNode(variable)) return true;
|
|
6646
6626
|
const candidates = [];
|
|
6647
|
-
const addCandidate = (value,
|
|
6648
|
-
|
|
6627
|
+
const addCandidate = (value, visibility = {
|
|
6628
|
+
branch: getConditionalBranch(value),
|
|
6629
|
+
node: value,
|
|
6630
|
+
order: 1
|
|
6631
|
+
}, previous) => {
|
|
6632
|
+
if (visibility.node.range[1] > id.range[0] || candidates.some((c) => c.value === value)) return;
|
|
6649
6633
|
candidates.push({
|
|
6650
|
-
branch:
|
|
6651
|
-
|
|
6634
|
+
branch: visibility.branch,
|
|
6635
|
+
order: visibility.order,
|
|
6636
|
+
position: visibility.node.range[1],
|
|
6652
6637
|
previous,
|
|
6653
6638
|
value
|
|
6654
6639
|
});
|
|
@@ -6661,12 +6646,13 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6661
6646
|
if (!reference.isWrite() || reference.writeExpr == null) continue;
|
|
6662
6647
|
if (reference.init === true && variable.defs.some((d) => d.type === DefinitionType.Parameter && refParams?.has(d.name) === true)) continue;
|
|
6663
6648
|
const writeExpr = reference.writeExpr;
|
|
6664
|
-
|
|
6649
|
+
const visibility = getVisibleWriteLocation(writeExpr, id);
|
|
6650
|
+
if (visibility == null) continue;
|
|
6665
6651
|
const parent = reference.identifier.parent;
|
|
6666
|
-
addCandidate(writeExpr, parent.type === AST_NODE_TYPES.AssignmentExpression && parent.operator !== "=" && Extract.unwrap(parent.left) === reference.identifier ? reference.identifier : void 0);
|
|
6652
|
+
addCandidate(writeExpr, visibility, parent.type === AST_NODE_TYPES.AssignmentExpression && parent.operator !== "=" && Extract.unwrap(parent.left) === reference.identifier ? reference.identifier : void 0);
|
|
6667
6653
|
}
|
|
6668
6654
|
const survivingCandidates = [];
|
|
6669
|
-
for (const candidate of [...candidates].sort((a, b) => a.position - b.position)) {
|
|
6655
|
+
for (const candidate of [...candidates].sort((a, b) => a.position - b.position || a.order - b.order)) {
|
|
6670
6656
|
if (candidate.branch == null) survivingCandidates.length = 0;
|
|
6671
6657
|
else {
|
|
6672
6658
|
const previousIndex = survivingCandidates.findIndex((o) => o.branch === candidate.branch);
|
|
@@ -6709,14 +6695,18 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6709
6695
|
if (seen.has(key)) continue;
|
|
6710
6696
|
seen.add(key);
|
|
6711
6697
|
const childRefParams = getRefDerivedParams(expression, target.node, refParams);
|
|
6712
|
-
if (getReturnExpressions
|
|
6698
|
+
if (getReturnExpressions(target.node).some((r) => isRefValue(r, childRefParams, seen, mode))) return true;
|
|
6713
6699
|
}
|
|
6714
6700
|
return isRefValue(expression.callee, refParams, seen, mode) || expression.arguments.some((a) => isRefValue(a, refParams, seen, mode));
|
|
6715
6701
|
case AST_NODE_TYPES.BinaryExpression:
|
|
6716
6702
|
case AST_NODE_TYPES.LogicalExpression: return isRefValue(expression.left, refParams, seen, mode) || isRefValue(expression.right, refParams, seen, mode);
|
|
6717
6703
|
case AST_NODE_TYPES.UnaryExpression:
|
|
6718
6704
|
case AST_NODE_TYPES.UpdateExpression: return isRefValue(expression.argument, refParams, seen, mode);
|
|
6719
|
-
case AST_NODE_TYPES.ConditionalExpression: return
|
|
6705
|
+
case AST_NODE_TYPES.ConditionalExpression: return [
|
|
6706
|
+
mode === "initializer" ? expression.test : null,
|
|
6707
|
+
expression.consequent,
|
|
6708
|
+
expression.alternate
|
|
6709
|
+
].some((e) => e != null && isRefValue(e, refParams, seen, mode));
|
|
6720
6710
|
case AST_NODE_TYPES.SequenceExpression: return expression.expressions.some((p) => isRefValue(p, refParams, seen, mode));
|
|
6721
6711
|
case AST_NODE_TYPES.TemplateLiteral: return expression.expressions.some((p) => isRefValue(p, refParams, seen, mode));
|
|
6722
6712
|
case AST_NODE_TYPES.TaggedTemplateExpression: return isRefValue(expression.tag, refParams, seen, mode) || isRefValue(expression.quasi, refParams, seen, mode);
|
|
@@ -6737,7 +6727,30 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6737
6727
|
return context.sourceCode.getScope(expression.body).references.some((r) => isRefValue(r.identifier, refParams, seen, "argument"));
|
|
6738
6728
|
}
|
|
6739
6729
|
function isRefInExpression(node, refParams) {
|
|
6740
|
-
return getIdentifiers(node).some((id) => isInitializedFromRef(id, refParams));
|
|
6730
|
+
return Collect.getIdentifiers(node).some((id) => isInitializedFromRef(id, refParams));
|
|
6731
|
+
}
|
|
6732
|
+
function hasRefGatedTerminator(statements, refParams) {
|
|
6733
|
+
return statements.some((statement) => isRefGatedTerminator(statement, refParams));
|
|
6734
|
+
}
|
|
6735
|
+
function isRefGatedTerminator(statement, refParams) {
|
|
6736
|
+
switch (statement.type) {
|
|
6737
|
+
case AST_NODE_TYPES.IfStatement: return isRefInExpression(statement.test, refParams) && (Analyze.isTerminatingStatement(statement.consequent) || statement.alternate != null && Analyze.isTerminatingStatement(statement.alternate));
|
|
6738
|
+
case AST_NODE_TYPES.BlockStatement: return hasRefGatedTerminator(statement.body, refParams);
|
|
6739
|
+
case AST_NODE_TYPES.TryStatement:
|
|
6740
|
+
if (statement.finalizer != null && hasRefGatedTerminator(statement.finalizer.body, refParams)) return true;
|
|
6741
|
+
if (statement.handler != null && !Analyze.isTerminatingStatement(statement.handler.body)) return false;
|
|
6742
|
+
return hasRefGatedTerminator(statement.block.body, refParams);
|
|
6743
|
+
default: return false;
|
|
6744
|
+
}
|
|
6745
|
+
}
|
|
6746
|
+
function hasRefGatedEarlyExit(statements, child, refParams) {
|
|
6747
|
+
const index = statements.findIndex((statement) => statement === child);
|
|
6748
|
+
if (index < 0) return false;
|
|
6749
|
+
for (let i = 0; i < index; i++) {
|
|
6750
|
+
const statement = statements[i];
|
|
6751
|
+
if (statement != null && isRefGatedTerminator(statement, refParams)) return true;
|
|
6752
|
+
}
|
|
6753
|
+
return false;
|
|
6741
6754
|
}
|
|
6742
6755
|
function isRefGatedContext(node, refParams) {
|
|
6743
6756
|
let child = node;
|
|
@@ -6752,15 +6765,16 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
|
|
|
6752
6765
|
case AST_NODE_TYPES.LogicalExpression:
|
|
6753
6766
|
if (child === current.right && isRefInExpression(current.left, refParams)) return true;
|
|
6754
6767
|
break;
|
|
6755
|
-
case AST_NODE_TYPES.
|
|
6756
|
-
|
|
6757
|
-
for (const statement of current.body.slice(0, Math.max(0, index))) {
|
|
6758
|
-
if (statement.type !== AST_NODE_TYPES.IfStatement) continue;
|
|
6759
|
-
if (!isRefInExpression(statement.test, refParams)) continue;
|
|
6760
|
-
if (isTerminatingStatement(statement.consequent)) return true;
|
|
6761
|
-
}
|
|
6768
|
+
case AST_NODE_TYPES.WhileStatement:
|
|
6769
|
+
if (child === current.body && isRefInExpression(current.test, refParams)) return true;
|
|
6762
6770
|
break;
|
|
6763
|
-
|
|
6771
|
+
case AST_NODE_TYPES.ForStatement:
|
|
6772
|
+
if ((child === current.body || child === current.update) && current.test != null && isRefInExpression(current.test, refParams)) return true;
|
|
6773
|
+
break;
|
|
6774
|
+
case AST_NODE_TYPES.BlockStatement:
|
|
6775
|
+
if (hasRefGatedEarlyExit(current.body, child, refParams)) return true;
|
|
6776
|
+
break;
|
|
6777
|
+
case AST_NODE_TYPES.SwitchCase: if (hasRefGatedEarlyExit(current.consequent, child, refParams)) return true;
|
|
6764
6778
|
}
|
|
6765
6779
|
child = current;
|
|
6766
6780
|
current = current.parent;
|
|
@@ -6799,24 +6813,24 @@ function inferViolations$2(context, facts) {
|
|
|
6799
6813
|
visited.add(key);
|
|
6800
6814
|
queue.push(state);
|
|
6801
6815
|
};
|
|
6802
|
-
const report = (
|
|
6803
|
-
|
|
6804
|
-
|
|
6805
|
-
|
|
6816
|
+
const report = (setter, reportNode) => {
|
|
6817
|
+
const name = resolver.getSetterName(setter.node);
|
|
6818
|
+
const key = `${String(reportNode.range[0])}:${String(reportNode.range[1])}:${name}`;
|
|
6819
|
+
getOrInsertComputed(violations, key, () => ({
|
|
6820
|
+
name,
|
|
6806
6821
|
node: reportNode
|
|
6807
|
-
});
|
|
6822
|
+
}));
|
|
6808
6823
|
};
|
|
6809
6824
|
const isExemptCall = (call, state) => {
|
|
6810
6825
|
if (state.inheritedRefGate || resolver.isRefGatedContext(call, state.refParams)) return true;
|
|
6811
|
-
|
|
6812
|
-
return argument != null && resolver.isArgumentUsingRefValue(argument, state.refParams);
|
|
6826
|
+
return call.arguments.some((argument) => resolver.isArgumentUsingRefValue(argument, state.refParams));
|
|
6813
6827
|
};
|
|
6814
6828
|
for (const root of [...facts.effectRoots].sort((a, b) => a.node.range[0] - b.node.range[0])) {
|
|
6815
6829
|
const setup = root.setup;
|
|
6816
6830
|
const unwrappedSetup = Extract.unwrap(setup);
|
|
6817
6831
|
for (const target of resolver.resolveValues(setup)) {
|
|
6818
6832
|
if (target.kind === "setter") {
|
|
6819
|
-
if (!resolver.isRefGatedContext(setup)) report(target
|
|
6833
|
+
if (!resolver.isRefGatedContext(setup)) report(target, setup);
|
|
6820
6834
|
continue;
|
|
6821
6835
|
}
|
|
6822
6836
|
const reportNode = unwrappedSetup === target.node ? null : setup;
|
|
@@ -6834,7 +6848,7 @@ function inferViolations$2(context, facts) {
|
|
|
6834
6848
|
const calls = callsByFunction.get(state.fn) ?? [];
|
|
6835
6849
|
for (const call of calls) for (const target of resolver.resolveValues(call.callee)) {
|
|
6836
6850
|
if (target.kind === "setter") {
|
|
6837
|
-
if (!isExemptCall(call, state)) report(
|
|
6851
|
+
if (!isExemptCall(call, state)) report(target, state.reportNode ?? call);
|
|
6838
6852
|
continue;
|
|
6839
6853
|
}
|
|
6840
6854
|
enqueue({
|
|
@@ -7166,61 +7180,1063 @@ function create$3(context) {
|
|
|
7166
7180
|
}
|
|
7167
7181
|
} });
|
|
7168
7182
|
}
|
|
7169
|
-
// src/rules/
|
|
7170
|
-
function
|
|
7171
|
-
const
|
|
7172
|
-
|
|
7173
|
-
|
|
7174
|
-
|
|
7175
|
-
|
|
7176
|
-
|
|
7177
|
-
|
|
7183
|
+
// src/rules/unstable-exhaustive-deps/lib.ts
|
|
7184
|
+
function getHookConfigs(hooks = []) {
|
|
7185
|
+
const reactive = /* @__PURE__ */ new Map();
|
|
7186
|
+
const stable = /* @__PURE__ */ new Map();
|
|
7187
|
+
for (const { name, closureIndex, dependenciesIndex, stableResult } of hooks) {
|
|
7188
|
+
if (closureIndex != null && dependenciesIndex != null && closureIndex !== dependenciesIndex) reactive.set(name, {
|
|
7189
|
+
closureIndex,
|
|
7190
|
+
dependenciesIndex
|
|
7191
|
+
});
|
|
7192
|
+
if (stableResult === true) stable.set(name, true);
|
|
7193
|
+
else if (typeof stableResult === "number") stable.set(name, /* @__PURE__ */ new Set([stableResult]));
|
|
7194
|
+
else if (Array.isArray(stableResult)) stable.set(name, new Set(stableResult));
|
|
7178
7195
|
}
|
|
7196
|
+
return {
|
|
7197
|
+
reactive,
|
|
7198
|
+
stable
|
|
7199
|
+
};
|
|
7179
7200
|
}
|
|
7180
|
-
|
|
7201
|
+
function getReactiveHookConfig(node, configs) {
|
|
7202
|
+
if (configs.reactive.size === 0) return null;
|
|
7203
|
+
const name = Extract.getCalleeName(node);
|
|
7204
|
+
if (name == null) return null;
|
|
7205
|
+
const config = configs.reactive.get(name);
|
|
7206
|
+
if (config == null) return null;
|
|
7207
|
+
return {
|
|
7208
|
+
name,
|
|
7209
|
+
...config
|
|
7210
|
+
};
|
|
7211
|
+
}
|
|
7212
|
+
function isConfiguredStableHookValue(variable, configs) {
|
|
7213
|
+
if (configs.stable.size === 0) return false;
|
|
7214
|
+
let matchedNode = null;
|
|
7215
|
+
let stableResult = null;
|
|
7216
|
+
let initializerCount = 0;
|
|
7217
|
+
for (const def of variable.defs) {
|
|
7218
|
+
if (def.type !== DefinitionType.Variable || def.node.init == null) continue;
|
|
7219
|
+
initializerCount++;
|
|
7220
|
+
const init = Extract.unwrap(def.node.init);
|
|
7221
|
+
if (init.type !== AST_NODE_TYPES.CallExpression) continue;
|
|
7222
|
+
const name = Extract.getCalleeName(init);
|
|
7223
|
+
if (name == null) continue;
|
|
7224
|
+
const config = configs.stable.get(name);
|
|
7225
|
+
if (config == null) continue;
|
|
7226
|
+
if (matchedNode != null) return false;
|
|
7227
|
+
matchedNode = def.node;
|
|
7228
|
+
stableResult = config;
|
|
7229
|
+
}
|
|
7230
|
+
if (initializerCount !== 1) return false;
|
|
7231
|
+
if (matchedNode == null || stableResult == null) return false;
|
|
7232
|
+
if (variable.references.some((reference) => reference.isWrite() && reference.init !== true)) return false;
|
|
7233
|
+
const { id } = matchedNode;
|
|
7234
|
+
if (stableResult === true) return id.type === AST_NODE_TYPES.Identifier;
|
|
7235
|
+
if (id.type !== AST_NODE_TYPES.ArrayPattern) return false;
|
|
7236
|
+
const index = id.elements.findIndex((element) => {
|
|
7237
|
+
if (element == null) return false;
|
|
7238
|
+
const binding = element.type === AST_NODE_TYPES.AssignmentPattern ? element.left : element;
|
|
7239
|
+
return variable.identifiers.some((identifier) => identifier === binding);
|
|
7240
|
+
});
|
|
7241
|
+
return index !== -1 && stableResult.has(index);
|
|
7242
|
+
}
|
|
7243
|
+
// src/rules/unstable-exhaustive-deps/unstable-exhaustive-deps.ts
|
|
7244
|
+
const rule = {
|
|
7181
7245
|
meta: {
|
|
7182
|
-
type: "
|
|
7183
|
-
docs: {
|
|
7184
|
-
|
|
7185
|
-
|
|
7186
|
-
with: "Do not use 'with' statements inside components or hooks. 'with' changes scope dynamically and is not supported by React Compiler."
|
|
7246
|
+
type: "suggestion",
|
|
7247
|
+
docs: {
|
|
7248
|
+
description: "Verifies the list of dependencies for Hooks like 'useEffect' and similar, with support for custom Hooks and stable Hook results.",
|
|
7249
|
+
url: "https://eslint-react.xyz/docs/rules/unstable-exhaustive-deps"
|
|
7187
7250
|
},
|
|
7188
|
-
|
|
7251
|
+
fixable: "code",
|
|
7252
|
+
hasSuggestions: true,
|
|
7253
|
+
schema: [{
|
|
7254
|
+
type: "object",
|
|
7255
|
+
additionalProperties: false,
|
|
7256
|
+
enableDangerousAutofixThisMayCauseInfiniteLoops: false,
|
|
7257
|
+
properties: {
|
|
7258
|
+
additionalHooks: { type: "string" },
|
|
7259
|
+
enableDangerousAutofixThisMayCauseInfiniteLoops: { type: "boolean" },
|
|
7260
|
+
experimental_autoDependenciesHooks: {
|
|
7261
|
+
type: "array",
|
|
7262
|
+
items: { type: "string" }
|
|
7263
|
+
},
|
|
7264
|
+
hooks: {
|
|
7265
|
+
type: "array",
|
|
7266
|
+
items: {
|
|
7267
|
+
type: "object",
|
|
7268
|
+
additionalProperties: false,
|
|
7269
|
+
dependencies: {
|
|
7270
|
+
closureIndex: ["dependenciesIndex"],
|
|
7271
|
+
dependenciesIndex: ["closureIndex"]
|
|
7272
|
+
},
|
|
7273
|
+
properties: {
|
|
7274
|
+
name: {
|
|
7275
|
+
type: "string",
|
|
7276
|
+
minLength: 1
|
|
7277
|
+
},
|
|
7278
|
+
closureIndex: {
|
|
7279
|
+
type: "integer",
|
|
7280
|
+
minimum: 0
|
|
7281
|
+
},
|
|
7282
|
+
dependenciesIndex: {
|
|
7283
|
+
type: "integer",
|
|
7284
|
+
minimum: 0
|
|
7285
|
+
},
|
|
7286
|
+
stableResult: { oneOf: [
|
|
7287
|
+
{ type: "boolean" },
|
|
7288
|
+
{
|
|
7289
|
+
type: "integer",
|
|
7290
|
+
minimum: 0
|
|
7291
|
+
},
|
|
7292
|
+
{
|
|
7293
|
+
type: "array",
|
|
7294
|
+
items: {
|
|
7295
|
+
type: "integer",
|
|
7296
|
+
minimum: 0
|
|
7297
|
+
},
|
|
7298
|
+
minItems: 1
|
|
7299
|
+
}
|
|
7300
|
+
] }
|
|
7301
|
+
},
|
|
7302
|
+
required: ["name"]
|
|
7303
|
+
}
|
|
7304
|
+
},
|
|
7305
|
+
requireExplicitEffectDeps: { type: "boolean" }
|
|
7306
|
+
}
|
|
7307
|
+
}]
|
|
7189
7308
|
},
|
|
7190
|
-
|
|
7191
|
-
|
|
7192
|
-
|
|
7193
|
-
|
|
7194
|
-
|
|
7195
|
-
|
|
7196
|
-
|
|
7197
|
-
|
|
7198
|
-
|
|
7199
|
-
|
|
7200
|
-
|
|
7201
|
-
|
|
7202
|
-
|
|
7203
|
-
|
|
7204
|
-
|
|
7205
|
-
|
|
7206
|
-
}
|
|
7207
|
-
|
|
7208
|
-
|
|
7209
|
-
|
|
7210
|
-
|
|
7211
|
-
|
|
7212
|
-
|
|
7213
|
-
|
|
7214
|
-
|
|
7215
|
-
|
|
7216
|
-
|
|
7217
|
-
|
|
7218
|
-
|
|
7219
|
-
|
|
7220
|
-
|
|
7221
|
-
|
|
7222
|
-
|
|
7223
|
-
|
|
7309
|
+
create(context) {
|
|
7310
|
+
const rawOptions = context.options && context.options[0];
|
|
7311
|
+
const additionalHooks = rawOptions && rawOptions.additionalHooks ? new RegExp(rawOptions.additionalHooks) : getSettingsFromContext(context).additionalEffectHooks;
|
|
7312
|
+
const enableDangerousAutofixThisMayCauseInfiniteLoops = rawOptions && rawOptions.enableDangerousAutofixThisMayCauseInfiniteLoops || false;
|
|
7313
|
+
const experimental_autoDependenciesHooks = rawOptions && Array.isArray(rawOptions.experimental_autoDependenciesHooks) ? rawOptions.experimental_autoDependenciesHooks : [];
|
|
7314
|
+
const requireExplicitEffectDeps = rawOptions && rawOptions.requireExplicitEffectDeps || false;
|
|
7315
|
+
const options = {
|
|
7316
|
+
additionalHooks,
|
|
7317
|
+
experimental_autoDependenciesHooks,
|
|
7318
|
+
enableDangerousAutofixThisMayCauseInfiniteLoops,
|
|
7319
|
+
hooks: getHookConfigs(rawOptions && rawOptions.hooks),
|
|
7320
|
+
requireExplicitEffectDeps
|
|
7321
|
+
};
|
|
7322
|
+
function reportProblem(problem) {
|
|
7323
|
+
if (enableDangerousAutofixThisMayCauseInfiniteLoops) {
|
|
7324
|
+
if (Array.isArray(problem.suggest) && problem.suggest.length > 0 && problem.suggest[0]) problem.fix = problem.suggest[0].fix;
|
|
7325
|
+
}
|
|
7326
|
+
context.report(problem);
|
|
7327
|
+
}
|
|
7328
|
+
const getSourceCode = typeof context.getSourceCode === "function" ? () => {
|
|
7329
|
+
return context.getSourceCode();
|
|
7330
|
+
} : () => {
|
|
7331
|
+
return context.sourceCode;
|
|
7332
|
+
};
|
|
7333
|
+
const getScope = typeof context.getScope === "function" ? () => {
|
|
7334
|
+
return context.getScope();
|
|
7335
|
+
} : (node) => {
|
|
7336
|
+
return context.sourceCode.getScope(node);
|
|
7337
|
+
};
|
|
7338
|
+
const scopeManager = getSourceCode().scopeManager;
|
|
7339
|
+
const setStateCallSites = /* @__PURE__ */ new WeakMap();
|
|
7340
|
+
const stateVariables = /* @__PURE__ */ new WeakSet();
|
|
7341
|
+
const stableKnownValueCache = /* @__PURE__ */ new WeakMap();
|
|
7342
|
+
const functionWithoutCapturedValueCache = /* @__PURE__ */ new WeakMap();
|
|
7343
|
+
const useEffectEventVariables = /* @__PURE__ */ new WeakSet();
|
|
7344
|
+
function memoizeWithWeakMap(fn, map) {
|
|
7345
|
+
return function(arg) {
|
|
7346
|
+
if (map.has(arg)) return map.get(arg);
|
|
7347
|
+
const result = fn(arg);
|
|
7348
|
+
map.set(arg, result);
|
|
7349
|
+
return result;
|
|
7350
|
+
};
|
|
7351
|
+
}
|
|
7352
|
+
function visitFunctionWithDependencies(node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, callExpression, dependenciesIndex) {
|
|
7353
|
+
if (isEffect && node.async) reportProblem({
|
|
7354
|
+
node,
|
|
7355
|
+
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"
|
|
7356
|
+
});
|
|
7357
|
+
const scope = scopeManager.acquire(node);
|
|
7358
|
+
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.");
|
|
7359
|
+
const pureScopes = /* @__PURE__ */ new Set();
|
|
7360
|
+
let componentScope = null;
|
|
7361
|
+
{
|
|
7362
|
+
let currentScope = scope.upper;
|
|
7363
|
+
while (currentScope) {
|
|
7364
|
+
pureScopes.add(currentScope);
|
|
7365
|
+
if (currentScope.type === "function" || currentScope.type === "hook" || currentScope.type === "component") break;
|
|
7366
|
+
currentScope = currentScope.upper;
|
|
7367
|
+
}
|
|
7368
|
+
if (!currentScope) return;
|
|
7369
|
+
componentScope = currentScope;
|
|
7370
|
+
}
|
|
7371
|
+
const isArray = Array.isArray;
|
|
7372
|
+
function isStableKnownHookValue(resolved) {
|
|
7373
|
+
if (!isArray(resolved.defs)) return false;
|
|
7374
|
+
const initializers = resolved.defs.filter((definition) => definition.type === "Variable" && definition.node.type === "VariableDeclarator" && definition.node.init != null);
|
|
7375
|
+
if (initializers.length !== 1) return false;
|
|
7376
|
+
const def = initializers[0];
|
|
7377
|
+
const defNode = def.node;
|
|
7378
|
+
if (defNode.type !== "VariableDeclarator") return false;
|
|
7379
|
+
let init = defNode.init;
|
|
7380
|
+
if (init == null) return false;
|
|
7381
|
+
while (init.type === "TSAsExpression" || init.type === "AsExpression") init = init.expression;
|
|
7382
|
+
let declaration = defNode.parent;
|
|
7383
|
+
if (declaration == null && componentScope != null) {
|
|
7384
|
+
fastFindReferenceWithParent(componentScope.block, def.node.id);
|
|
7385
|
+
declaration = def.node.parent;
|
|
7386
|
+
if (declaration == null) return false;
|
|
7387
|
+
}
|
|
7388
|
+
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;
|
|
7389
|
+
if (init.type !== "CallExpression") return false;
|
|
7390
|
+
let callee = init.callee;
|
|
7391
|
+
if (callee.type === "MemberExpression" && "name" in callee.object && callee.object.name === "React" && callee.property != null && !callee.computed) callee = callee.property;
|
|
7392
|
+
if (callee.type !== "Identifier") return false;
|
|
7393
|
+
const id = def.node.id;
|
|
7394
|
+
const { name } = callee;
|
|
7395
|
+
if (name === "useRef" && id.type === "Identifier") return true;
|
|
7396
|
+
else if (isUseEffectEventIdentifier(callee) && id.type === "Identifier") {
|
|
7397
|
+
for (const ref of resolved.references) if (ref !== id) useEffectEventVariables.add(ref.identifier);
|
|
7398
|
+
return true;
|
|
7399
|
+
} else if (name === "useState" || name === "useReducer" || name === "useActionState") {
|
|
7400
|
+
const isActionState = name === "useActionState";
|
|
7401
|
+
if (id.type === "ArrayPattern" && (isActionState ? id.elements.length >= 2 : id.elements.length === 2) && isArray(resolved.identifiers)) {
|
|
7402
|
+
const firstNode = id.elements[0] ?? null;
|
|
7403
|
+
const secondNode = id.elements[1] ?? null;
|
|
7404
|
+
const firstElement = firstNode?.type === "AssignmentPattern" ? firstNode.left : firstNode;
|
|
7405
|
+
const secondElement = secondNode?.type === "AssignmentPattern" ? secondNode.left : secondNode;
|
|
7406
|
+
if (resolved.identifiers.some((identifier) => identifier === secondElement)) {
|
|
7407
|
+
if (name === "useState") {
|
|
7408
|
+
const references = resolved.references;
|
|
7409
|
+
for (const reference of references) {
|
|
7410
|
+
if (reference.isWrite() && reference.init !== true) return false;
|
|
7411
|
+
setStateCallSites.set(reference.identifier, firstElement);
|
|
7412
|
+
}
|
|
7413
|
+
}
|
|
7414
|
+
return true;
|
|
7415
|
+
} else if (resolved.identifiers.some((identifier) => identifier === firstElement)) {
|
|
7416
|
+
if (name === "useState") {
|
|
7417
|
+
const references = resolved.references;
|
|
7418
|
+
for (const reference of references) stateVariables.add(reference.identifier);
|
|
7419
|
+
}
|
|
7420
|
+
return false;
|
|
7421
|
+
}
|
|
7422
|
+
}
|
|
7423
|
+
} else if (name === "useTransition") {
|
|
7424
|
+
if (id.type === "ArrayPattern" && id.elements.length === 2 && Array.isArray(resolved.identifiers)) {
|
|
7425
|
+
const secondNode = id.elements[1] ?? null;
|
|
7426
|
+
const secondElement = secondNode?.type === "AssignmentPattern" ? secondNode.left : secondNode;
|
|
7427
|
+
if (resolved.identifiers.some((identifier) => identifier === secondElement)) return true;
|
|
7428
|
+
}
|
|
7429
|
+
}
|
|
7430
|
+
return false;
|
|
7431
|
+
}
|
|
7432
|
+
function isFunctionWithoutCapturedValues(resolved) {
|
|
7433
|
+
if (!isArray(resolved.defs)) return false;
|
|
7434
|
+
const def = resolved.defs[0];
|
|
7435
|
+
if (def == null) return false;
|
|
7436
|
+
if (def.node == null || def.node.id == null) return false;
|
|
7437
|
+
const fnNode = def.node;
|
|
7438
|
+
const childScopes = componentScope?.childScopes || [];
|
|
7439
|
+
let fnScope = null;
|
|
7440
|
+
for (const childScope of childScopes) {
|
|
7441
|
+
const childScopeBlock = childScope.block;
|
|
7442
|
+
if (fnNode.type === "FunctionDeclaration" && childScopeBlock === fnNode || fnNode.type === "VariableDeclarator" && childScopeBlock.parent === fnNode) {
|
|
7443
|
+
fnScope = childScope;
|
|
7444
|
+
break;
|
|
7445
|
+
}
|
|
7446
|
+
}
|
|
7447
|
+
if (fnScope == null) return false;
|
|
7448
|
+
for (const ref of fnScope.through) {
|
|
7449
|
+
if (ref.resolved == null) continue;
|
|
7450
|
+
if (pureScopes.has(ref.resolved.scope) && !memoizedIsStableKnownHookValue(ref.resolved)) return false;
|
|
7451
|
+
}
|
|
7452
|
+
return true;
|
|
7453
|
+
}
|
|
7454
|
+
const memoizedIsStableKnownHookValue = memoizeWithWeakMap((resolved) => isStableKnownHookValue(resolved) || isConfiguredStableHookValue(resolved, options.hooks), stableKnownValueCache);
|
|
7455
|
+
const memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(isFunctionWithoutCapturedValues, functionWithoutCapturedValueCache);
|
|
7456
|
+
const currentRefsInEffectCleanup = /* @__PURE__ */ new Map();
|
|
7457
|
+
function isInsideEffectCleanup(reference) {
|
|
7458
|
+
let curScope = reference.from;
|
|
7459
|
+
let isInReturnedFunction = false;
|
|
7460
|
+
while (curScope != null && curScope.block !== node) {
|
|
7461
|
+
if (curScope.type === "function") isInReturnedFunction = curScope.block.parent != null && curScope.block.parent.type === "ReturnStatement";
|
|
7462
|
+
curScope = curScope.upper;
|
|
7463
|
+
}
|
|
7464
|
+
return isInReturnedFunction;
|
|
7465
|
+
}
|
|
7466
|
+
const dependencies = /* @__PURE__ */ new Map();
|
|
7467
|
+
const optionalChains = /* @__PURE__ */ new Map();
|
|
7468
|
+
gatherDependenciesRecursively(scope);
|
|
7469
|
+
function gatherDependenciesRecursively(currentScope) {
|
|
7470
|
+
for (const reference of currentScope.references) {
|
|
7471
|
+
if (!reference.resolved) continue;
|
|
7472
|
+
if (!pureScopes.has(reference.resolved.scope)) continue;
|
|
7473
|
+
const referenceNode = fastFindReferenceWithParent(node, reference.identifier);
|
|
7474
|
+
if (referenceNode == null) continue;
|
|
7475
|
+
const dependencyNode = getDependency(referenceNode);
|
|
7476
|
+
const dependency = analyzePropertyChain(dependencyNode, optionalChains);
|
|
7477
|
+
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, {
|
|
7478
|
+
reference,
|
|
7479
|
+
dependencyNode
|
|
7480
|
+
});
|
|
7481
|
+
if (dependencyNode.parent?.type === "TSTypeQuery" || dependencyNode.parent?.type === "TSTypeReference") continue;
|
|
7482
|
+
const def = reference.resolved.defs[0];
|
|
7483
|
+
if (def == null) continue;
|
|
7484
|
+
if (def.node != null && def.node.init === node.parent) continue;
|
|
7485
|
+
if (def.type === "TypeParameter" || dependencyNode.parent?.type === "GenericTypeAnnotation") continue;
|
|
7486
|
+
if (!dependencies.has(dependency)) {
|
|
7487
|
+
const resolved = reference.resolved;
|
|
7488
|
+
const isStable = memoizedIsStableKnownHookValue(resolved) || memoizedIsFunctionWithoutCapturedValues(resolved);
|
|
7489
|
+
dependencies.set(dependency, {
|
|
7490
|
+
isStable,
|
|
7491
|
+
references: [reference]
|
|
7492
|
+
});
|
|
7493
|
+
} else dependencies.get(dependency)?.references.push(reference);
|
|
7494
|
+
}
|
|
7495
|
+
for (const childScope of currentScope.childScopes) gatherDependenciesRecursively(childScope);
|
|
7496
|
+
}
|
|
7497
|
+
currentRefsInEffectCleanup.forEach(({ reference, dependencyNode }, dependency) => {
|
|
7498
|
+
const references = reference.resolved?.references || [];
|
|
7499
|
+
let foundCurrentAssignment = false;
|
|
7500
|
+
for (const ref of references) {
|
|
7501
|
+
const { identifier } = ref;
|
|
7502
|
+
const { parent } = identifier;
|
|
7503
|
+
if (parent != null && parent.type === "MemberExpression" && !parent.computed && parent.property.type === "Identifier" && parent.property.name === "current" && parent.parent?.type === "AssignmentExpression" && parent.parent.left === parent) {
|
|
7504
|
+
foundCurrentAssignment = true;
|
|
7505
|
+
break;
|
|
7506
|
+
}
|
|
7507
|
+
}
|
|
7508
|
+
if (foundCurrentAssignment) return;
|
|
7509
|
+
reportProblem({
|
|
7510
|
+
node: dependencyNode.parent.property,
|
|
7511
|
+
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.`
|
|
7512
|
+
});
|
|
7513
|
+
});
|
|
7514
|
+
const staleAssignments = /* @__PURE__ */ new Set();
|
|
7515
|
+
function reportStaleAssignment(writeExpr, key) {
|
|
7516
|
+
if (staleAssignments.has(key)) return;
|
|
7517
|
+
staleAssignments.add(key);
|
|
7518
|
+
reportProblem({
|
|
7519
|
+
node: writeExpr,
|
|
7520
|
+
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)}.`
|
|
7521
|
+
});
|
|
7522
|
+
}
|
|
7523
|
+
const stableDependencies = /* @__PURE__ */ new Set();
|
|
7524
|
+
dependencies.forEach(({ isStable, references }, key) => {
|
|
7525
|
+
if (isStable) stableDependencies.add(key);
|
|
7526
|
+
references.forEach((reference) => {
|
|
7527
|
+
if (reference.writeExpr) reportStaleAssignment(reference.writeExpr, key);
|
|
7528
|
+
});
|
|
7529
|
+
});
|
|
7530
|
+
if (staleAssignments.size > 0) return;
|
|
7531
|
+
if (!declaredDependenciesNode) {
|
|
7532
|
+
if (isAutoDepsHook) return;
|
|
7533
|
+
let setStateInsideEffectWithoutDeps = null;
|
|
7534
|
+
dependencies.forEach(({ references }, key) => {
|
|
7535
|
+
if (setStateInsideEffectWithoutDeps) return;
|
|
7536
|
+
references.forEach((reference) => {
|
|
7537
|
+
if (setStateInsideEffectWithoutDeps) return;
|
|
7538
|
+
const id = reference.identifier;
|
|
7539
|
+
if (!setStateCallSites.has(id)) return;
|
|
7540
|
+
let fnScope = reference.from;
|
|
7541
|
+
while (fnScope != null && fnScope.type !== "function") fnScope = fnScope.upper;
|
|
7542
|
+
if (fnScope?.block === node) setStateInsideEffectWithoutDeps = key;
|
|
7543
|
+
});
|
|
7544
|
+
});
|
|
7545
|
+
if (setStateInsideEffectWithoutDeps) {
|
|
7546
|
+
const { suggestedDependencies } = collectRecommendations({
|
|
7547
|
+
dependencies,
|
|
7548
|
+
declaredDependencies: [],
|
|
7549
|
+
stableDependencies,
|
|
7550
|
+
externalDependencies: /* @__PURE__ */ new Set(),
|
|
7551
|
+
isEffect: true
|
|
7552
|
+
});
|
|
7553
|
+
const suggestedDependenciesText = `[${suggestedDependencies.join(", ")}]`;
|
|
7554
|
+
const dependenciesArgument = callExpression.arguments[dependenciesIndex];
|
|
7555
|
+
const hasSpreadArgumentBeforeOrAtDependencies = callExpression.arguments.slice(0, dependenciesIndex + 1).some((argument) => argument?.type === "SpreadElement");
|
|
7556
|
+
let fix = null;
|
|
7557
|
+
if (!hasSpreadArgumentBeforeOrAtDependencies) {
|
|
7558
|
+
if (dependenciesArgument?.type === "Identifier" && dependenciesArgument.name === "undefined") fix = (fixer) => fixer.replaceText(dependenciesArgument, suggestedDependenciesText);
|
|
7559
|
+
else if (dependenciesArgument == null && dependenciesIndex === callExpression.arguments.length) {
|
|
7560
|
+
const closeParen = getSourceCode().getLastToken(callExpression);
|
|
7561
|
+
if (closeParen != null && closeParen.value === ")") {
|
|
7562
|
+
const tokenBeforeCloseParen = getSourceCode().getTokenBefore(closeParen);
|
|
7563
|
+
fix = tokenBeforeCloseParen?.value === "," ? (fixer) => fixer.insertTextAfter(tokenBeforeCloseParen, ` ${suggestedDependenciesText}`) : (fixer) => fixer.insertTextBefore(closeParen, `, ${suggestedDependenciesText}`);
|
|
7564
|
+
}
|
|
7565
|
+
}
|
|
7566
|
+
}
|
|
7567
|
+
const dependenciesArgumentText = dependenciesIndex === 1 ? "as a second argument" : `as the dependencies argument (index ${dependenciesIndex})`;
|
|
7568
|
+
const problem = {
|
|
7569
|
+
node: reactiveHook,
|
|
7570
|
+
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.`
|
|
7571
|
+
};
|
|
7572
|
+
if (fix != null) problem.suggest = [{
|
|
7573
|
+
desc: `Add dependencies array: ${suggestedDependenciesText}`,
|
|
7574
|
+
fix
|
|
7575
|
+
}];
|
|
7576
|
+
reportProblem(problem);
|
|
7577
|
+
}
|
|
7578
|
+
return;
|
|
7579
|
+
}
|
|
7580
|
+
if (isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) return;
|
|
7581
|
+
const declaredDependencies = [];
|
|
7582
|
+
const externalDependencies = /* @__PURE__ */ new Set();
|
|
7583
|
+
const isArrayExpression = declaredDependenciesNode.type === "ArrayExpression";
|
|
7584
|
+
const isTSAsArrayExpression = declaredDependenciesNode.type === "TSAsExpression" && declaredDependenciesNode.expression.type === "ArrayExpression";
|
|
7585
|
+
if (!isArrayExpression && !isTSAsArrayExpression) reportProblem({
|
|
7586
|
+
node: declaredDependenciesNode,
|
|
7587
|
+
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.`
|
|
7588
|
+
});
|
|
7589
|
+
else (isTSAsArrayExpression ? declaredDependenciesNode.expression : declaredDependenciesNode).elements.forEach((declaredDependencyNode) => {
|
|
7590
|
+
if (declaredDependencyNode === null) return;
|
|
7591
|
+
if (declaredDependencyNode.type === "SpreadElement") {
|
|
7592
|
+
reportProblem({
|
|
7593
|
+
node: declaredDependencyNode,
|
|
7594
|
+
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.`
|
|
7595
|
+
});
|
|
7596
|
+
return;
|
|
7597
|
+
}
|
|
7598
|
+
if (useEffectEventVariables.has(declaredDependencyNode)) reportProblem({
|
|
7599
|
+
node: declaredDependencyNode,
|
|
7600
|
+
message: `Functions returned from \`useEffectEvent\` must not be included in the dependency array. Remove \`${getSourceCode().getText(declaredDependencyNode)}\` from the list.`,
|
|
7601
|
+
suggest: [{
|
|
7602
|
+
desc: `Remove the dependency \`${getSourceCode().getText(declaredDependencyNode)}\``,
|
|
7603
|
+
fix(fixer) {
|
|
7604
|
+
return fixer.removeRange(declaredDependencyNode.range);
|
|
7605
|
+
}
|
|
7606
|
+
}]
|
|
7607
|
+
});
|
|
7608
|
+
let declaredDependency;
|
|
7609
|
+
try {
|
|
7610
|
+
declaredDependency = analyzePropertyChain(declaredDependencyNode, null);
|
|
7611
|
+
} catch (error) {
|
|
7612
|
+
if (error instanceof Error && /Unsupported node type/.test(error.message)) {
|
|
7613
|
+
if (declaredDependencyNode.type === "Literal") {
|
|
7614
|
+
if (declaredDependencyNode.value && dependencies.has(declaredDependencyNode.value)) reportProblem({
|
|
7615
|
+
node: declaredDependencyNode,
|
|
7616
|
+
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?`
|
|
7617
|
+
});
|
|
7618
|
+
else reportProblem({
|
|
7619
|
+
node: declaredDependencyNode,
|
|
7620
|
+
message: `The ${declaredDependencyNode.raw} literal is not a valid dependency because it never changes. You can safely remove it.`
|
|
7621
|
+
});
|
|
7622
|
+
} else reportProblem({
|
|
7623
|
+
node: declaredDependencyNode,
|
|
7624
|
+
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.`
|
|
7625
|
+
});
|
|
7626
|
+
return;
|
|
7627
|
+
} else throw error;
|
|
7628
|
+
}
|
|
7629
|
+
let maybeID = declaredDependencyNode;
|
|
7630
|
+
while (maybeID.type === "MemberExpression" || maybeID.type === "OptionalMemberExpression" || maybeID.type === "ChainExpression") maybeID = maybeID.object || maybeID.expression.object;
|
|
7631
|
+
const isDeclaredInComponent = !componentScope.through.some((ref) => ref.identifier === maybeID);
|
|
7632
|
+
declaredDependencies.push({
|
|
7633
|
+
key: declaredDependency,
|
|
7634
|
+
node: declaredDependencyNode
|
|
7635
|
+
});
|
|
7636
|
+
if (!isDeclaredInComponent) externalDependencies.add(declaredDependency);
|
|
7637
|
+
});
|
|
7638
|
+
const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies } = collectRecommendations({
|
|
7639
|
+
dependencies,
|
|
7640
|
+
declaredDependencies,
|
|
7641
|
+
stableDependencies,
|
|
7642
|
+
externalDependencies,
|
|
7643
|
+
isEffect
|
|
7644
|
+
});
|
|
7645
|
+
let suggestedDeps = suggestedDependencies;
|
|
7646
|
+
if (duplicateDependencies.size + missingDependencies.size + unnecessaryDependencies.size === 0) {
|
|
7647
|
+
scanForConstructions({
|
|
7648
|
+
declaredDependencies,
|
|
7649
|
+
declaredDependenciesNode,
|
|
7650
|
+
componentScope,
|
|
7651
|
+
scope
|
|
7652
|
+
}).forEach(({ construction, isUsedOutsideOfHook, depType }) => {
|
|
7653
|
+
const wrapperHook = depType === "function" ? "useCallback" : "useMemo";
|
|
7654
|
+
const constructionType = depType === "function" ? "definition" : "initialization";
|
|
7655
|
+
const defaultAdvice = `wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`;
|
|
7656
|
+
const advice = isUsedOutsideOfHook ? `To fix this, ${defaultAdvice}` : `Move it inside the ${reactiveHookName} callback. Alternatively, ${defaultAdvice}`;
|
|
7657
|
+
const causation = depType === "conditional" || depType === "logical expression" ? "could make" : "makes";
|
|
7658
|
+
const message = `The '${construction.name.name}' ${depType} ${causation} the dependencies of ${reactiveHookName} Hook (at line ${declaredDependenciesNode.loc?.start.line}) change on every render. ${advice}`;
|
|
7659
|
+
let suggest;
|
|
7660
|
+
if (isUsedOutsideOfHook && construction.type === "Variable" && depType === "function") suggest = [{
|
|
7661
|
+
desc: `Wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`,
|
|
7662
|
+
fix(fixer) {
|
|
7663
|
+
const [before, after] = wrapperHook === "useMemo" ? [`useMemo(() => { return `, "; })"] : ["useCallback(", ")"];
|
|
7664
|
+
return [fixer.insertTextBefore(construction.node.init, before), fixer.insertTextAfter(construction.node.init, after)];
|
|
7665
|
+
}
|
|
7666
|
+
}];
|
|
7667
|
+
reportProblem({
|
|
7668
|
+
node: construction.node,
|
|
7669
|
+
message,
|
|
7670
|
+
suggest
|
|
7671
|
+
});
|
|
7672
|
+
});
|
|
7673
|
+
return;
|
|
7674
|
+
}
|
|
7675
|
+
if (!isEffect && missingDependencies.size > 0) suggestedDeps = collectRecommendations({
|
|
7676
|
+
dependencies,
|
|
7677
|
+
declaredDependencies: [],
|
|
7678
|
+
stableDependencies,
|
|
7679
|
+
externalDependencies,
|
|
7680
|
+
isEffect
|
|
7681
|
+
}).suggestedDependencies;
|
|
7682
|
+
function areDeclaredDepsAlphabetized() {
|
|
7683
|
+
if (declaredDependencies.length === 0) return true;
|
|
7684
|
+
const declaredDepKeys = declaredDependencies.map((dep) => dep.key);
|
|
7685
|
+
const sortedDeclaredDepKeys = declaredDepKeys.slice().sort();
|
|
7686
|
+
return declaredDepKeys.join(",") === sortedDeclaredDepKeys.join(",");
|
|
7687
|
+
}
|
|
7688
|
+
if (areDeclaredDepsAlphabetized()) suggestedDeps.sort();
|
|
7689
|
+
function formatDependency(path) {
|
|
7690
|
+
const members = path.split(".");
|
|
7691
|
+
let finalPath = "";
|
|
7692
|
+
for (let i = 0; i < members.length; i++) {
|
|
7693
|
+
if (i !== 0) {
|
|
7694
|
+
const pathSoFar = members.slice(0, i + 1).join(".");
|
|
7695
|
+
const isOptional = optionalChains.get(pathSoFar) === true;
|
|
7696
|
+
finalPath += isOptional ? "?." : ".";
|
|
7697
|
+
}
|
|
7698
|
+
finalPath += members[i];
|
|
7699
|
+
}
|
|
7700
|
+
return finalPath;
|
|
7701
|
+
}
|
|
7702
|
+
function getWarningMessage(deps, singlePrefix, label, fixVerb) {
|
|
7703
|
+
if (deps.size === 0) return null;
|
|
7704
|
+
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.`;
|
|
7705
|
+
}
|
|
7706
|
+
let extraWarning = "";
|
|
7707
|
+
if (unnecessaryDependencies.size > 0) {
|
|
7708
|
+
let badRef = null;
|
|
7709
|
+
Array.from(unnecessaryDependencies.keys()).forEach((key) => {
|
|
7710
|
+
if (badRef !== null) return;
|
|
7711
|
+
if (key.endsWith(".current")) badRef = key;
|
|
7712
|
+
});
|
|
7713
|
+
if (badRef !== null) extraWarning = ` Mutable values like '${badRef}' aren't valid dependencies because mutating them doesn't re-render the component.`;
|
|
7714
|
+
else if (externalDependencies.size > 0) {
|
|
7715
|
+
const dep = Array.from(externalDependencies)[0];
|
|
7716
|
+
if (!scope.set.has(dep)) extraWarning = ` Outer scope values like '${dep}' aren't valid dependencies because mutating them doesn't re-render the component.`;
|
|
7717
|
+
}
|
|
7718
|
+
}
|
|
7719
|
+
if (!extraWarning && missingDependencies.has("props")) {
|
|
7720
|
+
const propDep = dependencies.get("props");
|
|
7721
|
+
if (propDep == null) return;
|
|
7722
|
+
const refs = propDep.references;
|
|
7723
|
+
if (!Array.isArray(refs)) return;
|
|
7724
|
+
let isPropsOnlyUsedInMembers = true;
|
|
7725
|
+
for (const ref of refs) {
|
|
7726
|
+
const id = fastFindReferenceWithParent(componentScope.block, ref.identifier);
|
|
7727
|
+
if (!id) {
|
|
7728
|
+
isPropsOnlyUsedInMembers = false;
|
|
7729
|
+
break;
|
|
7730
|
+
}
|
|
7731
|
+
const parent = id.parent;
|
|
7732
|
+
if (parent == null) {
|
|
7733
|
+
isPropsOnlyUsedInMembers = false;
|
|
7734
|
+
break;
|
|
7735
|
+
}
|
|
7736
|
+
if (parent.type !== "MemberExpression" && parent.type !== "OptionalMemberExpression") {
|
|
7737
|
+
isPropsOnlyUsedInMembers = false;
|
|
7738
|
+
break;
|
|
7739
|
+
}
|
|
7740
|
+
}
|
|
7741
|
+
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)}.`;
|
|
7742
|
+
}
|
|
7743
|
+
if (!extraWarning && missingDependencies.size > 0) {
|
|
7744
|
+
let missingCallbackDep = null;
|
|
7745
|
+
missingDependencies.forEach((missingDep) => {
|
|
7746
|
+
if (missingCallbackDep) return;
|
|
7747
|
+
const topScopeRef = componentScope.set.get(missingDep);
|
|
7748
|
+
const usedDep = dependencies.get(missingDep);
|
|
7749
|
+
if (!usedDep?.references || usedDep?.references[0]?.resolved !== topScopeRef) return;
|
|
7750
|
+
const def = topScopeRef?.defs[0];
|
|
7751
|
+
if (def == null || def.name == null || def.type !== "Parameter") return;
|
|
7752
|
+
let isFunctionCall = false;
|
|
7753
|
+
let id;
|
|
7754
|
+
for (const reference of usedDep.references) {
|
|
7755
|
+
id = reference.identifier;
|
|
7756
|
+
if (id != null && id.parent != null && (id.parent.type === "CallExpression" || id.parent.type === "OptionalCallExpression") && id.parent.callee === id) {
|
|
7757
|
+
isFunctionCall = true;
|
|
7758
|
+
break;
|
|
7759
|
+
}
|
|
7760
|
+
}
|
|
7761
|
+
if (!isFunctionCall) return;
|
|
7762
|
+
missingCallbackDep = missingDep;
|
|
7763
|
+
});
|
|
7764
|
+
if (missingCallbackDep !== null) extraWarning = ` If '${missingCallbackDep}' changes too often, find the parent component that defines it and wrap that definition in useCallback.`;
|
|
7765
|
+
}
|
|
7766
|
+
if (!extraWarning && missingDependencies.size > 0) {
|
|
7767
|
+
let setStateRecommendation = null;
|
|
7768
|
+
for (const missingDep of missingDependencies) {
|
|
7769
|
+
if (setStateRecommendation !== null) break;
|
|
7770
|
+
const references = dependencies.get(missingDep).references;
|
|
7771
|
+
let id;
|
|
7772
|
+
let maybeCall;
|
|
7773
|
+
for (const reference of references) {
|
|
7774
|
+
id = reference.identifier;
|
|
7775
|
+
maybeCall = id.parent;
|
|
7776
|
+
while (maybeCall != null && maybeCall !== componentScope.block) {
|
|
7777
|
+
if (maybeCall.type === "CallExpression") {
|
|
7778
|
+
const correspondingStateVariable = setStateCallSites.get(maybeCall.callee);
|
|
7779
|
+
if (correspondingStateVariable != null) {
|
|
7780
|
+
if ("name" in correspondingStateVariable && correspondingStateVariable.name === missingDep) setStateRecommendation = {
|
|
7781
|
+
missingDep,
|
|
7782
|
+
setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
|
|
7783
|
+
form: "updater"
|
|
7784
|
+
};
|
|
7785
|
+
else if (stateVariables.has(id)) setStateRecommendation = {
|
|
7786
|
+
missingDep,
|
|
7787
|
+
setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
|
|
7788
|
+
form: "reducer"
|
|
7789
|
+
};
|
|
7790
|
+
else {
|
|
7791
|
+
const resolved = reference.resolved;
|
|
7792
|
+
if (resolved != null) {
|
|
7793
|
+
const def = resolved.defs[0];
|
|
7794
|
+
if (def != null && def.type === "Parameter") setStateRecommendation = {
|
|
7795
|
+
missingDep,
|
|
7796
|
+
setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
|
|
7797
|
+
form: "inlineReducer"
|
|
7798
|
+
};
|
|
7799
|
+
}
|
|
7800
|
+
}
|
|
7801
|
+
break;
|
|
7802
|
+
}
|
|
7803
|
+
}
|
|
7804
|
+
maybeCall = maybeCall.parent;
|
|
7805
|
+
}
|
|
7806
|
+
if (setStateRecommendation !== null) break;
|
|
7807
|
+
}
|
|
7808
|
+
}
|
|
7809
|
+
if (setStateRecommendation !== null) switch (setStateRecommendation.form) {
|
|
7810
|
+
case "reducer":
|
|
7811
|
+
extraWarning = ` You can also replace multiple useState variables with useReducer if '${setStateRecommendation.setter}' needs the current value of '${setStateRecommendation.missingDep}'.`;
|
|
7812
|
+
break;
|
|
7813
|
+
case "inlineReducer":
|
|
7814
|
+
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.`;
|
|
7815
|
+
break;
|
|
7816
|
+
case "updater":
|
|
7817
|
+
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.`;
|
|
7818
|
+
break;
|
|
7819
|
+
default: throw new Error("Unknown case.");
|
|
7820
|
+
}
|
|
7821
|
+
}
|
|
7822
|
+
reportProblem({
|
|
7823
|
+
node: declaredDependenciesNode,
|
|
7824
|
+
message: `React Hook ${getSourceCode().getText(reactiveHook)} has ` + (getWarningMessage(missingDependencies, "a", "missing", "include") || getWarningMessage(unnecessaryDependencies, "an", "unnecessary", "exclude") || getWarningMessage(duplicateDependencies, "a", "duplicate", "omit")) + extraWarning,
|
|
7825
|
+
suggest: [{
|
|
7826
|
+
desc: `Update the dependencies array to be: [${suggestedDeps.map(formatDependency).join(", ")}]`,
|
|
7827
|
+
fix(fixer) {
|
|
7828
|
+
return fixer.replaceText(declaredDependenciesNode, `[${suggestedDeps.map(formatDependency).join(", ")}]`);
|
|
7829
|
+
}
|
|
7830
|
+
}]
|
|
7831
|
+
});
|
|
7832
|
+
}
|
|
7833
|
+
function visitCallExpression(node) {
|
|
7834
|
+
const configuredHook = getReactiveHookConfig(node, options.hooks);
|
|
7835
|
+
const callbackIndex = configuredHook ? configuredHook.closureIndex : getReactiveHookCallbackIndex(node.callee, options);
|
|
7836
|
+
if (callbackIndex === -1) return;
|
|
7837
|
+
let callback = node.arguments[callbackIndex];
|
|
7838
|
+
const reactiveHook = node.callee;
|
|
7839
|
+
const nodeWithoutNamespace = getNodeWithoutReactNamespace(reactiveHook);
|
|
7840
|
+
const reactiveHookName = configuredHook?.name ?? ("name" in nodeWithoutNamespace ? nodeWithoutNamespace.name : "");
|
|
7841
|
+
const dependenciesIndex = configuredHook ? configuredHook.dependenciesIndex : callbackIndex + 1;
|
|
7842
|
+
const maybeNode = node.arguments[dependenciesIndex];
|
|
7843
|
+
const declaredDependenciesNode = maybeNode && !(maybeNode.type === "Identifier" && maybeNode.name === "undefined") ? maybeNode : void 0;
|
|
7844
|
+
const isEffect = /Effect($|[^a-z])/g.test(reactiveHookName);
|
|
7845
|
+
if (!callback) {
|
|
7846
|
+
if (configuredHook) {
|
|
7847
|
+
const builtInCallbackIndex = getReactiveHookCallbackIndex(reactiveHook, { additionalHooks: void 0 });
|
|
7848
|
+
const builtInCallback = builtInCallbackIndex === -1 ? null : node.arguments[builtInCallbackIndex];
|
|
7849
|
+
if (builtInCallbackIndex === -1 || builtInCallback != null) return;
|
|
7850
|
+
}
|
|
7851
|
+
reportProblem({
|
|
7852
|
+
node: reactiveHook,
|
|
7853
|
+
message: `React Hook ${reactiveHookName} requires an effect callback. Did you forget to pass a callback to the hook?`
|
|
7854
|
+
});
|
|
7855
|
+
return;
|
|
7856
|
+
}
|
|
7857
|
+
if (!maybeNode && isEffect && options.requireExplicitEffectDeps) reportProblem({
|
|
7858
|
+
node: reactiveHook,
|
|
7859
|
+
message: `React Hook ${reactiveHookName} always requires dependencies. Please add a dependency array or an explicit \`undefined\``
|
|
7860
|
+
});
|
|
7861
|
+
const isAutoDepsHook = options.experimental_autoDependenciesHooks.includes(reactiveHookName);
|
|
7862
|
+
if ((!declaredDependenciesNode || isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) && !isEffect) {
|
|
7863
|
+
if (reactiveHookName === "useMemo" || reactiveHookName === "useCallback") reportProblem({
|
|
7864
|
+
node: reactiveHook,
|
|
7865
|
+
message: `React Hook ${reactiveHookName} does nothing when called with only one argument. Did you forget to pass an array of dependencies?`
|
|
7866
|
+
});
|
|
7867
|
+
return;
|
|
7868
|
+
}
|
|
7869
|
+
while (callback.type === "TSAsExpression" || callback.type === "AsExpression") callback = callback.expression;
|
|
7870
|
+
switch (callback.type) {
|
|
7871
|
+
case "FunctionExpression":
|
|
7872
|
+
case "ArrowFunctionExpression":
|
|
7873
|
+
visitFunctionWithDependencies(callback, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
|
|
7874
|
+
return;
|
|
7875
|
+
case "Identifier":
|
|
7876
|
+
if (!declaredDependenciesNode || isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) return;
|
|
7877
|
+
if ("elements" in declaredDependenciesNode && declaredDependenciesNode.elements && declaredDependenciesNode.elements.some((el) => el && el.type === "Identifier" && el.name === callback.name)) return;
|
|
7878
|
+
const variable = getScope(callback).set.get(callback.name);
|
|
7879
|
+
if (variable == null || variable.defs == null) return;
|
|
7880
|
+
const def = variable.defs[0];
|
|
7881
|
+
if (!def || !def.node) break;
|
|
7882
|
+
if (def.type === "Parameter") {
|
|
7883
|
+
reportProblem({
|
|
7884
|
+
node: reactiveHook,
|
|
7885
|
+
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
7886
|
+
});
|
|
7887
|
+
return;
|
|
7888
|
+
}
|
|
7889
|
+
if (def.type !== "Variable" && def.type !== "FunctionName") break;
|
|
7890
|
+
switch (def.node.type) {
|
|
7891
|
+
case "FunctionDeclaration":
|
|
7892
|
+
visitFunctionWithDependencies(def.node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
|
|
7893
|
+
return;
|
|
7894
|
+
case "VariableDeclarator":
|
|
7895
|
+
const init = def.node.init;
|
|
7896
|
+
if (!init) break;
|
|
7897
|
+
switch (init.type) {
|
|
7898
|
+
case "ArrowFunctionExpression":
|
|
7899
|
+
case "FunctionExpression":
|
|
7900
|
+
visitFunctionWithDependencies(init, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
|
|
7901
|
+
return;
|
|
7902
|
+
}
|
|
7903
|
+
}
|
|
7904
|
+
break;
|
|
7905
|
+
default:
|
|
7906
|
+
if (configuredHook) return;
|
|
7907
|
+
reportProblem({
|
|
7908
|
+
node: reactiveHook,
|
|
7909
|
+
message: getUnknownDependenciesMessage(reactiveHookName)
|
|
7910
|
+
});
|
|
7911
|
+
return;
|
|
7912
|
+
}
|
|
7913
|
+
reportProblem({
|
|
7914
|
+
node: reactiveHook,
|
|
7915
|
+
message: `React Hook ${reactiveHookName} has a missing dependency: '${callback.name}'. Either include it or remove the dependency array.`,
|
|
7916
|
+
suggest: [{
|
|
7917
|
+
desc: `Update the dependencies array to be: [${callback.name}]`,
|
|
7918
|
+
fix(fixer) {
|
|
7919
|
+
return fixer.replaceText(declaredDependenciesNode, `[${callback.name}]`);
|
|
7920
|
+
}
|
|
7921
|
+
}]
|
|
7922
|
+
});
|
|
7923
|
+
}
|
|
7924
|
+
return { CallExpression: visitCallExpression };
|
|
7925
|
+
}
|
|
7926
|
+
};
|
|
7927
|
+
function collectRecommendations({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect }) {
|
|
7928
|
+
const depTree = createDepTree();
|
|
7929
|
+
function createDepTree() {
|
|
7930
|
+
return {
|
|
7931
|
+
isUsed: false,
|
|
7932
|
+
isSatisfiedRecursively: false,
|
|
7933
|
+
isSubtreeUsed: false,
|
|
7934
|
+
children: /* @__PURE__ */ new Map()
|
|
7935
|
+
};
|
|
7936
|
+
}
|
|
7937
|
+
dependencies.forEach((_, key) => {
|
|
7938
|
+
const node = getOrCreateNodeByPath(depTree, key);
|
|
7939
|
+
node.isUsed = true;
|
|
7940
|
+
markAllParentsByPath(depTree, key, (parent) => {
|
|
7941
|
+
parent.isSubtreeUsed = true;
|
|
7942
|
+
});
|
|
7943
|
+
});
|
|
7944
|
+
declaredDependencies.forEach(({ key }) => {
|
|
7945
|
+
const node = getOrCreateNodeByPath(depTree, key);
|
|
7946
|
+
node.isSatisfiedRecursively = true;
|
|
7947
|
+
});
|
|
7948
|
+
stableDependencies.forEach((key) => {
|
|
7949
|
+
const node = getOrCreateNodeByPath(depTree, key);
|
|
7950
|
+
node.isSatisfiedRecursively = true;
|
|
7951
|
+
});
|
|
7952
|
+
function getOrCreateNodeByPath(rootNode, path) {
|
|
7953
|
+
const keys = path.split(".");
|
|
7954
|
+
let node = rootNode;
|
|
7955
|
+
for (const key of keys) {
|
|
7956
|
+
let child = node.children.get(key);
|
|
7957
|
+
if (!child) {
|
|
7958
|
+
child = createDepTree();
|
|
7959
|
+
node.children.set(key, child);
|
|
7960
|
+
}
|
|
7961
|
+
node = child;
|
|
7962
|
+
}
|
|
7963
|
+
return node;
|
|
7964
|
+
}
|
|
7965
|
+
function markAllParentsByPath(rootNode, path, fn) {
|
|
7966
|
+
const keys = path.split(".");
|
|
7967
|
+
let node = rootNode;
|
|
7968
|
+
for (const key of keys) {
|
|
7969
|
+
const child = node.children.get(key);
|
|
7970
|
+
if (!child) return;
|
|
7971
|
+
fn(child);
|
|
7972
|
+
node = child;
|
|
7973
|
+
}
|
|
7974
|
+
}
|
|
7975
|
+
const missingDependencies = /* @__PURE__ */ new Set();
|
|
7976
|
+
const satisfyingDependencies = /* @__PURE__ */ new Set();
|
|
7977
|
+
scanTreeRecursively(depTree, missingDependencies, satisfyingDependencies, (key) => key);
|
|
7978
|
+
function scanTreeRecursively(node, missingPaths, satisfyingPaths, keyToPath) {
|
|
7979
|
+
node.children.forEach((child, key) => {
|
|
7980
|
+
const path = keyToPath(key);
|
|
7981
|
+
if (child.isSatisfiedRecursively) {
|
|
7982
|
+
if (child.isSubtreeUsed) satisfyingPaths.add(path);
|
|
7983
|
+
return;
|
|
7984
|
+
}
|
|
7985
|
+
if (child.isUsed) {
|
|
7986
|
+
missingPaths.add(path);
|
|
7987
|
+
return;
|
|
7988
|
+
}
|
|
7989
|
+
scanTreeRecursively(child, missingPaths, satisfyingPaths, (childKey) => path + "." + childKey);
|
|
7990
|
+
});
|
|
7991
|
+
}
|
|
7992
|
+
const suggestedDependencies = [];
|
|
7993
|
+
const unnecessaryDependencies = /* @__PURE__ */ new Set();
|
|
7994
|
+
const duplicateDependencies = /* @__PURE__ */ new Set();
|
|
7995
|
+
declaredDependencies.forEach(({ key }) => {
|
|
7996
|
+
if (satisfyingDependencies.has(key)) {
|
|
7997
|
+
if (suggestedDependencies.indexOf(key) === -1) suggestedDependencies.push(key);
|
|
7998
|
+
else duplicateDependencies.add(key);
|
|
7999
|
+
} else if (isEffect && !key.endsWith(".current") && !externalDependencies.has(key)) {
|
|
8000
|
+
if (suggestedDependencies.indexOf(key) === -1) suggestedDependencies.push(key);
|
|
8001
|
+
} else unnecessaryDependencies.add(key);
|
|
8002
|
+
});
|
|
8003
|
+
missingDependencies.forEach((key) => {
|
|
8004
|
+
suggestedDependencies.push(key);
|
|
8005
|
+
});
|
|
8006
|
+
return {
|
|
8007
|
+
suggestedDependencies,
|
|
8008
|
+
unnecessaryDependencies,
|
|
8009
|
+
duplicateDependencies,
|
|
8010
|
+
missingDependencies
|
|
8011
|
+
};
|
|
8012
|
+
}
|
|
8013
|
+
function getConstructionExpressionType(node) {
|
|
8014
|
+
switch (node.type) {
|
|
8015
|
+
case "ObjectExpression": return "object";
|
|
8016
|
+
case "ArrayExpression": return "array";
|
|
8017
|
+
case "ArrowFunctionExpression":
|
|
8018
|
+
case "FunctionExpression": return "function";
|
|
8019
|
+
case "ClassExpression": return "class";
|
|
8020
|
+
case "ConditionalExpression":
|
|
8021
|
+
if (getConstructionExpressionType(node.consequent) != null || getConstructionExpressionType(node.alternate) != null) return "conditional";
|
|
8022
|
+
return null;
|
|
8023
|
+
case "LogicalExpression":
|
|
8024
|
+
if (getConstructionExpressionType(node.left) != null || getConstructionExpressionType(node.right) != null) return "logical expression";
|
|
8025
|
+
return null;
|
|
8026
|
+
case "JSXFragment": return "JSX fragment";
|
|
8027
|
+
case "JSXElement": return "JSX element";
|
|
8028
|
+
case "AssignmentExpression":
|
|
8029
|
+
if (getConstructionExpressionType(node.right) != null) return "assignment expression";
|
|
8030
|
+
return null;
|
|
8031
|
+
case "NewExpression": return "object construction";
|
|
8032
|
+
case "Literal":
|
|
8033
|
+
if (node.value instanceof RegExp) return "regular expression";
|
|
8034
|
+
return null;
|
|
8035
|
+
case "TypeCastExpression":
|
|
8036
|
+
case "AsExpression":
|
|
8037
|
+
case "TSAsExpression": return getConstructionExpressionType(node.expression);
|
|
8038
|
+
}
|
|
8039
|
+
return null;
|
|
8040
|
+
}
|
|
8041
|
+
function scanForConstructions({ declaredDependencies, declaredDependenciesNode, componentScope, scope }) {
|
|
8042
|
+
const constructions = declaredDependencies.map(({ key }) => {
|
|
8043
|
+
const ref = componentScope.variables.find((v) => v.name === key);
|
|
8044
|
+
if (ref == null) return null;
|
|
8045
|
+
const node = ref.defs[0];
|
|
8046
|
+
if (node == null) return null;
|
|
8047
|
+
if (node.type === "Variable" && node.node.type === "VariableDeclarator" && node.node.id.type === "Identifier" && node.node.init != null) {
|
|
8048
|
+
const constantExpressionType = getConstructionExpressionType(node.node.init);
|
|
8049
|
+
if (constantExpressionType) return [ref, constantExpressionType];
|
|
8050
|
+
}
|
|
8051
|
+
if (node.type === "FunctionName" && node.node.type === "FunctionDeclaration") return [ref, "function"];
|
|
8052
|
+
if (node.type === "ClassName" && node.node.type === "ClassDeclaration") return [ref, "class"];
|
|
8053
|
+
return null;
|
|
8054
|
+
}).filter(Boolean);
|
|
8055
|
+
function isUsedOutsideOfHook(ref) {
|
|
8056
|
+
let foundWriteExpr = false;
|
|
8057
|
+
for (const reference of ref.references) {
|
|
8058
|
+
if (reference.writeExpr) {
|
|
8059
|
+
if (foundWriteExpr) return true;
|
|
8060
|
+
else {
|
|
8061
|
+
foundWriteExpr = true;
|
|
8062
|
+
continue;
|
|
8063
|
+
}
|
|
8064
|
+
}
|
|
8065
|
+
let currentScope = reference.from;
|
|
8066
|
+
while (currentScope !== scope && currentScope != null) currentScope = currentScope.upper;
|
|
8067
|
+
if (currentScope !== scope) {
|
|
8068
|
+
if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) return true;
|
|
8069
|
+
}
|
|
8070
|
+
}
|
|
8071
|
+
return false;
|
|
8072
|
+
}
|
|
8073
|
+
return constructions.map(([ref, depType]) => ({
|
|
8074
|
+
construction: ref.defs[0],
|
|
8075
|
+
depType,
|
|
8076
|
+
isUsedOutsideOfHook: isUsedOutsideOfHook(ref)
|
|
8077
|
+
}));
|
|
8078
|
+
}
|
|
8079
|
+
function getDependency(node) {
|
|
8080
|
+
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);
|
|
8081
|
+
else if (node.type === "MemberExpression" && node.parent && node.parent.type === "AssignmentExpression" && node.parent.left === node) return node.object;
|
|
8082
|
+
else return node;
|
|
8083
|
+
}
|
|
8084
|
+
function markNode(node, optionalChains, result) {
|
|
8085
|
+
if (optionalChains) {
|
|
8086
|
+
if ("optional" in node && node.optional) {
|
|
8087
|
+
if (!optionalChains.has(result)) optionalChains.set(result, true);
|
|
8088
|
+
} else optionalChains.set(result, false);
|
|
8089
|
+
}
|
|
8090
|
+
}
|
|
8091
|
+
function analyzePropertyChain(node, optionalChains) {
|
|
8092
|
+
if (node.type === "Identifier" || node.type === "JSXIdentifier") {
|
|
8093
|
+
const result = node.name;
|
|
8094
|
+
if (optionalChains) optionalChains.set(result, false);
|
|
8095
|
+
return result;
|
|
8096
|
+
} else if (node.type === "MemberExpression" && !node.computed) {
|
|
8097
|
+
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
8098
|
+
markNode(node, optionalChains, result);
|
|
8099
|
+
return result;
|
|
8100
|
+
} else if (node.type === "OptionalMemberExpression" && !node.computed) {
|
|
8101
|
+
const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
|
|
8102
|
+
markNode(node, optionalChains, result);
|
|
8103
|
+
return result;
|
|
8104
|
+
} else if (node.type === "ChainExpression" && (!("computed" in node) || !node.computed)) {
|
|
8105
|
+
const expression = node.expression;
|
|
8106
|
+
if (expression.type === "CallExpression") throw new Error(`Unsupported node type: ${expression.type}`);
|
|
8107
|
+
const result = `${analyzePropertyChain(expression.object, optionalChains)}.${analyzePropertyChain(expression.property, null)}`;
|
|
8108
|
+
markNode(expression, optionalChains, result);
|
|
8109
|
+
return result;
|
|
8110
|
+
} else throw new Error(`Unsupported node type: ${node.type}`);
|
|
8111
|
+
}
|
|
8112
|
+
function getNodeWithoutReactNamespace(node) {
|
|
8113
|
+
if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "React" && node.property.type === "Identifier" && !node.computed) return node.property;
|
|
8114
|
+
return node;
|
|
8115
|
+
}
|
|
8116
|
+
function getReactiveHookCallbackIndex(calleeNode, options) {
|
|
8117
|
+
const node = getNodeWithoutReactNamespace(calleeNode);
|
|
8118
|
+
if (node.type !== "Identifier") return -1;
|
|
8119
|
+
switch (node.name) {
|
|
8120
|
+
case "useEffect":
|
|
8121
|
+
case "useLayoutEffect":
|
|
8122
|
+
case "useCallback":
|
|
8123
|
+
case "useMemo": return 0;
|
|
8124
|
+
case "useImperativeHandle": return 1;
|
|
8125
|
+
default: if (node === calleeNode && options && options.additionalHooks) {
|
|
8126
|
+
let name;
|
|
8127
|
+
try {
|
|
8128
|
+
name = analyzePropertyChain(node, null);
|
|
8129
|
+
} catch (error) {
|
|
8130
|
+
if (error instanceof Error && /Unsupported node type/.test(error.message)) return 0;
|
|
8131
|
+
else throw error;
|
|
8132
|
+
}
|
|
8133
|
+
if (options.additionalHooks instanceof RegExp) options.additionalHooks.lastIndex = 0;
|
|
8134
|
+
return options.additionalHooks.test(name) ? 0 : -1;
|
|
8135
|
+
} else return -1;
|
|
8136
|
+
}
|
|
8137
|
+
}
|
|
8138
|
+
function fastFindReferenceWithParent(start, target) {
|
|
8139
|
+
const queue = [start];
|
|
8140
|
+
let item;
|
|
8141
|
+
while (queue.length) {
|
|
8142
|
+
item = queue.shift();
|
|
8143
|
+
if (isSameIdentifier(item, target)) return item;
|
|
8144
|
+
if (!isAncestorNodeOf(item, target)) continue;
|
|
8145
|
+
for (const [key, value] of Object.entries(item)) {
|
|
8146
|
+
if (key === "parent") continue;
|
|
8147
|
+
if (isNodeLike(value)) {
|
|
8148
|
+
value.parent = item;
|
|
8149
|
+
queue.push(value);
|
|
8150
|
+
} else if (Array.isArray(value)) value.forEach((val) => {
|
|
8151
|
+
if (isNodeLike(val)) {
|
|
8152
|
+
val.parent = item;
|
|
8153
|
+
queue.push(val);
|
|
8154
|
+
}
|
|
8155
|
+
});
|
|
8156
|
+
}
|
|
8157
|
+
}
|
|
8158
|
+
return null;
|
|
8159
|
+
}
|
|
8160
|
+
function joinEnglish(arr) {
|
|
8161
|
+
let s = "";
|
|
8162
|
+
for (let i = 0; i < arr.length; i++) {
|
|
8163
|
+
s += arr[i];
|
|
8164
|
+
if (i === 0 && arr.length === 2) s += " and ";
|
|
8165
|
+
else if (i === arr.length - 2 && arr.length > 2) s += ", and ";
|
|
8166
|
+
else if (i < arr.length - 1) s += ", ";
|
|
8167
|
+
}
|
|
8168
|
+
return s;
|
|
8169
|
+
}
|
|
8170
|
+
function isNodeLike(val) {
|
|
8171
|
+
return typeof val === "object" && val !== null && !Array.isArray(val) && "type" in val && typeof val.type === "string";
|
|
8172
|
+
}
|
|
8173
|
+
function isSameIdentifier(a, b) {
|
|
8174
|
+
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];
|
|
8175
|
+
}
|
|
8176
|
+
function isAncestorNodeOf(a, b) {
|
|
8177
|
+
return !!a.range && !!b.range && a.range[0] <= b.range[0] && a.range[1] >= b.range[1];
|
|
8178
|
+
}
|
|
8179
|
+
function isUseEffectEventIdentifier(node) {
|
|
8180
|
+
return node.type === "Identifier" && node.name === "useEffectEvent";
|
|
8181
|
+
}
|
|
8182
|
+
function getUnknownDependenciesMessage(reactiveHookName) {
|
|
8183
|
+
return `React Hook ${reactiveHookName} received a function whose dependencies are unknown. Pass an inline function instead.`;
|
|
8184
|
+
}
|
|
8185
|
+
// src/rules/unsupported-syntax/lib.ts
|
|
8186
|
+
function isEvalCall(node) {
|
|
8187
|
+
const callee = Extract.unwrap(node.callee);
|
|
8188
|
+
switch (callee.type) {
|
|
8189
|
+
case AST_NODE_TYPES.Identifier: return callee.name === "eval";
|
|
8190
|
+
case AST_NODE_TYPES.MemberExpression:
|
|
8191
|
+
if (!Check.isIdentifier(Extract.unwrap(callee.object), "globalThis")) return false;
|
|
8192
|
+
return !callee.computed && Check.isIdentifier(callee.property, "eval");
|
|
8193
|
+
default: return false;
|
|
8194
|
+
}
|
|
8195
|
+
}
|
|
8196
|
+
var unsupported_syntax_default = createRule({
|
|
8197
|
+
meta: {
|
|
8198
|
+
type: "problem",
|
|
8199
|
+
docs: { description: "Validates against syntax that React Compiler does not support." },
|
|
8200
|
+
messages: {
|
|
8201
|
+
eval: "Do not use 'eval' inside components or hooks. 'eval' cannot be statically analyzed and is not supported by React Compiler.",
|
|
8202
|
+
with: "Do not use 'with' statements inside components or hooks. 'with' changes scope dynamically and is not supported by React Compiler."
|
|
8203
|
+
},
|
|
8204
|
+
schema: []
|
|
8205
|
+
},
|
|
8206
|
+
name: "unsupported-syntax",
|
|
8207
|
+
create: create$2
|
|
8208
|
+
});
|
|
8209
|
+
function create$2(context) {
|
|
8210
|
+
const hc = core.getHookCollector(context);
|
|
8211
|
+
const fc = core.getFunctionComponentCollector(context);
|
|
8212
|
+
const evalCalls = [];
|
|
8213
|
+
const withStmts = [];
|
|
8214
|
+
return merge(hc.visitor, fc.visitor, {
|
|
8215
|
+
CallExpression(node) {
|
|
8216
|
+
if (!isEvalCall(node)) return;
|
|
8217
|
+
const func = Traverse.findParent(node, Check.isFunction);
|
|
8218
|
+
if (func == null) return;
|
|
8219
|
+
evalCalls.push({
|
|
8220
|
+
func,
|
|
8221
|
+
node
|
|
8222
|
+
});
|
|
8223
|
+
},
|
|
8224
|
+
WithStatement(node) {
|
|
8225
|
+
const func = Traverse.findParent(node, Check.isFunction);
|
|
8226
|
+
if (func == null) return;
|
|
8227
|
+
withStmts.push({
|
|
8228
|
+
func,
|
|
8229
|
+
node
|
|
8230
|
+
});
|
|
8231
|
+
},
|
|
8232
|
+
"Program:exit"(node) {
|
|
8233
|
+
const comps = fc.api.getAllComponents(node);
|
|
8234
|
+
const hooks = hc.api.getAllHooks(node);
|
|
8235
|
+
const funcs = [...comps, ...hooks];
|
|
8236
|
+
for (const { func, node } of evalCalls) {
|
|
8237
|
+
if (!funcs.some((f) => f.node === func)) continue;
|
|
8238
|
+
context.report({
|
|
8239
|
+
messageId: "eval",
|
|
7224
8240
|
node
|
|
7225
8241
|
});
|
|
7226
8242
|
}
|
|
@@ -7240,16 +8256,6 @@ function isResultUsed(node) {
|
|
|
7240
8256
|
while (Check.isTypeExpression(parent)) parent = parent.parent;
|
|
7241
8257
|
return parent.type === AST_NODE_TYPES.VariableDeclarator || parent.type === AST_NODE_TYPES.AssignmentExpression || parent.type === AST_NODE_TYPES.AssignmentPattern || parent.type === AST_NODE_TYPES.Property || parent.type === AST_NODE_TYPES.ReturnStatement || parent.type === AST_NODE_TYPES.JSXExpressionContainer || parent.type === AST_NODE_TYPES.CallExpression || parent.type === AST_NODE_TYPES.NewExpression || parent.type === AST_NODE_TYPES.ArrayExpression || parent.type === AST_NODE_TYPES.ConditionalExpression || parent.type === AST_NODE_TYPES.LogicalExpression || parent.type === AST_NODE_TYPES.SequenceExpression || parent.type === AST_NODE_TYPES.SpreadElement || parent.type === AST_NODE_TYPES.TemplateLiteral || parent.type === AST_NODE_TYPES.BinaryExpression || parent.type === AST_NODE_TYPES.UnaryExpression || parent.type === AST_NODE_TYPES.MemberExpression || parent.type === AST_NODE_TYPES.TaggedTemplateExpression || parent.type === AST_NODE_TYPES.ChainExpression || parent.type === AST_NODE_TYPES.ArrowFunctionExpression || parent.type === AST_NODE_TYPES.ForOfStatement || parent.type === AST_NODE_TYPES.ForInStatement;
|
|
7242
8258
|
}
|
|
7243
|
-
function getReturnStatements(node) {
|
|
7244
|
-
const statements = [];
|
|
7245
|
-
const boundary = Check.isFunction(node) ? node : Traverse.findParent(node, Check.isFunction);
|
|
7246
|
-
simpleTraverse(node, { enter(node) {
|
|
7247
|
-
if (node.type !== AST_NODE_TYPES.ReturnStatement) return;
|
|
7248
|
-
if (Traverse.hasParent(node, Check.isFunction, (n) => n === boundary)) return;
|
|
7249
|
-
statements.push(node);
|
|
7250
|
-
} });
|
|
7251
|
-
return statements;
|
|
7252
|
-
}
|
|
7253
8259
|
// src/rules/use-memo/collect.ts
|
|
7254
8260
|
function createFactCollector(isUseMemoCall) {
|
|
7255
8261
|
const facts = { calls: [] };
|
|
@@ -7263,7 +8269,7 @@ function createFactCollector(isUseMemoCall) {
|
|
|
7263
8269
|
target
|
|
7264
8270
|
});
|
|
7265
8271
|
}
|
|
7266
|
-
simpleTraverse(callback.body, { enter(node) {
|
|
8272
|
+
Traverse.simpleTraverse(callback.body, { enter(node) {
|
|
7267
8273
|
switch (node.type) {
|
|
7268
8274
|
case AST_NODE_TYPES.AssignmentExpression:
|
|
7269
8275
|
for (const target of Extract.getAssignmentTargets(node.left)) pushWrite(node, target);
|
|
@@ -7289,7 +8295,7 @@ function createFactCollector(isUseMemoCall) {
|
|
|
7289
8295
|
callbackArg,
|
|
7290
8296
|
isResultUsed: isResultUsed(node),
|
|
7291
8297
|
node,
|
|
7292
|
-
returnStatements: callbackFunction != null ? getReturnStatements(callbackFunction) : [],
|
|
8298
|
+
returnStatements: callbackFunction != null ? Collect.getReturnStatements(callbackFunction) : [],
|
|
7293
8299
|
writes: callbackFunction != null ? collectWrites(callbackFunction) : []
|
|
7294
8300
|
});
|
|
7295
8301
|
} }
|
|
@@ -7383,125 +8389,50 @@ const LAZY_INIT_ALLOW_LIST = [
|
|
|
7383
8389
|
"String",
|
|
7384
8390
|
"Number"
|
|
7385
8391
|
];
|
|
7386
|
-
const EXPRESSION_VISITOR_KEYS = {
|
|
7387
|
-
[AST_NODE_TYPES.ArrayExpression]: ["elements"],
|
|
7388
|
-
[AST_NODE_TYPES.ArrayPattern]: ["elements"],
|
|
7389
|
-
[AST_NODE_TYPES.AssignmentExpression]: ["left", "right"],
|
|
7390
|
-
[AST_NODE_TYPES.AssignmentPattern]: ["left", "right"],
|
|
7391
|
-
[AST_NODE_TYPES.AwaitExpression]: ["argument"],
|
|
7392
|
-
[AST_NODE_TYPES.BinaryExpression]: ["left", "right"],
|
|
7393
|
-
[AST_NODE_TYPES.CallExpression]: ["callee", "arguments"],
|
|
7394
|
-
[AST_NODE_TYPES.ChainExpression]: ["expression"],
|
|
7395
|
-
[AST_NODE_TYPES.ConditionalExpression]: [
|
|
7396
|
-
"test",
|
|
7397
|
-
"consequent",
|
|
7398
|
-
"alternate"
|
|
7399
|
-
],
|
|
7400
|
-
[AST_NODE_TYPES.Decorator]: ["expression"],
|
|
7401
|
-
[AST_NODE_TYPES.DoWhileStatement]: ["test"],
|
|
7402
|
-
[AST_NODE_TYPES.ExpressionStatement]: ["expression"],
|
|
7403
|
-
[AST_NODE_TYPES.ForInStatement]: ["left", "right"],
|
|
7404
|
-
[AST_NODE_TYPES.ForOfStatement]: ["left", "right"],
|
|
7405
|
-
[AST_NODE_TYPES.ForStatement]: ["test"],
|
|
7406
|
-
[AST_NODE_TYPES.IfStatement]: [
|
|
7407
|
-
"test",
|
|
7408
|
-
"consequent",
|
|
7409
|
-
"alternate"
|
|
7410
|
-
],
|
|
7411
|
-
[AST_NODE_TYPES.ImportExpression]: ["source"],
|
|
7412
|
-
[AST_NODE_TYPES.JSXExpressionContainer]: ["expression"],
|
|
7413
|
-
[AST_NODE_TYPES.JSXSpreadChild]: ["expression"],
|
|
7414
|
-
[AST_NODE_TYPES.LogicalExpression]: ["left", "right"],
|
|
7415
|
-
[AST_NODE_TYPES.MemberExpression]: ["object", "property"],
|
|
7416
|
-
[AST_NODE_TYPES.NewExpression]: ["callee", "arguments"],
|
|
7417
|
-
[AST_NODE_TYPES.ObjectExpression]: ["properties"],
|
|
7418
|
-
[AST_NODE_TYPES.ObjectPattern]: ["properties"],
|
|
7419
|
-
[AST_NODE_TYPES.Property]: ["value"],
|
|
7420
|
-
[AST_NODE_TYPES.SequenceExpression]: ["expressions"],
|
|
7421
|
-
[AST_NODE_TYPES.SpreadElement]: ["argument"],
|
|
7422
|
-
[AST_NODE_TYPES.SwitchCase]: ["test", "consequent"],
|
|
7423
|
-
[AST_NODE_TYPES.TaggedTemplateExpression]: ["tag", "quasi"],
|
|
7424
|
-
[AST_NODE_TYPES.TemplateLiteral]: ["expressions"],
|
|
7425
|
-
[AST_NODE_TYPES.TSAsExpression]: ["expression"],
|
|
7426
|
-
[AST_NODE_TYPES.TSClassImplements]: ["expression"],
|
|
7427
|
-
[AST_NODE_TYPES.TSExportAssignment]: ["expression"],
|
|
7428
|
-
[AST_NODE_TYPES.TSExternalModuleReference]: ["expression"],
|
|
7429
|
-
[AST_NODE_TYPES.TSInstantiationExpression]: ["expression"],
|
|
7430
|
-
[AST_NODE_TYPES.TSInterfaceHeritage]: ["expression"],
|
|
7431
|
-
[AST_NODE_TYPES.TSNonNullExpression]: ["expression"],
|
|
7432
|
-
[AST_NODE_TYPES.TSSatisfiesExpression]: ["expression"],
|
|
7433
|
-
[AST_NODE_TYPES.TSTypeAssertion]: ["expression"],
|
|
7434
|
-
[AST_NODE_TYPES.UnaryExpression]: ["argument"],
|
|
7435
|
-
[AST_NODE_TYPES.UpdateExpression]: ["argument"],
|
|
7436
|
-
[AST_NODE_TYPES.WhileStatement]: ["test"],
|
|
7437
|
-
[AST_NODE_TYPES.YieldExpression]: ["argument"]
|
|
7438
|
-
};
|
|
7439
|
-
function getExpressionsOfType(type) {
|
|
7440
|
-
const isNodeOfType = Check.is(type);
|
|
7441
|
-
const recurse = (node) => {
|
|
7442
|
-
const expressions = [];
|
|
7443
|
-
simpleTraverse(node, {
|
|
7444
|
-
enter(node, parent) {
|
|
7445
|
-
if (parent?.type === AST_NODE_TYPES.MemberExpression && !parent.computed && parent.property === node) return;
|
|
7446
|
-
if (isNodeOfType(node)) expressions.push(node);
|
|
7447
|
-
},
|
|
7448
|
-
visitorKeys: EXPRESSION_VISITOR_KEYS
|
|
7449
|
-
});
|
|
7450
|
-
return expressions;
|
|
7451
|
-
};
|
|
7452
|
-
return recurse;
|
|
7453
|
-
}
|
|
7454
|
-
const getNewExpressions = getExpressionsOfType(AST_NODE_TYPES.NewExpression);
|
|
7455
|
-
const getCallExpressions = getExpressionsOfType(AST_NODE_TYPES.CallExpression);
|
|
7456
|
-
// src/rules/use-state/use-state.ts
|
|
7457
|
-
const RULE_NAME = "use-state";
|
|
7458
|
-
const defaultOptions = [{
|
|
7459
|
-
enforceAssignment: true,
|
|
7460
|
-
enforceLazyInitialization: true,
|
|
7461
|
-
enforceSetterName: true
|
|
7462
|
-
}];
|
|
7463
|
-
const schema = [{
|
|
7464
|
-
type: "object",
|
|
7465
|
-
additionalProperties: false,
|
|
7466
|
-
properties: {
|
|
7467
|
-
enforceAssignment: {
|
|
7468
|
-
type: "boolean",
|
|
7469
|
-
default: true
|
|
7470
|
-
},
|
|
7471
|
-
enforceLazyInitialization: {
|
|
7472
|
-
type: "boolean",
|
|
7473
|
-
default: true
|
|
7474
|
-
},
|
|
7475
|
-
enforceSetterName: {
|
|
7476
|
-
type: "boolean",
|
|
7477
|
-
default: true
|
|
7478
|
-
}
|
|
7479
|
-
}
|
|
7480
|
-
}];
|
|
7481
8392
|
var use_state_default = createRule({
|
|
7482
8393
|
meta: {
|
|
7483
8394
|
type: "suggestion",
|
|
7484
|
-
defaultOptions: [
|
|
8395
|
+
defaultOptions: [{}],
|
|
7485
8396
|
docs: { description: "Enforces correct usage of 'useState', including destructuring, symmetric naming of the value and setter, and wrapping expensive initializers in a lazy initializer function." },
|
|
7486
8397
|
messages: {
|
|
7487
8398
|
"invalid-initialization": "To prevent re-computation, consider using lazy initial state for useState calls that involve function calls. Ex: 'useState(() => getValue())'.",
|
|
7488
8399
|
"invalid-assignment": "useState should be destructured into a value and setter pair, e.g., const [state, setState] = useState(...).",
|
|
7489
8400
|
"invalid-setter-name": "The setter should be named 'set' followed by the capitalized state variable name, e.g., 'setState' for 'state'."
|
|
7490
8401
|
},
|
|
7491
|
-
schema
|
|
8402
|
+
schema: [{
|
|
8403
|
+
type: "object",
|
|
8404
|
+
additionalProperties: false,
|
|
8405
|
+
properties: {
|
|
8406
|
+
enforceAssignment: {
|
|
8407
|
+
type: "boolean",
|
|
8408
|
+
description: "Require the useState result to be assigned to a destructured value/setter pair."
|
|
8409
|
+
},
|
|
8410
|
+
enforceLazyInitialization: {
|
|
8411
|
+
type: "boolean",
|
|
8412
|
+
description: "Require expensive initializers to be wrapped in a lazy initializer function."
|
|
8413
|
+
},
|
|
8414
|
+
enforceSetterName: {
|
|
8415
|
+
type: "boolean",
|
|
8416
|
+
description: "Require the setter name to match the state value name."
|
|
8417
|
+
}
|
|
8418
|
+
}
|
|
8419
|
+
}]
|
|
7492
8420
|
},
|
|
7493
|
-
name:
|
|
8421
|
+
name: "use-state",
|
|
7494
8422
|
create
|
|
7495
8423
|
});
|
|
7496
8424
|
function create(context) {
|
|
7497
|
-
const
|
|
8425
|
+
const options = context.options[0] ?? {};
|
|
8426
|
+
const enforceAssignment = options.enforceAssignment ?? true;
|
|
8427
|
+
const enforceLazyInitialization = options.enforceLazyInitialization ?? true;
|
|
8428
|
+
const enforceSetterName = options.enforceSetterName ?? true;
|
|
7498
8429
|
const { additionalStateHooks } = getSettingsFromContext(context);
|
|
7499
8430
|
return { CallExpression(node) {
|
|
7500
8431
|
if (!core.isUseStateLikeCall(node, additionalStateHooks)) return;
|
|
7501
8432
|
if (enforceLazyInitialization) {
|
|
7502
8433
|
const [useStateInput] = node.arguments;
|
|
7503
8434
|
if (useStateInput != null) {
|
|
7504
|
-
for (const expr of getNewExpressions(useStateInput)) {
|
|
8435
|
+
for (const expr of Collect.getNewExpressions(useStateInput)) {
|
|
7505
8436
|
if (!hasProperty(expr.callee, "name")) continue;
|
|
7506
8437
|
if (LAZY_INIT_ALLOW_LIST.includes(expr.callee.name)) continue;
|
|
7507
8438
|
if (Traverse.hasParent(expr, core.isUseCall(context))) continue;
|
|
@@ -7510,7 +8441,7 @@ function create(context) {
|
|
|
7510
8441
|
node: expr
|
|
7511
8442
|
});
|
|
7512
8443
|
}
|
|
7513
|
-
for (const expr of getCallExpressions(useStateInput)) {
|
|
8444
|
+
for (const expr of Collect.getCallExpressions(useStateInput)) {
|
|
7514
8445
|
if (!hasProperty(expr.callee, "name")) continue;
|
|
7515
8446
|
if (core.isHookName(expr.callee.name)) continue;
|
|
7516
8447
|
if (LAZY_INIT_ALLOW_LIST.includes(expr.callee.name)) continue;
|
|
@@ -7581,7 +8512,7 @@ const plugin = {
|
|
|
7581
8512
|
},
|
|
7582
8513
|
rules: {
|
|
7583
8514
|
"error-boundaries": error_boundaries_default,
|
|
7584
|
-
"exhaustive-deps": rule$
|
|
8515
|
+
"exhaustive-deps": rule$2,
|
|
7585
8516
|
globals: globals_default,
|
|
7586
8517
|
immutability: immutability_default,
|
|
7587
8518
|
"no-access-state-in-setstate": no_access_state_in_setstate_default,
|
|
@@ -7626,10 +8557,11 @@ const plugin = {
|
|
|
7626
8557
|
"no-use-context": no_use_context_default,
|
|
7627
8558
|
purity: purity_default,
|
|
7628
8559
|
refs: refs_default,
|
|
7629
|
-
"rules-of-hooks": rule,
|
|
8560
|
+
"rules-of-hooks": rule$1,
|
|
7630
8561
|
"set-state-in-effect": set_state_in_effect_default,
|
|
7631
8562
|
"set-state-in-render": set_state_in_render_default,
|
|
7632
8563
|
"static-components": static_components_default,
|
|
8564
|
+
"unstable-exhaustive-deps": rule,
|
|
7633
8565
|
"unsupported-syntax": unsupported_syntax_default,
|
|
7634
8566
|
"use-memo": use_memo_default,
|
|
7635
8567
|
"use-state": use_state_default
|