eslint-plugin-functype 2.122.0 → 2.123.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 +111 -4
- package/dist/configs/agent.d.ts +5 -4
- package/dist/configs/agent.js +1 -1
- package/dist/configs/agent.js.map +1 -1
- package/dist/configs/recommended.d.ts +10 -0
- package/dist/configs/recommended.js +1 -1
- package/dist/configs/recommended.js.map +1 -1
- package/dist/configs/strict.d.ts +2 -0
- package/dist/configs/strict.js +1 -1
- package/dist/configs/strict.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/rules/index.d.ts +19 -15
- package/dist/rules/index.js +1 -1
- package/dist/rules/index.js.map +1 -1
- package/dist/rules/no-floating-result.d.ts +19 -0
- package/dist/rules/no-floating-result.js +2 -0
- package/dist/rules/no-floating-result.js.map +1 -0
- package/dist/rules/no-serialize-container.d.ts +16 -0
- package/dist/rules/no-serialize-container.js +2 -0
- package/dist/rules/no-serialize-container.js.map +1 -0
- package/dist/rules/prefer-do-notation.js +1 -4
- 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-option.js +1 -1
- package/dist/rules/prefer-option.js.map +1 -1
- package/dist/utils/host-throws.d.ts +33 -0
- package/dist/utils/host-throws.js +2 -0
- package/dist/utils/host-throws.js.map +1 -0
- package/dist/utils/type-aware.d.ts +24 -0
- package/dist/utils/type-aware.js +1 -1
- package/dist/utils/type-aware.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -61,6 +61,8 @@ export default [functype.configs.agent]
|
|
|
61
61
|
| `functype/prefer-list` | off | warn | off | Use `List` instead of native arrays |
|
|
62
62
|
| `functype/no-array-mutation` | off | error | error | Don't change an array in place (`push`, `sort`, `xs[i] = v`…); build a new one |
|
|
63
63
|
| `functype/no-floating-io` | off | warn | error | Don't build an `IO` and drop it, or `await` it unrun; run, return or `yield*` it |
|
|
64
|
+
| `functype/no-floating-result` | off | error | error | Don't drop an `Either`/`Try` result; a failure in it is silently ignored |
|
|
65
|
+
| `functype/no-serialize-container` | off | error | error | Don't send an `Either`/`Option`/`List` to `c.json()` or `JSON.stringify()`; unwrap it first |
|
|
64
66
|
| `functype/no-getOrThrow-in-render` | off | warn | error | React: no bare `.orThrow()` in a component or hook body; a throw in render unmounts the tree |
|
|
65
67
|
| `functype/must-fold-on-component-return` | off | warn | error | React: render an `Option`/`Either`/`Try` with `fold` or `<MatchOption>`, not a guard or `&&` |
|
|
66
68
|
|
|
@@ -78,6 +80,7 @@ A rule is **`error` in `recommended` once it is right on ~95–99% of real code*
|
|
|
78
80
|
| --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
|
|
79
81
|
| A bug check: the condition can only fail because of a programmer error | `invariant(cond, msg)` from `functype` |
|
|
80
82
|
| A host contract: the caller (React `use()`, React Query, a step runner, an MCP tool) needs a throw or rejection | `@interop <reason>` on the declaration, or `orThrow(builder)` |
|
|
83
|
+
| A router's control flow: `throw redirect(…)` or `throw notFound()` in a loader or route guard | nothing: recognized by its import (below) |
|
|
81
84
|
| Anything that can fail in normal operation | return an `Either` |
|
|
82
85
|
|
|
83
86
|
```ts
|
|
@@ -106,6 +109,27 @@ const value = either.orThrow((left) => new StepError(left.message))
|
|
|
106
109
|
- **Only JSDoc (`/** … */`) counts.** A `//` comment mentioning the tag does not.
|
|
107
110
|
- **Opt out** per rule with `allowInteropMarker: false`.
|
|
108
111
|
|
|
112
|
+
### Router control-flow throws
|
|
113
|
+
|
|
114
|
+
TanStack Router redirects or shows Not found only when `beforeLoad` or `loader` throws the value `redirect()` or `notFound()` returns, and React Router and Remix loaders work the same way. That throw is the router's API, so `prefer-either` leaves it alone when the helper is imported from one of these modules, under any local name or through a namespace import:
|
|
115
|
+
|
|
116
|
+
| Module | Helpers |
|
|
117
|
+
| ------------------------------------------------------------------------------- | --------------------------------------------------------- |
|
|
118
|
+
| `@tanstack/react-router`, `@tanstack/router-core` | `redirect`, `notFound` |
|
|
119
|
+
| `react-router` | `redirect`, `redirectDocument`, `replace`, `data` |
|
|
120
|
+
| `react-router-dom` (React Router 6), `@remix-run/node`, `@remix-run/cloudflare` | `redirect`, `redirectDocument`, `replace`, `data`, `json` |
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
import { redirect } from "@tanstack/react-router"
|
|
124
|
+
|
|
125
|
+
beforeLoad: ({ params }) => {
|
|
126
|
+
if (params.id === "all") throw redirect({ to: "/queue" }) // fine: the router's redirect
|
|
127
|
+
if (!isValid(params.id)) throw new Error("bad id") // still reported
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Unlike `@interop`, this exempts only the router's own throws, so a real error thrown in the same function is still reported. A local `redirect` helper isn't the router's, and neither is `throw new Response(…)`. Add your own framework with the `hostThrows` option: `{ hostThrows: { "@acme/router": ["bounce"] } }`. It adds to the defaults: naming a default module adds helpers to its list rather than replacing it, and a module set to `[]` turns that module's defaults off.
|
|
132
|
+
|
|
109
133
|
Prefer either tool to `eslint-disable`. A disable covers a whole file or line and says only "be quiet". `rg 'invariant\('` lists every bug check, and `rg '@interop'` lists every place the code touches a throw-based host.
|
|
110
134
|
|
|
111
135
|
## Rule options
|
|
@@ -214,6 +238,51 @@ void save(user) // fine: a deliberate drop
|
|
|
214
238
|
|
|
215
239
|
Measured (2026-10-16) on functype's own source and tests, functype-log, functype-react, agent-todo's agent-gate-api and civala.ai's API: 0 false positives across about 1,340 IO-typed calls. The only hits were four deliberate drops in type-only tests. It's `off` in `recommended` and `warn` in `strict` while it is measured further.
|
|
216
240
|
|
|
241
|
+
### `functype/no-floating-result`
|
|
242
|
+
|
|
243
|
+
Reports a statement that computes a result that can carry a failure, such as an `Either` or `Try`, and drops it. A `Left` or `Failure` in it is silently ignored. `no-floating-promises` doesn't help: awaiting the promise satisfies it while the result inside is thrown away.
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
await userService.updateSubscription(id, plan) // reported: a failed write goes unnoticed
|
|
247
|
+
parse(input) // reported, when parse returns an Either
|
|
248
|
+
await save(user).run() // reported: run() returns an Either → check it, or use runOrThrow()
|
|
249
|
+
|
|
250
|
+
const result = await userService.updateSubscription(id, plan) // fine: then check result.isLeft()
|
|
251
|
+
await audit.write(entry).tapLeft((e) => log.error(e)) // fine: a best-effort write that logs its failure
|
|
252
|
+
void (await cache.refresh()) // fine: a deliberate drop
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
- **What counts:** a type, or a member of its union, with `fold` and `isLeft` or `isFailure`. That covers `Either`, `Try`, `Exit`, `Validation`, `Task`'s result (`TaskOutcome`) and Either-shaped wrappers such as a `ServiceResult`. An ignored `Option` or `List` loses no error, so it isn't reported. An `IO` that is never run is `no-floating-io`'s.
|
|
256
|
+
- **Handled chains:** a chain that passes through `.tapError(…)` or `.tapLeft(…)` isn't reported, because it handles its failure. A `.flatMap(…)` after the handler can bring in a new failure, so that chain is reported again. `Try` has no failure tap, so mark a deliberate `Try` drop with `void`.
|
|
257
|
+
- **Tests:** a test that calls something for its side effect and then checks mocks is reported too. Assert on the result, or turn the rule off for test files.
|
|
258
|
+
- **Not seen yet:** a drop inside a callback, such as `xs.forEach((x) => save(x))`, or in the first part of a comma expression, isn't its own statement, so it isn't reported. `ok && save(x)` and `ok ? a() : b()` are.
|
|
259
|
+
|
|
260
|
+
**It only runs with type-aware linting** (`parserOptions.projectService`). Without type information it reports nothing.
|
|
261
|
+
|
|
262
|
+
Measured (2026-10-30) on agent-todo's agent-gate-api, which kept a hand-written check for this: at the commit that added that check, the rule reports 20 drops in production code. agent-todo fixed every one of them as a real bug, among them 8 in the Stripe webhook handler, where a failed write still answered Stripe 200. On the current code, after those fixes, it reports none in production code and 12 in tests. functype-os, functype-log, functype-react, functype-eval and functype-mcp-server report none. It's `error` in `strict` and `agent`, and `off` in `recommended`, where it moves to `error` in 2.0.
|
|
263
|
+
|
|
264
|
+
### `functype/no-serialize-container`
|
|
265
|
+
|
|
266
|
+
Reports a functype container handed to a JSON sink, anywhere inside the value. An `Either`, `Option` or `List` serializes as its `{"@functype", _tag, value}` envelope, so a client reading `subscription.plan` gets `undefined`, and a body built around a `Left` answers 200. The compiler can't catch it, because `c.json()` and `JSON.stringify()` accept any value.
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
return c.json(await svc.getDetails(id)) // reported: sends the Either's envelope
|
|
270
|
+
return c.json({ user, subscription: details }) // reported, at subscription
|
|
271
|
+
return JSON.stringify({ success: true, checkout }) // reported, at checkout: an MCP tool reporting success on failure
|
|
272
|
+
|
|
273
|
+
return c.json(result.orThrow()) // fine, after checking result.isLeft()
|
|
274
|
+
return c.json({ items: list.toArray() }) // fine
|
|
275
|
+
return c.json(result.toJSON()) // fine: the envelope on purpose
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
- **Sinks:** `JSON.stringify(x)`, and any `.json(x)` call with an argument: Hono's `c.json`, `Response.json`, Express's `res.json`. `new Response(JSON.stringify(x))` is covered by the first. A read such as `await res.json()` has no argument, so it never matches.
|
|
279
|
+
- **What counts:** a type with `_tag` and `fold`, which every functype container has and its `toJSON()` envelope doesn't. The rule looks through unions and intersections, array and tuple elements, object properties, `Record` values and utility types such as `Partial<T>` and `Omit<T, K>`, up to 4 levels deep, and names the path in the message.
|
|
280
|
+
- **The envelope on purpose:** call `.toJSON()` or `.serialize()` first. A test that checks a container's JSON output is reported too, so call `.toJSON()` there as well.
|
|
281
|
+
|
|
282
|
+
**It only runs with type-aware linting** (`parserOptions.projectService`). Without type information it reports nothing.
|
|
283
|
+
|
|
284
|
+
Measured (2026-10-31) on agent-todo's agent-gate-api, which kept a hand-written check for this. Before its fix commit (f002b90), the rule reports 4 calls, and each is a bug agent-todo fixed: `GET /billing`, which showed every paying user "billing account isn't properly linked" for about nine months; `PATCH /user/me` and `PATCH /user/preferences`, which answered 200 with a `Left` in the body; and an MCP tool that reported success on failure. On the current code it reports none, and none in agent-todo's UI or in functype's own packages. It's `error` in `strict` and `agent`, and `off` in `recommended`, where it moves to `error` in 2.0.
|
|
285
|
+
|
|
217
286
|
### React rules
|
|
218
287
|
|
|
219
288
|
Two rules are for React code. They fire only inside a **component** (a function named in PascalCase whose body has JSX, including one wrapped in `memo` or `forwardRef`) or a **hook** (a function named `use` + a capital letter), so other code rarely trips them. The one exception is a non-React function whose name starts with `use` + a capital letter, which is read as a hook. Both are `off` in `recommended` and `warn` in `strict` while they're measured on real React code. To turn them on with `recommended`:
|
|
@@ -348,11 +417,49 @@ When the code after the guard awaits, the advice uses `flatMapAsync` / `foldAsyn
|
|
|
348
417
|
|
|
349
418
|
### `functype/prefer-option`
|
|
350
419
|
|
|
351
|
-
| Option
|
|
352
|
-
|
|
|
353
|
-
| `allowUseState`
|
|
420
|
+
| Option | Default | Description |
|
|
421
|
+
| ---------------------- | ------- | -------------------------------------------------------------------------------------------------------- |
|
|
422
|
+
| `allowUseState` | `true` | Don't report `T \| null` inside the type argument of `useState` / `useRef` (bare or `React.`-qualified). |
|
|
423
|
+
| `checkOptionalMembers` | `false` | Report "may be absent" members and parameters too: `a?: T` and `a: T \| undefined` alike. |
|
|
424
|
+
|
|
425
|
+
`null` is idiomatic React state, and an `Option` there fights the hook's own API.
|
|
426
|
+
|
|
427
|
+
On a type-literal or interface member, and on a parameter, `a?: T` and `a: T | undefined` both mean "may be absent", so both are skipped by default. The caller writes `<X b="v" />` or `f()`, and an `Option` there would make every caller wrap the value. Skipping only one spelling would teach people to rewrite `b: string | undefined` as `b?: string`, which makes a required key optional.
|
|
428
|
+
|
|
429
|
+
```ts
|
|
430
|
+
type Props = {
|
|
431
|
+
a?: string // fine
|
|
432
|
+
b: string | undefined // fine: the same "may be absent" as a?
|
|
433
|
+
c?: string | undefined // fine: the spelling exactOptionalPropertyTypes needs
|
|
434
|
+
d: string | null // reported: null is a deliberate value
|
|
435
|
+
}
|
|
436
|
+
const f = (x: string | undefined) => x ?? "" // fine
|
|
437
|
+
function g(): string | undefined {} // reported: a return type, where an Option pays
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
Return types, variables, class fields and generic arguments (`Array<string | undefined>`) are still reported. With `checkOptionalMembers: true`, `a?: T` is reported too, so the two spellings still get the same verdict, and `c?: T | undefined` is reported once, as an optional member.
|
|
441
|
+
|
|
442
|
+
### `functype/prefer-do-notation`
|
|
443
|
+
|
|
444
|
+
| Option | Default | Description |
|
|
445
|
+
| ------------------- | ------- | ----------------------------------------------------------------------------------------- |
|
|
446
|
+
| `minChainDepth` | `3` | Report a `.flatMap(…)` chain once it has this many `flatMap`/`map`/`filter`/`fold` steps. |
|
|
447
|
+
| `detectMixedMonads` | `true` | Report a composition chain that moves between Option, Either, Try and Task. |
|
|
448
|
+
|
|
449
|
+
It reports three shapes, each once, at the outermost step:
|
|
450
|
+
|
|
451
|
+
```ts
|
|
452
|
+
o.flatMap(f).flatMap(g).flatMap(h) // a flatMap chain 3 steps deep → Do notation
|
|
453
|
+
Option(x)
|
|
454
|
+
.flatMap((v) => Either.right(v))
|
|
455
|
+
.map(f) // a chain that mixes monads → Do notation
|
|
456
|
+
user && user.profile && user.profile.name // a guard on each step of a path → user?.profile?.name
|
|
457
|
+
```
|
|
354
458
|
|
|
355
|
-
|
|
459
|
+
- **Only chains on a monad count.** With type information the type of the value each step is called on decides, so an array's `.flatMap(…)` chain is never reported, and neither is one after `.getOrElse([])` or `.fold(…)` has unwrapped the monad. Without it, the chain must start from a monad constructor, companion or conversion (`Option(x)`, `Either.right(x)`, `Try(f).toOption()`), an identifier annotated with a monad type, or one named like a monad (`option`, `result`, or a capitalized suffix such as `userOption`; `entry` and `registry` don't count).
|
|
460
|
+
- **Mixing is read along the chain**, from the monad each step's callback returns. A conversion such as `.toOption()` keeps the chain in one monad, and a monad built somewhere inside a callback isn't a step.
|
|
461
|
+
- **A guard chain is read from the AST.** Each operand must be a property of the one before it, so `isAdmin && settings.theme && user.profile.name` isn't one.
|
|
462
|
+
- **It has no autofix.** It reports only, so `eslint --fix` can't change code on its behalf.
|
|
356
463
|
|
|
357
464
|
### `functype/prefer-map`
|
|
358
465
|
|
package/dist/configs/agent.d.ts
CHANGED
|
@@ -13,16 +13,16 @@
|
|
|
13
13
|
* `off`: prefer-flatmap and prefer-do-notation, whose precision is unmeasured. At `error` they would
|
|
14
14
|
* teach an agent to write `eslint-disable`; each moves to `error` here once it is measured. Also
|
|
15
15
|
* prefer-list: with type-aware linting, its in-place-change case is no-array-mutation's, which is `error`
|
|
16
|
-
* here, and the rest
|
|
17
|
-
* asks for `ReadonlyArray<T>` types, a typing choice `strict` keeps at `warn`.
|
|
16
|
+
* here, and the rest asks for `ReadonlyArray<T>` types, a typing choice `strict` keeps at `warn`.
|
|
18
17
|
*
|
|
19
|
-
* no-array-mutation
|
|
20
|
-
* report nothing.
|
|
18
|
+
* no-array-mutation, no-floating-io, no-floating-result and no-serialize-container are type-aware:
|
|
19
|
+
* without `parserOptions.projectService` they report nothing.
|
|
21
20
|
*/
|
|
22
21
|
declare const agentRules: {
|
|
23
22
|
"functype/no-floating-io": string;
|
|
24
23
|
"functype/no-getOrThrow-in-render": string;
|
|
25
24
|
"functype/must-fold-on-component-return": string;
|
|
25
|
+
"functype/no-serialize-container": string;
|
|
26
26
|
"functype/prefer-flatmap": string;
|
|
27
27
|
"functype/prefer-do-notation": string;
|
|
28
28
|
"functype/prefer-list": string;
|
|
@@ -31,6 +31,7 @@ declare const agentRules: {
|
|
|
31
31
|
"functype/prefer-try": string;
|
|
32
32
|
"functype/no-get-unsafe": string;
|
|
33
33
|
"functype/no-array-mutation": string;
|
|
34
|
+
"functype/no-floating-result": string;
|
|
34
35
|
"functype/prefer-functype-map": string;
|
|
35
36
|
"functype/prefer-functype-set": string;
|
|
36
37
|
"functype/no-imperative-loops": string;
|
package/dist/configs/agent.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"./strict.js";const t={...e,"functype/no-floating-io":`error`,"functype/no-getOrThrow-in-render":`error`,"functype/must-fold-on-component-return":`error`,"functype/prefer-flatmap":`off`,"functype/prefer-do-notation":`off`,"functype/prefer-list":`off`};export{t as default};
|
|
1
|
+
import e from"./strict.js";const t={...e,"functype/no-floating-io":`error`,"functype/no-getOrThrow-in-render":`error`,"functype/must-fold-on-component-return":`error`,"functype/no-serialize-container":`error`,"functype/prefer-flatmap":`off`,"functype/prefer-do-notation":`off`,"functype/prefer-list":`off`};export{t as default};
|
|
2
2
|
//# sourceMappingURL=agent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","names":["strictRules","agentRules"],"sources":["../../src/configs/agent.ts"],"sourcesContent":["import strictRules from \"./strict\"\n\n/**\n * The preset for code a coding agent writes. An agent acts on what fails its build and passes over a\n * warning, so this preset has none: every rule is `error` or `off`.\n *\n * `error`: everything `strict` errors on, plus three rules `strict` still warns on while they are\n * measured. no-floating-io has had 0 false positives across ~1,340 IO-typed calls, and the two React\n * rules none across 1,403 files. A forgotten `.run()` or a throw in render is the kind of mistake an\n * agent makes and a human reviewer misses. prefer-option, prefer-either and prefer-try are `error` here\n * as in `strict`: at a real boundary an agent marks it (`@interop <reason>` or `invariant()` for a\n * throw, `Wire<T>` for a data shape) instead of leaving the reader to guess.\n *\n * `off`: prefer-flatmap and prefer-do-notation, whose precision is unmeasured. At `error` they would\n * teach an agent to write `eslint-disable`; each moves to `error` here once it is measured. Also\n * prefer-list: with type-aware linting, its in-place-change case is no-array-mutation's, which is `error`\n * here, and the rest
|
|
1
|
+
{"version":3,"file":"agent.js","names":["strictRules","agentRules"],"sources":["../../src/configs/agent.ts"],"sourcesContent":["import strictRules from \"./strict\"\n\n/**\n * The preset for code a coding agent writes. An agent acts on what fails its build and passes over a\n * warning, so this preset has none: every rule is `error` or `off`.\n *\n * `error`: everything `strict` errors on, plus three rules `strict` still warns on while they are\n * measured. no-floating-io has had 0 false positives across ~1,340 IO-typed calls, and the two React\n * rules none across 1,403 files. A forgotten `.run()` or a throw in render is the kind of mistake an\n * agent makes and a human reviewer misses. prefer-option, prefer-either and prefer-try are `error` here\n * as in `strict`: at a real boundary an agent marks it (`@interop <reason>` or `invariant()` for a\n * throw, `Wire<T>` for a data shape) instead of leaving the reader to guess.\n *\n * `off`: prefer-flatmap and prefer-do-notation, whose precision is unmeasured. At `error` they would\n * teach an agent to write `eslint-disable`; each moves to `error` here once it is measured. Also\n * prefer-list: with type-aware linting, its in-place-change case is no-array-mutation's, which is `error`\n * here, and the rest asks for `ReadonlyArray<T>` types, a typing choice `strict` keeps at `warn`.\n *\n * no-array-mutation, no-floating-io, no-floating-result and no-serialize-container are type-aware:\n * without `parserOptions.projectService` they report nothing.\n */\nconst agentRules = {\n ...strictRules,\n \"functype/no-floating-io\": \"error\",\n \"functype/no-getOrThrow-in-render\": \"error\",\n \"functype/must-fold-on-component-return\": \"error\",\n \"functype/no-serialize-container\": \"error\",\n \"functype/prefer-flatmap\": \"off\",\n \"functype/prefer-do-notation\": \"off\",\n \"functype/prefer-list\": \"off\",\n}\n\nexport default agentRules\n"],"mappings":"2BAqBA,MAAMC,EAAa,CACjB,GAAGD,EACH,0BAA2B,QAC3B,mCAAoC,QACpC,yCAA0C,QAC1C,kCAAmC,QACnC,0BAA2B,MAC3B,8BAA+B,MAC/B,uBAAwB,KAC1B"}
|
|
@@ -27,6 +27,14 @@
|
|
|
27
27
|
* ~1,340 IO-typed calls in five codebases, but no real hits yet either. 2.0 decides `recommended` after
|
|
28
28
|
* measuring it against functype-os, whose async methods return IO there. Type-aware, like no-array-mutation.
|
|
29
29
|
*
|
|
30
|
+
* no-floating-result (1.23) is off here and `error` in strict: a dropped Either or Try is a defect, not a
|
|
31
|
+
* style, and on agent-todo's API it found the 20 drops that project fixed by hand as real bugs. Turning a
|
|
32
|
+
* new error on here would fail consumers' builds on a 1.x minor, so it moves to `error` here in 2.0. Type-aware.
|
|
33
|
+
*
|
|
34
|
+
* no-serialize-container (1.23) is off here and `error` in strict, for the same reason: a container sent
|
|
35
|
+
* to `c.json()` or `JSON.stringify()` is a defect, and turning a new error on here would fail consumers'
|
|
36
|
+
* builds on a 1.x minor. It moves to `error` here in 2.0. Type-aware.
|
|
37
|
+
*
|
|
30
38
|
* no-getOrThrow-in-render and must-fold-on-component-return are React rules: they fire only inside a
|
|
31
39
|
* component (a PascalCase function with JSX) or a hook (`use*`), so non-React code rarely trips them (a
|
|
32
40
|
* non-React function named `use*` is read as a hook). Both are new and unmeasured on real React code, so
|
|
@@ -50,6 +58,8 @@ declare const recommendedRules: {
|
|
|
50
58
|
"functype/prefer-list": string;
|
|
51
59
|
"functype/no-array-mutation": string;
|
|
52
60
|
"functype/no-floating-io": string;
|
|
61
|
+
"functype/no-floating-result": string;
|
|
62
|
+
"functype/no-serialize-container": string;
|
|
53
63
|
"functype/no-getOrThrow-in-render": string;
|
|
54
64
|
"functype/must-fold-on-component-return": string;
|
|
55
65
|
};
|
|
@@ -1,2 +1,2 @@
|
|
|
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/collection-naming":`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`,"functype/no-array-mutation":`off`,"functype/no-floating-io":`off`,"functype/no-getOrThrow-in-render":`off`,"functype/must-fold-on-component-return":`off`};export{e as default};
|
|
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/collection-naming":`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`,"functype/no-array-mutation":`off`,"functype/no-floating-io":`off`,"functype/no-floating-result":`off`,"functype/no-serialize-container":`off`,"functype/no-getOrThrow-in-render":`off`,"functype/must-fold-on-component-return":`off`};export{e as default};
|
|
2
2
|
//# sourceMappingURL=recommended.js.map
|
|
@@ -1 +1 @@
|
|
|
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 throws that are correct (bug checks, host contracts). Wire<T> (#325 B),\n * invariant() and @interop (#342) close those; graduating them is a measured decision.\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 *\n * collection-naming is a convention, not a heuristic — functype's Map/Set imported under their own names,\n * the built-in spelled globalThis.Map — so it has no false-positive class and starts at error.\n *\n * no-array-mutation is off here only because turning a new error on in a 1.x minor would fail consumers'\n * builds on upgrade (91 hits across five consumers, every one a real in-place mutation). It's `error` in\n * strict, and planned for `error` here in 2.0. It is type-aware: without type information it reports nothing.\n *\n * no-floating-io (1.17) is off here and `warn` in strict while it is measured: 0 false positives across\n * ~1,340 IO-typed calls in five codebases, but no real hits yet either. 2.0 decides `recommended` after\n * measuring it against functype-os, whose async methods return IO there. Type-aware, like no-array-mutation.\n *\n * no-getOrThrow-in-render and must-fold-on-component-return are React rules: they fire only inside a\n * component (a PascalCase function with JSX) or a hook (`use*`), so non-React code rarely trips them (a\n * non-React function named `use*` is read as a hook). Both are new and unmeasured on real React code, so\n * they start where no-floating-io did: off here, `warn` in strict. They work without type information and\n * are more precise with it.\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/collection-naming\": \"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 \"functype/no-array-mutation\": \"off\",\n \"functype/no-floating-io\": \"off\",\n \"functype/no-getOrThrow-in-render\": \"off\",\n \"functype/must-fold-on-component-return\": \"off\",\n}\n\nexport default recommendedRules\n"],"mappings":"
|
|
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 throws that are correct (bug checks, host contracts). Wire<T> (#325 B),\n * invariant() and @interop (#342) close those; graduating them is a measured decision.\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 *\n * collection-naming is a convention, not a heuristic — functype's Map/Set imported under their own names,\n * the built-in spelled globalThis.Map — so it has no false-positive class and starts at error.\n *\n * no-array-mutation is off here only because turning a new error on in a 1.x minor would fail consumers'\n * builds on upgrade (91 hits across five consumers, every one a real in-place mutation). It's `error` in\n * strict, and planned for `error` here in 2.0. It is type-aware: without type information it reports nothing.\n *\n * no-floating-io (1.17) is off here and `warn` in strict while it is measured: 0 false positives across\n * ~1,340 IO-typed calls in five codebases, but no real hits yet either. 2.0 decides `recommended` after\n * measuring it against functype-os, whose async methods return IO there. Type-aware, like no-array-mutation.\n *\n * no-floating-result (1.23) is off here and `error` in strict: a dropped Either or Try is a defect, not a\n * style, and on agent-todo's API it found the 20 drops that project fixed by hand as real bugs. Turning a\n * new error on here would fail consumers' builds on a 1.x minor, so it moves to `error` here in 2.0. Type-aware.\n *\n * no-serialize-container (1.23) is off here and `error` in strict, for the same reason: a container sent\n * to `c.json()` or `JSON.stringify()` is a defect, and turning a new error on here would fail consumers'\n * builds on a 1.x minor. It moves to `error` here in 2.0. Type-aware.\n *\n * no-getOrThrow-in-render and must-fold-on-component-return are React rules: they fire only inside a\n * component (a PascalCase function with JSX) or a hook (`use*`), so non-React code rarely trips them (a\n * non-React function named `use*` is read as a hook). Both are new and unmeasured on real React code, so\n * they start where no-floating-io did: off here, `warn` in strict. They work without type information and\n * are more precise with it.\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/collection-naming\": \"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 \"functype/no-array-mutation\": \"off\",\n \"functype/no-floating-io\": \"off\",\n \"functype/no-floating-result\": \"off\",\n \"functype/no-serialize-container\": \"off\",\n \"functype/no-getOrThrow-in-render\": \"off\",\n \"functype/must-fold-on-component-return\": \"off\",\n}\n\nexport default recommendedRules\n"],"mappings":"AA0CA,MAAMA,EAAmB,CACvB,kBAAmB,QACnB,+BAAgC,QAChC,+BAAgC,QAChC,+BAAgC,QAChC,sBAAuB,QACvB,uBAAwB,QACxB,6BAA8B,QAC9B,yBAA0B,OAC1B,yBAA0B,OAC1B,sBAAuB,OACvB,0BAA2B,OAC3B,8BAA+B,OAC/B,yBAA0B,MAC1B,uBAAwB,MACxB,6BAA8B,MAC9B,0BAA2B,MAC3B,8BAA+B,MAC/B,kCAAmC,MACnC,mCAAoC,MACpC,yCAA0C,KAC5C"}
|
package/dist/configs/strict.d.ts
CHANGED
|
@@ -7,6 +7,8 @@ declare const strictRules: {
|
|
|
7
7
|
"functype/prefer-list": string;
|
|
8
8
|
"functype/no-array-mutation": string;
|
|
9
9
|
"functype/no-floating-io": string;
|
|
10
|
+
"functype/no-floating-result": string;
|
|
11
|
+
"functype/no-serialize-container": string;
|
|
10
12
|
"functype/no-getOrThrow-in-render": string;
|
|
11
13
|
"functype/must-fold-on-component-return": string;
|
|
12
14
|
"functype/prefer-functype-map": string;
|
package/dist/configs/strict.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"./recommended.js";const t={...e,"functype/prefer-option":`error`,"functype/prefer-either":`error`,"functype/prefer-try":`error`,"functype/no-get-unsafe":`error`,"functype/prefer-list":`warn`,"functype/no-array-mutation":`error`,"functype/no-floating-io":`warn`,"functype/no-getOrThrow-in-render":`warn`,"functype/must-fold-on-component-return":`warn`,"functype/prefer-functype-map":`error`,"functype/prefer-functype-set":`error`,"functype/no-imperative-loops":`error`};export{t as default};
|
|
1
|
+
import e from"./recommended.js";const t={...e,"functype/prefer-option":`error`,"functype/prefer-either":`error`,"functype/prefer-try":`error`,"functype/no-get-unsafe":`error`,"functype/prefer-list":`warn`,"functype/no-array-mutation":`error`,"functype/no-floating-io":`warn`,"functype/no-floating-result":`error`,"functype/no-serialize-container":`error`,"functype/no-getOrThrow-in-render":`warn`,"functype/must-fold-on-component-return":`warn`,"functype/prefer-functype-map":`error`,"functype/prefer-functype-set":`error`,"functype/no-imperative-loops":`error`};export{t as default};
|
|
2
2
|
//# sourceMappingURL=strict.js.map
|
|
@@ -1 +1 @@
|
|
|
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/no-array-mutation\": \"error\",\n \"functype/no-floating-io\": \"warn\",\n \"functype/no-getOrThrow-in-render\": \"warn\",\n \"functype/must-fold-on-component-return\": \"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,6BAA8B,QAC9B,0BAA2B,OAC3B,mCAAoC,OACpC,yCAA0C,OAC1C,+BAAgC,QAChC,+BAAgC,QAChC,+BAAgC,OAClC"}
|
|
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/no-array-mutation\": \"error\",\n \"functype/no-floating-io\": \"warn\",\n \"functype/no-floating-result\": \"error\",\n \"functype/no-serialize-container\": \"error\",\n \"functype/no-getOrThrow-in-render\": \"warn\",\n \"functype/must-fold-on-component-return\": \"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,6BAA8B,QAC9B,0BAA2B,OAC3B,8BAA+B,QAC/B,kCAAmC,QACnC,mCAAoC,OACpC,yCAA0C,OAC1C,+BAAgC,QAChC,+BAAgC,QAChC,+BAAgC,OAClC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -17,6 +17,8 @@ declare const plugin: {
|
|
|
17
17
|
"collection-naming": import("eslint").Rule.RuleModule;
|
|
18
18
|
"no-array-mutation": import("eslint").Rule.RuleModule;
|
|
19
19
|
"no-floating-io": import("eslint").Rule.RuleModule;
|
|
20
|
+
"no-floating-result": import("eslint").Rule.RuleModule;
|
|
21
|
+
"no-serialize-container": import("eslint").Rule.RuleModule;
|
|
20
22
|
"no-getOrThrow-in-render": import("eslint").Rule.RuleModule;
|
|
21
23
|
"must-fold-on-component-return": import("eslint").Rule.RuleModule;
|
|
22
24
|
};
|
package/dist/rules/index.d.ts
CHANGED
|
@@ -2,20 +2,22 @@ import rule from "./collection-naming.js";
|
|
|
2
2
|
import rule$1 from "./must-fold-on-component-return.js";
|
|
3
3
|
import rule$2 from "./no-array-mutation.js";
|
|
4
4
|
import rule$3 from "./no-floating-io.js";
|
|
5
|
-
import rule$
|
|
6
|
-
import rule$
|
|
7
|
-
import rule$
|
|
8
|
-
import rule$7 from "./no-
|
|
9
|
-
import rule$8 from "./
|
|
10
|
-
import rule$9 from "./
|
|
11
|
-
import rule$10 from "./prefer-
|
|
12
|
-
import rule$11 from "./prefer-
|
|
13
|
-
import rule$12 from "./prefer-
|
|
14
|
-
import rule$13 from "./prefer-
|
|
15
|
-
import rule$14 from "./prefer-
|
|
16
|
-
import rule$15 from "./prefer-
|
|
17
|
-
import rule$16 from "./prefer-
|
|
18
|
-
import rule$17 from "./prefer-
|
|
5
|
+
import rule$4 from "./no-floating-result.js";
|
|
6
|
+
import rule$6 from "./no-get-unsafe.js";
|
|
7
|
+
import rule$5 from "./no-getOrThrow-in-render.js";
|
|
8
|
+
import rule$7 from "./no-imperative-loops.js";
|
|
9
|
+
import rule$8 from "./no-let.js";
|
|
10
|
+
import rule$9 from "./no-serialize-container.js";
|
|
11
|
+
import rule$10 from "./prefer-do-notation.js";
|
|
12
|
+
import rule$11 from "./prefer-either.js";
|
|
13
|
+
import rule$12 from "./prefer-flatmap.js";
|
|
14
|
+
import rule$13 from "./prefer-fold.js";
|
|
15
|
+
import rule$14 from "./prefer-functype-map.js";
|
|
16
|
+
import rule$15 from "./prefer-functype-set.js";
|
|
17
|
+
import rule$16 from "./prefer-list.js";
|
|
18
|
+
import rule$17 from "./prefer-map.js";
|
|
19
|
+
import rule$18 from "./prefer-option.js";
|
|
20
|
+
import rule$19 from "./prefer-try.js";
|
|
19
21
|
//#region src/rules/index.d.ts
|
|
20
22
|
declare const _default: {
|
|
21
23
|
"prefer-option": import("eslint").Rule.RuleModule;
|
|
@@ -34,9 +36,11 @@ declare const _default: {
|
|
|
34
36
|
"collection-naming": import("eslint").Rule.RuleModule;
|
|
35
37
|
"no-array-mutation": import("eslint").Rule.RuleModule;
|
|
36
38
|
"no-floating-io": import("eslint").Rule.RuleModule;
|
|
39
|
+
"no-floating-result": import("eslint").Rule.RuleModule;
|
|
40
|
+
"no-serialize-container": import("eslint").Rule.RuleModule;
|
|
37
41
|
"no-getOrThrow-in-render": import("eslint").Rule.RuleModule;
|
|
38
42
|
"must-fold-on-component-return": import("eslint").Rule.RuleModule;
|
|
39
43
|
};
|
|
40
44
|
//#endregion
|
|
41
|
-
export { rule as collectionNaming, _default as default, rule$1 as mustFoldOnComponentReturn, rule$2 as noArrayMutation, rule$3 as noFloatingIo, rule$4 as
|
|
45
|
+
export { rule as collectionNaming, _default as default, rule$1 as mustFoldOnComponentReturn, rule$2 as noArrayMutation, rule$3 as noFloatingIo, rule$4 as noFloatingResult, rule$5 as noGetOrThrowInRender, rule$6 as noGetUnsafe, rule$7 as noImperativeLoops, rule$8 as noLet, rule$9 as noSerializeContainer, rule$10 as preferDoNotation, rule$11 as preferEither, rule$12 as preferFlatmap, rule$13 as preferFold, rule$14 as preferFunctypeMap, rule$15 as preferFunctypeSet, rule$16 as preferList, rule$17 as preferMap, rule$18 as preferOption, rule$19 as preferTry };
|
|
42
46
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/rules/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"./collection-naming.js";import t from"./must-fold-on-component-return.js";import n from"./no-array-mutation.js";import r from"./no-floating-io.js";import i from"./no-get-unsafe.js";import
|
|
1
|
+
import e from"./collection-naming.js";import t from"./must-fold-on-component-return.js";import n from"./no-array-mutation.js";import r from"./no-floating-io.js";import i from"./no-floating-result.js";import a from"./no-get-unsafe.js";import o from"./no-getOrThrow-in-render.js";import s from"./no-imperative-loops.js";import c from"./no-let.js";import l from"./no-serialize-container.js";import u from"./prefer-do-notation.js";import d from"./prefer-either.js";import f from"./prefer-flatmap.js";import p from"./prefer-fold.js";import m from"./prefer-functype-map.js";import h from"./prefer-functype-set.js";import g from"./prefer-list.js";import _ from"./prefer-map.js";import v from"./prefer-option.js";import y from"./prefer-try.js";var b={"prefer-option":v,"prefer-either":d,"prefer-try":y,"prefer-list":g,"no-get-unsafe":a,"no-let":c,"prefer-fold":p,"prefer-map":_,"prefer-flatmap":f,"prefer-functype-map":m,"prefer-functype-set":h,"no-imperative-loops":s,"prefer-do-notation":u,"collection-naming":e,"no-array-mutation":n,"no-floating-io":r,"no-floating-result":i,"no-serialize-container":l,"no-getOrThrow-in-render":o,"must-fold-on-component-return":t};export{e as collectionNaming,b as default,t as mustFoldOnComponentReturn,n as noArrayMutation,r as noFloatingIo,i as noFloatingResult,o as noGetOrThrowInRender,a as noGetUnsafe,s as noImperativeLoops,c as noLet,l as noSerializeContainer,u as preferDoNotation,d as preferEither,f as preferFlatmap,p as preferFold,m as preferFunctypeMap,h as preferFunctypeSet,g as preferList,_ as preferMap,v as preferOption,y as preferTry};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
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","collectionNaming","noArrayMutation","noFloatingIo","noGetOrThrowInRender","mustFoldOnComponentReturn","rule","rule$1","rule$2","rule$3","rule$
|
|
1
|
+
{"version":3,"file":"index.js","names":["preferOption","preferEither","preferTry","preferList","noGetUnsafe","noLet","preferFold","preferMap","preferFlatmap","preferFunctypeMap","preferFunctypeSet","noImperativeLoops","preferDoNotation","collectionNaming","noArrayMutation","noFloatingIo","noFloatingResult","noSerializeContainer","noGetOrThrowInRender","mustFoldOnComponentReturn","rule","rule$1","rule$2","rule$3","rule$4","rule$6","rule$5","rule$7","rule$8","rule$9","rule$10","rule$11","rule$12","rule$13","rule$14","rule$15","rule$16","rule$17","rule$18","rule$19","rules_default"],"sources":["../../src/rules/index.ts"],"sourcesContent":["import collectionNaming from \"./collection-naming\"\nimport mustFoldOnComponentReturn from \"./must-fold-on-component-return\"\nimport noArrayMutation from \"./no-array-mutation\"\nimport noFloatingIo from \"./no-floating-io\"\nimport noFloatingResult from \"./no-floating-result\"\nimport noGetUnsafe from \"./no-get-unsafe\"\nimport noGetOrThrowInRender from \"./no-getOrThrow-in-render\"\nimport noImperativeLoops from \"./no-imperative-loops\"\nimport noLet from \"./no-let\"\nimport noSerializeContainer from \"./no-serialize-container\"\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 collectionNaming,\n mustFoldOnComponentReturn,\n noArrayMutation,\n noFloatingIo,\n noFloatingResult,\n noGetOrThrowInRender,\n noGetUnsafe,\n noImperativeLoops,\n noLet,\n noSerializeContainer,\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 \"collection-naming\": collectionNaming,\n \"no-array-mutation\": noArrayMutation,\n \"no-floating-io\": noFloatingIo,\n \"no-floating-result\": noFloatingResult,\n \"no-serialize-container\": noSerializeContainer,\n \"no-getOrThrow-in-render\": noGetOrThrowInRender,\n \"must-fold-on-component-return\": mustFoldOnComponentReturn,\n}\n"],"mappings":"guBA4CA,IAAAwC,EAAe,CACb,gBAAiBxC,EACjB,gBAAiBC,EACjB,aAAcC,EACd,cAAeC,EACf,gBAAiBC,EACjB,SAAUC,EACV,cAAeC,EACf,aAAcC,EACd,iBAAkBC,EAClB,sBAAuBC,EACvB,sBAAuBC,EACvB,sBAAuBC,EACvB,qBAAsBC,EACtB,oBAAqBC,EACrB,oBAAqBC,EACrB,iBAAkBC,EAClB,qBAAsBC,EACtB,yBAA0BC,EAC1B,0BAA2BC,EAC3B,gCAAiCC,CACnC"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Rule } from "eslint";
|
|
2
|
+
//#region src/rules/no-floating-result.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Reports a statement that computes an Either, Try or other failure-carrying result and drops it:
|
|
5
|
+
* `await userService.updateSubscription(id, plan)` on its own line, or `parse(input)`. A Left or a
|
|
6
|
+
* Failure in it is silently ignored. `no-floating-promises` doesn't help, because awaiting the promise
|
|
7
|
+
* satisfies it while the result inside is thrown away.
|
|
8
|
+
*
|
|
9
|
+
* Only results that can carry a failure count: an ignored Option or List loses no error. A chain that
|
|
10
|
+
* handles its own failure with `.tapError(…)` or `.tapLeft(…)` isn't reported: that is a best-effort
|
|
11
|
+
* write that logs a failure on purpose, as in agent-todo's audit and cleanup writes. `void result`
|
|
12
|
+
* marks any other deliberate drop. An `IO` that is never run is no-floating-io's.
|
|
13
|
+
*
|
|
14
|
+
* Type-aware only: without type information it reports nothing.
|
|
15
|
+
*/
|
|
16
|
+
declare const rule: Rule.RuleModule;
|
|
17
|
+
//#endregion
|
|
18
|
+
export { rule as default };
|
|
19
|
+
//# sourceMappingURL=no-floating-result.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{canCarryFailureByType as e}from"../utils/type-aware.js";const t=/* @__PURE__ */ new Set([`CallExpression`,`ChainExpression`,`AwaitExpression`,`LogicalExpression`,`ConditionalExpression`]),n=/* @__PURE__ */ new Set([`tapError`,`tapLeft`]),r=/* @__PURE__ */ new Set([`flatMap`,`chain`,`andThen`,`flatMapError`,`orElse`]),i=e=>{if(!e)return!1;if(e.type===`AwaitExpression`)return i(e.argument);if(e.type===`ChainExpression`)return i(e.expression);if(e.type!==`CallExpression`)return!1;let t=e.callee;if(t.type!==`MemberExpression`)return!1;let a=t.property,o=a.type===`Identifier`?a.name:``;return n.has(o)?!0:!r.has(o)&&i(t.object)},a={meta:{type:`problem`,docs:{description:`Disallow dropping an Either, Try or other result that can carry a failure`,recommended:!1},schema:[],messages:{floatingResult:`This result is dropped, so a failure in it is silently ignored. Check isLeft() / isFailure(), fold it, or return it. Use void if dropping it is deliberate`}},create(n){return{ExpressionStatement(r){let a=r.expression;t.has(a.type)&&!i(a)&&e(a,n)&&n.report({node:a,messageId:`floatingResult`})}}}};export{a as default};
|
|
2
|
+
//# sourceMappingURL=no-floating-result.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"no-floating-result.js","names":["CHECKED","FAILURE_HANDLERS","FAILURE_SOURCES","handlesItsFailure","node","callee","property","name","rule","expression","canCarryFailureByType","context"],"sources":["../../src/rules/no-floating-result.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { canCarryFailureByType } from \"../utils/type-aware\"\n\n/** `f()`, `a?.f()`, `await …`, and `ok && f()` / `ok ? f() : g()`: statements whose only job is a value. */\nconst CHECKED: ReadonlySet<string> = new Set([\n \"CallExpression\",\n \"ChainExpression\",\n \"AwaitExpression\",\n \"LogicalExpression\",\n \"ConditionalExpression\",\n])\n\n/** Methods that run a callback on the failure, so a chain through one has handled it. */\nconst FAILURE_HANDLERS: ReadonlySet<string> = new Set([\"tapError\", \"tapLeft\"])\n\n/** Methods that can bring in a new failure, so a handler before one no longer covers the result. */\nconst FAILURE_SOURCES: ReadonlySet<string> = new Set([\"flatMap\", \"chain\", \"andThen\", \"flatMapError\", \"orElse\"])\n\n/**\n * Does the call chain in `node` handle its own failure? Walks the receiver chain from the outermost\n * call in: a `.tapError(…)` or `.tapLeft(…)` counts, unless a later `.flatMap(…)` can bring in a new,\n * unlogged failure. Arguments are never walked into.\n */\nconst handlesItsFailure = (node: ASTNode | undefined): boolean => {\n if (!node) return false\n if (node.type === \"AwaitExpression\") return handlesItsFailure(node.argument as ASTNode)\n if (node.type === \"ChainExpression\") return handlesItsFailure(node.expression as ASTNode)\n if (node.type !== \"CallExpression\") return false\n const callee = node.callee as ASTNode\n if (callee.type !== \"MemberExpression\") return false\n const property = callee.property as ASTNode\n const name = property.type === \"Identifier\" ? (property.name as string) : \"\"\n if (FAILURE_HANDLERS.has(name)) return true\n if (FAILURE_SOURCES.has(name)) return false\n return handlesItsFailure(callee.object as ASTNode)\n}\n\n/**\n * Reports a statement that computes an Either, Try or other failure-carrying result and drops it:\n * `await userService.updateSubscription(id, plan)` on its own line, or `parse(input)`. A Left or a\n * Failure in it is silently ignored. `no-floating-promises` doesn't help, because awaiting the promise\n * satisfies it while the result inside is thrown away.\n *\n * Only results that can carry a failure count: an ignored Option or List loses no error. A chain that\n * handles its own failure with `.tapError(…)` or `.tapLeft(…)` isn't reported: that is a best-effort\n * write that logs a failure on purpose, as in agent-todo's audit and cleanup writes. `void result`\n * marks any other deliberate drop. An `IO` that is never run is no-floating-io's.\n *\n * Type-aware only: without type information it reports nothing.\n */\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Disallow dropping an Either, Try or other result that can carry a failure\",\n recommended: false,\n },\n schema: [],\n messages: {\n floatingResult:\n \"This result is dropped, so a failure in it is silently ignored. Check isLeft() / isFailure(), fold it, or return it. Use void if dropping it is deliberate\",\n },\n },\n\n create(context) {\n return {\n ExpressionStatement(node: ASTNode) {\n const expression = node.expression as ASTNode\n // `void result` is a UnaryExpression, so a deliberate drop never gets this far.\n if (!CHECKED.has(expression.type) || handlesItsFailure(expression)) return\n if (canCarryFailureByType(expression, context))\n context.report({ node: expression, messageId: \"floatingResult\" })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"+DAMA,MAAMA,kBAA+B,IAAI,IAAI,CAC3C,iBACA,kBACA,kBACA,oBACA,uBACF,CAAC,EAGKC,kBAAwC,IAAI,IAAI,CAAC,WAAY,SAAS,CAAC,EAGvEC,kBAAuC,IAAI,IAAI,CAAC,UAAW,QAAS,UAAW,eAAgB,QAAQ,CAAC,EAOxGC,EAAqB,GAAuC,CAChE,GAAI,CAACC,EAAM,MAAO,GAClB,GAAIA,EAAK,OAAS,kBAAmB,OAAOD,EAAkBC,EAAK,QAAmB,EACtF,GAAIA,EAAK,OAAS,kBAAmB,OAAOD,EAAkBC,EAAK,UAAqB,EACxF,GAAIA,EAAK,OAAS,iBAAkB,MAAO,GAC3C,IAAMC,EAASD,EAAK,OACpB,GAAIC,EAAO,OAAS,mBAAoB,MAAO,GAC/C,IAAMC,EAAWD,EAAO,SAClBE,EAAOD,EAAS,OAAS,aAAgBA,EAAS,KAAkB,GAG1E,OAFIL,EAAiB,IAAIM,CAAI,EAAU,GACvC,CAAIL,EAAgB,IAAIK,CAAI,GACrBJ,EAAkBE,EAAO,MAAiB,CACnD,EAeMG,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,4EACb,YAAa,EACf,EACA,OAAQ,CAAC,EACT,SAAU,CACR,eACE,4JACJ,CACF,EAEA,OAAO,EAAS,CACd,MAAO,CACL,oBAAoB,EAAe,CACjC,IAAMC,EAAaL,EAAK,WAEnBJ,EAAQ,IAAIS,EAAW,IAAI,GAAK,GAAkBA,CAAU,GAC7DC,EAAsBD,EAAYE,CAAO,GAC3CA,EAAQ,OAAO,CAAE,KAAMF,EAAY,UAAW,gBAAiB,CAAC,CACpE,CACF,CACF,CACF"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Rule } from "eslint";
|
|
2
|
+
//#region src/rules/no-serialize-container.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Reports a functype container handed to a JSON sink, anywhere inside the value. An Either, Option or
|
|
5
|
+
* List serializes as its `{"@functype", _tag, value}` envelope, so a client reading `subscription.plan`
|
|
6
|
+
* gets `undefined`, and a body built around a Left answers 200. The compiler can't catch it, because
|
|
7
|
+
* `c.json()` and `JSON.stringify()` accept any value (#364).
|
|
8
|
+
*
|
|
9
|
+
* Calling `.toJSON()` or `.serialize()` first says the envelope is what you mean, and isn't reported.
|
|
10
|
+
*
|
|
11
|
+
* Type-aware only: without type information it reports nothing.
|
|
12
|
+
*/
|
|
13
|
+
declare const rule: Rule.RuleModule;
|
|
14
|
+
//#endregion
|
|
15
|
+
export { rule as default };
|
|
16
|
+
//# sourceMappingURL=no-serialize-container.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{containerInsideByType as e}from"../utils/type-aware.js";function t(e){let t=e.callee,[n]=e.arguments;if(n===void 0||n.type===`SpreadElement`||t.type!==`MemberExpression`||t.computed||t.property.type!==`Identifier`)return;if(t.property.name===`json`)return n;let r=t.object;return t.property.name===`stringify`&&r.type===`Identifier`&&r.name===`JSON`?n:void 0}const n={meta:{type:`problem`,docs:{description:`Disallow passing an Either, Option, List or other functype container to a JSON sink`,recommended:!1},schema:[],messages:{serializedContainer:`This sends the {{name}}'s {_tag, value} envelope{{where}}, not its value. Unwrap it first: check isLeft() / isNone() and return the error, fold() it, or call .toArray() on a List. Use .toJSON() if the envelope is what you mean`}},create(n){return{CallExpression(r){let i=t(r);if(i===void 0)return;let a=e(i,n);a!==void 0&&n.report({node:i,messageId:`serializedContainer`,data:{name:a.name,where:a.path===``?``:` at ${a.path}`}})}}}};export{n as default};
|
|
2
|
+
//# sourceMappingURL=no-serialize-container.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"no-serialize-container.js","names":["serializedArgument","callee","call","first","object","rule","argument","node","found","containerInsideByType","context"],"sources":["../../src/rules/no-serialize-container.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { containerInsideByType } from \"../utils/type-aware\"\n\n/**\n * `JSON.stringify(x)` or `*.json(x)`: Hono's `c.json`, `Response.json`, Express's `res.json`. A read\n * such as `await res.json()` has no argument, so it never matches.\n */\nfunction serializedArgument(call: ASTNode): ASTNode | undefined {\n const callee = call.callee as ASTNode\n const [first] = call.arguments as ReadonlyArray<ASTNode>\n if (first === undefined || first.type === \"SpreadElement\") return undefined\n if (callee.type !== \"MemberExpression\" || callee.computed || callee.property.type !== \"Identifier\") return undefined\n if (callee.property.name === \"json\") return first\n const object = callee.object as ASTNode\n return callee.property.name === \"stringify\" && object.type === \"Identifier\" && object.name === \"JSON\"\n ? first\n : undefined\n}\n\n/**\n * Reports a functype container handed to a JSON sink, anywhere inside the value. An Either, Option or\n * List serializes as its `{\"@functype\", _tag, value}` envelope, so a client reading `subscription.plan`\n * gets `undefined`, and a body built around a Left answers 200. The compiler can't catch it, because\n * `c.json()` and `JSON.stringify()` accept any value (#364).\n *\n * Calling `.toJSON()` or `.serialize()` first says the envelope is what you mean, and isn't reported.\n *\n * Type-aware only: without type information it reports nothing.\n */\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Disallow passing an Either, Option, List or other functype container to a JSON sink\",\n recommended: false,\n },\n schema: [],\n messages: {\n serializedContainer:\n \"This sends the {{name}}'s {_tag, value} envelope{{where}}, not its value. Unwrap it first: check isLeft() / isNone() and return the error, fold() it, or call .toArray() on a List. Use .toJSON() if the envelope is what you mean\",\n },\n },\n\n create(context) {\n return {\n CallExpression(node: ASTNode) {\n const argument = serializedArgument(node)\n if (argument === undefined) return\n const found = containerInsideByType(argument, context)\n if (found === undefined) return\n context.report({\n node: argument,\n messageId: \"serializedContainer\",\n data: { name: found.name, where: found.path === \"\" ? \"\" : ` at ${found.path}` },\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"+DASA,SAASA,EAAmB,EAAoC,CAC9D,IAAMC,EAASC,EAAK,OACd,CAACC,GAASD,EAAK,UAErB,GADIC,IAAU,IAAA,IAAaA,EAAM,OAAS,iBACtCF,EAAO,OAAS,oBAAsBA,EAAO,UAAYA,EAAO,SAAS,OAAS,aAAc,OACpG,GAAIA,EAAO,SAAS,OAAS,OAAQ,OAAOE,EAC5C,IAAMC,EAASH,EAAO,OACtB,OAAOA,EAAO,SAAS,OAAS,aAAeG,EAAO,OAAS,cAAgBA,EAAO,OAAS,OAC3FD,EACA,IAAA,EACN,CAYA,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,sFACb,YAAa,EACf,EACA,OAAQ,CAAC,EACT,SAAU,CACR,oBACE,oOACJ,CACF,EAEA,OAAO,EAAS,CACd,MAAO,CACL,eAAe,EAAe,CAC5B,IAAMC,EAAWN,EAAmBO,CAAI,EACxC,GAAID,IAAa,IAAA,GAAW,OAC5B,IAAME,EAAQC,EAAsBH,EAAUI,CAAO,EACjDF,IAAU,IAAA,IACdE,EAAQ,OAAO,CACb,KAAMJ,EACN,UAAW,sBACX,KAAM,CAAE,KAAME,EAAM,KAAM,MAAOA,EAAM,OAAS,GAAK,GAAK,OAAOA,EAAM,MAAO,CAChF,CAAC,CACH,CACF,CACF,CACF"}
|
|
@@ -1,5 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
const obj = yield* $(Option(${n}))
|
|
3
|
-
return yield* $(Option(obj${i[0].substring(n.length)}))
|
|
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};
|
|
1
|
+
import{isExtractableByType as e}from"../utils/type-aware.js";import{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)}const s=/* @__PURE__ */ new Set([`flatMap`,`map`,`filter`,`fold`]),c=/* @__PURE__ */ new Set([`flatMap`]),l=/* @__PURE__ */ new Set([`flatMap`,`map`,`filter`]);function u(e){if(e.type!==`CallExpression`||e.callee?.type!==`MemberExpression`)return 0;let t=e.callee.property;return(t.type===`Identifier`&&s.has(t.name)?1:0)+u(e.callee.object)}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){return e.type!==`LogicalExpression`||e.operator!==`&&`?[e]:[...p(e.left),...p(e.right)]}const m=e=>e.type===`Identifier`||e.type===`ThisExpression`||e.type===`MemberExpression`,h=/* @__PURE__ */ new Set,g=/* @__PURE__ */ new Set([`ArrowFunctionExpression`,`FunctionExpression`,`FunctionDeclaration`]);function _(e){let t=e?.typeAnnotation;return t?.type!==`TSTypeReference`||t.typeName?.type!==`Identifier`?h:n.has(t.typeName.name)?/* @__PURE__ */ new Set([t.typeName.name]):h}const v=/^(option|opt|either|result|maybe|task)\d*$/i,y=/[a-z0-9](Option|Either|Result|Maybe|Try|Task)\d*$/,b=/* @__PURE__ */ new Map([[`toOption`,`Option`],[`toEither`,`Either`],[`toTry`,`Try`]]);function x(e){if(e.type===`ConditionalExpression`)return i(x(e.consequent),x(e.alternate));if(e.type!==`CallExpression`)return h;if(a(e).size>0)return a(e);if(e.callee?.type!==`MemberExpression`||e.callee.property.type!==`Identifier`)return h;let t=b.get(e.callee.property.name);return t===void 0?l.has(e.callee.property.name)?x(e.callee.object):h:/* @__PURE__ */ new Set([t])}function S(e){return e.type!==`CallExpression`||a(e).size>0||e.callee?.type!==`MemberExpression`||e.callee.property.type!==`Identifier`||!l.has(e.callee.property.name)?e:S(e.callee.object)}const C={meta:{type:`suggestion`,docs:{description:`Prefer Do notation for complex monadic compositions and nested operations`,recommended:!0},messages:{preferDoForNestedChecks:`This && chain guards each step of a property path. Use optional chaining (a?.b?.c), or Option(a).flatMap(…) when you want an Option`,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]||{},d=r.minChainDepth||3,C=r.detectMixedMonads!==!1,w=e=>n.sourceCode.getText(e).replace(/\s+/g,``);function T(e){let t=(n.sourceCode.getScope(e).references.find(t=>t.identifier===e)?.resolved)?.defs[0]?.name;return _(t?.typeAnnotation)}function E(t){let r=e(t.callee.object,n);if(r!==void 0)return r;let i=S(t);return x(i).size>0?!0:i.type===`Identifier`?T(i).size>0||v.test(i.name)||y.test(i.name):!1}function D(e){let t=e.parent,n=t?.parent;if(t?.type===`MemberExpression`&&t.object===e&&n?.type===`CallExpression`&&n.callee===t)return t.property.type===`Identifier`&&s.has(t.property.name)?n:void 0}function O(e,t){let n=D(e);if(n===void 0)return!1;let r=n.callee.property;return r.type===`Identifier`&&t.has(r.name)||O(n,t)}function k(e){if(e.operator!==`&&`)return;let t=e.parent;if(t?.type===`LogicalExpression`&&t.operator===`&&`)return;let r=p(e);r.reduce((e,t,n)=>{let i=r[n-1],a=i!==void 0&&m(i)&&t.type===`MemberExpression`&&w(t.object)===w(i)?e.run+1:1;return{run:a,best:Math.max(e.best,a)}},{run:0,best:0}).best>=3&&n.report({node:e,messageId:`preferDoForNestedChecks`})}function A(e){if(!t(e,`flatMap`)||O(e,c))return;let r=u(e);r<d||!E(e)||n.report({node:e,messageId:`preferDoForChainedMethods`,data:{count:r.toString()}})}function j(e){if(e?.type!==`ArrowFunctionExpression`&&e?.type!==`FunctionExpression`)return[];let t=e.body;if(t.type!==`BlockStatement`)return[t];let n=e=>e.type===`ReturnStatement`?e.argument?[e.argument]:[]:g.has(e.type)?[]:o(e).flatMap(n);return n(t)}function M(e){if(e.type===`Identifier`)return T(e);if(e.type!==`CallExpression`||e.callee?.type!==`MemberExpression`)return a(e);let t=e.callee.property,n=t.type===`Identifier`&&l.has(t.name)?j(e.arguments[0]).reduce((e,t)=>i(e,x(t)),h):h;if(a(e).size>0)return i(n,a(e));let r=t.type===`Identifier`?b.get(t.name):void 0;return r===void 0?i(n,M(e.callee.object)):i(n,/* @__PURE__ */ new Set([r]))}function N(e){C&&f(e)&&!O(e,l)&&E(e)&&M(e).size>=2&&n.report({node:e,messageId:`preferDoForMixedMonads`})}return{LogicalExpression(e){k(e)},CallExpression(e){A(e),N(e)}}}};export{C as default};
|
|
5
2
|
//# sourceMappingURL=prefer-do-notation.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-do-notation.js","names":["MONAD_TYPES","NON_CHILD_KEYS","union","a","b","monadAt","node","callee","astChildren","k","v","monadsIn","ast","acc","child","CHAIN_METHODS","COMPOSITION_METHODS","getChainDepth","method","next","compositionChainDepth","isCompositionChain","andChainDepth","rhs","rule","options","context","minChainDepth","detectMixedMonads","functypeImports","getFunctypeImports","hasDoImport","checkNestedNullChecks","hasNestedPropertyAccess","fixNestedChecks","fixer","matches","checkChainedMethods","isChainedMethodCall","chainDepth","fixChainedMethods","text","match","baseVar","doNotation","checkMixedMonads"],"sources":["../../src/rules/prefer-do-notation.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImports, isChainedMethodCall } from \"../utils/functype-detection\"\n\nconst MONAD_TYPES: ReadonlySet<string> = new Set([\"Option\", \"Either\", \"Try\", \"Task\"])\n\n/** AST keys that don't represent syntax children — back-edges and source metadata. */\nconst NON_CHILD_KEYS: ReadonlySet<string> = new Set([\"parent\", \"loc\", \"range\"])\n\nconst union = <T>(a: ReadonlySet<T>, b: ReadonlySet<T>): ReadonlySet<T> => new Set([...a, ...b])\n\n/**\n * Set of monad names that *this single AST node* names as a constructor call.\n * Does not look at children. Returns empty set for any non-monad-constructor node.\n */\nfunction monadAt(node: ASTNode): ReadonlySet<string> {\n if (node.type !== \"CallExpression\") return new Set()\n const callee = node.callee\n // Bare constructor: Option(...), Try(...), Either(...), Task(...)\n if (callee?.type === \"Identifier\" && MONAD_TYPES.has(callee.name)) {\n return new Set([callee.name])\n }\n // Companion call: Option.none(), Either.right(x), Try.success(v)\n if (\n callee?.type === \"MemberExpression\" &&\n callee.object?.type === \"Identifier\" &&\n MONAD_TYPES.has(callee.object.name)\n ) {\n return new Set([callee.object.name])\n }\n return new Set()\n}\n\n/**\n * AST children of `node` worth recursing into. Drops back-edges and source\n * metadata; flattens array-valued keys (e.g. `arguments`); filters non-object\n * leaves (literals, raw strings, numbers).\n */\nfunction astChildren(node: ASTNode): readonly unknown[] {\n return Object.entries(node)\n .filter(([k]) => !NON_CHILD_KEYS.has(k))\n .flatMap(([, v]) => (Array.isArray(v) ? v : [v]))\n .filter((v) => v !== null && typeof v === \"object\")\n}\n\n/**\n * Pure recursion: the set of all monad names reachable from `node` (including\n * `node` itself if it is a monad constructor call). No mutation, no\n * accumulator parameter — just a fold over the children's results.\n */\nfunction monadsIn(node: unknown): ReadonlySet<string> {\n if (!node || typeof node !== \"object\") return new Set()\n const ast = node as ASTNode\n return astChildren(ast).reduce<ReadonlySet<string>>((acc, child) => union(acc, monadsIn(child)), monadAt(ast))\n}\n\nconst CHAIN_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\", \"fold\"])\n\n/**\n * Methods that *compose* monadic operations (stay in the monad and feed the\n * next step). Distinct from terminal handlers (`fold`, `match`, `getOrElse`)\n * which *exit* the monad — those are conversions, not composition, and Do\n * notation doesn't apply to them.\n */\nconst COMPOSITION_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\"])\n\n/**\n * Length of the chain of `.flatMap()/.map()/.filter()/.fold()` calls walking\n * left from `node`. Returns 1 for a single call, N for N stacked calls. Pure\n * tail recursion — no mutable counter, no `while` loop.\n */\nfunction getChainDepth(node: ASTNode): number {\n if (node.callee.type !== \"MemberExpression\" || node.callee.object.type !== \"CallExpression\") return 1\n const method = node.callee.property\n const next = node.callee.object as ASTNode\n const here = method.type === \"Identifier\" && CHAIN_METHODS.has(method.name) ? 1 : 0\n return here + getChainDepth(next)\n}\n\n/**\n * Number of composition methods (`flatMap`/`map`/`filter`) stacked under\n * `node` via `.callee.object`. 0 if the callee isn't a member expression on\n * another call. Excludes terminal handlers by design.\n */\nfunction compositionChainDepth(node: ASTNode): number {\n if (node.callee?.type !== \"MemberExpression\" || node.callee.object?.type !== \"CallExpression\") return 0\n const method = node.callee.property\n const next = node.callee.object as ASTNode\n const here = method.type === \"Identifier\" && COMPOSITION_METHODS.has(method.name) ? 1 : 0\n return here + compositionChainDepth(next)\n}\n\n/**\n * True when `node`'s outermost call is a composition method AND at least one\n * more composition method appears below it — i.e. this is a real\n * `.flatMap(...).flatMap(...)`-style chain, not a terminal exit like\n * `.fold(...)` or a bare receiver like `option.flatMap(...)`.\n */\nfunction isCompositionChain(node: ASTNode): boolean {\n if (node.callee?.type !== \"MemberExpression\") return false\n const method = node.callee.property\n if (method.type !== \"Identifier\" || !COMPOSITION_METHODS.has(method.name)) return false\n return compositionChainDepth(node) >= 1\n}\n\n/**\n * Depth of a logical-AND chain (`a && b && c && ...`) where each right-hand\n * side is either a MemberExpression or another && chain — the shape that\n * indicates nested property-access guarding rather than arbitrary booleans.\n */\nfunction andChainDepth(node: ASTNode): number {\n if (node.type !== \"LogicalExpression\" || node.operator !== \"&&\") return 0\n const rhs = node.right\n const here = rhs.type === \"MemberExpression\" || (rhs.type === \"LogicalExpression\" && rhs.operator === \"&&\") ? 1 : 0\n return here + andChainDepth(node.left as ASTNode)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer Do notation for complex monadic compositions and nested operations\",\n recommended: true,\n },\n fixable: \"code\",\n messages: {\n preferDoForNestedChecks: \"Prefer Do notation for nested null/undefined checks instead of logical AND chains\",\n preferDoForChainedMethods: \"Prefer Do notation for complex flatMap chains ({{count}} levels deep)\",\n preferDoForMixedMonads: \"Consider Do notation when mixing Option, Either, and Try operations\",\n preferDoAsyncForChainedTasks: \"Prefer DoAsync notation for chained async operations\",\n },\n schema: [\n {\n type: \"object\",\n properties: {\n minChainDepth: {\n type: \"integer\",\n minimum: 2,\n default: 3,\n },\n detectMixedMonads: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n },\n create(context) {\n const options = context.options[0] || {}\n const minChainDepth = options.minChainDepth || 3\n const detectMixedMonads = options.detectMixedMonads !== false\n\n const functypeImports = getFunctypeImports(context)\n\n // Track if Do notation is already imported\n const hasDoImport = functypeImports.functions.has(\"Do\") || functypeImports.functions.has(\"DoAsync\")\n\n /**\n * Detect nested null/undefined checks like: a && a.b && a.b.c\n */\n function checkNestedNullChecks(node: ASTNode): void {\n if (node.operator !== \"&&\") return\n\n // Check if this looks like nested property access guarding\n if (andChainDepth(node) >= 2 && hasNestedPropertyAccess(node)) {\n context.report({\n node,\n messageId: \"preferDoForNestedChecks\",\n fix: hasDoImport ? (fixer) => fixNestedChecks(fixer, node) : undefined,\n })\n }\n }\n\n /**\n * Check if logical expression contains nested property access patterns\n */\n function hasNestedPropertyAccess(node: ASTNode): boolean {\n // Look for patterns like: obj && obj.prop && obj.prop.nested\n const matches = context.sourceCode.getText(node).match(/\\w+(\\.\\w+){2,}/g)\n return matches !== null && matches.length > 0\n }\n\n /**\n * Detect long flatMap chains\n */\n function checkChainedMethods(node: ASTNode): void {\n if (!isChainedMethodCall(node, \"flatMap\")) return\n\n const chainDepth = getChainDepth(node)\n\n if (chainDepth >= minChainDepth) {\n context.report({\n node,\n messageId: \"preferDoForChainedMethods\",\n data: { count: chainDepth.toString() },\n fix: hasDoImport ? (fixer) => fixChainedMethods(fixer, node) : undefined,\n })\n }\n }\n\n /**\n * Auto-fix for nested null checks\n */\n function fixNestedChecks(fixer: Rule.RuleFixer, node: ASTNode): Rule.Fix {\n const text = context.sourceCode.getText(node)\n\n // Simple transformation for common patterns\n // a && a.b && a.b.c -> Do(function* () { const x = yield* $(Option(a)); const y = yield* $(Option(x.b)); return Option(y.c) })\n const match = text.match(/(\\w+)(\\.\\w+)+/)\n if (match) {\n const baseVar = match[1]\n const chain = match[0]\n\n const doNotation = `Do(function* () {\n const obj = yield* $(Option(${baseVar}))\n return yield* $(Option(obj${chain.substring(baseVar.length)}))\n})`\n\n return fixer.replaceText(node, doNotation)\n }\n\n return fixer.replaceText(node, `/* TODO: Convert to Do notation */ ${text}`)\n }\n\n /**\n * Auto-fix for chained methods (basic)\n */\n function fixChainedMethods(fixer: Rule.RuleFixer, node: ASTNode): Rule.Fix {\n const text = context.sourceCode.getText(node)\n\n // For now, just add a comment suggesting Do notation\n return fixer.replaceText(node, `/* TODO: Consider Do notation for complex chains */ ${text}`)\n }\n\n /**\n * Detect mixed monad usage by walking the AST under `node` and counting\n * *distinct* monad constructor calls — not substring matches.\n *\n * A \"monad constructor call\" is a CallExpression whose callee is either:\n * - a bare identifier matching a known monad type (`Option(...)`, `Try(...)`),\n * or\n * - a member expression whose object is a known monad type\n * (`Option.none()`, `Either.right(...)`, `Try.success(...)`).\n *\n * Method calls like `.toEither(...)`, `.toOption()`, `.toTry()` are NOT\n * constructor calls — they're the idiomatic *conversion* API for crossing\n * monad boundaries. The old substring-based check fired on these because\n * `.toEither` contains \"Either\" as a substring; the AST check correctly\n * sees them as method calls, not new monad constructions.\n *\n * Implementation is pure recursion over the AST: `monadAt` reports what\n * a single node names; `monadsIn` returns the union of `monadAt(self)`\n * with the results from each child. No mutable accumulator, no for-loops\n * driving state changes.\n */\n function checkMixedMonads(node: ASTNode): void {\n if (!detectMixedMonads) return\n // Only flag genuine composition chains (.flatMap/.map/.filter stacked at\n // least twice deep). Terminal handlers (.fold/.match/.getOrElse) and\n // bare co-occurrence in arg lists are conversions, not compositions —\n // Do notation doesn't apply. See issue #205.\n if (!isCompositionChain(node)) return\n if (monadsIn(node).size >= 2) {\n context.report({ node, messageId: \"preferDoForMixedMonads\" })\n }\n }\n\n return {\n LogicalExpression(node) {\n checkNestedNullChecks(node)\n },\n\n CallExpression(node) {\n checkChainedMethods(node)\n checkMixedMonads(node)\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"6FAKA,MAAMA,kBAAmC,IAAI,IAAI,CAAC,SAAU,SAAU,MAAO,MAAM,CAAC,EAG9EC,kBAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC,EAExEC,GAAY,EAAmB,oBAAsC,IAAI,IAAI,CAAC,GAAGC,EAAG,GAAGC,CAAC,CAAC,EAM/F,SAASC,EAAQ,EAAoC,CACnD,GAAIC,EAAK,OAAS,iBAAkB,sBAAO,IAAI,IAC/C,IAAMC,EAASD,EAAK,OAapB,OAXIC,GAAQ,OAAS,cAAgBP,EAAY,IAAIO,EAAO,IAAI,kBACvD,IAAI,IAAI,CAACA,EAAO,IAAI,CAAC,EAI5BA,GAAQ,OAAS,oBACjBA,EAAO,QAAQ,OAAS,cACxBP,EAAY,IAAIO,EAAO,OAAO,IAAI,kBAE3B,IAAI,IAAI,CAACA,EAAO,OAAO,IAAI,CAAC,kBAE9B,IAAI,GACb,CAOA,SAASC,EAAY,EAAmC,CACtD,OAAO,OAAO,QAAQF,CAAI,CAAC,CACx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SAASC,EAAoB,EAAqB,CAChD,GAAI,CAACC,EAAoBhC,EAAM,SAAS,EAAG,OAE3C,IAAMiC,EAAatB,EAAcX,CAAI,EAEjCiC,GAAcZ,GAChBD,EAAQ,OAAO,CACb,OACA,UAAW,4BACX,KAAM,CAAE,MAAOa,EAAW,SAAS,CAAE,EACrC,IAAKR,EAAe,GAAUS,EAAkBL,EAAO7B,CAAI,EAAI,IAAA,EACjE,CAAC,CAEL,CAKA,SAAS4B,EAAgB,EAAuB,EAAyB,CACvE,IAAMO,EAAOf,EAAQ,WAAW,QAAQpB,CAAI,EAItCoC,EAAQD,EAAK,MAAM,eAAe,EACxC,GAAIC,EAAO,CACT,IAAMC,EAAUD,EAAM,GAGhBE,EAAa;gCACKD,EAAQ;8BAHlBD,EAAM,EAIO,CAAC,UAAUC,EAAQ,MAAM,EAAE;IAGtD,OAAOR,EAAM,YAAY7B,EAAMsC,CAAU,CAC3C,CAEA,OAAOT,EAAM,YAAY7B,EAAM,sCAAsCmC,GAAM,CAC7E,CAKA,SAASD,EAAkB,EAAuB,EAAyB,CACzE,IAAMC,EAAOf,EAAQ,WAAW,QAAQpB,CAAI,EAG5C,OAAO6B,EAAM,YAAY7B,EAAM,uDAAuDmC,GAAM,CAC9F,CAuBA,SAASI,EAAiB,EAAqB,CACxCjB,GAKAP,EAAmBf,CAAI,GACxBK,EAASL,CAAI,CAAC,CAAC,MAAQ,GACzBoB,EAAQ,OAAO,CAAE,OAAM,UAAW,wBAAyB,CAAC,CAEhE,CAEA,MAAO,CACL,kBAAkB,EAAM,CACtBM,EAAsB1B,CAAI,CAC5B,EAEA,eAAe,EAAM,CACnB+B,EAAoB/B,CAAI,EACxBuC,EAAiBvC,CAAI,CACvB,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-do-notation.js","names":["MONAD_TYPES","NON_CHILD_KEYS","union","a","b","monadAt","node","callee","astChildren","k","v","CHAIN_METHODS","FLAT_MAP","COMPOSITION_METHODS","getChainDepth","method","compositionChainDepth","next","isCompositionChain","andOperands","isPathStart","NONE","FUNCTION_TYPES","monadOfAnnotation","type","annotation","MONAD_NAME","MONAD_SUFFIX","CONVERSIONS","monadOfValue","converted","chainRoot","rule","options","context","minChainDepth","detectMixedMonads","text","declaredMonad","declared","identifier","reference","onMonad","byType","isExtractableByType","step","root","nextStep","member","call","hasStepAbove","methods","checkNestedNullChecks","parent","operands","previous","i","run","operand","acc","checkChainedMethods","isChainedMethodCall","chainDepth","returnedBy","callback","body","returns","monadsAlongChain","returned","checkMixedMonads"],"sources":["../../src/rules/prefer-do-notation.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { isChainedMethodCall } from \"../utils/functype-detection\"\nimport { isExtractableByType } from \"../utils/type-aware\"\n\nconst MONAD_TYPES: ReadonlySet<string> = new Set([\"Option\", \"Either\", \"Try\", \"Task\"])\n\n/** AST keys that don't represent syntax children — back-edges and source metadata. */\nconst NON_CHILD_KEYS: ReadonlySet<string> = new Set([\"parent\", \"loc\", \"range\"])\n\nconst union = <T>(a: ReadonlySet<T>, b: ReadonlySet<T>): ReadonlySet<T> => new Set([...a, ...b])\n\n/**\n * Set of monad names that *this single AST node* names as a constructor call.\n * Does not look at children. Returns empty set for any non-monad-constructor node.\n */\nfunction monadAt(node: ASTNode): ReadonlySet<string> {\n if (node.type !== \"CallExpression\") return new Set()\n const callee = node.callee\n // Bare constructor: Option(...), Try(...), Either(...), Task(...)\n if (callee?.type === \"Identifier\" && MONAD_TYPES.has(callee.name)) {\n return new Set([callee.name])\n }\n // Companion call: Option.none(), Either.right(x), Try.success(v)\n if (\n callee?.type === \"MemberExpression\" &&\n callee.object?.type === \"Identifier\" &&\n MONAD_TYPES.has(callee.object.name)\n ) {\n return new Set([callee.object.name])\n }\n return new Set()\n}\n\n/**\n * AST children of `node` worth recursing into. Drops back-edges and source\n * metadata; flattens array-valued keys (e.g. `arguments`); filters non-object\n * leaves (literals, raw strings, numbers).\n */\nfunction astChildren(node: ASTNode): readonly unknown[] {\n return Object.entries(node)\n .filter(([k]) => !NON_CHILD_KEYS.has(k))\n .flatMap(([, v]) => (Array.isArray(v) ? v : [v]))\n .filter((v) => v !== null && typeof v === \"object\")\n}\n\nconst CHAIN_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\", \"fold\"])\n\nconst FLAT_MAP: ReadonlySet<string> = new Set([\"flatMap\"])\n\n/**\n * Methods that *compose* monadic operations (stay in the monad and feed the\n * next step). Distinct from terminal handlers (`fold`, `match`, `getOrElse`)\n * which *exit* the monad — those are conversions, not composition, and Do\n * notation doesn't apply to them.\n */\nconst COMPOSITION_METHODS: ReadonlySet<string> = new Set([\"flatMap\", \"map\", \"filter\"])\n\n/**\n * Number of `.flatMap()/.map()/.filter()/.fold()` steps walking left from `node`. Only the steps\n * count: the receiver they start from, `o` or `Option(x)`, is not a level, so\n * `Option(x).flatMap(f).flatMap(g)` is 2 deep.\n */\nfunction getChainDepth(node: ASTNode): number {\n if (node.type !== \"CallExpression\" || node.callee?.type !== \"MemberExpression\") return 0\n const method = node.callee.property\n const here = method.type === \"Identifier\" && CHAIN_METHODS.has(method.name) ? 1 : 0\n return here + getChainDepth(node.callee.object as ASTNode)\n}\n\n/**\n * Number of composition methods (`flatMap`/`map`/`filter`) stacked under\n * `node` via `.callee.object`. 0 if the callee isn't a member expression on\n * another call. Excludes terminal handlers by design.\n */\nfunction compositionChainDepth(node: ASTNode): number {\n if (node.callee?.type !== \"MemberExpression\" || node.callee.object?.type !== \"CallExpression\") return 0\n const method = node.callee.property\n const next = node.callee.object as ASTNode\n const here = method.type === \"Identifier\" && COMPOSITION_METHODS.has(method.name) ? 1 : 0\n return here + compositionChainDepth(next)\n}\n\n/**\n * True when `node`'s outermost call is a composition method AND at least one\n * more composition method appears below it — i.e. this is a real\n * `.flatMap(...).flatMap(...)`-style chain, not a terminal exit like\n * `.fold(...)` or a bare receiver like `option.flatMap(...)`.\n */\nfunction isCompositionChain(node: ASTNode): boolean {\n if (node.callee?.type !== \"MemberExpression\") return false\n const method = node.callee.property\n if (method.type !== \"Identifier\" || !COMPOSITION_METHODS.has(method.name)) return false\n return compositionChainDepth(node) >= 1\n}\n\n/** The operands of an `a && b && c` chain, left to right, through any nesting of `&&`. */\nfunction andOperands(node: ASTNode): ReadonlyArray<ASTNode> {\n if (node.type !== \"LogicalExpression\" || node.operator !== \"&&\") return [node]\n return [...andOperands(node.left as ASTNode), ...andOperands(node.right as ASTNode)]\n}\n\n/** A plain property path a guard can start from: `a`, `this`, `a.b`. Optional chains are already the fix. */\nconst isPathStart = (node: ASTNode): boolean =>\n node.type === \"Identifier\" || node.type === \"ThisExpression\" || node.type === \"MemberExpression\"\n\nconst NONE: ReadonlySet<string> = new Set()\n\nconst FUNCTION_TYPES: ReadonlySet<string> = new Set([\n \"ArrowFunctionExpression\",\n \"FunctionExpression\",\n \"FunctionDeclaration\",\n])\n\n/** `MONAD_TYPES` entries a type annotation names: `Option<number>` → Option. */\nfunction monadOfAnnotation(annotation: ASTNode | undefined): ReadonlySet<string> {\n const type = annotation?.typeAnnotation as ASTNode | undefined\n if (type?.type !== \"TSTypeReference\" || type.typeName?.type !== \"Identifier\") return NONE\n return MONAD_TYPES.has(type.typeName.name) ? new Set([type.typeName.name]) : NONE\n}\n\n/**\n * Receiver names that say \"this holds a monad\", for code linted without type information: `option`,\n * `opt`, `either`, `result`, `maybe`, `task`, or a numbered one such as `option1`, in any case; or a\n * camelCase suffix such as `userOption` or `parseResult`, which must be capitalized, so `entry`,\n * `retry` and `registry` don't count.\n */\nconst MONAD_NAME = /^(option|opt|either|result|maybe|task)\\d*$/i\nconst MONAD_SUFFIX = /[a-z0-9](Option|Either|Result|Maybe|Try|Task)\\d*$/\n\n/** Methods that turn one monad into another: `Try(f).toOption()` is an Option. */\nconst CONVERSIONS: ReadonlyMap<string, string> = new Map([\n [\"toOption\", \"Option\"],\n [\"toEither\", \"Either\"],\n [\"toTry\", \"Try\"],\n])\n\n/**\n * The monad an expression's value is, as far as the syntax shows: a constructor or companion call\n * (`Option(x)`, `Either.right(x)`), a conversion (`Try(f).toOption()` is an Option), a step that keeps\n * its receiver's monad (`Option(x).map(f)`), or either branch of `ok ? a : b`. Anything else is unknown.\n */\nfunction monadOfValue(node: ASTNode): ReadonlySet<string> {\n if (node.type === \"ConditionalExpression\")\n return union(monadOfValue(node.consequent as ASTNode), monadOfValue(node.alternate as ASTNode))\n if (node.type !== \"CallExpression\") return NONE\n if (monadAt(node).size > 0) return monadAt(node)\n if (node.callee?.type !== \"MemberExpression\" || node.callee.property.type !== \"Identifier\") return NONE\n const converted = CONVERSIONS.get(node.callee.property.name)\n if (converted !== undefined) return new Set([converted])\n return COMPOSITION_METHODS.has(node.callee.property.name) ? monadOfValue(node.callee.object as ASTNode) : NONE\n}\n\n/**\n * The receiver a method chain starts from: `Option(x)` in `Option(x).map(f).flatMap(g)`, `o` in\n * `o.flatMap(f)`. Walks back only through steps that keep the monad (`flatMap`, `map`, `filter`), so\n * in `Option(xs).getOrElse([]).flatMap(f)` or after a `.fold(…)` the root is the unwrapped value, not\n * `Option(xs)`. A monad constructor or companion\n * call is a root of its own.\n */\nfunction chainRoot(node: ASTNode): ASTNode {\n if (node.type !== \"CallExpression\" || monadAt(node).size > 0) return node\n if (node.callee?.type !== \"MemberExpression\" || node.callee.property.type !== \"Identifier\") return node\n if (!COMPOSITION_METHODS.has(node.callee.property.name)) return node\n return chainRoot(node.callee.object as ASTNode)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n docs: {\n description: \"Prefer Do notation for complex monadic compositions and nested operations\",\n recommended: true,\n },\n messages: {\n preferDoForNestedChecks:\n \"This && chain guards each step of a property path. Use optional chaining (a?.b?.c), or Option(a).flatMap(…) when you want an Option\",\n preferDoForChainedMethods: \"Prefer Do notation for complex flatMap chains ({{count}} levels deep)\",\n preferDoForMixedMonads: \"Consider Do notation when mixing Option, Either, and Try operations\",\n preferDoAsyncForChainedTasks: \"Prefer DoAsync notation for chained async operations\",\n },\n schema: [\n {\n type: \"object\",\n properties: {\n minChainDepth: {\n type: \"integer\",\n minimum: 2,\n default: 3,\n },\n detectMixedMonads: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n },\n create(context) {\n const options = context.options[0] || {}\n const minChainDepth = options.minChainDepth || 3\n const detectMixedMonads = options.detectMixedMonads !== false\n const text = (node: ASTNode): string => context.sourceCode.getText(node).replace(/\\s+/g, \"\")\n\n /** The monad a chain root is declared as, through its variable's or parameter's annotation. */\n function declaredMonad(identifier: ASTNode): ReadonlySet<string> {\n const variable = context.sourceCode\n .getScope(identifier)\n .references.find((reference) => reference.identifier === identifier)?.resolved\n const declared = variable?.defs[0]?.name as ASTNode | undefined\n return monadOfAnnotation(declared?.typeAnnotation as ASTNode | undefined)\n }\n\n /**\n * Is `step` a step on a functype monad? With type information, the type of the value it's called on\n * decides, so a `string[]`, or an Option already unwrapped with `.getOrElse([])`, never counts, and\n * `service.getUser(1)` returning an Option does. Without it, the chain's root must be a monad\n * constructor, companion or conversion, an identifier annotated with a monad type, or one named\n * like a monad.\n */\n function onMonad(step: ASTNode): boolean {\n const byType = isExtractableByType(step.callee.object as ASTNode, context)\n if (byType !== undefined) return byType\n const root = chainRoot(step)\n if (monadOfValue(root).size > 0) return true\n if (root.type !== \"Identifier\") return false\n return declaredMonad(root).size > 0 || MONAD_NAME.test(root.name) || MONAD_SUFFIX.test(root.name)\n }\n\n /** The call that takes `node` as its receiver for a further `.flatMap/.map/.filter/.fold` step, if any. */\n function nextStep(node: ASTNode): ASTNode | undefined {\n const member = node.parent as ASTNode | undefined\n const call = member?.parent as ASTNode | undefined\n if (member?.type !== \"MemberExpression\" || member.object !== node) return undefined\n if (call?.type !== \"CallExpression\" || call.callee !== member) return undefined\n return member.property.type === \"Identifier\" && CHAIN_METHODS.has(member.property.name) ? call : undefined\n }\n\n /**\n * Is there a `methods` step further out on this chain? Then that step reports, once, for the whole\n * chain. A trailing `.fold(…)` or `.map(…)` isn't one, so it doesn't hide the flatMaps under it.\n */\n function hasStepAbove(node: ASTNode, methods: ReadonlySet<string>): boolean {\n const step = nextStep(node)\n if (step === undefined) return false\n const method = step.callee.property\n return (method.type === \"Identifier\" && methods.has(method.name)) || hasStepAbove(step, methods)\n }\n\n /**\n * `a && a.b && a.b.c`: at least three operands in a row, each a property of the one before it.\n * Matched on the AST, so `isAdmin && settings.theme && user.profile.name` is not a guard chain.\n */\n function checkNestedNullChecks(node: ASTNode): void {\n if (node.operator !== \"&&\") return\n const parent = node.parent as ASTNode | undefined\n if (parent?.type === \"LogicalExpression\" && parent.operator === \"&&\") return\n const operands = andOperands(node)\n const longestRun = operands.reduce<{ readonly run: number; readonly best: number }>(\n (acc, operand, i) => {\n const previous = operands[i - 1]\n const extends_ =\n previous !== undefined &&\n isPathStart(previous) &&\n operand.type === \"MemberExpression\" &&\n text(operand.object as ASTNode) === text(previous)\n const run = extends_ ? acc.run + 1 : 1\n return { run, best: Math.max(acc.best, run) }\n },\n { run: 0, best: 0 },\n ).best\n if (longestRun >= 3) context.report({ node, messageId: \"preferDoForNestedChecks\" })\n }\n\n /** A long `.flatMap(…)` chain on a monad, reported once at its outermost step. */\n function checkChainedMethods(node: ASTNode): void {\n if (!isChainedMethodCall(node, \"flatMap\") || hasStepAbove(node, FLAT_MAP)) return\n const chainDepth = getChainDepth(node)\n if (chainDepth < minChainDepth || !onMonad(node)) return\n context.report({\n node,\n messageId: \"preferDoForChainedMethods\",\n data: { count: chainDepth.toString() },\n })\n }\n\n /** What a step's callback returns: its expression body, or the arguments of its own `return`s. */\n function returnedBy(callback: ASTNode | undefined): ReadonlyArray<ASTNode> {\n if (callback?.type !== \"ArrowFunctionExpression\" && callback?.type !== \"FunctionExpression\") return []\n const body = callback.body as ASTNode\n if (body.type !== \"BlockStatement\") return [body]\n const returns = (node: ASTNode): ReadonlyArray<ASTNode> => {\n if (node.type === \"ReturnStatement\") return node.argument ? [node.argument as ASTNode] : []\n if (FUNCTION_TYPES.has(node.type)) return []\n return (astChildren(node) as ASTNode[]).flatMap(returns)\n }\n return returns(body)\n }\n\n /** The monads a composition chain moves through: its root, and what each step's callback returns. */\n function monadsAlongChain(node: ASTNode): ReadonlySet<string> {\n if (node.type === \"Identifier\") return declaredMonad(node)\n if (node.type !== \"CallExpression\" || node.callee?.type !== \"MemberExpression\") return monadAt(node)\n const method = node.callee.property\n const step =\n method.type === \"Identifier\" && COMPOSITION_METHODS.has(method.name)\n ? returnedBy(node.arguments[0] as ASTNode | undefined).reduce<ReadonlySet<string>>(\n (acc, returned) => union(acc, monadOfValue(returned)),\n NONE,\n )\n : NONE\n if (monadAt(node).size > 0) return union(step, monadAt(node))\n // From a conversion on, the chain is the converted monad: what it converted from doesn't count.\n const converted = method.type === \"Identifier\" ? CONVERSIONS.get(method.name) : undefined\n if (converted !== undefined) return union(step, new Set([converted]))\n return union(step, monadsAlongChain(node.callee.object as ASTNode))\n }\n\n /**\n * Mixed monads along one composition chain: `option.flatMap((x) => Either.right(x)).flatMap((y) => Try(…))`.\n * Only the chain's own steps count, not every monad written somewhere inside its callbacks, and\n * only a chain that starts from a monad: an array's `.map((x) => Option(x))` is not a mix.\n * Conversions such as `.toEither(…)` and terminal handlers such as `.fold(…)` are not steps (#205).\n */\n function checkMixedMonads(node: ASTNode): void {\n if (!detectMixedMonads || !isCompositionChain(node) || hasStepAbove(node, COMPOSITION_METHODS)) return\n if (!onMonad(node)) return\n if (monadsAlongChain(node).size >= 2) context.report({ node, messageId: \"preferDoForMixedMonads\" })\n }\n\n return {\n LogicalExpression(node) {\n checkNestedNullChecks(node)\n },\n\n CallExpression(node) {\n checkChainedMethods(node)\n checkMixedMonads(node)\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"kIAMA,MAAMA,kBAAmC,IAAI,IAAI,CAAC,SAAU,SAAU,MAAO,MAAM,CAAC,EAG9EC,kBAAsC,IAAI,IAAI,CAAC,SAAU,MAAO,OAAO,CAAC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EAAST,EAAK,OAAO,SACrBuC,EACJ9B,EAAO,OAAS,cAAgBF,EAAoB,IAAIE,EAAO,IAAI,EAC/DgD,EAAWzD,EAAK,UAAU,EAAyB,CAAC,CAAC,QAClD,EAAK,IAAaJ,EAAMyD,EAAK9B,EAAauC,CAAQ,CAAC,EACpD/C,CACF,EACAA,EACN,GAAIhB,EAAQC,CAAI,CAAC,CAAC,KAAO,EAAG,OAAOJ,EAAM2C,EAAMxC,EAAQC,CAAI,CAAC,EAE5D,IAAMwB,EAAYf,EAAO,OAAS,aAAea,EAAY,IAAIb,EAAO,IAAI,EAAI,IAAA,GAEhF,OADIe,IAAc,IAAA,GACX5B,EAAM2C,EAAMsB,EAAiB7D,EAAK,OAAO,MAAiB,CAAC,EAD9BJ,EAAM2C,kBAAM,IAAI,IAAI,CAACf,CAAS,CAAC,CAAC,CAEtE,CAQA,SAASuC,EAAiB,EAAqB,CACxCjC,GAAsBlB,EAAmBZ,CAAI,GAAK,GAAaA,EAAMO,CAAmB,GACxF6B,EAAQpC,CAAI,GACb6D,EAAiB7D,CAAI,CAAC,CAAC,MAAQ,GAAG4B,EAAQ,OAAO,CAAE,OAAM,UAAW,wBAAyB,CAAC,CACpG,CAEA,MAAO,CACL,kBAAkB,EAAM,CACtBkB,EAAsB9C,CAAI,CAC5B,EAEA,eAAe,EAAM,CACnBsD,EAAoBtD,CAAI,EACxB+D,EAAiB/D,CAAI,CACvB,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{HOST_THROWS_SCHEMA as t,hostThrowsWith as n,isHostThrow as r}from"../utils/host-throws.js";import{createImportFixer as i,hasFunctypeSymbol as a}from"../utils/import-fixer.js";function o(e){let t=e?.parent;return t?t.type===`CatchClause`||o(t):!1}const s={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Use Either/Left/Right for typed domain errors instead of throwing`,recommended:!0},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},allowThrowInTests:{type:`boolean`,default:!0},hostThrows:t},additionalProperties:!1}],messages:{preferEitherOverThrow:`Prefer Either.left(error) over throw statement. For a bug check use invariant(); for a host that needs the throw, tag the function @interop`,preferEitherReturn:`Consider returning Either<Error, {{type}}> instead of throwing. For a bug check use invariant(); for a host that needs the throw, tag the function @interop`,suggestEitherLeft:`Replace with Either.left(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(t){let s=t.options[0]||{},c=s.allowInteropMarker!==!1,l=n=>c&&e(n,`interop`,t.sourceCode),u=s.allowThrowInTests!==!1,d=n(s.hostThrows);function f(){let e=t.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function p(e){let t=e.parent;return t?h(t)?t:p(t):null}function m(e){let n=e?.returnType?.typeAnnotation;if(!n)return null;let r=t.sourceCode.getText(n);return r.includes(`Either`)?null:r}function h(e){return e?[`FunctionDeclaration`,`FunctionExpression`,`ArrowFunctionExpression`].includes(e.type):!1}function g(e){let t=e.parent;if(!t)return!1;if(t.type===`BlockStatement`&&h(t.parent))return!0;if(t.type===`BlockStatement`&&t.parent?.type===`IfStatement`){let e=t.parent.parent;return e?.type===`BlockStatement`&&h(e.parent)}return!1}return{ThrowStatement(e){if(l(e)||r(e.argument,d,t)||u&&f()||o(e))return;let n=t.sourceCode,s=[];if(g(e)){let t=e.argument,r=n.getText(t),o=t?.type===`NewExpression`&&t.callee?.type===`Identifier`&&t.callee.name===`Error`?r:`new Error(String(${r}))`;s.push({messageId:`suggestEitherLeft`,fix(t){return t.replaceText(e,`return Either.left(${o})`)}}),a(n,`Either`)||s.push({messageId:`suggestAddImport`,data:{symbol:`Either`},fix:i(n,`Either`)})}let c=m(p(e));t.report({node:e,...c===null?{messageId:`preferEitherOverThrow`}:{messageId:`preferEitherReturn`,data:{type:c}},suggest:s})}}}};export{s as default};
|
|
2
2
|
//# sourceMappingURL=prefer-either.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-either.js","names":["insideCatchClause","parent","node","rule","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowThrowInTests","isInTestFile","filename","enclosingFunction","isFunctionLike","nonEitherReturnType","returnType","fn","text","isDirectInFunctionBody","ifParent","sourceCode","suggest","throwArg","argText","eitherArg","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-either.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\n/** True iff any ancestor of `node` is a `CatchClause`. Pure tail recursion. */\nfunction insideCatchClause(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return parent.type === \"CatchClause\" || insideCatchClause(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Use Either/Left/Right for typed domain errors instead of throwing\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferEitherOverThrow:\n \"Prefer Either.left(error) over throw statement. For a bug check use invariant(); for a host that needs the throw, tag the function @interop\",\n preferEitherReturn:\n \"Consider returning Either<Error, {{type}}> instead of throwing. For a bug check use invariant(); for a host that needs the throw, tag the function @interop\",\n suggestEitherLeft: \"Replace with Either.left(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n // Bug checks are `invariant()` calls from functype (#342): a call, not a throw, so nothing to exempt.\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n const allowThrowInTests = options.allowThrowInTests !== false\n\n function isInTestFile() {\n const filename = context.filename\n return (\n /\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(filename) ||\n filename.includes(\"__tests__\") ||\n filename.includes(\"/test/\") ||\n filename.includes(\"/tests/\")\n )\n }\n\n /** The nearest function the throw belongs to — a nested function owns its own throws. */\n function enclosingFunction(node: ASTNode): ASTNode | null {\n const parent = node.parent\n if (!parent) return null\n return isFunctionLike(parent) ? parent : enclosingFunction(parent)\n }\n\n /** The declared return type when the function declares one that is not already an Either. */\n function nonEitherReturnType(fn: ASTNode | null): string | null {\n const returnType = fn?.returnType?.typeAnnotation\n if (!returnType) return null\n const text = context.sourceCode.getText(returnType)\n return text.includes(\"Either\") ? null : text\n }\n\n function isFunctionLike(node: ASTNode): boolean {\n if (!node) return false\n return [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"].includes(node.type)\n }\n\n function isDirectInFunctionBody(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"BlockStatement\" && isFunctionLike(parent.parent)) return true\n if (parent.type === \"BlockStatement\" && parent.parent?.type === \"IfStatement\") {\n const ifParent = parent.parent.parent\n return ifParent?.type === \"BlockStatement\" && isFunctionLike(ifParent.parent)\n }\n return false\n }\n\n return {\n ThrowStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n // Allow throws in test files if configured\n if (allowThrowInTests && isInTestFile()) return\n\n // Allow re-throwing in catch blocks (common pattern)\n if (insideCatchClause(node)) return\n\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isDirectInFunctionBody(node)) {\n const throwArg = node.argument\n const argText = sourceCode.getText(throwArg)\n const isErrorExpr =\n throwArg?.type === \"NewExpression\" &&\n throwArg.callee?.type === \"Identifier\" &&\n throwArg.callee.name === \"Error\"\n const eitherArg = isErrorExpr ? argText : `new Error(String(${argText}))`\n\n suggest.push({\n messageId: \"suggestEitherLeft\",\n fix(fixer) {\n return fixer.replaceText(node, `return Either.left(${eitherArg})`)\n },\n })\n\n if (!hasFunctypeSymbol(sourceCode, \"Either\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Either\" },\n fix: createImportFixer(sourceCode, \"Either\"),\n })\n }\n }\n\n // One report per throw (#324). When the enclosing function declares a non-Either return type,\n // the message names the Either it should return instead of reporting the function separately.\n const returnType = nonEitherReturnType(enclosingFunction(node))\n context.report({\n node,\n ...(returnType === null\n ? { messageId: \"preferEitherOverThrow\" }\n : { messageId: \"preferEitherReturn\", data: { type: returnType } }),\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"prefer-either.js","names":["insideCatchClause","parent","node","rule","HOST_THROWS_SCHEMA","options","context","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowThrowInTests","hostThrows","hostThrowsWith","isInTestFile","filename","enclosingFunction","isFunctionLike","nonEitherReturnType","returnType","fn","text","isDirectInFunctionBody","ifParent","isHostThrow","sourceCode","suggest","throwArg","argText","eitherArg","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-either.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { HOST_THROWS_SCHEMA, hostThrowsWith, isHostThrow } from \"../utils/host-throws\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\n\n/** True iff any ancestor of `node` is a `CatchClause`. Pure tail recursion. */\nfunction insideCatchClause(node: ASTNode | null | undefined): boolean {\n const parent = node?.parent as ASTNode | undefined\n if (!parent) return false\n return parent.type === \"CatchClause\" || insideCatchClause(parent)\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Use Either/Left/Right for typed domain errors instead of throwing\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n allowThrowInTests: {\n type: \"boolean\",\n default: true,\n },\n hostThrows: HOST_THROWS_SCHEMA,\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferEitherOverThrow:\n \"Prefer Either.left(error) over throw statement. For a bug check use invariant(); for a host that needs the throw, tag the function @interop\",\n preferEitherReturn:\n \"Consider returning Either<Error, {{type}}> instead of throwing. For a bug check use invariant(); for a host that needs the throw, tag the function @interop\",\n suggestEitherLeft: \"Replace with Either.left(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n // Bug checks are `invariant()` calls from functype (#342): a call, not a throw, so nothing to exempt.\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n const allowThrowInTests = options.allowThrowInTests !== false\n // `throw redirect(…)` / `throw notFound()` from a router is the router's API, not an error (#445).\n const hostThrows = hostThrowsWith(options.hostThrows)\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 /** The nearest function the throw belongs to — a nested function owns its own throws. */\n function enclosingFunction(node: ASTNode): ASTNode | null {\n const parent = node.parent\n if (!parent) return null\n return isFunctionLike(parent) ? parent : enclosingFunction(parent)\n }\n\n /** The declared return type when the function declares one that is not already an Either. */\n function nonEitherReturnType(fn: ASTNode | null): string | null {\n const returnType = fn?.returnType?.typeAnnotation\n if (!returnType) return null\n const text = context.sourceCode.getText(returnType)\n return text.includes(\"Either\") ? null : text\n }\n\n function isFunctionLike(node: ASTNode): boolean {\n if (!node) return false\n return [\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"].includes(node.type)\n }\n\n function isDirectInFunctionBody(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"BlockStatement\" && isFunctionLike(parent.parent)) return true\n if (parent.type === \"BlockStatement\" && parent.parent?.type === \"IfStatement\") {\n const ifParent = parent.parent.parent\n return ifParent?.type === \"BlockStatement\" && isFunctionLike(ifParent.parent)\n }\n return false\n }\n\n return {\n ThrowStatement(node: ASTNode) {\n if (isExemptByMarker(node)) return\n if (isHostThrow(node.argument, hostThrows, context)) return\n // Allow throws in test files if configured\n if (allowThrowInTests && isInTestFile()) return\n\n // Allow re-throwing in catch blocks (common pattern)\n if (insideCatchClause(node)) return\n\n const sourceCode = context.sourceCode\n const suggest: Rule.SuggestionReportDescriptor[] = []\n\n if (isDirectInFunctionBody(node)) {\n const throwArg = node.argument\n const argText = sourceCode.getText(throwArg)\n const isErrorExpr =\n throwArg?.type === \"NewExpression\" &&\n throwArg.callee?.type === \"Identifier\" &&\n throwArg.callee.name === \"Error\"\n const eitherArg = isErrorExpr ? argText : `new Error(String(${argText}))`\n\n suggest.push({\n messageId: \"suggestEitherLeft\",\n fix(fixer) {\n return fixer.replaceText(node, `return Either.left(${eitherArg})`)\n },\n })\n\n if (!hasFunctypeSymbol(sourceCode, \"Either\")) {\n suggest.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Either\" },\n fix: createImportFixer(sourceCode, \"Either\"),\n })\n }\n }\n\n // One report per throw (#324). When the enclosing function declares a non-Either return type,\n // the message names the Either it should return instead of reporting the function separately.\n const returnType = nonEitherReturnType(enclosingFunction(node))\n context.report({\n node,\n ...(returnType === null\n ? { messageId: \"preferEitherOverThrow\" }\n : { messageId: \"preferEitherReturn\", data: { type: returnType } }),\n suggest,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"4PAQA,SAASA,EAAkB,EAA2C,CACpE,IAAMC,EAASC,GAAM,OAErB,OADKD,EACEA,EAAO,OAAS,eAAiBD,EAAkBC,CAAM,EAD5C,EAEtB,CAEA,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,oEACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,mBAAoB,CAClB,KAAM,UACN,QAAS,EACX,EACA,kBAAmB,CACjB,KAAM,UACN,QAAS,EACX,EACA,WAAYC,CACd,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,sBACE,8IACF,mBACE,8JACF,kBAAmB,gCACnB,iBAAkB,qCACpB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EAEjCC,EAAqBF,EAAQ,qBAAuB,GAEpDG,EAAoB,GACxBD,GAAsBE,EAA0BP,EAAA,UAAmBI,EAAQ,UAAU,EACjFI,EAAoBL,EAAQ,oBAAsB,GAElDM,EAAaC,EAAeP,EAAQ,UAAU,EAEpD,SAASQ,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,CAGA,SAASC,EAAkB,EAA+B,CACxD,IAAMd,EAASC,EAAK,OAEpB,OADKD,EACEe,EAAef,CAAM,EAAIA,EAASc,EAAkBd,CAAM,EAD7C,IAEtB,CAGA,SAASgB,EAAoB,EAAmC,CAC9D,IAAMC,EAAaC,GAAI,YAAY,eACnC,GAAI,CAACD,EAAY,OAAO,KACxB,IAAME,EAAOd,EAAQ,WAAW,QAAQY,CAAU,EAClD,OAAOE,EAAK,SAAS,Q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ACA,GAAIY,IAAe,KACf,CAAE,UAAW,uBAAwB,EACrC,CAAE,UAAW,qBAAsB,KAAM,CAAE,KAAMA,CAAW,CAAE,EAClE,SACF,CAAC,CACH,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
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
|
|
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=e=>e.type===`TSNullKeyword`||e.type===`TSUndefinedKeyword`;function d(e){let t=e.parent;if(!t)return!1;if(t.type===`AssignmentPattern`&&t.left===e)return d(t);if(t.type===`TSParameterProperty`)return!0;let n=t.params;return Array.isArray(n)&&n.includes(e)}function f(e){let t=e?.type===`TSTypeAnnotation`?e.parent:void 0;if(t)return t.type===`TSPropertySignature`||d(t)?t:void 0}const p={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},checkOptionalMembers:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{preferOption:`Prefer Option<{{type}}> over nullable type '{{nullable}}'`,preferOptionReturn:`Prefer Option<{{type}}> as return type over nullable '{{nullable}}'`,preferOptionOverOptional:`Prefer '{{name}}: Option<{{type}}>' over the optional '{{name}}?'`,suggestOptionType:`Replace with Option<{{type}}>`,suggestAddImport:`Add {{symbol}} import from functype`}},create(s){let p=s.options[0]||{},m=p.wireTypes??o,h=p.allowInteropMarker!==!1,g=t=>h&&e(t,`interop`,s.sourceCode),_=p.allowUseState!==!1,v=p.checkOptionalMembers===!0;function y(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 y(t)}let b=t(s);function x(e){if(!v||e.optional!==!0||e.type!==`TSPropertySignature`&&!d(e)||c(e,m)||g(e))return;let t=e.typeAnnotation?.typeAnnotation;if(!t||r(t,b)||t.type===`TSUnionType`&&t.types.some(e=>e.type===`TSNullKeyword`))return;let n=t.type===`TSUnionType`?t.types.filter(e=>!u(e)):[t];if(n.length!==1||r(n[0],b))return;let i=e.type===`TSPropertySignature`?e.key:e,a=i.type===`Identifier`?i.name:i.type===`Literal`?String(i.value):s.sourceCode.getText(i);s.report({node:i,messageId:`preferOptionOverOptional`,data:{name:a,type:s.sourceCode.getText(n[0])}})}return{TSPropertySignature:x,Identifier:x,TSUnionType(e){if(c(e,m)||g(e)||!e.types||e.types.length<2||_&&y(e)||!e.types.some(e=>u(e)))return;let t=f(e.parent),o=!e.types.some(e=>e.type===`TSNullKeyword`);if(t&&o&&(!v||t.optional===!0))return;let l=e.types.filter(e=>!u(e));if(l.length===1){let t=l[0];if(r(t,b)||n(e,b))return;let o=s.sourceCode,c=o.getText(t),u=o.getText(e);if(c.startsWith(`Option<`))return;let d=[{messageId:`suggestOptionType`,data:{type:c},fix(t){return t.replaceText(e,`Option<${c}>`)}}];a(o,`Option`)||d.push({messageId:`suggestAddImport`,data:{symbol:`Option`},fix:i(o,`Option`)}),s.report({node:e,messageId:`preferOption`,data:{type:c,nullable:u},suggest:d})}}}}};export{p as default};
|
|
2
2
|
//# sourceMappingURL=prefer-option.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-option.js","names":["REACT_STATE_HOOKS","rule","WIRE_TYPES_SCHEMA","options","context","wireTypes","DEFAULT_WIRE_TYPES","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","node","allowUseState","isInHookTypeArgument","parent","callee","name","functypeImports","getFunctypeImportsLegacy","isInsideWireType","type","nonNullTypes","nonNullType","isFunctypeType","isAlreadyUsingFunctype","sourceCode","nonNullTypeText","fullType","suggestions","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-option.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype, isFunctypeType } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\n\nconst REACT_STATE_HOOKS: ReadonlySet<string> = new Set([\"useState\", \"useRef\"])\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Option<T> over nullable types (T | null | undefined)\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowNullableIntersections: {\n type: \"boolean\",\n default: false,\n },\n allowUseState: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferOption: \"Prefer Option<{{type}}> over nullable type '{{nullable}}'\",\n preferOptionReturn: \"Prefer Option<{{type}}> as return type over nullable '{{nullable}}'\",\n suggestOptionType: \"Replace with Option<{{type}}>\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // Everything inside `Wire<…>` is the declared serialization shape (#325 B).\n const wireTypes: ReadonlyArray<string> = options.wireTypes ?? DEFAULT_WIRE_TYPES\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n // `null` is idiomatic React state (`useState<User | null>(null)`, `useRef<El | null>(null)`); an\n // Option in a hook's type argument buys nothing and fights the hook's own API (#325).\n const allowUseState = options.allowUseState !== false\n\n /** Is `node` inside the type argument of a `useState` / `useRef` call (bare or `React.`-qualified)? */\n function isInHookTypeArgument(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"TSTypeParameterInstantiation\" && parent.parent?.type === \"CallExpression\") {\n const callee = parent.parent.callee\n const name =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (name !== null && REACT_STATE_HOOKS.has(name)) return true\n }\n return isInHookTypeArgument(parent)\n }\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n return {\n TSUnionType(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (isExemptByMarker(node)) return\n if (!node.types || node.types.length < 2) return\n if (allowUseState && isInHookTypeArgument(node)) return\n\n const hasNull = node.types.some(\n (type: ASTNode) => type.type === \"TSNullKeyword\" || type.type === \"TSUndefinedKeyword\",\n )\n\n if (!hasNull) return\n\n const nonNullTypes = node.types.filter(\n (type: ASTNode) => type.type !== \"TSNullKeyword\" && type.type !== \"TSUndefinedKeyword\",\n )\n\n if (nonNullTypes.length === 1) {\n const nonNullType = nonNullTypes[0]\n\n // Skip if it's already an Option type or other functype type\n if (isFunctypeType(nonNullType, functypeImports)) return\n\n // Skip if we're already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const nonNullTypeText = sourceCode.getText(nonNullType)\n const fullType = sourceCode.getText(node)\n\n // Skip if it's already an Option type (fallback check)\n if (nonNullTypeText.startsWith(\"Option<\")) return\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestOptionType\",\n data: { type: nonNullTypeText },\n fix(fixer) {\n return fixer.replaceText(node, `Option<${nonNullTypeText}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"Option\")) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Option\" },\n fix: createImportFixer(sourceCode, \"Option\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferOption\",\n data: {\n type: nonNullTypeText,\n nullable: fullType,\n },\n suggest: suggestions,\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"6XAQA,MAAMA,kBAAyC,IAAI,IAAI,CAAC,WAAY,QAAQ,CAAC,EAEvEC,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,8DACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,C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IC,EAAa,SAAW,EAAG,CAC7B,IAAMC,EAAcD,EAAa,GAMjC,GAHIE,EAAeD,EAAaL,CAAe,GAG3CO,EAAuBb,EAAMM,CAAe,EAAG,OAEnD,IAAMQ,EAAapB,EAAQ,WACrBqB,EAAkBD,EAAW,QAAQH,CAAW,EAChDK,EAAWF,EAAW,QAAQd,CAAI,EAGxC,GAAIe,EAAgB,WAAW,SAAS,EAAG,OAE3C,IAAME,EAAiD,CACrD,CACE,UAAW,oBACX,KAAM,CAAE,KAAMF,CAAgB,EAC9B,IAAI,EAAO,CACT,OAAOG,EAAM,YAAYlB,EAAM,UAAUe,EAAgB,EAAE,CAC7D,CACF,CACF,EAEKI,EAAkBL,EAAY,QAAQ,GACzCG,EAAY,KAAK,CACf,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKG,EAAkBN,EAAY,QAAQ,CAC7C,CAAC,EAGHpB,EAAQ,OAAO,CACb,OACA,UAAW,eACX,KAAM,CACJ,KAAMqB,EACN,SAAUC,CACZ,EACA,QAASC,CACX,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-option.js","names":["REACT_STATE_HOOKS","isNullish","type","isParameter","parent","node","params","memberOrParameterOf","owner","annotation","rule","WIRE_TYPES_SCHEMA","options","context","wireTypes","DEFAULT_WIRE_TYPES","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowUseState","checkOptionalMembers","isInHookTypeArgument","callee","name","functypeImports","getFunctypeImportsLegacy","checkOptional","isInsideWireType","isFunctypeType","t","kept","key","undefinedOnly","nonNullTypes","nonNullType","isAlreadyUsingFunctype","sourceCode","nonNullTypeText","fullType","suggestions","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-option.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype, isFunctypeType } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\n\nconst REACT_STATE_HOOKS: ReadonlySet<string> = new Set([\"useState\", \"useRef\"])\n\nconst isNullish = (type: ASTNode): boolean => type.type === \"TSNullKeyword\" || type.type === \"TSUndefinedKeyword\"\n\n/** Is `node` a parameter: of a function, a method signature or a function type, with or without a default? */\nfunction isParameter(node: ASTNode): boolean {\n const parent = node.parent as ASTNode | undefined\n if (!parent) return false\n if (parent.type === \"AssignmentPattern\" && parent.left === node) return isParameter(parent)\n if (parent.type === \"TSParameterProperty\") return true\n const params = (parent as { readonly params?: ReadonlyArray<ASTNode> }).params\n return Array.isArray(params) && params.includes(node)\n}\n\n/**\n * The member or parameter a type annotation belongs to, when it's the annotation of a type-literal or\n * interface member (`b: string | undefined`) or a parameter (`(x: string | undefined) => …`). Those are\n * the caller's shapes: a prop, an options-bag field, an argument (#446).\n */\nfunction memberOrParameterOf(annotation: ASTNode | undefined): ASTNode | undefined {\n const owner = annotation?.type === \"TSTypeAnnotation\" ? (annotation.parent as ASTNode | undefined) : undefined\n if (!owner) return undefined\n if (owner.type === \"TSPropertySignature\") return owner\n return isParameter(owner) ? owner : undefined\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Option<T> over nullable types (T | null | undefined)\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowNullableIntersections: {\n type: \"boolean\",\n default: false,\n },\n allowUseState: {\n type: \"boolean\",\n default: true,\n },\n checkOptionalMembers: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferOption: \"Prefer Option<{{type}}> over nullable type '{{nullable}}'\",\n preferOptionReturn: \"Prefer Option<{{type}}> as return type over nullable '{{nullable}}'\",\n preferOptionOverOptional: \"Prefer '{{name}}: Option<{{type}}>' over the optional '{{name}}?'\",\n suggestOptionType: \"Replace with Option<{{type}}>\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // Everything inside `Wire<…>` is the declared serialization shape (#325 B).\n const wireTypes: ReadonlyArray<string> = options.wireTypes ?? DEFAULT_WIRE_TYPES\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n // `null` is idiomatic React state (`useState<User | null>(null)`, `useRef<El | null>(null)`); an\n // Option in a hook's type argument buys nothing and fights the hook's own API (#325).\n const allowUseState = options.allowUseState !== false\n // `a?: T` and `a: T | undefined` on a member or parameter both mean \"may be absent\", and the caller\n // writes `<X b=\"v\" />` or `f()`. Skip both unless asked to report them (#446).\n const checkOptionalMembers = options.checkOptionalMembers === true\n\n /** Is `node` inside the type argument of a `useState` / `useRef` call (bare or `React.`-qualified)? */\n function isInHookTypeArgument(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"TSTypeParameterInstantiation\" && parent.parent?.type === \"CallExpression\") {\n const callee = parent.parent.callee\n const name =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (name !== null && REACT_STATE_HOOKS.has(name)) return true\n }\n return isInHookTypeArgument(parent)\n }\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n /** With checkOptionalMembers, `a?: T` on a member or parameter is reported like `a: T | undefined`. */\n function checkOptional(node: ASTNode): void {\n if (!checkOptionalMembers || node.optional !== true) return\n if (node.type !== \"TSPropertySignature\" && !isParameter(node)) return\n if (isInsideWireType(node, wireTypes) || isExemptByMarker(node)) return\n const annotation = (node.typeAnnotation as ASTNode | undefined)?.typeAnnotation as ASTNode | undefined\n if (!annotation || isFunctypeType(annotation, functypeImports)) return\n // `a?: T | null` is reported once, by the union check, which keeps its suggestions.\n if (annotation.type === \"TSUnionType\" && annotation.types.some((t: ASTNode) => t.type === \"TSNullKeyword\")) return\n const kept =\n annotation.type === \"TSUnionType\" ? annotation.types.filter((t: ASTNode) => !isNullish(t)) : [annotation]\n if (kept.length !== 1 || isFunctypeType(kept[0], functypeImports)) return\n const key = (node.type === \"TSPropertySignature\" ? node.key : node) as ASTNode\n const name =\n key.type === \"Identifier\"\n ? key.name\n : key.type === \"Literal\"\n ? String(key.value)\n : context.sourceCode.getText(key)\n context.report({\n node: key,\n messageId: \"preferOptionOverOptional\",\n data: { name, type: context.sourceCode.getText(kept[0]) },\n })\n }\n\n return {\n TSPropertySignature: checkOptional,\n Identifier: checkOptional,\n\n TSUnionType(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (isExemptByMarker(node)) return\n if (!node.types || node.types.length < 2) return\n if (allowUseState && isInHookTypeArgument(node)) return\n\n const hasNull = node.types.some((type: ASTNode) => isNullish(type))\n\n if (!hasNull) return\n\n // On a member or parameter, `T | undefined` is the same \"may be absent\" as `?:`: skipped unless\n // checkOptionalMembers is on, and never reported on an optional one (`c?: T | undefined` is the\n // spelling exactOptionalPropertyTypes needs; the optional-member check reports it, once).\n const owner = memberOrParameterOf(node.parent)\n const undefinedOnly = !node.types.some((type: ASTNode) => type.type === \"TSNullKeyword\")\n if (owner && undefinedOnly && (!checkOptionalMembers || owner.optional === true)) return\n\n const nonNullTypes = node.types.filter((type: ASTNode) => !isNullish(type))\n\n if (nonNullTypes.length === 1) {\n const nonNullType = nonNullTypes[0]\n\n // Skip if it's already an Option type or other functype type\n if (isFunctypeType(nonNullType, functypeImports)) return\n\n // Skip if we're already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const nonNullTypeText = sourceCode.getText(nonNullType)\n const fullType = sourceCode.getText(node)\n\n // Skip if it's already an Option type (fallback check)\n if (nonNullTypeText.startsWith(\"Option<\")) return\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestOptionType\",\n data: { type: nonNullTypeText },\n fix(fixer) {\n return fixer.replaceText(node, `Option<${nonNullTypeText}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"Option\")) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Option\" },\n fix: createImportFixer(sourceCode, \"Option\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferOption\",\n data: {\n type: nonNullTypeText,\n nullable: fullType,\n },\n suggest: suggestions,\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"6XAQA,MAAMA,kBAAyC,IAAI,IAAI,CAAC,WAAY,QAAQ,CAAC,EAEvEC,EAAa,GAA2BC,EAAK,OAAS,iBAAmBA,EAAK,OAAS,qBAG7F,SAASC,EAAY,EAAwB,CAC3C,IAAMC,EAASC,EAAK,OACpB,GAAI,CAACD,EAAQ,MAAO,GACpB,GAAIA,EAAO,OAAS,qBAAuBA,EAAO,OAASC,EAAM,OAAOF,EAAYC,CAAM,EAC1F,GAAIA,EAAO,OAAS,sBAAuB,MAAO,GAClD,IAAME,EAAUF,EAAwD,OACxE,OAAO,MAAM,QAAQE,CAAM,GAAKA,EAAO,SAASD,CAAI,CACtD,CAOA,SAASE,EAAoB,EAAsD,CACjF,IAAMC,EAAQC,GAAY,OAAS,mBAAsBA,EAAW,OAAiC,IAAA,GACrG,GAAKD,EAEL,OADIA,EAAM,OAAS,uBACZL,EAAYK,CAAK,EADyBA,EACb,IAAA,EACtC,CAEA,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,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AAeM,EAAaV,CAAe,GAG3CW,EAAuB9B,EAAMmB,CAAe,EAAG,OAEnD,IAAMY,EAAavB,EAAQ,WACrBwB,EAAkBD,EAAW,QAAQF,CAAW,EAChDI,EAAWF,EAAW,QAAQ/B,CAAI,EAGxC,GAAIgC,EAAgB,WAAW,SAAS,EAAG,OAE3C,IAAME,EAAiD,CACrD,CACE,UAAW,oBACX,KAAM,CAAE,KAAMF,CAAgB,EAC9B,IAAI,EAAO,CACT,OAAOG,EAAM,YAAYnC,EAAM,UAAUgC,EAAgB,EAAE,CAC7D,CACF,CACF,EAEKI,EAAkBL,EAAY,QAAQ,GACzCG,EAAY,KAAK,CACf,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKG,EAAkBN,EAAY,QAAQ,CAC7C,CAAC,EAGHvB,EAAQ,OAAO,CACb,OACA,UAAW,eACX,KAAM,CACJ,KAAMwB,EACN,SAAUC,CACZ,EACA,QAASC,CACX,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { ASTNode } from "../types/ast.js";
|
|
2
|
+
import { Rule } from "eslint";
|
|
3
|
+
//#region src/utils/host-throws.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Router helpers whose return value a loader or route guard throws to redirect or show Not found
|
|
6
|
+
* (#445). The throw is the framework's API, not an error path: returning `Either.left(…)` instead
|
|
7
|
+
* breaks it. Each name was checked against the package's exports on 2026-10-31. React Router 6 loaders
|
|
8
|
+
* import from react-router-dom, and Remix on Workers from @remix-run/cloudflare.
|
|
9
|
+
*/
|
|
10
|
+
export declare const DEFAULT_HOST_THROWS: Readonly<Record<string, ReadonlyArray<string>>>;
|
|
11
|
+
export declare const HOST_THROWS_SCHEMA: {
|
|
12
|
+
readonly type: "object";
|
|
13
|
+
readonly additionalProperties: {
|
|
14
|
+
readonly type: "array";
|
|
15
|
+
readonly items: {
|
|
16
|
+
readonly type: "string";
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The defaults with a project's own `hostThrows` added: naming a module adds helpers to its defaults,
|
|
22
|
+
* so `{ "react-router": ["myRedirect"] }` keeps `redirect` and the rest, and `[]` turns that module's
|
|
23
|
+
* defaults off. A module the defaults don't name is added.
|
|
24
|
+
*/
|
|
25
|
+
export declare const hostThrowsWith: (overrides: Readonly<Record<string, ReadonlyArray<string>>> | undefined) => ReadonlyMap<string, ReadonlySet<string>>;
|
|
26
|
+
/**
|
|
27
|
+
* Is `argument`, the value a `throw` throws, a call to a host helper? `throw redirect(…)` and
|
|
28
|
+
* `throw notFound()` with the name imported from a listed module, under any local name, or
|
|
29
|
+
* `throw Router.redirect(…)` through a namespace import of one.
|
|
30
|
+
*/
|
|
31
|
+
export declare function isHostThrow(argument: ASTNode | null | undefined, hostThrows: ReadonlyMap<string, ReadonlySet<string>>, context: Rule.RuleContext): boolean;
|
|
32
|
+
//#endregion
|
|
33
|
+
//# sourceMappingURL=host-throws.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e={"@tanstack/react-router":[`redirect`,`notFound`],"@tanstack/router-core":[`redirect`,`notFound`],"react-router":[`redirect`,`redirectDocument`,`replace`,`data`],"react-router-dom":[`redirect`,`redirectDocument`,`replace`,`data`,`json`],"@remix-run/node":[`redirect`,`redirectDocument`,`replace`,`data`,`json`],"@remix-run/cloudflare":[`redirect`,`redirectDocument`,`replace`,`data`,`json`]},t={type:`object`,additionalProperties:{type:`array`,items:{type:`string`}}},n=t=>{let n=/* @__PURE__ */ new Set([...Object.keys(e),...Object.keys(t??{})]);return new Map([...n].map(n=>{let r=t?.[n],i=r!==void 0&&r.length===0?[]:[...e[n]??[],...r??[]];return[n,new Set(i)]}))};function r(e,t){let n=(t.sourceCode.getScope(e).references.find(t=>t.identifier===e)?.resolved)?.defs[0];return n?.type===`ImportBinding`?n:void 0}const i=e=>e.type===`ImportSpecifier`?e.imported.name??e.imported.value:e.type===`ImportDefaultSpecifier`?`default`:void 0;function a(e,t,n){if(e?.type!==`CallExpression`)return!1;let a=e.callee;if(a.type===`Identifier`){let e=r(a,n),o=e?.parent?.source?.value,s=e?i(e.node):void 0;return o!==void 0&&s!==void 0&&t.get(o)?.has(s)===!0}if(a.type!==`MemberExpression`||a.computed||a.object.type!==`Identifier`)return!1;let o=r(a.object,n);if(o?.node.type!==`ImportNamespaceSpecifier`)return!1;let s=o.parent?.source?.value;return s!==void 0&&t.get(s)?.has(a.property.name)===!0}export{e as DEFAULT_HOST_THROWS,t as HOST_THROWS_SCHEMA,n as hostThrowsWith,a as isHostThrow};
|
|
2
|
+
//# sourceMappingURL=host-throws.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"host-throws.js","names":["DEFAULT_HOST_THROWS","HOST_THROWS_SCHEMA","hostThrowsWith","modules","overrides","added","module","names","importOf","def","context","identifier","reference","importedName","specifier","isHostThrow","argument","callee","name","hostThrows"],"sources":["../../src/utils/host-throws.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Router helpers whose return value a loader or route guard throws to redirect or show Not found\n * (#445). The throw is the framework's API, not an error path: returning `Either.left(…)` instead\n * breaks it. Each name was checked against the package's exports on 2026-10-31. React Router 6 loaders\n * import from react-router-dom, and Remix on Workers from @remix-run/cloudflare.\n */\nexport const DEFAULT_HOST_THROWS: Readonly<Record<string, ReadonlyArray<string>>> = {\n \"@tanstack/react-router\": [\"redirect\", \"notFound\"],\n \"@tanstack/router-core\": [\"redirect\", \"notFound\"],\n \"react-router\": [\"redirect\", \"redirectDocument\", \"replace\", \"data\"],\n \"react-router-dom\": [\"redirect\", \"redirectDocument\", \"replace\", \"data\", \"json\"],\n \"@remix-run/node\": [\"redirect\", \"redirectDocument\", \"replace\", \"data\", \"json\"],\n \"@remix-run/cloudflare\": [\"redirect\", \"redirectDocument\", \"replace\", \"data\", \"json\"],\n}\n\nexport const HOST_THROWS_SCHEMA = {\n type: \"object\",\n additionalProperties: { type: \"array\", items: { type: \"string\" } },\n} as const\n\n/**\n * The defaults with a project's own `hostThrows` added: naming a module adds helpers to its defaults,\n * so `{ \"react-router\": [\"myRedirect\"] }` keeps `redirect` and the rest, and `[]` turns that module's\n * defaults off. A module the defaults don't name is added.\n */\nexport const hostThrowsWith = (\n overrides: Readonly<Record<string, ReadonlyArray<string>>> | undefined,\n): ReadonlyMap<string, ReadonlySet<string>> => {\n const modules = new Set([...Object.keys(DEFAULT_HOST_THROWS), ...Object.keys(overrides ?? {})])\n return new Map(\n [...modules].map((module) => {\n const added = overrides?.[module]\n const names =\n added !== undefined && added.length === 0 ? [] : [...(DEFAULT_HOST_THROWS[module] ?? []), ...(added ?? [])]\n return [module, new Set(names)]\n }),\n )\n}\n\ntype ImportDef = {\n readonly type: string\n readonly node: ASTNode\n readonly parent?: ASTNode | null\n}\n\n/** The import an identifier is bound to, through scope, so a local helper of the same name isn't one. */\nfunction importOf(identifier: ASTNode, context: Rule.RuleContext): ImportDef | undefined {\n const variable = context.sourceCode\n .getScope(identifier)\n .references.find((reference) => reference.identifier === identifier)?.resolved\n const def = variable?.defs[0] as unknown as ImportDef | undefined\n return def?.type === \"ImportBinding\" ? def : undefined\n}\n\n/** The name a specifier imports: `redirect` for `import { redirect as go }`. */\nconst importedName = (specifier: ASTNode): string | undefined =>\n specifier.type === \"ImportSpecifier\"\n ? (specifier.imported.name ?? specifier.imported.value)\n : specifier.type === \"ImportDefaultSpecifier\"\n ? \"default\"\n : undefined\n\n/**\n * Is `argument`, the value a `throw` throws, a call to a host helper? `throw redirect(…)` and\n * `throw notFound()` with the name imported from a listed module, under any local name, or\n * `throw Router.redirect(…)` through a namespace import of one.\n */\nexport function isHostThrow(\n argument: ASTNode | null | undefined,\n hostThrows: ReadonlyMap<string, ReadonlySet<string>>,\n context: Rule.RuleContext,\n): boolean {\n if (argument?.type !== \"CallExpression\") return false\n const callee = argument.callee as ASTNode\n if (callee.type === \"Identifier\") {\n const def = importOf(callee, context)\n const module = def?.parent?.source?.value as string | undefined\n const name = def ? importedName(def.node) : undefined\n return module !== undefined && name !== undefined && hostThrows.get(module)?.has(name) === true\n }\n if (callee.type !== \"MemberExpression\" || callee.computed || callee.object.type !== \"Identifier\") return false\n const def = importOf(callee.object as ASTNode, context)\n if (def?.node.type !== \"ImportNamespaceSpecifier\") return false\n const module = def.parent?.source?.value as string | undefined\n return module !== undefined && hostThrows.get(module)?.has(callee.property.name) === true\n}\n"],"mappings":"AAUA,MAAaA,EAAuE,CAClF,yBAA0B,CAAC,WAAY,UAAU,EACjD,wBAAyB,CAAC,WAAY,UAAU,EAChD,eAAgB,CAAC,WAAY,mBAAoB,UAAW,MAAM,EAClE,mBAAoB,CAAC,WAAY,mBAAoB,UAAW,OAAQ,MAAM,EAC9E,kBAAmB,CAAC,WAAY,mBAAoB,UAAW,OAAQ,MAAM,EAC7E,wBAAyB,CAAC,WAAY,mBAAoB,UAAW,OAAQ,MAAM,CACrF,EAEaC,EAAqB,CAChC,KAAM,SACN,qBAAsB,CAAE,KAAM,QAAS,MAAO,CAAE,KAAM,QAAS,CAAE,CACnE,EAOaC,EACX,GAC6C,CAC7C,IAAMC,kBAAU,IAAI,IAAI,CAAC,GAAG,OAAO,KAAKH,CAAmB,EAAG,GAAG,OAAO,KAAKI,GAAa,CAAC,CAAC,CAAC,CAAC,EAC9F,OAAO,IAAI,IACT,CAAC,GAAGD,CAAO,CAAC,CAAC,IAAK,GAAW,CAC3B,IAAME,EAAQD,IAAYE,GACpBC,EACJF,IAAU,IAAA,IAAaA,EAAM,SAAW,EAAI,CAAC,EAAI,CAAC,GAAIL,EAAoBM,IAAW,CAAC,EAAI,GAAID,GAAS,CAAC,CAAE,EAC5G,MAAO,CAACC,EAAQ,IAAI,IAAIC,CAAK,CAAC,CAChC,CAAC,CACH,CACF,EASA,SAASC,EAAS,EAAqB,EAAkD,CAIvF,IAAMC,GAHWC,EAAQ,WACtB,SAASC,CAAU,CAAC,CACpB,WAAW,KAAM,GAAcC,EAAU,aAAeD,CAAU,CAAC,EAAE,SAAA,EAClD,KAAK,GAC3B,OAAOF,GAAK,OAAS,gBAAkBA,EAAM,IAAA,EAC/C,CAGA,MAAMI,EAAgB,GACpBC,EAAU,OAAS,kBACdA,EAAU,SAAS,MAAQA,EAAU,SAAS,MAC/CA,EAAU,OAAS,yBACjB,UACA,IAAA,GAOR,SAAgBC,EACd,EACA,EACA,EACS,CACT,GAAIC,GAAU,OAAS,iBAAkB,MAAO,GAChD,IAAMC,EAASD,EAAS,OACxB,GAAIC,EAAO,OAAS,aAAc,CAChC,IAAMR,EAAMD,EAASS,EAAQP,CAAO,EAC9BJ,EAASG,GAAK,QAAQ,QAAQ,MAC9BS,EAAOT,EAAMI,EAAaJ,EAAI,IAAI,EAAI,IAAA,GAC5C,OAAOH,IAAW,IAAA,IAAaY,IAAS,IAAA,IAAaC,EAAW,IAAIb,CAAM,CAAC,EAAE,IAAIY,CAAI,IAAM,EAC7F,CACA,GAAID,EAAO,OAAS,oBAAsBA,EAAO,UAAYA,EAAO,OAAO,OAAS,aAAc,MAAO,GACzG,IAAMR,EAAMD,EAASS,EAAO,OAAmBP,CAAO,EACtD,GAAID,GAAK,KAAK,OAAS,2BAA4B,MAAO,GAC1D,IAAMH,EAASG,EAAI,QAAQ,QAAQ,MACnC,OAAOH,IAAW,IAAA,IAAaa,EAAW,IAAIb,CAAM,CAAC,EAAE,IAAIW,EAAO,SAAS,IAAI,IAAM,EACvF"}
|
|
@@ -19,6 +19,30 @@ export declare const isExtractableByType: (node: ASTNode, context: Rule.RuleCont
|
|
|
19
19
|
* `undefined` when type information isn't available.
|
|
20
20
|
*/
|
|
21
21
|
export declare const isIOByType: (node: ASTNode, context: Rule.RuleContext) => boolean | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* Can `node`'s value carry a failure that dropping it would lose? Structural: the type, or a member of
|
|
24
|
+
* its union, has `fold` and `isLeft` or `isFailure`. That covers Either, Try, Exit, Validation and
|
|
25
|
+
* Either-shaped wrappers such as a `ServiceResult`, and leaves out Option and List, whose `None` or
|
|
26
|
+
* empty value is no error. An `IO` is left to no-floating-io: it hasn't run, so it holds no failure yet.
|
|
27
|
+
*
|
|
28
|
+
* `undefined` when type information isn't available.
|
|
29
|
+
*/
|
|
30
|
+
export declare const canCarryFailureByType: (node: ASTNode, context: Rule.RuleContext) => boolean | undefined;
|
|
31
|
+
/** Where a functype container sits inside a value, and what it is called. */
|
|
32
|
+
export type ContainerAt = {
|
|
33
|
+
readonly path: string;
|
|
34
|
+
readonly name: string;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* The first functype container inside the value `node` evaluates to, and the path to it: `subscription`,
|
|
38
|
+
* `items[]`, or empty for the whole value. A container is a type with `_tag` and `fold`, which every
|
|
39
|
+
* functype container has and its `toJSON()` envelope doesn't. Walks unions, intersections, array and
|
|
40
|
+
* tuple elements, object properties and string index signatures, up to 4 levels deep, and checks for a
|
|
41
|
+
* container before skipping types declared in node_modules, where functype itself lives (#364).
|
|
42
|
+
*
|
|
43
|
+
* `undefined` when there is none, or when type information isn't available.
|
|
44
|
+
*/
|
|
45
|
+
export declare const containerInsideByType: (node: ASTNode, context: Rule.RuleContext) => ContainerAt | undefined;
|
|
22
46
|
/**
|
|
23
47
|
* Does `node` (an expression) flow into a slot that is typed as an array, a tuple or `any`/`unknown`?
|
|
24
48
|
* That's the expected type TypeScript checks it against: the parameter it is passed to, the property
|
package/dist/utils/type-aware.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=/* @__PURE__ */ new Set([`Iterable`,`AsyncIterable`,`IterableIterator`,`ArrayLike`]),t=e=>{let t=e.sourceCode.parserServices;return t?.program&&t.esTreeNodeToTSNodeMap?t:void 0},n=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);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},r=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),o=a.getNonNullableType(a.getTypeAtLocation(i));return a.getPropertyOfType(o,`runExit`)!==void 0&&a.getPropertyOfType(o,`provideLayer`)!==void 0},i=e=>e.
|
|
1
|
+
const e=/* @__PURE__ */ new Set([`Iterable`,`AsyncIterable`,`IterableIterator`,`ArrayLike`]),t=e=>{let t=e.sourceCode.parserServices;return t?.program&&t.esTreeNodeToTSNodeMap?t:void 0},n=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);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},r=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),o=a.getNonNullableType(a.getTypeAtLocation(i));return a.getPropertyOfType(o,`runExit`)!==void 0&&a.getPropertyOfType(o,`provideLayer`)!==void 0},i=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),o=a.getNonNullableType(a.getTypeAtLocation(i)),s=(e,t)=>a.getPropertyOfType(e,t)!==void 0;return(o.types??[o]).some(e=>s(e,`fold`)&&(s(e,`isLeft`)||s(e,`isFailure`))&&!s(e,`runExit`))},a={LeftOf:`Either`,RightOf:`Either`},o=e=>{let t=(e.aliasSymbol?.name??e.getSymbol?.()?.name)?.replace(/\$\d+$/,``);return t===void 0||t.startsWith(`__`)?`functype container`:a[t]??t},s=e=>{let t=e.getSymbol?.();return t===void 0||t.name.startsWith(`__`)?!1:(t.getDeclarations?.()??[]).some(e=>e.getSourceFile().fileName.includes(`/node_modules/`))},c=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),c=/* @__PURE__ */ new Set,u=e=>a.getPropertyOfType(e,`_tag`)!==void 0&&a.getPropertyOfType(e,`fold`)!==void 0,d=(e,t)=>e===``?t:t.startsWith(`[`)?e+t:`${e}.${t}`,f=(e,t,n)=>{if(n>4||c.has(e)||l(e))return;c.add(e);let r=e;if(u(e))return{path:t,name:o(r)};if(r.isUnionOrIntersection?.()===!0)return(r.types??[]).map(e=>f(e,t,n)).find(e=>e!==void 0);if((r.getCallSignatures?.()??[]).length>0)return;if(a.isArrayLikeType(e)||a.isTupleType(e))return a.getTypeArguments(e).map(e=>f(e,t===``?`[]`:`${t}[]`,n+1)).find(e=>e!==void 0);let p=a.getIndexInfoOfType(e,0)?.type,m=p===void 0?void 0:f(p,d(t,`[key]`),n+1);if(m!==void 0)return m;if(!(r.getSymbol?.()===void 0||s(r)))return a.getPropertiesOfType(e).map(e=>f(a.getTypeOfSymbolAtLocation(e,i),d(t,e.name),n+1)).find(e=>e!==void 0)};return f(a.getTypeAtLocation(i),``,0)},l=e=>e.isTypeParameter?.()===!0,u=e=>{let t=e.parent;if(!t)return null;if((t.type===`CallExpression`||t.type===`NewExpression`)&&t.callee!==e){let n=t.arguments.indexOf(e);return n<0?null:{call:t,argument:e,index:n}}return t.type===`TSAsExpression`||t.type===`TSSatisfiesExpression`||t.type===`ConditionalExpression`&&t.test!==e||t.type===`LogicalExpression`||t.type===`Property`||t.type===`ObjectExpression`||t.type===`ArrayExpression`||t.type===`SpreadElement`?u(t):null},d=(e,t,n)=>{let r=u(n),i=r?t.esTreeNodeToTSNodeMap.get(r.call):void 0,a=i?e.getResolvedSignature(i)?.getDeclaration()?.parameters:void 0;if(!r||!a||a.length===0)return!1;let o=a[Math.min(r.index,a.length-1)];if(o?.type===void 0)return!1;let s=e.getTypeAtLocation(o.type);return(s.types??[s]).some(l)},f=(e,t,n)=>{let r=u(n),i=r?t.esTreeNodeToTSNodeMap.get(r.call):void 0,a=i?e.getResolvedSignature(i):void 0,o=r?t.esTreeNodeToTSNodeMap.get(r.argument):void 0;if(!a||!o)return!1;let s=e.getTypeAtLocation(o),c=t=>t===s||e.isTypeAssignableTo(s,t)&&e.isTypeAssignableTo(t,s),l=(t,n)=>{if(n>3)return!1;if(c(t))return!0;let{types:r,target:i}=t;if(r)return r.some(e=>l(e,n+1));if(i!==void 0&&(e.isTupleType(t)||e.isArrayLikeType(t)))return e.getTypeArguments(t).some(e=>l(e,n+1));let a=e.getAwaitedType(t);return a!==void 0&&a!==t&&l(a,n+1)};return l(e.getReturnTypeOfSignature(a),0)},p=(e,t,n)=>h(n.type)||l(n.type)&&!f(e,t,n.at),m=(t,n,r)=>{if(p(t,n,r))return!0;let{types:i,symbol:a}=r.type;return i?i.some(e=>m(t,n,{type:e,at:r.at})):a?.name!==void 0&&e.has(a.name)?!0:!l(r.type)&&t.isArrayLikeType(r.type)},h=e=>{let{flags:t}=e;return t!==void 0&&!!(t&3)},g=(e,t)=>{let{types:n,symbol:r}=t;return n?n.some(t=>g(e,t)):r?.name===`Array`&&e.isArrayLikeType(t)},_=e=>e.computed?null:e.key?.type===`Identifier`?e.key.name:e.key?.type===`Literal`&&typeof e.key.value==`string`?e.key.value:null,v=(e,t,n,r,i=0)=>{if(i>4)return;let a=t.esTreeNodeToTSNodeMap.get(n),o=a?e.getContextualType(a):void 0;if(o!==void 0)return{type:o,at:n};let s=n.parent;if(s?.type===`ArrowFunctionExpression`&&s.body===n){let n=s.parent;if(n?.type===`VariableDeclarator`&&n.init===s&&n.id?.type===`Identifier`)return(r.sourceCode.getDeclaredVariables(n)[0]?.references??[]).map(e=>e.identifier.parent).filter(e=>e?.type===`CallExpression`).map(n=>v(e,t,n,r,i+1)).find(e=>e!==void 0)}if((s?.type===`CallExpression`||s?.type===`NewExpression`)&&s.callee!==n){let r=s.arguments.indexOf(n),i=t.esTreeNodeToTSNodeMap.get(s),a=r>=0&&i?e.getResolvedSignature(i)?.parameters[r]:void 0;return a===void 0?void 0:{type:e.getTypeOfSymbolAtLocation(a,i),at:n}}let c=s?.type===`Property`&&s.value===n?s.parent:void 0;if(c?.type!==`ObjectExpression`)return;let l=v(e,t,c,r,i+1);if(l===void 0||p(e,t,l))return l;let u=l.type,d=_(s);if(d===null){let r=s.key,i=r?t.esTreeNodeToTSNodeMap.get(r):void 0,o=i?e.getTypeAtLocation(i):void 0,c=o?.value??o?.types?.[0]?.value,l=typeof c==`string`?e.getPropertyOfType(u,c):void 0,d=l===void 0?e.getIndexInfoOfType(u,0)?.type:e.getTypeOfSymbolAtLocation(l,a);return d===void 0?void 0:{type:d,at:n}}let f=e.getPropertyOfType(u,d);return f===void 0?void 0:{type:e.getTypeOfSymbolAtLocation(f,a),at:n}},y=(e,n)=>{let r=t(n);if(!r)return;let i=r.program.getTypeChecker(),a=v(i,r,e,n);if(a!==void 0)return d(i,r,a.at)?!f(i,r,a.at):m(i,r,a)},b=(e,n)=>{let r=t(n);if(!r)return;let i=r.program.getTypeChecker(),a=v(i,r,e,n);return a===void 0||d(i,r,a.at)?!1:g(i,a.type)},x=(e,n)=>{let r=t(n);if(!r)return;let i=r.esTreeNodeToTSNodeMap.get(e);if(!i)return;let a=r.program.getTypeChecker(),o=a.getTypeAtLocation(i);if(h(o))return!0;if(!a.isArrayLikeType(o))return!1;let s=a.getTypeArguments(o)[0];return s!==void 0&&h(s)},S=e=>t(e)!==void 0;export{i as canCarryFailureByType,c as containerInsideByType,y as flowsIntoArraySlot,b as flowsIntoMutableArraySlot,S as hasTypeInformation,n as isExtractableByType,r as isIOByType,x as isUntypedExpression};
|
|
2
2
|
//# sourceMappingURL=type-aware.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"type-aware.js","names":["CONSUMED_COLLECTION_TYPES","typedServices","services","context","isExtractableByType","tsNode","node","checker","type","isIOByType","isTypeParameter","enclosingCall","parent","at","index","isGenericParameterArgument","found","callTs","parameters","declared","annotated","handsArgumentBack","signature","argTs","argType","sameAsArgument","candidate","search","depth","types","member","target","element","awaited","isOpaqueSink","isUntyped","slot","isArrayLikeOrUntyped","symbol","flags","isMutableArrayType","propertyKey","property","expectedSlot","own","declarator","ref","call","parameter","objectLiteral","outerSlot","outer","key","keyNode","keyTs","keyType","literal","named","flowsIntoArraySlot","flowsIntoMutableArraySlot","isUntypedExpression","hasTypeInformation"],"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 getContextualType(node: unknown): TypeLike | undefined\n isArrayLikeType(type: TypeLike): boolean\n getTypeOfSymbolAtLocation(symbol: unknown, node: unknown): TypeLike\n getTypeArguments(type: TypeLike): ReadonlyArray<TypeLike>\n getResolvedSignature(node: unknown): SignatureLike | undefined\n getIndexInfoOfType(type: TypeLike, kind: number): { readonly type: TypeLike } | undefined\n getReturnTypeOfSignature(signature: unknown): TypeLike\n getAwaitedType(type: TypeLike): TypeLike | undefined\n isTupleType(type: TypeLike): boolean\n isTypeAssignableTo(source: TypeLike, target: TypeLike): boolean\n}\n\ntype SignatureLike = {\n readonly parameters: ReadonlyArray<unknown>\n getDeclaration(): { readonly parameters?: ReadonlyArray<unknown> } | undefined\n}\n\n/** `ts.TypeFlags.Any` / `Unknown`, inlined so the plugin needs no runtime `typescript` import. */\nconst ANY_OR_UNKNOWN_FLAGS = 1 | 2\n\n/** Interfaces a consumer reads through rather than keeps: `importKey(…, usages: Iterable<KeyUsage>)`, `new Set(values)`. */\nconst CONSUMED_COLLECTION_TYPES: ReadonlySet<string> = new Set([\n \"Iterable\",\n \"AsyncIterable\",\n \"IterableIterator\",\n \"ArrayLike\",\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\n/**\n * Is `node`'s type a functype `IO`? Structural: the type has both `runExit` and `provideLayer`, which\n * only `IO` carries — `Task`, `Lazy` and the other containers have neither — and has carried since\n * well before 1.9, so older functype versions are recognized too. A union of IOs counts.\n * `any` and `unknown` have no properties, so they don't.\n *\n * `undefined` when type information isn't available.\n */\nexport const isIOByType = (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, \"runExit\") !== undefined &&\n checker.getPropertyOfType(type, \"provideLayer\") !== undefined\n )\n}\n\n/** A slot's expected type and the expression TypeScript computed it for. */\ntype Slot = { readonly type: TypeLike; readonly at: ASTNode }\n\n/**\n * Uses the `Type` object's own predicate rather than a `TypeFlags` bit: TypeScript renumbers its flags\n * between majors (TypeParameter is `1 << 19` in TS 6, `1 << 18` before), and the plugin has no runtime\n * `typescript` import to read them from.\n */\nconst isTypeParameter = (type: TypeLike): boolean =>\n (type as { isTypeParameter?: () => boolean }).isTypeParameter?.() === true\n\n/**\n * `f(…, arg, …)` where `at` is `arg` or sits inside it (an object property, an array element, a spread,\n * a conditional branch, an `as`): the call, the whole argument, and its index.\n */\nconst enclosingCall = (\n at: ASTNode,\n): { readonly call: ASTNode; readonly argument: ASTNode; readonly index: number } | null => {\n const parent = at.parent as ASTNode | undefined\n if (!parent) return null\n if ((parent.type === \"CallExpression\" || parent.type === \"NewExpression\") && parent.callee !== at) {\n const index = (parent.arguments as ReadonlyArray<ASTNode>).indexOf(at)\n return index < 0 ? null : { call: parent, argument: at, index }\n }\n const passesThrough =\n parent.type === \"TSAsExpression\" ||\n parent.type === \"TSSatisfiesExpression\" ||\n (parent.type === \"ConditionalExpression\" && parent.test !== at) ||\n parent.type === \"LogicalExpression\" ||\n parent.type === \"Property\" ||\n parent.type === \"ObjectExpression\" ||\n parent.type === \"ArrayExpression\" ||\n parent.type === \"SpreadElement\"\n return passesThrough ? enclosingCall(parent) : null\n}\n\n/**\n * Is the parameter that `at` is passed to (directly or nested) declared as a type parameter, or a union\n * containing one — `json<T>(data: T)`, `useState<S>(init: S | (() => S))`? Then TypeScript's expected type for `at` is only an echo of what it inferred from\n * `at` itself (`[1, 2]` → `number[]`), not a shape the library demands.\n */\nconst isGenericParameterArgument = (checker: CheckerLike, services: TypedServices, at: ASTNode): boolean => {\n const found = enclosingCall(at)\n const callTs = found ? services.esTreeNodeToTSNodeMap.get(found.call) : undefined\n const parameters = callTs ? checker.getResolvedSignature(callTs)?.getDeclaration()?.parameters : undefined\n if (!found || !parameters || parameters.length === 0) return false\n const declared = parameters[Math.min(found.index, parameters.length - 1)] as { readonly type?: unknown } | undefined\n // The parameter's type annotation node (`T` in `value: T`); asking for the declaration node's type gives `any`.\n if (declared?.type === undefined) return false\n const annotated = checker.getTypeAtLocation(declared.type)\n // React's `useState<S>(init: S | (() => S))`: a union that contains the type parameter is generic too.\n const members = (annotated as { types?: ReadonlyArray<TypeLike> }).types ?? [annotated]\n return members.some(isTypeParameter)\n}\n\n/**\n * Does the generic call around `at` hand the argument straight back to the caller — `useState(init)`\n * returning `[init, set]`, `identity(x)`, a `Promise` of it? Then the shape stays the caller's, and a\n * type parameter isn't a sink. Looks only at the return type itself, union / intersection members,\n * tuple and array elements, and an awaited Promise, not object properties: Hono's `c.json<T>` returns a\n * `Response` that carries a *parsed* copy of `T` for its RPC client, which the caller doesn't get back.\n */\nconst handsArgumentBack = (checker: CheckerLike, services: TypedServices, at: ASTNode): boolean => {\n const found = enclosingCall(at)\n const callTs = found ? services.esTreeNodeToTSNodeMap.get(found.call) : undefined\n const signature = callTs ? checker.getResolvedSignature(callTs) : undefined\n const argTs = found ? services.esTreeNodeToTSNodeMap.get(found.argument) : undefined\n if (!signature || !argTs) return false\n const argType = checker.getTypeAtLocation(argTs)\n const sameAsArgument = (candidate: TypeLike): boolean =>\n candidate === argType ||\n (checker.isTypeAssignableTo(argType, candidate) && checker.isTypeAssignableTo(candidate, argType))\n const search = (type: TypeLike, depth: number): boolean => {\n if (depth > 3) return false\n if (sameAsArgument(type)) return true\n const { types, target } = type as { types?: ReadonlyArray<TypeLike>; target?: unknown }\n if (types) return types.some((member) => search(member, depth + 1))\n if (target !== undefined && (checker.isTupleType(type) || checker.isArrayLikeType(type))) {\n return checker.getTypeArguments(type).some((element) => search(element, depth + 1))\n }\n const awaited = checker.getAwaitedType(type)\n return awaited !== undefined && awaited !== type && search(awaited, depth + 1)\n }\n return search(checker.getReturnTypeOfSignature(signature), 0)\n}\n\n/**\n * Untyped, or a type parameter of a call that doesn't hand the argument back: an object handed to\n * `c.json<T>(data: T)` or `JSON.stringify` goes to a sink. `useState<T>(init: T)` is not one.\n */\nconst isOpaqueSink = (checker: CheckerLike, services: TypedServices, slot: Slot): boolean =>\n isUntyped(slot.type) || (isTypeParameter(slot.type) && !handsArgumentBack(checker, services, slot.at))\n\nconst isArrayLikeOrUntyped = (checker: CheckerLike, services: TypedServices, slot: Slot): boolean => {\n if (isOpaqueSink(checker, services, slot)) return true\n const { types, symbol } = slot.type as { types?: ReadonlyArray<TypeLike>; symbol?: { name?: string } }\n if (types) return types.some((member) => isArrayLikeOrUntyped(checker, services, { type: member, at: slot.at }))\n if (symbol?.name !== undefined && CONSUMED_COLLECTION_TYPES.has(symbol.name)) return true\n return !isTypeParameter(slot.type) && checker.isArrayLikeType(slot.type)\n}\n\nconst isUntyped = (type: TypeLike): boolean => {\n const { flags } = type as { flags?: number }\n return flags !== undefined && (flags & ANY_OR_UNKNOWN_FLAGS) !== 0\n}\n\n/** The mutable `Array` type, as opposed to `ReadonlyArray`: the one a `ReadonlyArray` can't be passed to. */\nconst isMutableArrayType = (checker: CheckerLike, type: TypeLike): boolean => {\n const { types, symbol } = type as { types?: ReadonlyArray<TypeLike>; symbol?: { name?: string } }\n if (types) return types.some((member) => isMutableArrayType(checker, member))\n return symbol?.name === \"Array\" && checker.isArrayLikeType(type)\n}\n\n/** The name a property is written under: `params` in `{ params }`, `parts` in `{ parts: … }` or `{ \"parts\": … }`. */\nconst propertyKey = (property: ASTNode): string | null => {\n if (property.computed) return null\n if (property.key?.type === \"Identifier\") return property.key.name\n return property.key?.type === \"Literal\" && typeof property.key.value === \"string\" ? property.key.value : null\n}\n\n/**\n * The expected type of `node`, looking through object literals when TypeScript gives the value none of\n * its own. Two cases: a shorthand `{ params }` passed to a function, where the expected type is that\n * property's type on the parameter; and `[…]` in `JSON.stringify({ parts: [...] })`, where the object is\n * passed to an `any` parameter, so the whole object is going to an untyped host.\n */\nconst expectedSlot = (\n checker: CheckerLike,\n services: TypedServices,\n node: ASTNode,\n context: Rule.RuleContext,\n depth = 0,\n): Slot | undefined => {\n if (depth > 4) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n const own = tsNode ? checker.getContextualType(tsNode) : undefined\n if (own !== undefined) return { type: own, at: node }\n const parent = node.parent as ASTNode | undefined\n // `const metadata = (url) => ({ … })` with no declared return type: the object goes wherever the\n // calls' results go (`c.json(metadata(url))`), so take the expected type at the first call site.\n if (parent?.type === \"ArrowFunctionExpression\" && parent.body === node) {\n const declarator = parent.parent as ASTNode | undefined\n if (\n declarator?.type === \"VariableDeclarator\" &&\n declarator.init === parent &&\n declarator.id?.type === \"Identifier\"\n ) {\n const variable = context.sourceCode.getDeclaredVariables(declarator)[0]\n const calls = (variable?.references ?? [])\n .map((ref) => (ref.identifier as unknown as ASTNode).parent as ASTNode | undefined)\n .filter((call): call is ASTNode => call?.type === \"CallExpression\")\n return calls\n .map((call) => expectedSlot(checker, services, call, context, depth + 1))\n .find((slot) => slot !== undefined)\n }\n }\n // An argument to an overloaded function (`crypto.subtle.importKey(…, [\"decrypt\"])`) gets no contextual\n // type; the parameter of the overload TypeScript picked is the expected type.\n if ((parent?.type === \"CallExpression\" || parent?.type === \"NewExpression\") && parent.callee !== node) {\n const index = (parent.arguments as ReadonlyArray<ASTNode>).indexOf(node)\n const call = services.esTreeNodeToTSNodeMap.get(parent)\n const parameter = index >= 0 && call ? checker.getResolvedSignature(call)?.parameters[index] : undefined\n return parameter === undefined ? undefined : { type: checker.getTypeOfSymbolAtLocation(parameter, call), at: node }\n }\n const objectLiteral = parent?.type === \"Property\" && parent.value === node ? (parent.parent as ASTNode) : undefined\n if (objectLiteral?.type !== \"ObjectExpression\") return undefined\n const outerSlot = expectedSlot(checker, services, objectLiteral, context, depth + 1)\n if (outerSlot === undefined || isOpaqueSink(checker, services, outerSlot)) return outerSlot\n const outer = outerSlot.type\n const key = propertyKey(parent as ASTNode)\n // `{ [k]: [...] }` (a reduce accumulator keyed by category): the property named by the key's literal\n // type, else the string index signature's type.\n if (key === null) {\n const keyNode = (parent as ASTNode).key\n const keyTs = keyNode ? services.esTreeNodeToTSNodeMap.get(keyNode) : undefined\n const keyType = keyTs\n ? (checker.getTypeAtLocation(keyTs) as { value?: unknown; types?: ReadonlyArray<{ value?: unknown }> })\n : undefined\n const literal = keyType?.value ?? keyType?.types?.[0]?.value\n const named = typeof literal === \"string\" ? checker.getPropertyOfType(outer, literal) : undefined\n const type =\n named !== undefined\n ? checker.getTypeOfSymbolAtLocation(named, tsNode)\n : checker.getIndexInfoOfType(outer, 0)?.type\n return type === undefined ? undefined : { type, at: node }\n }\n const member = checker.getPropertyOfType(outer, key)\n return member === undefined ? undefined : { type: checker.getTypeOfSymbolAtLocation(member, tsNode), at: node }\n}\n\n/**\n * Does `node` (an expression) flow into a slot that is typed as an array, a tuple or `any`/`unknown`?\n * That's the expected type TypeScript checks it against: the parameter it is passed to, the property\n * it initialises, the declared return type. A literal in such a slot is handed to code that requires an\n * array, such as drizzle's `.values([...])` or an index definition, so `List` can't go there. A literal\n * inside an object passed to an `any` parameter (a `JSON.stringify` request body) counts too.\n *\n * `undefined` when type information isn't available, or when there is no expected type (a free-standing\n * literal), so the caller can fall back.\n */\nexport const flowsIntoArraySlot = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const checker = services.program.getTypeChecker()\n const slot = expectedSlot(checker, services, node, context)\n if (slot === undefined) return undefined\n // A bare `T` parameter: a sink unless the call hands the argument straight back (`useState`, `identity`).\n if (isGenericParameterArgument(checker, services, slot.at)) return !handsArgumentBack(checker, services, slot.at)\n return isArrayLikeOrUntyped(checker, services, slot)\n}\n\n/**\n * Does `node` flow into a slot that requires a *mutable* array — a parameter typed `T[]`, such as pg's\n * `query(text, values: unknown[])`, drizzle's `inArray(col, values)` or ReactFlow's `nodes`? There a\n * `ReadonlyArray` won't type-check, so a mutable annotation is what the library demands.\n *\n * `undefined` when type information isn't available.\n */\nexport const flowsIntoMutableArraySlot = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const checker = services.program.getTypeChecker()\n const slot = expectedSlot(checker, services, node, context)\n if (slot === undefined || isGenericParameterArgument(checker, services, slot.at)) return false\n return isMutableArrayType(checker, slot.type)\n}\n\n/**\n * Is `node`'s own type `any` / `unknown`, or an array of them — `JSON.parse(raw)`, `await res.json()`,\n * `raw` after `Array.isArray(raw)` (narrowed to `any[]`)? `undefined` when type information isn't available.\n */\nexport const isUntypedExpression = (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.getTypeAtLocation(tsNode)\n if (isUntyped(type)) return true\n if (!checker.isArrayLikeType(type)) return false\n const element = checker.getTypeArguments(type)[0]\n return element !== undefined && isUntyped(element)\n}\n\n/** Is type-aware linting on for this file (`parserOptions.projectService` or `project`)? */\nexport const hasTypeInformation = (context: Rule.RuleContext): boolean => typedServices(context) !== undefined\n"],"mappings":"AAqCA,MAGMA,kBAAiD,IAAI,IAAI,CAC7D,WACA,gBACA,mBACA,WACF,CAAC,EAOKC,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,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EAA2BR,EAASL,EAAUkC,EAAK,EAAE,EAAU,GAClFI,EAAmBjC,EAAS6B,EAAK,IAAI,CAC9C,EAMawB,GAAuB,EAAe,IAAmD,CACpG,IAAM1D,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,kBAAkBF,CAAM,EAC7C,GAAI8B,EAAU3B,CAAI,EAAG,MAAO,GAC5B,GAAI,CAACD,EAAQ,gBAAgBC,CAAI,EAAG,MAAO,GAC3C,IAAMwB,EAAUzB,EAAQ,iBAAiBC,CAAI,CAAC,CAAC,GAC/C,OAAOwB,IAAY,IAAA,IAAaG,EAAUH,CAAO,CACnD,EAGa6B,EAAsB,GAAuC5D,EAAcE,CAAO,IAAM,IAAA"}
|
|
1
|
+
{"version":3,"file":"type-aware.js","names":["CONSUMED_COLLECTION_TYPES","typedServices","services","context","isExtractableByType","tsNode","node","checker","type","isIOByType","canCarryFailureByType","has","member","name","MEMBER_TO_CONTAINER","containerName","raw","isFromDependency","symbol","declaration","containerInsideByType","seen","isContainer","at","path","step","find","depth","isTypeParameter","shape","h","element","indexed","byIndex","property","enclosingCall","parent","index","isGenericParameterArgument","found","callTs","parameters","declared","annotated","handsArgumentBack","signature","argTs","argType","sameAsArgument","candidate","search","types","target","awaited","isOpaqueSink","isUntyped","slot","isArrayLikeOrUntyped","flags","isMutableArrayType","propertyKey","expectedSlot","own","declarator","ref","call","parameter","objectLiteral","outerSlot","outer","key","keyNode","keyTs","keyType","literal","named","flowsIntoArraySlot","flowsIntoMutableArraySlot","isUntypedExpression","hasTypeInformation"],"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 getContextualType(node: unknown): TypeLike | undefined\n isArrayLikeType(type: TypeLike): boolean\n getTypeOfSymbolAtLocation(symbol: unknown, node: unknown): TypeLike\n getTypeArguments(type: TypeLike): ReadonlyArray<TypeLike>\n getResolvedSignature(node: unknown): SignatureLike | undefined\n getIndexInfoOfType(type: TypeLike, kind: number): { readonly type: TypeLike } | undefined\n getReturnTypeOfSignature(signature: unknown): TypeLike\n getAwaitedType(type: TypeLike): TypeLike | undefined\n isTupleType(type: TypeLike): boolean\n isTypeAssignableTo(source: TypeLike, target: TypeLike): boolean\n getPropertiesOfType(type: TypeLike): ReadonlyArray<{ readonly name: string }>\n}\n\ntype SignatureLike = {\n readonly parameters: ReadonlyArray<unknown>\n getDeclaration(): { readonly parameters?: ReadonlyArray<unknown> } | undefined\n}\n\n/** `ts.TypeFlags.Any` / `Unknown`, inlined so the plugin needs no runtime `typescript` import. */\nconst ANY_OR_UNKNOWN_FLAGS = 1 | 2\n\n/** Interfaces a consumer reads through rather than keeps: `importKey(…, usages: Iterable<KeyUsage>)`, `new Set(values)`. */\nconst CONSUMED_COLLECTION_TYPES: ReadonlySet<string> = new Set([\n \"Iterable\",\n \"AsyncIterable\",\n \"IterableIterator\",\n \"ArrayLike\",\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\n/**\n * Is `node`'s type a functype `IO`? Structural: the type has both `runExit` and `provideLayer`, which\n * only `IO` carries — `Task`, `Lazy` and the other containers have neither — and has carried since\n * well before 1.9, so older functype versions are recognized too. A union of IOs counts.\n * `any` and `unknown` have no properties, so they don't.\n *\n * `undefined` when type information isn't available.\n */\nexport const isIOByType = (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, \"runExit\") !== undefined &&\n checker.getPropertyOfType(type, \"provideLayer\") !== undefined\n )\n}\n\n/**\n * Can `node`'s value carry a failure that dropping it would lose? Structural: the type, or a member of\n * its union, has `fold` and `isLeft` or `isFailure`. That covers Either, Try, Exit, Validation and\n * Either-shaped wrappers such as a `ServiceResult`, and leaves out Option and List, whose `None` or\n * empty value is no error. An `IO` is left to no-floating-io: it hasn't run, so it holds no failure yet.\n *\n * `undefined` when type information isn't available.\n */\nexport const canCarryFailureByType = (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 const has = (member: TypeLike, name: string): boolean => checker.getPropertyOfType(member, name) !== undefined\n const carries = (member: TypeLike): boolean =>\n has(member, \"fold\") && (has(member, \"isLeft\") || has(member, \"isFailure\")) && !has(member, \"runExit\")\n const members = (type as { readonly types?: ReadonlyArray<TypeLike> }).types ?? [type]\n return members.some(carries)\n}\n\n/** Where a functype container sits inside a value, and what it is called. */\nexport type ContainerAt = { readonly path: string; readonly name: string }\n\ntype TypeShape = {\n readonly types?: ReadonlyArray<TypeLike>\n readonly aliasSymbol?: SymbolShape\n isUnionOrIntersection?: () => boolean\n getSymbol?: () => SymbolShape | undefined\n getCallSignatures?: () => ReadonlyArray<unknown>\n}\ntype SymbolShape = {\n readonly name: string\n getDeclarations?: () => ReadonlyArray<{ getSourceFile(): { readonly fileName: string } }> | undefined\n}\n\nconst SERIALIZE_DEPTH = 4\n\n/** A name to show for a container type: `Either`, `Option`, `List`, or the generic fallback. */\n/** Member names TypeScript shows once a union loses its alias (`Either<E, A> | null`), mapped back. */\nconst MEMBER_TO_CONTAINER: Readonly<Record<string, string>> = { LeftOf: \"Either\", RightOf: \"Either\" }\n\nconst containerName = (type: TypeShape): string => {\n // A bundled .d.ts renames a clashing declaration `Map$1`.\n const raw = (type.aliasSymbol?.name ?? type.getSymbol?.()?.name)?.replace(/\\$\\d+$/, \"\")\n if (raw === undefined || raw.startsWith(\"__\")) return \"functype container\"\n return MEMBER_TO_CONTAINER[raw] ?? raw\n}\n\n/** Declared in a dependency or the TypeScript lib: Stripe objects, Date, Request. Never descended into. */\nconst isFromDependency = (type: TypeShape): boolean => {\n // The type's own symbol, not its alias: `Partial<User>` and `Omit<Row, \"x\">` are anonymous mapped\n // types whose alias is declared in TypeScript's lib, and their properties are the caller's.\n const symbol = type.getSymbol?.()\n if (symbol === undefined || symbol.name.startsWith(\"__\")) return false\n return (symbol.getDeclarations?.() ?? []).some((declaration) =>\n declaration.getSourceFile().fileName.includes(\"/node_modules/\"),\n )\n}\n\n/**\n * The first functype container inside the value `node` evaluates to, and the path to it: `subscription`,\n * `items[]`, or empty for the whole value. A container is a type with `_tag` and `fold`, which every\n * functype container has and its `toJSON()` envelope doesn't. Walks unions, intersections, array and\n * tuple elements, object properties and string index signatures, up to 4 levels deep, and checks for a\n * container before skipping types declared in node_modules, where functype itself lives (#364).\n *\n * `undefined` when there is none, or when type information isn't available.\n */\nexport const containerInsideByType = (node: ASTNode, context: Rule.RuleContext): ContainerAt | 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 seen = new Set<TypeLike>()\n const isContainer = (type: TypeLike): boolean =>\n checker.getPropertyOfType(type, \"_tag\") !== undefined && checker.getPropertyOfType(type, \"fold\") !== undefined\n const at = (path: string, step: string): string =>\n path === \"\" ? step : step.startsWith(\"[\") ? path + step : `${path}.${step}`\n\n const find = (type: TypeLike, path: string, depth: number): ContainerAt | undefined => {\n if (depth > SERIALIZE_DEPTH || seen.has(type) || isTypeParameter(type)) return undefined\n seen.add(type)\n const shape = type as TypeShape\n // Before splitting: an Either union has `_tag` and `fold` on every member, and `Stack` is an\n // intersection whose `_tag` and `fold` come from different members.\n if (isContainer(type)) return { path, name: containerName(shape) }\n if (shape.isUnionOrIntersection?.() === true) {\n return (shape.types ?? []).map((member) => find(member, path, depth)).find((h) => h !== undefined)\n }\n if ((shape.getCallSignatures?.() ?? []).length > 0) return undefined\n if (checker.isArrayLikeType(type) || checker.isTupleType(type)) {\n return checker\n .getTypeArguments(type)\n .map((element) => find(element, path === \"\" ? \"[]\" : `${path}[]`, depth + 1))\n .find((h) => h !== undefined)\n }\n // Before the dependency skip: `Record<string, Option<T>>` is declared in TypeScript's lib.\n const indexed = checker.getIndexInfoOfType(type, 0)?.type\n const byIndex = indexed === undefined ? undefined : find(indexed, at(path, \"[key]\"), depth + 1)\n if (byIndex !== undefined) return byIndex\n if (shape.getSymbol?.() === undefined || isFromDependency(shape)) return undefined\n return checker\n .getPropertiesOfType(type)\n .map((property) => find(checker.getTypeOfSymbolAtLocation(property, tsNode), at(path, property.name), depth + 1))\n .find((h) => h !== undefined)\n }\n\n return find(checker.getTypeAtLocation(tsNode), \"\", 0)\n}\n\n/** A slot's expected type and the expression TypeScript computed it for. */\ntype Slot = { readonly type: TypeLike; readonly at: ASTNode }\n\n/**\n * Uses the `Type` object's own predicate rather than a `TypeFlags` bit: TypeScript renumbers its flags\n * between majors (TypeParameter is `1 << 19` in TS 6, `1 << 18` before), and the plugin has no runtime\n * `typescript` import to read them from.\n */\nconst isTypeParameter = (type: TypeLike): boolean =>\n (type as { isTypeParameter?: () => boolean }).isTypeParameter?.() === true\n\n/**\n * `f(…, arg, …)` where `at` is `arg` or sits inside it (an object property, an array element, a spread,\n * a conditional branch, an `as`): the call, the whole argument, and its index.\n */\nconst enclosingCall = (\n at: ASTNode,\n): { readonly call: ASTNode; readonly argument: ASTNode; readonly index: number } | null => {\n const parent = at.parent as ASTNode | undefined\n if (!parent) return null\n if ((parent.type === \"CallExpression\" || parent.type === \"NewExpression\") && parent.callee !== at) {\n const index = (parent.arguments as ReadonlyArray<ASTNode>).indexOf(at)\n return index < 0 ? null : { call: parent, argument: at, index }\n }\n const passesThrough =\n parent.type === \"TSAsExpression\" ||\n parent.type === \"TSSatisfiesExpression\" ||\n (parent.type === \"ConditionalExpression\" && parent.test !== at) ||\n parent.type === \"LogicalExpression\" ||\n parent.type === \"Property\" ||\n parent.type === \"ObjectExpression\" ||\n parent.type === \"ArrayExpression\" ||\n parent.type === \"SpreadElement\"\n return passesThrough ? enclosingCall(parent) : null\n}\n\n/**\n * Is the parameter that `at` is passed to (directly or nested) declared as a type parameter, or a union\n * containing one — `json<T>(data: T)`, `useState<S>(init: S | (() => S))`? Then TypeScript's expected type for `at` is only an echo of what it inferred from\n * `at` itself (`[1, 2]` → `number[]`), not a shape the library demands.\n */\nconst isGenericParameterArgument = (checker: CheckerLike, services: TypedServices, at: ASTNode): boolean => {\n const found = enclosingCall(at)\n const callTs = found ? services.esTreeNodeToTSNodeMap.get(found.call) : undefined\n const parameters = callTs ? checker.getResolvedSignature(callTs)?.getDeclaration()?.parameters : undefined\n if (!found || !parameters || parameters.length === 0) return false\n const declared = parameters[Math.min(found.index, parameters.length - 1)] as { readonly type?: unknown } | undefined\n // The parameter's type annotation node (`T` in `value: T`); asking for the declaration node's type gives `any`.\n if (declared?.type === undefined) return false\n const annotated = checker.getTypeAtLocation(declared.type)\n // React's `useState<S>(init: S | (() => S))`: a union that contains the type parameter is generic too.\n const members = (annotated as { types?: ReadonlyArray<TypeLike> }).types ?? [annotated]\n return members.some(isTypeParameter)\n}\n\n/**\n * Does the generic call around `at` hand the argument straight back to the caller — `useState(init)`\n * returning `[init, set]`, `identity(x)`, a `Promise` of it? Then the shape stays the caller's, and a\n * type parameter isn't a sink. Looks only at the return type itself, union / intersection members,\n * tuple and array elements, and an awaited Promise, not object properties: Hono's `c.json<T>` returns a\n * `Response` that carries a *parsed* copy of `T` for its RPC client, which the caller doesn't get back.\n */\nconst handsArgumentBack = (checker: CheckerLike, services: TypedServices, at: ASTNode): boolean => {\n const found = enclosingCall(at)\n const callTs = found ? services.esTreeNodeToTSNodeMap.get(found.call) : undefined\n const signature = callTs ? checker.getResolvedSignature(callTs) : undefined\n const argTs = found ? services.esTreeNodeToTSNodeMap.get(found.argument) : undefined\n if (!signature || !argTs) return false\n const argType = checker.getTypeAtLocation(argTs)\n const sameAsArgument = (candidate: TypeLike): boolean =>\n candidate === argType ||\n (checker.isTypeAssignableTo(argType, candidate) && checker.isTypeAssignableTo(candidate, argType))\n const search = (type: TypeLike, depth: number): boolean => {\n if (depth > 3) return false\n if (sameAsArgument(type)) return true\n const { types, target } = type as { types?: ReadonlyArray<TypeLike>; target?: unknown }\n if (types) return types.some((member) => search(member, depth + 1))\n if (target !== undefined && (checker.isTupleType(type) || checker.isArrayLikeType(type))) {\n return checker.getTypeArguments(type).some((element) => search(element, depth + 1))\n }\n const awaited = checker.getAwaitedType(type)\n return awaited !== undefined && awaited !== type && search(awaited, depth + 1)\n }\n return search(checker.getReturnTypeOfSignature(signature), 0)\n}\n\n/**\n * Untyped, or a type parameter of a call that doesn't hand the argument back: an object handed to\n * `c.json<T>(data: T)` or `JSON.stringify` goes to a sink. `useState<T>(init: T)` is not one.\n */\nconst isOpaqueSink = (checker: CheckerLike, services: TypedServices, slot: Slot): boolean =>\n isUntyped(slot.type) || (isTypeParameter(slot.type) && !handsArgumentBack(checker, services, slot.at))\n\nconst isArrayLikeOrUntyped = (checker: CheckerLike, services: TypedServices, slot: Slot): boolean => {\n if (isOpaqueSink(checker, services, slot)) return true\n const { types, symbol } = slot.type as { types?: ReadonlyArray<TypeLike>; symbol?: { name?: string } }\n if (types) return types.some((member) => isArrayLikeOrUntyped(checker, services, { type: member, at: slot.at }))\n if (symbol?.name !== undefined && CONSUMED_COLLECTION_TYPES.has(symbol.name)) return true\n return !isTypeParameter(slot.type) && checker.isArrayLikeType(slot.type)\n}\n\nconst isUntyped = (type: TypeLike): boolean => {\n const { flags } = type as { flags?: number }\n return flags !== undefined && (flags & ANY_OR_UNKNOWN_FLAGS) !== 0\n}\n\n/** The mutable `Array` type, as opposed to `ReadonlyArray`: the one a `ReadonlyArray` can't be passed to. */\nconst isMutableArrayType = (checker: CheckerLike, type: TypeLike): boolean => {\n const { types, symbol } = type as { types?: ReadonlyArray<TypeLike>; symbol?: { name?: string } }\n if (types) return types.some((member) => isMutableArrayType(checker, member))\n return symbol?.name === \"Array\" && checker.isArrayLikeType(type)\n}\n\n/** The name a property is written under: `params` in `{ params }`, `parts` in `{ parts: … }` or `{ \"parts\": … }`. */\nconst propertyKey = (property: ASTNode): string | null => {\n if (property.computed) return null\n if (property.key?.type === \"Identifier\") return property.key.name\n return property.key?.type === \"Literal\" && typeof property.key.value === \"string\" ? property.key.value : null\n}\n\n/**\n * The expected type of `node`, looking through object literals when TypeScript gives the value none of\n * its own. Two cases: a shorthand `{ params }` passed to a function, where the expected type is that\n * property's type on the parameter; and `[…]` in `JSON.stringify({ parts: [...] })`, where the object is\n * passed to an `any` parameter, so the whole object is going to an untyped host.\n */\nconst expectedSlot = (\n checker: CheckerLike,\n services: TypedServices,\n node: ASTNode,\n context: Rule.RuleContext,\n depth = 0,\n): Slot | undefined => {\n if (depth > 4) return undefined\n const tsNode = services.esTreeNodeToTSNodeMap.get(node)\n const own = tsNode ? checker.getContextualType(tsNode) : undefined\n if (own !== undefined) return { type: own, at: node }\n const parent = node.parent as ASTNode | undefined\n // `const metadata = (url) => ({ … })` with no declared return type: the object goes wherever the\n // calls' results go (`c.json(metadata(url))`), so take the expected type at the first call site.\n if (parent?.type === \"ArrowFunctionExpression\" && parent.body === node) {\n const declarator = parent.parent as ASTNode | undefined\n if (\n declarator?.type === \"VariableDeclarator\" &&\n declarator.init === parent &&\n declarator.id?.type === \"Identifier\"\n ) {\n const variable = context.sourceCode.getDeclaredVariables(declarator)[0]\n const calls = (variable?.references ?? [])\n .map((ref) => (ref.identifier as unknown as ASTNode).parent as ASTNode | undefined)\n .filter((call): call is ASTNode => call?.type === \"CallExpression\")\n return calls\n .map((call) => expectedSlot(checker, services, call, context, depth + 1))\n .find((slot) => slot !== undefined)\n }\n }\n // An argument to an overloaded function (`crypto.subtle.importKey(…, [\"decrypt\"])`) gets no contextual\n // type; the parameter of the overload TypeScript picked is the expected type.\n if ((parent?.type === \"CallExpression\" || parent?.type === \"NewExpression\") && parent.callee !== node) {\n const index = (parent.arguments as ReadonlyArray<ASTNode>).indexOf(node)\n const call = services.esTreeNodeToTSNodeMap.get(parent)\n const parameter = index >= 0 && call ? checker.getResolvedSignature(call)?.parameters[index] : undefined\n return parameter === undefined ? undefined : { type: checker.getTypeOfSymbolAtLocation(parameter, call), at: node }\n }\n const objectLiteral = parent?.type === \"Property\" && parent.value === node ? (parent.parent as ASTNode) : undefined\n if (objectLiteral?.type !== \"ObjectExpression\") return undefined\n const outerSlot = expectedSlot(checker, services, objectLiteral, context, depth + 1)\n if (outerSlot === undefined || isOpaqueSink(checker, services, outerSlot)) return outerSlot\n const outer = outerSlot.type\n const key = propertyKey(parent as ASTNode)\n // `{ [k]: [...] }` (a reduce accumulator keyed by category): the property named by the key's literal\n // type, else the string index signature's type.\n if (key === null) {\n const keyNode = (parent as ASTNode).key\n const keyTs = keyNode ? services.esTreeNodeToTSNodeMap.get(keyNode) : undefined\n const keyType = keyTs\n ? (checker.getTypeAtLocation(keyTs) as { value?: unknown; types?: ReadonlyArray<{ value?: unknown }> })\n : undefined\n const literal = keyType?.value ?? keyType?.types?.[0]?.value\n const named = typeof literal === \"string\" ? checker.getPropertyOfType(outer, literal) : undefined\n const type =\n named !== undefined\n ? checker.getTypeOfSymbolAtLocation(named, tsNode)\n : checker.getIndexInfoOfType(outer, 0)?.type\n return type === undefined ? undefined : { type, at: node }\n }\n const member = checker.getPropertyOfType(outer, key)\n return member === undefined ? undefined : { type: checker.getTypeOfSymbolAtLocation(member, tsNode), at: node }\n}\n\n/**\n * Does `node` (an expression) flow into a slot that is typed as an array, a tuple or `any`/`unknown`?\n * That's the expected type TypeScript checks it against: the parameter it is passed to, the property\n * it initialises, the declared return type. A literal in such a slot is handed to code that requires an\n * array, such as drizzle's `.values([...])` or an index definition, so `List` can't go there. A literal\n * inside an object passed to an `any` parameter (a `JSON.stringify` request body) counts too.\n *\n * `undefined` when type information isn't available, or when there is no expected type (a free-standing\n * literal), so the caller can fall back.\n */\nexport const flowsIntoArraySlot = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const checker = services.program.getTypeChecker()\n const slot = expectedSlot(checker, services, node, context)\n if (slot === undefined) return undefined\n // A bare `T` parameter: a sink unless the call hands the argument straight back (`useState`, `identity`).\n if (isGenericParameterArgument(checker, services, slot.at)) return !handsArgumentBack(checker, services, slot.at)\n return isArrayLikeOrUntyped(checker, services, slot)\n}\n\n/**\n * Does `node` flow into a slot that requires a *mutable* array — a parameter typed `T[]`, such as pg's\n * `query(text, values: unknown[])`, drizzle's `inArray(col, values)` or ReactFlow's `nodes`? There a\n * `ReadonlyArray` won't type-check, so a mutable annotation is what the library demands.\n *\n * `undefined` when type information isn't available.\n */\nexport const flowsIntoMutableArraySlot = (node: ASTNode, context: Rule.RuleContext): boolean | undefined => {\n const services = typedServices(context)\n if (!services) return undefined\n const checker = services.program.getTypeChecker()\n const slot = expectedSlot(checker, services, node, context)\n if (slot === undefined || isGenericParameterArgument(checker, services, slot.at)) return false\n return isMutableArrayType(checker, slot.type)\n}\n\n/**\n * Is `node`'s own type `any` / `unknown`, or an array of them — `JSON.parse(raw)`, `await res.json()`,\n * `raw` after `Array.isArray(raw)` (narrowed to `any[]`)? `undefined` when type information isn't available.\n */\nexport const isUntypedExpression = (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.getTypeAtLocation(tsNode)\n if (isUntyped(type)) return true\n if (!checker.isArrayLikeType(type)) return false\n const element = checker.getTypeArguments(type)[0]\n return element !== undefined && isUntyped(element)\n}\n\n/** Is type-aware linting on for this file (`parserOptions.projectService` or `project`)? */\nexport const hasTypeInformation = (context: Rule.RuleContext): boolean => typedServices(context) !== undefined\n"],"mappings":"AAsCA,MAGMA,kBAAiD,IAAI,IAAI,CAC7D,WACA,gBACA,mBACA,WACF,CAAC,EAOKC,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,EA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
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.1",
|
|
43
43
|
"@typescript-eslint/rule-tester": "^8.71.0",
|
|
44
44
|
"eslint-config-prettier": "^10.1.8",
|
|
45
|
-
"functype": "^1.
|
|
45
|
+
"functype": "^1.23.0",
|
|
46
46
|
"ts-builds": "^3.4.3",
|
|
47
47
|
"tsdown": "^0.23.0"
|
|
48
48
|
},
|