@siim-m/config 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,250 @@
1
+ // Changed from the fork: a data-first source built with `.pipe(Effect.tapError(...))` counts as logged, and a
2
+ // yielded value bound to a name, such as `const ref = yield* Ref.make(0)`, or the `make` of an Effect value module,
3
+ // such as `Ref.make(0)`, is not a constructed error.
4
+ import { defineRule } from "@oxlint/plugins";
5
+ import { collectEffectModuleNames, genFunction, isFunction, keyName, moduleCallName, moduleMemberName, precedingSteps, returnedExpressions, unwrapNode, walk, } from "../shared/effect-modules.js";
6
+ const narrowingOperators = new Set(["mapError", "catch", "catchAll", "catchCause", "orElse"]);
7
+ const tapOperators = new Set(["tapError", "tapErrorCause", "tapCause", "tapErrorTag"]);
8
+ const effectModuleNamesList = [
9
+ "Context",
10
+ "Effect",
11
+ "Layer",
12
+ "ManagedRuntime",
13
+ ];
14
+ /** Whether the handler never reads the error it receives. */
15
+ function ignoresError(handler, sourceCode) {
16
+ const [parameter] = handler.params;
17
+ if (parameter === undefined)
18
+ return true;
19
+ if (parameter.type !== "Identifier")
20
+ return false;
21
+ const variable = sourceCode
22
+ .getDeclaredVariables(handler)
23
+ .find((candidate) => candidate.identifiers.some((identifier) => identifier === parameter));
24
+ return variable !== undefined && variable.references.length === 0;
25
+ }
26
+ /**
27
+ * Effect 3 and 4 modules whose `make` builds a value, such as a `Ref` or a `Queue`, rather than an error.
28
+ * Not exhaustive: for a module missing here, suppress with a reason.
29
+ */
30
+ const valueModules = new Set([
31
+ "Array",
32
+ "BigDecimal",
33
+ "Cache",
34
+ "Chunk",
35
+ "Combiner",
36
+ "ConfigProvider",
37
+ "Cron",
38
+ "DateTime",
39
+ "Deferred",
40
+ "Equivalence",
41
+ "ExecutionPlan",
42
+ "FiberHandle",
43
+ "FiberMap",
44
+ "FiberRef",
45
+ "FiberSet",
46
+ "Filter",
47
+ "Graph",
48
+ "HashMap",
49
+ "HashRing",
50
+ "HashSet",
51
+ "KeyedPool",
52
+ "Latch",
53
+ "LayerMap",
54
+ "LayerRef",
55
+ "List",
56
+ "Logger",
57
+ "Mailbox",
58
+ "MutableHashMap",
59
+ "MutableHashSet",
60
+ "MutableList",
61
+ "MutableRef",
62
+ "Order",
63
+ "PartitionedSemaphore",
64
+ "Pool",
65
+ "PubSub",
66
+ "Queue",
67
+ "RcMap",
68
+ "RcRef",
69
+ "Redacted",
70
+ "Reducer",
71
+ "Ref",
72
+ "RequestResolver",
73
+ "Scope",
74
+ "ScopedCache",
75
+ "ScopedRef",
76
+ "Semaphore",
77
+ "Sink",
78
+ "SortedMap",
79
+ "SortedSet",
80
+ "Stream",
81
+ "SubscriptionRef",
82
+ "SynchronizedRef",
83
+ "TArray",
84
+ "TDeferred",
85
+ "TMap",
86
+ "TPriorityQueue",
87
+ "TPubSub",
88
+ "TQueue",
89
+ "TReentrantLock",
90
+ "TRef",
91
+ "TSemaphore",
92
+ "TSet",
93
+ "TSubscriptionRef",
94
+ "Tracer",
95
+ "Trie",
96
+ "Tuple",
97
+ "TxChunk",
98
+ "TxDeferred",
99
+ "TxHashMap",
100
+ "TxHashSet",
101
+ "TxPriorityQueue",
102
+ "TxQueue",
103
+ "TxReentrantLock",
104
+ "TxRef",
105
+ "TxSemaphore",
106
+ "TxSubscriptionRef",
107
+ ]);
108
+ /** The local names a file binds to Effect's value modules: `import { Ref } from "effect"` or `import * as Ref from "effect/Ref"`. */
109
+ function effectImports(program) {
110
+ const locals = new Set();
111
+ for (const statement of program.body) {
112
+ if (statement.type !== "ImportDeclaration")
113
+ continue;
114
+ const source = statement.source.value;
115
+ for (const specifier of statement.specifiers) {
116
+ if (source === "effect" && specifier.type === "ImportSpecifier") {
117
+ const name = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
118
+ if (valueModules.has(name))
119
+ locals.add(specifier.local.name);
120
+ }
121
+ else if (source.startsWith("effect/") && specifier.type !== "ImportSpecifier") {
122
+ if (valueModules.has(source.slice("effect/".length)))
123
+ locals.add(specifier.local.name);
124
+ }
125
+ }
126
+ }
127
+ return locals;
128
+ }
129
+ /** `new X(...)` or `X.make(...)` for a capitalized `X` that is not an Effect module. */
130
+ function isErrorConstruction(node, names, imported) {
131
+ if (node.type === "NewExpression")
132
+ return unwrapNode(node.callee).type === "Identifier" || unwrapNode(node.callee).type === "MemberExpression";
133
+ if (node.type !== "CallExpression")
134
+ return false;
135
+ const callee = unwrapNode(node.callee);
136
+ if (callee.type !== "MemberExpression" ||
137
+ callee.computed ||
138
+ callee.property.type !== "Identifier" ||
139
+ callee.property.name !== "make") {
140
+ return false;
141
+ }
142
+ const owner = unwrapNode(callee.object);
143
+ const ownerName = owner.type === "Identifier" ? owner.name : owner.type === "MemberExpression" && owner.property.type === "Identifier" ? owner.property.name : null;
144
+ if (ownerName === null || !/^[A-Z]/u.test(ownerName))
145
+ return false;
146
+ if (owner.type === "Identifier" && imported.has(owner.name))
147
+ return false;
148
+ return !effectModuleNamesList.some((module) => moduleMemberName(callee, names, module) !== null);
149
+ }
150
+ /** Whether any argument is an object literal with a `cause` property or a spread that may supply one. */
151
+ function passesCause(node) {
152
+ return node.arguments.some((argument) => {
153
+ const expression = unwrapNode(argument);
154
+ return (expression.type === "ObjectExpression" &&
155
+ expression.properties.some((property) => property.type === "SpreadElement" || (!property.computed && keyName(property.key) === "cause")));
156
+ });
157
+ }
158
+ /** The constructed errors a handler produces without descending into nested functions. */
159
+ function constructedErrors(handler, names, imported) {
160
+ const found = [];
161
+ const consider = (node) => {
162
+ const expression = unwrapNode(node);
163
+ if (expression.type === "YieldExpression" && expression.argument !== null) {
164
+ consider(expression.argument);
165
+ return;
166
+ }
167
+ if (isErrorConstruction(expression, names, imported))
168
+ found.push(expression);
169
+ };
170
+ for (const returned of returnedExpressions(handler))
171
+ consider(returned);
172
+ if (handler.body === null)
173
+ return found;
174
+ walk(handler.body, (node) => {
175
+ // An Effect.gen generator runs as the handler's own effect; other nested functions run later, if at all.
176
+ if (isFunction(node))
177
+ return node.type === "FunctionExpression" && genFunction(node.parent, names) === node;
178
+ if (moduleCallName(node, names, "Effect") === "fail" && node.type === "CallExpression") {
179
+ const [argument] = node.arguments;
180
+ if (argument !== undefined)
181
+ consider(argument);
182
+ }
183
+ // A yielded value bound to a name, such as `const ref = yield* Ref.make(0)`, is not the error the handler fails with.
184
+ if (node.type === "YieldExpression" && node.delegate && node.argument !== null && node.parent.type !== "VariableDeclarator") {
185
+ consider(node.argument);
186
+ }
187
+ return true;
188
+ });
189
+ return [...new Set(found)];
190
+ }
191
+ /** The steps that build a data-first source: the steps of `source.pipe(...)` or `pipe(source, ...)`, or the source itself. */
192
+ function sourceSteps(source) {
193
+ const expression = unwrapNode(source);
194
+ if (expression.type !== "CallExpression")
195
+ return [expression];
196
+ const callee = unwrapNode(expression.callee);
197
+ if (callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && callee.property.name === "pipe") {
198
+ return [expression, ...expression.arguments];
199
+ }
200
+ if (callee.type === "Identifier" && callee.name === "pipe")
201
+ return [expression, ...expression.arguments.slice(1)];
202
+ return [expression];
203
+ }
204
+ /** Whether `node` is a call of a tap operator, or the operator itself. */
205
+ function isTapStep(node, names) {
206
+ const expression = unwrapNode(node);
207
+ const member = moduleCallName(expression, names, "Effect") ?? moduleMemberName(expression, names, "Effect");
208
+ return member !== null && tapOperators.has(member);
209
+ }
210
+ /** Require narrowing handlers that replace an error to keep the original as `cause`. */
211
+ export const requireCauseWhenNarrowingRule = defineRule({
212
+ meta: {
213
+ type: "problem",
214
+ docs: {
215
+ description: "Require Effect.mapError/catch/catchAll/catchCause/orElse handlers that construct a new error to keep the original error as `cause`.",
216
+ },
217
+ messages: {
218
+ missingCause: "This {{operator}} handler discards the original error and constructs a new one without it. Name the handler's parameter and pass it as `cause` (`(error) => new {{error}}({ ..., cause: error })`, or `new Error(message, { cause: error })` for a native Error), or log it first with `Effect.tapError(Effect.logError)` before narrowing.",
219
+ },
220
+ },
221
+ create(context) {
222
+ const names = collectEffectModuleNames(context.sourceCode.ast);
223
+ const imported = effectImports(context.sourceCode.ast);
224
+ return {
225
+ CallExpression(node) {
226
+ const operator = moduleCallName(node, names, "Effect");
227
+ if (operator === null || !narrowingOperators.has(operator))
228
+ return;
229
+ const handler = node.arguments.at(-1);
230
+ if (handler === undefined || !isFunction(handler))
231
+ return;
232
+ if (!ignoresError(handler, context.sourceCode))
233
+ return;
234
+ const constructed = constructedErrors(handler, names, imported).find((construction) => !passesCause(construction));
235
+ if (constructed === undefined)
236
+ return;
237
+ const dataFirstSource = node.arguments.length > 1 ? node.arguments[0] : undefined;
238
+ const earlier = dataFirstSource === undefined ? precedingSteps(node) : sourceSteps(dataFirstSource);
239
+ if (earlier.some((step) => isTapStep(step, names)))
240
+ return;
241
+ const callee = unwrapNode(constructed.callee);
242
+ // `X.make(...)` names `X`; `new A.B(...)` names `A.B`.
243
+ const errorName = callee.type === "MemberExpression" && constructed.type === "CallExpression"
244
+ ? context.sourceCode.getText(callee.object)
245
+ : context.sourceCode.getText(callee);
246
+ context.report({ node: constructed, messageId: "missingCause", data: { operator: `Effect.${operator}`, error: errorName } });
247
+ },
248
+ };
249
+ },
250
+ });
@@ -0,0 +1,2 @@
1
+ /** Reject `throw` in an Effect generator body, where it becomes a defect instead of a typed failure. */
2
+ export declare const throwInEffectGenRule: import("@oxlint/plugins").Rule;
@@ -0,0 +1,87 @@
1
+ // Ported from mpsuesser/enfect's `throw-in-effect-gen` (https://github.com/mpsuesser/enfect, MIT, @enfect/oxlint 0.10.0).
2
+ // The upstream rule reports any `throw` lexically inside an `Effect.gen`, `Effect.fn` or `Effect.fnUntraced` call
3
+ // unless it sits in an exactly shaped `Effect.try` callback, so it also reports throws in plain helpers, promise
4
+ // callbacks and object methods that only happen to be declared inside the generator. This version reports a throw
5
+ // only when the nearest enclosing function is the generator itself.
6
+ import { defineRule } from "@oxlint/plugins";
7
+ import { collectEffectModuleNames, isFunction, moduleCallName, unwrapNode, } from "../shared/effect-modules.js";
8
+ /** `Effect` constructors whose generator body runs as the Effect program. */
9
+ const generatorConstructors = new Set(["fn", "fnUntraced", "gen"]);
10
+ /** Constructors that take the generator in a second call: `Effect.fn("name")(function* () {...})`. */
11
+ const curriedConstructors = new Set(["fn", "fnUntraced"]);
12
+ /** The node that holds `node` in place of its wrappers: parentheses, type assertions and the like. */
13
+ function outermostWrapper(node) {
14
+ let current = node;
15
+ while (current.parent !== null && unwrapNode(current.parent) !== current.parent)
16
+ current = current.parent;
17
+ return current;
18
+ }
19
+ /** Whether a synchronous function is called where it is written, so its throws reach the enclosing function. */
20
+ function isImmediatelyInvoked(fn) {
21
+ if (fn.async || fn.generator || fn.type === "FunctionDeclaration")
22
+ return false;
23
+ const expression = outermostWrapper(fn);
24
+ const call = expression.parent;
25
+ return call?.type === "CallExpression" && unwrapNode(call.callee) === fn;
26
+ }
27
+ /** Whether `fn` is the generator passed to `Effect.gen`, `Effect.fn` or `Effect.fnUntraced`. */
28
+ function isEffectGenerator(fn, names) {
29
+ if (fn.type !== "FunctionExpression" || !fn.generator)
30
+ return false;
31
+ const argument = outermostWrapper(fn);
32
+ const call = argument.parent;
33
+ if (call?.type !== "CallExpression" || !call.arguments.some((candidate) => candidate === argument))
34
+ return false;
35
+ const direct = moduleCallName(call, names, "Effect");
36
+ if (direct !== null)
37
+ return generatorConstructors.has(direct);
38
+ const curried = moduleCallName(unwrapNode(call.callee), names, "Effect");
39
+ return curried !== null && curriedConstructors.has(curried);
40
+ }
41
+ /**
42
+ * Whether a throw escapes into an Effect generator. A throw belongs to the nearest enclosing function, looking
43
+ * through synchronous functions invoked in place, and does not escape a `try` block that has a `catch` clause.
44
+ * Callbacks that Effect runs later, such as the `try` callback of `Effect.try`, or synchronously, such as the
45
+ * thunk of `Effect.sync`, are their own functions and are not reported.
46
+ */
47
+ function throwsIntoEffectGenerator(node, names) {
48
+ let child = node;
49
+ let current = node.parent;
50
+ while (current !== null) {
51
+ if (current.type === "TryStatement" && current.block === child && current.handler !== null)
52
+ return false;
53
+ if (isFunction(current)) {
54
+ if (!isImmediatelyInvoked(current))
55
+ return isEffectGenerator(current, names);
56
+ }
57
+ else if (current.type === "StaticBlock" || current.type === "PropertyDefinition") {
58
+ return false;
59
+ }
60
+ child = current;
61
+ current = current.parent;
62
+ }
63
+ return false;
64
+ }
65
+ /** Reject `throw` in an Effect generator body, where it becomes a defect instead of a typed failure. */
66
+ export const throwInEffectGenRule = defineRule({
67
+ meta: {
68
+ type: "problem",
69
+ docs: {
70
+ description: "Disallow `throw` in the generator body of `Effect.gen`, `Effect.fn` or `Effect.fnUntraced`, where it becomes a defect instead of a typed failure.",
71
+ },
72
+ messages: {
73
+ throwInEffectGen: "This `throw` becomes a defect, not a typed failure. Use `return yield* Effect.fail(new MyError(...))` or `return yield* new MyTaggedError({...})` so `Effect.catchTag` can handle it.",
74
+ },
75
+ },
76
+ create(context) {
77
+ const names = collectEffectModuleNames(context.sourceCode.ast);
78
+ if (!names.has("Effect"))
79
+ return {};
80
+ return {
81
+ ThrowStatement(node) {
82
+ if (throwsIntoEffectGenerator(node, names))
83
+ context.report({ node, messageId: "throwInEffectGen" });
84
+ },
85
+ };
86
+ },
87
+ });
@@ -0,0 +1,79 @@
1
+ import type { ESTree, SourceCode, Variable } from "@oxlint/plugins";
2
+ /** Resolve an identifier node to its binding by walking lexical scopes upward. */
3
+ export declare function resolveIdentifier(sourceCode: SourceCode, identifier: ESTree.Node & {
4
+ readonly name: string;
5
+ }): Variable | null;
6
+ /** Effect modules whose members the Effect rules recognize. */
7
+ export type EffectModule = "Context" | "Effect" | "HttpClient" | "Layer" | "ManagedRuntime" | "Schedule" | "Stream";
8
+ /** Local names bound to each Effect module by the file's imports. */
9
+ export type EffectModuleNames = ReadonlyMap<EffectModule, ReadonlySet<string>>;
10
+ /**
11
+ * Collect `import { Effect } from "effect"`, `import { HttpClient } from "effect/http"`,
12
+ * `import * as Effect from "effect/Effect"`, and `import * as HttpClient from "effect/http/HttpClient"` bindings.
13
+ */
14
+ export declare function collectEffectModuleNames(program: ESTree.Program): EffectModuleNames;
15
+ /** Strip parentheses, type assertions and instantiation expressions from an expression. */
16
+ export declare function unwrapExpression(expression: ESTree.Expression): ESTree.Expression;
17
+ /** Like {@link unwrapExpression}, for any node. */
18
+ export declare function unwrapNode(node: ESTree.Node): ESTree.Node;
19
+ /** The member name when `node` is `<module>.<member>` for one of the module's local names, else null. */
20
+ export declare function moduleMemberName(node: ESTree.Node | null | undefined, names: EffectModuleNames, module: EffectModule): string | null;
21
+ /** The member name when `node` is a call of `<module>.<member>(...)`, else null. */
22
+ export declare function moduleCallName(node: ESTree.Node | null | undefined, names: EffectModuleNames, module: EffectModule): string | null;
23
+ /** The parts of `class X extends Context.Service<...>()("key", options) {}`. */
24
+ export interface ServiceClass {
25
+ readonly node: ESTree.Class;
26
+ readonly name: string | null;
27
+ readonly options: ESTree.ObjectExpression | null;
28
+ }
29
+ /** Read a Context.Service class declaration, or null when the class is not one. */
30
+ export declare function serviceClass(node: ESTree.Class, names: EffectModuleNames): ServiceClass | null;
31
+ /** The innermost class whose body contains `node`, or null. */
32
+ export declare function enclosingClass(node: ESTree.Node): ESTree.Class | null;
33
+ /** The member name when `node` is `this.<member>` or `<ClassName>.<member>`, else null. */
34
+ export declare function classMemberName(node: ESTree.Node | null | undefined, service: ServiceClass): string | null;
35
+ /** The name of a non-computed property key, or null. */
36
+ export declare function keyName(key: ESTree.Node): string | null;
37
+ /** A static class property or method, with its name. */
38
+ export interface StaticMember {
39
+ readonly name: string;
40
+ readonly node: ESTree.PropertyDefinition | ESTree.MethodDefinition;
41
+ /** The property initializer or the method function. */
42
+ readonly value: ESTree.Expression | null;
43
+ }
44
+ /** Every non-computed static member of a class. */
45
+ export declare function staticMembers(node: ESTree.Class): readonly StaticMember[];
46
+ /** The expressions that construct the service: the options `make` and a static `make`. */
47
+ export declare function serviceMakes(service: ServiceClass): readonly ESTree.Expression[];
48
+ /** Whether the file is a `*.test.*` or `*.spec.*` file. */
49
+ export declare const isTestFile: (filename: string) => boolean;
50
+ /** Visit every descendant of `node`. Return false from `visit` to skip a node's children. */
51
+ export declare function walk(node: ESTree.Node, visit: (node: ESTree.Node) => boolean): void;
52
+ /** Whether any descendant of `node`, including itself, satisfies `predicate`. */
53
+ export declare function contains(node: ESTree.Node, predicate: (node: ESTree.Node) => boolean): boolean;
54
+ /** A function expression, arrow, or declaration. */
55
+ export type FunctionNode = ESTree.ArrowFunctionExpression | ESTree.Function;
56
+ /** Whether `node` is a function expression, arrow, or declaration. */
57
+ export declare const isFunction: (node: ESTree.Node | null | undefined) => node is FunctionNode;
58
+ /** The return statements of a function body, without descending into nested functions. */
59
+ export declare function ownReturns(body: ESTree.Node): readonly ESTree.ReturnStatement[];
60
+ /** The expressions a function produces: its expression body or the arguments of its own returns. */
61
+ export declare function returnedExpressions(fn: FunctionNode): readonly ESTree.Expression[];
62
+ /** For `x.pipe(...)`, the receiver `x`; otherwise null. */
63
+ export declare function pipeReceiver(node: ESTree.Node): ESTree.Expression | null;
64
+ /**
65
+ * The steps that run before `call` when it is an argument of a pipeline-like call such as `x.pipe(a, call)`,
66
+ * `pipe(x, a, call)`, or `Effect.fn("name")(body, a, call)`, including earlier `.pipe(...)` receivers.
67
+ */
68
+ export declare function precedingSteps(call: ESTree.Node): readonly ESTree.Node[];
69
+ /** The initializer of the single declarator an identifier resolves to, or the declared function. */
70
+ export declare function resolveInitializer(sourceCode: SourceCode, identifier: ESTree.Node & {
71
+ readonly name: string;
72
+ }): ESTree.Expression | ESTree.Function | null;
73
+ /** The generator passed to `Effect.gen(...)`, or null when `node` is not such a call. */
74
+ export declare function genFunction(node: ESTree.Node, names: EffectModuleNames): ESTree.Function | null;
75
+ /**
76
+ * The generator body that builds a service from a make expression: `Effect.gen(function* () {...})`, optionally
77
+ * followed by `.pipe(...)`, or an arrow that returns one.
78
+ */
79
+ export declare function makeGenerator(make: ESTree.Expression, names: EffectModuleNames): ESTree.Function | null;