eslint-plugin-functype 2.113.0 → 2.114.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 +10 -5
- package/dist/rules/no-get-unsafe.js +1 -1
- package/dist/rules/no-get-unsafe.js.map +1 -1
- package/dist/rules/prefer-fold.js +1 -1
- package/dist/rules/prefer-option.js +1 -1
- package/dist/rules/prefer-try.js +1 -1
- package/dist/utils/type-aware.d.ts +14 -0
- package/dist/utils/type-aware.js +2 -0
- package/dist/utils/type-aware.js.map +1 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -118,12 +118,17 @@ type UserRow = Wire<{ readonly email: string | null; readonly tags: ReadonlyArra
|
|
|
118
118
|
|
|
119
119
|
### `functype/no-get-unsafe`
|
|
120
120
|
|
|
121
|
-
| Option
|
|
122
|
-
|
|
|
123
|
-
| `allowInTests`
|
|
124
|
-
| `
|
|
121
|
+
| Option | Default | Description |
|
|
122
|
+
| -------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
123
|
+
| `allowInTests` | `true` | Silence the rule inside test files (same predicate as above). |
|
|
124
|
+
| `allowInteropMarker` | `true` | Skip calls inside a declaration tagged `@interop <reason>`, as `prefer-either` does. |
|
|
125
|
+
| `unsafeMethods` | `["orThrow", "expect", "get", "getOrThrow", "unwrap"]` | Method names flagged when called on a suspected `Option` / `Either` / other `Extractable` receiver. Includes both current (`orThrow`, `expect`) and legacy (`get`, `getOrThrow`, `unwrap`) names. |
|
|
125
126
|
|
|
126
|
-
|
|
127
|
+
**Which receivers count.** With type-aware linting on (`parserOptions.projectService` or `project`), the rule checks the receiver's type: anything with both `orThrow` and `fold` (every functype container) is checked, whatever the variable is called, and a native `Map` named `options` is not. Without type information it falls back to guessing from the receiver's name and shape (`option`, `either`, `result`… or a `.map/.flatMap/.filter/.fold` chain), which misses a container bound to any other name. Turn type-aware linting on if you rely on this rule.
|
|
128
|
+
|
|
129
|
+
`.orThrow(error)` and `.orThrow((e) => error)` are not reported: the caller chose the error, which is the documented way to throw for a host that needs it (see the decision table above). A bare `.orThrow()` throws a generic error and is reported.
|
|
130
|
+
|
|
131
|
+
The rule reports each match with two suggestions — `.orElse(default)` for value fallback and `.fold(onNone, onSome)` for branch handling. There is no autofix: the correct replacement depends on human judgment about a default value, and `.expect(msg)` would silently lose its argument. Apply a suggestion explicitly in your editor when you know which one fits.
|
|
127
132
|
|
|
128
133
|
### `functype/prefer-fold`
|
|
129
134
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{isExtractableByType as t}from"../utils/type-aware.js";const n=[`orThrow`,`expect`,`get`,`getOrThrow`,`unwrap`],r={meta:{type:`problem`,docs:{description:`Avoid unsafe extractor calls on Option, Either, and other Extractable types`,recommended:!0},hasSuggestions:!0,schema:[{type:`object`,properties:{allowInTests:{type:`boolean`,default:!0},allowInteropMarker:{type:`boolean`,default:!0},unsafeMethods:{type:`array`,items:{type:`string`},default:[...n]}},additionalProperties:!1}],messages:{noUnsafeGet:`Avoid unsafe .{{method}}() call: it throws a generic error. Use .fold(), .map(), or .orElse() instead. If a host needs the throw, name the error: .orThrow((e) => new MyError(e))`,suggestOrElse:`Replace with .orElse(default) for a value fallback`,suggestFold:`Replace with .fold(onNone, onSome) for branch handling`}},create(r){let i=r.options[0]||{},a=i.allowInTests!==!1,o=i.unsafeMethods||n,s=i.allowInteropMarker!==!1,c=(e,t)=>e===`orThrow`&&t.arguments.length>0;function l(){let e=r.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function u(e){if(!e)return!1;let t=r.sourceCode.getText(e);if(/\b(Option|Either|Maybe|Result|Some|None|Left|Right)\b/.test(t)||/\.(map|flatMap|filter|fold)\s*\(/.test(t)||/\b(option|either|maybe|result|some|none|left|right)\w*\b/i.test(t))return!0;if(e.type===`Identifier`){let t=e.name.toLowerCase();if(/(option|either|maybe|result|some|none|left|right|opt)/.test(t))return!0}return e.type===`CallExpression`&&e.callee.type===`MemberExpression`&&e.callee.object?u(e.callee.object):!1}return{CallExpression(n){if(a&&l()||n.callee.type!==`MemberExpression`)return;let i=n.callee.property;if(!i||i.type!==`Identifier`)return;let d=i.name;if(o.includes(d)&&!c(d,n)&&!(s&&e(n,`interop`,r.sourceCode))&&(t(n.callee.object,r)??u(n.callee.object))){let e=r.sourceCode,t=e.getText(n.callee.object),i=n.arguments.map(t=>e.getText(t)).join(`, `),a=i?`; was ${d}(${i})`:``;r.report({node:n,messageId:`noUnsafeGet`,data:{method:d},suggest:[{messageId:`suggestOrElse`,fix(e){return e.replaceText(n,`${t}.orElse(undefined /* TODO: default${a} */)`)}},{messageId:`suggestFold`,fix(e){return e.replaceText(n,`${t}.fold(() => undefined /* TODO: onNone${a} */, (v) => v /* TODO: onSome */)`)}}]})}}}}};export{r as default};
|
|
2
2
|
//# sourceMappingURL=no-get-unsafe.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-get-unsafe.js","names":["DEFAULT_UNSAFE_METHODS","rule","options","context","allowInTests","unsafeMethods","
|
|
1
|
+
{"version":3,"file":"no-get-unsafe.js","names":["DEFAULT_UNSAFE_METHODS","rule","options","context","allowInTests","unsafeMethods","allowInteropMarker","isChosenErrorThrow","methodName","node","isInTestFile","filename","isMonadicType","text","varName","property","isInsideTaggedDeclaration","isExtractableByType","sourceCode","objectText","argsText","a","wasSuffix","fixer"],"sources":["../../src/rules/no-get-unsafe.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { isExtractableByType } from \"../utils/type-aware\"\n\nconst DEFAULT_UNSAFE_METHODS: readonly string[] = [\"orThrow\", \"expect\", \"get\", \"getOrThrow\", \"unwrap\"]\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Avoid unsafe extractor calls on Option, Either, and other Extractable types\",\n recommended: true,\n },\n hasSuggestions: true,\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n unsafeMethods: {\n type: \"array\",\n items: { type: \"string\" },\n default: [...DEFAULT_UNSAFE_METHODS],\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noUnsafeGet:\n \"Avoid unsafe .{{method}}() call: it throws a generic error. Use .fold(), .map(), or .orElse() instead. If a host needs the throw, name the error: .orThrow((e) => new MyError(e))\",\n suggestOrElse: \"Replace with .orElse(default) for a value fallback\",\n suggestFold: \"Replace with .fold(onNone, onSome) for branch handling\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n const unsafeMethods: readonly string[] = options.unsafeMethods || DEFAULT_UNSAFE_METHODS\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary, as in prefer-either.\n const allowInteropMarker = options.allowInteropMarker !== false\n\n /**\n * `.orThrow(error)` / `.orThrow((e) => error)`: the caller chose the error. That is the documented way\n * to throw for a host that needs it, not an unsafe extraction; `prefer-either` and the README's\n * decision table both treat it that way. Only a bare `.orThrow()` throws a generic error.\n */\n const isChosenErrorThrow = (methodName: string, node: ASTNode): boolean =>\n methodName === \"orThrow\" && node.arguments.length > 0\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 isMonadicType(node: ASTNode): boolean {\n // This is a simplified check - in a real implementation, you'd want\n // more sophisticated type checking using TypeScript's type checker\n if (!node) return false\n\n const sourceCode = context.sourceCode\n\n // Check for common patterns that indicate monadic types\n const text = sourceCode.getText(node)\n\n // Direct type checks - constructors or type names\n if (/\\b(Option|Either|Maybe|Result|Some|None|Left|Right)\\b/.test(text)) {\n return true\n }\n\n // Method chains that suggest monadic operations\n if (/\\.(map|flatMap|filter|fold)\\s*\\(/.test(text)) {\n return true\n }\n\n // Variable names that suggest monadic types (case insensitive)\n if (/\\b(option|either|maybe|result|some|none|left|right)\\w*\\b/i.test(text)) {\n return true\n }\n\n // Check the specific node type and name\n if (node.type === \"Identifier\") {\n const varName = node.name.toLowerCase()\n if (/(option|either|maybe|result|some|none|left|right|opt)/.test(varName)) {\n return true\n }\n }\n\n // Check for CallExpression pattern like Some(\"test\").map()\n if (node.type === \"CallExpression\" && node.callee.type === \"MemberExpression\" && node.callee.object) {\n return isMonadicType(node.callee.object)\n }\n\n return false\n }\n\n return {\n CallExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (node.callee.type !== \"MemberExpression\") return\n\n const property = node.callee.property\n if (!property || property.type !== \"Identifier\") return\n\n const methodName = property.name\n if (!unsafeMethods.includes(methodName)) return\n if (isChosenErrorThrow(methodName, node)) return\n if (allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)) return\n\n // With type information, the receiver's type decides: no name guessing, so `missing.orThrow()`\n // on an Option is reported and `options.get(\"k\")` on a native Map is not. Without it, fall\n // back to the name/shape heuristic.\n const byType = isExtractableByType(node.callee.object, context)\n if (byType ?? isMonadicType(node.callee.object)) {\n const sourceCode = context.sourceCode\n const objectText = sourceCode.getText(node.callee.object)\n\n // Preserve the original call's argument text in the TODO comment so a suggestion\n // applied to `.expect(\"Should have a user here\")` or `.orThrow(new NotFound())`\n // doesn't silently drop information the developer intended to keep. Omit the\n // \"was\" suffix when the original call had no args (`.get()`, `.unwrap()`, etc.).\n const argsText = node.arguments.map((a: ASTNode) => sourceCode.getText(a)).join(\", \")\n const wasSuffix = argsText ? `; was ${methodName}(${argsText})` : \"\"\n\n context.report({\n node,\n messageId: \"noUnsafeGet\",\n data: { method: methodName },\n suggest: [\n {\n messageId: \"suggestOrElse\",\n fix(fixer) {\n return fixer.replaceText(node, `${objectText}.orElse(undefined /* TODO: default${wasSuffix} */)`)\n },\n },\n {\n messageId: \"suggestFold\",\n fix(fixer) {\n return fixer.replaceText(\n node,\n `${objectText}.fold(() => undefined /* TODO: onNone${wasSuffix} */, (v) => v /* TODO: onSome */)`,\n )\n },\n },\n ],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"mIAMA,MAAMA,EAA4C,CAAC,UAAW,SAAU,MAAO,aAAc,QAAQ,EAE/FC,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,8EACb,YAAa,EACf,EACA,eAAgB,GAChB,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,EACA,mBAAoB,CAClB,KAAM,UACN,QAAS,EACX,EACA,cAAe,CACb,KAAM,QACN,MAAO,CAAE,KAAM,QAAS,EACxB,QAAS,CAAC,GAAGD,CAAsB,CACrC,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,YACE,oLACF,cAAe,qDACf,YAAa,wDACf,CACF,EAEA,OAAO,EAAS,CACd,IAAME,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EACjCC,EAAeF,EAAQ,eAAiB,GACxCG,EAAmCH,EAAQ,eAAiBF,EAE5DM,EAAqBJ,EAAQ,qBAAuB,GAOpDK,GAAsB,EAAoB,IAC9CC,IAAe,WAAaC,EAAK,UAAU,OAAS,EAEtD,SAASC,GAAe,CACtB,IAAMC,EAAWR,EAAQ,SACzB,MACE,kCAAkC,KAAKQ,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,SAASC,EAAc,EAAwB,CAG7C,GAAI,CAACH,EAAM,MAAO,GAKlB,IAAMI,EAHaV,EAAQ,WAGH,QAAQM,CAAI,EAapC,GAVI,wDAAwD,KAAKI,CAAI,GAKjE,mCAAmC,KAAKA,CAAI,GAK5C,4DAA4D,KAAKA,CAAI,EACvE,MAAO,GAIT,GAAIJ,EAAK,OAAS,aAAc,CAC9B,IAAMK,EAAUL,EAAK,KAAK,YAAY,EACtC,GAAI,wDAAwD,KAAKK,CAAO,EACtE,MAAO,EAEX,CAOA,OAJIL,EAAK,OAAS,kBAAoBA,EAAK,OAAO,OAAS,oBAAsBA,EAAK,OAAO,OACpFG,EAAcH,EAAK,OAAO,MAAM,EAGlC,EACT,CAEA,MAAO,CACL,eAAe,EAAe,CAG5B,GAFIL,GAAgBM,EAAa,GAE7BD,EAAK,OAAO,OAAS,mBAAoB,OAE7C,IAAMM,EAAWN,EAAK,OAAO,SAC7B,GAAI,CAACM,GAAYA,EAAS,OAAS,aAAc,OAEjD,IAAMP,EAAaO,EAAS,KAC5B,GAAKV,EAAc,SAASG,CAAU,GAClC,GAAmBA,EAAYC,CAAI,GACnC,KAAsBO,EAA0BP,EAAA,UAAmBN,EAAQ,UAAU,KAK1Ec,EAAoBR,EAAK,OAAO,OAAQN,CAC9C,GAAKS,EAAcH,EAAK,OAAO,MAAM,GAAG,CAC/C,IAAMS,EAAaf,EAAQ,WACrBgB,EAAaD,EAAW,QAAQT,EAAK,OAAO,MAAM,EAMlDW,EAAWX,EAAK,UAAU,IAAK,GAAeS,EAAW,QAAQG,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAC9EC,EAAYF,EAAW,SAASZ,EAAW,GAAGY,EAAS,GAAK,GAElEjB,EAAQ,OAAO,CACb,OACA,UAAW,cACX,KAAM,CAAE,OAAQK,CAAW,EAC3B,QAAS,CACP,CACE,UAAW,gBACX,IAAI,EAAO,CACT,OAAOe,EAAM,YAAYd,EAAM,GAAGU,EAAW,oCAAoCG,EAAU,KAAK,CAClG,CACF,EACA,CACE,UAAW,cACX,IAAI,EAAO,CACT,OAAOC,EAAM,YACXd,EACA,GAAGU,EAAW,uCAAuCG,EAAU,kCACjE,CACF,CACF,CACF,CACF,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{childNodes as t}from"../utils/ast-walk.js";const n=/* @__PURE__ */ new Set([`isSome`,`isRight`,`isSuccess`]),r=/* @__PURE__ */ new Set([`isNone`,`isLeft`,`isFailure`]),i={isSome:null,isNone:null,isRight:{param:`left`,member:`value`},isLeft:{param:`left`,member:`value`},isSuccess:{param:`error`,member:`error`},isFailure:{param:`error`,member:`error`}},a=[`get`,`orThrow`];function o(e){return e.type===`Literal`&&e.value===null||e.type===`Identifier`&&e.name===`undefined`}function s(e,t){if(e.type!==`CallExpression`||e.callee.type!==`MemberExpression`)return null;let a=e.callee.property.name,o=t.getText(e.callee.object),s=i[a]??null;return n.has(a)?{obj:o,isNegated:!1,failure:s}:r.has(a)?{obj:o,isNegated:!0,failure:s}:null}const c=e=>e.replace(/\s+/g,``),l={members:[`value`],methods:a};function u(e,n,r,i){let a=e=>{let t=e.type===`TSNonNullExpression`?e.expression:e;return c(i.getText(t))===c(n)},o=(e,t)=>e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&t.includes(e.property.name)&&a(e.object),s=e=>{let n=e.parent,i=n?.type===`CallExpression`&&n.callee===e,a=n?.type===`AssignmentExpression`&&n.left===e||n?.type===`UpdateExpression`;return o(e,r.members)&&!i&&!a||e.type===`CallExpression`&&e.arguments.length===0&&o(e.callee,r.methods)?[e.range]:t(e).flatMap(s)};return s(e)}const d=(e,t)=>{let n=e=>t.some(t=>RegExp(`(?<![\\w$.])${e}(?![\\w$])`).test(t));return[e,...Array.from({length:20},(t,n)=>`${e}${n+1}`)].find(e=>!n(e))??`${e}_`},f=(e,t)=>e.type===`ObjectExpression`||e.type===`SequenceExpression`?`(${t})`:t;function p(e,t,n,r,i){let a=i.getText(e),o=n===null?[]:u(e,t,n,i);if(o.length===0)return`() => ${f(e,a)}`;let s=e.range[0],c=[...o].sort((e,t)=>t[0]-e[0]).reduce((e,[t,n])=>e.slice(0,t-s)+r+e.slice(n-s),a);return`(${r}) => ${f(e,c)}`}function m(e,t,n,r,i){let a=[i.getText(n),i.getText(r)],o=p(r,e,l,d(`value`,a),i);return`${e}.fold(${t===null?p(n,e,null,``,i):p(n,e,{members:[t.member],methods:[]},d(t.param,a),i)}, ${o})`}function h(e){let t=e.type===`BlockStatement`&&e.body.length===1?e.body[0]:e;return t.type===`ReturnStatement`&&t.argument?t.argument:null}function g(e){return e.alternate?e.alternate.type===`IfStatement`?1+g(e.alternate):2:1}const _={meta:{type:`suggestion`,docs:{description:`Prefer .fold() over if/else chains when working with monadic types`,recommended:!0},hasSuggestions:!0,schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},minComplexity:{type:`integer`,minimum:1,default:2},checkNullable:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{preferFold:`Prefer .fold() over if/else when working with {{type}} types`,preferFoldTernary:`Consider using .fold() instead of ternary operator for {{type}}`,suggestFold:`Replace with .fold()`,suggestOr:`Replace with {{receiver}}.or({{alternative}}) — keep the first when it is present, else the alternative`}},create(t){let n=t.options[0]||{},r=n.allowInteropMarker!==!1,i=n=>r&&e(n,`interop`,t.sourceCode),a=n.minComplexity||2,l=n.checkNullable===!0;function u(e){let n=t.sourceCode;if(e.type!==`IfStatement`||!e.alternate)return null;let r=s(e.test,n);if(!r)return null;let i=h(e.consequent),a=h(e.alternate);if(!i||!a)return null;let o=[e.test,i,a];if(!n.getCommentsInside(e).every(e=>e.range!==void 0&&o.some(t=>e.range[0]>=t.range[0]&&e.range[1]<=t.range[1])))return null;let{obj:c,isNegated:l,failure:u}=r,[d,f]=l?[i,a]:[a,i];return`return ${m(c,u,d,f,n)}`}function d(e){let n=t.sourceCode,r=s(e.test,n);if(!r)return[];let{obj:i,isNegated:a,failure:l}=r,[u,d]=a?[e.consequent,e.alternate]:[e.alternate,e.consequent],f=n.getText(u),p=n.getText(d);if(c(p)===c(i))return u.type===`Literal`||u.type===`TemplateLiteral`||o(u)?[]:[{messageId:`suggestOr`,data:{receiver:i,alternative:f},fix:t=>t.replaceText(e,`${i}.or(${f})`)}];let h=m(i,l,u,d,n);return[{messageId:`suggestFold`,fix:t=>t.replaceText(e,h)}]}function f(e){if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`){let t=e.callee.property.name;return[`isSome`,`isNone`,`isRight`,`isLeft`,`isSuccess`,`isFailure`].includes(t)}return!1}function p(e){let n=t.sourceCode.getText(e);if(/\.(isSome|isNone|isDefined)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Option`,via:`method`};if(/\.(isLeft|isRight)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Either`,via:`method`};if(/\.(isSuccess|isFailure)\s*\(\s*\)/.test(n))return{isMonadic:!0,type:`Result`,via:`method`};if(l&&e.type===`BinaryExpression`){if((e.operator===`===`||e.operator===`!==`||e.operator===`==`||e.operator===`!=`)&&(e.left.type===`Literal`&&(e.left.value===null||e.left.value===void 0)||e.right.type===`Literal`&&(e.right.value===null||e.right.value===void 0)))return{isMonadic:!0,type:`Option`,via:`nullable`};if(e.operator===`==`||e.operator===`!=`||e.operator===`===`||e.operator===`!==`){let t=e.left.type===`Identifier`&&e.left.name===`undefined`,n=e.right.type===`Identifier`&&e.right.name===`undefined`;if(t||n)return{isMonadic:!0,type:`Option`,via:`nullable`}}}return{isMonadic:!1,type:``,via:``}}function _(e){if(!f(e.test))return[];let t=u(e);return t?[{messageId:`suggestFold`,fix:n=>n.replaceText(e,t)}]:[]}function v(e){let n=e.test,r=p(n);r.isMonadic&&(e.parent&&e.parent.type===`IfStatement`||g(e)>=a&&t.report({node:e,messageId:`preferFold`,data:{type:r.type},suggest:_(e)}))}return{IfStatement(e){i(e)||v(e)},ConditionalExpression(e){if(i(e))return;let n=p(e.test);(n.via!==`nullable`||!o(e.consequent)&&!o(e.alternate))&&n.isMonadic&&t.report({node:e,messageId:`preferFoldTernary`,data:{type:n.type},suggest:f(e.test)?d(e):[]})}}}};export{_ as default};
|
|
2
2
|
//# sourceMappingURL=prefer-fold.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{getFunctypeImportsLegacy as t,isAlreadyUsingFunctype as n,isFunctypeType as r}from"../utils/functype-detection.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=t=>f&&e(t,`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=t(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 t=e.types.filter(e=>e.type!==`TSNullKeyword`&&e.type!==`TSUndefinedKeyword`);if(t.length===1){let o=t[0];if(r(o,g)||n(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
|
package/dist/rules/prefer-try.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{containsAwait as t}from"../utils/async-detection.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=t=>o&&e(t,`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(e){if(s(e)||e.finalizer||c&&l()||e.handler&&e.handler.body&&e.handler.body.body.some(e=>e.type===`ThrowStatement`))return;let a=i.sourceCode,o=[];if(u(e)&&d(e)){let t=e.block.body[0];if(t.type===`ReturnStatement`){let i=t.argument,s=a.getText(i);if(f(e)){let t=i.type===`AwaitExpression`?i.argument:i,n=a.getText(t);o.push({messageId:`suggestTryFromPromise`,fix(t){return t.replaceText(e,`return Try.fromPromise(${n})`)}})}else o.push({messageId:`suggestTry`,fix(t){return t.replaceText(e,`return Try(() => ${s})`)}});r(a,`Try`)||o.push({messageId:`suggestAddImport`,data:{symbol:`Try`},fix:n(a,`Try`)})}}i.report({node:e,messageId:t(e.block)?`preferAsyncTryOverTryCatch`:`preferTryOverTryCatch`,suggest:o})}}}};export{i as default};
|
|
2
2
|
//# sourceMappingURL=prefer-try.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { ASTNode } from "../types/ast.js";
|
|
2
|
+
import { Rule } from "eslint";
|
|
3
|
+
//#region src/utils/type-aware.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Is `node`'s type a functype extractable container (Option, Either, Try, Lazy, …)? Structural:
|
|
6
|
+
* the type, after stripping `null` / `undefined`, has both `orThrow` and `fold` — true of every
|
|
7
|
+
* functype container, including union types like `Either` (each member has both). Native
|
|
8
|
+
* collections (`Map#get`) and arbitrary objects don't.
|
|
9
|
+
*
|
|
10
|
+
* `undefined` when type information isn't available, so the caller can fall back.
|
|
11
|
+
*/
|
|
12
|
+
export declare const isExtractableByType: (node: ASTNode, context: Rule.RuleContext) => boolean | undefined;
|
|
13
|
+
//#endregion
|
|
14
|
+
//# sourceMappingURL=type-aware.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=e=>{let t=e.sourceCode.parserServices;return t?.program&&t.esTreeNodeToTSNodeMap?t:void 0},t=(t,n)=>{let r=e(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(t);if(!i)return;let a=r.program.getTypeChecker(),o=a.getNonNullableType(a.getTypeAtLocation(i));return a.getPropertyOfType(o,`orThrow`)!==void 0&&a.getPropertyOfType(o,`fold`)!==void 0};export{t as isExtractableByType};
|
|
2
|
+
//# sourceMappingURL=type-aware.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"type-aware.js","names":["typedServices","services","context","isExtractableByType","tsNode","node","checker","type"],"sources":["../../src/utils/type-aware.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Type-aware helpers that work only when the consumer turns on type-aware linting\n * (`parserOptions.projectService` or `project`). Without it they report \"unknown\", and a rule\n * falls back to its syntactic heuristic.\n *\n * The checker is reached through `parserServices` and typed structurally here, so the plugin\n * takes no runtime dependency on `typescript`.\n */\n\ntype TypeLike = object\n\ntype CheckerLike = {\n getTypeAtLocation(node: unknown): TypeLike\n getNonNullableType(type: TypeLike): TypeLike\n getPropertyOfType(type: TypeLike, name: string): unknown\n}\n\ntype TypedServices = {\n readonly program: { getTypeChecker(): CheckerLike }\n readonly esTreeNodeToTSNodeMap: { get(node: unknown): unknown }\n}\n\nconst typedServices = (context: Rule.RuleContext): TypedServices | undefined => {\n const services = context.sourceCode.parserServices as Partial<TypedServices> | undefined\n return services?.program && services.esTreeNodeToTSNodeMap ? (services as TypedServices) : undefined\n}\n\n/**\n * Is `node`'s type a functype extractable container (Option, Either, Try, Lazy, …)? Structural:\n * the type, after stripping `null` / `undefined`, has both `orThrow` and `fold` — true of every\n * functype container, including union types like `Either` (each member has both). Native\n * collections (`Map#get`) and arbitrary objects don't.\n *\n * `undefined` when type information isn't available, so the caller can fall back.\n */\nexport const isExtractableByType = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n if (!tsNode) return undefined\n const checker = services.program.getTypeChecker()\n const type = checker.getNonNullableType(checker.getTypeAtLocation(tsNode))\n return (\n checker.getPropertyOfType(type, \"orThrow\") !== undefined && checker.getPropertyOfType(type, \"fold\") !== undefined\n )\n}\n"],"mappings":"AA0BA,MAAMA,EAAiB,GAAyD,CAC9E,IAAMC,EAAWC,EAAQ,WAAW,eACpC,OAAOD,GAAU,SAAWA,EAAS,sBAAyBA,EAA6B,IAAA,EAC7F,EAUaE,GAAuB,EAAe,IAAmD,CACpG,IAAMF,EAAWD,EAAcE,CAAO,EACtC,GAAI,CAACD,EAAU,OACf,IAAMG,EAASH,EAAS,sBAAsB,IAAII,CAAI,EACtD,GAAI,CAACD,EAAQ,OACb,IAAME,EAAUL,EAAS,QAAQ,eAAe,EAC1CM,EAAOD,EAAQ,mBAAmBA,EAAQ,kBAAkBF,CAAM,CAAC,EACzE,OACEE,EAAQ,kBAAkBC,EAAM,SAAS,IAAM,IAAA,IAAaD,EAAQ,kBAAkBC,EAAM,MAAM,IAAM,IAAA,EAE5G"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-functype",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.114.0",
|
|
4
4
|
"description": "Custom ESLint rules for functional TypeScript programming with functype library patterns including Do notation (ESLint 10+)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"@types/node": "^24.19.0",
|
|
43
43
|
"@typescript-eslint/rule-tester": "^8.71.0",
|
|
44
44
|
"eslint-config-prettier": "^10.1.8",
|
|
45
|
-
"functype": "^1.
|
|
45
|
+
"functype": "^1.14.0",
|
|
46
46
|
"ts-builds": "^3.4.3",
|
|
47
47
|
"tsdown": "^0.23.0"
|
|
48
48
|
},
|