@itin-labs/eslint-plugin-worklet-order 0.0.0-stage → 0.2.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # @itin-labs/eslint-plugin-worklet-order
2
+
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - d10951c: Changed: the messages no longer say the worklet "gets undefined". With React Native's preset that's what happens to a `const` or `let`, but a class, or a build that keeps block scoping, throws a `ReferenceError` when the module loads instead. They now say the variable isn't set yet, which covers both.
8
+ - d10951c: Added: functions the Babel plugin makes worklets without a `'worklet'` directive are checked too. That's a function passed inline or by name to `useAnimatedStyle`, `useDerivedValue`, `runOnUI`, an animation's callback, a `Gesture.Pan()` callback and the other calls the plugin knows, from anywhere in the file. So `useAnimatedStyle(styleFn)` in a component now gets a module-level `function styleFn` reported when it uses a constant declared below it, and module-level code that uses `styleFn` above its declaration is reported as well. The rule's docs list the calls, and the README lists the cases it still doesn't follow.
9
+
10
+ ### Patch Changes
11
+
12
+ - d10951c: Fixed: a worklet that only assigns to a variable declared further down, with `=`, `+=` and the like or as a destructuring target, is no longer reported. The Babel plugin doesn't capture those. `x++` and a `for (x of ...)` target are still reported, since the plugin captures them.
13
+ - d10951c: Fixed: with a Flow parser, a `typeof` in a type above a worklet declaration, and `declare var`, `declare function` or `declare class` below a worklet, are no longer reported. The build erases both. Names in Flow annotations inside a worklet are still checked, because the Babel plugin captures them.
14
+
15
+ ## 0.1.0
16
+
17
+ ### Minor Changes
18
+
19
+ - 6e6695d: Added: first release, with the `no-capture-before-define` rule and a recommended config. The rule reports worklets that capture a variable set further down the file, worklets that capture the variable they're assigned to, and module-level code that uses a worklet above its declaration, including in worklet files.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ITIN Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,119 @@
1
- # Temporary Holding Version
1
+ # @itin-labs/eslint-plugin-worklet-order
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An ESLint rule for React Native apps using worklets (Reanimated, react-native-worklets). It catches a module-level worklet that uses a variable or another worklet defined further down the file, and module-level code that uses a worklet before its declaration. That code passes type checks, then fails at run time.
4
+
5
+ ```sh
6
+ npm install --save-dev @itin-labs/eslint-plugin-worklet-order
7
+ ```
8
+
9
+ ```js
10
+ // eslint.config.js
11
+ import workletOrder from '@itin-labs/eslint-plugin-worklet-order';
12
+
13
+ export default [
14
+ // ...your other config
15
+ workletOrder.configs.recommended,
16
+ ];
17
+ ```
18
+
19
+ The package is an ES module, so in a CommonJS config the plugin is the `default` of what `require` returns:
20
+
21
+ ```js
22
+ // eslint.config.cjs
23
+ const workletOrder = require('@itin-labs/eslint-plugin-worklet-order').default;
24
+
25
+ module.exports = [workletOrder.configs.recommended];
26
+ ```
27
+
28
+ It needs ESLint 9 or later with a flat config (the older `.eslintrc` format isn't supported) and Node 22.12 or later. ESLint lints only `.js`, `.mjs` and `.cjs` files unless a config entry names others, so `.ts` and `.tsx` files need an entry with a TypeScript parser, such as typescript-eslint's, in front of this one.
29
+
30
+ It's for anyone writing worklets as plain functions at the top of a module, which is the usual way to share math between gesture handlers and animated styles.
31
+
32
+ ## The problem
33
+
34
+ ```js
35
+ function landingTop(heights, from, to) {
36
+ 'worklet';
37
+ return from + travel(heights, from, to); // travel is undefined here
38
+ }
39
+
40
+ function travel(heights, from, to) {
41
+ 'worklet';
42
+ return heights.slice(from, to).reduce((a, b) => a + b, 0);
43
+ }
44
+ ```
45
+
46
+ This looks fine, since function declarations are hoisted. But the worklets Babel plugin rewrites every function with a `'worklet'` directive into `const name = factory([...captured])`, and the factory call copies each outside variable the worklet uses at the moment the definition runs. `travel` is no longer hoisted, and it isn't set yet when `landingTop` is defined.
47
+
48
+ React Native's and Expo's Babel presets turn `const` and `let` into `var`, so the worklet silently keeps `undefined` and the app crashes the first time it's called, usually on the UI thread. A class declared further down is different: the module throws a `ReferenceError` when it loads. Tests run through Jest with the same Babel config hit the same `undefined`.
49
+
50
+ The fix is to define things before the code that uses them:
51
+
52
+ ```js
53
+ function travel(heights, from, to) {
54
+ 'worklet';
55
+ return heights.slice(from, to).reduce((a, b) => a + b, 0);
56
+ }
57
+
58
+ function landingTop(heights, from, to) {
59
+ 'worklet';
60
+ return from + travel(heights, from, to);
61
+ }
62
+ ```
63
+
64
+ ## The rule: `worklet-order/no-capture-before-define`
65
+
66
+ The recommended config turns it on as an error. It has no options. It reports three things.
67
+
68
+ A worklet that runs while the module loads and uses a module-level binding that only gets its value further down the file. That's a worklet at the top level, in a top-level object or call, or in a static class field or static block, but not one inside a function or an instance member, which is created later. The binding can be a `const`, `let` or `var`, a class, an enum or namespace, or another worklet, and the use can be anywhere in the worklet, including default parameters and nested functions, because the plugin captures for the whole function.
69
+
70
+ A worklet that uses the variable it's being assigned to, such as an arrow worklet calling itself or a method reading its own object.
71
+
72
+ Module-level code that uses a worklet function declared further down, outside any function: `export const handlers = { onEnd: snap }` above `function snap() { 'worklet'; ... }`. The worklets docs list this one as a pitfall.
73
+
74
+ Files that start with a `'worklet'` directive are understood too: there the plugin makes every top-level function a worklet, so plain function declarations lose their hoisting as well.
75
+
76
+ So are most functions the plugin makes worklets without a directive: a function passed inline or by name to `useAnimatedStyle`, `useDerivedValue`, `runOnUI`, an animation's callback, a gesture callback such as `Gesture.Pan().onEnd(...)`, and the other calls listed in the rule's docs. A call anywhere in the file counts, so `function styleFn() { return { opacity: OPACITY }; }` above `const OPACITY = 0.5`, used from a component as `useAnimatedStyle(styleFn)`, is reported: the plugin makes `styleFn` a worklet, which captures `OPACITY` before it's set.
77
+
78
+ It doesn't report imports, configured globals, plain function declarations in ordinary files (they're hoisted with their value), `declare` statements, a named worklet calling itself, worklets marked `'no-worklet-closure'`, uses only in TypeScript types or in a Flow `typeof` outside a worklet, assignments to a variable (`x = 1`, `x += 1`, destructuring), JSX element names, or anything shadowed by a local name. The details and more examples are in [the rule's docs](docs/rules/no-capture-before-define.md).
79
+
80
+ ## How it compares
81
+
82
+ ESLint's own `no-use-before-define` doesn't fit. With its defaults it reports these cases, but also every helper function and constant used above its definition from inside a function, which is ordinary, safe code. Many configs turn those checks off with `functions: false` and `variables: false`, and then it allows exactly the cases that crash. It doesn't know which functions the Babel plugin rewrites.
83
+
84
+ [eslint-plugin-reanimated](https://www.npmjs.com/package/eslint-plugin-reanimated) checks a different mistake, calling a plain JavaScript function from a worklet, using type information. Its last release was 2.0.1, in August 2023.
85
+
86
+ ## Limitations
87
+
88
+ What the rule doesn't catch, or can't:
89
+
90
+ - Some functions the plugin makes worklets without a directive. The rule follows functions passed to the calls its docs list, and not these, which still capture when they're defined: functions in an object argument, such as `useAnimatedScrollHandler({ onScroll: handleScroll })` or the `use...Gesture` hooks, even when they name a module-level function; layout animation callbacks such as `FadeIn.withCallback(...)`; functions in a config object, such as `withTiming`'s `easing` or `createWorkletRuntime`'s `initializer`; a name that reaches the function through another variable (`const g = f`) or an assignment after its declaration (`let f; f = () => ...`); and a call written as `(0, runOnUI)(f)` or `(api?.runOnUI)(f)`. The lists match react-native-worklets 0.14.1, which a weekly check compares with the newest release; Reanimated 3's own copy of the plugin isn't checked.
91
+ - Worklets created inside a function that happens to run while the module loads, such as an IIFE.
92
+ - Bindings declared inside a module-level block, like `if (x) { const L = 1; }`, or inside a TypeScript namespace. Only bindings at the top of the module are checked.
93
+ - A named `export default function snap() { 'worklet'; ... }`. The plugin replaces it with `export default factory(...)`, so the name `snap` stops existing inside the file, and every use of it throws a `ReferenceError`. The rule reports uses above the declaration, with a message that assumes `snap` becomes a `const` there, and doesn't report uses below it.
94
+ - Worklets that call each other in a cycle. No order works, since each captures the other when it's defined; the rule reports one of them. Pass one in as an argument, or merge them.
95
+ - Flow types inside a worklet. The plugin skips TypeScript's types when it works out what a worklet captures, but not Flow's, so a type alias or imported type named in an annotation inside a worklet, its parameters and return type included, is captured, and the build erases it: a `ReferenceError` when the worklet is defined. The rule reports this only when the type is declared further down with `type`, `opaque type` or `interface` (not `declare type`), and then its advice to move the declaration doesn't help.
96
+ - Worklet classes (a class in a worklet file, or one with `__workletClass`), and worklet methods, which the plugin turns into instance fields created per instance.
97
+ - One file at a time, so it can't follow a capture into another module. Imports are always safe for this reason.
98
+ - Values that change. A `let` reassigned after the worklet is defined stays at its old value inside the worklet, which is a different problem.
99
+ - The plugin's bundle mode. The rule follows the default mode. Bundle mode also captures JSX names, ignores `'no-worklet-closure'` and imports some bindings instead of capturing them, and the plugin's Oxc port only has bundle mode.
100
+
101
+ CommonJS files and scripts are handled like modules.
102
+
103
+ ## Privacy
104
+
105
+ The rule only reads the code ESLint gives it, and never uses the network. When it loads, the plugin reads its own package.json to report its name and version; it touches no other files.
106
+
107
+ ## Status and versioning
108
+
109
+ The RuleTester tests cover every case above, with TypeScript cases through typescript-eslint's parser and Flow cases through hermes-eslint, and check the recommended config end to end. A property-based test runs the rule on 500 generated modules each run, with nested and shadowed uses, and compares it with an oracle that restates the rule's position logic, so it checks the scope handling but can't catch a wrong model of the plugin. A differential test covers that: it runs the real worklets Babel plugin on every test input and checks that the rule reports exactly the captures and early uses Babel's output has. It needs the plugin, which isn't a dev dependency because it pulls in react-native, so CI installs it: a fixed version on every pull request, and the newest release weekly. A plain `npm test` skips it. CI runs the rest on Node 22, 24 and 26 with ESLint 10, and on ESLint 9.0.
110
+
111
+ Versions are 0.x until the rule has settled. A minor release can report new cases or change messages, and says so in the changelog; a patch release only fixes false positives or crashes. 1.0 will come when:
112
+
113
+ - it has run on at least two React Native apps for three months without a false positive report open
114
+ - the differential test has passed against every plugin release in that time
115
+ - the autoworkletized cases are either covered or documented as out of scope for good
116
+
117
+ ## License
118
+
119
+ MIT
@@ -0,0 +1,15 @@
1
+ import type { Linter, Rule } from 'eslint';
2
+ interface Plugin {
3
+ meta: {
4
+ name: string;
5
+ version: string;
6
+ };
7
+ rules: {
8
+ 'no-capture-before-define': Rule.RuleModule;
9
+ };
10
+ configs: {
11
+ recommended: Linter.Config;
12
+ };
13
+ }
14
+ declare const plugin: Plugin;
15
+ export default plugin;
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ import { createRequire } from 'node:module';
2
+ import { rule } from "./rule.js";
3
+ // From dist/index.js (and src/index.ts in this repo's tests) the package.json is one level up.
4
+ const { name, version } = createRequire(import.meta.url)('../package.json');
5
+ const plugin = {
6
+ meta: { name, version },
7
+ rules: { 'no-capture-before-define': rule },
8
+ configs: {
9
+ recommended: {
10
+ name: 'worklet-order/recommended',
11
+ rules: { 'worklet-order/no-capture-before-define': 'error' },
12
+ },
13
+ },
14
+ };
15
+ // The config refers back to the plugin, so it's added once the plugin exists.
16
+ plugin.configs.recommended.plugins = { 'worklet-order': plugin };
17
+ export default plugin;
package/dist/rule.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { Rule } from 'eslint';
2
+ export declare const WORKLET_ARGUMENTS: Map<string, number[]>;
3
+ export declare const GESTURE_OBJECTS: Set<string>;
4
+ export declare const GESTURE_CALLBACKS: Set<string>;
5
+ export declare const rule: Rule.RuleModule;
package/dist/rule.js ADDED
@@ -0,0 +1,380 @@
1
+ // The worklets Babel plugin skips identifiers inside TypeScript type positions when it builds a
2
+ // closure. ESLint's own types don't know these node types, so they're compared as strings.
3
+ const TYPE_POSITIONS = new Set([
4
+ 'TSTypeAnnotation',
5
+ 'TSTypeQuery',
6
+ 'TSTypeReference',
7
+ 'TSTypeAliasDeclaration',
8
+ 'TSInterfaceDeclaration',
9
+ 'TSTypeParameterInstantiation',
10
+ 'TSTypeParameterDeclaration',
11
+ 'TSClassImplements',
12
+ ]);
13
+ // Outside a worklet, Flow's `typeof x` is erased too. Inside one it isn't: the plugin skips only
14
+ // TypeScript's types, so a name in a Flow annotation there is captured like any other.
15
+ const ERASED_OUTSIDE_WORKLETS = new Set([...TYPE_POSITIONS, 'TypeofTypeAnnotation']);
16
+ // Calls whose function arguments the plugin makes worklets without a directive, with the argument
17
+ // positions it looks at, and the gesture chains whose callbacks it does the same for. Copied from
18
+ // react-native-worklets 0.14.1: reanimatedFunctionArgsToWorkletize in autoworkletization.ts, and
19
+ // gestureHandlerGestureObjects and gestureHandlerBuilderMethods in
20
+ // gestureHandlerAutoworkletization.ts, both under plugin/src in its repository and bundled into
21
+ // plugin/index.js in the package. The differential test compares them with the installed plugin's
22
+ // bundle, so the weekly run against its newest release fails when they change.
23
+ export const WORKLET_ARGUMENTS = new Map([
24
+ ['useFrameCallback', [0]],
25
+ ['useAnimatedStyle', [0]],
26
+ ['useAnimatedProps', [0]],
27
+ ['createAnimatedPropAdapter', [0]],
28
+ ['useDerivedValue', [0]],
29
+ ['useAnimatedScrollHandler', [0]],
30
+ ['useAnimatedReaction', [0, 1]],
31
+ ['withTiming', [2, 3]],
32
+ ['withSpring', [2, 3]],
33
+ ['withDecay', [1]],
34
+ ['withRepeat', [3]],
35
+ ['runOnUI', [0]],
36
+ ['executeOnUIRuntimeSync', [0]],
37
+ ['scheduleOnUI', [0]],
38
+ ['runOnUISync', [0]],
39
+ ['runOnUIAsync', [0]],
40
+ ['runOnRuntime', [1]],
41
+ ['runOnRuntimeSync', [1]],
42
+ ['runOnRuntimeAsync', [1]],
43
+ ['scheduleOnRuntime', [1]],
44
+ ['runOnRuntimeSyncWithId', [1]],
45
+ ['runOnRuntimeAsyncWithId', [1]],
46
+ ['scheduleOnRuntimeWithId', [1]],
47
+ ['createWorkletRuntime', [1]],
48
+ ]);
49
+ export const GESTURE_OBJECTS = new Set([
50
+ 'Tap',
51
+ 'Pan',
52
+ 'Pinch',
53
+ 'Rotation',
54
+ 'Fling',
55
+ 'LongPress',
56
+ 'ForceTouch',
57
+ 'Native',
58
+ 'Manual',
59
+ 'Race',
60
+ 'Simultaneous',
61
+ 'Exclusive',
62
+ 'Hover',
63
+ ]);
64
+ export const GESTURE_CALLBACKS = new Set([
65
+ 'onBegin',
66
+ 'onStart',
67
+ 'onEnd',
68
+ 'onFinalize',
69
+ 'onUpdate',
70
+ 'onChange',
71
+ 'onTouchesDown',
72
+ 'onTouchesMove',
73
+ 'onTouchesUp',
74
+ 'onTouchesCancelled',
75
+ ]);
76
+ export const rule = {
77
+ meta: {
78
+ type: 'problem',
79
+ docs: {
80
+ description: 'Disallow module-level worklets that capture a variable before it is set',
81
+ recommended: true,
82
+ url: 'https://github.com/ITIN-Labs/eslint-plugin-worklet-order/blob/main/docs/rules/no-capture-before-define.md',
83
+ },
84
+ schema: [],
85
+ messages: {
86
+ later: "{{worklet}} captures '{{name}}' when it's defined, but '{{name}}' isn't set until further down the file. Move '{{name}}' above the worklet.",
87
+ self: "{{worklet}} captures '{{name}}' while '{{name}}' is still being set. Don't refer to '{{name}}' inside its own value.",
88
+ usedAbove: "'{{name}}' is a worklet, which the Babel plugin turns into a const that's only set where it's declared, further down the file, so it isn't set yet here. Move '{{name}}' above this line.",
89
+ },
90
+ },
91
+ create(context) {
92
+ const { sourceCode } = context;
93
+ const program = sourceCode.ast;
94
+ // Worklets without a directive of their own: a worklet file's functions, and the functions
95
+ // passed to the calls above, added as the calls are visited.
96
+ const workletized = workletFileFunctions(program);
97
+ const isWorklet = (node) => workletized.has(node) || directives(node).includes('worklet');
98
+ const functions = [];
99
+ function markCallbacks(call) {
100
+ const { callee } = call;
101
+ const name = callee.type === 'Identifier'
102
+ ? callee.name
103
+ : callee.type === 'MemberExpression' && callee.property.type === 'Identifier'
104
+ ? callee.property.name
105
+ : undefined;
106
+ // The plugin doesn't look at calls in an optional chain.
107
+ if (name === undefined || isOptional(call))
108
+ return;
109
+ const positions = WORKLET_ARGUMENTS.get(name);
110
+ const isGestureCallback = callee.type === 'MemberExpression' && GESTURE_CALLBACKS.has(name) && hasGesture(callee.object);
111
+ call.arguments.forEach((argument, index) => {
112
+ if (!positions?.includes(index) && !isGestureCallback)
113
+ return;
114
+ const worklet = functionPassed(argument);
115
+ if (worklet)
116
+ workletized.add(worklet);
117
+ });
118
+ }
119
+ /** The function an argument is, or the one its name stands for, as far as the plugin follows it. */
120
+ function functionPassed(argument) {
121
+ if (isFunctionExpression(argument))
122
+ return argument;
123
+ if (argument.type !== 'Identifier')
124
+ return undefined;
125
+ const variable = sourceCode.getScope(argument).references.find((r) => r.identifier === argument)?.resolved;
126
+ // TypeScript's overload signatures are erased; the plugin sees only the implementation.
127
+ const defs = variable?.defs.filter((d) => d.node.type !== 'TSDeclareFunction');
128
+ const def = defs?.length === 1 ? defs[0] : undefined;
129
+ if (def?.type === 'FunctionName' && def.node.type === 'FunctionDeclaration')
130
+ return def.node;
131
+ // A variable that keeps the function it starts with. The plugin also follows one that's
132
+ // assigned again, to its last assignment; that isn't followed here.
133
+ const init = def?.type === 'Variable' ? def.node.init : undefined;
134
+ const reassigned = variable?.references.some((r) => r.isWrite() && !r.init);
135
+ return init && isFunctionExpression(init) && !reassigned ? init : undefined;
136
+ }
137
+ function check(node) {
138
+ if (!isWorklet(node) || !runsAtLoad(node))
139
+ return;
140
+ // The plugin captures nothing for these, outside its bundle mode.
141
+ if (directives(node).includes('no-worklet-closure'))
142
+ return;
143
+ const [start] = range(node);
144
+ const reported = new Set();
145
+ // `through` holds every reference in the function and the functions nested in it that isn't
146
+ // resolved inside them, which is the same set the Babel plugin captures.
147
+ for (const reference of sourceCode.getScope(node).through) {
148
+ const variable = reference.resolved;
149
+ if (!variable || reported.has(variable) || !isModuleVariable(variable))
150
+ continue;
151
+ // The plugin doesn't capture a named worklet's references to itself.
152
+ if (variable.defs.some((def) => def.node === node))
153
+ continue;
154
+ // JSX names aren't captured by the plugin outside its bundle mode.
155
+ const identifier = reference.identifier;
156
+ if (identifier.type === 'JSXIdentifier' || isInTypePosition(identifier, node, TYPE_POSITIONS))
157
+ continue;
158
+ if (isAssignmentTarget(identifier))
159
+ continue;
160
+ const ready = readyAt(variable, isWorklet);
161
+ if (ready === undefined || ready <= start)
162
+ continue;
163
+ reported.add(variable);
164
+ const self = variable.defs.some((def) => contains(def.node, node));
165
+ context.report({
166
+ node: identifier,
167
+ messageId: self ? 'self' : 'later',
168
+ data: { worklet: describe(node), name: variable.name },
169
+ });
170
+ }
171
+ }
172
+ // A worklet function declaration loses its hoisting, so module-level code above it that uses
173
+ // it, outside any function, reads it before it's set.
174
+ function checkUsesAbove() {
175
+ const globalScope = sourceCode.getScope(program);
176
+ const scopes = [globalScope, ...globalScope.childScopes.filter((scope) => scope.block === program)];
177
+ for (const variable of scopes.flatMap((scope) => scope.variables)) {
178
+ const declaration = variable.defs.find((def) => def.node.type === 'FunctionDeclaration' && !isAmbient(def) && isWorklet(def.node))?.node;
179
+ if (!declaration)
180
+ continue;
181
+ const [declared] = range(declaration);
182
+ for (const reference of variable.references) {
183
+ // JSX names are identifiers too; ESLint's types just don't say so.
184
+ const node = reference.identifier;
185
+ if (range(node)[0] >= declared)
186
+ continue;
187
+ // An export list only links the binding; it doesn't read it.
188
+ if (node.parent?.type === 'ExportSpecifier' || isInTypePosition(node, program, ERASED_OUTSIDE_WORKLETS)) {
189
+ continue;
190
+ }
191
+ if (!runsAtLoad(node))
192
+ continue;
193
+ context.report({ node, messageId: 'usedAbove', data: { name: variable.name } });
194
+ break;
195
+ }
196
+ }
197
+ }
198
+ return {
199
+ CallExpression: markCallbacks,
200
+ ':function'(node) {
201
+ functions.push(node);
202
+ },
203
+ // A call further down the file can make a function above it a worklet, so the checks wait.
204
+ 'Program:exit'() {
205
+ functions.forEach(check);
206
+ checkUsesAbove();
207
+ },
208
+ };
209
+ },
210
+ };
211
+ function directives(node) {
212
+ const found = [];
213
+ if (node.body.type !== 'BlockStatement')
214
+ return found;
215
+ for (const statement of node.body.body) {
216
+ if (statement.type !== 'ExpressionStatement' || !('directive' in statement))
217
+ break;
218
+ found.push(statement.directive);
219
+ }
220
+ return found;
221
+ }
222
+ function isFunctionExpression(node) {
223
+ return node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression';
224
+ }
225
+ /** Part of an optional chain from its first `?.` on. */
226
+ function isOptional(node) {
227
+ if (node.type !== 'CallExpression' && node.type !== 'MemberExpression')
228
+ return false;
229
+ return node.optional || isOptional(node.type === 'CallExpression' ? node.callee : node.object);
230
+ }
231
+ /** A chain of method calls with `Gesture.Pan()`, or another gesture, somewhere along it. */
232
+ function hasGesture(node) {
233
+ if (node.type !== 'CallExpression' || node.callee.type !== 'MemberExpression')
234
+ return false;
235
+ const { object, property } = node.callee;
236
+ const isGesture = object.type === 'Identifier' &&
237
+ object.name === 'Gesture' &&
238
+ property.type === 'Identifier' &&
239
+ GESTURE_OBJECTS.has(property.name);
240
+ return isGesture || hasGesture(object);
241
+ }
242
+ /**
243
+ * In a file whose prologue has 'worklet', the plugin workletizes every top-level function, exported
244
+ * or not, every function a top-level variable is initialized with, and the methods and function
245
+ * values of top-level object literals. Classes become worklet classes, which this rule leaves alone.
246
+ */
247
+ function workletFileFunctions(program) {
248
+ const found = new Set();
249
+ let isWorkletFile = false;
250
+ for (const statement of program.body) {
251
+ if (statement.type !== 'ExpressionStatement' || !('directive' in statement))
252
+ break;
253
+ if (statement.directive === 'worklet')
254
+ isWorkletFile = true;
255
+ }
256
+ if (!isWorkletFile)
257
+ return found;
258
+ const visit = (node) => {
259
+ if (!node)
260
+ return;
261
+ if (node.type === 'FunctionDeclaration' || node.type.endsWith('FunctionExpression')) {
262
+ found.add(node);
263
+ }
264
+ else if (node.type === 'ObjectExpression') {
265
+ for (const property of node.properties)
266
+ if (property.type === 'Property')
267
+ visit(property.value);
268
+ }
269
+ };
270
+ for (const statement of program.body) {
271
+ const exported = statement.type === 'ExportNamedDeclaration' || statement.type === 'ExportDefaultDeclaration';
272
+ const target = exported ? statement.declaration : statement;
273
+ if (target?.type === 'VariableDeclaration') {
274
+ for (const declarator of target.declarations)
275
+ visit(declarator.init);
276
+ }
277
+ else if (target?.type === 'FunctionDeclaration' || statement.type === 'ExportDefaultDeclaration') {
278
+ visit(target);
279
+ }
280
+ }
281
+ return found;
282
+ }
283
+ /**
284
+ * Runs while the module loads. Not inside a function, which runs when it's called. Not in a
285
+ * non-static class member: the plugin turns worklet methods into instance fields, and instance
286
+ * fields run per instance. Static fields and static blocks run when the class is defined.
287
+ */
288
+ function runsAtLoad(node) {
289
+ for (let parent = node.parent; parent && parent.type !== 'Program'; parent = parent.parent) {
290
+ const type = parent.type;
291
+ if (type.endsWith('FunctionExpression') || type === 'FunctionDeclaration' || type === 'MethodDefinition') {
292
+ return false;
293
+ }
294
+ if ((type === 'PropertyDefinition' || type === 'AccessorProperty') && !parent.static) {
295
+ return false;
296
+ }
297
+ }
298
+ return true;
299
+ }
300
+ function isModuleVariable(variable) {
301
+ // Covers modules, scripts and CommonJS. Variables with no definition are configured globals,
302
+ // which exist before any code runs.
303
+ return variable.scope.block.type === 'Program' && variable.defs.length > 0;
304
+ }
305
+ /** Where in the source the variable first holds its value, or undefined when it always does. */
306
+ function readyAt(variable, isWorklet) {
307
+ let ready;
308
+ for (const def of variable.defs) {
309
+ // Imports are set before any code runs.
310
+ if (def.type === 'ImportBinding')
311
+ return undefined;
312
+ // Ambient declarations are erased, which leaves any real declaration of the same name to count.
313
+ if (isAmbient(def))
314
+ continue;
315
+ // A function declaration is hoisted with its value, unless it's a worklet: the Babel plugin
316
+ // turns those into `const name = factory(...)`, which isn't set until that line runs.
317
+ if (def.type === 'FunctionName' && def.node.type === 'FunctionDeclaration' && !isWorklet(def.node)) {
318
+ return undefined;
319
+ }
320
+ const [, end] = range(def.node);
321
+ if (ready === undefined || end < ready)
322
+ ready = end;
323
+ }
324
+ return ready;
325
+ }
326
+ /** `declare const`, `declare function` and the rest: types only, gone at run time. */
327
+ function isAmbient(def) {
328
+ // Flow has a node type for each, such as DeclareVariable.
329
+ if (def.node.type.startsWith('Declare'))
330
+ return true;
331
+ return Boolean(def.node.declare || def.parent?.declare);
332
+ }
333
+ /**
334
+ * Written to, not read, the way Babel's `isReferenced` sees it, which is what the plugin captures
335
+ * by: the left of `=` or `+=`, and destructuring targets. A plain `for (x of ...)` target and
336
+ * `x++` count as reads.
337
+ */
338
+ function isAssignmentTarget(identifier) {
339
+ // Every identifier in a `through` list has a parent.
340
+ const parent = identifier.parent;
341
+ switch (parent.type) {
342
+ case 'AssignmentExpression':
343
+ case 'AssignmentPattern':
344
+ return parent.left === identifier;
345
+ case 'ArrayPattern':
346
+ case 'RestElement':
347
+ return true;
348
+ case 'Property':
349
+ return parent.value === identifier && parent.parent.type === 'ObjectPattern';
350
+ default:
351
+ return false;
352
+ }
353
+ }
354
+ function isInTypePosition(identifier, until, positions) {
355
+ for (let node = identifier.parent; node && node !== until; node = node.parent) {
356
+ if (positions.has(node.type))
357
+ return true;
358
+ }
359
+ return false;
360
+ }
361
+ // ESLint always sets range on the nodes it passes to rules.
362
+ function range(node) {
363
+ return node.range;
364
+ }
365
+ function contains(outer, inner) {
366
+ const [a, b] = range(outer);
367
+ const [c, d] = range(inner);
368
+ return a <= c && d <= b;
369
+ }
370
+ function describe(node) {
371
+ if (node.type !== 'ArrowFunctionExpression' && node.id)
372
+ return `Worklet '${node.id.name}'`;
373
+ const parent = node.parent;
374
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier')
375
+ return `Worklet '${parent.id.name}'`;
376
+ if ((parent.type === 'Property' || parent.type === 'PropertyDefinition') && parent.key.type === 'Identifier') {
377
+ return `Worklet '${parent.key.name}'`;
378
+ }
379
+ return 'This worklet';
380
+ }
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "@itin-labs/eslint-plugin-worklet-order",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "ESLint rule that catches React Native worklets which capture a variable before it is set, the mistake that crashes on the UI thread.",
5
+ "keywords": [
6
+ "eslint",
7
+ "eslintplugin",
8
+ "eslint-plugin",
9
+ "react-native",
10
+ "reanimated",
11
+ "worklets",
12
+ "react-native-worklets"
13
+ ],
14
+ "homepage": "https://github.com/ITIN-Labs/eslint-plugin-worklet-order#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/ITIN-Labs/eslint-plugin-worklet-order/issues"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/ITIN-Labs/eslint-plugin-worklet-order.git"
21
+ },
22
+ "license": "MIT",
23
+ "author": "ITIN Labs",
24
+ "type": "module",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "CHANGELOG.md"
34
+ ],
35
+ "sideEffects": false,
36
+ "engines": {
37
+ "node": ">=22.12"
38
+ },
39
+ "peerDependencies": {
40
+ "eslint": ">=9"
41
+ },
42
+ "scripts": {
43
+ "build": "tsc -p tsconfig.build.json",
44
+ "test": "node --test --experimental-test-coverage --test-coverage-include=\"src/**\" --test-coverage-lines=95 --test-coverage-branches=90 --test-coverage-functions=95 \"test/**/*.test.ts\"",
45
+ "typecheck": "tsc",
46
+ "lint": "eslint . && prettier --check .",
47
+ "format": "prettier --write .",
48
+ "check:package": "publint --strict",
49
+ "changeset": "changeset",
50
+ "version-packages": "changeset version && npm install --package-lock-only",
51
+ "release": "npm test && npm run build && npm run check:package && npm stage publish"
52
+ },
53
+ "devDependencies": {
54
+ "@changesets/cli": "^3.0.3",
55
+ "@eslint/js": "^10.0.1",
56
+ "@types/estree": "^1.0.11",
57
+ "@types/node": "^24.19.2",
58
+ "eslint": "^10.15.0",
59
+ "eslint-config-prettier": "^10.1.8",
60
+ "expect-type": "^1.4.0",
61
+ "fast-check": "^4.11.0",
62
+ "hermes-eslint": "^0.37.0",
63
+ "prettier": "^3.10.1",
64
+ "publint": "^0.3.25",
65
+ "typescript": "^6.0.3",
66
+ "typescript-eslint": "^8.74.0"
67
+ }
68
+ }