eslint-plugin-functype 2.126.1 → 2.127.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/README.md CHANGED
@@ -163,7 +163,7 @@ Prefer either tool to `eslint-disable`. A disable covers a whole file or line an
163
163
 
164
164
  Also skipped: `as const` and other tuple assertions, tuple rest elements (`[string, ...string[]]`), rest parameters (`...args: T[]`), literals passed straight into `List(…)` / `Set(…)`, and files marked generated (`@generated`, "auto-generated", "DO NOT EDIT"). Generators with no marker, such as Supabase's types, need an `ignores` entry. Anything still reported that is a deliberate host shape gets `Wire<…>`.
165
165
 
166
- Measured on five consumers (2026-10-10), with type-aware linting: **2,000 hits under 2.114, 696 after.** By repo, before → after: CivalaOS 821 → 215, agent-todo 843 → 328, dokploy-mcp-server 170 → 68, ts-builds 111 → 43, supabase-typed-query 55 → 42. Known false positives left: 25 hits in agent-todo's unmarked Supabase types (an `ignores` entry), one nested ReactFlow return type (`Wire`), one AWS SES request built in an untyped object. Linting all of CivalaOS with the rule on takes about 18 seconds.
166
+ Measured on five consumers (2026-10-10), with type-aware linting: **2,000 hits under 2.114, 696 after.** By repo, before → after: a private app monorepo 821 → 215, agent-todo 843 → 328, dokploy-mcp-server 170 → 68, ts-builds 111 → 43, supabase-typed-query 55 → 42. Known false positives left: 25 hits in agent-todo's unmarked Supabase types (an `ignores` entry), one nested ReactFlow return type (`Wire`), one AWS SES request built in an untyped object. Linting all of that monorepo with the rule on takes about 18 seconds.
167
167
 
168
168
  **Boundary recipe (recommended for codebases touching serialization boundaries):**
169
169
 
@@ -236,7 +236,7 @@ void save(user) // fine: a deliberate drop
236
236
 
237
237
  **It only runs with type-aware linting** (`parserOptions.projectService`). It recognizes `IO` by its type (it has `runExit` and `provideLayer`), whatever the call is named. Without type information it reports nothing.
238
238
 
239
- Measured (2026-10-16) on functype's own source and tests, functype-log, functype-react, agent-todo's agent-gate-api and civala.ai's API: 0 false positives across about 1,340 IO-typed calls. The only hits were four deliberate drops in type-only tests. It's `off` in `recommended` and `warn` in `strict` while it is measured further.
239
+ Measured (2026-10-16) on functype's own source and tests, functype-log, functype-react, agent-todo's agent-gate-api and a private web app's API: 0 false positives across about 1,340 IO-typed calls. The only hits were four deliberate drops in type-only tests. It's `off` in `recommended` and `warn` in `strict` while it is measured further.
240
240
 
241
241
  ### `functype/no-floating-result`
242
242
 
@@ -367,7 +367,7 @@ A ternary or an if/else on a predicate is `prefer-fold`'s, everywhere, so this r
367
367
  | -------------------- | :-----: | ---------------------------------------------------------- |
368
368
  | `allowInteropMarker` | `true` | Skip code inside a declaration tagged `@interop <reason>`. |
369
369
 
370
- Measured (2026-10-25) with both rules on functype-react's source and tests (type-aware), and on agent-todo, mnemons and civala.ai (1,403 files, without type information): no reports. None of that code uses these shapes in a component, and `useIOValue`'s `exit.orThrow()` is guarded by `exit.isSuccess()`, so the measurement shows the false-positive rate, not the hit rate.
370
+ Measured (2026-10-25) with both rules on functype-react's source and tests (type-aware), and on agent-todo, mnemons and a private web app (1,403 files, without type information): no reports. None of that code uses these shapes in a component, and `useIOValue`'s `exit.orThrow()` is guarded by `exit.isSuccess()`, so the measurement shows the false-positive rate, not the hit rate.
371
371
 
372
372
  ### `functype/no-get-unsafe`
373
373
 
