@milkenjoyer/toolchain 0.0.0-stage → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3493 @@
1
+ import * as Arr from "effect/Array";
2
+ import { pipe } from "effect/Function";
3
+ import * as HashSet from "effect/HashSet";
4
+ import * as Option from "effect/Option";
5
+ import * as Schema from "effect/Schema";
6
+ import * as Str from "effect/String";
7
+ import { AST, Diagnostic, Plugin, Rule, RuleContext, Scope, SourceCode, Visitor } from "effect-oxlint";
8
+ import * as Effect from "effect/Effect";
9
+ import * as Ref from "effect/Ref";
10
+ import { pipe as pipe$1 } from "effect";
11
+ import * as Result from "effect/Result";
12
+ import * as Bool from "effect/Boolean";
13
+ import * as P from "effect/Predicate";
14
+ // ../../node_modules/.bun/@mpsuesser+oxlint-plugin-effect@0.6.0/node_modules/@mpsuesser/oxlint-plugin-effect/dist/index.js
15
+ const rule$56 = Rule.define({
16
+ name: "avoid-any",
17
+ meta: Rule.meta({
18
+ type: "suggestion",
19
+ description: "Disallow `as any` and `as unknown as T` type assertions"
20
+ }),
21
+ create: function* () {
22
+ const ctx = yield* RuleContext;
23
+ return { TSAsExpression: (node) => {
24
+ const tsAs = node;
25
+ if (tsAs.typeAnnotation.type === "TSAnyKeyword") return ctx.report(Diagnostic.make({
26
+ node,
27
+ message: "Avoid `as any` — it erases type safety. Use `Schema.decodeUnknown*` to validate unknown data, generics to preserve types, or fix the upstream type. (EF-3)"
28
+ }));
29
+ if (tsAs.typeAnnotation.type === "TSUnknownKeyword" && tsAs.parent.type === "TSAsExpression") return ctx.report(Diagnostic.make({
30
+ node,
31
+ message: "Avoid `as unknown as T` — casting through unknown erases type information. Use `Schema.decodeUnknown*` to validate data, or fix the upstream type."
32
+ }));
33
+ return Effect.void;
34
+ } };
35
+ }
36
+ });
37
+ const rule$55 = Rule.banMember("Data", "TaggedError", { message: "Use `Schema.TaggedError` instead of `Data.TaggedError` for public failures. Schema-based errors integrate with decode/encode and carry structured metadata. (EF-1)" });
38
+ const rule$54 = Rule.banMember("JSON", ["parse", "stringify"], { message: "Avoid `JSON.parse`/`JSON.stringify` in Effect code. Use `Schema.fromJsonString(MySchema)` for typed boundaries or `Schema.fromJsonString(Schema.Unknown)` for unknown payloads, with `Schema.decodeUnknownEffect` / `Schema.encodeEffect`. (EF-19)" });
39
+ const TagEqualityOperator = Schema.Literals(["===", "!=="]).annotate({
40
+ title: "TagEqualityOperator",
41
+ description: "Strict-equality operators that participate in `._tag` discrimination checks."
42
+ });
43
+ const isTagEqualityOperator = Schema.is(TagEqualityOperator);
44
+ const TagLiteralNodeType = Schema.Literals(["Literal", "TemplateLiteral"]).annotate({
45
+ title: "TagLiteralNodeType",
46
+ description: "AST node types that count as a \"literal\" tag value when comparing against `._tag`."
47
+ });
48
+ const isTagLiteralNodeType = Schema.is(TagLiteralNodeType);
49
+ /** A `MemberExpression` whose property is the identifier `_tag`. */
50
+ const isTagAccess = (node) => pipe(AST.narrow(node, "MemberExpression"), Option.flatMap(AST.memberNames), Option.exists(([, prop]) => prop === "_tag"));
51
+ /** Plain or template literal — a constant tag value at the call site. */
52
+ const isLiteralLikeNode = (node) => isTagLiteralNodeType(node.type);
53
+ /**
54
+ * One side of `===`/`!==` is `._tag` and the other side is a literal.
55
+ * Order doesn't matter — `x._tag === "Foo"` and `"Foo" === x._tag` both
56
+ * count.
57
+ */
58
+ const isTagComparisonPair = (left, right) => isTagAccess(left) && isLiteralLikeNode(right) || isTagAccess(right) && isLiteralLikeNode(left);
59
+ const MESSAGE$9 = "Avoid direct `._tag === \"...\"` checks. Use `$is(\"Tag\")` for type guards, `$match` for exhaustive pattern matching, or `Match.value(...).pipe(Match.when(...))` for composable branching. (EF-7)";
60
+ const rule$53 = Rule.define({
61
+ name: "avoid-direct-tag-checks",
62
+ meta: Rule.meta({
63
+ type: "suggestion",
64
+ description: "Disallow direct `._tag === '...'` / `!== '...'` checks and `switch(_._tag)` discrimination — use `$is`, `$match`, or `Match` instead."
65
+ }),
66
+ create: function* () {
67
+ const ctx = yield* RuleContext;
68
+ return Visitor.merge(Visitor.on("BinaryExpression", (node) => {
69
+ if (!isTagEqualityOperator(node.operator)) return Effect.void;
70
+ if (!isTagComparisonPair(node.left, node.right)) return Effect.void;
71
+ return ctx.report(Diagnostic.make({
72
+ node,
73
+ message: MESSAGE$9
74
+ }));
75
+ }), Visitor.on("SwitchStatement", (node) => isTagAccess(node.discriminant) ? ctx.report(Diagnostic.make({
76
+ node,
77
+ message: MESSAGE$9
78
+ })) : Effect.void));
79
+ }
80
+ });
81
+ const rule$52 = Rule.define({
82
+ name: "avoid-expect-in-if",
83
+ meta: Rule.meta({
84
+ type: "problem",
85
+ description: "Disallow expect() inside if blocks in tests — use assert to narrow types and fail fast"
86
+ }),
87
+ create: function* () {
88
+ const ctx = yield* RuleContext;
89
+ const ifBlockDepth = yield* Ref.make(0);
90
+ return Visitor.merge(Visitor.tracked("IfStatement", () => true, ifBlockDepth), Visitor.on("CallExpression", (node) => Effect.gen(function* () {
91
+ if ((yield* Ref.get(ifBlockDepth)) <= 0) return;
92
+ const call = node;
93
+ if (call.callee.type === "Identifier" && call.callee.name === "expect") yield* ctx.report(Diagnostic.make({
94
+ node,
95
+ message: "Avoid `expect()` inside `if` blocks — the test silently passes when the condition is false. Use `assert` or `expect(...).toBeDefined()` to narrow types and fail fast."
96
+ }));
97
+ })));
98
+ }
99
+ });
100
+ const LayerFactoryName$2 = Schema.Literals([
101
+ "effect",
102
+ "scoped",
103
+ "succeed"
104
+ ]).annotate({
105
+ title: "LayerFactoryName",
106
+ description: "Service-owning `Layer.effect` / `Layer.succeed` factories, including legacy `Layer.scoped` input."
107
+ });
108
+ const isLayerFactoryName$2 = Schema.is(LayerFactoryName$2);
109
+ const MutableVariableKind = Schema.Literal("let").annotate({
110
+ title: "MutableVariableKind",
111
+ description: "Variable declaration kinds flagged inside service-owning factories."
112
+ });
113
+ const isMutableVariableKind = Schema.is(MutableVariableKind);
114
+ /** `Layer.effect(...)`, `Layer.scoped(...)`, or `Layer.succeed(...)`. */
115
+ const isLayerFactoryCall$1 = (node) => pipe(AST.narrow(node.callee, "MemberExpression"), Option.flatMap(AST.memberNames), Option.exists(([obj, prop]) => obj === "Layer" && isLayerFactoryName$2(prop)));
116
+ /**
117
+ * `Context.Service<...>()(<key>, { make: ... })` — the canonical site of
118
+ * in-service mutable state. We only flag the call when the second argument
119
+ * carries a `make` property, so plain accessor-only services don't
120
+ * unnecessarily trip the rule.
121
+ */
122
+ const isContextServiceMakeCall = (node) => {
123
+ if (!pipe(AST.narrow(node.callee, "CallExpression"), Option.flatMap((inner) => AST.narrow(inner.callee, "MemberExpression")), Option.exists(AST.isMember("Context", "Service")))) return false;
124
+ return pipe(Option.fromNullishOr(node.arguments[1]), Option.flatMap(AST.narrow("ObjectExpression")), Option.exists(AST.objectHasKey("make")));
125
+ };
126
+ const MESSAGE$8 = "Consider `Ref`, `SynchronizedRef`, or `Effect.cached` instead of `let` inside service-owning factories. Shared mutable bindings hide fiber-visible state and lifecycle behavior. `let` is fine in pure helpers and narrow scopes.";
127
+ const rule$51 = Rule.define({
128
+ name: "avoid-mutable-state",
129
+ meta: Rule.meta({
130
+ type: "suggestion",
131
+ description: "Flag `let` inside `Layer.effect` / `Layer.scoped` / `Layer.succeed` and `Context.Service` make blocks — service bodies where mutable state hides fiber-visible behavior."
132
+ }),
133
+ create: function* () {
134
+ const ctx = yield* RuleContext;
135
+ const layerFactoryDepth = yield* Ref.make(0);
136
+ const serviceMakeDepth = yield* Ref.make(0);
137
+ const insideFactoryBody = Effect.gen(function* () {
138
+ const layer = yield* Ref.get(layerFactoryDepth);
139
+ const service = yield* Ref.get(serviceMakeDepth);
140
+ return layer > 0 || service > 0;
141
+ });
142
+ return Visitor.merge(Visitor.tracked("CallExpression", isLayerFactoryCall$1, layerFactoryDepth), Visitor.tracked("CallExpression", isContextServiceMakeCall, serviceMakeDepth), Visitor.on("VariableDeclaration", (node) => Effect.gen(function* () {
143
+ if (!isMutableVariableKind(node.kind)) return;
144
+ if (!(yield* insideFactoryBody)) return;
145
+ yield* ctx.report(Diagnostic.make({
146
+ node,
147
+ message: MESSAGE$8
148
+ }));
149
+ })));
150
+ }
151
+ });
152
+ const MESSAGE$7 = "Avoid native `fetch()` in Effect code. Use `HttpClientRequest`, `HttpClientResponse`, and `HttpClient` from Effect for typed errors, composable request building, and testability via layer substitution. (EF-9b)";
153
+ const rule$50 = Rule.define({
154
+ name: "avoid-native-fetch",
155
+ meta: Rule.meta({
156
+ type: "suggestion",
157
+ description: "Disallow native fetch() — use Effect HttpClient modules instead"
158
+ }),
159
+ create: function* () {
160
+ const ctx = yield* RuleContext;
161
+ return { CallExpression: (node) => {
162
+ const call = node;
163
+ return Option.match(AST.calleeName(call), {
164
+ onNone: () => {
165
+ if (call.callee.type !== "MemberExpression") return Effect.void;
166
+ if (AST.isMember(call.callee, "window", "fetch") || AST.isMember(call.callee, "globalThis", "fetch")) return ctx.report(Diagnostic.make({
167
+ node,
168
+ message: MESSAGE$7
169
+ }));
170
+ return Effect.void;
171
+ },
172
+ onSome: (name) => name === "fetch" ? ctx.report(Diagnostic.make({
173
+ node,
174
+ message: MESSAGE$7
175
+ })) : Effect.void
176
+ });
177
+ } };
178
+ }
179
+ });
180
+ const rule$49 = Rule.define({
181
+ name: "avoid-native-object-helpers",
182
+ meta: Rule.meta({
183
+ type: "suggestion",
184
+ description: "Disallow native Object.keys/values/entries and new Map/Set — use Effect modules (EF-5)"
185
+ }),
186
+ create: function* () {
187
+ const ctx = yield* RuleContext;
188
+ return Visitor.merge(Visitor.on("MemberExpression", (node) => {
189
+ const member = node;
190
+ if (AST.isMember(member, "Object", "keys")) return ctx.report(Diagnostic.make({
191
+ node,
192
+ message: "Use `R.keys(obj)` from `effect/Record` instead of `Object.keys(...)`. Effect Record helpers are type-safe and composable. (EF-5)"
193
+ }));
194
+ if (AST.isMember(member, "Object", "values")) return ctx.report(Diagnostic.make({
195
+ node,
196
+ message: "Use `R.values(obj)` from `effect/Record` instead of `Object.values(...)`. Effect Record helpers are type-safe and composable. (EF-5)"
197
+ }));
198
+ if (AST.isMember(member, "Object", "entries")) return ctx.report(Diagnostic.make({
199
+ node,
200
+ message: "Use `R.toEntries(obj)` from `effect/Record` instead of `Object.entries(...)`. Effect Record helpers are type-safe and composable. (EF-5)"
201
+ }));
202
+ if (AST.isMember(member, "Object", "fromEntries")) return ctx.report(Diagnostic.make({
203
+ node,
204
+ message: "Use `R.fromEntries(entries)` from `effect/Record` instead of `Object.fromEntries(...)`. Effect Record helpers are type-safe and composable. (EF-5)"
205
+ }));
206
+ return Effect.void;
207
+ }), Visitor.on("NewExpression", (node) => {
208
+ const newExpr = node;
209
+ if (newExpr.callee.type !== "Identifier") return Effect.void;
210
+ const name = newExpr.callee.name;
211
+ if (name === "Map") return ctx.report(Diagnostic.make({
212
+ node,
213
+ message: "Use `HashMap` from `effect/HashMap` instead of native `Map`. HashMap provides structural equality and immutability. (EF-5)"
214
+ }));
215
+ if (name === "Set") return ctx.report(Diagnostic.make({
216
+ node,
217
+ message: "Use `HashSet` from `effect/HashSet` instead of native `Set`. HashSet provides structural equality and immutability. (EF-5)"
218
+ }));
219
+ return Effect.void;
220
+ }));
221
+ }
222
+ });
223
+ const SPECIFIC_SOURCES = /* @__PURE__ */ new Set([
224
+ "node:fs",
225
+ "node:fs/promises",
226
+ "node:path",
227
+ "node:os",
228
+ "node:child_process",
229
+ "node:http",
230
+ "node:https"
231
+ ]);
232
+ const rule$48 = Rule.banImport((src) => src.startsWith("node:") && !SPECIFIC_SOURCES.has(src), { message: "Avoid `node:*` imports in domain code. Use `FileSystem`, `Path`, and `Crypto` from `effect`, `ChildProcessSpawner` from `effect/process`, and `HttpClient` from `effect/http` for portable, testable code. (EF-21)" });
233
+ const MESSAGE$6 = "Avoid the `!` non-null assertion — it tells the compiler \"trust me\" and crashes at runtime if wrong. Model absence with `Option`, decode unknown shapes via `Schema.decodeUnknown*`, or guard at the boundary with `Option.fromNullishOr` / `?.` / `??`. (EF-2)";
234
+ const rule$47 = Rule.define({
235
+ name: "avoid-non-null-assertion",
236
+ meta: Rule.meta({
237
+ type: "suggestion",
238
+ description: "Disallow the `!` non-null assertion operator — model absence with `Option`, decode unknowns with `Schema`, and handle nullish at boundaries."
239
+ }),
240
+ create: function* () {
241
+ const ctx = yield* RuleContext;
242
+ return Visitor.on("TSNonNullExpression", (node) => ctx.report(Diagnostic.make({
243
+ node,
244
+ message: MESSAGE$6
245
+ })));
246
+ }
247
+ });
248
+ const rule$46 = Rule.define({
249
+ name: "avoid-object-type",
250
+ meta: Rule.meta({
251
+ type: "suggestion",
252
+ description: "Disallow Object and {} as types — use Record, Schema, or specific interfaces"
253
+ }),
254
+ create: function* () {
255
+ const ctx = yield* RuleContext;
256
+ return Visitor.merge(Visitor.on("TSTypeReference", (node) => {
257
+ const ref = node;
258
+ if (ref.typeName.type === "Identifier" && ref.typeName.name === "Object") return ctx.report(Diagnostic.make({
259
+ node,
260
+ message: "Avoid using `Object` as a type — it provides no type safety. Use a specific interface, `Record<string, unknown>`, or a `Schema.Class`."
261
+ }));
262
+ return Effect.void;
263
+ }), Visitor.on("TSTypeLiteral", (node) => {
264
+ if (node.members.length === 0) return ctx.report(Diagnostic.make({
265
+ node,
266
+ message: "Avoid using `{}` as a type — it matches any non-nullish value. Use `Record<string, never>` for an empty object, or a specific interface."
267
+ }));
268
+ return Effect.void;
269
+ }));
270
+ }
271
+ });
272
+ const MESSAGE$5 = "Do not use `.getOrThrow` — it defeats the purpose of `Option` / `Result` / `Either`. Use `match`, `getOrElse`, or `map` to handle both cases explicitly. (EF-2)";
273
+ /**
274
+ * The property of a static `MemberExpression` is `getOrThrow`, regardless
275
+ * of receiver. Computed accesses (`opt['getOrThrow']`) and private
276
+ * identifiers (`#getOrThrow`) are excluded — `AST.memberNames` already
277
+ * filters those out.
278
+ */
279
+ const isGetOrThrowAccess = (node) => pipe(AST.memberNames(node), Option.exists(([, prop]) => prop === "getOrThrow"));
280
+ const rule$45 = Rule.define({
281
+ name: "avoid-option-getorthrow",
282
+ meta: Rule.meta({
283
+ type: "suggestion",
284
+ description: "Disallow any `<receiver>.getOrThrow` member access — `Option.getOrThrow`, namespace aliases, `Either.getOrThrow`, `Result.getOrThrow` are all flagged. (EF-2)"
285
+ }),
286
+ create: function* () {
287
+ const ctx = yield* RuleContext;
288
+ return Visitor.on("MemberExpression", (node) => isGetOrThrowAccess(node) ? ctx.report(Diagnostic.make({
289
+ node,
290
+ message: MESSAGE$5
291
+ })) : Effect.void);
292
+ }
293
+ });
294
+ /**
295
+ * A file path inside a binding package: matches `packages/<name>/binding/...`
296
+ * anywhere in the path.
297
+ */
298
+ const BindingPackagePath = Schema.String.check(Schema.isPattern(/(?:^|\/)packages\/[^/]+\/binding\//, {
299
+ identifier: "BindingPackagePathCheck",
300
+ title: "Binding Package Path",
301
+ description: "A file path that resolves under `packages/<name>/binding/`.",
302
+ message: "Path must be inside a binding package"
303
+ })).pipe(Schema.brand("BindingPackagePath"), Schema.annotate({
304
+ title: "BindingPackagePath",
305
+ description: "Absolute file path inside `packages/<name>/binding/` — the only files where platform-bun imports are forbidden."
306
+ }));
307
+ const isBindingPackagePath = Schema.is(BindingPackagePath);
308
+ /**
309
+ * An import source that points at the concrete Bun platform package —
310
+ * either the root or any submodule.
311
+ */
312
+ const PlatformBunImportSource = Schema.String.check(Schema.makeFilter((src) => src === "@effect/platform-bun" || src.startsWith("@effect/platform-bun/"), {
313
+ identifier: "PlatformBunImportSourceCheck",
314
+ title: "Platform-Bun Import Source",
315
+ description: "An import source naming `@effect/platform-bun` or any of its submodules.",
316
+ message: "Import source must name @effect/platform-bun or a submodule"
317
+ })).pipe(Schema.brand("PlatformBunImportSource"), Schema.annotate({
318
+ title: "PlatformBunImportSource",
319
+ description: "Concrete Bun platform-binding import source. Forbidden inside binding packages; allowed elsewhere."
320
+ }));
321
+ const isPlatformBunImportSource = Schema.is(PlatformBunImportSource);
322
+ const MESSAGE$4 = "Binding packages must be platform-agnostic. Import abstract services from `effect`, `effect/http`, or `effect/process` instead of concrete `@effect/platform-bun` implementations. Platform layers belong in the runtime entry point.";
323
+ const rule$44 = Rule.define({
324
+ name: "avoid-platform-coupling",
325
+ meta: Rule.meta({
326
+ type: "suggestion",
327
+ description: "Forbid `@effect/platform-bun` imports inside `packages/<name>/binding/` — bindings stay platform-agnostic; concrete platforms wire up at the runtime entry point."
328
+ }),
329
+ create: function* () {
330
+ const ctx = yield* RuleContext;
331
+ return yield* Visitor.filter(isBindingPackagePath, Visitor.on("ImportDeclaration", (node) => pipe(AST.matchImport(node, isPlatformBunImportSource), Option.match({
332
+ onNone: () => Effect.void,
333
+ onSome: (matched) => ctx.report(Diagnostic.make({
334
+ node: matched,
335
+ message: MESSAGE$4
336
+ }))
337
+ }))));
338
+ }
339
+ });
340
+ const rule$43 = Rule.banMember("process", "env", { message: "Avoid direct `process.env` access in domain code. Use `Config.String`, `Config.Int`, `Config.Redacted`, etc. for typed, testable configuration loading. (EF-28)" });
341
+ const REACT_HOOKS = /* @__PURE__ */ new Set([
342
+ "useState",
343
+ "useEffect",
344
+ "useReducer",
345
+ "useCallback",
346
+ "useMemo",
347
+ "useRef",
348
+ "useLayoutEffect",
349
+ "useImperativeHandle",
350
+ "useDebugValue",
351
+ "useDeferredValue",
352
+ "useTransition",
353
+ "useId",
354
+ "useSyncExternalStore",
355
+ "useInsertionEffect"
356
+ ]);
357
+ const rule$42 = Rule.define({
358
+ name: "avoid-react-hooks",
359
+ meta: Rule.meta({
360
+ type: "suggestion",
361
+ description: "Disallow React hooks — use View Models with Effect Atom instead"
362
+ }),
363
+ create: function* () {
364
+ const ctx = yield* RuleContext;
365
+ return { CallExpression: (node) => {
366
+ const call = node;
367
+ return Option.match(AST.calleeName(call), {
368
+ onNone: () => Effect.void,
369
+ onSome: (name) => REACT_HOOKS.has(name) ? ctx.report(Diagnostic.make({
370
+ node,
371
+ message: `Avoid \`${name}\` — use View Models with Effect Atom instead. State belongs in atoms, effects in actions, components as pure renderers.`
372
+ })) : Effect.void
373
+ });
374
+ } };
375
+ }
376
+ });
377
+ const rule$41 = Rule.define({
378
+ name: "avoid-schema-suffix",
379
+ meta: Rule.meta({
380
+ type: "suggestion",
381
+ description: "Disallow Schema suffix on schema constant names — name after the domain type instead"
382
+ }),
383
+ create: function* () {
384
+ const ctx = yield* RuleContext;
385
+ return { VariableDeclarator: (node) => {
386
+ const decl = node;
387
+ if (decl.id.type !== "Identifier" || !decl.id.name.endsWith("Schema") || decl.id.name === "Schema") return Effect.void;
388
+ if (!decl.init) return Effect.void;
389
+ if (decl.init.type === "CallExpression" && decl.init.callee.type === "MemberExpression" && AST.isMember(decl.init.callee, "Schema", decl.init.callee.property.type === "Identifier" ? decl.init.callee.property.name : "") || decl.init.type === "MemberExpression" && decl.init.object.type === "Identifier" && decl.init.object.name === "Schema" || decl.init.type === "CallExpression" && decl.init.callee.type === "MemberExpression" && decl.init.callee.object.type === "MemberExpression" && decl.init.callee.object.object.type === "Identifier" && decl.init.callee.object.object.name === "Schema") return ctx.report(Diagnostic.make({
390
+ node,
391
+ message: `Avoid naming schema constants with a "Schema" suffix. Name \`${decl.id.name}\` after the domain type it represents (e.g., \`${decl.id.name.replace(/Schema$/, "")}\`). (EF-3, EF-8)`
392
+ }));
393
+ return Effect.void;
394
+ } };
395
+ }
396
+ });
397
+ const SYNC_FS_METHODS = /* @__PURE__ */ new Set([
398
+ "readFileSync",
399
+ "writeFileSync",
400
+ "mkdirSync",
401
+ "readdirSync",
402
+ "statSync",
403
+ "existsSync",
404
+ "copyFileSync",
405
+ "unlinkSync",
406
+ "rmdirSync",
407
+ "renameSync",
408
+ "appendFileSync"
409
+ ]);
410
+ const rule$40 = Rule.define({
411
+ name: "avoid-sync-fs",
412
+ meta: Rule.meta({
413
+ type: "suggestion",
414
+ description: "Disallow synchronous fs operations — use Effect FileSystem service for async I/O"
415
+ }),
416
+ create: function* () {
417
+ const ctx = yield* RuleContext;
418
+ return { CallExpression: (node) => {
419
+ const call = node;
420
+ return Option.match(AST.calleeName(call), {
421
+ onNone: () => {
422
+ if (call.callee.type === "MemberExpression" && call.callee.property.type === "Identifier" && SYNC_FS_METHODS.has(call.callee.property.name)) return ctx.report(Diagnostic.make({
423
+ node,
424
+ message: `Avoid synchronous \`${call.callee.property.name}\` — it blocks the event loop. Use Effect's \`FileSystem\` service for async, composable file operations.`
425
+ }));
426
+ return Effect.void;
427
+ },
428
+ onSome: (name) => SYNC_FS_METHODS.has(name) ? ctx.report(Diagnostic.make({
429
+ node,
430
+ message: `Avoid synchronous \`${name}\` — it blocks the event loop. Use Effect's \`FileSystem\` service for async, composable file operations.`
431
+ })) : Effect.void
432
+ });
433
+ } };
434
+ }
435
+ });
436
+ const rule$39 = Rule.banStatement("TryStatement", { message: "Avoid try-catch in Effect code. Use `Effect.try` or `Effect.tryPromise` with `Schema.TaggedError` for typed, composable error handling. (EF-1)" });
437
+ const rule$38 = Rule.define({
438
+ name: "avoid-ts-ignore",
439
+ meta: Rule.meta({
440
+ type: "problem",
441
+ description: "Disallow @ts-ignore and @ts-expect-error comments — fix the underlying type issue"
442
+ }),
443
+ create: function* () {
444
+ const ctx = yield* RuleContext;
445
+ return { Program: (node) => Effect.gen(function* () {
446
+ const comments = yield* SourceCode.getAllComments();
447
+ for (const comment of comments) if (comment.value.includes("@ts-ignore") || comment.value.includes("@ts-expect-error")) yield* ctx.report(Diagnostic.make({
448
+ node,
449
+ message: "Avoid `@ts-ignore` and `@ts-expect-error` — they suppress type errors and hide bugs. Fix the underlying type issue instead."
450
+ }));
451
+ }) };
452
+ }
453
+ });
454
+ const ErrorConstructor = Schema.Literal("Error").annotate({
455
+ title: "ErrorConstructor",
456
+ description: "The bare global `Error` constructor — pattern EF-1 forbids using it for recoverable domain failures."
457
+ });
458
+ const isErrorConstructor = Schema.is(ErrorConstructor);
459
+ const NEW_MESSAGE = "Avoid `new Error(...)` in Effect code. Use `Schema.TaggedError` for typed, tagged errors that compose with `catchTag`/`catchTags`. (EF-1)";
460
+ const INSTANCEOF_MESSAGE = "Avoid `instanceof Error` in Effect code. Use `catchTag`/`catchTags` with `Schema.TaggedError` for domain failures, or `Schema.isSchemaError` for decoder failures. Schema constructors such as `makeEffect` fail directly with `SchemaIssue.Issue`. (EF-30)";
461
+ const rule$37 = Rule.define({
462
+ name: "avoid-untagged-errors",
463
+ meta: Rule.meta({
464
+ type: "suggestion",
465
+ description: "Disallow `new Error(...)` and `<expr> instanceof Error` — use `Schema.TaggedError` instead (EF-1)"
466
+ }),
467
+ create: function* () {
468
+ const ctx = yield* RuleContext;
469
+ return Visitor.merge(Visitor.on("NewExpression", (node) => pipe$1(AST.narrow(node.callee, "Identifier"), Option.map((id) => id.name), Option.filter(isErrorConstructor), Option.match({
470
+ onNone: () => Effect.void,
471
+ onSome: () => ctx.report(Diagnostic.make({
472
+ node,
473
+ message: NEW_MESSAGE
474
+ }))
475
+ }))), Visitor.on("BinaryExpression", (node) => {
476
+ if (node.operator !== "instanceof") return Effect.void;
477
+ return pipe$1(AST.narrow(node.right, "Identifier"), Option.map((id) => id.name), Option.filter(isErrorConstructor), Option.match({
478
+ onNone: () => Effect.void,
479
+ onSome: () => ctx.report(Diagnostic.make({
480
+ node,
481
+ message: INSTANCEOF_MESSAGE
482
+ }))
483
+ }));
484
+ }));
485
+ }
486
+ });
487
+ const DIRECT_YIELD_TARGETS = /* @__PURE__ */ new Set([
488
+ "ref",
489
+ "deferred",
490
+ "fiber",
491
+ "latch"
492
+ ]);
493
+ const rule$36 = Rule.define({
494
+ name: "avoid-yield-ref",
495
+ meta: Rule.meta({
496
+ type: "problem",
497
+ description: "Disallow yield* on Ref/Deferred/Fiber/Latch — use explicit method calls in Effect v4"
498
+ }),
499
+ create: function* () {
500
+ const ctx = yield* RuleContext;
501
+ return { YieldExpression: (node) => {
502
+ const expr = node;
503
+ if (!expr.delegate || !expr.argument) return Effect.void;
504
+ if (expr.argument.type === "Identifier" && DIRECT_YIELD_TARGETS.has(expr.argument.name.toLowerCase())) return ctx.report(Diagnostic.make({
505
+ node,
506
+ message: `Direct \`yield* ${expr.argument.name}\` was removed in Effect v4. Use explicit method calls instead: \`Ref.get(ref)\`, \`Deferred.await(deferred)\`, \`Fiber.join(fiber)\`, \`Latch.await(latch)\`. (EF-8)`
507
+ }));
508
+ return Effect.void;
509
+ } };
510
+ }
511
+ });
512
+ const rule$35 = Rule.define({
513
+ name: "casting-awareness",
514
+ meta: Rule.meta({
515
+ type: "suggestion",
516
+ description: "Flag type assertions (as T) — verify the cast is necessary or improve upstream types"
517
+ }),
518
+ create: function* () {
519
+ const ctx = yield* RuleContext;
520
+ return { TSAsExpression: (node) => {
521
+ const tsAs = node;
522
+ if (tsAs.typeAnnotation.type === "TSTypeReference") {
523
+ const name = tsAs.typeAnnotation.typeName;
524
+ if (name.type === "Identifier" && name.name === "const") return Effect.void;
525
+ }
526
+ if (tsAs.typeAnnotation.type === "TSLiteralType") return Effect.void;
527
+ if (tsAs.typeAnnotation.type === "TSAnyKeyword" || tsAs.typeAnnotation.type === "TSUnknownKeyword") return Effect.void;
528
+ if (tsAs.typeAnnotation.type === "TSNeverKeyword") return Effect.void;
529
+ return ctx.report(Diagnostic.make({
530
+ node,
531
+ message: "Type assertion `as T` tells the compiler \"trust me.\" Before casting, check: (1) is the cast redundant? (2) can generics or Schema.decodeUnknownEffect replace it? (3) does the upstream type need fixing? `as const` is always acceptable."
532
+ }));
533
+ } };
534
+ }
535
+ });
536
+ const rule$34 = Rule.define({
537
+ name: "context-tag-extends",
538
+ meta: Rule.meta({
539
+ type: "problem",
540
+ description: "Disallow removed Context/Effect service APIs and old ServiceMap aliases — use Context.Service and Context.* (Effect v4 beta.46)"
541
+ }),
542
+ create: function* () {
543
+ const ctx = yield* RuleContext;
544
+ return Visitor.merge({ ClassDeclaration: (node) => {
545
+ const decl = node;
546
+ if (decl.id && decl.id.name.endsWith("Tag") && decl.superClass && decl.superClass.type === "CallExpression" && decl.superClass.callee.type === "MemberExpression" && AST.isMember(decl.superClass.callee, "Context", "Tag")) return ctx.report(Diagnostic.make({
547
+ node,
548
+ message: "The `class *Tag extends Context.Tag` pattern was removed in Effect v4. Use `Context.Service` instead, and name the service directly (no *Tag suffix)."
549
+ }));
550
+ return Effect.void;
551
+ } }, { MemberExpression: (node) => {
552
+ const member = node;
553
+ if (AST.isMember(member, "Context", "GenericTag")) return ctx.report(Diagnostic.make({
554
+ node,
555
+ message: "`Context.GenericTag` was removed in Effect v4. Use `Context.Service` for service definitions instead."
556
+ }));
557
+ if (AST.isMember(member, "Context", "Tag")) return ctx.report(Diagnostic.make({
558
+ node,
559
+ message: "`Context.Tag` was removed in Effect v4. Use `Context.Service` for service definitions instead."
560
+ }));
561
+ if (AST.isMember(member, "Effect", "Service")) return ctx.report(Diagnostic.make({
562
+ node,
563
+ message: "`Effect.Service` was removed in Effect v4. Use `Context.Service` for service definitions instead."
564
+ }));
565
+ if (AST.isMember(member, "ServiceMap", "Service")) return ctx.report(Diagnostic.make({
566
+ node,
567
+ message: "`ServiceMap.Service` was removed before Effect v4 beta.46 stabilized. Use `Context.Service` for service definitions instead."
568
+ }));
569
+ if (AST.isMember(member, "ServiceMap", "Reference")) return ctx.report(Diagnostic.make({
570
+ node,
571
+ message: "`ServiceMap.Reference` was removed before Effect v4 beta.46 stabilized. Use `Context.Reference` instead."
572
+ }));
573
+ if (AST.isMember(member, "ServiceMap", "make")) return ctx.report(Diagnostic.make({
574
+ node,
575
+ message: "`ServiceMap.make` was removed before Effect v4 beta.46 stabilized. Use `Context.make` instead."
576
+ }));
577
+ if (AST.isMember(member, "ServiceMap", "get")) return ctx.report(Diagnostic.make({
578
+ node,
579
+ message: "`ServiceMap.get` was removed before Effect v4 beta.46 stabilized. Use `Context.get` instead."
580
+ }));
581
+ if (AST.isMember(member, "ServiceMap", "add")) return ctx.report(Diagnostic.make({
582
+ node,
583
+ message: "`ServiceMap.add` was removed before Effect v4 beta.46 stabilized. Use `Context.add` instead."
584
+ }));
585
+ if (AST.isMember(member, "ServiceMap", "mergeAll")) return ctx.report(Diagnostic.make({
586
+ node,
587
+ message: "`ServiceMap.mergeAll` was removed before Effect v4 beta.46 stabilized. Use `Context.mergeAll` instead."
588
+ }));
589
+ return Effect.void;
590
+ } }, { CallExpression: (node) => {
591
+ const call = node;
592
+ if (call.callee.type === "CallExpression" && call.callee.callee.type === "MemberExpression" && AST.isMember(call.callee.callee, "Effect", "Service")) {
593
+ const { parent } = call;
594
+ if (parent?.type === "ClassDeclaration" || parent?.type === "ClassExpression") return ctx.report(Diagnostic.make({
595
+ node,
596
+ message: "`Effect.Service` was removed in Effect v4. Use `Context.Service` for service definitions instead."
597
+ }));
598
+ }
599
+ return Effect.void;
600
+ } });
601
+ }
602
+ });
603
+ /**
604
+ * All v3 + v4 names for blanket catch APIs.
605
+ * v3: `catchAll`, `catchAllCause`
606
+ * v4: `catch`, `catchCause`
607
+ */
608
+ const CatchMethodName = Schema.Literals([
609
+ "catchAll",
610
+ "catch",
611
+ "catchAllCause",
612
+ "catchCause"
613
+ ]).annotate({
614
+ title: "CatchMethodName",
615
+ description: "Method names on `Effect` that perform blanket error recovery — covers both v3 (`catchAll(Cause)`) and v4 (`catch(Cause)`) spellings."
616
+ });
617
+ const isCatchMethodName = Schema.is(CatchMethodName);
618
+ /**
619
+ * Method names that produce a successful effect from a value — when one
620
+ * of these appears as the body of a blanket catch handler, the recovery
621
+ * is "return a default value" and the diagnostic applies.
622
+ */
623
+ const DefaultProducerName = Schema.Literals(["succeed", "sync"]).annotate({
624
+ title: "DefaultProducerName",
625
+ description: "`Effect.succeed` / `Effect.sync` (or their bare-callee forms) produce a constant default — using them inside a blanket catch silently swallows every error."
626
+ });
627
+ const isDefaultProducerName = Schema.is(DefaultProducerName);
628
+ /** A `CallExpression` whose callee is `Effect.<catch-method>(...)`. */
629
+ const isBlanketCatchCall = (node) => pipe$1(AST.narrow(node.callee, "MemberExpression"), Option.flatMap(AST.memberNames), Option.exists(([obj, prop]) => obj === "Effect" && isCatchMethodName(prop)));
630
+ /**
631
+ * A `CallExpression` that produces a default value — matches both the
632
+ * fully-qualified form `Effect.succeed(x)` / `Effect.sync(x)` and the
633
+ * bare-callee form `succeed(x)` / `sync(x)`.
634
+ */
635
+ const isDefaultProducerCall = (node) => {
636
+ const bareName = pipe$1(AST.calleeName(node), Option.filter(isDefaultProducerName));
637
+ if (Option.isSome(bareName)) return true;
638
+ return pipe$1(AST.narrow(node.callee, "MemberExpression"), Option.flatMap(AST.memberNames), Option.exists(([obj, prop]) => obj === "Effect" && isDefaultProducerName(prop)));
639
+ };
640
+ /**
641
+ * Extract the expression a function body evaluates to, when statically obvious.
642
+ *
643
+ * Handles:
644
+ * - Arrow concise body: `() => expr`
645
+ * - Arrow block body with single return: `() => { return expr }`
646
+ * - Function expression block body with single return: `function() { return expr }`
647
+ */
648
+ const handlerReturnExpression = (handler) => {
649
+ const fromArrow = pipe$1(AST.narrow(handler, "ArrowFunctionExpression"), Option.flatMap((node) => node.body.type === "BlockStatement" ? singleReturnExpression(node.body) : Option.some(node.body)));
650
+ const fromFunctionExpr = pipe$1(AST.narrow(handler, "FunctionExpression"), Option.flatMap((node) => Option.fromNullishOr(node.body)), Option.flatMap(singleReturnExpression));
651
+ return pipe$1(fromArrow, Option.orElse(() => fromFunctionExpr));
652
+ };
653
+ /** A block body containing exactly `return <expr>;` yields `Some(<expr>)`. */
654
+ const singleReturnExpression = (body) => {
655
+ if (body.body.length !== 1) return Option.none();
656
+ return pipe$1(Option.fromNullishOr(body.body[0]), Option.flatMap(AST.narrow("ReturnStatement")), Option.flatMap((ret) => Option.fromNullishOr(ret.argument)));
657
+ };
658
+ const MESSAGE$3 = "Avoid blanket `Effect.catch` / `Effect.catchCause` with default values — this silently swallows all errors. Use `Effect.catchTag` or `Effect.catchTags` for precise, targeted recovery. (EF-30)";
659
+ const rule$33 = Rule.define({
660
+ name: "effect-catchall-default",
661
+ meta: Rule.meta({
662
+ type: "suggestion",
663
+ description: "Disallow `Effect.catch`/`catchCause`/`catchAll`/`catchAllCause` whose handler returns a constant default — use `catchTag` for precise recovery (EF-30)"
664
+ }),
665
+ create: function* () {
666
+ const ctx = yield* RuleContext;
667
+ return { CallExpression: (node) => pipe$1(AST.narrow(node, "CallExpression"), Option.filter(isBlanketCatchCall), Option.flatMap((call) => Option.fromNullishOr(call.arguments[0])), Option.flatMap(handlerReturnExpression), Option.flatMap(AST.narrow("CallExpression")), Option.filter(isDefaultProducerCall), Option.match({
668
+ onNone: () => Effect.void,
669
+ onSome: () => ctx.report(Diagnostic.make({
670
+ node,
671
+ message: MESSAGE$3
672
+ }))
673
+ })) };
674
+ }
675
+ });
676
+ const rule$32 = Rule.banMember("Effect", "promise", { message: "Prefer `Effect.tryPromise` over `Effect.promise`. `tryPromise` captures rejections in the typed error channel via a `catch` handler, while `promise` treats rejections as defects. (EF-22)" });
677
+ const rule$31 = Rule.banMember("Effect", [
678
+ "runSync",
679
+ "runPromise",
680
+ "runFork"
681
+ ], { message: "Avoid `Effect.runSync`/`Effect.runPromise`/`Effect.runFork` in library or domain code. Keep runtime execution at the boundary (entrypoint/test harness). Return `Effect` values instead. (EF-21)" });
682
+ const rule$30 = Rule.banMultiple({ statements: [
683
+ "ForStatement",
684
+ "ForInStatement",
685
+ "ForOfStatement",
686
+ "WhileStatement",
687
+ "DoWhileStatement"
688
+ ] }, {
689
+ name: "imperative-loops",
690
+ message: "Avoid imperative loops in domain code. Use `Arr.map`, `Arr.filter`, `Arr.filterMap`, `Arr.reduce`, or `Effect.forEach` for functional, composable transformations. (EF-5)"
691
+ });
692
+ /**
693
+ * Effect conventions reserve the `maybe*` prefix exclusively for `Option<T>`. Two axes
694
+ * are enforced:
695
+ *
696
+ * 1. TS bindings / parameters / interface members named `maybe*` whose type
697
+ * annotation is `T | undefined` / `T | null` rather than `Option<T>`.
698
+ * 2. Schema struct fields named `maybe*` whose value is not a
699
+ * `Schema.Option(...)` / `S.Option(...)` (or `OptionFromNullOr`, etc.)
700
+ * constructor call.
701
+ *
702
+ * The fix is either to change the type/schema to use `Option`, or rename the
703
+ * binding to `nullable*` if `T | undefined` is the intended shape.
704
+ *
705
+ * @since 0.4.0
706
+ */
707
+ const SCHEMA_NAMESPACES$1 = ["Schema", "S"];
708
+ const MaybePrefixedName = Schema.String.check(Schema.isPattern(/^maybe[A-Z]/, {
709
+ identifier: "MaybePrefixedName",
710
+ title: "Maybe-Prefixed Identifier",
711
+ description: "An identifier beginning with `maybe` followed by an uppercase letter — Effect conventions reserve this prefix for `Option<T>`."
712
+ }));
713
+ const isMaybePrefixedName = Schema.is(MaybePrefixedName);
714
+ const NodeWithType = Schema.Struct({ type: Schema.String });
715
+ const isNodeWithType = Schema.is(NodeWithType);
716
+ const TypeAnnotationWrapper = Schema.Struct({
717
+ type: Schema.Literal("TSTypeAnnotation"),
718
+ typeAnnotation: NodeWithType
719
+ });
720
+ const TSUnionShape = Schema.Struct({
721
+ type: Schema.Literal("TSUnionType"),
722
+ types: Schema.Array(NodeWithType)
723
+ });
724
+ const isTSUnionShape = Schema.is(TSUnionShape);
725
+ const TSTypeReferenceIdent = Schema.Struct({
726
+ type: Schema.Literal("TSTypeReference"),
727
+ typeName: Schema.Struct({
728
+ type: Schema.Literal("Identifier"),
729
+ name: Schema.String
730
+ })
731
+ });
732
+ const TSTypeReferenceQualified = Schema.Struct({
733
+ type: Schema.Literal("TSTypeReference"),
734
+ typeName: Schema.Struct({
735
+ type: Schema.Literal("TSQualifiedName"),
736
+ right: Schema.Struct({
737
+ type: Schema.Literal("Identifier"),
738
+ name: Schema.String
739
+ })
740
+ })
741
+ });
742
+ const isTSTypeReferenceIdent = Schema.is(TSTypeReferenceIdent);
743
+ const isTSTypeReferenceQualified = Schema.is(TSTypeReferenceQualified);
744
+ const TSLiteralNull = Schema.Struct({
745
+ type: Schema.Literal("TSLiteralType"),
746
+ literal: Schema.Struct({ type: Schema.Literal("NullLiteral") })
747
+ });
748
+ const isTSLiteralNull = Schema.is(TSLiteralNull);
749
+ const TSUndefinedKeyword = Schema.Struct({ type: Schema.Literal("TSUndefinedKeyword") });
750
+ const TSNullKeyword = Schema.Struct({ type: Schema.Literal("TSNullKeyword") });
751
+ const isTSUndefinedKeyword = Schema.is(TSUndefinedKeyword);
752
+ const isTSNullKeyword = Schema.is(TSNullKeyword);
753
+ /** Read the inner TS annotation off any node, regardless of `.d.ts` narrowness. */
754
+ const readAnnotation = (node) => {
755
+ if (!Schema.is(Schema.Struct({ typeAnnotation: Schema.Unknown }))(node)) return Option.none();
756
+ const wrapper = node.typeAnnotation;
757
+ if (!Schema.is(TypeAnnotationWrapper)(wrapper)) return Option.none();
758
+ return Option.some(wrapper.typeAnnotation);
759
+ };
760
+ const isUndefinedOrNullKeyword = (n) => isTSUndefinedKeyword(n) || isTSNullKeyword(n) || isTSLiteralNull(n);
761
+ const isOptionTypeReference = (n) => {
762
+ if (isTSTypeReferenceIdent(n)) return n.typeName.name === "Option";
763
+ if (isTSTypeReferenceQualified(n)) return n.typeName.right.name === "Option";
764
+ return false;
765
+ };
766
+ const annotationIsBareNullish = (ann) => {
767
+ if (!isTSUnionShape(ann)) return false;
768
+ if (!pipe$1(ann.types, Arr.some(isUndefinedOrNullKeyword))) return false;
769
+ return pipe$1(ann.types, Arr.filter((t) => !isUndefinedOrNullKeyword(t)), Arr.match({
770
+ onEmpty: () => true,
771
+ onNonEmpty: (items) => !pipe$1(items, Arr.every(isOptionTypeReference))
772
+ }));
773
+ };
774
+ const isSchemaStructCall$1 = (call) => pipe$1(SCHEMA_NAMESPACES$1, Arr.some((ns) => AST.isCallOf(call, ns, "Struct")));
775
+ /**
776
+ * Accept any `Schema.Option*` / `S.Option*` constructor call —
777
+ * `Option`, `OptionFromNullOr`, `OptionFromNullishOr`, `OptionFromOptional`,
778
+ * `OptionFromOptionalKey`.
779
+ */
780
+ const isSchemaOptionLikeCall = (node) => {
781
+ if (node.type !== "CallExpression") return false;
782
+ const callee = node.callee;
783
+ if (callee.type !== "MemberExpression") return false;
784
+ const object = callee.object;
785
+ const property = callee.property;
786
+ if (object.type !== "Identifier") return false;
787
+ if (property.type !== "Identifier") return false;
788
+ const objectName = object.name;
789
+ const propertyName = property.name;
790
+ if (!pipe$1(SCHEMA_NAMESPACES$1, Arr.some((ns) => ns === objectName))) return false;
791
+ return propertyName.startsWith("Option");
792
+ };
793
+ const schemaFindings = (fields) => pipe$1(fields.properties, Arr.filterMap((prop) => {
794
+ if (prop.type !== "Property") return Result.failVoid;
795
+ if (prop.key.type !== "Identifier") return Result.failVoid;
796
+ if (!isMaybePrefixedName(prop.key.name)) return Result.failVoid;
797
+ if (isSchemaOptionLikeCall(prop.value)) return Result.failVoid;
798
+ return Result.succeed({
799
+ node: prop,
800
+ key: prop.key.name
801
+ });
802
+ }));
803
+ const fieldsArg$1 = (call) => {
804
+ const arg = call.arguments[0];
805
+ return arg !== void 0 && arg.type === "ObjectExpression" ? Option.some(arg) : Option.none();
806
+ };
807
+ const renameSuffix = (key) => key.slice(5);
808
+ const tsMessage = (key) => `\`${key}\` is prefixed \`maybe*\` but its type is not \`Option<T>\`. Either change the type to \`Option<T>\`, or rename to \`nullable${renameSuffix(key)}\`. (EF)`;
809
+ const schemaMessage = (key) => `Schema field \`${key}\` is prefixed \`maybe*\` but uses \`S.optional\` / nullable shape instead of \`S.Option\`. Use \`${key}: S.Option(...)\` (or \`S.OptionFromNullishOr\`, etc.) to match the prefix. (EF)`;
810
+ const rule$29 = Rule.define({
811
+ name: "maybe-prefix-requires-option",
812
+ meta: Rule.meta({
813
+ type: "suggestion",
814
+ description: "`maybe*`-prefixed names must be typed as `Option<T>` (TS) or `Schema.Option(...)` (Schema) (EF)"
815
+ }),
816
+ create: function* () {
817
+ const ctx = yield* RuleContext;
818
+ const reportTs = (node, key) => ctx.report(Diagnostic.make({
819
+ node,
820
+ message: tsMessage(key)
821
+ }));
822
+ const reportSchema = (node, key) => ctx.report(Diagnostic.make({
823
+ node,
824
+ message: schemaMessage(key)
825
+ }));
826
+ const checkAnnotated = (node, key) => pipe$1(readAnnotation(node), Option.filter(annotationIsBareNullish), Option.match({
827
+ onNone: () => Effect.void,
828
+ onSome: () => reportTs(node, key)
829
+ }));
830
+ const tsIdentifierVisitor = Visitor.on("Identifier", (node) => {
831
+ if (!isMaybePrefixedName(node.name)) return Effect.void;
832
+ return checkAnnotated(node, node.name);
833
+ });
834
+ const tsPropertySignatureVisitor = Visitor.on("TSPropertySignature", (node) => {
835
+ if (!isNodeWithType(node.key)) return Effect.void;
836
+ if (node.key.type !== "Identifier") return Effect.void;
837
+ const keyName = node.key.name;
838
+ if (!isMaybePrefixedName(keyName)) return Effect.void;
839
+ return checkAnnotated(node, keyName);
840
+ });
841
+ const schemaStructVisitor = Visitor.on("CallExpression", (node) => {
842
+ if (!isSchemaStructCall$1(node)) return Effect.void;
843
+ return pipe$1(fieldsArg$1(node), Option.map(schemaFindings), Option.match({
844
+ onNone: () => Effect.void,
845
+ onSome: (findings) => Effect.forEach(findings, (f) => reportSchema(f.node, f.key), {
846
+ concurrency: 1,
847
+ discard: true
848
+ })
849
+ }));
850
+ });
851
+ return Visitor.merge(tsIdentifierVisitor, tsPropertySignatureVisitor, schemaStructVisitor);
852
+ }
853
+ });
854
+ /**
855
+ * Packages where barrel imports (named imports from package root) should
856
+ * be namespace imports from submodules instead.
857
+ */
858
+ const BARREL_PACKAGES = /* @__PURE__ */ new Set(["effect"]);
859
+ const isFunctionExport = Schema.is(Schema.Literals([
860
+ "absurd",
861
+ "cast",
862
+ "flow",
863
+ "hole",
864
+ "identity",
865
+ "pipe"
866
+ ]));
867
+ const rule$28 = Rule.define({
868
+ name: "no-barrel-imports",
869
+ meta: Rule.meta({
870
+ type: "suggestion",
871
+ description: "Disallow named imports from barrel packages — use submodule namespace imports instead"
872
+ }),
873
+ create: function* () {
874
+ const ctx = yield* RuleContext;
875
+ return { ImportDeclaration: (node) => {
876
+ const decl = node;
877
+ const src = decl.source.value;
878
+ if (!BARREL_PACKAGES.has(src)) return Effect.void;
879
+ if (decl.importKind === "type") return Effect.void;
880
+ for (const specifier of decl.specifiers) {
881
+ if (specifier.type !== "ImportSpecifier") continue;
882
+ if (specifier.importKind === "type") continue;
883
+ const imported = specifier.imported;
884
+ if (!imported || imported.type !== "Identifier") continue;
885
+ const name = imported.name;
886
+ const local = specifier.local.name;
887
+ const suggestion = isFunctionExport(name) ? `import { ${name === local ? name : `${name} as ${local}`} } from "effect/Function"` : `import * as ${local} from "effect/${name}"`;
888
+ return ctx.report(Diagnostic.make({
889
+ node,
890
+ message: `Prefer \`${suggestion}\` over a named import from "${src}" to keep the dependency on its owning module explicit.`
891
+ }));
892
+ }
893
+ return Effect.void;
894
+ } };
895
+ }
896
+ });
897
+ function isTypeAssertionExpression(node) {
898
+ return node.type === "TSAsExpression" || node.type === "TSTypeAssertion";
899
+ }
900
+ function unwrapParenthesizedExpression(expression) {
901
+ let current = expression;
902
+ while (current.type === "ParenthesizedExpression") current = current.expression;
903
+ return current;
904
+ }
905
+ function isConstAssertion$1(node) {
906
+ const { typeAnnotation } = node;
907
+ return typeAnnotation.type === "TSTypeReference" && typeAnnotation.typeName.type === "Identifier" && typeAnnotation.typeName.name === "const";
908
+ }
909
+ function isOutermostAssertionInChain(node) {
910
+ let current = node;
911
+ let parent = node.parent;
912
+ while (parent.type === "ParenthesizedExpression" && parent.expression === current) {
913
+ current = parent;
914
+ parent = parent.parent;
915
+ }
916
+ return !isTypeAssertionExpression(parent) || parent.expression !== current;
917
+ }
918
+ function isForbiddenAssertionChain(node) {
919
+ let assertionCount = 0;
920
+ let hasNonConstAssertion = false;
921
+ let current = node;
922
+ while (isTypeAssertionExpression(current)) {
923
+ assertionCount += 1;
924
+ hasNonConstAssertion ||= !isConstAssertion$1(current);
925
+ current = unwrapParenthesizedExpression(current.expression);
926
+ }
927
+ return assertionCount > 1 && hasNonConstAssertion;
928
+ }
929
+ /** Disallow nested TypeScript type assertions, while permitting chains made only of const assertions. */
930
+ const noChainedTypeAssertionsRule = Rule.define({
931
+ name: "no-chained-type-assertions",
932
+ meta: {
933
+ type: "problem",
934
+ docs: { description: "Disallow chained TypeScript as and angle-bracket assertions, including parenthesized chains." },
935
+ messages: { chained: "This assertion chain discards type evidence. Keep the original precise type, or parse untrusted input at its boundary before narrowing it." }
936
+ },
937
+ create: function* () {
938
+ const context = yield* RuleContext;
939
+ const checkTypeAssertion = Effect.fn("no-chained-type-assertions.checkTypeAssertion")(function* (node) {
940
+ if (!isOutermostAssertionInChain(node) || !isForbiddenAssertionChain(node)) return;
941
+ yield* context.report({
942
+ node,
943
+ messageId: "chained"
944
+ });
945
+ });
946
+ return Visitor.merge(Visitor.on("TSAsExpression", checkTypeAssertion), Visitor.on("TSTypeAssertion", checkTypeAssertion));
947
+ }
948
+ });
949
+ function unwrapParentheses(node) {
950
+ let current = node;
951
+ while (current.type === "ParenthesizedExpression") current = current.expression;
952
+ return current;
953
+ }
954
+ function isEmptyObjectExpression$1(node) {
955
+ return node.type === "ObjectExpression" && node.properties.length === 0;
956
+ }
957
+ function isConditionalEmptyObjectSpread(node) {
958
+ const conditional = unwrapParentheses(node);
959
+ return conditional.type === "ConditionalExpression" && (isEmptyObjectExpression$1(conditional.consequent) || isEmptyObjectExpression$1(conditional.alternate));
960
+ }
961
+ /** Ban conditional empty-object spreads without changing their omission semantics. */
962
+ const noConditionalEmptyObjectSpreadRule = Rule.define({
963
+ name: "no-conditional-empty-object-spread",
964
+ meta: {
965
+ type: "suggestion",
966
+ docs: { description: "Disallow object spreads that conditionally spread an empty object to omit fields." },
967
+ messages: { avoid: "This conditional spread hides property omission behind an empty object. Build the object in separate statements and add the property only when present." }
968
+ },
969
+ create: function* () {
970
+ const context = yield* RuleContext;
971
+ return Visitor.on("SpreadElement", Effect.fn("no-conditional-empty-object-spread.SpreadElement")(function* (node) {
972
+ if (node.parent.type !== "ObjectExpression") return;
973
+ if (isConditionalEmptyObjectSpread(node.argument)) yield* context.report({
974
+ node,
975
+ messageId: "avoid"
976
+ });
977
+ }));
978
+ }
979
+ });
980
+ function isNode$1(value) {
981
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
982
+ }
983
+ function collectInferTypeParameterNames(node, visitorKeys, names) {
984
+ if (node.type === "TSInferType") names.add(node.typeParameter.name.name);
985
+ const record = node;
986
+ for (const key of visitorKeys[node.type] ?? []) {
987
+ const value = record[key];
988
+ if (isNode$1(value)) {
989
+ collectInferTypeParameterNames(value, visitorKeys, names);
990
+ continue;
991
+ }
992
+ if (!Array.isArray(value)) continue;
993
+ for (const child of value) if (isNode$1(child)) collectInferTypeParameterNames(child, visitorKeys, names);
994
+ }
995
+ }
996
+ /** Collect type binders that are in scope at a node and can shadow module aliases. */
997
+ function lexicalTypeParameterNames(node, visitorKeys) {
998
+ const names = /* @__PURE__ */ new Set();
999
+ let descendant = node;
1000
+ let current = node;
1001
+ while (current !== null && current.type !== "Program") {
1002
+ if ("typeParameters" in current) for (const parameter of current.typeParameters?.params ?? []) names.add(parameter.name.name);
1003
+ if (current.type === "TSMappedType" && (descendant === current.nameType || descendant === current.typeAnnotation)) names.add(current.key.name);
1004
+ if (current.type === "TSConditionalType" && descendant === current.trueType) collectInferTypeParameterNames(current.extendsType, visitorKeys, names);
1005
+ descendant = current;
1006
+ current = current.parent;
1007
+ }
1008
+ return names;
1009
+ }
1010
+ function isNode(value) {
1011
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
1012
+ }
1013
+ function enclosingTypeScope(node) {
1014
+ let current = node.parent;
1015
+ while (current !== null) {
1016
+ if (current.type === "Program" || current.type === "BlockStatement" || current.type === "TSModuleBlock" || current.type === "StaticBlock" || current.type === "SwitchStatement") return current;
1017
+ current = current.parent;
1018
+ }
1019
+ return node;
1020
+ }
1021
+ function declaredTypeBinding(node) {
1022
+ if (node.type === "TSTypeAliasDeclaration") return {
1023
+ alias: node,
1024
+ name: node.id.name
1025
+ };
1026
+ if (node.type === "TSInterfaceDeclaration" || node.type === "TSEnumDeclaration" || node.type === "ClassDeclaration" || node.type === "ClassExpression") return node.id === null ? null : {
1027
+ alias: null,
1028
+ name: node.id.name
1029
+ };
1030
+ if (node.type === "ImportSpecifier" || node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier") return {
1031
+ alias: null,
1032
+ name: node.local.name
1033
+ };
1034
+ return null;
1035
+ }
1036
+ function collectTypeBindings(node, visitorKeys, bindingsByName, aliases) {
1037
+ const declared = declaredTypeBinding(node);
1038
+ if (declared !== null) {
1039
+ const bindings = bindingsByName.get(declared.name) ?? [];
1040
+ bindings.push({
1041
+ ...declared,
1042
+ scope: enclosingTypeScope(node)
1043
+ });
1044
+ bindingsByName.set(declared.name, bindings);
1045
+ if (declared.alias !== null) aliases.push(declared.alias);
1046
+ }
1047
+ const fields = node;
1048
+ for (const key of visitorKeys[node.type] ?? []) {
1049
+ const value = fields[key];
1050
+ if (isNode(value)) {
1051
+ collectTypeBindings(value, visitorKeys, bindingsByName, aliases);
1052
+ continue;
1053
+ }
1054
+ if (!Array.isArray(value)) continue;
1055
+ for (const child of value) if (isNode(child)) collectTypeBindings(child, visitorKeys, bindingsByName, aliases);
1056
+ }
1057
+ }
1058
+ /** Collect every lexical type alias and competing type binding in a program. */
1059
+ function createTypeAliasEnvironment(program, visitorKeys) {
1060
+ const bindingsByName = /* @__PURE__ */ new Map();
1061
+ const aliases = [];
1062
+ collectTypeBindings(program, visitorKeys, bindingsByName, aliases);
1063
+ return {
1064
+ aliases,
1065
+ bindingsByName,
1066
+ visitorKeys
1067
+ };
1068
+ }
1069
+ function ancestorDistance(ancestor, node) {
1070
+ let current = node;
1071
+ let distance = 0;
1072
+ while (current !== null) {
1073
+ if (current === ancestor) return distance;
1074
+ current = current.parent;
1075
+ distance += 1;
1076
+ }
1077
+ return null;
1078
+ }
1079
+ function nearestTypeBindings(name, use, environment) {
1080
+ const candidates = environment.bindingsByName.get(name) ?? [];
1081
+ let nearestDistance = Number.POSITIVE_INFINITY;
1082
+ let nearest = [];
1083
+ for (const candidate of candidates) {
1084
+ const distance = ancestorDistance(candidate.scope, use);
1085
+ if (distance === null || distance > nearestDistance) continue;
1086
+ if (distance === nearestDistance) {
1087
+ nearest.push(candidate);
1088
+ continue;
1089
+ }
1090
+ nearestDistance = distance;
1091
+ nearest = [candidate];
1092
+ }
1093
+ return nearest;
1094
+ }
1095
+ /** Resolve the nearest visible alias with this name, respecting lexical shadowing. */
1096
+ function visibleTypeAlias(name, use, environment) {
1097
+ if (lexicalTypeParameterNames(use, environment.visitorKeys).has(name)) return null;
1098
+ const bindings = nearestTypeBindings(name, use, environment);
1099
+ return bindings.length === 1 ? bindings[0]?.alias ?? null : null;
1100
+ }
1101
+ /** Return whether a local declaration shadows a built-in type at this use. */
1102
+ function hasVisibleTypeBinding(name, use, environment) {
1103
+ return lexicalTypeParameterNames(use, environment.visitorKeys).has(name) || nearestTypeBindings(name, use, environment).length > 0;
1104
+ }
1105
+ function typeReferenceName$3(type) {
1106
+ return type.typeName.type === "Identifier" ? type.typeName.name : null;
1107
+ }
1108
+ function aliasSubstitutions(alias, reference, base) {
1109
+ const parameters = alias.typeParameters?.params ?? [];
1110
+ const arguments_ = reference.typeArguments?.params ?? [];
1111
+ const next = new Map(base);
1112
+ for (const [index, parameter] of parameters.entries()) {
1113
+ const explicitArgument = arguments_[index];
1114
+ const argument = explicitArgument ?? parameter.default;
1115
+ if (argument === null || argument === void 0) return null;
1116
+ const argumentSubstitutions = explicitArgument === void 0 ? next : base;
1117
+ next.set(parameter.name.name, {
1118
+ type: argument,
1119
+ substitutions: new Map(argumentSubstitutions)
1120
+ });
1121
+ }
1122
+ return next;
1123
+ }
1124
+ /** Match a type after resolving visible aliases and substituting their type parameters. */
1125
+ function resolvedTypeMatches(type, environment, matcher) {
1126
+ const evaluate = (current, substitutions, resolvingAliases) => {
1127
+ if (current.type === "TSTypeReference") {
1128
+ const name = typeReferenceName$3(current);
1129
+ if (name !== null) {
1130
+ const substitution = substitutions.get(name);
1131
+ if (substitution !== void 0 && !current.typeArguments?.params.length) return evaluate(substitution.type, substitution.substitutions, resolvingAliases);
1132
+ const alias = visibleTypeAlias(name, current, environment);
1133
+ if (alias !== null && !resolvingAliases.has(alias)) {
1134
+ const nextSubstitutions = aliasSubstitutions(alias, current, substitutions);
1135
+ if (nextSubstitutions !== null) {
1136
+ const nextResolving = new Set(resolvingAliases);
1137
+ nextResolving.add(alias);
1138
+ return evaluate(alias.typeAnnotation, nextSubstitutions, nextResolving);
1139
+ }
1140
+ }
1141
+ }
1142
+ }
1143
+ return matcher(current, (child) => evaluate(child, substitutions, resolvingAliases));
1144
+ };
1145
+ return evaluate(type, /* @__PURE__ */ new Map(), /* @__PURE__ */ new Set());
1146
+ }
1147
+ const BUILT_INS = /* @__PURE__ */ new Set([
1148
+ "Record",
1149
+ "Readonly",
1150
+ "Partial",
1151
+ "Required",
1152
+ "Pick",
1153
+ "Omit",
1154
+ "PropertyKey",
1155
+ "NonNullable"
1156
+ ]);
1157
+ const TRANSPARENT_WRAPPERS = /* @__PURE__ */ new Set([
1158
+ "Readonly",
1159
+ "Partial",
1160
+ "Required",
1161
+ "NonNullable"
1162
+ ]);
1163
+ function declaredStatement(statement) {
1164
+ return statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? statement.declaration ?? null : statement;
1165
+ }
1166
+ /** Collect interfaces and scoped aliases without retaining another file's AST. */
1167
+ function createTypeEnvironment(program, visitorKeys) {
1168
+ const interfaces = /* @__PURE__ */ new Map();
1169
+ for (const statement of program.body) {
1170
+ const declaration = declaredStatement(statement);
1171
+ if (declaration?.type !== "TSInterfaceDeclaration") continue;
1172
+ const declarations = interfaces.get(declaration.id.name) ?? [];
1173
+ declarations.push(declaration);
1174
+ interfaces.set(declaration.id.name, declarations);
1175
+ }
1176
+ return {
1177
+ interfaces,
1178
+ typeAliases: createTypeAliasEnvironment(program, visitorKeys)
1179
+ };
1180
+ }
1181
+ function typeReferenceName$2(type) {
1182
+ return type.typeName.type === "Identifier" ? type.typeName.name : null;
1183
+ }
1184
+ function isBuiltIn(name, use, environment) {
1185
+ return BUILT_INS.has(name) && !hasVisibleTypeBinding(name, use, environment.typeAliases);
1186
+ }
1187
+ function isUnappliedReferenceTo(type, name) {
1188
+ const unwrapped = unwrapTransparentType(type);
1189
+ return unwrapped.type === "TSTypeReference" && typeReferenceName$2(unwrapped) === name && (unwrapped.typeArguments === null || unwrapped.typeArguments === void 0 || unwrapped.typeArguments.params.length === 0);
1190
+ }
1191
+ function unwrapTransparentType(type) {
1192
+ let current = type;
1193
+ while (current.type === "TSParenthesizedType" || current.type === "TSTypeOperator" && current.operator === "readonly") current = current.typeAnnotation;
1194
+ return current;
1195
+ }
1196
+ function isNeverType(type) {
1197
+ return unwrapTransparentType(type).type === "TSNeverKeyword";
1198
+ }
1199
+ function isEffectivelyEmptyMember(member) {
1200
+ return member.type === "TSPropertySignature" && member.optional === true && member.typeAnnotation !== null && member.typeAnnotation !== void 0 && isNeverType(member.typeAnnotation.typeAnnotation);
1201
+ }
1202
+ function isEffectivelyEmptyTypeLiteral(type) {
1203
+ return type.members.length === 0 || type.members.every(isEffectivelyEmptyMember);
1204
+ }
1205
+ function isEffectivelyEmptyInterface(declarations) {
1206
+ if (declarations.length !== 1) return false;
1207
+ const [type] = declarations;
1208
+ return type !== void 0 && type.extends.length === 0 && (type.body.body.length === 0 || type.body.body.every(isEffectivelyEmptyMember));
1209
+ }
1210
+ function resolvedSubstitutionArgument(type, base, resolving = /* @__PURE__ */ new Set()) {
1211
+ const unwrapped = unwrapTransparentType(type);
1212
+ if (unwrapped.type !== "TSTypeReference") return type;
1213
+ const name = typeReferenceName$2(unwrapped);
1214
+ if (name === null || resolving.has(name)) return type;
1215
+ const substitution = base.get(name);
1216
+ if (substitution === void 0) return type;
1217
+ const nextResolving = new Set(resolving);
1218
+ nextResolving.add(name);
1219
+ return resolvedSubstitutionArgument(substitution, base, nextResolving);
1220
+ }
1221
+ function aliasSubstitution(alias, type, base) {
1222
+ const parameters = alias.typeParameters?.params ?? [];
1223
+ const arguments_ = type.typeArguments?.params ?? [];
1224
+ const next = new Map(base);
1225
+ for (const [index, parameter] of parameters.entries()) {
1226
+ const argument = arguments_[index] ?? parameter.default;
1227
+ if (argument === null || argument === void 0) return null;
1228
+ next.set(parameter.name.name, resolvedSubstitutionArgument(argument, next));
1229
+ }
1230
+ return next;
1231
+ }
1232
+ function unsafeDirectValue(type, environment, substitutions, resolvingAliases) {
1233
+ const unwrapped = unwrapTransparentType(type);
1234
+ if (unwrapped.type === "TSUnknownKeyword") return "unknown";
1235
+ if (unwrapped.type === "TSAnyKeyword") return "any";
1236
+ if (unwrapped.type === "TSObjectKeyword") return "object";
1237
+ if (unwrapped.type === "TSTypeLiteral" && isEffectivelyEmptyTypeLiteral(unwrapped)) return "empty-object";
1238
+ if (unwrapped.type === "TSUnionType") return unwrapped.types.some((member) => unsafeDirectValue(member, environment, substitutions, resolvingAliases) !== null) ? "union" : null;
1239
+ if (unwrapped.type === "TSIntersectionType") {
1240
+ const unsafeMembers = unwrapped.types.map((member) => unsafeDirectValue(member, environment, substitutions, resolvingAliases));
1241
+ if (unsafeMembers.includes("any")) return "any";
1242
+ return unsafeMembers.length > 0 && unsafeMembers.every((member) => member !== null) ? unsafeMembers[0] ?? null : null;
1243
+ }
1244
+ if (unwrapped.type !== "TSTypeReference") return null;
1245
+ const name = typeReferenceName$2(unwrapped);
1246
+ if (name === null) return null;
1247
+ if (TRANSPARENT_WRAPPERS.has(name) && isBuiltIn(name, unwrapped, environment)) {
1248
+ const wrapped = unwrapped.typeArguments?.params[0];
1249
+ return wrapped === void 0 ? null : unsafeDirectValue(wrapped, environment, substitutions, resolvingAliases);
1250
+ }
1251
+ const substitution = substitutions.get(name);
1252
+ if (substitution !== void 0) return isUnappliedReferenceTo(substitution, name) ? null : unsafeDirectValue(substitution, environment, substitutions, resolvingAliases);
1253
+ const interfaceDeclarations = environment.interfaces.get(name);
1254
+ if (interfaceDeclarations !== void 0) return isEffectivelyEmptyInterface(interfaceDeclarations) ? "empty-object" : null;
1255
+ const alias = visibleTypeAlias(name, unwrapped, environment.typeAliases);
1256
+ if (alias === null || resolvingAliases.has(name)) return null;
1257
+ const nextSubstitutions = aliasSubstitution(alias, unwrapped, substitutions);
1258
+ if (nextSubstitutions === null) return null;
1259
+ const nextResolving = new Set(resolvingAliases);
1260
+ nextResolving.add(name);
1261
+ return unsafeDirectValue(alias.typeAnnotation, environment, nextSubstitutions, nextResolving);
1262
+ }
1263
+ function dictionaryValueTypes(type, environment, substitutions, resolvingAliases) {
1264
+ const unwrapped = unwrapTransparentType(type);
1265
+ if (unwrapped.type === "TSTypeLiteral") return unwrapped.members.flatMap((member) => member.type === "TSIndexSignature" && member.typeAnnotation !== null ? [{
1266
+ type: member.typeAnnotation.typeAnnotation,
1267
+ substitutions
1268
+ }] : []);
1269
+ if (unwrapped.type === "TSMappedType") return unwrapped.typeAnnotation === null ? [] : [{
1270
+ type: unwrapped.typeAnnotation,
1271
+ substitutions
1272
+ }];
1273
+ if (unwrapped.type !== "TSTypeReference") return [];
1274
+ const name = typeReferenceName$2(unwrapped);
1275
+ if (name === null) return [];
1276
+ const substitution = substitutions.get(name);
1277
+ if (substitution !== void 0) return isUnappliedReferenceTo(substitution, name) ? [] : dictionaryValueTypes(substitution, environment, substitutions, resolvingAliases);
1278
+ if (TRANSPARENT_WRAPPERS.has(name) && isBuiltIn(name, unwrapped, environment)) {
1279
+ const wrapped = unwrapped.typeArguments?.params[0];
1280
+ return wrapped === void 0 ? [] : dictionaryValueTypes(wrapped, environment, substitutions, resolvingAliases);
1281
+ }
1282
+ if (name === "Record" && isBuiltIn(name, unwrapped, environment)) {
1283
+ const value = unwrapped.typeArguments?.params[1] ?? null;
1284
+ return value === null ? [] : [{
1285
+ type: value,
1286
+ substitutions
1287
+ }];
1288
+ }
1289
+ if ((name === "Pick" || name === "Omit") && isBuiltIn(name, unwrapped, environment)) {
1290
+ const source = unwrapped.typeArguments?.params[0];
1291
+ return source === void 0 ? [] : dictionaryValueTypes(source, environment, substitutions, resolvingAliases);
1292
+ }
1293
+ const alias = visibleTypeAlias(name, unwrapped, environment.typeAliases);
1294
+ if (alias === null || resolvingAliases.has(name)) return [];
1295
+ const nextSubstitutions = aliasSubstitution(alias, unwrapped, substitutions);
1296
+ if (nextSubstitutions === null) return [];
1297
+ const nextResolving = new Set(resolvingAliases);
1298
+ nextResolving.add(name);
1299
+ return dictionaryValueTypes(alias.typeAnnotation, environment, nextSubstitutions, nextResolving);
1300
+ }
1301
+ /** Classify a direct dictionary value type after resolving local aliases. */
1302
+ function classifyUnsafeDictionaryValue(valueType, environment) {
1303
+ const unsafeValue = unsafeDirectValue(valueType, environment, /* @__PURE__ */ new Map(), /* @__PURE__ */ new Set());
1304
+ return unsafeValue === null ? null : {
1305
+ kind: "unsafe-dictionary",
1306
+ unsafeValue
1307
+ };
1308
+ }
1309
+ /** Find an unsafe direct value in an object-dictionary contract. */
1310
+ function classifyUnsafeDictionary(type, environment) {
1311
+ for (const valueType of dictionaryValueTypes(type, environment, /* @__PURE__ */ new Map(), /* @__PURE__ */ new Set())) {
1312
+ const unsafeValue = unsafeDirectValue(valueType.type, environment, valueType.substitutions, /* @__PURE__ */ new Set());
1313
+ if (unsafeValue !== null) return {
1314
+ kind: "unsafe-dictionary",
1315
+ unsafeValue
1316
+ };
1317
+ }
1318
+ return null;
1319
+ }
1320
+ /** Classify broad targets while preserving finite-key records and nominal owners. */
1321
+ function classifyWideningTarget(type, environment) {
1322
+ const unwrapped = unwrapTransparentType(type);
1323
+ if (unwrapped.type === "TSUnknownKeyword") return { kind: "unknown" };
1324
+ if (unwrapped.type === "TSObjectKeyword") return { kind: "object" };
1325
+ if (unwrapped.type === "TSTypeLiteral") return unwrapped.members.some((member) => member.type === "TSIndexSignature") ? { kind: "open dictionary" } : unwrapped.members.length > 0 ? { kind: "anonymous object" } : null;
1326
+ if (unwrapped.type === "TSMappedType") return { kind: "open dictionary" };
1327
+ if (unwrapped.type !== "TSTypeReference") return null;
1328
+ const name = typeReferenceName$2(unwrapped);
1329
+ if (name === null) return null;
1330
+ if (TRANSPARENT_WRAPPERS.has(name) && isBuiltIn(name, unwrapped, environment)) {
1331
+ const wrapped = unwrapped.typeArguments?.params[0];
1332
+ return wrapped === void 0 ? null : classifyWideningTarget(wrapped, environment);
1333
+ }
1334
+ if (name === "Record" && isBuiltIn(name, unwrapped, environment)) return hasBroadRecordKey(unwrapped, environment, /* @__PURE__ */ new Map()) ? { kind: "open dictionary" } : null;
1335
+ const alias = visibleTypeAlias(name, unwrapped, environment.typeAliases);
1336
+ if (alias === null) return null;
1337
+ if ((alias.typeParameters?.params.length ?? 0) > 0) {
1338
+ const substitutions = aliasSubstitution(alias, unwrapped, /* @__PURE__ */ new Map());
1339
+ return (substitutions === null ? null : classifyAliasBroadTarget(alias.typeAnnotation, environment, substitutions, /* @__PURE__ */ new Set([name])))?.kind === "open dictionary" ? { kind: "generic container" } : null;
1340
+ }
1341
+ const substitutions = aliasSubstitution(alias, unwrapped, /* @__PURE__ */ new Map());
1342
+ if (substitutions === null) return null;
1343
+ return classifyAliasBroadTarget(alias.typeAnnotation, environment, substitutions, /* @__PURE__ */ new Set([name]));
1344
+ }
1345
+ function hasBroadRecordKey(type, environment, substitutions) {
1346
+ const key = type.typeArguments?.params[0];
1347
+ return key === void 0 || isBroadMappedKey(key, environment, substitutions);
1348
+ }
1349
+ function isBroadMappedKey(type, environment, substitutions, visitedAliases = /* @__PURE__ */ new Set()) {
1350
+ const unwrapped = unwrapTransparentType(type);
1351
+ if (unwrapped.type === "TSStringKeyword" || unwrapped.type === "TSNumberKeyword" || unwrapped.type === "TSSymbolKeyword") return true;
1352
+ if (unwrapped.type === "TSUnionType") return unwrapped.types.some((member) => isBroadMappedKey(member, environment, substitutions, visitedAliases));
1353
+ if (unwrapped.type !== "TSTypeReference") return false;
1354
+ const name = typeReferenceName$2(unwrapped);
1355
+ if (name === null) return false;
1356
+ const substitution = substitutions.get(name);
1357
+ if (substitution !== void 0 && !isUnappliedReferenceTo(substitution, name)) return isBroadMappedKey(substitution, environment, substitutions, visitedAliases);
1358
+ if (name === "PropertyKey" && isBuiltIn(name, unwrapped, environment)) return true;
1359
+ const alias = visibleTypeAlias(name, unwrapped, environment.typeAliases);
1360
+ if (alias === null || (alias.typeParameters?.params.length ?? 0) > 0 || visitedAliases.has(name)) return false;
1361
+ const nextVisited = new Set(visitedAliases);
1362
+ nextVisited.add(name);
1363
+ return isBroadMappedKey(alias.typeAnnotation, environment, substitutions, nextVisited);
1364
+ }
1365
+ function classifyAliasBroadTarget(type, environment, substitutions, resolvingAliases) {
1366
+ const unwrapped = unwrapTransparentType(type);
1367
+ if (unwrapped.type === "TSUnknownKeyword") return { kind: "unknown" };
1368
+ if (unwrapped.type === "TSObjectKeyword") return { kind: "object" };
1369
+ if (unwrapped.type === "TSTypeLiteral") return unwrapped.members.some((member) => member.type === "TSIndexSignature") ? { kind: "open dictionary" } : null;
1370
+ if (unwrapped.type === "TSMappedType") return isBroadMappedKey(unwrapped.constraint, environment, substitutions) ? { kind: "open dictionary" } : null;
1371
+ if (unwrapped.type !== "TSTypeReference") return null;
1372
+ const name = typeReferenceName$2(unwrapped);
1373
+ if (name === null) return null;
1374
+ const substitution = substitutions.get(name);
1375
+ if (substitution !== void 0) return isUnappliedReferenceTo(substitution, name) ? null : classifyAliasBroadTarget(substitution, environment, substitutions, resolvingAliases);
1376
+ if (TRANSPARENT_WRAPPERS.has(name) && isBuiltIn(name, unwrapped, environment)) {
1377
+ const wrapped = unwrapped.typeArguments?.params[0];
1378
+ return wrapped === void 0 ? null : classifyAliasBroadTarget(wrapped, environment, substitutions, resolvingAliases);
1379
+ }
1380
+ if (name === "Record" && isBuiltIn(name, unwrapped, environment)) return hasBroadRecordKey(unwrapped, environment, substitutions) ? { kind: "open dictionary" } : null;
1381
+ const alias = visibleTypeAlias(name, unwrapped, environment.typeAliases);
1382
+ if (alias === null || resolvingAliases.has(name)) return null;
1383
+ const nextSubstitutions = aliasSubstitution(alias, unwrapped, substitutions);
1384
+ if (nextSubstitutions === null) return null;
1385
+ const nextResolving = new Set(resolvingAliases);
1386
+ nextResolving.add(name);
1387
+ return classifyAliasBroadTarget(alias.typeAnnotation, environment, nextSubstitutions, nextResolving);
1388
+ }
1389
+ /** Recognize expressions carrying syntactically established value evidence. */
1390
+ function isKnownEvidenceExpression(expression) {
1391
+ let current = expression;
1392
+ while (current.type === "ParenthesizedExpression" || current.type === "TSAsExpression" || current.type === "TSTypeAssertion" || current.type === "TSNonNullExpression" || current.type === "TSSatisfiesExpression") current = current.expression;
1393
+ if (current.type === "ObjectExpression") return true;
1394
+ return current.type === "ArrayExpression" || current.type === "ArrowFunctionExpression" || current.type === "ClassExpression" || current.type === "FunctionExpression" || current.type === "NewExpression" || current.type === "Literal" || current.type === "TemplateLiteral" || current.type === "UnaryExpression";
1395
+ }
1396
+ /** Return whether a type is or contains TypeScript's absorbing unknown top type. */
1397
+ function containsUnknownType(type) {
1398
+ if (type.type === "TSUnknownKeyword") return true;
1399
+ if (type.type === "TSParenthesizedType") return containsUnknownType(type.typeAnnotation);
1400
+ return type.type === "TSUnionType" && type.types.some(containsUnknownType);
1401
+ }
1402
+ /** Return the TypeScript annotation attached to a function parameter or its wrapped binding. */
1403
+ function functionParameterTypeAnnotation(parameter) {
1404
+ if (parameter.type === "TSParameterProperty") return functionParameterTypeAnnotation(parameter.parameter);
1405
+ if (parameter.type === "RestElement") return parameter.typeAnnotation ?? functionParameterTypeAnnotation(parameter.argument);
1406
+ if (parameter.type === "AssignmentPattern") return parameter.typeAnnotation ?? functionParameterTypeAnnotation(parameter.left);
1407
+ return parameter.typeAnnotation;
1408
+ }
1409
+ /** Return only a function parameter's local binding, excluding its annotation and default value. */
1410
+ function functionParameterBindingName(parameter, sourceCode) {
1411
+ if (parameter.type === "TSParameterProperty") return functionParameterBindingName(parameter.parameter, sourceCode);
1412
+ if (parameter.type === "AssignmentPattern") return functionParameterBindingName(parameter.left, sourceCode);
1413
+ if (parameter.type === "RestElement") return functionParameterBindingName(parameter.argument, sourceCode);
1414
+ if (parameter.type === "Identifier") return parameter.name;
1415
+ const sourceText = sourceCode.getText(parameter);
1416
+ const annotationStart = functionParameterTypeAnnotation(parameter)?.start;
1417
+ return annotationStart === void 0 ? sourceText : sourceText.slice(0, annotationStart - parameter.start).trimEnd();
1418
+ }
1419
+ function unwrapExpression(expression) {
1420
+ let current = expression;
1421
+ while (current.type === "ParenthesizedExpression" || current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "TSTypeAssertion" || current.type === "TSNonNullExpression") current = current.expression;
1422
+ return current;
1423
+ }
1424
+ function resolveVariable(sourceCode, identifier) {
1425
+ let scope = sourceCode.getScope(identifier);
1426
+ while (scope !== null) {
1427
+ const variable = scope.set.get(identifier.name);
1428
+ if (variable !== void 0) return variable;
1429
+ scope = scope.upper;
1430
+ }
1431
+ return null;
1432
+ }
1433
+ function variableDeclarator$1(variable) {
1434
+ if (variable.defs.length !== 1) return null;
1435
+ const [definition] = variable.defs;
1436
+ return definition?.type === "Variable" && definition.node.type === "VariableDeclarator" ? definition.node : null;
1437
+ }
1438
+ function isStableConstVariable(variable, declarator) {
1439
+ return declarator.parent.type === "VariableDeclaration" && declarator.parent.kind === "const" && variable.references.every((reference) => reference.init || !reference.isWrite());
1440
+ }
1441
+ function hasKnownEvidence(sourceCode, expression, visitedVariables = /* @__PURE__ */ new Set()) {
1442
+ if (isKnownEvidenceExpression(expression)) return true;
1443
+ const unwrapped = unwrapExpression(expression);
1444
+ if (unwrapped.type !== "Identifier") return false;
1445
+ const variable = resolveVariable(sourceCode, unwrapped);
1446
+ if (variable === null || visitedVariables.has(variable)) return false;
1447
+ const declarator = variableDeclarator$1(variable);
1448
+ if (declarator === null || declarator.init === null || !isStableConstVariable(variable, declarator)) return false;
1449
+ visitedVariables.add(variable);
1450
+ return hasKnownEvidence(sourceCode, declarator.init, visitedVariables);
1451
+ }
1452
+ function isFunctionExpression(node) {
1453
+ return node.type === "ArrowFunctionExpression" || node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "TSDeclareFunction" || node.type === "TSEmptyBodyFunctionExpression";
1454
+ }
1455
+ function localFunctionForCall(sourceCode, callee) {
1456
+ const unwrapped = unwrapExpression(callee);
1457
+ if (isFunctionExpression(unwrapped)) return unwrapped;
1458
+ if (unwrapped.type !== "Identifier") return null;
1459
+ const variable = resolveVariable(sourceCode, unwrapped);
1460
+ if (variable === null || variable.defs.length !== 1) return null;
1461
+ const [definition] = variable.defs;
1462
+ if (definition === void 0) return null;
1463
+ if (definition.type === "FunctionName" && isFunctionExpression(definition.node)) return definition.node;
1464
+ if (definition.type !== "Variable" || definition.node.type !== "VariableDeclarator") return null;
1465
+ const initializer = definition.node.init;
1466
+ if (initializer === null) return null;
1467
+ const unwrappedInitializer = unwrapExpression(initializer);
1468
+ return isFunctionExpression(unwrappedInitializer) ? unwrappedInitializer : null;
1469
+ }
1470
+ function variableTypeAnnotation(sourceCode, variable) {
1471
+ if (variable.defs.length !== 1) return null;
1472
+ const [definition] = variable.defs;
1473
+ if (definition === void 0) return null;
1474
+ if (definition.type === "Variable" && definition.node.type === "VariableDeclarator" && definition.node.id.type === "Identifier") return definition.node.id.typeAnnotation ?? null;
1475
+ if (definition.type !== "Parameter" || !isFunctionExpression(definition.node)) return null;
1476
+ const parameter = definition.node.params.find((candidate) => functionParameterBindingName(candidate, sourceCode) === variable.name);
1477
+ return parameter === void 0 ? null : functionParameterTypeAnnotation(parameter) ?? null;
1478
+ }
1479
+ function hasInformativeType(type, environment) {
1480
+ return classifyUnsafeDictionaryValue(type, environment) === null;
1481
+ }
1482
+ function hasKnownCallArgumentEvidence(sourceCode, expression, environment, visitedVariables = /* @__PURE__ */ new Set()) {
1483
+ if (expression.type === "ParenthesizedExpression" || expression.type === "TSNonNullExpression") return hasKnownCallArgumentEvidence(sourceCode, expression.expression, environment, visitedVariables);
1484
+ if (expression.type === "TSAsExpression" || expression.type === "TSTypeAssertion") return hasInformativeType(expression.typeAnnotation, environment);
1485
+ if (expression.type === "TSSatisfiesExpression") return hasKnownCallArgumentEvidence(sourceCode, expression.expression, environment, visitedVariables);
1486
+ if (expression.type === "CallExpression") {
1487
+ const returnType = localFunctionForCall(sourceCode, expression.callee)?.returnType?.typeAnnotation;
1488
+ return returnType !== void 0 && hasInformativeType(returnType, environment);
1489
+ }
1490
+ if (expression.type !== "Identifier") return isKnownEvidenceExpression(expression);
1491
+ const variable = resolveVariable(sourceCode, expression);
1492
+ if (variable === null || visitedVariables.has(variable)) return false;
1493
+ const annotation = variableTypeAnnotation(sourceCode, variable);
1494
+ if (annotation !== null) return hasInformativeType(annotation.typeAnnotation, environment);
1495
+ const declarator = variableDeclarator$1(variable);
1496
+ if (declarator === null || declarator.init === null || !isStableConstVariable(variable, declarator)) return false;
1497
+ visitedVariables.add(variable);
1498
+ return hasKnownCallArgumentEvidence(sourceCode, declarator.init, environment, visitedVariables);
1499
+ }
1500
+ function typePredicateSubjectIndex(sourceCode, owner) {
1501
+ const predicate = owner.returnType?.typeAnnotation;
1502
+ if (predicate?.type !== "TSTypePredicate" || predicate.parameterName.type !== "Identifier") return null;
1503
+ const predicateParameterName = predicate.parameterName.name;
1504
+ const index = owner.params.findIndex((parameter) => functionParameterBindingName(parameter, sourceCode) === predicateParameterName);
1505
+ return index === -1 ? null : index;
1506
+ }
1507
+ function annotationTarget(annotation, environment) {
1508
+ return annotation === null || annotation === void 0 ? null : classifyWideningTarget(annotation.typeAnnotation, environment);
1509
+ }
1510
+ function enclosingFunction(node) {
1511
+ let current = node.parent;
1512
+ while (current !== null && current.type !== "Program") {
1513
+ if (current.type === "ArrowFunctionExpression" || current.type === "FunctionDeclaration" || current.type === "FunctionExpression") return current;
1514
+ current = current.parent;
1515
+ }
1516
+ return null;
1517
+ }
1518
+ function sourceKeyName(sourceCode, key) {
1519
+ if (key.type === "Identifier" || key.type === "PrivateIdentifier") return key.name;
1520
+ if (key.type === "Literal") return String(key.value);
1521
+ return sourceCode.getText(key);
1522
+ }
1523
+ function functionName(sourceCode, owner) {
1524
+ if (owner === null) return "anonymous function";
1525
+ if (owner.id !== null) return owner.id.name;
1526
+ const parent = owner.parent;
1527
+ if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") return parent.id.name;
1528
+ if (parent.type === "MethodDefinition") return sourceKeyName(sourceCode, parent.key);
1529
+ return "anonymous function";
1530
+ }
1531
+ function isEmptyObjectExpression(expression) {
1532
+ const unwrapped = unwrapExpression(expression);
1533
+ return unwrapped.type === "ObjectExpression" && unwrapped.properties.length === 0;
1534
+ }
1535
+ function isDictionaryAccumulatorTarget(destination) {
1536
+ return destination.kind === "open dictionary" || destination.kind === "generic container";
1537
+ }
1538
+ function hasParentAssertion(node) {
1539
+ return node.parent?.type === "TSAsExpression" || node.parent?.type === "TSTypeAssertion";
1540
+ }
1541
+ /** Detect sound syntactic cases where a known value is explicitly widened and loses evidence. */
1542
+ const noKnownValueWideningRule = Rule.define({
1543
+ name: "no-known-value-widening",
1544
+ meta: {
1545
+ type: "problem",
1546
+ docs: { description: "Disallow syntactically established values from flowing into explicitly broad or anonymous target types that discard useful evidence." },
1547
+ messages: { widening: "The explicit {{target}} type on {{subject}} discards known type evidence. Keep inference, validate with `satisfies`, or use a named owner contract." }
1548
+ },
1549
+ create: function* () {
1550
+ const context = yield* RuleContext;
1551
+ const environment = createTypeEnvironment(context.sourceCode.ast, context.sourceCode.visitorKeys);
1552
+ const reportFlow = Effect.fn("no-known-value-widening.reportFlow")(function* (expression, destination, subject) {
1553
+ if (destination === null) return;
1554
+ if (isDictionaryAccumulatorTarget(destination) && isEmptyObjectExpression(expression)) return;
1555
+ if (!hasKnownEvidence(context.sourceCode, expression)) return;
1556
+ yield* context.report({
1557
+ node: expression,
1558
+ messageId: "widening",
1559
+ data: {
1560
+ subject,
1561
+ target: destination.kind
1562
+ }
1563
+ });
1564
+ });
1565
+ const targetFromAnnotation = (annotation) => annotationTarget(annotation, environment);
1566
+ return Visitor.merge(Visitor.on("VariableDeclarator", Effect.fn("no-known-value-widening.VariableDeclarator")(function* (node) {
1567
+ if (node.init === null || node.id.type !== "Identifier") return;
1568
+ yield* reportFlow(node.init, targetFromAnnotation(node.id.typeAnnotation), `binding \`${node.id.name}\``);
1569
+ })), Visitor.on("PropertyDefinition", Effect.fn("no-known-value-widening.PropertyDefinition")(function* (node) {
1570
+ if (node.value === null) return;
1571
+ yield* reportFlow(node.value, targetFromAnnotation(node.typeAnnotation), `property \`${sourceKeyName(context.sourceCode, node.key)}\``);
1572
+ })), Visitor.on("AccessorProperty", Effect.fn("no-known-value-widening.AccessorProperty")(function* (node) {
1573
+ if (node.value === null) return;
1574
+ yield* reportFlow(node.value, targetFromAnnotation(node.typeAnnotation), `property \`${sourceKeyName(context.sourceCode, node.key)}\``);
1575
+ })), Visitor.on("AssignmentExpression", Effect.fn("no-known-value-widening.AssignmentExpression")(function* (node) {
1576
+ if (node.operator !== "=" || node.left.type !== "Identifier") return;
1577
+ const variable = resolveVariable(context.sourceCode, node.left);
1578
+ if (variable === null) return;
1579
+ const declarator = variableDeclarator$1(variable);
1580
+ if (declarator === null || declarator.id.type !== "Identifier") return;
1581
+ yield* reportFlow(node.right, targetFromAnnotation(declarator.id.typeAnnotation), `binding \`${declarator.id.name}\``);
1582
+ })), Visitor.on("CallExpression", Effect.fn("no-known-value-widening.CallExpression")(function* (node) {
1583
+ const owner = localFunctionForCall(context.sourceCode, node.callee);
1584
+ if (owner === null) return;
1585
+ const parameterIndex = typePredicateSubjectIndex(context.sourceCode, owner);
1586
+ if (parameterIndex === null) return;
1587
+ const parameter = owner.params[parameterIndex];
1588
+ const argument = node.arguments[parameterIndex];
1589
+ if (parameter === void 0 || argument === void 0 || argument.type === "SpreadElement") return;
1590
+ const parameterAnnotation = functionParameterTypeAnnotation(parameter);
1591
+ if (parameterAnnotation === null || parameterAnnotation === void 0 || !containsUnknownType(parameterAnnotation.typeAnnotation)) return;
1592
+ if (!hasKnownCallArgumentEvidence(context.sourceCode, argument, environment)) return;
1593
+ yield* context.report({
1594
+ node: argument,
1595
+ messageId: "widening",
1596
+ data: {
1597
+ subject: `argument for parameter \`${functionParameterBindingName(parameter, context.sourceCode)}\` of \`${functionName(context.sourceCode, owner)}\``,
1598
+ target: "unknown"
1599
+ }
1600
+ });
1601
+ })), Visitor.on("ReturnStatement", Effect.fn("no-known-value-widening.ReturnStatement")(function* (node) {
1602
+ if (node.argument === null) return;
1603
+ const owner = enclosingFunction(node);
1604
+ yield* reportFlow(node.argument, targetFromAnnotation(owner?.returnType), `return value of \`${functionName(context.sourceCode, owner)}\``);
1605
+ })), Visitor.on("ArrowFunctionExpression", Effect.fn("no-known-value-widening.ArrowFunctionExpression")(function* (node) {
1606
+ if (node.body.type === "BlockStatement") return;
1607
+ yield* reportFlow(node.body, targetFromAnnotation(node.returnType), `return value of \`${functionName(context.sourceCode, node)}\``);
1608
+ })), Visitor.on("TSAsExpression", Effect.fn("no-known-value-widening.TSAsExpression")(function* (node) {
1609
+ if (hasParentAssertion(node)) return;
1610
+ yield* reportFlow(node.expression, classifyWideningTarget(node.typeAnnotation, environment), "assertion");
1611
+ })), Visitor.on("TSTypeAssertion", Effect.fn("no-known-value-widening.TSTypeAssertion")(function* (node) {
1612
+ if (hasParentAssertion(node)) return;
1613
+ yield* reportFlow(node.expression, classifyWideningTarget(node.typeAnnotation, environment), "assertion");
1614
+ })));
1615
+ }
1616
+ });
1617
+ const isModuleMockMethod = Schema.is(Schema.Literals([
1618
+ "doMock",
1619
+ "mock",
1620
+ "unstable_mockModule"
1621
+ ]));
1622
+ function importedName(node) {
1623
+ if (node.type !== "ImportSpecifier") return null;
1624
+ return node.imported.type === "Identifier" ? node.imported.name : node.imported.value;
1625
+ }
1626
+ function isTestFrameworkObject(sourceCode, expression) {
1627
+ if (expression.type !== "Identifier") return false;
1628
+ if ((expression.name === "vi" || expression.name === "jest") && sourceCode.isGlobalReference(expression)) return true;
1629
+ return Option.match(Scope.findVariableUp(sourceCode.getScope(expression), expression.name), {
1630
+ onNone: () => expression.name === "vi" || expression.name === "jest",
1631
+ onSome: (variable) => Arr.match(variable.defs, {
1632
+ onEmpty: () => expression.name === "vi" || expression.name === "jest",
1633
+ onNonEmpty: (definitions) => Arr.some(definitions, (definition) => {
1634
+ if (definition.type !== "ImportBinding" || definition.parent?.type !== "ImportDeclaration") return false;
1635
+ const source = definition.parent.source.value;
1636
+ const name = importedName(definition.node);
1637
+ return source === "vitest" && name === "vi" || source === "@jest/globals" && name === "jest";
1638
+ })
1639
+ })
1640
+ });
1641
+ }
1642
+ function moduleMockCall(sourceCode, callee) {
1643
+ if (!("property" in callee) || !("object" in callee) || !("computed" in callee)) return false;
1644
+ if (!isTestFrameworkObject(sourceCode, callee.object)) return false;
1645
+ const property = callee.property;
1646
+ return isModuleMockMethod(callee.computed ? property.type === "Literal" && isModuleMockMethod(property.value) ? property.value : null : property.type === "Identifier" ? property.name : null);
1647
+ }
1648
+ /** Ban test framework module mocking in favor of real dependency seams. */
1649
+ const noModuleMockingRule = Rule.define({
1650
+ name: "no-module-mocking",
1651
+ meta: {
1652
+ type: "problem",
1653
+ docs: { description: "Disallow Vitest and Jest module mocking; tests must replace dependencies through real interfaces." },
1654
+ messages: { moduleMock: "Replace module mocking with dependency injection through a real interface, service layer, or faithful test implementation." }
1655
+ },
1656
+ create: function* () {
1657
+ const context = yield* RuleContext;
1658
+ return Visitor.on("CallExpression", Effect.fn("no-module-mocking.CallExpression")(function* (node) {
1659
+ if (node.callee.type === "Super" || node.callee.type === "V8IntrinsicExpression") return;
1660
+ if (moduleMockCall(context.sourceCode, node.callee)) yield* context.report({
1661
+ node,
1662
+ messageId: "moduleMock"
1663
+ });
1664
+ }));
1665
+ }
1666
+ });
1667
+ /** Ban the broad object type on function inputs, including local aliases to object. */
1668
+ const noObjectParametersRule = Rule.define({
1669
+ name: "no-object-parameters",
1670
+ meta: {
1671
+ type: "problem",
1672
+ docs: { description: "Disallow object function parameters; inputs must use an owner-provided type and be parsed at their boundary." },
1673
+ messages: { objectParameter: "Parameter `{{parameter}}` uses the broad `object` type. Accept a named owner type; parse external input at its boundary before calling this function." }
1674
+ },
1675
+ create: function* () {
1676
+ const context = yield* RuleContext;
1677
+ const environment = createTypeAliasEnvironment(context.sourceCode.ast, context.sourceCode.visitorKeys);
1678
+ const resolvesToObject = (type) => resolvedTypeMatches(type, environment, (resolved, matches) => {
1679
+ if (resolved.type === "TSObjectKeyword") return true;
1680
+ if (resolved.type === "TSParenthesizedType") return matches(resolved.typeAnnotation);
1681
+ return resolved.type === "TSUnionType" && resolved.types.some(matches);
1682
+ });
1683
+ const checkParameters = Effect.fn("no-object-parameters.checkParameters")(function* (node) {
1684
+ yield* Effect.forEach(node.params, Effect.fnUntraced(function* (parameter) {
1685
+ const annotation = functionParameterTypeAnnotation(parameter);
1686
+ if (annotation === null || annotation === void 0) return;
1687
+ if (!resolvesToObject(annotation.typeAnnotation)) return;
1688
+ yield* context.report({
1689
+ node: annotation.typeAnnotation,
1690
+ messageId: "objectParameter",
1691
+ data: { parameter: functionParameterBindingName(parameter, context.sourceCode) }
1692
+ });
1693
+ }), {
1694
+ concurrency: 1,
1695
+ discard: true
1696
+ });
1697
+ });
1698
+ return Visitor.merge(Visitor.on("ArrowFunctionExpression", checkParameters), Visitor.on("FunctionDeclaration", checkParameters), Visitor.on("FunctionExpression", checkParameters), Visitor.on("TSCallSignatureDeclaration", checkParameters), Visitor.on("TSConstructSignatureDeclaration", checkParameters), Visitor.on("TSConstructorType", checkParameters), Visitor.on("TSDeclareFunction", checkParameters), Visitor.on("TSEmptyBodyFunctionExpression", checkParameters), Visitor.on("TSFunctionType", checkParameters), Visitor.on("TSMethodSignature", checkParameters));
1699
+ }
1700
+ });
1701
+ function isGlobalReflect(sourceCode, expression) {
1702
+ if (expression.type !== "Identifier" || expression.name !== "Reflect") return false;
1703
+ if (sourceCode.isGlobalReference(expression)) return true;
1704
+ return Option.match(Scope.findVariableUp(sourceCode.getScope(expression), expression.name), {
1705
+ onNone: () => true,
1706
+ onSome: (variable) => variable.defs.length === 0
1707
+ });
1708
+ }
1709
+ /** Reports whether a call target names one method on the global Reflect object. */
1710
+ function isGlobalReflectMethodCall(sourceCode, callee, methodName) {
1711
+ if (!("property" in callee) || !("object" in callee) || !("computed" in callee)) return false;
1712
+ if (!isGlobalReflect(sourceCode, callee.object)) return false;
1713
+ const property = callee.property;
1714
+ return callee.computed ? property.type === "Literal" && property.value === methodName : property.type === "Identifier" && property.name === methodName;
1715
+ }
1716
+ /** Ban Reflect.apply, which bypasses ordinary typed function calls. */
1717
+ const noReflectApplyRule = Rule.define({
1718
+ name: "no-reflect-apply",
1719
+ meta: {
1720
+ type: "problem",
1721
+ docs: { description: "Disallow Reflect.apply; call typed functions directly or model dynamic dispatch behind an interface." },
1722
+ messages: { reflectApply: "Replace `Reflect.apply` with a typed function call. Model dynamic dispatch behind a named interface." }
1723
+ },
1724
+ create: function* () {
1725
+ const context = yield* RuleContext;
1726
+ return Visitor.on("CallExpression", Effect.fn("no-reflect-apply.CallExpression")(function* (node) {
1727
+ if (node.callee.type === "Super" || node.callee.type === "V8IntrinsicExpression") return;
1728
+ if (isGlobalReflectMethodCall(context.sourceCode, node.callee, "apply")) yield* context.report({
1729
+ node,
1730
+ messageId: "reflectApply"
1731
+ });
1732
+ }));
1733
+ }
1734
+ });
1735
+ /** Ban Reflect.get, which bypasses ordinary property access and useful type evidence. */
1736
+ const noReflectGetRule = Rule.define({
1737
+ name: "no-reflect-get",
1738
+ meta: {
1739
+ type: "problem",
1740
+ docs: { description: "Disallow Reflect.get; use typed property access or parse dynamic input into a domain type." },
1741
+ messages: { reflectGet: "Replace `Reflect.get` with typed property access. Parse dynamic input into a named domain type before reading it." }
1742
+ },
1743
+ create: function* () {
1744
+ const context = yield* RuleContext;
1745
+ return Visitor.on("CallExpression", Effect.fn("no-reflect-get.CallExpression")(function* (node) {
1746
+ if (node.callee.type === "Super" || node.callee.type === "V8IntrinsicExpression") return;
1747
+ if (isGlobalReflectMethodCall(context.sourceCode, node.callee, "get")) yield* context.report({
1748
+ node,
1749
+ messageId: "reflectGet"
1750
+ });
1751
+ }));
1752
+ }
1753
+ });
1754
+ var TypeofOptions = class extends Schema.Class("TypeofOptions")({ allowInTypeGuards: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(false))) }) {};
1755
+ function isRuntimeFunction(node) {
1756
+ return node.type === "ArrowFunctionExpression" || node.type === "FunctionDeclaration" || node.type === "FunctionExpression";
1757
+ }
1758
+ function isInsideTypeGuard(node) {
1759
+ let current = node.parent;
1760
+ while (current !== null && current.type !== "Program") {
1761
+ if (isRuntimeFunction(current)) return current.returnType?.typeAnnotation.type === "TSTypePredicate";
1762
+ current = current.parent;
1763
+ }
1764
+ return false;
1765
+ }
1766
+ /** Return whether typeof safely probes for the existence of a possibly absent binding. */
1767
+ function isExistenceProbe(node) {
1768
+ const parent = node.parent;
1769
+ if (parent.type !== "BinaryExpression") return false;
1770
+ if (![
1771
+ "===",
1772
+ "!==",
1773
+ "==",
1774
+ "!="
1775
+ ].includes(parent.operator)) return false;
1776
+ const other = parent.left === node ? parent.right : parent.left;
1777
+ return other.type === "Literal" && other.value === "undefined";
1778
+ }
1779
+ /** Disallow runtime typeof checks that narrow unparsed values instead of decoding them. */
1780
+ const noRuntimeTypeofRule = Rule.define({
1781
+ name: "no-runtime-typeof",
1782
+ options: TypeofOptions.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
1783
+ meta: {
1784
+ type: "problem",
1785
+ docs: { description: "Disallow runtime typeof checks; external values must be decoded into meaningful types at their I/O boundary." },
1786
+ messages: { runtimeTypeof: "A `typeof` check narrows a representation without establishing its contract. Parse input at its I/O boundary, then branch on the domain value." },
1787
+ schema: [{
1788
+ type: "object",
1789
+ properties: { allowInTypeGuards: { type: "boolean" } },
1790
+ additionalProperties: false
1791
+ }],
1792
+ defaultOptions: [{ allowInTypeGuards: false }]
1793
+ },
1794
+ create: function* ({ allowInTypeGuards }) {
1795
+ const context = yield* RuleContext;
1796
+ return Visitor.on("UnaryExpression", Effect.fn("no-runtime-typeof.UnaryExpression")(function* (node) {
1797
+ if (node.operator === "typeof" && !isExistenceProbe(node) && (!allowInTypeGuards || !isInsideTypeGuard(node))) yield* context.report({
1798
+ node,
1799
+ messageId: "runtimeTypeof"
1800
+ });
1801
+ }));
1802
+ }
1803
+ });
1804
+ const isServiceConstructorName = Schema.is(Schema.String.check(Schema.isPattern(/^make[A-Z]/u)));
1805
+ const isTestFilename = Schema.is(Schema.String.check(Schema.isPattern(/\.(?:test|spec)\.[cm]?[jt]sx?$/u)));
1806
+ function isProjectLocalImport(source) {
1807
+ return Str.startsWith("./")(source) || Str.startsWith("../")(source);
1808
+ }
1809
+ function getImportedName(specifier) {
1810
+ if (specifier.imported.type === "Identifier") return specifier.imported.name;
1811
+ return specifier.imported.value;
1812
+ }
1813
+ /** Keep dependency-bearing Effect service constructors local to their owning capability modules. */
1814
+ const noServiceConstructorImportsRule = Rule.define({
1815
+ name: "no-service-constructor-imports",
1816
+ meta: {
1817
+ type: "problem",
1818
+ docs: { description: "Disallow project-local make<CapabilityName> imports outside test and spec files." },
1819
+ messages: { serviceConstructorImport: "Do not import Effect service constructor \"{{name}}\" into runtime code. Import the owning Layer, yield the contextual service, and allow its requirements to propagate to the composition root." }
1820
+ },
1821
+ create: function* () {
1822
+ const context = yield* RuleContext;
1823
+ const isTestFile = isTestFilename(Str.replaceAll("\\", "/")(context.filename));
1824
+ return Visitor.on("ImportDeclaration", Effect.fn("no-service-constructor-imports.ImportDeclaration")(function* (node) {
1825
+ if (isTestFile || !isProjectLocalImport(node.source.value)) return;
1826
+ yield* Effect.forEach(node.specifiers, Effect.fnUntraced(function* (specifier) {
1827
+ if (specifier.type !== "ImportSpecifier") return;
1828
+ const importedName = getImportedName(specifier);
1829
+ if (!isServiceConstructorName(importedName)) return;
1830
+ yield* context.report({
1831
+ node: specifier,
1832
+ messageId: "serviceConstructorImport",
1833
+ data: { name: importedName }
1834
+ });
1835
+ }), {
1836
+ concurrency: 1,
1837
+ discard: true
1838
+ });
1839
+ }));
1840
+ }
1841
+ });
1842
+ const isForbiddenLowercaseName = Schema.is(Schema.String.check(Schema.isIncluding("shape")));
1843
+ const containsForbiddenSymbolName = (name) => isForbiddenLowercaseName(Str.toLowerCase(name));
1844
+ /** Return whether an identifier names a statically accessed member owned by another value. */
1845
+ function isBorrowedMemberName(node) {
1846
+ const parent = node.parent;
1847
+ if (parent === null || parent.type !== "MemberExpression") return false;
1848
+ return parent.property === node && parent.computed === false;
1849
+ }
1850
+ /** Ban the case-insensitive substring "shape" in every JavaScript and TypeScript symbol name. */
1851
+ const noForbiddenTermInSymbolNamesRule = Rule.define({
1852
+ name: "no-shape-in-symbol-names",
1853
+ meta: {
1854
+ type: "problem",
1855
+ docs: { description: "Disallow the case-insensitive substring \"shape\" in JavaScript, TypeScript, private, and JSX symbol names." },
1856
+ messages: { forbiddenSymbolName: "Rename symbol \"{{name}}\" for its domain role; \"shape\" describes structure rather than ownership." }
1857
+ },
1858
+ create: function* () {
1859
+ const context = yield* RuleContext;
1860
+ const reportForbiddenSymbolName = Effect.fn("no-shape-in-symbol-names.reportForbiddenSymbolName")(function* (node) {
1861
+ if (!containsForbiddenSymbolName(node.name) || isBorrowedMemberName(node)) return;
1862
+ yield* context.report({
1863
+ node,
1864
+ messageId: "forbiddenSymbolName",
1865
+ data: { name: node.name }
1866
+ });
1867
+ });
1868
+ return Visitor.merge(Visitor.on("Identifier", reportForbiddenSymbolName), Visitor.on("PrivateIdentifier", reportForbiddenSymbolName), Visitor.on("JSXIdentifier", reportForbiddenSymbolName));
1869
+ }
1870
+ });
1871
+ function isTypePredicateSubject(owner, parameterName) {
1872
+ const predicate = owner.returnType?.typeAnnotation;
1873
+ return predicate?.type === "TSTypePredicate" && predicate.parameterName.type === "Identifier" && predicate.parameterName.name === parameterName;
1874
+ }
1875
+ /** Disallow unknown inputs except explicitly named error-cause enrichment. */
1876
+ const noUnknownParametersRule = Rule.define({
1877
+ name: "no-unknown-parameters",
1878
+ meta: {
1879
+ type: "problem",
1880
+ docs: { description: "Disallow explicitly unknown function parameters except `cause` and type-predicate subjects; decode unknown input at its I/O boundary instead." },
1881
+ messages: { unknownParameter: "Parameter `{{parameter}}` leaves input unparsed. Accept a named domain type; run the expected schema or parser at the I/O boundary before calling this function." }
1882
+ },
1883
+ create: function* () {
1884
+ const context = yield* RuleContext;
1885
+ const checkParameters = Effect.fn("no-unknown-parameters.checkParameters")(function* (node) {
1886
+ yield* Effect.forEach(node.params, Effect.fnUntraced(function* (parameter) {
1887
+ const annotation = functionParameterTypeAnnotation(parameter);
1888
+ if (annotation === null || annotation === void 0) return;
1889
+ if (!containsUnknownType(annotation.typeAnnotation)) return;
1890
+ const name = functionParameterBindingName(parameter, context.sourceCode);
1891
+ if (name === "cause" || isTypePredicateSubject(node, name)) return;
1892
+ yield* context.report({
1893
+ node: annotation.typeAnnotation,
1894
+ messageId: "unknownParameter",
1895
+ data: { parameter: name }
1896
+ });
1897
+ }), {
1898
+ concurrency: 1,
1899
+ discard: true
1900
+ });
1901
+ });
1902
+ return Visitor.merge(Visitor.on("ArrowFunctionExpression", checkParameters), Visitor.on("FunctionDeclaration", checkParameters), Visitor.on("FunctionExpression", checkParameters), Visitor.on("TSCallSignatureDeclaration", checkParameters), Visitor.on("TSConstructSignatureDeclaration", checkParameters), Visitor.on("TSConstructorType", checkParameters), Visitor.on("TSDeclareFunction", checkParameters), Visitor.on("TSEmptyBodyFunctionExpression", checkParameters), Visitor.on("TSFunctionType", checkParameters), Visitor.on("TSMethodSignature", checkParameters));
1903
+ }
1904
+ });
1905
+ /** Ban function contracts that return unknown instead of a parsed domain type. */
1906
+ const noUnknownReturnsRule = Rule.define({
1907
+ name: "no-unknown-returns",
1908
+ meta: {
1909
+ type: "problem",
1910
+ docs: { description: "Disallow functions whose explicit return contract is unknown or Promise<unknown>." },
1911
+ messages: { unknownReturn: "This function exposes `unknown` to its caller. Parse the value at its boundary and return a named domain type." }
1912
+ },
1913
+ create: function* () {
1914
+ const context = yield* RuleContext;
1915
+ const environment = createTypeAliasEnvironment(context.sourceCode.ast, context.sourceCode.visitorKeys);
1916
+ const resolvesToUnknown = (type) => resolvedTypeMatches(type, environment, (resolved, matches) => {
1917
+ if (resolved.type === "TSUnknownKeyword") return true;
1918
+ if (resolved.type === "TSParenthesizedType") return matches(resolved.typeAnnotation);
1919
+ if (resolved.type === "TSUnionType") return resolved.types.some(matches);
1920
+ if (resolved.type !== "TSTypeReference" || resolved.typeName.type !== "Identifier" || resolved.typeName.name !== "Promise" && resolved.typeName.name !== "PromiseLike") return false;
1921
+ const value = resolved.typeArguments?.params[0];
1922
+ return value !== void 0 && matches(value);
1923
+ });
1924
+ const checkReturnType = Effect.fn("no-unknown-returns.checkReturnType")(function* (node) {
1925
+ const annotation = node.returnType;
1926
+ if (annotation === null || annotation === void 0) return;
1927
+ if (!resolvesToUnknown(annotation.typeAnnotation)) return;
1928
+ yield* context.report({
1929
+ node: annotation.typeAnnotation,
1930
+ messageId: "unknownReturn"
1931
+ });
1932
+ });
1933
+ return Visitor.merge(Visitor.on("ArrowFunctionExpression", checkReturnType), Visitor.on("FunctionDeclaration", checkReturnType), Visitor.on("FunctionExpression", checkReturnType), Visitor.on("TSCallSignatureDeclaration", checkReturnType), Visitor.on("TSConstructSignatureDeclaration", checkReturnType), Visitor.on("TSConstructorType", checkReturnType), Visitor.on("TSDeclareFunction", checkReturnType), Visitor.on("TSEmptyBodyFunctionExpression", checkReturnType), Visitor.on("TSFunctionType", checkReturnType), Visitor.on("TSMethodSignature", checkReturnType));
1934
+ }
1935
+ });
1936
+ /** Ban named aliases that merely conceal TypeScript's unknown top type. */
1937
+ const noUnknownTypeAliasesRule = Rule.define({
1938
+ name: "no-unknown-type-aliases",
1939
+ meta: {
1940
+ type: "problem",
1941
+ docs: { description: "Disallow type aliases whose resolved type is unknown; unknown must remain visible at an allowed boundary." },
1942
+ messages: { unknownAlias: "Type alias `{{alias}}` hides `unknown`. Keep `unknown` explicit at the parsing boundary or on an allowed `cause` field; otherwise use the parsed owner type." }
1943
+ },
1944
+ create: function* () {
1945
+ const context = yield* RuleContext;
1946
+ const environment = createTypeAliasEnvironment(context.sourceCode.ast, context.sourceCode.visitorKeys);
1947
+ const resolvesToUnknown = (type) => resolvedTypeMatches(type, environment, (resolved, matches) => {
1948
+ if (resolved.type === "TSUnknownKeyword") return true;
1949
+ if (resolved.type === "TSParenthesizedType") return matches(resolved.typeAnnotation);
1950
+ return resolved.type === "TSUnionType" && resolved.types.some(matches);
1951
+ });
1952
+ return Visitor.on("TSTypeAliasDeclaration", Effect.fn("no-unknown-type-aliases.TSTypeAliasDeclaration")(function* (node) {
1953
+ if (!resolvesToUnknown(node.typeAnnotation)) return;
1954
+ yield* context.report({
1955
+ node: node.id,
1956
+ messageId: "unknownAlias",
1957
+ data: { alias: node.id.name }
1958
+ });
1959
+ }));
1960
+ }
1961
+ });
1962
+ const typeNodeKinds = /* @__PURE__ */ new Set([
1963
+ "JSDocNonNullableType",
1964
+ "JSDocNullableType",
1965
+ "JSDocUnknownType",
1966
+ "TSAnyKeyword",
1967
+ "TSArrayType",
1968
+ "TSBigIntKeyword",
1969
+ "TSBooleanKeyword",
1970
+ "TSConditionalType",
1971
+ "TSConstructorType",
1972
+ "TSFunctionType",
1973
+ "TSImportType",
1974
+ "TSIndexedAccessType",
1975
+ "TSInferType",
1976
+ "TSIntersectionType",
1977
+ "TSIntrinsicKeyword",
1978
+ "TSLiteralType",
1979
+ "TSMappedType",
1980
+ "TSNamedTupleMember",
1981
+ "TSNeverKeyword",
1982
+ "TSNullKeyword",
1983
+ "TSNumberKeyword",
1984
+ "TSObjectKeyword",
1985
+ "TSParenthesizedType",
1986
+ "TSStringKeyword",
1987
+ "TSSymbolKeyword",
1988
+ "TSTemplateLiteralType",
1989
+ "TSThisType",
1990
+ "TSTupleType",
1991
+ "TSTypeLiteral",
1992
+ "TSTypeOperator",
1993
+ "TSTypePredicate",
1994
+ "TSTypeQuery",
1995
+ "TSTypeReference",
1996
+ "TSUndefinedKeyword",
1997
+ "TSUnionType",
1998
+ "TSUnknownKeyword",
1999
+ "TSVoidKeyword"
2000
+ ]);
2001
+ function isTypeNode(node) {
2002
+ return typeNodeKinds.has(node.type);
2003
+ }
2004
+ function typeReferenceName$1(type) {
2005
+ return type.typeName.type === "Identifier" ? type.typeName.name : null;
2006
+ }
2007
+ function isInsideTypeAliasDeclaration(node) {
2008
+ let current = node.parent;
2009
+ while (current !== null && current.type !== "Program") {
2010
+ if (current.type === "TSTypeAliasDeclaration") return true;
2011
+ current = current.parent;
2012
+ }
2013
+ return false;
2014
+ }
2015
+ function isPlainAliasConsumerUse(node, environment) {
2016
+ if (node.type !== "TSTypeReference" || node.typeArguments?.params.length) return false;
2017
+ const name = typeReferenceName$1(node);
2018
+ return name !== null && visibleTypeAlias(name, node, environment.typeAliases) !== null && !isInsideTypeAliasDeclaration(node);
2019
+ }
2020
+ function isInsideTypeParameterConstraint(node) {
2021
+ let child = node;
2022
+ let parent = child.parent;
2023
+ while (parent !== null && parent.type !== "Program") {
2024
+ if (parent.type === "TSTypeParameter" && parent.constraint === child) return true;
2025
+ child = parent;
2026
+ parent = child.parent;
2027
+ }
2028
+ return false;
2029
+ }
2030
+ function shouldReportType(node, environment) {
2031
+ if (isInsideTypeParameterConstraint(node)) return false;
2032
+ if (isPlainAliasConsumerUse(node, environment)) return false;
2033
+ if (classifyUnsafeDictionary(node, environment) === null) return false;
2034
+ let current = node.parent;
2035
+ while (current !== null && current.type !== "Program") {
2036
+ if (isTypeNode(current) && classifyUnsafeDictionary(current, environment) !== null) return false;
2037
+ current = current.parent;
2038
+ }
2039
+ return true;
2040
+ }
2041
+ /** Disallow object-dictionary contracts whose direct value type is an unsafe escape hatch. */
2042
+ const noUnsafeDictionaryTypeRule = Rule.define({
2043
+ name: "no-unsafe-dictionary-type",
2044
+ meta: {
2045
+ type: "problem",
2046
+ docs: { description: "Disallow object-dictionary contracts whose direct value type is unknown, any, object, {}, or a union/alias containing one of those escape hatches." },
2047
+ messages: { unsafeDictionary: "This dictionary's {{value}} value type gives callers no concrete value contract. Use an owner/schema-derived value type; parse external payloads before insertion." }
2048
+ },
2049
+ create: function* () {
2050
+ const context = yield* RuleContext;
2051
+ const environment = createTypeEnvironment(context.sourceCode.ast, context.sourceCode.visitorKeys);
2052
+ const report = Effect.fn("no-unsafe-dictionary-type.report")(function* (node, value) {
2053
+ yield* context.report({
2054
+ node,
2055
+ messageId: "unsafeDictionary",
2056
+ data: { value }
2057
+ });
2058
+ });
2059
+ const reportIfUnsafe = Effect.fn("no-unsafe-dictionary-type.reportIfUnsafe")(function* (node) {
2060
+ if (!shouldReportType(node, environment)) return;
2061
+ const unsafe = classifyUnsafeDictionary(node, environment);
2062
+ if (unsafe === null) return;
2063
+ yield* report(node, unsafe.unsafeValue);
2064
+ });
2065
+ return Visitor.merge(Visitor.on("TSTypeReference", reportIfUnsafe), Visitor.on("TSTypeLiteral", reportIfUnsafe), Visitor.on("TSMappedType", reportIfUnsafe), Visitor.on("TSIndexSignature", Effect.fn("no-unsafe-dictionary-type.TSIndexSignature")(function* (node) {
2066
+ if (node.typeAnnotation === null || node.parent.type === "TSTypeLiteral") return;
2067
+ const unsafe = classifyUnsafeDictionaryValue(node.typeAnnotation.typeAnnotation, environment);
2068
+ if (unsafe !== null) yield* report(node, unsafe.unsafeValue);
2069
+ })));
2070
+ }
2071
+ });
2072
+ const functionBoundaryTypes = /* @__PURE__ */ new Set([
2073
+ "ArrowFunctionExpression",
2074
+ "FunctionDeclaration",
2075
+ "FunctionExpression",
2076
+ "TSDeclareFunction",
2077
+ "TSEmptyBodyFunctionExpression"
2078
+ ]);
2079
+ function unwrapExpressionParentheses(expression) {
2080
+ let current = expression;
2081
+ while (current.type === "ParenthesizedExpression") current = current.expression;
2082
+ return current;
2083
+ }
2084
+ function unwrapTypeParentheses(type) {
2085
+ let current = type;
2086
+ while (current.type === "TSParenthesizedType") current = current.typeAnnotation;
2087
+ return current;
2088
+ }
2089
+ function typeReferenceName(type) {
2090
+ return type.typeName.type === "Identifier" ? type.typeName.name : null;
2091
+ }
2092
+ function isUnknownOrAnyType(type) {
2093
+ const unwrapped = unwrapTypeParentheses(type);
2094
+ return unwrapped.type === "TSUnknownKeyword" || unwrapped.type === "TSAnyKeyword";
2095
+ }
2096
+ function isBroadRecordKeyType(type) {
2097
+ const unwrapped = unwrapTypeParentheses(type);
2098
+ if (unwrapped.type === "TSStringKeyword" || unwrapped.type === "TSNumberKeyword" || unwrapped.type === "TSSymbolKeyword") return true;
2099
+ if (unwrapped.type === "TSUnionType") return unwrapped.types.every(isBroadRecordKeyType);
2100
+ return unwrapped.type === "TSTypeReference" && typeReferenceName(unwrapped) === "PropertyKey";
2101
+ }
2102
+ function isBroadRecordType(type) {
2103
+ const unwrapped = unwrapTypeParentheses(type);
2104
+ if (unwrapped.type === "TSTypeReference") {
2105
+ if (typeReferenceName(unwrapped) === "Readonly") {
2106
+ const [inner] = unwrapped.typeArguments?.params ?? [];
2107
+ return inner !== void 0 && isBroadRecordType(inner);
2108
+ }
2109
+ if (typeReferenceName(unwrapped) !== "Record") return false;
2110
+ const parameters = unwrapped.typeArguments?.params ?? [];
2111
+ return parameters.length === 2 && parameters[0] !== void 0 && parameters[1] !== void 0 && isBroadRecordKeyType(parameters[0]) && isUnknownOrAnyType(parameters[1]);
2112
+ }
2113
+ if (unwrapped.type !== "TSTypeLiteral" || unwrapped.members.length !== 1) return false;
2114
+ const [member] = unwrapped.members;
2115
+ const [parameter] = member?.type === "TSIndexSignature" ? member.parameters : [];
2116
+ return member?.type === "TSIndexSignature" && member.parameters.length === 1 && parameter !== void 0 && isBroadRecordKeyType(parameter.typeAnnotation.typeAnnotation) && isUnknownOrAnyType(member.typeAnnotation.typeAnnotation);
2117
+ }
2118
+ function broadTypeKind(type) {
2119
+ const unwrapped = unwrapTypeParentheses(type);
2120
+ if (unwrapped.type === "TSUnknownKeyword" || unwrapped.type === "TSAnyKeyword") return "top";
2121
+ if (unwrapped.type === "TSObjectKeyword") return "object";
2122
+ return isBroadRecordType(unwrapped) ? "record" : null;
2123
+ }
2124
+ function assertedExpression(node) {
2125
+ return unwrapExpressionParentheses(node.expression);
2126
+ }
2127
+ function assertionFromExpression(expression) {
2128
+ const unwrapped = unwrapExpressionParentheses(expression);
2129
+ return unwrapped.type === "TSAsExpression" || unwrapped.type === "TSTypeAssertion" ? unwrapped : null;
2130
+ }
2131
+ function normalizedTypeText(sourceText, type) {
2132
+ return sourceText.slice(type.start, type.end).replaceAll(/\s+/gu, "");
2133
+ }
2134
+ function typesHaveSameSyntax(sourceText, left, right) {
2135
+ return left !== null && normalizedTypeText(sourceText, unwrapTypeParentheses(left)) === normalizedTypeText(sourceText, unwrapTypeParentheses(right));
2136
+ }
2137
+ function isDefinitelyObjectType(type) {
2138
+ const unwrapped = unwrapTypeParentheses(type);
2139
+ switch (unwrapped.type) {
2140
+ case "TSArrayType":
2141
+ case "TSConstructorType":
2142
+ case "TSFunctionType":
2143
+ case "TSMappedType":
2144
+ case "TSObjectKeyword":
2145
+ case "TSTupleType": return true;
2146
+ case "TSTypeLiteral": return unwrapped.members.length > 0;
2147
+ case "TSIntersectionType": return unwrapped.types.every(isDefinitelyObjectType);
2148
+ case "TSTypeOperator": return unwrapped.operator === "readonly" && isDefinitelyObjectType(unwrapped.typeAnnotation);
2149
+ default: return false;
2150
+ }
2151
+ }
2152
+ function isDefinitelyNarrowerRecordType(type) {
2153
+ const unwrapped = unwrapTypeParentheses(type);
2154
+ if (unwrapped.type === "TSTypeLiteral") return unwrapped.members.some((member) => member.type !== "TSIndexSignature");
2155
+ if (unwrapped.type !== "TSTypeReference") return false;
2156
+ if (typeReferenceName(unwrapped) === "Readonly") {
2157
+ const [inner] = unwrapped.typeArguments?.params ?? [];
2158
+ return inner !== void 0 && isDefinitelyNarrowerRecordType(inner);
2159
+ }
2160
+ if (typeReferenceName(unwrapped) !== "Record") return false;
2161
+ const parameters = unwrapped.typeArguments?.params ?? [];
2162
+ return parameters.length === 2 && parameters[1] !== void 0 && !isUnknownOrAnyType(parameters[1]);
2163
+ }
2164
+ function functionBoundary(node) {
2165
+ let current = node.parent;
2166
+ while (current !== null && current.type !== "Program") {
2167
+ if (functionBoundaryTypes.has(current.type)) return current;
2168
+ current = current.parent;
2169
+ }
2170
+ return null;
2171
+ }
2172
+ function resolvedVariableForIdentifier(scopes, identifier) {
2173
+ for (const scope of scopes) {
2174
+ const reference = scope.references.find((candidate) => candidate.identifier.start === identifier.start && candidate.identifier.end === identifier.end);
2175
+ if (reference !== void 0) return reference.resolved;
2176
+ }
2177
+ return null;
2178
+ }
2179
+ function variableDeclarator(variable) {
2180
+ for (const definition of variable.defs) if (definition.type === "Variable" && definition.node.type === "VariableDeclarator") return definition.node;
2181
+ return null;
2182
+ }
2183
+ function knownValueEvidence(expression, scopes, boundary, visitedVariables) {
2184
+ const unwrapped = unwrapExpressionParentheses(expression);
2185
+ if (unwrapped.type === "TSAsExpression" || unwrapped.type === "TSTypeAssertion") {
2186
+ if (broadTypeKind(unwrapped.typeAnnotation) !== null) return null;
2187
+ return { type: unwrapped.typeAnnotation };
2188
+ }
2189
+ if (unwrapped.type === "Literal" || unwrapped.type === "TemplateLiteral") return { type: null };
2190
+ if (unwrapped.type === "ArrayExpression" || unwrapped.type === "ArrowFunctionExpression" || unwrapped.type === "ClassExpression" || unwrapped.type === "FunctionExpression" || unwrapped.type === "NewExpression" || unwrapped.type === "ObjectExpression") return { type: null };
2191
+ if (unwrapped.type !== "Identifier") return null;
2192
+ const variable = resolvedVariableForIdentifier(scopes, unwrapped);
2193
+ if (variable === null || visitedVariables.has(variable)) return null;
2194
+ const annotatedIdentifier = variable.identifiers.find((identifier) => identifier.typeAnnotation !== null && identifier.typeAnnotation !== void 0);
2195
+ const annotation = annotatedIdentifier?.typeAnnotation?.typeAnnotation;
2196
+ if (annotation !== void 0 && annotatedIdentifier !== void 0) {
2197
+ if (functionBoundary(annotatedIdentifier) !== boundary || broadTypeKind(annotation) !== null) return null;
2198
+ return { type: annotation };
2199
+ }
2200
+ const declarator = variableDeclarator(variable);
2201
+ if (declarator === null || declarator.parent.type !== "VariableDeclaration" || declarator.parent.kind !== "const" || declarator.init === null || variable.references.some((reference) => reference.isWrite() && !reference.init) || functionBoundary(declarator) !== boundary) return null;
2202
+ return knownValueEvidence(declarator.init, scopes, boundary, /* @__PURE__ */ new Set([...visitedVariables, variable]));
2203
+ }
2204
+ function widenedBinding(variable, scopes) {
2205
+ const declarator = variableDeclarator(variable);
2206
+ const declaredType = declarator === null ? void 0 : functionParameterTypeAnnotation(declarator.id)?.typeAnnotation;
2207
+ if (declarator === null || declarator.parent.type !== "VariableDeclaration" || declarator.parent.kind !== "const" || declarator.id.type !== "Identifier" || declarator.init === null || variable.references.some((reference) => reference.isWrite() && !reference.init)) return null;
2208
+ const boundary = functionBoundary(declarator);
2209
+ const initializerAssertion = assertionFromExpression(declarator.init);
2210
+ const initializerBroadKind = initializerAssertion === null ? null : broadTypeKind(initializerAssertion.typeAnnotation);
2211
+ const broadKind = (declaredType === void 0 ? null : broadTypeKind(declaredType)) ?? initializerBroadKind;
2212
+ if (broadKind === null) return null;
2213
+ const evidence = knownValueEvidence(initializerAssertion !== null && initializerBroadKind !== null ? assertedExpression(initializerAssertion) : declarator.init, scopes, boundary, /* @__PURE__ */ new Set([variable]));
2214
+ return evidence === null ? null : {
2215
+ broadKind,
2216
+ evidence,
2217
+ declaredAt: declarator.end,
2218
+ boundary
2219
+ };
2220
+ }
2221
+ function assertionIsNarrower(sourceText, broadKind, evidence, assertedType) {
2222
+ if (broadTypeKind(assertedType) !== null) return false;
2223
+ if (broadKind === "top") return true;
2224
+ if (typesHaveSameSyntax(sourceText, evidence.type, assertedType)) return true;
2225
+ if (broadKind === "object") return isDefinitelyObjectType(assertedType);
2226
+ return isDefinitelyNarrowerRecordType(assertedType);
2227
+ }
2228
+ /** Detect immutable local bindings that erase a known type and are later asserted back to a narrower type. */
2229
+ const noWidenThenAssertRule = Rule.define({
2230
+ name: "no-widen-then-assert",
2231
+ meta: {
2232
+ type: "problem",
2233
+ docs: { description: "Disallow local const flows that explicitly widen a known value before asserting the widened binding to a narrower type." },
2234
+ messages: { widenThenAssert: "Binding \"{{name}}\" discards type evidence and later recreates it with an assertion. Keep the precise type from initialization through use; parse boundary input once." }
2235
+ },
2236
+ create: function* () {
2237
+ const context = yield* RuleContext;
2238
+ const scopes = context.sourceCode.scopeManager.scopes;
2239
+ const checkAssertion = Effect.fn("no-widen-then-assert.checkAssertion")(function* (node) {
2240
+ const expression = assertedExpression(node);
2241
+ if (expression.type !== "Identifier") return;
2242
+ const variable = resolvedVariableForIdentifier(scopes, expression);
2243
+ if (variable === null) return;
2244
+ const widened = widenedBinding(variable, scopes);
2245
+ if (widened === null || node.start <= widened.declaredAt || functionBoundary(node) !== widened.boundary || !assertionIsNarrower(context.sourceCode.text, widened.broadKind, widened.evidence, node.typeAnnotation)) return;
2246
+ yield* context.report({
2247
+ node,
2248
+ messageId: "widenThenAssert",
2249
+ data: { name: expression.name }
2250
+ });
2251
+ });
2252
+ return Visitor.merge(Visitor.on("TSAsExpression", checkAssertion), Visitor.on("TSTypeAssertion", checkAssertion));
2253
+ }
2254
+ });
2255
+ const DEFAULT_SAFETY_MARKERS = ["SAFETY"];
2256
+ var SafetyCommentOptions = class extends Schema.Class("SafetyCommentOptions")({ markers: Schema.Array(Schema.String).pipe(Schema.withDecodingDefaultKey(Effect.succeed(DEFAULT_SAFETY_MARKERS))) }) {};
2257
+ const commentOwnerKinds = /* @__PURE__ */ new Set([
2258
+ "ExpressionStatement",
2259
+ "PropertyDefinition",
2260
+ "ReturnStatement",
2261
+ "ThrowStatement",
2262
+ "VariableDeclaration"
2263
+ ]);
2264
+ function isConstAssertion(node) {
2265
+ return node.typeAnnotation.type === "TSTypeReference" && node.typeAnnotation.typeName.type === "Identifier" && node.typeAnnotation.typeName.name === "const";
2266
+ }
2267
+ function markerPattern(markers) {
2268
+ const alternation = Arr.join(Arr.map(markers, Str.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`)), "|");
2269
+ return new RegExp(String.raw`(?:^|[^\p{L}\p{N}_])(?:${alternation})\s*:\s*\S`, "u");
2270
+ }
2271
+ function hasSafetyJustificationBefore(sourceCode, owner, assertion, pattern) {
2272
+ return sourceCode.getCommentsBefore(owner).some((comment) => comment.end <= assertion.start && pattern.test(comment.value));
2273
+ }
2274
+ function hasSafetyComment(sourceCode, node, pattern) {
2275
+ let current = node;
2276
+ while (true) {
2277
+ if (hasSafetyJustificationBefore(sourceCode, current, node, pattern)) return true;
2278
+ if (commentOwnerKinds.has(current.type)) {
2279
+ const exportDeclaration = current.parent;
2280
+ return exportDeclaration.type === "ExportNamedDeclaration" && exportDeclaration.declaration === current && hasSafetyJustificationBefore(sourceCode, exportDeclaration, node, pattern);
2281
+ }
2282
+ if (current.parent.type === "Program") return false;
2283
+ current = current.parent;
2284
+ }
2285
+ }
2286
+ /** Require every non-const type assertion to state the invariant TypeScript cannot express. */
2287
+ const requireSafetyCommentForTypeAssertionRule = Rule.define({
2288
+ name: "require-safety-comment-for-type-assertion",
2289
+ options: SafetyCommentOptions.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
2290
+ meta: {
2291
+ type: "problem",
2292
+ docs: { description: "Require a nearby SAFETY comment for every TypeScript type assertion except const assertions." },
2293
+ messages: { missingSafetyComment: "This type assertion has no `{{marker}}:` justification. State the checked invariant immediately before the assertion or its containing statement." },
2294
+ schema: [{
2295
+ type: "object",
2296
+ properties: { markers: {
2297
+ type: "array",
2298
+ items: {
2299
+ type: "string",
2300
+ minLength: 1
2301
+ },
2302
+ minItems: 1,
2303
+ uniqueItems: true
2304
+ } },
2305
+ additionalProperties: false
2306
+ }],
2307
+ defaultOptions: [{ markers: ["SAFETY"] }]
2308
+ },
2309
+ create: function* (options) {
2310
+ const context = yield* RuleContext;
2311
+ const markers = Arr.match(Arr.filter(Arr.map(options.markers, Str.trim), Str.isNonEmpty), {
2312
+ onEmpty: () => DEFAULT_SAFETY_MARKERS,
2313
+ onNonEmpty: (values) => values
2314
+ });
2315
+ const pattern = markerPattern(markers);
2316
+ const checkAssertion = Effect.fn("require-safety-comment-for-type-assertion.checkAssertion")(function* (node) {
2317
+ if (isConstAssertion(node)) return;
2318
+ if (hasSafetyComment(context.sourceCode, node, pattern)) return;
2319
+ yield* context.report({
2320
+ node,
2321
+ messageId: "missingSafetyComment",
2322
+ data: { marker: markers[0] }
2323
+ });
2324
+ });
2325
+ return Visitor.merge(Visitor.on("TSAsExpression", checkAssertion), Visitor.on("TSTypeAssertion", checkAssertion));
2326
+ }
2327
+ });
2328
+ /**
2329
+ * Navigation primitives whose `Effect` has no error
2330
+ * channel — `Effect.ignore` is a no-op on these.
2331
+ */
2332
+ const INFALLIBLE_FN_NAMES = HashSet.make("pushUrl", "load", "loadExternalUrl", "back", "forward");
2333
+ const isEffectIgnoreMember = (node) => node.type === "MemberExpression" && AST.isMember(node, "Effect", "ignore");
2334
+ const isEffectAsCall = (node) => node.type === "CallExpression" && AST.isCallOf(node, "Effect", "as");
2335
+ /**
2336
+ * Walk a chain of `<expr>.pipe(...)` calls to the leaf callee identifier
2337
+ * (e.g. `pushUrl` in `pushUrl(...).pipe(...)`).
2338
+ */
2339
+ const leafCalleeName = (node) => {
2340
+ if (node.type === "CallExpression") {
2341
+ if (node.callee.type === "Identifier") return Option.some(node.callee.name);
2342
+ if (node.callee.type === "MemberExpression") return leafCalleeName(node.callee.object);
2343
+ return Option.none();
2344
+ }
2345
+ if (node.type === "MemberExpression") return leafCalleeName(node.object);
2346
+ return Option.none();
2347
+ };
2348
+ const pipeReceiverObject = (call) => call.callee.type === "MemberExpression" && call.callee.property.type === "Identifier" && call.callee.property.name === "pipe" ? Option.some(call.callee.object) : Option.none();
2349
+ const adjacencyFindings = (args) => pipe$1(Arr.range(0, Math.max(args.length - 2, -1)), Arr.filterMap((i) => {
2350
+ const a = args[i];
2351
+ const b = args[i + 1];
2352
+ if (a === void 0 || b === void 0) return Result.failVoid;
2353
+ if (a.type === "SpreadElement" || b.type === "SpreadElement") return Result.failVoid;
2354
+ return isEffectIgnoreMember(a) && isEffectAsCall(b) ? Result.succeed({
2355
+ node: a,
2356
+ message: "`Effect.ignore` immediately before `Effect.as(...)` is redundant. `Effect.as` already discards the success value; the `ignore` only hides errors. Either drop `Effect.ignore` (if the Effect is infallible) or catch errors explicitly. (EF)"
2357
+ }) : Result.failVoid;
2358
+ }));
2359
+ const infallibleFindings = (args, leaf) => pipe$1(args, Arr.filterMap((arg) => arg.type !== "SpreadElement" && isEffectIgnoreMember(arg) ? Result.succeed({
2360
+ node: arg,
2361
+ message: `\`Effect.ignore\` on \`${leaf}(...)\` is a no-op — the Effect is infallible (\`Effect.Effect<void>\`). Drop the \`Effect.ignore\` step. (EF)`
2362
+ }) : Result.failVoid));
2363
+ const rule$27 = Rule.define({
2364
+ name: "no-effect-ignore-then-as",
2365
+ meta: Rule.meta({
2366
+ type: "suggestion",
2367
+ description: "Disallow `Effect.ignore` followed by `Effect.as` and `Effect.ignore` on infallible primitives (EF)"
2368
+ }),
2369
+ create: function* () {
2370
+ const ctx = yield* RuleContext;
2371
+ return Visitor.on("CallExpression", (node) => pipe$1(pipeReceiverObject(node), Option.match({
2372
+ onNone: () => Effect.void,
2373
+ onSome: (receiver) => {
2374
+ const adjacency = adjacencyFindings(node.arguments);
2375
+ const infallible = pipe$1(leafCalleeName(receiver), Option.filter((name) => HashSet.has(INFALLIBLE_FN_NAMES, name)), Option.match({
2376
+ onNone: () => Arr.empty(),
2377
+ onSome: (leaf) => infallibleFindings(node.arguments, leaf)
2378
+ }));
2379
+ return Effect.forEach(Arr.appendAll(adjacency, infallible), (f) => ctx.report(Diagnostic.make({
2380
+ node: f.node,
2381
+ message: f.message
2382
+ })), {
2383
+ concurrency: 1,
2384
+ discard: true
2385
+ });
2386
+ }
2387
+ })));
2388
+ }
2389
+ });
2390
+ const SUSPECT_OPS = HashSet.make("===", "!==", "==", "!=", ">", "<", ">=", "<=");
2391
+ const isLengthAccess$1 = (n) => n.type === "MemberExpression" && n.property.type === "Identifier" && n.property.name === "length";
2392
+ const isZero$1 = (n) => n.type === "Literal" && n.value === 0;
2393
+ const lengthAgainstZero = (bin) => {
2394
+ const leftLen = isLengthAccess$1(bin.left);
2395
+ const rightLen = isLengthAccess$1(bin.right);
2396
+ const leftZero = isZero$1(bin.left);
2397
+ const rightZero = isZero$1(bin.right);
2398
+ return leftLen && rightZero || leftZero && rightLen;
2399
+ };
2400
+ const rule$26 = Rule.define({
2401
+ name: "no-length-comparison",
2402
+ meta: Rule.meta({
2403
+ type: "suggestion",
2404
+ description: "Disallow `.length === 0` / `.length > 0` — use `Arr.isReadonlyArrayEmpty`, `Arr.isReadonlyArrayNonEmpty`, `Str.isEmpty`, `Str.isNonEmpty`, or `Arr.match` (EF)"
2405
+ }),
2406
+ create: function* () {
2407
+ const ctx = yield* RuleContext;
2408
+ return Visitor.on("BinaryExpression", (node) => Bool.match(HashSet.has(SUSPECT_OPS, node.operator) && lengthAgainstZero(node), {
2409
+ onFalse: () => Effect.void,
2410
+ onTrue: () => ctx.report(Diagnostic.make({
2411
+ node,
2412
+ message: "Avoid `.length` comparisons against `0`. Use `Arr.isReadonlyArrayEmpty(xs)` / `Arr.isReadonlyArrayNonEmpty(xs)` for arrays, `Str.isEmpty(s)` / `Str.isNonEmpty(s)` for strings, or `Arr.match({ onEmpty, onNonEmpty })` for branching. (EF)"
2413
+ }))
2414
+ }));
2415
+ }
2416
+ });
2417
+ /** Check if a MemberExpression is `Schema.Opaque` (or similar namespace.Opaque). */
2418
+ const isMemberExprForOpaque = (node, schemaIdentifiers) => node.object.type === "Identifier" && schemaIdentifiers.has(node.object.name) && node.property.type === "Identifier" && node.property.name === "Opaque";
2419
+ /** Check a class node for opaque violations. */
2420
+ const checkClass = (node, schemaIdentifiers, opaqueIdentifiers, ctx) => {
2421
+ if (!node.superClass) return Effect.void;
2422
+ const superClass = node.superClass;
2423
+ if (superClass.type !== "CallExpression") return Effect.void;
2424
+ if (superClass.callee.type !== "CallExpression") return Effect.void;
2425
+ const innerCallee = superClass.callee.callee;
2426
+ if (!(innerCallee.type === "MemberExpression" && isMemberExprForOpaque(innerCallee, schemaIdentifiers) || innerCallee.type === "Identifier" && opaqueIdentifiers.has(innerCallee.name))) return Effect.void;
2427
+ const reports = [];
2428
+ for (const member of node.body.body) if (member.type === "MethodDefinition" || member.type === "PropertyDefinition") {
2429
+ if (member.static) continue;
2430
+ const keyName = member.key.type === "Identifier" ? member.key.name : void 0;
2431
+ reports.push(ctx.report(Diagnostic.make({
2432
+ node: member,
2433
+ message: `\`Schema.Opaque\` classes should be pure opaque wrappers — do not add instance ${member.type === "MethodDefinition" ? "methods" : "properties"}${keyName ? ` (\`${keyName}\`)` : ""}. Use static methods or external functions instead.`
2434
+ })));
2435
+ }
2436
+ if (reports.length === 0) return Effect.void;
2437
+ return Effect.all(reports, { discard: true });
2438
+ };
2439
+ const rule$25 = Rule.define({
2440
+ name: "no-opaque-instance-fields",
2441
+ meta: Rule.meta({
2442
+ type: "problem",
2443
+ description: "Disallow instance members on Schema.Opaque classes — they should be pure opaque wrappers"
2444
+ }),
2445
+ create: function* () {
2446
+ const ctx = yield* RuleContext;
2447
+ const schemaIdsRef = yield* Ref.make(/* @__PURE__ */ new Set());
2448
+ const opaqueIdsRef = yield* Ref.make(/* @__PURE__ */ new Set());
2449
+ return Visitor.merge(Visitor.on("ImportDeclaration", (node) => Effect.gen(function* () {
2450
+ const importNode = node;
2451
+ const src = importNode.source.value;
2452
+ if (src !== "effect" && src !== "effect/Schema") return;
2453
+ for (const specifier of importNode.specifiers) {
2454
+ if (specifier.type === "ImportNamespaceSpecifier") {
2455
+ if (src === "effect/Schema" || src === "effect") yield* Ref.update(schemaIdsRef, (s) => /* @__PURE__ */ new Set([...s, specifier.local.name]));
2456
+ }
2457
+ if (specifier.type === "ImportSpecifier") {
2458
+ const imported = specifier.imported;
2459
+ if (imported.type === "Identifier") {
2460
+ if (imported.name === "Schema") yield* Ref.update(schemaIdsRef, (s) => /* @__PURE__ */ new Set([...s, specifier.local.name]));
2461
+ if (imported.name === "Opaque") yield* Ref.update(opaqueIdsRef, (s) => /* @__PURE__ */ new Set([...s, specifier.local.name]));
2462
+ }
2463
+ }
2464
+ }
2465
+ })), Visitor.on("ClassDeclaration", (node) => Effect.gen(function* () {
2466
+ yield* checkClass(node, yield* Ref.get(schemaIdsRef), yield* Ref.get(opaqueIdsRef), ctx);
2467
+ })), Visitor.on("ClassExpression", (node) => Effect.gen(function* () {
2468
+ yield* checkClass(node, yield* Ref.get(schemaIdsRef), yield* Ref.get(opaqueIdsRef), ctx);
2469
+ })));
2470
+ }
2471
+ });
2472
+ const isLengthAccess = (n) => n.type === "MemberExpression" && n.property.type === "Identifier" && n.property.name === "length";
2473
+ const isZero = (n) => n.type === "Literal" && n.value === 0;
2474
+ const isOne = (n) => n.type === "Literal" && n.value === 1;
2475
+ const rule$24 = Rule.define({
2476
+ name: "prefer-arr-match",
2477
+ meta: Rule.meta({
2478
+ type: "suggestion",
2479
+ description: "Prefer Arr.match for empty/non-empty array branching (EF-7)"
2480
+ }),
2481
+ create: function* () {
2482
+ const ctx = yield* RuleContext;
2483
+ return { BinaryExpression: (node) => {
2484
+ const { left, right, operator } = node;
2485
+ if (isLengthAccess(left) && isZero(right) && (operator === "===" || operator === "!==" || operator === ">" || operator === "==" || operator === "!=") || isZero(left) && isLengthAccess(right) && (operator === "===" || operator === "!==" || operator === "<" || operator === "==" || operator === "!=") || isLengthAccess(left) && isOne(right) && (operator === ">=" || operator === "<") || isOne(left) && isLengthAccess(right) && (operator === "<=" || operator === ">")) return ctx.report(Diagnostic.make({
2486
+ node,
2487
+ message: "Use `Arr.match(array, { onEmpty: () => ..., onNonEmpty: (values) => ... })` instead of manual length checks for empty/non-empty branching. (EF-7)"
2488
+ }));
2489
+ return Effect.void;
2490
+ } };
2491
+ }
2492
+ });
2493
+ const rule$23 = Rule.define({
2494
+ name: "prefer-arr-sort",
2495
+ meta: Rule.meta({
2496
+ type: "suggestion",
2497
+ description: "Disallow native .sort() — use Arr.sort with explicit Order instead"
2498
+ }),
2499
+ create: function* () {
2500
+ const ctx = yield* RuleContext;
2501
+ return { CallExpression: (node) => {
2502
+ const call = node;
2503
+ if (call.callee.type !== "MemberExpression" || call.callee.property.type !== "Identifier" || call.callee.property.name !== "sort") return Effect.void;
2504
+ if (call.callee.object.type === "Identifier" && call.callee.object.name === "Arr") return Effect.void;
2505
+ return ctx.report(Diagnostic.make({
2506
+ node,
2507
+ message: "Avoid native `.sort()`. Use `Arr.sort(items, order)` from `effect/Array` with an explicit `Order` for predictable, immutable sorting. (EF-38)"
2508
+ }));
2509
+ } };
2510
+ }
2511
+ });
2512
+ const isEmptyArrayExpr = (node) => node.type === "ArrayExpression" && node.elements.length === 0;
2513
+ const isSingletonArrayExpr = (node) => node.type === "ArrayExpression" && node.elements.length === 1 && node.elements[0] !== null;
2514
+ const returnedExpression = (arrow) => {
2515
+ if (arrow.body.type !== "BlockStatement") return Option.some(arrow.body);
2516
+ return pipe$1(arrow.body.body, Arr.findFirst((stmt) => stmt.type === "ReturnStatement" ? Option.some(stmt) : Option.none()), Option.flatMap((ret) => ret.argument === null ? Option.none() : Option.some(ret.argument)));
2517
+ };
2518
+ const arrowReturnsEmptyArray = (arrow) => pipe$1(returnedExpression(arrow), Option.map(isEmptyArrayExpr), Option.getOrElse(() => false));
2519
+ const arrowReturnsSingletonArray = (arrow) => pipe$1(returnedExpression(arrow), Option.map(isSingletonArrayExpr), Option.getOrElse(() => false));
2520
+ const propertyKeyMatches = (prop, name) => {
2521
+ if (prop.key.type === "Identifier") return prop.key.name === name;
2522
+ if (prop.key.type === "Literal" && P.isString(prop.key.value)) return prop.key.value === name;
2523
+ return false;
2524
+ };
2525
+ const namedProperty = (obj, name) => pipe$1(obj.properties, Arr.findFirst((p) => p.type === "Property" && propertyKeyMatches(p, name) ? Option.some(p) : Option.none()));
2526
+ const propertyArrow = (prop) => prop.value.type === "ArrowFunctionExpression" ? Option.some(prop.value) : Option.none();
2527
+ const looksLikeFromOption = (branches) => pipe$1(Option.all({
2528
+ onNone: pipe$1(namedProperty(branches, "onNone"), Option.flatMap(propertyArrow)),
2529
+ onSome: pipe$1(namedProperty(branches, "onSome"), Option.flatMap(propertyArrow))
2530
+ }), Option.map(({ onNone, onSome }) => arrowReturnsEmptyArray(onNone) && arrowReturnsSingletonArray(onSome)), Option.getOrElse(() => false));
2531
+ const matchBranchesFromDirectCall = (call) => {
2532
+ if (!AST.isCallOf(call, "Option", "match")) return Option.none();
2533
+ const arg = call.arguments[1];
2534
+ return arg !== void 0 && arg.type === "ObjectExpression" ? Option.some(arg) : Option.none();
2535
+ };
2536
+ const matchCallBranches = (call) => {
2537
+ if (!AST.isCallOf(call, "Option", "match")) return Option.none();
2538
+ const branches = call.arguments[0];
2539
+ return branches !== void 0 && branches.type === "ObjectExpression" ? Option.some(branches) : Option.none();
2540
+ };
2541
+ const matchBranchesFromPipedCall = (call) => {
2542
+ if (call.callee.type !== "Identifier" || call.callee.name !== "pipe") return Option.none();
2543
+ return pipe$1(call.arguments, Arr.findFirst((arg) => arg.type === "CallExpression" ? Option.some(arg) : Option.none()), Option.flatMap(matchCallBranches));
2544
+ };
2545
+ const matchBranches = (call) => pipe$1(matchBranchesFromDirectCall(call), Option.orElse(() => matchBranchesFromPipedCall(call)));
2546
+ const rule$22 = Rule.define({
2547
+ name: "prefer-array-fromoption-over-option-match-empty",
2548
+ meta: Rule.meta({
2549
+ type: "suggestion",
2550
+ description: "Use `Array.fromOption(maybeX)` instead of `Option.match` returning `[]` vs `[x]` (EF)"
2551
+ }),
2552
+ create: function* () {
2553
+ const ctx = yield* RuleContext;
2554
+ return Visitor.on("CallExpression", (node) => pipe$1(matchBranches(node), Option.filter(looksLikeFromOption), Option.match({
2555
+ onNone: () => Effect.void,
2556
+ onSome: () => ctx.report(Diagnostic.make({
2557
+ node,
2558
+ message: "Use `Array.fromOption(maybeValue)` instead of `Option.match({ onNone: () => [], onSome: (v) => [v] })`. (EF)"
2559
+ }))
2560
+ })));
2561
+ }
2562
+ });
2563
+ const EffectDurationApi = Schema.Literals([
2564
+ "timeout",
2565
+ "timeoutOption",
2566
+ "timeoutOrElse",
2567
+ "sleep",
2568
+ "delay"
2569
+ ]).annotate({
2570
+ title: "EffectDurationApi",
2571
+ description: "`Effect.*` helpers that accept a Duration or a numeric milliseconds value."
2572
+ });
2573
+ const ScheduleDurationApi = Schema.Literals([
2574
+ "spaced",
2575
+ "fixed",
2576
+ "windowed",
2577
+ "duration"
2578
+ ]).annotate({
2579
+ title: "ScheduleDurationApi",
2580
+ description: "`Schedule.*` constructors that accept a Duration or a numeric milliseconds value. Schedule-combining APIs are intentionally excluded."
2581
+ });
2582
+ const isEffectDurationApi = Schema.is(EffectDurationApi);
2583
+ const isScheduleDurationApi = Schema.is(ScheduleDurationApi);
2584
+ /**
2585
+ * If the call's callee is a recognised duration API, return the qualified
2586
+ * name so it can appear in diagnostics.
2587
+ */
2588
+ const matchDurationCall = (call) => pipe(AST.narrow(call.callee, "MemberExpression"), Option.flatMap(AST.memberNames), Option.flatMap(([obj, prop]) => {
2589
+ if (obj === "Effect" && isEffectDurationApi(prop)) return Option.some(`Effect.${prop}`);
2590
+ if (obj === "Schedule" && isScheduleDurationApi(prop)) return Option.some(`Schedule.${prop}`);
2591
+ return Option.none();
2592
+ }));
2593
+ /** Type predicate distinguishing `NumericLiteral` from the other Literal
2594
+ * subtypes (Boolean / Null / String / BigInt / RegExp), which all share
2595
+ * `type: 'Literal'` but carry different `.value` runtime types. */
2596
+ const isNumericLiteral = (node) => node.type === "Literal" && P.isNumber(node.value);
2597
+ /** A `Literal` whose `.value` is a number, lifted into `Option`. */
2598
+ const asNumericLiteral = (node) => isNumericLiteral(node) ? Option.some(node) : Option.none();
2599
+ /**
2600
+ * An argument may contribute one flagged numeric literal:
2601
+ * - direct positional number → the argument itself
2602
+ * - options object with `duration: <number>` → the inner literal
2603
+ */
2604
+ const flaggedLiteralIn = (arg) => pipe(asNumericLiteral(arg), Option.orElse(() => pipe(AST.narrow(arg, "ObjectExpression"), Option.flatMap(AST.objectGetValue("duration")), Option.flatMap(asNumericLiteral))));
2605
+ const messageFor$1 = (apiName, value) => `Use \`Duration.millis(${value})\` or \`Duration.seconds(...)\` instead of a raw numeric literal in \`${apiName}\`. Duration constructors are self-documenting and prevent unit confusion. (EF-16)`;
2606
+ const rule$21 = Rule.define({
2607
+ name: "prefer-duration-constructors",
2608
+ meta: Rule.meta({
2609
+ type: "suggestion",
2610
+ description: "Prefer Duration constructors over raw numeric literals for time values in Effect/Schedule APIs, including the `duration` key inside options-object arguments. (EF-16)"
2611
+ }),
2612
+ create: function* () {
2613
+ const ctx = yield* RuleContext;
2614
+ return Visitor.on("CallExpression", (node) => pipe(matchDurationCall(node), Option.match({
2615
+ onNone: () => Effect.void,
2616
+ onSome: (apiName) => Effect.forEach(pipe(node.arguments, Arr.filterMap((arg) => Result.fromOption(flaggedLiteralIn(arg), () => void 0))), (lit) => ctx.report(Diagnostic.make({
2617
+ node: lit,
2618
+ message: messageFor$1(apiName, lit.value)
2619
+ })), {
2620
+ concurrency: 1,
2621
+ discard: true
2622
+ })
2623
+ })));
2624
+ }
2625
+ });
2626
+ const LayerFactoryName$1 = Schema.Literals([
2627
+ "effect",
2628
+ "scoped",
2629
+ "succeed"
2630
+ ]).annotate({
2631
+ title: "LayerFactoryName",
2632
+ description: "Service-building `Layer.effect` / `Layer.succeed` factories and legacy `Layer.scoped` calls."
2633
+ });
2634
+ const isLayerFactoryName$1 = Schema.is(LayerFactoryName$1);
2635
+ const EffectFnLikeName = Schema.Literals(["fn", "fnUntraced"]).annotate({
2636
+ title: "EffectFnLikeName",
2637
+ description: "`Effect.fn` and `Effect.fnUntraced` wrappers; `Effect.gen` inside them is exempt. Only named `Effect.fn` adds a span."
2638
+ });
2639
+ const isEffectFnLikeName = Schema.is(EffectFnLikeName);
2640
+ const FlaggedAssignmentParentType = Schema.Literals(["VariableDeclarator", "ExportDefaultDeclaration"]).annotate({
2641
+ title: "FlaggedAssignmentParentType",
2642
+ description: "Parent shapes of a top-level `Effect.gen(...)` worth flagging — the function effectively gets a name through the binding."
2643
+ });
2644
+ const isFlaggedAssignmentParentType = Schema.is(FlaggedAssignmentParentType);
2645
+ /** `Layer.effect(...)` / `Layer.scoped(...)` / `Layer.succeed(...)`. */
2646
+ const isLayerFactoryCall = (node) => pipe(AST.narrow(node.callee, "MemberExpression"), Option.flatMap(AST.memberNames), Option.exists(([obj, prop]) => obj === "Layer" && isLayerFactoryName$1(prop)));
2647
+ /**
2648
+ * `Context.Service<...>()(...)` — the second call of the canonical
2649
+ * double-call service definition pattern.
2650
+ */
2651
+ const isContextServiceDoubleCall = (node) => pipe(AST.narrow(node.callee, "CallExpression"), Option.flatMap((inner) => AST.narrow(inner.callee, "MemberExpression")), Option.exists(AST.isMember("Context", "Service")));
2652
+ /** `Effect.gen(...)`. */
2653
+ const isEffectGenCall = (node) => AST.isCallOf(node, "Effect", "gen");
2654
+ /** `Effect.fn(...)` or `Effect.fnUntraced(...)`. */
2655
+ const isEffectFnLikeCall = (node) => pipe(AST.narrow(node.callee, "MemberExpression"), Option.flatMap(AST.memberNames), Option.exists(([obj, prop]) => obj === "Effect" && isEffectFnLikeName(prop)));
2656
+ /**
2657
+ * Oxlint's ESTree types carry `parent: Node | null` on every node, so a
2658
+ * direct lift via `Option.fromNullishOr` is all we need.
2659
+ */
2660
+ const parentNode = (node) => Option.fromNullishOr(node.parent);
2661
+ const parentOfType$1 = (node, type) => pipe(parentNode(node), Option.flatMap(AST.narrow(type)));
2662
+ /**
2663
+ * The `Effect.gen` IS the direct factory body of a `Layer.*` call —
2664
+ * i.e., its immediate parent is `Layer.effect|scoped|succeed`. The gen
2665
+ * at this position is the service constructor, not a method, and must
2666
+ * not be flagged.
2667
+ */
2668
+ const isLayerFactoryBody = (node) => pipe(parentOfType$1(node, "CallExpression"), Option.exists(isLayerFactoryCall));
2669
+ /**
2670
+ * The `Effect.gen` IS the value of `make:` inside a
2671
+ * `Context.Service<...>()(<key>, { make: ... })` definition. Path:
2672
+ * gen → Property(make) → ObjectExpression → Context.Service double-call.
2673
+ */
2674
+ const isContextServiceMakeBody = (node) => pipe(parentOfType$1(node, "Property"), Option.filter((prop) => prop.key.type === "Identifier" && prop.key.name === "make"), Option.flatMap((prop) => parentOfType$1(prop, "ObjectExpression")), Option.flatMap((obj) => parentOfType$1(obj, "CallExpression")), Option.exists(isContextServiceDoubleCall));
2675
+ /** Either flavour of factory-body position — exempt from the rule. */
2676
+ const isServiceFactoryBody = (node) => isLayerFactoryBody(node) || isContextServiceMakeBody(node);
2677
+ /**
2678
+ * `const x = Effect.gen(...)` or `export default Effect.gen(...)` — a
2679
+ * named, reused effect whose call site deserves a span.
2680
+ */
2681
+ const isFlaggedTopLevelAssignment = (node) => pipe(parentNode(node), Option.exists((p) => isFlaggedAssignmentParentType(p.type)));
2682
+ const SERVICE_MESSAGE = "Use `Effect.fn(\"ServiceName.methodName\")(function* (...) { ... })` instead of `Effect.gen` for service methods. `Effect.fn` provides automatic tracing with named spans. (EF-14)";
2683
+ const TOP_LEVEL_MESSAGE = "Use `Effect.fn(\"functionName\")(function* (...) { ... })` instead of assigning `Effect.gen(...)` to a variable. `Effect.fn` provides automatic tracing with named spans. (EF-14)";
2684
+ const rule$20 = Rule.define({
2685
+ name: "prefer-effect-fn",
2686
+ meta: Rule.meta({
2687
+ type: "suggestion",
2688
+ description: "Flag `Effect.gen(...)` inside service-defining factories (`Layer.effect|scoped|succeed` or `Context.Service<...>()(..., { make })`), the factory-body `Effect.gen` itself exempted, and top-level named-binding assignments. `Effect.gen` inside `Effect.fn` / `Effect.fnUntraced` is exempt. (EF-14)"
2689
+ }),
2690
+ create: function* () {
2691
+ const ctx = yield* RuleContext;
2692
+ const layerFactoryDepth = yield* Ref.make(0);
2693
+ const serviceDefDepth = yield* Ref.make(0);
2694
+ const effectFnDepth = yield* Ref.make(0);
2695
+ return Visitor.merge(Visitor.tracked("CallExpression", isLayerFactoryCall, layerFactoryDepth), Visitor.tracked("CallExpression", isContextServiceDoubleCall, serviceDefDepth), Visitor.tracked("CallExpression", isEffectFnLikeCall, effectFnDepth), Visitor.on("CallExpression", (node) => Effect.gen(function* () {
2696
+ if (!isEffectGenCall(node)) return;
2697
+ if ((yield* Ref.get(effectFnDepth)) > 0) return;
2698
+ if (isServiceFactoryBody(node)) return;
2699
+ const layer = yield* Ref.get(layerFactoryDepth);
2700
+ const svcDef = yield* Ref.get(serviceDefDepth);
2701
+ if (layer > 0 || svcDef > 0) {
2702
+ yield* ctx.report(Diagnostic.make({
2703
+ node,
2704
+ message: SERVICE_MESSAGE
2705
+ }));
2706
+ return;
2707
+ }
2708
+ if (isFlaggedTopLevelAssignment(node)) yield* ctx.report(Diagnostic.make({
2709
+ node,
2710
+ message: TOP_LEVEL_MESSAGE
2711
+ }));
2712
+ })));
2713
+ }
2714
+ });
2715
+ const TYPEOF_MAP = {
2716
+ string: "P.isString",
2717
+ number: "P.isNumber",
2718
+ boolean: "P.isBoolean",
2719
+ function: "P.isFunction",
2720
+ bigint: "P.isBigInt",
2721
+ symbol: "P.isSymbol",
2722
+ undefined: "P.isUndefined",
2723
+ object: "P.isObject"
2724
+ };
2725
+ const rule$19 = Rule.define({
2726
+ name: "prefer-effect-is",
2727
+ meta: Rule.meta({
2728
+ type: "suggestion",
2729
+ description: "Prefer Effect Predicate helpers over typeof checks (EF-6)"
2730
+ }),
2731
+ create: function* () {
2732
+ const ctx = yield* RuleContext;
2733
+ return { BinaryExpression: (node) => {
2734
+ const bin = node;
2735
+ if (bin.operator !== "===" && bin.operator !== "!==") return Effect.void;
2736
+ let typeofArg;
2737
+ const { left, right } = bin;
2738
+ if (left.type === "UnaryExpression" && left.operator === "typeof" && right.type === "Literal" && typeof right.value === "string") typeofArg = right.value;
2739
+ else if (right.type === "UnaryExpression" && right.operator === "typeof" && left.type === "Literal" && typeof left.value === "string") typeofArg = left.value;
2740
+ if (!typeofArg) return Effect.void;
2741
+ const predicate = TYPEOF_MAP[typeofArg];
2742
+ if (!predicate) return Effect.void;
2743
+ return ctx.report(Diagnostic.make({
2744
+ node,
2745
+ message: `Use \`${predicate}(x)\` instead of \`typeof x ${bin.operator} "${typeofArg}"\`. Effect Predicate helpers are composable and type-safe. (EF-6)`
2746
+ }));
2747
+ } };
2748
+ }
2749
+ });
2750
+ const rule$18 = Rule.banStatement("SwitchStatement", { message: "Avoid `switch` statements in Effect code. Use `Match.value(...).pipe(Match.when(...), ..., Match.exhaustive)` for exhaustive, type-safe branching. (EF-7)" });
2751
+ /**
2752
+ * Canonical alias map: Effect submodule -> required namespace alias.
2753
+ * Only modules that have a non-obvious alias are listed here.
2754
+ */
2755
+ const CANONICAL_ALIASES = {
2756
+ Array: "Arr",
2757
+ Predicate: "P",
2758
+ Record: "R",
2759
+ String: "Str",
2760
+ Equal: "Eq",
2761
+ Boolean: "Bool"
2762
+ };
2763
+ /**
2764
+ * Effect submodules that MUST use namespace imports.
2765
+ */
2766
+ const NAMESPACE_MODULES = /* @__PURE__ */ new Set([
2767
+ "Array",
2768
+ "Option",
2769
+ "Predicate",
2770
+ "Record",
2771
+ "Schema",
2772
+ "String",
2773
+ "Equal",
2774
+ "Boolean"
2775
+ ]);
2776
+ const rule$17 = Rule.define({
2777
+ name: "prefer-namespace-imports",
2778
+ meta: Rule.meta({
2779
+ type: "suggestion",
2780
+ description: "Enforce canonical namespace imports for Effect submodules (EF-4)"
2781
+ }),
2782
+ create: function* () {
2783
+ const ctx = yield* RuleContext;
2784
+ return { ImportDeclaration: (node) => {
2785
+ const decl = node;
2786
+ const src = decl.source.value;
2787
+ if (src.startsWith("effect/")) {
2788
+ const submodule = src.slice(7);
2789
+ if (!NAMESPACE_MODULES.has(submodule)) return Effect.void;
2790
+ if (decl.specifiers.some((s) => s.type === "ImportSpecifier")) {
2791
+ const alias = CANONICAL_ALIASES[submodule];
2792
+ const suggestion = alias ? `import * as ${alias} from "${src}"` : `import * as ${submodule} from "${src}"`;
2793
+ return ctx.report(Diagnostic.make({
2794
+ node,
2795
+ message: `Use namespace imports for Effect helper modules: \`${suggestion}\`. This keeps module ownership explicit and follows the canonical alias convention. (EF-4)`
2796
+ }));
2797
+ }
2798
+ const nsSpecifier = decl.specifiers.find((s) => s.type === "ImportNamespaceSpecifier");
2799
+ if (nsSpecifier && CANONICAL_ALIASES[submodule]) {
2800
+ const expected = CANONICAL_ALIASES[submodule];
2801
+ const local = nsSpecifier.type === "ImportNamespaceSpecifier" ? nsSpecifier.local.name : "";
2802
+ if (local !== expected) return ctx.report(Diagnostic.make({
2803
+ node,
2804
+ message: `Use the canonical alias \`${expected}\` for \`${src}\` — got \`${local}\`. (EF-4)`
2805
+ }));
2806
+ }
2807
+ }
2808
+ if (src === "effect") for (const specifier of decl.specifiers) {
2809
+ if (specifier.type !== "ImportSpecifier") continue;
2810
+ const imported = specifier.imported;
2811
+ if (!imported || imported.type !== "Identifier") continue;
2812
+ if (specifier.importKind === "type") continue;
2813
+ const name = imported.name;
2814
+ if (NAMESPACE_MODULES.has(name)) {
2815
+ const alias = CANONICAL_ALIASES[name] ?? name;
2816
+ return ctx.report(Diagnostic.make({
2817
+ node,
2818
+ message: `Import \`${name}\` from its submodule: \`import * as ${alias} from "effect/${name}"\`. Use the canonical helper-module import. (EF-4)`
2819
+ }));
2820
+ }
2821
+ }
2822
+ return Effect.void;
2823
+ } };
2824
+ }
2825
+ });
2826
+ const rule$16 = Rule.define({
2827
+ name: "prefer-option-over-null",
2828
+ meta: Rule.meta({
2829
+ type: "suggestion",
2830
+ description: "Flag | null and | undefined in type unions — consider using Option<T> instead for explicit absence modeling (EF-2)"
2831
+ }),
2832
+ create: function* () {
2833
+ const ctx = yield* RuleContext;
2834
+ return { TSUnionType: (node) => {
2835
+ const union = node;
2836
+ const hasNull = union.types.some((t) => t.type === "TSNullKeyword");
2837
+ const hasUndefined = union.types.some((t) => t.type === "TSUndefinedKeyword");
2838
+ if (hasNull && hasUndefined) return ctx.report(Diagnostic.make({
2839
+ node,
2840
+ message: "Consider using `Option<T>` instead of `T | null | undefined` for explicit absence modeling. `Option` provides composable helpers (`map`, `flatMap`, `match`, `getOrElse`) and eliminates null-check bugs. (EF-2)"
2841
+ }));
2842
+ else if (hasNull) return ctx.report(Diagnostic.make({
2843
+ node,
2844
+ message: "Consider using `Option<T>` instead of `T | null` for explicit absence modeling. `Option` provides composable helpers (`map`, `flatMap`, `match`, `getOrElse`) and eliminates null-check bugs. (EF-2)"
2845
+ }));
2846
+ else if (hasUndefined) return ctx.report(Diagnostic.make({
2847
+ node,
2848
+ message: "Consider using `Option<T>` instead of `T | undefined` for explicit absence modeling. `Option` provides composable helpers (`map`, `flatMap`, `match`, `getOrElse`) and eliminates null-check bugs. (EF-2)"
2849
+ }));
2850
+ return Effect.void;
2851
+ } };
2852
+ }
2853
+ });
2854
+ const SecretKeyName = Schema.String.check(Schema.isPattern(/(?:api[_-]?key|auth[_-]?token|token|secret|password|passwd|private[_-]?key|client[_-]?secret|database[_-]?url|db[_-]?url|connection[_-]?string|dsn)/i, {
2855
+ identifier: "SecretKeyNameCheck",
2856
+ title: "Secret-Looking Key Name",
2857
+ description: "A configuration key whose name conventionally identifies a secret value (api key, auth token, password, private key, client secret, DSN, etc.).",
2858
+ message: "Key name matches a secret-value convention"
2859
+ })).pipe(Schema.brand("SecretKeyName"), Schema.annotate({
2860
+ title: "SecretKeyName",
2861
+ description: "Configuration key name that conventionally identifies a secret value. Such values must be loaded via `Config.Redacted` or wrapped in `Schema.Redacted` so they stay redacted from logs and `toString`."
2862
+ }));
2863
+ const isSecretKeyName = Schema.is(SecretKeyName);
2864
+ const ConfigPrimitiveApi = Schema.Literals([
2865
+ "String",
2866
+ "NonEmptyString",
2867
+ "string",
2868
+ "nonEmptyString"
2869
+ ]).annotate({
2870
+ title: "ConfigPrimitiveApi",
2871
+ description: "Current and legacy `Config.*` string loaders whose secret-looking key names should use redacted configuration."
2872
+ });
2873
+ const isConfigPrimitiveApi = Schema.is(ConfigPrimitiveApi);
2874
+ const PlainStringSchemaName = Schema.Literals(["String", "NonEmptyString"]).annotate({
2875
+ title: "PlainStringSchemaName",
2876
+ description: "`Schema.String` and `Schema.NonEmptyString` — the unredacted shapes that should be wrapped in `Schema.Redacted(...)` when modelling secret-looking fields inside `Config.schema(...)`."
2877
+ });
2878
+ const isPlainStringSchemaName = Schema.is(PlainStringSchemaName);
2879
+ /**
2880
+ * Extract the static name of an object property's key. Identifier keys and
2881
+ * string-literal keys both qualify; computed and other shapes do not.
2882
+ */
2883
+ const propertyKeyName = (prop) => {
2884
+ if (prop.computed) return Option.none();
2885
+ return pipe(AST.narrow(prop.key, "Identifier"), Option.map((idNode) => idNode.name), Option.orElse(() => pipe(AST.narrow(prop.key, "Literal"), Option.flatMap((lit) => P.isString(lit.value) ? Option.some(lit.value) : Option.none()))));
2886
+ };
2887
+ /**
2888
+ * Is the value a bare `Schema.String` / `Schema.NonEmptyString` member
2889
+ * access — i.e. not wrapped in `Schema.Redacted(...)` or piped through any
2890
+ * other helper? Anything more complex (call, pipe chain, identifier) is
2891
+ * left alone deliberately: this rule only flags the unambiguous shapes.
2892
+ */
2893
+ const isPlainStringSchemaMember = (node) => pipe(AST.narrow(node, "MemberExpression"), Option.flatMap(AST.memberNames), Option.exists(([obj, prop]) => obj === "Schema" && isPlainStringSchemaName(prop)));
2894
+ /**
2895
+ * Pull the `ObjectExpression` out of a `Config.schema(Schema.Struct({...}))`
2896
+ * shape. Returns `Option.none()` for any other arrangement (named schema
2897
+ * argument, non-Struct schema, computed args, etc.) so the rule only fires
2898
+ * on the literal-struct case it can statically analyse.
2899
+ */
2900
+ const matchConfigSchemaStruct = (call) => pipe(AST.matchCallOf(call, "Config", "schema"), Option.flatMap((c) => Option.fromNullishOr(c.arguments[0])), Option.flatMap(AST.narrow("CallExpression")), Option.filter((inner) => pipe(AST.narrow(inner.callee, "MemberExpression"), Option.exists(AST.isMember("Schema", "Struct")))), Option.flatMap((inner) => Option.fromNullishOr(inner.arguments[0])), Option.flatMap(AST.narrow("ObjectExpression")));
2901
+ /**
2902
+ * Detection 1: `Config.String("API_KEY")` / `Config.NonEmptyString("TOKEN")`
2903
+ * — primitive loaders called with a secret-shaped key literal.
2904
+ */
2905
+ const matchPrimitiveSecretCall = (call) => pipe(AST.narrow(call.callee, "MemberExpression"), Option.flatMap(AST.memberNames), Option.filter(([obj, prop]) => obj === "Config" && isConfigPrimitiveApi(prop)), Option.flatMap(([, apiName]) => pipe(Option.fromNullishOr(call.arguments[0]), Option.flatMap(AST.narrow("Literal")), Option.flatMap((lit) => P.isString(lit.value) && isSecretKeyName(lit.value) ? Option.some([apiName, lit.value]) : Option.none()))));
2906
+ /**
2907
+ * Detection 2: secret-shaped properties of a literal `Schema.Struct({...})`
2908
+ * argument to `Config.schema(...)`. Returns one `(property, key)` pair per
2909
+ * violating field so the diagnostic can land on the field itself.
2910
+ */
2911
+ const findSecretSchemaFields = (struct) => pipe(struct.properties, Arr.filterMap((p) => p.type !== "Property" ? Result.fail(void 0) : pipe(propertyKeyName(p), Option.filter(isSecretKeyName), Option.filter(() => isPlainStringSchemaMember(p.value)), Option.map((key) => [p, key]), Result.fromOption(() => void 0))));
2912
+ const primitiveMessageFor = (apiName, key) => {
2913
+ return `Configuration key \`${key}\` looks like a secret. Use \`${apiName === "NonEmptyString" || apiName === "nonEmptyString" ? `Config.schema(Schema.Redacted(Schema.NonEmptyString), "${key}")` : `Config.Redacted("${key}")`}\` instead of \`Config.${apiName}("${key}")\` so the loaded value stays redacted from logs and \`toString\`. (EF-29)`;
2914
+ };
2915
+ const schemaFieldMessageFor = (key) => `Field \`${key}\` inside \`Config.schema(...)\` looks like a secret. Wrap its inner schema in \`Schema.Redacted(...)\` (e.g. \`Schema.Redacted(Schema.String)\`) so the value stays redacted from logs and \`toString\`. (EF-29)`;
2916
+ const rule$15 = Rule.define({
2917
+ name: "prefer-redacted-config",
2918
+ meta: Rule.meta({
2919
+ type: "suggestion",
2920
+ description: "Flag secret-shaped configuration values that escape redaction: `Config.String(\"API_KEY\")` should use `Config.Redacted`, while `Config.NonEmptyString(\"TOKEN\")` needs `Config.schema(Schema.Redacted(Schema.NonEmptyString), \"TOKEN\")` to preserve validation. Fields inside `Config.schema(Schema.Struct({...}))` should be wrapped in `Schema.Redacted`."
2921
+ }),
2922
+ create: function* () {
2923
+ const ctx = yield* RuleContext;
2924
+ const reportPrimitive = (call, apiName, key) => ctx.report(Diagnostic.make({
2925
+ node: call,
2926
+ message: primitiveMessageFor(apiName, key)
2927
+ }));
2928
+ const reportSchemaField = (prop, key) => ctx.report(Diagnostic.make({
2929
+ node: prop,
2930
+ message: schemaFieldMessageFor(key)
2931
+ }));
2932
+ return Visitor.on("CallExpression", (node) => Effect.gen(function* () {
2933
+ yield* pipe(matchPrimitiveSecretCall(node), Option.match({
2934
+ onNone: () => Effect.void,
2935
+ onSome: ([apiName, key]) => reportPrimitive(node, apiName, key)
2936
+ }));
2937
+ yield* pipe(matchConfigSchemaStruct(node), Option.match({
2938
+ onNone: () => Effect.void,
2939
+ onSome: (struct) => Effect.forEach(findSecretSchemaFields(struct), ([prop, key]) => reportSchemaField(prop, key), {
2940
+ concurrency: 1,
2941
+ discard: true
2942
+ })
2943
+ }));
2944
+ }));
2945
+ }
2946
+ });
2947
+ const ConcurrencyApi = Schema.Literals([
2948
+ "forEach",
2949
+ "all",
2950
+ "validate"
2951
+ ]).annotate({
2952
+ title: "ConcurrencyApi",
2953
+ description: "`Effect.*` collection combinators where throughput/ordering intent should be visible at the call site via an explicit `concurrency` option."
2954
+ });
2955
+ const isConcurrencyApi = Schema.is(ConcurrencyApi);
2956
+ /** If the call's callee is `Effect.<concurrency-api>`, return the api name. */
2957
+ const matchConcurrencyCall = (call) => pipe(AST.narrow(call.callee, "MemberExpression"), Option.flatMap(AST.memberNames), Option.flatMap(([obj, prop]) => obj === "Effect" && isConcurrencyApi(prop) ? Option.some(`Effect.${prop}`) : Option.none()));
2958
+ /** Is this argument an options object that statically declares concurrency? */
2959
+ const carriesConcurrency = (arg) => pipe(AST.narrow(arg, "ObjectExpression"), Option.exists(AST.objectHasKey("concurrency")));
2960
+ const anyArgCarriesConcurrency = (call) => Arr.some(call.arguments, carriesConcurrency);
2961
+ const messageFor = (apiName) => `Specify \`concurrency\` explicitly on \`${apiName}\`. Even sequential execution is a concurrency decision — make throughput and ordering intent reviewable at the call site (e.g. \`{ concurrency: 1 }\`, \`{ concurrency: 'unbounded' }\`, or a numeric limit). (EF-27)`;
2962
+ const rule$14 = Rule.define({
2963
+ name: "require-effect-concurrency",
2964
+ meta: Rule.meta({
2965
+ type: "suggestion",
2966
+ description: "Require an explicit `concurrency` option on `Effect.forEach`, `Effect.all`, and `Effect.validate` so throughput intent is visible at the call site."
2967
+ }),
2968
+ create: function* () {
2969
+ const ctx = yield* RuleContext;
2970
+ return Visitor.on("CallExpression", (node) => pipe(matchConcurrencyCall(node), Option.filter(() => !anyArgCarriesConcurrency(node)), Option.match({
2971
+ onNone: () => Effect.void,
2972
+ onSome: (apiName) => ctx.report(Diagnostic.make({
2973
+ node,
2974
+ message: messageFor(apiName)
2975
+ }))
2976
+ })));
2977
+ }
2978
+ });
2979
+ const REQUIRED_KEYS = [
2980
+ "identifier",
2981
+ "title",
2982
+ "description"
2983
+ ];
2984
+ function checkOptionsObject(fnName, node, optionsArg) {
2985
+ if (optionsArg.type !== "ObjectExpression") return [];
2986
+ const presentKeys = /* @__PURE__ */ new Set();
2987
+ for (const propOrSpread of optionsArg.properties) {
2988
+ if (propOrSpread.type !== "Property") continue;
2989
+ const keyName = propOrSpread.key.type === "Identifier" ? propOrSpread.key.name : propOrSpread.key.type === "Literal" ? String(propOrSpread.key.value) : void 0;
2990
+ if (keyName) presentKeys.add(keyName);
2991
+ }
2992
+ return REQUIRED_KEYS.filter((k) => !presentKeys.has(k));
2993
+ }
2994
+ const rule$13 = Rule.define({
2995
+ name: "require-filter-metadata",
2996
+ meta: Rule.meta({
2997
+ type: "suggestion",
2998
+ description: "Schema.makeFilter/makeFilterGroup must include identifier, title, and description (EF-12c)"
2999
+ }),
3000
+ create: function* () {
3001
+ const ctx = yield* RuleContext;
3002
+ return { CallExpression: (node) => {
3003
+ const call = node;
3004
+ if (AST.isCallOf(call, "Schema", "makeFilter")) {
3005
+ const optionsArg = call.arguments[1];
3006
+ if (!optionsArg) return ctx.report(Diagnostic.make({
3007
+ node,
3008
+ message: "`Schema.makeFilter` must include a metadata object with `identifier`, `title`, and `description` as the second argument. (EF-12c)"
3009
+ }));
3010
+ const missing = checkOptionsObject("Schema.makeFilter", node, optionsArg);
3011
+ if (missing.length > 0) return ctx.report(Diagnostic.make({
3012
+ node,
3013
+ message: `\`Schema.makeFilter\` is missing required metadata: ${missing.map((k) => `\`${k}\``).join(", ")}. Reusable schema checks must include \`identifier\`, \`title\`, and \`description\`. (EF-12c)`
3014
+ }));
3015
+ }
3016
+ if (AST.isCallOf(call, "Schema", "makeFilterGroup")) {
3017
+ const optionsArg = call.arguments[1];
3018
+ if (!optionsArg) return ctx.report(Diagnostic.make({
3019
+ node,
3020
+ message: "`Schema.makeFilterGroup` must include a metadata object with `identifier`, `title`, and `description` as the second argument. (EF-12c)"
3021
+ }));
3022
+ const missing = checkOptionsObject("Schema.makeFilterGroup", node, optionsArg);
3023
+ if (missing.length > 0) return ctx.report(Diagnostic.make({
3024
+ node,
3025
+ message: `\`Schema.makeFilterGroup\` is missing required metadata: ${missing.map((k) => `\`${k}\``).join(", ")}. Reusable schema checks must include \`identifier\`, \`title\`, and \`description\`. (EF-12c)`
3026
+ }));
3027
+ }
3028
+ return Effect.void;
3029
+ } };
3030
+ }
3031
+ });
3032
+ const SCHEMA_NAMESPACES = ["Schema", "S"];
3033
+ const BooleanPrefixedName = Schema.String.check(Schema.isPattern(new RegExp(`^(${[
3034
+ "is",
3035
+ "has",
3036
+ "can",
3037
+ "should",
3038
+ "was",
3039
+ "will"
3040
+ ].join("|")})[A-Z]`), {
3041
+ identifier: "BooleanPrefixedName",
3042
+ title: "Boolean-Prefixed Field Name",
3043
+ description: "An identifier beginning with a Effect boolean prefix (is/has/can/should/was/will) followed by an uppercase letter."
3044
+ }));
3045
+ const isBooleanPrefixedName = Schema.is(BooleanPrefixedName);
3046
+ const isSchemaStructCall = (call) => pipe$1(SCHEMA_NAMESPACES, Arr.some((ns) => AST.isCallOf(call, ns, "Struct")));
3047
+ const isSchemaBoolean = (node) => node.type === "MemberExpression" && pipe$1(SCHEMA_NAMESPACES, Arr.some((ns) => AST.isMember(node, ns, "Boolean")));
3048
+ const findings = (fields) => pipe$1(fields.properties, Arr.filterMap((prop) => {
3049
+ if (prop.type !== "Property") return Result.failVoid;
3050
+ if (prop.key.type !== "Identifier") return Result.failVoid;
3051
+ if (!isSchemaBoolean(prop.value)) return Result.failVoid;
3052
+ if (isBooleanPrefixedName(prop.key.name)) return Result.failVoid;
3053
+ return Result.succeed({
3054
+ node: prop,
3055
+ key: prop.key.name
3056
+ });
3057
+ }));
3058
+ const fieldsArg = (call) => {
3059
+ const arg = call.arguments[0];
3060
+ return arg !== void 0 && arg.type === "ObjectExpression" ? arg : void 0;
3061
+ };
3062
+ const rule$12 = Rule.define({
3063
+ name: "require-is-prefix-for-boolean-schema-field",
3064
+ meta: Rule.meta({
3065
+ type: "suggestion",
3066
+ description: "Boolean fields in `Schema.Struct` must use a boolean prefix (is/has/can/should/was/will) (EF)"
3067
+ }),
3068
+ create: function* () {
3069
+ const ctx = yield* RuleContext;
3070
+ return Visitor.on("CallExpression", (node) => {
3071
+ if (!isSchemaStructCall(node)) return Effect.void;
3072
+ const fields = fieldsArg(node);
3073
+ if (fields === void 0) return Effect.void;
3074
+ return Effect.forEach(findings(fields), (f) => ctx.report(Diagnostic.make({
3075
+ node: f.node,
3076
+ message: `Boolean field \`${f.key}\` must use a boolean prefix (\`is*\`, \`has*\`, \`can*\`, \`should*\`, \`was*\`, or \`will*\`) — e.g. \`is${f.key.charAt(0).toUpperCase()}${f.key.slice(1)}\`. (EF)`
3077
+ })), {
3078
+ concurrency: 1,
3079
+ discard: true
3080
+ });
3081
+ });
3082
+ }
3083
+ });
3084
+ const isSchemaUtility = Schema.is(Schema.Union([Schema.String.check(Schema.isPattern(/^is(?:[A-Z]|$)/u)), Schema.Literals([
3085
+ "makeFilter",
3086
+ "makeFilterGroup",
3087
+ "toEquivalence",
3088
+ "toFormatter"
3089
+ ])]));
3090
+ /** Check if an expression references Schema.* (member access or call). */
3091
+ const isSchemaReference = (init) => {
3092
+ if (init.type === "MemberExpression" && init.object.type === "Identifier" && init.object.name === "Schema") return true;
3093
+ if (init.type === "CallExpression" && init.callee.type === "MemberExpression") {
3094
+ if (init.callee.object.type === "Identifier" && init.callee.object.name === "Schema" && init.callee.property.type === "Identifier" && isSchemaUtility(init.callee.property.name)) return false;
3095
+ if (init.callee.object.type === "Identifier" && init.callee.object.name === "Schema") return true;
3096
+ return isSchemaReference(init.callee.object);
3097
+ }
3098
+ return false;
3099
+ };
3100
+ const rule$11 = Rule.define({
3101
+ name: "require-schema-type-alias",
3102
+ meta: Rule.meta({
3103
+ type: "suggestion",
3104
+ description: "Exported non-class schemas should have a matching type alias export (EF-3)"
3105
+ }),
3106
+ create: function* () {
3107
+ const ctx = yield* RuleContext;
3108
+ return yield* Visitor.accumulate("ExportNamedDeclaration", (node) => {
3109
+ const decl = node.declaration;
3110
+ if (!decl) return Option.none();
3111
+ if (decl.type === "TSTypeAliasDeclaration") return Option.some({
3112
+ name: decl.id.name,
3113
+ node: decl.id,
3114
+ isTypeAlias: true
3115
+ });
3116
+ if (decl.type !== "VariableDeclaration") return Option.none();
3117
+ for (const declarator of decl.declarations) {
3118
+ if (declarator.id.type !== "Identifier") continue;
3119
+ const name = declarator.id.name;
3120
+ const init = declarator.init;
3121
+ if (!init) continue;
3122
+ if (isSchemaReference(init)) return Option.some({
3123
+ name,
3124
+ node: declarator.id,
3125
+ isTypeAlias: false
3126
+ });
3127
+ }
3128
+ return Option.none();
3129
+ }, (items) => Effect.gen(function* () {
3130
+ const schemaConsts = /* @__PURE__ */ new Map();
3131
+ const typeAliases = /* @__PURE__ */ new Set();
3132
+ for (const item of items) if (item.isTypeAlias) typeAliases.add(item.name);
3133
+ else schemaConsts.set(item.name, item.node);
3134
+ for (const [name, constNode] of schemaConsts) if (!typeAliases.has(name)) yield* ctx.report(Diagnostic.make({
3135
+ node: constNode,
3136
+ message: `Exported schema constant \`${name}\` should have a matching \`export type ${name} = typeof ${name}.Type\`. Non-class schemas need explicit type alias exports. (EF-3)`
3137
+ }));
3138
+ }));
3139
+ }
3140
+ });
3141
+ const EffectGenLikeName = Schema.Literals([
3142
+ "gen",
3143
+ "fn",
3144
+ "fnUntraced"
3145
+ ]).annotate({
3146
+ title: "EffectGenLikeName",
3147
+ description: "`Effect.*` constructors whose body uses generator syntax — `throw` inside any of these escapes the typed error channel."
3148
+ });
3149
+ const isEffectGenLikeName = Schema.is(EffectGenLikeName);
3150
+ const EffectTryName = Schema.Literals(["try", "tryPromise"]).annotate({
3151
+ title: "EffectTryName",
3152
+ description: "`Effect.try` and `Effect.tryPromise` capture thrown errors from a direct thunk or `try:` callback in the error channel."
3153
+ });
3154
+ const isEffectTryName = Schema.is(EffectTryName);
3155
+ /** The direct `.parent` of a node, lifted into `Option<ESTree.Node>`. */
3156
+ const parent = (node) => Option.fromNullishOr(node.parent);
3157
+ /**
3158
+ * The direct parent, narrowed to a specific node `type`. Unlike
3159
+ * `AST.findAncestor` (which walks the whole chain), this only succeeds
3160
+ * when the immediate parent matches — so a property named `try` sitting
3161
+ * inside an unrelated object literal nested deeper inside `Effect.try`
3162
+ * does not get a false exemption.
3163
+ */
3164
+ const parentOfType = (node, type) => pipe(parent(node), Option.flatMap(AST.narrow(type)));
3165
+ /** A call of the form `Effect.gen(...)` / `Effect.fn(...)` / `Effect.fnUntraced(...)`. */
3166
+ const isEffectGenLikeCall = (node) => pipe(AST.narrow(node.callee, "MemberExpression"), Option.flatMap(AST.memberNames), Option.exists(([obj, prop]) => obj === "Effect" && isEffectGenLikeName(prop)));
3167
+ const isEffectTryCall = (node) => pipe(AST.narrow(node.callee, "MemberExpression"), Option.flatMap(AST.memberNames), Option.exists(([obj, prop]) => obj === "Effect" && isEffectTryName(prop)));
3168
+ /** A direct thunk passed as the first argument to `Effect.try` or `tryPromise`. */
3169
+ const isDirectThunkOfEffectTry = (node) => pipe(parentOfType(node, "CallExpression"), Option.exists((call) => call.arguments[0] === node && isEffectTryCall(call)));
3170
+ /**
3171
+ * A `Property` whose key is the identifier `try`, sitting as a direct
3172
+ * key of an `ObjectExpression` that is itself the direct argument of a
3173
+ * `CallExpression` whose callee is `Effect.try` / `Effect.tryPromise`.
3174
+ */
3175
+ const isTryPropertyOfEffectTry = (node) => {
3176
+ if (!pipe(AST.narrow(node, "Property"), Option.exists((p) => p.key.type === "Identifier" && p.key.name === "try"))) return false;
3177
+ return pipe(parentOfType(node, "ObjectExpression"), Option.flatMap((obj) => parentOfType(obj, "CallExpression")), Option.exists(isEffectTryCall));
3178
+ };
3179
+ const MESSAGE$2 = "Do not throw inside `Effect.gen` / `Effect.fn` / `Effect.fnUntraced`. Use `yield* Effect.fail(new MyError(...))` (or `yield* new MyTaggedError({...})`) to keep errors in the typed channel. (EF-1)";
3180
+ const rule$10 = Rule.define({
3181
+ name: "throw-in-effect-gen",
3182
+ meta: Rule.meta({
3183
+ type: "problem",
3184
+ description: "Disallow `throw` inside `Effect.gen` / `Effect.fn` / `Effect.fnUntraced` — use `yield* Effect.fail(...)` so the failure stays in the typed error channel. Throws inside direct thunks and `try:` callbacks of `Effect.try` / `Effect.tryPromise` are exempt."
3185
+ }),
3186
+ create: function* () {
3187
+ const ctx = yield* RuleContext;
3188
+ const generatorDepth = yield* Ref.make(0);
3189
+ const capturedTryDepth = yield* Ref.make(0);
3190
+ return Visitor.merge(Visitor.tracked("CallExpression", isEffectGenLikeCall, generatorDepth), Visitor.tracked("Property", isTryPropertyOfEffectTry, capturedTryDepth), Visitor.tracked("ArrowFunctionExpression", isDirectThunkOfEffectTry, capturedTryDepth), Visitor.tracked("FunctionExpression", isDirectThunkOfEffectTry, capturedTryDepth), Visitor.on("ThrowStatement", (node) => Effect.gen(function* () {
3191
+ const gen = yield* Ref.get(generatorDepth);
3192
+ const tryDepth = yield* Ref.get(capturedTryDepth);
3193
+ if (gen > 0 && tryDepth === 0) yield* ctx.report(Diagnostic.make({
3194
+ node,
3195
+ message: MESSAGE$2
3196
+ }));
3197
+ })));
3198
+ }
3199
+ });
3200
+ const DateGlobal = Schema.Literal("Date").annotate({
3201
+ title: "DateGlobal",
3202
+ description: "The global `Date` constructor — both `new Date(...)` and `Date.*` static helpers should yield to `Clock`/`DateTime`."
3203
+ });
3204
+ const isDateGlobal = Schema.is(DateGlobal);
3205
+ const MESSAGE$1 = "Avoid direct `Date` usage in Effect code. Use `DateTime` from `effect` or the `Clock` service for testable, deterministic time. Suppress with `oxlint-disable-next-line` for legitimate parse cases. (EF-9)";
3206
+ const rule$9 = Rule.define({
3207
+ name: "use-clock-service",
3208
+ meta: Rule.meta({
3209
+ type: "suggestion",
3210
+ description: "Disallow `new Date(...)` and `Date.*` — use Effect `DateTime` / `Clock` instead (EF-9)"
3211
+ }),
3212
+ create: function* () {
3213
+ const ctx = yield* RuleContext;
3214
+ return Visitor.merge(Visitor.on("NewExpression", (node) => pipe$1(AST.narrow(node.callee, "Identifier"), Option.map((id) => id.name), Option.filter(isDateGlobal), Option.match({
3215
+ onNone: () => Effect.void,
3216
+ onSome: () => ctx.report(Diagnostic.make({
3217
+ node,
3218
+ message: MESSAGE$1
3219
+ }))
3220
+ }))), Visitor.on("MemberExpression", (node) => pipe$1(AST.memberNames(node), Option.filter(([obj]) => isDateGlobal(obj)), Option.match({
3221
+ onNone: () => Effect.void,
3222
+ onSome: () => ctx.report(Diagnostic.make({
3223
+ node,
3224
+ message: MESSAGE$1
3225
+ }))
3226
+ }))));
3227
+ }
3228
+ });
3229
+ const ChildProcessImportSource = Schema.Literals(["child_process", "node:child_process"]).annotate({
3230
+ title: "ChildProcessImportSource",
3231
+ description: "Node `child_process` module import specifiers. Use `ChildProcessSpawner` (Effect v4) or `CommandExecutor` (`@effect/platform`) instead."
3232
+ });
3233
+ const isChildProcessImportSource = Schema.is(ChildProcessImportSource);
3234
+ const rule$8 = Rule.banImport(isChildProcessImportSource, { message: "Avoid importing `child_process` / `node:child_process`. Use `ChildProcessSpawner` + `ChildProcess` from `effect/process` for typed, scoped, composable process spawning. See the `effect-command-executor` skill." });
3235
+ const MESSAGE = "Avoid `console.*` in Effect code. Use `Effect.logInfo`, `Effect.logError`, `Effect.logWarning`, `Effect.logDebug`, or the `Console` service for structured, testable logging. (EF-15)";
3236
+ /**
3237
+ * A static `MemberExpression` of the form `console.<anything>`. Computed
3238
+ * accesses (`console['log']`) and private identifiers are excluded —
3239
+ * `AST.memberNames` already filters those out.
3240
+ */
3241
+ const isConsoleAccess = (node) => pipe(AST.memberNames(node), Option.exists(([obj]) => obj === "console"));
3242
+ const rule$7 = Rule.define({
3243
+ name: "use-console-service",
3244
+ meta: Rule.meta({
3245
+ type: "suggestion",
3246
+ description: "Disallow any `console.*` access in Effect code — including `log`, `error`, `warn`, `info`, `debug`, `trace`, `table`, `dir`, `group*`, `time*`, `assert`, `count*`, `profile*`, etc. (EF-15)"
3247
+ }),
3248
+ create: function* () {
3249
+ const ctx = yield* RuleContext;
3250
+ return Visitor.on("MemberExpression", (node) => isConsoleAccess(node) ? ctx.report(Diagnostic.make({
3251
+ node,
3252
+ message: MESSAGE
3253
+ })) : Effect.void);
3254
+ }
3255
+ });
3256
+ const FsImportSource = Schema.Literals([
3257
+ "fs",
3258
+ "node:fs",
3259
+ "fs/promises",
3260
+ "node:fs/promises"
3261
+ ]).annotate({
3262
+ title: "FsImportSource",
3263
+ description: "Node `fs` module import specifiers — both the legacy callback/sync API and the Promise-based variant. Use `FileSystem` from `@effect/platform` instead."
3264
+ });
3265
+ const isFsImportSource = Schema.is(FsImportSource);
3266
+ const rule$6 = Rule.banImport(isFsImportSource, { message: "Avoid importing `fs` / `node:fs` / `fs/promises`. Use the `FileSystem` service from `@effect/platform` for typed, Effect-native file I/O. See the `effect-filesystem` skill." });
3267
+ const HttpImportSource = Schema.Literals([
3268
+ "http",
3269
+ "https",
3270
+ "node:http",
3271
+ "node:https"
3272
+ ]).annotate({
3273
+ title: "HttpImportSource",
3274
+ description: "Node `http` / `https` module import specifiers. Use `HttpClient` from `effect/http` with a platform layer (`BunHttpClient.layer` / `NodeHttpClient.layerUndici`) instead."
3275
+ });
3276
+ const isHttpImportSource = Schema.is(HttpImportSource);
3277
+ const rule$5 = Rule.banImport(isHttpImportSource, { message: "Avoid importing `http` / `https` / `node:http` / `node:https`. Use `HttpClientRequest`, `HttpClientResponse`, and `HttpClient` from `effect/http` for typed errors, composable HTTP, and testable layer substitution. See the `effect-http-client` skill. (EF-9b)" });
3278
+ const PathImportSource = Schema.Literals(["path", "node:path"]).annotate({
3279
+ title: "PathImportSource",
3280
+ description: "Node `path` module import specifiers. Use `Path.Path` from `@effect/platform` instead."
3281
+ });
3282
+ const isPathImportSource = Schema.is(PathImportSource);
3283
+ const rule$4 = Rule.banImport(isPathImportSource, { message: "Avoid importing `path` / `node:path`. Use the `Path` service from `@effect/platform` for cross-platform path operations. See the `effect-path` skill." });
3284
+ const rule$3 = Rule.banMember("Math", "random", { message: "Avoid `Math.random()` in Effect code. Use the `Random` service for testable, deterministic randomness. (EF-9)" });
3285
+ const OsImportSource = Schema.Literals(["os", "node:os"]).annotate({
3286
+ title: "OsImportSource",
3287
+ description: "Import sources for Node's built-in `os` module that expose `tmpdir()`."
3288
+ });
3289
+ const isOsImportSource = Schema.is(OsImportSource);
3290
+ const UnscopedTempApiName = Schema.Literals(["makeTempFile", "makeTempDirectory"]).annotate({
3291
+ title: "UnscopedTempApiName",
3292
+ description: "Effect platform FileSystem APIs that allocate a temp resource without binding cleanup to a scope."
3293
+ });
3294
+ const isUnscopedTempApiName = Schema.is(UnscopedTempApiName);
3295
+ /**
3296
+ * Extract the property name when a `MemberExpression` calls a member
3297
+ * matching one of the unscoped temp APIs, regardless of the receiver.
3298
+ * Returns `Option<UnscopedTempApiName>` so the diagnostic can name the
3299
+ * specific API.
3300
+ */
3301
+ const matchUnscopedTempMember = (node) => pipe(AST.memberNames(node), Option.flatMap(([, prop]) => isUnscopedTempApiName(prop) ? Option.some(prop) : Option.none()));
3302
+ const IMPORT_MESSAGE = "Avoid `os` / `node:os` — use `FileSystem.makeTempFileScoped` from `@effect/platform` for scoped temp files with automatic cleanup.";
3303
+ const TMPDIR_MESSAGE = "Avoid `os.tmpdir()` — use `FileSystem.makeTempFileScoped` from `@effect/platform` for scoped temp files with automatic cleanup.";
3304
+ const unscopedMessage = (api) => `Avoid \`${api}\` — the unscoped variant requires manual cleanup. Use \`${api}Scoped\` so the resource is finalized when its scope closes.`;
3305
+ const rule$2 = Rule.define({
3306
+ name: "use-temp-file-scoped",
3307
+ meta: Rule.meta({
3308
+ type: "suggestion",
3309
+ description: "Disallow `os`/`os.tmpdir()` and the unscoped `makeTempFile` / `makeTempDirectory` FileSystem APIs — prefer their `*Scoped` siblings so cleanup is bound to scope finalization."
3310
+ }),
3311
+ create: function* () {
3312
+ const ctx = yield* RuleContext;
3313
+ return Visitor.merge(Visitor.on("ImportDeclaration", (node) => isOsImportSource(AST.importSource(node)) ? ctx.report(Diagnostic.make({
3314
+ node,
3315
+ message: IMPORT_MESSAGE
3316
+ })) : Effect.void), Visitor.on("MemberExpression", (node) => pipe(AST.matchMember(node, "os", "tmpdir"), Option.match({
3317
+ onNone: () => Effect.void,
3318
+ onSome: (matched) => ctx.report(Diagnostic.make({
3319
+ node: matched,
3320
+ message: TMPDIR_MESSAGE
3321
+ }))
3322
+ }))), Visitor.on("CallExpression", (node) => pipe(AST.narrow(node.callee, "MemberExpression"), Option.flatMap(matchUnscopedTempMember), Option.match({
3323
+ onNone: () => Effect.void,
3324
+ onSome: (api) => ctx.report(Diagnostic.make({
3325
+ node,
3326
+ message: unscopedMessage(api)
3327
+ }))
3328
+ }))));
3329
+ }
3330
+ });
3331
+ const LayerFactoryName = Schema.Literals(["effect", "scoped"]).annotate({
3332
+ title: "LayerFactoryName",
3333
+ description: "`Layer.effect` and legacy `Layer.scoped` calls where a VM tag appears as the first argument."
3334
+ });
3335
+ const isLayerFactoryName = Schema.is(LayerFactoryName);
3336
+ const VmName = Schema.String.check(Schema.makeFilter((s) => Str.endsWith("VM")(s), {
3337
+ identifier: "VmNameCheck",
3338
+ title: "VM name",
3339
+ description: "A name ending with the suffix `VM`.",
3340
+ message: "Name must end with VM"
3341
+ })).pipe(Schema.brand("VmName"), Schema.annotate({
3342
+ title: "VmName",
3343
+ description: "A type/identifier name following the View Model naming convention (`...VM`)."
3344
+ }));
3345
+ const isVmName = Schema.is(VmName);
3346
+ const interfaceName = (node) => node.id.name;
3347
+ /**
3348
+ * The first type argument of `Context.Service<FooVM>` — returns the
3349
+ * identifier name when it exists and is a bare identifier reference.
3350
+ */
3351
+ const contextServiceTypeArgumentName = (node) => pipe(AST.narrow(node.callee, "CallExpression"), Option.filter((inner) => inner.callee.type === "MemberExpression" && AST.isMember(inner.callee, "Context", "Service")), Option.flatMap((inner) => Option.fromNullishOr(inner.typeArguments?.params[0])), Option.flatMap(AST.narrow("TSTypeReference")), Option.flatMap((ref) => ref.typeName.type === "Identifier" ? Option.some(ref.typeName.name) : Option.none()));
3352
+ /**
3353
+ * The first positional argument of `Layer.effect|scoped(FooVM, ...)` —
3354
+ * returns the identifier name when the argument is a bare identifier.
3355
+ */
3356
+ const layerFactoryFirstArgumentName = (node) => pipe(AST.narrow(node.callee, "MemberExpression"), Option.flatMap(AST.memberNames), Option.filter(([obj, prop]) => obj === "Layer" && isLayerFactoryName(prop)), Option.flatMap(() => Option.fromNullishOr(node.arguments[0])), Option.flatMap(AST.narrow("Identifier")), Option.map((id) => id.name));
3357
+ const interfaceMessage = (name, suggestedFile) => `View Model interface \`${name}\` must be in a \`.vm.ts\` file. Move it to \`${suggestedFile}\` to keep rendering and state management separated.`;
3358
+ const layerMessage = (factory, name) => `View Model layer \`Layer.${factory}(${name}, ...)\` must be in a \`.vm.ts\` file. Move it to keep rendering and state management separated.`;
3359
+ const serviceMessage = (name) => `View Model service \`Context.Service<${name}>(...)\` must be defined in a \`.vm.ts\` file. Move it to keep rendering and state management separated.`;
3360
+ const vmFileSuggestion = (filename) => filename.replace(/\.(ts|tsx)$/, ".vm.$1");
3361
+ const rule$1 = Rule.define({
3362
+ name: "vm-in-wrong-file",
3363
+ meta: Rule.meta({
3364
+ type: "problem",
3365
+ description: "View Model definitions (`interface FooVM`, `Context.Service<FooVM>(...)`, `Layer.effect(FooVM, ...)`) must live in `.vm.ts` / `.vm.tsx` files."
3366
+ }),
3367
+ create: function* () {
3368
+ const ctx = yield* RuleContext;
3369
+ return yield* Visitor.filter((filename) => !filename.endsWith(".vm.ts") && !filename.endsWith(".vm.tsx"), Visitor.merge(Visitor.on("TSInterfaceDeclaration", (node) => isVmName(interfaceName(node)) ? ctx.report(Diagnostic.make({
3370
+ node,
3371
+ message: interfaceMessage(interfaceName(node), vmFileSuggestion(ctx.filename))
3372
+ })) : Effect.void), Visitor.on("CallExpression", (node) => pipe(contextServiceTypeArgumentName(node), Option.filter(isVmName), Option.match({
3373
+ onNone: () => Effect.void,
3374
+ onSome: (name) => ctx.report(Diagnostic.make({
3375
+ node,
3376
+ message: serviceMessage(name)
3377
+ }))
3378
+ }))), Visitor.on("CallExpression", (node) => pipe(AST.narrow(node.callee, "MemberExpression"), Option.flatMap(AST.memberNames), Option.filter(([, prop]) => isLayerFactoryName(prop)), Option.flatMap(([, factory]) => pipe(layerFactoryFirstArgumentName(node), Option.filter(isVmName), Option.map((name) => [factory, name]))), Option.match({
3379
+ onNone: () => Effect.void,
3380
+ onSome: ([factory, name]) => ctx.report(Diagnostic.make({
3381
+ node,
3382
+ message: layerMessage(factory, name)
3383
+ }))
3384
+ })))));
3385
+ }
3386
+ });
3387
+ const rules = {
3388
+ "no-chained-type-assertions": noChainedTypeAssertionsRule,
3389
+ "no-conditional-empty-object-spread": noConditionalEmptyObjectSpreadRule,
3390
+ "no-known-value-widening": noKnownValueWideningRule,
3391
+ "no-module-mocking": noModuleMockingRule,
3392
+ "no-object-parameters": noObjectParametersRule,
3393
+ "no-reflect-apply": noReflectApplyRule,
3394
+ "no-reflect-get": noReflectGetRule,
3395
+ "no-runtime-typeof": noRuntimeTypeofRule,
3396
+ "no-service-constructor-imports": noServiceConstructorImportsRule,
3397
+ "no-shape-in-symbol-names": noForbiddenTermInSymbolNamesRule,
3398
+ "no-unknown-parameters": noUnknownParametersRule,
3399
+ "no-unknown-returns": noUnknownReturnsRule,
3400
+ "no-unknown-type-aliases": noUnknownTypeAliasesRule,
3401
+ "no-unsafe-dictionary-type": noUnsafeDictionaryTypeRule,
3402
+ "no-widen-then-assert": noWidenThenAssertRule,
3403
+ "require-safety-comment-for-type-assertion": requireSafetyCommentForTypeAssertionRule,
3404
+ "avoid-try-catch": rule$39,
3405
+ "prefer-match-over-switch": rule$18,
3406
+ "imperative-loops": rule$30,
3407
+ "avoid-data-tagged-error": rule$55,
3408
+ "avoid-direct-json": rule$54,
3409
+ "avoid-option-getorthrow": rule$45,
3410
+ "avoid-process-env": rule$43,
3411
+ "use-random-service": rule$3,
3412
+ "effect-run-in-body": rule$31,
3413
+ "effect-promise-vs-trypromise": rule$32,
3414
+ "use-console-service": rule$7,
3415
+ "use-filesystem-service": rule$6,
3416
+ "use-path-service": rule$4,
3417
+ "use-command-executor-service": rule$8,
3418
+ "use-http-client-service": rule$5,
3419
+ "avoid-platform-coupling": rule$44,
3420
+ "avoid-node-imports": rule$48,
3421
+ "avoid-any": rule$56,
3422
+ "avoid-object-type": rule$46,
3423
+ "avoid-ts-ignore": rule$38,
3424
+ "avoid-mutable-state": rule$51,
3425
+ "avoid-schema-suffix": rule$41,
3426
+ "avoid-non-null-assertion": rule$47,
3427
+ "prefer-option-over-null": rule$16,
3428
+ "casting-awareness": rule$35,
3429
+ "use-clock-service": rule$9,
3430
+ "avoid-native-fetch": rule$50,
3431
+ "avoid-react-hooks": rule$42,
3432
+ "avoid-sync-fs": rule$40,
3433
+ "avoid-untagged-errors": rule$37,
3434
+ "prefer-arr-sort": rule$23,
3435
+ "context-tag-extends": rule$34,
3436
+ "throw-in-effect-gen": rule$10,
3437
+ "prefer-effect-fn": rule$20,
3438
+ "yield-in-for-loop": Rule.define({
3439
+ name: "yield-in-for-loop",
3440
+ meta: Rule.meta({
3441
+ type: "suggestion",
3442
+ description: "Disallow yield* inside for loops — use Effect.forEach for declarative effectful iteration"
3443
+ }),
3444
+ create: function* () {
3445
+ const ctx = yield* RuleContext;
3446
+ const forLoopDepth = yield* Ref.make(0);
3447
+ return Visitor.merge(Visitor.tracked("ForStatement", () => true, forLoopDepth), Visitor.tracked("ForInStatement", () => true, forLoopDepth), Visitor.tracked("ForOfStatement", () => true, forLoopDepth), Visitor.on("YieldExpression", (node) => Effect.gen(function* () {
3448
+ if ((yield* Ref.get(forLoopDepth)) > 0 && node.delegate) yield* ctx.report(Diagnostic.make({
3449
+ node,
3450
+ message: "Avoid `yield*` inside `for` loops. Use `Effect.forEach(items, fn, { concurrency: ... })` for declarative, parallelizable effectful iteration. (EF-5)"
3451
+ }));
3452
+ })));
3453
+ }
3454
+ }),
3455
+ "avoid-expect-in-if": rule$52,
3456
+ "avoid-yield-ref": rule$36,
3457
+ "effect-catchall-default": rule$33,
3458
+ "avoid-direct-tag-checks": rule$53,
3459
+ "vm-in-wrong-file": rule$1,
3460
+ "use-temp-file-scoped": rule$2,
3461
+ "avoid-native-object-helpers": rule$49,
3462
+ "prefer-array-fromoption-over-option-match-empty": rule$22,
3463
+ "no-length-comparison": rule$26,
3464
+ "no-effect-ignore-then-as": rule$27,
3465
+ "prefer-namespace-imports": rule$17,
3466
+ "prefer-effect-is": rule$19,
3467
+ "prefer-duration-constructors": rule$21,
3468
+ "prefer-arr-match": rule$24,
3469
+ "prefer-redacted-config": rule$15,
3470
+ "require-schema-type-alias": rule$11,
3471
+ "require-filter-metadata": rule$13,
3472
+ "require-is-prefix-for-boolean-schema-field": rule$12,
3473
+ "maybe-prefix-requires-option": rule$29,
3474
+ "require-effect-concurrency": rule$14,
3475
+ "no-barrel-imports": rule$28,
3476
+ "no-opaque-instance-fields": rule$25
3477
+ };
3478
+ /**
3479
+ * Oxlint plugin for Effect-first TypeScript rules and generated config presets.
3480
+ *
3481
+ * @since 0.2.2
3482
+ */
3483
+ const plugin$1 = Plugin.define({
3484
+ name: "effect",
3485
+ specifier: "@mpsuesser/oxlint-plugin-effect",
3486
+ rules
3487
+ });
3488
+ // src/effect-plugin.ts
3489
+ const plugin = {
3490
+ meta: plugin$1.meta,
3491
+ rules: plugin$1.rules
3492
+ };
3493
+ export { plugin as t };