@eslint-react/core 2.0.0-next.16 → 2.0.0-next.162

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 (3) hide show
  1. package/dist/index.d.ts +498 -264
  2. package/dist/index.js +1154 -872
  3. package/package.json +14 -14
package/dist/index.js CHANGED
@@ -1,958 +1,1240 @@
1
- import { AST_NODE_TYPES } from '@typescript-eslint/types';
2
- import * as AST14 from '@eslint-react/ast';
3
- import { flip, dual, constFalse, identity, constTrue, _ } from '@eslint-react/eff';
4
- import { RegExp, Selector } from '@eslint-react/kit';
5
- import { coerceSettings, DEFAULT_ESLINT_REACT_SETTINGS, getId } from '@eslint-react/shared';
6
- import * as VAR3 from '@eslint-react/var';
7
- import { isMatching, P, match } from 'ts-pattern';
8
- import birecord from 'birecord';
9
-
10
- // src/component/component-children.ts
1
+ import { AST_NODE_TYPES } from "@typescript-eslint/types";
2
+ import * as AST from "@eslint-react/ast";
3
+ import { constFalse, constTrue, dual, flip, identity, unit } from "@eslint-react/eff";
4
+ import { RegExp, Selector } from "@eslint-react/kit";
5
+ import { DEFAULT_ESLINT_REACT_SETTINGS, coerceSettings, getId } from "@eslint-react/shared";
6
+ import * as VAR from "@eslint-react/var";
7
+ import { P, isMatching, match } from "ts-pattern";
8
+ import birecord from "birecord";
9
+ import { isFalseLiteralType, isTrueLiteralType, isTypeFlagSet } from "ts-api-utils";
10
+ import ts from "typescript";
11
+
12
+ //#region src/utils/is-react-api.ts
11
13
  function isReactAPI(api) {
12
- const func = (context, node) => {
13
- if (node == null) return false;
14
- const getText = (n) => context.sourceCode.getText(n);
15
- const name = AST14.toStringFormat(node, getText);
16
- if (name === api) return true;
17
- if (name.substring(name.indexOf(".") + 1) === api) return true;
18
- return false;
19
- };
20
- return dual(2, func);
14
+ const func = (context, node) => {
15
+ if (node == null) return false;
16
+ const getText = (n) => context.sourceCode.getText(n);
17
+ const name = AST.toStringFormat(node, getText);
18
+ if (name === api) return true;
19
+ if (name.substring(name.indexOf(".") + 1) === api) return true;
20
+ return false;
21
+ };
22
+ return dual(2, func);
21
23
  }
22
24
  function isReactAPICall(api) {
23
- const func = (context, node) => {
24
- if (node == null) return false;
25
- if (node.type !== AST_NODE_TYPES.CallExpression) return false;
26
- return isReactAPI(api)(context, node.callee);
27
- };
28
- return dual(2, func);
29
- }
30
- var isCaptureOwnerStack = isReactAPI("captureOwnerStack");
31
- var isChildrenCount = isReactAPI("Children.count");
32
- var isChildrenForEach = isReactAPI("Children.forEach");
33
- var isChildrenMap = isReactAPI("Children.map");
34
- var isChildrenOnly = isReactAPI("Children.only");
35
- var isChildrenToArray = isReactAPI("Children.toArray");
36
- var isCloneElement = isReactAPI("cloneElement");
37
- var isCreateContext = isReactAPI("createContext");
38
- var isCreateElement = isReactAPI("createElement");
39
- var isCreateRef = isReactAPI("createRef");
40
- var isForwardRef = isReactAPI("forwardRef");
41
- var isMemo = isReactAPI("memo");
42
- var isLazy = isReactAPI("lazy");
43
- var isCaptureOwnerStackCall = isReactAPICall("captureOwnerStack");
44
- var isChildrenCountCall = isReactAPICall("Children.count");
45
- var isChildrenForEachCall = isReactAPICall("Children.forEach");
46
- var isChildrenMapCall = isReactAPICall("Children.map");
47
- var isChildrenOnlyCall = isReactAPICall("Children.only");
48
- var isChildrenToArrayCall = isReactAPICall("Children.toArray");
49
- var isCloneElementCall = isReactAPICall("cloneElement");
50
- var isCreateContextCall = isReactAPICall("createContext");
51
- var isCreateElementCall = isReactAPICall("createElement");
52
- var isCreateRefCall = isReactAPICall("createRef");
53
- var isForwardRefCall = isReactAPICall("forwardRef");
54
- var isMemoCall = isReactAPICall("memo");
55
- var isLazyCall = isReactAPICall("lazy");
56
-
57
- // src/component/component-children.ts
25
+ const func = (context, node) => {
26
+ if (node == null) return false;
27
+ if (node.type !== AST_NODE_TYPES.CallExpression) return false;
28
+ return isReactAPI(api)(context, node.callee);
29
+ };
30
+ return dual(2, func);
31
+ }
32
+ const isCaptureOwnerStack = isReactAPI("captureOwnerStack");
33
+ const isChildrenCount = isReactAPI("Children.count");
34
+ const isChildrenForEach = isReactAPI("Children.forEach");
35
+ const isChildrenMap = isReactAPI("Children.map");
36
+ const isChildrenOnly = isReactAPI("Children.only");
37
+ const isChildrenToArray = isReactAPI("Children.toArray");
38
+ const isCloneElement = isReactAPI("cloneElement");
39
+ const isCreateContext = isReactAPI("createContext");
40
+ const isCreateElement = isReactAPI("createElement");
41
+ const isCreateRef = isReactAPI("createRef");
42
+ const isForwardRef = isReactAPI("forwardRef");
43
+ const isMemo = isReactAPI("memo");
44
+ const isLazy = isReactAPI("lazy");
45
+ const isCaptureOwnerStackCall = isReactAPICall("captureOwnerStack");
46
+ const isChildrenCountCall = isReactAPICall("Children.count");
47
+ const isChildrenForEachCall = isReactAPICall("Children.forEach");
48
+ const isChildrenMapCall = isReactAPICall("Children.map");
49
+ const isChildrenOnlyCall = isReactAPICall("Children.only");
50
+ const isChildrenToArrayCall = isReactAPICall("Children.toArray");
51
+ const isCloneElementCall = isReactAPICall("cloneElement");
52
+ const isCreateContextCall = isReactAPICall("createContext");
53
+ const isCreateElementCall = isReactAPICall("createElement");
54
+ const isCreateRefCall = isReactAPICall("createRef");
55
+ const isForwardRefCall = isReactAPICall("forwardRef");
56
+ const isMemoCall = isReactAPICall("memo");
57
+ const isLazyCall = isReactAPICall("lazy");
58
+
59
+ //#endregion
60
+ //#region src/component/component-children.ts
61
+ /**
62
+ * Determines whether inside `createElement`'s children.
63
+ * @param context The rule context
64
+ * @param node The AST node to check
65
+ * @returns `true` if the node is inside createElement's children
66
+ */
58
67
  function isChildrenOfCreateElement(context, node) {
59
- const parent = node.parent;
60
- if (parent == null || parent.type !== AST_NODE_TYPES.CallExpression) return false;
61
- if (!isCreateElementCall(context, parent)) return false;
62
- return parent.arguments.slice(2).some((arg) => arg === node);
68
+ const parent = node.parent;
69
+ if (parent == null || parent.type !== AST_NODE_TYPES.CallExpression) return false;
70
+ if (!isCreateElementCall(context, parent)) return false;
71
+ return parent.arguments.slice(2).some((arg) => arg === node);
63
72
  }
73
+
74
+ //#endregion
75
+ //#region src/utils/get-instance-id.ts
76
+ /**
77
+ * Gets the identifier node of an instance based on AST node relationships.
78
+ * Used for tracking where hooks or components are being assigned in the code.
79
+ * @param node The current AST node to evaluate
80
+ * @param prev The previous AST node in the traversal (used for context)
81
+ * @internal
82
+ */
64
83
  function getInstanceId(node, prev) {
65
- switch (true) {
66
- case (node.type === AST_NODE_TYPES.VariableDeclarator && node.init === prev):
67
- return node.id;
68
- case (node.type === AST_NODE_TYPES.AssignmentExpression && node.right === prev):
69
- return node.left;
70
- case (node.type === AST_NODE_TYPES.PropertyDefinition && node.value === prev):
71
- return node.key;
72
- case (node.type === AST_NODE_TYPES.BlockStatement || node.type === AST_NODE_TYPES.Program || node.parent === node):
73
- return _;
74
- default:
75
- return getInstanceId(node.parent, node);
76
- }
84
+ switch (true) {
85
+ case node.type === AST_NODE_TYPES.VariableDeclarator && node.init === prev: return node.id;
86
+ case node.type === AST_NODE_TYPES.AssignmentExpression && node.right === prev: return node.left;
87
+ case node.type === AST_NODE_TYPES.PropertyDefinition && node.value === prev: return node.key;
88
+ case node.type === AST_NODE_TYPES.BlockStatement || node.type === AST_NODE_TYPES.Program || node.parent === node: return unit;
89
+ default: return getInstanceId(node.parent, node);
90
+ }
77
91
  }
92
+
93
+ //#endregion
94
+ //#region src/utils/is-from-react.ts
95
+ /**
96
+ * Get the arguments of a require expression
97
+ * @param node The node to match
98
+ * @returns The require expression arguments or undefined if the node is not a require expression
99
+ */
78
100
  function getRequireExpressionArguments(node) {
79
- return match(node).with({ type: AST_NODE_TYPES.CallExpression, arguments: P.select(), callee: { type: AST_NODE_TYPES.Identifier, name: "require" } }, identity).with({ type: AST_NODE_TYPES.MemberExpression, object: P.select() }, getRequireExpressionArguments).otherwise(() => null);
80
- }
101
+ return match(node).with({
102
+ type: AST_NODE_TYPES.CallExpression,
103
+ arguments: P.select(),
104
+ callee: {
105
+ type: AST_NODE_TYPES.Identifier,
106
+ name: "require"
107
+ }
108
+ }, identity).with({
109
+ type: AST_NODE_TYPES.MemberExpression,
110
+ object: P.select()
111
+ }, getRequireExpressionArguments).otherwise(() => null);
112
+ }
113
+ /**
114
+ * Check if an identifier name is initialized from react
115
+ * @param name The top-level identifier's name
116
+ * @param importSource The import source to check against
117
+ * @param initialScope Initial scope to search for the identifier
118
+ * @returns Whether the identifier name is initialized from react
119
+ * @internal
120
+ */
81
121
  function isInitializedFromReact(name, importSource, initialScope) {
82
- if (name.toLowerCase() === "react") return true;
83
- const latestDef = VAR3.findVariable(name, initialScope)?.defs.at(-1);
84
- if (latestDef == null) return false;
85
- const { node, parent } = latestDef;
86
- if (node.type === AST_NODE_TYPES.VariableDeclarator && node.init != null) {
87
- const { init } = node;
88
- if (init.type === AST_NODE_TYPES.MemberExpression && init.object.type === AST_NODE_TYPES.Identifier) {
89
- return isInitializedFromReact(init.object.name, importSource, initialScope);
90
- }
91
- if (init.type === AST_NODE_TYPES.Identifier) {
92
- return isInitializedFromReact(init.name, importSource, initialScope);
93
- }
94
- const args = getRequireExpressionArguments(init);
95
- const arg0 = args?.[0];
96
- if (arg0 == null || !AST14.isLiteral(arg0, "string")) {
97
- return false;
98
- }
99
- return arg0.value === importSource || arg0.value.startsWith(`${importSource}/`);
100
- }
101
- return parent?.type === AST_NODE_TYPES.ImportDeclaration && parent.source.value === importSource;
122
+ if (name.toLowerCase() === "react") return true;
123
+ const latestDef = VAR.findVariable(name, initialScope)?.defs.at(-1);
124
+ if (latestDef == null) return false;
125
+ const { node, parent } = latestDef;
126
+ if (node.type === AST_NODE_TYPES.VariableDeclarator && node.init != null) {
127
+ const { init } = node;
128
+ if (init.type === AST_NODE_TYPES.MemberExpression && init.object.type === AST_NODE_TYPES.Identifier) return isInitializedFromReact(init.object.name, importSource, initialScope);
129
+ if (init.type === AST_NODE_TYPES.Identifier) return isInitializedFromReact(init.name, importSource, initialScope);
130
+ const args = getRequireExpressionArguments(init);
131
+ const arg0 = args?.[0];
132
+ if (arg0 == null || !AST.isLiteral(arg0, "string")) return false;
133
+ return arg0.value === importSource || arg0.value.startsWith(`${importSource}/`);
134
+ }
135
+ return parent?.type === AST_NODE_TYPES.ImportDeclaration && parent.source.value === importSource;
102
136
  }
