eslint-plugin-functype 2.121.0 → 2.121.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/list-rules.js.map +1 -1
- package/dist/configs/recommended.d.ts +2 -0
- package/dist/configs/recommended.js.map +1 -1
- package/dist/configs/strict.d.ts +2 -0
- package/dist/configs/strict.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js.map +1 -1
- package/dist/rules/collection-naming.d.ts +2 -0
- package/dist/rules/collection-naming.js.map +1 -1
- package/dist/rules/index.d.ts +2 -0
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/must-fold-on-component-return.d.ts +2 -0
- package/dist/rules/must-fold-on-component-return.js.map +1 -1
- package/dist/rules/no-array-mutation.d.ts +2 -0
- package/dist/rules/no-array-mutation.js.map +1 -1
- package/dist/rules/no-floating-io.d.ts +2 -0
- package/dist/rules/no-floating-io.js.map +1 -1
- package/dist/rules/no-get-unsafe.d.ts +2 -0
- package/dist/rules/no-get-unsafe.js.map +1 -1
- package/dist/rules/no-getOrThrow-in-render.d.ts +2 -0
- package/dist/rules/no-getOrThrow-in-render.js.map +1 -1
- package/dist/rules/no-imperative-loops.d.ts +2 -0
- 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 +2 -0
- package/dist/rules/no-let.js.map +1 -1
- package/dist/rules/prefer-do-notation.d.ts +2 -0
- package/dist/rules/prefer-do-notation.js.map +1 -1
- package/dist/rules/prefer-either.d.ts +2 -0
- package/dist/rules/prefer-either.js.map +1 -1
- package/dist/rules/prefer-flatmap.d.ts +2 -0
- package/dist/rules/prefer-flatmap.js +1 -1
- package/dist/rules/prefer-flatmap.js.map +1 -1
- package/dist/rules/prefer-fold.d.ts +2 -0
- package/dist/rules/prefer-fold.js.map +1 -1
- package/dist/rules/prefer-functype-map.d.ts +2 -0
- package/dist/rules/prefer-functype-map.js.map +1 -1
- package/dist/rules/prefer-functype-set.d.ts +2 -0
- package/dist/rules/prefer-functype-set.js.map +1 -1
- package/dist/rules/prefer-list.d.ts +2 -0
- package/dist/rules/prefer-list.js +1 -1
- package/dist/rules/prefer-list.js.map +1 -1
- package/dist/rules/prefer-map.d.ts +2 -0
- package/dist/rules/prefer-map.js.map +1 -1
- package/dist/rules/prefer-option.d.ts +2 -0
- package/dist/rules/prefer-option.js.map +1 -1
- package/dist/rules/prefer-try.d.ts +2 -0
- package/dist/rules/prefer-try.js.map +1 -1
- package/dist/types/ast.d.ts +2 -0
- package/dist/utils/array-mutation.d.ts +2 -0
- package/dist/utils/array-mutation.js.map +1 -1
- package/dist/utils/ast-walk.d.ts +2 -0
- package/dist/utils/ast-walk.js.map +1 -1
- package/dist/utils/async-detection.d.ts +2 -0
- package/dist/utils/async-detection.js.map +1 -1
- package/dist/utils/boundary-tags.d.ts +2 -0
- package/dist/utils/boundary-tags.js.map +1 -1
- package/dist/utils/collection-binding.d.ts +2 -0
- package/dist/utils/collection-binding.js.map +1 -1
- package/dist/utils/dependency-validator.d.ts +2 -1
- package/dist/utils/dependency-validator.js.map +1 -1
- package/dist/utils/functype-detection.d.ts +2 -0
- package/dist/utils/functype-detection.js.map +1 -1
- package/dist/utils/functype-predicates.d.ts +2 -0
- package/dist/utils/functype-predicates.js.map +1 -1
- package/dist/utils/import-fixer.d.ts +2 -0
- package/dist/utils/import-fixer.js.map +1 -1
- package/dist/utils/mutable-collection.d.ts +2 -0
- package/dist/utils/mutable-collection.js.map +1 -1
- package/dist/utils/react-render.d.ts +2 -0
- package/dist/utils/react-render.js.map +1 -1
- package/dist/utils/readonly-contract.d.ts +2 -0
- package/dist/utils/readonly-contract.js.map +1 -1
- package/dist/utils/type-aware.d.ts +2 -0
- package/dist/utils/type-aware.js.map +1 -1
- package/dist/utils/wire-types.d.ts +2 -0
- package/dist/utils/wire-types.js.map +1 -1
- package/package.json +6 -6
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { ASTNode } from "../types/ast.js";
|
|
2
|
+
//#region src/utils/async-detection.d.ts
|
|
2
3
|
export declare const containsAwait: (node: ASTNode) => boolean;
|
|
3
4
|
export declare const containsYield: (node: ASTNode) => boolean;
|
|
5
|
+
//#endregion
|
|
4
6
|
//# sourceMappingURL=async-detection.d.ts.map
|
|
@@ -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":"
|
|
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,5 +1,6 @@
|
|
|
1
1
|
import { ASTNode } from "../types/ast.js";
|
|
2
2
|
import { SourceCode } from "eslint";
|
|
3
|
+
//#region src/utils/boundary-tags.d.ts
|
|
3
4
|
/**
|
|
4
5
|
* Structural exemptions recorded in JSDoc, instead of `eslint-disable` (#241).
|
|
5
6
|
*
|
|
@@ -21,4 +22,5 @@ export declare const INTEROP_TAG = "interop";
|
|
|
21
22
|
* declaration is checked, so a tag on a function covers the callbacks nested inside it.
|
|
22
23
|
*/
|
|
23
24
|
export declare const isInsideTaggedDeclaration: (node: ASTNode, tag: string, sourceCode: SourceCode) => boolean;
|
|
25
|
+
//#endregion
|
|
24
26
|
//# sourceMappingURL=boundary-tags.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"boundary-tags.js","names":["INTEROP_TAG","DOCUMENTABLE","EXPORT_WRAPPERS","leadingJSDoc","anchor","node","comments","sourceCode","last","hasTagWithReason","tag","jsdoc","isInsideTaggedDeclaration","check","current"],"sources":["../../src/utils/boundary-tags.ts"],"sourcesContent":["import type { SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Structural exemptions recorded in JSDoc, instead of `eslint-disable` (#241).\n *\n * `@interop <reason>` — the enclosing declaration bridges functype to a host whose contract is the\n * non-FP shape: React's `use()` needs a throw, React Query needs a rejected promise, a hook that converts\n * nullables into `Option` must accept nullables.\n *\n * Bug checks are not tagged: they are `invariant(cond, msg)` calls from functype, which narrow types and\n * cover one statement. (An `@invariant` tag shipped in 1.10.0 and was removed in #342 — it exempted a\n * whole function, including any expected-failure throw added to it later.)\n *\n * Why a tag rather than a disable comment: it covers one declaration (and what is nested inside it), not\n * a whole file; it must carry a reason on the same line, so a bare tag exempts nothing; and it is\n * greppable — `rg '@interop'` is the inventory of every place the code touches a throw-based host.\n */\n\nexport const INTEROP_TAG = \"interop\"\n\n/** Declarations whose leading JSDoc can carry a tag. */\nconst DOCUMENTABLE: ReadonlySet<string> = new Set([\n \"FunctionDeclaration\",\n \"VariableDeclaration\",\n \"MethodDefinition\",\n \"PropertyDefinition\",\n \"Property\",\n \"TSTypeAliasDeclaration\",\n \"TSInterfaceDeclaration\",\n \"TSPropertySignature\",\n \"TSMethodSignature\",\n])\n\nconst EXPORT_WRAPPERS: ReadonlySet<string> = new Set([\"ExportNamedDeclaration\", \"ExportDefaultDeclaration\"])\n\n/** The JSDoc block (`/** … *\\/`) directly before `node`, or before its `export` wrapper. */\nconst leadingJSDoc = (node: ASTNode, sourceCode: SourceCode): string | null => {\n const anchor = node.parent && EXPORT_WRAPPERS.has(node.parent.type) ? node.parent : node\n const comments = sourceCode.getCommentsBefore(anchor)\n const last = comments[comments.length - 1]\n return last?.type === \"Block\" && last.value.startsWith(\"*\") ? last.value : null\n}\n\n/** `@tag` followed by a reason on the same line. A bare tag carries no reason and exempts nothing. */\nconst hasTagWithReason = (jsdoc: string, tag: string): boolean =>\n new RegExp(`(^|[\\\\s*])@${tag}[ \\\\t]+\\\\S`, \"m\").test(jsdoc)\n\n/**\n * Is `node` inside a declaration whose JSDoc carries `@<tag> <reason>`? Every enclosing documentable\n * declaration is checked, so a tag on a function covers the callbacks nested inside it.\n */\nexport const isInsideTaggedDeclaration = (node: ASTNode, tag: string, sourceCode: SourceCode): boolean => {\n const check = (current: ASTNode | null | undefined): boolean => {\n if (!current) return false\n if (DOCUMENTABLE.has(current.type)) {\n const jsdoc = leadingJSDoc(current, sourceCode)\n if (jsdoc !== null && hasTagWithReason(jsdoc, tag)) return true\n }\n return check(current.parent)\n }\n return check(node)\n}\n"],"mappings":"AAoBA,MAAaA,EAAc,UAGrBC,kBAAoC,IAAI,IAAI,CAChD,sBACA,sBACA,mBACA,qBACA,WACA,yBACA,yBACA,sBACA,mBACF,CAAC,EAEKC,kBAAuC,IAAI,IAAI,CAAC,yBAA0B,0BAA0B,CAAC,EAGrGC,GAAgB,EAAe,IAA0C,CAC7E,IAAMC,EAASC,EAAK,QAAUH,EAAgB,IAAIG,EAAK,OAAO,IAAI,EAAIA,EAAK,OAASA,EAC9EC,EAAWC,EAAW,kBAAkBH,CAAM,EAC9CI,EAAOF,EAASA,EAAS,OAAS,GACxC,OAAOE,GAAM,OAAS,SAAWA,EAAK,MAAM,WAAW,GAAG,EAAIA,EAAK,MAAQ,IAC7E,EAGMC,GAAoB,EAAe,IACnC,OAAO,cAAcC,EAAI,YAAa,GAAG,CAAC,CAAC,KAAKC,CAAK,EAM9CC,GAA6B,EAAe,EAAa,IAAoC,CACxG,IAAMC,EAAS,GAAiD,CAC9D,GAAI,CAACC,EAAS,MAAO,GACrB,GAAIb,EAAa,IAAIa,EAAQ,IAAI,EAAG,CAClC,IAAMH,EAAQR,EAAaW,EAASP,CAAU,EAC9C,GAAII,IAAU,MAAQF,EAAiBE,EAAOD,CAAG,EAAG,MAAO,EAC7D,CACA,OAAOG,EAAMC,EAAQ,MAAM,CAC7B,EACA,OAAOD,EAAMR,CAAI,CACnB
|
|
1
|
+
{"version":3,"file":"boundary-tags.js","names":["INTEROP_TAG","DOCUMENTABLE","EXPORT_WRAPPERS","leadingJSDoc","anchor","node","comments","sourceCode","last","hasTagWithReason","tag","jsdoc","isInsideTaggedDeclaration","check","current"],"sources":["../../src/utils/boundary-tags.ts"],"sourcesContent":["import type { SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Structural exemptions recorded in JSDoc, instead of `eslint-disable` (#241).\n *\n * `@interop <reason>` — the enclosing declaration bridges functype to a host whose contract is the\n * non-FP shape: React's `use()` needs a throw, React Query needs a rejected promise, a hook that converts\n * nullables into `Option` must accept nullables.\n *\n * Bug checks are not tagged: they are `invariant(cond, msg)` calls from functype, which narrow types and\n * cover one statement. (An `@invariant` tag shipped in 1.10.0 and was removed in #342 — it exempted a\n * whole function, including any expected-failure throw added to it later.)\n *\n * Why a tag rather than a disable comment: it covers one declaration (and what is nested inside it), not\n * a whole file; it must carry a reason on the same line, so a bare tag exempts nothing; and it is\n * greppable — `rg '@interop'` is the inventory of every place the code touches a throw-based host.\n */\n\nexport const INTEROP_TAG = \"interop\"\n\n/** Declarations whose leading JSDoc can carry a tag. */\nconst DOCUMENTABLE: ReadonlySet<string> = new Set([\n \"FunctionDeclaration\",\n \"VariableDeclaration\",\n \"MethodDefinition\",\n \"PropertyDefinition\",\n \"Property\",\n \"TSTypeAliasDeclaration\",\n \"TSInterfaceDeclaration\",\n \"TSPropertySignature\",\n \"TSMethodSignature\",\n])\n\nconst EXPORT_WRAPPERS: ReadonlySet<string> = new Set([\"ExportNamedDeclaration\", \"ExportDefaultDeclaration\"])\n\n/** The JSDoc block (`/** … *\\/`) directly before `node`, or before its `export` wrapper. */\nconst leadingJSDoc = (node: ASTNode, sourceCode: SourceCode): string | null => {\n const anchor = node.parent && EXPORT_WRAPPERS.has(node.parent.type) ? node.parent : node\n const comments = sourceCode.getCommentsBefore(anchor)\n const last = comments[comments.length - 1]\n return last?.type === \"Block\" && last.value.startsWith(\"*\") ? last.value : null\n}\n\n/** `@tag` followed by a reason on the same line. A bare tag carries no reason and exempts nothing. */\nconst hasTagWithReason = (jsdoc: string, tag: string): boolean =>\n new RegExp(`(^|[\\\\s*])@${tag}[ \\\\t]+\\\\S`, \"m\").test(jsdoc)\n\n/**\n * Is `node` inside a declaration whose JSDoc carries `@<tag> <reason>`? Every enclosing documentable\n * declaration is checked, so a tag on a function covers the callbacks nested inside it.\n */\nexport const isInsideTaggedDeclaration = (node: ASTNode, tag: string, sourceCode: SourceCode): boolean => {\n const check = (current: ASTNode | null | undefined): boolean => {\n if (!current) return false\n if (DOCUMENTABLE.has(current.type)) {\n const jsdoc = leadingJSDoc(current, sourceCode)\n if (jsdoc !== null && hasTagWithReason(jsdoc, tag)) return true\n }\n return check(current.parent)\n }\n return check(node)\n}\n"],"mappings":"AAoBA,MAAaA,EAAc,UAGrBC,kBAAoC,IAAI,IAAI,CAChD,sBACA,sBACA,mBACA,qBACA,WACA,yBACA,yBACA,sBACA,mBACF,CAAC,EAEKC,kBAAuC,IAAI,IAAI,CAAC,yBAA0B,0BAA0B,CAAC,EAGrGC,GAAgB,EAAe,IAA0C,CAC7E,IAAMC,EAASC,EAAK,QAAUH,EAAgB,IAAIG,EAAK,OAAO,IAAI,EAAIA,EAAK,OAASA,EAC9EC,EAAWC,EAAW,kBAAkBH,CAAM,EAC9CI,EAAOF,EAASA,EAAS,OAAS,GACxC,OAAOE,GAAM,OAAS,SAAWA,EAAK,MAAM,WAAW,GAAG,EAAIA,EAAK,MAAQ,IAC7E,EAGMC,GAAoB,EAAe,IACnC,OAAO,cAAcC,EAAI,YAAa,GAAG,CAAC,CAAC,KAAKC,CAAK,EAM9CC,GAA6B,EAAe,EAAa,IAAoC,CACxG,IAAMC,EAAS,GAAiD,CAC9D,GAAI,CAACC,EAAS,MAAO,GACrB,GAAIb,EAAa,IAAIa,EAAQ,IAAI,EAAG,CAClC,IAAMH,EAAQR,EAAaW,EAASP,CAAU,EAC9C,GAAII,IAAU,MAAQF,EAAiBE,EAAOD,CAAG,EAAG,MAAO,EAC7D,CACA,OAAOG,EAAMC,EAAQ,MAAM,CAC7B,EACA,OAAOD,EAAMR,CAAI,CACnB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ASTNode } from "../types/ast.js";
|
|
2
2
|
import { SourceCode } from "eslint";
|
|
3
|
+
//#region src/utils/collection-binding.d.ts
|
|
3
4
|
/**
|
|
4
5
|
* What `Map` / `Set` means at a use site (#350). Deciding from the file's import list was wrong both ways:
|
|
5
6
|
* `import { Map as FMap } from "functype"` silenced the whole file even though the bare `Map` there is still
|
|
@@ -30,4 +31,5 @@ export declare const functypeCollectionAt: (expr: ASTNode, sourceCode: SourceCod
|
|
|
30
31
|
* functype's `ESMap` re-export of the native Map? Bare `Map` is handled by {@link bindingOf}.
|
|
31
32
|
*/
|
|
32
33
|
export declare const isExplicitNativeCollection: (callee: ASTNode, name: string, sourceCode: SourceCode) => boolean;
|
|
34
|
+
//#endregion
|
|
33
35
|
//# sourceMappingURL=collection-binding.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collection-binding.js","names":["isFunctypeSource","value","resolve","lookup","scope","name","sourceCode","node","bindingOf","variable","def","functypeLocalName","n","decl","spec","COLLECTION_NAMES","functypeCollectionAt","expr","isExplicitNativeCollection","callee"],"sources":["../../src/utils/collection-binding.ts"],"sourcesContent":["import type { Scope, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * What `Map` / `Set` means at a use site (#350). Deciding from the file's import list was wrong both ways:\n * `import { Map as FMap } from \"functype\"` silenced the whole file even though the bare `Map` there is still\n * the native one. Resolving the identifier through scope asks the question that matters.\n *\n * - `functype` — it is functype's import (under any local name), so there is nothing to report;\n * - `shadowed` — a local declaration or a non-functype import, so it isn't the native collection;\n * - `native` — unresolved, or a global / lib binding with no declaration: the built-in.\n */\nexport type CollectionBinding = \"native\" | \"functype\" | \"shadowed\"\n\nconst isFunctypeSource = (value: unknown): boolean =>\n typeof value === \"string\" && (value === \"functype\" || value.startsWith(\"functype/\"))\n\nconst resolve = (node: ASTNode, name: string, sourceCode: SourceCode): Scope.Variable | null => {\n const lookup = (scope: Scope.Scope | null): Scope.Variable | null =>\n scope === null ? null : (scope.set.get(name) ?? lookup(scope.upper))\n return lookup(sourceCode.getScope(node))\n}\n\nexport const bindingOf = (node: ASTNode, name: string, sourceCode: SourceCode): CollectionBinding => {\n const variable = resolve(node, name, sourceCode)\n if (variable === null || variable.defs.length === 0) return \"native\"\n const def = variable.defs[0] as unknown as { readonly type: string; readonly parent?: ASTNode }\n if (def.type === \"ImportBinding\") return isFunctypeSource(def.parent?.source?.value) ? \"functype\" : \"shadowed\"\n return \"shadowed\"\n}\n\n/**\n * The name this file already uses for functype's `name`: `\"FMap\"` for `import { Map as FMap }`,\n * `\"F.Map\"` for `import * as F`, or null when it isn't imported (so the fix must add the import).\n */\nexport const functypeLocalName = (sourceCode: SourceCode, name: string): string | null => {\n const names = (sourceCode.ast.body as ReadonlyArray<ASTNode>)\n .filter((n) => n.type === \"ImportDeclaration\" && isFunctypeSource(n.source?.value))\n .flatMap((decl) => (decl.specifiers ?? []) as ReadonlyArray<ASTNode>)\n .flatMap((spec): ReadonlyArray<string> => {\n if (spec.type === \"ImportSpecifier\" && spec.imported?.type === \"Identifier\" && spec.imported.name === name) {\n return [spec.local.name]\n }\n if (spec.type === \"ImportNamespaceSpecifier\") return [`${spec.local.name}.${name}`]\n return []\n })\n return names[0] ?? null\n}\n\nexport const COLLECTION_NAMES: ReadonlyArray<string> = [\"Map\", \"Set\"]\n\n/**\n * If `expr` names functype's `Map` / `Set` — an identifier bound to its import (any local name), or a\n * namespace member like `F.Map` — returns the imported name and how this file spells it; else null.\n */\nexport const functypeCollectionAt = (\n expr: ASTNode,\n sourceCode: SourceCode,\n): { readonly name: string; readonly local: string } | null => {\n if (expr?.type === \"Identifier\") {\n const def = resolve(expr, expr.name, sourceCode)?.defs[0] as\n { readonly type: string; readonly node?: ASTNode; readonly parent?: ASTNode } | undefined\n if (def?.type !== \"ImportBinding\" || !isFunctypeSource(def.parent?.source?.value)) return null\n const spec = def.node\n if (spec?.type !== \"ImportSpecifier\" || spec.imported?.type !== \"Identifier\") return null\n return COLLECTION_NAMES.includes(spec.imported.name) ? { name: spec.imported.name, local: expr.name } : null\n }\n if (\n expr?.type === \"MemberExpression\" &&\n !expr.computed &&\n expr.object.type === \"Identifier\" &&\n expr.property.type === \"Identifier\" &&\n COLLECTION_NAMES.includes(expr.property.name)\n ) {\n const def = resolve(expr.object, expr.object.name, sourceCode)?.defs[0] as\n { readonly type: string; readonly node?: ASTNode; readonly parent?: ASTNode } | undefined\n const isNamespace =\n def?.type === \"ImportBinding\" &&\n def.node?.type === \"ImportNamespaceSpecifier\" &&\n isFunctypeSource(def.parent?.source?.value)\n return isNamespace ? { name: expr.property.name, local: `${expr.object.name}.${expr.property.name}` } : null\n }\n return null\n}\n\n/**\n * Is `callee` the built-in constructor spelled explicitly — `globalThis.Map` / `globalThis.Set`, or\n * functype's `ESMap` re-export of the native Map? Bare `Map` is handled by {@link bindingOf}.\n */\nexport const isExplicitNativeCollection = (callee: ASTNode, name: string, sourceCode: SourceCode): boolean => {\n if (\n callee?.type === \"MemberExpression\" &&\n !callee.computed &&\n callee.object.type === \"Identifier\" &&\n callee.object.name === \"globalThis\" &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === name\n ) {\n // A local binding named `globalThis` would shadow the real one.\n return resolve(callee.object, \"globalThis\", sourceCode)?.defs.length ? false : true\n }\n if (callee?.type === \"Identifier\" && name === \"Map\") {\n const def = resolve(callee, callee.name, sourceCode)?.defs[0] as\n { readonly type: string; readonly node?: ASTNode; readonly parent?: ASTNode } | undefined\n return (\n def?.type === \"ImportBinding\" &&\n isFunctypeSource(def.parent?.source?.value) &&\n def.node?.type === \"ImportSpecifier\" &&\n def.node.imported?.name === \"ESMap\"\n )\n }\n return false\n}\n"],"mappings":"AAeA,MAAMA,EAAoB,GACxB,OAAOC,GAAU,WAAaA,IAAU,YAAcA,EAAM,WAAW,WAAW,GAE9EC,GAAW,EAAe,EAAc,IAAkD,CAC9F,IAAMC,EAAU,GACdC,IAAU,KAAO,KAAQA,EAAM,IAAI,IAAIC,CAAI,GAAKF,EAAOC,EAAM,KAAK,EACpE,OAAOD,EAAOG,EAAW,SAASC,CAAI,CAAC,CACzC,EAEaC,GAAa,EAAe,EAAc,IAA8C,CACnG,IAAMC,EAAWP,EAAQK,EAAMF,EAAMC,CAAU,EAC/C,GAAIG,IAAa,MAAQA,EAAS,KAAK,SAAW,EAAG,MAAO,SAC5D,IAAMC,EAAMD,EAAS,KAAK,GAE1B,OADIC,EAAI,OAAS,iBAAwBV,EAAiBU,EAAI,QAAQ,QAAQ,KAAK,EAAI,
|
|
1
|
+
{"version":3,"file":"collection-binding.js","names":["isFunctypeSource","value","resolve","lookup","scope","name","sourceCode","node","bindingOf","variable","def","functypeLocalName","n","decl","spec","COLLECTION_NAMES","functypeCollectionAt","expr","isExplicitNativeCollection","callee"],"sources":["../../src/utils/collection-binding.ts"],"sourcesContent":["import type { Scope, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * What `Map` / `Set` means at a use site (#350). Deciding from the file's import list was wrong both ways:\n * `import { Map as FMap } from \"functype\"` silenced the whole file even though the bare `Map` there is still\n * the native one. Resolving the identifier through scope asks the question that matters.\n *\n * - `functype` — it is functype's import (under any local name), so there is nothing to report;\n * - `shadowed` — a local declaration or a non-functype import, so it isn't the native collection;\n * - `native` — unresolved, or a global / lib binding with no declaration: the built-in.\n */\nexport type CollectionBinding = \"native\" | \"functype\" | \"shadowed\"\n\nconst isFunctypeSource = (value: unknown): boolean =>\n typeof value === \"string\" && (value === \"functype\" || value.startsWith(\"functype/\"))\n\nconst resolve = (node: ASTNode, name: string, sourceCode: SourceCode): Scope.Variable | null => {\n const lookup = (scope: Scope.Scope | null): Scope.Variable | null =>\n scope === null ? null : (scope.set.get(name) ?? lookup(scope.upper))\n return lookup(sourceCode.getScope(node))\n}\n\nexport const bindingOf = (node: ASTNode, name: string, sourceCode: SourceCode): CollectionBinding => {\n const variable = resolve(node, name, sourceCode)\n if (variable === null || variable.defs.length === 0) return \"native\"\n const def = variable.defs[0] as unknown as { readonly type: string; readonly parent?: ASTNode }\n if (def.type === \"ImportBinding\") return isFunctypeSource(def.parent?.source?.value) ? \"functype\" : \"shadowed\"\n return \"shadowed\"\n}\n\n/**\n * The name this file already uses for functype's `name`: `\"FMap\"` for `import { Map as FMap }`,\n * `\"F.Map\"` for `import * as F`, or null when it isn't imported (so the fix must add the import).\n */\nexport const functypeLocalName = (sourceCode: SourceCode, name: string): string | null => {\n const names = (sourceCode.ast.body as ReadonlyArray<ASTNode>)\n .filter((n) => n.type === \"ImportDeclaration\" && isFunctypeSource(n.source?.value))\n .flatMap((decl) => (decl.specifiers ?? []) as ReadonlyArray<ASTNode>)\n .flatMap((spec): ReadonlyArray<string> => {\n if (spec.type === \"ImportSpecifier\" && spec.imported?.type === \"Identifier\" && spec.imported.name === name) {\n return [spec.local.name]\n }\n if (spec.type === \"ImportNamespaceSpecifier\") return [`${spec.local.name}.${name}`]\n return []\n })\n return names[0] ?? null\n}\n\nexport const COLLECTION_NAMES: ReadonlyArray<string> = [\"Map\", \"Set\"]\n\n/**\n * If `expr` names functype's `Map` / `Set` — an identifier bound to its import (any local name), or a\n * namespace member like `F.Map` — returns the imported name and how this file spells it; else null.\n */\nexport const functypeCollectionAt = (\n expr: ASTNode,\n sourceCode: SourceCode,\n): { readonly name: string; readonly local: string } | null => {\n if (expr?.type === \"Identifier\") {\n const def = resolve(expr, expr.name, sourceCode)?.defs[0] as\n { readonly type: string; readonly node?: ASTNode; readonly parent?: ASTNode } | undefined\n if (def?.type !== \"ImportBinding\" || !isFunctypeSource(def.parent?.source?.value)) return null\n const spec = def.node\n if (spec?.type !== \"ImportSpecifier\" || spec.imported?.type !== \"Identifier\") return null\n return COLLECTION_NAMES.includes(spec.imported.name) ? { name: spec.imported.name, local: expr.name } : null\n }\n if (\n expr?.type === \"MemberExpression\" &&\n !expr.computed &&\n expr.object.type === \"Identifier\" &&\n expr.property.type === \"Identifier\" &&\n COLLECTION_NAMES.includes(expr.property.name)\n ) {\n const def = resolve(expr.object, expr.object.name, sourceCode)?.defs[0] as\n { readonly type: string; readonly node?: ASTNode; readonly parent?: ASTNode } | undefined\n const isNamespace =\n def?.type === \"ImportBinding\" &&\n def.node?.type === \"ImportNamespaceSpecifier\" &&\n isFunctypeSource(def.parent?.source?.value)\n return isNamespace ? { name: expr.property.name, local: `${expr.object.name}.${expr.property.name}` } : null\n }\n return null\n}\n\n/**\n * Is `callee` the built-in constructor spelled explicitly — `globalThis.Map` / `globalThis.Set`, or\n * functype's `ESMap` re-export of the native Map? Bare `Map` is handled by {@link bindingOf}.\n */\nexport const isExplicitNativeCollection = (callee: ASTNode, name: string, sourceCode: SourceCode): boolean => {\n if (\n callee?.type === \"MemberExpression\" &&\n !callee.computed &&\n callee.object.type === \"Identifier\" &&\n callee.object.name === \"globalThis\" &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === name\n ) {\n // A local binding named `globalThis` would shadow the real one.\n return resolve(callee.object, \"globalThis\", sourceCode)?.defs.length ? false : true\n }\n if (callee?.type === \"Identifier\" && name === \"Map\") {\n const def = resolve(callee, callee.name, sourceCode)?.defs[0] as\n { readonly type: string; readonly node?: ASTNode; readonly parent?: ASTNode } | undefined\n return (\n def?.type === \"ImportBinding\" &&\n isFunctypeSource(def.parent?.source?.value) &&\n def.node?.type === \"ImportSpecifier\" &&\n def.node.imported?.name === \"ESMap\"\n )\n }\n return false\n}\n"],"mappings":"AAeA,MAAMA,EAAoB,GACxB,OAAOC,GAAU,WAAaA,IAAU,YAAcA,EAAM,WAAW,WAAW,GAE9EC,GAAW,EAAe,EAAc,IAAkD,CAC9F,IAAMC,EAAU,GACdC,IAAU,KAAO,KAAQA,EAAM,IAAI,IAAIC,CAAI,GAAKF,EAAOC,EAAM,KAAK,EACpE,OAAOD,EAAOG,EAAW,SAASC,CAAI,CAAC,CACzC,EAEaC,GAAa,EAAe,EAAc,IAA8C,CACnG,IAAMC,EAAWP,EAAQK,EAAMF,EAAMC,CAAU,EAC/C,GAAIG,IAAa,MAAQA,EAAS,KAAK,SAAW,EAAG,MAAO,SAC5D,IAAMC,EAAMD,EAAS,KAAK,GAE1B,OADIC,EAAI,OAAS,iBAAwBV,EAAiBU,EAAI,QAAQ,QAAQ,KAAK,EAAI,WAAa,UAEtG,EAMaC,GAAqB,EAAwB,IACzCL,EAAW,IAAI,KAC3B,OAAQ,GAAMM,EAAE,OAAS,qBAAuBZ,EAAiBY,EAAE,QAAQ,KAAK,CAAC,CAAC,CAClF,QAAS,GAAUC,EAAK,YAAc,CAAC,CAA4B,CAAC,CACpE,QAAS,GACJC,EAAK,OAAS,mBAAqBA,EAAK,UAAU,OAAS,cAAgBA,EAAK,SAAS,OAAST,EAC7F,CAACS,EAAK,MAAM,IAAI,EAErBA,EAAK,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GAAIa,GAAQ,OAAS,cAAgBd,IAAS,MAAO,CACnD,IAAMK,EAAMR,EAAQiB,EAAQA,EAAO,KAAMb,CAAU,CAAC,EAAE,KAAK,GAE3D,OACEI,GAAK,OAAS,iBACdV,EAAiBU,EAAI,QAAQ,QAAQ,KAAK,GAC1CA,EAAI,MAAM,OAAS,mBACnBA,EAAI,KAAK,UAAU,OAAS,OAEhC,CACA,MAAO,EACT"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
//#region src/utils/dependency-validator.d.ts
|
|
1
2
|
interface PeerDependency {
|
|
2
3
|
name: string;
|
|
3
4
|
packageName: string;
|
|
@@ -14,5 +15,5 @@ export interface ValidationResult {
|
|
|
14
15
|
export declare function validatePeerDependencies(): ValidationResult;
|
|
15
16
|
export declare function createValidationError(result: ValidationResult): Error;
|
|
16
17
|
export declare function shouldValidateDependencies(): boolean;
|
|
17
|
-
|
|
18
|
+
//#endregion
|
|
18
19
|
//# sourceMappingURL=dependency-validator.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dependency-validator.js","names":["__require","PEER_DEPENDENCIES","tryRequire","packageName","validatePeerDependencies","available","missing","ok","bad","dep","warnings","requiredMissing","installCommand","createValidationError","result","message","shouldValidateDependencies"],"sources":["../../src/utils/dependency-validator.ts"],"sourcesContent":["// Utility to validate peer dependencies and provide helpful error messages\n\ninterface PeerDependency {\n name: string\n packageName: string\n description: string\n required: boolean\n}\n\nconst PEER_DEPENDENCIES: PeerDependency[] = [\n {\n name: \"@typescript-eslint/eslint-plugin\",\n packageName: \"@typescript-eslint/eslint-plugin\",\n description: \"TypeScript-aware ESLint rules\",\n required: true,\n },\n {\n name: \"@typescript-eslint/parser\",\n packageName: \"@typescript-eslint/parser\",\n description: \"TypeScript parser for ESLint\",\n required: true,\n },\n {\n name: \"eslint-plugin-functional\",\n packageName: \"eslint-plugin-functional\",\n description: \"Functional programming ESLint rules\",\n required: true,\n },\n {\n name: \"eslint-plugin-prettier\",\n packageName: \"eslint-plugin-prettier\",\n description: \"Code formatting rules\",\n required: false,\n },\n {\n name: \"eslint-plugin-simple-import-sort\",\n packageName: \"eslint-plugin-simple-import-sort\",\n description: \"Import sorting rules\",\n required: false,\n },\n {\n name: \"prettier\",\n packageName: \"prettier\",\n description: \"Code formatter\",\n required: false,\n },\n]\n\nexport interface ValidationResult {\n isValid: boolean\n missing: PeerDependency[]\n available: PeerDependency[]\n installCommand: string\n warnings: string[]\n}\n\nfunction tryRequire(packageName: string): boolean {\n try {\n require.resolve(packageName)\n return true\n } catch {\n return false\n }\n}\n\nexport function validatePeerDependencies(): ValidationResult {\n // Partition each dep into present/absent up-front; downstream calcs are\n // pure derivations from those two arrays.\n const [available, missing] = PEER_DEPENDENCIES.reduce<[PeerDependency[], PeerDependency[]]>(\n ([ok, bad], dep) => (tryRequire(dep.packageName) ? [[...ok, dep], bad] : [ok, [...bad, dep]]),\n [[], []],\n )\n\n const warnings = missing\n .filter((dep) => !dep.required)\n .map((dep) => `Optional plugin '${dep.name}' not found. Some rules will be skipped.`)\n\n const requiredMissing = missing.filter((dep) => dep.required)\n const installCommand = missing.length > 0 ? `pnpm add -D ${missing.map((dep) => dep.packageName).join(\" \")}` : \"\"\n\n return {\n isValid: requiredMissing.length === 0,\n missing,\n available,\n installCommand,\n warnings,\n }\n}\n\nexport function createValidationError(result: ValidationResult): Error {\n const requiredMissing = result.missing.filter((dep) => dep.required)\n\n if (requiredMissing.length === 0) {\n return new Error(\"No validation errors\")\n }\n\n const missingList = requiredMissing.map((dep) => ` • ${dep.name} - ${dep.description}`).join(\"\\n\")\n\n const message = [\n \"❌ Missing required peer dependencies for eslint-plugin-functype:\",\n \"\",\n missingList,\n \"\",\n \"📦 Install missing dependencies:\",\n ` ${result.installCommand}`,\n \"\",\n \"📖 See installation guide: https://github.com/jordanburke/eslint-plugin-functype#installation\",\n ].join(\"\\n\")\n\n return new Error(message)\n}\n\nexport function shouldValidateDependencies(): boolean {\n // Skip validation in test environments or when explicitly disabled\n return process.env.NODE_ENV !== \"test\" && process.env.FUNCTYPE_SKIP_VALIDATION !== \"true\"\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"dependency-validator.js","names":["__require","PEER_DEPENDENCIES","tryRequire","packageName","validatePeerDependencies","available","missing","ok","bad","dep","warnings","requiredMissing","installCommand","createValidationError","result","message","shouldValidateDependencies"],"sources":["../../src/utils/dependency-validator.ts"],"sourcesContent":["// Utility to validate peer dependencies and provide helpful error messages\n\ninterface PeerDependency {\n name: string\n packageName: string\n description: string\n required: boolean\n}\n\nconst PEER_DEPENDENCIES: PeerDependency[] = [\n {\n name: \"@typescript-eslint/eslint-plugin\",\n packageName: \"@typescript-eslint/eslint-plugin\",\n description: \"TypeScript-aware ESLint rules\",\n required: true,\n },\n {\n name: \"@typescript-eslint/parser\",\n packageName: \"@typescript-eslint/parser\",\n description: \"TypeScript parser for ESLint\",\n required: true,\n },\n {\n name: \"eslint-plugin-functional\",\n packageName: \"eslint-plugin-functional\",\n description: \"Functional programming ESLint rules\",\n required: true,\n },\n {\n name: \"eslint-plugin-prettier\",\n packageName: \"eslint-plugin-prettier\",\n description: \"Code formatting rules\",\n required: false,\n },\n {\n name: \"eslint-plugin-simple-import-sort\",\n packageName: \"eslint-plugin-simple-import-sort\",\n description: \"Import sorting rules\",\n required: false,\n },\n {\n name: \"prettier\",\n packageName: \"prettier\",\n description: \"Code formatter\",\n required: false,\n },\n]\n\nexport interface ValidationResult {\n isValid: boolean\n missing: PeerDependency[]\n available: PeerDependency[]\n installCommand: string\n warnings: string[]\n}\n\nfunction tryRequire(packageName: string): boolean {\n try {\n require.resolve(packageName)\n return true\n } catch {\n return false\n }\n}\n\nexport function validatePeerDependencies(): ValidationResult {\n // Partition each dep into present/absent up-front; downstream calcs are\n // pure derivations from those two arrays.\n const [available, missing] = PEER_DEPENDENCIES.reduce<[PeerDependency[], PeerDependency[]]>(\n ([ok, bad], dep) => (tryRequire(dep.packageName) ? [[...ok, dep], bad] : [ok, [...bad, dep]]),\n [[], []],\n )\n\n const warnings = missing\n .filter((dep) => !dep.required)\n .map((dep) => `Optional plugin '${dep.name}' not found. Some rules will be skipped.`)\n\n const requiredMissing = missing.filter((dep) => dep.required)\n const installCommand = missing.length > 0 ? `pnpm add -D ${missing.map((dep) => dep.packageName).join(\" \")}` : \"\"\n\n return {\n isValid: requiredMissing.length === 0,\n missing,\n available,\n installCommand,\n warnings,\n }\n}\n\nexport function createValidationError(result: ValidationResult): Error {\n const requiredMissing = result.missing.filter((dep) => dep.required)\n\n if (requiredMissing.length === 0) {\n return new Error(\"No validation errors\")\n }\n\n const missingList = requiredMissing.map((dep) => ` • ${dep.name} - ${dep.description}`).join(\"\\n\")\n\n const message = [\n \"❌ Missing required peer dependencies for eslint-plugin-functype:\",\n \"\",\n missingList,\n \"\",\n \"📦 Install missing dependencies:\",\n ` ${result.installCommand}`,\n \"\",\n \"📖 See installation guide: https://github.com/jordanburke/eslint-plugin-functype#installation\",\n ].join(\"\\n\")\n\n return new Error(message)\n}\n\nexport function shouldValidateDependencies(): boolean {\n // Skip validation in test environments or when explicitly disabled\n return process.env.NODE_ENV !== \"test\" && process.env.FUNCTYPE_SKIP_VALIDATION !== \"true\"\n}\n"],"mappings":"qFASA,MAAMC,EAAsC,CAC1C,CACE,KAAM,mCACN,YAAa,mCACb,YAAa,gCACb,SAAU,EACZ,EACA,CACE,KAAM,4BACN,YAAa,4BACb,YAAa,+BACb,SAAU,EACZ,EACA,CACE,KAAM,2BACN,YAAa,2BACb,YAAa,sCACb,SAAU,EACZ,EACA,CACE,KAAM,yBACN,YAAa,yBACb,YAAa,wBACb,SAAU,EACZ,EACA,CACE,KAAM,mCACN,YAAa,mCACb,YAAa,uBACb,SAAU,EACZ,EACA,CACE,KAAM,WACN,YAAa,WACb,YAAa,iBACb,SAAU,EACZ,CACF,EAUA,SAASC,EAAW,EAA8B,CAChD,GAAI,CAEF,OADAF,EAAQ,QAAQG,CAAW,EACpB,EACT,MAAQ,C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5
|
* Check if functype library is imported in the current file
|
|
5
6
|
*/
|
|
@@ -59,4 +60,5 @@ export declare function shouldUseDoNotation(node: ASTNode, functypeImports: Func
|
|
|
59
60
|
shouldUse: boolean;
|
|
60
61
|
reason: "nested-checks" | "chained-flatmaps" | "mixed-monads" | "async-chains" | null;
|
|
61
62
|
};
|
|
63
|
+
//#endregion
|
|
62
64
|
//# sourceMappingURL=functype-detection.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"functype-detection.js","names":["TYPE_NAMES","isFunctypeImport","node","hasFunctypeImport","context","categorizeSpecifier","spec","name","pickPresent","buckets","v","b","key","getFunctypeImports","getFunctypeImportsLegacy","isFunctypeType","types","functypeImports","typeName","isFunctypeCall","callee","objectName","methodName","ancestorSatisfies","parent","pred","isAlreadyUsingFunctype","hasFunctypeTypeAnnotation","isDoNotationCall","isDollarHelper","isInsideDoNotation","n","isChainedMethodCall","shouldUseDoNotation","text","flatMapChainDepth"],"sources":["../../src/utils/functype-detection.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Utility functions for detecting functype library usage in ESLint rules.\n *\n * Implementation style: pure helpers operating over native immutable\n * primitives (Array.prototype methods + ReadonlySet). No mutable\n * accumulators, no `for-of` driving state changes. The plugin's domain\n * (AST traversal) is naturally tree-shaped; the helpers compose as\n * folds/filters/maps over those trees.\n */\n\nconst TYPE_NAMES: ReadonlySet<string> = new Set([\n \"Option\",\n \"Either\",\n \"List\",\n \"LazyList\",\n \"Task\",\n \"Try\",\n \"Map\",\n \"Set\",\n \"Stack\",\n])\n\n/** `import ... from \"functype\"` — including `functype/<subpath>` */\nconst isFunctypeImport = (node: ASTNode): boolean =>\n node.type === \"ImportDeclaration\" && node.source.type === \"Literal\" && node.source.value === \"functype\"\n\n/**\n * Check if functype library is imported in the current file\n */\nexport function hasFunctypeImport(context: Rule.RuleContext): boolean {\n return context.sourceCode.ast.body.some(isFunctypeImport)\n}\n\n/**\n * Enhanced functype imports tracking\n */\nexport interface FunctypeImports {\n types: Set<string> // Option, Either, List, etc.\n functions: Set<string> // Do, DoAsync, $, etc.\n all: Set<string> // Combined for compatibility\n}\n\ntype SpecifierBuckets = { readonly type: string | null; readonly fn: string | null; readonly all: string }\n\n/** Sort a single import specifier into the three buckets (or none). */\nfunction categorizeSpecifier(spec: ASTNode): SpecifierBuckets | null {\n if (spec.type === \"ImportSpecifier\" && spec.imported.type === \"Identifier\") {\n const name = spec.imported.name\n // Named imports split by whether they're a functype TYPE or anything else.\n // (Do/DoAsync/$ + any other named import bucket as `functions`, matching\n // the original behavior — the explicit Do/DoAsync/$ branch was redundant.)\n return TYPE_NAMES.has(name) ? { type: name, fn: null, all: name } : { type: null, fn: name, all: name }\n }\n if (spec.type === \"ImportDefaultSpecifier\") return { type: null, fn: \"default\", all: \"default\" }\n if (spec.type === \"ImportNamespaceSpecifier\") return { type: \"*\", fn: \"*\", all: \"*\" }\n return null\n}\n\nconst pickPresent = <K extends keyof SpecifierBuckets>(buckets: readonly SpecifierBuckets[], key: K): string[] =>\n buckets.flatMap((b) => {\n const v = b[key]\n return v === null ? [] : [v as string]\n })\n\n/**\n * Get imported functype symbols from the current file\n */\nexport function getFunctypeImports(context: Rule.RuleContext): FunctypeImports {\n const buckets = context.sourceCode.ast.body\n .filter(isFunctypeImport)\n .flatMap((node: ASTNode) => (node.specifiers ?? []) as ASTNode[])\n .map(categorizeSpecifier)\n .filter((b): b is SpecifierBuckets => b !== null)\n\n return {\n types: new Set(pickPresent(buckets, \"type\")),\n functions: new Set(pickPresent(buckets, \"fn\")),\n all: new Set(buckets.map((b) => b.all)),\n }\n}\n\n/**\n * Legacy compatibility - returns the 'all' set\n */\nexport function getFunctypeImportsLegacy(context: Rule.RuleContext): Set<string> {\n return getFunctypeImports(context).all\n}\n\n/**\n * Check if a type reference is using functype types\n */\nexport function isFunctypeType(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean {\n if (!node) return false\n\n // Handle both new and legacy API\n const types = functypeImports instanceof Set ? functypeImports : functypeImports.types || functypeImports.all\n\n // Check direct type names\n if (node.type === \"TSTypeReference\" && node.typeName?.type === \"Identifier\") {\n const typeName = node.typeName.name\n return (\n types.has(typeName) ||\n [\"Option\", \"Either\", \"List\", \"LazyList\", \"Task\", \"Try\", \"Map\", \"Set\", \"Stack\"].includes(typeName)\n )\n }\n\n return false\n}\n\n/**\n * Check if a call expression is using functype methods\n */\nexport function isFunctypeCall(node: ASTNode, functypeImports: Set<string>): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for static method calls like Option.some(), Either.left(), List.of()\n if (callee.type === \"MemberExpression\" && callee.object.type === \"Identifier\") {\n const objectName = callee.object.name\n const methodName = callee.property?.name\n\n // Check if calling methods on imported functype types\n if (functypeImports.has(objectName)) return true\n\n // Check for common functype patterns\n if (\n (objectName === \"Option\" && [\"some\", \"none\", \"of\"].includes(methodName)) ||\n (objectName === \"Either\" && [\"left\", \"right\", \"of\"].includes(methodName)) ||\n (objectName === \"List\" && [\"of\", \"from\", \"empty\"].includes(methodName)) ||\n (objectName === \"Map\" && [\"of\", \"empty\"].includes(methodName)) ||\n (objectName === \"Set\" && [\"of\", \"empty\"].includes(methodName))\n ) {\n return true\n }\n }\n\n // Check for method calls on functype instances like someOption.map()\n if (callee.type === \"MemberExpression\") {\n const methodName = callee.property?.name\n\n // Common functype methods\n if (\n [\n \"map\",\n \"flatMap\",\n \"filter\",\n \"fold\",\n \"foldLeft\",\n \"foldRight\",\n \"getOrElse\",\n \"orElse\",\n \"isEmpty\",\n \"nonEmpty\",\n \"isDefined\",\n \"isSome\",\n \"isNone\",\n \"isLeft\",\n \"isRight\",\n \"toArray\",\n ].includes(methodName)\n ) {\n return true\n }\n }\n\n return false\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/**\n * Check if current context is already using functype patterns appropriately\n */\nexport function isAlreadyUsingFunctype(node: ASTNode, functypeImports: Set<string>): boolean {\n return ancestorSatisfies(\n node,\n (parent) => isFunctypeCall(parent, functypeImports) || isFunctypeType(parent, functypeImports),\n )\n}\n\n/**\n * Check if a variable or parameter is typed with functype types\n */\nexport function hasFunctypeTypeAnnotation(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean {\n // Check for type annotation\n if (node.typeAnnotation?.typeAnnotation) {\n return isFunctypeType(node.typeAnnotation.typeAnnotation, functypeImports)\n }\n\n return false\n}\n\n/**\n * Check if a call expression is a Do notation call\n */\nexport function isDoNotationCall(node: ASTNode, functypeImports: FunctypeImports): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for Do() or DoAsync() calls\n if (callee.type === \"Identifier\") {\n const name = callee.name\n return functypeImports.functions.has(name) && [\"Do\", \"DoAsync\"].includes(name)\n }\n\n return false\n}\n\n/**\n * Check if a call expression uses the $ helper function\n */\nexport function isDollarHelper(node: ASTNode, functypeImports: FunctypeImports): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for $() calls\n if (callee.type === \"Identifier\" && callee.name === \"$\") {\n return functypeImports.functions.has(\"$\")\n }\n\n return false\n}\n\n/**\n * Check if current expression is inside a Do notation block\n */\nexport function isInsideDoNotation(node: ASTNode, functypeImports: FunctypeImports): boolean {\n return ancestorSatisfies(node, (n) => n.type === \"CallExpression\" && isDoNotationCall(n, functypeImports))\n}\n\n/**\n * Check if a method call is a chained method call on functype types\n */\nexport function isChainedMethodCall(node: ASTNode, methodName: string): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n if (\n callee.type === \"MemberExpression\" &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === methodName\n ) {\n return true\n }\n\n return false\n}\n\n/**\n * Detect if code could benefit from Do notation\n */\nexport function shouldUseDoNotation(\n node: ASTNode,\n functypeImports: FunctypeImports,\n): {\n shouldUse: boolean\n reason: \"nested-checks\" | \"chained-flatmaps\" | \"mixed-monads\" | \"async-chains\" | null\n} {\n // Already using Do notation\n if (isInsideDoNotation(node, functypeImports)) {\n return { shouldUse: false, reason: null }\n }\n\n // Check for nested null checks (a && a.b && a.b.c pattern)\n if (node.type === \"LogicalExpression\" && node.operator === \"&&\") {\n const text = node.toString ? node.toString() : \"\"\n if (text.includes(\"&&\") && text.match(/\\w+(\\.\\w+){2,}/)) {\n return { shouldUse: true, reason: \"nested-checks\" }\n }\n }\n\n // Check for chained flatMap calls\n if (isChainedMethodCall(node, \"flatMap\") && flatMapChainDepth(node) >= 3) {\n return { shouldUse: true, reason: \"chained-flatmaps\" }\n }\n\n return { shouldUse: false, reason: null }\n}\n\n/** Length of an unbroken `.flatMap().flatMap()...` chain starting at `node`. */\nfunction flatMapChainDepth(node: ASTNode): number {\n if (!node || node.type !== \"CallExpression\" || !isChainedMethodCall(node, \"flatMap\")) return 0\n if (node.callee.type !== \"MemberExpression\") return 1\n return 1 + flatMapChainDepth(node.callee.object as ASTNode)\n}\n"],"mappings":"AAcA,MAAMA,kBAAkC,IAAI,IAAI,CAC9C,SACA,SACA,OACA,WACA,OACA,MACA,MACA,MACA,OACF,CAAC,EAGKC,EAAoB,GACxBC,EAAK,OAAS,qBAAuBA,EAAK,OAAO,OAAS,WAAaA,EAAK,OAAO,QAAU,WAK/F,SAAgBC,EAAkB,EAAoC,CACpE,OAAOC,EAAQ,WAAW,IAAI,KAAK,KAAKH,CAAgB,CAC1D,CAcA,SAASI,EAAoB,EAAwC,CACnE,GAAIC,EAAK,OAAS,mBAAqBA,EAAK,SAAS,OAAS,aAAc,CAC1E,IAAMC,EAAOD,EAAK,SAAS,KAI3B,OAAON,EAAW,IAAIO,CAAI,EAAI,CAAE,KAAMA,EAAM,GAAI,KAAM,IAAKA,CAAK,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EAGhD,CAAE,UAAW,GAAO,OAAQ,IAAK,CAC1C,CAGA,SAASiC,EAAkB,EAAuB,CAGhD,MAFI,CAACjC,GAAQA,EAAK,OAAS,kBAAoB,CAAC8B,EAAoB9B,EAAM,SAAS,EAAU,EACzFA,EAAK,OAAO,OAAS,mBAClB,EAAIiC,EAAkBjC,EAAK,OAAO,MAAiB,EADN,CAEtD,C"}
|
|
1
|
+
{"version":3,"file":"functype-detection.js","names":["TYPE_NAMES","isFunctypeImport","node","hasFunctypeImport","context","categorizeSpecifier","spec","name","pickPresent","buckets","v","b","key","getFunctypeImports","getFunctypeImportsLegacy","isFunctypeType","types","functypeImports","typeName","isFunctypeCall","callee","objectName","methodName","ancestorSatisfies","parent","pred","isAlreadyUsingFunctype","hasFunctypeTypeAnnotation","isDoNotationCall","isDollarHelper","isInsideDoNotation","n","isChainedMethodCall","shouldUseDoNotation","text","flatMapChainDepth"],"sources":["../../src/utils/functype-detection.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Utility functions for detecting functype library usage in ESLint rules.\n *\n * Implementation style: pure helpers operating over native immutable\n * primitives (Array.prototype methods + ReadonlySet). No mutable\n * accumulators, no `for-of` driving state changes. The plugin's domain\n * (AST traversal) is naturally tree-shaped; the helpers compose as\n * folds/filters/maps over those trees.\n */\n\nconst TYPE_NAMES: ReadonlySet<string> = new Set([\n \"Option\",\n \"Either\",\n \"List\",\n \"LazyList\",\n \"Task\",\n \"Try\",\n \"Map\",\n \"Set\",\n \"Stack\",\n])\n\n/** `import ... from \"functype\"` — including `functype/<subpath>` */\nconst isFunctypeImport = (node: ASTNode): boolean =>\n node.type === \"ImportDeclaration\" && node.source.type === \"Literal\" && node.source.value === \"functype\"\n\n/**\n * Check if functype library is imported in the current file\n */\nexport function hasFunctypeImport(context: Rule.RuleContext): boolean {\n return context.sourceCode.ast.body.some(isFunctypeImport)\n}\n\n/**\n * Enhanced functype imports tracking\n */\nexport interface FunctypeImports {\n types: Set<string> // Option, Either, List, etc.\n functions: Set<string> // Do, DoAsync, $, etc.\n all: Set<string> // Combined for compatibility\n}\n\ntype SpecifierBuckets = { readonly type: string | null; readonly fn: string | null; readonly all: string }\n\n/** Sort a single import specifier into the three buckets (or none). */\nfunction categorizeSpecifier(spec: ASTNode): SpecifierBuckets | null {\n if (spec.type === \"ImportSpecifier\" && spec.imported.type === \"Identifier\") {\n const name = spec.imported.name\n // Named imports split by whether they're a functype TYPE or anything else.\n // (Do/DoAsync/$ + any other named import bucket as `functions`, matching\n // the original behavior — the explicit Do/DoAsync/$ branch was redundant.)\n return TYPE_NAMES.has(name) ? { type: name, fn: null, all: name } : { type: null, fn: name, all: name }\n }\n if (spec.type === \"ImportDefaultSpecifier\") return { type: null, fn: \"default\", all: \"default\" }\n if (spec.type === \"ImportNamespaceSpecifier\") return { type: \"*\", fn: \"*\", all: \"*\" }\n return null\n}\n\nconst pickPresent = <K extends keyof SpecifierBuckets>(buckets: readonly SpecifierBuckets[], key: K): string[] =>\n buckets.flatMap((b) => {\n const v = b[key]\n return v === null ? [] : [v as string]\n })\n\n/**\n * Get imported functype symbols from the current file\n */\nexport function getFunctypeImports(context: Rule.RuleContext): FunctypeImports {\n const buckets = context.sourceCode.ast.body\n .filter(isFunctypeImport)\n .flatMap((node: ASTNode) => (node.specifiers ?? []) as ASTNode[])\n .map(categorizeSpecifier)\n .filter((b): b is SpecifierBuckets => b !== null)\n\n return {\n types: new Set(pickPresent(buckets, \"type\")),\n functions: new Set(pickPresent(buckets, \"fn\")),\n all: new Set(buckets.map((b) => b.all)),\n }\n}\n\n/**\n * Legacy compatibility - returns the 'all' set\n */\nexport function getFunctypeImportsLegacy(context: Rule.RuleContext): Set<string> {\n return getFunctypeImports(context).all\n}\n\n/**\n * Check if a type reference is using functype types\n */\nexport function isFunctypeType(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean {\n if (!node) return false\n\n // Handle both new and legacy API\n const types = functypeImports instanceof Set ? functypeImports : functypeImports.types || functypeImports.all\n\n // Check direct type names\n if (node.type === \"TSTypeReference\" && node.typeName?.type === \"Identifier\") {\n const typeName = node.typeName.name\n return (\n types.has(typeName) ||\n [\"Option\", \"Either\", \"List\", \"LazyList\", \"Task\", \"Try\", \"Map\", \"Set\", \"Stack\"].includes(typeName)\n )\n }\n\n return false\n}\n\n/**\n * Check if a call expression is using functype methods\n */\nexport function isFunctypeCall(node: ASTNode, functypeImports: Set<string>): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for static method calls like Option.some(), Either.left(), List.of()\n if (callee.type === \"MemberExpression\" && callee.object.type === \"Identifier\") {\n const objectName = callee.object.name\n const methodName = callee.property?.name\n\n // Check if calling methods on imported functype types\n if (functypeImports.has(objectName)) return true\n\n // Check for common functype patterns\n if (\n (objectName === \"Option\" && [\"some\", \"none\", \"of\"].includes(methodName)) ||\n (objectName === \"Either\" && [\"left\", \"right\", \"of\"].includes(methodName)) ||\n (objectName === \"List\" && [\"of\", \"from\", \"empty\"].includes(methodName)) ||\n (objectName === \"Map\" && [\"of\", \"empty\"].includes(methodName)) ||\n (objectName === \"Set\" && [\"of\", \"empty\"].includes(methodName))\n ) {\n return true\n }\n }\n\n // Check for method calls on functype instances like someOption.map()\n if (callee.type === \"MemberExpression\") {\n const methodName = callee.property?.name\n\n // Common functype methods\n if (\n [\n \"map\",\n \"flatMap\",\n \"filter\",\n \"fold\",\n \"foldLeft\",\n \"foldRight\",\n \"getOrElse\",\n \"orElse\",\n \"isEmpty\",\n \"nonEmpty\",\n \"isDefined\",\n \"isSome\",\n \"isNone\",\n \"isLeft\",\n \"isRight\",\n \"toArray\",\n ].includes(methodName)\n ) {\n return true\n }\n }\n\n return false\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/**\n * Check if current context is already using functype patterns appropriately\n */\nexport function isAlreadyUsingFunctype(node: ASTNode, functypeImports: Set<string>): boolean {\n return ancestorSatisfies(\n node,\n (parent) => isFunctypeCall(parent, functypeImports) || isFunctypeType(parent, functypeImports),\n )\n}\n\n/**\n * Check if a variable or parameter is typed with functype types\n */\nexport function hasFunctypeTypeAnnotation(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean {\n // Check for type annotation\n if (node.typeAnnotation?.typeAnnotation) {\n return isFunctypeType(node.typeAnnotation.typeAnnotation, functypeImports)\n }\n\n return false\n}\n\n/**\n * Check if a call expression is a Do notation call\n */\nexport function isDoNotationCall(node: ASTNode, functypeImports: FunctypeImports): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for Do() or DoAsync() calls\n if (callee.type === \"Identifier\") {\n const name = callee.name\n return functypeImports.functions.has(name) && [\"Do\", \"DoAsync\"].includes(name)\n }\n\n return false\n}\n\n/**\n * Check if a call expression uses the $ helper function\n */\nexport function isDollarHelper(node: ASTNode, functypeImports: FunctypeImports): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n // Check for $() calls\n if (callee.type === \"Identifier\" && callee.name === \"$\") {\n return functypeImports.functions.has(\"$\")\n }\n\n return false\n}\n\n/**\n * Check if current expression is inside a Do notation block\n */\nexport function isInsideDoNotation(node: ASTNode, functypeImports: FunctypeImports): boolean {\n return ancestorSatisfies(node, (n) => n.type === \"CallExpression\" && isDoNotationCall(n, functypeImports))\n}\n\n/**\n * Check if a method call is a chained method call on functype types\n */\nexport function isChainedMethodCall(node: ASTNode, methodName: string): boolean {\n if (!node || node.type !== \"CallExpression\") return false\n\n const callee = node.callee\n\n if (\n callee.type === \"MemberExpression\" &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === methodName\n ) {\n return true\n }\n\n return false\n}\n\n/**\n * Detect if code could benefit from Do notation\n */\nexport function shouldUseDoNotation(\n node: ASTNode,\n functypeImports: FunctypeImports,\n): {\n shouldUse: boolean\n reason: \"nested-checks\" | \"chained-flatmaps\" | \"mixed-monads\" | \"async-chains\" | null\n} {\n // Already using Do notation\n if (isInsideDoNotation(node, functypeImports)) {\n return { shouldUse: false, reason: null }\n }\n\n // Check for nested null checks (a && a.b && a.b.c pattern)\n if (node.type === \"LogicalExpression\" && node.operator === \"&&\") {\n const text = node.toString ? node.toString() : \"\"\n if (text.includes(\"&&\") && text.match(/\\w+(\\.\\w+){2,}/)) {\n return { shouldUse: true, reason: \"nested-checks\" }\n }\n }\n\n // Check for chained flatMap calls\n if (isChainedMethodCall(node, \"flatMap\") && flatMapChainDepth(node) >= 3) {\n return { shouldUse: true, reason: \"chained-flatmaps\" }\n }\n\n return { shouldUse: false, reason: null }\n}\n\n/** Length of an unbroken `.flatMap().flatMap()...` chain starting at `node`. */\nfunction flatMapChainDepth(node: ASTNode): number {\n if (!node || node.type !== \"CallExpression\" || !isChainedMethodCall(node, \"flatMap\")) return 0\n if (node.callee.type !== \"MemberExpression\") return 1\n return 1 + flatMapChainDepth(node.callee.object as ASTNode)\n}\n"],"mappings":"AAcA,MAAMA,kBAAkC,IAAI,IAAI,CAC9C,SACA,SACA,OACA,WACA,OACA,MACA,MACA,MACA,OACF,CAAC,EAGKC,EAAoB,GACxBC,EAAK,OAAS,qBAAuBA,EAAK,OAAO,OAAS,WAAaA,EAAK,OAAO,QAAU,WAK/F,SAAgBC,EAAkB,EAAoC,CACpE,OAAOC,EAAQ,WAAW,IAAI,KAAK,KAAKH,CAAgB,CAC1D,CAcA,SAASI,EAAoB,EAAwC,CACnE,GAAIC,EAAK,OAAS,mBAAqBA,EAAK,SAAS,OAAS,aAAc,CAC1E,IAAMC,EAAOD,EAAK,SAAS,KAI3B,OAAON,EAAW,IAAIO,CAAI,EAAI,CAAE,KAAMA,EAAM,GAAI,KAAM,IAAKA,CAAK,EAAI,CAAE,KAAM,KAAM,GAAIA,EAAM,IAAK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1C,CAGA,SAASiC,EAAkB,EAAuB,CAGhD,MAFI,CAACjC,GAAQA,EAAK,OAAS,kBAAoB,CAAC8B,EAAoB9B,EAAM,SAAS,EAAU,EACzFA,EAAK,OAAO,OAAS,mBAClB,EAAIiC,EAAkBjC,EAAK,OAAO,MAAiB,EADN,CAEtD"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ASTNode } from "../types/ast.js";
|
|
2
2
|
import { SourceCode } from "eslint";
|
|
3
|
+
//#region src/utils/functype-predicates.d.ts
|
|
3
4
|
/** Methods on a monadic value that mean "this is the Some/Right/Success path." */
|
|
4
5
|
export declare const POSITIVE_PREDICATES: ReadonlySet<string>;
|
|
5
6
|
/** Methods that mean "this is the None/Left/Failure path." */
|
|
@@ -35,4 +36,5 @@ export type Presence = "present" | "absent" | null;
|
|
|
35
36
|
export declare const provesWhen: (test: ASTNode, outcome: boolean, receiverText: string, sourceCode: SourceCode) => Presence;
|
|
36
37
|
/** The functype-react component that renders both cases of the container a predicate belongs to. */
|
|
37
38
|
export declare const MATCH_COMPONENT: Readonly<Record<string, string>>;
|
|
39
|
+
//#endregion
|
|
38
40
|
//# sourceMappingURL=functype-predicates.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"functype-predicates.js","names":["POSITIVE_PREDICATES","NEGATIVE_PREDICATES","compact","text","predicateCall","node","callee","method","isNegated","sourceCode","testedPredicate","test","inner","isEmptyRead","receiverText","provesWhen","self","value","outcome","left","right","predicate","isAbsenceTest","MATCH_COMPONENT"],"sources":["../../src/utils/functype-predicates.ts"],"sourcesContent":["import type { SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/** Methods on a monadic value that mean \"this is the Some/Right/Success path.\" */\nexport const POSITIVE_PREDICATES: ReadonlySet<string> = new Set([\"isSome\", \"isRight\", \"isSuccess\"])\n/** Methods that mean \"this is the None/Left/Failure path.\" */\n// `isEmpty` is deliberately absent: it is a property on every functype container, never a method, so\n// `x.isEmpty()` is not functype code (and on a List, `.fold` is a reduce, not a branch).\nexport const NEGATIVE_PREDICATES: ReadonlySet<string> = new Set([\"isNone\", \"isLeft\", \"isFailure\"])\n\n/** Source text with all whitespace removed — receivers match however they are line-broken. */\nexport const compact = (text: string): string => text.replace(/\\s+/g, \"\")\n\n/** A functype predicate call such as `o.isSome()`, split into its receiver and method. */\nexport type PredicateCall = {\n readonly receiver: ASTNode\n /** The receiver's source text, whitespace removed, for matching against other reads of it. */\n readonly receiverText: string\n readonly method: string\n readonly isNegated: boolean\n}\n\n/**\n * `o.isSome()`, `e.isLeft()`, `t.isFailure()` — a zero-argument call of a functype predicate method.\n * A property read (`state.isPending`, `items.isEmpty`) is not a call, so it never matches.\n */\nexport const predicateCall = (node: ASTNode, sourceCode: SourceCode): PredicateCall | null => {\n if (node?.type !== \"CallExpression\" || node.arguments.length !== 0) return null\n const callee = node.callee as ASTNode\n if (callee.type !== \"MemberExpression\" || callee.computed || callee.property.type !== \"Identifier\") return null\n const method = callee.property.name as string\n const isNegated = NEGATIVE_PREDICATES.has(method)\n if (!isNegated && !POSITIVE_PREDICATES.has(method)) return null\n return { receiver: callee.object, receiverText: compact(sourceCode.getText(callee.object)), method, isNegated }\n}\n\n/**\n * The first predicate call a test branches on, looking through `!` (which flips it) and `&&` / `||`:\n * `o.isSome()`, `!o.isSome()`, `loading || o.isNone()`. `isNegated` is the predicate's own meaning\n * with any `!` applied, so `!o.isSome()` reads like `o.isNone()`.\n */\nexport const testedPredicate = (test: ASTNode, sourceCode: SourceCode): PredicateCall | null => {\n if (test?.type === \"UnaryExpression\" && test.operator === \"!\") {\n const inner = testedPredicate(test.argument, sourceCode)\n return inner === null ? null : { ...inner, isNegated: !inner.isNegated }\n }\n if (test?.type === \"LogicalExpression\" && (test.operator === \"&&\" || test.operator === \"||\")) {\n return testedPredicate(test.left, sourceCode) ?? testedPredicate(test.right, sourceCode)\n }\n return predicateCall(test, sourceCode)\n}\n\n/** What a test proves about a receiver's value: there, missing, or nothing. */\nexport type Presence = \"present\" | \"absent\" | null\n\n/** `o.isEmpty` read (not called): Option's narrowing property, true when the value is missing. */\nconst isEmptyRead = (node: ASTNode, receiverText: string, sourceCode: SourceCode): boolean =>\n node?.type === \"MemberExpression\" &&\n !node.computed &&\n node.property.type === \"Identifier\" &&\n node.property.name === \"isEmpty\" &&\n !(node.parent?.type === \"CallExpression\" && node.parent.callee === node) &&\n compact(sourceCode.getText(node.object)) === receiverText\n\n/**\n * What `test` evaluating to `outcome` proves about `receiverText`. Looks through `!`, `&&` and `||`:\n * `a && b` being true proves whatever either side proves, `a || b` being false likewise, and the other\n * two cases prove something only when both sides agree. `o.isEmpty` counts as a test for absence.\n */\nexport const provesWhen = (test: ASTNode, outcome: boolean, receiverText: string, sourceCode: SourceCode): Presence => {\n const self = (node: ASTNode, value: boolean): Presence => provesWhen(node, value, receiverText, sourceCode)\n if (test?.type === \"UnaryExpression\" && test.operator === \"!\") return self(test.argument, !outcome)\n if (test?.type === \"LogicalExpression\" && (test.operator === \"&&\" || test.operator === \"||\")) {\n const left = self(test.left, outcome)\n const right = self(test.right, outcome)\n // `a && b` true, or `a || b` false: both sides hold that outcome, so either one's proof counts.\n if ((test.operator === \"&&\") === outcome) return left ?? right\n return left === right ? left : null\n }\n const predicate = predicateCall(test, sourceCode)\n const isAbsenceTest =\n predicate !== null && predicate.receiverText === receiverText\n ? predicate.isNegated\n : isEmptyRead(test, receiverText, sourceCode)\n ? true\n : null\n if (isAbsenceTest === null) return null\n return isAbsenceTest === outcome ? \"absent\" : \"present\"\n}\n\n/** The functype-react component that renders both cases of the container a predicate belongs to. */\nexport const MATCH_COMPONENT: Readonly<Record<string, string>> = {\n isSome: \"MatchOption\",\n isNone: \"MatchOption\",\n isLeft: \"MatchEither\",\n isRight: \"MatchEither\",\n isSuccess: \"MatchTry\",\n isFailure: \"MatchTry\",\n}\n"],"mappings":"AAKA,MAAaA,kBAA2C,IAAI,IAAI,CAAC,SAAU,UAAW,WAAW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EAAMY,EAAOH,EAAcL,CAAU,EAC1G,GAAIE,GAAM,OAAS,mBAAqBA,EAAK,WAAa,IAAK,OAAOK,EAAKL,EAAK,SAAU,CAACO,CAAO,EAClG,GAAIP,GAAM,OAAS,sBAAwBA,EAAK,WAAa,MAAQA,EAAK,WAAa,MAAO,CAC5F,IAAMQ,EAAOH,EAAKL,EAAK,KAAMO,CAAO,EAC9BE,EAAQJ,EAAKL,EAAK,MAAOO,CAAO,EAGtC,OADKP,EAAK,WAAa,OAAUO,EAAgBC,GAAQC,EAClDD,IAASC,EAAQD,EAAO,IACjC,CACA,IAAME,EAAYjB,EAAcO,EAAMF,CAAU,EAC1Ca,EACJD,IAAc,MAAQA,EAAU,eAAiBP,EAC7CO,EAAU,UACVR,EAAYF,EAAMG,EAAcL,CAAU,EACxC,GACA,KAER,OADIa,IAAkB,KAAa,KAC5BA,IAAkBJ,EAAU,SAAW,SAChD,EAGaK,EAAoD,CAC/D,OAAQ,cACR,OAAQ,cACR,OAAQ,cACR,QAAS,cACT,UAAW,WACX,UAAW,UACb
|
|
1
|
+
{"version":3,"file":"functype-predicates.js","names":["POSITIVE_PREDICATES","NEGATIVE_PREDICATES","compact","text","predicateCall","node","callee","method","isNegated","sourceCode","testedPredicate","test","inner","isEmptyRead","receiverText","provesWhen","self","value","outcome","left","right","predicate","isAbsenceTest","MATCH_COMPONENT"],"sources":["../../src/utils/functype-predicates.ts"],"sourcesContent":["import type { SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/** Methods on a monadic value that mean \"this is the Some/Right/Success path.\" */\nexport const POSITIVE_PREDICATES: ReadonlySet<string> = new Set([\"isSome\", \"isRight\", \"isSuccess\"])\n/** Methods that mean \"this is the None/Left/Failure path.\" */\n// `isEmpty` is deliberately absent: it is a property on every functype container, never a method, so\n// `x.isEmpty()` is not functype code (and on a List, `.fold` is a reduce, not a branch).\nexport const NEGATIVE_PREDICATES: ReadonlySet<string> = new Set([\"isNone\", \"isLeft\", \"isFailure\"])\n\n/** Source text with all whitespace removed — receivers match however they are line-broken. */\nexport const compact = (text: string): string => text.replace(/\\s+/g, \"\")\n\n/** A functype predicate call such as `o.isSome()`, split into its receiver and method. */\nexport type PredicateCall = {\n readonly receiver: ASTNode\n /** The receiver's source text, whitespace removed, for matching against other reads of it. */\n readonly receiverText: string\n readonly method: string\n readonly isNegated: boolean\n}\n\n/**\n * `o.isSome()`, `e.isLeft()`, `t.isFailure()` — a zero-argument call of a functype predicate method.\n * A property read (`state.isPending`, `items.isEmpty`) is not a call, so it never matches.\n */\nexport const predicateCall = (node: ASTNode, sourceCode: SourceCode): PredicateCall | null => {\n if (node?.type !== \"CallExpression\" || node.arguments.length !== 0) return null\n const callee = node.callee as ASTNode\n if (callee.type !== \"MemberExpression\" || callee.computed || callee.property.type !== \"Identifier\") return null\n const method = callee.property.name as string\n const isNegated = NEGATIVE_PREDICATES.has(method)\n if (!isNegated && !POSITIVE_PREDICATES.has(method)) return null\n return { receiver: callee.object, receiverText: compact(sourceCode.getText(callee.object)), method, isNegated }\n}\n\n/**\n * The first predicate call a test branches on, looking through `!` (which flips it) and `&&` / `||`:\n * `o.isSome()`, `!o.isSome()`, `loading || o.isNone()`. `isNegated` is the predicate's own meaning\n * with any `!` applied, so `!o.isSome()` reads like `o.isNone()`.\n */\nexport const testedPredicate = (test: ASTNode, sourceCode: SourceCode): PredicateCall | null => {\n if (test?.type === \"UnaryExpression\" && test.operator === \"!\") {\n const inner = testedPredicate(test.argument, sourceCode)\n return inner === null ? null : { ...inner, isNegated: !inner.isNegated }\n }\n if (test?.type === \"LogicalExpression\" && (test.operator === \"&&\" || test.operator === \"||\")) {\n return testedPredicate(test.left, sourceCode) ?? testedPredicate(test.right, sourceCode)\n }\n return predicateCall(test, sourceCode)\n}\n\n/** What a test proves about a receiver's value: there, missing, or nothing. */\nexport type Presence = \"present\" | \"absent\" | null\n\n/** `o.isEmpty` read (not called): Option's narrowing property, true when the value is missing. */\nconst isEmptyRead = (node: ASTNode, receiverText: string, sourceCode: SourceCode): boolean =>\n node?.type === \"MemberExpression\" &&\n !node.computed &&\n node.property.type === \"Identifier\" &&\n node.property.name === \"isEmpty\" &&\n !(node.parent?.type === \"CallExpression\" && node.parent.callee === node) &&\n compact(sourceCode.getText(node.object)) === receiverText\n\n/**\n * What `test` evaluating to `outcome` proves about `receiverText`. Looks through `!`, `&&` and `||`:\n * `a && b` being true proves whatever either side proves, `a || b` being false likewise, and the other\n * two cases prove something only when both sides agree. `o.isEmpty` counts as a test for absence.\n */\nexport const provesWhen = (test: ASTNode, outcome: boolean, receiverText: string, sourceCode: SourceCode): Presence => {\n const self = (node: ASTNode, value: boolean): Presence => provesWhen(node, value, receiverText, sourceCode)\n if (test?.type === \"UnaryExpression\" && test.operator === \"!\") return self(test.argument, !outcome)\n if (test?.type === \"LogicalExpression\" && (test.operator === \"&&\" || test.operator === \"||\")) {\n const left = self(test.left, outcome)\n const right = self(test.right, outcome)\n // `a && b` true, or `a || b` false: both sides hold that outcome, so either one's proof counts.\n if ((test.operator === \"&&\") === outcome) return left ?? right\n return left === right ? left : null\n }\n const predicate = predicateCall(test, sourceCode)\n const isAbsenceTest =\n predicate !== null && predicate.receiverText === receiverText\n ? predicate.isNegated\n : isEmptyRead(test, receiverText, sourceCode)\n ? true\n : null\n if (isAbsenceTest === null) return null\n return isAbsenceTest === outcome ? \"absent\" : \"present\"\n}\n\n/** The functype-react component that renders both cases of the container a predicate belongs to. */\nexport const MATCH_COMPONENT: Readonly<Record<string, string>> = {\n isSome: \"MatchOption\",\n isNone: \"MatchOption\",\n isLeft: \"MatchEither\",\n isRight: \"MatchEither\",\n isSuccess: \"MatchTry\",\n isFailure: \"MatchTry\",\n}\n"],"mappings":"AAKA,MAAaA,kBAA2C,IAAI,IAAI,CAAC,SAAU,UAAW,WAAW,CAAC,EAIrFC,kBAA2C,IAAI,IAAI,CAAC,SAAU,SAAU,WAAW,CAAC,EAGpFC,EAAW,GAAyBC,EAAK,QAAQ,OAAQ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,CAACO,CAAO,EAClG,GAAIP,GAAM,OAAS,sBAAwBA,EAAK,WAAa,MAAQA,EAAK,WAAa,MAAO,CAC5F,IAAMQ,EAAOH,EAAKL,EAAK,KAAMO,CAAO,EAC9BE,EAAQJ,EAAKL,EAAK,MAAOO,CAAO,EAGtC,OADKP,EAAK,WAAa,OAAUO,EAAgBC,GAAQC,EAClDD,IAASC,EAAQD,EAAO,IACjC,CACA,IAAME,EAAYjB,EAAcO,EAAMF,CAAU,EAC1Ca,EACJD,IAAc,MAAQA,EAAU,eAAiBP,EAC7CO,EAAU,UACVR,EAAYF,EAAMG,EAAcL,CAAU,EACxC,GACA,KAER,OADIa,IAAkB,KAAa,KAC5BA,IAAkBJ,EAAU,SAAW,SAChD,EAGaK,EAAoD,CAC/D,OAAQ,cACR,OAAQ,cACR,OAAQ,cACR,QAAS,cACT,UAAW,WACX,UAAW,UACb"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Rule, SourceCode } from "eslint";
|
|
2
|
+
//#region src/utils/import-fixer.d.ts
|
|
2
3
|
/**
|
|
3
4
|
* Check if a given symbol is already imported from functype
|
|
4
5
|
*/
|
|
@@ -8,4 +9,5 @@ export declare function hasFunctypeSymbol(sourceCode: SourceCode, symbolName: st
|
|
|
8
9
|
* Returns a factory compatible with ESLint suggest[].fix signature.
|
|
9
10
|
*/
|
|
10
11
|
export declare function createImportFixer(sourceCode: SourceCode, symbolName: string): (fixer: Rule.RuleFixer) => Rule.Fix | null;
|
|
12
|
+
//#endregion
|
|
11
13
|
//# sourceMappingURL=import-fixer.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"import-fixer.js","names":["isImportDecl","node","isFunctypeImportDecl","specifierMatches","spec","symbolName","hasFunctypeSymbol","sourceCode","n","createImportFixer","program","imports","lastImportNode","existingFunctypeImport","s","lastSpecifier","fixer","importText","newImport","firstNode"],"sources":["../../src/utils/import-fixer.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\nimport type { SourceCode } from \"eslint\"\n\ntype ImportSpec = {\n type: string\n imported?: { type: string; name: string }\n}\ntype ImportNode = {\n type: \"ImportDeclaration\"\n source: { type: string; value: string }\n specifiers?: readonly ImportSpec[]\n}\n\nconst isImportDecl = (node: { type: string }): node is ImportNode => node.type === \"ImportDeclaration\"\n\nconst isFunctypeImportDecl = (node: { type: string }): node is ImportNode =>\n isImportDecl(node) && node.source?.type === \"Literal\" && node.source.value === \"functype\"\n\nconst specifierMatches = (spec: ImportSpec, symbolName: string): boolean =>\n spec.type === \"ImportNamespaceSpecifier\" ||\n (spec.type === \"ImportSpecifier\" && spec.imported?.type === \"Identifier\" && spec.imported.name === symbolName)\n\n/**\n * Check if a given symbol is already imported from functype\n */\nexport function hasFunctypeSymbol(sourceCode: SourceCode, symbolName: string): boolean {\n return (sourceCode.ast.body as readonly unknown[])\n .filter((n): n is ImportNode => isFunctypeImportDecl(n as { type: string }))\n .flatMap((node) => node.specifiers ?? [])\n .some((spec) => specifierMatches(spec, symbolName))\n}\n\n/**\n * Create a fixer function that adds a symbol to the functype import.\n * Returns a factory compatible with ESLint suggest[].fix signature.\n */\nexport function createImportFixer(\n sourceCode: SourceCode,\n symbolName: string,\n): (fixer: Rule.RuleFixer) => Rule.Fix | null {\n return (fixer: Rule.RuleFixer): Rule.Fix | null => {\n // Already imported — nothing to do.\n if (hasFunctypeSymbol(sourceCode, symbolName)) return null\n\n const program = sourceCode.ast\n const imports = (program.body as readonly unknown[]).filter((n): n is ImportNode =>\n isImportDecl(n as { type: string }),\n )\n const lastImportNode = imports.at(-1) ?? null\n const existingFunctypeImport = imports.find((n) => isFunctypeImportDecl(n)) ?? null\n\n if (existingFunctypeImport) {\n // Namespace import (`import * as F from \"functype\"`) — can't add named.\n const hasNamespace =\n existingFunctypeImport.specifiers?.some((s) => s.type === \"ImportNamespaceSpecifier\") ?? false\n if (hasNamespace) return null\n\n // Append after the last named specifier if one exists.\n const namedSpecifiers = (existingFunctypeImport.specifiers ?? []).filter((s) => s.type === \"ImportSpecifier\")\n const lastSpecifier = namedSpecifiers.at(-1)\n if (lastSpecifier) return fixer.insertTextAfter(lastSpecifier as never, `, ${symbolName}`)\n\n // No named specifiers — fill the empty braces.\n const importText = sourceCode.getText(existingFunctypeImport as never)\n return fixer.replaceText(existingFunctypeImport as never, importText.replace(/\\{(\\s*)\\}/, `{ ${symbolName} }`))\n }\n\n // No existing functype import — insert a new one.\n const newImport = `import { ${symbolName} } from \"functype\"`\n if (lastImportNode) return fixer.insertTextAfter(lastImportNode as never, `\\n${newImport}`)\n\n const firstNode = program.body[0]\n if (firstNode) return fixer.insertTextBefore(firstNode, `${newImport}\\n`)\n return fixer.insertTextBeforeRange([0, 0], `${newImport}\\n`)\n }\n}\n"],"mappings":"AAaA,MAAMA,EAAgB,GAA+CC,EAAK,OAAS,oBAE7EC,EAAwB,GAC5BF,EAAaC,CAAI,GAAKA,EAAK,QAAQ,OAAS,WAAaA,EAAK,OAAO,QAAU,WAE3EE,GAAoB,EAAkB,IAC1CC,EAAK,OAAS,4BACbA,EAAK,OAAS,mBAAqBA,EAAK,UAAU,OAAS,cAAgBA,EAAK,SAAS,OAASC,EAKrG,SAAgBC,EAAkB,EAAwB,EAA6B,CACrF,OAAQC,EAAW,IAAI,KACpB,OAAQ,GAAuBL,EAAqBM,CAAqB,CAAC,CAAC,CAC3E,QAAS,GAASP,EAAK,YAAc,CAAC,CAAC,CAAC,CACxC,KAAM,GAASE,EAAiBC,EAAMC,CAAU,CAAC,CACtD,CAMA,SAAgBI,EACd,EACA,EAC4C,CAC5C,MAAQ,IAA2C,CAEjD,GAAIH,EAAkBC,EAAYF,CAAU,EAAG,OAAO,KAEtD,IAAMK,EAAUH,EAAW,IACrBI,EAAWD,EAAQ,KAA4B,OAAQ,GAC3DV,EAAaQ,CAAqB,CACpC,EACMI,EAAiBD,EAAQ,GAAG,EAAE,GAAK,KACnCE,EAAyBF,EAAQ,KAAM,GAAMT,EAAqBM,CAAC,CAAC,GAAK,KAE/E,GAAIK,EAAwB,CAI1B,GADEA,EAAuB,YAAY,KAAM,GAAMC,EAAE,OAAS,0BAA0B,GAAK,GACzE,OAAO,KAIzB,IAAMC,GADmBF,EAAuB,YAAc,CAAC,EAAA,CAAG,OAAQ,GAAMC,EAAE,OAAS,iBACvD,CAAC,CAAC,GAAG,EAAE,EAC3C,GAAIC,EAAe,OAAOC,EAAM,gBAAgBD,EAAwB,KAAKV,GAAY,EAGzF,IAAMY,EAAaV,EAAW,QAAQM,CAA+B,EACrE,OAAOG,EAAM,YAAYH,EAAiCI,EAAW,QAAQ,YAAa,KAAKZ,EAAW,GAAG,CAAC,CAChH,CAGA,IAAMa,EAAY,YAAYb,EAAW,oBACzC,GAAIO,EAAgB,OAAOI,EAAM,gBAAgBJ,EAAyB,KAAKM,GAAW,EAE1F,IAAMC,EAAYT,EAAQ,KAAK,GAE/B,OADIS,EAAkBH,EAAM,iBAAiBG,EAAW,GAAGD,EAAU,GAAG,EACjEF,EAAM,sBAAsB,CAAC,EAAG,CAAC,EAAG,GAAGE,EAAU,GAAG,CAC7D,CACF
|
|
1
|
+
{"version":3,"file":"import-fixer.js","names":["isImportDecl","node","isFunctypeImportDecl","specifierMatches","spec","symbolName","hasFunctypeSymbol","sourceCode","n","createImportFixer","program","imports","lastImportNode","existingFunctypeImport","s","lastSpecifier","fixer","importText","newImport","firstNode"],"sources":["../../src/utils/import-fixer.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\nimport type { SourceCode } from \"eslint\"\n\ntype ImportSpec = {\n type: string\n imported?: { type: string; name: string }\n}\ntype ImportNode = {\n type: \"ImportDeclaration\"\n source: { type: string; value: string }\n specifiers?: readonly ImportSpec[]\n}\n\nconst isImportDecl = (node: { type: string }): node is ImportNode => node.type === \"ImportDeclaration\"\n\nconst isFunctypeImportDecl = (node: { type: string }): node is ImportNode =>\n isImportDecl(node) && node.source?.type === \"Literal\" && node.source.value === \"functype\"\n\nconst specifierMatches = (spec: ImportSpec, symbolName: string): boolean =>\n spec.type === \"ImportNamespaceSpecifier\" ||\n (spec.type === \"ImportSpecifier\" && spec.imported?.type === \"Identifier\" && spec.imported.name === symbolName)\n\n/**\n * Check if a given symbol is already imported from functype\n */\nexport function hasFunctypeSymbol(sourceCode: SourceCode, symbolName: string): boolean {\n return (sourceCode.ast.body as readonly unknown[])\n .filter((n): n is ImportNode => isFunctypeImportDecl(n as { type: string }))\n .flatMap((node) => node.specifiers ?? [])\n .some((spec) => specifierMatches(spec, symbolName))\n}\n\n/**\n * Create a fixer function that adds a symbol to the functype import.\n * Returns a factory compatible with ESLint suggest[].fix signature.\n */\nexport function createImportFixer(\n sourceCode: SourceCode,\n symbolName: string,\n): (fixer: Rule.RuleFixer) => Rule.Fix | null {\n return (fixer: Rule.RuleFixer): Rule.Fix | null => {\n // Already imported — nothing to do.\n if (hasFunctypeSymbol(sourceCode, symbolName)) return null\n\n const program = sourceCode.ast\n const imports = (program.body as readonly unknown[]).filter((n): n is ImportNode =>\n isImportDecl(n as { type: string }),\n )\n const lastImportNode = imports.at(-1) ?? null\n const existingFunctypeImport = imports.find((n) => isFunctypeImportDecl(n)) ?? null\n\n if (existingFunctypeImport) {\n // Namespace import (`import * as F from \"functype\"`) — can't add named.\n const hasNamespace =\n existingFunctypeImport.specifiers?.some((s) => s.type === \"ImportNamespaceSpecifier\") ?? false\n if (hasNamespace) return null\n\n // Append after the last named specifier if one exists.\n const namedSpecifiers = (existingFunctypeImport.specifiers ?? []).filter((s) => s.type === \"ImportSpecifier\")\n const lastSpecifier = namedSpecifiers.at(-1)\n if (lastSpecifier) return fixer.insertTextAfter(lastSpecifier as never, `, ${symbolName}`)\n\n // No named specifiers — fill the empty braces.\n const importText = sourceCode.getText(existingFunctypeImport as never)\n return fixer.replaceText(existingFunctypeImport as never, importText.replace(/\\{(\\s*)\\}/, `{ ${symbolName} }`))\n }\n\n // No existing functype import — insert a new one.\n const newImport = `import { ${symbolName} } from \"functype\"`\n if (lastImportNode) return fixer.insertTextAfter(lastImportNode as never, `\\n${newImport}`)\n\n const firstNode = program.body[0]\n if (firstNode) return fixer.insertTextBefore(firstNode, `${newImport}\\n`)\n return fixer.insertTextBeforeRange([0, 0], `${newImport}\\n`)\n }\n}\n"],"mappings":"AAaA,MAAMA,EAAgB,GAA+CC,EAAK,OAAS,oBAE7EC,EAAwB,GAC5BF,EAAaC,CAAI,GAAKA,EAAK,QAAQ,OAAS,WAAaA,EAAK,OAAO,QAAU,WAE3EE,GAAoB,EAAkB,IAC1CC,EAAK,OAAS,4BACbA,EAAK,OAAS,mBAAqBA,EAAK,UAAU,OAAS,cAAgBA,EAAK,SAAS,OAASC,EAKrG,SAAgBC,EAAkB,EAAwB,EAA6B,CACrF,OAAQC,EAAW,IAAI,KACpB,OAAQ,GAAuBL,EAAqBM,CAAqB,CAAC,CAAC,CAC3E,QAAS,GAASP,EAAK,YAAc,CAAC,CAAC,CAAC,CACxC,KAAM,GAASE,EAAiBC,EAAMC,CAAU,CAAC,CACtD,CAMA,SAAgBI,EACd,EACA,EAC4C,CAC5C,MAAQ,IAA2C,CAEjD,GAAIH,EAAkBC,EAAYF,CAAU,EAAG,OAAO,KAEtD,IAAMK,EAAUH,EAAW,IACrBI,EAAWD,EAAQ,KAA4B,OAAQ,GAC3DV,EAAaQ,CAAqB,CACpC,EACMI,EAAiBD,EAAQ,GAAG,EAAE,GAAK,KACnCE,EAAyBF,EAAQ,KAAM,GAAMT,EAAqBM,CAAC,CAAC,GAAK,KAE/E,GAAIK,EAAwB,CAI1B,GADEA,EAAuB,YAAY,KAAM,GAAMC,EAAE,OAAS,0BAA0B,GAAK,GACzE,OAAO,KAIzB,IAAMC,GADmBF,EAAuB,YAAc,CAAC,EAAA,CAAG,OAAQ,GAAMC,EAAE,OAAS,iBACvD,CAAC,CAAC,GAAG,EAAE,EAC3C,GAAIC,EAAe,OAAOC,EAAM,gBAAgBD,EAAwB,KAAKV,GAAY,EAGzF,IAAMY,EAAaV,EAAW,QAAQM,CAA+B,EACrE,OAAOG,EAAM,YAAYH,EAAiCI,EAAW,QAAQ,YAAa,KAAKZ,EAAW,GAAG,CAAC,CAChH,CAGA,IAAMa,EAAY,YAAYb,EAAW,oBACzC,GAAIO,EAAgB,OAAOI,EAAM,gBAAgBJ,EAAyB,KAAKM,GAAW,EAE1F,IAAMC,EAAYT,EAAQ,KAAK,GAE/B,OADIS,EAAkBH,EAAM,iBAAiBG,EAAW,GAAGD,EAAU,GAAG,EACjEF,EAAM,sBAAsB,CAAC,EAAG,CAAC,EAAG,GAAGE,EAAU,GAAG,CAC7D,CACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ASTNode } from "../types/ast.js";
|
|
2
2
|
import { SourceCode } from "eslint";
|
|
3
|
+
//#region src/utils/mutable-collection.d.ts
|
|
3
4
|
/**
|
|
4
5
|
* Detects a native Set/Map that the code mutates on purpose — a cache, a registry, an in-place
|
|
5
6
|
* accumulator, a React copy-then-add. functype's collections are immutable, so they cannot express
|
|
@@ -25,4 +26,5 @@ export declare const isMutatedCollection: (newExpr: ASTNode, mutators: ReadonlyA
|
|
|
25
26
|
* constructor parameter property (`constructor(private s: Set<T>)`).
|
|
26
27
|
*/
|
|
27
28
|
export declare const annotatesMutatedBinding: (typeRef: ASTNode, mutators: ReadonlyArray<string>, sourceCode: SourceCode) => boolean;
|
|
29
|
+
//#endregion
|
|
28
30
|
//# sourceMappingURL=mutable-collection.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutable-collection.js","names":["SET_MUTATORS","MAP_MUTATORS","isMutatorCallOn","parent","expr","mutators","fieldName","key","enclosingClassBody","node","isFieldMutated","body","descendants","n","name","resolveVariable","lookup","scope","sourceCode","isNameMutated","identifier","ref","isIdentifierBindingMutated","owner","isBindingMutated","target","binding","value","isMutatedCollection","newExpr","annotatesMutatedBinding","annotation","typeRef"],"sources":["../../src/utils/mutable-collection.ts"],"sourcesContent":["import type { Scope, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { descendants } from \"./ast-walk\"\n\n/**\n * Detects a native Set/Map that the code mutates on purpose — a cache, a registry, an in-place\n * accumulator, a React copy-then-add. functype's collections are immutable, so they cannot express\n * these, and a rule that suggests them there is noise (#324).\n *\n * Mutation means a call of one of `mutators` on the collection itself:\n * - directly on a `new` expression that copies something (`new Set(prev).add(id)`) — an empty\n * `new Map().set(a, 1).set(b, 2)` is a builder, a `Map.of` candidate, and is NOT exempt;\n * - through the variable, parameter or later-assigned `let` it is bound to;\n * - through `this.<field>` in the owning class (field initializer, constructor assignment, or\n * constructor parameter property).\n *\n * Not followed: aliases (`const t = s; t.add(x)`), `useRef(new Set()).current.add(x)`, a mutator\n * passed as a callback (`xs.forEach(seen.add, seen)`), and a collection passed into another function.\n */\n\nexport const SET_MUTATORS: ReadonlyArray<string> = [\"add\", \"delete\", \"clear\"]\nexport const MAP_MUTATORS: ReadonlyArray<string> = [\"set\", \"delete\", \"clear\"]\n\n/** `expr.add(...)` / `expr!.add(...)` — `expr` is the object of a called mutator member. */\nconst isMutatorCallOn = (expr: ASTNode, mutators: ReadonlyArray<string>): boolean => {\n const parent = expr.parent\n if (parent?.type === \"TSNonNullExpression\" && parent.expression === expr) return isMutatorCallOn(parent, mutators)\n return (\n parent?.type === \"MemberExpression\" &&\n parent.object === expr &&\n !parent.computed &&\n parent.property.type === \"Identifier\" &&\n mutators.includes(parent.property.name) &&\n parent.parent?.type === \"CallExpression\" &&\n parent.parent.callee === parent\n )\n}\n\n/** The field name for `foo` / `#foo` keys, matching how `this.foo` / `this.#foo` spell it. */\nconst fieldName = (key: ASTNode): string | null =>\n key?.type === \"Identifier\" ? key.name : key?.type === \"PrivateIdentifier\" ? `#${key.name}` : null\n\nconst enclosingClassBody = (node: ASTNode): ASTNode | null =>\n node === null || node === undefined ? null : node.type === \"ClassBody\" ? node : enclosingClassBody(node.parent)\n\n/** Is `this.<name>` mutated anywhere in the class that contains `node`? */\nconst isFieldMutated = (node: ASTNode, name: string, mutators: ReadonlyArray<string>): boolean => {\n const body = enclosingClassBody(node)\n if (body === null) return false\n return descendants(body).some(\n (n) =>\n n.type === \"MemberExpression\" &&\n n.object.type === \"ThisExpression\" &&\n !n.computed &&\n fieldName(n.property) === name &&\n isMutatorCallOn(n, mutators),\n )\n}\n\n/** Lexical lookup of `name` from the scope that contains `node`. */\nconst resolveVariable = (node: ASTNode, name: string, sourceCode: SourceCode): Scope.Variable | null => {\n const lookup = (scope: Scope.Scope | null): Scope.Variable | null =>\n scope === null ? null : (scope.set.get(name) ?? lookup(scope.upper))\n return lookup(sourceCode.getScope(node))\n}\n\n/** Is any reference to the variable named by `identifier` the object of a mutator call? */\nconst isNameMutated = (identifier: ASTNode, mutators: ReadonlyArray<string>, sourceCode: SourceCode): boolean =>\n resolveVariable(identifier, identifier.name, sourceCode)?.references.some((ref) =>\n isMutatorCallOn(ref.identifier, mutators),\n ) ?? false\n\n/**\n * Is the binding identified by `identifier` mutated? A constructor parameter property is a class\n * field; any other identifier is a variable or parameter.\n */\nconst isIdentifierBindingMutated = (\n identifier: ASTNode,\n mutators: ReadonlyArray<string>,\n sourceCode: SourceCode,\n): boolean => {\n const owner = identifier.parent?.type === \"AssignmentPattern\" ? identifier.parent.parent : identifier.parent\n return owner?.type === \"TSParameterProperty\"\n ? isFieldMutated(owner, identifier.name, mutators)\n : isNameMutated(identifier, mutators, sourceCode)\n}\n\n/** Is the binding that `value` initializes or is assigned to mutated? */\nconst isBindingMutated = (\n binding: ASTNode,\n value: ASTNode,\n mutators: ReadonlyArray<string>,\n sourceCode: SourceCode,\n): boolean => {\n // `const s = new Set()` / `s = new Set()` / `(s = new Set()) =>` / `constructor(private s = new Set())`\n const target =\n binding?.type === \"VariableDeclarator\"\n ? binding.id\n : binding?.type === \"AssignmentExpression\" || binding?.type === \"AssignmentPattern\"\n ? binding.right === value\n ? binding.left\n : null\n : null\n if (target?.type === \"Identifier\") return isIdentifierBindingMutated(target, mutators, sourceCode)\n if (target?.type === \"MemberExpression\" && target.object.type === \"ThisExpression\") {\n const name = fieldName(target.property)\n return name !== null && isFieldMutated(binding, name, mutators)\n }\n if (binding?.type === \"PropertyDefinition\" && binding.value === value) {\n const name = fieldName(binding.key)\n return name !== null && isFieldMutated(binding, name, mutators)\n }\n return false\n}\n\n/** `new Set(...)` / `new Map(...)` that is mutated, directly or through what it is bound to. */\nexport const isMutatedCollection = (\n newExpr: ASTNode,\n mutators: ReadonlyArray<string>,\n sourceCode: SourceCode,\n): boolean =>\n (newExpr.arguments.length > 0 && isMutatorCallOn(newExpr, mutators)) ||\n isBindingMutated(newExpr.parent, newExpr, mutators, sourceCode)\n\n/**\n * A `Set<T>` / `Map<K, V>` type reference annotating a binding that is mutated — a variable\n * (`let s: Set<T>`), a parameter (`(s: Set<T>) =>`), a class field (`private s: Set<T>`), or a\n * constructor parameter property (`constructor(private s: Set<T>)`).\n */\nexport const annotatesMutatedBinding = (\n typeRef: ASTNode,\n mutators: ReadonlyArray<string>,\n sourceCode: SourceCode,\n): boolean => {\n const annotation = typeRef.parent\n if (annotation?.type !== \"TSTypeAnnotation\" || annotation.typeAnnotation !== typeRef) return false\n const owner = annotation.parent\n if (owner?.type === \"Identifier\") return isIdentifierBindingMutated(owner, mutators, sourceCode)\n if (owner?.type === \"PropertyDefinition\") {\n const name = fieldName(owner.key)\n return name !== null && isFieldMutated(owner, name, mutators)\n }\n return false\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"mutable-collection.js","names":["SET_MUTATORS","MAP_MUTATORS","isMutatorCallOn","parent","expr","mutators","fieldName","key","enclosingClassBody","node","isFieldMutated","body","descendants","n","name","resolveVariable","lookup","scope","sourceCode","isNameMutated","identifier","ref","isIdentifierBindingMutated","owner","isBindingMutated","target","binding","value","isMutatedCollection","newExpr","annotatesMutatedBinding","annotation","typeRef"],"sources":["../../src/utils/mutable-collection.ts"],"sourcesContent":["import type { Scope, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { descendants } from \"./ast-walk\"\n\n/**\n * Detects a native Set/Map that the code mutates on purpose — a cache, a registry, an in-place\n * accumulator, a React copy-then-add. functype's collections are immutable, so they cannot express\n * these, and a rule that suggests them there is noise (#324).\n *\n * Mutation means a call of one of `mutators` on the collection itself:\n * - directly on a `new` expression that copies something (`new Set(prev).add(id)`) — an empty\n * `new Map().set(a, 1).set(b, 2)` is a builder, a `Map.of` candidate, and is NOT exempt;\n * - through the variable, parameter or later-assigned `let` it is bound to;\n * - through `this.<field>` in the owning class (field initializer, constructor assignment, or\n * constructor parameter property).\n *\n * Not followed: aliases (`const t = s; t.add(x)`), `useRef(new Set()).current.add(x)`, a mutator\n * passed as a callback (`xs.forEach(seen.add, seen)`), and a collection passed into another function.\n */\n\nexport const SET_MUTATORS: ReadonlyArray<string> = [\"add\", \"delete\", \"clear\"]\nexport const MAP_MUTATORS: ReadonlyArray<string> = [\"set\", \"delete\", \"clear\"]\n\n/** `expr.add(...)` / `expr!.add(...)` — `expr` is the object of a called mutator member. */\nconst isMutatorCallOn = (expr: ASTNode, mutators: ReadonlyArray<string>): boolean => {\n const parent = expr.parent\n if (parent?.type === \"TSNonNullExpression\" && parent.expression === expr) return isMutatorCallOn(parent, mutators)\n return (\n parent?.type === \"MemberExpression\" &&\n parent.object === expr &&\n !parent.computed &&\n parent.property.type === \"Identifier\" &&\n mutators.includes(parent.property.name) &&\n parent.parent?.type === \"CallExpression\" &&\n parent.parent.callee === parent\n )\n}\n\n/** The field name for `foo` / `#foo` keys, matching how `this.foo` / `this.#foo` spell it. */\nconst fieldName = (key: ASTNode): string | null =>\n key?.type === \"Identifier\" ? key.name : key?.type === \"PrivateIdentifier\" ? `#${key.name}` : null\n\nconst enclosingClassBody = (node: ASTNode): ASTNode | null =>\n node === null || node === undefined ? null : node.type === \"ClassBody\" ? node : enclosingClassBody(node.parent)\n\n/** Is `this.<name>` mutated anywhere in the class that contains `node`? */\nconst isFieldMutated = (node: ASTNode, name: string, mutators: ReadonlyArray<string>): boolean => {\n const body = enclosingClassBody(node)\n if (body === null) return false\n return descendants(body).some(\n (n) =>\n n.type === \"MemberExpression\" &&\n n.object.type === \"ThisExpression\" &&\n !n.computed &&\n fieldName(n.property) === name &&\n isMutatorCallOn(n, mutators),\n )\n}\n\n/** Lexical lookup of `name` from the scope that contains `node`. */\nconst resolveVariable = (node: ASTNode, name: string, sourceCode: SourceCode): Scope.Variable | null => {\n const lookup = (scope: Scope.Scope | null): Scope.Variable | null =>\n scope === null ? null : (scope.set.get(name) ?? lookup(scope.upper))\n return lookup(sourceCode.getScope(node))\n}\n\n/** Is any reference to the variable named by `identifier` the object of a mutator call? */\nconst isNameMutated = (identifier: ASTNode, mutators: ReadonlyArray<string>, sourceCode: SourceCode): boolean =>\n resolveVariable(identifier, identifier.name, sourceCode)?.references.some((ref) =>\n isMutatorCallOn(ref.identifier, mutators),\n ) ?? false\n\n/**\n * Is the binding identified by `identifier` mutated? A constructor parameter property is a class\n * field; any other identifier is a variable or parameter.\n */\nconst isIdentifierBindingMutated = (\n identifier: ASTNode,\n mutators: ReadonlyArray<string>,\n sourceCode: SourceCode,\n): boolean => {\n const owner = identifier.parent?.type === \"AssignmentPattern\" ? identifier.parent.parent : identifier.parent\n return owner?.type === \"TSParameterProperty\"\n ? isFieldMutated(owner, identifier.name, mutators)\n : isNameMutated(identifier, mutators, sourceCode)\n}\n\n/** Is the binding that `value` initializes or is assigned to mutated? */\nconst isBindingMutated = (\n binding: ASTNode,\n value: ASTNode,\n mutators: ReadonlyArray<string>,\n sourceCode: SourceCode,\n): boolean => {\n // `const s = new Set()` / `s = new Set()` / `(s = new Set()) =>` / `constructor(private s = new Set())`\n const target =\n binding?.type === \"VariableDeclarator\"\n ? binding.id\n : binding?.type === \"AssignmentExpression\" || binding?.type === \"AssignmentPattern\"\n ? binding.right === value\n ? binding.left\n : null\n : null\n if (target?.type === \"Identifier\") return isIdentifierBindingMutated(target, mutators, sourceCode)\n if (target?.type === \"MemberExpression\" && target.object.type === \"ThisExpression\") {\n const name = fieldName(target.property)\n return name !== null && isFieldMutated(binding, name, mutators)\n }\n if (binding?.type === \"PropertyDefinition\" && binding.value === value) {\n const name = fieldName(binding.key)\n return name !== null && isFieldMutated(binding, name, mutators)\n }\n return false\n}\n\n/** `new Set(...)` / `new Map(...)` that is mutated, directly or through what it is bound to. */\nexport const isMutatedCollection = (\n newExpr: ASTNode,\n mutators: ReadonlyArray<string>,\n sourceCode: SourceCode,\n): boolean =>\n (newExpr.arguments.length > 0 && isMutatorCallOn(newExpr, mutators)) ||\n isBindingMutated(newExpr.parent, newExpr, mutators, sourceCode)\n\n/**\n * A `Set<T>` / `Map<K, V>` type reference annotating a binding that is mutated — a variable\n * (`let s: Set<T>`), a parameter (`(s: Set<T>) =>`), a class field (`private s: Set<T>`), or a\n * constructor parameter property (`constructor(private s: Set<T>)`).\n */\nexport const annotatesMutatedBinding = (\n typeRef: ASTNode,\n mutators: ReadonlyArray<string>,\n sourceCode: SourceCode,\n): boolean => {\n const annotation = typeRef.parent\n if (annotation?.type !== \"TSTypeAnnotation\" || annotation.typeAnnotation !== typeRef) return false\n const owner = annotation.parent\n if (owner?.type === \"Identifier\") return isIdentifierBindingMutated(owner, mutators, sourceCode)\n if (owner?.type === \"PropertyDefinition\") {\n const name = fieldName(owner.key)\n return name !== null && isFieldMutated(owner, name, mutators)\n }\n return false\n}\n"],"mappings":"4CAqBA,MAAaA,EAAsC,CAAC,MAAO,SAAU,OAAO,EAC/DC,EAAsC,CAAC,MAAO,SAAU,OAAO,EAGtEC,GAAmB,EAAe,IAA6C,CACnF,IAAMC,EAASC,EAAK,OAEpB,OADID,GAAQ,OAAS,uBAAyBA,EAAO,aAAeC,EAAaF,EAAgBC,EAAQE,CAAQ,EAE/GF,GAAQ,OAAS,oBACjBA,EAAO,SAAWC,GAClB,CAACD,EAAO,UACRA,EAAO,SAAS,OAAS,cACzBE,EAAS,SAASF,EAAO,SAAS,IAAI,GACtCA,EAAO,QAAQ,OAAS,kBACxBA,EAAO,O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EAAUa,CAAU,EACjG,GAAIO,GAAQ,OAAS,oBAAsBA,EAAO,OAAO,OAAS,iBAAkB,CAClF,IAAMX,EAAOR,EAAUmB,EAAO,QAAQ,EACtC,OAAOX,IAAS,MAAQJ,EAAegB,EAASZ,EAAMT,CAAQ,CAChE,CACA,GAAIqB,GAAS,OAAS,sBAAwBA,EAAQ,QAAUC,EAAO,CACrE,IAAMb,EAAOR,EAAUoB,EAAQ,GAAG,EAClC,OAAOZ,IAAS,MAAQJ,EAAegB,EAASZ,EAAMT,CAAQ,CAChE,CACA,MAAO,EACT,EAGauB,GACX,EACA,EACA,IAECC,EAAQ,UAAU,OAAS,GAAK3B,EAAgB2B,EAASxB,CAAQ,GAClEmB,EAAiBK,EAAQ,OAAQA,EAASxB,EAAUa,CAAU,EAOnDY,GACX,EACA,EACA,IACY,CACZ,IAAMC,EAAaC,EAAQ,OAC3B,GAAID,GAAY,OAAS,oBAAsBA,EAAW,iBAAmBC,EAAS,MAAO,GAC7F,IAAMT,EAAQQ,EAAW,OACzB,GAAIR,GAAO,OAAS,aAAc,OAAOD,EAA2BC,EAAOlB,EAAUa,CAAU,EAC/F,GAAIK,GAAO,OAAS,qBAAsB,CACxC,IAAMT,EAAOR,EAAUiB,EAAM,GAAG,EAChC,OAAOT,IAAS,MAAQJ,EAAea,EAAOT,EAAMT,CAAQ,CAC9D,CACA,MAAO,EACT"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ASTNode } from "../types/ast.js";
|
|
2
|
+
//#region src/utils/react-render.d.ts
|
|
2
3
|
/** The nearest function enclosing `node`, or null at the top level. */
|
|
3
4
|
export declare const enclosingFunction: (node: ASTNode) => ASTNode | null;
|
|
4
5
|
export declare const isJSX: (node: ASTNode) => boolean;
|
|
@@ -10,4 +11,5 @@ export type RenderKind = "component" | "hook";
|
|
|
10
11
|
* candidate node (an unwrap, a predicate call), so the JSX scan over the body stays rare.
|
|
11
12
|
*/
|
|
12
13
|
export declare const renderKind: (fn: ASTNode) => RenderKind | null;
|
|
14
|
+
//#endregion
|
|
13
15
|
//# sourceMappingURL=react-render.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react-render.js","names":["FUNCTION_TYPES","WRAPPERS","isWrapperCall","node","fn","callee","name","enclosingFunction","parent","functionName","holder","isJSX","producesJSX","HOOK_NAME","COMPONENT_NAME","renderKind","descendants"],"sources":["../../src/utils/react-render.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\nimport { descendants } from \"./ast-walk\"\n\n/**\n * Finds the function a node renders in: a React function component or a hook. Syntactic, by the\n * conventions React's own tooling uses (`eslint-plugin-react-hooks`):\n *\n * - a **component** is a function named in PascalCase whose body contains JSX — declared\n * (`function Card() {}`), assigned (`const Card = () => …`) or wrapped (`memo(…)`, `forwardRef(…)`);\n * - a **hook** is a function named `use` + an uppercase letter or digit (`useThing`, `use2D`).\n *\n * Only the function's own body is its render path. A function nested inside it (an event handler, a\n * `useEffect` callback, a `.map` callback) is a separate function: the rules that use this ask for the\n * *nearest* enclosing function, so code in a nested callback is never attributed to the render.\n */\n\nconst FUNCTION_TYPES: ReadonlySet<string> = new Set([\n \"FunctionDeclaration\",\n \"FunctionExpression\",\n \"ArrowFunctionExpression\",\n])\n\n/** `memo(fn)`, `forwardRef(fn)`, `React.memo(fn)`: the wrapped function keeps the variable's name. */\nconst WRAPPERS: ReadonlySet<string> = new Set([\"memo\", \"forwardRef\"])\n\nconst isWrapperCall = (node: ASTNode, fn: ASTNode): boolean => {\n if (node?.type !== \"CallExpression\" || node.arguments[0] !== fn) return false\n const callee = node.callee as ASTNode\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 return name !== null && WRAPPERS.has(name)\n}\n\n/** The nearest function enclosing `node`, or null at the top level. */\nexport const enclosingFunction = (node: ASTNode): ASTNode | null => {\n const parent = node.parent as ASTNode | undefined\n if (!parent) return null\n return FUNCTION_TYPES.has(parent.type) ? parent : enclosingFunction(parent)\n}\n\n/** The name a function is known by: its own id, or the variable it (or its `memo` wrapper) is assigned to. */\nconst functionName = (fn: ASTNode): string | null => {\n if (fn.id?.type === \"Identifier\") return fn.id.name\n const parent = fn.parent as ASTNode | undefined\n const holder = isWrapperCall(parent, fn) ? (parent?.parent as ASTNode | undefined) : parent\n return holder?.type === \"VariableDeclarator\" && holder.id.type === \"Identifier\" ? holder.id.name : null\n}\n\nexport const isJSX = (node: ASTNode): boolean => node?.type === \"JSXElement\" || node?.type === \"JSXFragment\"\n\n/** JSX, or a conditional / logical expression with JSX in a branch: `<A />`, `ok ? <A /> : null`, `ok && <A />`. */\nexport const producesJSX = (node: ASTNode): boolean => {\n if (isJSX(node)) return true\n if (node?.type === \"ConditionalExpression\") return producesJSX(node.consequent) || producesJSX(node.alternate)\n if (node?.type === \"LogicalExpression\") return producesJSX(node.right)\n return false\n}\n\nexport type RenderKind = \"component\" | \"hook\"\n\nconst HOOK_NAME = /^use[A-Z0-9]/\nconst COMPONENT_NAME = /^[A-Z]/\n\n/**\n * Is `fn` a component or a hook, and which? Null for any other function. Rules call this only for a\n * candidate node (an unwrap, a predicate call), so the JSX scan over the body stays rare.\n */\nexport const renderKind = (fn: ASTNode): RenderKind | null => {\n const name = functionName(fn)\n if (name === null) return null\n if (HOOK_NAME.test(name)) return \"hook\"\n return COMPONENT_NAME.test(name) && descendants(fn.body).some(isJSX) ? \"component\" : null\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"react-render.js","names":["FUNCTION_TYPES","WRAPPERS","isWrapperCall","node","fn","callee","name","enclosingFunction","parent","functionName","holder","isJSX","producesJSX","HOOK_NAME","COMPONENT_NAME","renderKind","descendants"],"sources":["../../src/utils/react-render.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\nimport { descendants } from \"./ast-walk\"\n\n/**\n * Finds the function a node renders in: a React function component or a hook. Syntactic, by the\n * conventions React's own tooling uses (`eslint-plugin-react-hooks`):\n *\n * - a **component** is a function named in PascalCase whose body contains JSX — declared\n * (`function Card() {}`), assigned (`const Card = () => …`) or wrapped (`memo(…)`, `forwardRef(…)`);\n * - a **hook** is a function named `use` + an uppercase letter or digit (`useThing`, `use2D`).\n *\n * Only the function's own body is its render path. A function nested inside it (an event handler, a\n * `useEffect` callback, a `.map` callback) is a separate function: the rules that use this ask for the\n * *nearest* enclosing function, so code in a nested callback is never attributed to the render.\n */\n\nconst FUNCTION_TYPES: ReadonlySet<string> = new Set([\n \"FunctionDeclaration\",\n \"FunctionExpression\",\n \"ArrowFunctionExpression\",\n])\n\n/** `memo(fn)`, `forwardRef(fn)`, `React.memo(fn)`: the wrapped function keeps the variable's name. */\nconst WRAPPERS: ReadonlySet<string> = new Set([\"memo\", \"forwardRef\"])\n\nconst isWrapperCall = (node: ASTNode, fn: ASTNode): boolean => {\n if (node?.type !== \"CallExpression\" || node.arguments[0] !== fn) return false\n const callee = node.callee as ASTNode\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 return name !== null && WRAPPERS.has(name)\n}\n\n/** The nearest function enclosing `node`, or null at the top level. */\nexport const enclosingFunction = (node: ASTNode): ASTNode | null => {\n const parent = node.parent as ASTNode | undefined\n if (!parent) return null\n return FUNCTION_TYPES.has(parent.type) ? parent : enclosingFunction(parent)\n}\n\n/** The name a function is known by: its own id, or the variable it (or its `memo` wrapper) is assigned to. */\nconst functionName = (fn: ASTNode): string | null => {\n if (fn.id?.type === \"Identifier\") return fn.id.name\n const parent = fn.parent as ASTNode | undefined\n const holder = isWrapperCall(parent, fn) ? (parent?.parent as ASTNode | undefined) : parent\n return holder?.type === \"VariableDeclarator\" && holder.id.type === \"Identifier\" ? holder.id.name : null\n}\n\nexport const isJSX = (node: ASTNode): boolean => node?.type === \"JSXElement\" || node?.type === \"JSXFragment\"\n\n/** JSX, or a conditional / logical expression with JSX in a branch: `<A />`, `ok ? <A /> : null`, `ok && <A />`. */\nexport const producesJSX = (node: ASTNode): boolean => {\n if (isJSX(node)) return true\n if (node?.type === \"ConditionalExpression\") return producesJSX(node.consequent) || producesJSX(node.alternate)\n if (node?.type === \"LogicalExpression\") return producesJSX(node.right)\n return false\n}\n\nexport type RenderKind = \"component\" | \"hook\"\n\nconst HOOK_NAME = /^use[A-Z0-9]/\nconst COMPONENT_NAME = /^[A-Z]/\n\n/**\n * Is `fn` a component or a hook, and which? Null for any other function. Rules call this only for a\n * candidate node (an unwrap, a predicate call), so the JSX scan over the body stays rare.\n */\nexport const renderKind = (fn: ASTNode): RenderKind | null => {\n const name = functionName(fn)\n if (name === null) return null\n if (HOOK_NAME.test(name)) return \"hook\"\n return COMPONENT_NAME.test(name) && descendants(fn.body).some(isJSX) ? \"component\" : null\n}\n"],"mappings":"4CAgBA,MAAMA,kBAAsC,IAAI,IAAI,CAClD,sBACA,qBACA,yBACF,CAAC,EAGKC,kBAAgC,IAAI,IAAI,CAAC,OAAQ,YAAY,CAAC,EAE9DC,GAAiB,EAAe,IAAyB,CAC7D,GAAIC,GAAM,OAAS,kBAAoBA,EAAK,UAAU,KAAOC,EAAI,MAAO,GACxE,IAAMC,EAASF,EAAK,OACdG,EACJD,EAAO,OAAS,aACZA,EAAO,KACPA,EAAO,OAAS,oBAAsBA,EAAO,SAAS,OAAS,aAC7DA,EAAO,SAAS,KAChB,KACR,OAAOC,IAAS,MAAQL,EAAS,IAAIK,CAAI,CAC3C,EAGaC,EAAqB,GAAkC,CAClE,IAAMC,EAASL,EAAK,OAEpB,OADKK,EACER,EAAe,IAAIQ,EAAO,IAAI,EAAIA,EAASD,EAAkBC,CAAM,EADtD,IAEtB,EAGMC,EAAgB,GAA+B,CACnD,GAAIL,EAAG,IAAI,OAAS,aAAc,OAAOA,EAAG,GAAG,KAC/C,IAAMI,EAASJ,EAAG,OACZM,EAASR,EAAcM,EAAQJ,CAAE,EAAKI,GAAQ,OAAiCA,EACrF,OAAOE,GAAQ,OAAS,sBAAwBA,EAAO,GAAG,OAAS,aAAeA,EAAO,GAAG,KAAO,IACrG,EAEaC,EAAS,GAA2BR,GAAM,OAAS,cAAgBA,GAAM,OAAS,cAGlFS,EAAe,GACtBD,EAAMR,CAAI,EAAU,GACpBA,GAAM,OAAS,wBAAgCS,EAAYT,EAAK,UAAU,GAAKS,EAAYT,EAAK,SAAS,EACzGA,GAAM,OAAS,qBAA4BS,EAAYT,EAAK,KAAK,EAMjEU,EAAY,eACZC,EAAiB,SAMVC,EAAc,GAAmC,CAC5D,IAAMT,EAAOG,EAAaL,CAAE,EAG5B,OAFIE,IAAS,KAAa,KACtBO,EAAU,KAAKP,CAAI,EAAU,OAC1BQ,EAAe,KAAKR,CAAI,GAAKU,EAAYZ,EAAG,IAAI,CAAC,CAAC,KAAKO,CAAK,EAAI,YAAc,IACvF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readonly-contract.js","names":["FUNCTIONS","isNamed","type","name","typeArgs","isReadonlyContract","readonlyName","annotationOf","node","nearestFunction","flowsIntoReadonlyContract","parent"],"sources":["../../src/utils/readonly-contract.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\n\n/**\n * Does this expression flow straight into a declared native read-only contract (#350)?\n *\n * `prefer-functype-map` / `-set` never report a `ReadonlyMap` / `ReadonlySet` annotation, so they must not\n * report the constructor that annotation requires: when a function is declared to return\n * `ReadonlyMap<K, V>` — typically because a callee's interface takes one — the native `new Map(...)` it\n * returns is the contract, not an oversight. Recognized positions:\n *\n * - `return` in the nearest enclosing function whose declared return type is `R` or `Promise<R>`\n * (a callback nested inside such a function does not inherit its signature);\n * - the expression body of an arrow function with that return type;\n * - the initializer of a variable, class field, or parameter default annotated `R`;\n * - an `as R` / `satisfies R` assertion;\n * and through ternary branches and `??` / `||` / `&&` operands on the way there.\n */\n\nconst FUNCTIONS: ReadonlySet<string> = new Set([\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"])\n\nconst isNamed = (type: ASTNode | undefined, name: string): boolean =>\n type?.type === \"TSTypeReference\" && type.typeName?.type === \"Identifier\" && type.typeName.name === name\n\nconst typeArgs = (type: ASTNode): ReadonlyArray<ASTNode> =>\n (type.typeArguments?.params ?? type.typeParameters?.params ?? []) as ReadonlyArray<ASTNode>\n\n/** `R<…>` or `Promise<R<…>>`. */\nconst isReadonlyContract = (type: ASTNode | undefined, readonlyName: string): boolean =>\n isNamed(type, readonlyName) || (isNamed(type, \"Promise\") && isReadonlyContract(typeArgs(type!)[0], readonlyName))\n\nconst annotationOf = (node: ASTNode | undefined): ASTNode | undefined => node?.typeAnnotation?.typeAnnotation\n\nconst nearestFunction = (node: ASTNode | undefined): ASTNode | undefined =>\n node === undefined || node === null ? undefined : FUNCTIONS.has(node.type) ? node : nearestFunction(node.parent)\n\nexport const flowsIntoReadonlyContract = (node: ASTNode, readonlyName: string): boolean => {\n const parent = node.parent\n if (!parent) return false\n switch (parent.type) {\n case \"ConditionalExpression\":\n return parent.test !== node && flowsIntoReadonlyContract(parent, readonlyName)\n case \"LogicalExpression\":\n return flowsIntoReadonlyContract(parent, readonlyName)\n case \"TSAsExpression\":\n case \"TSSatisfiesExpression\":\n return isReadonlyContract(parent.typeAnnotation, readonlyName) || flowsIntoReadonlyContract(parent, readonlyName)\n case \"ReturnStatement\":\n return isReadonlyContract(nearestFunction(parent)?.returnType?.typeAnnotation, readonlyName)\n case \"ArrowFunctionExpression\":\n return parent.body === node && isReadonlyContract(parent.returnType?.typeAnnotation, readonlyName)\n case \"VariableDeclarator\":\n return parent.init === node && isReadonlyContract(annotationOf(parent.id), readonlyName)\n case \"PropertyDefinition\":\n return parent.value === node && isReadonlyContract(annotationOf(parent), readonlyName)\n case \"AssignmentPattern\":\n return parent.right === node && isReadonlyContract(annotationOf(parent.left), readonlyName)\n default:\n return false\n }\n}\n"],"mappings":"AAkBA,MAAMA,kBAAiC,IAAI,IAAI,CAAC,sBAAuB,qBAAsB,yBAAyB,CAAC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ract.js","names":["FUNCTIONS","isNamed","type","name","typeArgs","isReadonlyContract","readonlyName","annotationOf","node","nearestFunction","flowsIntoReadonlyContract","parent"],"sources":["../../src/utils/readonly-contract.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\n\n/**\n * Does this expression flow straight into a declared native read-only contract (#350)?\n *\n * `prefer-functype-map` / `-set` never report a `ReadonlyMap` / `ReadonlySet` annotation, so they must not\n * report the constructor that annotation requires: when a function is declared to return\n * `ReadonlyMap<K, V>` — typically because a callee's interface takes one — the native `new Map(...)` it\n * returns is the contract, not an oversight. Recognized positions:\n *\n * - `return` in the nearest enclosing function whose declared return type is `R` or `Promise<R>`\n * (a callback nested inside such a function does not inherit its signature);\n * - the expression body of an arrow function with that return type;\n * - the initializer of a variable, class field, or parameter default annotated `R`;\n * - an `as R` / `satisfies R` assertion;\n * and through ternary branches and `??` / `||` / `&&` operands on the way there.\n */\n\nconst FUNCTIONS: ReadonlySet<string> = new Set([\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"])\n\nconst isNamed = (type: ASTNode | undefined, name: string): boolean =>\n type?.type === \"TSTypeReference\" && type.typeName?.type === \"Identifier\" && type.typeName.name === name\n\nconst typeArgs = (type: ASTNode): ReadonlyArray<ASTNode> =>\n (type.typeArguments?.params ?? type.typeParameters?.params ?? []) as ReadonlyArray<ASTNode>\n\n/** `R<…>` or `Promise<R<…>>`. */\nconst isReadonlyContract = (type: ASTNode | undefined, readonlyName: string): boolean =>\n isNamed(type, readonlyName) || (isNamed(type, \"Promise\") && isReadonlyContract(typeArgs(type!)[0], readonlyName))\n\nconst annotationOf = (node: ASTNode | undefined): ASTNode | undefined => node?.typeAnnotation?.typeAnnotation\n\nconst nearestFunction = (node: ASTNode | undefined): ASTNode | undefined =>\n node === undefined || node === null ? undefined : FUNCTIONS.has(node.type) ? node : nearestFunction(node.parent)\n\nexport const flowsIntoReadonlyContract = (node: ASTNode, readonlyName: string): boolean => {\n const parent = node.parent\n if (!parent) return false\n switch (parent.type) {\n case \"ConditionalExpression\":\n return parent.test !== node && flowsIntoReadonlyContract(parent, readonlyName)\n case \"LogicalExpression\":\n return flowsIntoReadonlyContract(parent, readonlyName)\n case \"TSAsExpression\":\n case \"TSSatisfiesExpression\":\n return isReadonlyContract(parent.typeAnnotation, readonlyName) || flowsIntoReadonlyContract(parent, readonlyName)\n case \"ReturnStatement\":\n return isReadonlyContract(nearestFunction(parent)?.returnType?.typeAnnotation, readonlyName)\n case \"ArrowFunctionExpression\":\n return parent.body === node && isReadonlyContract(parent.returnType?.typeAnnotation, readonlyName)\n case \"VariableDeclarator\":\n return parent.init === node && isReadonlyContract(annotationOf(parent.id), readonlyName)\n case \"PropertyDefinition\":\n return parent.value === node && isReadonlyContract(annotationOf(parent), readonlyName)\n case \"AssignmentPattern\":\n return parent.right === node && isReadonlyContract(annotationOf(parent.left), readonlyName)\n default:\n return false\n }\n}\n"],"mappings":"AAkBA,MAAMA,kBAAiC,IAAI,IAAI,CAAC,sBAAuB,qBAAsB,yBAAyB,CAAC,EAEjHC,GAAW,EAA2B,IAC1CC,GAAM,OAAS,mBAAqBA,EAAK,UAAU,OAAS,cAAgBA,EAAK,SAAS,OAASC,EAE/FC,EAAY,GACfF,EAAK,eAAe,QAAUA,EAAK,gBAAgB,QAAU,CAAC,EAG3DG,GAAsB,EAA2B,IACrDJ,EAAQC,EAAMI,CAAY,GAAML,EAAQC,EAAM,SAAS,GAAKG,EAAmBD,EAASF,CAAK,CAAC,CAAC,GAAII,CAAY,EAE3GC,EAAgB,GAAmDC,GAAM,gBAAgB,eAEzFC,EAAmB,GACvBD,GAA+B,KAAO,IAAA,GAAYR,EAAU,IAAIQ,EAAK,IAAI,EAAIA,EAAOC,EAAgBD,EAAK,MAAM,EAEpGE,GAA6B,EAAe,IAAkC,CACzF,IAAMC,EAASH,EAAK,OACpB,GAAI,CAACG,EAAQ,MAAO,GACpB,OAAQA,EAAO,KAAf,CACE,IAAK,wBACH,OAAOA,EAAO,OAASH,GAAQE,EAA0BC,EAAQL,CAAY,EAC/E,IAAK,oBACH,OAAOI,EAA0BC,EAAQL,CAAY,EACvD,IAAK,iBACL,IAAK,wBACH,OAAOD,EAAmBM,EAAO,eAAgBL,CAAY,GAAKI,EAA0BC,EAAQL,CAAY,EAClH,IAAK,kBACH,OAAOD,EAAmBI,EAAgBE,CAAM,CAAC,EAAE,YAAY,eAAgBL,CAAY,EAC7F,IAAK,0BACH,OAAOK,EAAO,OAASH,GAAQH,EAAmBM,EAAO,YAAY,eAAgBL,CAAY,EACnG,IAAK,qBACH,OAAOK,EAAO,OAASH,GAAQH,EAAmBE,EAAaI,EAAO,EAAE,EAAGL,CAAY,EACzF,IAAK,qBACH,OAAOK,EAAO,QAAUH,GAAQH,EAAmBE,EAAaI,CAAM,EAAGL,CAAY,EACvF,IAAK,oBACH,OAAOK,EAAO,QAAUH,GAAQH,EAAmBE,EAAaI,EAAO,IAAI,EAAGL,CAAY,EAC5F,QACE,MAAO,EACX,CACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ASTNode } from "../types/ast.js";
|
|
2
2
|
import { Rule } from "eslint";
|
|
3
|
+
//#region src/utils/type-aware.d.ts
|
|
3
4
|
/**
|
|
4
5
|
* Is `node`'s type a functype extractable container (Option, Either, Try, Lazy, …)? Structural:
|
|
5
6
|
* the type, after stripping `null` / `undefined`, has both `orThrow` and `fold` — true of every
|
|
@@ -44,4 +45,5 @@ export declare const flowsIntoMutableArraySlot: (node: ASTNode, context: Rule.Ru
|
|
|
44
45
|
export declare const isUntypedExpression: (node: ASTNode, context: Rule.RuleContext) => boolean | undefined;
|
|
45
46
|
/** Is type-aware linting on for this file (`parserOptions.projectService` or `project`)? */
|
|
46
47
|
export declare const hasTypeInformation: (context: Rule.RuleContext) => boolean;
|
|
48
|
+
//#endregion
|
|
47
49
|
//# sourceMappingURL=type-aware.d.ts.map
|