eslint-plugin-functype 2.108.0 → 2.109.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 +36 -0
- 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-fold.js.map +1 -1
- package/dist/rules/prefer-list.js +1 -1
- package/dist/rules/prefer-list.js.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -40,6 +40,42 @@ export default [functype.configs.strict]
|
|
|
40
40
|
| `functype/no-get-unsafe` | off | error | Disallow unsafe `.get()` on `Option`/`Either` |
|
|
41
41
|
| `functype/prefer-list` | off | warn | Use `List` instead of native arrays |
|
|
42
42
|
|
|
43
|
+
## Rule options
|
|
44
|
+
|
|
45
|
+
### `functype/prefer-list`
|
|
46
|
+
|
|
47
|
+
| Option | Default | Description |
|
|
48
|
+
| --------------------- | :-----: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
49
|
+
| `allowArraysInTests` | `true` | Silence the rule inside test files (`.test.ts`, `.spec.ts`, `__tests__/`, `/test/`, `/tests/`). |
|
|
50
|
+
| `allowReadonlyArrays` | `true` | When `true`, `ReadonlyArray<T>` **and** `readonly T[]` pass. When `false`, both are flagged consistently. Use `false` in combination with `Wire<T>` from `functype` to hold the rule at `error` — every unmarked `ReadonlyArray<T>` becomes a lint error and `Wire<T>` is the sole explicit escape hatch. |
|
|
51
|
+
| `allowArrayLiterals` | `false` | When `true`, `const xs = [1, 2, 3]` is not reported. Useful when you want type-position enforcement but tolerate idiomatic literals like `[...map.entries()]`. Mutable `T[]` in type positions is always reported regardless. |
|
|
52
|
+
|
|
53
|
+
**Boundary recipe (recommended for codebases touching serialization boundaries):**
|
|
54
|
+
|
|
55
|
+
```jsonc
|
|
56
|
+
{
|
|
57
|
+
"functype/prefer-list": ["error", { "allowReadonlyArrays": false }],
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Then annotate boundaries with `Wire<T>` from `functype`:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import type { Wire } from "functype"
|
|
65
|
+
type ClaimedDoc = Wire<Row>
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`Wire<T>` is `ReadonlyArray<T>` structurally, so no casts. The syntactic rule ignores unrecognized type names — `Wire<T>` passes for free, and consumer aliases stack cleanly.
|
|
69
|
+
|
|
70
|
+
### `functype/no-get-unsafe`
|
|
71
|
+
|
|
72
|
+
| Option | Default | Description |
|
|
73
|
+
| --------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
74
|
+
| `allowInTests` | `true` | Silence the rule inside test files (same predicate as above). |
|
|
75
|
+
| `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. |
|
|
76
|
+
|
|
77
|
+
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)` / `.orThrow(err)` would silently lose their argument. Apply a suggestion explicitly in your editor when you know which one fits.
|
|
78
|
+
|
|
43
79
|
## Combining with eslint-config-functype
|
|
44
80
|
|
|
45
81
|
For a complete setup with functional rules, TypeScript, Prettier, and import sorting:
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e={meta:{type:`problem`,docs:{description:`Avoid unsafe
|
|
1
|
+
const e=[`orThrow`,`expect`,`get`,`getOrThrow`,`unwrap`],t={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},unsafeMethods:{type:`array`,items:{type:`string`},default:[...e]}},additionalProperties:!1}],messages:{noUnsafeGet:`Avoid unsafe .{{method}}() call. Use .fold(), .map(), or .orElse() instead`,suggestOrElse:`Replace with .orElse(default) for a value fallback`,suggestFold:`Replace with .fold(onNone, onSome) for branch handling`}},create(t){let n=t.options[0]||{},r=n.allowInTests!==!1,i=n.unsafeMethods||e;function a(){let e=t.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function o(e){if(!e)return!1;let n=t.sourceCode.getText(e);if(/\b(Option|Either|Maybe|Result|Some|None|Left|Right)\b/.test(n)||/\.(map|flatMap|filter|fold)\s*\(/.test(n)||/\b(option|either|maybe|result|some|none|left|right)\w*\b/i.test(n))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?o(e.callee.object):!1}return{CallExpression(e){if(r&&a()||e.callee.type!==`MemberExpression`)return;let n=e.callee.property;if(!n||n.type!==`Identifier`)return;let s=n.name;if(i.includes(s)&&o(e.callee.object)){let n=t.sourceCode,r=n.getText(e.callee.object),i=e.arguments.map(e=>n.getText(e)).join(`, `),a=i?`; was ${s}(${i})`:``;t.report({node:e,messageId:`noUnsafeGet`,data:{method:s},suggest:[{messageId:`suggestOrElse`,fix(t){return t.replaceText(e,`${r}.orElse(undefined /* TODO: default${a} */)`)}},{messageId:`suggestFold`,fix(t){return t.replaceText(e,`${r}.fold(() => undefined /* TODO: onNone${a} */, (v) => v /* TODO: onSome */)`)}}]})}}}}};export{t as default};
|
|
2
2
|
//# sourceMappingURL=no-get-unsafe.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-get-unsafe.js","names":[],"sources":["../../src/rules/no-get-unsafe.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Avoid unsafe
|
|
1
|
+
{"version":3,"file":"no-get-unsafe.js","names":[],"sources":["../../src/rules/no-get-unsafe.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\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 unsafeMethods: {\n type: \"array\",\n items: { type: \"string\" },\n default: [...DEFAULT_UNSAFE_METHODS],\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noUnsafeGet: \"Avoid unsafe .{{method}}() call. Use .fold(), .map(), or .orElse() instead\",\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\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\n // Check if this looks like it's being called on a monadic type\n if (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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AC7B,GAAI,CAAC,GAAY,EAAS,OAAS,aAAc,OAEjD,IAAM,EAAa,EAAS,KACvB,KAAc,SAAS,CAAU,GAGlC,EAAc,EAAK,OAAO,MAAM,EAAG,CACrC,IAAM,EAAa,EAAQ,WACrB,EAAa,EAAW,QAAQ,EAAK,OAAO,MAAM,EAMlD,EAAW,EAAK,UAAU,IAAK,GAAe,EAAW,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAC9E,EAAY,EAAW,SAAS,EAAW,GAAG,EAAS,GAAK,GAElE,EAAQ,OAAO,CACb,OACA,UAAW,cACX,KAAM,CAAE,OAAQ,CAAW,EAC3B,QAAS,CACP,CACE,UAAW,gBACX,IAAI,EAAO,CACT,OAAO,EAAM,YAAY,EAAM,GAAG,EAAW,oCAAoC,EAAU,KAAK,CAClG,CACF,EACA,CACE,UAAW,cACX,IAAI,EAAO,CACT,OAAO,EAAM,YACX,EACA,GAAG,EAAW,uCAAuC,EAAU,kCACjE,CACF,CACF,CACF,CACF,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=new Set([`isSome`,`isRight`,`isSuccess`]),t=new Set([`isNone`,`isEmpty`,`isLeft`,`isFailure`]);function n(e){return e.type===`Literal`&&e.value===null||e.type===`Identifier`&&e.name===`undefined`}function r(n,r){if(n.type!==`CallExpression`||n.callee.type!==`MemberExpression`)return null;let i=n.callee.property.name,a=r.getText(n.callee.object);return e.has(i)?{obj:a,isNegated:!1}:t.has(i)?{obj:a,isNegated:!0}:null}function i(e){return e.alternate?e.alternate.type===`IfStatement`?1+i(e.alternate):2:1}const a={meta:{type:`suggestion`,docs:{description:`Prefer .fold() over if/else chains when working with monadic types`,recommended:!0},fixable:`code`,schema:[{type:`object`,properties:{minComplexity:{type:`integer`,minimum:1,default:2}},additionalProperties:!1}],messages:{preferFold:`Prefer .fold() over if/else when working with {{type}} types`,preferFoldTernary:`Consider using .fold() instead of ternary operator for {{type}}`}},create(e){let t=(e.options[0]||{}).minComplexity||2;function a(e,t){if(e.type===`BlockStatement`){let n=e.body;return n.length===1&&n[0].type===`ReturnStatement`?t.getText(n[0].argument):t.getText(e).slice(1,-1).trim()}
|
|
1
|
+
const e=new Set([`isSome`,`isRight`,`isSuccess`]),t=new Set([`isNone`,`isEmpty`,`isLeft`,`isFailure`]);function n(e){return e.type===`Literal`&&e.value===null||e.type===`Identifier`&&e.name===`undefined`}function r(n,r){if(n.type!==`CallExpression`||n.callee.type!==`MemberExpression`)return null;let i=n.callee.property.name,a=r.getText(n.callee.object);return e.has(i)?{obj:a,isNegated:!1}:t.has(i)?{obj:a,isNegated:!0}:null}function i(e){return e.alternate?e.alternate.type===`IfStatement`?1+i(e.alternate):2:1}const a={meta:{type:`suggestion`,docs:{description:`Prefer .fold() over if/else chains when working with monadic types`,recommended:!0},fixable:`code`,schema:[{type:`object`,properties:{minComplexity:{type:`integer`,minimum:1,default:2}},additionalProperties:!1}],messages:{preferFold:`Prefer .fold() over if/else when working with {{type}} types`,preferFoldTernary:`Consider using .fold() instead of ternary operator for {{type}}`}},create(e){let t=(e.options[0]||{}).minComplexity||2;function a(e,t){if(e.type===`BlockStatement`){let n=e.body;return n.length===1&&n[0].type===`ReturnStatement`?t.getText(n[0].argument):t.getText(e).slice(1,-1).trim()}return t.getText(e)}function o(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return e.replace(RegExp(`${n}\\.get\\(\\)`,`g`),`value`)}function s(t){let n=e.sourceCode;if(t.type!==`IfStatement`)return null;let i=t.test,s=t.consequent,c=t.alternate;if(!s||!c)return null;let l=r(i,n);if(!l)return null;let{obj:u,isNegated:d}=l;if(s.type===`BlockStatement`&&(s.body.length!==1||s.body[0].type!==`ReturnStatement`))return null;if(c.type===`BlockStatement`){if(c.body.length!==1||c.body[0].type!==`ReturnStatement`)return null}else if(c.type===`IfStatement`)return null;let f=a(s,n),p=a(c,n);return d?`${u}.fold(() => ${f}, (value) => ${o(p,u)})`:`${u}.fold(() => ${p}, (value) => ${o(f,u)})`}function c(t){let n=e.sourceCode;if(t.type!==`ConditionalExpression`)return null;let i=t.test,a=t.consequent,s=t.alternate,c=r(i,n);if(!c)return null;let{obj:l,isNegated:u}=c,d=n.getText(a),f=n.getText(s);return u?`${l}.fold(() => ${d}, (value) => ${o(f,l)})`:`${l}.fold(() => ${f}, (value) => ${o(d,l)})`}function l(e){if(e.type===`CallExpression`&&e.callee.type===`MemberExpression`){let t=e.callee.property.name;return[`isSome`,`isNone`,`isEmpty`,`isRight`,`isLeft`,`isSuccess`,`isFailure`].includes(t)}return!1}function u(t){let n=e.sourceCode.getText(t);if(/\.(isSome|isNone|isEmpty|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(t.type===`BinaryExpression`){if((t.operator===`===`||t.operator===`!==`||t.operator===`==`||t.operator===`!=`)&&(t.left.type===`Literal`&&(t.left.value===null||t.left.value===void 0)||t.right.type===`Literal`&&(t.right.value===null||t.right.value===void 0)))return{isMonadic:!0,type:`Option`,via:`nullable`};if(t.operator===`==`||t.operator===`!=`||t.operator===`===`||t.operator===`!==`){let e=t.left.type===`Identifier`&&t.left.name===`undefined`,n=t.right.type===`Identifier`&&t.right.name===`undefined`;if(e||n)return{isMonadic:!0,type:`Option`,via:`nullable`}}}return{isMonadic:!1,type:``,via:``}}function d(n){let r=n.test,a=u(r);a.isMonadic&&(n.parent&&n.parent.type===`IfStatement`||i(n)>=t&&e.report({node:n,messageId:`preferFold`,data:{type:a.type},fix(e){if(!l(n.test))return null;let t=s(n);return t?e.replaceText(n,t):null}}))}return{IfStatement(e){d(e)},ConditionalExpression(t){let r=u(t.test);r.via===`nullable`&&(n(t.consequent)||n(t.alternate))||r.isMonadic&&e.report({node:t,messageId:`preferFoldTernary`,data:{type:r.type},fix(e){if(!l(t.test))return null;let n=c(t);return n?e.replaceText(t,n):null}})}}}};export{a as default};
|
|
2
2
|
//# sourceMappingURL=prefer-fold.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-fold.js","names":[],"sources":["../../src/rules/prefer-fold.ts"],"sourcesContent":["import type { Rule, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/** Methods on a monadic value that mean \"this is the Some/Right/Success path.\" */\nconst POSITIVE_PREDICATES: ReadonlySet<string> = new Set([\"isSome\", \"isRight\", \"isSuccess\"])\n/** Methods that mean \"this is the None/Left/Failure path.\" */\nconst NEGATIVE_PREDICATES: ReadonlySet<string> = new Set([\"isNone\", \"isEmpty\", \"isLeft\", \"isFailure\"])\n\n/**\n * A literal `null` or the `undefined` identifier. A ternary that yields one of these in a branch is\n * building an optional value (prefer-option's concern), not folding a monad — so the untyped nullable\n * heuristic must not treat `x !== undefined ? \"a\" : undefined` as a fold candidate.\n */\nfunction isNullishLiteral(node: ASTNode): boolean {\n return (node.type === \"Literal\" && node.value === null) || (node.type === \"Identifier\" && node.name === \"undefined\")\n}\n\n/**\n * If `test` is a monadic predicate call like `option.isSome()` or\n * `either.isLeft()`, returns the receiver expression's text plus whether the\n * predicate is the \"absence\" side. Returns null for anything else.\n */\nfunction extractMonadicTest(test: ASTNode, sourceCode: SourceCode): { obj: string; isNegated: boolean } | null {\n if (test.type !== \"CallExpression\" || test.callee.type !== \"MemberExpression\") return null\n const methodName = test.callee.property.name\n const obj = sourceCode.getText(test.callee.object)\n if (POSITIVE_PREDICATES.has(methodName)) return { obj, isNegated: false }\n if (NEGATIVE_PREDICATES.has(methodName)) return { obj, isNegated: true }\n return null\n}\n\n/**\n * Length of an if/else-if/else chain rooted at `node`. Counts the root as 1\n * and adds 1 per linked alternate IfStatement. Terminates on a non-If\n * alternate (the final `else { ... }`) which counts as the last branch.\n */\nfunction ifElseChainLength(node: ASTNode): number {\n if (!node.alternate) return 1\n if (node.alternate.type === \"IfStatement\") return 1 + ifElseChainLength(node.alternate as ASTNode)\n return 2 // root + the terminal else\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .fold() over if/else chains when working with monadic types\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n minComplexity: {\n type: \"integer\",\n minimum: 1,\n default: 2,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFold: \"Prefer .fold() over if/else when working with {{type}} types\",\n preferFoldTernary: \"Consider using .fold() instead of ternary operator for {{type}}\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const minComplexity = options.minComplexity || 2\n\n function extractBodyForFold(node: ASTNode, sourceCode: SourceCode): string {\n if (node.type === \"BlockStatement\") {\n const statements = node.body\n if (statements.length === 1 && statements[0].type === \"ReturnStatement\") {\n // Extract just the return value, not the return statement\n return sourceCode.getText(statements[0].argument)\n } else {\n // For complex blocks, keep the full structure but remove outer braces\n return sourceCode.getText(node).slice(1, -1).trim()\n }\n } else {\n return sourceCode.getText(node)\n }\n }\n\n function replaceGetWithValue(body: string, monadicObj: string): string {\n // Replace monadicObj.get() with value, and monadicObj.get().chain with value.chain\n const escaped = monadicObj.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n return body.replace(new RegExp(`${escaped}\\\\.get\\\\(\\\\)`, \"g\"), \"value\")\n }\n\n function generateFoldFromIf(node: ASTNode): string | null {\n const sourceCode = context.sourceCode\n\n if (node.type !== \"IfStatement\") return null\n\n const test = node.test\n const consequent = node.consequent\n const alternate = node.alternate\n\n if (!consequent || !alternate) return null\n\n // Extract the monadic object + negation from the test predicate.\n const extracted = extractMonadicTest(test, sourceCode)\n if (!extracted) return null\n const { obj: monadicObj, isNegated } = extracted\n\n // Only handle simple cases - single return statements in blocks, no nested if statements\n if (consequent.type === \"BlockStatement\") {\n if (consequent.body.length !== 1 || consequent.body[0].type !== \"ReturnStatement\") {\n return null // Too complex, don't auto-fix\n }\n }\n\n if (alternate.type === \"BlockStatement\") {\n if (alternate.body.length !== 1 || alternate.body[0].type !== \"ReturnStatement\") {\n return null // Too complex, don't auto-fix\n }\n } else if (alternate.type === \"IfStatement\") {\n return null // Nested if/else is too complex for simple fold pattern\n }\n\n // Extract consequent and alternate bodies\n const thenBody = extractBodyForFold(consequent, sourceCode)\n const elseBody = extractBodyForFold(alternate, sourceCode)\n\n // Generate fold expression — replace .get() calls with value parameter\n if (isNegated) {\n // isNone/isLeft/isFailure: consequent is the \"none\" branch, alternate is the \"some\" branch\n const successBody = replaceGetWithValue(elseBody, monadicObj)\n return `${monadicObj}.fold(() => ${thenBody}, (value) => ${successBody})`\n } else {\n // isSome/isRight/isSuccess: consequent is the \"some\" branch, alternate is the \"none\" branch\n const successBody = replaceGetWithValue(thenBody, monadicObj)\n return `${monadicObj}.fold(() => ${elseBody}, (value) => ${successBody})`\n }\n }\n\n function generateFoldFromTernary(node: ASTNode): string | null {\n const sourceCode = context.sourceCode\n\n if (node.type !== \"ConditionalExpression\") return null\n\n const test = node.test\n const consequent = node.consequent\n const alternate = node.alternate\n\n // Extract the monadic object + negation from the test predicate.\n const extracted = extractMonadicTest(test, sourceCode)\n if (!extracted) return null\n const { obj: monadicObj, isNegated } = extracted\n\n const thenExpr = sourceCode.getText(consequent)\n const elseExpr = sourceCode.getText(alternate)\n\n // Generate fold expression — replace .get() calls with value parameter\n if (isNegated) {\n const successExpr = replaceGetWithValue(elseExpr, monadicObj)\n return `${monadicObj}.fold(() => ${thenExpr}, (value) => ${successExpr})`\n } else {\n const successExpr = replaceGetWithValue(thenExpr, monadicObj)\n return `${monadicObj}.fold(() => ${elseExpr}, (value) => ${successExpr})`\n }\n }\n\n function shouldAutoFix(node: ASTNode): boolean {\n // Only auto-fix when we detect functype method calls (indicating it's already a functype instance)\n if (node.type === \"CallExpression\" && node.callee.type === \"MemberExpression\") {\n const methodName = node.callee.property.name\n // These methods indicate the object is already a functype instance\n return [\"isSome\", \"isNone\", \"isEmpty\", \"isRight\", \"isLeft\", \"isSuccess\", \"isFailure\"].includes(methodName)\n }\n return false\n }\n\n // `via` records HOW we matched: a functype predicate call (`method`, precise) vs the untyped\n // null/undefined heuristic (`nullable`, a guess that can't tell a real Option from a plain nullable).\n function isMonadicCheck(node: ASTNode): { isMonadic: boolean; type: string; via: \"method\" | \"nullable\" | \"\" } {\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Check for common monadic type checks\n if (/\\.(isSome|isNone|isEmpty|isDefined)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Option\", via: \"method\" }\n }\n\n if (/\\.(isLeft|isRight)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Either\", via: \"method\" }\n }\n\n if (/\\.(isSuccess|isFailure)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Result\", via: \"method\" }\n }\n\n // Check for null/undefined checks on variables that might be Options\n if (node.type === \"BinaryExpression\") {\n if (\n (node.operator === \"===\" || node.operator === \"!==\" || node.operator === \"==\" || node.operator === \"!=\") &&\n ((node.left.type === \"Literal\" && (node.left.value === null || node.left.value === undefined)) ||\n (node.right.type === \"Literal\" && (node.right.value === null || node.right.value === undefined)))\n ) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n\n // Check for === or == with undefined identifier\n if (node.operator === \"==\" || node.operator === \"!=\" || node.operator === \"===\" || node.operator === \"!==\") {\n const leftIsUndefined = node.left.type === \"Identifier\" && node.left.name === \"undefined\"\n const rightIsUndefined = node.right.type === \"Identifier\" && node.right.name === \"undefined\"\n\n if (leftIsUndefined || rightIsUndefined) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n }\n }\n\n return { isMonadic: false, type: \"\", via: \"\" }\n }\n\n function analyzeIfStatement(node: ASTNode) {\n const test = node.test\n const monadicInfo = isMonadicCheck(test)\n\n if (!monadicInfo.isMonadic) return\n\n // Don't analyze if this is part of a larger if/else chain\n // (only analyze the outermost if statement)\n if (node.parent && node.parent.type === \"IfStatement\") return\n\n // Count the complexity (if/else if/else chain)\n if (ifElseChainLength(node) >= minComplexity) {\n context.report({\n node,\n messageId: \"preferFold\",\n data: { type: monadicInfo.type },\n fix(fixer) {\n // Only auto-fix if we can detect it's already a functype instance\n if (!shouldAutoFix(node.test)) {\n return null\n }\n const replacement = generateFoldFromIf(node)\n if (replacement) {\n return fixer.replaceText(node, replacement)\n }\n return null\n },\n })\n }\n }\n\n return {\n IfStatement(node: ASTNode) {\n analyzeIfStatement(node)\n },\n\n ConditionalExpression(node: ASTNode) {\n const monadicInfo = isMonadicCheck(node.test)\n // The untyped nullable heuristic can't distinguish a real Option from a plain nullable primitive.\n // When it fires on a ternary that yields `undefined`/`null` in a branch, that's optional value\n // construction (prefer-option's concern), not a fold — skip it. False positive this kills:\n // `x !== undefined ? \"a\" : undefined`. Predicate-call matches (`.isSome()` etc.) are unaffected.\n if (monadicInfo.via === \"nullable\" && (isNullishLiteral(node.consequent) || isNullishLiteral(node.alternate))) {\n return\n }\n if (monadicInfo.isMonadic) {\n context.report({\n node,\n messageId: \"preferFoldTernary\",\n data: { type: monadicInfo.type },\n fix(fixer) {\n // Only auto-fix if we can detect it's already a functype instance\n if (!shouldAutoFix(node.test)) {\n return null\n }\n const replacement = generateFoldFromTernary(node)\n if (replacement) {\n return fixer.replaceText(node, replacement)\n }\n return null\n },\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAKA,MAAM,EAA2C,IAAI,IAAI,CAAC,SAAU,UAAW,WAAW,CAAC,EAErF,EAA2C,IAAI,IAAI,CAAC,SAAU,UAAW,SAAU,WAAW,CAAC,EAOrG,SAAS,EAAiB,EAAwB,CAChD,OAAQ,EAAK,OAAS,WAAa,EAAK,QAAU,MAAU,EAAK,OAAS,cAAgB,EAAK,OAAS,WAC1G,CAOA,SAAS,EAAmB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AmB,EAAe,CACzC,IAAM,EAAO,EAAK,KACZ,EAAc,EAAe,CAAI,EAElC,EAAY,YAIb,EAAK,QAAU,EAAK,OAAO,OAAS,eAGpC,EAAkB,CAAI,GAAK,GAC7B,EAAQ,OAAO,CACb,OACA,UAAW,aACX,KAAM,CAAE,KAAM,EAAY,IAAK,EAC/B,IAAI,EAAO,CAET,GAAI,CAAC,EAAc,EAAK,IAAI,EAC1B,OAAO,KAET,IAAM,EAAc,EAAmB,CAAI,EAI3C,OAHI,EACK,EAAM,YAAY,EAAM,CAAW,EAErC,IACT,CACF,CAAC,EAEL,CAEA,MAAO,CACL,YAAY,EAAe,CACzB,EAAmB,CAAI,CACzB,EAEA,sBAAsB,EAAe,CACnC,IAAM,EAAc,EAAe,EAAK,IAAI,EAKxC,EAAY,MAAQ,aAAe,EAAiB,EAAK,UAAU,GAAK,EAAiB,EAAK,SAAS,IAGvG,EAAY,WACd,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,KAAM,EAAY,IAAK,EAC/B,IAAI,EAAO,CAET,GAAI,CAAC,EAAc,EAAK,IAAI,EAC1B,OAAO,KAET,IAAM,EAAc,EAAwB,CAAI,EAIhD,OAHI,EACK,EAAM,YAAY,EAAM,CAAW,EAErC,IACT,CACF,CAAC,CAEL,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-fold.js","names":[],"sources":["../../src/rules/prefer-fold.ts"],"sourcesContent":["import type { Rule, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/** Methods on a monadic value that mean \"this is the Some/Right/Success path.\" */\nconst POSITIVE_PREDICATES: ReadonlySet<string> = new Set([\"isSome\", \"isRight\", \"isSuccess\"])\n/** Methods that mean \"this is the None/Left/Failure path.\" */\nconst NEGATIVE_PREDICATES: ReadonlySet<string> = new Set([\"isNone\", \"isEmpty\", \"isLeft\", \"isFailure\"])\n\n/**\n * A literal `null` or the `undefined` identifier. A ternary that yields one of these in a branch is\n * building an optional value (prefer-option's concern), not folding a monad — so the untyped nullable\n * heuristic must not treat `x !== undefined ? \"a\" : undefined` as a fold candidate.\n */\nfunction isNullishLiteral(node: ASTNode): boolean {\n return (node.type === \"Literal\" && node.value === null) || (node.type === \"Identifier\" && node.name === \"undefined\")\n}\n\n/**\n * If `test` is a monadic predicate call like `option.isSome()` or\n * `either.isLeft()`, returns the receiver expression's text plus whether the\n * predicate is the \"absence\" side. Returns null for anything else.\n */\nfunction extractMonadicTest(test: ASTNode, sourceCode: SourceCode): { obj: string; isNegated: boolean } | null {\n if (test.type !== \"CallExpression\" || test.callee.type !== \"MemberExpression\") return null\n const methodName = test.callee.property.name\n const obj = sourceCode.getText(test.callee.object)\n if (POSITIVE_PREDICATES.has(methodName)) return { obj, isNegated: false }\n if (NEGATIVE_PREDICATES.has(methodName)) return { obj, isNegated: true }\n return null\n}\n\n/**\n * Length of an if/else-if/else chain rooted at `node`. Counts the root as 1\n * and adds 1 per linked alternate IfStatement. Terminates on a non-If\n * alternate (the final `else { ... }`) which counts as the last branch.\n */\nfunction ifElseChainLength(node: ASTNode): number {\n if (!node.alternate) return 1\n if (node.alternate.type === \"IfStatement\") return 1 + ifElseChainLength(node.alternate as ASTNode)\n return 2 // root + the terminal else\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer .fold() over if/else chains when working with monadic types\",\n recommended: true,\n },\n fixable: \"code\",\n schema: [\n {\n type: \"object\",\n properties: {\n minComplexity: {\n type: \"integer\",\n minimum: 1,\n default: 2,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFold: \"Prefer .fold() over if/else when working with {{type}} types\",\n preferFoldTernary: \"Consider using .fold() instead of ternary operator for {{type}}\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const minComplexity = options.minComplexity || 2\n\n function extractBodyForFold(node: ASTNode, sourceCode: SourceCode): string {\n if (node.type === \"BlockStatement\") {\n const statements = node.body\n if (statements.length === 1 && statements[0].type === \"ReturnStatement\") {\n // Extract just the return value, not the return statement\n return sourceCode.getText(statements[0].argument)\n } else {\n // For complex blocks, keep the full structure but remove outer braces\n return sourceCode.getText(node).slice(1, -1).trim()\n }\n } else {\n return sourceCode.getText(node)\n }\n }\n\n function replaceGetWithValue(body: string, monadicObj: string): string {\n // Replace monadicObj.get() with value, and monadicObj.get().chain with value.chain\n const escaped = monadicObj.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n return body.replace(new RegExp(`${escaped}\\\\.get\\\\(\\\\)`, \"g\"), \"value\")\n }\n\n function generateFoldFromIf(node: ASTNode): string | null {\n const sourceCode = context.sourceCode\n\n if (node.type !== \"IfStatement\") return null\n\n const test = node.test\n const consequent = node.consequent\n const alternate = node.alternate\n\n if (!consequent || !alternate) return null\n\n // Extract the monadic object + negation from the test predicate.\n const extracted = extractMonadicTest(test, sourceCode)\n if (!extracted) return null\n const { obj: monadicObj, isNegated } = extracted\n\n // Only handle simple cases - single return statements in blocks, no nested if statements\n if (consequent.type === \"BlockStatement\") {\n if (consequent.body.length !== 1 || consequent.body[0].type !== \"ReturnStatement\") {\n return null // Too complex, don't auto-fix\n }\n }\n\n if (alternate.type === \"BlockStatement\") {\n if (alternate.body.length !== 1 || alternate.body[0].type !== \"ReturnStatement\") {\n return null // Too complex, don't auto-fix\n }\n } else if (alternate.type === \"IfStatement\") {\n return null // Nested if/else is too complex for simple fold pattern\n }\n\n // Extract consequent and alternate bodies\n const thenBody = extractBodyForFold(consequent, sourceCode)\n const elseBody = extractBodyForFold(alternate, sourceCode)\n\n // Generate fold expression — replace .get() calls with value parameter\n if (isNegated) {\n // isNone/isLeft/isFailure: consequent is the \"none\" branch, alternate is the \"some\" branch\n const successBody = replaceGetWithValue(elseBody, monadicObj)\n return `${monadicObj}.fold(() => ${thenBody}, (value) => ${successBody})`\n } else {\n // isSome/isRight/isSuccess: consequent is the \"some\" branch, alternate is the \"none\" branch\n const successBody = replaceGetWithValue(thenBody, monadicObj)\n return `${monadicObj}.fold(() => ${elseBody}, (value) => ${successBody})`\n }\n }\n\n function generateFoldFromTernary(node: ASTNode): string | null {\n const sourceCode = context.sourceCode\n\n if (node.type !== \"ConditionalExpression\") return null\n\n const test = node.test\n const consequent = node.consequent\n const alternate = node.alternate\n\n // Extract the monadic object + negation from the test predicate.\n const extracted = extractMonadicTest(test, sourceCode)\n if (!extracted) return null\n const { obj: monadicObj, isNegated } = extracted\n\n const thenExpr = sourceCode.getText(consequent)\n const elseExpr = sourceCode.getText(alternate)\n\n // Generate fold expression — replace .get() calls with value parameter\n if (isNegated) {\n const successExpr = replaceGetWithValue(elseExpr, monadicObj)\n return `${monadicObj}.fold(() => ${thenExpr}, (value) => ${successExpr})`\n } else {\n const successExpr = replaceGetWithValue(thenExpr, monadicObj)\n return `${monadicObj}.fold(() => ${elseExpr}, (value) => ${successExpr})`\n }\n }\n\n function shouldAutoFix(node: ASTNode): boolean {\n // Only auto-fix when we detect functype method calls (indicating it's already a functype instance)\n if (node.type === \"CallExpression\" && node.callee.type === \"MemberExpression\") {\n const methodName = node.callee.property.name\n // These methods indicate the object is already a functype instance\n return [\"isSome\", \"isNone\", \"isEmpty\", \"isRight\", \"isLeft\", \"isSuccess\", \"isFailure\"].includes(methodName)\n }\n return false\n }\n\n // `via` records HOW we matched: a functype predicate call (`method`, precise) vs the untyped\n // null/undefined heuristic (`nullable`, a guess that can't tell a real Option from a plain nullable).\n function isMonadicCheck(node: ASTNode): { isMonadic: boolean; type: string; via: \"method\" | \"nullable\" | \"\" } {\n const sourceCode = context.sourceCode\n const text = sourceCode.getText(node)\n\n // Check for common monadic type checks\n if (/\\.(isSome|isNone|isEmpty|isDefined)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Option\", via: \"method\" }\n }\n\n if (/\\.(isLeft|isRight)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Either\", via: \"method\" }\n }\n\n if (/\\.(isSuccess|isFailure)\\s*\\(\\s*\\)/.test(text)) {\n return { isMonadic: true, type: \"Result\", via: \"method\" }\n }\n\n // Check for null/undefined checks on variables that might be Options\n if (node.type === \"BinaryExpression\") {\n if (\n (node.operator === \"===\" || node.operator === \"!==\" || node.operator === \"==\" || node.operator === \"!=\") &&\n ((node.left.type === \"Literal\" && (node.left.value === null || node.left.value === undefined)) ||\n (node.right.type === \"Literal\" && (node.right.value === null || node.right.value === undefined)))\n ) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n\n // Check for === or == with undefined identifier\n if (node.operator === \"==\" || node.operator === \"!=\" || node.operator === \"===\" || node.operator === \"!==\") {\n const leftIsUndefined = node.left.type === \"Identifier\" && node.left.name === \"undefined\"\n const rightIsUndefined = node.right.type === \"Identifier\" && node.right.name === \"undefined\"\n\n if (leftIsUndefined || rightIsUndefined) {\n return { isMonadic: true, type: \"Option\", via: \"nullable\" }\n }\n }\n }\n\n return { isMonadic: false, type: \"\", via: \"\" }\n }\n\n function analyzeIfStatement(node: ASTNode) {\n const test = node.test\n const monadicInfo = isMonadicCheck(test)\n\n if (!monadicInfo.isMonadic) return\n\n // Don't analyze if this is part of a larger if/else chain\n // (only analyze the outermost if statement)\n if (node.parent && node.parent.type === \"IfStatement\") return\n\n // Count the complexity (if/else if/else chain)\n if (ifElseChainLength(node) >= minComplexity) {\n context.report({\n node,\n messageId: \"preferFold\",\n data: { type: monadicInfo.type },\n fix(fixer) {\n // Only auto-fix if we can detect it's already a functype instance\n if (!shouldAutoFix(node.test)) {\n return null\n }\n const replacement = generateFoldFromIf(node)\n if (replacement) {\n return fixer.replaceText(node, replacement)\n }\n return null\n },\n })\n }\n }\n\n return {\n IfStatement(node: ASTNode) {\n analyzeIfStatement(node)\n },\n\n ConditionalExpression(node: ASTNode) {\n const monadicInfo = isMonadicCheck(node.test)\n // The untyped nullable heuristic can't distinguish a real Option from a plain nullable primitive.\n // When it fires on a ternary that yields `undefined`/`null` in a branch, that's optional value\n // construction (prefer-option's concern), not a fold — skip it. False positive this kills:\n // `x !== undefined ? \"a\" : undefined`. Predicate-call matches (`.isSome()` etc.) are unaffected.\n if (monadicInfo.via === \"nullable\" && (isNullishLiteral(node.consequent) || isNullishLiteral(node.alternate))) {\n return\n }\n if (monadicInfo.isMonadic) {\n context.report({\n node,\n messageId: \"preferFoldTernary\",\n data: { type: monadicInfo.type },\n fix(fixer) {\n // Only auto-fix if we can detect it's already a functype instance\n if (!shouldAutoFix(node.test)) {\n return null\n }\n const replacement = generateFoldFromTernary(node)\n if (replacement) {\n return fixer.replaceText(node, replacement)\n }\n return null\n },\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAKA,MAAM,EAA2C,IAAI,IAAI,CAAC,SAAU,UAAW,WAAW,CAAC,EAErF,EAA2C,IAAI,IAAI,CAAC,SAAU,UAAW,SAAU,WAAW,CAAC,EAOrG,SAAS,EAAiB,EAAwB,CAChD,OAAQ,EAAK,OAAS,WAAa,EAAK,QAAU,MAAU,EAAK,OAAS,cAAgB,EAAK,OAAS,WAC1G,CAOA,SAAS,EAAmB,EAAe,EAAoE,CAC7G,GAAI,EAAK,OAAS,kBAAoB,EAAK,OAAO,OAAS,mBAAoB,OAAO,KACtF,IAAM,EAAa,EAAK,OAAO,SAAS,KAClC,EAAM,EAAW,QAAQ,EAAK,OAAO,MAAM,EAGjD,OAFI,EAAoB,IAAI,CAAU,EAAU,CAAE,MAAK,UAAW,EAAM,EACpE,EAAoB,IAAI,CAAU,EAAU,CAAE,MAAK,UAAW,EAAK,EAChE,IACT,CAOA,SAAS,EAAkB,EAAuB,CAGhD,OAFK,EAAK,UACN,EAAK,UAAU,OAAS,cAAsB,EAAI,EAAkB,EAAK,SAAoB,EAC1F,EAFqB,CAG9B,CAEA,MAAM,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,KAAM,CACJ,YAAa,qEACb,YAAa,EACf,EACA,QAAS,OACT,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,cAAe,CACb,KAAM,UACN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EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,KAAM,EAAY,IAAK,EAC/B,IAAI,EAAO,CAET,GAAI,CAAC,EAAc,EAAK,IAAI,EAC1B,OAAO,KAET,IAAM,EAAc,EAAwB,CAAI,EAIhD,OAHI,EACK,EAAM,YAAY,EAAM,CAAW,EAErC,IACT,CACF,CAAC,CAEL,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getFunctypeImportsLegacy as e,isFunctypeCall as t}from"../utils/functype-detection.js";import{createImportFixer as n,hasFunctypeSymbol as r}from"../utils/import-fixer.js";const i=new Set([`parent`,`loc`,`range`]);function a(e){return Object.entries(e).filter(([e])=>!i.has(e)).flatMap(([,e])=>Array.isArray(e)?e:[e]).filter(e=>typeof e==`object`&&!!e)}function o(e,t){let n=e?.parent;return n?t(n)||o(n,t):!1}function s(e){return e?.type===`CallExpression`&&e.callee.type===`MemberExpression`&&e.callee.object.type===`Identifier`&&e.callee.object.name===`List`&&[`from`,`of`].includes(e.callee.property.name)}function c(e){return e.type===`VariableDeclarator`&&!!e.id?.typeAnnotation||e.type===`TSTypeAnnotation`}const l={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer List<T> over native arrays for immutable collections`,recommended:!0},schema:[{type:`object`,properties:{allowArraysInTests:{type:`boolean`,default:!0},allowReadonlyArrays:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferList:`Prefer List<{{type}}> over array type {{arrayType}}`,preferListLiteral:`Prefer List.of(...) or List.from([...]) over array literal`,suggestListType:`Replace with List<{{type}}>`,suggestListOf:`Replace with List.of(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(i){let l=i.options[0]||{},u=l.allowArraysInTests!==!1,d=l.allowReadonlyArrays!==!1,f=e(i);function
|
|
1
|
+
import{getFunctypeImportsLegacy as e,isFunctypeCall as t}from"../utils/functype-detection.js";import{createImportFixer as n,hasFunctypeSymbol as r}from"../utils/import-fixer.js";const i=new Set([`parent`,`loc`,`range`]);function a(e){return Object.entries(e).filter(([e])=>!i.has(e)).flatMap(([,e])=>Array.isArray(e)?e:[e]).filter(e=>typeof e==`object`&&!!e)}function o(e,t){let n=e?.parent;return n?t(n)||o(n,t):!1}function s(e){return e?.type===`CallExpression`&&e.callee.type===`MemberExpression`&&e.callee.object.type===`Identifier`&&e.callee.object.name===`List`&&[`from`,`of`].includes(e.callee.property.name)}function c(e){return e.type===`VariableDeclarator`&&!!e.id?.typeAnnotation||e.type===`TSTypeAnnotation`}const l={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer List<T> over native arrays for immutable collections`,recommended:!0},schema:[{type:`object`,properties:{allowArraysInTests:{type:`boolean`,default:!0},allowReadonlyArrays:{type:`boolean`,default:!0},allowArrayLiterals:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{preferList:`Prefer List<{{type}}> over array type {{arrayType}}`,preferListLiteral:`Prefer List.of(...) or List.from([...]) over array literal`,suggestListType:`Replace with List<{{type}}>`,suggestListOf:`Replace with List.of(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(i){let l=i.options[0]||{},u=l.allowArraysInTests!==!1,d=l.allowReadonlyArrays!==!1,f=l.allowArrayLiterals===!0,p=e(i);function m(){let e=i.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function h(e,t){function n(e){return e.type===`TSTypeParameterInstantiation`&&e.params&&e.params[0]?t.getText(e.params[0]):a(e).filter(e=>typeof e?.type==`string`).map(e=>n(e)).find(e=>e!==null)??null}return n(e)}return{TSArrayType(e){if(u&&m())return;let t=e.parent,a=t?.type===`TSTypeOperator`&&t.operator===`readonly`;if(a&&d)return;let o=i.sourceCode,s=o.getText(e.elementType),c=a?t:e,l=o.getText(c),f=[{messageId:`suggestListType`,data:{type:s},fix(e){return e.replaceText(c,`List<${s}>`)}}];r(o,`List`)||f.push({messageId:`suggestAddImport`,data:{symbol:`List`},fix:n(o,`List`)}),i.report({node:c,messageId:`preferList`,data:{type:s,arrayType:l},suggest:f})},TSTypeReference(e){if(u&&m())return;let t=i.sourceCode;if(!e.typeName)return;let a=e.typeName.type===`Identifier`?e.typeName.name:t.getText(e.typeName);if(a===`Array`){let a=h(e,t),o=t.getText(e),s=a||`T`,c=[{messageId:`suggestListType`,data:{type:s},fix(t){return t.replaceText(e,`List<${s}>`)}}];r(t,`List`)||c.push({messageId:`suggestAddImport`,data:{symbol:`List`},fix:n(t,`List`)}),i.report({node:e,messageId:`preferList`,data:{type:s,arrayType:o},suggest:c})}if(a===`ReadonlyArray`){if(d)return;let a=h(e,t),o=t.getText(e),s=a||`T`,c=[{messageId:`suggestListType`,data:{type:s},fix(t){return t.replaceText(e,`List<${s}>`)}}];r(t,`List`)||c.push({messageId:`suggestAddImport`,data:{symbol:`List`},fix:n(t,`List`)}),i.report({node:e,messageId:`preferList`,data:{type:s,arrayType:o},suggest:c})}},ArrayExpression(e){if(u&&m()||f||e.elements.length===0)return;let a=e.parent;if(a&&t(a,p)||s(a)||o(e,e=>e.type===`ArrayExpression`)||o(e,c))return;if(e.elements.some(e=>e!==null&&e.type===`SpreadElement`)){i.report({node:e,messageId:`preferListLiteral`});return}let l=i.sourceCode,d=e.elements.filter(e=>e!==null).map(e=>l.getText(e)),h=[{messageId:`suggestListOf`,fix(t){return t.replaceText(e,`List.of(${d.join(`, `)})`)}}];r(l,`List`)||h.push({messageId:`suggestAddImport`,data:{symbol:`List`},fix:n(l,`List`)}),i.report({node:e,messageId:`preferListLiteral`,suggest:h})}}}};export{l as default};
|
|
2
2
|
//# sourceMappingURL=prefer-list.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-list.js","names":[],"sources":["../../src/rules/prefer-list.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImportsLegacy, isFunctypeCall } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\n/** AST keys that don't represent syntax children — back-edges and source metadata. */\nconst NON_CHILD_KEYS: ReadonlySet<string> = new Set([\"parent\", \"loc\", \"range\"])\n\n/** AST children of `node`: drops back-edges, flattens array-valued keys, filters non-object leaves. */\nfunction astChildren(node: ASTNode): readonly unknown[] {\n return Object.entries(node)\n .filter(([k]) => !NON_CHILD_KEYS.has(k))\n .flatMap(([, v]) => (Array.isArray(v) ? v : [v]))\n .filter((v) => v !== null && typeof v === \"object\")\n}\n\n/** True iff any ancestor of `node` satisfies `pred`. Pure tail recursion. */\nfunction ancestorSatisfies(node: ASTNode | null | undefined, pred: (n: ASTNode) => boolean): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return pred(parent) || ancestorSatisfies(parent, pred)\n}\n\n/** `parent` is `List.from(arr)` or `List.of(...arr)`. */\nfunction isListFactoryArg(parent: ASTNode | null | undefined): boolean {\n return (\n parent?.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n parent.callee.object.type === \"Identifier\" &&\n parent.callee.object.name === \"List\" &&\n [\"from\", \"of\"].includes(parent.callee.property.name)\n )\n}\n\n/** `node` is a VariableDeclarator with its own type annotation, or a TSTypeAnnotation node directly. */\nfunction hasOwnTypeAnnotation(node: ASTNode): boolean {\n return (node.type === \"VariableDeclarator\" && Boolean(node.id?.typeAnnotation)) || node.type === \"TSTypeAnnotation\"\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer List<T> over native arrays for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowArraysInTests: {\n type: \"boolean\",\n default: true,\n },\n allowReadonlyArrays: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferList: \"Prefer List<{{type}}> over array type {{arrayType}}\",\n preferListLiteral: \"Prefer List.of(...) or List.from([...]) over array literal\",\n suggestListType: \"Replace with List<{{type}}>\",\n suggestListOf: \"Replace with List.of(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowArraysInTests = options.allowArraysInTests !== false\n const allowReadonlyArrays = options.allowReadonlyArrays !== false\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function findTypeParameter(node: ASTNode, sourceCode: typeof context.sourceCode): string | null {\n // Pure pre-order search: look at this node, then recursively at each\n // child until we find a TSTypeParameterInstantiation with a first param.\n function findInNode(n: ASTNode): string | null {\n if (n.type === \"TSTypeParameterInstantiation\" && n.params && n.params[0]) {\n return sourceCode.getText(n.params[0])\n }\n const results = astChildren(n)\n .filter((c): c is ASTNode => typeof (c as ASTNode)?.type === \"string\")\n .map((child) => findInNode(child))\n return results.find((r) => r !== null) ?? null\n }\n return findInNode(node)\n }\n\n return {\n TSArrayType(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n\n const sourceCode = context.sourceCode\n const elementType = sourceCode.getText(node.elementType)\n const fullType = sourceCode.getText(node)\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: elementType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List<${elementType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferList\",\n data: {\n type: elementType,\n arrayType: fullType,\n },\n suggest,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n\n const sourceCode = context.sourceCode\n\n // Get type name - handle both simple identifiers and member expressions\n if (!node.typeName) return // No type name found\n\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n // Handle Array<T> syntax\n if (typeName === \"Array\") {\n // Look for type parameters in child nodes\n const typeParam = findTypeParameter(node, sourceCode)\n const fullType = sourceCode.getText(node)\n\n // Skip if already readonly\n if (allowReadonlyArrays && fullType.startsWith(\"readonly\")) return\n\n const resolvedType = typeParam || \"T\"\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: resolvedType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List<${resolvedType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferList\",\n data: {\n type: resolvedType,\n arrayType: fullType,\n },\n suggest,\n })\n }\n\n // Handle ReadonlyArray<T> - suggest List even if allowing readonly arrays\n if (typeName === \"ReadonlyArray\") {\n const typeParam = findTypeParameter(node, sourceCode)\n const fullType = sourceCode.getText(node)\n const resolvedType = typeParam || \"T\"\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: resolvedType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List<${resolvedType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferList\",\n data: {\n type: resolvedType,\n arrayType: fullType,\n },\n suggest,\n })\n }\n },\n\n ArrayExpression(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n\n // Only flag non-empty arrays to avoid noise\n if (node.elements.length === 0) return\n\n const parent = node.parent\n\n // Don't flag arrays that are already arguments to functype calls.\n if (parent && isFunctypeCall(parent, functypeImports)) return\n\n // Don't flag arrays that are arguments to List.from / List.of.\n if (isListFactoryArg(parent)) return\n\n // Don't flag nested array literals — let the outermost one handle it.\n if (ancestorSatisfies(node, (n) => n.type === \"ArrayExpression\")) return\n\n // Don't flag array literals that already live in a type-annotated\n // context (those are handled by the type-checking rules).\n if (ancestorSatisfies(node, hasOwnTypeAnnotation)) return\n\n // Check if any element is a SpreadElement — ambiguous semantics, skip suggestions\n const hasSpread = node.elements.some((el) => el !== null && el.type === \"SpreadElement\")\n\n if (hasSpread) {\n context.report({\n node,\n messageId: \"preferListLiteral\",\n })\n return\n }\n\n const sourceCode = context.sourceCode\n const elementTexts = node.elements.filter((el) => el !== null).map((el) => sourceCode.getText(el))\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListOf\",\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List.of(${elementTexts.join(\", \")})`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferListLiteral\",\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"kLAOA,MAAM,EAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAG9E,SAAS,EAAY,EAAmC,CACtD,OAAO,OAAO,QAAQ,CAAI,CAAC,CACxB,QAAQ,CAAC,KAAO,CAAC,EAAe,IAAI,CAAC,CAAC,CAAC,CACvC,SAAS,EAAG,KAAQ,MAAM,QAAQ,CAAC,EAAI,EAAI,CAAC,CAAC,CAAE,CAAC,CAChD,OAAQ,GAAoB,OAAO,GAAM,YAA3B,CAAmC,CACtD,CAGA,SAAS,EAAkB,EAAkC,EAA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,IAAI,EAAuB,CACzB,OAAO,EAAM,YAAY,EAAM,WAAW,EAAa,KAAK,IAAI,EAAE,EAAE,CACtE,CACF,CACF,EAEK,EAAkB,EAAY,MAAM,GACvC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,MAAO,EACvB,IAAK,EAAkB,EAAY,MAAM,CAC3C,CAAC,EAGH,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,SACF,CAAC,CACH,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-list.js","names":[],"sources":["../../src/rules/prefer-list.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImportsLegacy, isFunctypeCall } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\n/** AST keys that don't represent syntax children — back-edges and source metadata. */\nconst NON_CHILD_KEYS: ReadonlySet<string> = new Set([\"parent\", \"loc\", \"range\"])\n\n/** AST children of `node`: drops back-edges, flattens array-valued keys, filters non-object leaves. */\nfunction astChildren(node: ASTNode): readonly unknown[] {\n return Object.entries(node)\n .filter(([k]) => !NON_CHILD_KEYS.has(k))\n .flatMap(([, v]) => (Array.isArray(v) ? v : [v]))\n .filter((v) => v !== null && typeof v === \"object\")\n}\n\n/** True iff any ancestor of `node` satisfies `pred`. Pure tail recursion. */\nfunction ancestorSatisfies(node: ASTNode | null | undefined, pred: (n: ASTNode) => boolean): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return pred(parent) || ancestorSatisfies(parent, pred)\n}\n\n/** `parent` is `List.from(arr)` or `List.of(...arr)`. */\nfunction isListFactoryArg(parent: ASTNode | null | undefined): boolean {\n return (\n parent?.type === \"CallExpression\" &&\n parent.callee.type === \"MemberExpression\" &&\n parent.callee.object.type === \"Identifier\" &&\n parent.callee.object.name === \"List\" &&\n [\"from\", \"of\"].includes(parent.callee.property.name)\n )\n}\n\n/** `node` is a VariableDeclarator with its own type annotation, or a TSTypeAnnotation node directly. */\nfunction hasOwnTypeAnnotation(node: ASTNode): boolean {\n return (node.type === \"VariableDeclarator\" && Boolean(node.id?.typeAnnotation)) || node.type === \"TSTypeAnnotation\"\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer List<T> over native arrays for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowArraysInTests: {\n type: \"boolean\",\n default: true,\n },\n allowReadonlyArrays: {\n type: \"boolean\",\n default: true,\n },\n allowArrayLiterals: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferList: \"Prefer List<{{type}}> over array type {{arrayType}}\",\n preferListLiteral: \"Prefer List.of(...) or List.from([...]) over array literal\",\n suggestListType: \"Replace with List<{{type}}>\",\n suggestListOf: \"Replace with List.of(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowArraysInTests = options.allowArraysInTests !== false\n const allowReadonlyArrays = options.allowReadonlyArrays !== false\n const allowArrayLiterals = options.allowArrayLiterals === true\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function findTypeParameter(node: ASTNode, sourceCode: typeof context.sourceCode): string | null {\n // Pure pre-order search: look at this node, then recursively at each\n // child until we find a TSTypeParameterInstantiation with a first param.\n function findInNode(n: ASTNode): string | null {\n if (n.type === \"TSTypeParameterInstantiation\" && n.params && n.params[0]) {\n return sourceCode.getText(n.params[0])\n }\n const results = astChildren(n)\n .filter((c): c is ASTNode => typeof (c as ASTNode)?.type === \"string\")\n .map((child) => findInNode(child))\n return results.find((r) => r !== null) ?? null\n }\n return findInNode(node)\n }\n\n return {\n TSArrayType(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n\n // `readonly T[]` parses as TSTypeOperator(operator: \"readonly\") wrapping TSArrayType.\n // When the parent is that readonly wrapper, we treat the whole `readonly T[]` as\n // the reported unit — both for gating (parity with the ReadonlyArray<T> branch\n // below) and for the suggestion's replacement range. Replacing only the inner\n // TSArrayType would leave `readonly List<T>` behind, which is invalid TS\n // (TS1354: `readonly` only applies to array/tuple types).\n const parent = node.parent as ASTNode | undefined\n const isReadonly =\n parent?.type === \"TSTypeOperator\" && (parent as { operator?: string }).operator === \"readonly\"\n\n if (isReadonly && allowReadonlyArrays) return\n\n const sourceCode = context.sourceCode\n const elementType = sourceCode.getText(node.elementType)\n const reportNode = isReadonly ? (parent as ASTNode) : node\n const fullType = sourceCode.getText(reportNode)\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: elementType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(reportNode, `List<${elementType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node: reportNode,\n messageId: \"preferList\",\n data: {\n type: elementType,\n arrayType: fullType,\n },\n suggest,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n\n const sourceCode = context.sourceCode\n\n // Get type name - handle both simple identifiers and member expressions\n if (!node.typeName) return // No type name found\n\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n // Handle Array<T> syntax\n if (typeName === \"Array\") {\n // Look for type parameters in child nodes\n const typeParam = findTypeParameter(node, sourceCode)\n const fullType = sourceCode.getText(node)\n\n const resolvedType = typeParam || \"T\"\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: resolvedType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List<${resolvedType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferList\",\n data: {\n type: resolvedType,\n arrayType: fullType,\n },\n suggest,\n })\n }\n\n // Handle ReadonlyArray<T> — gated on allowReadonlyArrays (parity with `readonly T[]`).\n if (typeName === \"ReadonlyArray\") {\n if (allowReadonlyArrays) return\n\n const typeParam = findTypeParameter(node, sourceCode)\n const fullType = sourceCode.getText(node)\n const resolvedType = typeParam || \"T\"\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListType\",\n data: { type: resolvedType },\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List<${resolvedType}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferList\",\n data: {\n type: resolvedType,\n arrayType: fullType,\n },\n suggest,\n })\n }\n },\n\n ArrayExpression(node: ASTNode) {\n if (allowArraysInTests && isInTestFile()) return\n if (allowArrayLiterals) return\n\n // Only flag non-empty arrays to avoid noise\n if (node.elements.length === 0) return\n\n const parent = node.parent\n\n // Don't flag arrays that are already arguments to functype calls.\n if (parent && isFunctypeCall(parent, functypeImports)) return\n\n // Don't flag arrays that are arguments to List.from / List.of.\n if (isListFactoryArg(parent)) return\n\n // Don't flag nested array literals — let the outermost one handle it.\n if (ancestorSatisfies(node, (n) => n.type === \"ArrayExpression\")) return\n\n // Don't flag array literals that already live in a type-annotated\n // context (those are handled by the type-checking rules).\n if (ancestorSatisfies(node, hasOwnTypeAnnotation)) return\n\n // Check if any element is a SpreadElement — ambiguous semantics, skip suggestions\n const hasSpread = node.elements.some((el) => el !== null && el.type === \"SpreadElement\")\n\n if (hasSpread) {\n context.report({\n node,\n messageId: \"preferListLiteral\",\n })\n return\n }\n\n const sourceCode = context.sourceCode\n const elementTexts = node.elements.filter((el) => el !== null).map((el) => sourceCode.getText(el))\n\n const suggest: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestListOf\",\n fix(fixer: Rule.RuleFixer) {\n return fixer.replaceText(node, `List.of(${elementTexts.join(\", \")})`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"List\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"List\" },\n fix: createImportFixer(sourceCode, \"List\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferListLiteral\",\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"kLAOA,MAAM,EAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAG9E,SAAS,EAAY,EAAmC,CACtD,OAAO,OAAO,QAAQ,CAAI,CAAC,CACxB,QAAQ,CAAC,KAAO,CAAC,EAAe,IAAI,CAAC,CAAC,CAAC,CACvC,SAAS,EAAG,KAAQ,MAAM,QAAQ,CAAC,EAAI,EAAI,CAAC,CAAC,CAAE,CAAC,CAChD,OAAQ,GAAoB,OAAO,GAAM,YAA3B,CAAmC,CACtD,CAGA,SAAS,EAAkB,EAAkC,EAAwC,CACnG,IAAM,EAAS,GAAM,OAErB,OADK,EACE,EAAK,CAAM,GAAK,EAAkB,EAAQ,CAAI,EADjC,EAEtB,CAGA,SAAS,EAAiB,EAA6C,CACrE,OACE,GAAQ,OAAS,kBACjB,EAAO,OAAO,OAAS,oBACvB,EAAO,OAAO,OAAO,OAAS,cAC9B,EAAO,OAAO,OAAO,OAAS,QAC9B,CAAC,OAAQ,IAAI,CAAC,CAAC,SAAS,EAAO,OAAO,SA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AM,GACvC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,MAAO,EACvB,IAAK,EAAkB,EAAY,MAAM,CAC3C,CAAC,EAGH,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,SACF,CAAC,CACH,CACF,CACF,CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-functype",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.109.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",
|
|
@@ -40,11 +40,11 @@
|
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
42
|
"@types/node": "^24.13.3",
|
|
43
|
-
"@typescript-eslint/rule-tester": "^8.
|
|
43
|
+
"@typescript-eslint/rule-tester": "^8.67.0",
|
|
44
44
|
"eslint-config-prettier": "^10.1.8",
|
|
45
|
-
"ts-builds": "^3.
|
|
45
|
+
"ts-builds": "^3.4.1",
|
|
46
46
|
"tsdown": "^0.22.14",
|
|
47
|
-
"functype": "^1.
|
|
47
|
+
"functype": "^1.9.0"
|
|
48
48
|
},
|
|
49
49
|
"publishConfig": {
|
|
50
50
|
"access": "public",
|