137
+
138
+ //#endregion
139
+ //#region src/utils/is-instance-id-equal.ts
140
+ /** @internal */
103
141
  function isInstanceIdEqual(context, a, b) {
104
- return AST14.isNodeEqual(a, b) || VAR3.isNodeValueEqual(a, b, [
105
- context.sourceCode.getScope(a),
106
- context.sourceCode.getScope(b)
107
- ]);
108
- }
109
-
110
- // src/hook/hook-name.ts
111
- var REACT_BUILTIN_HOOK_NAMES = [
112
- "use",
113
- "useActionState",
114
- "useCallback",
115
- "useContext",
116
- "useDebugValue",
117
- "useDeferredValue",
118
- "useEffect",
119
- "useFormStatus",
120
- "useId",
121
- "useImperativeHandle",
122
- "useInsertionEffect",
123
- "useLayoutEffect",
124
- "useMemo",
125
- "useOptimistic",
126
- "useReducer",
127
- "useRef",
128
- "useState",
129
- "useSyncExternalStore",
130
- "useTransition"
142
+ return AST.isNodeEqual(a, b) || VAR.isNodeValueEqual(a, b, [context.sourceCode.getScope(a), context.sourceCode.getScope(b)]);
143
+ }
144
+
145
+ //#endregion
146
+ //#region src/hook/hook-name.ts
147
+ const REACT_BUILTIN_HOOK_NAMES = [
148
+ "use",
149
+ "useActionState",
150
+ "useCallback",
151
+ "useContext",
152
+ "useDebugValue",
153
+ "useDeferredValue",
154
+ "useEffect",
155
+ "useFormStatus",
156
+ "useId",
157
+ "useImperativeHandle",
158
+ "useInsertionEffect",
159
+ "useLayoutEffect",
160
+ "useMemo",
161
+ "useOptimistic",
162
+ "useReducer",
163
+ "useRef",
164
+ "useState",
165
+ "useSyncExternalStore",
166
+ "useTransition"
131
167
  ];
168
+ /**
169
+ * Catch all identifiers that begin with "use" followed by an uppercase Latin
170
+ * character to exclude identifiers like "user".
171
+ * @param name The name of the identifier to check.
172
+ * @see https://github.com/facebook/react/blob/1d6c8168db1d82713202e842df3167787ffa00ed/packages/eslint-plugin-react-hooks/src/rules/RulesOfHooks.ts#L16
173
+ */
132
174
  function isReactHookName(name) {
133
- return name === "use" || /^use[A-Z0-9]/.test(name);
175
+ return name === "use" || /^use[A-Z0-9]/.test(name);
134
176
  }
135
177
 
136
- // src/hook/hook-is.ts
178
+ //#endregion
179
+ //#region src/hook/hook-is.ts
180
+ /**
181
+ * Determines if a function node is a React Hook based on its name.
182
+ * @param node The function node to check
183
+ * @returns True if the function is a React Hook, false otherwise
184
+ */
137
185
  function isReactHook(node) {
138
- if (node == null) return false;
139
- const id = AST14.getFunctionId(node);
140
- return id?.name != null && isReactHookName(id.name);
141
- }
186
+ if (node == null) return false;
187
+ const id = AST.getFunctionId(node);
188
+ return id?.name != null && isReactHookName(id.name);
189
+ }
190
+ /**
191
+ * Check if the given node is a React Hook call by its name.
192
+ * @param node The node to check.
193
+ * @returns `true` if the node is a React Hook call, `false` otherwise.
194
+ */
142
195
  function isReactHookCall(node) {
143
- if (node == null) return false;
144
- if (node.type !== AST_NODE_TYPES.CallExpression) {
145
- return false;
146
- }
147
- if (node.callee.type === AST_NODE_TYPES.Identifier) {
148
- return isReactHookName(node.callee.name);
149
- }
150
- if (node.callee.type === AST_NODE_TYPES.MemberExpression) {
151
- return node.callee.property.type === AST_NODE_TYPES.Identifier && isReactHookName(node.callee.property.name);
152
- }
153
- return false;
154
- }
196
+ if (node == null) return false;
197
+ if (node.type !== AST_NODE_TYPES.CallExpression) return false;
198
+ if (node.callee.type === AST_NODE_TYPES.Identifier) return isReactHookName(node.callee.name);
199
+ if (node.callee.type === AST_NODE_TYPES.MemberExpression) return node.callee.property.type === AST_NODE_TYPES.Identifier && isReactHookName(node.callee.property.name);
200
+ return false;
201
+ }
202
+ /**
203
+ * Checks if a node is a call to a specific React hook, with React import validation.
204
+ * Returns a function that accepts a hook name to check against.
205
+ * @param context The rule context
206
+ * @param node The AST node to check
207
+ * @returns A function that takes a hook name and returns boolean
208
+ */
155
209
  function isReactHookCallWithName(context, node) {
156
- if (node == null || node.type !== AST_NODE_TYPES.CallExpression) return constFalse;
157
- const {
158
- importSource = DEFAULT_ESLINT_REACT_SETTINGS.importSource,
159
- skipImportCheck = true
160
- } = coerceSettings(context.settings);
161
- const initialScope = context.sourceCode.getScope(node);
162
- return (name) => {
163
- switch (true) {
164
- case (node.callee.type === AST_NODE_TYPES.Identifier && node.callee.name === name):
165
- return skipImportCheck || isInitializedFromReact(name, importSource, initialScope);
166
- case (node.callee.type === AST_NODE_TYPES.MemberExpression && node.callee.property.type === AST_NODE_TYPES.Identifier && node.callee.property.name === name && "name" in node.callee.object):
167
- return skipImportCheck || isInitializedFromReact(node.callee.object.name, importSource, initialScope);
168
- default:
169
- return false;
170
- }
171
- };
172
- }
210
+ if (node == null || node.type !== AST_NODE_TYPES.CallExpression) return constFalse;
211
+ const { importSource = DEFAULT_ESLINT_REACT_SETTINGS.importSource, skipImportCheck = true } = coerceSettings(context.settings);
212
+ const initialScope = context.sourceCode.getScope(node);
213
+ return (name) => {
214
+ switch (true) {
215
+ case node.callee.type === AST_NODE_TYPES.Identifier && node.callee.name === name: return skipImportCheck || isInitializedFromReact(name, importSource, initialScope);
216
+ case node.callee.type === AST_NODE_TYPES.MemberExpression && node.callee.property.type === AST_NODE_TYPES.Identifier && node.callee.property.name === name && "name" in node.callee.object: return skipImportCheck || isInitializedFromReact(node.callee.object.name, importSource, initialScope);
217
+ default: return false;
218
+ }
219
+ };
220
+ }
221
+ /**
222
+ * Lightweight version of isReactHookCallWithName that doesn't check imports.
223
+ * @param node The AST node to check
224
+ * @returns A function that takes a hook name and returns boolean
225
+ */
173
226
  function isReactHookCallWithNameLoose(node) {
174
- if (node == null || node.type !== AST_NODE_TYPES.CallExpression) return constFalse;
175
- return (name) => {
176
- switch (node.callee.type) {
177
- case AST_NODE_TYPES.Identifier:
178
- return node.callee.name === name;
179
- case AST_NODE_TYPES.MemberExpression:
180
- return node.callee.property.type === AST_NODE_TYPES.Identifier && node.callee.property.name === name;
181
- default:
182
- return false;
183
- }
184
- };
185
- }
227
+ if (node == null || node.type !== AST_NODE_TYPES.CallExpression) return constFalse;
228
+ return (name) => {
229
+ switch (node.callee.type) {
230
+ case AST_NODE_TYPES.Identifier: return node.callee.name === name;
231
+ case AST_NODE_TYPES.MemberExpression: return node.callee.property.type === AST_NODE_TYPES.Identifier && node.callee.property.name === name;
232
+ default: return false;
233
+ }
234
+ };
235
+ }
236
+ /**
237
+ * Checks if a node is a call to a specific React hook or one of its aliases.
238
+ * @param context The rule context
239
+ * @param name The primary hook name to check
240
+ * @param alias Optional array of alias names to also accept
241
+ * @returns Function that checks if a node matches the hook name or aliases
242
+ */
186
243
  function isReactHookCallWithNameAlias(context, name, alias = []) {
187
- const {
188
- importSource = DEFAULT_ESLINT_REACT_SETTINGS.importSource,
189
- skipImportCheck = true
190
- } = coerceSettings(context.settings);
191
- return (node) => {
192
- const initialScope = context.sourceCode.getScope(node);
193
- switch (true) {
194
- case (node.callee.type === AST_NODE_TYPES.Identifier && node.callee.name === name):
195
- return skipImportCheck || isInitializedFromReact(name, importSource, initialScope);
196
- case (node.callee.type === AST_NODE_TYPES.MemberExpression && node.callee.property.type === AST_NODE_TYPES.Identifier && node.callee.property.name === name && "name" in node.callee.object):
197
- return skipImportCheck || isInitializedFromReact(node.callee.object.name, importSource, initialScope);
198
- default:
199
- return alias.some(isReactHookCallWithNameLoose(node));
200
- }
201
- };
202
- }
244
+ const { importSource = DEFAULT_ESLINT_REACT_SETTINGS.importSource, skipImportCheck = true } = coerceSettings(context.settings);
245
+ return (node) => {
246
+ const initialScope = context.sourceCode.getScope(node);
247
+ switch (true) {
248
+ case node.callee.type === AST_NODE_TYPES.Identifier && node.callee.name === name: return skipImportCheck || isInitializedFromReact(name, importSource, initialScope);
249
+ case node.callee.type === AST_NODE_TYPES.MemberExpression && node.callee.property.type === AST_NODE_TYPES.Identifier && node.callee.property.name === name && "name" in node.callee.object: return skipImportCheck || isInitializedFromReact(node.callee.object.name, importSource, initialScope);
250
+ default: return alias.some(isReactHookCallWithNameLoose(node));
251
+ }
252
+ };
253
+ }
254
+ /**
255
+ * Detects useEffect calls and variations (useLayoutEffect, etc.) using regex pattern.
256
+ * @param node The AST node to check
257
+ * @returns True if the node is a useEffect-like call
258
+ */
203
259
  function isUseEffectCallLoose(node) {
204
- if (node == null) return false;
205
- if (node.type !== AST_NODE_TYPES.CallExpression) {
206
- return false;
207
- }
208
- switch (node.callee.type) {
209
- case AST_NODE_TYPES.Identifier:
210
- return /^use\w*Effect$/u.test(node.callee.name);
211
- case AST_NODE_TYPES.MemberExpression:
212
- return node.callee.property.type === AST_NODE_TYPES.Identifier && /^use\w*Effect$/u.test(node.callee.property.name);
213
- default:
214
- return false;
215
- }
216
- }
217
- var isUseCall = flip(isReactHookCallWithName)("use");
218
- var isUseActionStateCall = flip(isReactHookCallWithName)("useActionState");
219
- var isUseCallbackCall = flip(isReactHookCallWithName)("useCallback");
220
- var isUseContextCall = flip(isReactHookCallWithName)("useContext");
221
- var isUseDebugValueCall = flip(isReactHookCallWithName)("useDebugValue");
222
- var isUseDeferredValueCall = flip(isReactHookCallWithName)("useDeferredValue");
223
- var isUseEffectCall = flip(isReactHookCallWithName)("useEffect");
224
- var isUseFormStatusCall = flip(isReactHookCallWithName)("useFormStatus");
225
- var isUseIdCall = flip(isReactHookCallWithName)("useId");
226
- var isUseImperativeHandleCall = flip(isReactHookCallWithName)("useImperativeHandle");
227
- var isUseInsertionEffectCall = flip(isReactHookCallWithName)("useInsertionEffect");
228
- var isUseLayoutEffectCall = flip(isReactHookCallWithName)("useLayoutEffect");
229
- var isUseMemoCall = flip(isReactHookCallWithName)("useMemo");
230
- var isUseOptimisticCall = flip(isReactHookCallWithName)("useOptimistic");
231
- var isUseReducerCall = flip(isReactHookCallWithName)("useReducer");
232
- var isUseRefCall = flip(isReactHookCallWithName)("useRef");
233
- var isUseStateCall = flip(isReactHookCallWithName)("useState");
234
- var isUseSyncExternalStoreCall = flip(isReactHookCallWithName)("useSyncExternalStore");
235
- var isUseTransitionCall = flip(isReactHookCallWithName)("useTransition");
236
-
237
- // src/hook/hook-collector.ts
260
+ if (node == null) return false;
261
+ if (node.type !== AST_NODE_TYPES.CallExpression) return false;
262
+ switch (node.callee.type) {
263
+ case AST_NODE_TYPES.Identifier: return /^use\w*Effect$/u.test(node.callee.name);
264
+ case AST_NODE_TYPES.MemberExpression: return node.callee.property.type === AST_NODE_TYPES.Identifier && /^use\w*Effect$/u.test(node.callee.property.name);
265
+ default: return false;
266
+ }
267
+ }
268
+ const isUseCall = flip(isReactHookCallWithName)("use");
269
+ const isUseActionStateCall = flip(isReactHookCallWithName)("useActionState");
270
+ const isUseCallbackCall = flip(isReactHookCallWithName)("useCallback");
271
+ const isUseContextCall = flip(isReactHookCallWithName)("useContext");
272
+ const isUseDebugValueCall = flip(isReactHookCallWithName)("useDebugValue");
273
+ const isUseDeferredValueCall = flip(isReactHookCallWithName)("useDeferredValue");
274
+ const isUseEffectCall = flip(isReactHookCallWithName)("useEffect");
275
+ const isUseFormStatusCall = flip(isReactHookCallWithName)("useFormStatus");
276
+ const isUseIdCall = flip(isReactHookCallWithName)("useId");
277
+ const isUseImperativeHandleCall = flip(isReactHookCallWithName)("useImperativeHandle");
278
+ const isUseInsertionEffectCall = flip(isReactHookCallWithName)("useInsertionEffect");
279
+ const isUseLayoutEffectCall = flip(isReactHookCallWithName)("useLayoutEffect");
280
+ const isUseMemoCall = flip(isReactHookCallWithName)("useMemo");
281
+ const isUseOptimisticCall = flip(isReactHookCallWithName)("useOptimistic");
282
+ const isUseReducerCall = flip(isReactHookCallWithName)("useReducer");
283
+ const isUseRefCall = flip(isReactHookCallWithName)("useRef");
284
+ const isUseStateCall = flip(isReactHookCallWithName)("useState");
285
+ const isUseSyncExternalStoreCall = flip(isReactHookCallWithName)("useSyncExternalStore");
286
+ const isUseTransitionCall = flip(isReactHookCallWithName)("useTransition");
287
+
288
+ //#endregion
289
+ //#region src/hook/hook-collector.ts
238
290
  function useHookCollector() {
239
- const hooks = /* @__PURE__ */ new Map();
240
- const functionEntries = [];
241
- const onFunctionEnter = (node) => {
242
- const id = AST14.getFunctionId(node);
243
- const key = getId();
244
- const name = id?.name;
245
- if (name != null && isReactHookName(name)) {
246
- functionEntries.push({ key, node, isHook: true });
247
- hooks.set(key, {
248
- id,
249
- key,
250
- kind: "function",
251
- name,
252
- node,
253
- flag: 0n,
254
- hint: 0n,
255
- hookCalls: []
256
- });
257
- return;
258
- }
259
- functionEntries.push({ key, node, isHook: false });
260
- };
261
- const onFunctionExit = () => {
262
- functionEntries.pop();
263
- };
264
- const ctx = {
265
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
266
- getAllHooks(node) {
267
- return hooks;
268
- }
269
- };
270
- const listeners = {
271
- ":function[type]": onFunctionEnter,
272
- ":function[type]:exit": onFunctionExit,
273
- "CallExpression[type]"(node) {
274
- if (!isReactHookCall(node)) {
275
- return;
276
- }
277
- const fEntry = functionEntries.at(-1);
278
- if (fEntry?.key == null) {
279
- return;
280
- }
281
- const hook = hooks.get(fEntry.key);
282
- if (hook == null) {
283
- return;
284
- }
285
- hook.hookCalls.push(node);
286
- }
287
- };
288
- return { ctx, listeners };
291
+ const hooks = /* @__PURE__ */ new Map();
292
+ const functionEntries = [];
293
+ const onFunctionEnter = (node) => {
294
+ const id = AST.getFunctionId(node);
295
+ const key = getId();
296
+ const name = id?.name;
297
+ if (name != null && isReactHookName(name)) {
298
+ functionEntries.push({
299
+ key,
300
+ node,
301
+ isHook: true
302
+ });
303
+ hooks.set(key, {
304
+ id,
305
+ key,
306
+ kind: "function",
307
+ name,
308
+ node,
309
+ flag: 0n,
310
+ hint: 0n,
311
+ hookCalls: []
312
+ });
313
+ return;
314
+ }
315
+ functionEntries.push({
316
+ key,
317
+ node,
318
+ isHook: false
319
+ });
320
+ };
321
+ const onFunctionExit = () => {
322
+ functionEntries.pop();
323
+ };
324
+ const ctx = { getAllHooks(node) {
325
+ return hooks;
326
+ } };
327
+ const listeners = {
328
+ ":function[type]": onFunctionEnter,
329
+ ":function[type]:exit": onFunctionExit,
330
+ "CallExpression[type]"(node) {
331
+ if (!isReactHookCall(node)) return;
332
+ const fEntry = functionEntries.at(-1);
333
+ if (fEntry?.key == null) return;
334
+ const hook = hooks.get(fEntry.key);
335
+ if (hook == null) return;
336
+ hook.hookCalls.push(node);
337
+ }
338
+ };
339
+ return {
340
+ ctx,
341
+ listeners
342
+ };
289
343
  }
