@eslint-react/jsx 5.30.0-beta.5 → 5.30.0-beta.6

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 +399 -274
  2. package/dist/index.js +142 -183
  3. package/package.json +4 -6
package/dist/index.d.ts CHANGED
@@ -1,78 +1,56 @@
1
- import { TSESTreeJSXAttributeLike, TSESTreeJSXElementLike } from "@eslint-react/ast";
1
+ import { TSESTreeJSXElementLike } from "@eslint-react/ast";
2
2
  import { TSESTree } from "@typescript-eslint/types";
3
3
  import { RuleContext } from "@eslint-react/eslint";
4
4
  /**
5
- * Find a JSX attribute (or a spread attribute containing the property) by name.
5
+ * A test used to select a `JSXAttribute`.
6
6
  *
7
- * Returns the last matching attribute to mirror React's behavior where later props win.
8
- * Spread attributes are resolved when possible: if the spread argument is an identifier
9
- * that resolves to an object expression, the object's properties are searched for a
10
- * matching key (see {@link findSpreadProperty}).
11
- * @param context The ESLint rule context (needed for variable resolution in spread attributes).
12
- * @param element The `JSXElement` node to search.
13
- * @param name The attribute name to look for (ex: "className").
14
- * @returns The matching `JSXAttribute` or `JSXSpreadAttribute`, or `undefined` when not found.
15
- */
16
- export declare function findAttribute(context: RuleContext, element: TSESTree.JSXElement, name: string): TSESTreeJSXAttributeLike | undefined;
17
- /**
18
- * Walk up the AST from `node` to find the nearest `JSXAttribute` ancestor, optionally matching a predicate.
19
- * @param node The starting node for the upward search.
20
- * @param test Optional predicate to filter candidate `JSXAttribute` nodes.
21
- * @returns The first matching `JSXAttribute` ancestor, or `undefined` when none is found.
22
- */
23
- export declare function findParentAttribute(node: TSESTree.Node, test?: (node: TSESTree.JSXAttribute) => boolean): TSESTree.JSXAttribute | undefined;
24
- /**
25
- * Find the `Property` node that provides a given key inside a spread argument.
26
- *
27
- * This is the single resolution routine shared by {@link findAttribute} (existence
28
- * checks) and the `spreadProps` variant of `resolveAttributeValue` (value extraction):
29
- *
30
- * - An `Identifier` argument is resolved to its initializer via variable
31
- * resolution, following alias chains (`const b = a`) like `getStaticValue`
32
- * does; an `ObjectExpression` argument is searched directly.
33
- * - Properties are walked **in reverse** so that later entries win, matching
34
- * JavaScript object semantics (`{ ...a, k: 1 }` -> the literal `k`).
35
- * - Nested `SpreadElement`s (identifiers or inline object expressions) are
36
- * searched recursively; a `seen` set guards against circular references.
37
- * - Plain identifier keys and string literal keys are matched directly;
38
- * computed keys are matched when they are statically evaluable
39
- * (ex: `{ ["class" + "Name"]: 1 }`).
40
- * @param context The ESLint rule context (needed for variable resolution).
41
- * @param argument The spread argument expression to search.
42
- * @param name The property name to look for.
43
- * @param seen Internal set of already-visited nodes (cycle guard).
44
- * @returns The matching `Property` node, or `undefined` when the key is not found.
45
- */
46
- export declare function findSpreadProperty(context: RuleContext, argument: TSESTree.Expression, name: string, seen?: Set<TSESTree.Node>): TSESTree.Property | undefined;
47
- /**
48
- * Check if the element has an attribute with the given name.
49
- *
50
- * Spread attributes are taken into account: `<Comp {...{ disabled: true }} />`
51
- * reports `true` for `"disabled"` (see {@link findAttribute}).
52
- * @param context The ESLint rule context (needed for variable resolution in spread attributes).
53
- * @param element The `JSXElement` node to check.
54
- * @param name The attribute name to look for (ex: "className").
55
- * @returns `true` if the attribute is present on the element.
56
- */
57
- export declare function hasAttribute(context: RuleContext, element: TSESTree.JSXElement, name: string): boolean;
58
- /**
59
- * Check if the element has at least one of the given attributes.
60
- * @param context The ESLint rule context (needed for variable resolution in spread attributes).
61
- * @param element The `JSXElement` node to check.
62
- * @param names The attribute names to look for.
63
- * @returns `true` if at least one of the attributes is present.
7
+ * A string is matched against the full attribute name (including a namespace);
8
+ * a function receives the attribute node.
64
9
  */
65
- export declare function hasAnyAttribute(context: RuleContext, element: TSESTree.JSXElement, names: string[]): boolean;
10
+ type AttributeTest = string | ((attribute: TSESTree.JSXAttribute) => boolean);
66
11
  /**
67
- * Check if the element has all of the given attributes.
68
- * @param context The ESLint rule context (needed for variable resolution in spread attributes).
69
- * @param element The `JSXElement` node to check.
70
- * @param names The attribute names to look for.
71
- * @returns `true` if every attribute is present on the element.
12
+ * The structural value of a direct JSX attribute.
13
+ *
14
+ * - `boolean`: the attribute has no value (ex: `<input disabled />`).
15
+ * - `literal`: the value is a literal.
16
+ * - `unknown`: a non-empty expression, normally in an expression container;
17
+ * the expression is not evaluated.
18
+ * - `element`: the value is a JSX element or fragment.
19
+ * - `missing`: no expression, normally an empty expression container
20
+ * (`{}` or `{/* comment *\/}`).
21
+ *
22
+ * Every variant carries the source `attribute`; `node` is `null` only for the
23
+ * `boolean` kind. This is plain data; use {@link getAttributeStaticValue} to
24
+ * collapse values to a plain JavaScript value.
25
+ * @remarks
26
+ * The `spreadChild` variant is omitted because it is not valid in attribute
27
+ * value position and is not produced by current parsers. The `spreadProps`
28
+ * variant is omitted because spread props are not resolved and direct attribute
29
+ * lookup never produces a spread descriptor.
72
30
  */
73
- export declare function hasEveryAttribute(context: RuleContext, element: TSESTree.JSXElement, names: string[]): boolean;
31
+ type AttributeValue = {
32
+ readonly kind: "boolean";
33
+ readonly attribute: TSESTree.JSXAttribute;
34
+ readonly node: null;
35
+ } | {
36
+ readonly kind: "literal";
37
+ readonly attribute: TSESTree.JSXAttribute;
38
+ readonly node: TSESTree.Literal;
39
+ } | {
40
+ readonly kind: "unknown";
41
+ readonly attribute: TSESTree.JSXAttribute;
42
+ readonly node: TSESTree.Expression;
43
+ } | {
44
+ readonly kind: "element";
45
+ readonly attribute: TSESTree.JSXAttribute;
46
+ readonly node: TSESTreeJSXElementLike;
47
+ } | {
48
+ readonly kind: "missing";
49
+ readonly attribute: TSESTree.JSXAttribute;
50
+ readonly node: TSESTree.JSXEmptyExpression;
51
+ };
74
52
  /**
75
- * Get the stringified name of a `JSXAttribute` node.
53
+ * Get the full name of a `JSXAttribute` node.
76
54
  *
77
55
  * - `className` -> `"className"`
78
56
  * - `aria-label` -> `"aria-label"`
@@ -82,232 +60,356 @@ export declare function hasEveryAttribute(context: RuleContext, element: TSESTre
82
60
  */
83
61
  export declare function getAttributeName(node: TSESTree.JSXAttribute): string;
84
62
  /**
85
- * Check if the node is a `JSXAttribute` with the given name.
63
+ * Check if the node is a `JSXAttribute` with the given plain identifier name.
86
64
  *
87
- * Only plain identifier names are matched (ex: `className`); namespaced
88
- * attributes (ex: `xml:space`) do not match.
65
+ * Namespaced attributes (ex: `xml:space`) never match; use
66
+ * {@link isAttributeNamed} for full-name matching.
89
67
  *
90
68
  * Supports both data-first and data-last (curried) call styles:
91
- * - `isAttribute(node, "className")`
92
- * - `isAttribute("className")(node)`.
69
+ * - `isPlainAttribute(node, "className")`
70
+ * - `isPlainAttribute("className")(node)`.
93
71
  * @param node The node to check.
94
- * @param name The attribute name to match (ex: "className").
95
- * @returns `true` if the node is a `JSXAttribute` named `name`.
72
+ * @param name The plain attribute name to match (ex: "className").
73
+ * @returns `true` if the node is a `JSXAttribute` whose identifier name is `name`.
74
+ * @remarks
75
+ * This is a name predicate, not a type guard: a `false` result does not mean
76
+ * the node is not a `JSXAttribute`, only that it does not match `name`.
96
77
  */
