eslint-plugin-functype 2.109.0 → 2.110.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +110 -19
- package/dist/cli/list-rules.js.map +1 -1
- package/dist/configs/recommended.d.ts +21 -5
- package/dist/configs/recommended.js +1 -1
- package/dist/configs/recommended.js.map +1 -1
- package/dist/configs/strict.d.ts +1 -1
- package/dist/configs/strict.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/no-get-unsafe.js.map +1 -1
- package/dist/rules/no-imperative-loops.js +1 -1
- package/dist/rules/no-imperative-loops.js.map +1 -1
- package/dist/rules/no-let.js.map +1 -1
- package/dist/rules/prefer-do-notation.js +1 -1
- package/dist/rules/prefer-do-notation.js.map +1 -1
- package/dist/rules/prefer-either.js +1 -1
- package/dist/rules/prefer-either.js.map +1 -1
- package/dist/rules/prefer-flatmap.js +1 -1
- package/dist/rules/prefer-flatmap.js.map +1 -1
- package/dist/rules/prefer-fold.js +1 -1
- package/dist/rules/prefer-fold.js.map +1 -1
- package/dist/rules/prefer-functype-map.js +1 -1
- package/dist/rules/prefer-functype-map.js.map +1 -1
- package/dist/rules/prefer-functype-set.js +1 -1
- package/dist/rules/prefer-functype-set.js.map +1 -1
- package/dist/rules/prefer-list.js +1 -1
- package/dist/rules/prefer-list.js.map +1 -1
- package/dist/rules/prefer-map.js +1 -1
- package/dist/rules/prefer-map.js.map +1 -1
- package/dist/rules/prefer-option.js +1 -1
- package/dist/rules/prefer-option.js.map +1 -1
- package/dist/rules/prefer-try.js +1 -1
- package/dist/rules/prefer-try.js.map +1 -1
- package/dist/types/ast.d.ts +1 -2
- package/dist/utils/ast-walk.d.ts +12 -0
- package/dist/utils/ast-walk.js +2 -0
- package/dist/utils/ast-walk.js.map +1 -0
- package/dist/utils/async-detection.d.ts +6 -0
- package/dist/utils/async-detection.js +2 -0
- package/dist/utils/async-detection.js.map +1 -0
- package/dist/utils/boundary-tags.d.ts +25 -0
- package/dist/utils/boundary-tags.js +2 -0
- package/dist/utils/boundary-tags.js.map +1 -0
- package/dist/utils/dependency-validator.d.ts +4 -5
- package/dist/utils/dependency-validator.js +1 -1
- package/dist/utils/dependency-validator.js.map +1 -1
- package/dist/utils/functype-detection.d.ts +13 -14
- package/dist/utils/functype-detection.js +1 -1
- package/dist/utils/functype-detection.js.map +1 -1
- package/dist/utils/import-fixer.d.ts +2 -3
- package/dist/utils/import-fixer.js.map +1 -1
- package/dist/utils/mutable-collection.d.ts +30 -0
- package/dist/utils/mutable-collection.js +2 -0
- package/dist/utils/mutable-collection.js.map +1 -0
- package/dist/utils/wire-types.d.ts +21 -0
- package/dist/utils/wire-types.js +2 -0
- package/dist/utils/wire-types.js.map +1 -0
- package/package.json +6 -6
package/dist/rules/prefer-map.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const
|
|
1
|
+
import{containsAwait as e,containsYield as t}from"../utils/async-detection.js";const n=/* @__PURE__ */ new Set([`forEach`,`for`]);function r(e){let t=e?.parent;return t?t.type===`CallExpression`&&t.callee.type===`MemberExpression`&&n.has(t.callee.property.name)?!0:r(t):!1}const i={meta:{type:`suggestion`,docs:{description:`Prefer .map() over manual transformations and imperative patterns`,recommended:!0},fixable:`code`,schema:[{type:`object`,properties:{checkArrayMethods:{type:`boolean`,default:!0},checkForLoops:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{preferMapOverLoop:`Prefer .map() over for loop for transforming {{collection}}`,preferMapOverPush:`Prefer .map() over manual .push() in loop`,preferMapChain:`Consider using .map() for transformation instead of manual property access`}},create(n){let i=n.options[0]||{},a=i.checkArrayMethods!==!1,o=i.checkForLoops===!0;function s(e){if(e.type!==`CallExpression`||e.callee.type!==`MemberExpression`||e.callee.property.name!==`forEach`)return!1;let t=e.arguments[0];return t&&(t.type===`ArrowFunctionExpression`||t.type===`FunctionExpression`)?t.body.type===`MemberExpression`:!1}function c(e){if(!e.body||e.body.type!==`BlockStatement`)return!1;let t=e.body.body;return t.length!==0&&t.some(e=>{if(e.type===`ExpressionStatement`&&e.expression.type===`CallExpression`){let t=e.expression;return t.callee.type===`MemberExpression`&&t.callee.property.name===`push`}return!1})}function l(e){if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`&&e.callee.property.name===`forEach`){let t=e.arguments[0];if(t&&(t.type===`ArrowFunctionExpression`||t.type===`FunctionExpression`)&&t.body.type===`MemberExpression`)return!0}return!1}function u(n){return n.await===!0||e(n.body)||t(n.body)}return{ForStatement(e){o&&c(e)&&!u(e)&&n.report({node:e,messageId:`preferMapOverLoop`,data:{collection:`array`}})},ForInStatement(e){o&&c(e)&&!u(e)&&n.report({node:e,messageId:`preferMapOverLoop`,data:{collection:`object`}})},ForOfStatement(e){o&&c(e)&&!u(e)&&n.report({node:e,messageId:`preferMapOverLoop`,data:{collection:`iterable`}})},CallExpression(e){a&&(e.callee.type===`MemberExpression`&&e.callee.property.name===`forEach`&&l(e)&&n.report({node:e,messageId:`preferMapChain`,fix(t){if(!s(e))return null;let r=n.sourceCode.getText(e).replace(/\.forEach\s*\(/g,`.map(`);return t.replaceText(e,r)}}),e.callee.type===`MemberExpression`&&e.callee.property.name===`push`&&r(e)&&n.report({node:e,messageId:`preferMapOverPush`}))}}}};export{i as default};
|
|
2
2
|
//# sourceMappingURL=prefer-map.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-map.js","names":[],"sources":["../../src/rules/prefer-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\nconst ITERATION_METHOD_NAMES: ReadonlySet<string> = new Set([\"forEach\", \"for\"])\n\n/** True iff any ancestor of `node` is a `.forEach(...)` or `.for(...)` call. */\nfunction insideIterationCallback(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n if (\n parent.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n ITERATION_METHOD_NAMES.has(parent.callee.property.name)\n ) {\n return true\n }\n return insideIterationCallback(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .map() over manual transformations and imperative patterns\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n checkArrayMethods: {\n type: \"boolean\",\n default: true,\n },\n checkForLoops: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferMapOverLoop: \"Prefer .map() over for loop for transforming {{collection}}\",\n preferMapOverPush: \"Prefer .map() over manual .push() in loop\",\n preferMapChain: \"Consider using .map() for transformation instead of manual property access\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const checkArrayMethods = options.checkArrayMethods !== false\n const checkForLoops = options.checkForLoops !== false\n\n function isForEachToMapSafe(node: ASTNode): boolean {\n // Only auto-fix simple forEach → map transformations on expressions that return values\n // This is safe because both native arrays and functype Lists have these methods\n if (\n node.type !== \"CallExpression\" ||\n node.callee.type !== \"MemberExpression\" ||\n node.callee.property.name !== \"forEach\"\n ) {\n return false\n }\n\n // Check if the callback returns a value (simple property access pattern)\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function (e.g., item => item.name)\n return body.type === \"MemberExpression\"\n }\n return false\n }\n\n function isTransformationLoop(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n\n const statements = node.body.body\n if (statements.length === 0) return false\n\n // Look for patterns like: newArray.push(transform(item))\n return statements.some((stmt: ASTNode) => {\n if (stmt.type === \"ExpressionStatement\" && stmt.expression.type === \"CallExpression\") {\n const call = stmt.expression\n return call.callee.type === \"MemberExpression\" && call.callee.property.name === \"push\"\n }\n return false\n })\n }\n\n function isSimplePropertyAccess(node: ASTNode): boolean {\n // Check for patterns like: items.forEach(item => console.log(item.name))\n // These could often be: items.map(item => item.name)\n if (\n node.type === \"CallExpression\" &&\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"forEach\"\n ) {\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function\n if (body.type === \"MemberExpression\") {\n return true\n }\n }\n }\n return false\n }\n\n return {\n ForStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n if (isTransformationLoop(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"array\" },\n })\n }\n },\n\n ForInStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n if (isTransformationLoop(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"object\" },\n })\n }\n },\n\n ForOfStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n if (isTransformationLoop(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"iterable\" },\n })\n }\n },\n\n CallExpression(node: ASTNode) {\n if (!checkArrayMethods) return\n\n // Check for forEach that could be map\n if (node.callee.type === \"MemberExpression\" && node.callee.property.name === \"forEach\") {\n if (isSimplePropertyAccess(node)) {\n context.report({\n node,\n messageId: \"preferMapChain\",\n fix(fixer) {\n // Only auto-fix safe forEach → map transformations\n if (!isForEachToMapSafe(node)) {\n return null\n }\n\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Simple replacement: forEach -> map\n const fixedText = text.replace(/\\.forEach\\s*\\(/g, \".map(\")\n return fixer.replaceText(node, fixedText)\n },\n })\n }\n }\n\n // Check for manual push patterns in callbacks\n if (\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"push\" &&\n insideIterationCallback(node)\n ) {\n context.report({ node, messageId: \"preferMapOverPush\" })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAIA,MAAM,EAA8C,IAAI,IAAI,CAAC,UAAW,KAAK,CAAC,EAG9E,SAAS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,EAAK,OAAS,kBACd,EAAK,OAAO,OAAS,oBACrB,EAAK,OAAO,SAAS,OAAS,UAC9B,CACA,IAAM,EAAW,EAAK,UAAU,GAChC,GAAI,IAAa,EAAS,OAAS,2BAA6B,EAAS,OAAS,uBACnE,EAAS,KAEb,OAAS,mBAChB,MAAO,EAGb,CACA,MAAO,EACT,CAEA,MAAO,CACL,aAAa,EAAe,CACrB,GAED,EAAqB,CAAI,GAC3B,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,WAAY,OAAQ,CAC9B,CAAC,CAEL,EAEA,eAAe,EAAe,CACvB,GAED,EAAqB,CAAI,GAC3B,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,WAAY,QAAS,CAC/B,CAAC,CAEL,EAEA,eAAe,EAAe,CACvB,GAED,EAAqB,CAAI,GAC3B,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,WAAY,UAAW,CACjC,CAAC,CAEL,EAEA,eAAe,EAAe,CACvB,IAGD,EAAK,OAAO,OAAS,oBAAsB,EAAK,OAAO,SAAS,OAAS,WACvE,EAAuB,CAAI,GAC7B,EAAQ,OAAO,CACb,OACA,UAAW,iBACX,IAAI,EAAO,CAET,GAAI,CAAC,EAAmB,CAAI,EAC1B,OAAO,KAOT,IAAM,EAJa,EAAQ,WACH,QAAQ,CAGX,CAAC,CAAC,QAAQ,kBAAmB,OAAO,EACzD,OAAO,EAAM,YAAY,EAAM,CAAS,CAC1C,CACF,CAAC,EAMH,EAAK,OAAO,OAAS,oBACrB,EAAK,OAAO,SAAS,OAAS,QAC9B,EAAwB,CAAI,GAE5B,EAAQ,OAAO,CAAE,OAAM,UAAW,mBAAoB,CAAC,EAE3D,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-map.js","names":["ITERATION_METHOD_NAMES","insideIterationCallback","parent","node","rule","options","context","checkArrayMethods","checkForLoops","isForEachToMapSafe","callback","isTransformationLoop","statements","stmt","call","isSimplePropertyAccess","suspends","containsAwait","containsYield","fixedText","fixer"],"sources":["../../src/rules/prefer-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containsAwait, containsYield } from \"../utils/async-detection\"\n\nconst ITERATION_METHOD_NAMES: ReadonlySet<string> = new Set([\"forEach\", \"for\"])\n\n/** True iff any ancestor of `node` is a `.forEach(...)` or `.for(...)` call. */\nfunction insideIterationCallback(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n if (\n parent.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n ITERATION_METHOD_NAMES.has(parent.callee.property.name)\n ) {\n return true\n }\n return insideIterationCallback(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .map() over manual transformations and imperative patterns\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n checkArrayMethods: {\n type: \"boolean\",\n default: true,\n },\n checkForLoops: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferMapOverLoop: \"Prefer .map() over for loop for transforming {{collection}}\",\n preferMapOverPush: \"Prefer .map() over manual .push() in loop\",\n preferMapChain: \"Consider using .map() for transformation instead of manual property access\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const checkArrayMethods = options.checkArrayMethods !== false\n // Off by default (#325): no-imperative-loops already reports every loop, and reporting the same loop\n // here too doubled each hit. Opt in when no-imperative-loops is disabled.\n const checkForLoops = options.checkForLoops === true\n\n function isForEachToMapSafe(node: ASTNode): boolean {\n // Only auto-fix simple forEach → map transformations on expressions that return values\n // This is safe because both native arrays and functype Lists have these methods\n if (\n node.type !== \"CallExpression\" ||\n node.callee.type !== \"MemberExpression\" ||\n node.callee.property.name !== \"forEach\"\n ) {\n return false\n }\n\n // Check if the callback returns a value (simple property access pattern)\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function (e.g., item => item.name)\n return body.type === \"MemberExpression\"\n }\n return false\n }\n\n function isTransformationLoop(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n\n const statements = node.body.body\n if (statements.length === 0) return false\n\n // Look for patterns like: newArray.push(transform(item))\n return statements.some((stmt: ASTNode) => {\n if (stmt.type === \"ExpressionStatement\" && stmt.expression.type === \"CallExpression\") {\n const call = stmt.expression\n return call.callee.type === \"MemberExpression\" && call.callee.property.name === \"push\"\n }\n return false\n })\n }\n\n function isSimplePropertyAccess(node: ASTNode): boolean {\n // Check for patterns like: items.forEach(item => console.log(item.name))\n // These could often be: items.map(item => item.name)\n if (\n node.type === \"CallExpression\" &&\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"forEach\"\n ) {\n const callback = node.arguments[0]\n if (callback && (callback.type === \"ArrowFunctionExpression\" || callback.type === \"FunctionExpression\")) {\n const body = callback.body\n // Simple property access in arrow function\n if (body.type === \"MemberExpression\") {\n return true\n }\n }\n }\n return false\n }\n\n function suspends(node: ASTNode): boolean {\n return node.await === true || containsAwait(node.body) || containsYield(node.body)\n }\n\n return {\n ForStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"array\" },\n })\n }\n },\n\n ForInStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"object\" },\n })\n }\n },\n\n ForOfStatement(node: ASTNode) {\n if (!checkForLoops) return\n\n // An awaiting loop is a sequential traversal, not a map: `.map` cannot await (#323), and neither a\n // `for await` stream nor a generator's yielding loop has a .map form (#324).\n if (isTransformationLoop(node) && !suspends(node)) {\n context.report({\n node,\n messageId: \"preferMapOverLoop\",\n data: { collection: \"iterable\" },\n })\n }\n },\n\n CallExpression(node: ASTNode) {\n if (!checkArrayMethods) return\n\n // Check for forEach that could be map\n if (node.callee.type === \"MemberExpression\" && node.callee.property.name === \"forEach\") {\n if (isSimplePropertyAccess(node)) {\n context.report({\n node,\n messageId: \"preferMapChain\",\n fix(fixer) {\n // Only auto-fix safe forEach → map transformations\n if (!isForEachToMapSafe(node)) {\n return null\n }\n\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Simple replacement: forEach -> map\n const fixedText = text.replace(/\\.forEach\\s*\\(/g, \".map(\")\n return fixer.replaceText(node, fixedText)\n },\n })\n }\n }\n\n // Check for manual push patterns in callbacks\n if (\n node.callee.type === \"MemberExpression\" &&\n node.callee.property.name === \"push\" &&\n insideIterationCallback(node)\n ) {\n context.report({ node, messageId: \"preferMapOverPush\" })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"+EAKA,MAAMA,kBAA8C,IAAI,IAAI,CAAC,UAAW,KAAK,CAAC,EAG9E,SAASC,EAAwB,EAA2C,CAC1E,IAAMC,EAASC,GAAM,OASrB,OARKD,EAEHA,EAAO,OAAS,kBAChBA,EAAO,OAAO,OAAS,oBACvBF,EAAuB,IAAIE,EAAO,OAAO,SAAS,IAAI,EAE/C,GAEFD,EAAwBC,CAAM,EARjB,EAStB,CAEA,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,KAAM,CACJ,YAAa,oEACb,YAAa,EACf,EACA,QAAS,OACT,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,kBAAmB,CACjB,KAAM,UACN,QAAS,EACX,EACA,cAAe,CACb,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAA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GAIDG,EAAqBR,CAAI,GAAK,CAACa,EAASb,CAAI,GAC9CG,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,WAAY,OAAQ,CAC9B,CAAC,CAEL,EAEA,eAAe,EAAe,CACvBE,GAIDG,EAAqBR,CAAI,GAAK,CAACa,EAASb,CAAI,GAC9CG,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,WAAY,QAAS,CAC/B,CAAC,CAEL,EAEA,eAAe,EAAe,CACvBE,GAIDG,EAAqBR,CAAI,GAAK,CAACa,EAASb,CAAI,GAC9CG,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,WAAY,UAAW,CACjC,CAAC,CAEL,EAEA,eAAe,EAAe,CACvBC,IAGDJ,EAAK,OAAO,OAAS,oBAAsBA,EAAK,OAAO,SAAS,OAAS,WACvEY,EAAuBZ,CAAI,GAC7BG,EAAQ,OAAO,CACb,OACA,UAAW,iBACX,IAAI,EAAO,CAET,GAAI,CAACG,EAAmBN,CAAI,EAC1B,OAAO,KAOT,IAAMgB,EAJab,EAAQ,WACH,QAAQH,CAGX,CAAC,CAAC,QAAQ,kBAAmB,OAAO,EACzD,OAAOiB,EAAM,YAAYjB,EAAMgB,CAAS,CAC1C,CACF,CAAC,EAMHhB,EAAK,OAAO,OAAS,oBACrBA,EAAK,OAAO,SAAS,OAAS,QAC9BF,EAAwBE,CAAI,GAE5BG,EAAQ,OAAO,CAAE,OAAM,UAAW,mBAAoB,CAAC,EAE3D,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getFunctypeImportsLegacy as e,isAlreadyUsingFunctype as t,isFunctypeType as n}from"../utils/functype-detection.js";import{createImportFixer as
|
|
1
|
+
import{getFunctypeImportsLegacy as e,isAlreadyUsingFunctype as t,isFunctypeType as n}from"../utils/functype-detection.js";import{isInsideTaggedDeclaration as r}from"../utils/boundary-tags.js";import{createImportFixer as i,hasFunctypeSymbol as a}from"../utils/import-fixer.js";import{DEFAULT_WIRE_TYPES as o,WIRE_TYPES_SCHEMA as s,isInsideWireType as c}from"../utils/wire-types.js";const l=/* @__PURE__ */ new Set([`useState`,`useRef`]),u={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer Option<T> over nullable types (T | null | undefined)`,recommended:!0},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},wireTypes:s,allowNullableIntersections:{type:`boolean`,default:!1},allowUseState:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferOption:`Prefer Option<{{type}}> over nullable type '{{nullable}}'`,preferOptionReturn:`Prefer Option<{{type}}> as return type over nullable '{{nullable}}'`,suggestOptionType:`Replace with Option<{{type}}>`,suggestAddImport:`Add {{symbol}} import from functype`}},create(s){let u=s.options[0]||{},d=u.wireTypes??o,f=u.allowInteropMarker!==!1,p=e=>f&&r(e,`interop`,s.sourceCode),m=u.allowUseState!==!1;function h(e){let t=e.parent;if(!t)return!1;if(t.type===`TSTypeParameterInstantiation`&&t.parent?.type===`CallExpression`){let e=t.parent.callee,n=e.type===`Identifier`?e.name:e.type===`MemberExpression`&&e.property.type===`Identifier`?e.property.name:null;if(n!==null&&l.has(n))return!0}return h(t)}let g=e(s);return{TSUnionType(e){if(c(e,d)||p(e)||!e.types||e.types.length<2||m&&h(e)||!e.types.some(e=>e.type===`TSNullKeyword`||e.type===`TSUndefinedKeyword`))return;let r=e.types.filter(e=>e.type!==`TSNullKeyword`&&e.type!==`TSUndefinedKeyword`);if(r.length===1){let o=r[0];if(n(o,g)||t(e,g))return;let c=s.sourceCode,l=c.getText(o),u=c.getText(e);if(l.startsWith(`Option<`))return;let d=[{messageId:`suggestOptionType`,data:{type:l},fix(t){return t.replaceText(e,`Option<${l}>`)}}];a(c,`Option`)||d.push({messageId:`suggestAddImport`,data:{symbol:`Option`},fix:i(c,`Option`)}),s.report({node:e,messageId:`preferOption`,data:{type:l,nullable:u},suggest:d})}}}}};export{u as default};
|
|
2
2
|
//# sourceMappingURL=prefer-option.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-option.js","names":[],"sources":["../../src/rules/prefer-option.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype, isFunctypeType } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Option<T> over nullable types (T | null | undefined)\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowNullableIntersections: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferOption: \"Prefer Option<{{type}}> over nullable type '{{nullable}}'\",\n preferOptionReturn: \"Prefer Option<{{type}}> as return type over nullable '{{nullable}}'\",\n suggestOptionType: \"Replace with Option<{{type}}>\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n
|
|
1
|
+
{"version":3,"file":"prefer-option.js","names":["REACT_STATE_HOOKS","rule","WIRE_TYPES_SCHEMA","options","context","wireTypes","DEFAULT_WIRE_TYPES","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","node","allowUseState","isInHookTypeArgument","parent","callee","name","functypeImports","getFunctypeImportsLegacy","isInsideWireType","type","nonNullTypes","nonNullType","isFunctypeType","isAlreadyUsingFunctype","sourceCode","nonNullTypeText","fullType","suggestions","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-option.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype, isFunctypeType } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\n\nconst REACT_STATE_HOOKS: ReadonlySet<string> = new Set([\"useState\", \"useRef\"])\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Option<T> over nullable types (T | null | undefined)\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowNullableIntersections: {\n type: \"boolean\",\n default: false,\n },\n allowUseState: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferOption: \"Prefer Option<{{type}}> over nullable type '{{nullable}}'\",\n preferOptionReturn: \"Prefer Option<{{type}}> as return type over nullable '{{nullable}}'\",\n suggestOptionType: \"Replace with Option<{{type}}>\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // Everything inside `Wire<…>` is the declared serialization shape (#325 B).\n const wireTypes: ReadonlyArray<string> = options.wireTypes ?? DEFAULT_WIRE_TYPES\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n // `null` is idiomatic React state (`useState<User | null>(null)`, `useRef<El | null>(null)`); an\n // Option in a hook's type argument buys nothing and fights the hook's own API (#325).\n const allowUseState = options.allowUseState !== false\n\n /** Is `node` inside the type argument of a `useState` / `useRef` call (bare or `React.`-qualified)? */\n function isInHookTypeArgument(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"TSTypeParameterInstantiation\" && parent.parent?.type === \"CallExpression\") {\n const callee = parent.parent.callee\n const name =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (name !== null && REACT_STATE_HOOKS.has(name)) return true\n }\n return isInHookTypeArgument(parent)\n }\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n return {\n TSUnionType(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (isExemptByMarker(node)) return\n if (!node.types || node.types.length < 2) return\n if (allowUseState && isInHookTypeArgument(node)) return\n\n const hasNull = node.types.some(\n (type: ASTNode) => type.type === \"TSNullKeyword\" || type.type === \"TSUndefinedKeyword\",\n )\n\n if (!hasNull) return\n\n const nonNullTypes = node.types.filter(\n (type: ASTNode) => type.type !== \"TSNullKeyword\" && type.type !== \"TSUndefinedKeyword\",\n )\n\n if (nonNullTypes.length === 1) {\n const nonNullType = nonNullTypes[0]\n\n // Skip if it's already an Option type or other functype type\n if (isFunctypeType(nonNullType, functypeImports)) return\n\n // Skip if we're already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const nonNullTypeText = sourceCode.getText(nonNullType)\n const fullType = sourceCode.getText(node)\n\n // Skip if it's already an Option type (fallback check)\n if (nonNullTypeText.startsWith(\"Option<\")) return\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestOptionType\",\n data: { type: nonNullTypeText },\n fix(fixer) {\n return fixer.replaceText(node, `Option<${nonNullTypeText}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"Option\")) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Option\" },\n fix: createImportFixer(sourceCode, \"Option\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferOption\",\n data: {\n type: nonNullTypeText,\n nullable: fullType,\n },\n suggest: suggestions,\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"6XAQA,MAAMA,kBAAyC,IAA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MAAM,KACxB,GAAkBS,EAAK,OAAS,iBAAmBA,EAAK,OAAS,oBAGzD,EAAG,OAEd,IAAMC,EAAeV,EAAK,MAAM,OAC7B,GAAkBS,EAAK,OAAS,iBAAmBA,EAAK,OAAS,oBACpE,EAEA,GAAIC,EAAa,SAAW,EAAG,CAC7B,IAAMC,EAAcD,EAAa,GAMjC,GAHIE,EAAeD,EAAaL,CAAe,GAG3CO,EAAuBb,EAAMM,CAAe,EAAG,OAEnD,IAAMQ,EAAapB,EAAQ,WACrBqB,EAAkBD,EAAW,QAAQH,CAAW,EAChDK,EAAWF,EAAW,QAAQd,CAAI,EAGxC,GAAIe,EAAgB,WAAW,SAAS,EAAG,OAE3C,IAAME,EAAiD,CACrD,CACE,UAAW,oBACX,KAAM,CAAE,KAAMF,CAAgB,EAC9B,IAAI,EAAO,CACT,OAAOG,EAAM,YAAYlB,EAAM,UAAUe,EAAgB,EAAE,CAC7D,CACF,CACF,EAEKI,EAAkBL,EAAY,QAAQ,GACzCG,EAAY,KAAK,CACf,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKG,EAAkBN,EAAY,QAAQ,CAC7C,CAAC,EAGHpB,EAAQ,OAAO,CACb,OACA,UAAW,eACX,KAAM,CACJ,KAAMqB,EACN,SAAUC,CACZ,EACA,QAASC,CACX,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
package/dist/rules/prefer-try.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createImportFixer as
|
|
1
|
+
import{containsAwait as e}from"../utils/async-detection.js";import{isInsideTaggedDeclaration as t}from"../utils/boundary-tags.js";import{createImportFixer as n,hasFunctypeSymbol as r}from"../utils/import-fixer.js";const i={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer Try for computations that may throw`,recommended:!0},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},allowThrowInTests:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferTryOverTryCatch:`Prefer Try(() => ...) over try/catch block`,preferAsyncTryOverTryCatch:`Prefer Try.fromPromise(...), Either.fromPromise(...) or IO.tryPromise(...) over an async try/catch — Try(() => ...) cannot catch an awaited rejection`,suggestTry:`Replace with Try(() => ...)`,suggestTryFromPromise:`Replace with Try.fromPromise(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(i){let a=i.options[0]||{},o=a.allowInteropMarker!==!1,s=e=>o&&t(e,`interop`,i.sourceCode),c=a.allowThrowInTests!==!1;function l(){let e=i.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function u(e){return e.block?.body?.length===1}function d(e){if(!e.handler?.body)return!1;let t=e.handler.body.body;return t.length===0||t.length===1&&(t[0].type===`ReturnStatement`||t[0].type===`ExpressionStatement`)}function f(e){let t=e.block.body[0];return t.type===`ReturnStatement`&&t.argument?.type===`AwaitExpression`||t.type===`ExpressionStatement`&&t.expression?.type===`AwaitExpression`}return{TryStatement(t){if(s(t)||t.finalizer||c&&l()||t.handler&&t.handler.body&&t.handler.body.body.some(e=>e.type===`ThrowStatement`))return;let a=i.sourceCode,o=[];if(u(t)&&d(t)){let e=t.block.body[0];if(e.type===`ReturnStatement`){let i=e.argument,s=a.getText(i);if(f(t)){let e=i.type===`AwaitExpression`?i.argument:i,n=a.getText(e);o.push({messageId:`suggestTryFromPromise`,fix(e){return e.replaceText(t,`return Try.fromPromise(${n})`)}})}else o.push({messageId:`suggestTry`,fix(e){return e.replaceText(t,`return Try(() => ${s})`)}});r(a,`Try`)||o.push({messageId:`suggestAddImport`,data:{symbol:`Try`},fix:n(a,`Try`)})}}i.report({node:t,messageId:e(t.block)?`preferAsyncTryOverTryCatch`:`preferTryOverTryCatch`,suggest:o})}}}};export{i as default};
|
|
2
2
|
//# sourceMappingURL=prefer-try.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-try.js","names":[],"sources":["../../src/rules/prefer-try.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Try for computations that may throw\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferTryOverTryCatch: \"Prefer Try(() => ...) over try/catch block\",\n suggestTry: \"Replace with Try(() => ...)\",\n suggestTryFromPromise: \"Replace with Try.fromPromise(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowThrowInTests = options.allowThrowInTests !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function isSimpleTryBody(node: ASTNode): boolean {\n return node.block?.body?.length === 1\n }\n\n function isSimpleCatch(node: ASTNode): boolean {\n if (!node.handler?.body) return false\n const catchBody = node.handler.body.body\n return (\n catchBody.length === 0 ||\n (catchBody.length === 1 &&\n (catchBody[0].type === \"ReturnStatement\" || catchBody[0].type === \"ExpressionStatement\"))\n )\n }\n\n function tryBodyHasAwait(node: ASTNode): boolean {\n const stmt = node.block.body[0]\n if (stmt.type === \"ReturnStatement\" && stmt.argument?.type === \"AwaitExpression\") return true\n if (stmt.type === \"ExpressionStatement\" && stmt.expression?.type === \"AwaitExpression\") return true\n return false\n }\n\n return {\n TryStatement(node: ASTNode) {\n // Try cannot model `finally` — bail on any try statement with a finalizer.\n // Covers two bugs: (1) catch-less try/finally fires a misleading warning\n // with no useful autofix; (2) try/catch/finally autofix would lift the\n // catch into Try(() => …) and silently drop the finally clause. The FP\n // primitive for guaranteed cleanup is IO.bracket, on the lazy IO type.\n // See #206.\n if (node.finalizer) return\n\n // Allow try/catch in test files\n if (allowThrowInTests && isInTestFile()) return\n\n // Allow try/catch that re-throws in the catch block (even with logging)\n if (node.handler && node.handler.body) {\n const catchBody = node.handler.body.body\n const hasRethrow = catchBody.some((stmt: ASTNode) => stmt.type === \"ThrowStatement\")\n if (hasRethrow) return\n }\n\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isSimpleTryBody(node) && isSimpleCatch(node)) {\n const tryStmt = node.block.body[0]\n const isReturn = tryStmt.type === \"ReturnStatement\"\n\n // Only suggest when the try body is a return statement — non-return expression\n // replacements would produce syntactically ambiguous code without knowing the context\n if (isReturn) {\n const expr = tryStmt.argument\n const exprText = sourceCode.getText(expr)\n\n if (tryBodyHasAwait(node)) {\n const awaitExpr = expr.type === \"AwaitExpression\" ? expr.argument : expr\n const innerText = sourceCode.getText(awaitExpr)\n suggest.push({\n messageId: \"suggestTryFromPromise\",\n fix(fixer) {\n return fixer.replaceText(node, `return Try.fromPromise(${innerText})`)\n },\n })\n } else {\n suggest.push({\n messageId: \"suggestTry\",\n fix(fixer) {\n return fixer.replaceText(node, `return Try(() => ${exprText})`)\n },\n })\n }\n\n if (!hasFunctypeSymbol(sourceCode, \"Try\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Try\" },\n fix: createImportFixer(sourceCode, \"Try\"),\n })\n }\n }\n }\n\n context.report({\n node,\n messageId: \"preferTryOverTryCatch\",\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"prefer-try.js","names":["rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","node","allowThrowInTests","isInTestFile","filename","isSimpleTryBody","isSimpleCatch","catchBody","tryBodyHasAwait","stmt","sourceCode","suggest","tryStmt","expr","exprText","awaitExpr","innerText","fixer","hasFunctypeSymbol","createImportFixer","containsAwait"],"sources":["../../src/rules/prefer-try.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containsAwait } from \"../utils/async-detection\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Try for computations that may throw\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferTryOverTryCatch: \"Prefer Try(() => ...) over try/catch block\",\n preferAsyncTryOverTryCatch:\n \"Prefer Try.fromPromise(...), Either.fromPromise(...) or IO.tryPromise(...) over an async try/catch — Try(() => ...) cannot catch an awaited rejection\",\n suggestTry: \"Replace with Try(() => ...)\",\n suggestTryFromPromise: \"Replace with Try.fromPromise(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n const allowThrowInTests = options.allowThrowInTests !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function isSimpleTryBody(node: ASTNode): boolean {\n return node.block?.body?.length === 1\n }\n\n function isSimpleCatch(node: ASTNode): boolean {\n if (!node.handler?.body) return false\n const catchBody = node.handler.body.body\n return (\n catchBody.length === 0 ||\n (catchBody.length === 1 &&\n (catchBody[0].type === \"ReturnStatement\" || catchBody[0].type === \"ExpressionStatement\"))\n )\n }\n\n function tryBodyHasAwait(node: ASTNode): boolean {\n const stmt = node.block.body[0]\n if (stmt.type === \"ReturnStatement\" && stmt.argument?.type === \"AwaitExpression\") return true\n if (stmt.type === \"ExpressionStatement\" && stmt.expression?.type === \"AwaitExpression\") return true\n return false\n }\n\n return {\n TryStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n // Try cannot model `finally` — bail on any try statement with a finalizer.\n // Covers two bugs: (1) catch-less try/finally fires a misleading warning\n // with no useful autofix; (2) try/catch/finally autofix would lift the\n // catch into Try(() => …) and silently drop the finally clause. The FP\n // primitive for guaranteed cleanup is IO.bracket, on the lazy IO type.\n // See #206.\n if (node.finalizer) return\n\n // Allow try/catch in test files\n if (allowThrowInTests && isInTestFile()) return\n\n // Allow try/catch that re-throws in the catch block (even with logging)\n if (node.handler && node.handler.body) {\n const catchBody = node.handler.body.body\n const hasRethrow = catchBody.some((stmt: ASTNode) => stmt.type === \"ThrowStatement\")\n if (hasRethrow) return\n }\n\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isSimpleTryBody(node) && isSimpleCatch(node)) {\n const tryStmt = node.block.body[0]\n const isReturn = tryStmt.type === \"ReturnStatement\"\n\n // Only suggest when the try body is a return statement — non-return expression\n // replacements would produce syntactically ambiguous code without knowing the context\n if (isReturn) {\n const expr = tryStmt.argument\n const exprText = sourceCode.getText(expr)\n\n if (tryBodyHasAwait(node)) {\n const awaitExpr = expr.type === \"AwaitExpression\" ? expr.argument : expr\n const innerText = sourceCode.getText(awaitExpr)\n suggest.push({\n messageId: \"suggestTryFromPromise\",\n fix(fixer) {\n return fixer.replaceText(node, `return Try.fromPromise(${innerText})`)\n },\n })\n } else {\n suggest.push({\n messageId: \"suggestTry\",\n fix(fixer) {\n return fixer.replaceText(node, `return Try(() => ${exprText})`)\n },\n })\n }\n\n if (!hasFunctypeSymbol(sourceCode, \"Try\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Try\" },\n fix: createImportFixer(sourceCode, \"Try\"),\n })\n }\n }\n }\n\n context.report({\n node,\n messageId: containsAwait(node.block) ? \"preferAsyncTryOverTryCatch\" : \"preferTryOverTryCatch\",\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"sNAOA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,6CACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,mBAAoB,CAClB,KAAM,UACN,QAAS,EACX,EACA,kBAAmB,CACjB,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,sBAAuB,6CACvB,2BACE,wJACF,WAAY,8BACZ,sBAAuB,oCACvB,iBAAkB,qCACpB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EAEjCC,EAAqBF,EAAQ,qBAAuB,GACpDG,EAAoB,GACxBD,GAAsBE,EAA0BC,EAAA,UAAmBJ,EAAQ,UAAU,EACjFK,EAAoBN,EAAQ,oBAAsB,GAExD,SAASO,GAAe,CACtB,IAAMC,EAAWP,EAAQ,SACzB,MACE,kCAAkC,KAAKO,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,SAASC,EAAgB,EAAwB,CAC/C,OAAOJ,EAAK,OAAO,MAAM,SAAW,CACtC,CAEA,SAASK,EAAc,EAAwB,CAC7C,GAAI,CAACL,EAAK,SAAS,KAAM,MAAO,GAChC,IAAMM,EAAYN,EAAK,QAAQ,KAAK,KACpC,OACEM,EAAU,SAAW,GACpBA,EAAU,SAAW,IACnBA,EAAU,EAAE,CAAC,OAAS,mBAAqBA,EA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,6BAA+B,wBACtE,SACF,CAAC,CACH,CACF,CACF,CACF"}
|
package/dist/types/ast.d.ts
CHANGED
|
@@ -6,7 +6,6 @@
|
|
|
6
6
|
* Using `any` is the standard practice for ESLint rule development when working
|
|
7
7
|
* with AST nodes that need dynamic property access.
|
|
8
8
|
*/
|
|
9
|
-
type ASTNode = any;
|
|
9
|
+
export type ASTNode = any;
|
|
10
10
|
//#endregion
|
|
11
|
-
export { ASTNode };
|
|
12
11
|
//# sourceMappingURL=ast.d.ts.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ASTNode } from "../types/ast.js";
|
|
2
|
+
//#region src/utils/ast-walk.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Generic ESTree child traversal for rules that need to look inside a subtree without a visitor.
|
|
5
|
+
* `parent` is skipped (it points up, not down); `loc`/`range`/tokens are plain data, not nodes.
|
|
6
|
+
*/
|
|
7
|
+
export declare const isNode: (value: unknown) => value is ASTNode;
|
|
8
|
+
export declare const childNodes: (node: ASTNode) => ReadonlyArray<ASTNode>;
|
|
9
|
+
/** Every node in the subtree rooted at `node`, root included. */
|
|
10
|
+
export declare const descendants: (node: ASTNode) => ReadonlyArray<ASTNode>;
|
|
11
|
+
//#endregion
|
|
12
|
+
//# sourceMappingURL=ast-walk.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=e=>typeof e==`object`&&!!e&&typeof e.type==`string`,t=t=>Object.entries(t).filter(([e])=>e!==`parent`).flatMap(([,t])=>Array.isArray(t)?t.filter(e):e(t)?[t]:[]),n=e=>[e,...t(e).flatMap(n)];export{t as childNodes,n as descendants,e as isNode};
|
|
2
|
+
//# sourceMappingURL=ast-walk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ast-walk.js","names":["isNode","value","childNodes","node","key","descendants"],"sources":["../../src/utils/ast-walk.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\n\n/**\n * Generic ESTree child traversal for rules that need to look inside a subtree without a visitor.\n * `parent` is skipped (it points up, not down); `loc`/`range`/tokens are plain data, not nodes.\n */\n\nexport const isNode = (value: unknown): value is ASTNode =>\n typeof value === \"object\" && value !== null && typeof (value as { type?: unknown }).type === \"string\"\n\nexport const childNodes = (node: ASTNode): ReadonlyArray<ASTNode> =>\n Object.entries(node)\n .filter(([key]) => key !== \"parent\")\n .flatMap(([, value]) => (Array.isArray(value) ? value.filter(isNode) : isNode(value) ? [value] : []))\n\n/** Every node in the subtree rooted at `node`, root included. */\nexport const descendants = (node: ASTNode): ReadonlyArray<ASTNode> => [node, ...childNodes(node).flatMap(descendants)]\n"],"mappings":"AAOA,MAAaA,EAAU,GACrB,OAAOC,GAAU,YAAYA,GAAkB,OAAQA,EAA6B,MAAS,SAElFC,EAAc,GACzB,OAAO,QAAQC,CAAI,CAAC,CACjB,QAAQ,CAACC,KAASA,IAAQ,QAAQ,CAAC,CACnC,SAAS,EAAGH,KAAY,MAAM,QAAQA,CAAK,EAAIA,EAAM,OAAOD,CAAM,EAAIA,EAAOC,CAAK,EAAI,CAACA,CAAK,EAAI,CAAC,CAAE,EAG3FI,EAAe,GAA0C,CAACF,EAAM,GAAGD,EAAWC,CAAI,CAAC,CAAC,QAAQE,CAAW,CAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { ASTNode } from "../types/ast.js";
|
|
2
|
+
//#region src/utils/async-detection.d.ts
|
|
3
|
+
export declare const containsAwait: (node: ASTNode) => boolean;
|
|
4
|
+
export declare const containsYield: (node: ASTNode) => boolean;
|
|
5
|
+
//#endregion
|
|
6
|
+
//# sourceMappingURL=async-detection.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{childNodes as e,isNode as t}from"./ast-walk.js";const n=/* @__PURE__ */ new Set([`ArrowFunctionExpression`,`FunctionExpression`,`FunctionDeclaration`]),r=r=>i=>{let a=i=>t(i)?r(i)?!0:!n.has(i.type)&&e(i).some(a):!1;return a(i)},i=r(e=>e.type===`AwaitExpression`||e.type===`ForOfStatement`&&e.await===!0),a=r(e=>e.type===`YieldExpression`);export{i as containsAwait,a as containsYield};
|
|
2
|
+
//# sourceMappingURL=async-detection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"async-detection.js","names":["FUNCTION_BOUNDARIES","containsInOwnFlow","walk","isNode","n","matches","childNodes","node","containsAwait","containsYield"],"sources":["../../src/utils/async-detection.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\nimport { childNodes, isNode } from \"./ast-walk\"\n\n/**\n * Detects suspension points — `await` and `yield` — in a statement's own control flow.\n *\n * A suspension inside a nested function (arrow, expression, declaration, method) belongs to that\n * function, not to the enclosing loop or try block, so the walk stops at function boundaries. That\n * distinction is what makes the answer useful: `try { run(async () => { await x }) }` is a synchronous\n * try block, and `Try(() => ...)` is a correct replacement for it; `try { await x }` is not. Likewise a\n * loop body that yields cannot become a `.forEach` callback, but one that only defines a generator can.\n */\n\nconst FUNCTION_BOUNDARIES: ReadonlySet<string> = new Set([\n \"ArrowFunctionExpression\",\n \"FunctionExpression\",\n \"FunctionDeclaration\",\n])\n\nconst containsInOwnFlow =\n (matches: (node: ASTNode) => boolean) =>\n (node: ASTNode): boolean => {\n const walk = (n: ASTNode): boolean => {\n if (!isNode(n)) return false\n if (matches(n)) return true\n if (FUNCTION_BOUNDARIES.has(n.type)) return false\n return childNodes(n).some(walk)\n }\n return walk(node)\n }\n\nexport const containsAwait = containsInOwnFlow(\n (node) => node.type === \"AwaitExpression\" || (node.type === \"ForOfStatement\" && node.await === true),\n)\n\nexport const containsYield = containsInOwnFlow((node) => node.type === \"YieldExpression\")\n"],"mappings":"uDAaA,MAAMA,kBAA2C,IAAI,IAAI,CACvD,0BACA,qBACA,qBACF,CAAC,EAEKC,EACH,GACA,GAA2B,CAC1B,IAAMC,EAAQ,GACPC,EAAOC,CAAC,EACTC,EAAQD,CAAC,EAAU,GACvB,CAAIJ,EAAoB,IAAII,EAAE,IAAI,GAC3BE,EAAWF,CAAC,CAAC,CAAC,KAAKF,CAAI,EAHP,GAKzB,OAAOA,EAAKK,CAAI,CAClB,EAEWC,EAAgBP,EAC1B,GAASM,EAAK,OAAS,mBAAsBA,EAAK,OAAS,kBAAoBA,EAAK,QAAU,EACjG,EAEaE,EAAgBR,EAAmB,GAASM,EAAK,OAAS,iBAAiB"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { ASTNode } from "../types/ast.js";
|
|
2
|
+
import { SourceCode } from "eslint";
|
|
3
|
+
//#region src/utils/boundary-tags.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Structural exemptions recorded in JSDoc, instead of `eslint-disable` (#241).
|
|
6
|
+
*
|
|
7
|
+
* - `@interop <reason>` — the enclosing declaration bridges functype to a host whose contract is the
|
|
8
|
+
* non-FP shape: React's `use()` needs a throw, React Query needs a rejected promise, a hook that
|
|
9
|
+
* converts nullables into `Option` must accept nullables.
|
|
10
|
+
* - `@invariant <reason>` — the enclosing declaration throws only for programmer errors, never for
|
|
11
|
+
* expected failures (#325 D). Only `prefer-either` honors it.
|
|
12
|
+
*
|
|
13
|
+
* Why a tag rather than a disable comment: it covers one declaration (and what is nested inside it), not
|
|
14
|
+
* a whole file; it must carry a reason on the same line, so a bare tag exempts nothing; and it is
|
|
15
|
+
* greppable — `rg '@interop'` is the inventory of every place the code touches a throw-based host.
|
|
16
|
+
*/
|
|
17
|
+
export declare const INTEROP_TAG = "interop";
|
|
18
|
+
export declare const INVARIANT_TAG = "invariant";
|
|
19
|
+
/**
|
|
20
|
+
* Is `node` inside a declaration whose JSDoc carries `@<tag> <reason>`? Every enclosing documentable
|
|
21
|
+
* declaration is checked, so a tag on a function covers the callbacks nested inside it.
|
|
22
|
+
*/
|
|
23
|
+
export declare const isInsideTaggedDeclaration: (node: ASTNode, tag: string, sourceCode: SourceCode) => boolean;
|
|
24
|
+
//#endregion
|
|
25
|
+
//# sourceMappingURL=boundary-tags.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=`interop`,t=`invariant`,n=/* @__PURE__ */ new Set([`FunctionDeclaration`,`VariableDeclaration`,`MethodDefinition`,`PropertyDefinition`,`Property`,`TSTypeAliasDeclaration`,`TSInterfaceDeclaration`,`TSPropertySignature`,`TSMethodSignature`]),r=/* @__PURE__ */ new Set([`ExportNamedDeclaration`,`ExportDefaultDeclaration`]),i=(e,t)=>{let n=e.parent&&r.has(e.parent.type)?e.parent:e,i=t.getCommentsBefore(n),a=i[i.length-1];return a?.type===`Block`&&a.value.startsWith(`*`)?a.value:null},a=(e,t)=>RegExp(`(^|[\\s*])@${t}[ \\t]+\\S`,`m`).test(e),o=(e,t,r)=>{let o=e=>{if(!e)return!1;if(n.has(e.type)){let n=i(e,r);if(n!==null&&a(n,t))return!0}return o(e.parent)};return o(e)};export{e as INTEROP_TAG,t as INVARIANT_TAG,o as isInsideTaggedDeclaration};
|
|
2
|
+
//# sourceMappingURL=boundary-tags.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"boundary-tags.js","names":["INTEROP_TAG","INVARIANT_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\n * converts nullables into `Option` must accept nullables.\n * - `@invariant <reason>` — the enclosing declaration throws only for programmer errors, never for\n * expected failures (#325 D). Only `prefer-either` honors it.\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\"\nexport const INVARIANT_TAG = \"invariant\"\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":"AAkBA,MAAaA,EAAc,UACdC,EAAgB,YAGvBC,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"}
|
|
@@ -5,16 +5,15 @@ interface PeerDependency {
|
|
|
5
5
|
description: string;
|
|
6
6
|
required: boolean;
|
|
7
7
|
}
|
|
8
|
-
interface ValidationResult {
|
|
8
|
+
export interface ValidationResult {
|
|
9
9
|
isValid: boolean;
|
|
10
10
|
missing: PeerDependency[];
|
|
11
11
|
available: PeerDependency[];
|
|
12
12
|
installCommand: string;
|
|
13
13
|
warnings: string[];
|
|
14
14
|
}
|
|
15
|
-
declare function validatePeerDependencies(): ValidationResult;
|
|
16
|
-
declare function createValidationError(result: ValidationResult): Error;
|
|
17
|
-
declare function shouldValidateDependencies(): boolean;
|
|
15
|
+
export declare function validatePeerDependencies(): ValidationResult;
|
|
16
|
+
export declare function createValidationError(result: ValidationResult): Error;
|
|
17
|
+
export declare function shouldValidateDependencies(): boolean;
|
|
18
18
|
//#endregion
|
|
19
|
-
export { ValidationResult, createValidationError, shouldValidateDependencies, validatePeerDependencies };
|
|
20
19
|
//# sourceMappingURL=dependency-validator.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";var t
|
|
1
|
+
import{createRequire as e}from"node:module";var t=/* @__PURE__ */ e(import.meta.url);const n=[{name:`@typescript-eslint/eslint-plugin`,packageName:`@typescript-eslint/eslint-plugin`,description:`TypeScript-aware ESLint rules`,required:!0},{name:`@typescript-eslint/parser`,packageName:`@typescript-eslint/parser`,description:`TypeScript parser for ESLint`,required:!0},{name:`eslint-plugin-functional`,packageName:`eslint-plugin-functional`,description:`Functional programming ESLint rules`,required:!0},{name:`eslint-plugin-prettier`,packageName:`eslint-plugin-prettier`,description:`Code formatting rules`,required:!1},{name:`eslint-plugin-simple-import-sort`,packageName:`eslint-plugin-simple-import-sort`,description:`Import sorting rules`,required:!1},{name:`prettier`,packageName:`prettier`,description:`Code formatter`,required:!1}];function r(e){try{return t.resolve(e),!0}catch{return!1}}function i(){let[e,t]=n.reduce(([e,t],n)=>r(n.packageName)?[[...e,n],t]:[e,[...t,n]],[[],[]]),i=t.filter(e=>!e.required).map(e=>`Optional plugin '${e.name}' not found. Some rules will be skipped.`),a=t.filter(e=>e.required),o=t.length>0?`pnpm add -D ${t.map(e=>e.packageName).join(` `)}`:``;return{isValid:a.length===0,missing:t,available:e,installCommand:o,warnings:i}}function a(e){let t=e.missing.filter(e=>e.required);if(t.length===0)return/* @__PURE__ */ Error(`No validation errors`);let n=[`❌ Missing required peer dependencies for eslint-plugin-functype:`,``,t.map(e=>` • ${e.name} - ${e.description}`).join(`
|
|
2
2
|
`),``,`📦 Install missing dependencies:`,` ${e.installCommand}`,``,`📖 See installation guide: https://github.com/jordanburke/eslint-plugin-functype#installation`].join(`
|
|
3
3
|
`);return Error(n)}function o(){return process.env.NODE_ENV!==`test`&&process.env.FUNCTYPE_SKIP_VALIDATION!==`true`}export{a as createValidationError,o as shouldValidateDependencies,i as validatePeerDependencies};
|
|
4
4
|
//# sourceMappingURL=dependency-validator.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dependency-validator.js","names":[],"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,CACN,MAAO,EACT,CACF,CAEA,SAAgBC,GAA6C,CAG3D,GAAM,CAACC,EAAWC,GAAWL,EAAkB,QAC5C,CAACM,EAAIC,GAAM,IAASN,EAAWO,EAAI,WAAW,EAAI,CAAC,CAAC,GAAGF,EAAIE,CAAG,EAAGD,CAAG,EAAI,CAACD,EAAI,CAAC,GAAGC,EAAKC,CAAG,CAAC,EAC3F,CAAC,CAAC,EAAG,CAAC,CAAC,CACT,EAEMC,EAAWJ,EACd,OAAQ,GAAQ,CAACG,EAAI,QAAQ,CAAC,CAC9B,IAAK,GAAQ,oBAAoBA,EAAI,KAAK,yCAAyC,EAEhFE,EAAkBL,EAAQ,OAAQ,GAAQG,EAAI,QAAQ,EACtDG,EAAiBN,EAAQ,OAAS,EAAI,eAAeA,EAAQ,IAAK,GAAQG,EAAI,WAAW,CAAC,CAAC,KAAK,GAAG,IAAM,GAE/G,MAAO,CACL,QAASE,EAAgB,SAAW,EACpC,UACA,YACA,iBACA,UACF,CACF,CAEA,SAAgBE,EAAsB,EAAiC,CACrE,IAAMF,EAAkBG,EAAO,QAAQ,OAAQ,GAAQL,EAAI,QAAQ,EAEnE,GAAIE,EAAgB,SAAW,EAC7B,MAAO,gBAAI,MAAM,sBAAsB,EAKzC,IAAMI,EAAU,CACd,mEACA,GAJkBJ,EAAgB,IAAK,GAAQ,OAAOF,EAAI,KAAK,KAAKA,EAAI,aAAa,CAAC,CAAC,KAAK;CAKlF,EACV,GACA,mCACA,MAAMK,EAAO,iBACb,GACA,+FACF,CAAC,CAAC,KAAK;CAAI,EAEX,OAAW,MAAMC,CAAO,CAC1B,CAEA,SAAgBC,GAAsC,CAEpD,OAAO,QAAQ,IAAI,WAAa,QAAU,QAAQ,IAAI,2BAA6B,MACrF"}
|
|
@@ -4,11 +4,11 @@ import { Rule } from "eslint";
|
|
|
4
4
|
/**
|
|
5
5
|
* Check if functype library is imported in the current file
|
|
6
6
|
*/
|
|
7
|
-
declare function hasFunctypeImport(context: Rule.RuleContext): boolean;
|
|
7
|
+
export declare function hasFunctypeImport(context: Rule.RuleContext): boolean;
|
|
8
8
|
/**
|
|
9
9
|
* Enhanced functype imports tracking
|
|
10
10
|
*/
|
|
11
|
-
interface FunctypeImports {
|
|
11
|
+
export interface FunctypeImports {
|
|
12
12
|
types: Set<string>;
|
|
13
13
|
functions: Set<string>;
|
|
14
14
|
all: Set<string>;
|
|
@@ -16,50 +16,49 @@ interface FunctypeImports {
|
|
|
16
16
|
/**
|
|
17
17
|
* Get imported functype symbols from the current file
|
|
18
18
|
*/
|
|
19
|
-
declare function getFunctypeImports(context: Rule.RuleContext): FunctypeImports;
|
|
19
|
+
export declare function getFunctypeImports(context: Rule.RuleContext): FunctypeImports;
|
|
20
20
|
/**
|
|
21
21
|
* Legacy compatibility - returns the 'all' set
|
|
22
22
|
*/
|
|
23
|
-
declare function getFunctypeImportsLegacy(context: Rule.RuleContext): Set<string>;
|
|
23
|
+
export declare function getFunctypeImportsLegacy(context: Rule.RuleContext): Set<string>;
|
|
24
24
|
/**
|
|
25
25
|
* Check if a type reference is using functype types
|
|
26
26
|
*/
|
|
27
|
-
declare function isFunctypeType(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean;
|
|
27
|
+
export declare function isFunctypeType(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean;
|
|
28
28
|
/**
|
|
29
29
|
* Check if a call expression is using functype methods
|
|
30
30
|
*/
|
|
31
|
-
declare function isFunctypeCall(node: ASTNode, functypeImports: Set<string>): boolean;
|
|
31
|
+
export declare function isFunctypeCall(node: ASTNode, functypeImports: Set<string>): boolean;
|
|
32
32
|
/**
|
|
33
33
|
* Check if current context is already using functype patterns appropriately
|
|
34
34
|
*/
|
|
35
|
-
declare function isAlreadyUsingFunctype(node: ASTNode, functypeImports: Set<string>): boolean;
|
|
35
|
+
export declare function isAlreadyUsingFunctype(node: ASTNode, functypeImports: Set<string>): boolean;
|
|
36
36
|
/**
|
|
37
37
|
* Check if a variable or parameter is typed with functype types
|
|
38
38
|
*/
|
|
39
|
-
declare function hasFunctypeTypeAnnotation(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean;
|
|
39
|
+
export declare function hasFunctypeTypeAnnotation(node: ASTNode, functypeImports: FunctypeImports | Set<string>): boolean;
|
|
40
40
|
/**
|
|
41
41
|
* Check if a call expression is a Do notation call
|
|
42
42
|
*/
|
|
43
|
-
declare function isDoNotationCall(node: ASTNode, functypeImports: FunctypeImports): boolean;
|
|
43
|
+
export declare function isDoNotationCall(node: ASTNode, functypeImports: FunctypeImports): boolean;
|
|
44
44
|
/**
|
|
45
45
|
* Check if a call expression uses the $ helper function
|
|
46
46
|
*/
|
|
47
|
-
declare function isDollarHelper(node: ASTNode, functypeImports: FunctypeImports): boolean;
|
|
47
|
+
export declare function isDollarHelper(node: ASTNode, functypeImports: FunctypeImports): boolean;
|
|
48
48
|
/**
|
|
49
49
|
* Check if current expression is inside a Do notation block
|
|
50
50
|
*/
|
|
51
|
-
declare function isInsideDoNotation(node: ASTNode, functypeImports: FunctypeImports): boolean;
|
|
51
|
+
export declare function isInsideDoNotation(node: ASTNode, functypeImports: FunctypeImports): boolean;
|
|
52
52
|
/**
|
|
53
53
|
* Check if a method call is a chained method call on functype types
|
|
54
54
|
*/
|
|
55
|
-
declare function isChainedMethodCall(node: ASTNode, methodName: string): boolean;
|
|
55
|
+
export declare function isChainedMethodCall(node: ASTNode, methodName: string): boolean;
|
|
56
56
|
/**
|
|
57
57
|
* Detect if code could benefit from Do notation
|
|
58
58
|
*/
|
|
59
|
-
declare function shouldUseDoNotation(node: ASTNode, functypeImports: FunctypeImports): {
|
|
59
|
+
export declare function shouldUseDoNotation(node: ASTNode, functypeImports: FunctypeImports): {
|
|
60
60
|
shouldUse: boolean;
|
|
61
61
|
reason: "nested-checks" | "chained-flatmaps" | "mixed-monads" | "async-chains" | null;
|
|
62
62
|
};
|
|
63
63
|
//#endregion
|
|
64
|
-
export { FunctypeImports, getFunctypeImports, getFunctypeImportsLegacy, hasFunctypeImport, hasFunctypeTypeAnnotation, isAlreadyUsingFunctype, isChainedMethodCall, isDoNotationCall, isDollarHelper, isFunctypeCall, isFunctypeType, isInsideDoNotation, shouldUseDoNotation };
|
|
65
64
|
//# sourceMappingURL=functype-detection.d.ts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e
|
|
1
|
+
const e=/* @__PURE__ */ new Set([`Option`,`Either`,`List`,`LazyList`,`Task`,`Try`,`Map`,`Set`,`Stack`]),t=e=>e.type===`ImportDeclaration`&&e.source.type===`Literal`&&e.source.value===`functype`;function n(e){return e.sourceCode.ast.body.some(t)}function r(t){if(t.type===`ImportSpecifier`&&t.imported.type===`Identifier`){let n=t.imported.name;return e.has(n)?{type:n,fn:null,all:n}:{type:null,fn:n,all:n}}return t.type===`ImportDefaultSpecifier`?{type:null,fn:`default`,all:`default`}:t.type===`ImportNamespaceSpecifier`?{type:`*`,fn:`*`,all:`*`}:null}const i=(e,t)=>e.flatMap(e=>{let n=e[t];return n===null?[]:[n]});function a(e){let n=e.sourceCode.ast.body.filter(t).flatMap(e=>e.specifiers??[]).map(r).filter(e=>e!==null);return{types:new Set(i(n,`type`)),functions:new Set(i(n,`fn`)),all:new Set(n.map(e=>e.all))}}function o(e){return a(e).all}function s(e,t){if(!e)return!1;let n=t instanceof Set?t:t.types||t.all;if(e.type===`TSTypeReference`&&e.typeName?.type===`Identifier`){let t=e.typeName.name;return n.has(t)||[`Option`,`Either`,`List`,`LazyList`,`Task`,`Try`,`Map`,`Set`,`Stack`].includes(t)}return!1}function c(e,t){if(!e||e.type!==`CallExpression`)return!1;let n=e.callee;if(n.type===`MemberExpression`&&n.object.type===`Identifier`){let e=n.object.name,r=n.property?.name;if(t.has(e)||e===`Option`&&[`some`,`none`,`of`].includes(r)||e===`Either`&&[`left`,`right`,`of`].includes(r)||e===`List`&&[`of`,`from`,`empty`].includes(r)||e===`Map`&&[`of`,`empty`].includes(r)||e===`Set`&&[`of`,`empty`].includes(r))return!0}if(n.type===`MemberExpression`){let e=n.property?.name;if([`map`,`flatMap`,`filter`,`fold`,`foldLeft`,`foldRight`,`getOrElse`,`orElse`,`isEmpty`,`nonEmpty`,`isDefined`,`isSome`,`isNone`,`isLeft`,`isRight`,`toArray`].includes(e))return!0}return!1}function l(e,t){let n=e?.parent;return n?t(n)||l(n,t):!1}function u(e,t){return l(e,e=>c(e,t)||s(e,t))}function d(e,t){return e.typeAnnotation?.typeAnnotation?s(e.typeAnnotation.typeAnnotation,t):!1}function f(e,t){if(!e||e.type!==`CallExpression`)return!1;let n=e.callee;if(n.type===`Identifier`){let e=n.name;return t.functions.has(e)&&[`Do`,`DoAsync`].includes(e)}return!1}function p(e,t){if(!e||e.type!==`CallExpression`)return!1;let n=e.callee;return n.type===`Identifier`&&n.name===`$`&&t.functions.has(`$`)}function m(e,t){return l(e,e=>e.type===`CallExpression`&&f(e,t))}function h(e,t){if(!e||e.type!==`CallExpression`)return!1;let n=e.callee;return n.type===`MemberExpression`&&n.property.type===`Identifier`&&n.property.name===t}function g(e,t){if(m(e,t))return{shouldUse:!1,reason:null};if(e.type===`LogicalExpression`&&e.operator===`&&`){let t=e.toString?e.toString():``;if(t.includes(`&&`)&&t.match(/\w+(\.\w+){2,}/))return{shouldUse:!0,reason:`nested-checks`}}return h(e,`flatMap`)&&_(e)>=3?{shouldUse:!0,reason:`chained-flatmaps`}:{shouldUse:!1,reason:null}}function _(e){return!e||e.type!==`CallExpression`||!h(e,`flatMap`)?0:e.callee.type===`MemberExpression`?1+_(e.callee.object):1}export{a as getFunctypeImports,o as getFunctypeImportsLegacy,n as hasFunctypeImport,d as hasFunctypeTypeAnnotation,u as isAlreadyUsingFunctype,h as isChainedMethodCall,f as isDoNotationCall,p as isDollarHelper,c as isFunctypeCall,s as isFunctypeType,m as isInsideDoNotation,g as shouldUseDoNotation};
|
|
2
2
|
//# sourceMappingURL=functype-detection.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"functype-detection.js","names":[],"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,MAAM,EAAkC,IAAI,IAAI,CAC9C,SACA,SACA,OACA,WACA,OACA,MACA,MACA,MACA,OACF,CAAC,EAGK,EAAoB,GACxB,EAAK,OAAS,qBAAuB,EAAK,OAAO,OAAS,WAAa,EAAK,OAAO,QAAU,WAK/F,SAAgB,EAAkB,EAAoC,CACpE,OAAO,EAAQ,WAAW,IAAI,KAAK,KAAK,CAAgB,CAC1D,CAcA,SAAS,EAAoB,EAAwC,CACnE,GAAI,EAAK,OAAS,mBAAqB,EAAK,SAAS,OAAS,aAAc,CAC1E,IAAM,EAAO,EAAK,SAAS,KAI3B,OAAO,EAAW,IAAI,CAAI,EAAI,CAAE,KAAM,EAAM,GAAI,KAAM,IAAK,CAAK,E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OAAS,mBAClB,EAAI,EAAkB,EAAK,OAAO,MAAiB,EADN,CAEtD"}
|
|
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,IAAKA,CAAK,CACxG,CAGA,OAFID,EAAK,OAAS,yBAAiC,CAAE,KAAM,KAAM,GAAI,UAAW,IAAK,SAAU,EAC3FA,EAAK,OAAS,2BAAmC,CAAE,KAAM,IAAK,GAAI,IAAK,IAAK,GAAI,EAC7E,IACT,CAEA,MAAME,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,EADN,CAEtD"}
|
|
@@ -3,12 +3,11 @@ import { Rule, SourceCode } from "eslint";
|
|
|
3
3
|
/**
|
|
4
4
|
* Check if a given symbol is already imported from functype
|
|
5
5
|
*/
|
|
6
|
-
declare function hasFunctypeSymbol(sourceCode: SourceCode, symbolName: string): boolean;
|
|
6
|
+
export declare function hasFunctypeSymbol(sourceCode: SourceCode, symbolName: string): boolean;
|
|
7
7
|
/**
|
|
8
8
|
* Create a fixer function that adds a symbol to the functype import.
|
|
9
9
|
* Returns a factory compatible with ESLint suggest[].fix signature.
|
|
10
10
|
*/
|
|
11
|
-
declare function createImportFixer(sourceCode: SourceCode, symbolName: string): (fixer: Rule.RuleFixer) => Rule.Fix | null;
|
|
11
|
+
export declare function createImportFixer(sourceCode: SourceCode, symbolName: string): (fixer: Rule.RuleFixer) => Rule.Fix | null;
|
|
12
12
|
//#endregion
|
|
13
|
-
export { createImportFixer, hasFunctypeSymbol };
|
|
14
13
|
//# sourceMappingURL=import-fixer.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"import-fixer.js","names":[],"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,
|
|
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,EAAY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