344
+
345
+ //#endregion
346
+ //#region src/hook/hook-id.ts
290
347
  function isReactHookId(id) {
291
- switch (id.type) {
292
- case AST_NODE_TYPES.Identifier:
293
- return isReactHookName(id.name);
294
- case AST_NODE_TYPES.MemberExpression:
295
- return "name" in id.property && isReactHookName(id.property.name);
296
- default:
297
- return false;
298
- }
348
+ switch (id.type) {
349
+ case AST_NODE_TYPES.Identifier: return isReactHookName(id.name);
350
+ case AST_NODE_TYPES.MemberExpression: return "name" in id.property && isReactHookName(id.property.name);
351
+ default: return false;
352
+ }
299
353
  }
354
+
355
+ //#endregion
356
+ //#region src/jsx/jsx-stringify.ts
357
+ /**
358
+ * Incomplete but sufficient stringification of JSX nodes for common use cases
359
+ *
360
+ * @param node - JSX node from TypeScript ESTree
361
+ * @returns String representation of the JSX node
362
+ */
300
363
  function stringifyJsx(node) {
301
- switch (node.type) {
302
- case AST_NODE_TYPES.JSXIdentifier:
303
- return node.name;
304
- case AST_NODE_TYPES.JSXNamespacedName:
305
- return `${node.namespace.name}:${node.name.name}`;
306
- case AST_NODE_TYPES.JSXMemberExpression:
307
- return `${stringifyJsx(node.object)}.${stringifyJsx(node.property)}`;
308
- case AST_NODE_TYPES.JSXText:
309
- return node.value;
310
- case AST_NODE_TYPES.JSXOpeningElement:
311
- return `<${stringifyJsx(node.name)}>`;
312
- case AST_NODE_TYPES.JSXClosingElement:
313
- return `</${stringifyJsx(node.name)}>`;
314
- case AST_NODE_TYPES.JSXOpeningFragment:
315
- return "<>";
316
- case AST_NODE_TYPES.JSXClosingFragment:
317
- return "</>";
318
- }
319
- }
320
-
321
- // src/jsx/jsx-attribute-name.ts
364
+ switch (node.type) {
365
+ case AST_NODE_TYPES.JSXIdentifier: return node.name;
366
+ case AST_NODE_TYPES.JSXNamespacedName: return `${node.namespace.name}:${node.name.name}`;
367
+ case AST_NODE_TYPES.JSXMemberExpression: return `${stringifyJsx(node.object)}.${stringifyJsx(node.property)}`;
368
+ case AST_NODE_TYPES.JSXText: return node.value;
369
+ case AST_NODE_TYPES.JSXOpeningElement: return `<${stringifyJsx(node.name)}>`;
370
+ case AST_NODE_TYPES.JSXClosingElement: return `</${stringifyJsx(node.name)}>`;
371
+ case AST_NODE_TYPES.JSXOpeningFragment: return "<>";
372
+ case AST_NODE_TYPES.JSXClosingFragment: return "</>";
373
+ }
374
+ }
375
+
376
+ //#endregion
377
+ //#region src/jsx/jsx-attribute-name.ts
378
+ /**
379
+ * Get the stringified name of a JSX attribute
380
+ * @param context The ESLint rule context
381
+ * @param node The JSX attribute node
382
+ * @returns The name of the attribute
383
+ */
322
384
  function getAttributeName(context, node) {
323
- return stringifyJsx(node.name);
385
+ return stringifyJsx(node.name);
324
386
  }
325
387
 
326
- // src/jsx/jsx-attribute.ts
388
+ //#endregion
389
+ //#region src/jsx/jsx-attribute.ts
390
+ /**
391
+ * Searches for a specific JSX attribute by name in a list of attributes
392
+ * Returns the last matching attribute (rightmost in JSX)
393
+ *
394
+ * @param context - ESLint rule context
395
+ * @param name - The name of the attribute to find
396
+ * @param attributes - Array of JSX attributes to search through
397
+ * @param initialScope - Optional scope for resolving variables
398
+ * @returns The found attribute or undefined
399
+ */
327
400
  function getAttribute(context, name, attributes, initialScope) {
328
- return attributes.findLast((attr) => {
329
- if (attr.type === AST_NODE_TYPES.JSXAttribute) {
330
- return getAttributeName(context, attr) === name;
331
- }
332
- if (initialScope == null) return false;
333
- switch (attr.argument.type) {
334
- case AST_NODE_TYPES.Identifier: {
335
- const variable = VAR3.findVariable(attr.argument.name, initialScope);
336
- const variableNode = VAR3.getVariableInitNode(variable, 0);
337
- if (variableNode?.type === AST_NODE_TYPES.ObjectExpression) {
338
- return VAR3.findPropertyInProperties(name, variableNode.properties, initialScope) != null;
339
- }
340
- return false;
341
- }
342
- case AST_NODE_TYPES.ObjectExpression:
343
- return VAR3.findPropertyInProperties(name, attr.argument.properties, initialScope) != null;
344
- }
345
- return false;
346
- });
401
+ return attributes.findLast((attr) => {
402
+ if (attr.type === AST_NODE_TYPES.JSXAttribute) return getAttributeName(context, attr) === name;
403
+ if (initialScope == null) return false;
404
+ switch (attr.argument.type) {
405
+ case AST_NODE_TYPES.Identifier: {
406
+ const variable = VAR.findVariable(attr.argument.name, initialScope);
407
+ const variableNode = VAR.getVariableDefinitionNode(variable, 0);
408
+ if (variableNode?.type === AST_NODE_TYPES.ObjectExpression) return VAR.findProperty(name, variableNode.properties, initialScope) != null;
409
+ return false;
410
+ }
411
+ case AST_NODE_TYPES.ObjectExpression: return VAR.findProperty(name, attr.argument.properties, initialScope) != null;
412
+ }
413
+ return false;
414
+ });
347
415
  }
416
+
417
+ //#endregion
418
+ //#region src/jsx/jsx-attribute-value.ts
419
+ /**
420
+ * Extracts the value of a JSX attribute by name
421
+ * @param context - ESLint rule context
422
+ * @param node - JSX attribute or spread attribute node
423
+ * @param name - Name of the attribute to extract
424
+ * @returns The extracted attribute value in a structured format
425
+ */
348
426
  function getAttributeValue(context, node, name) {
349
- const initialScope = context.sourceCode.getScope(node);
350
- switch (node.type) {
351
- case AST_NODE_TYPES.JSXAttribute:
352
- if (node.value?.type === AST_NODE_TYPES.Literal) {
353
- return {
354
- kind: "some",
355
- node: node.value,
356
- initialScope,
357
- value: node.value.value
358
- };
359
- }
360
- if (node.value?.type === AST_NODE_TYPES.JSXExpressionContainer) {
361
- return VAR3.toStaticValue({
362
- kind: "lazy",
363
- node: node.value.expression,
364
- initialScope
365
- });
366
- }
367
- return { kind: "none", node, initialScope };
368
- case AST_NODE_TYPES.JSXSpreadAttribute: {
369
- const staticValue = VAR3.toStaticValue({
370
- kind: "lazy",
371
- node: node.argument,
372
- initialScope
373
- });
374
- if (staticValue.kind === "none") {
375
- return staticValue;
376
- }
377
- return match(staticValue.value).with({ [name]: P.select(P.any) }, (value) => ({
378
- kind: "some",
379
- node: node.argument,
380
- initialScope,
381
- value
382
- })).otherwise(() => ({ kind: "none", node, initialScope }));
383
- }
384
- default:
385
- return { kind: "none", node, initialScope };
386
- }
387
- }
388
-
389
- // src/jsx/jsx-detection-hint.ts
390
- var JSXDetectionHint = {
391
- None: 0n,
392
- SkipUndefined: 1n << 0n,
393
- SkipNullLiteral: 1n << 1n,
394
- SkipBooleanLiteral: 1n << 2n,
395
- SkipStringLiteral: 1n << 3n,
396
- SkipNumberLiteral: 1n << 4n,
397
- SkipBigIntLiteral: 1n << 5n,
398
- SkipEmptyArray: 1n << 6n,
399
- SkipCreateElement: 1n << 7n,
400
- StrictArray: 1n << 8n,
401
- StrictLogical: 1n << 9n,
402
- StrictConditional: 1n << 10n
403
- };
404
- var DEFAULT_JSX_DETECTION_HINT = 0n | JSXDetectionHint.SkipUndefined | JSXDetectionHint.SkipBooleanLiteral;
427
+ const initialScope = context.sourceCode.getScope(node);
428
+ switch (node.type) {
429
+ case AST_NODE_TYPES.JSXAttribute:
430
+ if (node.value?.type === AST_NODE_TYPES.Literal) return {
431
+ kind: "some",
432
+ node: node.value,
433
+ initialScope,
434
+ value: node.value.value
435
+ };
436
+ if (node.value?.type === AST_NODE_TYPES.JSXExpressionContainer) return VAR.toStaticValue({
437
+ kind: "lazy",
438
+ node: node.value.expression,
439
+ initialScope
440
+ });
441
+ return {
442
+ kind: "none",
443
+ node,
444
+ initialScope
445
+ };
446
+ case AST_NODE_TYPES.JSXSpreadAttribute: {
447
+ const staticValue = VAR.toStaticValue({
448
+ kind: "lazy",
449
+ node: node.argument,
450
+ initialScope
451
+ });
452
+ if (staticValue.kind === "none") return staticValue;
453
+ return match(staticValue.value).with({ [name]: P.select(P.any) }, (value) => ({
454
+ kind: "some",
455
+ node: node.argument,
456
+ initialScope,
457
+ value
458
+ })).otherwise(() => ({
459
+ kind: "none",
460
+ node,
461
+ initialScope
462
+ }));
463
+ }
464
+ default: return {
465
+ kind: "none",
466
+ node,
467
+ initialScope
468
+ };
469
+ }
470
+ }
405
471
 
