eslint-plugin-functype 2.200.0 → 2.201.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 +30 -2
- package/dist/cli/list-rules.js.map +1 -1
- package/dist/configs/recommended.d.ts +5 -1
- package/dist/configs/recommended.js +1 -1
- package/dist/configs/recommended.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/rules/collection-naming.js.map +1 -1
- package/dist/rules/index.d.ts +13 -11
- package/dist/rules/index.js +1 -1
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/must-fold-on-component-return.js.map +1 -1
- package/dist/rules/no-array-mutation.js.map +1 -1
- package/dist/rules/no-floating-io.js.map +1 -1
- package/dist/rules/no-floating-result.js.map +1 -1
- package/dist/rules/no-get-unsafe.js.map +1 -1
- package/dist/rules/no-getOrThrow-in-render.js.map +1 -1
- package/dist/rules/no-imperative-loops.js.map +1 -1
- package/dist/rules/no-let.js.map +1 -1
- package/dist/rules/no-serialize-container.js.map +1 -1
- package/dist/rules/no-uncalled-method.d.ts +16 -0
- package/dist/rules/no-uncalled-method.js +2 -0
- package/dist/rules/no-uncalled-method.js.map +1 -0
- package/dist/rules/prefer-do-notation.js +1 -1
- package/dist/rules/prefer-do-notation.js.map +1 -1
- package/dist/rules/prefer-either.js.map +1 -1
- package/dist/rules/prefer-flatmap.js.map +1 -1
- package/dist/rules/prefer-fold.js +1 -1
- package/dist/rules/prefer-fold.js.map +1 -1
- package/dist/rules/prefer-functype-map.js.map +1 -1
- package/dist/rules/prefer-functype-set.js.map +1 -1
- package/dist/rules/prefer-list.js.map +1 -1
- package/dist/rules/prefer-map.js.map +1 -1
- package/dist/rules/prefer-option.js.map +1 -1
- package/dist/rules/prefer-try.js.map +1 -1
- package/dist/utils/array-mutation.d.ts +1 -1
- package/dist/utils/array-mutation.js.map +1 -1
- package/dist/utils/ast-walk.js.map +1 -1
- package/dist/utils/async-detection.js.map +1 -1
- package/dist/utils/boundary-tags.d.ts +1 -1
- package/dist/utils/boundary-tags.js.map +1 -1
- package/dist/utils/collection-binding.d.ts +1 -1
- package/dist/utils/collection-binding.js.map +1 -1
- package/dist/utils/dependency-validator.js.map +1 -1
- package/dist/utils/functype-detection.d.ts +1 -1
- package/dist/utils/functype-detection.js.map +1 -1
- package/dist/utils/functype-predicates.d.ts +1 -1
- package/dist/utils/functype-predicates.js.map +1 -1
- package/dist/utils/host-throws.d.ts +1 -1
- package/dist/utils/host-throws.js.map +1 -1
- package/dist/utils/import-fixer.js.map +1 -1
- package/dist/utils/mutable-collection.d.ts +1 -1
- package/dist/utils/mutable-collection.js.map +1 -1
- package/dist/utils/react-render.js.map +1 -1
- package/dist/utils/readonly-contract.js.map +1 -1
- package/dist/utils/type-aware.d.ts +13 -1
- package/dist/utils/type-aware.js +1 -1
- package/dist/utils/type-aware.js.map +1 -1
- package/dist/utils/wire-types.js.map +1 -1
- package/package.json +3 -3
|
@@ -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","containsYield","thunkBody","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, containsYield } 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(…).getOrElse(() => 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(…).getOrElse(() => …)` 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`, `getOrElse`… 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 suggestOrElse:\n \"Replace with {{receiver}}.orElse(() => {{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(…).getOrElse(() => 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 * `getOrElse` 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\n // `.orElse(() => b)`, and a fold would only rebuild it with an unused parameter. `.orElse` takes a\n // thunk that returns a container, so a literal or `undefined` fallback gets no suggestion at all:\n // neither `.orElse(() => 5)` nor a fold mixing a container with a plain value would type-check. An\n // `await` or `yield` in the fallback can't move into the thunk, so that gets none either.\n if (compact(successText) === compact(obj)) {\n if (failureNode.type === \"Literal\" || failureNode.type === \"TemplateLiteral\" || isNullishLiteral(failureNode)) {\n return []\n }\n if (containsAwait(failureNode) || containsYield(failureNode)) return []\n // An arrow body that starts with `{` reads as a block, and a sequence's comma would split the call's\n // arguments, so both go in parentheses: `{}.x` and `(b, c)` stay one expression.\n const needsParens = failureText.trimStart().startsWith(\"{\") || failureNode.type === \"SequenceExpression\"\n const thunkBody = needsParens ? `(${failureText})` : failureText\n return [\n {\n messageId: \"suggestOrElse\",\n data: { receiver: obj, alternative: failureText },\n fix: (fixer) => fixer.replaceText(node, `${obj}.orElse(() => ${thunkBody})`),\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":"A,oUAgBA,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,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,OAC5B,IAAMoH,EAAcN,EAAe9G,EAAK,IAAI,GAKxCoH,EAAY,MAAQ,YAAe,GAAiBpH,EAAK,UAAU,GAAK,GAAiBA,EAAK,SAAS,IAGvGoH,EAAY,WACd7C,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,KAAM6C,EAAY,IAAK,EAC/B,QAASP,EAAwB7G,EAAK,IAAI,EAAIsG,EAAmBtG,CAAI,EAAI,CAAC,CAC5E,CAAC,CAEL,CACF,CACF,CACF,E"}
|
|
1
|
+
{"version":3,"file":"prefer-fold.js","names":["childNodes","descendants","containsAwait","containsYield","isInsideTaggedDeclaration","NEGATIVE_PREDICATES","POSITIVE_PREDICATES","compact","FAILURE_SIDE","SUCCESS_METHODS","SUCCESS_MEMBER","isNullishLiteral","node","extractMonadicTest","test","sourceCode","methodName","obj","failure","SUCCESS_READS","receiverReads","branch","receiver","reads","isReceiver","target","isMember","names","visit","parent","isCalled","isWritten","freshName","base","branches","isTaken","name","b","_","i","asArrowBody","text","foldCallback","param","ranges","offset","rewritten","a","acc","start","end","buildFold","failureNode","successNode","onSuccess","returnedExpression","statement","ifElseChainLength","FAILURE_CONSTRUCTORS","readsMember","member","n","guardExitStatement","consequent","last","classifyGuardExit","failureMember","found","argument","callee","calleeName","args","unwrapsReceiver","statements","nodes","guardOf","extracted","rule","context","options","allowInteropMarker","isExemptByMarker","minComplexity","checkNullable","checkGuards","SEQUENCE_ADVICE","isAsync","GUARD_ADVICE","r","checkGuard","block","body","after","exit","sequenced","candidate","other","otherReceiver","otherAfter","kind","generateFoldFromIf","thenExpr","elseExpr","kept","c","isNegated","failureExpr","successExpr","ternarySuggestions","failureText","successText","thunkBody","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, containsYield } 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(…).getOrElse(() => 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(…).getOrElse(() => …)` 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`, `getOrElse`… 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 suggestOrElse:\n \"Replace with {{receiver}}.orElse(() => {{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(…).getOrElse(() => 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 * `getOrElse` 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\n // `.orElse(() => b)`, and a fold would only rebuild it with an unused parameter. `.orElse` takes a\n // thunk that returns a container, so a literal or `undefined` fallback gets no suggestion at all:\n // neither `.orElse(() => 5)` nor a fold mixing a container with a plain value would type-check. An\n // `await` or `yield` in the fallback can't move into the thunk, so that gets none either.\n if (compact(successText) === compact(obj)) {\n if (failureNode.type === \"Literal\" || failureNode.type === \"TemplateLiteral\" || isNullishLiteral(failureNode)) {\n return []\n }\n if (containsAwait(failureNode) || containsYield(failureNode)) return []\n // An arrow body that starts with `{` reads as a block, and a sequence's comma would split the call's\n // arguments, so both go in parentheses: `{}.x` and `(b, c)` stay one expression.\n const needsParens = failureText.trimStart().startsWith(\"{\") || failureNode.type === \"SequenceExpression\"\n const thunkBody = needsParens ? `(${failureText})` : failureText\n return [\n {\n messageId: \"suggestOrElse\",\n data: { receiver: obj, alternative: failureText },\n fix: (fixer) => fixer.replaceText(node, `${obj}.orElse(() => ${thunkBody})`),\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":"A,oUAgBA,MAAMQ,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,EAAiBC,EAAwB,CAChD,OAAQA,EAAK,OAAS,WAAaA,EAAK,QAAU,MAAUA,EAAK,OAAS,cAAgBA,EAAK,OAAS,WAC1G,CAOA,SAASC,EACPC,EACAC,EACkE,CAClE,GAAID,EAAK,OAAS,kBAAoBA,EAAK,OAAO,OAAS,mBAAoB,OAAO,KACtF,IAAME,EAAaF,EAAK,OAAO,SAAS,KAClCG,EAAMF,EAAW,QAAQD,EAAK,OAAO,MAAM,EAC3CI,EAAUV,EAAaQ,IAAe,KAG5C,OAFIV,EAAoB,IAAIU,CAAU,EAAU,CAAEC,MAAK,UAAW,GAAOC,SAAQ,EAC7Eb,EAAoB,IAAIW,CAAU,EAAU,CAAEC,MAAK,UAAW,GAAMC,SAAQ,EACzE,IACT,CAKA,MAAMC,EAAuB,CAAE,QAAS,CAACT,CAAc,EAAG,QAASD,CAAgB,EAQnF,SAASW,EACPC,EACAC,EACAC,EACAR,EAC0C,CAC1C,IAAMS,EAAcZ,GAA2B,CAC7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,CACblE,OACA,UAAW,oBACX,KAAM,CAAE,KAAM6G,EAAY,IAAK,EAC/B,QAASP,EAAwBtG,EAAK,IAAI,EAAIgG,EAAmBhG,CAAI,EAAI,CAAC,CAC5E,CAAC,CAEL,CACF,CACF,CACF,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-functype-map.js","names":["rule","options","context","allowInTests","allowMutable","isInTestFile","filename","functypeImports","getFunctypeImportsLegacy","node","bindingOf","isExplicitNativeCollection","isMutatedCollection","MAP_MUTATORS","flowsIntoReadonlyContract","isAlreadyUsingFunctype","sourceCode","imported","functypeLocalName","name","args","suggestions","fixer","mapOfArgs","el","argText","createImportFixer","typeName","annotatesMutatedBinding","typeParams","keyType","valueType"],"sources":["../../src/rules/prefer-functype-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { bindingOf, functypeLocalName, isExplicitNativeCollection } from \"../utils/collection-binding\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, MAP_MUTATORS } from \"../utils/mutable-collection\"\nimport { flowsIntoReadonlyContract } from \"../utils/readonly-contract\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functype Map<K, V> over native Map for immutable key-value collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowMutable: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFunctypeMap: \"Prefer functype Map<{{keyType}}, {{valueType}}> over native Map\",\n preferFunctypeMapLiteral: \"Prefer Map.of(...) or Map.empty() over new Map()\",\n suggestMapEmpty: \"Replace with {{name}}.empty()\",\n suggestMapOf: \"Replace with {{name}}.of(...)\",\n suggestMapFrom: \"Replace with {{name}}(...)\",\n suggestUseLocalName: \"Replace with {{name}}\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n // A native Map the code mutates on purpose (cache, registry, accumulator) is a deliberate choice —\n // functype's Map is immutable and cannot express it (#324).\n const allowMutable = options.allowMutable !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n const functypeImports = getFunctypeImportsLegacy(context)\n\n return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // The built-in, however it's spelled: bare `Map` that resolves to the global (functype's import\n // or a local shadow doesn't count, #350), or explicit `globalThis.Map` — the spelling the\n // functype-by-default convention uses, which must not be an escape hatch (#349).\n const isBareNative =\n node.callee?.type === \"Identifier\" &&\n node.callee.name === \"Map\" &&\n bindingOf(node.callee, \"Map\", context.sourceCode) === \"native\"\n if (!isBareNative && !isExplicitNativeCollection(node.callee, \"Map\", context.sourceCode)) return\n\n if (allowMutable && isMutatedCollection(node, MAP_MUTATORS, context.sourceCode)) return\n\n // A native Map flowing into a declared `ReadonlyMap` contract is what that contract requires (#350).\n if (flowsIntoReadonlyContract(node, \"ReadonlyMap\")) return\n\n // Skip if already using functype\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const imported = functypeLocalName(sourceCode, \"Map\")\n const name = imported ?? \"Map\"\n const args = node.arguments as ASTNode[]\n\n const suggestions: Rule.SuggestionReportDescriptor[] = []\n\n if (args.length === 0) {\n // new Map() → Map.empty()\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n } else if (args.length === 1 && args[0].type === \"ArrayExpression\") {\n // new Map([[\"a\", 1], [\"b\", 2]]) → Map.of([\"a\", 1], [\"b\", 2])\n const arrayArg = args[0] as ASTNode\n const elements = arrayArg.elements as ASTNode[]\n const tupleTexts = elements.map((el: ASTNode) => sourceCode.getText(el))\n const mapOfArgs = tupleTexts.join(\", \")\n suggestions.push({\n messageId: \"suggestMapOf\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.of(${mapOfArgs})`)\n },\n })\n } else if (args.length === 1) {\n // new Map(someVar) → Map(someVar)\n const argText = sourceCode.getText(args[0])\n suggestions.push({\n messageId: \"suggestMapFrom\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}(${argText})`)\n },\n })\n } else {\n // Generic fallback for any other args\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n }\n\n if (imported === null) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Map\" },\n fix: createImportFixer(sourceCode, \"Map\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferFunctypeMapLiteral\",\n suggest: suggestions,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (!node.typeName) return\n\n const sourceCode = context.sourceCode\n // `Map<…>` or the explicit `globalThis.Map<…>`.\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Map\" && typeName !== \"globalThis.Map\") return\n\n if (allowMutable && annotatesMutatedBinding(node, MAP_MUTATORS, context.sourceCode)) return\n\n if (node.typeName.type === \"Identifier\" && bindingOf(node.typeName, \"Map\", context.sourceCode) !== \"native\")\n return\n\n // Extract key/value type params if present (typeArguments for newer TS-ESLint, typeParameters for older)\n const typeParams = node.typeArguments?.params ?? node.typeParameters?.params\n const keyType = typeParams?.[0] ? sourceCode.getText(typeParams[0]) : \"K\"\n const valueType = typeParams && typeParams.length >= 2 ? sourceCode.getText(typeParams[1]) : \"V\"\n\n // Already imported under another name (`Map as FMap`): point at that name instead of adding a\n // second import that would shadow the native `Map` the rest of the file uses.\n const imported = functypeLocalName(sourceCode, \"Map\")\n const suggestions: Rule.SuggestionReportDescriptor[] =\n imported === null\n ? [{ messageId: \"suggestAddImport\", data: { symbol: \"Map\" }, fix: createImportFixer(sourceCode, \"Map\") }]\n : [\n {\n messageId: \"suggestUseLocalName\",\n data: { name: imported },\n fix: (fixer) => fixer.replaceText(node.typeName, imported),\n },\n ]\n\n context.report({\n node,\n messageId: \"preferFunctypeMap\",\n data: { keyType, valueType },\n suggest: suggestions,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,mdASA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,gFACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,EACA,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,kBAAmB,kEACnB,yBAA0B,mDAC1B,gBAAiB,gCACjB,aAAc,gCACd,eAAgB,6BAChB,oBAAqB,wBACrB,iBAAkB,qCACpB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EACjCC,EAAeF,EAAQ,eAAiB,GAGxCG,EAAeH,EAAQ,eAAiB,GAE9C,SAASI,GAAe,CACtB,IAAMC,EAAWJ,EAAQ,SACzB,MACE,kCAAkC,KAAKI,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,IAAMC,EAAkBC,EAAyBN,CAAO,EAExD,MAAO,CACL,cAAc,EAAe,CAkB3B,GAjBIC,GAAgBE,EAAa,IAM/BI,EAAK,QAAQ,OAAS,cACtBA,EAAK,OAAO,OAAS,O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a,MACfI,EAAY,KAAK,CACf,UAAW,mBACX,KAAM,CAAE,OAAQ,KAAM,EACtB,IAAKK,EAAkBV,EAAY,KAAK,CAC1C,CAAC,EAGHd,EAAQ,OAAO,CACb,OACA,UAAW,2BACX,QAASmB,CACX,CAAC,CACH,EAEA,gBAAgB,EAAe,CAG7B,GAFIlB,GAAgBE,EAAa,GAE7B,CAACI,EAAK,SAAU,OAEpB,IAAMO,EAAad,EAAQ,WAErByB,EAAWlB,EAAK,SAAS,OAAS,aAAeA,EAAK,SAAS,KAAOO,EAAW,QAAQP,EAAK,QAAQ,EAM5G,GAJIkB,IAAa,OAASA,IAAa,kBAEnCvB,GAAgBwB,EAAwBnB,EAAMI,EAAcX,EAAQ,UAAU,GAE9EO,EAAK,SAAS,OAAS,cAAgBC,EAAUD,EAAK,SAAU,MAAOP,EAAQ,UAAU,IAAM,SACjG,OAGF,IAAM2B,EAAapB,EAAK,eAAe,QAAUA,EAAK,gBAAgB,OAChEqB,EAAUD,IAAa,GAAKb,EAAW,QAAQa,EAAW,EAAE,EAAI,IAChEE,EAAYF,GAAcA,EAAW,QAAU,EAAIb,EAAW,QAAQa,EAAW,EAAE,EAAI,IAIvFZ,EAAWC,EAAkBF,EAAY,KAAK,EAC9CK,EACJJ,IAAa,KACT,CAAC,CAAE,UAAW,mBAAoB,KAAM,CAAE,OAAQ,KAAM,EAAG,IAAKS,EAAkBV,EAAY,KAAK,CAAE,CAAC,EACtG,CACE,CACE,UAAW,sBACX,KAAM,CAAE,KAAMC,CAAS,EACvB,IAAM,GAAUK,EAAM,YAAYb,EAAK,SAAUQ,CAAQ,CAC3D,CACF,EAENf,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,UAAS,WAAU,EAC3B,QAASmB,CACX,CAAC,CACH,CACF,CACF,CACF,E"}
|
|
1
|
+
{"version":3,"file":"prefer-functype-map.js","names":["bindingOf","functypeLocalName","isExplicitNativeCollection","getFunctypeImportsLegacy","isAlreadyUsingFunctype","createImportFixer","MAP_MUTATORS","annotatesMutatedBinding","isMutatedCollection","flowsIntoReadonlyContract","rule","context","options","allowInTests","allowMutable","isInTestFile","filename","functypeImports","node","sourceCode","imported","name","args","suggestions","fixer","mapOfArgs","el","argText","typeName","typeParams","keyType","valueType"],"sources":["../../src/rules/prefer-functype-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { bindingOf, functypeLocalName, isExplicitNativeCollection } from \"../utils/collection-binding\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, MAP_MUTATORS } from \"../utils/mutable-collection\"\nimport { flowsIntoReadonlyContract } from \"../utils/readonly-contract\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functype Map<K, V> over native Map for immutable key-value collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowMutable: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFunctypeMap: \"Prefer functype Map<{{keyType}}, {{valueType}}> over native Map\",\n preferFunctypeMapLiteral: \"Prefer Map.of(...) or Map.empty() over new Map()\",\n suggestMapEmpty: \"Replace with {{name}}.empty()\",\n suggestMapOf: \"Replace with {{name}}.of(...)\",\n suggestMapFrom: \"Replace with {{name}}(...)\",\n suggestUseLocalName: \"Replace with {{name}}\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n // A native Map the code mutates on purpose (cache, registry, accumulator) is a deliberate choice —\n // functype's Map is immutable and cannot express it (#324).\n const allowMutable = options.allowMutable !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n const functypeImports = getFunctypeImportsLegacy(context)\n\n return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // The built-in, however it's spelled: bare `Map` that resolves to the global (functype's import\n // or a local shadow doesn't count, #350), or explicit `globalThis.Map` — the spelling the\n // functype-by-default convention uses, which must not be an escape hatch (#349).\n const isBareNative =\n node.callee?.type === \"Identifier\" &&\n node.callee.name === \"Map\" &&\n bindingOf(node.callee, \"Map\", context.sourceCode) === \"native\"\n if (!isBareNative && !isExplicitNativeCollection(node.callee, \"Map\", context.sourceCode)) return\n\n if (allowMutable && isMutatedCollection(node, MAP_MUTATORS, context.sourceCode)) return\n\n // A native Map flowing into a declared `ReadonlyMap` contract is what that contract requires (#350).\n if (flowsIntoReadonlyContract(node, \"ReadonlyMap\")) return\n\n // Skip if already using functype\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const imported = functypeLocalName(sourceCode, \"Map\")\n const name = imported ?? \"Map\"\n const args = node.arguments as ASTNode[]\n\n const suggestions: Rule.SuggestionReportDescriptor[] = []\n\n if (args.length === 0) {\n // new Map() → Map.empty()\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n } else if (args.length === 1 && args[0].type === \"ArrayExpression\") {\n // new Map([[\"a\", 1], [\"b\", 2]]) → Map.of([\"a\", 1], [\"b\", 2])\n const arrayArg = args[0] as ASTNode\n const elements = arrayArg.elements as ASTNode[]\n const tupleTexts = elements.map((el: ASTNode) => sourceCode.getText(el))\n const mapOfArgs = tupleTexts.join(\", \")\n suggestions.push({\n messageId: \"suggestMapOf\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.of(${mapOfArgs})`)\n },\n })\n } else if (args.length === 1) {\n // new Map(someVar) → Map(someVar)\n const argText = sourceCode.getText(args[0])\n suggestions.push({\n messageId: \"suggestMapFrom\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}(${argText})`)\n },\n })\n } else {\n // Generic fallback for any other args\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n }\n\n if (imported === null) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Map\" },\n fix: createImportFixer(sourceCode, \"Map\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferFunctypeMapLiteral\",\n suggest: suggestions,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (!node.typeName) return\n\n const sourceCode = context.sourceCode\n // `Map<…>` or the explicit `globalThis.Map<…>`.\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Map\" && typeName !== \"globalThis.Map\") return\n\n if (allowMutable && annotatesMutatedBinding(node, MAP_MUTATORS, context.sourceCode)) return\n\n if (node.typeName.type === \"Identifier\" && bindingOf(node.typeName, \"Map\", context.sourceCode) !== \"native\")\n return\n\n // Extract key/value type params if present (typeArguments for newer TS-ESLint, typeParameters for older)\n const typeParams = node.typeArguments?.params ?? node.typeParameters?.params\n const keyType = typeParams?.[0] ? sourceCode.getText(typeParams[0]) : \"K\"\n const valueType = typeParams && typeParams.length >= 2 ? sourceCode.getText(typeParams[1]) : \"V\"\n\n // Already imported under another name (`Map as FMap`): point at that name instead of adding a\n // second import that would shadow the native `Map` the rest of the file uses.\n const imported = functypeLocalName(sourceCode, \"Map\")\n const suggestions: Rule.SuggestionReportDescriptor[] =\n imported === null\n ? [{ messageId: \"suggestAddImport\", data: { symbol: \"Map\" }, fix: createImportFixer(sourceCode, \"Map\") }]\n : [\n {\n messageId: \"suggestUseLocalName\",\n data: { name: imported },\n fix: (fixer) => fixer.replaceText(node.typeName, imported),\n },\n ]\n\n context.report({\n node,\n messageId: \"preferFunctypeMap\",\n data: { keyType, valueType },\n suggest: suggestions,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,mdASA,MAAMU,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,gFACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,EACA,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,kBAAmB,kEACnB,yBAA0B,mDAC1B,gBAAiB,gCACjB,aAAc,gCACd,eAAgB,6BAChB,oBAAqB,wBACrB,iBAAkB,qCACpB,CACF,EAEA,OAAOC,EAAS,CACd,IAAMC,EAAUD,EAAQ,QAAQ,IAAM,CAAC,EACjCE,EAAeD,EAAQ,eAAiB,GAGxCE,EAAeF,EAAQ,eAAiB,GAE9C,SAASG,GAAe,CACtB,IAAMC,EAAWL,EAAQ,SACzB,MACE,kCAAkC,KAAKK,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,IAAMC,EAAkBd,EAAyBQ,CAAO,EAExD,MAAO,CACL,cAAcO,EAAe,CAkB3B,GAjBIL,GAAgBE,EAAa,IAM/BG,EAAK,QAAQ,OAAS,cACtBA,EAAK,OAAO,OAAS,OACrBlB,EAAUkB,EAAK,OAAQ,MAAOP,EAAQ,UAAU,IAAM,WACnC,CAACT,EAA2BgB,EAAK,OAAQ,MAAOP,EAAQ,UAAU,GAEnFG,GAAgBN,EAAoBU,EAAMZ,EAAcK,EAAQ,UAAU,GAG1EF,EAA0BS,EAAM,aAAa,GAG7Cd,EAAuBc,EAAMD,CAAe,EAAG,OAEnD,IAAME,EAAaR,EAAQ,WACrBS,EAAWnB,EAAkBkB,EAAY,KA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AQ,WAErBiB,EAAWV,EAAK,SAAS,OAAS,aAAeA,EAAK,SAAS,KAAOC,EAAW,QAAQD,EAAK,QAAQ,EAM5G,GAJIU,IAAa,OAASA,IAAa,kBAEnCd,GAAgBP,EAAwBW,EAAMZ,EAAcK,EAAQ,UAAU,GAE9EO,EAAK,SAAS,OAAS,cAAgBlB,EAAUkB,EAAK,SAAU,MAAOP,EAAQ,UAAU,IAAM,SACjG,OAGF,IAAMkB,EAAaX,EAAK,eAAe,QAAUA,EAAK,gBAAgB,OAChEY,EAAUD,IAAa,GAAKV,EAAW,QAAQU,EAAW,EAAE,EAAI,IAChEE,EAAYF,GAAcA,EAAW,QAAU,EAAIV,EAAW,QAAQU,EAAW,EAAE,EAAI,IAIvFT,EAAWnB,EAAkBkB,EAAY,KAAK,EAC9CI,EACJH,IAAa,KACT,CAAC,CAAE,UAAW,mBAAoB,KAAM,CAAE,OAAQ,KAAM,EAAG,IAAKf,EAAkBc,EAAY,KAAK,CAAE,CAAC,EACtG,CACE,CACE,UAAW,sBACX,KAAM,CAAE,KAAMC,CAAS,EACvB,IAAMI,GAAUA,EAAM,YAAYN,EAAK,SAAUE,CAAQ,CAC3D,CACF,EAENT,EAAQ,OAAO,CACbO,OACA,UAAW,oBACX,KAAM,CAAEY,UAASC,WAAU,EAC3B,QAASR,CACX,CAAC,CACH,CACF,CACF,CACF,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-functype-set.js","names":["rule","options","context","allowInTests","allowMutable","isInTestFile","filename","functypeImports","getFunctypeImportsLegacy","node","bindingOf","isExplicitNativeCollection","isMutatedCollection","SET_MUTATORS","flowsIntoReadonlyContract","isAlreadyUsingFunctype","sourceCode","imported","functypeLocalName","name","args","suggestions","fixer","argsText","el","argText","createImportFixer","typeName","annotatesMutatedBinding","typeParamNode","typeParam"],"sources":["../../src/rules/prefer-functype-set.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { bindingOf, functypeLocalName, isExplicitNativeCollection } from \"../utils/collection-binding\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, SET_MUTATORS } from \"../utils/mutable-collection\"\nimport { flowsIntoReadonlyContract } from \"../utils/readonly-contract\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functype Set<T> over native Set for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowMutable: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFunctypeSet: \"Prefer functype Set<{{type}}> over native Set\",\n preferFunctypeSetLiteral: \"Prefer Set.of(...) or Set.empty() over new Set()\",\n suggestSetEmpty: \"Replace with {{name}}.empty()\",\n suggestSetOf: \"Replace with {{name}}.of(...)\",\n suggestSetFrom: \"Replace with {{name}}(...)\",\n suggestUseLocalName: \"Replace with {{name}}\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n // A native Set the code mutates on purpose (cache, registry, accumulator) is a deliberate choice —\n // functype's Set is immutable and cannot express it (#324).\n const allowMutable = options.allowMutable !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n const functypeImports = getFunctypeImportsLegacy(context)\n\n return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // The built-in, however it's spelled: bare `Set` that resolves to the global (functype's import\n // or a local shadow doesn't count, #350), or explicit `globalThis.Set` — the spelling the\n // functype-by-default convention uses, which must not be an escape hatch (#349).\n const isBareNative =\n node.callee?.type === \"Identifier\" &&\n node.callee.name === \"Set\" &&\n bindingOf(node.callee, \"Set\", context.sourceCode) === \"native\"\n if (!isBareNative && !isExplicitNativeCollection(node.callee, \"Set\", context.sourceCode)) return\n\n if (allowMutable && isMutatedCollection(node, SET_MUTATORS, context.sourceCode)) return\n\n // A native Set flowing into a declared `ReadonlySet` contract is what that contract requires (#350).\n if (flowsIntoReadonlyContract(node, \"ReadonlySet\")) return\n\n // Skip if already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const imported = functypeLocalName(sourceCode, \"Set\")\n const name = imported ?? \"Set\"\n const args = node.arguments || []\n const suggestions: Rule.SuggestionReportDescriptor[] = []\n\n if (args.length === 0) {\n // new Set() → Set.empty()\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n } else if (args.length === 1 && args[0].type === \"ArrayExpression\") {\n // new Set([\"a\", \"b\", \"c\"]) → Set.of(\"a\", \"b\", \"c\")\n const arrayNode = args[0]\n const elements = arrayNode.elements || []\n const elementTexts = elements.map((el: ASTNode) => sourceCode.getText(el))\n const argsText = elementTexts.join(\", \")\n suggestions.push({\n messageId: \"suggestSetOf\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.of(${argsText})`)\n },\n })\n } else if (args.length === 1) {\n // new Set(someVar) → Set(someVar)\n const argText = sourceCode.getText(args[0])\n suggestions.push({\n messageId: \"suggestSetFrom\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}(${argText})`)\n },\n })\n } else {\n // Fallback for unexpected cases\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n }\n\n if (imported === null) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Set\" },\n fix: createImportFixer(sourceCode, \"Set\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferFunctypeSetLiteral\",\n suggest: suggestions,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (!node.typeName) return\n\n const sourceCode = context.sourceCode\n // `Set<…>` or the explicit `globalThis.Set<…>`.\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Set\" && typeName !== \"globalThis.Set\") return\n\n if (allowMutable && annotatesMutatedBinding(node, SET_MUTATORS, context.sourceCode)) return\n\n if (node.typeName.type === \"Identifier\" && bindingOf(node.typeName, \"Set\", context.sourceCode) !== \"native\")\n return\n\n // Extract type parameter if present (typeArguments for newer TS-ESLint, typeParameters for older)\n const typeParamNode = node.typeParameters?.params?.[0] ?? node.typeArguments?.params?.[0]\n const typeParam = typeParamNode ? sourceCode.getText(typeParamNode) : \"T\"\n\n // Already imported under another name (`Set as FSet`): point at that name instead of adding a\n // second import that would shadow the native `Set` the rest of the file uses.\n const imported = functypeLocalName(sourceCode, \"Set\")\n const suggestions: Rule.SuggestionReportDescriptor[] =\n imported === null\n ? [{ messageId: \"suggestAddImport\", data: { symbol: \"Set\" }, fix: createImportFixer(sourceCode, \"Set\") }]\n : [\n {\n messageId: \"suggestUseLocalName\",\n data: { name: imported },\n fix: (fixer) => fixer.replaceText(node.typeName, imported),\n },\n ]\n\n context.report({\n node,\n messageId: \"preferFunctypeSet\",\n data: { type: typeParam },\n suggest: suggestions,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,mdASA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,mEACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,EACA,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA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,EAAW,QAAQa,CAAa,EAAI,IAIhEZ,EAAWC,EAAkBF,EAAY,KAAK,EAC9CK,EACJJ,IAAa,KACT,CAAC,CAAE,UAAW,mBAAoB,KAAM,CAAE,OAAQ,KAAM,EAAG,IAAKS,EAAkBV,EAAY,KAAK,CAAE,CAAC,EACtG,CACE,CACE,UAAW,sBACX,KAAM,CAAE,KAAMC,CAAS,EACvB,IAAM,GAAUK,EAAM,YAAYb,EAAK,SAAUQ,CAAQ,CAC3D,CACF,EAENf,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,KAAM4B,CAAU,EACxB,QAAST,CACX,CAAC,CACH,CACF,CACF,CACF,E"}
|
|
1
|
+
{"version":3,"file":"prefer-functype-set.js","names":["bindingOf","functypeLocalName","isExplicitNativeCollection","getFunctypeImportsLegacy","isAlreadyUsingFunctype","createImportFixer","SET_MUTATORS","annotatesMutatedBinding","isMutatedCollection","flowsIntoReadonlyContract","rule","context","options","allowInTests","allowMutable","isInTestFile","filename","functypeImports","node","sourceCode","imported","name","args","suggestions","fixer","argsText","el","argText","typeName","typeParamNode","typeParam"],"sources":["../../src/rules/prefer-functype-set.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { bindingOf, functypeLocalName, isExplicitNativeCollection } from \"../utils/collection-binding\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, SET_MUTATORS } from \"../utils/mutable-collection\"\nimport { flowsIntoReadonlyContract } from \"../utils/readonly-contract\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functype Set<T> over native Set for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowMutable: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFunctypeSet: \"Prefer functype Set<{{type}}> over native Set\",\n preferFunctypeSetLiteral: \"Prefer Set.of(...) or Set.empty() over new Set()\",\n suggestSetEmpty: \"Replace with {{name}}.empty()\",\n suggestSetOf: \"Replace with {{name}}.of(...)\",\n suggestSetFrom: \"Replace with {{name}}(...)\",\n suggestUseLocalName: \"Replace with {{name}}\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n // A native Set the code mutates on purpose (cache, registry, accumulator) is a deliberate choice —\n // functype's Set is immutable and cannot express it (#324).\n const allowMutable = options.allowMutable !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n const functypeImports = getFunctypeImportsLegacy(context)\n\n return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // The built-in, however it's spelled: bare `Set` that resolves to the global (functype's import\n // or a local shadow doesn't count, #350), or explicit `globalThis.Set` — the spelling the\n // functype-by-default convention uses, which must not be an escape hatch (#349).\n const isBareNative =\n node.callee?.type === \"Identifier\" &&\n node.callee.name === \"Set\" &&\n bindingOf(node.callee, \"Set\", context.sourceCode) === \"native\"\n if (!isBareNative && !isExplicitNativeCollection(node.callee, \"Set\", context.sourceCode)) return\n\n if (allowMutable && isMutatedCollection(node, SET_MUTATORS, context.sourceCode)) return\n\n // A native Set flowing into a declared `ReadonlySet` contract is what that contract requires (#350).\n if (flowsIntoReadonlyContract(node, \"ReadonlySet\")) return\n\n // Skip if already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const imported = functypeLocalName(sourceCode, \"Set\")\n const name = imported ?? \"Set\"\n const args = node.arguments || []\n const suggestions: Rule.SuggestionReportDescriptor[] = []\n\n if (args.length === 0) {\n // new Set() → Set.empty()\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n } else if (args.length === 1 && args[0].type === \"ArrayExpression\") {\n // new Set([\"a\", \"b\", \"c\"]) → Set.of(\"a\", \"b\", \"c\")\n const arrayNode = args[0]\n const elements = arrayNode.elements || []\n const elementTexts = elements.map((el: ASTNode) => sourceCode.getText(el))\n const argsText = elementTexts.join(\", \")\n suggestions.push({\n messageId: \"suggestSetOf\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.of(${argsText})`)\n },\n })\n } else if (args.length === 1) {\n // new Set(someVar) → Set(someVar)\n const argText = sourceCode.getText(args[0])\n suggestions.push({\n messageId: \"suggestSetFrom\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}(${argText})`)\n },\n })\n } else {\n // Fallback for unexpected cases\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n }\n\n if (imported === null) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Set\" },\n fix: createImportFixer(sourceCode, \"Set\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferFunctypeSetLiteral\",\n suggest: suggestions,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (!node.typeName) return\n\n const sourceCode = context.sourceCode\n // `Set<…>` or the explicit `globalThis.Set<…>`.\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Set\" && typeName !== \"globalThis.Set\") return\n\n if (allowMutable && annotatesMutatedBinding(node, SET_MUTATORS, context.sourceCode)) return\n\n if (node.typeName.type === \"Identifier\" && bindingOf(node.typeName, \"Set\", context.sourceCode) !== \"native\")\n return\n\n // Extract type parameter if present (typeArguments for newer TS-ESLint, typeParameters for older)\n const typeParamNode = node.typeParameters?.params?.[0] ?? node.typeArguments?.params?.[0]\n const typeParam = typeParamNode ? sourceCode.getText(typeParamNode) : \"T\"\n\n // Already imported under another name (`Set as FSet`): point at that name instead of adding a\n // second import that would shadow the native `Set` the rest of the file uses.\n const imported = functypeLocalName(sourceCode, \"Set\")\n const suggestions: Rule.SuggestionReportDescriptor[] =\n imported === null\n ? [{ messageId: \"suggestAddImport\", data: { symbol: \"Set\" }, fix: createImportFixer(sourceCode, \"Set\") }]\n : [\n {\n messageId: \"suggestUseLocalName\",\n data: { name: imported },\n fix: (fixer) => fixer.replaceText(node.typeName, imported),\n },\n ]\n\n context.report({\n node,\n messageId: \"preferFunctypeSet\",\n data: { type: typeParam },\n suggest: suggestions,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,mdASA,MAAMU,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,mEACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,EACA,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,kBAAmB,gDACnB,yBAA0B,mDAC1B,gBAAiB,gCACjB,aAAc,gCACd,eAAgB,6BAChB,oBAAqB,wBACrB,iBAAkB,qCACpB,CACF,EAEA,OAAOC,EAAS,CACd,IAAMC,EAAUD,EAAQ,QAAQ,IAAM,CAAC,EACjCE,EAAeD,EAAQ,eAAiB,GAGxCE,EAAeF,EAAQ,eAAiB,GAE9C,SAASG,GAAe,CACtB,IAAMC,EAAWL,EAAQ,SACzB,MACE,kCAAkC,KAAKK,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,IAAMC,EAAkBd,EAAyBQ,CAAO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1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-list.js","names":["NON_CHILD_KEYS","astChildren","node","k","v","ancestorSatisfies","parent","pred","isListFactoryArg","isTupleAssertion","raw","annotation","MUTATING_METHODS","throughConditionals","TERMINAL_METHODS","chainEnd","member","receiver","call","chainEndsInSingleValue","isTerminalRead","isJsxChild","grand","name","isSpreadIntoCall","annotatedBinding","climb","n","typeNode","returningFunctionName","fn","declarator","annotatedFieldName","field","castOf","child","outer","current","exportedTypeName","declaration","statement","isSupabaseGeneratedTypes","names","program","hasOwnTypeAnnotation","rule","WIRE_TYPES_SCHEMA","header","context","comment","options","wireTypes","DEFAULT_WIRE_TYPES","allowArraysInTests","allowReadonlyArrays","allowArrayLiterals","functypeImports","getFunctypeImportsLegacy","isInTestFile","filename","findTypeParameter","findInNode","sourceCode","c","r","isFunctypeConstructorArg","reachesArraySlot","flowsIntoArraySlot","isOnlyHandedToArraySlots","uses","variable","ref","usesOf","owner","binding","mutationOf","identifier","how","mutatedFields","fieldMutationIn","entries","descendants","method","target","feedsMutableSlot","flowsIntoMutableArraySlot","leftToArrayMutation","hasTypeInformation","isMutableArrayExpression","checkMutable","cast","reportNode","castSource","source","decodes","isUntypedExpression","elementType","fullType","fixer","fnName","fieldMutation","reportMutable","suggest","hasFunctypeSymbol","createImportFixer","readonlyUtilityWrapper","instantiation","params","wrapper","reportReadonly","isInsideWireType","utility","readonlyNode","typeName","typeParam","isFunctypeCall","targetParent","end","el","elementTexts"],"sources":["../../src/rules/prefer-list.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { isMutableArrayExpression } from \"../utils/array-mutation\"\nimport { descendants } from \"../utils/ast-walk\"\nimport { getFunctypeImportsLegacy, isFunctypeCall } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport {\n flowsIntoArraySlot,\n flowsIntoMutableArraySlot,\n hasTypeInformation,\n isUntypedExpression,\n} from \"../utils/type-aware\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\n\n/** AST keys that don't represent syntax children — back-edges and source metadata. */\nconst NON_CHILD_KEYS: ReadonlySet<string> = new Set([\"parent\", \"loc\", \"range\"])\n\n/** AST children of `node`: drops back-edges, flattens array-valued keys, filters non-object leaves. */\nfunction astChildren(node: ASTNode): readonly unknown[] {\n return Object.entries(node)\n .filter(([k]) => !NON_CHILD_KEYS.has(k))\n .flatMap(([, v]) => (Array.isArray(v) ? v : [v]))\n .filter((v) => v !== null && typeof v === \"object\")\n}\n\n/** True iff any ancestor of `node` satisfies `pred`. Pure tail recursion. */\nfunction ancestorSatisfies(node: ASTNode | null | undefined, pred: (n: ASTNode) => boolean): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return pred(parent) || ancestorSatisfies(parent, pred)\n}\n\n/** `parent` is `List.from(arr)` or `List.of(...arr)`. */\nfunction isListFactoryArg(parent: ASTNode | null | undefined): boolean {\n return (\n parent?.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n parent.callee.object.type === \"Identifier\" &&\n parent.callee.object.name === \"List\" &&\n [\"from\", \"of\"].includes(parent.callee.property.name)\n )\n}\n\n/**\n * `[…] as const` or `[…] as [string, ...string[]]`: the literal is asserted to a tuple, a fixed shape that\n * `List` can't express (an enum's values, the argument zod's `z.enum` requires).\n */\nfunction isTupleAssertion(parent: ASTNode | null | undefined): boolean {\n const raw = parent?.type === \"TSAsExpression\" ? parent.typeAnnotation : undefined\n const annotation = raw?.type === \"TSTypeOperator\" ? raw.typeAnnotation : raw\n if (annotation?.type === \"TSTupleType\") return true\n return (\n annotation?.type === \"TSTypeReference\" &&\n annotation.typeName?.type === \"Identifier\" &&\n annotation.typeName.name === \"const\"\n )\n}\n\n/** Array methods that change the array in place. */\nconst MUTATING_METHODS: ReadonlySet<string> = new Set([\n \"push\",\n \"pop\",\n \"shift\",\n \"unshift\",\n \"splice\",\n \"sort\",\n \"reverse\",\n \"fill\",\n \"copyWithin\",\n])\n\n/**\n * The expression a literal stands in for once conditionals are looked through: `[x]` in\n * `List(c ? xs : [x])` or `const args = c ? [a] : [\"--fix\", a]` behaves like the whole conditional.\n */\nfunction throughConditionals(node: ASTNode): ASTNode {\n const parent = node.parent as ASTNode | undefined\n if (parent?.type === \"ConditionalExpression\" && parent.test !== node) return throughConditionals(parent)\n if (parent?.type === \"LogicalExpression\") return throughConditionals(parent)\n return node\n}\n\n/**\n * Methods that turn an array into a single value: using a collection only through these makes it a\n * temporary (`lines.join(\"\\n\")`, `[a, b].includes(x)`). Methods that produce another collection\n * (`map`, `filter`, `slice`, `concat`, `reduce`…) are collection work, which is what `List` is for.\n */\nconst TERMINAL_METHODS: ReadonlySet<string> = new Set([\n \"join\",\n \"includes\",\n \"indexOf\",\n \"lastIndexOf\",\n \"some\",\n \"every\",\n \"find\",\n \"findIndex\",\n \"findLast\",\n \"findLastIndex\",\n \"at\",\n])\n\n/**\n * The end of a method chain that starts at `receiver`: `[…].map(f).filter(g)` → the `.filter(g)` call.\n * `receiver` itself when no method is called on it.\n */\nfunction chainEnd(receiver: ASTNode): ASTNode {\n const member = receiver.parent as ASTNode | undefined\n const call = member?.parent as ASTNode | undefined\n if (member?.type !== \"MemberExpression\" || member.object !== receiver) return receiver\n return call?.type === \"CallExpression\" && call.callee === member ? chainEnd(call) : receiver\n}\n\n/**\n * Does the method chain starting at `receiver` end in a single value: `[a, b].filter(Boolean).length`,\n * `[name, email].filter(nonEmpty).join(\"\\n\")`, `[...xs].sort(byRank)[0]`? Then every array in it is a\n * temporary, the same as `lines.join(\"\\n\")`.\n */\nfunction chainEndsInSingleValue(receiver: ASTNode): boolean {\n if (isTerminalRead(receiver)) return true\n const member = receiver.parent as ASTNode | undefined\n const call = member?.parent as ASTNode | undefined\n if (member?.type !== \"MemberExpression\" || member.object !== receiver) return false\n return call?.type === \"CallExpression\" && call.callee === member && chainEndsInSingleValue(call)\n}\n\n/** `{items.map((i) => <Row />)}`: an expression rendered as JSX children, which React takes as an array. */\nfunction isJsxChild(node: ASTNode): boolean {\n return (node.parent as ASTNode | undefined)?.type === \"JSXExpressionContainer\"\n}\n\n/**\n * Is `receiver` read down to a single value on the spot: `.length`, `[i]`, or a terminal method call?\n * The same test applies to a literal (`[a, b].includes(x)`) and to every use of a const (`lines.join`).\n */\nfunction isTerminalRead(receiver: ASTNode): boolean {\n const member = receiver.parent as ASTNode | undefined\n if (member?.type !== \"MemberExpression\" || member.object !== receiver) return false\n const grand = member.parent as ASTNode | undefined\n if (grand?.type === \"AssignmentExpression\" && grand.left === member) return false\n if (member.computed) return true\n const name = member.property?.type === \"Identifier\" ? member.property.name : null\n if (name === \"length\") return true\n return name !== null && TERMINAL_METHODS.has(name) && grand?.type === \"CallExpression\" && grand.callee === member\n}\n\n/**\n * Is `node` spread straight into a call's arguments, `and(...conds)` or `and(...(c ? [x] : []))`?\n * The function receives the elements one by one; the array is never a collection of your own.\n */\nfunction isSpreadIntoCall(node: ASTNode): boolean {\n const parent = node.parent as ASTNode | undefined\n if (!parent) return false\n if (parent.type === \"ConditionalExpression\" && parent.test !== node) return isSpreadIntoCall(parent)\n if (parent.type === \"LogicalExpression\" && parent.right === node) return isSpreadIntoCall(parent)\n return (\n parent.type === \"SpreadElement\" &&\n (parent.parent?.type === \"CallExpression\" || parent.parent?.type === \"NewExpression\")\n )\n}\n\n/** The `x` in `const x: T[] = …` or `(x: T[]) => …`, when the array type is (part of) its annotation. */\nfunction annotatedBinding(typeNode: ASTNode): ASTNode | null {\n const climb = (n: ASTNode | null | undefined): ASTNode | null => {\n if (!n) return null\n if (n.type === \"TSTypeAnnotation\") return n.parent?.type === \"Identifier\" ? (n.parent as ASTNode) : null\n if (n.type === \"TSAsExpression\" || n.type === \"TSSatisfiesExpression\" || n.type.endsWith(\"Statement\")) return null\n return climb(n.parent as ASTNode | undefined)\n }\n return climb(typeNode.parent as ASTNode | undefined)\n}\n\n/**\n * The name of the function whose declared return type *is* this array type: `f` in\n * `function f(): T[]` or `const f = (): T[] => …`. Null for anything nested (`(): { nodes: T[] }`).\n */\nfunction returningFunctionName(typeNode: ASTNode): ASTNode | null {\n const annotation = typeNode.parent as ASTNode | undefined\n const fn = annotation?.type === \"TSTypeAnnotation\" ? (annotation.parent as ASTNode | undefined) : undefined\n if (!fn || fn.returnType !== annotation) return null\n if (fn.type === \"FunctionDeclaration\") return fn.id?.type === \"Identifier\" ? (fn.id as ASTNode) : null\n const declarator = fn.parent as ASTNode | undefined\n return (fn.type === \"ArrowFunctionExpression\" || fn.type === \"FunctionExpression\") &&\n declarator?.type === \"VariableDeclarator\" &&\n declarator.init === fn &&\n declarator.id?.type === \"Identifier\"\n ? (declarator.id as ASTNode)\n : null\n}\n\n/** The property name when the array type annotates a field: `errors` in `{ errors: string[] }` or `class { errors: T[] }`. */\nfunction annotatedFieldName(typeNode: ASTNode): string | null {\n const annotation = typeNode.parent as ASTNode | undefined\n const field = annotation?.type === \"TSTypeAnnotation\" ? (annotation.parent as ASTNode | undefined) : undefined\n if (field?.type !== \"TSPropertySignature\" && field?.type !== \"PropertyDefinition\") return null\n return field.key?.type === \"Identifier\" && !field.computed ? field.key.name : null\n}\n\n/** The outermost `x as … as T[]` around an array type used as a cast target, or null. */\nfunction castOf(typeNode: ASTNode): ASTNode | null {\n const climb = (n: ASTNode | null | undefined, child: ASTNode): ASTNode | null => {\n if (!n || n.type === \"TSTypeAnnotation\" || n.type.endsWith(\"Statement\")) return null\n if (n.type === \"TSAsExpression\" && n.typeAnnotation === child) {\n const outer = (current: ASTNode): ASTNode =>\n current.parent?.type === \"TSAsExpression\" ? outer(current.parent as ASTNode) : current\n return outer(n)\n }\n return climb(n.parent as ASTNode | undefined, n)\n }\n return climb(typeNode.parent as ASTNode | undefined, typeNode)\n}\n\n/** Names a top-level `export type X = …` or `export interface X` declares. */\nfunction exportedTypeName(statement: ASTNode): string | undefined {\n const declaration = statement.type === \"ExportNamedDeclaration\" ? (statement.declaration as ASTNode | null) : null\n if (declaration?.type !== \"TSTypeAliasDeclaration\" && declaration?.type !== \"TSInterfaceDeclaration\") return undefined\n return (declaration.id as ASTNode | undefined)?.name as string | undefined\n}\n\n/**\n * Supabase's generated types (`supabase gen types typescript`) carry no generated-file marker, but\n * always export both `type Json` and `Database` (a type alias, or an interface from older CLIs) at\n * the top level. No hand-written module exports that pair, so the shape identifies the file.\n */\nfunction isSupabaseGeneratedTypes(program: ASTNode): boolean {\n const names = new Set((program.body as ASTNode[]).map(exportedTypeName))\n return names.has(\"Json\") && names.has(\"Database\")\n}\n\n/** `node` is a VariableDeclarator with its own type annotation, or a TSTypeAnnotation node directly. */\nfunction hasOwnTypeAnnotation(node: ASTNode): boolean {\n return (node.type === \"VariableDeclarator\" && Boolean(node.id?.typeAnnotation)) || node.type === \"TSTypeAnnotation\"\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer List<T> over native arrays for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowArraysInTests: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowReadonlyArrays: {\n type: \"boolean\",\n default: true,\n },\n allowArrayLiterals: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferList: \"Prefer List<{{type}}> over array type {{arrayType}}\",\n preferReadonlyOrList:\n \"Mutable array type {{arrayType}}: anything holding it can change it. Use ReadonlyArray<{{type}}>, which every caller and library accepts, or List<{{type}}> for a collection you transform\",\n preferWireCast:\n \"Cast to the mutable array {{arrayType}}: this is data decoded from outside. Declare its shape once as Wire<ReadonlyArray<{{type}}>> (functype's boundary marker) and cast to that\",\n mutatedArray:\n \"{{name}} is a mutable array changed in place (.{{how}}()). Build it without mutation instead: map/filter/flatMap, a List, or a fold\",\n preferListLiteral: \"Prefer List.of(...) or List.from([...]) over array literal\",\n suggestListType: \"Replace with List<{{type}}>\",\n suggestReadonlyArray: \"Replace with ReadonlyArray<{{type}}>\",\n suggestListOf: \"Replace with List.of(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n // A generated file (`// @generated`, \"Auto-generated … DO NOT EDIT\") isn't edited by hand, so there's\n // nothing for its author to fix. Supabase's types have no marker and are recognized by shape.\n const header = context.sourceCode\n .getAllComments()\n .slice(0, 3)\n .map((comment) => comment.value)\n .join(\"\\n\")\n if (/@generated|auto-generated|do not edit/i.test(header)) return {}\n if (isSupabaseGeneratedTypes(context.sourceCode.ast as unknown as ASTNode)) return {}\n\n const options = context.options[0] || {}\n // Everything inside `Wire<…>` is the declared serialization shape (#325 B).\n const wireTypes: ReadonlyArray<string> = options.wireTypes ?? DEFAULT_WIRE_TYPES\n const allowArraysInTests = options.allowArraysInTests !== false\n const allowReadonlyArrays = options.allowReadonlyArrays !== false\n const allowArrayLiterals = options.allowArrayLiterals === true\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function findTypeParameter(node: ASTNode, sourceCode: typeof context.sourceCode): string | null {\n // Pure pre-order search: look at this node, then recursively at each\n // child until we find a TSTypeParameterInstantiation with a first param.\n function findInNode(n: ASTNode): string | null {\n if (n.type === \"TSTypeParameterInstantiation\" && n.params && n.params[0]) {\n return sourceCode.getText(n.params[0])\n }\n const results = astChildren(n)\n .filter((c): c is ASTNode => typeof (c as ASTNode)?.type === \"string\")\n .map((child) => findInNode(child))\n return results.find((r) => r !== null) ?? null\n }\n return findInNode(node)\n }\n\n /** `List([...x])`, `Set([a, b])`: the literal is already being captured into a functype value. */\n function isFunctypeConstructorArg(node: ASTNode, parent: ASTNode | null | undefined): boolean {\n return (\n parent?.type === \"CallExpression\" &&\n parent.callee.type === \"Identifier\" &&\n functypeImports.has(parent.callee.name) &&\n parent.arguments.includes(node)\n )\n }\n\n /** Is `node` handed straight to an array-typed slot, directly or spread into a literal that is? */\n function reachesArraySlot(node: ASTNode): boolean {\n if (flowsIntoArraySlot(node, context) === true) return true\n if (isSpreadIntoCall(node)) return true\n const parent = node.parent as ASTNode | undefined\n return (\n parent?.type === \"SpreadElement\" &&\n parent.parent?.type === \"ArrayExpression\" &&\n flowsIntoArraySlot(parent.parent as ASTNode, context) === true\n )\n }\n\n /**\n * `const OPTIONS = [...]` whose every use hands it to an array-typed slot (`<Select data={OPTIONS} />`,\n * `db.insert(t).values(ROWS)`) or reads it down to a single value (`lines.join(\"\\n\")`, `xs.length`): data\n * built to give to a library, or a temporary, declared before it's used. Needs at least one local use; an exported\n * constant with no local use is still reported, because its consumers aren't visible here.\n */\n function isOnlyHandedToArraySlots(declarator: ASTNode | null | undefined): boolean {\n if (declarator?.type !== \"VariableDeclarator\" || declarator.id?.type !== \"Identifier\") return false\n const uses = context.sourceCode\n .getDeclaredVariables(declarator)\n .flatMap((variable) => variable.references.filter((ref) => !ref.init))\n return (\n uses.length > 0 &&\n uses.every((ref) => reachesArraySlot(ref.identifier as ASTNode) || isTerminalRead(ref.identifier as ASTNode))\n )\n }\n\n /** References to `binding` other than its declaration. */\n function usesOf(binding: ASTNode): ReadonlyArray<{ identifier: ASTNode }> {\n // The declaring node: a VariableDeclarator, a FunctionDeclaration (its name lives in the outer\n // scope) or, for a parameter, its function. getDeclaredVariables on it yields the binding.\n const owner = (binding.parent as ASTNode | undefined) ?? binding\n const variable =\n context.sourceCode.getDeclaredVariables(owner).find((v) => v.name === binding.name) ??\n context.sourceCode.getScope(binding).set.get(binding.name)\n return (variable?.references ?? [])\n .filter((ref) => !ref.init && ref.identifier !== binding)\n .map((ref) => ({ identifier: ref.identifier as ASTNode }))\n }\n\n /** The in-place mutation applied to `binding` (`push`, `sort`, `x[i] = …`), if any. */\n function mutationOf(binding: ASTNode): string | null {\n const found = usesOf(binding)\n .map(({ identifier }) => {\n const parent = identifier.parent as ASTNode | undefined\n if (parent?.type !== \"MemberExpression\" || parent.object !== identifier) return null\n const grand = parent.parent as ASTNode | undefined\n if (grand?.type === \"AssignmentExpression\" && grand.left === parent)\n return parent.computed ? \"[index] =\" : null\n const name = parent.property?.type === \"Identifier\" && !parent.computed ? parent.property.name : null\n return name && MUTATING_METHODS.has(name) && grand?.type === \"CallExpression\" && grand.callee === parent\n ? name\n : null\n })\n .find((how) => how !== null)\n return found ?? null\n }\n\n /**\n * Fields mutated in place anywhere in the file, `errors` → `push` for `t.errors.push(e)`. Built once per\n * file, on first use, from the syntax tree.\n */\n const mutatedFields: { map?: ReadonlyMap<string, string> } = {}\n function fieldMutationIn(field: string): string | null {\n if (!mutatedFields.map) {\n const entries = descendants(context.sourceCode.ast as unknown as ASTNode).flatMap(\n (node): [string, string][] => {\n if (node.type !== \"CallExpression\" || node.callee?.type !== \"MemberExpression\") return []\n const method = node.callee.property?.type === \"Identifier\" ? node.callee.property.name : null\n const target = node.callee.object as ASTNode\n const name =\n target?.type === \"MemberExpression\" && target.property?.type === \"Identifier\" && !target.computed\n ? target.property.name\n : null\n return method && name && MUTATING_METHODS.has(method) ? [[name, method]] : []\n },\n )\n mutatedFields.map = new globalThis.Map(entries.reverse())\n }\n return mutatedFields.map.get(field) ?? null\n }\n\n /** Is `binding` handed to a slot that requires a mutable array (pg `query` values, ReactFlow `nodes`)? */\n function feedsMutableSlot(binding: ASTNode): boolean {\n return usesOf(binding).some(({ identifier }) => flowsIntoMutableArraySlot(identifier, context) === true)\n }\n\n /**\n * A local array changed in place by a method (`acc.push(x)`) or an index write (`acc[i] = x`) is one\n * mistake, building it by mutation, with two sites. With type information, no-array-mutation reports\n * the change itself, which is where the fix goes, so this rule leaves the declaration to it rather\n * than report it twice. Without type information no-array-mutation reports nothing, so the\n * declaration gets the advice. Fields stay reported here: they are matched by name across the file,\n * which can't tell which declaration a mutation belongs to.\n */\n function leftToArrayMutation(binding: ASTNode): boolean {\n // no-array-mutation sees only a plain mutable array: an intersection such as\n // `string[] & { tag?: string }` it skips, so this rule must still report that one.\n return hasTypeInformation(context) && isMutableArrayExpression(binding, context)\n }\n\n /**\n * Report a mutable array type, unless a library demands it. The order matters: a library slot that\n * requires `T[]` makes the type correct as written; a binding mutated in place can't take\n * `ReadonlyArray` without a rewrite, so it gets advice instead of a suggestion that wouldn't compile;\n * a cast is decoded outside data, so it points at `Wire`.\n */\n function checkMutable(reportNode: ASTNode, elementType: string, fullType: string): void {\n const cast = castOf(reportNode)\n // The value under every `as`: `JSON.parse(raw)` in `JSON.parse(raw) as unknown as T[]`.\n const castSource = (n: ASTNode): ASTNode =>\n n.type === \"TSAsExpression\" ? castSource(n.expression as ASTNode) : n\n if (cast && flowsIntoMutableArraySlot(cast, context) === true) return\n // Only a cast of an untyped value (`JSON.parse`, `res.json()`, a raw row) is decoding outside data,\n // the Wire case. It needs type evidence: without it the rule can't tell decoding from re-casting a\n // typed value, so it gives the plain message rather than advice that flips when types are turned on.\n const source = cast ? castSource(cast) : null\n const decodes =\n source !== null && source.type !== \"ArrayExpression\" && isUntypedExpression(source, context) === true\n if (cast && decodes) {\n context.report({\n node: reportNode,\n messageId: \"preferWireCast\",\n data: { type: elementType, arrayType: fullType },\n suggest: [\n {\n messageId: \"suggestReadonlyArray\",\n data: { type: elementType },\n fix: (fixer: Rule.RuleFixer) => fixer.replaceText(reportNode, `ReadonlyArray<${elementType}>`),\n },\n ],\n })\n return\n }\n // `function allowedTools(): string[]` whose result goes to an SDK option typed `string[]`.\n const fnName = returningFunctionName(reportNode)\n const feedsFromCall =\n fnName !== null &&\n usesOf(fnName).some(({ identifier }) => {\n const call = identifier.parent as ASTNode | undefined\n return (\n call?.type === \"CallExpression\" &&\n call.callee === identifier &&\n flowsIntoMutableArraySlot(call, context) === true\n )\n })\n if (feedsFromCall) return\n // A field mutated somewhere in the file (`result.errors.push(e)`, `this.events.push(e)`): a\n // ReadonlyArray suggestion wouldn't compile, so give the mutation advice. Matched by name, which only\n // picks the message, never whether to report.\n const field = annotatedFieldName(reportNode)\n const fieldMutation = field === null ? null : fieldMutationIn(field)\n if (field !== null && fieldMutation !== null) {\n context.report({ node: reportNode, messageId: \"mutatedArray\", data: { name: field, how: fieldMutation } })\n return\n }\n const binding = annotatedBinding(reportNode)\n if (binding) {\n if (feedsMutableSlot(binding)) return\n const how = mutationOf(binding)\n if (how) {\n if (!leftToArrayMutation(binding)) {\n context.report({ node: reportNode, messageId: \"mutatedArray\", data: { name: binding.name, how } })\n }\n return\n }\n }\n reportMutable(reportNode, elementType, fullType)\n }\n\n /**\n * A mutable `T[]` / `Array<T>` is the real defect: anything holding it can push, sort or splice.\n * `ReadonlyArray<T>` fixes that and still fits wherever a library expects an array, so it's offered\n * first; `List<T>` is for collections that live inside your own code.\n */\n function reportMutable(reportNode: ASTNode, elementType: string, fullType: string): void {\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestReadonlyArray\",\n data: { type: elementType },\n fix: (fixer: Rule.RuleFixer) => fixer.replaceText(reportNode, `ReadonlyArray<${elementType}>`),\n },\n {\n messageId: \"suggestListType\",\n data: { type: elementType },\n fix: (fixer: Rule.RuleFixer) => fixer.replaceText(reportNode, `List<${elementType}>`),\n },\n ]\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n context.report({\n node: reportNode,\n messageId: \"preferReadonlyOrList\",\n data: { type: elementType, arrayType: fullType },\n suggest,\n })\n }\n\n /**\n * `Readonly<T[]>` / `Readonly<Array<T>>`: the utility type makes the array read-only, as\n * `ReadonlyArray<T>` does. Returns the `Readonly<…>` node when `node` is its only type argument.\n */\n function readonlyUtilityWrapper(node: ASTNode): ASTNode | undefined {\n const instantiation = node.parent as ASTNode | undefined\n if (instantiation?.type !== \"TSTypeParameterInstantiation\") return undefined\n const params = (instantiation as { params?: readonly ASTNode[] }).params\n if (params?.length !== 1 || params[0] !== node) return undefined\n const wrapper = instantiation.parent as ASTNode | undefined\n if (wrapper?.type !== \"TSTypeReference\") return undefined\n const name = (wrapper as { typeName?: { type?: string; name?: string } }).typeName\n return name?.type === \"Identifier\" && name.name === \"Readonly\" ? wrapper : undefined\n }\n\n /** Reports a read-only array type, which `allowReadonlyArrays: false` asks to be a List. */\n function reportReadonly(reportNode: ASTNode, elementType: string, fullType: string): void {\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: elementType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(reportNode, `List<${elementType}>`)\n },\n },\n ]\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n context.report({\n node: reportNode,\n messageId: \"preferList\",\n data: { type: elementType, arrayType: fullType },\n suggest,\n })\n }\n\n return {\n TSArrayType(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (allowArraysInTests && isInTestFile()) return\n\n // `readonly T[]` parses as TSTypeOperator(operator: \"readonly\") wrapping TSArrayType.\n // When the parent is that readonly wrapper, we treat the whole `readonly T[]` as\n // the reported unit — both for gating (parity with the ReadonlyArray<T> branch\n // below) and for the suggestion's replacement range. Replacing only the inner\n // TSArrayType would leave `readonly List<T>` behind, which is invalid TS\n // (TS1354: `readonly` only applies to array/tuple types).\n const parent = node.parent as ASTNode | undefined\n // `[string, ...string[]]`: a tuple's rest element must be written as an array type, and libraries\n // such as zod's `z.enum` require exactly that shape. The tuple is the type; its rest isn't a list.\n if (parent?.type === \"TSRestType\") return\n // `(...args: string[])`: a rest parameter is a fresh array on every call, owned by the callee.\n if (parent?.type === \"TSTypeAnnotation\" && parent.parent?.type === \"RestElement\") return\n\n const utility = readonlyUtilityWrapper(node)\n const operator =\n parent?.type === \"TSTypeOperator\" && (parent as { operator?: string }).operator === \"readonly\"\n ? (parent as ASTNode)\n : undefined\n const readonlyNode = operator ?? utility\n\n if (readonlyNode && allowReadonlyArrays) return\n\n const sourceCode = context.sourceCode\n const elementType = sourceCode.getText(node.elementType)\n const reportNode = readonlyNode ?? node\n const fullType = sourceCode.getText(reportNode)\n\n if (!readonlyNode) {\n checkMutable(reportNode, elementType, fullType)\n return\n }\n reportReadonly(reportNode, elementType, fullType)\n },\n\n TSTypeReference(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (allowArraysInTests && isInTestFile()) return\n\n const sourceCode = context.sourceCode\n\n // Get type name - handle both simple identifiers and member expressions\n if (!node.typeName) return // No type name found\n\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n // Handle Array<T> syntax: mutable, same as T[], unless `Readonly<…>` wraps it.\n if (typeName === \"Array\") {\n const typeParam = findTypeParameter(node, sourceCode) || \"T\"\n const utility = readonlyUtilityWrapper(node)\n if (!utility) {\n checkMutable(node, typeParam, sourceCode.getText(node))\n return\n }\n if (allowReadonlyArrays) return\n reportReadonly(utility, typeParam, sourceCode.getText(utility))\n return\n }\n\n // Handle ReadonlyArray<T> — gated on allowReadonlyArrays (parity with `readonly T[]`).\n if (typeName === \"ReadonlyArray\") {\n if (allowReadonlyArrays) return\n reportReadonly(node, findTypeParameter(node, sourceCode) || \"T\", sourceCode.getText(node))\n }\n },\n\n ArrayExpression(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n if (allowArrayLiterals) return\n\n // Only flag non-empty arrays to avoid noise\n if (node.elements.length === 0) return\n\n const parent = node.parent\n\n // Don't flag arrays that are already arguments to functype calls.\n if (parent && isFunctypeCall(parent, functypeImports)) return\n\n // Don't flag arrays that are arguments to List.from / List.of.\n if (isListFactoryArg(parent)) return\n\n // Don't flag nested array literals — let the outermost one handle it.\n if (ancestorSatisfies(node, (n) => n.type === \"ArrayExpression\")) return\n\n // Don't flag array literals that already live in a type-annotated\n // context (those are handled by the type-checking rules).\n if (ancestorSatisfies(node, hasOwnTypeAnnotation)) return\n\n // Look through `c ? xs : [x]` / `xs ?? [x]`: the checks below apply to the whole expression.\n const target = throughConditionals(node)\n const targetParent = target.parent as ASTNode | undefined\n\n // A literal asserted to a tuple (`as const`, `as [string, ...string[]]`) is a fixed shape.\n if (isTupleAssertion(parent)) return\n\n // With type information: a literal passed where an array is expected — drizzle's\n // `.values([...])`, an index definition, a schema `target: [...]` — is handed straight to code\n // that requires an array. It never becomes a collection in your own code, so it's the\n // boundary itself and `List` can't go there.\n if (flowsIntoArraySlot(node, context) === true || flowsIntoArraySlot(target, context) === true) return\n if (isFunctypeConstructorArg(target, targetParent)) return\n // Read down to one value on the spot (`[a, b].includes(x)`, `[a, b].filter(Boolean).join(\" \")`):\n // nothing is stored.\n if (chainEndsInSingleValue(node) || chainEndsInSingleValue(target)) return\n // A chain whose result goes to React or a library (`{[\"PDF\", \"DOCX\"].map((f) => <Chip />)}`,\n // `marks={[3, 4].map(…)}`): the transformed array is what's handed over, so the literal is too.\n const end = chainEnd(target)\n if (end !== target && (isJsxChild(end) || flowsIntoArraySlot(end, context) === true)) return\n // Spread into a call (`and(...(c ? [x] : []))`): the function gets the elements one by one.\n if (isSpreadIntoCall(node)) return\n // `const acc = [...]; acc.push(x)`: an accumulator. The defect is the mutation, so it gets the same\n // advice as a mutated `T[]` binding, not a List.of suggestion that has no push.\n if (targetParent?.type === \"VariableDeclarator\" && targetParent.id?.type === \"Identifier\") {\n const how = mutationOf(targetParent.id as ASTNode)\n if (how) {\n if (!leftToArrayMutation(targetParent.id as ASTNode)) {\n context.report({ node, messageId: \"mutatedArray\", data: { name: targetParent.id.name, how } })\n }\n return\n }\n }\n // Without type information the rule can't tell a literal handed to a library (drizzle\n // `.values([...])`) from a collection of your own, so it reports neither rather than guess.\n if (!hasTypeInformation(context)) return\n if (isOnlyHandedToArraySlots(targetParent)) return\n\n // Check if any element is a SpreadElement — ambiguous semantics, skip suggestions\n const hasSpread = node.elements.some((el) => el !== null && el.type === \"SpreadElement\")\n\n if (hasSpread) {\n context.report({\n node,\n messageId: \"preferListLiteral\",\n })\n return\n }\n\n const sourceCode = context.sourceCode\n const elementTexts = node.elements.filter((el) => el !== null).map((el) => sourceCode.getText(el))\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListOf\",\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List.of(${elementTexts.join(\", \")})`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferListLiteral\",\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,giBAgBA,MAAMA,kBAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAG9E,SAASC,EAAY,EAAmC,CACtD,OAAO,OAAO,QAAQC,CAAI,CAAC,CACxB,QAAQ,CAACC,KAAO,CAACH,EAAe,IAAIG,CAAC,CAAC,CAAC,CACvC,SAAS,EAAGC,KAAQ,MAAM,QAAQA,CAAC,EAAIA,EAAI,CAACA,CAAC,CAAE,CAAC,CAChD,OAAQ,GAAoB,OAAOA,GAAM,YAA3BA,CAAmC,CACtD,CAGA,SAASC,EAAkB,EAAkC,EAAwC,CACnG,IAAMC,EAASJ,GAAM,OAErB,OADKI,EACEC,EAAKD,CAAM,GAAKD,EAAkBC,EAAQC,CAAI,EADjC,EAEtB,CAGA,SAASC,EAAiB,EAA6C,CACrE,OACEF,GAAQ,OAAS,kBACjBA,EAAO,OAAO,OAAS,oBACvBA,EAAO,OAAO,OAAO,OAAS,cAC9BA,EAAO,OAAO,OAAO,OAAS,QAC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,CAAG,GAAKlD,EAAmBkD,EAAKrE,CAAO,IAAM,KAE3ExB,EAAiBtB,CAAI,EAAG,OAG5B,GAAIkH,GAAc,OAAS,sBAAwBA,EAAa,IAAI,OAAS,aAAc,CACzF,IAAMvC,EAAMF,EAAWyC,EAAa,EAAa,EACjD,GAAIvC,EAAK,CACFS,EAAoB8B,EAAa,EAAa,GACjDpE,EAAQ,OAAO,CAAE,OAAM,UAAW,eAAgB,KAAM,CAAE,KAAMoE,EAAa,GAAG,KAAM,KAAI,CAAE,CAAC,EAE/F,MACF,CACF,CAIA,GADI,CAAC7B,EAAmBvC,CAAO,GAC3BoB,EAAyBgD,CAAY,EAAG,OAK5C,GAFkBlH,EAAK,SAAS,KAAM,GAAOoH,IAAO,MAAQA,EAAG,OAAS,eAE5D,EAAG,CACbtE,EAAQ,OAAO,CACb,OACA,UAAW,mBACb,CAAC,EACD,MACF,CAEA,IAAMc,EAAad,EAAQ,WACrBuE,EAAerH,EAAK,SAAS,OAAQ,GAAOoH,IAAO,IAAI,CAAC,CAAC,IAAK,GAAOxD,EAAW,QAAQwD,CAAE,CAAC,EAE3FhB,EAA6C,CACjD,CACE,UAAW,gBACX,IAAI,EAAuB,CACzB,OAAOJ,EAAM,YAAYhG,EAAM,WAAWqH,EAAa,KAAK,IAAI,EAAE,EAAE,CACtE,CACF,CACF,EAEKhB,EAAkBzC,EAAY,MAAM,GACvCwC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,MAAO,EACvB,IAAKE,EAAkB1C,EAAY,MAAM,CAC3C,CAAC,EAGHd,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,SACF,CAAC,CACH,CACF,CACF,CACF,E"}
|
|
1
|
+
{"version":3,"file":"prefer-list.js","names":["isMutableArrayExpression","descendants","getFunctypeImportsLegacy","isFunctypeCall","createImportFixer","hasFunctypeSymbol","flowsIntoArraySlot","flowsIntoMutableArraySlot","hasTypeInformation","isUntypedExpression","DEFAULT_WIRE_TYPES","WIRE_TYPES_SCHEMA","isInsideWireType","NON_CHILD_KEYS","astChildren","node","k","v","ancestorSatisfies","pred","parent","isListFactoryArg","isTupleAssertion","raw","annotation","MUTATING_METHODS","throughConditionals","TERMINAL_METHODS","chainEnd","receiver","member","call","chainEndsInSingleValue","isTerminalRead","isJsxChild","grand","name","isSpreadIntoCall","annotatedBinding","typeNode","climb","n","returningFunctionName","fn","declarator","annotatedFieldName","field","castOf","child","outer","current","exportedTypeName","statement","declaration","isSupabaseGeneratedTypes","program","names","hasOwnTypeAnnotation","rule","context","header","comment","options","wireTypes","allowArraysInTests","allowReadonlyArrays","allowArrayLiterals","functypeImports","isInTestFile","filename","findTypeParameter","sourceCode","findInNode","c","r","isFunctypeConstructorArg","reachesArraySlot","isOnlyHandedToArraySlots","uses","variable","ref","usesOf","binding","owner","mutationOf","identifier","how","mutatedFields","fieldMutationIn","entries","method","target","feedsMutableSlot","leftToArrayMutation","checkMutable","reportNode","elementType","fullType","cast","castSource","source","decodes","fixer","fnName","fieldMutation","reportMutable","suggest","readonlyUtilityWrapper","instantiation","params","wrapper","reportReadonly","utility","readonlyNode","typeName","typeParam","targetParent","end","el","elementTexts"],"sources":["../../src/rules/prefer-list.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { isMutableArrayExpression } from \"../utils/array-mutation\"\nimport { descendants } from \"../utils/ast-walk\"\nimport { getFunctypeImportsLegacy, isFunctypeCall } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport {\n flowsIntoArraySlot,\n flowsIntoMutableArraySlot,\n hasTypeInformation,\n isUntypedExpression,\n} from \"../utils/type-aware\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\n\n/** AST keys that don't represent syntax children — back-edges and source metadata. */\nconst NON_CHILD_KEYS: ReadonlySet<string> = new Set([\"parent\", \"loc\", \"range\"])\n\n/** AST children of `node`: drops back-edges, flattens array-valued keys, filters non-object leaves. */\nfunction astChildren(node: ASTNode): readonly unknown[] {\n return Object.entries(node)\n .filter(([k]) => !NON_CHILD_KEYS.has(k))\n .flatMap(([, v]) => (Array.isArray(v) ? v : [v]))\n .filter((v) => v !== null && typeof v === \"object\")\n}\n\n/** True iff any ancestor of `node` satisfies `pred`. Pure tail recursion. */\nfunction ancestorSatisfies(node: ASTNode | null | undefined, pred: (n: ASTNode) => boolean): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return pred(parent) || ancestorSatisfies(parent, pred)\n}\n\n/** `parent` is `List.from(arr)` or `List.of(...arr)`. */\nfunction isListFactoryArg(parent: ASTNode | null | undefined): boolean {\n return (\n parent?.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n parent.callee.object.type === \"Identifier\" &&\n parent.callee.object.name === \"List\" &&\n [\"from\", \"of\"].includes(parent.callee.property.name)\n )\n}\n\n/**\n * `[…] as const` or `[…] as [string, ...string[]]`: the literal is asserted to a tuple, a fixed shape that\n * `List` can't express (an enum's values, the argument zod's `z.enum` requires).\n */\nfunction isTupleAssertion(parent: ASTNode | null | undefined): boolean {\n const raw = parent?.type === \"TSAsExpression\" ? parent.typeAnnotation : undefined\n const annotation = raw?.type === \"TSTypeOperator\" ? raw.typeAnnotation : raw\n if (annotation?.type === \"TSTupleType\") return true\n return (\n annotation?.type === \"TSTypeReference\" &&\n annotation.typeName?.type === \"Identifier\" &&\n annotation.typeName.name === \"const\"\n )\n}\n\n/** Array methods that change the array in place. */\nconst MUTATING_METHODS: ReadonlySet<string> = new Set([\n \"push\",\n \"pop\",\n \"shift\",\n \"unshift\",\n \"splice\",\n \"sort\",\n \"reverse\",\n \"fill\",\n \"copyWithin\",\n])\n\n/**\n * The expression a literal stands in for once conditionals are looked through: `[x]` in\n * `List(c ? xs : [x])` or `const args = c ? [a] : [\"--fix\", a]` behaves like the whole conditional.\n */\nfunction throughConditionals(node: ASTNode): ASTNode {\n const parent = node.parent as ASTNode | undefined\n if (parent?.type === \"ConditionalExpression\" && parent.test !== node) return throughConditionals(parent)\n if (parent?.type === \"LogicalExpression\") return throughConditionals(parent)\n return node\n}\n\n/**\n * Methods that turn an array into a single value: using a collection only through these makes it a\n * temporary (`lines.join(\"\\n\")`, `[a, b].includes(x)`). Methods that produce another collection\n * (`map`, `filter`, `slice`, `concat`, `reduce`…) are collection work, which is what `List` is for.\n */\nconst TERMINAL_METHODS: ReadonlySet<string> = new Set([\n \"join\",\n \"includes\",\n \"indexOf\",\n \"lastIndexOf\",\n \"some\",\n \"every\",\n \"find\",\n \"findIndex\",\n \"findLast\",\n \"findLastIndex\",\n \"at\",\n])\n\n/**\n * The end of a method chain that starts at `receiver`: `[…].map(f).filter(g)` → the `.filter(g)` call.\n * `receiver` itself when no method is called on it.\n */\nfunction chainEnd(receiver: ASTNode): ASTNode {\n const member = receiver.parent as ASTNode | undefined\n const call = member?.parent as ASTNode | undefined\n if (member?.type !== \"MemberExpression\" || member.object !== receiver) return receiver\n return call?.type === \"CallExpression\" && call.callee === member ? chainEnd(call) : receiver\n}\n\n/**\n * Does the method chain starting at `receiver` end in a single value: `[a, b].filter(Boolean).length`,\n * `[name, email].filter(nonEmpty).join(\"\\n\")`, `[...xs].sort(byRank)[0]`? Then every array in it is a\n * temporary, the same as `lines.join(\"\\n\")`.\n */\nfunction chainEndsInSingleValue(receiver: ASTNode): boolean {\n if (isTerminalRead(receiver)) return true\n const member = receiver.parent as ASTNode | undefined\n const call = member?.parent as ASTNode | undefined\n if (member?.type !== \"MemberExpression\" || member.object !== receiver) return false\n return call?.type === \"CallExpression\" && call.callee === member && chainEndsInSingleValue(call)\n}\n\n/** `{items.map((i) => <Row />)}`: an expression rendered as JSX children, which React takes as an array. */\nfunction isJsxChild(node: ASTNode): boolean {\n return (node.parent as ASTNode | undefined)?.type === \"JSXExpressionContainer\"\n}\n\n/**\n * Is `receiver` read down to a single value on the spot: `.length`, `[i]`, or a terminal method call?\n * The same test applies to a literal (`[a, b].includes(x)`) and to every use of a const (`lines.join`).\n */\nfunction isTerminalRead(receiver: ASTNode): boolean {\n const member = receiver.parent as ASTNode | undefined\n if (member?.type !== \"MemberExpression\" || member.object !== receiver) return false\n const grand = member.parent as ASTNode | undefined\n if (grand?.type === \"AssignmentExpression\" && grand.left === member) return false\n if (member.computed) return true\n const name = member.property?.type === \"Identifier\" ? member.property.name : null\n if (name === \"length\") return true\n return name !== null && TERMINAL_METHODS.has(name) && grand?.type === \"CallExpression\" && grand.callee === member\n}\n\n/**\n * Is `node` spread straight into a call's arguments, `and(...conds)` or `and(...(c ? [x] : []))`?\n * The function receives the elements one by one; the array is never a collection of your own.\n */\nfunction isSpreadIntoCall(node: ASTNode): boolean {\n const parent = node.parent as ASTNode | undefined\n if (!parent) return false\n if (parent.type === \"ConditionalExpression\" && parent.test !== node) return isSpreadIntoCall(parent)\n if (parent.type === \"LogicalExpression\" && parent.right === node) return isSpreadIntoCall(parent)\n return (\n parent.type === \"SpreadElement\" &&\n (parent.parent?.type === \"CallExpression\" || parent.parent?.type === \"NewExpression\")\n )\n}\n\n/** The `x` in `const x: T[] = …` or `(x: T[]) => …`, when the array type is (part of) its annotation. */\nfunction annotatedBinding(typeNode: ASTNode): ASTNode | null {\n const climb = (n: ASTNode | null | undefined): ASTNode | null => {\n if (!n) return null\n if (n.type === \"TSTypeAnnotation\") return n.parent?.type === \"Identifier\" ? (n.parent as ASTNode) : null\n if (n.type === \"TSAsExpression\" || n.type === \"TSSatisfiesExpression\" || n.type.endsWith(\"Statement\")) return null\n return climb(n.parent as ASTNode | undefined)\n }\n return climb(typeNode.parent as ASTNode | undefined)\n}\n\n/**\n * The name of the function whose declared return type *is* this array type: `f` in\n * `function f(): T[]` or `const f = (): T[] => …`. Null for anything nested (`(): { nodes: T[] }`).\n */\nfunction returningFunctionName(typeNode: ASTNode): ASTNode | null {\n const annotation = typeNode.parent as ASTNode | undefined\n const fn = annotation?.type === \"TSTypeAnnotation\" ? (annotation.parent as ASTNode | undefined) : undefined\n if (!fn || fn.returnType !== annotation) return null\n if (fn.type === \"FunctionDeclaration\") return fn.id?.type === \"Identifier\" ? (fn.id as ASTNode) : null\n const declarator = fn.parent as ASTNode | undefined\n return (fn.type === \"ArrowFunctionExpression\" || fn.type === \"FunctionExpression\") &&\n declarator?.type === \"VariableDeclarator\" &&\n declarator.init === fn &&\n declarator.id?.type === \"Identifier\"\n ? (declarator.id as ASTNode)\n : null\n}\n\n/** The property name when the array type annotates a field: `errors` in `{ errors: string[] }` or `class { errors: T[] }`. */\nfunction annotatedFieldName(typeNode: ASTNode): string | null {\n const annotation = typeNode.parent as ASTNode | undefined\n const field = annotation?.type === \"TSTypeAnnotation\" ? (annotation.parent as ASTNode | undefined) : undefined\n if (field?.type !== \"TSPropertySignature\" && field?.type !== \"PropertyDefinition\") return null\n return field.key?.type === \"Identifier\" && !field.computed ? field.key.name : null\n}\n\n/** The outermost `x as … as T[]` around an array type used as a cast target, or null. */\nfunction castOf(typeNode: ASTNode): ASTNode | null {\n const climb = (n: ASTNode | null | undefined, child: ASTNode): ASTNode | null => {\n if (!n || n.type === \"TSTypeAnnotation\" || n.type.endsWith(\"Statement\")) return null\n if (n.type === \"TSAsExpression\" && n.typeAnnotation === child) {\n const outer = (current: ASTNode): ASTNode =>\n current.parent?.type === \"TSAsExpression\" ? outer(current.parent as ASTNode) : current\n return outer(n)\n }\n return climb(n.parent as ASTNode | undefined, n)\n }\n return climb(typeNode.parent as ASTNode | undefined, typeNode)\n}\n\n/** Names a top-level `export type X = …` or `export interface X` declares. */\nfunction exportedTypeName(statement: ASTNode): string | undefined {\n const declaration = statement.type === \"ExportNamedDeclaration\" ? (statement.declaration as ASTNode | null) : null\n if (declaration?.type !== \"TSTypeAliasDeclaration\" && declaration?.type !== \"TSInterfaceDeclaration\") return undefined\n return (declaration.id as ASTNode | undefined)?.name as string | undefined\n}\n\n/**\n * Supabase's generated types (`supabase gen types typescript`) carry no generated-file marker, but\n * always export both `type Json` and `Database` (a type alias, or an interface from older CLIs) at\n * the top level. No hand-written module exports that pair, so the shape identifies the file.\n */\nfunction isSupabaseGeneratedTypes(program: ASTNode): boolean {\n const names = new Set((program.body as ASTNode[]).map(exportedTypeName))\n return names.has(\"Json\") && names.has(\"Database\")\n}\n\n/** `node` is a VariableDeclarator with its own type annotation, or a TSTypeAnnotation node directly. */\nfunction hasOwnTypeAnnotation(node: ASTNode): boolean {\n return (node.type === \"VariableDeclarator\" && Boolean(node.id?.typeAnnotation)) || node.type === \"TSTypeAnnotation\"\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer List<T> over native arrays for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowArraysInTests: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowReadonlyArrays: {\n type: \"boolean\",\n default: true,\n },\n allowArrayLiterals: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferList: \"Prefer List<{{type}}> over array type {{arrayType}}\",\n preferReadonlyOrList:\n \"Mutable array type {{arrayType}}: anything holding it can change it. Use ReadonlyArray<{{type}}>, which every caller and library accepts, or List<{{type}}> for a collection you transform\",\n preferWireCast:\n \"Cast to the mutable array {{arrayType}}: this is data decoded from outside. Declare its shape once as Wire<ReadonlyArray<{{type}}>> (functype's boundary marker) and cast to that\",\n mutatedArray:\n \"{{name}} is a mutable array changed in place (.{{how}}()). Build it without mutation instead: map/filter/flatMap, a List, or a fold\",\n preferListLiteral: \"Prefer List.of(...) or List.from([...]) over array literal\",\n suggestListType: \"Replace with List<{{type}}>\",\n suggestReadonlyArray: \"Replace with ReadonlyArray<{{type}}>\",\n suggestListOf: \"Replace with List.of(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n // A generated file (`// @generated`, \"Auto-generated … DO NOT EDIT\") isn't edited by hand, so there's\n // nothing for its author to fix. Supabase's types have no marker and are recognized by shape.\n const header = context.sourceCode\n .getAllComments()\n .slice(0, 3)\n .map((comment) => comment.value)\n .join(\"\\n\")\n if (/@generated|auto-generated|do not edit/i.test(header)) return {}\n if (isSupabaseGeneratedTypes(context.sourceCode.ast as unknown as ASTNode)) return {}\n\n const options = context.options[0] || {}\n // Everything inside `Wire<…>` is the declared serialization shape (#325 B).\n const wireTypes: ReadonlyArray<string> = options.wireTypes ?? DEFAULT_WIRE_TYPES\n const allowArraysInTests = options.allowArraysInTests !== false\n const allowReadonlyArrays = options.allowReadonlyArrays !== false\n const allowArrayLiterals = options.allowArrayLiterals === true\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function findTypeParameter(node: ASTNode, sourceCode: typeof context.sourceCode): string | null {\n // Pure pre-order search: look at this node, then recursively at each\n // child until we find a TSTypeParameterInstantiation with a first param.\n function findInNode(n: ASTNode): string | null {\n if (n.type === \"TSTypeParameterInstantiation\" && n.params && n.params[0]) {\n return sourceCode.getText(n.params[0])\n }\n const results = astChildren(n)\n .filter((c): c is ASTNode => typeof (c as ASTNode)?.type === \"string\")\n .map((child) => findInNode(child))\n return results.find((r) => r !== null) ?? null\n }\n return findInNode(node)\n }\n\n /** `List([...x])`, `Set([a, b])`: the literal is already being captured into a functype value. */\n function isFunctypeConstructorArg(node: ASTNode, parent: ASTNode | null | undefined): boolean {\n return (\n parent?.type === \"CallExpression\" &&\n parent.callee.type === \"Identifier\" &&\n functypeImports.has(parent.callee.name) &&\n parent.arguments.includes(node)\n )\n }\n\n /** Is `node` handed straight to an array-typed slot, directly or spread into a literal that is? */\n function reachesArraySlot(node: ASTNode): boolean {\n if (flowsIntoArraySlot(node, context) === true) return true\n if (isSpreadIntoCall(node)) return true\n const parent = node.parent as ASTNode | undefined\n return (\n parent?.type === \"SpreadElement\" &&\n parent.parent?.type === \"ArrayExpression\" &&\n flowsIntoArraySlot(parent.parent as ASTNode, context) === true\n )\n }\n\n /**\n * `const OPTIONS = [...]` whose every use hands it to an array-typed slot (`<Select data={OPTIONS} />`,\n * `db.insert(t).values(ROWS)`) or reads it down to a single value (`lines.join(\"\\n\")`, `xs.length`): data\n * built to give to a library, or a temporary, declared before it's used. Needs at least one local use; an exported\n * constant with no local use is still reported, because its consumers aren't visible here.\n */\n function isOnlyHandedToArraySlots(declarator: ASTNode | null | undefined): boolean {\n if (declarator?.type !== \"VariableDeclarator\" || declarator.id?.type !== \"Identifier\") return false\n const uses = context.sourceCode\n .getDeclaredVariables(declarator)\n .flatMap((variable) => variable.references.filter((ref) => !ref.init))\n return (\n uses.length > 0 &&\n uses.every((ref) => reachesArraySlot(ref.identifier as ASTNode) || isTerminalRead(ref.identifier as ASTNode))\n )\n }\n\n /** References to `binding` other than its declaration. */\n function usesOf(binding: ASTNode): ReadonlyArray<{ identifier: ASTNode }> {\n // The declaring node: a VariableDeclarator, a FunctionDeclaration (its name lives in the outer\n // scope) or, for a parameter, its function. getDeclaredVariables on it yields the binding.\n const owner = (binding.parent as ASTNode | undefined) ?? binding\n const variable =\n context.sourceCode.getDeclaredVariables(owner).find((v) => v.name === binding.name) ??\n context.sourceCode.getScope(binding).set.get(binding.name)\n return (variable?.references ?? [])\n .filter((ref) => !ref.init && ref.identifier !== binding)\n .map((ref) => ({ identifier: ref.identifier as ASTNode }))\n }\n\n /** The in-place mutation applied to `binding` (`push`, `sort`, `x[i] = …`), if any. */\n function mutationOf(binding: ASTNode): string | null {\n const found = usesOf(binding)\n .map(({ identifier }) => {\n const parent = identifier.parent as ASTNode | undefined\n if (parent?.type !== \"MemberExpression\" || parent.object !== identifier) return null\n const grand = parent.parent as ASTNode | undefined\n if (grand?.type === \"AssignmentExpression\" && grand.left === parent)\n return parent.computed ? \"[index] =\" : null\n const name = parent.property?.type === \"Identifier\" && !parent.computed ? parent.property.name : null\n return name && MUTATING_METHODS.has(name) && grand?.type === \"CallExpression\" && grand.callee === parent\n ? name\n : null\n })\n .find((how) => how !== null)\n return found ?? null\n }\n\n /**\n * Fields mutated in place anywhere in the file, `errors` → `push` for `t.errors.push(e)`. Built once per\n * file, on first use, from the syntax tree.\n */\n const mutatedFields: { map?: ReadonlyMap<string, string> } = {}\n function fieldMutationIn(field: string): string | null {\n if (!mutatedFields.map) {\n const entries = descendants(context.sourceCode.ast as unknown as ASTNode).flatMap(\n (node): [string, string][] => {\n if (node.type !== \"CallExpression\" || node.callee?.type !== \"MemberExpression\") return []\n const method = node.callee.property?.type === \"Identifier\" ? node.callee.property.name : null\n const target = node.callee.object as ASTNode\n const name =\n target?.type === \"MemberExpression\" && target.property?.type === \"Identifier\" && !target.computed\n ? target.property.name\n : null\n return method && name && MUTATING_METHODS.has(method) ? [[name, method]] : []\n },\n )\n mutatedFields.map = new globalThis.Map(entries.reverse())\n }\n return mutatedFields.map.get(field) ?? null\n }\n\n /** Is `binding` handed to a slot that requires a mutable array (pg `query` values, ReactFlow `nodes`)? */\n function feedsMutableSlot(binding: ASTNode): boolean {\n return usesOf(binding).some(({ identifier }) => flowsIntoMutableArraySlot(identifier, context) === true)\n }\n\n /**\n * A local array changed in place by a method (`acc.push(x)`) or an index write (`acc[i] = x`) is one\n * mistake, building it by mutation, with two sites. With type information, no-array-mutation reports\n * the change itself, which is where the fix goes, so this rule leaves the declaration to it rather\n * than report it twice. Without type information no-array-mutation reports nothing, so the\n * declaration gets the advice. Fields stay reported here: they are matched by name across the file,\n * which can't tell which declaration a mutation belongs to.\n */\n function leftToArrayMutation(binding: ASTNode): boolean {\n // no-array-mutation sees only a plain mutable array: an intersection such as\n // `string[] & { tag?: string }` it skips, so this rule must still report that one.\n return hasTypeInformation(context) && isMutableArrayExpression(binding, context)\n }\n\n /**\n * Report a mutable array type, unless a library demands it. The order matters: a library slot that\n * requires `T[]` makes the type correct as written; a binding mutated in place can't take\n * `ReadonlyArray` without a rewrite, so it gets advice instead of a suggestion that wouldn't compile;\n * a cast is decoded outside data, so it points at `Wire`.\n */\n function checkMutable(reportNode: ASTNode, elementType: string, fullType: string): void {\n const cast = castOf(reportNode)\n // The value under every `as`: `JSON.parse(raw)` in `JSON.parse(raw) as unknown as T[]`.\n const castSource = (n: ASTNode): ASTNode =>\n n.type === \"TSAsExpression\" ? castSource(n.expression as ASTNode) : n\n if (cast && flowsIntoMutableArraySlot(cast, context) === true) return\n // Only a cast of an untyped value (`JSON.parse`, `res.json()`, a raw row) is decoding outside data,\n // the Wire case. It needs type evidence: without it the rule can't tell decoding from re-casting a\n // typed value, so it gives the plain message rather than advice that flips when types are turned on.\n const source = cast ? castSource(cast) : null\n const decodes =\n source !== null && source.type !== \"ArrayExpression\" && isUntypedExpression(source, context) === true\n if (cast && decodes) {\n context.report({\n node: reportNode,\n messageId: \"preferWireCast\",\n data: { type: elementType, arrayType: fullType },\n suggest: [\n {\n messageId: \"suggestReadonlyArray\",\n data: { type: elementType },\n fix: (fixer: Rule.RuleFixer) => fixer.replaceText(reportNode, `ReadonlyArray<${elementType}>`),\n },\n ],\n })\n return\n }\n // `function allowedTools(): string[]` whose result goes to an SDK option typed `string[]`.\n const fnName = returningFunctionName(reportNode)\n const feedsFromCall =\n fnName !== null &&\n usesOf(fnName).some(({ identifier }) => {\n const call = identifier.parent as ASTNode | undefined\n return (\n call?.type === \"CallExpression\" &&\n call.callee === identifier &&\n flowsIntoMutableArraySlot(call, context) === true\n )\n })\n if (feedsFromCall) return\n // A field mutated somewhere in the file (`result.errors.push(e)`, `this.events.push(e)`): a\n // ReadonlyArray suggestion wouldn't compile, so give the mutation advice. Matched by name, which only\n // picks the message, never whether to report.\n const field = annotatedFieldName(reportNode)\n const fieldMutation = field === null ? null : fieldMutationIn(field)\n if (field !== null && fieldMutation !== null) {\n context.report({ node: reportNode, messageId: \"mutatedArray\", data: { name: field, how: fieldMutation } })\n return\n }\n const binding = annotatedBinding(reportNode)\n if (binding) {\n if (feedsMutableSlot(binding)) return\n const how = mutationOf(binding)\n if (how) {\n if (!leftToArrayMutation(binding)) {\n context.report({ node: reportNode, messageId: \"mutatedArray\", data: { name: binding.name, how } })\n }\n return\n }\n }\n reportMutable(reportNode, elementType, fullType)\n }\n\n /**\n * A mutable `T[]` / `Array<T>` is the real defect: anything holding it can push, sort or splice.\n * `ReadonlyArray<T>` fixes that and still fits wherever a library expects an array, so it's offered\n * first; `List<T>` is for collections that live inside your own code.\n */\n function reportMutable(reportNode: ASTNode, elementType: string, fullType: string): void {\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestReadonlyArray\",\n data: { type: elementType },\n fix: (fixer: Rule.RuleFixer) => fixer.replaceText(reportNode, `ReadonlyArray<${elementType}>`),\n },\n {\n messageId: \"suggestListType\",\n data: { type: elementType },\n fix: (fixer: Rule.RuleFixer) => fixer.replaceText(reportNode, `List<${elementType}>`),\n },\n ]\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n context.report({\n node: reportNode,\n messageId: \"preferReadonlyOrList\",\n data: { type: elementType, arrayType: fullType },\n suggest,\n })\n }\n\n /**\n * `Readonly<T[]>` / `Readonly<Array<T>>`: the utility type makes the array read-only, as\n * `ReadonlyArray<T>` does. Returns the `Readonly<…>` node when `node` is its only type argument.\n */\n function readonlyUtilityWrapper(node: ASTNode): ASTNode | undefined {\n const instantiation = node.parent as ASTNode | undefined\n if (instantiation?.type !== \"TSTypeParameterInstantiation\") return undefined\n const params = (instantiation as { params?: readonly ASTNode[] }).params\n if (params?.length !== 1 || params[0] !== node) return undefined\n const wrapper = instantiation.parent as ASTNode | undefined\n if (wrapper?.type !== \"TSTypeReference\") return undefined\n const name = (wrapper as { typeName?: { type?: string; name?: string } }).typeName\n return name?.type === \"Identifier\" && name.name === \"Readonly\" ? wrapper : undefined\n }\n\n /** Reports a read-only array type, which `allowReadonlyArrays: false` asks to be a List. */\n function reportReadonly(reportNode: ASTNode, elementType: string, fullType: string): void {\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: elementType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(reportNode, `List<${elementType}>`)\n },\n },\n ]\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n context.report({\n node: reportNode,\n messageId: \"preferList\",\n data: { type: elementType, arrayType: fullType },\n suggest,\n })\n }\n\n return {\n TSArrayType(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (allowArraysInTests && isInTestFile()) return\n\n // `readonly T[]` parses as TSTypeOperator(operator: \"readonly\") wrapping TSArrayType.\n // When the parent is that readonly wrapper, we treat the whole `readonly T[]` as\n // the reported unit — both for gating (parity with the ReadonlyArray<T> branch\n // below) and for the suggestion's replacement range. Replacing only the inner\n // TSArrayType would leave `readonly List<T>` behind, which is invalid TS\n // (TS1354: `readonly` only applies to array/tuple types).\n const parent = node.parent as ASTNode | undefined\n // `[string, ...string[]]`: a tuple's rest element must be written as an array type, and libraries\n // such as zod's `z.enum` require exactly that shape. The tuple is the type; its rest isn't a list.\n if (parent?.type === \"TSRestType\") return\n // `(...args: string[])`: a rest parameter is a fresh array on every call, owned by the callee.\n if (parent?.type === \"TSTypeAnnotation\" && parent.parent?.type === \"RestElement\") return\n\n const utility = readonlyUtilityWrapper(node)\n const operator =\n parent?.type === \"TSTypeOperator\" && (parent as { operator?: string }).operator === \"readonly\"\n ? (parent as ASTNode)\n : undefined\n const readonlyNode = operator ?? utility\n\n if (readonlyNode && allowReadonlyArrays) return\n\n const sourceCode = context.sourceCode\n const elementType = sourceCode.getText(node.elementType)\n const reportNode = readonlyNode ?? node\n const fullType = sourceCode.getText(reportNode)\n\n if (!readonlyNode) {\n checkMutable(reportNode, elementType, fullType)\n return\n }\n reportReadonly(reportNode, elementType, fullType)\n },\n\n TSTypeReference(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (allowArraysInTests && isInTestFile()) return\n\n const sourceCode = context.sourceCode\n\n // Get type name - handle both simple identifiers and member expressions\n if (!node.typeName) return // No type name found\n\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n // Handle Array<T> syntax: mutable, same as T[], unless `Readonly<…>` wraps it.\n if (typeName === \"Array\") {\n const typeParam = findTypeParameter(node, sourceCode) || \"T\"\n const utility = readonlyUtilityWrapper(node)\n if (!utility) {\n checkMutable(node, typeParam, sourceCode.getText(node))\n return\n }\n if (allowReadonlyArrays) return\n reportReadonly(utility, typeParam, sourceCode.getText(utility))\n return\n }\n\n // Handle ReadonlyArray<T> — gated on allowReadonlyArrays (parity with `readonly T[]`).\n if (typeName === \"ReadonlyArray\") {\n if (allowReadonlyArrays) return\n reportReadonly(node, findTypeParameter(node, sourceCode) || \"T\", sourceCode.getText(node))\n }\n },\n\n ArrayExpression(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n if (allowArrayLiterals) return\n\n // Only flag non-empty arrays to avoid noise\n if (node.elements.length === 0) return\n\n const parent = node.parent\n\n // Don't flag arrays that are already arguments to functype calls.\n if (parent && isFunctypeCall(parent, functypeImports)) return\n\n // Don't flag arrays that are arguments to List.from / List.of.\n if (isListFactoryArg(parent)) return\n\n // Don't flag nested array literals — let the outermost one handle it.\n if (ancestorSatisfies(node, (n) => n.type === \"ArrayExpression\")) return\n\n // Don't flag array literals that already live in a type-annotated\n // context (those are handled by the type-checking rules).\n if (ancestorSatisfies(node, hasOwnTypeAnnotation)) return\n\n // Look through `c ? xs : [x]` / `xs ?? [x]`: the checks below apply to the whole expression.\n const target = throughConditionals(node)\n const targetParent = target.parent as ASTNode | undefined\n\n // A literal asserted to a tuple (`as const`, `as [string, ...string[]]`) is a fixed shape.\n if (isTupleAssertion(parent)) return\n\n // With type information: a literal passed where an array is expected — drizzle's\n // `.values([...])`, an index definition, a schema `target: [...]` — is handed straight to code\n // that requires an array. It never becomes a collection in your own code, so it's the\n // boundary itself and `List` can't go there.\n if (flowsIntoArraySlot(node, context) === true || flowsIntoArraySlot(target, context) === true) return\n if (isFunctypeConstructorArg(target, targetParent)) return\n // Read down to one value on the spot (`[a, b].includes(x)`, `[a, b].filter(Boolean).join(\" \")`):\n // nothing is stored.\n if (chainEndsInSingleValue(node) || chainEndsInSingleValue(target)) return\n // A chain whose result goes to React or a library (`{[\"PDF\", \"DOCX\"].map((f) => <Chip />)}`,\n // `marks={[3, 4].map(…)}`): the transformed array is what's handed over, so the literal is too.\n const end = chainEnd(target)\n if (end !== target && (isJsxChild(end) || flowsIntoArraySlot(end, context) === true)) return\n // Spread into a call (`and(...(c ? [x] : []))`): the function gets the elements one by one.\n if (isSpreadIntoCall(node)) return\n // `const acc = [...]; acc.push(x)`: an accumulator. The defect is the mutation, so it gets the same\n // advice as a mutated `T[]` binding, not a List.of suggestion that has no push.\n if (targetParent?.type === \"VariableDeclarator\" && targetParent.id?.type === \"Identifier\") {\n const how = mutationOf(targetParent.id as ASTNode)\n if (how) {\n if (!leftToArrayMutation(targetParent.id as ASTNode)) {\n context.report({ node, messageId: \"mutatedArray\", data: { name: targetParent.id.name, how } })\n }\n return\n }\n }\n // Without type information the rule can't tell a literal handed to a library (drizzle\n // `.values([...])`) from a collection of your own, so it reports neither rather than guess.\n if (!hasTypeInformation(context)) return\n if (isOnlyHandedToArraySlots(targetParent)) return\n\n // Check if any element is a SpreadElement — ambiguous semantics, skip suggestions\n const hasSpread = node.elements.some((el) => el !== null && el.type === \"SpreadElement\")\n\n if (hasSpread) {\n context.report({\n node,\n messageId: \"preferListLiteral\",\n })\n return\n }\n\n const sourceCode = context.sourceCode\n const elementTexts = node.elements.filter((el) => el !== null).map((el) => sourceCode.getText(el))\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListOf\",\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List.of(${elementTexts.join(\", \")})`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferListLiteral\",\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,giBAgBA,MAAMa,kBAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAG9E,SAASC,EAAYC,EAAmC,CACtD,OAAO,OAAO,QAAQA,CAAI,CAAC,CACxB,QAAQ,CAACC,KAAO,CAACH,EAAe,IAAIG,CAAC,CAAC,CAAC,CACvC,SAAS,EAAGC,KAAQ,MAAM,QAAQA,CAAC,EAAIA,EAAI,CAACA,CAAC,CAAE,CAAC,CAChD,OAAQA,GAAoB,OAAOA,GAAM,YAA3BA,CAAmC,CACtD,CAGA,SAASC,EAAkBH,EAAkCI,EAAwC,CACnG,IAAMC,EAASL,GAAM,OAErB,OADKK,EACED,EAAKC,CAAM,GAAKF,EAAkBE,EAAQD,CAAI,EADjC,EAEtB,CAGA,SAASE,EAAiBD,EAA6C,CACrE,OACEA,GAAQ,OAAS,kBACjBA,EAAO,OAAO,OAAS,oBACvBA,EAAO,OAAO,OAAO,OAAS,cAC9BA,EAAO,OAAO,OAAO,OAAS,QAC9B,CAAC,OAAQ,IAAI,CAAC,CAAC,SAASA,EAAO,OAAO,SAAS,IAAI,CAEvD,CAMA,SAASE,EAAiBF,EAA6C,CACrE,IAAMG,EAAMH,GAAQ,OAAS,iBAAmBA,EAAO,eAAiB,IAAA,GAClEI,EAAaD,GAAK,OAAS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