eslint-plugin-react-x 5.30.0-beta.8 → 5.30.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +317 -1236
  2. package/package.json +11 -11
package/dist/index.js CHANGED
@@ -2,10 +2,11 @@ import { DEFAULT_ESLINT_REACT_SETTINGS, getSettingsFromContext, toRegExp } from
2
2
  import * as ESLintUtils from "@typescript-eslint/utils/eslint-utils";
3
3
  import { Analyze, Check, Collect, Compare, Extract, Traverse } from "@eslint-react/ast";
4
4
  import * as core from "@eslint-react/core";
5
- import { complete, getConstrainedTypeAtLocation, getText, merge, report } from "@eslint-react/eslint";
5
+ import { isChildrenMap, isChildrenMapCall, isChildrenToArray, isChildrenToArrayCall } from "@eslint-react/core";
6
+ import { getConstrainedTypeAtLocation, getText, merge, report } from "@eslint-react/eslint";
6
7
  import { AST_NODE_TYPES } from "@typescript-eslint/types";
7
8
  import { P, isMatching, match } from "ts-pattern";
8
- import { isAssignmentTargetEqual, isInitializedFromReact, resolveEnclosingAssignmentTarget, resolveObjectType, resolveOrigin, resolveOriginChain } from "@eslint-react/var";
9
+ import { isAssignmentTargetEqual, isInitializedFromReact, resolveAssignmentTargets, resolveEnclosingAssignmentTarget, resolveObjectType, resolveOrigin, resolveOriginChain } from "@eslint-react/var";
9
10
  import { DefinitionType, ScopeType } from "@typescript-eslint/scope-manager";
10
11
  import { findVariable, getStaticValue } from "@typescript-eslint/utils/ast-utils";
11
12
  import { findParentAttribute, getElementFullType, getElementSelfType, hasAttribute, isInsideCreateElementProps, isPlainAttribute, parseCreateElementCall } from "@eslint-react/jsx";