406
- // src/jsx/jsx-detection.ts
472
+ //#endregion
473
+ //#region src/jsx/jsx-detection.ts
474
+ /**
475
+ * Flags to control JSX detection behavior:
476
+ * - Skip* flags: Ignore specific node types when detecting JSX
477
+ * - Strict* flags: Enforce stricter rules for container types
478
+ */
479
+ const JSXDetectionHint = {
480
+ None: 0n,
481
+ SkipUndefined: 1n << 0n,
482
+ SkipNullLiteral: 1n << 1n,
483
+ SkipBooleanLiteral: 1n << 2n,
484
+ SkipStringLiteral: 1n << 3n,
485
+ SkipNumberLiteral: 1n << 4n,
486
+ SkipBigIntLiteral: 1n << 5n,
487
+ SkipEmptyArray: 1n << 6n,
488
+ SkipCreateElement: 1n << 7n,
489
+ StrictArray: 1n << 8n,
490
+ StrictLogical: 1n << 9n,
491
+ StrictConditional: 1n << 10n
492
+ };
493
+ /**
494
+ * Default JSX detection configuration
495
+ * Skips undefined and boolean literals (common in React)
496
+ */
497
+ const DEFAULT_JSX_DETECTION_HINT = 0n | JSXDetectionHint.SkipUndefined | JSXDetectionHint.SkipBooleanLiteral;
498
+ /**
499
+ * Checks if a node is a `JSXText` or a `Literal` node
500
+ * @param node The AST node to check
501
+ * @returns `true` if the node is a `JSXText` or a `Literal` node
502
+ */
407
503
  function isJsxText(node) {
408
- if (node == null) return false;
409
- return node.type === AST_NODE_TYPES.JSXText || node.type === AST_NODE_TYPES.Literal;
410
- }
504
+ if (node == null) return false;
505
+ return node.type === AST_NODE_TYPES.JSXText || node.type === AST_NODE_TYPES.Literal;
506
+ }
507
+ /**
508
+ * Determines if a node represents JSX-like content based on heuristics
509
+ * Supports configuration through hint flags to customize detection behavior
510
+ *
511
+ * @param code The source code with scope lookup capability
512
+ * @param code.getScope The function to get the scope of a node
513
+ * @param node The AST node to analyze
514
+ * @param hint The configuration flags to adjust detection behavior
515
+ * @returns boolean Whether the node is considered JSX-like
516
+ */
411
517
  function isJsxLike(code, node, hint = DEFAULT_JSX_DETECTION_HINT) {
412
- if (node == null) return false;
413
- if (AST14.isJSX(node)) return true;
414
- switch (node.type) {
415
- case AST_NODE_TYPES.Literal: {
416
- switch (typeof node.value) {
417
- case "boolean":
418
- return !(hint & JSXDetectionHint.SkipBooleanLiteral);
419
- case "string":
420
- return !(hint & JSXDetectionHint.SkipStringLiteral);
421
- case "number":
422
- return !(hint & JSXDetectionHint.SkipNumberLiteral);
423
- case "bigint":
424
- return !(hint & JSXDetectionHint.SkipBigIntLiteral);
425
- }
426
- if (node.value == null) {
427
- return !(hint & JSXDetectionHint.SkipNullLiteral);
428
- }
429
- return false;
430
- }
431
- case AST_NODE_TYPES.TemplateLiteral: {
432
- return !(hint & JSXDetectionHint.SkipStringLiteral);
433
- }
434
- case AST_NODE_TYPES.ArrayExpression: {
435
- if (hint & JSXDetectionHint.StrictArray) {
436
- return node.elements.every((n) => isJsxLike(code, n, hint));
437
- }
438
- return node.elements.some((n) => isJsxLike(code, n, hint));
439
- }
440
- case AST_NODE_TYPES.LogicalExpression: {
441
- if (hint & JSXDetectionHint.StrictLogical) {
442
- return isJsxLike(code, node.left, hint) && isJsxLike(code, node.right, hint);
443
- }
444
- return isJsxLike(code, node.left, hint) || isJsxLike(code, node.right, hint);
445
- }
446
- case AST_NODE_TYPES.ConditionalExpression: {
447
- let leftHasJSX2 = function(node2) {
448
- if (Array.isArray(node2.consequent)) {
449
- if (node2.consequent.length === 0) {
450
- return !(hint & JSXDetectionHint.SkipEmptyArray);
451
- }
452
- if (hint & JSXDetectionHint.StrictArray) {
453
- return node2.consequent.every((n) => isJsxLike(code, n, hint));
454
- }
455
- return node2.consequent.some((n) => isJsxLike(code, n, hint));
456
- }
457
- return isJsxLike(code, node2.consequent, hint);
458
- }, rightHasJSX2 = function(node2) {
459
- return isJsxLike(code, node2.alternate, hint);
460
- };
461
- if (hint & JSXDetectionHint.StrictConditional) {
462
- return leftHasJSX2(node) && rightHasJSX2(node);
463
- }
464
- return leftHasJSX2(node) || rightHasJSX2(node);
465
- }
466
- case AST_NODE_TYPES.SequenceExpression: {
467
- const exp = node.expressions.at(-1);
468
- return isJsxLike(code, exp, hint);
469
- }
470
- case AST_NODE_TYPES.CallExpression: {
471
- if (hint & JSXDetectionHint.SkipCreateElement) {
472
- return false;
473
- }
474
- switch (node.callee.type) {
475
- case AST_NODE_TYPES.Identifier:
476
- return node.callee.name === "createElement";
477
- case AST_NODE_TYPES.MemberExpression:
478
- return node.callee.property.type === AST_NODE_TYPES.Identifier && node.callee.property.name === "createElement";
479
- }
480
- return false;
481
- }
482
- case AST_NODE_TYPES.Identifier: {
483
- const { name } = node;
484
- if (name === "undefined") {
485
- return !(hint & JSXDetectionHint.SkipUndefined);
486
- }
487
- if (AST14.isJSXTagNameExpression(node)) {
488
- return true;
489
- }
490
- const variable = VAR3.findVariable(name, code.getScope(node));
491
- const variableNode = variable && VAR3.getVariableInitNode(variable, 0);
492
- return !!variableNode && isJsxLike(code, variableNode, hint);
493
- }
494
- }
495
- return false;
518
+ if (node == null) return false;
519
+ if (AST.isJSX(node)) return true;
520
+ switch (node.type) {
521
+ case AST_NODE_TYPES.Literal:
522
+ switch (typeof node.value) {
523
+ case "boolean": return !(hint & JSXDetectionHint.SkipBooleanLiteral);
524
+ case "string": return !(hint & JSXDetectionHint.SkipStringLiteral);
525
+ case "number": return !(hint & JSXDetectionHint.SkipNumberLiteral);
526
+ case "bigint": return !(hint & JSXDetectionHint.SkipBigIntLiteral);
527
+ }
528
+ if (node.value == null) return !(hint & JSXDetectionHint.SkipNullLiteral);
529
+ return false;
530
+ case AST_NODE_TYPES.TemplateLiteral: return !(hint & JSXDetectionHint.SkipStringLiteral);
531
+ case AST_NODE_TYPES.ArrayExpression:
532
+ if (node.elements.length === 0) return !(hint & JSXDetectionHint.SkipEmptyArray);
533
+ if (hint & JSXDetectionHint.StrictArray) return node.elements.every((n) => isJsxLike(code, n, hint));
534
+ return node.elements.some((n) => isJsxLike(code, n, hint));
535
+ case AST_NODE_TYPES.LogicalExpression:
536
+ if (hint & JSXDetectionHint.StrictLogical) return isJsxLike(code, node.left, hint) && isJsxLike(code, node.right, hint);
537
+ return isJsxLike(code, node.left, hint) || isJsxLike(code, node.right, hint);
538
+ case AST_NODE_TYPES.ConditionalExpression: {
539
+ function leftHasJSX(node$1) {
540
+ if (Array.isArray(node$1.consequent)) {
541
+ if (node$1.consequent.length === 0) return !(hint & JSXDetectionHint.SkipEmptyArray);
542
+ if (hint & JSXDetectionHint.StrictArray) return node$1.consequent.every((n) => isJsxLike(code, n, hint));
543
+ return node$1.consequent.some((n) => isJsxLike(code, n, hint));
544
+ }
545
+ return isJsxLike(code, node$1.consequent, hint);
546
+ }
547
+ function rightHasJSX(node$1) {
548
+ return isJsxLike(code, node$1.alternate, hint);
549
+ }
550
+ if (hint & JSXDetectionHint.StrictConditional) return leftHasJSX(node) && rightHasJSX(node);
551
+ return leftHasJSX(node) || rightHasJSX(node);
552
+ }
553
+ case AST_NODE_TYPES.SequenceExpression: {
554
+ const exp = node.expressions.at(-1);
555
+ return isJsxLike(code, exp, hint);
556
+ }
557
+ case AST_NODE_TYPES.CallExpression:
558
+ if (hint & JSXDetectionHint.SkipCreateElement) return false;
559
+ switch (node.callee.type) {
560
+ case AST_NODE_TYPES.Identifier: return node.callee.name === "createElement";
561
+ case AST_NODE_TYPES.MemberExpression: return node.callee.property.type === AST_NODE_TYPES.Identifier && node.callee.property.name === "createElement";
562
+ }
563
+ return false;
564
+ case AST_NODE_TYPES.Identifier: {
565
+ const { name } = node;
566
+ if (name === "undefined") return !(hint & JSXDetectionHint.SkipUndefined);
567
+ if (AST.isJSXTagNameExpression(node)) return true;
568
+ const variable = VAR.findVariable(name, code.getScope(node));
569
+ const variableNode = variable && VAR.getVariableDefinitionNode(variable, 0);
570
+ return !!variableNode && isJsxLike(code, variableNode, hint);
571
+ }
572
+ }
573
+ return false;
496
574
  }
575
+
576
+ //#endregion
577
+ //#region src/jsx/jsx-element-type.ts
578
+ /**
579
+ * Extracts the element type name from a JSX element or fragment
580
+ * For JSX elements, returns the stringified name (e.g., "div", "Button", "React.Fragment")
581
+ * For JSX fragments, returns an empty string
582
+ *
583
+ * @param context - ESLint rule context
584
+ * @param node - JSX element or fragment node
585
+ * @returns String representation of the element type
586
+ */
497
587
  function getElementType(context, node) {
498
- if (node.type === AST_NODE_TYPES.JSXFragment) {
499
- return "";
500
- }
501
- return stringifyJsx(node.openingElement.name);
588
+ if (node.type === AST_NODE_TYPES.JSXFragment) return "";
589
+ return stringifyJsx(node.openingElement.name);
502
590
  }
503
591
 
504
- // src/jsx/jsx-has.ts
505
- function hasAttribute(context, name, attributes, initialScope) {
506
- return getAttribute(context, name, attributes, initialScope) != null;
592
+ //#endregion
593
+ //#region src/jsx/jsx-element-is.ts
594
+ /**
595
+ * Determines if a JSX element is a host element
596
+ * Host elements in React start with lowercase letters (e.g., div, span)
597
+ *
598
+ * @param context - ESLint rule context
599
+ * @param node - AST node to check
600
+ * @returns boolean indicating if the element is a host element
601
+ */
602
+ function isHostElement(context, node) {
603
+ return node.type === AST_NODE_TYPES.JSXElement && node.openingElement.name.type === AST_NODE_TYPES.JSXIdentifier && /^[a-z]/u.test(node.openingElement.name.name);
604
+ }
605
+ /**
606
+ * Determines if a JSX element is a React Fragment
607
+ * Fragments can be imported from React and used like <Fragment> or <React.Fragment>
608
+ *
609
+ * @param context - ESLint rule context
610
+ * @param node - AST node to check
611
+ * @returns boolean indicating if the element is a Fragment with type narrowing
612
+ */
613
+ function isFragmentElement(context, node) {
614
+ if (node.type !== AST_NODE_TYPES.JSXElement) return false;
615
+ return getElementType(context, node).split(".").at(-1) === "Fragment";
507
616
  }
617
+
618
+ //#endregion
619
+ //#region src/jsx/jsx-has.ts
620
+ /**
621
+ * Checks if a JSX element has a specific attribute
622
+ *
623
+ * @param context - ESLint rule context
624
+ * @param name - Name of the attribute to check for
625
+ * @param attributes - List of JSX attributes from opening element
626
+ * @param initialScope - Optional scope for resolving variables in spread attributes
627
+ * @returns boolean indicating whether the attribute exists
628
+ */
629
+ function hasAttribute(context, name, attributes, initialScope) {
630
+ return getAttribute(context, name, attributes, initialScope) != null;
631
+ }
632
+ /**
633
+ * Checks if a JSX element has at least one of the specified attributes
634
+ *
635
+ * @param context - ESLint rule context
636
+ * @param names - Array of attribute names to check for
637
+ * @param attributes - List of JSX attributes from opening element
638
+ * @param initialScope - Optional scope for resolving variables in spread attributes
639
+ * @returns boolean indicating whether any of the attributes exist
640
+ */
508
641
  function hasAnyAttribute(context, names, attributes, initialScope) {
509
- return names.some((n) => hasAttribute(context, n, attributes, initialScope));
510
- }
642
+ return names.some((n) => hasAttribute(context, n, attributes, initialScope));
643
+ }
644
+ /**
645
+ * Checks if a JSX element has all of the specified attributes
646
+ *
647
+ * @param context - ESLint rule context
648
+ * @param names - Array of attribute names to check for
649
+ * @param attributes - List of JSX attributes from opening element
650
+ * @param initialScope - Optional scope for resolving variables in spread attributes
651
+ * @returns boolean indicating whether all of the attributes exist
652
+ */
511
653
  function hasEveryAttribute(context, names, attributes, initialScope) {
512
- return names.every((n) => hasAttribute(context, n, attributes, initialScope));
654
+ return names.every((n) => hasAttribute(context, n, attributes, initialScope));
513
655
  }
