@autotelic/plumb 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -46,6 +46,7 @@ import { requireExhaustiveTagSwitchRule } from "./rules/require-exhaustive-tag-s
46
46
  import { noMultipleFunctionParamsRule } from "./rules/no-multiple-function-params.js";
47
47
  import { noOptionalFunctionParametersRule } from "./rules/no-optional-function-parameters.js";
48
48
  import { noSingleUsePrivateFunctionsRule } from "./rules/no-single-use-private-functions.js";
49
+ import { noMutableEnvironmentCaptureRule } from "./rules/no-mutable-environment-capture.js";
49
50
  /** Generic Oxlint rules that reject low-evidence and low-signal implementation patterns. */
50
51
  const plumbPlugin = eslintCompatPlugin({
51
52
  meta: { name: "plumb" },
@@ -97,6 +98,7 @@ const plumbPlugin = eslintCompatPlugin({
97
98
  "no-multiple-function-params": noMultipleFunctionParamsRule,
98
99
  "no-optional-function-parameters": noOptionalFunctionParametersRule,
99
100
  "no-single-use-private-functions": noSingleUsePrivateFunctionsRule,
101
+ "no-mutable-environment-capture": noMutableEnvironmentCaptureRule,
100
102
  },
101
103
  });
102
104
  export default plumbPlugin;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * A function that reads or writes module state instead of taking it as a
3
+ * parameter is dishonest: its result depends on outside context, so it is not
4
+ * locally testable. Inject the value at the call site (the document's seed-the
5
+ * PRNG-once, pass-it-in pattern) so the dependency is explicit in the signature.
6
+ */
7
+ export declare const noMutableEnvironmentCaptureRule: import("@oxlint/plugins").Rule;
@@ -0,0 +1,134 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+ import { ancestorsOf } from "../shared/ancestors.js";
3
+ const TEST_FILE = /.(?:test|spec).[cm]?[jt]sx?$/u;
4
+ /**
5
+ * Whether the identifier sits inside a type annotation rather than a value position.
6
+ *
7
+ * @param {SourceCode} sourceCode - The rule's source-code accessor.
8
+ * @param {ESTree.Node} identifier - The reference identifier to test.
9
+ * @returns {boolean} True when an ancestor is a TypeScript type node.
10
+ */
11
+ function isTypePosition(sourceCode, identifier) {
12
+ for (const ancestor of ancestorsOf(sourceCode, identifier)) {
13
+ if (ancestor.type.startsWith("TS"))
14
+ return true;
15
+ }
16
+ return false;
17
+ }
18
+ /**
19
+ * The name a function is called by at its definition site.
20
+ *
21
+ * @param {ESTree.Node} node - The function-like node.
22
+ * @param {SourceCode} sourceCode - The rule's source-code accessor.
23
+ * @returns {string} The function's name, or "(anonymous)".
24
+ */
25
+ function functionName(node, sourceCode) {
26
+ if (node.type === "FunctionDeclaration" && node.id !== null)
27
+ return node.id.name;
28
+ const parent = ancestorsOf(sourceCode, node)[0];
29
+ if (parent !== undefined) {
30
+ if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier")
31
+ return parent.id.name;
32
+ if (parent.type === "AssignmentExpression" && parent.left.type === "Identifier")
33
+ return parent.left.name;
34
+ if (parent.type === "MethodDefinition" && parent.key.type === "Identifier")
35
+ return parent.key.name;
36
+ if (parent.type === "Property" && parent.key.type === "Identifier")
37
+ return parent.key.name;
38
+ if (parent.type === "ExportDefaultDeclaration")
39
+ return "default";
40
+ }
41
+ return "(anonymous)";
42
+ }
43
+ /**
44
+ * Collect module-scope let/var bindings, separating real state from
45
+ * function-valued helpers (which are legitimate module-private utilities).
46
+ *
47
+ * @param {ESTree.Program} program - The file's root node.
48
+ * @returns {ModuleState} Mutable state names and helper names.
49
+ */
50
+ function collectModuleState(program) {
51
+ const state = new Set();
52
+ const helpers = new Set();
53
+ for (const statement of program.body) {
54
+ const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
55
+ if (declaration === null || declaration === undefined)
56
+ continue;
57
+ if (declaration.type !== "VariableDeclaration")
58
+ continue;
59
+ if (declaration.kind !== "let" && declaration.kind !== "var")
60
+ continue;
61
+ for (const declarator of declaration.declarations) {
62
+ if (declarator.id.type !== "Identifier")
63
+ continue;
64
+ const init = declarator.init;
65
+ const isHelper = init !== null &&
66
+ init !== undefined &&
67
+ (init.type === "ArrowFunctionExpression" || init.type === "FunctionExpression");
68
+ (isHelper ? helpers : state).add(declarator.id.name);
69
+ }
70
+ }
71
+ return { state, helpers };
72
+ }
73
+ /**
74
+ * A function that reads or writes module state instead of taking it as a
75
+ * parameter is dishonest: its result depends on outside context, so it is not
76
+ * locally testable. Inject the value at the call site (the document's seed-the
77
+ * PRNG-once, pass-it-in pattern) so the dependency is explicit in the signature.
78
+ */
79
+ export const noMutableEnvironmentCaptureRule = defineRule({
80
+ meta: {
81
+ type: "problem",
82
+ docs: {
83
+ description: "Disallow functions that read or write module-scope mutable state (let/var) instead of receiving it as a parameter; hidden module state makes a function dishonest and not locally testable.",
84
+ },
85
+ messages: {
86
+ mutableModuleState: "Function `{{name}}` {{kind}} module-scope mutable state `{{binding}}` rather than receiving it as a parameter. Hidden module state makes the function dishonest: its result depends on outside context, so it is not locally testable. Inject `{{binding}}` at the call site or thread it through the signature so the dependency is explicit.",
87
+ },
88
+ },
89
+ createOnce(context) {
90
+ let moduleState = { state: new Set(), helpers: new Set() };
91
+ const check = (node) => {
92
+ if (node.type !== "FunctionDeclaration" &&
93
+ node.type !== "FunctionExpression" &&
94
+ node.type !== "ArrowFunctionExpression") {
95
+ return;
96
+ }
97
+ const scope = context.sourceCode.getScope(node);
98
+ const { state, helpers } = moduleState;
99
+ for (const reference of scope.references) {
100
+ const resolved = reference.resolved;
101
+ if (resolved === null || resolved === undefined)
102
+ continue;
103
+ const name = resolved.name;
104
+ if (helpers.has(name))
105
+ continue;
106
+ if (!state.has(name))
107
+ continue;
108
+ if (isTypePosition(context.sourceCode, reference.identifier))
109
+ continue;
110
+ context.report({
111
+ node: reference.identifier,
112
+ messageId: "mutableModuleState",
113
+ data: {
114
+ name: functionName(node, context.sourceCode),
115
+ kind: reference.isWrite() ? "writes" : "reads",
116
+ binding: name,
117
+ },
118
+ });
119
+ }
120
+ };
121
+ return {
122
+ before() {
123
+ if (TEST_FILE.test(context.filename.replaceAll("\\", "/")))
124
+ return false;
125
+ },
126
+ Program(node) {
127
+ moduleState = collectModuleState(node);
128
+ },
129
+ FunctionDeclaration: check,
130
+ FunctionExpression: check,
131
+ ArrowFunctionExpression: check,
132
+ };
133
+ },
134
+ });
@@ -1,6 +1,17 @@
1
- /** Top-level privates referenced exactly once are dead indirection; inline them at their single site.
1
+ import type { ESTree } from "@oxlint/plugins";
2
+ /**
3
+ * Whether a function is a pure alias: it returns a single call that forwards
4
+ * each of its parameters verbatim (a generator may delegate-yield such a call).
5
+ * Anything else raises the level of abstraction and earns its name.
2
6
  *
3
- * A leading JSDoc block marks the name as deliberately documented composition,
4
- * so such statements are exempt from the check.
7
+ * @param {ESTree.Node} fn - The function-like node to inspect.
8
+ * @returns {boolean} True when the function is dead indirection.
9
+ */
10
+ export declare function isTrivialForwarder(fn: ESTree.Node): boolean;
11
+ /**
12
+ * Top-level privates referenced exactly once are only worth inlining when they
13
+ * are pure aliases (they forward their inputs verbatim to another call). A
14
+ * single-use helper that earns its name by raising the level of abstraction is
15
+ * kept: the document argues for factoring proactively, even at n=1.
5
16
  */
6
17
  export declare const noSingleUsePrivateFunctionsRule: import("@oxlint/plugins").Rule;
@@ -27,10 +27,10 @@ function memberName(member) {
27
27
  }
28
28
  return null;
29
29
  }
