@itin-labs/eslint-plugin-worklet-order 0.0.0-stage → 0.1.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,7 @@
1
+ # @itin-labs/eslint-plugin-worklet-order
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 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,105 @@
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
+ 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.
20
+
21
+ ## The problem
22
+
23
+ ```js
24
+ function landingTop(heights, from, to) {
25
+ 'worklet';
26
+ return from + travel(heights, from, to); // travel is undefined here
27
+ }
28
+
29
+ function travel(heights, from, to) {
30
+ 'worklet';
31
+ return heights.slice(from, to).reduce((a, b) => a + b, 0);
32
+ }
33
+ ```
34
+
35
+ 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.
36
+
37
+ 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`.
38
+
39
+ The fix is to define things before the code that uses them:
40
+
41
+ ```js
42
+ function travel(heights, from, to) {
43
+ 'worklet';
44
+ return heights.slice(from, to).reduce((a, b) => a + b, 0);
45
+ }
46
+
47
+ function landingTop(heights, from, to) {
48
+ 'worklet';
49
+ return from + travel(heights, from, to);
50
+ }
51
+ ```
52
+
53
+ ## The rule: `worklet-order/no-capture-before-define`
54
+
55
+ The recommended config turns it on as an error. It has no options. It reports three things.
56
+
57
+ 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.
58
+
59
+ 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.
60
+
61
+ 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.
62
+
63
+ 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.
64
+
65
+ 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, 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).
66
+
67
+ ## How it compares
68
+
69
+ 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.
70
+
71
+ [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.
72
+
73
+ ## Limitations
74
+
75
+ What the rule doesn't catch, or can't:
76
+
77
+ - Functions the plugin workletizes without a directive. A function passed by name to `useAnimatedStyle`, `runOnUI`, a gesture builder and similar calls gets the directive added to its module-level declaration, so `function styleFn() { return { opacity: OPACITY }; }` above `const OPACITY = 0.5`, used from a component as `useAnimatedStyle(styleFn)`, captures `undefined`. Inline callbacks at module level, such as `const pan = Gesture.Pan().onUpdate(() => use(L))` or `FadeIn.withCallback(...)`, capture when the module loads. The rule only knows about the `'worklet'` directive and worklet files, so it misses both.
78
+ - Worklets created inside a function that happens to run while the module loads, such as an IIFE.
79
+ - Bindings declared inside a module-level block, like `if (x) { const L = 1; }`. Only bindings at the top of the module are checked.
80
+ - A named `export default function snap() { 'worklet'; ... }`. The plugin replaces it with `export default factory(...)`, so the name `snap` stops existing inside the file. The rule doesn't report uses of it.
81
+ - 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.
82
+ - 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.
83
+ - One file at a time, so it can't follow a capture into another module. Imports are always safe for this reason.
84
+ - Values that change. A `let` reassigned after the worklet is defined stays at its old value inside the worklet, which is a different problem.
85
+ - 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.
86
+
87
+ CommonJS files and scripts are handled like modules.
88
+
89
+ ## Privacy
90
+
91
+ 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.
92
+
93
+ ## Status and versioning
94
+
95
+ The RuleTester tests cover every case above, with TypeScript cases through typescript-eslint's parser, 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 it runs weekly in CI against the newest plugin release and skips itself elsewhere. CI runs the rest on Node 22, 24 and 26 with ESLint 10, and on ESLint 9.0.
96
+
97
+ 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:
98
+
99
+ - it has run on at least two React Native apps for three months without a false positive report open
100
+ - the differential test has passed against every plugin release in that time
101
+ - the autoworkletized cases are either covered or documented as out of scope for good
102
+
103
+ ## License
104
+
105
+ 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,2 @@
1
+ import type { Rule } from 'eslint';
2
+ export declare const rule: Rule.RuleModule;
package/dist/rule.js ADDED
@@ -0,0 +1,221 @@
1
+ // The worklets Babel plugin skips identifiers inside type positions when it builds a closure.
2
+ // ESLint's own types don't know these TypeScript 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
+ export const rule = {
14
+ meta: {
15
+ type: 'problem',
16
+ docs: {
17
+ description: 'Disallow module-level worklets that capture a variable before it is set',
18
+ recommended: true,
19
+ url: 'https://github.com/ITIN-Labs/eslint-plugin-worklet-order/blob/main/docs/rules/no-capture-before-define.md',
20
+ },
21
+ schema: [],
22
+ messages: {
23
+ later: "{{worklet}} captures '{{name}}' when it's defined, but '{{name}}' is set further down the file, so the worklet gets undefined. Move '{{name}}' above the worklet.",
24
+ self: "{{worklet}} captures '{{name}}' while '{{name}}' is still being set, so the worklet gets undefined. Don't refer to '{{name}}' inside its own value.",
25
+ 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's undefined here. Move '{{name}}' above this line.",
26
+ },
27
+ },
28
+ create(context) {
29
+ const { sourceCode } = context;
30
+ const program = sourceCode.ast;
31
+ const fileWorklets = workletFileFunctions(program);
32
+ const isWorklet = (node) => fileWorklets.has(node) || directives(node).includes('worklet');
33
+ function check(node) {
34
+ if (!isWorklet(node) || !runsAtLoad(node))
35
+ return;
36
+ // The plugin captures nothing for these, outside its bundle mode.
37
+ if (directives(node).includes('no-worklet-closure'))
38
+ return;
39
+ const [start] = range(node);
40
+ const reported = new Set();
41
+ // `through` holds every reference in the function and the functions nested in it that isn't
42
+ // resolved inside them, which is the same set the Babel plugin captures.
43
+ for (const reference of sourceCode.getScope(node).through) {
44
+ const variable = reference.resolved;
45
+ if (!variable || reported.has(variable) || !isModuleVariable(variable))
46
+ continue;
47
+ // The plugin doesn't capture a named worklet's references to itself.
48
+ if (variable.defs.some((def) => def.node === node))
49
+ continue;
50
+ // JSX names aren't captured by the plugin outside its bundle mode.
51
+ const identifier = reference.identifier;
52
+ if (identifier.type === 'JSXIdentifier' || isInTypePosition(identifier, node))
53
+ continue;
54
+ const ready = readyAt(variable, isWorklet);
55
+ if (ready === undefined || ready <= start)
56
+ continue;
57
+ reported.add(variable);
58
+ const self = variable.defs.some((def) => contains(def.node, node));
59
+ context.report({
60
+ node: identifier,
61
+ messageId: self ? 'self' : 'later',
62
+ data: { worklet: describe(node), name: variable.name },
63
+ });
64
+ }
65
+ }
66
+ // A worklet function declaration loses its hoisting, so module-level code above it that uses
67
+ // it, outside any function, reads it before it's set.
68
+ function checkUsesAbove() {
69
+ const globalScope = sourceCode.getScope(program);
70
+ const scopes = [globalScope, ...globalScope.childScopes.filter((scope) => scope.block === program)];
71
+ for (const variable of scopes.flatMap((scope) => scope.variables)) {
72
+ const declaration = variable.defs.find((def) => def.node.type === 'FunctionDeclaration' && !isAmbient(def) && isWorklet(def.node))?.node;
73
+ if (!declaration)
74
+ continue;
75
+ const [declared] = range(declaration);
76
+ for (const reference of variable.references) {
77
+ // JSX names are identifiers too; ESLint's types just don't say so.
78
+ const node = reference.identifier;
79
+ if (range(node)[0] >= declared)
80
+ continue;
81
+ // An export list only links the binding; it doesn't read it.
82
+ if (node.parent?.type === 'ExportSpecifier' || isInTypePosition(node, program))
83
+ continue;
84
+ if (!runsAtLoad(node))
85
+ continue;
86
+ context.report({ node, messageId: 'usedAbove', data: { name: variable.name } });
87
+ break;
88
+ }
89
+ }
90
+ }
91
+ return {
92
+ FunctionDeclaration: check,
93
+ FunctionExpression: check,
94
+ ArrowFunctionExpression: check,
95
+ 'Program:exit': checkUsesAbove,
96
+ };
97
+ },
98
+ };
99
+ function directives(node) {
100
+ const found = [];
101
+ if (node.body.type !== 'BlockStatement')
102
+ return found;
103
+ for (const statement of node.body.body) {
104
+ if (statement.type !== 'ExpressionStatement' || !('directive' in statement))
105
+ break;
106
+ found.push(statement.directive);
107
+ }
108
+ return found;
109
+ }
110
+ /**
111
+ * In a file whose prologue has 'worklet', the plugin workletizes every top-level function, exported
112
+ * or not, every function a top-level variable is initialized with, and the methods and function
113
+ * values of top-level object literals. Classes become worklet classes, which this rule leaves alone.
114
+ */
115
+ function workletFileFunctions(program) {
116
+ const found = new Set();
117
+ let isWorkletFile = false;
118
+ for (const statement of program.body) {
119
+ if (statement.type !== 'ExpressionStatement' || !('directive' in statement))
120
+ break;
121
+ if (statement.directive === 'worklet')
122
+ isWorkletFile = true;
123
+ }
124
+ if (!isWorkletFile)
125
+ return found;
126
+ const visit = (node) => {
127
+ if (!node)
128
+ return;
129
+ if (node.type === 'FunctionDeclaration' || node.type.endsWith('FunctionExpression')) {
130
+ found.add(node);
131
+ }
132
+ else if (node.type === 'ObjectExpression') {
133
+ for (const property of node.properties)
134
+ if (property.type === 'Property')
135
+ visit(property.value);
136
+ }
137
+ };
138
+ for (const statement of program.body) {
139
+ const exported = statement.type === 'ExportNamedDeclaration' || statement.type === 'ExportDefaultDeclaration';
140
+ const target = exported ? statement.declaration : statement;
141
+ if (target?.type === 'VariableDeclaration') {
142
+ for (const declarator of target.declarations)
143
+ visit(declarator.init);
144
+ }
145
+ else if (target?.type === 'FunctionDeclaration' || statement.type === 'ExportDefaultDeclaration') {
146
+ visit(target);
147
+ }
148
+ }
149
+ return found;
150
+ }
151
+ /**
152
+ * Runs while the module loads. Not inside a function, which runs when it's called. Not in a
153
+ * non-static class member: the plugin turns worklet methods into instance fields, and instance
154
+ * fields run per instance. Static fields and static blocks run when the class is defined.
155
+ */
156
+ function runsAtLoad(node) {
157
+ for (let parent = node.parent; parent && parent.type !== 'Program'; parent = parent.parent) {
158
+ const type = parent.type;
159
+ if (type.endsWith('FunctionExpression') || type === 'FunctionDeclaration' || type === 'MethodDefinition') {
160
+ return false;
161
+ }
162
+ if ((type === 'PropertyDefinition' || type === 'AccessorProperty') && !parent.static) {
163
+ return false;
164
+ }
165
+ }
166
+ return true;
167
+ }
168
+ function isModuleVariable(variable) {
169
+ // Covers modules, scripts and CommonJS. Variables with no definition are configured globals,
170
+ // which exist before any code runs.
171
+ return variable.scope.block.type === 'Program' && variable.defs.length > 0;
172
+ }
173
+ /** Where in the source the variable first holds its value, or undefined when it always does. */
174
+ function readyAt(variable, isWorklet) {
175
+ let ready;
176
+ for (const def of variable.defs) {
177
+ // Imports are set before any code runs, and ambient declarations are erased.
178
+ if (def.type === 'ImportBinding' || isAmbient(def))
179
+ return undefined;
180
+ // A function declaration is hoisted with its value, unless it's a worklet: the Babel plugin
181
+ // turns those into `const name = factory(...)`, which isn't set until that line runs.
182
+ if (def.type === 'FunctionName' && def.node.type === 'FunctionDeclaration' && !isWorklet(def.node)) {
183
+ return undefined;
184
+ }
185
+ const [, end] = range(def.node);
186
+ if (ready === undefined || end < ready)
187
+ ready = end;
188
+ }
189
+ return ready;
190
+ }
191
+ /** `declare const`, `declare function` and the rest: types only, gone at run time. */
192
+ function isAmbient(def) {
193
+ return Boolean(def.node.declare || def.parent?.declare);
194
+ }
195
+ function isInTypePosition(identifier, until) {
196
+ for (let node = identifier.parent; node && node !== until; node = node.parent) {
197
+ if (TYPE_POSITIONS.has(node.type))
198
+ return true;
199
+ }
200
+ return false;
201
+ }
202
+ // ESLint always sets range on the nodes it passes to rules.
203
+ function range(node) {
204
+ return node.range;
205
+ }
206
+ function contains(outer, inner) {
207
+ const [a, b] = range(outer);
208
+ const [c, d] = range(inner);
209
+ return a <= c && d <= b;
210
+ }
211
+ function describe(node) {
212
+ if (node.type !== 'ArrowFunctionExpression' && node.id)
213
+ return `Worklet '${node.id.name}'`;
214
+ const parent = node.parent;
215
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier')
216
+ return `Worklet '${parent.id.name}'`;
217
+ if ((parent.type === 'Property' || parent.type === 'PropertyDefinition') && parent.key.type === 'Identifier') {
218
+ return `Worklet '${parent.key.name}'`;
219
+ }
220
+ return 'This worklet';
221
+ }
package/package.json CHANGED
@@ -1,6 +1,70 @@
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.1.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 && attw --pack . --profile esm-only && size-limit",
49
+ "changeset": "changeset",
50
+ "version-packages": "changeset version && npm install --package-lock-only",
51
+ "release": "npm test && npm run build && npm run check:package && changeset publish"
52
+ },
53
+ "devDependencies": {
54
+ "@arethetypeswrong/cli": "^0.18.5",
55
+ "@changesets/cli": "^3.0.3",
56
+ "@eslint/js": "^10.0.1",
57
+ "@size-limit/file": "^14.3.0",
58
+ "@types/estree": "^1.0.11",
59
+ "@types/node": "^24.19.2",
60
+ "eslint": "^10.15.0",
61
+ "eslint-config-prettier": "^10.1.8",
62
+ "expect-type": "^1.4.0",
63
+ "fast-check": "^4.11.0",
64
+ "prettier": "^3.10.1",
65
+ "publint": "^0.3.25",
66
+ "size-limit": "^14.3.0",
67
+ "typescript": "^6.0.3",
68
+ "typescript-eslint": "^8.74.0"
69
+ }
70
+ }