656
+
657
+ //#endregion
658
+ //#region src/jsx/jsx-hierarchy.ts
659
+ /**
660
+ * Traverses up the AST to find a parent JSX attribute node that matches a given test
661
+ *
662
+ * @param node - The starting AST node
663
+ * @param test - Optional predicate function to test if the attribute meets criteria
664
+ * Defaults to always returning true (matches any attribute)
665
+ * @returns The first matching JSX attribute node found when traversing upwards, or undefined
666
+ */
514
667
  function findParentAttribute(node, test = constTrue) {
515
- const guard = (node2) => {
516
- return node2.type === AST_NODE_TYPES.JSXAttribute && test(node2);
517
- };
518
- return AST14.findParentNode(node, guard);
668
+ const guard = (node$1) => {
669
+ return node$1.type === AST_NODE_TYPES.JSXAttribute && test(node$1);
670
+ };
671
+ return AST.findParentNode(node, guard);
519
672
  }
520
- function isHostElement(context, node) {
521
- return node.type === AST_NODE_TYPES.JSXElement && node.openingElement.name.type === AST_NODE_TYPES.JSXIdentifier && /^[a-z]/u.test(node.openingElement.name.name);
522
- }
523
- function isKeyedElement(context, node, initialScope) {
524
- return node.type === AST_NODE_TYPES.JSXElement && hasAttribute(context, "key", node.openingElement.attributes, initialScope);
525
- }
526
- function isFragmentElement(context, node, allowJSXFragment = false) {
527
- if (node == null) return false;
528
- if (node.type !== AST_NODE_TYPES.JSXElement && node.type !== AST_NODE_TYPES.JSXFragment) return false;
529
- if (node.type === AST_NODE_TYPES.JSXFragment) return allowJSXFragment;
530
- return getElementType(context, node).split(".").at(-1) === "Fragment";
531
- }
532
-
533
- // src/component/component-detection-hint.ts
534
- var ComponentDetectionHint = {
535
- /**
536
- * 1n << 0n - 1n << 63n are reserved for JSXDetectionHint
537
- */
538
- ...JSXDetectionHint,
539
- /**
540
- * Skip function component created by React.memo
541
- */
542
- SkipMemo: 1n << 64n,
543
- /**
544
- * Skip function component created by React.forwardRef
545
- */
546
- SkipForwardRef: 1n << 65n,
547
- /**
548
- * Skip function component defined as array map argument
549
- */
550
- SkipArrayMapArgument: 1n << 66n,
551
- /**
552
- * Skip function component defined on object method
553
- */
554
- SkipObjectMethod: 1n << 67n,
555
- /**
556
- * Skip function component defined on class method
557
- */
558
- SkipClassMethod: 1n << 68n,
559
- /**
560
- * Skip function component defined on class property
561
- */
562
- SkipClassProperty: 1n << 69n
673
+
674
+ //#endregion
675
+ //#region src/component/component-detection-hint.ts
676
+ /**
677
+ * Hints for component collector
678
+ */
679
+ const ComponentDetectionHint = {
680
+ ...JSXDetectionHint,
681
+ SkipMemo: 1n << 64n,
682
+ SkipForwardRef: 1n << 65n,
683
+ SkipArrayMapArgument: 1n << 66n,
684
+ SkipObjectMethod: 1n << 67n,
685
+ SkipClassMethod: 1n << 68n,
686
+ SkipClassProperty: 1n << 69n
563
687
  };
564
- var DEFAULT_COMPONENT_DETECTION_HINT = 0n | ComponentDetectionHint.SkipBooleanLiteral | ComponentDetectionHint.SkipEmptyArray | ComponentDetectionHint.SkipArrayMapArgument | ComponentDetectionHint.SkipNumberLiteral | ComponentDetectionHint.SkipStringLiteral | ComponentDetectionHint.SkipUndefined | ComponentDetectionHint.StrictArray | ComponentDetectionHint.StrictConditional | ComponentDetectionHint.StrictLogical;
688
+ /**
689
+ * Default component detection hint
690
+ */
691
+ const DEFAULT_COMPONENT_DETECTION_HINT = 0n | ComponentDetectionHint.SkipBooleanLiteral | ComponentDetectionHint.SkipEmptyArray | ComponentDetectionHint.SkipArrayMapArgument | ComponentDetectionHint.SkipNumberLiteral | ComponentDetectionHint.SkipStringLiteral | ComponentDetectionHint.SkipUndefined | ComponentDetectionHint.StrictArray | ComponentDetectionHint.StrictConditional | ComponentDetectionHint.StrictLogical;
692
+
693
+ //#endregion
694
+ //#region src/component/component-is.ts
695
+ /**
696
+ * Check if a node is a React class component
697
+ * @param node The AST node to check
698
+ * @returns `true` if the node is a class component, `false` otherwise
699
+ */
565
700
  function isClassComponent(node) {
566
- if ("superClass" in node && node.superClass != null) {
567
- const re = /^(?:Pure)?Component$/u;
568
- switch (true) {
569
- case node.superClass.type === AST_NODE_TYPES.Identifier:
570
- return re.test(node.superClass.name);
571
- case (node.superClass.type === AST_NODE_TYPES.MemberExpression && node.superClass.property.type === AST_NODE_TYPES.Identifier):
572
- return re.test(node.superClass.property.name);
573
- }
574
- }
575
- return false;
576
- }
701
+ if ("superClass" in node && node.superClass != null) {
702
+ const re = /^(?:Pure)?Component$/u;
703
+ switch (true) {
704
+ case node.superClass.type === AST_NODE_TYPES.Identifier: return re.test(node.superClass.name);
705
+ case node.superClass.type === AST_NODE_TYPES.MemberExpression && node.superClass.property.type === AST_NODE_TYPES.Identifier: return re.test(node.superClass.property.name);
706
+ }
707
+ }
708
+ return false;
709
+ }
710
+ /**
711
+ * Check if a node is a React PureComponent
712
+ * @param node The AST node to check
713
+ * @returns `true` if the node is a pure component, `false` otherwise
714
+ */
577
715
  function isPureComponent(node) {
578
- if ("superClass" in node && node.superClass != null) {
579
- const re = /^PureComponent$/u;
580
- switch (true) {
581
- case node.superClass.type === AST_NODE_TYPES.Identifier:
582
- return re.test(node.superClass.name);
583
- case (node.superClass.type === AST_NODE_TYPES.MemberExpression && node.superClass.property.type === AST_NODE_TYPES.Identifier):
584
- return re.test(node.superClass.property.name);
585
- }
586
- }
587
- return false;
716
+ if ("superClass" in node && node.superClass != null) {
717
+ const re = /^PureComponent$/u;
718
+ switch (true) {
719
+ case node.superClass.type === AST_NODE_TYPES.Identifier: return re.test(node.superClass.name);
720
+ case node.superClass.type === AST_NODE_TYPES.MemberExpression && node.superClass.property.type === AST_NODE_TYPES.Identifier: return re.test(node.superClass.property.name);
721
+ }
722
+ }
723
+ return false;
588
724
  }
725
+
726
+ //#endregion
727
+ //#region src/component/component-render-method.ts
728
+ /**
729
+ * Check whether given node is a render method of a class component
730
+ * @example
731
+ * ```tsx
732
+ * class Component extends React.Component {
733
+ * renderHeader = () => <div />;
734
+ * renderFooter = () => <div />;
735
+ * }
736
+ * ```
737
+ * @param node The AST node to check
738
+ * @returns `true` if node is a render function, `false` if not
739
+ */
589
740
  function isRenderMethodLike(node) {
590
- return AST14.isMethodOrProperty(node) && node.key.type === AST_NODE_TYPES.Identifier && node.key.name.startsWith("render") && node.parent.parent.type === AST_NODE_TYPES.ClassDeclaration;
741
+ return AST.isMethodOrProperty(node) && node.key.type === AST_NODE_TYPES.Identifier && node.key.name.startsWith("render") && node.parent.parent.type === AST_NODE_TYPES.ClassDeclaration;
591
742
  }
592
743
 
593
- // src/component/component-definition.ts
594
- var isFunctionOfClassMethod = isMatching({
595
- type: P.union(AST_NODE_TYPES.ArrowFunctionExpression, AST_NODE_TYPES.FunctionExpression),
596
- parent: AST_NODE_TYPES.MethodDefinition
597
- });
598
- var isFunctionOfClassProperty = isMatching({
599
- type: P.union(AST_NODE_TYPES.ArrowFunctionExpression, AST_NODE_TYPES.FunctionExpression),
600
- parent: AST_NODE_TYPES.Property
601
- });
602
- var isFunctionOfObjectMethod = isMatching({
603
- type: P.union(AST_NODE_TYPES.ArrowFunctionExpression, AST_NODE_TYPES.FunctionExpression),
604
- parent: {
605
- type: AST_NODE_TYPES.Property,
606
- parent: {
607
- type: AST_NODE_TYPES.ObjectExpression
608
- }
609
- }
610
- });
744
+ //#endregion
745
+ //#region src/component/component-definition.ts
746
+ /**
747
+ * Function pattern matchers for different contexts
748
+ */
749
+ const functionPatterns = {
750
+ classMethod: {
751
+ type: P.union(AST_NODE_TYPES.ArrowFunctionExpression, AST_NODE_TYPES.FunctionExpression),
752
+ parent: AST_NODE_TYPES.MethodDefinition
753
+ },
754
+ classProperty: {
755
+ type: P.union(AST_NODE_TYPES.ArrowFunctionExpression, AST_NODE_TYPES.FunctionExpression),
756
+ parent: AST_NODE_TYPES.Property
757
+ },
758
+ objectMethod: {
759
+ type: P.union(AST_NODE_TYPES.ArrowFunctionExpression, AST_NODE_TYPES.FunctionExpression),
760
+ parent: {
761
+ type: AST_NODE_TYPES.Property,
762
+ parent: { type: AST_NODE_TYPES.ObjectExpression }
763
+ }
764
+ }
765
+ };
766
+ /**
767
+ * Check whether given node is a function of a render method of a class component
768
+ * @example
769
+ * ```tsx
770
+ * class Component extends React.Component {
771
+ * renderHeader = () => <div />;
772
+ * renderFooter = () => <div />;
773
+ * }
774
+ * ```
775
+ * @param node The AST node to check
776
+ * @returns `true` if node is a render function, `false` if not
777
+ */
611
778
  function isFunctionOfRenderMethod(node) {
612
- if (!isRenderMethodLike(node.parent)) {
613
- return false;
614
- }
615
- return isClassComponent(node.parent.parent.parent);
616
- }
617
- function isValidComponentDefinition(context, node, hint) {
618
- if (isChildrenOfCreateElement(context, node) || isFunctionOfRenderMethod(node)) {
619
- return false;
620
- }
621
- if (hint & ComponentDetectionHint.SkipObjectMethod && isFunctionOfObjectMethod(node.parent)) {
622
- return false;
623
- }
624
- if (hint & ComponentDetectionHint.SkipClassMethod && isFunctionOfClassMethod(node.parent)) {
625
- return false;
626
- }
627
- if (hint & ComponentDetectionHint.SkipClassProperty && isFunctionOfClassProperty(node.parent)) {
628
- return false;
629
- }
630
- if (hint & ComponentDetectionHint.SkipArrayMapArgument && AST14.isArrayMapCall(node.parent)) {
631
- return false;
632
- }
633
- const significantParent = AST14.findParentNode(
634
- node,
635
- AST14.isOneOf([
636
- AST_NODE_TYPES.JSXExpressionContainer,
637
- AST_NODE_TYPES.ArrowFunctionExpression,
638
- AST_NODE_TYPES.FunctionExpression,
639
- AST_NODE_TYPES.Property,
640
- AST_NODE_TYPES.ClassBody
641
- ])
642
- );
643
- return significantParent == null || significantParent.type !== AST_NODE_TYPES.JSXExpressionContainer;
779
+ return isRenderMethodLike(node.parent) && isClassComponent(node.parent.parent.parent);
780
+ }
781
+ /**
782
+ * Checks if a function node should be excluded based on detection hints
783
+ * @param node The function node to check
784
+ * @param hint Component detection hints as bit flags
785
+ * @returns `true` if the function should be excluded, `false` otherwise
786
+ */
787
+ function shouldExcludeBasedOnHint(node, hint) {
788
+ if (hint & ComponentDetectionHint.SkipObjectMethod && isMatching(functionPatterns.objectMethod)(node)) return true;
789
+ if (hint & ComponentDetectionHint.SkipClassMethod && isMatching(functionPatterns.classMethod)(node)) return true;
790
+ if (hint & ComponentDetectionHint.SkipClassProperty && isMatching(functionPatterns.classProperty)(node)) return true;
791
+ if (hint & ComponentDetectionHint.SkipArrayMapArgument && AST.isArrayMapCall(node.parent)) return true;
792
+ return false;
793
+ }
794
+ /**
795
+ * Determines if a function node represents a valid React component definition
796
+ * @param context The rule context
797
+ * @param node The function node to check
798
+ * @param hint Component detection hints as bit flags
799
+ * @returns `true` if the node is a valid component definition, `false` otherwise
800
+ */
801
+ function isComponentDefinition(context, node, hint) {
802
+ if (isChildrenOfCreateElement(context, node) || isFunctionOfRenderMethod(node)) return false;
803
+ if (shouldExcludeBasedOnHint(node, hint)) return false;
804
+ const significantParent = AST.findParentNode(node, AST.isOneOf([
805
+ AST_NODE_TYPES.JSXExpressionContainer,
806
+ AST_NODE_TYPES.ArrowFunctionExpression,
807
+ AST_NODE_TYPES.FunctionExpression,
808
+ AST_NODE_TYPES.Property,
809
+ AST_NODE_TYPES.ClassBody
810
+ ]));
811
+ return significantParent == null || significantParent.type !== AST_NODE_TYPES.JSXExpressionContainer;
644
812
  }
