eslint-plugin-functype 2.127.1 → 2.200.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 +93 -87
- package/dist/cli/list-rules.js.map +1 -1
- package/dist/configs/recommended.d.ts +40 -46
- package/dist/configs/recommended.js +1 -1
- package/dist/configs/recommended.js.map +1 -1
- package/dist/configs/tests.d.ts +8 -5
- package/dist/configs/tests.js +1 -1
- package/dist/configs/tests.js.map +1 -1
- package/dist/index.d.ts +1 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/rules/collection-naming.d.ts +1 -4
- package/dist/rules/collection-naming.js.map +1 -1
- package/dist/rules/index.d.ts +1 -4
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/must-fold-on-component-return.d.ts +1 -4
- package/dist/rules/must-fold-on-component-return.js.map +1 -1
- package/dist/rules/no-array-mutation.d.ts +1 -4
- package/dist/rules/no-array-mutation.js +1 -1
- package/dist/rules/no-array-mutation.js.map +1 -1
- package/dist/rules/no-floating-io.d.ts +1 -4
- package/dist/rules/no-floating-io.js.map +1 -1
- package/dist/rules/no-floating-result.d.ts +1 -4
- package/dist/rules/no-floating-result.js.map +1 -1
- package/dist/rules/no-get-unsafe.d.ts +1 -4
- package/dist/rules/no-get-unsafe.js +1 -1
- package/dist/rules/no-get-unsafe.js.map +1 -1
- package/dist/rules/no-getOrThrow-in-render.d.ts +1 -4
- package/dist/rules/no-getOrThrow-in-render.js +1 -1
- package/dist/rules/no-getOrThrow-in-render.js.map +1 -1
- package/dist/rules/no-imperative-loops.d.ts +1 -4
- package/dist/rules/no-imperative-loops.js +1 -1
- package/dist/rules/no-imperative-loops.js.map +1 -1
- package/dist/rules/no-let.d.ts +1 -4
- package/dist/rules/no-let.js.map +1 -1
- package/dist/rules/no-serialize-container.d.ts +1 -4
- package/dist/rules/no-serialize-container.js.map +1 -1
- package/dist/rules/prefer-do-notation.d.ts +1 -4
- package/dist/rules/prefer-do-notation.js +1 -1
- package/dist/rules/prefer-do-notation.js.map +1 -1
- package/dist/rules/prefer-either.d.ts +1 -4
- package/dist/rules/prefer-either.js.map +1 -1
- package/dist/rules/prefer-flatmap.d.ts +1 -4
- package/dist/rules/prefer-flatmap.js +1 -1
- package/dist/rules/prefer-flatmap.js.map +1 -1
- package/dist/rules/prefer-fold.d.ts +1 -4
- package/dist/rules/prefer-fold.js +1 -1
- package/dist/rules/prefer-fold.js.map +1 -1
- package/dist/rules/prefer-functype-map.d.ts +1 -4
- package/dist/rules/prefer-functype-map.js.map +1 -1
- package/dist/rules/prefer-functype-set.d.ts +1 -4
- package/dist/rules/prefer-functype-set.js.map +1 -1
- package/dist/rules/prefer-list.d.ts +1 -4
- package/dist/rules/prefer-list.js +2 -2
- package/dist/rules/prefer-list.js.map +1 -1
- package/dist/rules/prefer-map.d.ts +1 -4
- package/dist/rules/prefer-map.js.map +1 -1
- package/dist/rules/prefer-option.d.ts +1 -4
- package/dist/rules/prefer-option.js.map +1 -1
- package/dist/rules/prefer-try.d.ts +1 -4
- package/dist/rules/prefer-try.js +1 -1
- package/dist/rules/prefer-try.js.map +1 -1
- package/dist/types/ast.d.ts +1 -4
- package/dist/utils/array-mutation.d.ts +1 -4
- package/dist/utils/array-mutation.js.map +1 -1
- package/dist/utils/ast-walk.d.ts +1 -4
- package/dist/utils/ast-walk.js.map +1 -1
- package/dist/utils/async-detection.d.ts +1 -4
- package/dist/utils/async-detection.js.map +1 -1
- package/dist/utils/boundary-tags.d.ts +1 -4
- package/dist/utils/boundary-tags.js.map +1 -1
- package/dist/utils/collection-binding.d.ts +1 -4
- package/dist/utils/collection-binding.js.map +1 -1
- package/dist/utils/dependency-validator.d.ts +1 -3
- package/dist/utils/dependency-validator.js.map +1 -1
- package/dist/utils/functype-detection.d.ts +1 -4
- package/dist/utils/functype-detection.js +1 -1
- package/dist/utils/functype-detection.js.map +1 -1
- package/dist/utils/functype-predicates.d.ts +1 -4
- package/dist/utils/functype-predicates.js.map +1 -1
- package/dist/utils/host-throws.d.ts +1 -4
- package/dist/utils/host-throws.js.map +1 -1
- package/dist/utils/import-fixer.d.ts +1 -4
- package/dist/utils/import-fixer.js.map +1 -1
- package/dist/utils/mutable-collection.d.ts +1 -4
- package/dist/utils/mutable-collection.js.map +1 -1
- package/dist/utils/react-render.d.ts +1 -4
- package/dist/utils/react-render.js.map +1 -1
- package/dist/utils/readonly-contract.d.ts +1 -4
- package/dist/utils/readonly-contract.js.map +1 -1
- package/dist/utils/type-aware.d.ts +2 -5
- package/dist/utils/type-aware.js +1 -1
- package/dist/utils/type-aware.js.map +1 -1
- package/dist/utils/wire-types.d.ts +1 -4
- package/dist/utils/wire-types.js.map +1 -1
- package/package.json +5 -5
- package/dist/configs/agent.d.ts +0 -45
- package/dist/configs/agent.js +0 -2
- package/dist/configs/agent.js.map +0 -1
- package/dist/configs/strict.d.ts +0 -26
- package/dist/configs/strict.js +0 -2
- package/dist/configs/strict.js.map +0 -1
|
@@ -1 +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","checkMutable","cast","reportNode","castSource","source","decodes","isUntypedExpression","elementType","fullType","fixer","fnName","fieldMutation","reportMutable","suggest","hasFunctypeSymbol","createImportFixer","isInsideWireType","isReadonly","typeName","typeParam","resolvedType","isFunctypeCall","targetParent","end","hasTypeInformation","el","elementTexts"],"sources":["../../src/rules/prefer-list.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\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) return \"[index] =\"\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 * 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 context.report({ node: reportNode, messageId: \"mutatedArray\", data: { name: binding.name, how } })\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 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 isReadonly =\n parent?.type === \"TSTypeOperator\" && (parent as { operator?: string }).operator === \"readonly\"\n\n if (isReadonly && allowReadonlyArrays) return\n\n const sourceCode = context.sourceCode\n const elementType = sourceCode.getText(node.elementType)\n const reportNode = isReadonly ? (parent as ASTNode) : node\n const fullType = sourceCode.getText(reportNode)\n\n if (!isReadonly) {\n checkMutable(reportNode, elementType, fullType)\n return\n }\n\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\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: reportNode,\n messageId: \"preferList\",\n data: {\n type: elementType,\n arrayType: fullType,\n },\n suggest,\n })\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[]\n if (typeName === \"Array\") {\n const typeParam = findTypeParameter(node, sourceCode)\n checkMutable(node, typeParam || \"T\", sourceCode.getText(node))\n return\n }\n\n // Handle ReadonlyArray<T> — gated on allowReadonlyArrays (parity with `readonly T[]`).\n if (typeName === \"ReadonlyArray\") {\n if (allowReadonlyArrays) return\n\n const typeParam = findTypeParameter(node, sourceCode)\n const fullType = sourceCode.getText(node)\n const resolvedType = typeParam || \"T\"\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: resolvedType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List<${resolvedType}>`)\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: \"preferList\",\n data: {\n type: resolvedType,\n arrayType: fullType,\n },\n suggest,\n })\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 context.report({ node, messageId: \"mutatedArray\", data: { name: targetParent.id.name, how } })\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":"0dAeA,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,QAC9B,CAAC,OAAQ,IAAI,CAAC,CAAC,SAASA,EAAO,OAAO,SAAS,IAAI,CAEvD,CAMA,SAASG,EAAiB,EAA6C,CACrE,IAAMC,EAAMJ,GAAQ,OAAS,iBAAmBA,EAAO,eAAiB,IAAA,GAClEK,EAAaD,GAAK,OAAS,iBAAmBA,EAAI,eAAiBA,EAEzE,OADIC,GAAY,OAAS,eAEvBA,GAAY,OAAS,mBACrBA,EAAW,UAAU,OAAS,cAC9BA,EAAW,SAAS,OAAS,OAEj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,IAAI,EAAuB,CACzB,OAAOJ,EAAM,YAAY7F,EAAM,WAAW8G,EAAa,KAAK,IAAI,EAAE,EAAE,CACtE,CACF,CACF,EAEKZ,EAAkBtC,EAAY,MAAM,GACvCqC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,MAAO,EACvB,IAAKE,EAAkBvC,EAAY,MAAM,CAC3C,CAAC,EAGHd,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,SACF,CAAC,CACH,CACF,CACF,CACF"}
|
|
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,OAA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AAO,EACvB,IAAKE,EAAkB1C,EAAY,MAAM,CAC3C,CAAC,EAGHd,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,SACF,CAAC,CACH,CACF,CACF,CACF,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-map.js","names":["ITERATION_METHOD_NAMES","insideIterationCallback","parent","node","rule","options","context","checkArrayMethods","checkForLoops","isForEachToMapSafe","callback","isTransformationLoop","statements","stmt","call","isSimplePropertyAccess","suspends","containsAwait","containsYield","fixedText","fixer"],"sources":["../../src/rules/prefer-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containsAwait, containsYield } from \"../utils/async-detection\"\n\nconst ITERATION_METHOD_NAMES: ReadonlySet<string> = new Set([\"forEach\", \"for\"])\n\n/** True iff any ancestor of `node` is a `.forEach(...)` or `.for(...)` call. */\nfunction insideIterationCallback(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n if (\n parent.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n ITERATION_METHOD_NAMES.has(parent.callee.property.name)\n ) {\n return true\n }\n return insideIterationCallback(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .map() over manual transformations and imperative patterns\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n checkArrayMethods: {\n type: \"boolean\",\n default: true,\n },\n checkForLoops: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferMapOverLoop: \"Prefer .map() over for loop for transforming {{collection}}\",\n preferMapOverPush: \"Prefer .map() over manual .push() in loop\",\n preferMapChain: \"Consider using .map() for transformation instead of manual property access\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const checkArrayMethods = options.checkArrayMethods !== false\n // Off by default (#325): no-imperative-loops already reports every loop, and reporting the same loop\n // here too doubled each hit. Opt in when no-imperative-loops is disabled.\n const checkForLoops = options.checkForLoops === true\n\n function isForEachToMapSafe(node: ASTNode): boolean {\n // Only auto-fix simple forEach → map transformations on expressions that return values\n // This is safe because both native arrays and functype Lists have these methods\n if (\n node.type !== \"CallExpression\" ||\n node.callee.type !== \"MemberExpression\" ||\n node.callee.property.name !== \"forEach\"\n ) {\n return false\n }\n\n // Check if the callback returns a value (simple property access pattern)\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function (e.g., item => item.name)\n return body.type === \"MemberExpression\"\n }\n return false\n }\n\n function isTransformationLoop(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n\n const statements = node.body.body\n if (statements.length === 0) return false\n\n // Look for patterns like: newArray.push(transform(item))\n return statements.some((stmt: ASTNode) => {\n if (stmt.type === \"ExpressionStatement\" && stmt.expression.type === \"CallExpression\") {\n const call = stmt.expression\n return call.callee.type === \"MemberExpression\" && call.callee.property.name === \"push\"\n }\n return false\n })\n }\n\n function isSimplePropertyAccess(node: ASTNode): boolean {\n // Check for patterns like: items.forEach(item => console.log(item.name))\n // These could often be: items.map(item => item.name)\n if (\n node.type === \"CallExpression\" &&\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"forEach\"\n ) {\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function\n if (body.type === \"MemberExpression\") {\n return true\n }\n }\n }\n return false\n }\n\n function suspends(node: ASTNode): boolean {\n return node.await === true || containsAwait(node.body) || containsYield(node.body)\n }\n\n return {\n ForStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"array\" },\n })\n }\n },\n\n ForInStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"object\" },\n })\n }\n },\n\n ForOfStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"iterable\" },\n })\n }\n },\n\n CallExpression(node: ASTNode) {\n if (!checkArrayMethods) return\n\n // Check for forEach that could be map\n if (node.callee.type === \"MemberExpression\" && node.callee.property.name === \"forEach\") {\n if (isSimplePropertyAccess(node)) {\n context.report({\n node,\n messageId: \"preferMapChain\",\n fix(fixer) {\n // Only auto-fix safe forEach → map transformations\n if (!isForEachToMapSafe(node)) {\n return null\n }\n\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Simple replacement: forEach -> map\n const fixedText = text.replace(/\\.forEach\\s*\\(/g, \".map(\")\n return fixer.replaceText(node, fixedText)\n },\n })\n }\n }\n\n // Check for manual push patterns in callbacks\n if (\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"push\" &&\n insideIterationCallback(node)\n ) {\n context.report({ node, messageId: \"preferMapOverPush\" })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"+EAKA,MAAMA,kBAA8C,IAAI,IAAI,CAAC,UAAW,KAAK,CAAC,EAG9E,SAASC,EAAwB,EAA2C,CAC1E,IAAMC,EAASC,GAAM,OASrB,OARKD,EAEHA,EAAO,OAAS,kBAChBA,EAAO,OAAO,OAAS,oBACvBF,EAAuB,IAAI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,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-map.js","names":["ITERATION_METHOD_NAMES","insideIterationCallback","parent","node","rule","options","context","checkArrayMethods","checkForLoops","isForEachToMapSafe","callback","isTransformationLoop","statements","stmt","call","isSimplePropertyAccess","suspends","containsAwait","containsYield","fixedText","fixer"],"sources":["../../src/rules/prefer-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containsAwait, containsYield } from \"../utils/async-detection\"\n\nconst ITERATION_METHOD_NAMES: ReadonlySet<string> = new Set([\"forEach\", \"for\"])\n\n/** True iff any ancestor of `node` is a `.forEach(...)` or `.for(...)` call. */\nfunction insideIterationCallback(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n if (\n parent.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n ITERATION_METHOD_NAMES.has(parent.callee.property.name)\n ) {\n return true\n }\n return insideIterationCallback(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .map() over manual transformations and imperative patterns\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n checkArrayMethods: {\n type: \"boolean\",\n default: true,\n },\n checkForLoops: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferMapOverLoop: \"Prefer .map() over for loop for transforming {{collection}}\",\n preferMapOverPush: \"Prefer .map() over manual .push() in loop\",\n preferMapChain: \"Consider using .map() for transformation instead of manual property access\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const checkArrayMethods = options.checkArrayMethods !== false\n // Off by default (#325): no-imperative-loops already reports every loop, and reporting the same loop\n // here too doubled each hit. Opt in when no-imperative-loops is disabled.\n const checkForLoops = options.checkForLoops === true\n\n function isForEachToMapSafe(node: ASTNode): boolean {\n // Only auto-fix simple forEach → map transformations on expressions that return values\n // This is safe because both native arrays and functype Lists have these methods\n if (\n node.type !== \"CallExpression\" ||\n node.callee.type !== \"MemberExpression\" ||\n node.callee.property.name !== \"forEach\"\n ) {\n return false\n }\n\n // Check if the callback returns a value (simple property access pattern)\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function (e.g., item => item.name)\n return body.type === \"MemberExpression\"\n }\n return false\n }\n\n function isTransformationLoop(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n\n const statements = node.body.body\n if (statements.length === 0) return false\n\n // Look for patterns like: newArray.push(transform(item))\n return statements.some((stmt: ASTNode) => {\n if (stmt.type === \"ExpressionStatement\" && stmt.expression.type === \"CallExpression\") {\n const call = stmt.expression\n return call.callee.type === \"MemberExpression\" && call.callee.property.name === \"push\"\n }\n return false\n })\n }\n\n function isSimplePropertyAccess(node: ASTNode): boolean {\n // Check for patterns like: items.forEach(item => console.log(item.name))\n // These could often be: items.map(item => item.name)\n if (\n node.type === \"CallExpression\" &&\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"forEach\"\n ) {\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function\n if (body.type === \"MemberExpression\") {\n return true\n }\n }\n }\n return false\n }\n\n function suspends(node: ASTNode): boolean {\n return node.await === true || containsAwait(node.body) || containsYield(node.body)\n }\n\n return {\n ForStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"array\" },\n })\n }\n },\n\n ForInStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"object\" },\n })\n }\n },\n\n ForOfStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"iterable\" },\n })\n }\n },\n\n CallExpression(node: ASTNode) {\n if (!checkArrayMethods) return\n\n // Check for forEach that could be map\n if (node.callee.type === \"MemberExpression\" && node.callee.property.name === \"forEach\") {\n if (isSimplePropertyAccess(node)) {\n context.report({\n node,\n messageId: \"preferMapChain\",\n fix(fixer) {\n // Only auto-fix safe forEach → map transformations\n if (!isForEachToMapSafe(node)) {\n return null\n }\n\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Simple replacement: forEach -> map\n const fixedText = text.replace(/\\.forEach\\s*\\(/g, \".map(\")\n return fixer.replaceText(node, fixedText)\n },\n })\n }\n }\n\n // Check for manual push patterns in callbacks\n if (\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"push\" &&\n insideIterationCallback(node)\n ) {\n context.report({ node, messageId: \"preferMapOverPush\" })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,+EAKA,MAAMA,kBAA8C,IAAI,IAAI,CAAC,UAAW,KAAK,CAAC,EAG9E,SAASC,EAAwB,EAA2C,CAC1E,IAAMC,EAASC,GAAM,OASrB,OARKD,EAEHA,EAAO,OAAS,kBAChBA,EAAO,OAAO,OAAS,oBACvBF,EAAuB,IAAIE,EAAO,OAAO,SAAS,IAAI,EAE/C,GAEFD,EAAwBC,CAAM,EARjB,EAStB,CAEA,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,KAAM,CACJ,YA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,CACA,MAAO,EACT,CAEA,SAASM,EAAS,EAAwB,CACxC,OAAOb,EAAK,QAAU,IAAQc,EAAcd,EAAK,IAAI,GAAKe,EAAcf,EAAK,IAAI,CACnF,CAEA,MAAO,CACL,aAAa,EAAe,CACrBK,GAIDG,EAAqBR,CAAI,GAAK,CAACa,EAASb,CAAI,GAC9CG,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,WAAY,OAAQ,CAC9B,CAAC,CAEL,EAEA,eAAe,EAAe,CACvBE,GAIDG,EAAqBR,CAAI,GAAK,CAACa,EAASb,CAAI,GAC9CG,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,WAAY,QAAS,CAC/B,CAAC,CAEL,EAEA,eAAe,EAAe,CACvBE,GAIDG,EAAqBR,CAAI,GAAK,CAACa,EAASb,CAAI,GAC9CG,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,WAAY,UAAW,CACjC,CAAC,CAEL,EAEA,eAAe,EAAe,CACvBC,IAGDJ,EAAK,OAAO,OAAS,oBAAsBA,EAAK,OAAO,SAAS,OAAS,WACvEY,EAAuBZ,CAAI,GAC7BG,EAAQ,OAAO,CACb,OACA,UAAW,iBACX,IAAI,EAAO,CAET,GAAI,CAACG,EAAmBN,CAAI,EAC1B,OAAO,KAOT,IAAMgB,EAJab,EAAQ,WACH,QAAQH,CAGX,CAAC,CAAC,QAAQ,kBAAmB,OAAO,EACzD,OAAOiB,EAAM,YAAYjB,EAAMgB,CAAS,CAC1C,CACF,CAAC,EAMHhB,EAAK,OAAO,OAAS,oBACrBA,EAAK,OAAO,SAAS,OAAS,QAC9BF,EAAwBE,CAAI,GAE5BG,EAAQ,OAAO,CAAE,OAAM,UAAW,mBAAoB,CAAC,EAE3D,CACF,CACF,CACF,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-option.js","names":["REACT_STATE_HOOKS","isNullish","type","isParameter","parent","node","params","memberOrParameterOf","owner","annotation","unionMembers","union","t","threeStateSpellings","members","member","rule","WIRE_TYPES_SCHEMA","options","context","wireTypes","DEFAULT_WIRE_TYPES","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowUseState","checkOptionalMembers","isInHookTypeArgument","callee","name","functypeImports","getFunctypeImportsLegacy","checkOptional","isInsideWireType","isFunctypeType","kept","key","direct","undefinedOnly","nonNullTypes","nonNullType","isAlreadyUsingFunctype","sourceCode","nonNullTypeText","fullType","drop","suggestions","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-option.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype, isFunctypeType } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\n\nconst REACT_STATE_HOOKS: ReadonlySet<string> = new Set([\"useState\", \"useRef\"])\n\nconst isNullish = (type: ASTNode): boolean => type.type === \"TSNullKeyword\" || type.type === \"TSUndefinedKeyword\"\n\n/** Is `node` a parameter: of a function, a method signature or a function type, with or without a default? */\nfunction isParameter(node: ASTNode): boolean {\n const parent = node.parent as ASTNode | undefined\n if (!parent) return false\n if (parent.type === \"AssignmentPattern\" && parent.left === node) return isParameter(parent)\n if (parent.type === \"TSParameterProperty\") return true\n const params = (parent as { readonly params?: ReadonlyArray<ASTNode> }).params\n return Array.isArray(params) && params.includes(node)\n}\n\n/**\n * The member or parameter a type annotation belongs to, when it's the annotation of a type-literal or\n * interface member (`b: string | undefined`) or a parameter (`(x: string | undefined) => …`). Those are\n * the caller's shapes: a prop, an options-bag field, an argument (#446).\n */\nfunction memberOrParameterOf(annotation: ASTNode | undefined): ASTNode | undefined {\n const owner = annotation?.type === \"TSTypeAnnotation\" ? (annotation.parent as ASTNode | undefined) : undefined\n if (!owner) return undefined\n if (owner.type === \"TSPropertySignature\") return owner\n return isParameter(owner) ? owner : undefined\n}\n\n/**\n * A union's members, with nested unions spread in. The parser drops parentheses, so `(A | null) | undefined`\n * is a union holding a union; spread, it holds A, null and undefined.\n */\nfunction unionMembers(union: ASTNode): ReadonlyArray<ASTNode> {\n return union.types.flatMap((t: ASTNode) => (t.type === \"TSUnionType\" ? unionMembers(t) : [t]))\n}\n\n/**\n * Does a nullable union describe a three-state shape? Left out, cleared and set are three states, and\n * `Option` has two (#448). That's a type alias's body or a type-literal or interface member holding both\n * `null` and `undefined`, or an optional member that can also be `null` (`a?: T | null`). A parameter is a\n * converter's input and a return type is a result, so neither counts.\n *\n * Returns the two spellings of \"absent\" the type uses, for the message to say which to drop, or `undefined`\n * when the union isn't a three-state shape.\n */\nfunction threeStateSpellings(union: ASTNode, members: ReadonlyArray<ASTNode>): string | undefined {\n if (!members.some((t) => t.type === \"TSNullKeyword\")) return undefined\n const parent = union.parent as ASTNode | undefined\n const owner = parent?.type === \"TSTypeAnnotation\" ? (parent.parent as ASTNode | undefined) : undefined\n const member = owner?.type === \"TSPropertySignature\" ? owner : undefined\n if (member?.optional === true) return \"the ? or the | null\"\n if (!members.some((t) => t.type === \"TSUndefinedKeyword\")) return undefined\n return parent?.type === \"TSTypeAliasDeclaration\" || member !== undefined ? \"the | null or the | undefined\" : undefined\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Option<T> over nullable types (T | null | undefined)\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowNullableIntersections: {\n type: \"boolean\",\n default: false,\n },\n allowUseState: {\n type: \"boolean\",\n default: true,\n },\n checkOptionalMembers: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferOption:\n \"Prefer Option<{{type}}> over nullable type '{{nullable}}'. If this is a row, body or payload shape, wrap the type in Wire<…>\",\n preferOptionReturn: \"Prefer Option<{{type}}> as return type over nullable '{{nullable}}'\",\n preferOptionOverOptional:\n \"Prefer '{{name}}: Option<{{type}}>' over the optional '{{name}}?'. If this is a row, body or payload shape, wrap the type in Wire<…>\",\n preferWireForThreeStates:\n 'This type has three states, left out, null and set, and Option holds two. If it\\'s a row, body or payload shape, wrap the type in Wire<…>. If it only meant \"may be absent\", drop {{drop}} and use Option<{{type}}>',\n suggestOptionType: \"Replace with Option<{{type}}>\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\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 // `@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 // `null` is idiomatic React state (`useState<User | null>(null)`, `useRef<El | null>(null)`); an\n // Option in a hook's type argument buys nothing and fights the hook's own API (#325).\n const allowUseState = options.allowUseState !== false\n // `a?: T` and `a: T | undefined` on a member or parameter both mean \"may be absent\", and the caller\n // writes `<X b=\"v\" />` or `f()`. Skip both unless asked to report them (#446).\n const checkOptionalMembers = options.checkOptionalMembers === true\n\n /** Is `node` inside the type argument of a `useState` / `useRef` call (bare or `React.`-qualified)? */\n function isInHookTypeArgument(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"TSTypeParameterInstantiation\" && parent.parent?.type === \"CallExpression\") {\n const callee = parent.parent.callee\n const name =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (name !== null && REACT_STATE_HOOKS.has(name)) return true\n }\n return isInHookTypeArgument(parent)\n }\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n /** With checkOptionalMembers, `a?: T` on a member or parameter is reported like `a: T | undefined`. */\n function checkOptional(node: ASTNode): void {\n if (!checkOptionalMembers || node.optional !== true) return\n if (node.type !== \"TSPropertySignature\" && !isParameter(node)) return\n if (isInsideWireType(node, wireTypes) || isExemptByMarker(node)) return\n const annotation = (node.typeAnnotation as ASTNode | undefined)?.typeAnnotation as ASTNode | undefined\n if (!annotation || isFunctypeType(annotation, functypeImports)) return\n const members = annotation.type === \"TSUnionType\" ? unionMembers(annotation) : [annotation]\n // `a?: T | null` is reported once, by the union check.\n if (members.some((t) => t.type === \"TSNullKeyword\")) return\n const kept = members.filter((t) => !isNullish(t))\n if (kept.length !== 1 || isFunctypeType(kept[0], functypeImports)) return\n const key = (node.type === \"TSPropertySignature\" ? node.key : node) as ASTNode\n const name =\n key.type === \"Identifier\"\n ? key.name\n : key.type === \"Literal\"\n ? String(key.value)\n : context.sourceCode.getText(key)\n context.report({\n node: key,\n messageId: \"preferOptionOverOptional\",\n data: { name, type: context.sourceCode.getText(kept[0]) },\n })\n }\n\n return {\n TSPropertySignature: checkOptional,\n Identifier: checkOptional,\n\n TSUnionType(node: ASTNode) {\n // A union nested in a union is part of the outer one, which reports for both.\n if ((node.parent as ASTNode | undefined)?.type === \"TSUnionType\") return\n if (isInsideWireType(node, wireTypes)) return\n if (isExemptByMarker(node)) return\n if (!node.types || node.types.length < 2) return\n // The gate the rule always had: a nullish member of its own beside exactly one other. Spreading\n // nested unions below only refines what that one member is, so nothing new gets reported.\n const direct: ReadonlyArray<ASTNode> = node.types\n if (!direct.some((t) => isNullish(t)) || direct.filter((t) => !isNullish(t)).length !== 1) return\n if (allowUseState && isInHookTypeArgument(node)) return\n\n const members = unionMembers(node)\n const hasNull = members.some((type) => isNullish(type))\n\n if (!hasNull) return\n\n // On a member or parameter, `T | undefined` is the same \"may be absent\" as `?:`: skipped unless\n // checkOptionalMembers is on, and never reported on an optional one (`c?: T | undefined` is the\n // spelling exactOptionalPropertyTypes needs; the optional-member check reports it, once).\n const owner = memberOrParameterOf(node.parent)\n const undefinedOnly = !members.some((type) => type.type === \"TSNullKeyword\")\n if (owner && undefinedOnly && (!checkOptionalMembers || owner.optional === true)) return\n\n const nonNullTypes = members.filter((type) => !isNullish(type))\n\n if (nonNullTypes.length === 1) {\n const nonNullType = nonNullTypes[0]\n\n // Skip if it's already an Option type or other functype type\n if (isFunctypeType(nonNullType, functypeImports)) return\n\n // Skip if we're already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const nonNullTypeText = sourceCode.getText(nonNullType)\n const fullType = sourceCode.getText(node)\n\n // Skip if it's already an Option type (fallback check)\n if (nonNullTypeText.startsWith(\"Option<\")) return\n\n const drop = threeStateSpellings(node, members)\n if (drop !== undefined) {\n context.report({ node, messageId: \"preferWireForThreeStates\", data: { type: nonNullTypeText, drop } })\n return\n }\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestOptionType\",\n data: { type: nonNullTypeText },\n fix(fixer) {\n return fixer.replaceText(node, `Option<${nonNullTypeText}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"Option\")) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Option\" },\n fix: createImportFixer(sourceCode, \"Option\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferOption\",\n data: {\n type: nonNullTypeText,\n nullable: fullType,\n },\n suggest: suggestions,\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"6XAQA,MAAMA,kBAAyC,IAAI,IAAI,CAAC,WAAY,QAAQ,CAAC,EAEvEC,EAAa,GAA2BC,EAAK,OAAS,iBAAmBA,EAAK,OAAS,qBAG7F,SAASC,EAAY,EAAwB,CAC3C,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CAC7B,IAAMC,EAAcD,EAAa,GAMjC,GAHIL,EAAeM,EAAaV,CAAe,GAG3CW,EAAuBpC,EAAMyB,CAAe,EAAG,OAEnD,IAAMY,EAAavB,EAAQ,WACrBwB,EAAkBD,EAAW,QAAQF,CAAW,EAChDI,EAAWF,EAAW,QAAQrC,CAAI,EAGxC,GAAIsC,EAAgB,WAAW,SAAS,EAAG,OAE3C,IAAME,EAAOhC,EAAoBR,EAAMS,CAAO,EAC9C,GAAI+B,IAAS,IAAA,GAAW,CACtB1B,EAAQ,OAAO,CAAE,OAAM,UAAW,2BAA4B,KAAM,CAAE,KAAMwB,EAAiB,MAAK,CAAE,CAAC,EACrG,MACF,CAEA,IAAMG,EAAiD,CACrD,CACE,UAAW,oBACX,KAAM,CAAE,KAAMH,CAAgB,EAC9B,IAAI,EAAO,CACT,OAAOI,EAAM,YAAY1C,EAAM,UAAUsC,EAAgB,EAAE,CAC7D,CACF,CACF,EAEKK,EAAkBN,EAAY,QAAQ,GACzCI,EAAY,KAAK,CACf,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKG,EAAkBP,EAAY,QAAQ,CAC7C,CAAC,EAGHvB,EAAQ,OAAO,CACb,OACA,UAAW,eACX,KAAM,CACJ,KAAMwB,EACN,SAAUC,CACZ,EACA,QAASE,CACX,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-option.js","names":["REACT_STATE_HOOKS","isNullish","type","isParameter","parent","node","params","memberOrParameterOf","owner","annotation","unionMembers","union","t","threeStateSpellings","members","member","rule","WIRE_TYPES_SCHEMA","options","context","wireTypes","DEFAULT_WIRE_TYPES","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowUseState","checkOptionalMembers","isInHookTypeArgument","callee","name","functypeImports","getFunctypeImportsLegacy","checkOptional","isInsideWireType","isFunctypeType","kept","key","direct","undefinedOnly","nonNullTypes","nonNullType","isAlreadyUsingFunctype","sourceCode","nonNullTypeText","fullType","drop","suggestions","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-option.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype, isFunctypeType } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\n\nconst REACT_STATE_HOOKS: ReadonlySet<string> = new Set([\"useState\", \"useRef\"])\n\nconst isNullish = (type: ASTNode): boolean => type.type === \"TSNullKeyword\" || type.type === \"TSUndefinedKeyword\"\n\n/** Is `node` a parameter: of a function, a method signature or a function type, with or without a default? */\nfunction isParameter(node: ASTNode): boolean {\n const parent = node.parent as ASTNode | undefined\n if (!parent) return false\n if (parent.type === \"AssignmentPattern\" && parent.left === node) return isParameter(parent)\n if (parent.type === \"TSParameterProperty\") return true\n const params = (parent as { readonly params?: ReadonlyArray<ASTNode> }).params\n return Array.isArray(params) && params.includes(node)\n}\n\n/**\n * The member or parameter a type annotation belongs to, when it's the annotation of a type-literal or\n * interface member (`b: string | undefined`) or a parameter (`(x: string | undefined) => …`). Those are\n * the caller's shapes: a prop, an options-bag field, an argument (#446).\n */\nfunction memberOrParameterOf(annotation: ASTNode | undefined): ASTNode | undefined {\n const owner = annotation?.type === \"TSTypeAnnotation\" ? (annotation.parent as ASTNode | undefined) : undefined\n if (!owner) return undefined\n if (owner.type === \"TSPropertySignature\") return owner\n return isParameter(owner) ? owner : undefined\n}\n\n/**\n * A union's members, with nested unions spread in. The parser drops parentheses, so `(A | null) | undefined`\n * is a union holding a union; spread, it holds A, null and undefined.\n */\nfunction unionMembers(union: ASTNode): ReadonlyArray<ASTNode> {\n return union.types.flatMap((t: ASTNode) => (t.type === \"TSUnionType\" ? unionMembers(t) : [t]))\n}\n\n/**\n * Does a nullable union describe a three-state shape? Left out, cleared and set are three states, and\n * `Option` has two (#448). That's a type alias's body or a type-literal or interface member holding both\n * `null` and `undefined`, or an optional member that can also be `null` (`a?: T | null`). A parameter is a\n * converter's input and a return type is a result, so neither counts.\n *\n * Returns the two spellings of \"absent\" the type uses, for the message to say which to drop, or `undefined`\n * when the union isn't a three-state shape.\n */\nfunction threeStateSpellings(union: ASTNode, members: ReadonlyArray<ASTNode>): string | undefined {\n if (!members.some((t) => t.type === \"TSNullKeyword\")) return undefined\n const parent = union.parent as ASTNode | undefined\n const owner = parent?.type === \"TSTypeAnnotation\" ? (parent.parent as ASTNode | undefined) : undefined\n const member = owner?.type === \"TSPropertySignature\" ? owner : undefined\n if (member?.optional === true) return \"the ? or the | null\"\n if (!members.some((t) => t.type === \"TSUndefinedKeyword\")) return undefined\n return parent?.type === \"TSTypeAliasDeclaration\" || member !== undefined ? \"the | null or the | undefined\" : undefined\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Option<T> over nullable types (T | null | undefined)\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowNullableIntersections: {\n type: \"boolean\",\n default: false,\n },\n allowUseState: {\n type: \"boolean\",\n default: true,\n },\n checkOptionalMembers: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferOption:\n \"Prefer Option<{{type}}> over nullable type '{{nullable}}'. If this is a row, body or payload shape, wrap the type in Wire<…>\",\n preferOptionReturn: \"Prefer Option<{{type}}> as return type over nullable '{{nullable}}'\",\n preferOptionOverOptional:\n \"Prefer '{{name}}: Option<{{type}}>' over the optional '{{name}}?'. If this is a row, body or payload shape, wrap the type in Wire<…>\",\n preferWireForThreeStates:\n 'This type has three states, left out, null and set, and Option holds two. If it\\'s a row, body or payload shape, wrap the type in Wire<…>. If it only meant \"may be absent\", drop {{drop}} and use Option<{{type}}>',\n suggestOptionType: \"Replace with Option<{{type}}>\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\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 // `@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 // `null` is idiomatic React state (`useState<User | null>(null)`, `useRef<El | null>(null)`); an\n // Option in a hook's type argument buys nothing and fights the hook's own API (#325).\n const allowUseState = options.allowUseState !== false\n // `a?: T` and `a: T | undefined` on a member or parameter both mean \"may be absent\", and the caller\n // writes `<X b=\"v\" />` or `f()`. Skip both unless asked to report them (#446).\n const checkOptionalMembers = options.checkOptionalMembers === true\n\n /** Is `node` inside the type argument of a `useState` / `useRef` call (bare or `React.`-qualified)? */\n function isInHookTypeArgument(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"TSTypeParameterInstantiation\" && parent.parent?.type === \"CallExpression\") {\n const callee = parent.parent.callee\n const name =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (name !== null && REACT_STATE_HOOKS.has(name)) return true\n }\n return isInHookTypeArgument(parent)\n }\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n /** With checkOptionalMembers, `a?: T` on a member or parameter is reported like `a: T | undefined`. */\n function checkOptional(node: ASTNode): void {\n if (!checkOptionalMembers || node.optional !== true) return\n if (node.type !== \"TSPropertySignature\" && !isParameter(node)) return\n if (isInsideWireType(node, wireTypes) || isExemptByMarker(node)) return\n const annotation = (node.typeAnnotation as ASTNode | undefined)?.typeAnnotation as ASTNode | undefined\n if (!annotation || isFunctypeType(annotation, functypeImports)) return\n const members = annotation.type === \"TSUnionType\" ? unionMembers(annotation) : [annotation]\n // `a?: T | null` is reported once, by the union check.\n if (members.some((t) => t.type === \"TSNullKeyword\")) return\n const kept = members.filter((t) => !isNullish(t))\n if (kept.length !== 1 || isFunctypeType(kept[0], functypeImports)) return\n const key = (node.type === \"TSPropertySignature\" ? node.key : node) as ASTNode\n const name =\n key.type === \"Identifier\"\n ? key.name\n : key.type === \"Literal\"\n ? String(key.value)\n : context.sourceCode.getText(key)\n context.report({\n node: key,\n messageId: \"preferOptionOverOptional\",\n data: { name, type: context.sourceCode.getText(kept[0]) },\n })\n }\n\n return {\n TSPropertySignature: checkOptional,\n Identifier: checkOptional,\n\n TSUnionType(node: ASTNode) {\n // A union nested in a union is part of the outer one, which reports for both.\n if ((node.parent as ASTNode | undefined)?.type === \"TSUnionType\") return\n if (isInsideWireType(node, wireTypes)) return\n if (isExemptByMarker(node)) return\n if (!node.types || node.types.length < 2) return\n // The gate the rule always had: a nullish member of its own beside exactly one other. Spreading\n // nested unions below only refines what that one member is, so nothing new gets reported.\n const direct: ReadonlyArray<ASTNode> = node.types\n if (!direct.some((t) => isNullish(t)) || direct.filter((t) => !isNullish(t)).length !== 1) return\n if (allowUseState && isInHookTypeArgument(node)) return\n\n const members = unionMembers(node)\n const hasNull = members.some((type) => isNullish(type))\n\n if (!hasNull) return\n\n // On a member or parameter, `T | undefined` is the same \"may be absent\" as `?:`: skipped unless\n // checkOptionalMembers is on, and never reported on an optional one (`c?: T | undefined` is the\n // spelling exactOptionalPropertyTypes needs; the optional-member check reports it, once).\n const owner = memberOrParameterOf(node.parent)\n const undefinedOnly = !members.some((type) => type.type === \"TSNullKeyword\")\n if (owner && undefinedOnly && (!checkOptionalMembers || owner.optional === true)) return\n\n const nonNullTypes = members.filter((type) => !isNullish(type))\n\n if (nonNullTypes.length === 1) {\n const nonNullType = nonNullTypes[0]\n\n // Skip if it's already an Option type or other functype type\n if (isFunctypeType(nonNullType, functypeImports)) return\n\n // Skip if we're already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const nonNullTypeText = sourceCode.getText(nonNullType)\n const fullType = sourceCode.getText(node)\n\n // Skip if it's already an Option type (fallback check)\n if (nonNullTypeText.startsWith(\"Option<\")) return\n\n const drop = threeStateSpellings(node, members)\n if (drop !== undefined) {\n context.report({ node, messageId: \"preferWireForThreeStates\", data: { type: nonNullTypeText, drop } })\n return\n }\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestOptionType\",\n data: { type: nonNullTypeText },\n fix(fixer) {\n return fixer.replaceText(node, `Option<${nonNullTypeText}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"Option\")) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Option\" },\n fix: createImportFixer(sourceCode, \"Option\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferOption\",\n data: {\n type: nonNullTypeText,\n nullable: fullType,\n },\n suggest: suggestions,\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,6XAQA,MAAMA,kBAAyC,IAAI,IAAI,CAAC,WAAY,QAAQ,CAAC,EAEvEC,EAAa,GAA2BC,EAAK,OAAS,iBAAmBA,EAAK,OAAS,qBAG7F,SAASC,EAAY,EAAwB,CAC3C,IAAMC,EAASC,EAAK,OACpB,GAAI,CAACD,EAAQ,MAAO,GACpB,GAAIA,EAAO,OAAS,qBAAuBA,EAAO,OAASC,EAAM,OAAOF,EAAYC,CAAM,EAC1F,GAAIA,EAAO,OAAS,sBAAuB,MAAO,GAClD,IAAME,EAAUF,EAAwD,OACxE,OAAO,MAAM,QAAQE,CAAM,GAAKA,EAAO,SAASD,CAAI,CACtD,CAOA,SAASE,EAAoB,EAAsD,CACjF,IAA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C,GAAI+B,IAAS,IAAA,GAAW,CACtB1B,EAAQ,OAAO,CAAE,OAAM,UAAW,2BAA4B,KAAM,CAAE,KAAMwB,EAAiB,MAAK,CAAE,CAAC,EACrG,MACF,CAEA,IAAMG,EAAiD,CACrD,CACE,UAAW,oBACX,KAAM,CAAE,KAAMH,CAAgB,EAC9B,IAAI,EAAO,CACT,OAAOI,EAAM,YAAY1C,EAAM,UAAUsC,EAAgB,EAAE,CAC7D,CACF,CACF,EAEKK,EAAkBN,EAAY,QAAQ,GACzCI,EAAY,KAAK,CACf,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKG,EAAkBP,EAAY,QAAQ,CAC7C,CAAC,EAGHvB,EAAQ,OAAO,CACb,OACA,UAAW,eACX,KAAM,CACJ,KAAMwB,EACN,SAAUC,CACZ,EACA,QAASE,CACX,CAAC,CACH,CACF,CACF,CACF,CACF,E"}
|
package/dist/rules/prefer-try.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{containsAwait as e}from"../utils/async-detection.js";import{isInsideTaggedDeclaration as t}from"../utils/boundary-tags.js";import{createImportFixer as n,hasFunctypeSymbol as r}from"../utils/import-fixer.js";const i={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer Try for computations that may throw`,recommended:!0},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},allowThrowInTests:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferTryOverTryCatch:`Prefer Try(() => ...) over try/catch block`,preferAsyncTryOverTryCatch:`Prefer Try.fromPromise(...), Either.fromPromise(...) or IO.tryPromise(...) over an async try/catch — Try(() => ...) cannot catch an awaited rejection`,suggestTry:`Replace with Try(() => ...)`,suggestTryFromPromise:`Replace with Try.fromPromise(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(i){let a=i.options[0]||{},o=a.allowInteropMarker!==!1,s=e=>o&&t(e,`interop`,i.sourceCode),c=a.allowThrowInTests!==!1;function l(){let e=i.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function u(e){return e.block?.body?.length===1}function d(e){if(!e.handler?.body)return!1;let t=e.handler.body.body;return t.length===0||t.length===1&&(t[0].type===`ReturnStatement`||t[0].type===`ExpressionStatement`)}function f(e){let t=e.block.body[0];return t.type===`ReturnStatement`&&t.argument?.type===`AwaitExpression`||t.type===`ExpressionStatement`&&t.expression?.type===`AwaitExpression`}return{TryStatement(t){if(s(t)||t.finalizer||c&&l()||t.handler&&t.handler.body&&t.handler.body.body.some(e=>e.type===`ThrowStatement`))return;let a=i.sourceCode,o=[];if(u(t)&&d(t)){let e=t.block.body[0];if(e.type===`ReturnStatement`){let i=e.argument,s=a.getText(i);if(f(t)){let e=i.type===`AwaitExpression`?i.argument:i,n=a.getText(e);o.push({messageId:`suggestTryFromPromise`,fix(e){return e.replaceText(t,`return Try.fromPromise(${n})`)}})}else o.push({messageId:`suggestTry`,fix(e){return e.replaceText(t,`return Try(() => ${s})`)}});r(a,`Try`)||o.push({messageId:`suggestAddImport`,data:{symbol:`Try`},fix:n(a,`Try`)})}}i.report({node:t,messageId:e(t.block)?`preferAsyncTryOverTryCatch`:`preferTryOverTryCatch`,suggest:o})}}}};export{i as default};
|
|
2
2
|
//# sourceMappingURL=prefer-try.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-try.js","names":["rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","node","allowThrowInTests","isInTestFile","filename","isSimpleTryBody","isSimpleCatch","catchBody","tryBodyHasAwait","stmt","sourceCode","suggest","tryStmt","expr","exprText","awaitExpr","innerText","fixer","hasFunctypeSymbol","createImportFixer","containsAwait"],"sources":["../../src/rules/prefer-try.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containsAwait } from \"../utils/async-detection\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Try for computations that may throw\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferTryOverTryCatch: \"Prefer Try(() => ...) over try/catch block\",\n preferAsyncTryOverTryCatch:\n \"Prefer Try.fromPromise(...), Either.fromPromise(...) or IO.tryPromise(...) over an async try/catch — Try(() => ...) cannot catch an awaited rejection\",\n suggestTry: \"Replace with Try(() => ...)\",\n suggestTryFromPromise: \"Replace with Try.fromPromise(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\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 allowThrowInTests = options.allowThrowInTests !== 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 function isSimpleTryBody(node: ASTNode): boolean {\n return node.block?.body?.length === 1\n }\n\n function isSimpleCatch(node: ASTNode): boolean {\n if (!node.handler?.body) return false\n const catchBody = node.handler.body.body\n return (\n catchBody.length === 0 ||\n (catchBody.length === 1 &&\n (catchBody[0].type === \"ReturnStatement\" || catchBody[0].type === \"ExpressionStatement\"))\n )\n }\n\n function tryBodyHasAwait(node: ASTNode): boolean {\n const stmt = node.block.body[0]\n if (stmt.type === \"ReturnStatement\" && stmt.argument?.type === \"AwaitExpression\") return true\n if (stmt.type === \"ExpressionStatement\" && stmt.expression?.type === \"AwaitExpression\") return true\n return false\n }\n\n return {\n TryStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n // Try cannot model `finally` — bail on any try statement with a finalizer.\n // Covers two bugs: (1) catch-less try/finally fires a misleading warning\n // with no useful autofix; (2) try/catch/finally autofix would lift the\n // catch into Try(() => …) and silently drop the finally clause. The FP\n // primitive for guaranteed cleanup is IO.bracket, on the lazy IO type.\n // See #206.\n if (node.finalizer) return\n\n // Allow try/catch in test files\n if (allowThrowInTests && isInTestFile()) return\n\n // Allow try/catch that re-throws in the catch block (even with logging)\n if (node.handler && node.handler.body) {\n const catchBody = node.handler.body.body\n const hasRethrow = catchBody.some((stmt: ASTNode) => stmt.type === \"ThrowStatement\")\n if (hasRethrow) return\n }\n\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isSimpleTryBody(node) && isSimpleCatch(node)) {\n const tryStmt = node.block.body[0]\n const isReturn = tryStmt.type === \"ReturnStatement\"\n\n // Only suggest when the try body is a return statement — non-return expression\n // replacements would produce syntactically ambiguous code without knowing the context\n if (isReturn) {\n const expr = tryStmt.argument\n const exprText = sourceCode.getText(expr)\n\n if (tryBodyHasAwait(node)) {\n const awaitExpr = expr.type === \"AwaitExpression\" ? expr.argument : expr\n const innerText = sourceCode.getText(awaitExpr)\n suggest.push({\n messageId: \"suggestTryFromPromise\",\n fix(fixer) {\n return fixer.replaceText(node, `return Try.fromPromise(${innerText})`)\n },\n })\n } else {\n suggest.push({\n messageId: \"suggestTry\",\n fix(fixer) {\n return fixer.replaceText(node, `return Try(() => ${exprText})`)\n },\n })\n }\n\n if (!hasFunctypeSymbol(sourceCode, \"Try\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Try\" },\n fix: createImportFixer(sourceCode, \"Try\"),\n })\n }\n }\n }\n\n context.report({\n node,\n messageId: containsAwait(node.block) ? \"preferAsyncTryOverTryCatch\" : \"preferTryOverTryCatch\",\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"sNAOA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,6CACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,mBAAoB,CAClB,KAAM,UACN,QAAS,EACX,EACA,kBAAmB,CACjB,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,sBAAuB,6CACvB,2BACE,wJACF,WAAY,8BACZ,sBAAuB,oCACvB,iBAAkB,qCACpB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EAEjCC,EAAqBF,EAAQ,qBAAuB,GACpDG,EAAoB,GACxBD,GAAsBE,EAA0BC,EAAA,UAAmBJ,EAAQ,UAAU,EACjFK,EAAoBN,EAAQ,oBAAsB,GAExD,SAASO,GAAe,CACtB,IAAMC,EAAWP,EAAQ,SACzB,MACE,kCAAkC,KAAKO,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,SAASC,EAAgB,EAAwB,CAC/C,OAAOJ,EAAK,OAAO,MAAM,SAAW,CACtC,CAEA,SAASK,EAAc,EAAwB,CAC7C,GAAI,CAACL,EAAK,SAAS,KAAM,MAAO,GAChC,IAAMM,EAAYN,EAAK,QAAQ,KAAK,KACpC,OACEM,EAAU,SAAW,GACpBA,EAAU,SAAW,IACnBA,EAAU,EAAE,CAAC,OAAS,mBAAqBA,EAAU,EAAE,CAAC,OAAS,sBAExE,CAEA,SAASC,EAAgB,EAAwB,CAC/C,IAAMC,EAAOR,EAAK,MAAM,KAAK,GAG7B,OAFIQ,EAAK,OAAS,mBAAqBA,EAAK,UAAU,OAAS,mBAC3DA,EAAK,OAAS,uBAAyBA,EAAK,YAAY,OAAS,iBAEvE,CAEA,MAAO,CACL,aAAa,EAAe,CAc1B,GAbIV,EAAiBE,CAAI,GAOrBA,EAAK,WAGLC,GAAqBC,EAAa,GAGlCF,EAAK,SAAWA,EAAK,QAAQ,MACbA,EAAK,QAAQ,KAAK,KACP,KAAM,GAAkBQ,EAAK,OAAS,gBACtD,EAAG,OAGlB,IAAMC,EAAab,EAAQ,WACrBc,EAA6C,CAAC,EAEpD,GAAIN,EAAgBJ,CAAI,GAAKK,EAAcL,CAAI,EAAG,CAChD,IAAMW,EAAUX,EAAK,MAAM,KAAK,GAKhC,GAJiBW,EAAQ,OAAS,kBAIpB,CACZ,IAAMC,EAAOD,EAAQ,SACfE,EAAWJ,EAAW,QAAQG,CAAI,EAExC,GAAIL,EAAgBP,CAAI,EAAG,CACzB,IAAMc,EAAYF,EAAK,OAAS,kBAAoBA,EAAK,SAAWA,EAC9DG,EAAYN,EAAW,QAAQK,CAAS,EAC9CJ,EAAQ,KAAK,CACX,UAAW,wBACX,IAAI,EAAO,CACT,OAAOM,EAAM,YAAYhB,EAAM,0BAA0Be,EAAU,EAAE,CACvE,CACF,CAAC,CACH,MACEL,EAAQ,KAAK,CACX,UAAW,aACX,IAAI,EAAO,CACT,OAAOM,EAAM,YAAYhB,EAAM,oBAAoBa,EAAS,EAAE,CAChE,CACF,CAAC,EAGEI,EAAkBR,EAAY,KAAK,GACtCC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,KAAM,EACtB,IAAKQ,EAAkBT,EAAY,KAAK,CAC1C,CAAC,CAEL,CACF,CAEAb,EAAQ,OAAO,CACb,OACA,UAAWuB,EAAcnB,EAAK,KAAK,EAAI,6BAA+B,wBACtE,SACF,CAAC,CACH,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-try.js","names":["rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","node","allowThrowInTests","isInTestFile","filename","isSimpleTryBody","isSimpleCatch","catchBody","tryBodyHasAwait","stmt","sourceCode","suggest","tryStmt","expr","exprText","awaitExpr","innerText","fixer","hasFunctypeSymbol","createImportFixer","containsAwait"],"sources":["../../src/rules/prefer-try.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containsAwait } from \"../utils/async-detection\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Try for computations that may throw\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferTryOverTryCatch: \"Prefer Try(() => ...) over try/catch block\",\n preferAsyncTryOverTryCatch:\n \"Prefer Try.fromPromise(...), Either.fromPromise(...) or IO.tryPromise(...) over an async try/catch — Try(() => ...) cannot catch an awaited rejection\",\n suggestTry: \"Replace with Try(() => ...)\",\n suggestTryFromPromise: \"Replace with Try.fromPromise(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\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 allowThrowInTests = options.allowThrowInTests !== 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 function isSimpleTryBody(node: ASTNode): boolean {\n return node.block?.body?.length === 1\n }\n\n function isSimpleCatch(node: ASTNode): boolean {\n if (!node.handler?.body) return false\n const catchBody = node.handler.body.body\n return (\n catchBody.length === 0 ||\n (catchBody.length === 1 &&\n (catchBody[0].type === \"ReturnStatement\" || catchBody[0].type === \"ExpressionStatement\"))\n )\n }\n\n function tryBodyHasAwait(node: ASTNode): boolean {\n const stmt = node.block.body[0]\n if (stmt.type === \"ReturnStatement\" && stmt.argument?.type === \"AwaitExpression\") return true\n if (stmt.type === \"ExpressionStatement\" && stmt.expression?.type === \"AwaitExpression\") return true\n return false\n }\n\n return {\n TryStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n // Try cannot model `finally` — bail on any try statement with a finalizer.\n // Covers two bugs: (1) catch-less try/finally fires a misleading warning\n // with no useful autofix; (2) try/catch/finally autofix would lift the\n // catch into Try(() => …) and silently drop the finally clause. The FP\n // primitive for guaranteed cleanup is IO.bracket, on the lazy IO type.\n // See #206.\n if (node.finalizer) return\n\n // Allow try/catch in test files\n if (allowThrowInTests && isInTestFile()) return\n\n // Allow try/catch that re-throws in the catch block (even with logging)\n if (node.handler && node.handler.body) {\n const catchBody = node.handler.body.body\n const hasRethrow = catchBody.some((stmt: ASTNode) => stmt.type === \"ThrowStatement\")\n if (hasRethrow) return\n }\n\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isSimpleTryBody(node) && isSimpleCatch(node)) {\n const tryStmt = node.block.body[0]\n const isReturn = tryStmt.type === \"ReturnStatement\"\n\n // Only suggest when the try body is a return statement — non-return expression\n // replacements would produce syntactically ambiguous code without knowing the context\n if (isReturn) {\n const expr = tryStmt.argument\n const exprText = sourceCode.getText(expr)\n\n if (tryBodyHasAwait(node)) {\n const awaitExpr = expr.type === \"AwaitExpression\" ? expr.argument : expr\n const innerText = sourceCode.getText(awaitExpr)\n suggest.push({\n messageId: \"suggestTryFromPromise\",\n fix(fixer) {\n return fixer.replaceText(node, `return Try.fromPromise(${innerText})`)\n },\n })\n } else {\n suggest.push({\n messageId: \"suggestTry\",\n fix(fixer) {\n return fixer.replaceText(node, `return Try(() => ${exprText})`)\n },\n })\n }\n\n if (!hasFunctypeSymbol(sourceCode, \"Try\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Try\" },\n fix: createImportFixer(sourceCode, \"Try\"),\n })\n }\n }\n }\n\n context.report({\n node,\n messageId: containsAwait(node.block) ? \"preferAsyncTryOverTryCatch\" : \"preferTryOverTryCatch\",\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"A,sNAOA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,6CACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,mBAAoB,CAClB,KAAM,UACN,QAAS,EACX,EACA,kBAAmB,CACjB,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,sBAAuB,6CACvB,2BACE,wJACF,WAAY,8BACZ,sBAAuB,oCACvB,iBAAkB,qCACpB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EAEjCC,EAAqBF,EAAQ,qBAAuB,GACpDG,EAAoB,GACxBD,GAAsBE,EAA0BC,EAAA,UAAmBJ,EAAQ,UAAU,EACjFK,EAAoBN,EAAQ,oBAAsB,GAExD,SAASO,GAAe,CACtB,IAAMC,EAAWP,EAAQ,SACzB,MACE,kCAAkC,KAAKO,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,SAASC,EAAgB,EAAwB,CAC/C,OAAOJ,EAAK,OAAO,MAAM,SAAW,CACtC,CAEA,SAASK,EAAc,EAAwB,CAC7C,GAAI,CAACL,EAAK,SAAS,KAAM,M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,KAAM,EACtB,IAAKQ,EAAkBT,EAAY,KAAK,CAC1C,CAAC,CAEL,CACF,CAEAb,EAAQ,OAAO,CACb,OACA,UAAWuB,EAAcnB,EAAK,KAAK,EAAI,6BAA+B,wBACtE,SACF,CAAC,CACH,CACF,CACF,CACF,E"}
|
package/dist/types/ast.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/types/ast.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* ESLint AST Node type alias
|
|
4
3
|
*
|
|
@@ -6,6 +5,4 @@
|
|
|
6
5
|
* Using `any` is the standard practice for ESLint rule development when working
|
|
7
6
|
* with AST nodes that need dynamic property access.
|
|
8
7
|
*/
|
|
9
|
-
export type ASTNode = any;
|
|
10
|
-
//#endregion
|
|
11
|
-
//# sourceMappingURL=ast.d.ts.map
|
|
8
|
+
export type ASTNode = any;
|
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
import { ASTNode } from "../types/ast.js";
|
|
2
2
|
import { Rule } from "eslint";
|
|
3
|
-
//#region src/utils/array-mutation.d.ts
|
|
4
3
|
/** Is `node` (an expression) typed as a mutable array? `false` without type information. */
|
|
5
|
-
export declare const isMutableArrayExpression: (node: ASTNode, context: Rule.RuleContext) => boolean;
|
|
6
|
-
//#endregion
|
|
7
|
-
//# sourceMappingURL=array-mutation.d.ts.map
|
|
4
|
+
export declare const isMutableArrayExpression: (node: ASTNode, context: Rule.RuleContext) => boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"array-mutation.js","names":["typedServices","services","context","isMutableArray","type","types","checker","member","target","symbol","isMutableArrayExpression","tsNode","node"],"sources":["../../src/utils/array-mutation.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Type checks for `no-array-mutation`, reached through `parserServices` and typed structurally so the\n * plugin takes no runtime dependency on `typescript`. Every check answers `false` without type\n * information: the rule reports nothing it can't prove is an array.\n */\n\ntype TypeLike = object\n\ntype CheckerLike = {\n getTypeAtLocation(node: unknown): TypeLike\n getNonNullableType(type: TypeLike): TypeLike\n isArrayLikeType(type: TypeLike): boolean\n isTupleType(type: TypeLike): boolean\n}\n\ntype TypedServices = {\n readonly program: { getTypeChecker(): CheckerLike }\n readonly esTreeNodeToTSNodeMap: { get(node: unknown): unknown }\n}\n\nconst typedServices = (context: Rule.RuleContext): TypedServices | undefined => {\n const services = context.sourceCode.parserServices as Partial<TypedServices> | undefined\n return services?.program && services.esTreeNodeToTSNodeMap ? (services as TypedServices) : undefined\n}\n\n/**\n * The mutable `Array` type, or a non-readonly tuple — `ReadonlyArray` has no `push`, so TypeScript\n * already rejects mutating one. Every member of a union must be one, so `string[] | Set<string>`\n * isn't reported on a `.push` the compiler resolves some other way.\n */\nconst isMutableArray = (checker: CheckerLike, type: TypeLike): boolean => {\n const { types, symbol, target } = type as {\n types?: ReadonlyArray<TypeLike>\n symbol?: { name?: string }\n target?: { readonly?: boolean }\n }\n if (types) return types.length > 0 && types.every((member) => isMutableArray(checker, member))\n if (checker.isTupleType(type)) return target?.readonly !== true\n return symbol?.name === \"Array\" && checker.isArrayLikeType(type)\n}\n\n/** Is `node` (an expression) typed as a mutable array? `false` without type information. */\nexport const isMutableArrayExpression = (node: ASTNode, context: Rule.RuleContext): boolean => {\n const services = typedServices(context)\n const tsNode = services?.esTreeNodeToTSNodeMap.get(node)\n if (!services || !tsNode) return false\n const checker = services.program.getTypeChecker()\n return isMutableArray(checker, checker.getNonNullableType(checker.getTypeAtLocation(tsNode)))\n}\n"],"mappings":"AAwBA,MAAMA,EAAiB,GAAyD,CAC9E,IAAMC,EAAWC,EAAQ,WAAW,eACpC,OAAOD,GAAU,SAAWA,EAAS,sBAAyBA,EAA6B,IAAA,EAC7F,EAOME,GAAkB,EAAsB,IAA4B,CACxE,GAAM,CAAE,QAAO,SAAQ,UAAWC,EAOlC,OAFIC,EAAcA,EAAM,OAAS,GAAKA,EAAM,MAAO,GAAWF,EAAeG,EAASC,CAAM,CAAC,EACzFD,EAAQ,YAAYF,CAAI,EAAUI,GAAQ,WAAa,GACpDC,GAAQ,OAAS,SAAWH,EAAQ,gBAAgBF,CAAI,CACjE,EAGaM,GAA4B,EAAe,IAAuC,CAC7F,IAAMT,EAAWD,EAAcE,CAAO,EAChCS,EAASV,GAAU,sBAAsB,IAAIW,CAAI,EACvD,GAAI,CAACX,GAAY,CAACU,EAAQ,MAAO,GACjC,IAAML,EAAUL,EAAS,QAAQ,eAAe,EAChD,OAAOE,EAAeG,EAASA,EAAQ,mBAAmBA,EAAQ,kBAAkBK,CAAM,CAAC,CAAC,CAC9F"}
|
|
1
|
+
{"version":3,"file":"array-mutation.js","names":["typedServices","services","context","isMutableArray","type","types","checker","member","target","symbol","isMutableArrayExpression","tsNode","node"],"sources":["../../src/utils/array-mutation.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Type checks for `no-array-mutation`, reached through `parserServices` and typed structurally so the\n * plugin takes no runtime dependency on `typescript`. Every check answers `false` without type\n * information: the rule reports nothing it can't prove is an array.\n */\n\ntype TypeLike = object\n\ntype CheckerLike = {\n getTypeAtLocation(node: unknown): TypeLike\n getNonNullableType(type: TypeLike): TypeLike\n isArrayLikeType(type: TypeLike): boolean\n isTupleType(type: TypeLike): boolean\n}\n\ntype TypedServices = {\n readonly program: { getTypeChecker(): CheckerLike }\n readonly esTreeNodeToTSNodeMap: { get(node: unknown): unknown }\n}\n\nconst typedServices = (context: Rule.RuleContext): TypedServices | undefined => {\n const services = context.sourceCode.parserServices as Partial<TypedServices> | undefined\n return services?.program && services.esTreeNodeToTSNodeMap ? (services as TypedServices) : undefined\n}\n\n/**\n * The mutable `Array` type, or a non-readonly tuple — `ReadonlyArray` has no `push`, so TypeScript\n * already rejects mutating one. Every member of a union must be one, so `string[] | Set<string>`\n * isn't reported on a `.push` the compiler resolves some other way.\n */\nconst isMutableArray = (checker: CheckerLike, type: TypeLike): boolean => {\n const { types, symbol, target } = type as {\n types?: ReadonlyArray<TypeLike>\n symbol?: { name?: string }\n target?: { readonly?: boolean }\n }\n if (types) return types.length > 0 && types.every((member) => isMutableArray(checker, member))\n if (checker.isTupleType(type)) return target?.readonly !== true\n return symbol?.name === \"Array\" && checker.isArrayLikeType(type)\n}\n\n/** Is `node` (an expression) typed as a mutable array? `false` without type information. */\nexport const isMutableArrayExpression = (node: ASTNode, context: Rule.RuleContext): boolean => {\n const services = typedServices(context)\n const tsNode = services?.esTreeNodeToTSNodeMap.get(node)\n if (!services || !tsNode) return false\n const checker = services.program.getTypeChecker()\n return isMutableArray(checker, checker.getNonNullableType(checker.getTypeAtLocation(tsNode)))\n}\n"],"mappings":"AAwBA,MAAMA,EAAiB,GAAyD,CAC9E,IAAMC,EAAWC,EAAQ,WAAW,eACpC,OAAOD,GAAU,SAAWA,EAAS,sBAAyBA,EAA6B,IAAA,EAC7F,EAOME,GAAkB,EAAsB,IAA4B,CACxE,GAAM,CAAE,QAAO,SAAQ,UAAWC,EAOlC,OAFIC,EAAcA,EAAM,OAAS,GAAKA,EAAM,MAAO,GAAWF,EAAeG,EAASC,CAAM,CAAC,EACzFD,EAAQ,YAAYF,CAAI,EAAUI,GAAQ,WAAa,GACpDC,GAAQ,OAAS,SAAWH,EAAQ,gBAAgBF,CAAI,CACjE,EAGaM,GAA4B,EAAe,IAAuC,CAC7F,IAAMT,EAAWD,EAAcE,CAAO,EAChCS,EAASV,GAAU,sBAAsB,IAAIW,CAAI,EACvD,GAAI,CAACX,GAAY,CAACU,EAAQ,MAAO,GACjC,IAAML,EAAUL,EAAS,QAAQ,eAAe,EAChD,OAAOE,EAAeG,EAASA,EAAQ,mBAAmBA,EAAQ,kBAAkBK,CAAM,CAAC,CAAC,CAC9F,E"}
|
package/dist/utils/ast-walk.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { ASTNode } from "../types/ast.js";
|
|
2
|
-
//#region src/utils/ast-walk.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* Generic ESTree child traversal for rules that need to look inside a subtree without a visitor.
|
|
5
4
|
* `parent` is skipped (it points up, not down); `loc`/`range`/tokens are plain data, not nodes.
|
|
@@ -7,6 +6,4 @@ import { ASTNode } from "../types/ast.js";
|
|
|
7
6
|
export declare const isNode: (value: unknown) => value is ASTNode;
|
|
8
7
|
export declare const childNodes: (node: ASTNode) => ReadonlyArray<ASTNode>;
|
|
9
8
|
/** Every node in the subtree rooted at `node`, root included. */
|
|
10
|
-
export declare const descendants: (node: ASTNode) => ReadonlyArray<ASTNode>;
|
|
11
|
-
//#endregion
|
|
12
|
-
//# sourceMappingURL=ast-walk.d.ts.map
|
|
9
|
+
export declare const descendants: (node: ASTNode) => ReadonlyArray<ASTNode>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ast-walk.js","names":["isNode","value","childNodes","node","key","descendants"],"sources":["../../src/utils/ast-walk.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\n\n/**\n * Generic ESTree child traversal for rules that need to look inside a subtree without a visitor.\n * `parent` is skipped (it points up, not down); `loc`/`range`/tokens are plain data, not nodes.\n */\n\nexport const isNode = (value: unknown): value is ASTNode =>\n typeof value === \"object\" && value !== null && typeof (value as { type?: unknown }).type === \"string\"\n\nexport const childNodes = (node: ASTNode): ReadonlyArray<ASTNode> =>\n Object.entries(node)\n .filter(([key]) => key !== \"parent\")\n .flatMap(([, value]) => (Array.isArray(value) ? value.filter(isNode) : isNode(value) ? [value] : []))\n\n/** Every node in the subtree rooted at `node`, root included. */\nexport const descendants = (node: ASTNode): ReadonlyArray<ASTNode> => [node, ...childNodes(node).flatMap(descendants)]\n"],"mappings":"AAOA,MAAaA,EAAU,GACrB,OAAOC,GAAU,YAAYA,GAAkB,OAAQA,EAA6B,MAAS,SAElFC,EAAc,GACzB,OAAO,QAAQC,CAAI,CAAC,CACjB,QAAQ,CAACC,KAASA,IAAQ,QAAQ,CAAC,CACnC,SAAS,EAAGH,KAAY,MAAM,QAAQA,CAAK,EAAIA,EAAM,OAAOD,CAAM,EAAIA,EAAOC,CAAK,EAAI,CAACA,CAAK,EAAI,CAAC,CAAE,EAG3FI,EAAe,GAA0C,CAACF,EAAM,GAAGD,EAAWC,CAAI,CAAC,CAAC,QAAQE,CAAW,CAAC"}
|
|
1
|
+
{"version":3,"file":"ast-walk.js","names":["isNode","value","childNodes","node","key","descendants"],"sources":["../../src/utils/ast-walk.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\n\n/**\n * Generic ESTree child traversal for rules that need to look inside a subtree without a visitor.\n * `parent` is skipped (it points up, not down); `loc`/`range`/tokens are plain data, not nodes.\n */\n\nexport const isNode = (value: unknown): value is ASTNode =>\n typeof value === \"object\" && value !== null && typeof (value as { type?: unknown }).type === \"string\"\n\nexport const childNodes = (node: ASTNode): ReadonlyArray<ASTNode> =>\n Object.entries(node)\n .filter(([key]) => key !== \"parent\")\n .flatMap(([, value]) => (Array.isArray(value) ? value.filter(isNode) : isNode(value) ? [value] : []))\n\n/** Every node in the subtree rooted at `node`, root included. */\nexport const descendants = (node: ASTNode): ReadonlyArray<ASTNode> => [node, ...childNodes(node).flatMap(descendants)]\n"],"mappings":"AAOA,MAAaA,EAAU,GACrB,OAAOC,GAAU,YAAYA,GAAkB,OAAQA,EAA6B,MAAS,SAElFC,EAAc,GACzB,OAAO,QAAQC,CAAI,CAAC,CACjB,QAAQ,CAACC,KAASA,IAAQ,QAAQ,CAAC,CACnC,SAAS,EAAGH,KAAY,MAAM,QAAQA,CAAK,EAAIA,EAAM,OAAOD,CAAM,EAAIA,EAAOC,CAAK,EAAI,CAACA,CAAK,EAAI,CAAC,CAAE,EAG3FI,EAAe,GAA0C,CAACF,EAAM,GAAGD,EAAWC,CAAI,CAAC,CAAC,QAAQE,CAAW,CAAC,E"}
|
|
@@ -1,6 +1,3 @@
|
|
|
1
1
|
import { ASTNode } from "../types/ast.js";
|
|
2
|
-
//#region src/utils/async-detection.d.ts
|
|
3
2
|
export declare const containsAwait: (node: ASTNode) => boolean;
|
|
4
|
-
export declare const containsYield: (node: ASTNode) => boolean;
|
|
5
|
-
//#endregion
|
|
6
|
-
//# sourceMappingURL=async-detection.d.ts.map
|
|
3
|
+
export declare const containsYield: (node: ASTNode) => boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-detection.js","names":["FUNCTION_BOUNDARIES","containsInOwnFlow","walk","isNode","n","matches","childNodes","node","containsAwait","containsYield"],"sources":["../../src/utils/async-detection.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\nimport { childNodes, isNode } from \"./ast-walk\"\n\n/**\n * Detects suspension points — `await` and `yield` — in a statement's own control flow.\n *\n * A suspension inside a nested function (arrow, expression, declaration, method) belongs to that\n * function, not to the enclosing loop or try block, so the walk stops at function boundaries. That\n * distinction is what makes the answer useful: `try { run(async () => { await x }) }` is a synchronous\n * try block, and `Try(() => ...)` is a correct replacement for it; `try { await x }` is not. Likewise a\n * loop body that yields cannot become a `.forEach` callback, but one that only defines a generator can.\n */\n\nconst FUNCTION_BOUNDARIES: ReadonlySet<string> = new Set([\n \"ArrowFunctionExpression\",\n \"FunctionExpression\",\n \"FunctionDeclaration\",\n])\n\nconst containsInOwnFlow =\n (matches: (node: ASTNode) => boolean) =>\n (node: ASTNode): boolean => {\n const walk = (n: ASTNode): boolean => {\n if (!isNode(n)) return false\n if (matches(n)) return true\n if (FUNCTION_BOUNDARIES.has(n.type)) return false\n return childNodes(n).some(walk)\n }\n return walk(node)\n }\n\nexport const containsAwait = containsInOwnFlow(\n (node) => node.type === \"AwaitExpression\" || (node.type === \"ForOfStatement\" && node.await === true),\n)\n\nexport const containsYield = containsInOwnFlow((node) => node.type === \"YieldExpression\")\n"],"mappings":"uDAaA,MAAMA,kBAA2C,IAAI,IAAI,CACvD,0BACA,qBACA,qBACF,CAAC,EAEKC,EACH,GACA,GAA2B,CAC1B,IAAMC,EAAQ,GACPC,EAAOC,CAAC,EACTC,EAAQD,CAAC,EAAU,GACvB,CAAIJ,EAAoB,IAAII,EAAE,IAAI,GAC3BE,EAAWF,CAAC,CAAC,CAAC,KAAKF,CAAI,EAHP,GAKzB,OAAOA,EAAKK,CAAI,CAClB,EAEWC,EAAgBP,EAC1B,GAASM,EAAK,OAAS,mBAAsBA,EAAK,OAAS,kBAAoBA,EAAK,QAAU,EACjG,EAEaE,EAAgBR,EAAmB,GAASM,EAAK,OAAS,iBAAiB"}
|
|
1
|
+
{"version":3,"file":"async-detection.js","names":["FUNCTION_BOUNDARIES","containsInOwnFlow","walk","isNode","n","matches","childNodes","node","containsAwait","containsYield"],"sources":["../../src/utils/async-detection.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\nimport { childNodes, isNode } from \"./ast-walk\"\n\n/**\n * Detects suspension points — `await` and `yield` — in a statement's own control flow.\n *\n * A suspension inside a nested function (arrow, expression, declaration, method) belongs to that\n * function, not to the enclosing loop or try block, so the walk stops at function boundaries. That\n * distinction is what makes the answer useful: `try { run(async () => { await x }) }` is a synchronous\n * try block, and `Try(() => ...)` is a correct replacement for it; `try { await x }` is not. Likewise a\n * loop body that yields cannot become a `.forEach` callback, but one that only defines a generator can.\n */\n\nconst FUNCTION_BOUNDARIES: ReadonlySet<string> = new Set([\n \"ArrowFunctionExpression\",\n \"FunctionExpression\",\n \"FunctionDeclaration\",\n])\n\nconst containsInOwnFlow =\n (matches: (node: ASTNode) => boolean) =>\n (node: ASTNode): boolean => {\n const walk = (n: ASTNode): boolean => {\n if (!isNode(n)) return false\n if (matches(n)) return true\n if (FUNCTION_BOUNDARIES.has(n.type)) return false\n return childNodes(n).some(walk)\n }\n return walk(node)\n }\n\nexport const containsAwait = containsInOwnFlow(\n (node) => node.type === \"AwaitExpression\" || (node.type === \"ForOfStatement\" && node.await === true),\n)\n\nexport const containsYield = containsInOwnFlow((node) => node.type === \"YieldExpression\")\n"],"mappings":"A,uDAaA,MAAMA,kBAA2C,IAAI,IAAI,CACvD,0BACA,qBACA,qBACF,CAAC,EAEKC,EACH,GACA,GAA2B,CAC1B,IAAMC,EAAQ,GACPC,EAAOC,CAAC,EACTC,EAAQD,CAAC,EAAU,GACvB,CAAIJ,EAAoB,IAAII,EAAE,IAAI,GAC3BE,EAAWF,CAAC,CAAC,CAAC,KAAKF,CAAI,EAHP,GAKzB,OAAOA,EAAKK,CAAI,CAClB,EAEWC,EAAgBP,EAC1B,GAASM,EAAK,OAAS,mBAAsBA,EAAK,OAAS,kBAAoBA,EAAK,QAAU,EACjG,EAEaE,EAAgBR,EAAmB,GAASM,EAAK,OAAS,iBAAiB,E"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { ASTNode } from "../types/ast.js";
|
|
2
2
|
import { SourceCode } from "eslint";
|
|
3
|
-
//#region src/utils/boundary-tags.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* Structural exemptions recorded in JSDoc, instead of `eslint-disable` (#241).
|
|
6
5
|
*
|
|
@@ -21,6 +20,4 @@ export declare const INTEROP_TAG = "interop";
|
|
|
21
20
|
* Is `node` inside a declaration whose JSDoc carries `@<tag> <reason>`? Every enclosing documentable
|
|
22
21
|
* declaration is checked, so a tag on a function covers the callbacks nested inside it.
|
|
23
22
|
*/
|
|
24
|
-
export declare const isInsideTaggedDeclaration: (node: ASTNode, tag: string, sourceCode: SourceCode) => boolean;
|
|
25
|
-
//#endregion
|
|
26
|
-
//# sourceMappingURL=boundary-tags.d.ts.map
|
|
23
|
+
export declare const isInsideTaggedDeclaration: (node: ASTNode, tag: string, sourceCode: SourceCode) => boolean;
|