eslint-plugin-functype 2.112.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 CHANGED
@@ -30,7 +30,7 @@ export default [functype.configs.strict]
30
30
  | Rule | Recommended | Strict | Description |
31
31
  | ------------------------------ | :---------: | :----: | ---------------------------------------------------------------------------------------- |
32
32
  | `functype/no-let` | error | error | Use `const`; no reassignment |
33
- | `functype/no-imperative-loops` | error | error | Use `List`/array methods or `IO.forEach` instead of loops |
33
+ | `functype/no-imperative-loops` | error | error | Use `List`/array methods, async traversal or `IO.forEach` instead of loops |
34
34
  | `functype/prefer-functype-map` | error | error | Use functype `Map` instead of a native `Map` you only read |
35
35
  | `functype/prefer-functype-set` | error | error | Use functype `Set` instead of a native `Set` you only read |
36
36
  | `functype/collection-naming` | error | error | Import functype's `Map`/`Set` under their own names; spell the built-in `globalThis.Map` |
@@ -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 | Default | Description |
122
- | --------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
123
- | `allowInTests` | `true` | Silence the rule inside test files (same predicate as above). |
124
- | `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. |
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
- 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.
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
 
@@ -182,7 +187,7 @@ This is the escape for an interface that takes a native `ReadonlyMap` — declar
182
187
 
183
188
  functype's `Map` / `Set` are the default collections (the Scala convention: the immutable collection owns the plain name). This rule reports:
184
189
 
185
- - `new Map()` on functype's `Map` (or `Set`). It's a factory, so TypeScript only says TS7009 ("target lacks a construct signature"). The message says to write `Map(…)` / `Map.empty()`, or `new globalThis.Map(…)` for the built-in.
190
+ - `new Map()` on functype's `Map` (or `Set`). It's a factory, so TypeScript only says TS7009 ("target lacks a construct signature"), or TS2350 ("Only a void function can be called with the 'new' keyword") when `noImplicitAny` is off. The message says to write `Map(…)` / `Map.empty()`, or `new globalThis.Map(…)` for the built-in.
186
191
  - `import { Map as FMap } from "functype"`. An alias lets the plain name keep meaning the built-in, which inverts the convention and drifts between files.
187
192
 
188
193
  | Option | Default | Description |
@@ -198,7 +203,7 @@ These rules don't report loops that have no functional equivalent:
198
203
  - `for await` consumes a stream, and collecting it first would defeat the streaming.
199
204
  - A loop whose body `yield`s is a generator's body, and a callback can't yield.
200
205
 
201
- A loop whose body `await`s is still reported by `no-imperative-loops`, which points at `IO.forEach`. `prefer-map` doesn't report it.
206
+ A loop whose body `await`s is still reported by `no-imperative-loops`, which points at `List(items).mapAsync(f)`, `Either.traverseAsync` (stops at the first `Left`) or, inside `IO`, `IO.forEach`. `prefer-map` doesn't report it.
202
207
 
203
208
  ## Combining with eslint-config-functype
204
209
 
@@ -6,7 +6,8 @@ import { Rule } from "eslint";
6
6
  *
7
7
  * Two defects:
8
8
  * - `new Map()` on functype's Map. It's a factory, so TypeScript only says TS7009 ("target lacks a construct
9
- * signature, implicitly has an 'any' type"), which doesn't say what to write instead. This message does.
9
+ * signature, implicitly has an 'any' type"), or TS2350 ("Only a void function can be called with the 'new'
10
+ * keyword") when `noImplicitAny` is off. Neither says what to write instead. This message does.
10
11
  * - `import { Map as FMap } from "functype"`. Aliases let a file keep the built-in under the plain name,
11
12
  * which inverts the convention and drifts (`FMap`, `FMapOf`, `IMap`…). `allowAlias: true` opts out.
12
13
  *
@@ -1 +1 @@
1
- {"version":3,"file":"collection-naming.js","names":["rule","allowAlias","context","hit","functypeCollectionAt","node","source","spec","COLLECTION_NAMES"],"sources":["../../src/rules/collection-naming.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { COLLECTION_NAMES, functypeCollectionAt } from \"../utils/collection-binding\"\n\n/**\n * functype's `Map` / `Set` are the default collections (Scala-style): import them under their own names,\n * and spell the built-in `globalThis.Map` / `globalThis.Set` where it is genuinely needed.\n *\n * Two defects:\n * - `new Map()` on functype's Map. It's a factory, so TypeScript only says TS7009 (\"target lacks a construct\n * signature, implicitly has an 'any' type\"), which doesn't say what to write instead. This message does.\n * - `import { Map as FMap } from \"functype\"`. Aliases let a file keep the built-in under the plain name,\n * which inverts the convention and drifts (`FMap`, `FMapOf`, `IMap`…). `allowAlias: true` opts out.\n *\n * Applies in test files too: tests are read as examples, by people and agents.\n */\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Use functype's Map/Set under their own names; spell the built-in globalThis.Map/globalThis.Set\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowAlias: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n newFunctypeCollection:\n \"functype's {{name}} is a factory, not a class: use {{local}}(…) or {{local}}.empty(). For the built-in, write new globalThis.{{name}}(…)\",\n aliasedImport:\n \"Import functype's {{name}} as {{name}}, not {{local}}: functype's {{name}} is the default collection. Spell the built-in globalThis.{{name}}\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowAlias = options.allowAlias === true\n\n return {\n NewExpression(node: ASTNode) {\n const hit = functypeCollectionAt(node.callee, context.sourceCode)\n if (hit === null) return\n context.report({ node, messageId: \"newFunctypeCollection\", data: hit })\n },\n\n ImportDeclaration(node: ASTNode) {\n if (allowAlias) return\n const source = node.source?.value\n if (typeof source !== \"string\" || !(source === \"functype\" || source.startsWith(\"functype/\"))) return\n ;(node.specifiers as ReadonlyArray<ASTNode>)\n .filter(\n (spec) =>\n spec.type === \"ImportSpecifier\" &&\n spec.imported?.type === \"Identifier\" &&\n COLLECTION_NAMES.includes(spec.imported.name) &&\n spec.local.name !== spec.imported.name,\n )\n .forEach((spec) =>\n context.report({\n node: spec,\n messageId: \"aliasedImport\",\n data: { name: spec.imported.name, local: spec.local.name },\n }),\n )\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"4FAiBA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,iGACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,WAAY,CACV,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,sBACE,2IACF,cACE,8IACJ,CACF,EAEA,OAAO,EAAS,CAEd,IAAMC,GADUC,EAAQ,QAAQ,IAAM,CAAC,EAAA,CACZ,aAAe,GAE1C,MAAO,CACL,cAAc,EAAe,CAC3B,IAAMC,EAAMC,EAAqBC,EAAK,OAAQH,EAAQ,UAAU,EAC5DC,IAAQ,MACZD,EAAQ,OAAO,CAAE,OAAM,UAAW,wBAAyB,KAAMC,CAAI,CAAC,CACxE,EAEA,kBAAkB,EAAe,CAC/B,GAAIF,EAAY,OAChB,IAAMK,EAASD,EAAK,QAAQ,MACxB,OAAOC,GAAW,WAAcA,IAAW,YAAcA,EAAO,WAAW,WAAW,IACzFD,EAAM,WACJ,OACE,GACCE,EAAK,OAAS,mBACdA,EAAK,UAAU,OAAS,cACxBC,EAAiB,SAASD,EAAK,SAAS,IAAI,GAC5CA,EAAK,MAAM,OAASA,EAAK,SAAS,IACtC,CAAC,CACA,QAAS,GACRL,EAAQ,OAAO,CACb,KAAMK,EACN,UAAW,gBACX,KAAM,CAAE,KAAMA,EAAK,SAAS,KAAM,MAAOA,EAAK,MAAM,IAAK,CAC3D,CAAC,CACH,CACJ,CACF,CACF,CACF"}
1
+ {"version":3,"file":"collection-naming.js","names":["rule","allowAlias","context","hit","functypeCollectionAt","node","source","spec","COLLECTION_NAMES"],"sources":["../../src/rules/collection-naming.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { COLLECTION_NAMES, functypeCollectionAt } from \"../utils/collection-binding\"\n\n/**\n * functype's `Map` / `Set` are the default collections (Scala-style): import them under their own names,\n * and spell the built-in `globalThis.Map` / `globalThis.Set` where it is genuinely needed.\n *\n * Two defects:\n * - `new Map()` on functype's Map. It's a factory, so TypeScript only says TS7009 (\"target lacks a construct\n * signature, implicitly has an 'any' type\"), or TS2350 (\"Only a void function can be called with the 'new'\n * keyword\") when `noImplicitAny` is off. Neither says what to write instead. This message does.\n * - `import { Map as FMap } from \"functype\"`. Aliases let a file keep the built-in under the plain name,\n * which inverts the convention and drifts (`FMap`, `FMapOf`, `IMap`…). `allowAlias: true` opts out.\n *\n * Applies in test files too: tests are read as examples, by people and agents.\n */\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Use functype's Map/Set under their own names; spell the built-in globalThis.Map/globalThis.Set\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowAlias: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n newFunctypeCollection:\n \"functype's {{name}} is a factory, not a class: use {{local}}(…) or {{local}}.empty(). For the built-in, write new globalThis.{{name}}(…)\",\n aliasedImport:\n \"Import functype's {{name}} as {{name}}, not {{local}}: functype's {{name}} is the default collection. Spell the built-in globalThis.{{name}}\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowAlias = options.allowAlias === true\n\n return {\n NewExpression(node: ASTNode) {\n const hit = functypeCollectionAt(node.callee, context.sourceCode)\n if (hit === null) return\n context.report({ node, messageId: \"newFunctypeCollection\", data: hit })\n },\n\n ImportDeclaration(node: ASTNode) {\n if (allowAlias) return\n const source = node.source?.value\n if (typeof source !== \"string\" || !(source === \"functype\" || source.startsWith(\"functype/\"))) return\n ;(node.specifiers as ReadonlyArray<ASTNode>)\n .filter(\n (spec) =>\n spec.type === \"ImportSpecifier\" &&\n spec.imported?.type === \"Identifier\" &&\n COLLECTION_NAMES.includes(spec.imported.name) &&\n spec.local.name !== spec.imported.name,\n )\n .forEach((spec) =>\n context.report({\n node: spec,\n messageId: \"aliasedImport\",\n data: { name: spec.imported.name, local: spec.local.name },\n }),\n )\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"4FAkBA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,iGACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,WAAY,CACV,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,sBACE,2IACF,cACE,8IACJ,CACF,EAEA,OAAO,EAAS,CAEd,IAAMC,GADUC,EAAQ,QAAQ,IAAM,CAAC,EAAA,CACZ,aAAe,GAE1C,MAAO,CACL,cAAc,EAAe,CAC3B,IAAMC,EAAMC,EAAqBC,EAAK,OAAQH,EAAQ,UAAU,EAC5DC,IAAQ,MACZD,EAAQ,OAAO,CAAE,OAAM,UAAW,wBAAyB,KAAMC,CAAI,CAAC,CACxE,EAEA,kBAAkB,EAAe,CAC/B,GAAIF,EAAY,OAChB,IAAMK,EAASD,EAAK,QAAQ,MACxB,OAAOC,GAAW,WAAcA,IAAW,YAAcA,EAAO,WAAW,WAAW,IACzFD,EAAM,WACJ,OACE,GACCE,EAAK,OAAS,mBACdA,EAAK,UAAU,OAAS,cACxBC,EAAiB,SAASD,EAAK,SAAS,IAAI,GAC5CA,EAAK,MAAM,OAASA,EAAK,SAAS,IACtC,CAAC,CACA,QAAS,GACRL,EAAQ,OAAO,CACb,KAAMK,EACN,UAAW,gBACX,KAAM,CAAE,KAAMA,EAAK,SAAS,KAAM,MAAOA,EAAK,MAAM,IAAK,CAC3D,CAAC,CACH,CACJ,CACF,CACF,CACF"}
@@ -1,2 +1,2 @@
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};
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","isInTestFile","filename","isMonadicType","node","text","varName","property","methodName","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\"\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":"AAIA,MAAMA,EAA4C,CAAC,UAAW,SAAU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AC7B,GAAI,CAACG,GAAYA,EAAS,OAAS,aAAc,OAEjD,IAAMC,EAAaD,EAAS,KAC5B,GAAKP,EAAc,SAASQ,CAAU,GAGlCL,EAAcC,EAAK,OAAO,MAAM,EAAG,CACrC,IAAMK,EAAaX,EAAQ,WACrBY,EAAaD,EAAW,QAAQL,EAAK,OAAO,MAAM,EAMlDO,EAAWP,EAAK,UAAU,IAAK,GAAeK,EAAW,QAAQG,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAC9EC,EAAYF,EAAW,SAASH,EAAW,GAAGG,EAAS,GAAK,GAElEb,EAAQ,OAAO,CACb,OACA,UAAW,cACX,KAAM,CAAE,OAAQU,CAAW,EAC3B,QAAS,CACP,CACE,UAAW,gBACX,IAAI,EAAO,CACT,OAAOM,EAAM,YAAYV,EAAM,GAAGM,EAAW,oCAAoCG,EAAU,KAAK,CAClG,CACF,EACA,CACE,UAAW,cACX,IAAI,EAAO,CACT,OAAOC,EAAM,YACXV,EACA,GAAGM,EAAW,uCAAuCG,EAAU,kCACjE,CACF,CACF,CACF,CACF,CAAC,CACH,CACF,CACF,CACF,CACF"}
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,KAA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 @@
1
- import{containsAwait as e,containsYield as t}from"../utils/async-detection.js";const n={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer functional iteration methods over imperative for loops`,recommended:!0},schema:[{type:`object`,properties:{allowForIndexAccess:{type:`boolean`,default:!1},allowWhileLoops:{type:`boolean`,default:!1},allowInTests:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{noForLoop:`Prefer functional methods (.map, .filter, .forEach, .reduce) over for loops`,noForInLoop:`Prefer Object.keys().forEach() or functional methods over for..in loops`,noForOfLoop:`Prefer .forEach() or .map() over for..of loops`,noAsyncLoop:`This loop awaits, which .forEach()/.map() cannot do. For sequential effects use IO.forEach(items, f) (runs in order, stops at the first failure); for independent ones, IO.all`,noWhileLoop:`Prefer functional iteration or recursion over while loops`,noDoWhileLoop:`Prefer functional iteration or recursion over do..while loops`,suggestForEach:`Replace with {{iterable}}.forEach(...)`,suggestObjectKeys:`Replace with Object.keys({{object}}).forEach(...)`}},create(n){let r=n.options[0]||{},i=r.allowForIndexAccess||!1,a=r.allowWhileLoops||!1,o=r.allowInTests!==!1;function s(){let e=n.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function c(e){if(!e.body||e.body.type!==`BlockStatement`)return!1;let t=n.sourceCode.getText(e.body);return/\[\s*\w+\s*\]/.test(t)&&e.init&&e.init.type===`VariableDeclaration`}function l(e){return!e.body||e.body.type!==`BlockStatement`?!1:e.body.body.length===1}function u(e){let t=e.left;if(!t)return!1;if(t.type===`VariableDeclaration`&&t.declarations[0]){let e=t.declarations[0].id;return e.type===`ObjectPattern`||e.type===`ArrayPattern`}return!1}function d(e){return e.type===`ForOfStatement`&&e.await===!0||t(e.body)}function f(e){let t=n.sourceCode.getText(e.body);return/\b(break|continue)\b/.test(t)}return{ForStatement(t){if(!d(t)&&!(o&&s())&&!(i&&c(t))){if(e(t.body)){n.report({node:t,messageId:`noAsyncLoop`});return}n.report({node:t,messageId:`noForLoop`})}},ForInStatement(t){if(d(t)||o&&s())return;if(e(t.body)){n.report({node:t,messageId:`noAsyncLoop`});return}let r=[];if(l(t)&&!u(t)&&!f(t)){let e=n.sourceCode,i=t.body.body[0];if(i&&i.type===`ExpressionStatement`){let n=e.getText(i),a=e.getText(t.right),o=t.left,s=o.type===`VariableDeclaration`&&o.declarations[0]?e.getText(o.declarations[0].id):e.getText(o);r.push({messageId:`suggestObjectKeys`,data:{object:a},fix(e){return e.replaceText(t,`Object.keys(${a}).forEach((${s}) => {\n ${n}\n})`)}})}}n.report({node:t,messageId:`noForInLoop`,suggest:r.length>0?r:void 0})},ForOfStatement(t){if(d(t)||o&&s())return;if(e(t.body)){n.report({node:t,messageId:`noAsyncLoop`});return}let r=[];if(l(t)&&!u(t)&&!f(t)&&!e(t.right)){let e=n.sourceCode,i=t.body.body[0];if(i&&i.type===`ExpressionStatement`){let n=e.getText(i),a=e.getText(t.right),o=t.left,s=o.type===`VariableDeclaration`&&o.declarations[0]?e.getText(o.declarations[0].id):e.getText(o);n.includes(`.push(`)||r.push({messageId:`suggestForEach`,data:{iterable:a},fix(e){return e.replaceText(t,`${a}.forEach((${s}) => {\n ${n}\n})`)}})}}n.report({node:t,messageId:`noForOfLoop`,suggest:r.length>0?r:void 0})},WhileStatement(e){d(e)||a||o&&s()||n.report({node:e,messageId:`noWhileLoop`})},DoWhileStatement(e){d(e)||a||o&&s()||n.report({node:e,messageId:`noDoWhileLoop`})}}}};export{n as default};
1
+ import{containsAwait as e,containsYield as t}from"../utils/async-detection.js";const n={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer functional iteration methods over imperative for loops`,recommended:!0},schema:[{type:`object`,properties:{allowForIndexAccess:{type:`boolean`,default:!1},allowWhileLoops:{type:`boolean`,default:!1},allowInTests:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{noForLoop:`Prefer functional methods (.map, .filter, .forEach, .reduce) over for loops`,noForInLoop:`Prefer Object.keys().forEach() or functional methods over for..in loops`,noForOfLoop:`Prefer .forEach() or .map() over for..of loops`,noAsyncLoop:`This loop awaits, which .forEach()/.map() cannot do. To await in order use List(items).mapAsync(f), or Either.traverseAsync(items, f) when f returns Either (stops at the first Left). Inside IO, use IO.forEach(items, f)`,noWhileLoop:`Prefer functional iteration or recursion over while loops`,noDoWhileLoop:`Prefer functional iteration or recursion over do..while loops`,suggestForEach:`Replace with {{iterable}}.forEach(...)`,suggestObjectKeys:`Replace with Object.keys({{object}}).forEach(...)`}},create(n){let r=n.options[0]||{},i=r.allowForIndexAccess||!1,a=r.allowWhileLoops||!1,o=r.allowInTests!==!1;function s(){let e=n.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function c(e){if(!e.body||e.body.type!==`BlockStatement`)return!1;let t=n.sourceCode.getText(e.body);return/\[\s*\w+\s*\]/.test(t)&&e.init&&e.init.type===`VariableDeclaration`}function l(e){return!e.body||e.body.type!==`BlockStatement`?!1:e.body.body.length===1}function u(e){let t=e.left;if(!t)return!1;if(t.type===`VariableDeclaration`&&t.declarations[0]){let e=t.declarations[0].id;return e.type===`ObjectPattern`||e.type===`ArrayPattern`}return!1}function d(e){return e.type===`ForOfStatement`&&e.await===!0||t(e.body)}function f(e){let t=n.sourceCode.getText(e.body);return/\b(break|continue)\b/.test(t)}return{ForStatement(t){if(!d(t)&&!(o&&s())&&!(i&&c(t))){if(e(t.body)){n.report({node:t,messageId:`noAsyncLoop`});return}n.report({node:t,messageId:`noForLoop`})}},ForInStatement(t){if(d(t)||o&&s())return;if(e(t.body)){n.report({node:t,messageId:`noAsyncLoop`});return}let r=[];if(l(t)&&!u(t)&&!f(t)){let e=n.sourceCode,i=t.body.body[0];if(i&&i.type===`ExpressionStatement`){let n=e.getText(i),a=e.getText(t.right),o=t.left,s=o.type===`VariableDeclaration`&&o.declarations[0]?e.getText(o.declarations[0].id):e.getText(o);r.push({messageId:`suggestObjectKeys`,data:{object:a},fix(e){return e.replaceText(t,`Object.keys(${a}).forEach((${s}) => {\n ${n}\n})`)}})}}n.report({node:t,messageId:`noForInLoop`,suggest:r.length>0?r:void 0})},ForOfStatement(t){if(d(t)||o&&s())return;if(e(t.body)){n.report({node:t,messageId:`noAsyncLoop`});return}let r=[];if(l(t)&&!u(t)&&!f(t)&&!e(t.right)){let e=n.sourceCode,i=t.body.body[0];if(i&&i.type===`ExpressionStatement`){let n=e.getText(i),a=e.getText(t.right),o=t.left,s=o.type===`VariableDeclaration`&&o.declarations[0]?e.getText(o.declarations[0].id):e.getText(o);n.includes(`.push(`)||r.push({messageId:`suggestForEach`,data:{iterable:a},fix(e){return e.replaceText(t,`${a}.forEach((${s}) => {\n ${n}\n})`)}})}}n.report({node:t,messageId:`noForOfLoop`,suggest:r.length>0?r:void 0})},WhileStatement(e){d(e)||a||o&&s()||n.report({node:e,messageId:`noWhileLoop`})},DoWhileStatement(e){d(e)||a||o&&s()||n.report({node:e,messageId:`noDoWhileLoop`})}}}};export{n as default};
2
2
  //# sourceMappingURL=no-imperative-loops.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"no-imperative-loops.js","names":["rule","options","context","allowForIndexAccess","allowWhileLoops","allowInTests","isInTestFile","filename","needsIndexAccess","node","bodyText","isSingleStatementBody","hasDestructuringVariable","left","id","hasNoFunctionalEquivalent","containsYield","bodyContainsBreakOrContinue","containsAwait","suggest","sourceCode","bodyStmt","stmtText","objText","keyVar","fixer","iterableText","varDecl","varName"],"sources":["../../src/rules/no-imperative-loops.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containsAwait, containsYield } from \"../utils/async-detection\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functional iteration methods over imperative for loops\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowForIndexAccess: {\n type: \"boolean\",\n default: false,\n },\n allowWhileLoops: {\n type: \"boolean\",\n default: false,\n },\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noForLoop: \"Prefer functional methods (.map, .filter, .forEach, .reduce) over for loops\",\n noForInLoop: \"Prefer Object.keys().forEach() or functional methods over for..in loops\",\n noForOfLoop: \"Prefer .forEach() or .map() over for..of loops\",\n noAsyncLoop:\n \"This loop awaits, which .forEach()/.map() cannot do. For sequential effects use IO.forEach(items, f) (runs in order, stops at the first failure); for independent ones, IO.all\",\n noWhileLoop: \"Prefer functional iteration or recursion over while loops\",\n noDoWhileLoop: \"Prefer functional iteration or recursion over do..while loops\",\n suggestForEach: \"Replace with {{iterable}}.forEach(...)\",\n suggestObjectKeys: \"Replace with Object.keys({{object}}).forEach(...)\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowForIndexAccess = options.allowForIndexAccess || false\n const allowWhileLoops = options.allowWhileLoops || false\n const allowInTests = options.allowInTests !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function needsIndexAccess(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n\n const sourceCode = context.sourceCode\n const bodyText = sourceCode.getText(node.body)\n\n // Look for array index access patterns like arr[i]\n return /\\[\\s*\\w+\\s*\\]/.test(bodyText) && node.init && node.init.type === \"VariableDeclaration\"\n }\n\n function isSingleStatementBody(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n return node.body.body.length === 1\n }\n\n function hasDestructuringVariable(node: ASTNode): boolean {\n const left = node.left\n if (!left) return false\n if (left.type === \"VariableDeclaration\" && left.declarations[0]) {\n const id = left.declarations[0].id\n return id.type === \"ObjectPattern\" || id.type === \"ArrayPattern\"\n }\n return false\n }\n\n /**\n * Loops with no functional equivalent (#324): `for await` consumes a stream, and collecting it first\n * would defeat the streaming; a loop that yields is a generator's body, and a callback cannot yield.\n */\n function hasNoFunctionalEquivalent(node: ASTNode): boolean {\n return (node.type === \"ForOfStatement\" && node.await === true) || containsYield(node.body)\n }\n\n function bodyContainsBreakOrContinue(node: ASTNode): boolean {\n const sourceCode = context.sourceCode\n const bodyText = sourceCode.getText(node.body)\n return /\\b(break|continue)\\b/.test(bodyText)\n }\n\n return {\n ForStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowInTests && isInTestFile()) return\n\n // Allow traditional for loops if they need index access and option is set\n if (allowForIndexAccess && needsIndexAccess(node)) return\n\n if (containsAwait(node.body)) {\n context.report({ node, messageId: \"noAsyncLoop\" })\n return\n }\n\n context.report({\n node,\n messageId: \"noForLoop\",\n })\n },\n\n ForInStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowInTests && isInTestFile()) return\n\n if (containsAwait(node.body)) {\n context.report({ node, messageId: \"noAsyncLoop\" })\n return\n }\n\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isSingleStatementBody(node) && !hasDestructuringVariable(node) && !bodyContainsBreakOrContinue(node)) {\n const sourceCode = context.sourceCode\n const bodyStmt = node.body.body[0]\n\n if (bodyStmt && bodyStmt.type === \"ExpressionStatement\") {\n const stmtText = sourceCode.getText(bodyStmt)\n const objText = sourceCode.getText(node.right)\n\n const left = node.left\n const keyVar =\n left.type === \"VariableDeclaration\" && left.declarations[0]\n ? sourceCode.getText(left.declarations[0].id)\n : sourceCode.getText(left)\n\n suggest.push({\n messageId: \"suggestObjectKeys\",\n data: { object: objText },\n fix(fixer) {\n return fixer.replaceText(node, `Object.keys(${objText}).forEach((${keyVar}) => {\\n ${stmtText}\\n})`)\n },\n })\n }\n }\n\n context.report({\n node,\n messageId: \"noForInLoop\",\n suggest: suggest.length > 0 ? suggest : undefined,\n })\n },\n\n ForOfStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowInTests && isInTestFile()) return\n\n // A .forEach suggestion here would move `await` into a non-async callback — a syntax error —\n // so an awaiting body gets the IO.forEach pointer and no suggestion.\n if (containsAwait(node.body)) {\n context.report({ node, messageId: \"noAsyncLoop\" })\n return\n }\n\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n // `for (x of await xs())` → `await xs().forEach(...)` would bind `await` to the forEach call, so an\n // awaited iterable gets no suggestion.\n if (\n isSingleStatementBody(node) &&\n !hasDestructuringVariable(node) &&\n !bodyContainsBreakOrContinue(node) &&\n !containsAwait(node.right)\n ) {\n const sourceCode = context.sourceCode\n const bodyStmt = node.body.body[0]\n\n if (bodyStmt && bodyStmt.type === \"ExpressionStatement\") {\n const stmtText = sourceCode.getText(bodyStmt)\n const iterableText = sourceCode.getText(node.right)\n\n const varDecl = node.left\n const varName =\n varDecl.type === \"VariableDeclaration\" && varDecl.declarations[0]\n ? sourceCode.getText(varDecl.declarations[0].id)\n : sourceCode.getText(varDecl)\n\n if (!stmtText.includes(\".push(\")) {\n suggest.push({\n messageId: \"suggestForEach\",\n data: { iterable: iterableText },\n fix(fixer) {\n return fixer.replaceText(node, `${iterableText}.forEach((${varName}) => {\\n ${stmtText}\\n})`)\n },\n })\n }\n }\n }\n\n context.report({\n node,\n messageId: \"noForOfLoop\",\n suggest: suggest.length > 0 ? suggest : undefined,\n })\n },\n\n WhileStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowWhileLoops) return\n if (allowInTests && isInTestFile()) return\n\n context.report({\n node,\n messageId: \"noWhileLoop\",\n })\n },\n\n DoWhileStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowWhileLoops) return\n if (allowInTests && isInTestFile()) return\n\n context.report({\n node,\n messageId: \"noDoWhileLoop\",\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"+EAKA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN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BJ,EAA0BN,CAAI,GAC9BL,GACAC,GAAgBC,EAAa,GAEjCJ,EAAQ,OAAO,CACb,OACA,UAAW,aACb,CAAC,CACH,EAEA,iBAAiB,EAAe,CAC1Ba,EAA0BN,CAAI,GAC9BL,GACAC,GAAgBC,EAAa,GAEjCJ,EAAQ,OAAO,CACb,OACA,UAAW,eACb,CAAC,CACH,CACF,CACF,CACF"}
1
+ {"version":3,"file":"no-imperative-loops.js","names":["rule","options","context","allowForIndexAccess","allowWhileLoops","allowInTests","isInTestFile","filename","needsIndexAccess","node","bodyText","isSingleStatementBody","hasDestructuringVariable","left","id","hasNoFunctionalEquivalent","containsYield","bodyContainsBreakOrContinue","containsAwait","suggest","sourceCode","bodyStmt","stmtText","objText","keyVar","fixer","iterableText","varDecl","varName"],"sources":["../../src/rules/no-imperative-loops.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containsAwait, containsYield } from \"../utils/async-detection\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functional iteration methods over imperative for loops\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowForIndexAccess: {\n type: \"boolean\",\n default: false,\n },\n allowWhileLoops: {\n type: \"boolean\",\n default: false,\n },\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noForLoop: \"Prefer functional methods (.map, .filter, .forEach, .reduce) over for loops\",\n noForInLoop: \"Prefer Object.keys().forEach() or functional methods over for..in loops\",\n noForOfLoop: \"Prefer .forEach() or .map() over for..of loops\",\n noAsyncLoop:\n \"This loop awaits, which .forEach()/.map() cannot do. To await in order use List(items).mapAsync(f), or Either.traverseAsync(items, f) when f returns Either (stops at the first Left). Inside IO, use IO.forEach(items, f)\",\n noWhileLoop: \"Prefer functional iteration or recursion over while loops\",\n noDoWhileLoop: \"Prefer functional iteration or recursion over do..while loops\",\n suggestForEach: \"Replace with {{iterable}}.forEach(...)\",\n suggestObjectKeys: \"Replace with Object.keys({{object}}).forEach(...)\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowForIndexAccess = options.allowForIndexAccess || false\n const allowWhileLoops = options.allowWhileLoops || false\n const allowInTests = options.allowInTests !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n function needsIndexAccess(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n\n const sourceCode = context.sourceCode\n const bodyText = sourceCode.getText(node.body)\n\n // Look for array index access patterns like arr[i]\n return /\\[\\s*\\w+\\s*\\]/.test(bodyText) && node.init && node.init.type === \"VariableDeclaration\"\n }\n\n function isSingleStatementBody(node: ASTNode): boolean {\n if (!node.body || node.body.type !== \"BlockStatement\") return false\n return node.body.body.length === 1\n }\n\n function hasDestructuringVariable(node: ASTNode): boolean {\n const left = node.left\n if (!left) return false\n if (left.type === \"VariableDeclaration\" && left.declarations[0]) {\n const id = left.declarations[0].id\n return id.type === \"ObjectPattern\" || id.type === \"ArrayPattern\"\n }\n return false\n }\n\n /**\n * Loops with no functional equivalent (#324): `for await` consumes a stream, and collecting it first\n * would defeat the streaming; a loop that yields is a generator's body, and a callback cannot yield.\n */\n function hasNoFunctionalEquivalent(node: ASTNode): boolean {\n return (node.type === \"ForOfStatement\" && node.await === true) || containsYield(node.body)\n }\n\n function bodyContainsBreakOrContinue(node: ASTNode): boolean {\n const sourceCode = context.sourceCode\n const bodyText = sourceCode.getText(node.body)\n return /\\b(break|continue)\\b/.test(bodyText)\n }\n\n return {\n ForStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowInTests && isInTestFile()) return\n\n // Allow traditional for loops if they need index access and option is set\n if (allowForIndexAccess && needsIndexAccess(node)) return\n\n if (containsAwait(node.body)) {\n context.report({ node, messageId: \"noAsyncLoop\" })\n return\n }\n\n context.report({\n node,\n messageId: \"noForLoop\",\n })\n },\n\n ForInStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowInTests && isInTestFile()) return\n\n if (containsAwait(node.body)) {\n context.report({ node, messageId: \"noAsyncLoop\" })\n return\n }\n\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isSingleStatementBody(node) && !hasDestructuringVariable(node) && !bodyContainsBreakOrContinue(node)) {\n const sourceCode = context.sourceCode\n const bodyStmt = node.body.body[0]\n\n if (bodyStmt && bodyStmt.type === \"ExpressionStatement\") {\n const stmtText = sourceCode.getText(bodyStmt)\n const objText = sourceCode.getText(node.right)\n\n const left = node.left\n const keyVar =\n left.type === \"VariableDeclaration\" && left.declarations[0]\n ? sourceCode.getText(left.declarations[0].id)\n : sourceCode.getText(left)\n\n suggest.push({\n messageId: \"suggestObjectKeys\",\n data: { object: objText },\n fix(fixer) {\n return fixer.replaceText(node, `Object.keys(${objText}).forEach((${keyVar}) => {\\n ${stmtText}\\n})`)\n },\n })\n }\n }\n\n context.report({\n node,\n messageId: \"noForInLoop\",\n suggest: suggest.length > 0 ? suggest : undefined,\n })\n },\n\n ForOfStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowInTests && isInTestFile()) return\n\n // A .forEach suggestion here would move `await` into a non-async callback — a syntax error —\n // so an awaiting body gets the async-traversal pointer and no suggestion.\n if (containsAwait(node.body)) {\n context.report({ node, messageId: \"noAsyncLoop\" })\n return\n }\n\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n // `for (x of await xs())` → `await xs().forEach(...)` would bind `await` to the forEach call, so an\n // awaited iterable gets no suggestion.\n if (\n isSingleStatementBody(node) &&\n !hasDestructuringVariable(node) &&\n !bodyContainsBreakOrContinue(node) &&\n !containsAwait(node.right)\n ) {\n const sourceCode = context.sourceCode\n const bodyStmt = node.body.body[0]\n\n if (bodyStmt && bodyStmt.type === \"ExpressionStatement\") {\n const stmtText = sourceCode.getText(bodyStmt)\n const iterableText = sourceCode.getText(node.right)\n\n const varDecl = node.left\n const varName =\n varDecl.type === \"VariableDeclaration\" && varDecl.declarations[0]\n ? sourceCode.getText(varDecl.declarations[0].id)\n : sourceCode.getText(varDecl)\n\n if (!stmtText.includes(\".push(\")) {\n suggest.push({\n messageId: \"suggestForEach\",\n data: { iterable: iterableText },\n fix(fixer) {\n return fixer.replaceText(node, `${iterableText}.forEach((${varName}) => {\\n ${stmtText}\\n})`)\n },\n })\n }\n }\n }\n\n context.report({\n node,\n messageId: \"noForOfLoop\",\n suggest: suggest.length > 0 ? suggest : undefined,\n })\n },\n\n WhileStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowWhileLoops) return\n if (allowInTests && isInTestFile()) return\n\n context.report({\n node,\n messageId: \"noWhileLoop\",\n })\n },\n\n DoWhileStatement(node: ASTNode) {\n if (hasNoFunctionalEquivalent(node)) return\n if (allowWhileLoops) return\n if (allowInTests && isInTestFile()) return\n\n context.report({\n node,\n messageId: \"noDoWhileLoop\",\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"+EAKA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,gEACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,oBAAqB,CACnB,KAAM,UACN,QAAS,EACX,EACA,gBAAiB,CACf,KAAM,UACN,QAAS,EACX,EACA,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,UAAW,8EACX,YAAa,0EACb,YAAa,iDACb,YACE,6NACF,YAAa,4DACb,cAAe,gEACf,eAAgB,yCAChB,kBAAmB,mDACrB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EACjCC,E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AC,EAIpD,GACER,EAAsBF,CAAI,GAC1B,CAACG,EAAyBH,CAAI,GAC9B,CAACQ,EAA4BR,CAAI,GACjC,CAACS,EAAcT,EAAK,KAAK,EACzB,CACA,IAAMW,EAAalB,EAAQ,WACrBmB,EAAWZ,EAAK,KAAK,KAAK,GAEhC,GAAIY,GAAYA,EAAS,OAAS,sBAAuB,CACvD,IAAMC,EAAWF,EAAW,QAAQC,CAAQ,EACtCK,EAAeN,EAAW,QAAQX,EAAK,KAAK,EAE5CkB,EAAUlB,EAAK,KACfmB,EACJD,EAAQ,OAAS,uBAAyBA,EAAQ,aAAa,GAC3DP,EAAW,QAAQO,EAAQ,aAAa,EAAE,CAAC,EAAE,EAC7CP,EAAW,QAAQO,CAAO,EAE3BL,EAAS,SAAS,QAAQ,GAC7BH,EAAQ,KAAK,CACX,UAAW,iBACX,KAAM,CAAE,SAAUO,CAAa,EAC/B,IAAI,EAAO,CACT,OAAOD,EAAM,YAAYhB,EAAM,GAAGiB,EAAa,YAAYE,EAAQ,YAAYN,EAAS,KAAK,CAC/F,CACF,CAAC,CAEL,CACF,CAEApB,EAAQ,OAAO,CACb,OACA,UAAW,cACX,QAASiB,EAAQ,OAAS,EAAIA,EAAU,IAAA,EAC1C,CAAC,CACH,EAEA,eAAe,EAAe,CACxBJ,EAA0BN,CAAI,GAC9BL,GACAC,GAAgBC,EAAa,GAEjCJ,EAAQ,OAAO,CACb,OACA,UAAW,aACb,CAAC,CACH,EAEA,iBAAiB,EAAe,CAC1Ba,EAA0BN,CAAI,GAC9BL,GACAC,GAAgBC,EAAa,GAEjCJ,EAAQ,OAAO,CACb,OACA,UAAW,eACb,CAAC,CACH,CACF,CACF,CACF"}
@@ -1,2 +1,2 @@
1
- import{childNodes as e}from"../utils/ast-walk.js";import{isInsideTaggedDeclaration as t}from"../utils/boundary-tags.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(t,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=t=>{let n=t.parent,i=n?.type===`CallExpression`&&n.callee===t,a=n?.type===`AssignmentExpression`&&n.left===t||n?.type===`UpdateExpression`;return o(t,r.members)&&!i&&!a||t.type===`CallExpression`&&t.arguments.length===0&&o(t.callee,r.methods)?[t.range]:e(t).flatMap(s)};return s(t)}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(e){let n=e.options[0]||{},r=n.allowInteropMarker!==!1,i=n=>r&&t(n,`interop`,e.sourceCode),a=n.minComplexity||2,l=n.checkNullable===!0;function u(t){let n=e.sourceCode;if(t.type!==`IfStatement`||!t.alternate)return null;let r=s(t.test,n);if(!r)return null;let i=h(t.consequent),a=h(t.alternate);if(!i||!a)return null;let o=[t.test,i,a];if(!n.getCommentsInside(t).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(t){let n=e.sourceCode,r=s(t.test,n);if(!r)return[];let{obj:i,isNegated:a,failure:l}=r,[u,d]=a?[t.consequent,t.alternate]:[t.alternate,t.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:e=>e.replaceText(t,`${i}.or(${f})`)}];let h=m(i,l,u,d,n);return[{messageId:`suggestFold`,fix:e=>e.replaceText(t,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(t){let n=e.sourceCode.getText(t);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&&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 _(e){if(!f(e.test))return[];let t=u(e);return t?[{messageId:`suggestFold`,fix:n=>n.replaceText(e,t)}]:[]}function v(t){let n=t.test,r=p(n);r.isMonadic&&(t.parent&&t.parent.type===`IfStatement`||g(t)>=a&&e.report({node:t,messageId:`preferFold`,data:{type:r.type},suggest:_(t)}))}return{IfStatement(e){i(e)||v(e)},ConditionalExpression(t){if(i(t))return;let n=p(t.test);(n.via!==`nullable`||!o(t.consequent)&&!o(t.alternate))&&n.isMonadic&&e.report({node:t,messageId:`preferFoldTernary`,data:{type:n.type},suggest:f(t.test)?d(t):[]})}}}};export{_ as default};
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{getFunctypeImportsLegacy as e,isAlreadyUsingFunctype as t,isFunctypeType as n}from"../utils/functype-detection.js";import{isInsideTaggedDeclaration as r}from"../utils/boundary-tags.js";import{createImportFixer as i,hasFunctypeSymbol as a}from"../utils/import-fixer.js";import{DEFAULT_WIRE_TYPES as o,WIRE_TYPES_SCHEMA as s,isInsideWireType as c}from"../utils/wire-types.js";const l=/* @__PURE__ */ new Set([`useState`,`useRef`]),u={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer Option<T> over nullable types (T | null | undefined)`,recommended:!0},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},wireTypes:s,allowNullableIntersections:{type:`boolean`,default:!1},allowUseState:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferOption:`Prefer Option<{{type}}> over nullable type '{{nullable}}'`,preferOptionReturn:`Prefer Option<{{type}}> as return type over nullable '{{nullable}}'`,suggestOptionType:`Replace with Option<{{type}}>`,suggestAddImport:`Add {{symbol}} import from functype`}},create(s){let u=s.options[0]||{},d=u.wireTypes??o,f=u.allowInteropMarker!==!1,p=e=>f&&r(e,`interop`,s.sourceCode),m=u.allowUseState!==!1;function h(e){let t=e.parent;if(!t)return!1;if(t.type===`TSTypeParameterInstantiation`&&t.parent?.type===`CallExpression`){let e=t.parent.callee,n=e.type===`Identifier`?e.name:e.type===`MemberExpression`&&e.property.type===`Identifier`?e.property.name:null;if(n!==null&&l.has(n))return!0}return h(t)}let g=e(s);return{TSUnionType(e){if(c(e,d)||p(e)||!e.types||e.types.length<2||m&&h(e)||!e.types.some(e=>e.type===`TSNullKeyword`||e.type===`TSUndefinedKeyword`))return;let r=e.types.filter(e=>e.type!==`TSNullKeyword`&&e.type!==`TSUndefinedKeyword`);if(r.length===1){let o=r[0];if(n(o,g)||t(e,g))return;let c=s.sourceCode,l=c.getText(o),u=c.getText(e);if(l.startsWith(`Option<`))return;let d=[{messageId:`suggestOptionType`,data:{type:l},fix(t){return t.replaceText(e,`Option<${l}>`)}}];a(c,`Option`)||d.push({messageId:`suggestAddImport`,data:{symbol:`Option`},fix:i(c,`Option`)}),s.report({node:e,messageId:`preferOption`,data:{type:l,nullable:u},suggest:d})}}}}};export{u as default};
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
@@ -1,2 +1,2 @@
1
- import{containsAwait as e}from"../utils/async-detection.js";import{isInsideTaggedDeclaration as t}from"../utils/boundary-tags.js";import{createImportFixer as n,hasFunctypeSymbol as r}from"../utils/import-fixer.js";const i={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer Try for computations that may throw`,recommended:!0},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},allowThrowInTests:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferTryOverTryCatch:`Prefer Try(() => ...) over try/catch block`,preferAsyncTryOverTryCatch:`Prefer Try.fromPromise(...), Either.fromPromise(...) or IO.tryPromise(...) over an async try/catch — Try(() => ...) cannot catch an awaited rejection`,suggestTry:`Replace with Try(() => ...)`,suggestTryFromPromise:`Replace with Try.fromPromise(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(i){let a=i.options[0]||{},o=a.allowInteropMarker!==!1,s=e=>o&&t(e,`interop`,i.sourceCode),c=a.allowThrowInTests!==!1;function l(){let e=i.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function u(e){return e.block?.body?.length===1}function d(e){if(!e.handler?.body)return!1;let t=e.handler.body.body;return t.length===0||t.length===1&&(t[0].type===`ReturnStatement`||t[0].type===`ExpressionStatement`)}function f(e){let t=e.block.body[0];return t.type===`ReturnStatement`&&t.argument?.type===`AwaitExpression`||t.type===`ExpressionStatement`&&t.expression?.type===`AwaitExpression`}return{TryStatement(t){if(s(t)||t.finalizer||c&&l()||t.handler&&t.handler.body&&t.handler.body.body.some(e=>e.type===`ThrowStatement`))return;let a=i.sourceCode,o=[];if(u(t)&&d(t)){let e=t.block.body[0];if(e.type===`ReturnStatement`){let i=e.argument,s=a.getText(i);if(f(t)){let e=i.type===`AwaitExpression`?i.argument:i,n=a.getText(e);o.push({messageId:`suggestTryFromPromise`,fix(e){return e.replaceText(t,`return Try.fromPromise(${n})`)}})}else o.push({messageId:`suggestTry`,fix(e){return e.replaceText(t,`return Try(() => ${s})`)}});r(a,`Try`)||o.push({messageId:`suggestAddImport`,data:{symbol:`Try`},fix:n(a,`Try`)})}}i.report({node:t,messageId:e(t.block)?`preferAsyncTryOverTryCatch`:`preferTryOverTryCatch`,suggest:o})}}}};export{i as default};
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.112.0",
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.12.0",
45
+ "functype": "^1.14.0",
46
46
  "ts-builds": "^3.4.3",
47
47
  "tsdown": "^0.23.0"
48
48
  },