30
- /** Whether the call resolves to `Effect.<method>` (one invocation wrapper allowed for `Effect.fn("N")(...)`).
30
+ /** Whether the call resolves to Effect.<method> (one invocation wrapper allowed for Effect.fn("N")(...)).
31
31
  *
32
32
  * @param {{ call: ESTree.Node; method: string }} payload - The candidate call and Effect method name.
33
- * @returns {boolean} True when the call targets `Effect.<method>`.
33
+ * @returns {boolean} True when the call targets Effect.<method>.
34
34
  */
35
35
  function isEffectMethodCall(payload) {
36
36
  let callee = payload.call;
@@ -111,7 +111,7 @@ function exportedNames(program) {
111
111
  }
112
112
  return names;
113
113
  }
114
- /** Reads inside type positions (`: T`, `as T`, generics) are not runtime reads.
114
+ /** Reads inside type positions (: T, as T, generics) are not runtime reads.
115
115
  *
116
116
  * @param {SourceCode} sourceCode - The rule's source-code accessor.
117
117
  * @param {ESTree.Node} identifier - The identifier reference being counted.
@@ -188,26 +188,150 @@ function useCount(payload) {
188
188
  *
189
189
  * @param {{ sourceCode: SourceCode; node: ESTree.Node; name: string }} payload - Lookup inputs.
190
190
  * @returns {DeclaredVariable | undefined} The matching record, if any.
191
+ * For a VariableDeclarator the binding lives on its parent VariableDeclaration, so the declarator is unwrapped first.
191
192
  */
