@murky-web/oxlint-plugin-solid 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,237 @@
1
+ import { findVariable } from "../compat.mjs";
2
+ import {
3
+ isFunctionNode,
4
+ isPropsByName,
5
+ trackImports,
6
+ walkOwnBody,
7
+ } from "../utils.mjs";
8
+
9
+ /**
10
+ * Primitives whose first argument, when it is a function, is a reactive
11
+ * computation. Solid 2.0 reads a promise returned from one like a value, so
12
+ * the callback needs no `async` to be asynchronous.
13
+ */
14
+ const COMPUTATION_PRIMITIVES = [
15
+ "createMemo",
16
+ "createOptimistic",
17
+ "createOptimisticStore",
18
+ "createProjection",
19
+ "createSignal",
20
+ "createStore",
21
+ ];
22
+
23
+ /** The two-argument effects: the first function is the tracked compute phase. */
24
+ const EFFECT_PRIMITIVES = ["createEffect", "createRenderEffect"];
25
+
26
+ /** Primitives whose result is called to read it: `value()`. */
27
+ const ACCESSOR_PRIMITIVES = ["createMemo", "createOptimistic", "createSignal"];
28
+
29
+ /** Primitives whose result is read by property access: `store.items`. */
30
+ const STORE_PRIMITIVES = [
31
+ "createOptimisticStore",
32
+ "createProjection",
33
+ "createStore",
34
+ ];
35
+
36
+ const FIRST_ELEMENT = 0;
37
+
38
+ function getFirstBinding(declarator) {
39
+ if (declarator.id.type === "ArrayPattern") {
40
+ const element = declarator.id.elements[FIRST_ELEMENT];
41
+
42
+ return element?.type === "Identifier" ? element : null;
43
+ }
44
+
45
+ return declarator.id.type === "Identifier" ? declarator.id : null;
46
+ }
47
+
48
+ function getStart(node) {
49
+ return node.range?.[0] ?? node.start;
50
+ }
51
+
52
+ function getEnd(node) {
53
+ return node.range?.[1] ?? node.end;
54
+ }
55
+
56
+ function isInsideTry(node, callback) {
57
+ let current = node.parent;
58
+
59
+ while (current && current !== callback) {
60
+ if (current.type === "TryStatement") {
61
+ return true;
62
+ }
63
+
64
+ current = current.parent;
65
+ }
66
+
67
+ return false;
68
+ }
69
+
70
+ /** `return await x` or `async () => await x`, and nothing else awaited. */
71
+ function isOnlyReturnAwait(callback, awaits) {
72
+ if (awaits.length !== 1) {
73
+ return false;
74
+ }
75
+
76
+ const [only] = awaits;
77
+ if (callback.body === only) {
78
+ return true;
79
+ }
80
+
81
+ // Inside `try`, `return await` is what makes the catch see a rejection.
82
+ return only.parent?.type === "ReturnStatement" && !isInsideTry(only, callback);
83
+ }
84
+
85
+ export const reactiveAsyncRule = {
86
+ meta: {
87
+ type: "problem",
88
+ docs: {
89
+ description:
90
+ "Keep reads before the first await in async reactive computations and return promises without async.",
91
+ url: "https://docs.solidjs.com/",
92
+ },
93
+ schema: [],
94
+ messages: {
95
+ untrackedReadAfterAwait:
96
+ "'{{name}}' is read after an `await` in this `{{primitive}}` callback. Solid reports this as UNTRACKED_READ_AFTER_AWAIT: only reads before the first `await` are dependencies, so the result goes stale when it changes. Read it before the `await` and use the local afterwards: `const current = {{name}}; … await …`.",
97
+ redundantAsync:
98
+ "This `async` `{{primitive}}` callback only does `return await …`. Solid reads a returned promise like a value, so remove `async` and `await` and return the promise: `{{primitive}}(() => load(id()))`.",
99
+ },
100
+ },
101
+ defaultOptions: [],
102
+ create(context) {
103
+ const { matchImport, handleImportDeclaration } = trackImports();
104
+ // Identifier nodes that declare a reactive value, by what reading it
105
+ // looks like. Lookup goes through the scope, so a shadowing local with
106
+ // the same name is not mistaken for the signal.
107
+ const accessors = new Set();
108
+ const stores = new Set();
109
+
110
+ function bindingKind(identifier) {
111
+ const definition = findVariable(context, identifier)?.defs[0];
112
+ const declared = definition?.name;
113
+ if (accessors.has(declared)) {
114
+ return "accessor";
115
+ }
116
+
117
+ return stores.has(declared) ? "store" : null;
118
+ }
119
+
120
+ function readName(candidate) {
121
+ if (
122
+ candidate.type === "CallExpression" &&
123
+ candidate.callee.type === "Identifier" &&
124
+ bindingKind(candidate.callee) === "accessor"
125
+ ) {
126
+ return candidate.callee.name;
127
+ }
128
+
129
+ if (
130
+ candidate.type === "MemberExpression" &&
131
+ candidate.object.type === "Identifier" &&
132
+ candidate.property.type === "Identifier" &&
133
+ !candidate.computed
134
+ ) {
135
+ const { name } = candidate.object;
136
+ if (
137
+ isPropsByName(name) ||
138
+ bindingKind(candidate.object) === "store"
139
+ ) {
140
+ return `${name}.${candidate.property.name}`;
141
+ }
142
+ }
143
+
144
+ return null;
145
+ }
146
+
147
+ function checkCallback(callback, primitive) {
148
+ const awaits = [];
149
+ const reads = [];
150
+
151
+ walkOwnBody(callback.body, (candidate) => {
152
+ if (candidate.type === "AwaitExpression") {
153
+ awaits.push(candidate);
154
+ }
155
+
156
+ const name = readName(candidate);
157
+ if (name !== null) {
158
+ reads.push({ name, node: candidate });
159
+ }
160
+ });
161
+
162
+ if (awaits.length === 0) {
163
+ return;
164
+ }
165
+
166
+ if (callback.async === true && isOnlyReturnAwait(callback, awaits)) {
167
+ context.report({
168
+ node: callback,
169
+ messageId: "redundantAsync",
170
+ data: { primitive },
171
+ });
172
+ }
173
+
174
+ // A read inside the awaited expression itself still runs before the
175
+ // await suspends, so the boundary is where the first await ends.
176
+ const firstAwaitEnd = Math.min(...awaits.map(getEnd));
177
+ for (const read of reads) {
178
+ if (getStart(read.node) >= firstAwaitEnd) {
179
+ context.report({
180
+ node: read.node,
181
+ messageId: "untrackedReadAfterAwait",
182
+ data: { name: read.name, primitive },
183
+ });
184
+ }
185
+ }
186
+ }
187
+
188
+ return {
189
+ ImportDeclaration: handleImportDeclaration,
190
+ VariableDeclarator(node) {
191
+ if (
192
+ node.init?.type !== "CallExpression" ||
193
+ node.init.callee.type !== "Identifier"
194
+ ) {
195
+ return;
196
+ }
197
+
198
+ const binding = getFirstBinding(node);
199
+ if (!binding) {
200
+ return;
201
+ }
202
+
203
+ const callee = node.init.callee.name;
204
+ if (matchImport(ACCESSOR_PRIMITIVES, callee)) {
205
+ accessors.add(binding);
206
+ } else if (matchImport(STORE_PRIMITIVES, callee)) {
207
+ stores.add(binding);
208
+ }
209
+ },
210
+ CallExpression(node) {
211
+ if (node.callee.type !== "Identifier") {
212
+ return;
213
+ }
214
+
215
+ const [first, second] = node.arguments;
216
+ if (!isFunctionNode(first)) {
217
+ return;
218
+ }
219
+
220
+ const computation = matchImport(
221
+ COMPUTATION_PRIMITIVES,
222
+ node.callee.name,
223
+ );
224
+ if (computation) {
225
+ checkCallback(first, computation);
226
+ return;
227
+ }
228
+
229
+ // A lone function is the whole effect, not a compute phase.
230
+ const effect = matchImport(EFFECT_PRIMITIVES, node.callee.name);
231
+ if (effect && isFunctionNode(second)) {
232
+ checkCallback(first, effect);
233
+ }
234
+ },
235
+ };
236
+ },
237
+ };
@@ -2,7 +2,7 @@
2
2
  * File overview here, scroll to bottom.