@@ -38,7 +39,6 @@ const conflictingRules$1 = [
38
39
  "react/hook-use-state",
39
40
  "react/iframe-missing-sandbox",
40
41
  "react/jsx-boolean-value",
41
- "react/jsx-filename-extension",
42
42
  "react/jsx-fragments",
43
43
  "react/jsx-key",
44
44
  "react/jsx-no-comment-textnodes",
@@ -60,12 +60,13 @@ const conflictingRules$1 = [
60
60
  "react/no-find-dom-node",
61
61
  "react/no-namespace",
62
62
  "react/no-object-type-as-default-prop",
63
+ "react/no-redundant-should-component-update",
63
64
  "react/no-render-return-value",
64
65
  "react/no-string-refs",
65
66
  "react/no-unknown-property",
66
67
  "react/no-unsafe",
67
68
  "react/no-unstable-nested-components",
68
- "react/no-unused-class-component-members",
69
+ "react/no-unused-class-component-methods",
69
70
  "react/no-unused-state",
70
71
  "react/no-will-update-set-state",
71
72
  "react/prop-types",
@@ -112,8 +113,7 @@ const rules$7 = {
112
113
  "react-x/no-unused-state": "off",
113
114
  "react-x/refs": "off",
114
115
  "react-x/set-state-in-render": "off",
115
- "react-x/static-components": "off",
116
- "react-x/unstable-exhaustive-deps": "off"
116
+ "react-x/static-components": "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.8";
133
+ var version = "5.30.0-rc.0";
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$2 = {
195
+ const rule$1 = {
196
196
  meta: {
197
197
  type: "suggestion",
198
198
  docs: {
@@ -288,7 +288,7 @@ const rule$2 = {
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$1(componentScope.block, def.node.id);
291
+ fastFindReferenceWithParent(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$2 = {
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$2(callee) && id.type === "Identifier") {
303
+ else if (isUseEffectEventIdentifier$1(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$2 = {
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$1(node, reference.identifier);
375
+ const referenceNode = fastFindReferenceWithParent(node, reference.identifier);
376
376
  if (referenceNode == null) continue;
377
- const dependencyNode = getDependency$1(referenceNode);
378
- const dependency = analyzePropertyChain$1(dependencyNode, optionalChains);
377
+ const dependencyNode = getDependency(referenceNode);
378
+ const dependency = analyzePropertyChain(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$2 = {
445
445
  });
446
446
  });
447
447
  if (setStateInsideEffectWithoutDeps) {
448
- const { suggestedDependencies } = collectRecommendations$1({
448
+ const { suggestedDependencies } = collectRecommendations({
449
449
  dependencies,
450
450
  declaredDependencies: [],
451
451
  stableDependencies,
@@ -495,7 +495,7 @@ const rule$2 = {
495
495
  });
496
496
  let declaredDependency;
497
497
  try {
498
- declaredDependency = analyzePropertyChain$1(declaredDependencyNode, null);
498
+ declaredDependency = analyzePropertyChain(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$2 = {
523
523
  });
524
524
  if (!isDeclaredInComponent) externalDependencies.add(declaredDependency);
525
525
  });
526
- const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies } = collectRecommendations$1({
526
+ const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies } = collectRecommendations({
527
527
  dependencies,
528
528
  declaredDependencies,
529
529
  stableDependencies,
@@ -532,7 +532,7 @@ const rule$2 = {
532
532
  });
533
533
  let suggestedDeps = suggestedDependencies;
534
534
  if (duplicateDependencies.size + missingDependencies.size + unnecessaryDependencies.size === 0) {
535
- scanForConstructions$1({
535
+ scanForConstructions({
536
536
  declaredDependencies,
537
537
  declaredDependenciesNode,
538
538
  componentScope,
@@ -560,7 +560,7 @@ const rule$2 = {
560
560
  });
561
561
  return;
562
562
  }
563
- if (!isEffect && missingDependencies.size > 0) suggestedDeps = collectRecommendations$1({
563
+ if (!isEffect && missingDependencies.size > 0) suggestedDeps = collectRecommendations({
564
564
  dependencies,
565
565
  declaredDependencies: [],
566
566
  stableDependencies,
@@ -589,7 +589,7 @@ const rule$2 = {
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$1(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(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$2 = {
611
611
  if (!Array.isArray(refs)) return;
612
612
  let isPropsOnlyUsedInMembers = true;
613
613
  for (const ref of refs) {
614
- const id = fastFindReferenceWithParent$1(componentScope.block, ref.identifier);
614
+ const id = fastFindReferenceWithParent(componentScope.block, ref.identifier);
615
615
  if (!id) {
616
616
  isPropsOnlyUsedInMembers = false;
617
617
  break;
@@ -719,11 +719,11 @@ const rule$2 = {
719
719
  });
720
720
  }
721
721
  function visitCallExpression(node) {
722
- const callbackIndex = getReactiveHookCallbackIndex$1(node.callee, options);
722
+ const callbackIndex = getReactiveHookCallbackIndex(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$2(reactiveHook);
726
+ const nodeWithoutNamespace = getNodeWithoutReactNamespace$1(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$2 = {
763
763
  if (def.type === "Parameter") {
764
764
  reportProblem({
765
765
  node: reactiveHook,
766
- message: getUnknownDependenciesMessage$1(reactiveHookName)
766
+ message: getUnknownDependenciesMessage(reactiveHookName)
767
767
  });
768
768
  return;
769
769
  }
@@ -786,7 +786,7 @@ const rule$2 = {
786
786
  default:
787
787
  reportProblem({
788
788
  node: reactiveHook,
789
- message: getUnknownDependenciesMessage$1(reactiveHookName)
789
+ message: getUnknownDependenciesMessage(reactiveHookName)
790
790
  });
791
791
  return;
792
792
  }
@@ -804,7 +804,7 @@ const rule$2 = {
804
804
  return { CallExpression: visitCallExpression };
805
805
  }
806
806
  };
807
- function collectRecommendations$1({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect }) {
807
+ function collectRecommendations({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect }) {
808
808
  const depTree = createDepTree();
809
809
  function createDepTree() {
810
810
  return {
@@ -890,7 +890,7 @@ function collectRecommendations$1({ dependencies, declaredDependencies, stableDe
890
890
  missingDependencies
891
891
  };
892
892
  }
893
- function getConstructionExpressionType$1(node) {
893
+ function getConstructionExpressionType(node) {
894
894
  switch (node.type) {
895
895
  case "ObjectExpression": return "object";
896
896
  case "ArrayExpression": return "array";
@@ -898,15 +898,15 @@ function getConstructionExpressionType$1(node) {
898
898
  case "FunctionExpression": return "function";
899
899
  case "ClassExpression": return "class";
900
900
  case "ConditionalExpression":
901
- if (getConstructionExpressionType$1(node.consequent) != null || getConstructionExpressionType$1(node.alternate) != null) return "conditional";
901
+ if (getConstructionExpressionType(node.consequent) != null || getConstructionExpressionType(node.alternate) != null) return "conditional";
902
902
  return null;
903
903
  case "LogicalExpression":
904
- if (getConstructionExpressionType$1(node.left) != null || getConstructionExpressionType$1(node.right) != null) return "logical expression";
904
+ if (getConstructionExpressionType(node.left) != null || getConstructionExpressionType(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$1(node.right) != null) return "assignment expression";
909
+ if (getConstructionExpressionType(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$1(node) {
914
914
  return null;
915
915
  case "TypeCastExpression":
916
916
  case "AsExpression":
917
- case "TSAsExpression": return getConstructionExpressionType$1(node.expression);
917
+ case "TSAsExpression": return getConstructionExpressionType(node.expression);
918
918
  }
919
919
  return null;
920
920
  }
921
- function scanForConstructions$1({ declaredDependencies, declaredDependenciesNode, componentScope, scope }) {
921
+ function scanForConstructions({ 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$1(node.node.init);
928
+ const constantExpressionType = getConstructionExpressionType(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$1({ 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$1(declaredDependenciesNode, reference.identifier)) return true;
948
+ if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) return true;
949
949
  }
950
950
  }
951
951
  return false;
@@ -956,45 +956,45 @@ function scanForConstructions$1({ declaredDependencies, declaredDependenciesNode
956
956
  isUsedOutsideOfHook: isUsedOutsideOfHook(ref)
957
957
  }));
958
958
  }
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);
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);
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$1(node, optionalChains, result) {
964
+ function markNode(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$1(node, optionalChains) {
971
+ function analyzePropertyChain(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$1(node.object, optionalChains)}.${analyzePropertyChain$1(node.property, null)}`;
978
- markNode$1(node, optionalChains, result);
977
+ const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
978
+ markNode(node, optionalChains, result);
979
979
  return result;
980
980
  } else if (node.type === "OptionalMemberExpression" && !node.computed) {
981
- const result = `${analyzePropertyChain$1(node.object, optionalChains)}.${analyzePropertyChain$1(node.property, null)}`;
982
- markNode$1(node, optionalChains, result);
981
+ const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
982
+ markNode(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$1(expression.object, optionalChains)}.${analyzePropertyChain$1(expression.property, null)}`;
988
- markNode$1(expression, optionalChains, result);
987
+ const result = `${analyzePropertyChain(expression.object, optionalChains)}.${analyzePropertyChain(expression.property, null)}`;
988
+ markNode(expression, optionalChains, result);
989
989
  return result;
990
990
  } else throw new Error(`Unsupported node type: ${node.type}`);
991
991
  }
992
- function getNodeWithoutReactNamespace$2(node) {
992
+ function getNodeWithoutReactNamespace$1(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$1(calleeNode, options) {
997
- const node = getNodeWithoutReactNamespace$2(calleeNode);
996
+ function getReactiveHookCallbackIndex(calleeNode, options) {
997
+ const node = getNodeWithoutReactNamespace$1(calleeNode);
998
998
  if (node.type !== "Identifier") return -1;
999
999
  switch (node.name) {
1000
1000
  case "useEffect":
@@ -1005,7 +1005,7 @@ function getReactiveHookCallbackIndex$1(calleeNode, options) {
1005
1005
  default: if (node === calleeNode && options && options.additionalHooks) {
1006
1006
  let name;
1007
1007
  try {
1008
- name = analyzePropertyChain$1(node, null);
1008
+ name = analyzePropertyChain(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$1(calleeNode, options) {
1014
1014
  } else return -1;
1015
1015
  }
1016
1016
  }
1017
- function fastFindReferenceWithParent$1(start, target) {
1017
+ function fastFindReferenceWithParent(start, target) {
1018
1018
  const queue = [start];
1019
1019
  let item;
1020
1020
  while (queue.length) {
1021
1021
  item = queue.shift();
1022
- if (isSameIdentifier$1(item, target)) return item;
1023
- if (!isAncestorNodeOf$1(item, target)) continue;
1022
+ if (isSameIdentifier(item, target)) return item;
1023
+ if (!isAncestorNodeOf(item, target)) continue;
1024
1024
  for (const [key, value] of Object.entries(item)) {
1025
1025
  if (key === "parent") continue;
1026
- if (isNodeLike$1(value)) {
1026
+ if (isNodeLike(value)) {
1027
1027
  value.parent = item;
1028
1028
  queue.push(value);
1029
1029
  } else if (Array.isArray(value)) value.forEach((val) => {
1030
- if (isNodeLike$1(val)) {
1030
+ if (isNodeLike(val)) {
1031
1031
  val.parent = item;
1032
1032
  queue.push(val);
1033
1033
  }
@@ -1036,7 +1036,7 @@ function fastFindReferenceWithParent$1(start, target) {
1036
1036
  }
1037
1037
  return null;
1038
1038
  }
1039
- function joinEnglish$1(arr) {
1039
+ function joinEnglish(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$1(arr) {
1046
1046
  }
1047
1047
  return s;
1048
1048
  }
1049
- function isNodeLike$1(val) {
1049
+ function isNodeLike(val) {
1050
1050
  return typeof val === "object" && val !== null && !Array.isArray(val) && "type" in val && typeof val.type === "string";
1051
1051
  }
1052
- function isSameIdentifier$1(a, b) {
1052
+ function isSameIdentifier(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$1(a, b) {
1055
+ function isAncestorNodeOf(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$2(node) {
1058
+ function isUseEffectEventIdentifier$1(node) {
1059
1059
  return node.type === "Identifier" && node.name === "useEffectEvent";
1060
1060
  }
1061
- function getUnknownDependenciesMessage$1(reactiveHookName) {
1061
+ function getUnknownDependenciesMessage(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
@@ -1096,7 +1096,7 @@ function createFactCollector$6() {
1096
1096
  facts,
1097
1097
  visitor: {
1098
1098
  AssignmentExpression(node) {
1099
- for (const target of Extract.getAssignmentTargets(node.left)) pushWrite(node, target);
1099
+ for (const target of resolveAssignmentTargets(node.left)) pushWrite(node, target);
1100
1100
  },
1101
1101
  CallExpression(node) {
1102
1102
  const caller = getEnclosingFunction(node);
@@ -1118,11 +1118,11 @@ function createFactCollector$6() {
1118
1118
  },
1119
1119
  ForInStatement(node) {
1120
1120
  if (node.left.type === AST_NODE_TYPES.VariableDeclaration) return;
1121
- for (const target of Extract.getAssignmentTargets(node.left)) pushWrite(node, target);
1121
+ for (const target of resolveAssignmentTargets(node.left)) pushWrite(node, target);
1122
1122
  },
1123
1123
  ForOfStatement(node) {
1124
1124
  if (node.left.type === AST_NODE_TYPES.VariableDeclaration) return;
1125
- for (const target of Extract.getAssignmentTargets(node.left)) pushWrite(node, target);
1125
+ for (const target of resolveAssignmentTargets(node.left)) pushWrite(node, target);
1126
1126
  },
1127
1127
  UnaryExpression(node) {
1128
1128
  if (node.operator !== "delete") return;
@@ -1254,10 +1254,10 @@ function create$49(context) {
1254
1254
  const comps = core.getFunctionComponentCollector(context);
1255
1255
  const facts = createFactCollector$6();
1256
1256
  return merge(hooks.visitor, comps.visitor, facts.visitor, { "Program:exit"(program) {
1257
- const renderFunctions = [...comps.api.getAllComponents(program), ...hooks.api.getAllHooks(program)].map(({ node }) => node);
1257
+ const funcs = [...comps.api.getAllComponents(program), ...hooks.api.getAllHooks(program)].map(({ node }) => node);
1258
1258
  const directEffects = inferGlobalMutations(context, facts.facts);
1259
1259
  const callGraph = inferCallGraph$1(context, facts.facts.callEdges);
1260
- for (const effect of collectReachableEffects(renderFunctions, directEffects, callGraph)) {
1260
+ for (const effect of collectReachableEffects(funcs, directEffects, callGraph)) {
1261
1261
  const data = effect.method == null ? { name: effect.name } : {
1262
1262
  name: effect.name,
1263
1263
  method: effect.method
@@ -1304,9 +1304,13 @@ function isRefLikeName$2(name) {
1304
1304
  return name === "ref" || name.endsWith("Ref");
1305
1305
  }
1306
1306
  function hasRefLikeNameInChain(node) {
1307
- const expr = Extract.unwrap(node);
1308
- if (!Check.isExpression(expr)) return false;
1309
- return Extract.getMemberChain(expr).some((member) => Check.isIdentifier(member) && isRefLikeName$2(member.name));
1307
+ let current = Extract.unwrap(node);
1308
+ while (current.type === AST_NODE_TYPES.MemberExpression) {
1309
+ const property = Extract.unwrap(current.property);
1310
+ if (Check.isIdentifier(property) && isRefLikeName$2(property.name)) return true;
1311
+ current = Extract.unwrap(current.object);
1312
+ }
1313
+ return Check.isIdentifier(current) && isRefLikeName$2(current.name);
1310
1314
  }
1311
1315
  // src/rules/immutability/collect.ts
1312
1316
  function createFactCollector$5() {
@@ -1326,8 +1330,9 @@ function createFactCollector$5() {
1326
1330
  });
1327
1331
  }
1328
1332
  function pushMemberMutation(node, target) {
1329
- const root = Extract.getMemberChain(target).at(0);
1330
- if (root == null || !Check.isIdentifier(root)) return;
1333
+ let root = Extract.unwrap(target);
1334
+ while (root.type === AST_NODE_TYPES.MemberExpression) root = Extract.unwrap(root.object);
1335
+ if (!Check.isIdentifier(root)) return;
1331
1336
  pushMutation("value", node, target, root);
1332
1337
  }
1333
1338
  function pushTargetMutation(node, target) {
@@ -1341,7 +1346,7 @@ function createFactCollector$5() {
1341
1346
  facts,
1342
1347
  visitor: {
1343
1348
  AssignmentExpression(node) {
1344
- for (const target of Extract.getAssignmentTargets(node.left)) pushTargetMutation(node, target);
1349
+ for (const target of resolveAssignmentTargets(node.left)) pushTargetMutation(node, target);
1345
1350
  },
1346
1351
  CallExpression(node) {
1347
1352
  const callee = Extract.unwrap(node.callee);
@@ -1360,11 +1365,11 @@ function createFactCollector$5() {
1360
1365
  },
1361
1366
  ForInStatement(node) {
1362
1367
  if (node.left.type === AST_NODE_TYPES.VariableDeclaration) return;
1363
- for (const target of Extract.getAssignmentTargets(node.left)) pushTargetMutation(node, target);
1368
+ for (const target of resolveAssignmentTargets(node.left)) pushTargetMutation(node, target);
1364
1369
  },
1365
1370
  ForOfStatement(node) {
1366
1371
  if (node.left.type === AST_NODE_TYPES.VariableDeclaration) return;
1367
- for (const target of Extract.getAssignmentTargets(node.left)) pushTargetMutation(node, target);
1372
+ for (const target of resolveAssignmentTargets(node.left)) pushTargetMutation(node, target);
1368
1373
  },
1369
1374
  JSXAttribute(node) {
1370
1375
  if (node.value?.type !== AST_NODE_TYPES.JSXExpressionContainer) return;
@@ -1430,8 +1435,9 @@ function getStateHookName(context, init) {
1430
1435
  return null;
1431
1436
  }
1432
1437
  function isInitializedFromCall(context, node, isCall) {
1433
- const root = Extract.getMemberChain(node).at(0);
1434
- if (root == null || !Check.isIdentifier(root)) return false;
1438
+ let root = Extract.unwrap(node);
1439
+ while (root.type === AST_NODE_TYPES.MemberExpression) root = Extract.unwrap(root.object);
1440
+ if (!Check.isIdentifier(root)) return false;
1435
1441
  const variable = findVariable(context.sourceCode.getScope(root), root);
1436
1442
  if (variable == null) return false;
1437
1443
  const origin = resolveVariableOrigin(context, variable);
@@ -1461,8 +1467,9 @@ function classifyFrozenOrigin(context, variable, components, mode = "alias", see
1461
1467
  if (def.node.init == null) {
1462
1468
  const loop = def.node.parent.parent;
1463
1469
  if (loop.type !== AST_NODE_TYPES.ForOfStatement || loop.left !== def.node.parent) return null;
1464
- const root = Extract.getMemberChain(loop.right).at(0);
1465
- if (root == null || !Check.isIdentifier(root)) return null;
1470
+ let root = Extract.unwrap(loop.right);
1471
+ while (root.type === AST_NODE_TYPES.MemberExpression) root = Extract.unwrap(root.object);
1472
+ if (!Check.isIdentifier(root)) return null;
1466
1473
  const source = findVariable(context.sourceCode.getScope(root), root);
1467
1474
  if (source == null) return null;
1468
1475
  const inner = classifyFrozenOrigin(context, source, components, mode, seen);
@@ -1793,7 +1800,8 @@ function create$46(context) {
1793
1800
  for (const property of propsObject.properties) {
1794
1801
  if (property.type !== AST_NODE_TYPES.Property) continue;
1795
1802
  if (property.computed) continue;
1796
- if (Extract.getPropertyName(property, "max") !== "key") continue;
1803
+ const key = Extract.unwrap(property.key);
1804
+ if (Check.isIdentifier(key) ? key.name !== "key" : key.value !== "key") continue;
1797
1805
  const value = property.value;
1798
1806
  for (const desc of visitKeyExpression(value)) context.report(desc);
1799
1807
  }
@@ -2281,6 +2289,79 @@ function isAssignmentToThisState(node) {
2281
2289
  }
2282
2290
  return false;
2283
2291
  }
2292
+ // src/rules/no-duplicate-key/lib.ts
2293
+ function isReturnedBy(element, fn) {
2294
+ let node = element;
2295
+ let viaReturn = false;
2296
+ while (true) {
2297
+ const parent = node.parent;
2298
+ if (parent == null) return false;
2299
+ if (parent === fn) {
2300
+ if (viaReturn) return true;
2301
+ return parent.type === AST_NODE_TYPES.ArrowFunctionExpression && parent.body === node;
2302
+ }
2303
+ if (Check.isTypeOrChainExpression(parent) || parent.type === AST_NODE_TYPES.LogicalExpression) {
2304
+ node = parent;
2305
+ continue;
2306
+ }
2307
+ switch (parent.type) {
2308
+ case AST_NODE_TYPES.ConditionalExpression:
2309
+ if (parent.test === node) return false;
2310
+ node = parent;
2311
+ continue;
2312
+ case AST_NODE_TYPES.SequenceExpression:
2313
+ if (parent.expressions[parent.expressions.length - 1] !== node) return false;
2314
+ node = parent;
2315
+ continue;
2316
+ case AST_NODE_TYPES.ReturnStatement:
2317
+ viaReturn = true;
2318
+ node = parent;
2319
+ continue;
2320
+ case AST_NODE_TYPES.BlockStatement:
2321
+ case AST_NODE_TYPES.IfStatement:
2322
+ if (!viaReturn) return false;
2323
+ node = parent;
2324
+ continue;
2325
+ default: return false;
2326
+ }
2327
+ }
2328
+ }
2329
+ function isRekeyedByChildrenCall(context, root) {
2330
+ if (root.type === AST_NODE_TYPES.JSXElement) return false;
2331
+ let node = root.parent;
2332
+ while (node != null) {
2333
+ if (isChildrenToArrayCall(context, node) || isChildrenMapCall(context, node)) return true;
2334
+ switch (node.type) {
2335
+ case AST_NODE_TYPES.ArrayExpression:
2336
+ case AST_NODE_TYPES.ConditionalExpression:
2337
+ case AST_NODE_TYPES.JSXExpressionContainer:
2338
+ case AST_NODE_TYPES.JSXFragment:
2339
+ case AST_NODE_TYPES.LogicalExpression:
2340
+ case AST_NODE_TYPES.SpreadElement:
2341
+ node = node.parent;
2342
+ continue;
2343
+ default:
2344
+ if (Check.isTypeOrChainExpression(node)) {
2345
+ node = node.parent;
2346
+ continue;
2347
+ }
2348
+ return false;
2349
+ }
2350
+ }
2351
+ return false;
2352
+ }
2353
+ function mapsProvablyAtMostOneElement(call) {
2354
+ const callee = Extract.unwrap(call.callee);
2355
+ if (callee.type !== AST_NODE_TYPES.MemberExpression) return false;
2356
+ const object = Extract.unwrap(callee.object);
2357
+ return object.type === AST_NODE_TYPES.ArrayExpression && object.elements.length <= 1 && !object.elements.some((element) => element?.type === AST_NODE_TYPES.SpreadElement);
2358
+ }
2359
+ function isKeyValueEqual(a, b) {
2360
+ const aValue = a.value;
2361
+ const bValue = b.value;
2362
+ if (aValue == null || bValue == null) return false;
2363
+ return Compare.isEqual(aValue, bValue);
2364
+ }
2284
2365
  var no_duplicate_key_default = createRule({
2285
2366
  meta: {
2286
2367
  type: "problem",
@@ -2294,17 +2375,31 @@ var no_duplicate_key_default = createRule({
2294
2375
  function create$32(context) {
2295
2376
  if (!/\bkey\b/u.test(context.sourceCode.text)) return {};
2296
2377
  const keyGroups = /* @__PURE__ */ new Map();
2378
+ function getGroup(root) {
2379
+ let group = keyGroups.get(root);
2380
+ if (group == null) {
2381
+ group = { keys: [] };
2382
+ keyGroups.set(root, group);
2383
+ }
2384
+ return group;
2385
+ }
2297
2386
  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]
2387
+ if (isRekeyedByChildrenCall(context, root)) return;
2388
+ const group = getGroup(root);
2389
+ let duplicate = false;
2390
+ for (const entry of group.keys) if (isKeyValueEqual(entry.node, key)) {
2391
+ entry.duplicate = true;
2392
+ duplicate = true;
2393
+ }
2394
+ group.keys.push({
2395
+ duplicate,
2396
+ node: key
2302
2397
  });
2303
2398
  }
2304
2399
  function recordMapCallbackKey(call, key) {
2305
- keyGroups.set(call, {
2306
- hasDuplicate: key.value?.type === AST_NODE_TYPES.Literal,
2307
- keys: [key]
2400
+ getGroup(call).keys.push({
2401
+ duplicate: key.value?.type === AST_NODE_TYPES.Literal,
2402
+ node: key
2308
2403
  });
2309
2404
  }
2310
2405
  return {
@@ -2324,30 +2419,28 @@ function create$32(context) {
2324
2419
  return Check.isIdentifier(callee.property, "map");
2325
2420
  });
2326
2421
  if (call == null) return;
2422
+ if (isChildrenMap(context, call.callee) || isChildrenToArray(context, call.callee)) return;
2327
2423
  const callback = call.arguments[0];
2328
2424
  if (callback == null) return;
2329
- if (Traverse.findParent(jsxElement, Check.isFunction, (n) => n === call) !== Extract.unwrap(callback)) return;
2425
+ const callbackFn = Extract.unwrap(callback);
2426
+ if (!Check.isFunction(callbackFn)) return;
2427
+ if (!isReturnedBy(jsxElement, callbackFn)) return;
2428
+ if (mapsProvablyAtMostOneElement(call)) return;
2330
2429
  recordMapCallbackKey(call, node);
2331
2430
  }
2332
2431
  }
2333
2432
  },
2334
2433
  "Program:exit"() {
2335
- for (const { hasDuplicate, keys } of keyGroups.values()) {
2336
- if (!hasDuplicate) continue;
2337
- for (const key of keys) context.report({
2434
+ for (const { keys } of keyGroups.values()) for (const { duplicate, node } of keys) {
2435
+ if (!duplicate) continue;
2436
+ context.report({
2338
2437
  messageId: "default",
2339
- node: key
2438
+ node
2340
2439
  });
2341
2440
  }
2342
2441
  }
2343
2442
  };
2344
2443
  }
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
- }
2351
2444
  var no_forward_ref_default = createRule({
2352
2445
  meta: {
2353
2446
  type: "suggestion",
@@ -2703,24 +2796,13 @@ function create$25(context) {
2703
2796
  }
2704
2797
  };
2705
2798
  }
2706
- // src/utils/jsx-iterator.ts
2707
- const KNOWN_CALLBACK_POSITIONS = /* @__PURE__ */ new Map([
2799
+ // src/rules/no-missing-key/no-missing-key.ts
2800
+ const RULE_NAME$24 = "no-missing-key";
2801
+ const ITERATOR_CALLBACK_POSITIONS = /* @__PURE__ */ new Map([
2708
2802
  ["flatMap", 0],
2709
2803
  ["from", 1],
2710
2804
  ["map", 0]
2711
2805
  ]);
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;
2723
- }
2724
2806
  var no_missing_key_default = createRule({
2725
2807
  meta: {
2726
2808
  type: "problem",
@@ -2731,7 +2813,7 @@ var no_missing_key_default = createRule({
2731
2813
  },
2732
2814
  schema: []
2733
2815
  },
2734
- name: "no-missing-key",
2816
+ name: RULE_NAME$24,
2735
2817
  create: create$24
2736
2818
  });
2737
2819
  function create$24(context) {
@@ -2772,13 +2854,20 @@ function create$24(context) {
2772
2854
  }
2773
2855
  },
2774
2856
  CallExpression(node) {
2857
+ const call = node;
2775
2858
  if (core.isChildrenToArrayCall(context, node)) {
2776
2859
  childrenToArrayDepth += 1;
2777
2860
  return;
2778
2861
  }
2779
2862
  if (childrenToArrayDepth > 0) return;
2780
- const callback = getIteratorCallback(node);
2781
- if (callback == null) return;
2863
+ const callee = Extract.unwrap(call.callee);
2864
+ if (callee.type !== AST_NODE_TYPES.MemberExpression || !Check.isIdentifier(callee.property)) return;
2865
+ const position = ITERATOR_CALLBACK_POSITIONS.get(callee.property.name);
2866
+ if (position == null) return;
2867
+ const argument = call.arguments[position];
2868
+ if (argument == null) return;
2869
+ const callback = Extract.unwrap(argument);
2870
+ if (!Check.isFunction(callback)) return;
2782
2871
  for (const desc of visitIteratorCallback(callback)) context.report(desc);
2783
2872
  },
2784
2873
  "CallExpression:exit"(node) {
@@ -3285,31 +3374,27 @@ function getHumanReadableKind(node) {
3285
3374
  }
3286
3375
  return toLowerCase(delimiterCase(node.type, " "));
3287
3376
  }
3288
- // src/rules/no-unstable-default-props/no-unstable-default-props.ts
3289
- const RULE_NAME$12 = "no-unstable-default-props";
3290
- const defaultOptions$1 = [{ safeDefaultProps: [] }];
3291
- const schema$1 = [{
3292
- type: "object",
3293
- additionalProperties: false,
3294
- properties: { safeDefaultProps: {
3295
- type: "array",
3296
- description: "Property names or patterns that are safe to use as default props.",
3297
- items: { type: "string" }
3298
- } }
3299
- }];
3300
3377
  var no_unstable_default_props_default = createRule({
3301
3378
  meta: {
3302
3379
  type: "problem",
3303
- defaultOptions: [...defaultOptions$1],
3380
+ defaultOptions: [{}],
3304
3381
  docs: { description: "Prevents using referential-type values as default props in object destructuring." },
3305
3382
  messages: { default: "A/an '{{kind}}' as default prop. This could lead to potential infinite render loop in React. Use a variable instead of '{{kind}}'." },
3306
- schema: schema$1
3383
+ schema: [{
3384
+ type: "object",
3385
+ additionalProperties: false,
3386
+ properties: { safeDefaultProps: {
3387
+ type: "array",
3388
+ description: "Property names or patterns that are safe to use as default props.",
3389
+ items: { type: "string" }
3390
+ } }
3391
+ }]
3307
3392
  },
3308
- name: RULE_NAME$12,
3393
+ name: "no-unstable-default-props",
3309
3394
  create: create$12
3310
3395
  });
3311
3396
  function create$12(context) {
3312
- const { safeDefaultProps } = complete(context.options[0], defaultOptions$1[0]);
3397
+ const safeDefaultProps = (context.options[0] ?? {}).safeDefaultProps ?? [];
3313
3398
  const { compilationMode } = getSettingsFromContext(context);
3314
3399
  if (compilationMode === "infer" || compilationMode === "all") return {};
3315
3400
  if (compilationMode === "annotation" && context.sourceCode.ast.body.some((stmt) => Check.isDirective(stmt, "use memo"))) return {};
@@ -4074,16 +4159,23 @@ function getDestructuredPropertyName(pattern, name) {
4074
4159
  for (const property of pattern.properties) {
4075
4160
  if (property.type !== AST_NODE_TYPES.Property) continue;
4076
4161
  if ((property.value.type === AST_NODE_TYPES.AssignmentPattern ? property.value.left : property.value) !== name) continue;
4077
- return Extract.getPropertyName(property, "max");
4162
+ const key = Extract.unwrap(property.key);
4163
+ if (!property.computed && Check.isIdentifier(key)) return key.name;
4164
+ if (key.type === AST_NODE_TYPES.Literal && typeof key.value === "string") return key.value;
4165
+ if (key.type === AST_NODE_TYPES.TemplateLiteral && key.expressions.length === 0) return key.quasis[0]?.value.cooked ?? key.quasis[0]?.value.raw ?? null;
4166
+ return null;
4078
4167
  }
4079
4168
  return null;
4080
4169
  }
4081
4170
  function resolveBuiltinMember(context, node, seen = /* @__PURE__ */ new Set()) {
4082
- for (let current = node; current.type === AST_NODE_TYPES.MemberExpression; current = Extract.unwrap(current.object)) if (current.computed) return null;
4083
- const chain = Extract.getMemberChain(node);
4084
- const rootId = chain.at(0);
4085
- if (rootId == null || !Check.isIdentifier(rootId)) return null;
4086
- const segments = chain.slice(1);
4171
+ let rootId = Extract.unwrap(node);
4172
+ const segments = [];
4173
+ for (let current = rootId; current.type === AST_NODE_TYPES.MemberExpression; current = Extract.unwrap(current.object)) {
4174
+ if (current.computed) return null;
4175
+ segments.unshift(Extract.unwrap(current.property));
4176
+ rootId = Extract.unwrap(current.object);
4177
+ }
4178
+ if (!Check.isIdentifier(rootId)) return null;
4087
4179
  if (segments.length === 0 || !segments.every((segment) => Check.isIdentifier(segment))) return null;
4088
4180
  const resolved = resolveBuiltinObjectName(context, rootId, seen);
4089
4181
  if (resolved == null) return null;
@@ -6096,7 +6188,7 @@ function isInsideTryCatch(node) {
6096
6188
  }
6097
6189
  return false;
6098
6190
  }
6099
- function getNodeWithoutReactNamespace$1(node) {
6191
+ function getNodeWithoutReactNamespace(node) {
6100
6192
  if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "React" && node.property.type === "Identifier" && !node.computed) return node.property;
6101
6193
  return node;
6102
6194
  }
@@ -6105,7 +6197,7 @@ function isEffectIdentifier(node, additionalHooks) {
6105
6197
  if (additionalHooks && node.type === "Identifier") return additionalHooks.test(node.name);
6106
6198
  return false;
6107
6199
  }
6108
- function isUseEffectEventIdentifier$1(node) {
6200
+ function isUseEffectEventIdentifier(node) {
6109
6201
  return node.type === "Identifier" && node.name === "useEffectEvent";
6110
6202
  }
6111
6203
  function useEffectEventError(fn, called) {
@@ -6115,7 +6207,7 @@ function useEffectEventError(fn, called) {
6115
6207
  function isUseIdentifier(node) {
6116
6208
  return isReactFunction(node, "use");
6117
6209
  }
6118
- const rule$1 = {
6210
+ const rule = {
6119
6211
  meta: {
6120
6212
  type: "problem",
6121
6213
  docs: {
@@ -6140,7 +6232,7 @@ const rule$1 = {
6140
6232
  function recordAllUseEffectEventFunctions(scope) {
6141
6233
  for (const reference of scope.references) {
6142
6234
  const parent = reference.identifier.parent;
6143
- if (parent?.type === "VariableDeclarator" && parent.init && parent.init.type === "CallExpression" && parent.init.callee && isUseEffectEventIdentifier$1(parent.init.callee)) {
6235
+ if (parent?.type === "VariableDeclarator" && parent.init && parent.init.type === "CallExpression" && parent.init.callee && isUseEffectEventIdentifier(parent.init.callee)) {
6144
6236
  if (reference.resolved === null) throw new Error("Unexpected null reference.resolved");
6145
6237
  for (const ref of reference.resolved.references) if (ref !== reference) useEffectEventFunctions.add(ref.identifier);
6146
6238
  }
@@ -6319,9 +6411,9 @@ const rule$1 = {
6319
6411
  }
6320
6412
  reactHooks.push(callee);
6321
6413
  }
6322
- const nodeWithoutNamespace = getNodeWithoutReactNamespace$1(node.callee);
6323
- if ((isEffectIdentifier(nodeWithoutNamespace, additionalEffectHooks) || isUseEffectEventIdentifier$1(nodeWithoutNamespace)) && node.arguments.length > 0) lastEffect = node;
6324
- if (isUseEffectEventIdentifier$1(nodeWithoutNamespace) && node.parent?.type !== "VariableDeclarator" && node.parent?.type !== "ExpressionStatement") {
6414
+ const nodeWithoutNamespace = getNodeWithoutReactNamespace(node.callee);
6415
+ if ((isEffectIdentifier(nodeWithoutNamespace, additionalEffectHooks) || isUseEffectEventIdentifier(nodeWithoutNamespace)) && node.arguments.length > 0) lastEffect = node;
6416
+ if (isUseEffectEventIdentifier(nodeWithoutNamespace) && node.parent?.type !== "VariableDeclarator" && node.parent?.type !== "ExpressionStatement") {
6325
6417
  const message = useEffectEventError(null, false);
6326
6418
  context.report({
6327
6419
  node,
@@ -6667,6 +6759,9 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
6667
6759
  if (survivingCandidates.length > 0) return survivingCandidates.some((c) => c.previous != null && isInitializedFromRef(c.previous, refParams, seen) || isRefValue(c.value, refParams, seen, "initializer"));
6668
6760
  return variable.defs.some((d) => d.type === DefinitionType.Parameter && (refParams?.has(d.name) === true || d.name.type === AST_NODE_TYPES.Identifier && isRefLikeName(d.name.name)));
6669
6761
  }
6762
+ function isInitializedFromParameter(id) {
6763
+ return findVariable(context.sourceCode.getScope(id), id)?.defs.some((d) => d.type === DefinitionType.Parameter) ?? false;
6764
+ }
6670
6765
  function isRefValue(node, refParams, seen, mode) {
6671
6766
  const expression = Extract.unwrap(node);
6672
6767
  if (isUseRefCall(expression)) return true;
@@ -6675,7 +6770,7 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
6675
6770
  case AST_NODE_TYPES.MemberExpression: {
6676
6771
  const property = Extract.unwrap(expression.property);
6677
6772
  const object = Extract.unwrap(expression.object);
6678
- if (!expression.computed && Check.isIdentifier(property, "current") && object.type === AST_NODE_TYPES.Identifier && isParameterId(object)) return true;
6773
+ if (!expression.computed && Check.isIdentifier(property, "current") && object.type === AST_NODE_TYPES.Identifier && isInitializedFromParameter(object)) return true;
6679
6774
  if (mode === "initializer") {
6680
6775
  let current = expression;
6681
6776
  while (current.type === AST_NODE_TYPES.MemberExpression) {
@@ -6684,7 +6779,7 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
6684
6779
  if (!current.computed && Check.isIdentifier(currentProperty, "current")) {
6685
6780
  const sourceName = getRefSourceName(currentObject);
6686
6781
  if (sourceName != null && isRefLikeName(sourceName)) return true;
6687
- if (currentObject.type === AST_NODE_TYPES.Identifier && isParameterId(currentObject)) return true;
6782
+ if (currentObject.type === AST_NODE_TYPES.Identifier && isInitializedFromParameter(currentObject)) return true;
6688
6783
  }
6689
6784
  current = currentObject;
6690
6785
  }
@@ -6785,9 +6880,6 @@ function createSetStateResolver$1(context, facts = EMPTY_FACTS) {
6785
6880
  }
6786
6881
  return false;
6787
6882
  }
6788
- function isParameterId(id) {
6789
- return findVariable(context.sourceCode.getScope(id), id)?.defs.some((d) => d.type === DefinitionType.Parameter) ?? false;
6790
- }
6791
6883
  return {
6792
6884
  getRefDerivedParams,
6793
6885
  getSetterName,
@@ -7135,9 +7227,7 @@ function inferCreatedComponents(context, componentUsages, isInsideRender) {
7135
7227
  for (const usage of componentUsages) {
7136
7228
  const variable = findVariable(context.sourceCode.getScope(usage.node), usage.name);
7137
7229
  if (variable == null) continue;
7138
- const def = variable.defs.at(0);
7139
- if (def == null) continue;
7140
- if (!isInsideRender(def.node)) continue;
7230
+ if (!variable.defs.some((def) => isInsideRender(def.node))) continue;
7141
7231
  const { creationNode, isDynamic } = resolveDynamicComponentOrigin(context, variable, isInsideRender);
7142
7232
  if (!isDynamic) continue;
7143
7233
  effects.push({
@@ -7174,7 +7264,6 @@ function create$3(context) {
7174
7264
  messageId: "default",
7175
7265
  node: effect.node
7176
7266
  });
7177
- if (effect.creationNode == null) continue;
7178
7267
  if (reportedCreations.has(effect.creationNode)) continue;
7179
7268
  reportedCreations.add(effect.creationNode);
7180
7269
  context.report({
@@ -7184,1065 +7273,63 @@ function create$3(context) {
7184
7273
  }
7185
7274
  } });
7186
7275
  }
7187
- // src/rules/unstable-exhaustive-deps/lib.ts
7188
- function getHookConfigs(hooks = []) {
7189
- const reactive = /* @__PURE__ */ new Map();
7190
- const stable = /* @__PURE__ */ new Map();
7191
- for (const { name, closureIndex, dependenciesIndex, stableResult } of hooks) {
7192
- if (closureIndex != null && dependenciesIndex != null && closureIndex !== dependenciesIndex) reactive.set(name, {
7193
- closureIndex,
7194
- dependenciesIndex
7195
- });
7196
- if (stableResult === true) stable.set(name, true);
7197
- else if (typeof stableResult === "number") stable.set(name, /* @__PURE__ */ new Set([stableResult]));
7198
- else if (Array.isArray(stableResult)) stable.set(name, new Set(stableResult));
7276
+ // src/rules/unsupported-syntax/lib.ts
7277
+ function isEvalCall(node) {
7278
+ const callee = Extract.unwrap(node.callee);
7279
+ switch (callee.type) {
7280
+ case AST_NODE_TYPES.Identifier: return callee.name === "eval";
7281
+ case AST_NODE_TYPES.MemberExpression:
7282
+ if (!Check.isIdentifier(Extract.unwrap(callee.object), "globalThis")) return false;
7283
+ return !callee.computed && Check.isIdentifier(callee.property, "eval");
7284
+ default: return false;
7199
7285
  }
7200
- return {
7201
- reactive,
7202
- stable
7203
- };
7204
- }
7205
- function getReactiveHookConfig(node, configs) {
7206
- if (configs.reactive.size === 0) return null;
7207
- const name = Extract.getCalleeName(node);
7208
- if (name == null) return null;
7209
- const config = configs.reactive.get(name);
7210
- if (config == null) return null;
7211
- return {
7212
- name,
7213
- ...config
7214
- };
7215
- }
7216
- function isConfiguredStableHookValue(variable, configs) {
7217
- if (configs.stable.size === 0) return false;
7218
- let matchedNode = null;
7219
- let stableResult = null;
7220
- let initializerCount = 0;
7221
- for (const def of variable.defs) {
7222
- if (def.type !== DefinitionType.Variable || def.node.init == null) continue;
7223
- initializerCount++;
7224
- const init = Extract.unwrap(def.node.init);
7225
- if (init.type !== AST_NODE_TYPES.CallExpression) continue;
7226
- const name = Extract.getCalleeName(init);
7227
- if (name == null) continue;
7228
- const config = configs.stable.get(name);
7229
- if (config == null) continue;
7230
- if (matchedNode != null) return false;
7231
- matchedNode = def.node;
7232
- stableResult = config;
7233
- }
7234
- if (initializerCount !== 1) return false;
7235
- if (matchedNode == null || stableResult == null) return false;
7236
- if (variable.references.some((reference) => reference.isWrite() && reference.init !== true)) return false;
7237
- const { id } = matchedNode;
7238
- if (stableResult === true) return id.type === AST_NODE_TYPES.Identifier;
7239
- if (id.type !== AST_NODE_TYPES.ArrayPattern) return false;
7240
- const index = id.elements.findIndex((element) => {
7241
- if (element == null) return false;
7242
- const binding = element.type === AST_NODE_TYPES.AssignmentPattern ? element.left : element;
7243
- return variable.identifiers.some((identifier) => identifier === binding);
7244
- });
7245
- return index !== -1 && stableResult.has(index);
7246
7286
  }
7247
- // src/rules/unstable-exhaustive-deps/unstable-exhaustive-deps.ts
7248
- const rule = {
7287
+ var unsupported_syntax_default = createRule({
7249
7288
  meta: {
7250
- type: "suggestion",
7251
- docs: {
7252
- description: "Verifies the list of dependencies for Hooks like 'useEffect' and similar, with support for custom Hooks and stable Hook results.",
7253
- url: "https://eslint-react.xyz/docs/rules/unstable-exhaustive-deps"
7289
+ type: "problem",
7290
+ docs: { description: "Validates against syntax that React Compiler does not support." },
7291
+ messages: {
7292
+ eval: "Do not use 'eval' inside components or hooks. 'eval' cannot be statically analyzed and is not supported by React Compiler.",
7293
+ with: "Do not use 'with' statements inside components or hooks. 'with' changes scope dynamically and is not supported by React Compiler."
7254
7294
  },
7255
- fixable: "code",
7256
- hasSuggestions: true,
7257
- schema: [{
7258
- type: "object",
7259
- additionalProperties: false,
7260
- enableDangerousAutofixThisMayCauseInfiniteLoops: false,
7261
- properties: {
7262
- additionalHooks: { type: "string" },
7263
- enableDangerousAutofixThisMayCauseInfiniteLoops: { type: "boolean" },
7264
- experimental_autoDependenciesHooks: {
7265
- type: "array",
7266
- items: { type: "string" }
7267
- },
7268
- hooks: {
7269
- type: "array",
7270
- items: {
7271
- type: "object",
7272
- additionalProperties: false,
7273
- dependencies: {
7274
- closureIndex: ["dependenciesIndex"],
7275
- dependenciesIndex: ["closureIndex"]
7276
- },
7277
- properties: {
7278
- name: {
7279
- type: "string",
7280
- minLength: 1
7281
- },
7282
- closureIndex: {
7283
- type: "integer",
7284
- minimum: 0
7285
- },
7286
- dependenciesIndex: {
7287
- type: "integer",
7288
- minimum: 0
7289
- },
7290
- stableResult: { oneOf: [
7291
- { type: "boolean" },
7292
- {
7293
- type: "integer",
7294
- minimum: 0
7295
- },
7296
- {
7297
- type: "array",
7298
- items: {
7299
- type: "integer",
7300
- minimum: 0
7301
- },
7302
- minItems: 1
7303
- }
7304
- ] }
7305
- },
7306
- required: ["name"]
7307
- }
7308
- },
7309
- requireExplicitEffectDeps: { type: "boolean" }
7310
- }
7311
- }]
7295
+ schema: []
7312
7296
  },
7313
- create(context) {
7314
- const rawOptions = context.options && context.options[0];
7315
- const additionalHooks = rawOptions && rawOptions.additionalHooks ? new RegExp(rawOptions.additionalHooks) : getSettingsFromContext(context).additionalEffectHooks;
7316
- const enableDangerousAutofixThisMayCauseInfiniteLoops = rawOptions && rawOptions.enableDangerousAutofixThisMayCauseInfiniteLoops || false;
7317
- const experimental_autoDependenciesHooks = rawOptions && Array.isArray(rawOptions.experimental_autoDependenciesHooks) ? rawOptions.experimental_autoDependenciesHooks : [];
7318
- const requireExplicitEffectDeps = rawOptions && rawOptions.requireExplicitEffectDeps || false;
7319
- const options = {
7320
- additionalHooks,
7321
- experimental_autoDependenciesHooks,
7322
- enableDangerousAutofixThisMayCauseInfiniteLoops,
7323
- hooks: getHookConfigs(rawOptions && rawOptions.hooks),
7324
- requireExplicitEffectDeps
7325
- };
7326
- function reportProblem(problem) {
7327
- if (enableDangerousAutofixThisMayCauseInfiniteLoops) {
7328
- if (Array.isArray(problem.suggest) && problem.suggest.length > 0 && problem.suggest[0]) problem.fix = problem.suggest[0].fix;
7329
- }
7330
- context.report(problem);
7331
- }
7332
- const getSourceCode = typeof context.getSourceCode === "function" ? () => {
7333
- return context.getSourceCode();
7334
- } : () => {
7335
- return context.sourceCode;
7336
- };
7337
- const getScope = typeof context.getScope === "function" ? () => {
7338
- return context.getScope();
7339
- } : (node) => {
7340
- return context.sourceCode.getScope(node);
7341
- };
7342
- const scopeManager = getSourceCode().scopeManager;
7343
- const setStateCallSites = /* @__PURE__ */ new WeakMap();
7344
- const stateVariables = /* @__PURE__ */ new WeakSet();
7345
- const stableKnownValueCache = /* @__PURE__ */ new WeakMap();
7346
- const functionWithoutCapturedValueCache = /* @__PURE__ */ new WeakMap();
7347
- const useEffectEventVariables = /* @__PURE__ */ new WeakSet();
7348
- function memoizeWithWeakMap(fn, map) {
7349
- return function(arg) {
7350
- if (map.has(arg)) return map.get(arg);
7351
- const result = fn(arg);
7352
- map.set(arg, result);
7353
- return result;
7354
- };
7355
- }
7356
- function visitFunctionWithDependencies(node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, callExpression, dependenciesIndex) {
7357
- if (isEffect && node.async) reportProblem({
7358
- node,
7359
- 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"
7297
+ name: "unsupported-syntax",
7298
+ create: create$2
7299
+ });
7300
+ function create$2(context) {
7301
+ const hc = core.getHookCollector(context);
7302
+ const fc = core.getFunctionComponentCollector(context);
7303
+ const evalCalls = [];
7304
+ const withStmts = [];
7305
+ return merge(hc.visitor, fc.visitor, {
7306
+ CallExpression(node) {
7307
+ if (!isEvalCall(node)) return;
7308
+ const func = Traverse.findParent(node, Check.isFunction);
7309
+ if (func == null) return;
7310
+ evalCalls.push({
7311
+ func,
7312
+ node
7360
7313
  });
7361
- const scope = scopeManager.acquire(node);
7362
- 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.");
7363
- const pureScopes = /* @__PURE__ */ new Set();
7364
- let componentScope = null;
7365
- {
7366
- let currentScope = scope.upper;
7367
- while (currentScope) {
7368
- pureScopes.add(currentScope);
7369
- if (currentScope.type === "function" || currentScope.type === "hook" || currentScope.type === "component") break;
7370
- currentScope = currentScope.upper;
7371
- }
7372
- if (!currentScope) return;
7373
- componentScope = currentScope;
7374
- }
7375
- const isArray = Array.isArray;
7376
- function isStableKnownHookValue(resolved) {
7377
- if (!isArray(resolved.defs)) return false;
7378
- const initializers = resolved.defs.filter((definition) => definition.type === "Variable" && definition.node.type === "VariableDeclarator" && definition.node.init != null);
7379
- if (initializers.length !== 1) return false;
7380
- const def = initializers[0];
7381
- const defNode = def.node;
7382
- if (defNode.type !== "VariableDeclarator") return false;
7383
- let init = defNode.init;
7384
- if (init == null) return false;
7385
- while (init.type === "TSAsExpression" || init.type === "AsExpression") init = init.expression;
7386
- let declaration = defNode.parent;
7387
- if (declaration == null && componentScope != null) {
7388
- fastFindReferenceWithParent(componentScope.block, def.node.id);
7389
- declaration = def.node.parent;
7390
- if (declaration == null) return false;
7391
- }
7392
- 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;
7393
- if (init.type !== "CallExpression") return false;
7394
- let callee = init.callee;
7395
- if (callee.type === "MemberExpression" && "name" in callee.object && callee.object.name === "React" && callee.property != null && !callee.computed) callee = callee.property;
7396
- if (callee.type !== "Identifier") return false;
7397
- const id = def.node.id;
7398
- const { name } = callee;
7399
- if (name === "useRef" && id.type === "Identifier") return true;
7400
- else if (isUseEffectEventIdentifier(callee) && id.type === "Identifier") {
7401
- for (const ref of resolved.references) if (ref !== id) useEffectEventVariables.add(ref.identifier);
7402
- return true;
7403
- } else if (name === "useState" || name === "useReducer" || name === "useActionState") {
7404
- const isActionState = name === "useActionState";
7405
- if (id.type === "ArrayPattern" && (isActionState ? id.elements.length >= 2 : id.elements.length === 2) && isArray(resolved.identifiers)) {
7406
- const firstNode = id.elements[0] ?? null;
7407
- const secondNode = id.elements[1] ?? null;
7408
- const firstElement = firstNode?.type === "AssignmentPattern" ? firstNode.left : firstNode;
7409
- const secondElement = secondNode?.type === "AssignmentPattern" ? secondNode.left : secondNode;
7410
- if (resolved.identifiers.some((identifier) => identifier === secondElement)) {
7411
- if (name === "useState") {
7412
- const references = resolved.references;
7413
- for (const reference of references) {
7414
- if (reference.isWrite() && reference.init !== true) return false;
7415
- setStateCallSites.set(reference.identifier, firstElement);
7416
- }
7417
- }
7418
- return true;
7419
- } else if (resolved.identifiers.some((identifier) => identifier === firstElement)) {
7420
- if (name === "useState") {
7421
- const references = resolved.references;
7422
- for (const reference of references) stateVariables.add(reference.identifier);
7423
- }
7424
- return false;
7425
- }
7426
- }
7427
- } else if (name === "useTransition") {
7428
- if (id.type === "ArrayPattern" && id.elements.length === 2 && Array.isArray(resolved.identifiers)) {
7429
- const secondNode = id.elements[1] ?? null;
7430
- const secondElement = secondNode?.type === "AssignmentPattern" ? secondNode.left : secondNode;
7431
- if (resolved.identifiers.some((identifier) => identifier === secondElement)) return true;
7432
- }
7433
- }
7434
- return false;
7435
- }
7436
- function isFunctionWithoutCapturedValues(resolved) {
7437
- if (!isArray(resolved.defs)) return false;
7438
- const def = resolved.defs[0];
7439
- if (def == null) return false;
7440
- if (def.node == null || def.node.id == null) return false;
7441
- const fnNode = def.node;
7442
- const childScopes = componentScope?.childScopes || [];
7443
- let fnScope = null;
7444
- for (const childScope of childScopes) {
7445
- const childScopeBlock = childScope.block;
7446
- if (fnNode.type === "FunctionDeclaration" && childScopeBlock === fnNode || fnNode.type === "VariableDeclarator" && childScopeBlock.parent === fnNode) {
7447
- fnScope = childScope;
7448
- break;
7449
- }
7450
- }
7451
- if (fnScope == null) return false;
7452
- for (const ref of fnScope.through) {
7453
- if (ref.resolved == null) continue;
7454
- if (pureScopes.has(ref.resolved.scope) && !memoizedIsStableKnownHookValue(ref.resolved)) return false;
7455
- }
7456
- return true;
7457
- }
7458
- const memoizedIsStableKnownHookValue = memoizeWithWeakMap((resolved) => isStableKnownHookValue(resolved) || isConfiguredStableHookValue(resolved, options.hooks), stableKnownValueCache);
7459
- const memoizedIsFunctionWithoutCapturedValues = memoizeWithWeakMap(isFunctionWithoutCapturedValues, functionWithoutCapturedValueCache);
7460
- const currentRefsInEffectCleanup = /* @__PURE__ */ new Map();
7461
- function isInsideEffectCleanup(reference) {
7462
- let curScope = reference.from;
7463
- let isInReturnedFunction = false;
7464
- while (curScope != null && curScope.block !== node) {
7465
- if (curScope.type === "function") isInReturnedFunction = curScope.block.parent != null && curScope.block.parent.type === "ReturnStatement";
7466
- curScope = curScope.upper;
7467
- }
7468
- return isInReturnedFunction;
7469
- }
7470
- const dependencies = /* @__PURE__ */ new Map();
7471
- const optionalChains = /* @__PURE__ */ new Map();
7472
- gatherDependenciesRecursively(scope);
7473
- function gatherDependenciesRecursively(currentScope) {
7474
- for (const reference of currentScope.references) {
7475
- if (!reference.resolved) continue;
7476
- if (!pureScopes.has(reference.resolved.scope)) continue;
7477
- const referenceNode = fastFindReferenceWithParent(node, reference.identifier);
7478
- if (referenceNode == null) continue;
7479
- const dependencyNode = getDependency(referenceNode);
7480
- const dependency = analyzePropertyChain(dependencyNode, optionalChains);
7481
- 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, {
7482
- reference,
7483
- dependencyNode
7484
- });
7485
- if (dependencyNode.parent?.type === "TSTypeQuery" || dependencyNode.parent?.type === "TSTypeReference") continue;
7486
- const def = reference.resolved.defs[0];
7487
- if (def == null) continue;
7488
- if (def.node != null && def.node.init === node.parent) continue;
7489
- if (def.type === "TypeParameter" || dependencyNode.parent?.type === "GenericTypeAnnotation") continue;
7490
- if (!dependencies.has(dependency)) {
7491
- const resolved = reference.resolved;
7492
- const isStable = memoizedIsStableKnownHookValue(resolved) || memoizedIsFunctionWithoutCapturedValues(resolved);
7493
- dependencies.set(dependency, {
7494
- isStable,
7495
- references: [reference]
7496
- });
7497
- } else dependencies.get(dependency)?.references.push(reference);
7498
- }
7499
- for (const childScope of currentScope.childScopes) gatherDependenciesRecursively(childScope);
7500
- }
7501
- currentRefsInEffectCleanup.forEach(({ reference, dependencyNode }, dependency) => {
7502
- const references = reference.resolved?.references || [];
7503
- let foundCurrentAssignment = false;
7504
- for (const ref of references) {
7505
- const { identifier } = ref;
7506
- const { parent } = identifier;
7507
- if (parent != null && parent.type === "MemberExpression" && !parent.computed && parent.property.type === "Identifier" && parent.property.name === "current" && parent.parent?.type === "AssignmentExpression" && parent.parent.left === parent) {
7508
- foundCurrentAssignment = true;
7509
- break;
7510
- }
7511
- }
7512
- if (foundCurrentAssignment) return;
7513
- reportProblem({
7514
- node: dependencyNode.parent.property,
7515
- 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.`
7516
- });
7517
- });
7518
- const staleAssignments = /* @__PURE__ */ new Set();
7519
- function reportStaleAssignment(writeExpr, key) {
7520
- if (staleAssignments.has(key)) return;
7521
- staleAssignments.add(key);
7522
- reportProblem({
7523
- node: writeExpr,
7524
- 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)}.`
7525
- });
7526
- }
7527
- const stableDependencies = /* @__PURE__ */ new Set();
7528
- dependencies.forEach(({ isStable, references }, key) => {
7529
- if (isStable) stableDependencies.add(key);
7530
- references.forEach((reference) => {
7531
- if (reference.writeExpr) reportStaleAssignment(reference.writeExpr, key);
7532
- });
7533
- });
7534
- if (staleAssignments.size > 0) return;
7535
- if (!declaredDependenciesNode) {
7536
- if (isAutoDepsHook) return;
7537
- let setStateInsideEffectWithoutDeps = null;
7538
- dependencies.forEach(({ references }, key) => {
7539
- if (setStateInsideEffectWithoutDeps) return;
7540
- references.forEach((reference) => {
7541
- if (setStateInsideEffectWithoutDeps) return;
7542
- const id = reference.identifier;
7543
- if (!setStateCallSites.has(id)) return;
7544
- let fnScope = reference.from;
7545
- while (fnScope != null && fnScope.type !== "function") fnScope = fnScope.upper;
7546
- if (fnScope?.block === node) setStateInsideEffectWithoutDeps = key;
7547
- });
7548
- });
7549
- if (setStateInsideEffectWithoutDeps) {
7550
- const { suggestedDependencies } = collectRecommendations({
7551
- dependencies,
7552
- declaredDependencies: [],
7553
- stableDependencies,
7554
- externalDependencies: /* @__PURE__ */ new Set(),
7555
- isEffect: true
7556
- });
7557
- const suggestedDependenciesText = `[${suggestedDependencies.join(", ")}]`;
7558
- const dependenciesArgument = callExpression.arguments[dependenciesIndex];
7559
- const hasSpreadArgumentBeforeOrAtDependencies = callExpression.arguments.slice(0, dependenciesIndex + 1).some((argument) => argument?.type === "SpreadElement");
7560
- let fix = null;
7561
- if (!hasSpreadArgumentBeforeOrAtDependencies) {
7562
- if (dependenciesArgument?.type === "Identifier" && dependenciesArgument.name === "undefined") fix = (fixer) => fixer.replaceText(dependenciesArgument, suggestedDependenciesText);
7563
- else if (dependenciesArgument == null && dependenciesIndex === callExpression.arguments.length) {
7564
- const closeParen = getSourceCode().getLastToken(callExpression);
7565
- if (closeParen != null && closeParen.value === ")") {
7566
- const tokenBeforeCloseParen = getSourceCode().getTokenBefore(closeParen);
7567
- fix = tokenBeforeCloseParen?.value === "," ? (fixer) => fixer.insertTextAfter(tokenBeforeCloseParen, ` ${suggestedDependenciesText}`) : (fixer) => fixer.insertTextBefore(closeParen, `, ${suggestedDependenciesText}`);
7568
- }
7569
- }
7570
- }
7571
- const dependenciesArgumentText = dependenciesIndex === 1 ? "as a second argument" : `as the dependencies argument (index ${dependenciesIndex})`;
7572
- const problem = {
7573
- node: reactiveHook,
7574
- 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.`
7575
- };
7576
- if (fix != null) problem.suggest = [{
7577
- desc: `Add dependencies array: ${suggestedDependenciesText}`,
7578
- fix
7579
- }];
7580
- reportProblem(problem);
7581
- }
7582
- return;
7583
- }
7584
- if (isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) return;
7585
- const declaredDependencies = [];
7586
- const externalDependencies = /* @__PURE__ */ new Set();
7587
- const isArrayExpression = declaredDependenciesNode.type === "ArrayExpression";
7588
- const isTSAsArrayExpression = declaredDependenciesNode.type === "TSAsExpression" && declaredDependenciesNode.expression.type === "ArrayExpression";
7589
- if (!isArrayExpression && !isTSAsArrayExpression) reportProblem({
7590
- node: declaredDependenciesNode,
7591
- 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.`
7592
- });
7593
- else (isTSAsArrayExpression ? declaredDependenciesNode.expression : declaredDependenciesNode).elements.forEach((declaredDependencyNode) => {
7594
- if (declaredDependencyNode === null) return;
7595
- if (declaredDependencyNode.type === "SpreadElement") {
7596
- reportProblem({
7597
- node: declaredDependencyNode,
7598
- 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.`
7599
- });
7600
- return;
7601
- }
7602
- if (useEffectEventVariables.has(declaredDependencyNode)) reportProblem({
7603
- node: declaredDependencyNode,
7604
- message: `Functions returned from \`useEffectEvent\` must not be included in the dependency array. Remove \`${getSourceCode().getText(declaredDependencyNode)}\` from the list.`,
7605
- suggest: [{
7606
- desc: `Remove the dependency \`${getSourceCode().getText(declaredDependencyNode)}\``,
7607
- fix(fixer) {
7608
- return fixer.removeRange(declaredDependencyNode.range);
7609
- }
7610
- }]
7611
- });
7612
- let declaredDependency;
7613
- try {
7614
- declaredDependency = analyzePropertyChain(declaredDependencyNode, null);
7615
- } catch (error) {
7616
- if (error instanceof Error && /Unsupported node type/.test(error.message)) {
7617
- if (declaredDependencyNode.type === "Literal") {
7618
- if (declaredDependencyNode.value && dependencies.has(declaredDependencyNode.value)) reportProblem({
7619
- node: declaredDependencyNode,
7620
- 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?`
7621
- });
7622
- else reportProblem({
7623
- node: declaredDependencyNode,
7624
- message: `The ${declaredDependencyNode.raw} literal is not a valid dependency because it never changes. You can safely remove it.`
7625
- });
7626
- } else reportProblem({
7627
- node: declaredDependencyNode,
7628
- 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.`
7629
- });
7630
- return;
7631
- } else throw error;
7632
- }
7633
- let maybeID = declaredDependencyNode;
7634
- while (maybeID.type === "MemberExpression" || maybeID.type === "OptionalMemberExpression" || maybeID.type === "ChainExpression") maybeID = maybeID.object || maybeID.expression.object;
7635
- const isDeclaredInComponent = !componentScope.through.some((ref) => ref.identifier === maybeID);
7636
- declaredDependencies.push({
7637
- key: declaredDependency,
7638
- node: declaredDependencyNode
7639
- });
7640
- if (!isDeclaredInComponent) externalDependencies.add(declaredDependency);
7641
- });
7642
- const { suggestedDependencies, unnecessaryDependencies, missingDependencies, duplicateDependencies } = collectRecommendations({
7643
- dependencies,
7644
- declaredDependencies,
7645
- stableDependencies,
7646
- externalDependencies,
7647
- isEffect
7648
- });
7649
- let suggestedDeps = suggestedDependencies;
7650
- if (duplicateDependencies.size + missingDependencies.size + unnecessaryDependencies.size === 0) {
7651
- scanForConstructions({
7652
- declaredDependencies,
7653
- declaredDependenciesNode,
7654
- componentScope,
7655
- scope
7656
- }).forEach(({ construction, isUsedOutsideOfHook, depType }) => {
7657
- const wrapperHook = depType === "function" ? "useCallback" : "useMemo";
7658
- const constructionType = depType === "function" ? "definition" : "initialization";
7659
- const defaultAdvice = `wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`;
7660
- const advice = isUsedOutsideOfHook ? `To fix this, ${defaultAdvice}` : `Move it inside the ${reactiveHookName} callback. Alternatively, ${defaultAdvice}`;
7661
- const causation = depType === "conditional" || depType === "logical expression" ? "could make" : "makes";
7662
- const message = `The '${construction.name.name}' ${depType} ${causation} the dependencies of ${reactiveHookName} Hook (at line ${declaredDependenciesNode.loc?.start.line}) change on every render. ${advice}`;
7663
- let suggest;
7664
- if (isUsedOutsideOfHook && construction.type === "Variable" && depType === "function") suggest = [{
7665
- desc: `Wrap the ${constructionType} of '${construction.name.name}' in its own ${wrapperHook}() Hook.`,
7666
- fix(fixer) {
7667
- const [before, after] = wrapperHook === "useMemo" ? [`useMemo(() => { return `, "; })"] : ["useCallback(", ")"];
7668
- return [fixer.insertTextBefore(construction.node.init, before), fixer.insertTextAfter(construction.node.init, after)];
7669
- }
7670
- }];
7671
- reportProblem({
7672
- node: construction.node,
7673
- message,
7674
- suggest
7675
- });
7676
- });
7677
- return;
7678
- }
7679
- if (!isEffect && missingDependencies.size > 0) suggestedDeps = collectRecommendations({
7680
- dependencies,
7681
- declaredDependencies: [],
7682
- stableDependencies,
7683
- externalDependencies,
7684
- isEffect
7685
- }).suggestedDependencies;
7686
- function areDeclaredDepsAlphabetized() {
7687
- if (declaredDependencies.length === 0) return true;
7688
- const declaredDepKeys = declaredDependencies.map((dep) => dep.key);
7689
- const sortedDeclaredDepKeys = declaredDepKeys.slice().sort();
7690
- return declaredDepKeys.join(",") === sortedDeclaredDepKeys.join(",");
7691
- }
7692
- if (areDeclaredDepsAlphabetized()) suggestedDeps.sort();
7693
- function formatDependency(path) {
7694
- const members = path.split(".");
7695
- let finalPath = "";
7696
- for (let i = 0; i < members.length; i++) {
7697
- if (i !== 0) {
7698
- const pathSoFar = members.slice(0, i + 1).join(".");
7699
- const isOptional = optionalChains.get(pathSoFar) === true;
7700
- finalPath += isOptional ? "?." : ".";
7701
- }
7702
- finalPath += members[i];
7703
- }
7704
- return finalPath;
7705
- }
7706
- function getWarningMessage(deps, singlePrefix, label, fixVerb) {
7707
- if (deps.size === 0) return null;
7708
- 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.`;
7709
- }
7710
- let extraWarning = "";
7711
- if (unnecessaryDependencies.size > 0) {
7712
- let badRef = null;
7713
- Array.from(unnecessaryDependencies.keys()).forEach((key) => {
7714
- if (badRef !== null) return;
7715
- if (key.endsWith(".current")) badRef = key;
7716
- });
7717
- if (badRef !== null) extraWarning = ` Mutable values like '${badRef}' aren't valid dependencies because mutating them doesn't re-render the component.`;
7718
- else if (externalDependencies.size > 0) {
7719
- const dep = Array.from(externalDependencies)[0];
7720
- if (!scope.set.has(dep)) extraWarning = ` Outer scope values like '${dep}' aren't valid dependencies because mutating them doesn't re-render the component.`;
7721
- }
7722
- }
7723
- if (!extraWarning && missingDependencies.has("props")) {
7724
- const propDep = dependencies.get("props");
7725
- if (propDep == null) return;
7726
- const refs = propDep.references;
7727
- if (!Array.isArray(refs)) return;
7728
- let isPropsOnlyUsedInMembers = true;
7729
- for (const ref of refs) {
7730
- const id = fastFindReferenceWithParent(componentScope.block, ref.identifier);
7731
- if (!id) {
7732
- isPropsOnlyUsedInMembers = false;
7733
- break;
7734
- }
7735
- const parent = id.parent;
7736
- if (parent == null) {
7737
- isPropsOnlyUsedInMembers = false;
7738
- break;
7739
- }
7740
- if (parent.type !== "MemberExpression" && parent.type !== "OptionalMemberExpression") {
7741
- isPropsOnlyUsedInMembers = false;
7742
- break;
7743
- }
7744
- }
7745
- 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)}.`;
7746
- }
7747
- if (!extraWarning && missingDependencies.size > 0) {
7748
- let missingCallbackDep = null;
7749
- missingDependencies.forEach((missingDep) => {
7750
- if (missingCallbackDep) return;
7751
- const topScopeRef = componentScope.set.get(missingDep);
7752
- const usedDep = dependencies.get(missingDep);
7753
- if (!usedDep?.references || usedDep?.references[0]?.resolved !== topScopeRef) return;
7754
- const def = topScopeRef?.defs[0];
7755
- if (def == null || def.name == null || def.type !== "Parameter") return;
7756
- let isFunctionCall = false;
7757
- let id;
7758
- for (const reference of usedDep.references) {
7759
- id = reference.identifier;
7760
- if (id != null && id.parent != null && (id.parent.type === "CallExpression" || id.parent.type === "OptionalCallExpression") && id.parent.callee === id) {
7761
- isFunctionCall = true;
7762
- break;
7763
- }
7764
- }
7765
- if (!isFunctionCall) return;
7766
- missingCallbackDep = missingDep;
7767
- });
7768
- if (missingCallbackDep !== null) extraWarning = ` If '${missingCallbackDep}' changes too often, find the parent component that defines it and wrap that definition in useCallback.`;
7769
- }
7770
- if (!extraWarning && missingDependencies.size > 0) {
7771
- let setStateRecommendation = null;
7772
- for (const missingDep of missingDependencies) {
7773
- if (setStateRecommendation !== null) break;
7774
- const references = dependencies.get(missingDep).references;
7775
- let id;
7776
- let maybeCall;
7777
- for (const reference of references) {
7778
- id = reference.identifier;
7779
- maybeCall = id.parent;
7780
- while (maybeCall != null && maybeCall !== componentScope.block) {
7781
- if (maybeCall.type === "CallExpression") {
7782
- const correspondingStateVariable = setStateCallSites.get(maybeCall.callee);
7783
- if (correspondingStateVariable != null) {
7784
- if ("name" in correspondingStateVariable && correspondingStateVariable.name === missingDep) setStateRecommendation = {
7785
- missingDep,
7786
- setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
7787
- form: "updater"
7788
- };
7789
- else if (stateVariables.has(id)) setStateRecommendation = {
7790
- missingDep,
7791
- setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
7792
- form: "reducer"
7793
- };
7794
- else {
7795
- const resolved = reference.resolved;
7796
- if (resolved != null) {
7797
- const def = resolved.defs[0];
7798
- if (def != null && def.type === "Parameter") setStateRecommendation = {
7799
- missingDep,
7800
- setter: "name" in maybeCall.callee ? maybeCall.callee.name : "",
7801
- form: "inlineReducer"
7802
- };
7803
- }
7804
- }
7805
- break;
7806
- }
7807
- }
7808
- maybeCall = maybeCall.parent;
7809
- }
7810
- if (setStateRecommendation !== null) break;
7811
- }
7812
- }
7813
- if (setStateRecommendation !== null) switch (setStateRecommendation.form) {
7814
- case "reducer":
7815
- extraWarning = ` You can also replace multiple useState variables with useReducer if '${setStateRecommendation.setter}' needs the current value of '${setStateRecommendation.missingDep}'.`;
7816
- break;
7817
- case "inlineReducer":
7818
- 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.`;
7819
- break;
7820
- case "updater":
7821
- 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.`;
7822
- break;
7823
- default: throw new Error("Unknown case.");
7824
- }
7825
- }
7826
- reportProblem({
7827
- node: declaredDependenciesNode,
7828
- message: `React Hook ${getSourceCode().getText(reactiveHook)} has ` + (getWarningMessage(missingDependencies, "a", "missing", "include") || getWarningMessage(unnecessaryDependencies, "an", "unnecessary", "exclude") || getWarningMessage(duplicateDependencies, "a", "duplicate", "omit")) + extraWarning,
7829
- suggest: [{
7830
- desc: `Update the dependencies array to be: [${suggestedDeps.map(formatDependency).join(", ")}]`,
7831
- fix(fixer) {
7832
- return fixer.replaceText(declaredDependenciesNode, `[${suggestedDeps.map(formatDependency).join(", ")}]`);
7833
- }
7834
- }]
7835
- });
7836
- }
7837
- function visitCallExpression(node) {
7838
- const configuredHook = getReactiveHookConfig(node, options.hooks);
7839
- const callbackIndex = configuredHook ? configuredHook.closureIndex : getReactiveHookCallbackIndex(node.callee, options);
7840
- if (callbackIndex === -1) return;
7841
- let callback = node.arguments[callbackIndex];
7842
- const reactiveHook = node.callee;
7843
- const nodeWithoutNamespace = getNodeWithoutReactNamespace(reactiveHook);
7844
- const reactiveHookName = configuredHook?.name ?? ("name" in nodeWithoutNamespace ? nodeWithoutNamespace.name : "");
7845
- const dependenciesIndex = configuredHook ? configuredHook.dependenciesIndex : callbackIndex + 1;
7846
- const maybeNode = node.arguments[dependenciesIndex];
7847
- const declaredDependenciesNode = maybeNode && !(maybeNode.type === "Identifier" && maybeNode.name === "undefined") ? maybeNode : void 0;
7848
- const isEffect = /Effect($|[^a-z])/g.test(reactiveHookName);
7849
- if (!callback) {
7850
- if (configuredHook) {
7851
- const builtInCallbackIndex = getReactiveHookCallbackIndex(reactiveHook, { additionalHooks: void 0 });
7852
- const builtInCallback = builtInCallbackIndex === -1 ? null : node.arguments[builtInCallbackIndex];
7853
- if (builtInCallbackIndex === -1 || builtInCallback != null) return;
7854
- }
7855
- reportProblem({
7856
- node: reactiveHook,
7857
- message: `React Hook ${reactiveHookName} requires an effect callback. Did you forget to pass a callback to the hook?`
7858
- });
7859
- return;
7860
- }
7861
- if (!maybeNode && isEffect && options.requireExplicitEffectDeps) reportProblem({
7862
- node: reactiveHook,
7863
- message: `React Hook ${reactiveHookName} always requires dependencies. Please add a dependency array or an explicit \`undefined\``
7864
- });
7865
- const isAutoDepsHook = options.experimental_autoDependenciesHooks.includes(reactiveHookName);
7866
- if ((!declaredDependenciesNode || isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) && !isEffect) {
7867
- if (reactiveHookName === "useMemo" || reactiveHookName === "useCallback") reportProblem({
7868
- node: reactiveHook,
7869
- message: `React Hook ${reactiveHookName} does nothing when called with only one argument. Did you forget to pass an array of dependencies?`
7870
- });
7871
- return;
7872
- }
7873
- while (callback.type === "TSAsExpression" || callback.type === "AsExpression") callback = callback.expression;
7874
- switch (callback.type) {
7875
- case "FunctionExpression":
7876
- case "ArrowFunctionExpression":
7877
- visitFunctionWithDependencies(callback, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
7878
- return;
7879
- case "Identifier":
7880
- if (!declaredDependenciesNode || isAutoDepsHook && declaredDependenciesNode.type === "Literal" && declaredDependenciesNode.value === null) return;
7881
- if ("elements" in declaredDependenciesNode && declaredDependenciesNode.elements && declaredDependenciesNode.elements.some((el) => el && el.type === "Identifier" && el.name === callback.name)) return;
7882
- const variable = getScope(callback).set.get(callback.name);
7883
- if (variable == null || variable.defs == null) return;
7884
- const def = variable.defs[0];
7885
- if (!def || !def.node) break;
7886
- if (def.type === "Parameter") {
7887
- reportProblem({
7888
- node: reactiveHook,
7889
- message: getUnknownDependenciesMessage(reactiveHookName)
7890
- });
7891
- return;
7892
- }
7893
- if (def.type !== "Variable" && def.type !== "FunctionName") break;
7894
- switch (def.node.type) {
7895
- case "FunctionDeclaration":
7896
- visitFunctionWithDependencies(def.node, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
7897
- return;
7898
- case "VariableDeclarator":
7899
- const init = def.node.init;
7900
- if (!init) break;
7901
- switch (init.type) {
7902
- case "ArrowFunctionExpression":
7903
- case "FunctionExpression":
7904
- visitFunctionWithDependencies(init, declaredDependenciesNode, reactiveHook, reactiveHookName, isEffect, isAutoDepsHook, node, dependenciesIndex);
7905
- return;
7906
- }
7907
- }
7908
- break;
7909
- default:
7910
- if (configuredHook) return;
7911
- reportProblem({
7912
- node: reactiveHook,
7913
- message: getUnknownDependenciesMessage(reactiveHookName)
7914
- });
7915
- return;
7916
- }
7917
- reportProblem({
7918
- node: reactiveHook,
7919
- message: `React Hook ${reactiveHookName} has a missing dependency: '${callback.name}'. Either include it or remove the dependency array.`,
7920
- suggest: [{
7921
- desc: `Update the dependencies array to be: [${callback.name}]`,
7922
- fix(fixer) {
7923
- return fixer.replaceText(declaredDependenciesNode, `[${callback.name}]`);
7924
- }
7925
- }]
7926
- });
7927
- }
7928
- return { CallExpression: visitCallExpression };
7929
- }
7930
- };
7931
- function collectRecommendations({ dependencies, declaredDependencies, stableDependencies, externalDependencies, isEffect }) {
7932
- const depTree = createDepTree();
7933
- function createDepTree() {
7934
- return {
7935
- isUsed: false,
7936
- isSatisfiedRecursively: false,
7937
- isSubtreeUsed: false,
7938
- children: /* @__PURE__ */ new Map()
7939
- };
7940
- }
7941
- dependencies.forEach((_, key) => {
7942
- const node = getOrCreateNodeByPath(depTree, key);
7943
- node.isUsed = true;
7944
- markAllParentsByPath(depTree, key, (parent) => {
7945
- parent.isSubtreeUsed = true;
7946
- });
7947
- });
7948
- declaredDependencies.forEach(({ key }) => {
7949
- const node = getOrCreateNodeByPath(depTree, key);
7950
- node.isSatisfiedRecursively = true;
7951
- });
7952
- stableDependencies.forEach((key) => {
7953
- const node = getOrCreateNodeByPath(depTree, key);
7954
- node.isSatisfiedRecursively = true;
7955
- });
7956
- function getOrCreateNodeByPath(rootNode, path) {
7957
- const keys = path.split(".");
7958
- let node = rootNode;
7959
- for (const key of keys) {
7960
- let child = node.children.get(key);
7961
- if (!child) {
7962
- child = createDepTree();
7963
- node.children.set(key, child);
7964
- }
7965
- node = child;
7966
- }
7967
- return node;
7968
- }
7969
- function markAllParentsByPath(rootNode, path, fn) {
7970
- const keys = path.split(".");
7971
- let node = rootNode;
7972
- for (const key of keys) {
7973
- const child = node.children.get(key);
7974
- if (!child) return;
7975
- fn(child);
7976
- node = child;
7977
- }
7978
- }
7979
- const missingDependencies = /* @__PURE__ */ new Set();
7980
- const satisfyingDependencies = /* @__PURE__ */ new Set();
7981
- scanTreeRecursively(depTree, missingDependencies, satisfyingDependencies, (key) => key);
7982
- function scanTreeRecursively(node, missingPaths, satisfyingPaths, keyToPath) {
7983
- node.children.forEach((child, key) => {
7984
- const path = keyToPath(key);
7985
- if (child.isSatisfiedRecursively) {
7986
- if (child.isSubtreeUsed) satisfyingPaths.add(path);
7987
- return;
7988
- }
7989
- if (child.isUsed) {
7990
- missingPaths.add(path);
7991
- return;
7992
- }
7993
- scanTreeRecursively(child, missingPaths, satisfyingPaths, (childKey) => path + "." + childKey);
7994
- });
7995
- }
7996
- const suggestedDependencies = [];
7997
- const unnecessaryDependencies = /* @__PURE__ */ new Set();
7998
- const duplicateDependencies = /* @__PURE__ */ new Set();
7999
- declaredDependencies.forEach(({ key }) => {
8000
- if (satisfyingDependencies.has(key)) {
8001
- if (suggestedDependencies.indexOf(key) === -1) suggestedDependencies.push(key);
8002
- else duplicateDependencies.add(key);
8003
- } else if (isEffect && !key.endsWith(".current") && !externalDependencies.has(key)) {
8004
- if (suggestedDependencies.indexOf(key) === -1) suggestedDependencies.push(key);
8005
- } else unnecessaryDependencies.add(key);
8006
- });
8007
- missingDependencies.forEach((key) => {
8008
- suggestedDependencies.push(key);
8009
- });
8010
- return {
8011
- suggestedDependencies,
8012
- unnecessaryDependencies,
8013
- duplicateDependencies,
8014
- missingDependencies
8015
- };
8016
- }
8017
- function getConstructionExpressionType(node) {
8018
- switch (node.type) {
8019
- case "ObjectExpression": return "object";
8020
- case "ArrayExpression": return "array";
8021
- case "ArrowFunctionExpression":
8022
- case "FunctionExpression": return "function";
8023
- case "ClassExpression": return "class";
8024
- case "ConditionalExpression":
8025
- if (getConstructionExpressionType(node.consequent) != null || getConstructionExpressionType(node.alternate) != null) return "conditional";
8026
- return null;
8027
- case "LogicalExpression":
8028
- if (getConstructionExpressionType(node.left) != null || getConstructionExpressionType(node.right) != null) return "logical expression";
8029
- return null;
8030
- case "JSXFragment": return "JSX fragment";
8031
- case "JSXElement": return "JSX element";
8032
- case "AssignmentExpression":
8033
- if (getConstructionExpressionType(node.right) != null) return "assignment expression";
8034
- return null;
8035
- case "NewExpression": return "object construction";
8036
- case "Literal":
8037
- if (node.value instanceof RegExp) return "regular expression";
8038
- return null;
8039
- case "TypeCastExpression":
8040
- case "AsExpression":
8041
- case "TSAsExpression": return getConstructionExpressionType(node.expression);
8042
- }
8043
- return null;
8044
- }
8045
- function scanForConstructions({ declaredDependencies, declaredDependenciesNode, componentScope, scope }) {
8046
- const constructions = declaredDependencies.map(({ key }) => {
8047
- const ref = componentScope.variables.find((v) => v.name === key);
8048
- if (ref == null) return null;
8049
- const node = ref.defs[0];
8050
- if (node == null) return null;
8051
- if (node.type === "Variable" && node.node.type === "VariableDeclarator" && node.node.id.type === "Identifier" && node.node.init != null) {
8052
- const constantExpressionType = getConstructionExpressionType(node.node.init);
8053
- if (constantExpressionType) return [ref, constantExpressionType];
8054
- }
8055
- if (node.type === "FunctionName" && node.node.type === "FunctionDeclaration") return [ref, "function"];
8056
- if (node.type === "ClassName" && node.node.type === "ClassDeclaration") return [ref, "class"];
8057
- return null;
8058
- }).filter(Boolean);
8059
- function isUsedOutsideOfHook(ref) {
8060
- let foundWriteExpr = false;
8061
- for (const reference of ref.references) {
8062
- if (reference.writeExpr) {
8063
- if (foundWriteExpr) return true;
8064
- else {
8065
- foundWriteExpr = true;
8066
- continue;
8067
- }
8068
- }
8069
- let currentScope = reference.from;
8070
- while (currentScope !== scope && currentScope != null) currentScope = currentScope.upper;
8071
- if (currentScope !== scope) {
8072
- if (!isAncestorNodeOf(declaredDependenciesNode, reference.identifier)) return true;
8073
- }
8074
- }
8075
- return false;
8076
- }
8077
- return constructions.map(([ref, depType]) => ({
8078
- construction: ref.defs[0],
8079
- depType,
8080
- isUsedOutsideOfHook: isUsedOutsideOfHook(ref)
8081
- }));
8082
- }
8083
- function getDependency(node) {
8084
- 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);
8085
- else if (node.type === "MemberExpression" && node.parent && node.parent.type === "AssignmentExpression" && node.parent.left === node) return node.object;
8086
- else return node;
8087
- }
8088
- function markNode(node, optionalChains, result) {
8089
- if (optionalChains) {
8090
- if ("optional" in node && node.optional) {
8091
- if (!optionalChains.has(result)) optionalChains.set(result, true);
8092
- } else optionalChains.set(result, false);
8093
- }
8094
- }
8095
- function analyzePropertyChain(node, optionalChains) {
8096
- if (node.type === "Identifier" || node.type === "JSXIdentifier") {
8097
- const result = node.name;
8098
- if (optionalChains) optionalChains.set(result, false);
8099
- return result;
8100
- } else if (node.type === "MemberExpression" && !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 === "OptionalMemberExpression" && !node.computed) {
8105
- const result = `${analyzePropertyChain(node.object, optionalChains)}.${analyzePropertyChain(node.property, null)}`;
8106
- markNode(node, optionalChains, result);
8107
- return result;
8108
- } else if (node.type === "ChainExpression" && (!("computed" in node) || !node.computed)) {
8109
- const expression = node.expression;
8110
- if (expression.type === "CallExpression") throw new Error(`Unsupported node type: ${expression.type}`);
8111
- const result = `${analyzePropertyChain(expression.object, optionalChains)}.${analyzePropertyChain(expression.property, null)}`;
8112
- markNode(expression, optionalChains, result);
8113
- return result;
8114
- } else throw new Error(`Unsupported node type: ${node.type}`);
8115
- }
8116
- function getNodeWithoutReactNamespace(node) {
8117
- if (node.type === "MemberExpression" && node.object.type === "Identifier" && node.object.name === "React" && node.property.type === "Identifier" && !node.computed) return node.property;
8118
- return node;
8119
- }
8120
- function getReactiveHookCallbackIndex(calleeNode, options) {
8121
- const node = getNodeWithoutReactNamespace(calleeNode);
8122
- if (node.type !== "Identifier") return -1;
8123
- switch (node.name) {
8124
- case "useEffect":
8125
- case "useLayoutEffect":
8126
- case "useCallback":
8127
- case "useMemo": return 0;
8128
- case "useImperativeHandle": return 1;
8129
- default: if (node === calleeNode && options && options.additionalHooks) {
8130
- let name;
8131
- try {
8132
- name = analyzePropertyChain(node, null);
8133
- } catch (error) {
8134
- if (error instanceof Error && /Unsupported node type/.test(error.message)) return 0;
8135
- else throw error;
8136
- }
8137
- if (options.additionalHooks instanceof RegExp) options.additionalHooks.lastIndex = 0;
8138
- return options.additionalHooks.test(name) ? 0 : -1;
8139
- } else return -1;
8140
- }
8141
- }
8142
- function fastFindReferenceWithParent(start, target) {
8143
- const queue = [start];
8144
- let item;
8145
- while (queue.length) {
8146
- item = queue.shift();
8147
- if (isSameIdentifier(item, target)) return item;
8148
- if (!isAncestorNodeOf(item, target)) continue;
8149
- for (const [key, value] of Object.entries(item)) {
8150
- if (key === "parent") continue;
8151
- if (isNodeLike(value)) {
8152
- value.parent = item;
8153
- queue.push(value);
8154
- } else if (Array.isArray(value)) value.forEach((val) => {
8155
- if (isNodeLike(val)) {
8156
- val.parent = item;
8157
- queue.push(val);
8158
- }
8159
- });
8160
- }
8161
- }
8162
- return null;
8163
- }
8164
- function joinEnglish(arr) {
8165
- let s = "";
8166
- for (let i = 0; i < arr.length; i++) {
8167
- s += arr[i];
8168
- if (i === 0 && arr.length === 2) s += " and ";
8169
- else if (i === arr.length - 2 && arr.length > 2) s += ", and ";
8170
- else if (i < arr.length - 1) s += ", ";
8171
- }
8172
- return s;
8173
- }
8174
- function isNodeLike(val) {
8175
- return typeof val === "object" && val !== null && !Array.isArray(val) && "type" in val && typeof val.type === "string";
8176
- }
8177
- function isSameIdentifier(a, b) {
8178
- 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];
8179
- }
8180
- function isAncestorNodeOf(a, b) {
8181
- return !!a.range && !!b.range && a.range[0] <= b.range[0] && a.range[1] >= b.range[1];
8182
- }
8183
- function isUseEffectEventIdentifier(node) {
8184
- return node.type === "Identifier" && node.name === "useEffectEvent";
8185
- }
8186
- function getUnknownDependenciesMessage(reactiveHookName) {
8187
- return `React Hook ${reactiveHookName} received a function whose dependencies are unknown. Pass an inline function instead.`;
8188
- }
8189
- // src/rules/unsupported-syntax/lib.ts
8190
- function isEvalCall(node) {
8191
- const callee = Extract.unwrap(node.callee);
8192
- switch (callee.type) {
8193
- case AST_NODE_TYPES.Identifier: return callee.name === "eval";
8194
- case AST_NODE_TYPES.MemberExpression:
8195
- if (!Check.isIdentifier(Extract.unwrap(callee.object), "globalThis")) return false;
8196
- return !callee.computed && Check.isIdentifier(callee.property, "eval");
8197
- default: return false;
8198
- }
8199
- }
8200
- var unsupported_syntax_default = createRule({
8201
- meta: {
8202
- type: "problem",
8203
- docs: { description: "Validates against syntax that React Compiler does not support." },
8204
- messages: {
8205
- eval: "Do not use 'eval' inside components or hooks. 'eval' cannot be statically analyzed and is not supported by React Compiler.",
8206
- with: "Do not use 'with' statements inside components or hooks. 'with' changes scope dynamically and is not supported by React Compiler."
8207
- },
8208
- schema: []
8209
- },
8210
- name: "unsupported-syntax",
8211
- create: create$2
8212
- });
8213
- function create$2(context) {
8214
- const hc = core.getHookCollector(context);
8215
- const fc = core.getFunctionComponentCollector(context);
8216
- const evalCalls = [];
8217
- const withStmts = [];
8218
- return merge(hc.visitor, fc.visitor, {
8219
- CallExpression(node) {
8220
- if (!isEvalCall(node)) return;
8221
- const func = Traverse.findParent(node, Check.isFunction);
8222
- if (func == null) return;
8223
- evalCalls.push({
8224
- func,
8225
- node
8226
- });
8227
- },
8228
- WithStatement(node) {
8229
- const func = Traverse.findParent(node, Check.isFunction);
8230
- if (func == null) return;
8231
- withStmts.push({
8232
- func,
8233
- node
8234
- });
8235
- },
8236
- "Program:exit"(node) {
8237
- const comps = fc.api.getAllComponents(node);
8238
- const hooks = hc.api.getAllHooks(node);
8239
- const funcs = [...comps, ...hooks];
8240
- for (const { func, node } of evalCalls) {
8241
- if (!funcs.some((f) => f.node === func)) continue;
8242
- context.report({
8243
- messageId: "eval",
8244
- node
8245
- });
7314
+ },
7315
+ WithStatement(node) {
7316
+ const func = Traverse.findParent(node, Check.isFunction);
7317
+ if (func == null) return;
7318
+ withStmts.push({
7319
+ func,
7320
+ node
7321
+ });
7322
+ },
7323
+ "Program:exit"(node) {
7324
+ const comps = fc.api.getAllComponents(node);
7325
+ const hooks = hc.api.getAllHooks(node);
7326
+ const funcs = [...comps, ...hooks];
7327
+ for (const { func, node } of evalCalls) {
7328
+ if (!funcs.some((f) => f.node === func)) continue;
7329
+ context.report({
7330
+ messageId: "eval",
7331
+ node
7332
+ });
8246
7333
  }
8247
7334
  for (const { func, node } of withStmts) {
8248
7335
  if (!funcs.some((f) => f.node === func)) continue;
@@ -8276,12 +7363,12 @@ function createFactCollector(isUseMemoCall) {
8276
7363
  Traverse.simpleTraverse(callback.body, { enter(node) {
8277
7364
  switch (node.type) {
8278
7365
  case AST_NODE_TYPES.AssignmentExpression:
8279
- for (const target of Extract.getAssignmentTargets(node.left)) pushWrite(node, target);
7366
+ for (const target of resolveAssignmentTargets(node.left)) pushWrite(node, target);
8280
7367
  return;
8281
7368
  case AST_NODE_TYPES.ForInStatement:
8282
7369
  case AST_NODE_TYPES.ForOfStatement:
8283
7370
  if (node.left.type === AST_NODE_TYPES.VariableDeclaration) return;
8284
- for (const target of Extract.getAssignmentTargets(node.left)) pushWrite(node, target);
7371
+ for (const target of resolveAssignmentTargets(node.left)) pushWrite(node, target);
8285
7372
  return;
8286
7373
  }
8287
7374
  } });
@@ -8393,48 +7480,43 @@ const LAZY_INIT_ALLOW_LIST = [
8393
7480
  "String",
8394
7481
  "Number"
8395
7482
  ];
8396
- // src/rules/use-state/use-state.ts
8397
- const RULE_NAME = "use-state";
8398
- const defaultOptions = [{
8399
- enforceAssignment: true,
8400
- enforceLazyInitialization: true,
8401
- enforceSetterName: true
8402
- }];
8403
- const schema = [{
8404
- type: "object",
8405
- additionalProperties: false,
8406
- properties: {
8407
- enforceAssignment: {
8408
- type: "boolean",
8409
- description: "Require the useState result to be assigned to a destructured value/setter pair."
8410
- },
8411
- enforceLazyInitialization: {
8412
- type: "boolean",
8413
- description: "Require expensive initializers to be wrapped in a lazy initializer function."
8414
- },
8415
- enforceSetterName: {
8416
- type: "boolean",
8417
- description: "Require the setter name to match the state value name."
8418
- }
8419
- }
8420
- }];
8421
7483
  var use_state_default = createRule({
8422
7484
  meta: {
8423
7485
  type: "suggestion",
8424
- defaultOptions: [...defaultOptions],
7486
+ defaultOptions: [{}],
8425
7487
  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." },
8426
7488
  messages: {
8427
7489
  "invalid-initialization": "To prevent re-computation, consider using lazy initial state for useState calls that involve function calls. Ex: 'useState(() => getValue())'.",
8428
7490
  "invalid-assignment": "useState should be destructured into a value and setter pair, e.g., const [state, setState] = useState(...).",
8429
7491
  "invalid-setter-name": "The setter should be named 'set' followed by the capitalized state variable name, e.g., 'setState' for 'state'."
8430
7492
  },
8431
- schema
7493
+ schema: [{
7494
+ type: "object",
7495
+ additionalProperties: false,
7496
+ properties: {
7497
+ enforceAssignment: {
7498
+ type: "boolean",
7499
+ description: "Require the useState result to be assigned to a destructured value/setter pair."
7500
+ },
7501
+ enforceLazyInitialization: {
7502
+ type: "boolean",
7503
+ description: "Require expensive initializers to be wrapped in a lazy initializer function."
7504
+ },
7505
+ enforceSetterName: {
7506
+ type: "boolean",
7507
+ description: "Require the setter name to match the state value name."
7508
+ }
7509
+ }
7510
+ }]
8432
7511
  },
8433
- name: RULE_NAME,
7512
+ name: "use-state",
8434
7513
  create
8435
7514
  });
8436
7515
  function create(context) {
8437
- const { enforceAssignment, enforceLazyInitialization, enforceSetterName } = complete(context.options[0], defaultOptions[0]);
7516
+ const options = context.options[0] ?? {};
7517
+ const enforceAssignment = options.enforceAssignment ?? true;
7518
+ const enforceLazyInitialization = options.enforceLazyInitialization ?? true;
7519
+ const enforceSetterName = options.enforceSetterName ?? true;
8438
7520
  const { additionalStateHooks } = getSettingsFromContext(context);
8439
7521
  return { CallExpression(node) {
8440
7522
  if (!core.isUseStateLikeCall(node, additionalStateHooks)) return;
@@ -8521,7 +7603,7 @@ const plugin = {
8521
7603
  },
8522
7604
  rules: {
8523
7605
  "error-boundaries": error_boundaries_default,
8524
- "exhaustive-deps": rule$2,
7606
+ "exhaustive-deps": rule$1,
8525
7607
  globals: globals_default,
8526
7608
  immutability: immutability_default,
8527
7609
  "no-access-state-in-setstate": no_access_state_in_setstate_default,
@@ -8566,11 +7648,10 @@ const plugin = {
8566
7648
  "no-use-context": no_use_context_default,
8567
7649
  purity: purity_default,
8568
7650
  refs: refs_default,
8569
- "rules-of-hooks": rule$1,
7651
+ "rules-of-hooks": rule,
8570
7652
  "set-state-in-effect": set_state_in_effect_default,
8571
7653
  "set-state-in-render": set_state_in_render_default,
8572
7654
  "static-components": static_components_default,
8573
- "unstable-exhaustive-deps": rule,
8574
7655
  "unsupported-syntax": unsupported_syntax_default,
8575
7656
  "use-memo": use_memo_default,
8576
7657
  "use-state": use_state_default