@@ -413,7 +413,7 @@ if (t.isFailure()) {
413
413
 
414
414
  Pass-through guards are the clear case: they are hand-written `flatMap`. Fallback and other-work-first guards are closer to a style choice, since TypeScript narrows `Either` after the guard (Rust's `let-else` and Swift's `guard let` make the same trade). For `Option` and `Try` the guard doesn't narrow `.value`, so the case is stronger there. That split is why this is planned for `strict`, not `recommended`, in 2.0.
415
415
 
416
- When the code after the guard awaits, the advice uses `flatMapAsync` / `foldAsync`. Declarations tagged `@interop <reason>` are skipped. On CivalaOS it finds 75 guards, all of this shape.
416
+ When the code after the guard awaits, the advice uses `flatMapAsync` / `foldAsync`. Declarations tagged `@interop <reason>` are skipped. On a private app monorepo it finds 75 guards, all of this shape.
417
417
 
418
418
  ### `functype/prefer-option`
419
419
 
@@ -3,7 +3,7 @@
3
3
  * Severity policy (#325): a rule is `error` once it is right on ~95–99% of real code and its known
4
4
  * false-positive classes are closed; it stays `warn` only while those classes are still open. FP here
5
5
  * is governance — a rule that is reliably right should fail the build, not print advice nobody reads
6
- * (CivalaOS shipped 85 new violations under "lint OK" because every rule but `no-let` warned).
6
+ * (a private app monorepo shipped 85 new violations under "lint OK" because every rule but `no-let` warned).
7
7
  *
8
8
  * Still `warn`, and why:
9
9
  * - prefer-option / prefer-either / prefer-try: fire on correct code at serialization boundaries
@@ -13,7 +13,7 @@
13
13
  *
14
14
  * Graduated with a precision condition: prefer-fold checks functype predicate calls (`isSome()`,
15
15
  * `isLeft()`) only; its null-check heuristic is opt-in (`checkNullable`) because it fired on plain
16
- * nullables — 31 of 31 hits in CivalaOS. prefer-map leaves loops to no-imperative-loops (`checkForLoops`
16
+ * nullables — 31 of 31 hits in a private app monorepo. prefer-map leaves loops to no-imperative-loops (`checkForLoops`
17
17
  * off), so one loop is one error.
18
18
  *
19
19
  * collection-naming is a convention, not a heuristic — functype's Map/Set imported under their own names,
@@ -1 +1 @@
1
- {"version":3,"file":"recommended.js","names":["recommendedRules"],"sources":["../../src/configs/recommended.ts"],"sourcesContent":["/**\n * Severity policy (#325): a rule is `error` once it is right on ~95–99% of real code and its known\n * false-positive classes are closed; it stays `warn` only while those classes are still open. FP here\n * is governance — a rule that is reliably right should fail the build, not print advice nobody reads\n * (CivalaOS shipped 85 new violations under \"lint OK\" because every rule but `no-let` warned).\n *\n * Still `warn`, and why:\n * - prefer-option / prefer-either / prefer-try: fire on correct code at serialization boundaries\n * (JSON rows, DTOs) and on throws that are correct (bug checks, host contracts). Wire<T> (#325 B),\n * invariant() and @interop (#342) close those; graduating them is a measured decision.\n * - prefer-flatmap / prefer-do-notation: heuristics without type information; precision unmeasured.\n *\n * Graduated with a precision condition: prefer-fold checks functype predicate calls (`isSome()`,\n * `isLeft()`) only; its null-check heuristic is opt-in (`checkNullable`) because it fired on plain\n * nullables — 31 of 31 hits in CivalaOS. prefer-map leaves loops to no-imperative-loops (`checkForLoops`\n * off), so one loop is one error.\n *\n * collection-naming is a convention, not a heuristic — functype's Map/Set imported under their own names,\n * the built-in spelled globalThis.Map — so it has no false-positive class and starts at error.\n *\n * no-array-mutation is off here only because turning a new error on in a 1.x minor would fail consumers'\n * builds on upgrade (91 hits across five consumers, every one a real in-place mutation). It's `error` in\n * strict, and planned for `error` here in 2.0. It is type-aware: without type information it reports nothing.\n *\n * no-floating-io (1.17) is off here and `warn` in strict while it is measured: 0 false positives across\n * ~1,340 IO-typed calls in five codebases, but no real hits yet either. 2.0 decides `recommended` after\n * measuring it against functype-os, whose async methods return IO there. Type-aware, like no-array-mutation.\n *\n * no-floating-result (1.23) is off here and `error` in strict: a dropped Either or Try is a defect, not a\n * style, and on agent-todo's API it found the 20 drops that project fixed by hand as real bugs. Turning a\n * new error on here would fail consumers' builds on a 1.x minor, so it moves to `error` here in 2.0. Type-aware.\n *\n * no-serialize-container (1.23) is off here and `error` in strict, for the same reason: a container sent\n * to `c.json()` or `JSON.stringify()` is a defect, and turning a new error on here would fail consumers'\n * builds on a 1.x minor. It moves to `error` here in 2.0. Type-aware.\n *\n * no-getOrThrow-in-render and must-fold-on-component-return are React rules: they fire only inside a\n * component (a PascalCase function with JSX) or a hook (`use*`), so non-React code rarely trips them (a\n * non-React function named `use*` is read as a hook). Both are new and unmeasured on real React code, so\n * they start where no-floating-io did: off here, `warn` in strict. They work without type information and\n * are more precise with it.\n */\nconst recommendedRules = {\n \"functype/no-let\": \"error\",\n \"functype/no-imperative-loops\": \"error\",\n \"functype/prefer-functype-map\": \"error\",\n \"functype/prefer-functype-set\": \"error\",\n \"functype/prefer-map\": \"error\",\n \"functype/prefer-fold\": \"error\",\n \"functype/collection-naming\": \"error\",\n \"functype/prefer-option\": \"warn\",\n \"functype/prefer-either\": \"warn\",\n \"functype/prefer-try\": \"warn\",\n \"functype/prefer-flatmap\": \"warn\",\n \"functype/prefer-do-notation\": \"warn\",\n \"functype/no-get-unsafe\": \"off\",\n \"functype/prefer-list\": \"off\",\n \"functype/no-array-mutation\": \"off\",\n \"functype/no-floating-io\": \"off\",\n \"functype/no-floating-result\": \"off\",\n \"functype/no-serialize-container\": \"off\",\n \"functype/no-getOrThrow-in-render\": \"off\",\n \"functype/must-fold-on-component-return\": \"off\",\n}\n\nexport default recommendedRules\n"],"mappings":"AA0CA,MAAMA,EAAmB,CACvB,kBAAmB,QACnB,+BAAgC,QAChC,+BAAgC,QAChC,+BAAgC,QAChC,sBAAuB,QACvB,uBAAwB,QACxB,6BAA8B,QAC9B,yBAA0B,OAC1B,yBAA0B,OAC1B,sBAAuB,OACvB,0BAA2B,OAC3B,8BAA+B,OAC/B,yBAA0B,MAC1B,uBAAwB,MACxB,6BAA8B,MAC9B,0BAA2B,MAC3B,8BAA+B,MAC/B,kCAAmC,MACnC,mCAAoC,MACpC,yCAA0C,KAC5C"}
1
+ {"version":3,"file":"recommended.js","names":["recommendedRules"],"sources":["../../src/configs/recommended.ts"],"sourcesContent":["/**\n * Severity policy (#325): a rule is `error` once it is right on ~95–99% of real code and its known\n * false-positive classes are closed; it stays `warn` only while those classes are still open. FP here\n * is governance — a rule that is reliably right should fail the build, not print advice nobody reads\n * (a private app monorepo shipped 85 new violations under \"lint OK\" because every rule but `no-let` warned).\n *\n * Still `warn`, and why:\n * - prefer-option / prefer-either / prefer-try: fire on correct code at serialization boundaries\n * (JSON rows, DTOs) and on throws that are correct (bug checks, host contracts). Wire<T> (#325 B),\n * invariant() and @interop (#342) close those; graduating them is a measured decision.\n * - prefer-flatmap / prefer-do-notation: heuristics without type information; precision unmeasured.\n *\n * Graduated with a precision condition: prefer-fold checks functype predicate calls (`isSome()`,\n * `isLeft()`) only; its null-check heuristic is opt-in (`checkNullable`) because it fired on plain\n * nullables — 31 of 31 hits in a private app monorepo. prefer-map leaves loops to no-imperative-loops (`checkForLoops`\n * off), so one loop is one error.\n *\n * collection-naming is a convention, not a heuristic — functype's Map/Set imported under their own names,\n * the built-in spelled globalThis.Map — so it has no false-positive class and starts at error.\n *\n * no-array-mutation is off here only because turning a new error on in a 1.x minor would fail consumers'\n * builds on upgrade (91 hits across five consumers, every one a real in-place mutation). It's `error` in\n * strict, and planned for `error` here in 2.0. It is type-aware: without type information it reports nothing.\n *\n * no-floating-io (1.17) is off here and `warn` in strict while it is measured: 0 false positives across\n * ~1,340 IO-typed calls in five codebases, but no real hits yet either. 2.0 decides `recommended` after\n * measuring it against functype-os, whose async methods return IO there. Type-aware, like no-array-mutation.\n *\n * no-floating-result (1.23) is off here and `error` in strict: a dropped Either or Try is a defect, not a\n * style, and on agent-todo's API it found the 20 drops that project fixed by hand as real bugs. Turning a\n * new error on here would fail consumers' builds on a 1.x minor, so it moves to `error` here in 2.0. Type-aware.\n *\n * no-serialize-container (1.23) is off here and `error` in strict, for the same reason: a container sent\n * to `c.json()` or `JSON.stringify()` is a defect, and turning a new error on here would fail consumers'\n * builds on a 1.x minor. It moves to `error` here in 2.0. Type-aware.\n *\n * no-getOrThrow-in-render and must-fold-on-component-return are React rules: they fire only inside a\n * component (a PascalCase function with JSX) or a hook (`use*`), so non-React code rarely trips them (a\n * non-React function named `use*` is read as a hook). Both are new and unmeasured on real React code, so\n * they start where no-floating-io did: off here, `warn` in strict. They work without type information and\n * are more precise with it.\n */\nconst recommendedRules = {\n \"functype/no-let\": \"error\",\n \"functype/no-imperative-loops\": \"error\",\n \"functype/prefer-functype-map\": \"error\",\n \"functype/prefer-functype-set\": \"error\",\n \"functype/prefer-map\": \"error\",\n \"functype/prefer-fold\": \"error\",\n \"functype/collection-naming\": \"error\",\n \"functype/prefer-option\": \"warn\",\n \"functype/prefer-either\": \"warn\",\n \"functype/prefer-try\": \"warn\",\n \"functype/prefer-flatmap\": \"warn\",\n \"functype/prefer-do-notation\": \"warn\",\n \"functype/no-get-unsafe\": \"off\",\n \"functype/prefer-list\": \"off\",\n \"functype/no-array-mutation\": \"off\",\n \"functype/no-floating-io\": \"off\",\n \"functype/no-floating-result\": \"off\",\n \"functype/no-serialize-container\": \"off\",\n \"functype/no-getOrThrow-in-render\": \"off\",\n \"functype/must-fold-on-component-return\": \"off\",\n}\n\nexport default recommendedRules\n"],"mappings":"AA0CA,MAAMA,EAAmB,CACvB,kBAAmB,QACnB,+BAAgC,QAChC,+BAAgC,QAChC,+BAAgC,QAChC,sBAAuB,QACvB,uBAAwB,QACxB,6BAA8B,QAC9B,yBAA0B,OAC1B,yBAA0B,OAC1B,sBAAuB,OACvB,0BAA2B,OAC3B,8BAA+B,OAC/B,yBAA0B,MAC1B,uBAAwB,MACxB,6BAA8B,MAC9B,0BAA2B,MAC3B,8BAA+B,MAC/B,kCAAmC,MACnC,mCAAoC,MACpC,yCAA0C,KAC5C"}
@@ -1 +1 @@
1
- {"version":3,"file":"prefer-fold.js","names":["FAILURE_SIDE","SUCCESS_METHODS","SUCCESS_MEMBER","isNullishLiteral","node","extractMonadicTest","test","methodName","obj","sourceCode","failure","POSITIVE_PREDICATES","NEGATIVE_PREDICATES","SUCCESS_READS","receiverReads","isReceiver","target","compact","receiver","isMember","names","visit","parent","isCalled","isWritten","reads","childNodes","branch","freshName","isTaken","branches","name","b","base","i","asArrowBody","text","foldCallback","ranges","offset","rewritten","a","start","end","acc","param","buildFold","failureNode","successNode","onSuccess","returnedExpression","statement","ifElseChainLength","FAILURE_CONSTRUCTORS","readsMember","descendants","n","member","guardExitStatement","consequent","last","classifyGuardExit","found","argument","callee","calleeName","args","failureMember","unwrapsReceiver","nodes","statements","guardOf","extracted","rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","minComplexity","checkNullable","checkGuards","SEQUENCE_ADVICE","isAsync","GUARD_ADVICE","r","checkGuard","block","body","after","exit","containsAwait","sequenced","other","candidate","otherReceiver","otherAfter","kind","generateFoldFromIf","thenExpr","elseExpr","kept","c","failureExpr","successExpr","isNegated","ternarySuggestions","failureText","successText","fixer","fold","isFunctypePredicateCall","isMonadicCheck","leftIsUndefined","rightIsUndefined","suggestionsForIf","replacement","analyzeIfStatement","monadicInfo"],"sources":["../../src/rules/prefer-fold.ts"],"sourcesContent":["import type { Rule, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { childNodes, descendants } from \"../utils/ast-walk\"\nimport { containsAwait } from \"../utils/async-detection\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { compact, NEGATIVE_PREDICATES, POSITIVE_PREDICATES } from \"../utils/functype-predicates\"\n\n/**\n * How each container's fold exposes its failure side. `fold(onFailure, onSuccess)` everywhere, but\n * only Either and Try hand the failure callback a value — Option's `onNone` takes nothing. `member`\n * is the property a narrowed branch reads that value through (`e.value` after `isLeft()`,\n * `t.error` after `isFailure()`).\n */\ntype FailureSide = { readonly param: string; readonly member: string } | null\n\nconst FAILURE_SIDE: Readonly<Record<string, FailureSide>> = {\n isSome: null,\n isNone: null,\n isRight: { param: \"left\", member: \"value\" },\n isLeft: { param: \"left\", member: \"value\" },\n isSuccess: { param: \"error\", member: \"error\" },\n isFailure: { param: \"error\", member: \"error\" },\n}\n\n/** Reads of the success value that the fold's success parameter replaces. */\nconst SUCCESS_METHODS = [\"get\", \"orThrow\"]\nconst SUCCESS_MEMBER = \"value\"\n\n/**\n * A literal `null` or the `undefined` identifier. A ternary that yields one of these in a branch is\n * building an optional value (prefer-option's concern), not folding a monad — so the untyped nullable\n * heuristic must not treat `x !== undefined ? \"a\" : undefined` as a fold candidate.\n */\nfunction isNullishLiteral(node: ASTNode): boolean {\n return (node.type === \"Literal\" && node.value === null) || (node.type === \"Identifier\" && node.name === \"undefined\")\n}\n\n/**\n * If `test` is a monadic predicate call like `option.isSome()` or\n * `either.isLeft()`, returns the receiver expression's text plus whether the\n * predicate is the \"absence\" side. Returns null for anything else.\n */\nfunction extractMonadicTest(\n test: ASTNode,\n sourceCode: SourceCode,\n): { obj: string; isNegated: boolean; failure: FailureSide } | null {\n if (test.type !== \"CallExpression\" || test.callee.type !== \"MemberExpression\") return null\n const methodName = test.callee.property.name\n const obj = sourceCode.getText(test.callee.object)\n const failure = FAILURE_SIDE[methodName] ?? null\n if (POSITIVE_PREDICATES.has(methodName)) return { obj, isNegated: false, failure }\n if (NEGATIVE_PREDICATES.has(methodName)) return { obj, isNegated: true, failure }\n return null\n}\n\n/** Which reads of the narrowed receiver a fold parameter replaces. */\ntype Reads = { readonly members: ReadonlyArray<string>; readonly methods: ReadonlyArray<string> }\n\nconst SUCCESS_READS: Reads = { members: [SUCCESS_MEMBER], methods: SUCCESS_METHODS }\n\n/**\n * Source ranges inside `branch` that read the narrowed receiver: `e.value`, `e!.value`, `e?.value`,\n * `e.orThrow()`. Driven by the AST rather than the text, so a read never matches inside a string or\n * template literal, a comment, a longer name, or another object's member (`other.e.value`). A member\n * that is called (`e.value()`) or assigned (`e.value = 3`) is not a read.\n */\nfunction receiverReads(\n branch: ASTNode,\n receiver: string,\n reads: Reads,\n sourceCode: SourceCode,\n): ReadonlyArray<readonly [number, number]> {\n const isReceiver = (node: ASTNode): boolean => {\n const target = node.type === \"TSNonNullExpression\" ? node.expression : node\n return compact(sourceCode.getText(target)) === compact(receiver)\n }\n const isMember = (node: ASTNode, names: ReadonlyArray<string>): boolean =>\n node.type === \"MemberExpression\" &&\n !node.computed &&\n node.property.type === \"Identifier\" &&\n names.includes(node.property.name) &&\n isReceiver(node.object)\n\n const visit = (node: ASTNode): ReadonlyArray<readonly [number, number]> => {\n const parent = node.parent\n const isCalled = parent?.type === \"CallExpression\" && parent.callee === node\n const isWritten =\n (parent?.type === \"AssignmentExpression\" && parent.left === node) || parent?.type === \"UpdateExpression\"\n if (isMember(node, reads.members) && !isCalled && !isWritten) return [node.range]\n if (node.type === \"CallExpression\" && node.arguments.length === 0 && isMember(node.callee, reads.methods)) {\n return [node.range]\n }\n return childNodes(node).flatMap(visit)\n }\n return visit(branch)\n}\n\n/** A parameter name no branch already uses, so the fold never shadows a captured identifier. */\nconst freshName = (base: string, branches: ReadonlyArray<string>): string => {\n // `(?<![\\\\w$.])`: a property access (`e.value`) is not a free identifier, so it cannot be shadowed.\n const isTaken = (name: string): boolean => branches.some((b) => new RegExp(`(?<![\\\\w$.])${name}(?![\\\\w$])`).test(b))\n const candidates = [base, ...Array.from({ length: 20 }, (_, i) => `${base}${i + 1}`)]\n return candidates.find((name) => !isTaken(name)) ?? `${base}_`\n}\n\n/**\n * An arrow body must not start with `{` (it would parse as a block) and a comma expression must stay\n * one argument, so those two shapes are parenthesized. ESTree ranges exclude the source's own parens.\n */\nconst asArrowBody = (node: ASTNode, text: string): string =>\n node.type === \"ObjectExpression\" || node.type === \"SequenceExpression\" ? `(${text})` : text\n\n/**\n * One fold callback. Reads of the narrowed receiver become reads of the callback's parameter — the\n * receiver is NOT narrowed inside the callback, so leaving `e.value` there is a type error (#323).\n * A branch that never reads the value gets a parameterless callback, not an unused parameter.\n */\nfunction foldCallback(\n branch: ASTNode,\n receiver: string,\n reads: Reads | null,\n param: string,\n sourceCode: SourceCode,\n): string {\n const text = sourceCode.getText(branch)\n const ranges = reads === null ? [] : receiverReads(branch, receiver, reads, sourceCode)\n if (ranges.length === 0) return `() => ${asArrowBody(branch, text)}`\n const offset = branch.range[0]\n // Replace right-to-left so earlier offsets stay valid.\n const rewritten = [...ranges]\n .sort((a, b) => b[0] - a[0])\n .reduce((acc, [start, end]) => acc.slice(0, start - offset) + param + acc.slice(end - offset), text)\n return `(${param}) => ${asArrowBody(branch, rewritten)}`\n}\n\n/** `receiver.fold(onFailure, onSuccess)` from the two branch nodes. */\nfunction buildFold(\n receiver: string,\n failure: FailureSide,\n failureNode: ASTNode,\n successNode: ASTNode,\n sourceCode: SourceCode,\n): string {\n const branches = [sourceCode.getText(failureNode), sourceCode.getText(successNode)]\n const onSuccess = foldCallback(successNode, receiver, SUCCESS_READS, freshName(\"value\", branches), sourceCode)\n const onFailure =\n failure === null\n ? foldCallback(failureNode, receiver, null, \"\", sourceCode)\n : foldCallback(\n failureNode,\n receiver,\n { members: [failure.member], methods: [] },\n freshName(failure.param, branches),\n sourceCode,\n )\n return `${receiver}.fold(${onFailure}, ${onSuccess})`\n}\n\n/** The returned expression of a `return x` statement or a `{ return x }` block; null for anything else. */\nfunction returnedExpression(node: ASTNode): ASTNode | null {\n const statement = node.type === \"BlockStatement\" && node.body.length === 1 ? node.body[0] : node\n return statement.type === \"ReturnStatement\" && statement.argument ? statement.argument : null\n}\n\n/**\n * Length of an if/else-if/else chain rooted at `node`. Counts the root as 1\n * and adds 1 per linked alternate IfStatement. Terminates on a non-If\n * alternate (the final `else { ... }`) which counts as the last branch.\n */\nfunction ifElseChainLength(node: ASTNode): number {\n if (!node.alternate) return 1\n if (node.alternate.type === \"IfStatement\") return 1 + ifElseChainLength(node.alternate as ASTNode)\n return 2 // root + the terminal else\n}\n\n/**\n * What a guard's early exit does, which decides the advice:\n * - `passthrough`: hands the failure back unchanged (`return e`, `return Left(e.value)`, `return None()`),\n * so the rest of the function is a `flatMap`/`map`.\n * - `mappedFailure`: returns a new failure built from the old one (`return Left({ kind: e.value.kind })`),\n * so it's `mapLeft(…)` then `flatMap`.\n * - `default`: returns a plain fallback, so it's `map(…).orElse(fallback)` or a `fold`.\n * - `throw`: a host that needs a throw, so it's `orThrow((e) => …)`.\n * - `effect`: does other work first (logging, setting state), so it's a `fold`.\n */\ntype GuardExit = \"passthrough\" | \"mappedFailure\" | \"default\" | \"throw\" | \"effect\"\n\n/** Constructors (and companion methods) that build a failure: `Left(…)`, `None()`, `Failure(…)`, `Either.left(…)`. */\nconst FAILURE_CONSTRUCTORS: ReadonlySet<string> = new Set([\"Left\", \"None\", \"Failure\", \"left\", \"none\", \"failure\"])\n\n/** Does `node` read `<receiver>.<member>` anywhere inside it? */\nfunction readsMember(node: ASTNode, receiver: string, member: string, sourceCode: SourceCode): boolean {\n return descendants(node).some(\n (n) =>\n n.type === \"MemberExpression\" &&\n !n.computed &&\n n.property.type === \"Identifier\" &&\n n.property.name === member &&\n compact(sourceCode.getText(n.object)) === receiver,\n )\n}\n\n/** The single exit statement of a guard's consequent: `return x` / `throw x`, alone or as a one-statement block. */\nfunction guardExitStatement(consequent: ASTNode): { readonly exit: ASTNode; readonly extraWork: boolean } | null {\n if (consequent.type === \"ReturnStatement\" || consequent.type === \"ThrowStatement\") {\n return { exit: consequent, extraWork: false }\n }\n if (consequent.type !== \"BlockStatement\" || consequent.body.length === 0) return null\n const last = consequent.body[consequent.body.length - 1] as ASTNode\n if (last.type !== \"ReturnStatement\" && last.type !== \"ThrowStatement\") return null\n return { exit: last, extraWork: consequent.body.length > 1 }\n}\n\n/**\n * `receiver` is the compacted receiver text; `failureMember` is where the failure value lives once\n * narrowed (`value` for Either, `error` for Try, null for Option, whose None carries nothing).\n */\nfunction classifyGuardExit(\n consequent: ASTNode,\n receiver: string,\n failureMember: string | null,\n sourceCode: SourceCode,\n): GuardExit | null {\n const found = guardExitStatement(consequent)\n if (!found) return null\n if (found.exit.type === \"ThrowStatement\") return \"throw\"\n if (found.extraWork) return \"effect\"\n const argument = found.exit.argument as ASTNode | null\n if (!argument) return \"effect\"\n if (compact(sourceCode.getText(argument)) === receiver) return \"passthrough\"\n const callee = argument.type === \"CallExpression\" ? (argument.callee as ASTNode) : null\n const calleeName =\n callee?.type === \"Identifier\"\n ? callee.name\n : callee?.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (calleeName && FAILURE_CONSTRUCTORS.has(calleeName)) {\n const args = (argument.arguments ?? []) as ReadonlyArray<ASTNode>\n const unchanged =\n args.length === 0 ||\n (args.length === 1 &&\n failureMember !== null &&\n compact(sourceCode.getText(args[0])) === `${receiver}.${failureMember}`)\n return unchanged ? \"passthrough\" : \"mappedFailure\"\n }\n // A fallback built from the failure (`c.json({ error: r.value }, 500)`) can only be written as a fold:\n // outside the guard the failure isn't narrowed, so `map(…).orElse(…)` couldn't read it.\n if (failureMember !== null && readsMember(argument, receiver, failureMember, sourceCode)) return \"effect\"\n return \"default\"\n}\n\n/**\n * Does `statements` unwrap `receiver` the imperative way — `receiver.value`, `.orThrow()`, `.get()`?\n * Reads through `map`, `flatMap`, `fold`, `orElse`… are already the functional form and don't count.\n */\nfunction unwrapsReceiver(statements: ReadonlyArray<ASTNode>, receiver: string, sourceCode: SourceCode): boolean {\n const nodes = statements.flatMap((statement) => descendants(statement))\n // `e = next()` after the guard: later reads are of a different value, which the guard didn't check.\n const reassigned = nodes.some(\n (node) => node.type === \"AssignmentExpression\" && compact(sourceCode.getText(node.left)) === receiver,\n )\n if (reassigned) return false\n return nodes.some((node) => {\n if (node.type !== \"MemberExpression\" || compact(sourceCode.getText(node.object)) !== receiver) return false\n const name = node.property.type === \"Identifier\" ? node.property.name : null\n if (name === SUCCESS_MEMBER) return true\n const parent = node.parent as ASTNode | undefined\n if (name === null || !SUCCESS_METHODS.includes(name)) return false\n if (parent?.type !== \"CallExpression\" || parent.callee !== node) return false\n // `orThrow(error)` / `orThrow((e) => …)` names its error: no-get-unsafe treats that as a deliberate\n // host throw, so this rule doesn't count it as an unwrap either.\n return !(name === \"orThrow\" && (parent.arguments as ReadonlyArray<ASTNode>).length > 0)\n })\n}\n\n/** An exit-only negative guard (`if (e.isLeft()) return …`) on a functype predicate, or null. */\nfunction guardOf(node: ASTNode, sourceCode: SourceCode): ReturnType<typeof extractMonadicTest> {\n if (node.type !== \"IfStatement\" || node.alternate) return null\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted?.isNegated || !guardExitStatement(node.consequent)) return null\n return extracted\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .fold() over if/else chains when working with monadic types\",\n recommended: true,\n },\n // Suggestions, never an autofix (#323): `ts-builds validate` runs `eslint --fix`, which applies\n // fixable rules at warn severity too, and a fold rewrite cannot be proven type-correct without type\n // information. The developer applies it, and the compiler checks it.\n hasSuggestions: true,\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n minComplexity: {\n type: \"integer\",\n minimum: 1,\n default: 2,\n },\n checkNullable: {\n type: \"boolean\",\n default: false,\n },\n checkGuards: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFold: \"Prefer .fold() over if/else when working with {{type}} types\",\n preferFoldTernary: \"Consider using .fold() instead of ternary operator for {{type}}\",\n preferFoldGuard:\n \"{{receiver}} is checked with an early exit and then unwrapped. {{advice}} Branching first and unwrapping after is the imperative form.\",\n suggestFold: \"Replace with .fold()\",\n suggestOr:\n \"Replace with {{receiver}}.or({{alternative}}) — keep the first when it is present, else the alternative\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n const minComplexity = options.minComplexity || 2\n // Off by default (#325): a null check on a plain value (`x === null ? a : b`) is not a fold of a\n // functype value. Whether that value should be an Option is prefer-option's call, and at error this\n // path fired on JSX conditionals, style objects and conditional spreads (31 of 31 hits in CivalaOS,\n // 0 of which were functype values). Predicate calls (`o.isSome()`, `e.isLeft()`) are always checked.\n const checkNullable = options.checkNullable === true\n // Guard-then-unwrap (`if (e.isLeft()) return …; use(e.value)`). Opt-in while it's measured on real\n // code: prefer-fold is `error` in recommended, so turning this on by default would fail builds.\n const checkGuards = options.checkGuards === true\n\n const SEQUENCE_ADVICE = (isAsync: boolean): string =>\n isAsync\n ? \"Several guards in a row pass their failures through: sequence them with DoAsync(async function* () { const a = yield* $(await …) … }).\"\n : \"Several guards in a row pass their failures through: sequence them with Do(function* () { const a = yield* $(…); const b = yield* $(…); return … }).\"\n\n const GUARD_ADVICE: Readonly<Record<GuardExit, (receiver: string, isAsync: boolean) => string>> = {\n passthrough: (r, isAsync) =>\n isAsync\n ? `Keep it in the chain: ${r}.flatMapAsync(…), or lift the steps into IO.`\n : `Keep it in the chain: ${r}.flatMap(…) or ${r}.map(…); the failure passes through on its own.`,\n mappedFailure: (r, isAsync) =>\n `Keep it in the chain: ${r}.mapLeft(…).${isAsync ? \"flatMapAsync\" : \"flatMap\"}(…) builds the new failure and continues on success.`,\n default: (r) => `Use ${r}.map(…).orElse(fallback), or ${r}.fold(() => fallback, (value) => …).`,\n throw: (r) =>\n `If a host needs the throw, use ${r}.orThrow((e) => new YourError(e)); otherwise keep it in the chain with .flatMap or .fold.`,\n effect: (r, isAsync) =>\n isAsync ? `Use ${r}.foldAsync(onFailure, onSuccess).` : `Use ${r}.fold(onFailure, onSuccess).`,\n }\n\n /**\n * `if (e.isLeft()) return …` followed, in the same block, by reads of `e.value` / `e.orThrow()`.\n * `orElse` and `fold` are never flagged: both are proper ways to leave the container.\n */\n function checkGuard(node: ASTNode): void {\n if (!checkGuards) return\n const sourceCode = context.sourceCode\n const extracted = guardOf(node, sourceCode)\n if (!extracted) return\n const block = node.parent as ASTNode | undefined\n if (block?.type !== \"BlockStatement\" && block?.type !== \"Program\") return\n const body = block.body as ReadonlyArray<ASTNode>\n const after = body.slice(body.indexOf(node) + 1)\n const receiver = compact(extracted.obj)\n if (!unwrapsReceiver(after, receiver, sourceCode)) return\n const exit = classifyGuardExit(node.consequent, receiver, extracted.failure?.member ?? null, sourceCode)\n if (!exit) return\n const isAsync = after.some((statement) => containsAwait(statement))\n // Two or more pass-through guards in one block, each unwrapped later: nested flatMaps would be worse\n // than the guards, so the advice is a Do comprehension.\n const passThrough = (candidate: ASTNode): boolean => {\n const other = guardOf(candidate, sourceCode)\n if (!other) return false\n const otherReceiver = compact(other.obj)\n const otherAfter = body.slice(body.indexOf(candidate) + 1)\n const kind = classifyGuardExit(candidate.consequent, otherReceiver, other.failure?.member ?? null, sourceCode)\n return (\n (kind === \"passthrough\" || kind === \"mappedFailure\") && unwrapsReceiver(otherAfter, otherReceiver, sourceCode)\n )\n }\n const sequenced = (exit === \"passthrough\" || exit === \"mappedFailure\") && body.filter(passThrough).length > 1\n context.report({\n node,\n messageId: \"preferFoldGuard\",\n data: {\n receiver: extracted.obj,\n advice: sequenced ? SEQUENCE_ADVICE(isAsync) : GUARD_ADVICE[exit](extracted.obj, isAsync),\n },\n })\n }\n\n function generateFoldFromIf(node: ASTNode): string | null {\n const sourceCode = context.sourceCode\n if (node.type !== \"IfStatement\" || !node.alternate) return null\n\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted) return null\n\n // Only if/else where both branches return a value — the fold then replaces the whole statement\n // as `return receiver.fold(...)`. Anything else (side effects, nested else-if) is left alone.\n const thenExpr = returnedExpression(node.consequent)\n const elseExpr = returnedExpression(node.alternate)\n if (!thenExpr || !elseExpr) return null\n\n // The suggestion keeps only the test and the two returned values; a comment anywhere else in the\n // statement would be silently dropped, so none is offered.\n const kept = [node.test, thenExpr, elseExpr]\n const within = (c: { range?: [number, number] }): boolean =>\n c.range !== undefined && kept.some((n) => c.range![0] >= n.range[0] && c.range![1] <= n.range[1])\n if (!sourceCode.getCommentsInside(node).every(within)) return null\n\n const { obj, isNegated, failure } = extracted\n const [failureExpr, successExpr] = isNegated ? [thenExpr, elseExpr] : [elseExpr, thenExpr]\n return `return ${buildFold(obj, failure, failureExpr, successExpr, sourceCode)}`\n }\n\n function ternarySuggestions(node: ASTNode): Rule.SuggestionReportDescriptor[] {\n const sourceCode = context.sourceCode\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted) return []\n\n const { obj, isNegated, failure } = extracted\n const [failureNode, successNode] = isNegated\n ? [node.consequent, node.alternate]\n : [node.alternate, node.consequent]\n const failureText = sourceCode.getText(failureNode)\n const successText = sourceCode.getText(successNode)\n\n // `a.isSome() ? a : b` keeps the container when present and falls back otherwise — that is `.or`,\n // and a fold would only rebuild it with an unused parameter. `.or` takes a container, so a literal\n // or `undefined` fallback gets no suggestion at all: neither `.or(5)` nor a fold mixing a container\n // with a plain value would type-check.\n if (compact(successText) === compact(obj)) {\n if (failureNode.type === \"Literal\" || failureNode.type === \"TemplateLiteral\" || isNullishLiteral(failureNode)) {\n return []\n }\n return [\n {\n messageId: \"suggestOr\",\n data: { receiver: obj, alternative: failureText },\n fix: (fixer) => fixer.replaceText(node, `${obj}.or(${failureText})`),\n },\n ]\n }\n\n const fold = buildFold(obj, failure, failureNode, successNode, sourceCode)\n return [{ messageId: \"suggestFold\", fix: (fixer) => fixer.replaceText(node, fold) }]\n }\n\n function isFunctypePredicateCall(node: ASTNode): boolean {\n // Suggest a rewrite only when the test is a functype predicate call (the receiver is a functype value)\n if (node.type === \"CallExpression\" && node.callee.type === \"MemberExpression\") {\n const methodName = node.callee.property.name\n // These methods indicate the object is already a functype instance\n return [\"isSome\", \"isNone\", \"isRight\", \"isLeft\", \"isSuccess\", \"isFailure\"].includes(methodName)\n }\n return false\n }\n\n // `via` records HOW we matched: a functype predicate call (`method`, precise) vs the untyped\n // null/undefined heuristic (`nullable`, a guess that can't tell a real Option from a plain nullable).\n function isMonadicCheck(node: ASTNode): { isMonadic: boolean; type: string; via: \"method\" | \"nullable\" | \"\" } {\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Check for common monadic type checks\n if (/\\.(isSome|isNone|isDefined)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Option\", via: \"method\" }\n }\n\n if (/\\.(isLeft|isRight)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Either\", via: \"method\" }\n }\n\n if (/\\.(isSuccess|isFailure)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Result\", via: \"method\" }\n }\n\n // Check for null/undefined checks on variables that might be Options\n if (checkNullable && node.type === \"BinaryExpression\") {\n if (\n (node.operator === \"===\" || node.operator === \"!==\" || node.operator === \"==\" || node.operator === \"!=\") &&\n ((node.left.type === \"Literal\" && (node.left.value === null || node.left.value === undefined)) ||\n (node.right.type === \"Literal\" && (node.right.value === null || node.right.value === undefined)))\n ) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n\n // Check for === or == with undefined identifier\n if (node.operator === \"==\" || node.operator === \"!=\" || node.operator === \"===\" || node.operator === \"!==\") {\n const leftIsUndefined = node.left.type === \"Identifier\" && node.left.name === \"undefined\"\n const rightIsUndefined = node.right.type === \"Identifier\" && node.right.name === \"undefined\"\n\n if (leftIsUndefined || rightIsUndefined) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n }\n }\n\n return { isMonadic: false, type: \"\", via: \"\" }\n }\n\n function suggestionsForIf(node: ASTNode): Rule.SuggestionReportDescriptor[] {\n if (!isFunctypePredicateCall(node.test)) return []\n const replacement = generateFoldFromIf(node)\n return replacement ? [{ messageId: \"suggestFold\", fix: (fixer) => fixer.replaceText(node, replacement) }] : []\n }\n\n function analyzeIfStatement(node: ASTNode) {\n const test = node.test\n const monadicInfo = isMonadicCheck(test)\n\n if (!monadicInfo.isMonadic) return\n\n // Don't analyze if this is part of a larger if/else chain\n // (only analyze the outermost if statement)\n if (node.parent && node.parent.type === \"IfStatement\") return\n\n // Count the complexity (if/else if/else chain)\n if (ifElseChainLength(node) >= minComplexity) {\n context.report({\n node,\n messageId: \"preferFold\",\n data: { type: monadicInfo.type },\n suggest: suggestionsForIf(node),\n })\n }\n }\n\n return {\n IfStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n analyzeIfStatement(node)\n checkGuard(node)\n },\n\n ConditionalExpression(node: ASTNode) {\n if (isExemptByMarker(node)) return\n const monadicInfo = isMonadicCheck(node.test)\n // The untyped nullable heuristic can't distinguish a real Option from a plain nullable primitive.\n // When it fires on a ternary that yields `undefined`/`null` in a branch, that's optional value\n // construction (prefer-option's concern), not a fold — skip it. False positive this kills:\n // `x !== undefined ? \"a\" : undefined`. Predicate-call matches (`.isSome()` etc.) are unaffected.\n if (monadicInfo.via === \"nullable\" && (isNullishLiteral(node.consequent) || isNullishLiteral(node.alternate))) {\n return\n }\n if (monadicInfo.isMonadic) {\n context.report({\n node,\n messageId: \"preferFoldTernary\",\n data: { type: monadicInfo.type },\n suggest: isFunctypePredicateCall(node.test) ? ternarySuggestions(node) : [],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"iTAgBA,MAAMA,EAAsD,CAC1D,OAAQ,KACR,OAAQ,KACR,QAAS,CAAE,MAAO,OAAQ,OAAQ,OAAQ,EAC1C,OAAQ,CAAE,MAAO,OAAQ,OAAQ,OAAQ,EACzC,UAAW,CAAE,MAAO,QAAS,OAAQ,OAAQ,EAC7C,UAAW,CAAE,MAAO,QAAS,OAAQ,OAAQ,CAC/C,EAGMC,EAAkB,CAAC,MAAO,SAAS,EACnCC,EAAiB,QAOvB,SAASC,EAAiB,EAAwB,CAChD,OAAQC,EAAK,OAAS,WAAaA,EAAK,QAAU,MAAUA,EAAK,OAAS,cAAgBA,EAAK,OAAS,WAC1G,CAOA,SAASC,EACP,EACA,EACkE,CAClE,GAAIC,EAAK,OAAS,kBAAoBA,EAAK,OAAO,OAAS,mBAAoB,OAAO,KACtF,IAAMC,EAAaD,EAAK,OAAO,SAAS,KAClCE,EAAMC,EAAW,QAAQH,EAAK,OAAO,MAAM,EAC3CI,EAAUV,EAAaO,IAAe,KAG5C,OAFII,EAAoB,IAAIJ,CAAU,EAAU,CAAE,MAAK,UAAW,GAAO,SAAQ,EAC7EK,EAAoB,IAAIL,CAAU,EAAU,CAAE,MAAK,UAAW,GAAM,SAAQ,EACzE,IACT,CAKA,MAAMM,EAAuB,CAAE,QAAS,CAACX,CAAc,EAAG,QAASD,CAAgB,EAQnF,SAASa,EACP,EACA,EACA,EACA,EAC0C,CAC1C,IAAMC,EAAc,GAA2B,CAC7C,IAAMC,EAASZ,EAAK,OAAS,sBAAwBA,EAAK,WAAaA,EACvE,OAAOa,EAAQR,EAAW,QAAQO,CAAM,CAAC,IAAMC,EAAQC,CAAQ,CACjE,EACMC,GAAY,EAAe,IAC/Bf,EAAK,OAAS,oBACd,CAAC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CAAI,EAC3C,OAAOgH,EAAc,CAAC,CAAE,UAAW,cAAe,IAAM,GAAUP,EAAM,YAAYzG,EAAMgH,CAAW,CAAE,CAAC,EAAI,CAAC,CAC/G,CAEA,SAASC,EAAmB,EAAe,CACzC,IAAM/G,EAAOF,EAAK,KACZkH,EAAcN,EAAe1G,CAAI,EAElCgH,EAAY,YAIblH,EAAK,QAAUA,EAAK,OAAO,OAAS,eAGpCgD,EAAkBhD,CAAI,GAAK2E,GAC7BJ,EAAQ,OAAO,CACb,OACA,UAAW,aACX,KAAM,CAAE,KAAM2C,EAAY,IAAK,EAC/B,QAASH,EAAiB/G,CAAI,CAChC,CAAC,EAEL,CAEA,MAAO,CACL,YAAY,EAAe,CACrByE,EAAiBzE,CAAI,IACzBiH,EAAmBjH,CAAI,EACvBkF,EAAWlF,CAAI,EACjB,EAEA,sBAAsB,EAAe,CACnC,GAAIyE,EAAiBzE,CAAI,EAAG,OAC5B,IAAMkH,EAAcN,EAAe5G,EAAK,IAAI,GAKxCkH,EAAY,MAAQ,YAAe,GAAiBlH,EAAK,UAAU,GAAK,GAAiBA,EAAK,SAAS,IAGvGkH,EAAY,WACd3C,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,KAAM2C,EAAY,IAAK,EAC/B,QAASP,EAAwB3G,EAAK,IAAI,EAAIsG,EAAmBtG,CAAI,EAAI,CAAC,CAC5E,CAAC,CAEL,CACF,CACF,CACF"}
1
+ {"version":3,"file":"prefer-fold.js","names":["FAILURE_SIDE","SUCCESS_METHODS","SUCCESS_MEMBER","isNullishLiteral","node","extractMonadicTest","test","methodName","obj","sourceCode","failure","POSITIVE_PREDICATES","NEGATIVE_PREDICATES","SUCCESS_READS","receiverReads","isReceiver","target","compact","receiver","isMember","names","visit","parent","isCalled","isWritten","reads","childNodes","branch","freshName","isTaken","branches","name","b","base","i","asArrowBody","text","foldCallback","ranges","offset","rewritten","a","start","end","acc","param","buildFold","failureNode","successNode","onSuccess","returnedExpression","statement","ifElseChainLength","FAILURE_CONSTRUCTORS","readsMember","descendants","n","member","guardExitStatement","consequent","last","classifyGuardExit","found","argument","callee","calleeName","args","failureMember","unwrapsReceiver","nodes","statements","guardOf","extracted","rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","minComplexity","checkNullable","checkGuards","SEQUENCE_ADVICE","isAsync","GUARD_ADVICE","r","checkGuard","block","body","after","exit","containsAwait","sequenced","other","candidate","otherReceiver","otherAfter","kind","generateFoldFromIf","thenExpr","elseExpr","kept","c","failureExpr","successExpr","isNegated","ternarySuggestions","failureText","successText","fixer","fold","isFunctypePredicateCall","isMonadicCheck","leftIsUndefined","rightIsUndefined","suggestionsForIf","replacement","analyzeIfStatement","monadicInfo"],"sources":["../../src/rules/prefer-fold.ts"],"sourcesContent":["import type { Rule, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { childNodes, descendants } from \"../utils/ast-walk\"\nimport { containsAwait } from \"../utils/async-detection\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { compact, NEGATIVE_PREDICATES, POSITIVE_PREDICATES } from \"../utils/functype-predicates\"\n\n/**\n * How each container's fold exposes its failure side. `fold(onFailure, onSuccess)` everywhere, but\n * only Either and Try hand the failure callback a value — Option's `onNone` takes nothing. `member`\n * is the property a narrowed branch reads that value through (`e.value` after `isLeft()`,\n * `t.error` after `isFailure()`).\n */\ntype FailureSide = { readonly param: string; readonly member: string } | null\n\nconst FAILURE_SIDE: Readonly<Record<string, FailureSide>> = {\n isSome: null,\n isNone: null,\n isRight: { param: \"left\", member: \"value\" },\n isLeft: { param: \"left\", member: \"value\" },\n isSuccess: { param: \"error\", member: \"error\" },\n isFailure: { param: \"error\", member: \"error\" },\n}\n\n/** Reads of the success value that the fold's success parameter replaces. */\nconst SUCCESS_METHODS = [\"get\", \"orThrow\"]\nconst SUCCESS_MEMBER = \"value\"\n\n/**\n * A literal `null` or the `undefined` identifier. A ternary that yields one of these in a branch is\n * building an optional value (prefer-option's concern), not folding a monad — so the untyped nullable\n * heuristic must not treat `x !== undefined ? \"a\" : undefined` as a fold candidate.\n */\nfunction isNullishLiteral(node: ASTNode): boolean {\n return (node.type === \"Literal\" && node.value === null) || (node.type === \"Identifier\" && node.name === \"undefined\")\n}\n\n/**\n * If `test` is a monadic predicate call like `option.isSome()` or\n * `either.isLeft()`, returns the receiver expression's text plus whether the\n * predicate is the \"absence\" side. Returns null for anything else.\n */\nfunction extractMonadicTest(\n test: ASTNode,\n sourceCode: SourceCode,\n): { obj: string; isNegated: boolean; failure: FailureSide } | null {\n if (test.type !== \"CallExpression\" || test.callee.type !== \"MemberExpression\") return null\n const methodName = test.callee.property.name\n const obj = sourceCode.getText(test.callee.object)\n const failure = FAILURE_SIDE[methodName] ?? null\n if (POSITIVE_PREDICATES.has(methodName)) return { obj, isNegated: false, failure }\n if (NEGATIVE_PREDICATES.has(methodName)) return { obj, isNegated: true, failure }\n return null\n}\n\n/** Which reads of the narrowed receiver a fold parameter replaces. */\ntype Reads = { readonly members: ReadonlyArray<string>; readonly methods: ReadonlyArray<string> }\n\nconst SUCCESS_READS: Reads = { members: [SUCCESS_MEMBER], methods: SUCCESS_METHODS }\n\n/**\n * Source ranges inside `branch` that read the narrowed receiver: `e.value`, `e!.value`, `e?.value`,\n * `e.orThrow()`. Driven by the AST rather than the text, so a read never matches inside a string or\n * template literal, a comment, a longer name, or another object's member (`other.e.value`). A member\n * that is called (`e.value()`) or assigned (`e.value = 3`) is not a read.\n */\nfunction receiverReads(\n branch: ASTNode,\n receiver: string,\n reads: Reads,\n sourceCode: SourceCode,\n): ReadonlyArray<readonly [number, number]> {\n const isReceiver = (node: ASTNode): boolean => {\n const target = node.type === \"TSNonNullExpression\" ? node.expression : node\n return compact(sourceCode.getText(target)) === compact(receiver)\n }\n const isMember = (node: ASTNode, names: ReadonlyArray<string>): boolean =>\n node.type === \"MemberExpression\" &&\n !node.computed &&\n node.property.type === \"Identifier\" &&\n names.includes(node.property.name) &&\n isReceiver(node.object)\n\n const visit = (node: ASTNode): ReadonlyArray<readonly [number, number]> => {\n const parent = node.parent\n const isCalled = parent?.type === \"CallExpression\" && parent.callee === node\n const isWritten =\n (parent?.type === \"AssignmentExpression\" && parent.left === node) || parent?.type === \"UpdateExpression\"\n if (isMember(node, reads.members) && !isCalled && !isWritten) return [node.range]\n if (node.type === \"CallExpression\" && node.arguments.length === 0 && isMember(node.callee, reads.methods)) {\n return [node.range]\n }\n return childNodes(node).flatMap(visit)\n }\n return visit(branch)\n}\n\n/** A parameter name no branch already uses, so the fold never shadows a captured identifier. */\nconst freshName = (base: string, branches: ReadonlyArray<string>): string => {\n // `(?<![\\\\w$.])`: a property access (`e.value`) is not a free identifier, so it cannot be shadowed.\n const isTaken = (name: string): boolean => branches.some((b) => new RegExp(`(?<![\\\\w$.])${name}(?![\\\\w$])`).test(b))\n const candidates = [base, ...Array.from({ length: 20 }, (_, i) => `${base}${i + 1}`)]\n return candidates.find((name) => !isTaken(name)) ?? `${base}_`\n}\n\n/**\n * An arrow body must not start with `{` (it would parse as a block) and a comma expression must stay\n * one argument, so those two shapes are parenthesized. ESTree ranges exclude the source's own parens.\n */\nconst asArrowBody = (node: ASTNode, text: string): string =>\n node.type === \"ObjectExpression\" || node.type === \"SequenceExpression\" ? `(${text})` : text\n\n/**\n * One fold callback. Reads of the narrowed receiver become reads of the callback's parameter — the\n * receiver is NOT narrowed inside the callback, so leaving `e.value` there is a type error (#323).\n * A branch that never reads the value gets a parameterless callback, not an unused parameter.\n */\nfunction foldCallback(\n branch: ASTNode,\n receiver: string,\n reads: Reads | null,\n param: string,\n sourceCode: SourceCode,\n): string {\n const text = sourceCode.getText(branch)\n const ranges = reads === null ? [] : receiverReads(branch, receiver, reads, sourceCode)\n if (ranges.length === 0) return `() => ${asArrowBody(branch, text)}`\n const offset = branch.range[0]\n // Replace right-to-left so earlier offsets stay valid.\n const rewritten = [...ranges]\n .sort((a, b) => b[0] - a[0])\n .reduce((acc, [start, end]) => acc.slice(0, start - offset) + param + acc.slice(end - offset), text)\n return `(${param}) => ${asArrowBody(branch, rewritten)}`\n}\n\n/** `receiver.fold(onFailure, onSuccess)` from the two branch nodes. */\nfunction buildFold(\n receiver: string,\n failure: FailureSide,\n failureNode: ASTNode,\n successNode: ASTNode,\n sourceCode: SourceCode,\n): string {\n const branches = [sourceCode.getText(failureNode), sourceCode.getText(successNode)]\n const onSuccess = foldCallback(successNode, receiver, SUCCESS_READS, freshName(\"value\", branches), sourceCode)\n const onFailure =\n failure === null\n ? foldCallback(failureNode, receiver, null, \"\", sourceCode)\n : foldCallback(\n failureNode,\n receiver,\n { members: [failure.member], methods: [] },\n freshName(failure.param, branches),\n sourceCode,\n )\n return `${receiver}.fold(${onFailure}, ${onSuccess})`\n}\n\n/** The returned expression of a `return x` statement or a `{ return x }` block; null for anything else. */\nfunction returnedExpression(node: ASTNode): ASTNode | null {\n const statement = node.type === \"BlockStatement\" && node.body.length === 1 ? node.body[0] : node\n return statement.type === \"ReturnStatement\" && statement.argument ? statement.argument : null\n}\n\n/**\n * Length of an if/else-if/else chain rooted at `node`. Counts the root as 1\n * and adds 1 per linked alternate IfStatement. Terminates on a non-If\n * alternate (the final `else { ... }`) which counts as the last branch.\n */\nfunction ifElseChainLength(node: ASTNode): number {\n if (!node.alternate) return 1\n if (node.alternate.type === \"IfStatement\") return 1 + ifElseChainLength(node.alternate as ASTNode)\n return 2 // root + the terminal else\n}\n\n/**\n * What a guard's early exit does, which decides the advice:\n * - `passthrough`: hands the failure back unchanged (`return e`, `return Left(e.value)`, `return None()`),\n * so the rest of the function is a `flatMap`/`map`.\n * - `mappedFailure`: returns a new failure built from the old one (`return Left({ kind: e.value.kind })`),\n * so it's `mapLeft(…)` then `flatMap`.\n * - `default`: returns a plain fallback, so it's `map(…).orElse(fallback)` or a `fold`.\n * - `throw`: a host that needs a throw, so it's `orThrow((e) => …)`.\n * - `effect`: does other work first (logging, setting state), so it's a `fold`.\n */\ntype GuardExit = \"passthrough\" | \"mappedFailure\" | \"default\" | \"throw\" | \"effect\"\n\n/** Constructors (and companion methods) that build a failure: `Left(…)`, `None()`, `Failure(…)`, `Either.left(…)`. */\nconst FAILURE_CONSTRUCTORS: ReadonlySet<string> = new Set([\"Left\", \"None\", \"Failure\", \"left\", \"none\", \"failure\"])\n\n/** Does `node` read `<receiver>.<member>` anywhere inside it? */\nfunction readsMember(node: ASTNode, receiver: string, member: string, sourceCode: SourceCode): boolean {\n return descendants(node).some(\n (n) =>\n n.type === \"MemberExpression\" &&\n !n.computed &&\n n.property.type === \"Identifier\" &&\n n.property.name === member &&\n compact(sourceCode.getText(n.object)) === receiver,\n )\n}\n\n/** The single exit statement of a guard's consequent: `return x` / `throw x`, alone or as a one-statement block. */\nfunction guardExitStatement(consequent: ASTNode): { readonly exit: ASTNode; readonly extraWork: boolean } | null {\n if (consequent.type === \"ReturnStatement\" || consequent.type === \"ThrowStatement\") {\n return { exit: consequent, extraWork: false }\n }\n if (consequent.type !== \"BlockStatement\" || consequent.body.length === 0) return null\n const last = consequent.body[consequent.body.length - 1] as ASTNode\n if (last.type !== \"ReturnStatement\" && last.type !== \"ThrowStatement\") return null\n return { exit: last, extraWork: consequent.body.length > 1 }\n}\n\n/**\n * `receiver` is the compacted receiver text; `failureMember` is where the failure value lives once\n * narrowed (`value` for Either, `error` for Try, null for Option, whose None carries nothing).\n */\nfunction classifyGuardExit(\n consequent: ASTNode,\n receiver: string,\n failureMember: string | null,\n sourceCode: SourceCode,\n): GuardExit | null {\n const found = guardExitStatement(consequent)\n if (!found) return null\n if (found.exit.type === \"ThrowStatement\") return \"throw\"\n if (found.extraWork) return \"effect\"\n const argument = found.exit.argument as ASTNode | null\n if (!argument) return \"effect\"\n if (compact(sourceCode.getText(argument)) === receiver) return \"passthrough\"\n const callee = argument.type === \"CallExpression\" ? (argument.callee as ASTNode) : null\n const calleeName =\n callee?.type === \"Identifier\"\n ? callee.name\n : callee?.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (calleeName && FAILURE_CONSTRUCTORS.has(calleeName)) {\n const args = (argument.arguments ?? []) as ReadonlyArray<ASTNode>\n const unchanged =\n args.length === 0 ||\n (args.length === 1 &&\n failureMember !== null &&\n compact(sourceCode.getText(args[0])) === `${receiver}.${failureMember}`)\n return unchanged ? \"passthrough\" : \"mappedFailure\"\n }\n // A fallback built from the failure (`c.json({ error: r.value }, 500)`) can only be written as a fold:\n // outside the guard the failure isn't narrowed, so `map(…).orElse(…)` couldn't read it.\n if (failureMember !== null && readsMember(argument, receiver, failureMember, sourceCode)) return \"effect\"\n return \"default\"\n}\n\n/**\n * Does `statements` unwrap `receiver` the imperative way — `receiver.value`, `.orThrow()`, `.get()`?\n * Reads through `map`, `flatMap`, `fold`, `orElse`… are already the functional form and don't count.\n */\nfunction unwrapsReceiver(statements: ReadonlyArray<ASTNode>, receiver: string, sourceCode: SourceCode): boolean {\n const nodes = statements.flatMap((statement) => descendants(statement))\n // `e = next()` after the guard: later reads are of a different value, which the guard didn't check.\n const reassigned = nodes.some(\n (node) => node.type === \"AssignmentExpression\" && compact(sourceCode.getText(node.left)) === receiver,\n )\n if (reassigned) return false\n return nodes.some((node) => {\n if (node.type !== \"MemberExpression\" || compact(sourceCode.getText(node.object)) !== receiver) return false\n const name = node.property.type === \"Identifier\" ? node.property.name : null\n if (name === SUCCESS_MEMBER) return true\n const parent = node.parent as ASTNode | undefined\n if (name === null || !SUCCESS_METHODS.includes(name)) return false\n if (parent?.type !== \"CallExpression\" || parent.callee !== node) return false\n // `orThrow(error)` / `orThrow((e) => …)` names its error: no-get-unsafe treats that as a deliberate\n // host throw, so this rule doesn't count it as an unwrap either.\n return !(name === \"orThrow\" && (parent.arguments as ReadonlyArray<ASTNode>).length > 0)\n })\n}\n\n/** An exit-only negative guard (`if (e.isLeft()) return …`) on a functype predicate, or null. */\nfunction guardOf(node: ASTNode, sourceCode: SourceCode): ReturnType<typeof extractMonadicTest> {\n if (node.type !== \"IfStatement\" || node.alternate) return null\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted?.isNegated || !guardExitStatement(node.consequent)) return null\n return extracted\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .fold() over if/else chains when working with monadic types\",\n recommended: true,\n },\n // Suggestions, never an autofix (#323): `ts-builds validate` runs `eslint --fix`, which applies\n // fixable rules at warn severity too, and a fold rewrite cannot be proven type-correct without type\n // information. The developer applies it, and the compiler checks it.\n hasSuggestions: true,\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n minComplexity: {\n type: \"integer\",\n minimum: 1,\n default: 2,\n },\n checkNullable: {\n type: \"boolean\",\n default: false,\n },\n checkGuards: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFold: \"Prefer .fold() over if/else when working with {{type}} types\",\n preferFoldTernary: \"Consider using .fold() instead of ternary operator for {{type}}\",\n preferFoldGuard:\n \"{{receiver}} is checked with an early exit and then unwrapped. {{advice}} Branching first and unwrapping after is the imperative form.\",\n suggestFold: \"Replace with .fold()\",\n suggestOr:\n \"Replace with {{receiver}}.or({{alternative}}) — keep the first when it is present, else the alternative\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n const minComplexity = options.minComplexity || 2\n // Off by default (#325): a null check on a plain value (`x === null ? a : b`) is not a fold of a\n // functype value. Whether that value should be an Option is prefer-option's call, and at error this\n // path fired on JSX conditionals, style objects and conditional spreads (31 of 31 hits in a private app monorepo,\n // 0 of which were functype values). Predicate calls (`o.isSome()`, `e.isLeft()`) are always checked.\n const checkNullable = options.checkNullable === true\n // Guard-then-unwrap (`if (e.isLeft()) return …; use(e.value)`). Opt-in while it's measured on real\n // code: prefer-fold is `error` in recommended, so turning this on by default would fail builds.\n const checkGuards = options.checkGuards === true\n\n const SEQUENCE_ADVICE = (isAsync: boolean): string =>\n isAsync\n ? \"Several guards in a row pass their failures through: sequence them with DoAsync(async function* () { const a = yield* $(await …) … }).\"\n : \"Several guards in a row pass their failures through: sequence them with Do(function* () { const a = yield* $(…); const b = yield* $(…); return … }).\"\n\n const GUARD_ADVICE: Readonly<Record<GuardExit, (receiver: string, isAsync: boolean) => string>> = {\n passthrough: (r, isAsync) =>\n isAsync\n ? `Keep it in the chain: ${r}.flatMapAsync(…), or lift the steps into IO.`\n : `Keep it in the chain: ${r}.flatMap(…) or ${r}.map(…); the failure passes through on its own.`,\n mappedFailure: (r, isAsync) =>\n `Keep it in the chain: ${r}.mapLeft(…).${isAsync ? \"flatMapAsync\" : \"flatMap\"}(…) builds the new failure and continues on success.`,\n default: (r) => `Use ${r}.map(…).orElse(fallback), or ${r}.fold(() => fallback, (value) => …).`,\n throw: (r) =>\n `If a host needs the throw, use ${r}.orThrow((e) => new YourError(e)); otherwise keep it in the chain with .flatMap or .fold.`,\n effect: (r, isAsync) =>\n isAsync ? `Use ${r}.foldAsync(onFailure, onSuccess).` : `Use ${r}.fold(onFailure, onSuccess).`,\n }\n\n /**\n * `if (e.isLeft()) return …` followed, in the same block, by reads of `e.value` / `e.orThrow()`.\n * `orElse` and `fold` are never flagged: both are proper ways to leave the container.\n */\n function checkGuard(node: ASTNode): void {\n if (!checkGuards) return\n const sourceCode = context.sourceCode\n const extracted = guardOf(node, sourceCode)\n if (!extracted) return\n const block = node.parent as ASTNode | undefined\n if (block?.type !== \"BlockStatement\" && block?.type !== \"Program\") return\n const body = block.body as ReadonlyArray<ASTNode>\n const after = body.slice(body.indexOf(node) + 1)\n const receiver = compact(extracted.obj)\n if (!unwrapsReceiver(after, receiver, sourceCode)) return\n const exit = classifyGuardExit(node.consequent, receiver, extracted.failure?.member ?? null, sourceCode)\n if (!exit) return\n const isAsync = after.some((statement) => containsAwait(statement))\n // Two or more pass-through guards in one block, each unwrapped later: nested flatMaps would be worse\n // than the guards, so the advice is a Do comprehension.\n const passThrough = (candidate: ASTNode): boolean => {\n const other = guardOf(candidate, sourceCode)\n if (!other) return false\n const otherReceiver = compact(other.obj)\n const otherAfter = body.slice(body.indexOf(candidate) + 1)\n const kind = classifyGuardExit(candidate.consequent, otherReceiver, other.failure?.member ?? null, sourceCode)\n return (\n (kind === \"passthrough\" || kind === \"mappedFailure\") && unwrapsReceiver(otherAfter, otherReceiver, sourceCode)\n )\n }\n const sequenced = (exit === \"passthrough\" || exit === \"mappedFailure\") && body.filter(passThrough).length > 1\n context.report({\n node,\n messageId: \"preferFoldGuard\",\n data: {\n receiver: extracted.obj,\n advice: sequenced ? SEQUENCE_ADVICE(isAsync) : GUARD_ADVICE[exit](extracted.obj, isAsync),\n },\n })\n }\n\n function generateFoldFromIf(node: ASTNode): string | null {\n const sourceCode = context.sourceCode\n if (node.type !== \"IfStatement\" || !node.alternate) return null\n\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted) return null\n\n // Only if/else where both branches return a value — the fold then replaces the whole statement\n // as `return receiver.fold(...)`. Anything else (side effects, nested else-if) is left alone.\n const thenExpr = returnedExpression(node.consequent)\n const elseExpr = returnedExpression(node.alternate)\n if (!thenExpr || !elseExpr) return null\n\n // The suggestion keeps only the test and the two returned values; a comment anywhere else in the\n // statement would be silently dropped, so none is offered.\n const kept = [node.test, thenExpr, elseExpr]\n const within = (c: { range?: [number, number] }): boolean =>\n c.range !== undefined && kept.some((n) => c.range![0] >= n.range[0] && c.range![1] <= n.range[1])\n if (!sourceCode.getCommentsInside(node).every(within)) return null\n\n const { obj, isNegated, failure } = extracted\n const [failureExpr, successExpr] = isNegated ? [thenExpr, elseExpr] : [elseExpr, thenExpr]\n return `return ${buildFold(obj, failure, failureExpr, successExpr, sourceCode)}`\n }\n\n function ternarySuggestions(node: ASTNode): Rule.SuggestionReportDescriptor[] {\n const sourceCode = context.sourceCode\n const extracted = extractMonadicTest(node.test, sourceCode)\n if (!extracted) return []\n\n const { obj, isNegated, failure } = extracted\n const [failureNode, successNode] = isNegated\n ? [node.consequent, node.alternate]\n : [node.alternate, node.consequent]\n const failureText = sourceCode.getText(failureNode)\n const successText = sourceCode.getText(successNode)\n\n // `a.isSome() ? a : b` keeps the container when present and falls back otherwise — that is `.or`,\n // and a fold would only rebuild it with an unused parameter. `.or` takes a container, so a literal\n // or `undefined` fallback gets no suggestion at all: neither `.or(5)` nor a fold mixing a container\n // with a plain value would type-check.\n if (compact(successText) === compact(obj)) {\n if (failureNode.type === \"Literal\" || failureNode.type === \"TemplateLiteral\" || isNullishLiteral(failureNode)) {\n return []\n }\n return [\n {\n messageId: \"suggestOr\",\n data: { receiver: obj, alternative: failureText },\n fix: (fixer) => fixer.replaceText(node, `${obj}.or(${failureText})`),\n },\n ]\n }\n\n const fold = buildFold(obj, failure, failureNode, successNode, sourceCode)\n return [{ messageId: \"suggestFold\", fix: (fixer) => fixer.replaceText(node, fold) }]\n }\n\n function isFunctypePredicateCall(node: ASTNode): boolean {\n // Suggest a rewrite only when the test is a functype predicate call (the receiver is a functype value)\n if (node.type === \"CallExpression\" && node.callee.type === \"MemberExpression\") {\n const methodName = node.callee.property.name\n // These methods indicate the object is already a functype instance\n return [\"isSome\", \"isNone\", \"isRight\", \"isLeft\", \"isSuccess\", \"isFailure\"].includes(methodName)\n }\n return false\n }\n\n // `via` records HOW we matched: a functype predicate call (`method`, precise) vs the untyped\n // null/undefined heuristic (`nullable`, a guess that can't tell a real Option from a plain nullable).\n function isMonadicCheck(node: ASTNode): { isMonadic: boolean; type: string; via: \"method\" | \"nullable\" | \"\" } {\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Check for common monadic type checks\n if (/\\.(isSome|isNone|isDefined)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Option\", via: \"method\" }\n }\n\n if (/\\.(isLeft|isRight)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Either\", via: \"method\" }\n }\n\n if (/\\.(isSuccess|isFailure)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Result\", via: \"method\" }\n }\n\n // Check for null/undefined checks on variables that might be Options\n if (checkNullable && node.type === \"BinaryExpression\") {\n if (\n (node.operator === \"===\" || node.operator === \"!==\" || node.operator === \"==\" || node.operator === \"!=\") &&\n ((node.left.type === \"Literal\" && (node.left.value === null || node.left.value === undefined)) ||\n (node.right.type === \"Literal\" && (node.right.value === null || node.right.value === undefined)))\n ) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n\n // Check for === or == with undefined identifier\n if (node.operator === \"==\" || node.operator === \"!=\" || node.operator === \"===\" || node.operator === \"!==\") {\n const leftIsUndefined = node.left.type === \"Identifier\" && node.left.name === \"undefined\"\n const rightIsUndefined = node.right.type === \"Identifier\" && node.right.name === \"undefined\"\n\n if (leftIsUndefined || rightIsUndefined) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n }\n }\n\n return { isMonadic: false, type: \"\", via: \"\" }\n }\n\n function suggestionsForIf(node: ASTNode): Rule.SuggestionReportDescriptor[] {\n if (!isFunctypePredicateCall(node.test)) return []\n const replacement = generateFoldFromIf(node)\n return replacement ? [{ messageId: \"suggestFold\", fix: (fixer) => fixer.replaceText(node, replacement) }] : []\n }\n\n function analyzeIfStatement(node: ASTNode) {\n const test = node.test\n const monadicInfo = isMonadicCheck(test)\n\n if (!monadicInfo.isMonadic) return\n\n // Don't analyze if this is part of a larger if/else chain\n // (only analyze the outermost if statement)\n if (node.parent && node.parent.type === \"IfStatement\") return\n\n // Count the complexity (if/else if/else chain)\n if (ifElseChainLength(node) >= minComplexity) {\n context.report({\n node,\n messageId: \"preferFold\",\n data: { type: monadicInfo.type },\n suggest: suggestionsForIf(node),\n })\n }\n }\n\n return {\n IfStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n analyzeIfStatement(node)\n checkGuard(node)\n },\n\n ConditionalExpression(node: ASTNode) {\n if (isExemptByMarker(node)) return\n const monadicInfo = isMonadicCheck(node.test)\n // The untyped nullable heuristic can't distinguish a real Option from a plain nullable primitive.\n // When it fires on a ternary that yields `undefined`/`null` in a branch, that's optional value\n // construction (prefer-option's concern), not a fold — skip it. False positive this kills:\n // `x !== undefined ? \"a\" : undefined`. Predicate-call matches (`.isSome()` etc.) are unaffected.\n if (monadicInfo.via === \"nullable\" && (isNullishLiteral(node.consequent) || isNullishLiteral(node.alternate))) {\n return\n }\n if (monadicInfo.isMonadic) {\n context.report({\n node,\n messageId: \"preferFoldTernary\",\n data: { type: monadicInfo.type },\n suggest: isFunctypePredicateCall(node.test) ? ternarySuggestions(node) : [],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"iTAgBA,MAAMA,EAAsD,CAC1D,OAAQ,KACR,OAAQ,KACR,QAAS,CAAE,MAAO,OAAQ,OAAQ,OAAQ,EAC1C,OAAQ,CAAE,MAAO,OAAQ,OAAQ,OAAQ,EACzC,UAAW,CAAE,MAAO,QAAS,OAAQ,OAAQ,EAC7C,UAAW,CAAE,MAAO,QAAS,OAAQ,OAAQ,CAC/C,EAGMC,EAAkB,CAAC,MAAO,SAAS,EACnCC,EAAiB,QAOvB,SAASC,EAAiB,EAAwB,CAChD,OAAQC,EAAK,OAAS,WAAaA,EAAK,QAAU,MAAUA,EAAK,OAAS,cAAgBA,EAAK,OAAS,WAC1G,CAOA,SAASC,EACP,EACA,EACkE,CAClE,GAAIC,EAAK,OAAS,kBAAoBA,EAAK,OAAO,OAAS,mBAAoB,OAAO,KACtF,IAAMC,EAAaD,EAAK,OAAO,SAAS,KAClCE,EAAMC,EAAW,QAAQH,EAAK,OAAO,MAAM,EAC3CI,EAAUV,EAAaO,IAAe,KAG5C,OAFII,EAAoB,IAAIJ,CAAU,EAAU,CAAE,MAAK,UAAW,GAAO,SAAQ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AAI,EAAI,CAAC,CAC5E,CAAC,CAEL,CACF,CACF,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-functype",
3
- "version": "2.126.1",
3
+ "version": "2.127.0",
4
4
  "description": "Custom ESLint rules for functional TypeScript programming with functype library patterns including Do notation (ESLint 10+)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -42,7 +42,7 @@
42
42
  "@types/node": "^24.19.1",
43
43
  "@typescript-eslint/rule-tester": "^8.71.0",
44
44
  "eslint-config-prettier": "^10.1.8",
45
- "functype": "^1.26.1",
45
+ "functype": "^1.27.0",
46
46
  "ts-builds": "^4.5.0",
47
47
  "tsdown": "^0.23.0"
48
48
  },