813
+
814
+ //#endregion
815
+ //#region src/component/component-wrapper.ts
816
+ /**
817
+ * Check if the node is a call expression for a component wrapper
818
+ * @param context The ESLint rule context
819
+ * @param node The node to check
820
+ * @returns `true` if the node is a call expression for a component wrapper
821
+ */
645
822
  function isComponentWrapperCall(context, node) {
646
- if (node.type !== AST_NODE_TYPES.CallExpression) return false;
647
- return isMemoCall(context, node) || isForwardRefCall(context, node);
648
- }
823
+ if (node.type !== AST_NODE_TYPES.CallExpression) return false;
824
+ return isMemoCall(context, node) || isForwardRefCall(context, node);
825
+ }
826
+ /**
827
+ * Check if the node is a call expression for a component wrapper loosely
828
+ * @param context The ESLint rule context
829
+ * @param node The node to check
830
+ * @returns `true` if the node is a call expression for a component wrapper loosely
831
+ */
649
832
  function isComponentWrapperCallLoose(context, node) {
650
- if (node.type !== AST_NODE_TYPES.CallExpression) return false;
651
- return isComponentWrapperCall(context, node) || isUseCallbackCall(context, node);
833
+ if (node.type !== AST_NODE_TYPES.CallExpression) return false;
834
+ return isComponentWrapperCall(context, node) || isUseCallbackCall(context, node);
652
835
  }
653
836
 
654
- // src/component/component-id.ts
837
+ //#endregion
838
+ //#region src/component/component-id.ts
655
839
  function getFunctionComponentId(context, node) {
656
- const functionId = AST14.getFunctionId(node);
657
- if (functionId != null) {
658
- return functionId;
659
- }
660
- const { parent } = node;
661
- if (parent.type === AST_NODE_TYPES.CallExpression && isComponentWrapperCallLoose(context, parent) && parent.parent.type === AST_NODE_TYPES.VariableDeclarator && parent.parent.id.type === AST_NODE_TYPES.Identifier) {
662
- return parent.parent.id;
663
- }
664
- if (parent.type === AST_NODE_TYPES.CallExpression && isComponentWrapperCallLoose(context, parent) && parent.parent.type === AST_NODE_TYPES.CallExpression && isComponentWrapperCallLoose(context, parent.parent) && parent.parent.parent.type === AST_NODE_TYPES.VariableDeclarator && parent.parent.parent.id.type === AST_NODE_TYPES.Identifier) {
665
- return parent.parent.parent.id;
666
- }
667
- return _;
668
- }
669
-
670
- // src/component/component-flag.ts
671
- var ComponentFlag = {
672
- None: 0n,
673
- PureComponent: 1n << 0n,
674
- CreateElement: 1n << 1n,
675
- Memo: 1n << 2n,
676
- ForwardRef: 1n << 3n,
677
- Async: 1n << 4n
840
+ const functionId = AST.getFunctionId(node);
841
+ if (functionId != null) return functionId;
842
+ const { parent } = node;
843
+ if (parent.type === AST_NODE_TYPES.CallExpression && isComponentWrapperCallLoose(context, parent) && parent.parent.type === AST_NODE_TYPES.VariableDeclarator && parent.parent.id.type === AST_NODE_TYPES.Identifier) return parent.parent.id;
844
+ if (parent.type === AST_NODE_TYPES.CallExpression && isComponentWrapperCallLoose(context, parent) && parent.parent.type === AST_NODE_TYPES.CallExpression && isComponentWrapperCallLoose(context, parent.parent) && parent.parent.parent.type === AST_NODE_TYPES.VariableDeclarator && parent.parent.parent.id.type === AST_NODE_TYPES.Identifier) return parent.parent.parent.id;
845
+ return unit;
846
+ }
847
+
848
+ //#endregion
849
+ //#region src/component/component-flag.ts
850
+ const ComponentFlag = {
851
+ None: 0n,
852
+ PureComponent: 1n << 0n,
853
+ CreateElement: 1n << 1n,
854
+ Memo: 1n << 2n,
855
+ ForwardRef: 1n << 3n,
856
+ Async: 1n << 4n
678
857
  };
679
858
 
680
- // src/component/component-init-path.ts
859
+ //#endregion
860
+ //#region src/component/component-init-path.ts
681
861
  function getComponentFlagFromInitPath(initPath) {
682
- let flag = ComponentFlag.None;
683
- if (initPath != null && AST14.hasCallInFunctionInitPath("memo", initPath)) {
684
- flag |= ComponentFlag.Memo;
685
- }
686
- if (initPath != null && AST14.hasCallInFunctionInitPath("forwardRef", initPath)) {
687
- flag |= ComponentFlag.ForwardRef;
688
- }
689
- return flag;
862
+ let flag = ComponentFlag.None;
863
+ if (initPath != null && AST.hasCallInFunctionInitPath("memo", initPath)) flag |= ComponentFlag.Memo;
864
+ if (initPath != null && AST.hasCallInFunctionInitPath("forwardRef", initPath)) flag |= ComponentFlag.ForwardRef;
865
+ return flag;
690
866
  }
867
+
868
+ //#endregion
869
+ //#region src/component/component-name.ts
691
870
  function isComponentName(name) {
692
- return RegExp.COMPONENT_NAME.test(name);
871
+ return RegExp.COMPONENT_NAME.test(name);
693
872
  }
694
873
  function isComponentNameLoose(name) {
695
- return RegExp.COMPONENT_NAME_LOOSE.test(name);
874
+ return RegExp.COMPONENT_NAME_LOOSE.test(name);
696
875
  }
697
876
  function getComponentNameFromId(id) {
698
- if (id == null) return _;
699
- return Array.isArray(id) ? id.map((n) => n.name).join(".") : id.name;
877
+ if (id == null) return unit;
878
+ return Array.isArray(id) ? id.map((n) => n.name).join(".") : id.name;
700
879
  }
701
880
  function hasNoneOrLooseComponentName(context, fn) {
702
- const id = getFunctionComponentId(context, fn);
703
- if (id == null) return true;
704
- const name = Array.isArray(id) ? id.at(-1)?.name : id.name;
705
- return name != null && isComponentNameLoose(name);
881
+ const id = getFunctionComponentId(context, fn);
882
+ if (id == null) return true;
883
+ const name = Array.isArray(id) ? id.at(-1)?.name : id.name;
884
+ return name != null && isComponentNameLoose(name);
706
885
  }
707
886
 
708
- // src/component/component-collector.ts
887
+ //#endregion
888
+ //#region src/component/component-collector.ts
889
+ /**
890
+ * Get a ctx and listeners for the rule to collect function components
891
+ * @param context The ESLint rule context
892
+ * @param options The options to use
893
+ * @returns The component collector
894
+ */
709
895
  function useComponentCollector(context, options = {}) {
710
- const {
711
- collectDisplayName = false,
712
- collectHookCalls = false,
713
- hint = DEFAULT_COMPONENT_DETECTION_HINT
714
- } = options;
715
- const components = /* @__PURE__ */ new Map();
716
- const functionEntries = [];
717
- const getCurrentEntry = () => functionEntries.at(-1);
718
- const onFunctionEnter = (node) => {
719
- const key = getId();
720
- functionEntries.push({ key, node, hookCalls: [], isComponent: false });
721
- };
722
- const onFunctionExit = () => {
723
- const entry = functionEntries.at(-1);
724
- if (entry == null) return;
725
- if (!entry.isComponent) return functionEntries.pop();
726
- const shouldDrop = AST14.getNestedReturnStatements(entry.node.body).slice().reverse().some((r) => {
727
- return context.sourceCode.getScope(r).block === entry.node && r.argument != null && !isJsxLike(context.sourceCode, r.argument, hint);
728
- });
729
- if (shouldDrop) {
730
- components.delete(entry.key);
731
- }
732
- return functionEntries.pop();
733
- };
734
- const ctx = {
735
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
736
- getAllComponents(node) {
737
- return components;
738
- },
739
- getCurrentEntries() {
740
- return [...functionEntries];
741
- },
742
- getCurrentEntry
743
- };
744
- const listeners = {
745
- ":function[type]": onFunctionEnter,
746
- ":function[type]:exit": onFunctionExit,
747
- "ArrowFunctionExpression[body.type!='BlockStatement']"() {
748
- const entry = getCurrentEntry();
749
- if (entry == null) return;
750
- const { body } = entry.node;
751
- const isComponent = hasNoneOrLooseComponentName(context, entry.node) && isJsxLike(context.sourceCode, body, hint) && isValidComponentDefinition(context, entry.node, hint);
752
- if (!isComponent) return;
753
- const initPath = AST14.getFunctionInitPath(entry.node);
754
- const id = getFunctionComponentId(context, entry.node);
755
- const name = getComponentNameFromId(id);
756
- const key = getId();
757
- components.set(key, {
758
- id,
759
- key,
760
- kind: "function",
761
- name,
762
- node: entry.node,
763
- displayName: _,
764
- flag: getComponentFlagFromInitPath(initPath),
765
- hint,
766
- hookCalls: entry.hookCalls,
767
- initPath
768
- });
769
- },
770
- ...collectDisplayName ? {
771
- [Selector.DISPLAY_NAME_ASSIGNMENT_EXPRESSION](node) {
772
- const { left, right } = node;
773
- if (left.type !== AST_NODE_TYPES.MemberExpression) return;
774
- const componentName = left.object.type === AST_NODE_TYPES.Identifier ? left.object.name : _;
775
- const component = [...components.values()].findLast(({ name }) => name != null && name === componentName);
776
- if (component == null) return;
777
- component.displayName = right;
778
- }
779
- } : {},
780
- ...collectHookCalls ? {
781
- "CallExpression[type]:exit"(node) {
782
- if (!isReactHookCall(node)) return;
783
- const entry = getCurrentEntry();
784
- if (entry == null) return;
785
- entry.hookCalls.push(node);
786
- }
787
- } : {},
788
- "ReturnStatement[type]"(node) {
789
- const entry = getCurrentEntry();
790
- if (entry == null) return;
791
- const isComponent = hasNoneOrLooseComponentName(context, entry.node) && isJsxLike(context.sourceCode, node.argument, hint) && isValidComponentDefinition(context, entry.node, hint);
792
- if (!isComponent) return;
793
- entry.isComponent = true;
794
- const initPath = AST14.getFunctionInitPath(entry.node);
795
- const id = getFunctionComponentId(context, entry.node);
796
- const name = getComponentNameFromId(id);
797
- components.set(entry.key, {
798
- id,
799
- key: entry.key,
800
- kind: "function",
801
- name,
802
- node: entry.node,
803
- displayName: _,
804
- flag: getComponentFlagFromInitPath(initPath),
805
- hint,
806
- hookCalls: entry.hookCalls,
807
- initPath
808
- });
809
- }
810
- };
811
- return { ctx, listeners };
896
+ const { collectDisplayName = false, collectHookCalls = false, hint = DEFAULT_COMPONENT_DETECTION_HINT } = options;
897
+ const components = /* @__PURE__ */ new Map();
898
+ const functionEntries = [];
899
+ const getCurrentEntry = () => functionEntries.at(-1);
900
+ const onFunctionEnter = (node) => {
901
+ const key = getId();
902
+ functionEntries.push({
903
+ key,
904
+ node,
905
+ hookCalls: [],
906
+ isComponent: false
907
+ });
908
+ };
909
+ const onFunctionExit = () => {
910
+ const entry = functionEntries.at(-1);
911
+ if (entry == null) return;
912
+ if (!entry.isComponent) return functionEntries.pop();
913
+ const rets = AST.getNestedReturnStatements(entry.node.body);
914
+ for (let i = rets.length - 1; i >= 0; i--) {
915
+ const ret = rets[i];
916
+ if (ret == null) continue;
917
+ const shouldDrop = context.sourceCode.getScope(ret).block === entry.node && ret.argument != null && !isJsxLike(context.sourceCode, ret.argument, hint);
918
+ if (shouldDrop) {
919
+ components.delete(entry.key);
920
+ break;
921
+ }
922
+ }
923
+ return functionEntries.pop();
924
+ };
925
+ const ctx = {
926
+ getAllComponents(node) {
927
+ return components;
928
+ },
929
+ getCurrentEntries() {
930
+ return [...functionEntries];
931
+ },
932
+ getCurrentEntry
933
+ };
934
+ const listeners = {
935
+ ":function[type]": onFunctionEnter,
936
+ ":function[type]:exit": onFunctionExit,
937
+ "ArrowFunctionExpression[body.type!='BlockStatement']"() {
938
+ const entry = getCurrentEntry();
939
+ if (entry == null) return;
940
+ const { body } = entry.node;
941
+ const isComponent = hasNoneOrLooseComponentName(context, entry.node) && isJsxLike(context.sourceCode, body, hint) && isComponentDefinition(context, entry.node, hint);
942
+ if (!isComponent) return;
943
+ const initPath = AST.getFunctionInitPath(entry.node);
944
+ const id = getFunctionComponentId(context, entry.node);
945
+ const name = getComponentNameFromId(id);
946
+ const key = getId();
947
+ components.set(key, {
948
+ id,
949
+ key,
950
+ kind: "function",
951
+ name,
952
+ node: entry.node,
953
+ displayName: unit,
954
+ flag: getComponentFlagFromInitPath(initPath),
955
+ hint,
956
+ hookCalls: entry.hookCalls,
957
+ initPath
958
+ });
959
+ },
960
+ ...collectDisplayName ? { [Selector.DISPLAY_NAME_ASSIGNMENT_EXPRESSION](node) {
961
+ const { left, right } = node;
962
+ if (left.type !== AST_NODE_TYPES.MemberExpression) return;
963
+ const componentName = left.object.type === AST_NODE_TYPES.Identifier ? left.object.name : unit;
964
+ const component = [...components.values()].findLast(({ name }) => name != null && name === componentName);
965
+ if (component == null) return;
966
+ component.displayName = right;
967
+ } } : {},
968
+ ...collectHookCalls ? { "CallExpression[type]:exit"(node) {
969
+ if (!isReactHookCall(node)) return;
970
+ const entry = getCurrentEntry();
971
+ if (entry == null) return;
972
+ entry.hookCalls.push(node);
973
+ } } : {},
974
+ "ReturnStatement[type]"(node) {
975
+ const entry = getCurrentEntry();
976
+ if (entry == null) return;
977
+ const isComponent = hasNoneOrLooseComponentName(context, entry.node) && isJsxLike(context.sourceCode, node.argument, hint) && isComponentDefinition(context, entry.node, hint);
978
+ if (!isComponent) return;
979
+ entry.isComponent = true;
980
+ const initPath = AST.getFunctionInitPath(entry.node);
981
+ const id = getFunctionComponentId(context, entry.node);
982
+ const name = getComponentNameFromId(id);
983
+ components.set(entry.key, {
984
+ id,
985
+ key: entry.key,
986
+ kind: "function",
987
+ name,
988
+ node: entry.node,
989
+ displayName: unit,
990
+ flag: getComponentFlagFromInitPath(initPath),
991
+ hint,
992
+ hookCalls: entry.hookCalls,
993
+ initPath
994
+ });
995
+ }
996
+ };
997
+ return {
998
+ ctx,
999
+ listeners
1000
+ };
812
1001
  }