3
3
  * @link https://github.com/solidjs-community/eslint-plugin-solid/blob/main/docs/reactivity.md
4
4
  */
5
- import { ESLintUtils, ASTUtils } from "@typescript-eslint/utils";
5
+ import { getFunctionHeadLocation } from "@eslint-community/eslint-utils";
6
6
  import { traverse } from "estraverse";
7
7
 
8
8
  import { findVariable, getSourceCode } from "../compat.mjs";
@@ -19,9 +19,6 @@ import {
19
19
  isJSXElementOrFragment,
20
20
  trace,
21
21
  } from "../utils.mjs";
22
- const { getFunctionHeadLocation } = ASTUtils;
23
- const createRule = ESLintUtils.RuleCreator.withoutDocs;
24
-
25
22
  // Solid 2.0 removed `createResource`, `createMutable`, `indexArray` and
26
23
  // `<Index>`. Their branches below are kept structurally but matched against
27
24
  // `__removed_*` names so they can never fire; delete them once no Solid 1
@@ -174,7 +171,7 @@ const getReturnedVar = (id, context) => {
174
171
  }
175
172
  return null;
176
173
  };
177
- export default createRule({
174
+ export default {
178
175
  meta: {
179
176
  type: "problem",
180
177
  docs: {
@@ -203,7 +200,7 @@ export default createRule({
203
200
  noWrite:
204
201
  "The reactive variable '{{name}}' should not be reassigned or altered directly.",
205
202
  untrackedReactive:
206
- "The reactive variable '{{name}}' should be used within JSX, a tracked scope (like createEffect), or inside an event handler function, or else changes will be ignored.",
203
+ "The reactive variable '{{name}}' should be used within JSX, a tracked scope (like createEffect), or inside an event handler function, or else changes will be ignored. To keep it reactive, derive it rather than copy it: a plain function, `createMemo`, or `createSignal(() => ...)` / `createStore(() => ...)` for a local override that a new source value should replace.",
207
204
  expectedFunctionGotExpression:
208
205
  "The reactive variable '{{name}}' should be wrapped in a function for reactivity. This includes event handler bindings on native elements, which are not reactive like other JSX props.",
209
206
  badSignal:
@@ -223,7 +220,12 @@ export default createRule({
223
220
  customReactiveFunctions: [],
224
221
  },
225
222
  ],
226
- create(context, [options]) {
223
+ create(context) {
224
+ // `RuleCreator` used to merge `defaultOptions` into `context.options`
225
+ // and hand the result to a second `create` parameter. Without that
226
+ // wrapper the parameter is undefined, so the default is applied here.
227
+ const options = context.options[0] ?? { customReactiveFunctions: [] };
228
+
227
229
  const warnShouldDestructure = (node, nth) =>
228
230
  context.report({
229
231
  node,
@@ -1397,4 +1399,4 @@ export default createRule({
1397
1399
  },
1398
1400
  };
1399
1401
  },
1400
- });
1402
+ };
@@ -1,8 +1,5 @@
1
- import { ESLintUtils } from "@typescript-eslint/utils";
2
-
3
1
  import { getSourceCode } from "../compat.mjs";
4
2
  import { isDOMElementName } from "../utils.mjs";
5
- const createRule = ESLintUtils.RuleCreator.withoutDocs;
6
3
  function isComponent(node) {
7
4
  return (
8
5
  (node.name.type === "JSXIdentifier" &&
@@ -31,7 +28,7 @@ function childrenIsMultilineSpaces(node) {
31
28
  * This rule is adapted from eslint-plugin-react's self-closing-comp rule under the MIT license,
32
29
  * with some enhancements. Thank you for your work!
33
30
  */
34
- export default createRule({
31
+ export default {
35
32
  meta: {
36
33
  type: "layout",
37
34
  docs: {
@@ -150,4 +147,4 @@ export default createRule({
150
147
  },
151
148
  };
152
149
  },
153
- });
150
+ };
@@ -0,0 +1,201 @@
1
+ import { isFunctionNode, jsxPropName, trackImports } from "../utils.mjs";
2
+
3
+ const EVENT_HANDLER_NAME = /^on(?::|[A-Z])/;
4
+ const DOM_EVENT_NAME = /^on[a-z]/;
5
+ const DOM_ELEMENT_NAME = /^[a-z]/;
6
+ const CLEANUP_PRIMITIVES = ["onCleanup"];
7
+ const SETTLED_PRIMITIVES = ["onSettled"];
8
+
9
+ /** Values that can never be a cleanup function and are never void. */
10
+ const PLAIN_VALUE_TYPES = new Set([
11
+ "ArrayExpression",
12
+ "AssignmentExpression",
13
+ "BinaryExpression",
14
+ "Literal",
15
+ "ObjectExpression",
16
+ "TemplateLiteral",
17
+ "UpdateExpression",
18
+ ]);
19
+
20
+ function isVoidExpression(expression) {
21
+ return (
22
+ (expression.type === "UnaryExpression" &&
23
+ expression.operator === "void") ||
24
+ (expression.type === "Identifier" && expression.name === "undefined")
25
+ );
26
+ }
27
+
28
+ function describe(expression) {
29
+ return expression.type === "CallExpression"
30
+ ? "the call's result"
31
+ : "its value";
32
+ }
33
+
34
+ /** Every `return <expr>` of a function, without looking into inner ones. */
35
+ function collectReturns(node, into) {
36
+ if (node === null || typeof node !== "object") {
37
+ return;
38
+ }
39
+
40
+ if (node.type === "ReturnStatement" && node.argument) {
41
+ into.push(node.argument);
42
+ }
43
+
44
+ for (const [key, value] of Object.entries(node)) {
45
+ if (key === "parent") {
46
+ continue;
47
+ }
48
+
49
+ const candidates = Array.isArray(value) ? value : [value];
50
+ for (const candidate of candidates) {
51
+ if (
52
+ candidate !== null &&
53
+ typeof candidate === "object" &&
54
+ typeof candidate.type === "string" &&
55
+ !isFunctionNode(candidate)
56
+ ) {
57
+ collectReturns(candidate, into);
58
+ }
59
+ }
60
+ }
61
+ }
62
+
63
+ /** The callbacks a `ref` applies, including the ones in a ref array. */
64
+ function getRefCallbacks(expression) {
65
+ if (isFunctionNode(expression)) {
66
+ return [expression];
67
+ }
68
+
69
+ if (expression?.type === "ArrayExpression") {
70
+ return expression.elements.filter((element) => isFunctionNode(element));
71
+ }
72
+
73
+ return [];
74
+ }
75
+
76
+ export const strictVoidReturnRule = {
77
+ meta: {
78
+ type: "problem",
79
+ docs: {
80
+ description:
81
+ "Disallow returning a value from callbacks Solid ignores the return of (event handlers, ref callbacks, onCleanup, onSettled).",
82
+ url: "https://docs.solidjs.com/",
83
+ },
84
+ schema: [],
85
+ messages: {
86
+ handlerReturnsValue:
87
+ "This `{{attribute}}` callback is an expression-bodied arrow, so it returns {{what}}, which Solid ignores. Write a block body (`() => { … }`) or discard it explicitly with `void …`.",
88
+ cleanupReturnsValue:
89
+ "This `{{primitive}}` callback returns a value, which is ignored. Remove the `return`, or use a block body that does not return.",
90
+ settledReturnsValue:
91
+ "This `onSettled` callback returns a value that is not a function. Only a returned cleanup function is used; remove the `return` or return `() => { … }`.",
92
+ },
93
+ },
94
+ defaultOptions: [],
95
+ create(context) {
96
+ const { matchImport, handleImportDeclaration } = trackImports();
97
+
98
+ function checkHandler(callback, attribute) {
99
+ if (
100
+ !isFunctionNode(callback) ||
101
+ callback.body.type === "BlockStatement" ||
102
+ isVoidExpression(callback.body)
103
+ ) {
104
+ return;
105
+ }
106
+
107
+ context.report({
108
+ node: callback,
109
+ messageId: "handlerReturnsValue",
110
+ data: {
111
+ attribute,
112
+ what: describe(callback.body),
113
+ },
114
+ });
115
+ }
116
+
117
+ function checkCleanup(callback, primitive) {
118
+ const values = [];
119
+ if (callback.body.type === "BlockStatement") {
120
+ collectReturns(callback.body, values);
121
+ } else {
122
+ values.push(callback.body);
123
+ }
124
+
125
+ // A call may well return nothing (`() => clearInterval(id)`); without
126
+ // types only values that are certainly not void are reported.
127
+ if (
128
+ values.some(
129
+ (value) =>
130
+ PLAIN_VALUE_TYPES.has(value.type) &&
131
+ !isVoidExpression(value),
132
+ )
133
+ ) {
134
+ context.report({
135
+ node: callback,
136
+ messageId:
137
+ primitive === "onSettled"
138
+ ? "settledReturnsValue"
139
+ : "cleanupReturnsValue",
140
+ data: { primitive },
141
+ });
142
+ }
143
+ }
144
+
145
+ return {
146
+ ImportDeclaration: handleImportDeclaration,
147
+ JSXAttribute(node) {
148
+ const isForeignNamespace =
149
+ node.name.type === "JSXNamespacedName" &&
150
+ node.name.namespace.name !== "on";
151
+ if (
152
+ node.value?.type !== "JSXExpressionContainer" ||
153
+ isForeignNamespace
154
+ ) {
155
+ return;
156
+ }
157
+
158
+ const name = jsxPropName(node);
159
+ const tagName = node.parent?.name;
160
+ const isDomElement =
161
+ tagName?.type === "JSXIdentifier" &&
162
+ DOM_ELEMENT_NAME.test(tagName.name);
163
+
164
+ if (name === "ref") {
165
+ for (const callback of getRefCallbacks(
166
+ node.value.expression,
167
+ )) {
168
+ checkHandler(callback, "ref");
169
+ }
170
+
171
+ return;
172
+ }
173
+
174
+ if (
175
+ EVENT_HANDLER_NAME.test(name) ||
176
+ (isDomElement && DOM_EVENT_NAME.test(name))
177
+ ) {
178
+ checkHandler(node.value.expression, name);
179
+ }
180
+ },
181
+ CallExpression(node) {
182
+ if (node.callee.type !== "Identifier") {
183
+ return;
184
+ }
185
+
186
+ const [callback] = node.arguments;
187
+ if (!isFunctionNode(callback)) {
188
+ return;
189
+ }
190
+
191
+ const primitive = matchImport(
192
+ [...CLEANUP_PRIMITIVES, ...SETTLED_PRIMITIVES],
193
+ node.callee.name,
194
+ );
195
+ if (primitive) {
196
+ checkCleanup(callback, primitive);
197
+ }
198
+ },
199
+ };
200
+ },
201
+ };
@@ -1,15 +1,13 @@
1
- import { ESLintUtils, ASTUtils } from "@typescript-eslint/utils";
1
+ import { getPropertyName, getStaticValue } from "@eslint-community/eslint-utils";
2
2
  import kebabCase from "kebab-case";
3
3
  import { all as allCssProperties } from "known-css-properties";
4
4
  import parse from "style-to-object";
5
5
 
6
6
  import { getScope } from "../compat.mjs";
7
7
  import { jsxPropName } from "../utils.mjs";
8
- const createRule = ESLintUtils.RuleCreator.withoutDocs;
9
- const { getPropertyName, getStaticValue } = ASTUtils;
10
8
  const lengthPercentageRegex =
11
9
  /\b(?:width|height|margin|padding|border-width|font-size)\b/i;
12
- export default createRule({
10
+ export default {
13
11
  meta: {
14
12
  type: "problem",
15
13
  docs: {
@@ -152,4 +150,4 @@ export default createRule({
152
150
  },
153
151
  };
154
152
  },
155
- });
153
+ };
package/src/utils.mjs CHANGED
@@ -338,3 +338,36 @@ export function jsxGetProp(props, prop) {
338
338
  );
339
339
  });
340
340
  }
341
+
342
+ /**
343
+ * Visit `node` and everything below it, stopping at nested functions.
344
+ *
345
+ * What a function does itself is a different question from what a callback it
346
+ * creates does later, so the rules that reason about "this body" do not look
347
+ * into inner functions.
348
+ */
349
+ export function walkOwnBody(node, visit) {
350
+ if (node === null || typeof node !== "object") {
351
+ return;
352
+ }
353
+
354
+ visit(node);
355
+
356
+ for (const [key, value] of Object.entries(node)) {
357
+ if (key === "parent") {
358
+ continue;
359
+ }
360
+
361
+ const candidates = Array.isArray(value) ? value : [value];
362
+ for (const candidate of candidates) {
363
+ if (
364
+ candidate !== null &&
365
+ typeof candidate === "object" &&
366
+ typeof candidate.type === "string" &&
367
+ !isFunctionNode(candidate)
368
+ ) {
369
+ walkOwnBody(candidate, visit);
370
+ }
371
+ }
372
+ }
373
+ }