192
193
  function declaredVariablesOf(payload) {
193
- return payload.sourceCode.getDeclaredVariables(payload.node).find((variable) => variable.name === payload.name);
194
+ const node = payload.node.type === "VariableDeclarator"
195
+ ? (ancestorsOf(payload.sourceCode, payload.node).find((ancestor) => ancestor.type === "VariableDeclaration") ?? payload.node)
196
+ : payload.node;
197
+ return payload.sourceCode.getDeclaredVariables(node).find((variable) => variable.name === payload.name);
194
198
  }
195
- /** Top-level privates referenced exactly once are dead indirection; inline them at their single site.
199
+ /** Extract the handler function nested inside an Effect initializer (Effect.fn / Effect.gen).
196
200
  *
197
- * A leading JSDoc block marks the name as deliberately documented composition,
198
- * so such statements are exempt from the check.
201
+ * @param {ESTree.Node | null | undefined} init - The candidate's initializer expression.
202
+ * @returns {ESTree.Node | null} The handler function node, or null when absent.
203
+ */
204
+ function effectHandler(init) {
205
+ if (init === null || init === undefined || init.type !== "CallExpression")
206
+ return null;
207
+ let handler = null;
208
+ for (const arg of init.arguments) {
209
+ if (arg.type === "FunctionExpression" ||
210
+ arg.type === "ArrowFunctionExpression" ||
211
+ arg.type === "FunctionDeclaration") {
212
+ handler = arg;
213
+ }
214
+ }
215
+ return handler;
216
+ }
217
+ /** Simple identifier parameter names, or null when any parameter is a pattern.
218
+ *
219
+ * @param {ESTree.Node} fn - The function-like node to inspect.
220
+ * @returns {Set<string> | null} The parameter names, or null for non-functions/patterns.
221
+ */
222
+ function paramNames(fn) {
223
+ if (fn.type !== "FunctionDeclaration" &&
224
+ fn.type !== "FunctionExpression" &&
225
+ fn.type !== "ArrowFunctionExpression") {
226
+ return null;
227
+ }
228
+ const names = new Set();
229
+ for (const param of fn.params) {
230
+ if (param.type !== "Identifier")
231
+ return null;
232
+ names.add(param.name);
233
+ }
234
+ return names;
235
+ }
236
+ /**
237
+ * Whether a function is a pure alias: it returns a single call that forwards
238
+ * each of its parameters verbatim (a generator may delegate-yield such a call).
239
+ * Anything else raises the level of abstraction and earns its name.
240
+ *
241
+ * @param {ESTree.Node} fn - The function-like node to inspect.
242
+ * @returns {boolean} True when the function is dead indirection.
243
+ */
244
+ export function isTrivialForwarder(fn) {
245
+ if (fn.type !== "FunctionDeclaration" &&
246
+ fn.type !== "FunctionExpression" &&
247
+ fn.type !== "ArrowFunctionExpression") {
248
+ return false;
249
+ }
250
+ const names = paramNames(fn);
251
+ if (names === null || names.size === 0)
252
+ return false;
253
+ let call = null;
254
+ if (fn.body !== null && fn.body.type === "BlockStatement") {
255
+ const statements = fn.body.body;
256
+ const statement = statements[0];
257
+ if (statement !== undefined && statement.type === "ReturnStatement") {
258
+ const argument = statement.argument;
259
+ if (argument !== null && argument !== undefined && argument.type === "CallExpression") {
260
+ call = argument;
261
+ }
262
+ else if (argument !== null &&
263
+ argument !== undefined &&
264
+ argument.type === "YieldExpression" &&
265
+ argument.delegate === true &&
266
+ argument.argument !== null &&
267
+ argument.argument !== undefined &&
268
+ argument.argument.type === "CallExpression") {
269
+ call = argument.argument;
270
+ }
271
+ }
272
+ }
273
+ else if (fn.type === "ArrowFunctionExpression" && fn.body !== null && fn.body.type === "CallExpression") {
274
+ call = fn.body;
275
+ }
276
+ if (call === null)
277
+ return false;
278
+ const seen = new Set();
279
+ for (const arg of call.arguments) {
280
+ if (arg.type !== "Identifier")
281
+ return false;
282
+ if (!names.has(arg.name) || seen.has(arg.name))
283
+ return false;
284
+ seen.add(arg.name);
285
+ }
286
+ return seen.size === names.size;
287
+ }
288
+ /**
289
+ * Whether a single-use candidate is dead indirection worth inlining: a pure
290
+ * alias that forwards its inputs verbatim. Substantial single-use helpers that
291
+ * raise the level of abstraction are kept (the document's "factor at n=1").
292
+ *
293
+ * @param {SourceCode} sourceCode - The rule's source-code accessor.
294
+ * @param {Candidate} candidate - The candidate to grade.
295
+ * @returns {boolean} True when the candidate is a pure alias.
296
+ */
297
+ function isDeadIndirection(sourceCode, candidate) {
298
+ if (candidate.kind === "type")
299
+ return false;
300
+ let fn = null;
301
+ if (candidate.kind === "function") {
302
+ const node = candidate.node;
303
+ if (node.type === "FunctionDeclaration") {
304
+ fn = node;
305
+ }
306
+ else if (node.type === "VariableDeclarator") {
307
+ fn = node.init ?? null;
308
+ }
309
+ }
310
+ else {
311
+ const node = candidate.node;
312
+ fn = node.type === "VariableDeclarator" ? effectHandler(node.init) : null;
313
+ }
314
+ if (fn === null)
315
+ return false;
316
+ return isTrivialForwarder(fn);
317
+ }
318
+ /**
319
+ * Top-level privates referenced exactly once are only worth inlining when they
320
+ * are pure aliases (they forward their inputs verbatim to another call). A
321
+ * single-use helper that earns its name by raising the level of abstraction is
322
+ * kept: the document argues for factoring proactively, even at n=1.
199
323
  */