1002
+
1003
+ //#endregion
1004
+ //#region src/component/component-collector-legacy.ts
1005
+ /**
1006
+ * Get a ctx and listeners object for the rule to collect class components
1007
+ * @returns The context and listeners for the rule
1008
+ */
813
1009
  function useComponentCollectorLegacy() {
814
- const components = /* @__PURE__ */ new Map();
815
- const ctx = {
816
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
817
- getAllComponents(node) {
818
- return components;
819
- }
820
- };
821
- const collect = (node) => {
822
- if (!isClassComponent(node)) {
823
- return;
824
- }
825
- const id = AST14.getClassId(node);
826
- const key = getId();
827
- const flag = isPureComponent(node) ? ComponentFlag.PureComponent : ComponentFlag.None;
828
- components.set(
829
- key,
830
- {
831
- id,
832
- key,
833
- kind: "class",
834
- name: id?.name,
835
- node,
836
- // TODO: Get displayName of class component
837
- displayName: _,
838
- flag,
839
- hint: 0n,
840
- // TODO: Get methods of class component
841
- methods: []
842
- }
843
- );
844
- };
845
- const listeners = {
846
- "ClassDeclaration[type]": collect,
847
- "ClassExpression[type]": collect
848
- };
849
- return { ctx, listeners };
850
- }
851
- function isComponentDidCatch(node) {
852
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "componentDidCatch";
853
- }
854
- function isComponentDidMount(node) {
855
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "componentDidMount";
856
- }
857
- function isComponentDidUpdate(node) {
858
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "componentDidUpdate";
859
- }
860
- function isComponentWillMount(node) {
861
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "componentWillMount";
862
- }
863
- function isComponentWillReceiveProps(node) {
864
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "componentWillReceiveProps";
865
- }
866
- function isComponentWillUnmount(node) {
867
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "componentWillUnmount";
868
- }
869
- function isComponentWillUpdate(node) {
870
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "componentWillUpdate";
871
- }
872
- function isGetChildContext(node) {
873
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "getChildContext";
874
- }
875
- function isGetDefaultProps(node) {
876
- return AST14.isMethodOrProperty(node) && node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "getDefaultProps";
877
- }
878
- function isGetInitialState(node) {
879
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "getInitialState";
880
- }
881
- function isGetSnapshotBeforeUpdate(node) {
882
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "getSnapshotBeforeUpdate";
883
- }
884
- function isShouldComponentUpdate(node) {
885
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "shouldComponentUpdate";
886
- }
887
- function isUnsafeComponentWillMount(node) {
888
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "UNSAFE_componentWillMount";
889
- }
890
- function isUnsafeComponentWillReceiveProps(node) {
891
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "UNSAFE_componentWillReceiveProps";
892
- }
893
- function isUnsafeComponentWillUpdate(node) {
894
- return AST14.isMethodOrProperty(node) && !node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "UNSAFE_componentWillUpdate";
895
- }
896
- function isGetDerivedStateFromProps(node) {
897
- return AST14.isMethodOrProperty(node) && node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "getDerivedStateFromProps";
898
- }
899
- function isGetDerivedStateFromError(node) {
900
- return AST14.isMethodOrProperty(node) && node.static && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "getDerivedStateFromError";
901
- }
902
- var ComponentPhaseRelevance = birecord({
903
- mount: "unmount",
904
- setup: "cleanup"
905
- });
906
- var isInversePhase = dual(2, (a, b) => ComponentPhaseRelevance.get(a) === b);
907
- function isRenderLike(node) {
908
- return AST14.isMethodOrProperty(node) && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === "render" && node.parent.parent.type === AST_NODE_TYPES.ClassDeclaration;
909
- }
910
- function isFunctionOfRender(node) {
911
- if (!isRenderLike(node.parent)) {
912
- return false;
913
- }
914
- return isClassComponent(node.parent.parent.parent);
1010
+ const components = /* @__PURE__ */ new Map();
1011
+ const ctx = { getAllComponents(node) {
1012
+ return components;
1013
+ } };
1014
+ const collect = (node) => {
1015
+ if (!isClassComponent(node)) return;
1016
+ const id = AST.getClassId(node);
1017
+ const key = getId();
1018
+ const flag = isPureComponent(node) ? ComponentFlag.PureComponent : ComponentFlag.None;
1019
+ components.set(key, {
1020
+ id,
1021
+ key,
1022
+ kind: "class",
1023
+ name: id?.name,
1024
+ node,
1025
+ displayName: unit,
1026
+ flag,
1027
+ hint: 0n,
1028
+ methods: []
1029
+ });
1030
+ };
1031
+ const listeners = {
1032
+ "ClassDeclaration[type]": collect,
1033
+ "ClassExpression[type]": collect
1034
+ };
1035
+ return {
1036
+ ctx,
1037
+ listeners
1038
+ };
915
1039
  }
1040
+
1041
+ //#endregion
1042
+ //#region src/component/component-method.ts
1043
+ /**
1044
+ * Create a lifecycle method checker function
1045
+ * @param methodName The lifecycle method name
1046
+ * @param isStatic Whether the method is static
1047
+ */
1048
+ function createLifecycleChecker(methodName, isStatic) {
1049
+ return function(node) {
1050
+ return AST.isMethodOrProperty(node) && node.static === isStatic && node.key.type === AST_NODE_TYPES.Identifier && node.key.name === methodName;
1051
+ };
1052
+ }
1053
+ const isRender = createLifecycleChecker("render", false);
1054
+ const isComponentDidCatch = createLifecycleChecker("componentDidCatch", false);
1055
+ const isComponentDidMount = createLifecycleChecker("componentDidMount", false);
1056
+ const isComponentDidUpdate = createLifecycleChecker("componentDidUpdate", false);
1057
+ const isComponentWillMount = createLifecycleChecker("componentWillMount", false);
1058
+ const isComponentWillReceiveProps = createLifecycleChecker("componentWillReceiveProps", false);
1059
+ const isComponentWillUnmount = createLifecycleChecker("componentWillUnmount", false);
1060
+ const isComponentWillUpdate = createLifecycleChecker("componentWillUpdate", false);
1061
+ const isGetChildContext = createLifecycleChecker("getChildContext", false);
1062
+ const isGetInitialState = createLifecycleChecker("getInitialState", false);
1063
+ const isGetSnapshotBeforeUpdate = createLifecycleChecker("getSnapshotBeforeUpdate", false);
1064
+ const isShouldComponentUpdate = createLifecycleChecker("shouldComponentUpdate", false);
1065
+ const isUnsafeComponentWillMount = createLifecycleChecker("UNSAFE_componentWillMount", false);
1066
+ const isUnsafeComponentWillReceiveProps = createLifecycleChecker("UNSAFE_componentWillReceiveProps", false);
1067
+ const isUnsafeComponentWillUpdate = createLifecycleChecker("UNSAFE_componentWillUpdate", false);
1068
+ const isGetDefaultProps = createLifecycleChecker("getDefaultProps", true);
1069
+ const isGetDerivedStateFromProps = createLifecycleChecker("getDerivedStateFromProps", true);
1070
+ const isGetDerivedStateFromError = createLifecycleChecker("getDerivedStateFromError", true);
1071
+
1072
+ //#endregion
1073
+ //#region src/component/component-phase.ts
1074
+ const ComponentPhaseRelevance = birecord({
1075
+ mount: "unmount",
1076
+ setup: "cleanup"
1077
+ });
1078
+ const isInversePhase = dual(2, (a, b) => ComponentPhaseRelevance.get(a) === b);
1079
+
1080
+ //#endregion
1081
+ //#region src/component/component-render-prop.ts
1082
+ /**
1083
+ * Unsafe check whether given node is a render function
1084
+ * ```tsx
1085
+ * const renderRow = () => <div />
1086
+ * ` ^^^^^^^^^^^^`
1087
+ * _ = <Component renderRow={() => <div />} />
1088
+ * ` ^^^^^^^^^^^^^ `
1089
+ * ```
1090
+ * @param context The rule context
1091
+ * @param node The AST node to check
1092
+ * @returns `true` if node is a render function, `false` if not
1093
+ */
916
1094
  function isRenderFunctionLoose(context, node) {
917
- const { body, parent } = node;
918
- if (AST14.getFunctionId(node)?.name.startsWith("render")) {
919
- return parent.type === AST_NODE_TYPES.JSXExpressionContainer && parent.parent.type === AST_NODE_TYPES.JSXAttribute && parent.parent.name.type === AST_NODE_TYPES.JSXIdentifier && parent.parent.name.name.startsWith("render");
920
- }
921
- return isJsxLike(
922
- context.sourceCode,
923
- body,
924
- JSXDetectionHint.SkipNullLiteral | JSXDetectionHint.SkipUndefined | JSXDetectionHint.StrictLogical | JSXDetectionHint.StrictConditional
925
- );
926
- }
1095
+ const { body, parent } = node;
1096
+ if (AST.getFunctionId(node)?.name.startsWith("render")) return parent.type === AST_NODE_TYPES.JSXExpressionContainer && parent.parent.type === AST_NODE_TYPES.JSXAttribute && parent.parent.name.type === AST_NODE_TYPES.JSXIdentifier && parent.parent.name.name.startsWith("render");
1097
+ return isJsxLike(context.sourceCode, body, JSXDetectionHint.SkipNullLiteral | JSXDetectionHint.SkipUndefined | JSXDetectionHint.StrictLogical | JSXDetectionHint.StrictConditional);
1098
+ }
1099
+ /**
1100
+ * Unsafe check whether given JSXAttribute is a render prop
1101
+ * ```tsx
1102
+ * _ = <Component renderRow={() => <div />} />
1103
+ * ` ^^^^^^^^^^^^^^^^^^^^^^^^^ `
1104
+ * ```
1105
+ * @param context The rule context
1106
+ * @param node The AST node to check
1107
+ * @returns `true` if node is a render prop, `false` if not
1108
+ */
927
1109
  function isRenderPropLoose(context, node) {
928
- if (node.name.type !== AST_NODE_TYPES.JSXIdentifier) {
929
- return false;
930
- }
931
- return node.name.name.startsWith("render") && node.value?.type === AST_NODE_TYPES.JSXExpressionContainer && AST14.isFunction(node.value.expression) && isRenderFunctionLoose(context, node.value.expression);
932
- }
1110
+ if (node.name.type !== AST_NODE_TYPES.JSXIdentifier) return false;
1111
+ return node.name.name.startsWith("render") && node.value?.type === AST_NODE_TYPES.JSXExpressionContainer && AST.isFunction(node.value.expression) && isRenderFunctionLoose(context, node.value.expression);
1112
+ }
1113
+ /**
1114
+ * Unsafe check whether given node is declared directly inside a render property
1115
+ * ```tsx
1116
+ * const rows = { render: () => <div /> }
1117
+ * ` ^^^^^^^^^^^^^ `
1118
+ * _ = <Component rows={ [{ render: () => <div /> }] } />
1119
+ * ` ^^^^^^^^^^^^^ `
1120
+ * ```
1121
+ * @internal
1122
+ * @param node The AST node to check
1123
+ * @returns `true` if component is declared inside a render property, `false` if not
1124
+ */
933
1125
  function isDirectValueOfRenderPropertyLoose(node) {
934
- const matching = (node2) => {
935
- return node2.type === AST_NODE_TYPES.Property && node2.key.type === AST_NODE_TYPES.Identifier && node2.key.name.startsWith("render");
936
- };
937
- return matching(node) || node.parent != null && matching(node.parent);
938
- }
1126
+ const matching = (node$1) => {
1127
+ return node$1.type === AST_NODE_TYPES.Property && node$1.key.type === AST_NODE_TYPES.Identifier && node$1.key.name.startsWith("render");
1128
+ };
1129
+ return matching(node) || node.parent != null && matching(node.parent);
1130
+ }
1131
+ /**
1132
+ * Unsafe check whether given node is declared inside a render prop
1133
+ * ```tsx
1134
+ * _ = <Component renderRow={"node"} />
1135
+ * ` ^^^^^^ `
1136
+ * _ = <Component rows={ [{ render: "node" }] } />
1137
+ * ` ^^^^^^ `
1138
+ * ```
1139
+ * @param node The AST node to check
1140
+ * @returns `true` if component is declared inside a render prop, `false` if not
1141
+ */
939
1142
  function isDeclaredInRenderPropLoose(node) {
940
- if (isDirectValueOfRenderPropertyLoose(node)) {
941
- return true;
942
- }
943
- const parent = AST14.findParentNode(node, AST14.is(AST_NODE_TYPES.JSXExpressionContainer))?.parent;
944
- if (parent?.type !== AST_NODE_TYPES.JSXAttribute) {
945
- return false;
946
- }
947
- return parent.name.type === AST_NODE_TYPES.JSXIdentifier && parent.name.name.startsWith("render");
1143
+ if (isDirectValueOfRenderPropertyLoose(node)) return true;
1144
+ const parent = AST.findParentNode(node, AST.is(AST_NODE_TYPES.JSXExpressionContainer))?.parent;
1145
+ if (parent?.type !== AST_NODE_TYPES.JSXAttribute) return false;
1146
+ return parent.name.type === AST_NODE_TYPES.JSXIdentifier && parent.name.name.startsWith("render");
948
1147
  }
