eslint-plugin-functype 2.108.0 → 2.110.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +139 -12
- package/dist/cli/list-rules.js.map +1 -1
- package/dist/configs/recommended.d.ts +21 -5
- package/dist/configs/recommended.js +1 -1
- package/dist/configs/recommended.js.map +1 -1
- package/dist/configs/strict.d.ts +1 -1
- package/dist/configs/strict.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/no-get-unsafe.js +1 -1
- package/dist/rules/no-get-unsafe.js.map +1 -1
- package/dist/rules/no-imperative-loops.js +1 -1
- package/dist/rules/no-imperative-loops.js.map +1 -1
- package/dist/rules/no-let.js.map +1 -1
- package/dist/rules/prefer-do-notation.js +1 -1
- package/dist/rules/prefer-do-notation.js.map +1 -1
- package/dist/rules/prefer-either.js +1 -1
- package/dist/rules/prefer-either.js.map +1 -1
- package/dist/rules/prefer-flatmap.js +1 -1
- package/dist/rules/prefer-flatmap.js.map +1 -1
- package/dist/rules/prefer-fold.js +1 -1
- package/dist/rules/prefer-fold.js.map +1 -1
- package/dist/rules/prefer-functype-map.js +1 -1
- package/dist/rules/prefer-functype-map.js.map +1 -1
- package/dist/rules/prefer-functype-set.js +1 -1
- package/dist/rules/prefer-functype-set.js.map +1 -1
- package/dist/rules/prefer-list.js +1 -1
- package/dist/rules/prefer-list.js.map +1 -1
- package/dist/rules/prefer-map.js +1 -1
- package/dist/rules/prefer-map.js.map +1 -1
- package/dist/rules/prefer-option.js +1 -1
- package/dist/rules/prefer-option.js.map +1 -1
- package/dist/rules/prefer-try.js +1 -1
- package/dist/rules/prefer-try.js.map +1 -1
- package/dist/types/ast.d.ts +1 -2
- package/dist/utils/ast-walk.d.ts +12 -0
- package/dist/utils/ast-walk.js +2 -0
- package/dist/utils/ast-walk.js.map +1 -0
- package/dist/utils/async-detection.d.ts +6 -0
- package/dist/utils/async-detection.js +2 -0
- package/dist/utils/async-detection.js.map +1 -0
- package/dist/utils/boundary-tags.d.ts +25 -0
- package/dist/utils/boundary-tags.js +2 -0
- package/dist/utils/boundary-tags.js.map +1 -0
- package/dist/utils/dependency-validator.d.ts +4 -5
- package/dist/utils/dependency-validator.js +1 -1
- package/dist/utils/dependency-validator.js.map +1 -1
- package/dist/utils/functype-detection.d.ts +13 -14
- package/dist/utils/functype-detection.js +1 -1
- package/dist/utils/functype-detection.js.map +1 -1
- package/dist/utils/import-fixer.d.ts +2 -3
- package/dist/utils/import-fixer.js.map +1 -1
- package/dist/utils/mutable-collection.d.ts +30 -0
- package/dist/utils/mutable-collection.js +2 -0
- package/dist/utils/mutable-collection.js.map +1 -0
- package/dist/utils/wire-types.d.ts +21 -0
- package/dist/utils/wire-types.js +2 -0
- package/dist/utils/wire-types.js.map +1 -0
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -27,18 +27,145 @@ export default [functype.configs.strict]
|
|
|
27
27
|
|
|
28
28
|
## Rules
|
|
29
29
|
|
|
30
|
-
| Rule | Recommended | Strict | Description
|
|
31
|
-
| ------------------------------ | :---------: | :----: |
|
|
32
|
-
| `functype/
|
|
33
|
-
| `functype/
|
|
34
|
-
| `functype/prefer-
|
|
35
|
-
| `functype/prefer-
|
|
36
|
-
| `functype/prefer-map` |
|
|
37
|
-
| `functype/prefer-
|
|
38
|
-
| `functype/
|
|
39
|
-
| `functype/prefer-
|
|
40
|
-
| `functype/
|
|
41
|
-
| `functype/prefer-
|
|
30
|
+
| Rule | Recommended | Strict | Description |
|
|
31
|
+
| ------------------------------ | :---------: | :----: | ---------------------------------------------------------- |
|
|
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 |
|
|
34
|
+
| `functype/prefer-functype-map` | error | error | Use functype `Map` instead of a native `Map` you only read |
|
|
35
|
+
| `functype/prefer-functype-set` | error | error | Use functype `Set` instead of a native `Set` you only read |
|
|
36
|
+
| `functype/prefer-map` | error | error | Use `map` instead of pushing inside `forEach` |
|
|
37
|
+
| `functype/prefer-fold` | error | error | Use `fold` instead of branching on `isSome()`/`isLeft()`/… |
|
|
38
|
+
| `functype/prefer-option` | warn | error | Use `Option` instead of `null`/`undefined` |
|
|
39
|
+
| `functype/prefer-either` | warn | error | Use `Either` for typed domain errors instead of `throw` |
|
|
40
|
+
| `functype/prefer-try` | warn | error | Use `Try` / `Try.fromPromise` instead of try/catch |
|
|
41
|
+
| `functype/prefer-flatmap` | warn | warn | Use `flatMap` instead of `map().flat()` |
|
|
42
|
+
| `functype/prefer-do-notation` | warn | warn | Use `Do` notation for chained operations |
|
|
43
|
+
| `functype/no-get-unsafe` | off | error | Disallow unsafe extraction (`.orThrow()`, `.expect()`) |
|
|
44
|
+
| `functype/prefer-list` | off | warn | Use `List` instead of native arrays |
|
|
45
|
+
|
|
46
|
+
### Severity policy
|
|
47
|
+
|
|
48
|
+
A rule is **`error` in `recommended` once it is right on ~95–99% of real code**, meaning its known false-positive classes are closed. It stays `warn` only while those classes are still open. FP here is governance: a rule that is reliably right should fail the build, not print advice nobody reads. Expect `recommended` to get stricter as boundary markers (`Wire<T>`, `@interop`) close the remaining cases for `prefer-option`, `prefer-either` and `prefer-try`.
|
|
49
|
+
|
|
50
|
+
`prefer-fold` reports only; its rewrite is a suggestion you apply, never an autofix, so `eslint --fix` can't change code on your behalf.
|
|
51
|
+
|
|
52
|
+
## Boundary markers: `@interop` and `@invariant`
|
|
53
|
+
|
|
54
|
+
Some code is correct _because_ it isn't FP-shaped: a bridge to a host whose contract is the throw, the rejection or the nullable. Mark the declaration instead of disabling the rule:
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
/**
|
|
58
|
+
* Runs the effect, or throws a boxed error.
|
|
59
|
+
*
|
|
60
|
+
* @interop React Query signals failure only by promise rejection; an Either return reads as success.
|
|
61
|
+
*/
|
|
62
|
+
const runBoxed = async <E, A>(effect: () => IO<never, E, A>): Promise<A> => { … }
|
|
63
|
+
|
|
64
|
+
/** @invariant Called only inside a DBOS step, where every argument is already validated. */
|
|
65
|
+
function deriveRunId(workflowId: string, step: number): string {
|
|
66
|
+
if (step < 0) throw new Error("step must be non-negative")
|
|
67
|
+
…
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
| Tag | Honored by | Means |
|
|
72
|
+
| --------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
|
73
|
+
| `@interop <reason>` | `prefer-either`, `prefer-option`, `prefer-fold`, `prefer-try` | This declaration bridges functype to a host (React, React Query, an SDK) whose contract requires the non-FP shape. |
|
|
74
|
+
| `@invariant <reason>` | `prefer-either` | This declaration throws only for programmer errors, never for expected failures. |
|
|
75
|
+
|
|
76
|
+
- **Scope:** the tagged declaration and everything nested in it. That can be a function, `const`, method, class field, object property, type alias or interface. A sibling declaration is not covered.
|
|
77
|
+
- **The reason is required**, on the same line as the tag. A bare `@interop` exempts nothing.
|
|
78
|
+
- **Only JSDoc (`/** … */`) counts.** A `//` comment mentioning the tag does not.
|
|
79
|
+
- **Opt out** per rule with `allowInteropMarker: false` / `allowInvariantMarker: false`.
|
|
80
|
+
|
|
81
|
+
Prefer a marker to `eslint-disable`. A disable covers a whole file or line and says only "be quiet". A marker covers one declaration, carries its reason, and `rg '@interop'` gives the complete inventory of places the code touches a throw-based host.
|
|
82
|
+
|
|
83
|
+
## Rule options
|
|
84
|
+
|
|
85
|
+
### `functype/prefer-list`
|
|
86
|
+
|
|
87
|
+
| Option | Default | Description |
|
|
88
|
+
| --------------------- | :-----: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
89
|
+
| `allowArraysInTests` | `true` | Silence the rule inside test files (`.test.ts`, `.spec.ts`, `__tests__/`, `/test/`, `/tests/`). |
|
|
90
|
+
| `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 wrapping a boundary type in `Wire<…>` is the explicit escape hatch. |
|
|
91
|
+
| `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. |
|
|
92
|
+
|
|
93
|
+
**Boundary recipe (recommended for codebases touching serialization boundaries):**
|
|
94
|
+
|
|
95
|
+
```jsonc
|
|
96
|
+
{
|
|
97
|
+
"functype/prefer-list": ["error", { "allowReadonlyArrays": false }],
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Then annotate boundaries with `Wire<T>` from `functype`:
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
import type { Wire } from "functype"
|
|
105
|
+
type ClaimedDocs = Wire<ReadonlyArray<Row>>
|
|
106
|
+
type UserRow = Wire<{ readonly email: string | null; readonly tags: ReadonlyArray<string> }>
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`Wire<T>` is assignable both ways with the plain type, so no casts. `prefer-list` and `prefer-option` skip everything inside a `Wire<…>` type argument (`wireTypes` option, default `["Wire"]`; `[]` turns it off), and consumer aliases stack cleanly.
|
|
110
|
+
|
|
111
|
+
### `functype/no-get-unsafe`
|
|
112
|
+
|
|
113
|
+
| Option | Default | Description |
|
|
114
|
+
| --------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
115
|
+
| `allowInTests` | `true` | Silence the rule inside test files (same predicate as above). |
|
|
116
|
+
| `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. |
|
|
117
|
+
|
|
118
|
+
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.
|
|
119
|
+
|
|
120
|
+
### `functype/prefer-fold`
|
|
121
|
+
|
|
122
|
+
| Option | Default | Description |
|
|
123
|
+
| --------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
124
|
+
| `minComplexity` | `2` | Minimum if/else chain length (root + branches) before it is reported. |
|
|
125
|
+
| `checkNullable` | `false` | Also report null checks on plain values (`x === null ? a : b`). Off because whether `x` should be an `Option` is `prefer-option`'s call; at `error` this path fired on JSX, style objects and conditional spreads. |
|
|
126
|
+
|
|
127
|
+
Reports only; the rewrite is a **suggestion, never an autofix**. A fold rewrite can't be proven type-correct without type information, and `eslint --fix` applies fixable rules at warn severity too, so an autofix here would rewrite working code during `validate`. The suggestion reads narrowed values through the fold's parameters (`e.value` after `isLeft()` becomes `left`), omits unused parameters, keeps `return` on if/else chains, parenthesizes object-literal branches, and offers `a.or(b)` for `a.isSome() ? a : b`. Rewrites follow the syntax tree, so text inside strings, template literals and comments is left alone. No suggestion is offered when the rewrite would drop a comment or could not type-check (`a.isSome() ? a : 5`). Suggestions are applied by hand, so review each one: the rule has no type information and can't prove the result compiles.
|
|
128
|
+
|
|
129
|
+
### `functype/prefer-option`
|
|
130
|
+
|
|
131
|
+
| Option | Default | Description |
|
|
132
|
+
| --------------- | ------- | -------------------------------------------------------------------------------------------------------- |
|
|
133
|
+
| `allowUseState` | `true` | Don't report `T \| null` inside the type argument of `useState` / `useRef` (bare or `React.`-qualified). |
|
|
134
|
+
|
|
135
|
+
`null` is idiomatic React state, and an `Option` there fights the hook's own API. Nullable component parameters and props are still reported.
|
|
136
|
+
|
|
137
|
+
### `functype/prefer-map`
|
|
138
|
+
|
|
139
|
+
| Option | Default | Description |
|
|
140
|
+
| ------------------- | ------- | -------------------------------------------------------------------------------------------------------------- |
|
|
141
|
+
| `checkArrayMethods` | `true` | Report `.push` inside `forEach` callbacks and `forEach` used as a map. |
|
|
142
|
+
| `checkForLoops` | `false` | Also report `for`/`for..of`/`for..in` loops that push. Off because `no-imperative-loops` already reports them. |
|
|
143
|
+
|
|
144
|
+
### `functype/prefer-functype-set` / `functype/prefer-functype-map`
|
|
145
|
+
|
|
146
|
+
| Option | Default | Description |
|
|
147
|
+
| -------------- | ------- | ----------------------------------------------------------------------------------------------- |
|
|
148
|
+
| `allowInTests` | `true` | Silence the rule inside test files. |
|
|
149
|
+
| `allowMutable` | `true` | Don't report a native `Set`/`Map` the code mutates on purpose. Set `false` to report it anyway. |
|
|
150
|
+
|
|
151
|
+
A collection counts as mutated when `.add` / `.delete` / `.clear` (Set) or `.set` / `.delete` / `.clear` (Map) is called on it, including `x!.add(…)`. The call can be made:
|
|
152
|
+
|
|
153
|
+
- directly on a `new` expression that copies something (`new Set(prev).add(id)`, the React copy-then-add). An empty-`new` builder chain like `new Map().set(a, 1).set(b, 2)` is not exempt; use `Map.of` / `Set.of`.
|
|
154
|
+
- directly through the variable, parameter or later-assigned `let` holding it, in any nested scope.
|
|
155
|
+
- through `this.<field>` in the owning class: a field initializer, a constructor assignment, or a constructor parameter property.
|
|
156
|
+
|
|
157
|
+
Not followed: aliases (`const t = s; t.add(x)`), `useRef(new Set()).current.add(x)`, a mutator passed as a callback (`xs.forEach(seen.add, seen)`), and a collection passed into another function. Those are still reported.
|
|
158
|
+
|
|
159
|
+
functype's collections are immutable, so a cache, registry or in-place accumulator can't use them. A native collection that is only read (`.has`, `.get`, iteration) is still reported.
|
|
160
|
+
|
|
161
|
+
### `functype/no-imperative-loops` / `functype/prefer-map`
|
|
162
|
+
|
|
163
|
+
These rules don't report loops that have no functional equivalent:
|
|
164
|
+
|
|
165
|
+
- `for await` consumes a stream, and collecting it first would defeat the streaming.
|
|
166
|
+
- A loop whose body `yield`s is a generator's body, and a callback can't yield.
|
|
167
|
+
|
|
168
|
+
A loop whose body `await`s is still reported by `no-imperative-loops`, which points at `IO.forEach`. `prefer-map` doesn't report it.
|
|
42
169
|
|
|
43
170
|
## Combining with eslint-config-functype
|
|
44
171
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"list-rules.js","names":[],"sources":["../../src/cli/list-rules.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport plugin from \"../index.js\"\nimport { validatePeerDependencies, type ValidationResult } from \"../utils/dependency-validator.js\"\n\n// Colors for console output\nconst colors = {\n reset: \"\\x1b[0m\",\n bright: \"\\x1b[1m\",\n red: \"\\x1b[31m\",\n green: \"\\x1b[32m\",\n yellow: \"\\x1b[33m\",\n blue: \"\\x1b[34m\",\n magenta: \"\\x1b[35m\",\n cyan: \"\\x1b[36m\",\n} as const\n\nfunction colorize(text: string, color: keyof typeof colors): string {\n return colors[color] + text + colors.reset\n}\n\n// Removed unused utility functions - they were for the old config-based approach\n\nfunction printDependencyStatus(result: ValidationResult): void {\n console.log(colorize(\"\\n🔍 Dependency Status Check:\", \"bright\"))\n console.log(colorize(\"=\".repeat(40), \"blue\"))\n\n // Show available dependencies\n if (result.available.length > 0) {\n console.log(colorize(\"\\n✅ Available:\", \"green\"))\n result.available.forEach((dep) => {\n const icon = dep.required ? \"🔧\" : \"🔌\"\n console.log(` ${icon} ${colorize(dep.name, \"green\")} - ${dep.description}`)\n })\n }\n\n // Show missing dependencies\n if (result.missing.length > 0) {\n console.log(colorize(\"\\n❌ Missing:\", \"red\"))\n result.missing.forEach((dep) => {\n const icon = dep.required ? \"⚠️ \" : \"💡\"\n const color = dep.required ? \"red\" : \"yellow\"\n console.log(` ${icon} ${colorize(dep.name, color)} - ${dep.description}`)\n })\n\n if (result.installCommand) {\n console.log(colorize(\"\\n📦 Install missing dependencies:\", \"bright\"))\n console.log(` ${colorize(result.installCommand, \"cyan\")}`)\n }\n }\n\n // Show warnings\n if (result.warnings.length > 0) {\n console.log(colorize(\"\\n⚠️ Warnings:\", \"yellow\"))\n result.warnings.forEach((warning) => console.log(` ${warning}`))\n }\n\n // Overall status\n const status = result.isValid ? \"✅ Ready to use\" : \"❌ Configuration will fail\"\n const statusColor = result.isValid ? \"green\" : \"red\"\n console.log(colorize(`\\n${status}`, statusColor))\n}\n\nasync function main(): Promise<void> {\n const args = process.argv.slice(2)\n const showHelp = args.includes(\"--help\") || args.includes(\"-h\")\n const showUsage = args.includes(\"--usage\") || args.includes(\"-u\")\n const checkDeps = args.includes(\"--check-deps\") || args.includes(\"--check\")\n\n if (showHelp) {\n console.log(colorize(\"📋 ESLint Plugin Functype - Custom Rules\", \"bright\"))\n console.log(\"\\nUsage: pnpm run list-rules [options]\")\n console.log(\"\\nOptions:\")\n console.log(\" --verbose, -v Show rule descriptions and schemas\")\n console.log(\" --usage, -u Show usage examples\")\n console.log(\" --check-deps Check peer dependency status\")\n console.log(\" --help, -h Show this help message\")\n console.log(\"\\nThis command lists all custom rules provided by the functype plugin.\")\n return\n }\n\n // Handle dependency check\n if (checkDeps) {\n console.log(colorize(\"🔧 ESLint Plugin Functype - Dependency Check\", \"bright\"))\n const result = validatePeerDependencies()\n printDependencyStatus(result)\n\n if (!result.isValid) {\n process.exit(1)\n }\n return\n }\n\n console.log(colorize(\"🔧 ESLint Plugin Functype - Custom Rules\", \"bright\"))\n\n if (!plugin.rules) {\n console.error(colorize(\"❌ No rules found in plugin.\", \"red\"))\n process.exit(1)\n }\n\n console.log(colorize(\"\\n📦 Available Custom Rules:\", \"bright\"))\n console.log(colorize(\"=\".repeat(40), \"blue\"))\n\n const rules = Object.keys(plugin.rules)\n\n rules.forEach((ruleName) => {\n const rule = plugin.rules[ruleName]\n const fullName = `functype/${ruleName}`\n\n console.log(`\\n${colorize(\"●\", \"green\")} ${colorize(fullName, \"bright\")}`)\n\n if (rule.meta?.docs?.description) {\n console.log(` ${colorize(\"Description:\", \"cyan\")} ${rule.meta.docs.description}`)\n }\n\n if (rule.meta?.type) {\n const typeColor = rule.meta.type === \"problem\" ? \"red\" : rule.meta.type === \"suggestion\" ? \"yellow\" : \"blue\"\n console.log(` ${colorize(\"Type:\", \"cyan\")} ${colorize(rule.meta.type, typeColor)}`)\n }\n\n if (rule.meta?.fixable) {\n console.log(` ${colorize(\"Fixable:\", \"cyan\")} ${colorize(\"Yes\", \"green\")}`)\n }\n\n if (showUsage) {\n console.log(` ${colorize(\"Usage:\", \"cyan\")} \"${fullName}\": \"error\"`)\n }\n })\n\n console.log(colorize(`\\n📊 Summary: ${rules.length} custom rules available`, \"bright\"))\n\n if (showUsage) {\n printCustomUsageInfo()\n }\n\n console.log(colorize(\"\\n💡 Tips:\", \"bright\"))\n console.log(\"• Use --verbose to see detailed rule information\")\n console.log(\"• Use --usage to see configuration examples\")\n console.log('• All rules are prefixed with \"functype/\"')\n console.log(\"• Consider using eslint-config-functype for pre-configured setup\")\n\n console.log(colorize(\"\\n🔗 Links:\", \"bright\"))\n console.log(\"• Documentation: https://github.com/jordanburke/eslint-plugin-functype\")\n console.log(\"• Configuration Bundle: https://github.com/jordanburke/eslint-config-functype\")\n console.log(\"• Functype Library: https://github.com/jordanburke/functype\")\n}\n\nfunction printCustomUsageInfo(): void {\n console.log(colorize(\"\\n💡 Usage Examples:\", \"bright\"))\n console.log(colorize(\"=\".repeat(30), \"blue\"))\n console.log(\"\\n\" + colorize(\"ESLint 9+ (flat config):\", \"green\"))\n console.log(' import functypePlugin from \"eslint-plugin-functype\"')\n console.log(\" export default [\")\n console.log(\" {\")\n console.log(\" plugins: { functype: functypePlugin },\")\n console.log(\" rules: {\")\n console.log(' \"functype/prefer-option\": \"error\",')\n console.log(' \"functype/prefer-either\": \"error\",')\n console.log(' \"functype/no-get-unsafe\": \"error\",')\n console.log(\" }\")\n console.log(\" }\")\n console.log(\" ]\")\n console.log(\"\\n\" + colorize(\"With eslint-config-functype (recommended):\", \"green\"))\n console.log(' import functypeConfig from \"eslint-config-functype\"')\n console.log(\" export default [functypeConfig.recommended]\")\n}\n\n// Run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AAS,EACrB,QAAQ,IAAI,OAAO,EACnB,QAAQ,IAAI,KAAK,EACjB,QAAQ,IAAI;EAAO,EAAS,6CAA8C,OAAO,CAAC,EAClF,QAAQ,IAAI,uDAAuD,EACnE,QAAQ,IAAI,+CAA+C,CAC7D,CAGA,EAAK,CAAC,CAAC,MAAO,GAAU,CACtB,QAAQ,MAAM,EAAS,sBAAuB,KAAK,EAAG,CAAK,EAC3D,QAAQ,KAAK,CAAC,CAChB,CAAC"}
|
|
1
|
+
{"version":3,"file":"list-rules.js","names":["plugin","colors","colorize","color","text","printDependencyStatus","result","icon","dep","warning","status","statusColor","main","args","showHelp","showUsage","checkDeps","validatePeerDependencies","rules","rule","ruleName","fullName","typeColor","printCustomUsageInfo","error"],"sources":["../../src/cli/list-rules.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport plugin from \"../index.js\"\nimport { validatePeerDependencies, type ValidationResult } from \"../utils/dependency-validator.js\"\n\n// Colors for console output\nconst colors = {\n reset: \"\\x1b[0m\",\n bright: \"\\x1b[1m\",\n red: \"\\x1b[31m\",\n green: \"\\x1b[32m\",\n yellow: \"\\x1b[33m\",\n blue: \"\\x1b[34m\",\n magenta: \"\\x1b[35m\",\n cyan: \"\\x1b[36m\",\n} as const\n\nfunction colorize(text: string, color: keyof typeof colors): string {\n return colors[color] + text + colors.reset\n}\n\n// Removed unused utility functions - they were for the old config-based approach\n\nfunction printDependencyStatus(result: ValidationResult): void {\n console.log(colorize(\"\\n🔍 Dependency Status Check:\", \"bright\"))\n console.log(colorize(\"=\".repeat(40), \"blue\"))\n\n // Show available dependencies\n if (result.available.length > 0) {\n console.log(colorize(\"\\n✅ Available:\", \"green\"))\n result.available.forEach((dep) => {\n const icon = dep.required ? \"🔧\" : \"🔌\"\n console.log(` ${icon} ${colorize(dep.name, \"green\")} - ${dep.description}`)\n })\n }\n\n // Show missing dependencies\n if (result.missing.length > 0) {\n console.log(colorize(\"\\n❌ Missing:\", \"red\"))\n result.missing.forEach((dep) => {\n const icon = dep.required ? \"⚠️ \" : \"💡\"\n const color = dep.required ? \"red\" : \"yellow\"\n console.log(` ${icon} ${colorize(dep.name, color)} - ${dep.description}`)\n })\n\n if (result.installCommand) {\n console.log(colorize(\"\\n📦 Install missing dependencies:\", \"bright\"))\n console.log(` ${colorize(result.installCommand, \"cyan\")}`)\n }\n }\n\n // Show warnings\n if (result.warnings.length > 0) {\n console.log(colorize(\"\\n⚠️ Warnings:\", \"yellow\"))\n result.warnings.forEach((warning) => console.log(` ${warning}`))\n }\n\n // Overall status\n const status = result.isValid ? \"✅ Ready to use\" : \"❌ Configuration will fail\"\n const statusColor = result.isValid ? \"green\" : \"red\"\n console.log(colorize(`\\n${status}`, statusColor))\n}\n\nasync function main(): Promise<void> {\n const args = process.argv.slice(2)\n const showHelp = args.includes(\"--help\") || args.includes(\"-h\")\n const showUsage = args.includes(\"--usage\") || args.includes(\"-u\")\n const checkDeps = args.includes(\"--check-deps\") || args.includes(\"--check\")\n\n if (showHelp) {\n console.log(colorize(\"📋 ESLint Plugin Functype - Custom Rules\", \"bright\"))\n console.log(\"\\nUsage: pnpm run list-rules [options]\")\n console.log(\"\\nOptions:\")\n console.log(\" --verbose, -v Show rule descriptions and schemas\")\n console.log(\" --usage, -u Show usage examples\")\n console.log(\" --check-deps Check peer dependency status\")\n console.log(\" --help, -h Show this help message\")\n console.log(\"\\nThis command lists all custom rules provided by the functype plugin.\")\n return\n }\n\n // Handle dependency check\n if (checkDeps) {\n console.log(colorize(\"🔧 ESLint Plugin Functype - Dependency Check\", \"bright\"))\n const result = validatePeerDependencies()\n printDependencyStatus(result)\n\n if (!result.isValid) {\n process.exit(1)\n }\n return\n }\n\n console.log(colorize(\"🔧 ESLint Plugin Functype - Custom Rules\", \"bright\"))\n\n if (!plugin.rules) {\n console.error(colorize(\"❌ No rules found in plugin.\", \"red\"))\n process.exit(1)\n }\n\n console.log(colorize(\"\\n📦 Available Custom Rules:\", \"bright\"))\n console.log(colorize(\"=\".repeat(40), \"blue\"))\n\n const rules = Object.keys(plugin.rules)\n\n rules.forEach((ruleName) => {\n const rule = plugin.rules[ruleName]\n const fullName = `functype/${ruleName}`\n\n console.log(`\\n${colorize(\"●\", \"green\")} ${colorize(fullName, \"bright\")}`)\n\n if (rule.meta?.docs?.description) {\n console.log(` ${colorize(\"Description:\", \"cyan\")} ${rule.meta.docs.description}`)\n }\n\n if (rule.meta?.type) {\n const typeColor = rule.meta.type === \"problem\" ? \"red\" : rule.meta.type === \"suggestion\" ? \"yellow\" : \"blue\"\n console.log(` ${colorize(\"Type:\", \"cyan\")} ${colorize(rule.meta.type, typeColor)}`)\n }\n\n if (rule.meta?.fixable) {\n console.log(` ${colorize(\"Fixable:\", \"cyan\")} ${colorize(\"Yes\", \"green\")}`)\n }\n\n if (showUsage) {\n console.log(` ${colorize(\"Usage:\", \"cyan\")} \"${fullName}\": \"error\"`)\n }\n })\n\n console.log(colorize(`\\n📊 Summary: ${rules.length} custom rules available`, \"bright\"))\n\n if (showUsage) {\n printCustomUsageInfo()\n }\n\n console.log(colorize(\"\\n💡 Tips:\", \"bright\"))\n console.log(\"• Use --verbose to see detailed rule information\")\n console.log(\"• Use --usage to see configuration examples\")\n console.log('• All rules are prefixed with \"functype/\"')\n console.log(\"• Consider using eslint-config-functype for pre-configured setup\")\n\n console.log(colorize(\"\\n🔗 Links:\", \"bright\"))\n console.log(\"• Documentation: https://github.com/jordanburke/eslint-plugin-functype\")\n console.log(\"• Configuration Bundle: https://github.com/jordanburke/eslint-config-functype\")\n console.log(\"• Functype Library: https://github.com/jordanburke/functype\")\n}\n\nfunction printCustomUsageInfo(): void {\n console.log(colorize(\"\\n💡 Usage Examples:\", \"bright\"))\n console.log(colorize(\"=\".repeat(30), \"blue\"))\n console.log(\"\\n\" + colorize(\"ESLint 9+ (flat config):\", \"green\"))\n console.log(' import functypePlugin from \"eslint-plugin-functype\"')\n console.log(\" export default [\")\n console.log(\" {\")\n console.log(\" plugins: { functype: functypePlugin },\")\n console.log(\" rules: {\")\n console.log(' \"functype/prefer-option\": \"error\",')\n console.log(' \"functype/prefer-either\": \"error\",')\n console.log(' \"functype/no-get-unsafe\": \"error\",')\n console.log(\" }\")\n console.log(\" }\")\n console.log(\" ]\")\n console.log(\"\\n\" + colorize(\"With eslint-config-functype (recommended):\", \"green\"))\n console.log(' import functypeConfig from \"eslint-config-functype\"')\n console.log(\" export default [functypeConfig.recommended]\")\n}\n\n// Run the CLI\nmain().catch((error) => {\n console.error(colorize(\"❌ Unexpected error:\", \"red\"), error)\n process.exit(1)\n})\n"],"mappings":";uGAMA,MAAMC,EAAS,CACb,MAAO,UACP,OAAQ,UACR,IAAK,WACL,MAAO,WACP,OAAQ,WACR,KAAM,WACN,QAAS,WACT,KAAM,UACR,EAEA,SAASC,EAAS,EAAc,EAAoC,CAClE,OAAOD,EAAOE,GAASC,EAAOH,EAAO,KACvC,CAIA,SAASI,EAAsB,EAAgC,CAC7D,QAAQ,IAAIH,EAAS;6BAAiC,QAAQ,CAAC,EAC/D,QAAQ,IAAIA,EAAS,IAAI,OAAO,EAAE,EAAG,MAAM,CAAC,EAGxCI,EAAO,UAAU,OAAS,IAC5B,QAAQ,IAAIJ,EAAS;cAAkB,OAAO,CAAC,EAC/CI,EAAO,UAAU,QAAS,GAAQ,CAChC,IAAMC,EAAOC,EAAI,SAAW,KAAO,KACnC,QAAQ,IAAI,KAAKD,EAAK,GAAGL,EAASM,EAAI,KAAM,OAAO,EAAE,KAAKA,EAAI,aAAa,CAC7E,CAAC,GAICF,EAAO,QAAQ,OAAS,IAC1B,QAAQ,IAAIJ,EAAS;YAAgB,KAAK,CAAC,EAC3CI,EAAO,QAAQ,QAAS,GAAQ,CAC9B,IAAMC,EAAOC,EAAI,SAAW,MAAQ,KAC9BL,EAAQK,EAAI,SAAW,MAAQ,SACrC,QAAQ,IAAI,KAAKD,EAAK,GAAGL,EAASM,EAAI,KAAML,CAAK,EAAE,KAAKK,EAAI,aAAa,CAC3E,CAAC,EAEGF,EAAO,iB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CACpC,QAAQ,IAAIrB,EAAS;oBAAwB,QAAQ,CAAC,EACtD,QAAQ,IAAIA,EAAS,IAAI,OAAO,EAAE,EAAG,MAAM,CAAC,EAC5C,QAAQ,IAAI;EAAOA,EAAS,2BAA4B,OAAO,CAAC,EAChE,QAAQ,IAAI,uDAAuD,EACnE,QAAQ,IAAI,oBAAoB,EAChC,QAAQ,IAAI,OAAO,EACnB,QAAQ,IAAI,8CAA8C,EAC1D,QAAQ,IAAI,gBAAgB,EAC5B,QAAQ,IAAI,4CAA4C,EACxD,QAAQ,IAAI,4CAA4C,EACxD,QAAQ,IAAI,4CAA4C,EACxD,QAAQ,IAAI,SAAS,EACrB,QAAQ,IAAI,OAAO,EACnB,QAAQ,IAAI,KAAK,EACjB,QAAQ,IAAI;EAAOA,EAAS,6CAA8C,OAAO,CAAC,EAClF,QAAQ,IAAI,uDAAuD,EACnE,QAAQ,IAAI,+CAA+C,CAC7D,CAGAU,EAAK,CAAC,CAAC,MAAO,GAAU,CACtB,QAAQ,MAAMV,EAAS,sBAAuB,KAAK,EAAGsB,CAAK,EAC3D,QAAQ,KAAK,CAAC,CAChB,CAAC"}
|
|
@@ -1,15 +1,31 @@
|
|
|
1
1
|
//#region src/configs/recommended.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Severity policy (#325): a rule is `error` once it is right on ~95–99% of real code and its known
|
|
4
|
+
* false-positive classes are closed; it stays `warn` only while those classes are still open. FP here
|
|
5
|
+
* is governance — a rule that is reliably right should fail the build, not print advice nobody reads
|
|
6
|
+
* (CivalaOS shipped 85 new violations under "lint OK" because every rule but `no-let` warned).
|
|
7
|
+
*
|
|
8
|
+
* Still `warn`, and why:
|
|
9
|
+
* - prefer-option / prefer-either / prefer-try: fire on correct code at serialization boundaries
|
|
10
|
+
* (JSON rows, DTOs) and on documented invariant throws — #325 B/D close those.
|
|
11
|
+
* - prefer-flatmap / prefer-do-notation: heuristics without type information; precision unmeasured.
|
|
12
|
+
*
|
|
13
|
+
* Graduated with a precision condition: prefer-fold checks functype predicate calls (`isSome()`,
|
|
14
|
+
* `isLeft()`) only; its null-check heuristic is opt-in (`checkNullable`) because it fired on plain
|
|
15
|
+
* nullables — 31 of 31 hits in CivalaOS. prefer-map leaves loops to no-imperative-loops (`checkForLoops`
|
|
16
|
+
* off), so one loop is one error.
|
|
17
|
+
*/
|
|
2
18
|
declare const recommendedRules: {
|
|
3
19
|
"functype/no-let": string;
|
|
20
|
+
"functype/no-imperative-loops": string;
|
|
21
|
+
"functype/prefer-functype-map": string;
|
|
22
|
+
"functype/prefer-functype-set": string;
|
|
23
|
+
"functype/prefer-map": string;
|
|
24
|
+
"functype/prefer-fold": string;
|
|
4
25
|
"functype/prefer-option": string;
|
|
5
26
|
"functype/prefer-either": string;
|
|
6
27
|
"functype/prefer-try": string;
|
|
7
|
-
"functype/prefer-fold": string;
|
|
8
|
-
"functype/prefer-map": string;
|
|
9
28
|
"functype/prefer-flatmap": string;
|
|
10
|
-
"functype/prefer-functype-map": string;
|
|
11
|
-
"functype/prefer-functype-set": string;
|
|
12
|
-
"functype/no-imperative-loops": string;
|
|
13
29
|
"functype/prefer-do-notation": string;
|
|
14
30
|
"functype/no-get-unsafe": string;
|
|
15
31
|
"functype/prefer-list": string;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e={"functype/no-let":`error`,"functype/
|
|
1
|
+
const e={"functype/no-let":`error`,"functype/no-imperative-loops":`error`,"functype/prefer-functype-map":`error`,"functype/prefer-functype-set":`error`,"functype/prefer-map":`error`,"functype/prefer-fold":`error`,"functype/prefer-option":`warn`,"functype/prefer-either":`warn`,"functype/prefer-try":`warn`,"functype/prefer-flatmap":`warn`,"functype/prefer-do-notation":`warn`,"functype/no-get-unsafe":`off`,"functype/prefer-list":`off`};export{e as default};
|
|
2
2
|
//# sourceMappingURL=recommended.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recommended.js","names":[],"sources":["../../src/configs/recommended.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"recommended.js","names":["recommendedRules"],"sources":["../../src/configs/recommended.ts"],"sourcesContent":["/**\n * Severity policy (#325): a rule is `error` once it is right on ~95–99% of real code and its known\n * false-positive classes are closed; it stays `warn` only while those classes are still open. FP here\n * is governance — a rule that is reliably right should fail the build, not print advice nobody reads\n * (CivalaOS shipped 85 new violations under \"lint OK\" because every rule but `no-let` warned).\n *\n * Still `warn`, and why:\n * - prefer-option / prefer-either / prefer-try: fire on correct code at serialization boundaries\n * (JSON rows, DTOs) and on documented invariant throws — #325 B/D close those.\n * - prefer-flatmap / prefer-do-notation: heuristics without type information; precision unmeasured.\n *\n * Graduated with a precision condition: prefer-fold checks functype predicate calls (`isSome()`,\n * `isLeft()`) only; its null-check heuristic is opt-in (`checkNullable`) because it fired on plain\n * nullables — 31 of 31 hits in CivalaOS. prefer-map leaves loops to no-imperative-loops (`checkForLoops`\n * off), so one loop is one error.\n */\nconst recommendedRules = {\n \"functype/no-let\": \"error\",\n \"functype/no-imperative-loops\": \"error\",\n \"functype/prefer-functype-map\": \"error\",\n \"functype/prefer-functype-set\": \"error\",\n \"functype/prefer-map\": \"error\",\n \"functype/prefer-fold\": \"error\",\n \"functype/prefer-option\": \"warn\",\n \"functype/prefer-either\": \"warn\",\n \"functype/prefer-try\": \"warn\",\n \"functype/prefer-flatmap\": \"warn\",\n \"functype/prefer-do-notation\": \"warn\",\n \"functype/no-get-unsafe\": \"off\",\n \"functype/prefer-list\": \"off\",\n}\n\nexport default recommendedRules\n"],"mappings":"AAgBA,MAAMA,EAAmB,CACvB,kBAAmB,QACnB,+BAAgC,QAChC,+BAAgC,QAChC,+BAAgC,QAChC,sBAAuB,QACvB,uBAAwB,QACxB,yBAA0B,OAC1B,yBAA0B,OAC1B,sBAAuB,OACvB,0BAA2B,OAC3B,8BAA+B,OAC/B,yBAA0B,MAC1B,uBAAwB,KAC1B"}
|
package/dist/configs/strict.d.ts
CHANGED
|
@@ -9,8 +9,8 @@ declare const strictRules: {
|
|
|
9
9
|
"functype/prefer-functype-set": string;
|
|
10
10
|
"functype/no-imperative-loops": string;
|
|
11
11
|
"functype/no-let": string;
|
|
12
|
-
"functype/prefer-fold": string;
|
|
13
12
|
"functype/prefer-map": string;
|
|
13
|
+
"functype/prefer-fold": string;
|
|
14
14
|
"functype/prefer-flatmap": string;
|
|
15
15
|
"functype/prefer-do-notation": string;
|
|
16
16
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"strict.js","names":[],"sources":["../../src/configs/strict.ts"],"sourcesContent":["import recommendedRules from \"./recommended\"\n\nconst strictRules = {\n ...recommendedRules,\n \"functype/prefer-option\": \"error\",\n \"functype/prefer-either\": \"error\",\n \"functype/prefer-try\": \"error\",\n \"functype/no-get-unsafe\": \"error\",\n \"functype/prefer-list\": \"warn\",\n \"functype/prefer-functype-map\": \"error\",\n \"functype/prefer-functype-set\": \"error\",\n \"functype/no-imperative-loops\": \"error\",\n}\n\nexport default strictRules\n"],"mappings":"gCAEA,
|
|
1
|
+
{"version":3,"file":"strict.js","names":["recommendedRules","strictRules"],"sources":["../../src/configs/strict.ts"],"sourcesContent":["import recommendedRules from \"./recommended\"\n\nconst strictRules = {\n ...recommendedRules,\n \"functype/prefer-option\": \"error\",\n \"functype/prefer-either\": \"error\",\n \"functype/prefer-try\": \"error\",\n \"functype/no-get-unsafe\": \"error\",\n \"functype/prefer-list\": \"warn\",\n \"functype/prefer-functype-map\": \"error\",\n \"functype/prefer-functype-set\": \"error\",\n \"functype/no-imperative-loops\": \"error\",\n}\n\nexport default strictRules\n"],"mappings":"gCAEA,MAAMC,EAAc,CAClB,GAAGD,EACH,yBAA0B,QAC1B,yBAA0B,QAC1B,sBAAuB,QACvB,yBAA0B,QAC1B,uBAAwB,OACxB,+BAAgC,QAChC,+BAAgC,QAChC,+BAAgC,OAClC"}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import recommendedRules from \"./configs/recommended\"\nimport strictRules from \"./configs/strict\"\nimport rules from \"./rules\"\n\nconst plugin = {\n rules,\n meta: {\n name: \"eslint-plugin-functype\",\n version: \"2.0.0\",\n },\n configs: {} as Record<string, unknown>,\n}\n\n// Self-referencing plugin in configs (ESLint flat config pattern)\nplugin.configs = {\n recommended: {\n name: \"functype-plugin/recommended\",\n plugins: { functype: plugin },\n rules: recommendedRules,\n },\n strict: {\n name: \"functype-plugin/strict\",\n plugins: { functype: plugin },\n rules: strictRules,\n },\n}\n\nexport default plugin\n"],"mappings":"2GAIA,
|
|
1
|
+
{"version":3,"file":"index.js","names":["recommendedRules","strictRules","rules_default","plugin"],"sources":["../src/index.ts"],"sourcesContent":["import recommendedRules from \"./configs/recommended\"\nimport strictRules from \"./configs/strict\"\nimport rules from \"./rules\"\n\nconst plugin = {\n rules,\n meta: {\n name: \"eslint-plugin-functype\",\n version: \"2.0.0\",\n },\n configs: {} as Record<string, unknown>,\n}\n\n// Self-referencing plugin in configs (ESLint flat config pattern)\nplugin.configs = {\n recommended: {\n name: \"functype-plugin/recommended\",\n plugins: { functype: plugin },\n rules: recommendedRules,\n },\n strict: {\n name: \"functype-plugin/strict\",\n plugins: { functype: plugin },\n rules: strictRules,\n },\n}\n\nexport default plugin\n"],"mappings":"2GAIA,MAAMG,EAAS,CACb,MAAAD,EACA,KAAM,CACJ,KAAM,yBACN,QAAS,OACX,EACA,QAAS,CAAC,CACZ,EAGA,EAAO,QAAU,CACf,YAAa,CACX,KAAM,8BACN,QAAS,CAAE,SAAUC,CAAO,EAC5B,MAAOH,CACT,EACA,OAAQ,CACN,KAAM,yBACN,QAAS,CAAE,SAAUG,CAAO,EAC5B,MAAOF,CACT,CACF"}
|
package/dist/rules/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["preferOption","preferEither","preferTry","preferList","noGetUnsafe","noLet","preferFold","preferMap","preferFlatmap","preferFunctypeMap","preferFunctypeSet","noImperativeLoops","preferDoNotation"],"sources":["../../src/rules/index.ts"],"sourcesContent":["import noGetUnsafe from \"./no-get-unsafe\"\nimport noImperativeLoops from \"./no-imperative-loops\"\nimport noLet from \"./no-let\"\nimport preferDoNotation from \"./prefer-do-notation\"\nimport preferEither from \"./prefer-either\"\nimport preferFlatmap from \"./prefer-flatmap\"\nimport preferFold from \"./prefer-fold\"\nimport preferFunctypeMap from \"./prefer-functype-map\"\nimport preferFunctypeSet from \"./prefer-functype-set\"\nimport preferList from \"./prefer-list\"\nimport preferMap from \"./prefer-map\"\nimport preferOption from \"./prefer-option\"\nimport preferTry from \"./prefer-try\"\n\nexport {\n noGetUnsafe,\n noImperativeLoops,\n noLet,\n preferDoNotation,\n preferEither,\n preferFlatmap,\n preferFold,\n preferFunctypeMap,\n preferFunctypeSet,\n preferList,\n preferMap,\n preferOption,\n preferTry,\n}\n\nexport default {\n \"prefer-option\": preferOption,\n \"prefer-either\": preferEither,\n \"prefer-try\": preferTry,\n \"prefer-list\": preferList,\n \"no-get-unsafe\": noGetUnsafe,\n \"no-let\": noLet,\n \"prefer-fold\": preferFold,\n \"prefer-map\": preferMap,\n \"prefer-flatmap\": preferFlatmap,\n \"prefer-functype-map\": preferFunctypeMap,\n \"prefer-functype-set\": preferFunctypeSet,\n \"no-imperative-loops\": noImperativeLoops,\n \"prefer-do-notation\": preferDoNotation,\n}\n"],"mappings":"icA8BA,
|
|
1
|
+
{"version":3,"file":"index.js","names":["preferOption","preferEither","preferTry","preferList","noGetUnsafe","noLet","preferFold","preferMap","preferFlatmap","preferFunctypeMap","preferFunctypeSet","noImperativeLoops","preferDoNotation","rule","rule$1","rule$2","rule$3","rule$4","rule$5","rule$6","rule$7","rule$8","rule$9","rule$10","rule$11","rule$12","rules_default"],"sources":["../../src/rules/index.ts"],"sourcesContent":["import noGetUnsafe from \"./no-get-unsafe\"\nimport noImperativeLoops from \"./no-imperative-loops\"\nimport noLet from \"./no-let\"\nimport preferDoNotation from \"./prefer-do-notation\"\nimport preferEither from \"./prefer-either\"\nimport preferFlatmap from \"./prefer-flatmap\"\nimport preferFold from \"./prefer-fold\"\nimport preferFunctypeMap from \"./prefer-functype-map\"\nimport preferFunctypeSet from \"./prefer-functype-set\"\nimport preferList from \"./prefer-list\"\nimport preferMap from \"./prefer-map\"\nimport preferOption from \"./prefer-option\"\nimport preferTry from \"./prefer-try\"\n\nexport {\n noGetUnsafe,\n noImperativeLoops,\n noLet,\n preferDoNotation,\n preferEither,\n preferFlatmap,\n preferFold,\n preferFunctypeMap,\n preferFunctypeSet,\n preferList,\n preferMap,\n preferOption,\n preferTry,\n}\n\nexport default {\n \"prefer-option\": preferOption,\n \"prefer-either\": preferEither,\n \"prefer-try\": preferTry,\n \"prefer-list\": preferList,\n \"no-get-unsafe\": noGetUnsafe,\n \"no-let\": noLet,\n \"prefer-fold\": preferFold,\n \"prefer-map\": preferMap,\n \"prefer-flatmap\": preferFlatmap,\n \"prefer-functype-map\": preferFunctypeMap,\n \"prefer-functype-set\": preferFunctypeSet,\n \"no-imperative-loops\": noImperativeLoops,\n \"prefer-do-notation\": preferDoNotation,\n}\n"],"mappings":"icA8BA,IAAA0B,EAAe,CACb,gBAAiB1B,EACjB,gBAAiBC,EACjB,aAAcC,EACd,cAAeC,EACf,gBAAiBC,EACjB,SAAUC,EACV,cAAeC,EACf,aAAcC,EACd,iBAAkBC,EAClB,sBAAuBC,EACvB,sBAAuBC,EACvB,sBAAuBC,EACvB,qBAAsBC,CACxB"}
|
|
@@ -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":["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${wasSu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EA,MAAO,CACL,eAAe,EAAe,CAG5B,GAFIL,GAAgBE,EAAa,GAE7BG,EAAK,OAAO,OAAS,mBAAoB,OAE7C,IAAMG,EAAWH,EAAK,OAAO,SAC7B,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,2 +1,2 @@
|
|
|
1
|
-
const
|
|
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};
|
|
2
2
|
//# sourceMappingURL=no-imperative-loops.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-imperative-loops.js","names":[],"sources":["../../src/rules/no-imperative-loops.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\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 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 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 (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 context.report({\n node,\n messageId: \"noForLoop\",\n })\n },\n\n ForInStatement(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\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 (allowInTests && isInTestFile()) return\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 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 (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 (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":"AAIA,MAAM,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,YAAa,4DACb,cAAe,gEACf,eAAgB,yCAChB,kBAAmB,mDACrB,CACF,EAEA,OAAO,EAAS,CACd,IAAM,EAAU,EAAQ,QAAQ,IAAM,CAAC,EACjC,EAAsB,EAAQ,qBAAuB,GACrD,EAAkB,EAAQ,iBAAmB,GAC7C,EAAe,EAAQ,eAAiB,GAE9C,SAAS,GAAe,CACtB,IAAM,EAAW,EAAQ,SACzB,MACE,kCAAkC,KAAK,CAAQ,GAC/C,EAAS,SAAS,WAAW,GAC7B,EAAS,SAAS,QAAQ,GAC1B,EAAS,SAAS,SAAS,CAE/B,CAEA,SAAS,EAAiB,EAAwB,CAChD,GAAI,CAAC,EAAK,MAAQ,EAAK,KAAK,OAAS,iBAAkB,MAAO,GAG9D,IAAM,EADa,EAAQ,WACC,QAAQ,EAAK,IAAI,EAG7C,MAAO,gBAAgB,KAAK,CAAQ,GAAK,EAAK,MAAQ,EAAK,KAAK,OAAS,qBAC3E,CAEA,SAAS,EAAsB,EAAwB,CAErD,MADI,CAAC,EAAK,MAAQ,EAAK,KAAK,OAAS,iBAAyB,GACvD,EAAK,KAAK,KAAK,SAAW,CACnC,CAEA,SAAS,EAAyB,EAAwB,CACxD,IAAM,EAAO,EAAK,KAClB,GAAI,CAAC,EAAM,MAAO,G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D,GAAI,EAAsB,CAAI,GAAK,CAAC,EAAyB,CAAI,GAAK,CAAC,EAA4B,CAAI,EAAG,CACxG,IAAM,EAAa,EAAQ,WACrB,EAAW,EAAK,KAAK,KAAK,GAEhC,GAAI,GAAY,EAAS,OAAS,sBAAuB,CACvD,IAAM,EAAW,EAAW,QAAQ,CAAQ,EACtC,EAAe,EAAW,QAAQ,EAAK,KAAK,EAE5C,EAAU,EAAK,KACf,EACJ,EAAQ,OAAS,uBAAyB,EAAQ,aAAa,GAC3D,EAAW,QAAQ,EAAQ,aAAa,EAAE,CAAC,EAAE,EAC7C,EAAW,QAAQ,CAAO,EAE3B,EAAS,SAAS,QAAQ,GAC7B,EAAQ,KAAK,CACX,UAAW,iBACX,KAAM,CAAE,SAAU,CAAa,EAC/B,IAAI,EAAO,CACT,OAAO,EAAM,YAAY,EAAM,GAAG,EAAa,YAAY,EAAQ,YAAY,EAAS,KAAK,CAC/F,CACF,CAAC,CAEL,CACF,CAEA,EAAQ,OAAO,CACb,OACA,UAAW,cACX,QAAS,EAAQ,OAAS,EAAI,EAAU,IAAA,EAC1C,CAAC,CACH,EAEA,eAAe,EAAe,CACxB,GACA,GAAgB,EAAa,GAEjC,EAAQ,OAAO,CACb,OACA,UAAW,aACb,CAAC,CACH,EAEA,iBAAiB,EAAe,CAC1B,GACA,GAAgB,EAAa,GAEjC,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. 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,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,iLACF,YAAa,4DACb,cAAe,gEACf,eAAgB,yCAChB,kBAAmB,mDACrB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EACjCC,EAAsBF,EAAQ,qBAAuB,GACrDG,EAAkBH,EAAQ,iBAAmB,GAC7CI,EAAeJ,EAAQ,eAAiB,GAE9C,SAASK,GAAe,CACtB,IAAMC,EAAWL,EAAQ,SACzB,MACE,kCAAkC,KAAKK,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,SAASC,EAAiB,EAAwB,CAChD,GAAI,CAACC,EAAK,MAAQA,EAAK,KAAK,OAAS,iBAAkB,MAAO,GAG9D,IAAMC,EADaR,EAAQ,WACC,QAAQO,EAAK,IAAI,EAG7C,MAAO,gBAAgB,KAAKC,CAAQ,GAAKD,EAAK,MAAQA,EAAK,KAAK,OAAS,qBAC3E,CAEA,SAASE,EAAsB,EAAwB,CAErD,MADI,CAACF,EAAK,MAAQA,EAAK,KAAK,OAAS,iBAAyB,GACvDA,EAAK,KAAK,KAAK,SAAW,C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YhB,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"}
|
package/dist/rules/no-let.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"no-let.js","names":[],"sources":["../../src/rules/no-let.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n fixable: \"code\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer const over let — use immutable bindings\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noLet: \"Prefer const over let — use immutable bindings\",\n suggestConst: \"Replace let with const\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\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 return {\n VariableDeclaration(node: ASTNode) {\n if (node.kind !== \"let\") return\n if (allowInTests && isInTestFile()) return\n\n const declaredVars = context.sourceCode.getDeclaredVariables(node)\n const hasReassignment = declaredVars.some((variable: ASTNode) =>\n variable.references.some((ref: ASTNode) => ref.isWrite() && ref.identifier !== variable.defs[0]?.name),\n )\n\n if (!hasReassignment) {\n // Safe to autofix — no reassignment detected\n context.report({\n node,\n messageId: \"noLet\",\n fix(fixer: Rule.RuleFixer) {\n const sourceCode = context.sourceCode\n const firstToken = sourceCode.getFirstToken(node)\n if (firstToken && firstToken.value === \"let\") {\n return fixer.replaceText(firstToken, \"const\")\n }\n return null\n },\n })\n } else {\n // Reassignment found — warn only, with suggestion\n context.report({\n node,\n messageId: \"noLet\",\n suggest: [\n {\n messageId: \"suggestConst\",\n fix(fixer: Rule.RuleFixer) {\n const sourceCode = context.sourceCode\n const firstToken = sourceCode.getFirstToken(node)\n if (firstToken && firstToken.value === \"let\") {\n return fixer.replaceText(firstToken, \"const\")\n }\n return null\n },\n },\n ],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAIA,
|
|
1
|
+
{"version":3,"file":"no-let.js","names":["rule","allowInTests","context","isInTestFile","filename","node","variable","ref","firstToken","fixer"],"sources":["../../src/rules/no-let.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n fixable: \"code\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer const over let — use immutable bindings\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n noLet: \"Prefer const over let — use immutable bindings\",\n suggestConst: \"Replace let with const\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\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 return {\n VariableDeclaration(node: ASTNode) {\n if (node.kind !== \"let\") return\n if (allowInTests && isInTestFile()) return\n\n const declaredVars = context.sourceCode.getDeclaredVariables(node)\n const hasReassignment = declaredVars.some((variable: ASTNode) =>\n variable.references.some((ref: ASTNode) => ref.isWrite() && ref.identifier !== variable.defs[0]?.name),\n )\n\n if (!hasReassignment) {\n // Safe to autofix — no reassignment detected\n context.report({\n node,\n messageId: \"noLet\",\n fix(fixer: Rule.RuleFixer) {\n const sourceCode = context.sourceCode\n const firstToken = sourceCode.getFirstToken(node)\n if (firstToken && firstToken.value === \"let\") {\n return fixer.replaceText(firstToken, \"const\")\n }\n return null\n },\n })\n } else {\n // Reassignment found — warn only, with suggestion\n context.report({\n node,\n messageId: \"noLet\",\n suggest: [\n {\n messageId: \"suggestConst\",\n fix(fixer: Rule.RuleFixer) {\n const sourceCode = context.sourceCode\n const firstToken = sourceCode.getFirstToken(node)\n if (firstToken && firstToken.value === \"let\") {\n return fixer.replaceText(firstToken, \"const\")\n }\n return null\n },\n },\n ],\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"AAIA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,QAAS,OACT,eAAgB,GAChB,KAAM,CACJ,YAAa,iDACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,MAAO,iDACP,aAAc,wBAChB,CACF,EAEA,OAAO,EAAS,CAEd,IAAMC,GADUC,EAAQ,QAAQ,IAAM,CAAC,EAAA,CACV,eAAiB,GAE9C,SAASC,GAAe,CACtB,IAAMC,EAAWF,EAAQ,SACzB,MACE,kCAAkC,KAAKE,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,MAAO,CACL,oBAAoB,EAAe,CAC7BC,EAAK,OAAS,QACdJ,GAAgBE,EAAa,IAEZD,EAAQ,WAAW,qBAAqBG,CAC1B,CAAC,CAAC,KAAM,GACzCC,EAAS,WAAW,KAAM,GAAiBC,EAAI,QAAQ,GAAKA,EAAI,aAAeD,EAAS,KAAK,EAAE,EAAE,IAAI,CAGpF,EAgBjBJ,EAAQ,OAAO,CACb,OACA,UAAW,QACX,QAAS,CACP,CACE,UAAW,eACX,IAAI,EAAuB,CAEzB,IAAMM,EADaN,EAAQ,WACG,cAAcG,CAAI,EAIhD,OAHIG,GAAcA,EAAW,QAAU,MAC9BC,EAAM,YAAYD,EAAY,OAAO,EAEvC,IACT,CACF,CACF,CACF,CAAC,EA9BDN,EAAQ,OAAO,CACb,OACA,UAAW,QACX,IAAI,EAAuB,CAEzB,IAAMM,EADaN,EAAQ,WACG,cAAcG,CAAI,EAIhD,OAHIG,GAAcA,EAAW,QAAU,MAC9BC,EAAM,YAAYD,EAAY,OAAO,EAEvC,IACT,CACF,CAAC,GAqBL,CACF,CACF,CACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{getFunctypeImports as e,isChainedMethodCall as t}from"../utils/functype-detection.js";const n
|
|
1
|
+
import{getFunctypeImports as e,isChainedMethodCall as t}from"../utils/functype-detection.js";const n=/* @__PURE__ */ new Set([`Option`,`Either`,`Try`,`Task`]),r=/* @__PURE__ */ new Set([`parent`,`loc`,`range`]),i=(e,t)=>/* @__PURE__ */ new Set([...e,...t]);function a(e){if(e.type!==`CallExpression`)return/* @__PURE__ */ new Set;let t=e.callee;return t?.type===`Identifier`&&n.has(t.name)?/* @__PURE__ */ new Set([t.name]):t?.type===`MemberExpression`&&t.object?.type===`Identifier`&&n.has(t.object.name)?/* @__PURE__ */ new Set([t.object.name]):/* @__PURE__ */ new Set}function o(e){return Object.entries(e).filter(([e])=>!r.has(e)).flatMap(([,e])=>Array.isArray(e)?e:[e]).filter(e=>typeof e==`object`&&!!e)}function s(e){if(!e||typeof e!=`object`)return/* @__PURE__ */ new Set;let t=e;return o(t).reduce((e,t)=>i(e,s(t)),a(t))}const c=/* @__PURE__ */ new Set([`flatMap`,`map`,`filter`,`fold`]),l=/* @__PURE__ */ new Set([`flatMap`,`map`,`filter`]);function u(e){if(e.callee.type!==`MemberExpression`||e.callee.object.type!==`CallExpression`)return 1;let t=e.callee.property,n=e.callee.object;return(t.type===`Identifier`&&c.has(t.name)?1:0)+u(n)}function d(e){if(e.callee?.type!==`MemberExpression`||e.callee.object?.type!==`CallExpression`)return 0;let t=e.callee.property,n=e.callee.object;return(t.type===`Identifier`&&l.has(t.name)?1:0)+d(n)}function f(e){if(e.callee?.type!==`MemberExpression`)return!1;let t=e.callee.property;return t.type!==`Identifier`||!l.has(t.name)?!1:d(e)>=1}function p(e){if(e.type!==`LogicalExpression`||e.operator!==`&&`)return 0;let t=e.right;return+(t.type===`MemberExpression`||t.type===`LogicalExpression`&&t.operator===`&&`)+p(e.left)}const m={meta:{type:`suggestion`,docs:{description:`Prefer Do notation for complex monadic compositions and nested operations`,recommended:!0},fixable:`code`,messages:{preferDoForNestedChecks:`Prefer Do notation for nested null/undefined checks instead of logical AND chains`,preferDoForChainedMethods:`Prefer Do notation for complex flatMap chains ({{count}} levels deep)`,preferDoForMixedMonads:`Consider Do notation when mixing Option, Either, and Try operations`,preferDoAsyncForChainedTasks:`Prefer DoAsync notation for chained async operations`},schema:[{type:`object`,properties:{minChainDepth:{type:`integer`,minimum:2,default:3},detectMixedMonads:{type:`boolean`,default:!0}},additionalProperties:!1}]},create(n){let r=n.options[0]||{},i=r.minChainDepth||3,a=r.detectMixedMonads!==!1,o=e(n),c=o.functions.has(`Do`)||o.functions.has(`DoAsync`);function l(e){e.operator===`&&`&&p(e)>=2&&d(e)&&n.report({node:e,messageId:`preferDoForNestedChecks`,fix:c?t=>h(t,e):void 0})}function d(e){let t=n.sourceCode.getText(e).match(/\w+(\.\w+){2,}/g);return t!==null&&t.length>0}function m(e){if(!t(e,`flatMap`))return;let r=u(e);r>=i&&n.report({node:e,messageId:`preferDoForChainedMethods`,data:{count:r.toString()},fix:c?t=>g(t,e):void 0})}function h(e,t){let r=n.sourceCode.getText(t),i=r.match(/(\w+)(\.\w+)+/);if(i){let n=i[1],r=`Do(function* () {
|
|
2
2
|
const obj = yield* $(Option(${n}))
|
|
3
3
|
return yield* $(Option(obj${i[0].substring(n.length)}))
|
|
4
4
|
})`;return e.replaceText(t,r)}return e.replaceText(t,`/* TODO: Convert to Do notation */ ${r}`)}function g(e,t){let r=n.sourceCode.getText(t);return e.replaceText(t,`/* TODO: Consider Do notation for complex chains */ ${r}`)}function _(e){a&&f(e)&&s(e).size>=2&&n.report({node:e,messageId:`preferDoForMixedMonads`})}return{LogicalExpression(e){l(e)},CallExpression(e){m(e),_(e)}}}};export{m as default};
|