200
324
  export const noSingleUsePrivateFunctionsRule = defineRule({
201
325
  meta: {
202
326
  type: "suggestion",
203
327
  docs: {
204
- description: "Inline private top-level functions, Effect values, and types that are referenced exactly once; single-use indirection hides shape without earning a name.",
328
+ description: "Inline private top-level functions and Effect values that are referenced exactly once as a pure alias (they forward their inputs verbatim to another call); single-use indirection that adds no abstraction hides shape. Single-use helpers that raise the level of abstraction earn their name and are kept.",
205
329
  },
206
330
  messages: {
207
- singleUseFunction: "Private function `{{name}}` is read exactly once. Inline it at that use site instead of naming an indirection.",
208
- singleUseEffectFunction: "Private Effect function `{{name}}` is run exactly once. Inline the handler at its single use site.",
209
- singleUseEffectProgram: "Private Effect program `{{name}}` is composed into exactly one pipeline. Inline it there instead of naming an indirection.",
210
- singleUseType: "Private type `{{name}}` is referenced exactly once. Inline the annotation at that use site instead of naming it.",
331
+ singleUseFunction: "Private function {{name}} is a single-use pure alias: it forwards its inputs verbatim to another call. Inline the forwarded call at its use site instead of naming zero-abstraction indirection.",
332
+ singleUseEffectFunction: "Private Effect function {{name}} is run exactly once as a pure alias. Inline the forwarded handler at its single use site instead of naming zero-abstraction indirection.",
333
+ singleUseEffectProgram: "Private Effect program {{name}} is composed into exactly one pipeline as a pure alias. Inline it there instead of naming zero-abstraction indirection.",
334
+ singleUseType: "Private type {{name}} is referenced exactly once. Inline the annotation at that use site instead of naming it.",
211
335
  },
212
336
  },
213
337
  createOnce(context) {
@@ -264,12 +388,10 @@ export const noSingleUsePrivateFunctionsRule = defineRule({
264
388
  if (candidateKind === null)
265
389
  continue;
266
390
  const chain = ancestorsOf(sourceCode, declarator);
267
- const parent = chain[0];
268
- const grandparent = chain[1];
269
- if (parent === undefined ||
270
- grandparent === undefined ||
271
- parent.type !== "VariableDeclaration" ||
272
- grandparent.type !== "Program") {
391
+ const parentIndex = chain.findIndex((ancestor) => ancestor.type === "VariableDeclaration");
392
+ const parent = parentIndex >= 0 ? chain[parentIndex] : undefined;
393
+ const grandparent = parentIndex > 0 ? chain[parentIndex - 1] : chain[parentIndex + 1];
394
+ if (parent === undefined || grandparent === undefined || grandparent.type !== "Program") {
273
395
  continue;
274
396
  }
275
397
  if (exported.has(name) || isPascalCase(name))
@@ -283,6 +405,8 @@ export const noSingleUsePrivateFunctionsRule = defineRule({
283
405
  for (const candidate of candidates) {
284
406
  if (useCount({ sourceCode, candidate }) !== 1)
285
407
  continue;
408
+ if (!isDeadIndirection(sourceCode, candidate))
409
+ continue;
286
410
  context.report({
287
411
  node: candidate.node,
288
412
  messageId: MESSAGE_BY_KIND[candidate.kind],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autotelic/plumb",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "description": "Opinionated Oxlint rules that keep TypeScript true: generic and Effect-specific patterns, maintained as one source of truth for the autotelic repos.",
5
5
  "license": "MIT",
6
6
  "files": [