97
- export declare const isAttribute: {
98
- (name: string): (node: TSESTree.Node) => node is TSESTree.JSXAttribute;
99
- (node: TSESTree.Node, name: string): node is TSESTree.JSXAttribute;
78
+ export declare const isPlainAttribute: {
79
+ (name: string): (node: TSESTree.Node | null | undefined) => boolean;
80
+ (node: TSESTree.Node | null | undefined, name: string): boolean;
100
81
  };
101
82
  /**
102
- * Discriminated union representing the resolved value of a JSX attribute.
83
+ * Check if the node is a `JSXAttribute` with the given full name.
84
+ *
85
+ * The name includes the namespace when present, so `xml:space` can be matched.
86
+ * This is the name semantics used by {@link findAttribute} and the string form
87
+ * of {@link AttributeTest}.
103
88
  *
104
- * Each variant carries the original AST `node` (the `boolean` variant has no value
105
- * node and reports `null`) and a `toStatic()` helper that attempts to collapse the
106
- * value into a plain JavaScript value at analysis time. `toStatic()` returns
107
- * `undefined` when no static value is available; structural information is carried
108
- * by `kind`, value information by `toStatic()`.
89
+ * Supports both data-first and data-last (curried) call styles.
90
+ * @param node The node to check.
91
+ * @param name The full attribute name to match (ex: "className", "xml:space").
92
+ * @returns `true` if the node is a `JSXAttribute` whose full name is `name`.
93
+ * @remarks
94
+ * This is a name predicate, not a type guard: a `false` result does not mean
95
+ * the node is not a `JSXAttribute`, only that it does not match `name`.
109
96
  */
110
- type AttributeValue = {
111
- readonly kind: "boolean";
112
- readonly node: null;
113
- toStatic(): true;
114
- } | {
115
- readonly kind: "literal";
116
- readonly node: TSESTree.Literal;
117
- toStatic(): TSESTree.Literal["value"];
118
- } | {
119
- readonly kind: "unknown";
120
- readonly node: TSESTree.Expression;
121
- toStatic(): unknown;
122
- } | {
123
- readonly kind: "element";
124
- readonly node: TSESTreeJSXElementLike;
125
- toStatic(): undefined;
126
- } | {
127
- readonly kind: "missing";
128
- readonly node: TSESTree.JSXEmptyExpression;
129
- toStatic(): undefined;
130
- } | {
131
- readonly kind: "spreadChild";
132
- readonly node: TSESTree.JSXSpreadChild;
133
- toStatic(): undefined;
134
- } | {
135
- readonly kind: "spreadProps";
136
- getProperty(name: string): unknown;
137
- readonly node: TSESTree.JSXSpreadAttribute["argument"];
138
- toStatic(): unknown;
97
+ export declare const isAttributeNamed: {
98
+ (name: string): (node: TSESTree.Node | null | undefined) => boolean;
99
+ (node: TSESTree.Node | null | undefined, name: string): boolean;
139
100
  };
140
101
  /**
141
- * Resolve the value of a JSX attribute (or spread attribute) into an {@link AttributeValue} descriptor.
102
+ * Find the last direct JSX attribute with the given full name.
142
103
  *
143
- * When the attribute is a `JSXSpreadAttribute`, passing `name` (typically the name
144
- * the attribute was found by) makes `toStatic()` return the static value of that
145
- * named property. For the higher-level "find by name and resolve" combo, see {@link getAttributeValue}.
146
- * @param context The ESLint rule context (needed for scope look-ups).
147
- * @param attribute A `JSXAttribute` or `JSXSpreadAttribute` node.
148
- * @param name Optional property name used to resolve `toStatic()` for spread attributes.
104
+ * Later direct attributes take precedence, matching the order in which JSX
105
+ * props are written. Spread attributes are opaque: they are ignored by this lookup, and a
106
+ * spread after the returned attribute may still override it at runtime.
107
+ * @param element The `JSXElement` node to search.
108
+ * @param name The full attribute name to look for (ex: "className", "xml:space").
109
+ * @returns The last matching `JSXAttribute`, or `null` when not found.
110
+ */
111
+ export declare function findAttribute(element: TSESTree.JSXElement, name: string): TSESTree.JSXAttribute | null;
112
+ /**
113
+ * Walk up the AST from `node` to find the nearest `JSXAttribute` ancestor,
114
+ * optionally matching a string name or a predicate.
115
+ *
116
+ * The search starts at `node.parent`; `node` itself is not considered. When
117
+ * `test` is omitted, the nearest `JSXAttribute` ancestor matches.
118
+ * @param node The starting node for the upward search; nullish values return `null`.
119
+ * @param test Optional test to filter candidate `JSXAttribute` nodes. A string
120
+ * matches the full attribute name (see {@link isAttributeNamed}); a function
121
+ * receives the candidate attribute.
122
+ * @returns The first matching `JSXAttribute` ancestor, or `null` when none is found.
123
+ */
124
+ export declare function findParentAttribute(node: TSESTree.Node | null | undefined, test?: AttributeTest): TSESTree.JSXAttribute | null;
125
+ /**
126
+ * Check if the element has a direct attribute with the given full name.
127
+ *
128
+ * Spread attributes are ignored; only direct `JSXAttribute` nodes are checked.
129
+ * @param element The `JSXElement` node to check.
130
+ * @param name The full attribute name to look for (ex: "className", "xml:space").
131
+ * @returns `true` if the attribute is directly present on the element.
132
+ */
133
+ export declare function hasAttribute(element: TSESTree.JSXElement, name: string): boolean;
134
+ /**
135
+ * Check if the element has at least one of the given direct attributes.
136
+ *
137
+ * Spread attributes are ignored; only direct `JSXAttribute` nodes are checked.
138
+ * @param element The `JSXElement` node to check.
139
+ * @param names The full attribute names to look for (namespaces included).
140
+ * @returns `true` if at least one direct attribute is present; `false` for an empty list.
141
+ */
142
+ export declare function hasAnyAttribute(element: TSESTree.JSXElement, names: readonly string[]): boolean;
143
+ /**
144
+ * Check if the element has all of the given direct attributes.
145
+ *
146
+ * Spread attributes are ignored; only direct `JSXAttribute` nodes are checked.
147
+ * @param element The `JSXElement` node to check.
148
+ * @param names The full attribute names to look for (namespaces included).
149
+ * @returns `true` if every direct attribute is present; an empty list is vacuously `true`.
150
+ */
151
+ export declare function hasEveryAttribute(element: TSESTree.JSXElement, names: readonly string[]): boolean;
152
+ /**
153
+ * Get the structural value of a direct `JSXAttribute`.
154
+ *
155
+ * The attribute's value is classified syntactically; expressions are not
156
+ * evaluated. Only direct `JSXAttribute` nodes are accepted; spread attributes
157
+ * are outside this API.
158
+ * @param attribute The `JSXAttribute` node to get the value from.
149
159
  * @returns A discriminated-union descriptor of the attribute's value.
160
+ * @remarks
161
+ * A `JSXSpreadChild` in attribute value position is not valid JSX and is not
162
+ * produced by current parsers, but it is part of the TSESTree union. It is
163
+ * treated as its inner expression, or as `missing` when that expression is empty.
150
164
  */
151
- export declare function resolveAttributeValue(context: RuleContext, attribute: TSESTreeJSXAttributeLike, name?: string): AttributeValue;
165
+ export declare function getAttributeValue(attribute: TSESTree.JSXAttribute): AttributeValue;
152
166
  /**
153
- * Find an attribute by name on a JSX element and resolve its value in a single call.
167
+ * Find the last direct attribute with the given full name and get its value.
154
168
  *
155
- * Convenience composition of {@link findAttribute} and {@link resolveAttributeValue}.
156
- * @param context The ESLint rule context.
169
+ * Convenience composition of {@link findAttribute} and {@link getAttributeValue}.
170
+ * Spread attributes are ignored; a spread after the matched attribute may still
171
+ * override it at runtime.
157
172
  * @param element The `JSXElement` node to search.
158
- * @param name The attribute name to look up (ex: "className").
159
- * @returns An {@link AttributeValue} descriptor, or `undefined` when the attribute is not present.
173
+ * @param name The full attribute name to look up (ex: "className", "xml:space").
174
+ * @returns An {@link AttributeValue} descriptor, or `null` when no matching direct attribute is present.
175
+ */
176
+ export declare function getAttributeValueByName(element: TSESTree.JSXElement, name: string): AttributeValue | null;
177
+ /**
178
+ * Get the statically known value of an attribute value descriptor when possible.
179
+ *
180
+ * Boolean attributes resolve to `true`; literal attributes resolve to their
181
+ * literal value; other expressions are evaluated statically when possible.
182
+ * Returns `undefined` when the descriptor is null, is a JSX element or fragment,
183
+ * is a `missing` descriptor, cannot be statically evaluated, or evaluates to
184
+ * `undefined`. A statically known `undefined` is therefore indistinguishable
185
+ * from an indeterminate value.
186
+ * @param context The ESLint rule context (needed for scope look-ups).
187
+ * @param value The attribute value descriptor, or `null`.
188
+ * @returns The static value, or `undefined` when no statically known plain value is available.
160
189
  */
161
- export declare function getAttributeValue(context: RuleContext, element: TSESTree.JSXElement, name: string): AttributeValue | undefined;
190
+ export declare function getAttributeStaticValue(context: RuleContext, value: AttributeValue | null): unknown;
162
191
  /**
163
- * Find an attribute by name on a JSX element and collapse its value to a plain JavaScript value.
192
+ * Find the last direct attribute with the given full name and get its static value.
164
193
  *
165
- * Returns `undefined` both when the attribute is absent and when its value cannot
166
- * be statically determined; use {@link hasAttribute} when presence itself matters.
194
+ * Returns `undefined` when no matching direct attribute is present, or when its
195
+ * value is a JSX element or fragment, is a `missing` descriptor, cannot be
196
+ * statically evaluated, or evaluates to `undefined`. A statically known
197
+ * `undefined` is likewise indistinguishable from an absent or indeterminate
198
+ * value; use {@link hasAttribute} when presence itself matters. Spread
199
+ * attributes are ignored; a spread after the matched attribute may still
200
+ * override it at runtime.
167
201
  * @param context The ESLint rule context.
168
202
  * @param element The `JSXElement` node to check.
169
- * @param name The attribute name to look up (ex: "className").
203
+ * @param name The full attribute name to look up (ex: "className", "xml:space").
170
204
  * @returns The static value of the attribute, or `undefined` when absent or indeterminate.
171
205
  */
172
- export declare function getAttributeStaticValue(context: RuleContext, element: TSESTree.JSXElement, name: string): unknown;
206
+ export declare function getAttributeStaticValueByName(context: RuleContext, element: TSESTree.JSXElement, name: string): unknown;
173
207
  /**
174
- * Get the meaningful children of a JSX element or fragment.
208
+ * Check if the node is whitespace-only `JSXText`, based on its raw source text.
175
209
  *
176
- * Similar to Babel's `buildChildren` helper, with two differences: only padding
177
- * whitespace (whitespace containing a newline) is skipped, whereas Babel's
178
- * `cleanJSXElementLiteralChild` drops all whitespace-only `JSXText`; and empty
179
- * string expressions (`{""}`) are skipped as well, which follows React's
180
- * rendering behavior rather than Babel's:
181
- * 1. Iterate over `element.children`.
182
- * 2. Skip `JSXText` nodes that clean to nothing (padding whitespace).
183
- * 3. Skip `JSXExpressionContainer` nodes whose expression is empty.
184
- * 4. Skip empty string expressions (`{""}`), which produce no DOM node.
185
- * 5. Collect everything else.
210
+ * Matches any `JSXText` node whose raw text is empty after trimming, regardless
211
+ * of newlines. Same-line whitespace matches here; {@link isPaddingWhitespace}
212
+ * additionally requires a line feed and uses the decoded value.
213
+ *
214
+ * Reads `node.raw` rather than the entity-decoded `value`, so entity text such
215
+ * as `&nbsp;` or `&#32;` is treated as content even when its decoded value is
216
+ * whitespace. This is a syntactic check on the source text, not a model of
217
+ * React's whitespace collapsing.
218
+ * @param node The node to check.
219
+ * @returns `true` if the node is whitespace-only `JSXText` in its raw form.
220
+ * @remarks
221
+ * This is a content predicate, not a type guard: a `false` result does not
222
+ * mean the node is not `JSXText`, only that it is not whitespace-only text.
223
+ */
224
+ export declare function isWhitespaceText(node: TSESTree.Node | null | undefined): boolean;
225
+ /**
226
+ * Check if the node is whitespace-only `JSXText` that this module treats as
227
+ * padding: it cleans to nothing (see {@link collapseMultilineText}) and contains
228
+ * a line feed (`\n`).
229
+ *
230
+ * Reads the entity-decoded `node.value`, so an entity-encoded line break such as
231
+ * `&#10;` matches even though the raw text contains no line break. For a
232
+ * whitespace check based on raw source text, see {@link isWhitespaceText}.
233
+ * @param node The node to check.
234
+ * @returns `true` if the node is purely formatting whitespace by its decoded value.
235
+ * @remarks
236
+ * This is a content predicate, not a type guard: a `false` result does not
237
+ * mean the node is not `JSXText`.
238
+ */
239
+ export declare function isPaddingWhitespace(node: TSESTree.Node | null | undefined): boolean;
240
+ /**
241
+ * Check if the node is an empty expression container (`{}`, `{/* comment *\/}`).
242
+ *
243
+ * An empty `JSXExpressionContainer` holds no expression, so it produces no DOM
244
+ * node and is treated as non-rendered content, same as whitespace padding.
245
+ * @param node The node to check.
246
+ * @returns `true` if the node is an empty `JSXExpressionContainer`.
247
+ * @remarks
248
+ * This is a content predicate, not a type guard: a `false` result does not
249
+ * mean the node is not a `JSXExpressionContainer`.
250
+ */
251
+ export declare function isEmptyExpressionContainer(node: TSESTree.Node | null | undefined): boolean;
252
+ /**
253
+ * Check if the node is an empty string literal expression (`{""}`).
254
+ *
255
+ * Only a literal empty string matches; template literals and other expressions
256
+ * that happen to evaluate to `""` are not evaluated by this predicate.
257
+ * @param node The node to check.
258
+ * @returns `true` if the node is an expression container holding an empty string literal.
259
+ * @remarks
260
+ * This is a content predicate, not a type guard: a `false` result does not
261
+ * mean the node is not a `JSXExpressionContainer`.
262
+ */
263
+ export declare function isEmptyStringExpression(node: TSESTree.Node | null | undefined): boolean;
264
+ /**
265
+ * Check if the child carries content for the "meaningful children" semantics.
266
+ *
267
+ * Whitespace-only `JSXText` as determined by {@link isWhitespaceText} (which
268
+ * reads raw source text and therefore keeps entity text), empty expression
269
+ * containers, and empty string literal expressions are excluded. This is a
270
+ * syntactic check: `{null}`, `{false}`, and other dynamic expressions still
271
+ * count as children content.
272
+ * @param node The JSX child to check.
273
+ * @returns `true` if the child is not syntactically empty.
274
+ */
275
+ export declare function isMeaningfulChild(node: TSESTree.JSXChild): boolean;
276
+ /**
277
+ * Get the children of a JSX element or fragment after removing syntactic JSX
278
+ * artifacts: padding whitespace (see {@link isPaddingWhitespace}), empty
279
+ * expression containers, and empty string literal expressions.
280
+ *
281
+ * Same-line whitespace is kept because it is not padding by this definition and
282
+ * can render as a text node. This is a syntactic filter, not a runtime-rendering
283
+ * guarantee: `{null}`, `{false}`, and other expressions that may render nothing
284
+ * are kept.
186
285
  * @param element A `JSXElement` or `JSXFragment` node.
187
- * @returns The children nodes that contribute to rendered output.
286
+ * @returns The children that remain after removing padding artifacts.
188
287
  */
189
288
  export declare function getChildren(element: TSESTreeJSXElementLike): TSESTree.JSXChild[];
190
289
  /**
191
- * Check if the element has at least one meaningful child, that is, a child that
192
- * is not purely whitespace text, an empty expression container (`{}`), or an
193
- * empty string expression (`{""}`).
290
+ * Get the children of a JSX element or fragment that are not syntactically empty.
194
291
  *
195
- * Unlike {@link getChildren} (which only filters whitespace containing a newline),
196
- * this check treats any whitespace-only text as non-meaningful, so `hasChildren(node)`
197
- * is not always equal to `getChildren(node).length > 0` (ex: `<div> </div>`).
292
+ * Unlike {@link getChildren}, all whitespace-only `JSXText` as determined by
293
+ * {@link isWhitespaceText} is excluded, so `getMeaningfulChildren` is stricter
294
+ * for same-line whitespace (ex: `<div> </div>` yields no children here but one
295
+ * child from `getChildren`). Like `getChildren`, empty expression containers and
296
+ * empty string literal expressions are also excluded, and this is a syntactic
297
+ * check: `{null}`, `{false}`, and other dynamic expressions count as children.
198
298
  * @param element A `JSXElement` or `JSXFragment` node.
199
- * @returns `true` if the element has at least one meaningful child.
299
+ * @returns The children that are not syntactically empty.
200
300
  */
201
- export declare function hasChildren(element: TSESTreeJSXElementLike): boolean;
301
+ export declare function getMeaningfulChildren(element: TSESTreeJSXElementLike): TSESTree.JSXChild[];
202
302
  /**
203
- * Get the type argument (the first argument) of a `createElement` call.
204
- * @param context The ESLint rule context.
205
- * @param node The node to inspect.
206
- * @returns The type argument, or `null` when the node is not a `createElement` call or has no arguments.
303
+ * Check if the element has at least one syntactically non-empty child.
304
+ *
305
+ * A child counts when it is not whitespace-only `JSXText` as determined by
306
+ * {@link isWhitespaceText}, an empty expression container (`{}` or
307
+ * `{/* comment *\/}`), or an empty string literal expression (`{""}`). Same-line
308
+ * whitespace does not count, unlike in {@link getChildren}. `{null}`, `{false}`,
309
+ * and other dynamic expressions do count.
310
+ * @param element A `JSXElement` or `JSXFragment` node.
311
+ * @returns `true` if the element has at least one syntactically non-empty child.
207
312
  */
208
- export declare function getCreateElementTypeArgument(context: RuleContext, node: null | TSESTree.Node): TSESTree.CallExpressionArgument | null;
313
+ export declare function hasMeaningfulChildren(element: TSESTreeJSXElementLike): boolean;
209
314
  /**
210
- * Get the props object (the second argument) of a `createElement` call.
315
+ * A parsed `createElement` call.
211
316
  *
212
- * Type expressions and chain expressions wrapping the argument are unwrapped
213
- * before the object check; `null`, spread, or otherwise non-object props
214
- * arguments yield `null`.
317
+ * The raw positional argument fields (`typeArgument`, `propsArgument`, and
318
+ * `childrenArguments`) may contain `SpreadElement` nodes. `propsObject` is the
319
+ * only derived field: it is the second argument after unwrapping type/chain
320
+ * expressions, and is non-null only when that argument is syntactically an
321
+ * object literal.
322
+ */
323
+ interface CreateElementCall {
324
+ /** The raw arguments after the props argument. */
325
+ readonly childrenArguments: readonly TSESTree.CallExpressionArgument[];
326
+ /** The call expression node. */
327
+ readonly node: TSESTree.CallExpression;
328
+ /** The raw second positional argument (the props argument), if present. */
329
+ readonly propsArgument: TSESTree.CallExpressionArgument | null;
330
+ /** The second argument unwrapped, when it is an object literal. */
331
+ readonly propsObject: TSESTree.ObjectExpression | null;
332
+ /** The raw first positional argument (the element type), if present. */
333
+ readonly typeArgument: TSESTree.CallExpressionArgument | null;
334
+ }
335
+ /**
336
+ * Check if the node is a call to a `createElement` API.
215
337
  *
338
+ * Matching is name-based and namespace-agnostic: the fully qualified callee name
339
+ * must be `createElement` or end with `.createElement`. No import provenance
340
+ * check is performed, matching `isAPICall("createElement")` in `@eslint-react/core`.
216
341
  * @param context The ESLint rule context.
217
- * @param node The node to inspect.
218
- * @returns The props `ObjectExpression`, or `null` when absent or not statically an object literal.
342
+ * @param node The node to inspect; nullish or non-call nodes return `false`.
343
+ * @returns `true` if the node is a `createElement` call.
344
+ * @remarks
345
+ * This is a call-name predicate, not a type guard: a `false` result does not
346
+ * mean the node is not a `CallExpression`, only that it is not a
347
+ * `createElement` call.
219
348
  */
220
- export declare function getCreateElementPropsObject(context: RuleContext, node: null | TSESTree.Node): TSESTree.ObjectExpression | null;
349
+ export declare function isCreateElementCall(context: RuleContext, node: TSESTree.Node | null | undefined): boolean;
221
350
  /**
222
- * Get the children arguments (the arguments after the props object) of a `createElement` call.
351
+ * Parse a `createElement` call into its positional arguments.
352
+ *
353
+ * A nullish or non-`createElement` node yields `null`; a matched call always
354
+ * yields a descriptor, even when it has no arguments. This removes the ambiguity
355
+ * between "not a `createElement` call" and "a call with no props/children".
223
356
  * @param context The ESLint rule context.
224
357
  * @param node The node to inspect.
225
- * @returns The children arguments, or an empty array when the node is not a `createElement` call.
358
+ * @returns The parsed call, or `null` when the node is not a `createElement` call.
226
359
  */
227
- export declare function getCreateElementChildrenArguments(context: RuleContext, node: null | TSESTree.Node): TSESTree.CallExpressionArgument[];
360
+ export declare function parseCreateElementCall(context: RuleContext, node: TSESTree.Node | null | undefined): CreateElementCall | null;
228
361
  /**
229
- * Find a statically named property in the props object of a `createElement` call.
362
+ * Find a statically named direct property in the props object of a `createElement` call.
363
+ *
364
+ * Properties are scanned in reverse so that the last direct property takes precedence.
365
+ * Spread properties are ignored rather than statically resolved; a spread after
366
+ * the returned property may still override it at runtime. Statically evaluable
367
+ * computed keys are matched.
230
368
  *
231
- * Statically resolvable names include plain identifier keys as well as
232
- * string-literal and simple template-literal keys (computed or not).
369
+ * Returns `null` when the call is `null` or has no statically identifiable props
370
+ * object, that is, when the second argument is absent or is not an object
371
+ * literal after unwrapping type/chain expressions.
233
372
  * @param context The ESLint rule context.
234
- * @param node The node to inspect.
373
+ * @param call The parsed call, or `null`.
235
374
  * @param name The property name to look for (ex: `"children"`, `"key"`).
236
- * @returns The matching `Property` node, or `null` when the call has no static property with that name.
237
- *
238
- * @example
239
- * ```ts
240
- * import { getCreateElementProp } from "@eslint-react/jsx";
241
- *
242
- * const childrenProp = getCreateElementProp(context, node, "children");
243
- * ```
375
+ * @returns The last matching `Property` node, or `null` when not found.
244
376
  */
245
- export declare function getCreateElementProp(context: RuleContext, node: null | TSESTree.Node, name: string): TSESTree.Property | null;
377
+ export declare function findCreateElementProp(context: RuleContext, call: CreateElementCall | null, name: string): TSESTree.Property | null;
246
378
  /**
247
- * Check if the node is passed as a children argument (the third argument or
248
- * later) of a `createElement` call.
379
+ * Check if the node itself is passed as a children argument (the third argument
380
+ * or later) of a `createElement` call. Contiguous TypeScript type-expression
381
+ * ancestors are skipped, and the node is unwrapped before the comparison;
382
+ * expressions nested inside an argument are not considered.
249
383
  * @param context The ESLint rule context.
250
- * @param node The node to check.
384
+ * @param node The node to check; nullish values return `false`.
251
385
  * @returns `true` if the node is a direct children argument of a `createElement` call.
252
386
  */
253
- export declare function isCreateElementChildrenArgument(context: RuleContext, node: TSESTree.Node): boolean;
387
+ export declare function isCreateElementChildrenArgument(context: RuleContext, node: TSESTree.Node | null | undefined): boolean;
254
388
  /**
255
- * Check if the node is directly inside the props object (the second argument) of a `createElement` call,
256
- * that is, its closest `ObjectExpression` ancestor is the props object itself. Nodes nested deeper
257
- * (ex: inside an object nested in the props object) are not considered inside.
389
+ * Check if the node's closest `ObjectExpression` ancestor is the props object
390
+ * (the second argument) of its nearest enclosing `createElement` call. The
391
+ * second argument is unwrapped when it is a type or chain expression. Nodes that
392
+ * cross another object literal (ex: a value inside an object nested in the props
393
+ * object) are not considered inside.
258
394
  * @param context The ESLint rule context.
259
- * @param node The node to check.
260
- * @returns `true` if the node is directly inside `createElement`'s props object.
395
+ * @param node The node to check; nullish values return `false`.
396
+ * @returns `true` if the node's closest object literal is `createElement`'s props object.
261
397
  */
262
- export declare function isInsideCreateElementProps(context: RuleContext, node: TSESTree.Node): boolean;
398
+ export declare function isInsideCreateElementProps(context: RuleContext, node: TSESTree.Node | null | undefined): boolean;
263
399
  /**
264
- * A test that determines whether a JSX element matches.
400
+ * A test that determines whether a JSX element or fragment matches.
265
401
  *
266
- * - `string` matches against the full element type (ex: "div", "React.Fragment")
267
- * - `string[]` matches when the element type equals any of the given strings
268
- * - `function` receives the element type string and returns a boolean.
269
- */
270
- type ElementTest = string | readonly string[] | ((elementType: string, node: TSESTreeJSXElementLike) => boolean);
271
- /**
272
- * Check if the node is a `JSXElement` (or `JSXFragment`), optionally matching a given test.
402
+ * - `string` matches the full element type (ex: "div", "React.Fragment"; a
403
+ * fragment has type `""`)
404
+ * - `readonly string[]` matches when the full element type equals any entry
405
+ * - `function` receives the full element type string and the element or fragment node.
273
406
  *
274
- * Modelled after [`hast-util-is-element`](https://github.com/syntax-tree/hast-util-is-element):
275
- * the `test` parameter controls what counts as a match. When called without a test,
276
- * the function acts as a simple type guard for `JSXElement | JSXFragment`.
277
- * @param node The node to check.
278
- * @param test Optional test to match the element type against.
279
- * @returns `true` if the node is a matching JSX element.
407
+ * The function form receives `(elementType, node)`; this order is intentional:
408
+ * the element type is the primary subject of the test.
280
409
  */
281
- export declare function isElement(node: TSESTree.Node | null | undefined, test?: ElementTest): node is TSESTreeJSXElementLike;
282
- /**
283
- * Check if the node is a React Fragment element.
284
- *
285
- * Recognizes both the shorthand `<>...</>` syntax (`JSXFragment`) and the explicit
286
- * `<Fragment>` / `<React.Fragment>` form (`JSXElement`). The comparison is performed
287
- * against the self name (last dot-separated segment) of both the node and the
288
- * configured factory, so `<React.Fragment>` matches `"React.Fragment"` and
289
- * `<Fragment>` matches `"Fragment"`.
290
- *
291
- * The factory is a required parameter (no implicit `"React.Fragment"` default) so
292
- * that callers always pass the project-configured pragma — see `getJSXConfig` in
293
- * `@eslint-react/core` — and cannot silently use the wrong factory under a custom
294
- * JSX runtime (ex: Preact). Note the self-name comparison is a heuristic: any
295
- * `<*.Fragment>` member expression matches, regardless of the qualifier.
296
- * @param node The node to check.
297
- * @param jsxFragmentFactory The configured fragment factory string (ex: "React.Fragment").
298
- * @returns `true` if the node represents a React Fragment.
299
- */
300
- export declare function isFragmentElement(node: TSESTree.Node, jsxFragmentFactory: string): node is TSESTreeJSXElementLike;
301
- /**
302
- * Check if the node is a host (intrinsic / DOM) element, that is, a `JSXElement`
303
- * whose tag name starts with a lowercase letter (ex: `<div>` vs `<MyComponent>`).
304
- * For namespaced names, the local part is checked (ex: `rect` in `<svg:rect>`).
305
- * @param node The node to check.
306
- * @returns `true` if the node is a `JSXElement` with a lowercase tag name.
307
- */
308
- export declare function isHostElement(node: TSESTree.Node): node is TSESTree.JSXElement;
410
+ type ElementTest = string | readonly string[] | ((elementType: string, node: TSESTreeJSXElementLike) => boolean);
309
411
  /**
310
- * Get the string representation of a JSX element's type.
412
+ * Get the string representation of a JSX element or fragment's type.
311
413
  *
312
414
  * - `<div>` -> `"div"`
313
415
  * - `<Foo.Bar>` -> `"Foo.Bar"`
@@ -319,64 +421,87 @@ export declare function isHostElement(node: TSESTree.Node): node is TSESTree.JSX
319
421
  */
320
422
  export declare function getElementFullType(node: TSESTreeJSXElementLike): string;
321
423
  /**
322
- * Get the self name (last dot-separated segment) of a JSX element type.
424
+ * Get the self name (last dot-separated segment) of a JSX element or fragment type.
323
425
  *
324
426
  * - `<Foo.Bar.Baz>` -> `"Baz"`
325
427
  * - `<div>` -> `"div"`
428
+ * - `<xml:space>` -> `"xml:space"` (only `.` separates segments, not `:`)
326
429
  * - `<></>` -> `""`
327
430
  * @param node The `JSXElement` or `JSXFragment` node.
328
- * @returns The last segment of the element type, or `""` for fragments.
431
+ * @returns The last dot-separated segment of the element type, or `""` for fragments.
329
432
  */
330
433
  export declare function getElementSelfType(node: TSESTreeJSXElementLike): string;
331
434
  /**
332
- * Collapse a multiline JSX text string following React's whitespace rules.
333
- *
334
- * Mirrors Babel's `cleanJSXElementLiteralChild` algorithm:
335
- * 1. Split the raw text into lines.
336
- * 2. Find the last non-empty line.
337
- * 3. Collapse tabs into spaces.
338
- * 4. Trim leading spaces on non-first lines and trailing spaces on non-last lines.
339
- * 5. Append a single space after each non-last non-empty line.
340
- * @param text The raw JSX text string to collapse.
341
- * @returns The collapsed string, or `null` when the text contains only whitespace.
342
- * @see https://github.com/babel/babel/blob/main/packages/babel-types/src/utils/react/cleanJSXElementLiteralChild.ts
435
+ * Check if the node is a `JSXElement` or `JSXFragment`.
436
+ * @param node The node to check.
437
+ * @returns `true` if the node is a JSX element or fragment.
343
438
  */
344
- export declare function collapseMultilineText(text: string): string | null;
439
+ export declare function isElement(node: TSESTree.Node | null | undefined): node is TSESTreeJSXElementLike;
345
440
  /**
346
- * Check if the node is whitespace padding that React would trim away during
347
- * rendering, that is, a `JSXText` node that cleans to nothing (see
348
- * {@link collapseMultilineText}) and contains a newline.
349
- *
350
- * For the looser "any whitespace-only text" check, see {@link isWhitespaceText}.
441
+ * Check if the node is a `JSXElement` or `JSXFragment` matching the given test.
351
442
  *
352
- * Reads the entity-decoded `node.value`; `value` and `raw` differ only when the
353
- * text contains HTML entities (ex: `&nbsp;`), which is never whitespace-only,
354
- * so reading either field yields the same result here.
355
- * @param node The JSX child node to check.
356
- * @returns `true` if the node is purely formatting whitespace.
443
+ * Modelled after [`hast-util-is-element`](https://github.com/syntax-tree/hast-util-is-element):
444
+ * the `test` parameter controls what counts as a match.
445
+ * @param node The node to check.
446
+ * @param test Test to match the full element type against.
447
+ * @returns `true` if the node is a matching JSX element or fragment.
448
+ * @remarks
449
+ * This is a match predicate, not a type guard: a `false` result does not mean
450
+ * the node is not a JSX element or fragment, only that it does not match the test.
357
451
  */
358
- export declare function isPaddingWhitespace(node: TSESTree.JSXChild): boolean;
452
+ export declare function isElement(node: TSESTree.Node | null | undefined, test: ElementTest): boolean;
359
453
  /**
360
- * Check if the node is whitespace-only text.
454
+ * Check if the node is a React Fragment element.
361
455
  *
362
- * Looser variant of {@link isPaddingWhitespace}; matches every `JSXText` node
363
- * whose raw content is empty after trimming, regardless of newlines.
456
+ * Recognizes the shorthand `<>...</>` syntax (`JSXFragment`) and the explicit
457
+ * `<Fragment>` / `<React.Fragment>` form (`JSXElement`). Matching compares only
458
+ * the last dot-separated segment, so with the usual `"React.Fragment"` factory
459
+ * both `<React.Fragment>` and `<Fragment>` match.
364
460
  *
365
- * Reads `node.raw` rather than the entity-decoded `value`; for whitespace-only
366
- * text the two are identical (an entity is never whitespace), matching React's
367
- * behavior of rendering entity text like `&nbsp;` as a real text node.
368
- * @param node The JSX child node to check.
369
- * @returns `true` if the node is a whitespace-only `JSXText`.
461
+ * The factory is a required parameter (no implicit `"React.Fragment"` default) so
462
+ * that callers always pass the project-configured pragma — see `getJSXConfig` in
463
+ * `@eslint-react/core` — and cannot silently use the wrong factory under a custom
464
+ * JSX runtime (ex: Preact). Note the self-name comparison is a heuristic: any
465
+ * `<*.Fragment>` member expression matches, regardless of the qualifier.
466
+ * @param node The node to check.
467
+ * @param jsxFragmentFactory The configured fragment factory string (ex: "React.Fragment");
468
+ * only its last dot-separated segment is compared.
469
+ * @returns `true` if the node is a `JSXFragment` or its element type's self name matches the configured fragment self name.
470
+ * @remarks
471
+ * This is a match predicate, not a type guard: a `false` result does not mean
472
+ * the node is not a JSX element or fragment.
473
+ */
474
+ export declare function isFragmentElement(node: TSESTree.Node | null | undefined, jsxFragmentFactory: string): boolean;
475
+ /**
476
+ * Check if the node is a host (intrinsic / DOM) element, that is, a `JSXElement`
477
+ * whose tag name starts with an ASCII lowercase letter (ex: `<div>` vs
478
+ * `<MyComponent>`). For namespaced names, the local part is checked (ex: `rect`
479
+ * in `<svg:rect>`). Member-expression names (ex: `<foo.Bar>`) are not host elements.
480
+ * @param node The node to check.
481
+ * @returns `true` if the node is a `JSXElement` with a plain or namespaced tag
482
+ * name starting with an ASCII lowercase letter.
483
+ * @remarks
484
+ * This is a match predicate, not a type guard: a `false` result does not mean
485
+ * the node is not a `JSXElement`; custom components are also JSX elements.
370
486
  */
371
- export declare function isWhitespaceText(node: TSESTree.JSXChild): boolean;
487
+ export declare function isHostElement(node: TSESTree.Node | null | undefined): boolean;
372
488
  /**
373
- * Check if the node is an empty string expression (`{""}`).
489
+ * Collapse a JSX text string using Babel's `cleanJSXElementLiteralChild`
490
+ * whitespace rules.
374
491
  *
375
- * React's reconciler and SSR renderer explicitly skip empty strings, producing no
376
- * DOM node, so such expressions are treated as non-rendered children, same as
377
- * whitespace padding.
378
- * @param node The JSX child node to check.
379
- * @returns `true` if the node is a `{""}` expression container.
492
+ * 1. Split the input on CRLF, LF, or CR.
493
+ * 2. Track the last line containing a character other than a space or tab,
494
+ * defaulting to the first line when there is none.
495
+ * 3. Replace each tab with a space.
496
+ * 4. Remove leading spaces from non-first lines and trailing spaces from
497
+ * non-last physical lines.
498
+ * 5. Append a single space after each line that still has content, except the
499
+ * last tracked line.
500
+ * @param text The JSX text string to collapse (typically a decoded `JSXText.value`).
501
+ * @returns The collapsed string, or `null` when the collapsed result is empty
502
+ * (for example, for empty input or multiline input containing only spaces, tabs,
503
+ * and line breaks).
504
+ * @see https://github.com/babel/babel/blob/main/packages/babel-types/src/utils/react/cleanJSXElementLiteralChild.ts
380
505
  */
381
- export declare function isEmptyStringExpression(node: TSESTree.JSXChild): boolean;
382
- export type { AttributeValue, ElementTest };
506
+ export declare function collapseMultilineText(text: string): string | null;
507
+ export type { AttributeTest, AttributeValue, CreateElementCall, ElementTest };
package/dist/index.js CHANGED
@@ -1,9 +1,7 @@
1
1
  import { Check, Extract, Traverse } from "@eslint-react/ast";
2
- import { resolve } from "@eslint-react/var";
3
2
  import { AST_NODE_TYPES } from "@typescript-eslint/types";
4
3
  import { getStaticValue } from "@typescript-eslint/utils/ast-utils";
5
4
  import { getText } from "@eslint-react/eslint";
6
- import { P, match } from "ts-pattern";
7
5
  // ../../.pkgs/eff/dist/index.js
8
6
  const pipeArguments = (self, args) => {
9
7
  switch (args.length) {
@@ -68,12 +66,15 @@ const absurd = (_) => {
68
66
  };
69
67
  cast(absurd);
70
68
  dual(2, (a, b) => (data) => a(data) && b(data));
71
- const or = dual(2, (a, b) => (data) => a(data) || b(data));
69
+ dual(2, (a, b) => (data) => a(data) || b(data));
72
70
  dual(2, (a, b) => (data) => a(data) !== b(data));
73
71
  dual(2, (a, b) => (data) => a(data) === b(data));
74
72
  dual(2, (antecedent, consequent) => (data) => !antecedent(data) || consequent(data));
75
73
  dual(2, (a, b) => (data) => !a(data) && !b(data));
76
74
  dual(2, (a, b) => (data) => !a(data) || !b(data));
75
+ function isString(input) {
76
+ return typeof input === "string";
77
+ }
77
78
  function isFunction(input) {
78
79
  return typeof input === "function";
79
80
  }
@@ -95,148 +96,105 @@ dual(2, (self, predicate) => {
95
96
  while (idx < len && predicate(input[idx], idx)) idx++;
96
97
  return input.slice(0, idx);
97
98
  });
98
- // src/attribute-name.ts
99
+ // src/attribute.ts
99
100
  function getAttributeName(node) {
100
- if (node.name.type === AST_NODE_TYPES.JSXIdentifier) return node.name.name;
101
- return node.name.namespace.name + ":" + node.name.name.name;
101
+ return Extract.getJSXName(node.name);
102
102
  }
103
- const isAttribute = dual(2, (node, name) => {
104
- return node.type === AST_NODE_TYPES.JSXAttribute && node.name.type === AST_NODE_TYPES.JSXIdentifier && node.name.name === name;
103
+ const isPlainAttribute = dual(2, (node, name) => {
104
+ return node?.type === AST_NODE_TYPES.JSXAttribute && node.name.type === AST_NODE_TYPES.JSXIdentifier && node.name.name === name;
105
105
  });
106
- // src/attribute-find.ts
107
- function findAttribute(context, element, name) {
108
- return element.openingElement.attributes.findLast((attr) => {
109
- if (attr.type === AST_NODE_TYPES.JSXAttribute) return getAttributeName(attr) === name;
110
- return findSpreadProperty(context, attr.argument, name) != null;
111
- });
112
- }
113
- function findParentAttribute(node, test = () => true) {
114
- const guard = (n) => {
115
- return n.type === AST_NODE_TYPES.JSXAttribute && test(n);
116
- };
117
- return Traverse.findParent(node, guard) ?? void 0;
118
- }
119
- function findSpreadProperty(context, argument, name, seen = /* @__PURE__ */ new Set()) {
120
- let objectExpression;
121
- if (Check.isIdentifier(argument)) {
122
- let initNode = resolve(context, argument);
123
- while (initNode != null && Check.isIdentifier(initNode) && !seen.has(initNode)) {
124
- seen.add(initNode);
125
- initNode = resolve(context, initNode);
126
- }
127
- if (initNode?.type === AST_NODE_TYPES.ObjectExpression) objectExpression = initNode;
128
- } else if (argument.type === AST_NODE_TYPES.ObjectExpression) objectExpression = argument;
129
- if (objectExpression == null || seen.has(objectExpression)) return void 0;
130
- seen.add(objectExpression);
131
- const { properties } = objectExpression;
132
- for (let i = properties.length - 1; i >= 0; i--) {
133
- const property = properties[i];
134
- if (property == null) continue;
135
- if (property.type === AST_NODE_TYPES.Property) {
136
- const { key } = property;
137
- if (property.computed) {
138
- const keyScope = context.sourceCode.getScope(key);
139
- if (getStaticValue(key, keyScope)?.value === name) return property;
140
- continue;
141
- }
142
- if (Check.isIdentifier(key, name)) return property;
143
- if (key.type === AST_NODE_TYPES.Literal && key.value === name) return property;
144
- continue;
145
- }
146
- const found = findSpreadProperty(context, property.argument, name, seen);
147
- if (found != null) return found;
106
+ const isAttributeNamed = dual(2, (node, name) => {
107
+ return node?.type === AST_NODE_TYPES.JSXAttribute && getAttributeName(node) === name;
108
+ });
109
+ function findAttribute(element, name) {
110
+ const { attributes } = element.openingElement;
111
+ for (let i = attributes.length - 1; i >= 0; i--) {
112
+ const attribute = attributes[i];
113
+ if (attribute?.type === AST_NODE_TYPES.JSXAttribute && isAttributeNamed(attribute, name)) return attribute;
148
114
  }
115
+ return null;
149
116
  }
150
- // src/attribute-has.ts
151
- function hasAttribute(context, element, name) {
152
- return findAttribute(context, element, name) != null;
153
- }
154
- function hasAnyAttribute(context, element, names) {
155
- return names.some((name) => findAttribute(context, element, name) != null);
156
- }
157
- function hasEveryAttribute(context, element, names) {
158
- return names.every((name) => findAttribute(context, element, name) != null);
117
+ function findParentAttribute(node, test) {
118
+ if (node == null) return null;
119
+ const predicate = test == null ? () => true : typeof test === "function" ? test : isAttributeNamed(test);
120
+ const guard = (n) => {
121
+ return n.type === AST_NODE_TYPES.JSXAttribute && predicate(n);
122
+ };
123
+ return Traverse.findParent(node, guard);
159
124
  }
160
- // src/attribute-value.ts
161
- function resolveAttributeValue(context, attribute, name) {
162
- if (attribute.type === AST_NODE_TYPES.JSXAttribute) return resolveJSXAttribute(context, attribute);
163
- return resolveJSXSpreadAttribute(context, attribute, name);
125
+ function hasAttribute(element, name) {
126
+ return findAttribute(element, name) != null;
164
127
  }
165
- function getAttributeValue(context, element, name) {
166
- const attr = findAttribute(context, element, name);
167
- if (attr == null) return void 0;
168
- return resolveAttributeValue(context, attr, name);
128
+ function hasAnyAttribute(element, names) {
129
+ if (names.length === 0) return false;
130
+ return element.openingElement.attributes.some((a) => a.type === AST_NODE_TYPES.JSXAttribute && names.includes(getAttributeName(a)));
169
131
  }
170
- function getAttributeStaticValue(context, element, name) {
171
- return getAttributeValue(context, element, name)?.toStatic();
132
+ function hasEveryAttribute(element, names) {
133
+ if (names.length === 0) return true;
134
+ const remaining = new Set(names);
135
+ for (const attribute of element.openingElement.attributes) {
136
+ if (attribute.type === AST_NODE_TYPES.JSXAttribute) remaining.delete(getAttributeName(attribute));
137
+ if (remaining.size === 0) return true;
138
+ }
139
+ return false;
172
140
  }
173
- function resolveJSXAttribute(context, node) {
174
- const scope = context.sourceCode.getScope(node);
175
- if (node.value == null) return {
141
+ function getAttributeValue(attribute) {
142
+ const { value } = attribute;
143
+ if (value == null) return {
176
144
  kind: "boolean",
177
- node: null,
178
- toStatic() {
179
- return true;
180
- }
145
+ attribute,
146
+ node: null
181
147
  };
182
- switch (node.value.type) {
183
- case AST_NODE_TYPES.Literal: {
184
- const staticValue = node.value.value;
185
- return {
186
- kind: "literal",
187
- node: node.value,
188
- toStatic() {
189
- return staticValue;
190
- }
191
- };
192
- }
193
- case AST_NODE_TYPES.JSXExpressionContainer: {
194
- const expr = node.value.expression;
195
- if (expr.type === AST_NODE_TYPES.JSXEmptyExpression) return {
148
+ switch (value.type) {
149
+ case AST_NODE_TYPES.Literal: return {
150
+ kind: "literal",
151
+ attribute,
152
+ node: value
153
+ };
154
+ case AST_NODE_TYPES.JSXExpressionContainer:
155
+ if (value.expression.type === AST_NODE_TYPES.JSXEmptyExpression) return {
196
156
  kind: "missing",
197
- node: expr,
198
- toStatic() {}
157
+ attribute,
158
+ node: value.expression
199
159
  };
200
160
  return {
201
161
  kind: "unknown",
202
- node: expr,
203
- toStatic() {
204
- return getStaticValue(expr, scope)?.value;
205
- }
162
+ attribute,
163
+ node: value.expression
206
164
  };
207
- }
208
- case AST_NODE_TYPES.JSXElement: return {
209
- kind: "element",
210
- node: node.value,
211
- toStatic() {}
212
- };
165
+ case AST_NODE_TYPES.JSXElement:
213
166
  case AST_NODE_TYPES.JSXFragment: return {
214
167
  kind: "element",
215
- node: node.value,
216
- toStatic() {}
168
+ attribute,
169
+ node: value
217
170
  };
218
- case AST_NODE_TYPES.JSXSpreadChild: return {
219
- kind: "spreadChild",
220
- node: node.value,
221
- toStatic() {}
171
+ case AST_NODE_TYPES.JSXSpreadChild: return value.expression.type === AST_NODE_TYPES.JSXEmptyExpression ? {
172
+ kind: "missing",
173
+ attribute,
174
+ node: value.expression
175
+ } : {
176
+ kind: "unknown",
177
+ attribute,
178
+ node: value.expression
222
179
  };
223
180
  }
224
181
  }
225
- function resolveJSXSpreadAttribute(context, node, name) {
226
- const getProperty = (propertyName) => {
227
- const property = findSpreadProperty(context, node.argument, propertyName);
228
- if (property == null) return void 0;
229
- const propertyScope = context.sourceCode.getScope(property.value);
230
- return getStaticValue(property.value, propertyScope)?.value;
231
- };
232
- return {
233
- kind: "spreadProps",
234
- getProperty,
235
- node: node.argument,
236
- toStatic() {
237
- return name == null ? void 0 : getProperty(name);
238
- }
239
- };
182
+ function getAttributeValueByName(element, name) {
183
+ const attribute = findAttribute(element, name);
184
+ return attribute == null ? null : getAttributeValue(attribute);
185
+ }
186
+ function getAttributeStaticValue(context, value) {
187
+ if (value == null) return void 0;
188
+ switch (value.kind) {
189
+ case "boolean": return true;
190
+ case "literal": return value.node.value;
191
+ case "unknown": return getStaticValue(value.node, context.sourceCode.getScope(value.node))?.value;
192
+ case "element":
193
+ case "missing": return;
194
+ }
195
+ }
196
+ function getAttributeStaticValueByName(context, element, name) {
197
+ return getAttributeStaticValue(context, getAttributeValueByName(element, name));
240
198
  }
241
199
  // src/text.ts
242
200
  function collapseMultilineText(text) {
@@ -259,38 +217,30 @@ function collapseMultilineText(text) {
259
217
  }
260
218
  return str === "" ? null : str;
261
219
  }
262
- function isPaddingWhitespace(node) {
263
- if (node.type !== AST_NODE_TYPES.JSXText) return false;
264
- return collapseMultilineText(node.value) == null && node.value.includes("\n");
265
- }
220
+ // src/children.ts
266
221
  function isWhitespaceText(node) {
267
- if (node.type !== AST_NODE_TYPES.JSXText) return false;
268
- return node.raw.trim() === "";
222
+ return node?.type === AST_NODE_TYPES.JSXText && node.raw.trim() === "";
223
+ }
224
+ function isPaddingWhitespace(node) {
225
+ return node?.type === AST_NODE_TYPES.JSXText && collapseMultilineText(node.value) == null && node.value.includes("\n");
269
226
  }
270
227
  function isEmptyExpressionContainer(node) {
271
- if (node.type !== AST_NODE_TYPES.JSXExpressionContainer) return false;
272
- return node.expression.type === AST_NODE_TYPES.JSXEmptyExpression;
228
+ return node?.type === AST_NODE_TYPES.JSXExpressionContainer && node.expression.type === AST_NODE_TYPES.JSXEmptyExpression;
273
229
  }
274
230
  function isEmptyStringExpression(node) {
275
- if (node.type !== AST_NODE_TYPES.JSXExpressionContainer) return false;
276
- const expr = node.expression;
277
- if (expr.type !== AST_NODE_TYPES.Literal) return false;
278
- return expr.value === "";
231
+ return node?.type === AST_NODE_TYPES.JSXExpressionContainer && node.expression.type === AST_NODE_TYPES.Literal && node.expression.value === "";
232
+ }
233
+ function isMeaningfulChild(node) {
234
+ return !isWhitespaceText(node) && !isEmptyExpressionContainer(node) && !isEmptyStringExpression(node);
279
235
  }
280
- // src/children.ts
281
236
  function getChildren(element) {
282
- const children = [];
283
- for (const child of element.children) {
284
- if (isPaddingWhitespace(child)) continue;
285
- if (isEmptyExpressionContainer(child)) continue;
286
- if (isEmptyStringExpression(child)) continue;
287
- children.push(child);
288
- }
289
- return children;
237
+ return element.children.filter((child) => !isPaddingWhitespace(child) && !isEmptyExpressionContainer(child) && !isEmptyStringExpression(child));
290
238
  }
291
- function hasChildren(element) {
292
- if (element.children.length === 0) return false;
293
- return !element.children.every(or(or(isWhitespaceText, isEmptyExpressionContainer), isEmptyStringExpression));
239
+ function getMeaningfulChildren(element) {
240
+ return element.children.filter(isMeaningfulChild);
241
+ }
242
+ function hasMeaningfulChildren(element) {
243
+ return element.children.some(isMeaningfulChild);
294
244
  }
295
245
  // src/create-element.ts
296
246
  function isCreateElementCall(context, node) {
@@ -298,33 +248,42 @@ function isCreateElementCall(context, node) {
298
248
  const name = Extract.getFullyQualifiedName(Extract.unwrap(node.callee), getText(context));
299
249
  return name === "createElement" || name.endsWith(".createElement");
300
250
  }
301
- function getCreateElementTypeArgument(context, node) {
302
- if (!isCreateElementCall(context, node)) return null;
303
- return node.arguments[0] ?? null;
304
- }
305
- function getCreateElementPropsObject(context, node) {
306
- if (!isCreateElementCall(context, node)) return null;
307
- const propsArg = node.arguments[1];
308
- if (propsArg == null) return null;
309
- const expr = Extract.unwrap(propsArg);
310
- return expr.type === AST_NODE_TYPES.ObjectExpression ? expr : null;
311
- }
312
- function getCreateElementChildrenArguments(context, node) {
313
- if (!isCreateElementCall(context, node)) return [];
314
- return node.arguments.slice(2);
315
- }
316
- function getCreateElementProp(context, node, name) {
317
- const propsObject = getCreateElementPropsObject(context, node);
318
- if (propsObject == null) return null;
319
- for (const prop of propsObject.properties) if (prop.type === AST_NODE_TYPES.Property && Extract.getPropertyName(prop, "max") === name) return prop;
251
+ function parseCreateElementCall(context, node) {
252
+ if (node?.type !== AST_NODE_TYPES.CallExpression || !isCreateElementCall(context, node)) return null;
253
+ const propsArgument = node.arguments[1] ?? null;
254
+ const propsExpression = propsArgument == null ? null : Extract.unwrap(propsArgument);
255
+ return {
256
+ childrenArguments: node.arguments.slice(2),
257
+ node,
258
+ propsArgument,
259
+ propsObject: propsExpression?.type === AST_NODE_TYPES.ObjectExpression ? propsExpression : null,
260
+ typeArgument: node.arguments[0] ?? null
261
+ };
262
+ }
263
+ function getStaticPropertyName(context, property) {
264
+ if (!property.computed) return Extract.getPropertyName(property, "max");
265
+ const key = Extract.unwrap(property.key);
266
+ const staticValue = getStaticValue(key, context.sourceCode.getScope(key));
267
+ return typeof staticValue?.value === "string" ? staticValue.value : null;
268
+ }
269
+ function findCreateElementProp(context, call, name) {
270
+ if (call?.propsObject == null) return null;
271
+ const { properties } = call.propsObject;
272
+ for (let i = properties.length - 1; i >= 0; i--) {
273
+ const property = properties[i];
274
+ if (property?.type === AST_NODE_TYPES.Property && getStaticPropertyName(context, property) === name) return property;
275
+ }
320
276
  return null;
321
277
  }
322
278
  function isCreateElementChildrenArgument(context, node) {
279
+ if (node == null) return false;
323
280
  let parent = node.parent;
324
281
  while (Check.isTypeExpression(parent)) parent = parent.parent;
325
- return parent?.type === AST_NODE_TYPES.CallExpression && isCreateElementCall(context, parent) && parent.arguments.slice(2).some((arg) => Extract.unwrap(arg) === Extract.unwrap(node));
282
+ const target = Extract.unwrap(node);
283
+ return parent?.type === AST_NODE_TYPES.CallExpression && isCreateElementCall(context, parent) && parent.arguments.slice(2).some((arg) => Extract.unwrap(arg) === target);
326
284
  }
327
285
  function isInsideCreateElementProps(context, node) {
286
+ if (node == null) return false;
328
287
  const call = Traverse.findParent(node, (parent) => isCreateElementCall(context, parent));
329
288
  if (call == null) return false;
330
289
  const prop = Traverse.findParent(node, Check.isObjectExpression);
@@ -333,40 +292,40 @@ function isInsideCreateElementProps(context, node) {
333
292
  if (propsArg == null) return false;
334
293
  return prop === Extract.unwrap(propsArg);
335
294
  }
336
- // src/element-type.ts
295
+ // src/element.ts
337
296
  function getElementFullType(node) {
338
297
  if (node.type === AST_NODE_TYPES.JSXFragment) return "";
339
- function getQualifiedName(node) {
340
- switch (node.type) {
341
- case AST_NODE_TYPES.JSXIdentifier: return node.name;
342
- case AST_NODE_TYPES.JSXNamespacedName: return node.namespace.name + ":" + node.name.name;
343
- default: return getQualifiedName(node.object) + "." + getQualifiedName(node.property);
344
- }
345
- }
346
- return getQualifiedName(node.openingElement.name);
298
+ return Extract.getJSXName(node.openingElement.name);
299
+ }
300
+ function getSelfName(name) {
301
+ return name.slice(name.lastIndexOf(".") + 1);
347
302
  }
348
303
  function getElementSelfType(node) {
349
- return getElementFullType(node).split(".").at(-1) ?? "";
304
+ return getSelfName(getElementFullType(node));
305
+ }
306
+ function isElementTestFunction(test) {
307
+ return isFunction(test);
350
308
  }
351
- // src/element-is.ts
352
309
  function isElement(node, test) {
353
310
  if (node == null) return false;
354
311
  if (node.type !== AST_NODE_TYPES.JSXElement && node.type !== AST_NODE_TYPES.JSXFragment) return false;
355
312
  if (test == null) return true;
356
313
  const type = getElementFullType(node);
357
- return match(test).with(P.string, (t) => type === t).with(P.array(), (t) => t.includes(type)).with(P.instanceOf(Function), (t) => t(type, node)).exhaustive();
314
+ if (isString(test)) return type === test;
315
+ if (isElementTestFunction(test)) return test(type, node);
316
+ return test.includes(type);
358
317
  }
359
318
  function isFragmentElement(node, jsxFragmentFactory) {
319
+ if (node == null) return false;
360
320
  if (node.type === AST_NODE_TYPES.JSXFragment) return true;
361
321
  if (node.type !== AST_NODE_TYPES.JSXElement) return false;
362
- const fragment = jsxFragmentFactory.split(".").at(-1) ?? "Fragment";
363
- return getElementFullType(node).split(".").at(-1) === fragment;
322
+ return getElementSelfType(node) === getSelfName(jsxFragmentFactory);
364
323
  }
365
324
  function isHostElement(node) {
366
- if (node.type !== AST_NODE_TYPES.JSXElement) return false;
325
+ if (node?.type !== AST_NODE_TYPES.JSXElement) return false;
367
326
  const name = node.openingElement.name;
368
327
  if (name.type === AST_NODE_TYPES.JSXIdentifier) return /^[a-z]/u.test(name.name);
369
328
  if (name.type === AST_NODE_TYPES.JSXNamespacedName) return /^[a-z]/u.test(name.name.name);
370
329
  return false;
371
330
  }
372
- export { collapseMultilineText, findAttribute, findParentAttribute, findSpreadProperty, getAttributeName, getAttributeStaticValue, getAttributeValue, getChildren, getCreateElementChildrenArguments, getCreateElementProp, getCreateElementPropsObject, getCreateElementTypeArgument, getElementFullType, getElementSelfType, hasAnyAttribute, hasAttribute, hasChildren, hasEveryAttribute, isAttribute, isCreateElementChildrenArgument, isElement, isEmptyStringExpression, isFragmentElement, isHostElement, isInsideCreateElementProps, isPaddingWhitespace, isWhitespaceText, resolveAttributeValue };
331
+ export { collapseMultilineText, findAttribute, findCreateElementProp, findParentAttribute, getAttributeName, getAttributeStaticValue, getAttributeStaticValueByName, getAttributeValue, getAttributeValueByName, getChildren, getElementFullType, getElementSelfType, getMeaningfulChildren, hasAnyAttribute, hasAttribute, hasEveryAttribute, hasMeaningfulChildren, isAttributeNamed, isCreateElementCall, isCreateElementChildrenArgument, isElement, isEmptyExpressionContainer, isEmptyStringExpression, isFragmentElement, isHostElement, isInsideCreateElementProps, isMeaningfulChild, isPaddingWhitespace, isPlainAttribute, isWhitespaceText, parseCreateElementCall };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eslint-react/jsx",
3
- "version": "5.30.0-beta.5",
3
+ "version": "5.30.0-beta.6",
4
4
  "description": "ESLint React's TSESTree JSX utility module for static analysis of JSX patterns.",
5
5
  "homepage": "https://github.com/Rel1cx/eslint-react",
6
6
  "bugs": {
@@ -29,12 +29,10 @@
29
29
  "dist"
30
30
  ],
31
31
  "dependencies": {
32
- "@eslint-react/ast": "5.30.0-beta.5",
33
- "@eslint-react/eslint": "5.30.0-beta.5",
34
- "@eslint-react/var": "5.30.0-beta.5",
32
+ "@eslint-react/ast": "5.30.0-beta.6",
33
+ "@eslint-react/eslint": "5.30.0-beta.6",
35
34
  "@typescript-eslint/types": "^8.72.1",
36
- "@typescript-eslint/utils": "^8.72.1",
37
- "ts-pattern": "^5.9.2"
35
+ "@typescript-eslint/utils": "^8.72.1"
38
36
  },
39
37
  "devDependencies": {
40
38
  "@local/configs": "0.0.0",