@devries-cameron20 / composio Mirror · read-only / commits / dac610cd9
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 03:37 UTC

chore(lint): enforce Effect error-handling rules (#5424)

This PR: - adds `composio-effect/require-cause-when-narrowing` to reject broad Effect handlers that discard an error while constructing its replacement. - adds `composio-effect/no-ordie-in-service-construction` to keep service-construction failures in the typed error channel. - adapts the rules and fixtures from [K-Mistele/anti-slop at b7c1619](https://github.com/K-Mistele/anti-slop/tree/b7c1619b4d51b4815e89ba3700a975a6ec54b8c3), preserves the MIT license, and adds lexical-binding checks for shadowed imports. - enables both rules for handwritten CLI source, excludes tests/fixtures/generated files, and documents the syntax-only limits. No production-code changes or new baseline allowances are needed. - runs their fixtures, a real-config enforcement test, and plugin typechecking in Agent Substrate CI. Validation: `pnpm test:antislop`, `pnpm typecheck:effect-rules`, `pnpm lint:antislop`, `bun run validate:agent-skills`, `bun run validate:skill-routing`, changed-file Prettier, actionlint, and CI-mode frozen dependency installation passed. Root Oxlint also passed with `--disable-nested-config`; ordinary `pnpm run lint` is blocked locally by the unrelated modified Effect submodule's missing `@effect/oxc/oxlint` dependency. <!-- sdk-release-note-exempt: Internal lint tooling only; no published SDK runtime or public contract changes. -->

Alberto Schiabel committed Nov 17, 2026 at 10:50 UTC dac610cd9844f4e7f926fee74e35bced13eff7b7
15 files changed +1132 -23
.github/workflows/agent-substrate.yml
+3
@@ -52,6 +52,9 @@ jobs:
52 - name: Test anti-slop rules and enforcement
53 run: pnpm test:antislop
54
55 + - name: Typecheck Effect lint rules
56 + run: pnpm typecheck:effect-rules
57 +
58 - name: Reject new anti-slop findings
59 run: pnpm lint:antislop
60
.oxlintrc.json
+22 -1
@@ -4,7 +4,10 @@
4 // everything except no-restricted-syntax, which runs through the
5 // oxlint-plugin-eslint JS plugin as eslint-js/no-restricted-syntax.
6 "plugins": ["typescript", "unicorn", "oxc"],
7 - "jsPlugins": [{ "name": "eslint-js", "specifier": "oxlint-plugin-eslint" }],
7 + "jsPlugins": [
8 + { "name": "eslint-js", "specifier": "oxlint-plugin-eslint" },
9 + { "name": "composio-effect", "specifier": "./tools/oxlint/effect/index.ts" }
10 + ],
11 "categories": {
12 "correctness": "error"
13 },
@@ -116,6 +119,24 @@
119 "typescript/no-namespace": "off"
120 }
121 },
122 + {
123 + "files": ["ts/packages/cli/src/**/*.{ts,tsx}"],
124 + "excludeFiles": [
125 + "**/*.test.*",
126 + "**/*.spec.*",
127 + "**/__tests__/**",
128 + "**/test/**",
129 + "**/tests/**",
130 + "**/__fixtures__/**",
131 + "**/fixtures/**",
132 + "**/generated/**",
133 + "**/.generated/**"
134 + ],
135 + "rules": {
136 + "composio-effect/require-cause-when-narrowing": "error",
137 + "composio-effect/no-ordie-in-service-construction": "error"
138 + }
139 + },
140 {
141 "files": ["ts/packages/cli/src/**/*.{ts,tsx}"],
142 "rules": {
CONTRIBUTING.md
+7
@@ -225,6 +225,13 @@ Fix a finding by parsing or narrowing input, handling the failure, or keeping th
225
226 Existing findings are recorded in [`.ast-grep/baseline.json`](.ast-grep/baseline.json) by rule, path, full matched source lines, and occurrence count. The baseline records adoption debt, not approved patterns. A new source, a changed source, a moved file, or another identical occurrence fails the check. Line-number changes alone do not. After fixing an existing finding, run `pnpm lint:antislop:prune` and include the reduced baseline in your change. Pruning refuses to add allowances. Do not regenerate or expand the baseline to pass CI.
227
228 +CLI source also enables two local Oxlint rules from [`tools/oxlint/effect`](tools/oxlint/effect/UPSTREAM.md), adapted from MIT-licensed anti-slop rules:
229 +
230 +- `composio-effect/require-cause-when-narrowing` rejects broad Effect recovery or error-mapping callbacks that ignore their error and construct a replacement. Keep the original as `cause`, or capture it before replacing it. Tag-specific recovery is excluded. This syntax check does not prove that every error is preserved: callbacks that read their error, object spreads, and preceding error taps are left to review.
231 +- `composio-effect/no-ordie-in-service-construction` rejects `Effect.orDie`/`orDieWith` in inline service construction and `Layer.orDie`. Keep expected failures in the typed error channel with the package's tagged errors. Operations returned by a service are outside the construction check; it does not follow imported or separately defined helper effects.
232 +
233 +Both rules run through `pnpm lint:antislop` and its CI job. Tests, fixtures, and generated files are excluded. Run `pnpm test:effect-rules` for their fixtures and config-enforcement test, and `pnpm typecheck:effect-rules` to typecheck the plugin. A justified exception needs a nearby invariant comment and a rule-specific `oxlint-disable-next-line` directive.
234 +
235 ## Documentation Changes
236
237 Update docs when a change affects public behavior, install flows, examples, environment variables, release steps, or provider usage.
package.json
+7 -3
@@ -46,11 +46,14 @@
46 "typecheck": "turbo typecheck --filter=./ts/packages/**",
47 "typecheck:examples": "turbo typecheck --filter='./ts/examples/*'",
48 "lint:examples": "turbo lint --filter='./ts/examples/*'",
49 - "lint": "oxlint ts test tsdown.config.base.ts && pnpm run lint:antislop",
50 - "lint:antislop": "node scripts/check-antislop.mjs",
49 + "lint": "oxlint ts test tools/oxlint tsdown.config.base.ts && pnpm run lint:antislop",
50 + "lint:antislop": "node scripts/check-antislop.mjs && pnpm run lint:effect-rules",
51 + "lint:effect-rules": "oxlint ts/packages/cli/src",
52 "lint:antislop:scan": "ast-grep scan --config sgconfig.yml --error=no-suppress-all --error=unused-suppression",
53 "lint:antislop:prune": "node scripts/check-antislop.mjs --prune",
53 - "test:antislop": "ast-grep test --config sgconfig.yml --skip-snapshot-tests && node --test test/antislop.test.mjs",
54 + "test:antislop": "ast-grep test --config sgconfig.yml --skip-snapshot-tests && node --test test/antislop.test.mjs && pnpm run test:effect-rules",
55 + "test:effect-rules": "tsx tools/oxlint/effect/rules/require-cause-when-narrowing.test.ts && tsx tools/oxlint/effect/rules/no-ordie-in-service-construction.test.ts && bun test test/effect-lint.test.ts",
56 + "typecheck:effect-rules": "tsc -p tsconfig.effect-rules.json",
57 "lint:packages": "oxlint ts/packages",
58 "lint:fix": "oxlint --fix .",
59 "lint:fix:packages": "oxlint --fix ts/packages",
@@ -98,6 +101,7 @@
101 "@composio/openai": "workspace:*",
102 "@effect/platform-bun": "catalog:",
103 "@manypkg/get-packages": "3.1.0",
104 + "@oxlint/plugins": "1.93.0",
105 "@types/bun": "catalog:",
106 "@types/node": "^26.6.6",
107 "@types/semver": "^7.8.0",
pnpm-lock.yaml
+28 -19
@@ -177,6 +177,9 @@ importers:
177 '@manypkg/get-packages':
178 specifier: 3.1.0
179 version: 3.1.0
180 + '@oxlint/plugins':
181 + specifier: 1.93.0
182 + version: 1.93.0
183 '@types/bun':
184 specifier: 'catalog:'
185 version: 1.4.4
@@ -744,7 +747,7 @@ importers:
747 version: link:../../packages/core
748 '@modelcontextprotocol/sdk':
749 specifier: 'catalog:'
747 - version: 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)
750 + version: 1.32.2(@cfworker/json-schema@4.1.6)(supports-color@10.2.2)(zod@4.6.7)
751 dotenv:
752 specifier: 'catalog:'
753 version: 18.0.10
@@ -848,7 +851,7 @@ importers:
851 version: 2.30.0(@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7))
852 '@modelcontextprotocol/sdk':
853 specifier: 'catalog:'
851 - version: 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)
854 + version: 1.32.2(@cfworker/json-schema@4.1.6)(supports-color@10.2.2)(zod@4.6.7)
855 dotenv:
856 specifier: 'catalog:'
857 version: 18.0.10
@@ -1000,7 +1003,7 @@ importers:
1003 version: link:../../packages/providers/vercel
1004 '@modelcontextprotocol/sdk':
1005 specifier: 'catalog:'
1003 - version: 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)
1006 + version: 1.32.2(@cfworker/json-schema@4.1.6)(supports-color@10.2.2)(zod@4.6.7)
1007 ai:
1008 specifier: 'catalog:'
1009 version: 7.0.166(zod@4.6.7)
@@ -1053,7 +1056,7 @@ importers:
1056 version: link:../../packages/providers/openai-agents
1057 '@modelcontextprotocol/sdk':
1058 specifier: 'catalog:'
1056 - version: 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)
1059 + version: 1.32.2(@cfworker/json-schema@4.1.6)(supports-color@10.2.2)(zod@4.6.7)
1060 '@openai/agents':
1061 specifier: ^0.21.0
1062 version: 0.21.0(@aws-sdk/credential-provider-node@3.972.87)(@smithy/signature-v4@5.7.4)(google-auth-library@10.9.1)(supports-color@10.2.2)(undici@6.29.1)(ws@8.22.2)(zod@4.6.7)
@@ -1282,7 +1285,7 @@ importers:
1285 version: link:../../packages/providers/vercel
1286 '@modelcontextprotocol/sdk':
1287 specifier: 'catalog:'
1285 - version: 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)
1288 + version: 1.32.2(@cfworker/json-schema@4.1.6)(supports-color@10.2.2)(zod@4.6.7)
1289 ai:
1290 specifier: 'catalog:'
1291 version: 7.0.166(zod@4.6.7)
@@ -1659,7 +1662,7 @@ importers:
1662 version: link:../../core
1663 '@modelcontextprotocol/sdk':
1664 specifier: 'catalog:'
1662 - version: 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)
1665 + version: 1.32.2(@cfworker/json-schema@4.1.6)(supports-color@10.2.2)(zod@4.6.7)
1666 tsdown:
1667 specifier: 'catalog:'
1668 version: 0.23.7(@arethetypeswrong/core@0.18.5)(publint@0.3.25)(tsx@4.23.15)(typescript@7.0.2)(unrun@0.2.27(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2))
@@ -3689,6 +3692,10 @@ packages:
3692 cpu: [x64]
3693 os: [win32]
3694
3695 + '@oxlint/plugins@1.93.0':
3696 + resolution: {integrity: sha512-bKWQI1g9jn8bWUZsvhbOLfgva576Fbp1KwoTNSUCMdT9tlTAvQS2JkifX1UrhPPdyN4GHvM20HhvIMqqU1yotQ==}
3697 + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
3698 +
3699 '@pnpm/deps.graph-sequencer@1100.0.1':
3700 resolution: {integrity: sha512-pOr5+q1fLYKwFN3LAJuGZEnfXDcQ73zqgDHMtGy+K+uIoUqyY+6MeDCWFwfu+4EFuq76I5EPFofoNAI+Bmmq4A==}
3701 engines: {node: '>=22.13'}
@@ -7161,7 +7168,7 @@ snapshots:
7168 '@anthropic-ai/claude-agent-sdk@0.3.322(@anthropic-ai/sdk@1.7.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7))(zod@4.6.7)':
7169 dependencies:
7170 '@anthropic-ai/sdk': 1.7.0(zod@4.6.7)
7164 - '@modelcontextprotocol/sdk': 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)
7171 + '@modelcontextprotocol/sdk': 1.32.2(@cfworker/json-schema@4.1.6)(supports-color@10.2.2)(zod@4.6.7)
7172 zod: 4.6.7
7173 optionalDependencies:
7174 '@anthropic-ai/claude-agent-sdk-darwin-arm64': 0.3.322
@@ -7982,7 +7989,7 @@ snapshots:
7989 protobufjs: 7.6.5
7990 ws: 8.21.3
7991 optionalDependencies:
7985 - '@modelcontextprotocol/sdk': 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)
7992 + '@modelcontextprotocol/sdk': 1.32.2(@cfworker/json-schema@4.1.6)(supports-color@10.2.2)(zod@4.6.7)
7993 transitivePeerDependencies:
7994 - bufferutil
7995 - supports-color
@@ -7995,7 +8002,7 @@ snapshots:
8002 protobufjs: 7.6.5
8003 ws: 8.22.0
8004 optionalDependencies:
7998 - '@modelcontextprotocol/sdk': 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)
8005 + '@modelcontextprotocol/sdk': 1.32.2(@cfworker/json-schema@4.1.6)(supports-color@10.2.2)(zod@4.6.7)
8006 transitivePeerDependencies:
8007 - bufferutil
8008 - supports-color
@@ -8008,7 +8015,7 @@ snapshots:
8015 protobufjs: 7.6.5
8016 ws: 8.22.0
8017 optionalDependencies:
8011 - '@modelcontextprotocol/sdk': 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)
8018 + '@modelcontextprotocol/sdk': 1.32.2(@cfworker/json-schema@4.1.6)(supports-color@10.2.2)(zod@4.6.7)
8019 transitivePeerDependencies:
8020 - bufferutil
8021 - supports-color
@@ -8377,7 +8384,7 @@ snapshots:
8384
8385 '@llamaindex/workflow-core@1.3.4(@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7))(hono@4.13.17)(zod@4.6.7)':
8386 optionalDependencies:
8380 - '@modelcontextprotocol/sdk': 1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)
8387 + '@modelcontextprotocol/sdk': 1.32.2(@cfworker/json-schema@4.1.6)(supports-color@10.2.2)(zod@4.6.7)
8388 hono: 4.13.17
8389 zod: 4.6.7
8390
@@ -8629,7 +8636,7 @@ snapshots:
8636 eventsource: 3.0.7
8637 eventsource-parser: 3.1.1
8638 express: 5.3.0
8632 - express-rate-limit: 8.7.1(express@5.3.0)
8639 + express-rate-limit: 8.7.1(express@5.3.0)(supports-color@10.2.2)
8640 hono: 4.13.13
8641 jose: 6.2.13
8642 json-schema-typed: 8.0.2
@@ -8653,7 +8660,7 @@ snapshots:
8660 eventsource: 3.0.7
8661 eventsource-parser: 3.1.1
8662 express: 5.3.0
8656 - express-rate-limit: 8.7.1(express@5.3.0)
8663 + express-rate-limit: 8.7.1(express@5.3.0)(supports-color@10.2.2)
8664 hono: 4.13.13
8665 jose: 6.2.13
8666 json-schema-typed: 8.0.2
@@ -8677,7 +8684,7 @@ snapshots:
8684 eventsource: 3.0.7
8685 eventsource-parser: 3.1.1
8686 express: 5.3.0
8680 - express-rate-limit: 8.7.1(express@5.3.0)
8687 + express-rate-limit: 8.7.1(express@5.3.0)(supports-color@10.2.2)
8688 hono: 4.13.13
8689 jose: 6.2.13
8690 json-schema-typed: 8.0.2
@@ -8701,7 +8708,7 @@ snapshots:
8708 eventsource: 3.0.7
8709 eventsource-parser: 3.1.1
8710 express: 5.3.0
8704 - express-rate-limit: 8.7.1(express@5.3.0)
8711 + express-rate-limit: 8.7.1(express@5.3.0)(supports-color@10.2.2)
8712 hono: 4.13.13
8713 jose: 6.2.13
8714 json-schema-typed: 8.0.2
@@ -8714,7 +8721,7 @@ snapshots:
8721 transitivePeerDependencies:
8722 - supports-color
8723
8717 - '@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.6)(zod@4.6.7)':
8724 + '@modelcontextprotocol/sdk@1.32.2(@cfworker/json-schema@4.1.6)(supports-color@10.2.2)(zod@4.6.7)':
8725 dependencies:
8726 '@hono/node-server': 2.1.6(hono@4.13.17)
8727 ajv: 8.20.0
@@ -8725,7 +8732,7 @@ snapshots:
8732 eventsource: 3.0.7
8733 eventsource-parser: 3.1.1
8734 express: 5.3.0
8728 - express-rate-limit: 8.7.1(express@5.3.0)
8735 + express-rate-limit: 8.7.1(express@5.3.0)(supports-color@10.2.2)
8736 hono: 4.13.17
8737 jose: 6.2.13
8738 json-schema-typed: 8.0.2
@@ -8743,7 +8750,7 @@ snapshots:
8750 '@modelcontextprotocol/core': 2.4.0
8751 content-type: 1.0.5
8752 cors: 2.8.6
8746 - express-rate-limit: 8.7.1(express@5.3.0)
8753 + express-rate-limit: 8.7.1(express@5.3.0)(supports-color@10.2.2)
8754 pkce-challenge: 5.0.1
8755 raw-body: 3.0.2
8756 zod: 4.6.7
@@ -8915,6 +8922,8 @@ snapshots:
8922 '@oxlint/binding-win32-x64-msvc@1.93.0':
8923 optional: true
8924
8925 + '@oxlint/plugins@1.93.0': {}
8926 +
8927 '@pnpm/deps.graph-sequencer@1100.0.1': {}
8928
8929 '@polka/url@1.0.0-next.29': {}
@@ -10000,7 +10009,7 @@ snapshots:
10009
10010 expect-type@1.4.0: {}
10011
10003 - express-rate-limit@8.7.1(express@5.3.0):
10012 + express-rate-limit@8.7.1(express@5.3.0)(supports-color@10.2.2):
10013 dependencies:
10014 debug: 4.4.3(supports-color@10.2.2)
10015 express: 5.3.0
test/effect-lint.test.ts new
+74
@@ -0,0 +1,74 @@
1 +import { expect, test } from 'bun:test';
2 +import {
3 + mkdirSync,
4 + mkdtempSync,
5 + readFileSync,
6 + realpathSync,
7 + rmSync,
8 + symlinkSync,
9 + writeFileSync,
10 +} from 'node:fs';
11 +import { tmpdir } from 'node:os';
12 +import { dirname, join, resolve } from 'node:path';
13 +import { fileURLToPath } from 'node:url';
14 +
15 +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
16 +const oxlint = join(root, 'node_modules/oxlint/bin/oxlint');
17 +
18 +test('the repository config enforces both Effect rules only in CLI source', () => {
19 + const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'composio-effect-lint-')));
20 + const config = join(cwd, '.oxlintrc.json');
21 + symlinkSync(join(root, 'node_modules'), join(cwd, 'node_modules'), 'dir');
22 + writeFileSync(
23 + config,
24 + readFileSync(join(root, '.oxlintrc.json'), 'utf8').replace(
25 + './tools/oxlint/effect/index.ts',
26 + join(root, 'tools/oxlint/effect/index.ts')
27 + )
28 + );
29 + const source = `
30 + import { Context, Effect, Layer } from 'effect';
31 + class Client extends Context.Service<Client, {}>()('Client') {
32 + static make = Effect.gen(function* () {
33 + yield* load.pipe(Effect.orDie);
34 + return {};
35 + });
36 + }
37 + const result = load.pipe(Effect.mapError(() => new Failed()));
38 + `;
39 + const lint = (filename: string) => {
40 + const file = join(cwd, filename);
41 + mkdirSync(dirname(file), { recursive: true });
42 + writeFileSync(file, source);
43 + const result = Bun.spawnSync(['node', oxlint, '-c', config, '--format', 'json', filename], {
44 + cwd,
45 + });
46 + expect(result.stderr.toString()).toBe('');
47 + const output = JSON.parse(result.stdout.toString());
48 + return {
49 + status: result.exitCode,
50 + rules: output.diagnostics
51 + .map((diagnostic: { code: string }) => diagnostic.code)
52 + .filter((code: string) => code.startsWith('composio-effect(')),
53 + };
54 + };
55 + try {
56 + expect(lint('ts/packages/cli/src/services/lint-fixture.ts')).toEqual({
57 + status: 1,
58 + rules: expect.arrayContaining([
59 + 'composio-effect(require-cause-when-narrowing)',
60 + 'composio-effect(no-ordie-in-service-construction)',
61 + ]),
62 + });
63 + for (const file of [
64 + 'ts/packages/core/src/lint-fixture.ts',
65 + 'ts/packages/cli/test/lint-fixture.ts',
66 + 'ts/packages/cli/src/services/lint-fixture.test.ts',
67 + 'ts/packages/cli/src/services/__fixtures__/lint-fixture.ts',
68 + ]) {
69 + expect(lint(file).rules).toEqual([]);
70 + }
71 + } finally {
72 + rmSync(cwd, { recursive: true, force: true });
73 + }
74 +});
tools/oxlint/effect/LICENSE new
+21
@@ -0,0 +1,21 @@
1 +MIT License
2 +
3 +Copyright (c) 2026 Dillon Mulroy
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.
tools/oxlint/effect/UPSTREAM.md new
+19
@@ -0,0 +1,19 @@
1 +# Effect lint rules
2 +
3 +Adapted from [K-Mistele/anti-slop](https://github.com/K-Mistele/anti-slop/tree/b7c1619b4d51b4815e89ba3700a975a6ec54b8c3),
4 +commit `b7c1619b4d51b4815e89ba3700a975a6ec54b8c3` (MIT, copyright Dillon Mulroy).
5 +The license is preserved in [LICENSE](LICENSE).
6 +
7 +Borrowed files: `src/effect/rules/require-cause-when-narrowing.ts`,
8 +`src/effect/rules/no-ordie-in-service-construction.ts`, their fixtures, and the
9 +parts of `src/effect/shared/effect-modules.ts` those rules use.
10 +
11 +Local changes adapt the diagnostics to Composio's tagged-error conventions,
12 +remove unused helpers, and register only these two rules as `composio-effect`.
13 +Import recognition also resolves lexical bindings, so a local parameter that
14 +shadows an Effect import is not treated as the Effect module.
15 +Local traversal handles conditional error replacements, property values yielded
16 +during construction, and transparent wrappers around service options while
17 +preserving deferred service operations.
18 +These are syntax and same-file scope checks, not type checking or a proof that
19 +every failure retains its cause.
tools/oxlint/effect/index.ts new
+11
@@ -0,0 +1,11 @@
1 +import { eslintCompatPlugin } from '@oxlint/plugins';
2 +import { noOrDieInServiceConstructionRule } from './rules/no-ordie-in-service-construction.ts';
3 +import { requireCauseWhenNarrowingRule } from './rules/require-cause-when-narrowing.ts';
4 +
5 +export default eslintCompatPlugin({
6 + meta: { name: 'composio-effect' },
7 + rules: {
8 + 'require-cause-when-narrowing': requireCauseWhenNarrowingRule,
9 + 'no-ordie-in-service-construction': noOrDieInServiceConstructionRule,
10 + },
11 +});
tools/oxlint/effect/rules/no-ordie-in-service-construction.test.ts new
+185
@@ -0,0 +1,185 @@
1 +import { RuleTester } from 'oxlint/plugins-dev';
2 +
3 +import { noOrDieInServiceConstructionRule } from './no-ordie-in-service-construction.ts';
4 +
5 +const tester = new RuleTester({ languageOptions: { parserOptions: { lang: 'ts' } } });
6 +const imports = `
7 + import * as Context from "effect/Context";
8 + import * as Effect from "effect/Effect";
9 + import * as Layer from "effect/Layer";
10 +`;
11 +const constructionOrDie = { messageId: 'constructionOrDie', data: { member: 'orDie' } };
12 +const constructionOptions = `{
13 + make: Effect.gen(function* () {
14 + const token = yield* load.pipe(Effect.orDie);
15 + return { token };
16 + }),
17 +}`;
18 +const serviceCall = (options: string) =>
19 + `Context.Service<Client, ClientShape>()("Client", ${options})`;
20 +
21 +tester.run('anti-slop-effect/no-ordie-in-service-construction', noOrDieInServiceConstructionRule, {
22 + valid: [
23 + `import { Layer } from "effect";
24 + function build(Layer: OtherLibrary) { return live.pipe(Layer.orDie); }`,
25 + `${imports}
26 + const ordinary = define(({ make: Effect.gen(function* () {
27 + return yield* load.pipe(Effect.orDie);
28 + }) } satisfies Options));
29 + class NotService extends (define(({ make: Effect.gen(function* () {
30 + return yield* load.pipe(Effect.orDie);
31 + }) } as Options)) as Constructor) {}`,
32 + `${imports}
33 + class Store extends (Context.Service<Store, StoreShape>()("Store", ({
34 + make: Effect.gen(function* () {
35 + return { find: () => Effect.gen(function* () {
36 + return yield* load.pipe(Effect.orDie);
37 + }) };
38 + }),
39 + } satisfies Options)) as Constructor) {}`,
40 + `import { Context } from "other-library";
41 + import { Effect } from "effect";
42 + class OtherService extends (Context.Service<OtherService, OtherShape>()("Other", ({
43 + make: Effect.gen(function* () { return yield* load.pipe(Effect.orDie); }),
44 + } satisfies Options)) as Constructor) {}`,
45 + // orDie inside an operation of the returned service.
46 + `${imports}
47 + export class Store extends Context.Service<Store, StoreShape>()("@app/Store", {
48 + make: Effect.gen(function* () {
49 + const sql = yield* Sql;
50 + return {
51 + find: (id: string) => Effect.gen(function* () {
52 + return yield* sql.find(id).pipe(Effect.orDie);
53 + }),
54 + list: Effect.orDie(sql.list),
55 + };
56 + }),
57 + }) {
58 + static readonly layer = Layer.effect(this, this.make);
59 + }`,
60 + // orDie inside an Effect.fn operation and in an effect make defines without running it.
61 + `${imports}
62 + export class Store extends Context.Service<Store, StoreShape>()("@app/Store", {
63 + make: Effect.gen(function* () {
64 + const find = Effect.fn("Store.find")(function* (id: string) {
65 + return yield* lookup(id).pipe(Effect.orDie);
66 + });
67 + const unwrap = Effect.fnUntraced(function* (id: string) { return id; }, Effect.orDie);
68 + const collect = Stream.runCollect(entries).pipe(Effect.orDie);
69 + return { find, unwrap, collect };
70 + }),
71 + }) {
72 + static readonly layer = Layer.effect(this, this.make);
73 + }`,
74 + // orDie outside service construction.
75 + `${imports}
76 + const program = Effect.gen(function* () {
77 + yield* risky.pipe(Effect.orDie);
78 + });`,
79 + `${imports}
80 + class Store extends Context.Service<Store, StoreShape>()("Store", {
81 + make: Effect.gen(function* () {
82 + return {
83 + nested: { later: Effect.gen(function* () { return yield* load.pipe(Effect.orDie); }) },
84 + [key]: load.pipe(Effect.orDie),
85 + };
86 + }),
87 + }) {}`,
88 + {
89 + filename: 'store.test.ts',
90 + code: `${imports}
91 + const layer = Store.layer.pipe(Layer.orDie);`,
92 + },
93 + // Not Effect's Layer.
94 + `
95 + import * as Layer from "other-library";
96 + const layer = live.pipe(Layer.orDie);`,
97 + ],
98 + invalid: [
99 + ...[
100 + serviceCall(`(${constructionOptions})`),
101 + serviceCall(`${constructionOptions} as Options`),
102 + serviceCall(`<Options>${constructionOptions}`),
103 + serviceCall(`${constructionOptions} satisfies Options`),
104 + `(${serviceCall(constructionOptions)})`,
105 + `(${serviceCall(constructionOptions)} as Constructor)`,
106 + `(<Constructor>${serviceCall(constructionOptions)})`,
107 + `(${serviceCall(constructionOptions)} satisfies Constructor)`,
108 + `(((${serviceCall(`((${constructionOptions} as Options) satisfies Options)`)} as Constructor) satisfies Constructor))`,
109 + ].map(extendsExpression => ({
110 + code: `${imports} class Client extends ${extendsExpression} {}`,
111 + errors: [constructionOrDie],
112 + })),
113 + {
114 + code: `${imports}
115 + class Client extends Context.Service<Client, ClientShape>()("Client", {
116 + make: Effect.gen(function* () {
117 + return {
118 + token: yield* load.pipe(Effect.orDie),
119 + nested: { token: yield* load.pipe(Effect.orDie) },
120 + [yield* key.pipe(Effect.orDie)]: true,
121 + };
122 + }),
123 + }) {}`,
124 + errors: [constructionOrDie, constructionOrDie, constructionOrDie],
125 + },
126 + {
127 + code: `import { Context as Ctx, Effect as Fx, Layer as L } from "effect";
128 + class Client extends Ctx.Service<Client, {}>()("Client") {
129 + static make = Fx.gen(function* () {
130 + yield* load.pipe(Fx.orDie);
131 + return {};
132 + });
133 + }
134 + const layer = live.pipe(L.orDie);`,
135 + errors: [constructionOrDie, { messageId: 'layerOrDie' }],
136 + },
137 + {
138 + code: `${imports}
139 + export class Client extends Context.Service<Client, ClientShape>()("@app/Client", {
140 + make: Effect.gen(function* () {
141 + const token = yield* Config.string("TOKEN").pipe(Effect.orDie);
142 + return { token };
143 + }),
144 + }) {
145 + static readonly layer = Layer.effect(this, this.make);
146 + }`,
147 + errors: [constructionOrDie],
148 + },
149 + {
150 + code: `${imports}
151 + export class Client extends Context.Service<Client, ClientShape>()("@app/Client", {
152 + make: Effect.gen(function* () {
153 + return {};
154 + }).pipe(Effect.orDieWith((error) => error)),
155 + }) {
156 + static readonly layer = Layer.effect(this, this.make);
157 + }`,
158 + errors: [{ messageId: 'constructionOrDie', data: { member: 'orDieWith' } }],
159 + },
160 + {
161 + code: `${imports}
162 + export class Database extends Context.Service<Database, DatabaseShape>()("@app/Database") {
163 + static readonly make = (file: string) => Effect.gen(function* () {
164 + yield* migrate(file).pipe(Effect.orDie);
165 + return {};
166 + });
167 + static readonly layer = (file: string) => Layer.effect(this, this.make(file));
168 + }`,
169 + errors: [constructionOrDie],
170 + },
171 + {
172 + code: `${imports}
173 + export const live = Layer.effect(Store, Effect.gen(function* () {
174 + const key = yield* Effect.suspend(() => loadKey.pipe(Effect.orDie));
175 + return { key };
176 + }));`,
177 + errors: [constructionOrDie],
178 + },
179 + {
180 + code: `${imports}
181 + const logLayer = layerJsonl(path).pipe(Layer.orDie);`,
182 + errors: [{ messageId: 'layerOrDie' }],
183 + },
184 + ],
185 +});
tools/oxlint/effect/rules/no-ordie-in-service-construction.ts new
+166
@@ -0,0 +1,166 @@
1 +import { defineRule } from '@oxlint/plugins';
2 +
3 +import type { ESTree } from '@oxlint/plugins';
4 +
5 +import {
6 + collectEffectModuleNames,
7 + isFunction,
8 + isTestFile,
9 + keyName,
10 + moduleCallName,
11 + moduleMemberName,
12 + serviceClass,
13 + unwrapNode,
14 + type EffectModuleNames,
15 +} from '../shared/effect-modules.ts';
16 +
17 +const orDieMembers: ReadonlySet<string> = new Set(['orDie', 'orDieWith']);
18 +/** Effect constructors whose function argument runs as part of the surrounding construction. */
19 +const transparentThunks: ReadonlySet<string> = new Set(['suspend', 'sync']);
20 +/** Effect constructors that define an operation; their arguments run when it is called, not during construction. */
21 +const operationConstructors: ReadonlySet<string> = new Set(['fn', 'fnUntraced']);
22 +const isLayerMemberName = (name: string): boolean =>
23 + name === 'layer' || /^layer[A-Z0-9_]/u.test(name);
24 +const isLayerConstructor = (name: string | null): boolean =>
25 + name === 'effect' || name === 'scoped' || (name?.startsWith('unwrap') ?? false);
26 +
27 +function isServiceClassNode(node: ESTree.Node | null, names: EffectModuleNames): boolean {
28 + return (
29 + (node?.type === 'ClassDeclaration' || node?.type === 'ClassExpression') &&
30 + serviceClass(node, names) !== null
31 + );
32 +}
33 +
34 +/** The parent outside parentheses and erased TypeScript expression wrappers. */
35 +function expressionParent(node: ESTree.Node): ESTree.Node | null {
36 + let current = node;
37 + while (current.parent !== null && unwrapNode(current.parent) === node) {
38 + current = current.parent;
39 + }
40 + return current.parent;
41 +}
42 +
43 +/** Whether `node`, entered from `child`, is where a service is constructed. */
44 +function isConstructionRoot(
45 + node: ESTree.Node,
46 + child: ESTree.Node,
47 + names: EffectModuleNames
48 +): boolean {
49 + if (
50 + (node.type === 'PropertyDefinition' || node.type === 'MethodDefinition') &&
51 + node.static &&
52 + !node.computed
53 + ) {
54 + const name = keyName(node.key);
55 + return (
56 + node.value === child &&
57 + name !== null &&
58 + (name === 'make' || isLayerMemberName(name)) &&
59 + isServiceClassNode(node.parent.parent, names)
60 + );
61 + }
62 + if (
63 + node.type === 'Property' &&
64 + !node.computed &&
65 + node.value === child &&
66 + keyName(node.key) === 'make'
67 + ) {
68 + const options = node.parent;
69 + if (options.type !== 'ObjectExpression') return false;
70 + const superCall = expressionParent(options);
71 + if (superCall?.type !== 'CallExpression') return false;
72 + const owner = expressionParent(superCall);
73 + return (
74 + (owner?.type === 'ClassDeclaration' || owner?.type === 'ClassExpression') &&
75 + serviceClass(owner, names)?.options === options
76 + );
77 + }
78 + if (node.type === 'CallExpression' && node.arguments.some(argument => argument === child)) {
79 + return isLayerConstructor(moduleCallName(node, names, 'Layer'));
80 + }
81 + return false;
82 +}
83 +
84 +/** The Effect constructor a function is passed to, such as `gen` for `Effect.gen(function* () {})`. */
85 +function effectConstructorOf(fn: ESTree.Node, names: EffectModuleNames): string | null {
86 + const parent = fn.parent;
87 + if (parent?.type !== 'CallExpression' || !parent.arguments.some(argument => argument === fn))
88 + return null;
89 + return moduleCallName(parent, names, 'Effect');
90 +}
91 +
92 +/** Whether `node` is `Effect.fn(...)(...)` or `Effect.fnUntraced(...)`: an operation definition. */
93 +function isOperationDefinition(node: ESTree.Node, names: EffectModuleNames): boolean {
94 + if (node.type !== 'CallExpression') return false;
95 + const direct = moduleCallName(node, names, 'Effect');
96 + if (direct !== null && operationConstructors.has(direct)) return true;
97 + const curried = moduleCallName(node.callee, names, 'Effect');
98 + return curried !== null && operationConstructors.has(curried);
99 +}
100 +
101 +/**
102 + * Whether `node` runs while the service is constructed. Construction stops at operation boundaries: functions other
103 + * than Effect.gen generators and suspend/sync thunks, Effect.fn definitions, object-literal properties without a
104 + * delegated yield (operations in the returned service or callbacks in options), and effects a generator defines without yielding.
105 + */
106 +function isInServiceConstruction(node: ESTree.Node, names: EffectModuleNames): boolean {
107 + let child: ESTree.Node = node;
108 + let current: ESTree.Node | null = node.parent;
109 + let yielded = false;
110 + while (current !== null) {
111 + if (isFunction(current)) {
112 + if (current.parent !== null && isConstructionRoot(current.parent, current, names))
113 + return true;
114 + const constructor = effectConstructorOf(current, names);
115 + if (constructor === 'gen') {
116 + if (!yielded) return false;
117 + yielded = false;
118 + } else if (constructor === null || !transparentThunks.has(constructor)) {
119 + return false;
120 + }
121 + } else if (isConstructionRoot(current, child, names)) {
122 + return true;
123 + } else if ((current.type === 'Property' && !yielded) || isOperationDefinition(current, names)) {
124 + return false;
125 + } else if (current.type === 'YieldExpression' && current.delegate) {
126 + yielded = true;
127 + }
128 + child = current;
129 + current = current.parent;
130 + }
131 + return false;
132 +}
133 +
134 +/** Keep service construction failures typed instead of turning them into defects. */
135 +export const noOrDieInServiceConstructionRule = defineRule({
136 + meta: {
137 + type: 'problem',
138 + docs: {
139 + description:
140 + 'Disallow `Effect.orDie` while constructing a service (its make, its static layers, or Layer.effect/unwrap arguments) and `Layer.orDie` anywhere.',
141 + },
142 + messages: {
143 + constructionOrDie:
144 + "`Effect.{{member}}` turns a service construction failure into a defect. Classify the failure as a Data.TaggedError (or Schema.TaggedError when encoding is needed) and let it flow through the layer's error channel (`Layer.Layer<Service, ThatError>`), or handle it here with Effect.catchTag.",
145 + layerOrDie:
146 + "`Layer.orDie` hides this layer's construction failures as defects. Leave them in the layer's error channel as tagged errors and handle them where the runtime is built.",
147 + },
148 + },
149 + create(context) {
150 + if (isTestFile(context.filename)) return {};
151 + const names = collectEffectModuleNames(context.sourceCode);
152 +
153 + return {
154 + MemberExpression(node) {
155 + if (moduleMemberName(node, names, 'Layer') === 'orDie') {
156 + context.report({ node, messageId: 'layerOrDie' });
157 + return;
158 + }
159 + const member = moduleMemberName(node, names, 'Effect');
160 + if (member === null || !orDieMembers.has(member) || !isInServiceConstruction(node, names))
161 + return;
162 + context.report({ node, messageId: 'constructionOrDie', data: { member } });
163 + },
164 + };
165 + },
166 +});
tools/oxlint/effect/rules/require-cause-when-narrowing.test.ts new
+111
@@ -0,0 +1,111 @@
1 +import { RuleTester } from 'oxlint/plugins-dev';
2 +
3 +import { requireCauseWhenNarrowingRule } from './require-cause-when-narrowing.ts';
4 +
5 +const tester = new RuleTester({ languageOptions: { parserOptions: { lang: 'ts' } } });
6 +const imports = `
7 + import * as Effect from "effect/Effect";
8 +`;
9 +const missingCause = (operator: string, error: string) => ({
10 + messageId: 'missingCause',
11 + data: { operator, error },
12 +});
13 +
14 +tester.run('anti-slop-effect/require-cause-when-narrowing', requireCauseWhenNarrowingRule, {
15 + valid: [
16 + // A parameter can shadow an Effect import without referring to Effect.
17 + `import { Effect } from "effect";
18 + function recover(Effect: OtherLibrary) {
19 + return load.pipe(Effect.mapError(() => new Failed()));
20 + }`,
21 + `${imports}
22 + const a = decode(text).pipe(Effect.mapError((cause) => BadRequest.make({ reason: "Invalid JSON", cause })));
23 + const b = decode(text).pipe(Effect.mapError((error) => new BadRequest({ reason: error.message })));
24 + const c = decode(text).pipe(Effect.mapError(() => BadRequest.make({ reason: "Invalid JSON", ...details })));`,
25 + // Capture before narrowing.
26 + `${imports}
27 + const a = decode(text).pipe(Effect.tapError(Effect.logError), Effect.mapError(() => BadRequest.make({ reason: "Invalid JSON" })));
28 + const b = Effect.fn("decode")(function* () {}, Effect.tapCause(Effect.logError), Effect.catch(() => Effect.fail(new Failed())));
29 + const c = Effect.mapError(Effect.tapErrorCause(decode(text), Effect.logError), () => new Failed());`,
30 + // Specific expected tags are handled on purpose.
31 + `${imports}
32 + const a = load.pipe(Effect.catchTag("NotFound", () => Effect.fail(new Missing())));
33 + const b = load.pipe(Effect.catchTags({ NotFound: () => Effect.fail(new Missing()) }));`,
34 + // Recovering with a value, or constructing inside a nested function, is not narrowing.
35 + `${imports}
36 + const a = load.pipe(Effect.orElse(() => Effect.succeed(new Fallback())));
37 + const b = load.pipe(Effect.catch(() => Effect.sync(() => new Fallback())));
38 + const c = load.pipe(Effect.catch(() => Effect.succeed(Option.make(1))));`,
39 + `${imports}
40 + const preserved = load.pipe(Effect.mapError(() => retryable
41 + ? new RetryFailed({ cause })
42 + : Failed.make({ cause })));
43 + const recovered = load.pipe(Effect.catch(() => retryable
44 + ? Effect.succeed(new Fallback())
45 + : Effect.sync(() => new OtherFallback())));
46 + const deferred = load.pipe(Effect.catch(() => () => retryable
47 + ? new RetryFailed()
48 + : new Failed()));
49 + const discarded = load.pipe(Effect.mapError(() => (new Discarded(), Failed.make({ cause }))));
50 + const truthy = load.pipe(Effect.mapError(() => new Discarded() && Failed.make({ cause })));`,
51 + // Not Effect's Effect.
52 + `
53 + import * as Effect from "other-library";
54 + const a = load.pipe(Effect.mapError(() => new Failed()));`,
55 + ],
56 + invalid: [
57 + {
58 + code: `${imports}
59 + const conditional = load.pipe(Effect.mapError(() => retryable ? new RetryFailed() : new Failed()));
60 + const nested = load.pipe(Effect.mapError(() => retryable
61 + ? Failed.make({ cause })
62 + : offline ? Failed.make({ cause }) : new Offline()));
63 + const logical = load.pipe(Effect.mapError(() => fallback ?? new Missing()));
64 + const sequence = load.pipe(Effect.mapError(() => (record(), new Failed())));
65 + const failed = load.pipe(Effect.catch(() => Effect.fail(retryable ? new RetryFailed() : new Failed())));`,
66 + errors: [
67 + missingCause('Effect.mapError', 'RetryFailed'),
68 + missingCause('Effect.mapError', 'Offline'),
69 + missingCause('Effect.mapError', 'Missing'),
70 + missingCause('Effect.mapError', 'Failed'),
71 + missingCause('Effect.catch', 'RetryFailed'),
72 + ],
73 + },
74 + {
75 + code: `import { Effect as Fx } from "effect";
76 + const result = load.pipe(Fx.mapError(() => new Failed()));`,
77 + errors: [missingCause('Effect.mapError', 'Failed')],
78 + },
79 + {
80 + code: `${imports}
81 + const a = decode(text).pipe(Effect.mapError(() => BadRequest.make({ reason: "Invalid JSON" })));`,
82 + errors: [missingCause('Effect.mapError', 'BadRequest')],
83 + },
84 + {
85 + code: `${imports}
86 + const a = Effect.mapError(decode(text), (_error) => new McpDialFailed({ message: "bad frame" }));`,
87 + errors: [missingCause('Effect.mapError', 'McpDialFailed')],
88 + },
89 + {
90 + code: `${imports}
91 + const a = read.pipe(Effect.catch(() => AuthUnavailable.make({ error: "unavailable" })));
92 + const b = read.pipe(Effect.catchAll(() => Effect.fail(new Unavailable())));
93 + const c = read.pipe(Effect.orElse(() => Effect.gen(function* () {
94 + return yield* new Unavailable({ reason: "down" });
95 + })));
96 + const d = read.pipe(Effect.catchCause(() => { return Effect.fail(Errors.Unavailable.make()); }));`,
97 + errors: [
98 + missingCause('Effect.catch', 'AuthUnavailable'),
99 + missingCause('Effect.catchAll', 'Unavailable'),
100 + missingCause('Effect.orElse', 'Unavailable'),
101 + missingCause('Effect.catchCause', 'Errors.Unavailable'),
102 + ],
103 + },
104 + {
105 + code: `${imports}
106 + const a = read.pipe(Effect.tapError(Effect.logError)).pipe(Effect.map(f), Effect.mapError(() => new Failed()));
107 + const b = read.pipe(Effect.mapError(() => new Failed()), Effect.tapError(Effect.logError));`,
108 + errors: [missingCause('Effect.mapError', 'Failed')],
109 + },
110 + ],
111 +});
tools/oxlint/effect/rules/require-cause-when-narrowing.ts new
+195
@@ -0,0 +1,195 @@
1 +import { defineRule } from '@oxlint/plugins';
2 +
3 +import type { ESTree, SourceCode } from '@oxlint/plugins';
4 +
5 +import {
6 + collectEffectModuleNames,
7 + genFunction,
8 + isFunction,
9 + keyName,
10 + moduleCallName,
11 + moduleMemberName,
12 + precedingSteps,
13 + returnedExpressions,
14 + unwrapNode,
15 + walk,
16 + type EffectModuleNames,
17 + type FunctionNode,
18 +} from '../shared/effect-modules.ts';
19 +
20 +const narrowingOperators: ReadonlySet<string> = new Set([
21 + 'mapError',
22 + 'catch',
23 + 'catchAll',
24 + 'catchCause',
25 + 'orElse',
26 +]);
27 +const tapOperators: ReadonlySet<string> = new Set([
28 + 'tapError',
29 + 'tapErrorCause',
30 + 'tapCause',
31 + 'tapErrorTag',
32 +]);
33 +const effectModuleNamesList: readonly ('Context' | 'Effect' | 'Layer' | 'ManagedRuntime')[] = [
34 + 'Context',
35 + 'Effect',
36 + 'Layer',
37 + 'ManagedRuntime',
38 +];
39 +
40 +/** Whether the handler never reads the error it receives. */
41 +function ignoresError(handler: FunctionNode, sourceCode: SourceCode): boolean {
42 + const [parameter] = handler.params;
43 + if (parameter === undefined) return true;
44 + if (parameter.type !== 'Identifier') return false;
45 + const variable = sourceCode
46 + .getDeclaredVariables(handler)
47 + .find(candidate => candidate.identifiers.some(identifier => identifier === parameter));
48 + return variable !== undefined && variable.references.length === 0;
49 +}
50 +
51 +/** `new X(...)` or `X.make(...)` for a capitalized `X` that is not an Effect module. */
52 +function isErrorConstruction(
53 + node: ESTree.Node,
54 + names: EffectModuleNames
55 +): node is ESTree.NewExpression | ESTree.CallExpression {
56 + if (node.type === 'NewExpression')
57 + return (
58 + unwrapNode(node.callee).type === 'Identifier' ||
59 + unwrapNode(node.callee).type === 'MemberExpression'
60 + );
61 + if (node.type !== 'CallExpression') return false;
62 + const callee = unwrapNode(node.callee);
63 + if (
64 + callee.type !== 'MemberExpression' ||
65 + callee.computed ||
66 + callee.property.type !== 'Identifier' ||
67 + callee.property.name !== 'make'
68 + ) {
69 + return false;
70 + }
71 + const owner = unwrapNode(callee.object);
72 + const ownerName =
73 + owner.type === 'Identifier'
74 + ? owner.name
75 + : owner.type === 'MemberExpression' && owner.property.type === 'Identifier'
76 + ? owner.property.name
77 + : null;
78 + if (ownerName === null || !/^[A-Z]/u.test(ownerName)) return false;
79 + return !effectModuleNamesList.some(module => moduleMemberName(callee, names, module) !== null);
80 +}
81 +
82 +/** Whether any argument is an object literal with a `cause` property or a spread that may supply one. */
83 +function passesCause(node: ESTree.NewExpression | ESTree.CallExpression): boolean {
84 + return node.arguments.some(argument => {
85 + const expression = unwrapNode(argument);
86 + return (
87 + expression.type === 'ObjectExpression' &&
88 + expression.properties.some(
89 + property =>
90 + property.type === 'SpreadElement' ||
91 + (!property.computed && keyName(property.key) === 'cause')
92 + )
93 + );
94 + });
95 +}
96 +
97 +/** The constructed errors a handler produces without descending into nested functions. */
98 +function constructedErrors(
99 + handler: FunctionNode,
100 + names: EffectModuleNames
101 +): readonly (ESTree.NewExpression | ESTree.CallExpression)[] {
102 + const found: (ESTree.NewExpression | ESTree.CallExpression)[] = [];
103 + const consider = (node: ESTree.Node) => {
104 + const expression = unwrapNode(node);
105 + if (expression.type === 'YieldExpression' && expression.argument !== null) {
106 + consider(expression.argument);
107 + return;
108 + }
109 + if (expression.type === 'ConditionalExpression') {
110 + consider(expression.consequent);
111 + consider(expression.alternate);
112 + return;
113 + }
114 + if (expression.type === 'LogicalExpression') {
115 + // An object constructor is truthy, so && cannot return its left operand.
116 + if (expression.operator !== '&&') consider(expression.left);
117 + consider(expression.right);
118 + return;
119 + }
120 + if (expression.type === 'SequenceExpression') {
121 + const last = expression.expressions.at(-1);
122 + if (last !== undefined) consider(last);
123 + return;
124 + }
125 + if (isErrorConstruction(expression, names)) found.push(expression);
126 + };
127 + for (const returned of returnedExpressions(handler)) consider(returned);
128 + if (handler.body === null) return found;
129 + walk(handler.body, node => {
130 + // An Effect.gen generator runs as the handler's own effect; other nested functions run later, if at all.
131 + if (isFunction(node))
132 + return node.type === 'FunctionExpression' && genFunction(node.parent, names) === node;
133 + if (moduleCallName(node, names, 'Effect') === 'fail' && node.type === 'CallExpression') {
134 + const [argument] = node.arguments;
135 + if (argument !== undefined) consider(argument);
136 + }
137 + if (node.type === 'YieldExpression' && node.delegate && node.argument !== null)
138 + consider(node.argument);
139 + return true;
140 + });
141 + return [...new Set(found)];
142 +}
143 +
144 +/** Whether `node` is a call of a tap operator, or the operator itself. */
145 +function isTapStep(node: ESTree.Node, names: EffectModuleNames): boolean {
146 + const expression = unwrapNode(node);
147 + const member =
148 + moduleCallName(expression, names, 'Effect') ?? moduleMemberName(expression, names, 'Effect');
149 + return member !== null && tapOperators.has(member);
150 +}
151 +
152 +/** Require narrowing handlers that replace an error to keep the original as `cause`. */
153 +export const requireCauseWhenNarrowingRule = defineRule({
154 + meta: {
155 + type: 'problem',
156 + docs: {
157 + description:
158 + 'Require Effect.mapError/catch/catchAll/catchCause/orElse handlers that construct a new error to keep the original error as `cause`.',
159 + },
160 + messages: {
161 + missingCause:
162 + "This {{operator}} handler discards the original error and constructs a new one without it. Name the handler's parameter and pass it as `cause` (`(error) => new {{error}}({ ..., cause: error })`), or log it first with `Effect.tapError(Effect.logError)` before narrowing.",
163 + },
164 + },
165 + create(context) {
166 + const names = collectEffectModuleNames(context.sourceCode);
167 +
168 + return {
169 + CallExpression(node) {
170 + const operator = moduleCallName(node, names, 'Effect');
171 + if (operator === null || !narrowingOperators.has(operator)) return;
172 + const handler = node.arguments.at(-1);
173 + if (handler === undefined || !isFunction(handler)) return;
174 + if (!ignoresError(handler, context.sourceCode)) return;
175 + const constructed = constructedErrors(handler, names).find(
176 + construction => !passesCause(construction)
177 + );
178 + if (constructed === undefined) return;
179 + const dataFirstSource = node.arguments.length > 1 ? node.arguments[0] : undefined;
180 + const earlier = dataFirstSource === undefined ? precedingSteps(node) : [dataFirstSource];
181 + if (earlier.some(step => isTapStep(step, names))) return;
182 + const callee = unwrapNode(constructed.callee);
183 + const errorName =
184 + callee.type === 'MemberExpression'
185 + ? context.sourceCode.getText(callee.object)
186 + : context.sourceCode.getText(callee);
187 + context.report({
188 + node: constructed,
189 + messageId: 'missingCause',
190 + data: { operator: `Effect.${operator}`, error: errorName },
191 + });
192 + },
193 + };
194 + },
195 +});
tools/oxlint/effect/shared/effect-modules.ts new
+270
@@ -0,0 +1,270 @@
1 +import type { ESTree, Scope, SourceCode, Variable } from '@oxlint/plugins';
2 +
3 +/** Resolve an identifier node to its binding by walking lexical scopes upward. */
4 +export function resolveIdentifier(
5 + sourceCode: SourceCode,
6 + identifier: ESTree.Node & { readonly name: string }
7 +): Variable | null {
8 + let scope: Scope | null = sourceCode.getScope(identifier);
9 + while (scope !== null) {
10 + const variable = scope.set.get(identifier.name);
11 + if (variable !== undefined) return variable;
12 + scope = scope.upper;
13 + }
14 + return null;
15 +}
16 +
17 +/** Effect modules whose members the Effect rules recognize. */
18 +export type EffectModule = 'Context' | 'Effect' | 'Layer' | 'ManagedRuntime';
19 +
20 +const effectModules: ReadonlySet<string> = new Set<EffectModule>([
21 + 'Context',
22 + 'Effect',
23 + 'Layer',
24 + 'ManagedRuntime',
25 +]);
26 +
27 +/** Local names bound to each Effect module by the file's imports. */
28 +export interface EffectModuleNames {
29 + readonly sourceCode: SourceCode;
30 + readonly modules: ReadonlyMap<EffectModule, ReadonlySet<string>>;
31 +}
32 +
33 +const isEffectModule = (name: string): name is EffectModule => effectModules.has(name);
34 +
35 +const importedName = (specifier: ESTree.ImportSpecifier): string =>
36 + specifier.imported.type === 'Identifier' ? specifier.imported.name : specifier.imported.value;
37 +
38 +/** Collect `import { Effect } from "effect"` and `import * as Effect from "effect/Effect"` bindings. */
39 +export function collectEffectModuleNames(sourceCode: SourceCode): EffectModuleNames {
40 + const names = new Map<EffectModule, Set<string>>();
41 + const add = (module: EffectModule, local: string) => {
42 + const existing = names.get(module) ?? new Set<string>();
43 + existing.add(local);
44 + names.set(module, existing);
45 + };
46 +
47 + for (const statement of sourceCode.ast.body) {
48 + if (statement.type !== 'ImportDeclaration') continue;
49 + const source = statement.source.value;
50 + if (source === 'effect') {
51 + for (const specifier of statement.specifiers) {
52 + if (specifier.type !== 'ImportSpecifier') continue;
53 + const name = importedName(specifier);
54 + if (isEffectModule(name)) add(name, specifier.local.name);
55 + }
56 + continue;
57 + }
58 + const module = source.startsWith('effect/') ? source.slice('effect/'.length) : '';
59 + if (!isEffectModule(module)) continue;
60 + for (const specifier of statement.specifiers) {
61 + if (
62 + specifier.type === 'ImportNamespaceSpecifier' ||
63 + specifier.type === 'ImportDefaultSpecifier'
64 + ) {
65 + add(module, specifier.local.name);
66 + }
67 + }
68 + }
69 +
70 + return { sourceCode, modules: names };
71 +}
72 +
73 +/** Strip parentheses, type assertions and instantiation expressions from an expression. */
74 +export function unwrapExpression(expression: ESTree.Expression): ESTree.Expression {
75 + let current = expression;
76 + while (
77 + current.type === 'ParenthesizedExpression' ||
78 + current.type === 'TSAsExpression' ||
79 + current.type === 'TSSatisfiesExpression' ||
80 + current.type === 'TSTypeAssertion' ||
81 + current.type === 'TSNonNullExpression' ||
82 + current.type === 'TSInstantiationExpression'
83 + ) {
84 + current = current.expression;
85 + }
86 + return current;
87 +}
88 +
89 +/** Like {@link unwrapExpression}, for any node. */
90 +export function unwrapNode(node: ESTree.Node): ESTree.Node {
91 + let current = node;
92 + while (
93 + current.type === 'ParenthesizedExpression' ||
94 + current.type === 'TSAsExpression' ||
95 + current.type === 'TSSatisfiesExpression' ||
96 + current.type === 'TSTypeAssertion' ||
97 + current.type === 'TSNonNullExpression' ||
98 + current.type === 'TSInstantiationExpression'
99 + ) {
100 + current = current.expression;
101 + }
102 + return current;
103 +}
104 +
105 +/** The member name when `node` is `<module>.<member>` for one of the module's local names, else null. */
106 +export function moduleMemberName(
107 + node: ESTree.Node | null | undefined,
108 + names: EffectModuleNames,
109 + module: EffectModule
110 +): string | null {
111 + if (node === null || node === undefined) return null;
112 + const expression = node.type === 'TSInstantiationExpression' ? node.expression : node;
113 + if (
114 + expression.type !== 'MemberExpression' ||
115 + expression.computed ||
116 + expression.object.type !== 'Identifier' ||
117 + !(names.modules.get(module)?.has(expression.object.name) ?? false) ||
118 + expression.property.type !== 'Identifier'
119 + ) {
120 + return null;
121 + }
122 + const binding = resolveIdentifier(names.sourceCode, expression.object);
123 + if (!binding?.defs.some(definition => definition.type === 'ImportBinding')) return null;
124 + return expression.property.name;
125 +}
126 +
127 +/** The member name when `node` is a call of `<module>.<member>(...)`, else null. */
128 +export function moduleCallName(
129 + node: ESTree.Node | null | undefined,
130 + names: EffectModuleNames,
131 + module: EffectModule
132 +): string | null {
133 + return node?.type === 'CallExpression'
134 + ? moduleMemberName(unwrapExpression(node.callee), names, module)
135 + : null;
136 +}
137 +
138 +/** The parts of `class X extends Context.Service<...>()("key", options) {}`. */
139 +export interface ServiceClass {
140 + readonly node: ESTree.Class;
141 + readonly name: string | null;
142 + readonly options: ESTree.ObjectExpression | null;
143 +}
144 +
145 +/** Read a Context.Service class declaration, or null when the class is not one. */
146 +export function serviceClass(node: ESTree.Class, names: EffectModuleNames): ServiceClass | null {
147 + if (node.superClass === null) return null;
148 + const superClass = unwrapExpression(node.superClass);
149 + if (superClass.type !== 'CallExpression') return null;
150 + const factory = unwrapExpression(superClass.callee);
151 + if (
152 + factory.type !== 'CallExpression' ||
153 + moduleMemberName(unwrapExpression(factory.callee), names, 'Context') !== 'Service'
154 + ) {
155 + return null;
156 + }
157 + const optionsArgument = superClass.arguments[1];
158 + const options =
159 + optionsArgument !== undefined && optionsArgument.type !== 'SpreadElement'
160 + ? unwrapExpression(optionsArgument)
161 + : null;
162 + return {
163 + node,
164 + name: node.id?.name ?? null,
165 + options: options?.type === 'ObjectExpression' ? options : null,
166 + };
167 +}
168 +
169 +/** The name of a non-computed property key, or null. */
170 +export function keyName(key: ESTree.Node): string | null {
171 + if (key.type === 'Identifier' || key.type === 'PrivateIdentifier') return key.name;
172 + if (key.type === 'Literal' && typeof key.value === 'string') return key.value;
173 + return null;
174 +}
175 +
176 +const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/u;
177 +
178 +/** Whether the file is a `*.test.*` or `*.spec.*` file. */
179 +export const isTestFile = (filename: string): boolean =>
180 + TEST_FILE.test(filename.replaceAll('\\', '/'));
181 +
182 +const skippedKeys: ReadonlySet<string> = new Set(['parent', 'loc', 'range', 'start', 'end']);
183 +
184 +const isNode = (value: unknown): value is ESTree.Node =>
185 + typeof value === 'object' && value !== null && 'type' in value && typeof value.type === 'string';
186 +
187 +/** Visit every descendant of `node`. Return false from `visit` to skip a node's children. */
188 +export function walk(node: ESTree.Node, visit: (node: ESTree.Node) => boolean): void {
189 + if (!visit(node)) return;
190 + for (const [key, value] of Object.entries(node)) {
191 + if (skippedKeys.has(key)) continue;
192 + if (Array.isArray(value)) {
193 + for (const item of value) {
194 + if (isNode(item)) walk(item, visit);
195 + }
196 + } else if (isNode(value)) {
197 + walk(value, visit);
198 + }
199 + }
200 +}
201 +
202 +/** A function expression, arrow, or declaration. */
203 +export type FunctionNode = ESTree.ArrowFunctionExpression | ESTree.Function;
204 +
205 +/** Whether `node` is a function expression, arrow, or declaration. */
206 +export const isFunction = (node: ESTree.Node | null | undefined): node is FunctionNode =>
207 + node?.type === 'ArrowFunctionExpression' ||
208 + node?.type === 'FunctionExpression' ||
209 + node?.type === 'FunctionDeclaration';
210 +
211 +/** The return statements of a function body, without descending into nested functions. */
212 +export function ownReturns(body: ESTree.Node): readonly ESTree.ReturnStatement[] {
213 + const returns: ESTree.ReturnStatement[] = [];
214 + walk(body, node => {
215 + if (node !== body && isFunction(node)) return false;
216 + if (node.type === 'ReturnStatement') returns.push(node);
217 + return true;
218 + });
219 + return returns;
220 +}
221 +
222 +/** The expressions a function produces: its expression body or the arguments of its own returns. */
223 +export function returnedExpressions(fn: FunctionNode): readonly ESTree.Expression[] {
224 + if (fn.body === null) return [];
225 + if (fn.body.type !== 'BlockStatement') return [fn.body];
226 + return ownReturns(fn.body).flatMap(statement =>
227 + statement.argument === null ? [] : [statement.argument]
228 + );
229 +}
230 +
231 +const isPipeMember = (node: ESTree.Node): node is ESTree.MemberExpression =>
232 + node.type === 'MemberExpression' &&
233 + !node.computed &&
234 + node.property.type === 'Identifier' &&
235 + node.property.name === 'pipe';
236 +
237 +/** For `x.pipe(...)`, the receiver `x`; otherwise null. */
238 +export function pipeReceiver(node: ESTree.Node): ESTree.Expression | null {
239 + if (node.type !== 'CallExpression') return null;
240 + const callee = unwrapExpression(node.callee);
241 + return isPipeMember(callee) ? unwrapExpression(callee.object) : null;
242 +}
243 +
244 +/**
245 + * The steps that run before `call` when it is an argument of a pipeline-like call such as `x.pipe(a, call)`,
246 + * `pipe(x, a, call)`, or `Effect.fn("name")(body, a, call)`, including earlier `.pipe(...)` receivers.
247 + */
248 +export function precedingSteps(call: ESTree.Node): readonly ESTree.Node[] {
249 + const parent = call.parent;
250 + if (parent?.type !== 'CallExpression') return [];
251 + const index = parent.arguments.findIndex(argument => argument === call);
252 + if (index < 0) return [];
253 + const steps: ESTree.Node[] = [];
254 + let receiver = pipeReceiver(parent);
255 + while (receiver !== null) {
256 + steps.push(receiver);
257 + if (receiver.type === 'CallExpression') steps.push(...receiver.arguments);
258 + receiver = pipeReceiver(receiver);
259 + }
260 + steps.push(...parent.arguments.slice(0, index));
261 + return steps;
262 +}
263 +
264 +/** The generator passed to `Effect.gen(...)`, or null when `node` is not such a call. */
265 +export function genFunction(node: ESTree.Node, names: EffectModuleNames): ESTree.Function | null {
266 + if (moduleCallName(node, names, 'Effect') !== 'gen' || node.type !== 'CallExpression')
267 + return null;
268 + const body = node.arguments.at(-1);
269 + return body?.type === 'FunctionExpression' ? body : null;
270 +}
tsconfig.effect-rules.json new
+13
@@ -0,0 +1,13 @@
1 +{
2 + "compilerOptions": {
3 + "target": "ESNext",
4 + "module": "NodeNext",
5 + "moduleResolution": "NodeNext",
6 + "strict": true,
7 + "skipLibCheck": true,
8 + "noEmit": true,
9 + "allowImportingTsExtensions": true,
10 + "types": ["bun"]
11 + },
12 + "include": ["tools/oxlint/**/*.ts", "test/effect-lint.test.ts"]
13 +}