1148
+
1149
+ //#endregion
1150
+ //#region src/component/component-state.ts
949
1151
  function isThisSetState(node) {
950
- const { callee } = node;
951
- return callee.type === AST_NODE_TYPES.MemberExpression && AST14.isThisExpression(callee.object) && callee.property.type === AST_NODE_TYPES.Identifier && callee.property.name === "setState";
1152
+ const { callee } = node;
1153
+ return callee.type === AST_NODE_TYPES.MemberExpression && AST.isThisExpression(callee.object) && callee.property.type === AST_NODE_TYPES.Identifier && callee.property.name === "setState";
952
1154
  }
953
1155
  function isAssignmentToThisState(node) {
954
- const { left } = node;
955
- return left.type === AST_NODE_TYPES.MemberExpression && AST14.isThisExpression(left.object) && AST14.getPropertyName(left.property) === "state";
1156
+ const { left } = node;
1157
+ return left.type === AST_NODE_TYPES.MemberExpression && AST.isThisExpression(left.object) && AST.getPropertyName(left.property) === "state";
1158
+ }
1159
+
1160
+ //#endregion
1161
+ //#region src/type/type-is.ts
1162
+ /** @internal */
1163
+ const isAnyType = (type) => isTypeFlagSet(type, ts.TypeFlags.TypeParameter | ts.TypeFlags.Any);
1164
+ /** @internal */
1165
+ const isBigIntType = (type) => isTypeFlagSet(type, ts.TypeFlags.BigIntLike);
1166
+ /** @internal */
1167
+ const isBooleanType = (type) => isTypeFlagSet(type, ts.TypeFlags.BooleanLike);
1168
+ /** @internal */
1169
+ const isEnumType = (type) => isTypeFlagSet(type, ts.TypeFlags.EnumLike);
1170
+ /** @internal */
1171
+ const isFalsyBigIntType = (type) => type.isLiteral() && isMatching({ value: { base10Value: "0" } }, type);
1172
+ /** @internal */
1173
+ const isFalsyNumberType = (type) => type.isNumberLiteral() && type.value === 0;
1174
+ /** @internal */
1175
+ const isFalsyStringType = (type) => type.isStringLiteral() && type.value === "";
1176
+ /** @internal */
1177
+ const isNeverType = (type) => isTypeFlagSet(type, ts.TypeFlags.Never);
1178
+ /** @internal */
1179
+ const isNullishType = (type) => isTypeFlagSet(type, ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.VoidLike);
1180
+ /** @internal */
1181
+ const isNumberType = (type) => isTypeFlagSet(type, ts.TypeFlags.NumberLike);
1182
+ /** @internal */
1183
+ const isObjectType = (type) => !isTypeFlagSet(type, ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.VoidLike | ts.TypeFlags.BooleanLike | ts.TypeFlags.StringLike | ts.TypeFlags.NumberLike | ts.TypeFlags.BigIntLike | ts.TypeFlags.TypeParameter | ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never);
1184
+ /** @internal */
1185
+ const isStringType = (type) => isTypeFlagSet(type, ts.TypeFlags.StringLike);
1186
+ /** @internal */
1187
+ const isTruthyBigIntType = (type) => type.isLiteral() && isMatching({ value: { base10Value: P.not("0") } }, type);
1188
+ /** @internal */
1189
+ const isTruthyNumberType = (type) => type.isNumberLiteral() && type.value !== 0;
1190
+ /** @internal */
1191
+ const isTruthyStringType = (type) => type.isStringLiteral() && type.value !== "";
1192
+ /** @internal */
1193
+ const isUnknownType = (type) => isTypeFlagSet(type, ts.TypeFlags.Unknown);
1194
+
1195
+ //#endregion
1196
+ //#region src/type/type-variant.ts
1197
+ /**
1198
+ * Ported from https://github.com/typescript-eslint/typescript-eslint/blob/eb736bbfc22554694400e6a4f97051d845d32e0b/packages/eslint-plugin/src/rules/strict-boolean-expressions.ts#L826 with some enhancements
1199
+ * Get the variants of an array of types.
1200
+ * @param types The types to get the variants of
1201
+ * @returns The variants of the types
1202
+ * @internal
1203
+ */
1204
+ function getTypeVariants(types) {
1205
+ const variants = /* @__PURE__ */ new Set();
1206
+ if (types.some(isUnknownType)) {
1207
+ variants.add("unknown");
1208
+ return variants;
1209
+ }
1210
+ if (types.some(isNullishType)) variants.add("nullish");
1211
+ const booleans = types.filter(isBooleanType);
1212
+ const boolean0 = booleans[0];
1213
+ if (booleans.length === 1 && boolean0 != null) {
1214
+ if (isFalseLiteralType(boolean0)) variants.add("falsy boolean");
1215
+ else if (isTrueLiteralType(boolean0)) variants.add("truthy boolean");
1216
+ } else if (booleans.length === 2) variants.add("boolean");
1217
+ const strings = types.filter(isStringType);
1218
+ if (strings.length > 0) {
1219
+ const evaluated = match(strings).when((types$1) => types$1.every(isTruthyStringType), () => "truthy string").when((types$1) => types$1.every(isFalsyStringType), () => "falsy string").otherwise(() => "string");
1220
+ variants.add(evaluated);
1221
+ }
1222
+ const bigints = types.filter(isBigIntType);
1223
+ if (bigints.length > 0) {
1224
+ const evaluated = match(bigints).when((types$1) => types$1.every(isTruthyBigIntType), () => "truthy bigint").when((types$1) => types$1.every(isFalsyBigIntType), () => "falsy bigint").otherwise(() => "bigint");
1225
+ variants.add(evaluated);
1226
+ }
1227
+ const numbers = types.filter(isNumberType);
1228
+ if (numbers.length > 0) {
1229
+ const evaluated = match(numbers).when((types$1) => types$1.every(isTruthyNumberType), () => "truthy number").when((types$1) => types$1.every(isFalsyNumberType), () => "falsy number").otherwise(() => "number");
1230
+ variants.add(evaluated);
1231
+ }
1232
+ if (types.some(isEnumType)) variants.add("enum");
1233
+ if (types.some(isObjectType)) variants.add("object");
1234
+ if (types.some(isAnyType)) variants.add("any");
1235
+ if (types.some(isNeverType)) variants.add("never");
1236
+ return variants;
956
1237
  }
957
1238
 
958
- export { ComponentDetectionHint, ComponentFlag, ComponentPhaseRelevance, DEFAULT_COMPONENT_DETECTION_HINT, DEFAULT_JSX_DETECTION_HINT, JSXDetectionHint, REACT_BUILTIN_HOOK_NAMES, findParentAttribute, getAttribute, getAttributeName, getAttributeValue, getComponentFlagFromInitPath, getComponentNameFromId, getElementType, getFunctionComponentId, getInstanceId, hasAnyAttribute, hasAttribute, hasEveryAttribute, hasNoneOrLooseComponentName, isAssignmentToThisState, isCaptureOwnerStack, isCaptureOwnerStackCall, isChildrenCount, isChildrenCountCall, isChildrenForEach, isChildrenForEachCall, isChildrenMap, isChildrenMapCall, isChildrenOfCreateElement, isChildrenOnly, isChildrenOnlyCall, isChildrenToArray, isChildrenToArrayCall, isClassComponent, isCloneElement, isCloneElementCall, isComponentDidCatch, isComponentDidMount, isComponentDidUpdate, isComponentName, isComponentNameLoose, isComponentWillMount, isComponentWillReceiveProps, isComponentWillUnmount, isComponentWillUpdate, isComponentWrapperCall, isComponentWrapperCallLoose, isCreateContext, isCreateContextCall, isCreateElement, isCreateElementCall, isCreateRef, isCreateRefCall, isDeclaredInRenderPropLoose, isDirectValueOfRenderPropertyLoose, isForwardRef, isForwardRefCall, isFragmentElement, isFunctionOfRender, isFunctionOfRenderMethod, isGetChildContext, isGetDefaultProps, isGetDerivedStateFromError, isGetDerivedStateFromProps, isGetInitialState, isGetSnapshotBeforeUpdate, isHostElement, isInitializedFromReact, isInstanceIdEqual, isInversePhase, isJsxLike, isJsxText, isKeyedElement, isLazy, isLazyCall, isMemo, isMemoCall, isPureComponent, isReactAPI, isReactAPICall, isReactHook, isReactHookCall, isReactHookCallWithName, isReactHookCallWithNameAlias, isReactHookCallWithNameLoose, isReactHookId, isReactHookName, isRenderFunctionLoose, isRenderLike, isRenderMethodLike, isRenderPropLoose, isShouldComponentUpdate, isThisSetState, isUnsafeComponentWillMount, isUnsafeComponentWillReceiveProps, isUnsafeComponentWillUpdate, isUseActionStateCall, isUseCall, isUseCallbackCall, isUseContextCall, isUseDebugValueCall, isUseDeferredValueCall, isUseEffectCall, isUseEffectCallLoose, isUseFormStatusCall, isUseIdCall, isUseImperativeHandleCall, isUseInsertionEffectCall, isUseLayoutEffectCall, isUseMemoCall, isUseOptimisticCall, isUseReducerCall, isUseRefCall, isUseStateCall, isUseSyncExternalStoreCall, isUseTransitionCall, isValidComponentDefinition, stringifyJsx, useComponentCollector, useComponentCollectorLegacy, useHookCollector };
1239
+ //#endregion
1240
+ export { ComponentDetectionHint, ComponentFlag, ComponentPhaseRelevance, DEFAULT_COMPONENT_DETECTION_HINT, DEFAULT_JSX_DETECTION_HINT, JSXDetectionHint, REACT_BUILTIN_HOOK_NAMES, findParentAttribute, getAttribute, getAttributeName, getAttributeValue, getComponentFlagFromInitPath, getComponentNameFromId, getElementType, getFunctionComponentId, getInstanceId, getTypeVariants, hasAnyAttribute, hasAttribute, hasEveryAttribute, hasNoneOrLooseComponentName, isAnyType, isAssignmentToThisState, isBigIntType, isBooleanType, isCaptureOwnerStack, isCaptureOwnerStackCall, isChildrenCount, isChildrenCountCall, isChildrenForEach, isChildrenForEachCall, isChildrenMap, isChildrenMapCall, isChildrenOfCreateElement, isChildrenOnly, isChildrenOnlyCall, isChildrenToArray, isChildrenToArrayCall, isClassComponent, isCloneElement, isCloneElementCall, isComponentDefinition, isComponentDidCatch, isComponentDidMount, isComponentDidUpdate, isComponentName, isComponentNameLoose, isComponentWillMount, isComponentWillReceiveProps, isComponentWillUnmount, isComponentWillUpdate, isComponentWrapperCall, isComponentWrapperCallLoose, isCreateContext, isCreateContextCall, isCreateElement, isCreateElementCall, isCreateRef, isCreateRefCall, isDeclaredInRenderPropLoose, isDirectValueOfRenderPropertyLoose, isEnumType, isFalseLiteralType, isFalsyBigIntType, isFalsyNumberType, isFalsyStringType, isForwardRef, isForwardRefCall, isFragmentElement, isFunctionOfRenderMethod, isGetChildContext, isGetDefaultProps, isGetDerivedStateFromError, isGetDerivedStateFromProps, isGetInitialState, isGetSnapshotBeforeUpdate, isHostElement, isInitializedFromReact, isInstanceIdEqual, isInversePhase, isJsxLike, isJsxText, isLazy, isLazyCall, isMemo, isMemoCall, isNeverType, isNullishType, isNumberType, isObjectType, isPureComponent, isReactAPI, isReactAPICall, isReactHook, isReactHookCall, isReactHookCallWithName, isReactHookCallWithNameAlias, isReactHookCallWithNameLoose, isReactHookId, isReactHookName, isRender, isRenderFunctionLoose, isRenderMethodLike, isRenderPropLoose, isShouldComponentUpdate, isStringType, isThisSetState, isTrueLiteralType, isTruthyBigIntType, isTruthyNumberType, isTruthyStringType, isUnknownType, isUnsafeComponentWillMount, isUnsafeComponentWillReceiveProps, isUnsafeComponentWillUpdate, isUseActionStateCall, isUseCall, isUseCallbackCall, isUseContextCall, isUseDebugValueCall, isUseDeferredValueCall, isUseEffectCall, isUseEffectCallLoose, isUseFormStatusCall, isUseIdCall, isUseImperativeHandleCall, isUseInsertionEffectCall, isUseLayoutEffectCall, isUseMemoCall, isUseOptimisticCall, isUseReducerCall, isUseRefCall, isUseStateCall, isUseSyncExternalStoreCall, isUseTransitionCall, stringifyJsx, useComponentCollector, useComponentCollectorLegacy, useHookCollector };