eslint-plugin-functype 2.110.0 → 2.111.1
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 +33 -14
- package/dist/configs/recommended.d.ts +2 -1
- package/dist/configs/recommended.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-functype-map.js +1 -1
- package/dist/rules/prefer-functype-map.js.map +1 -1
- package/dist/rules/prefer-functype-set.js +1 -1
- package/dist/rules/prefer-functype-set.js.map +1 -1
- package/dist/utils/boundary-tags.d.ts +7 -6
- package/dist/utils/boundary-tags.js +1 -1
- package/dist/utils/boundary-tags.js.map +1 -1
- package/dist/utils/collection-binding.d.ts +21 -0
- package/dist/utils/collection-binding.js +2 -0
- package/dist/utils/collection-binding.js.map +1 -0
- package/dist/utils/readonly-contract.d.ts +5 -0
- package/dist/utils/readonly-contract.js +2 -0
- package/dist/utils/readonly-contract.js.map +1 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -49,11 +49,24 @@ A rule is **`error` in `recommended` once it is right on ~95–99% of real code*
|
|
|
49
49
|
|
|
50
50
|
`prefer-fold` reports only; its rewrite is a suggestion you apply, never an autofix, so `eslint --fix` can't change code on your behalf.
|
|
51
51
|
|
|
52
|
-
##
|
|
52
|
+
## Throwing on purpose: `invariant()` and `@interop`
|
|
53
53
|
|
|
54
|
-
|
|
54
|
+
`prefer-either` reports every `throw`. Two kinds of throw are correct, and each has its own tool:
|
|
55
|
+
|
|
56
|
+
| The throw is… | Use |
|
|
57
|
+
| --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
|
|
58
|
+
| A bug check: the condition can only fail because of a programmer error | `invariant(cond, msg)` from `functype` |
|
|
59
|
+
| 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)` |
|
|
60
|
+
| Anything that can fail in normal operation | return an `Either` |
|
|
55
61
|
|
|
56
62
|
```ts
|
|
63
|
+
import { invariant } from "functype"
|
|
64
|
+
|
|
65
|
+
function deriveRunId(workflowId: string, step: number): string {
|
|
66
|
+
invariant(step >= 0, "step must be non-negative") // a call, not a throw: nothing to report
|
|
67
|
+
return `${workflowId}:${step}`
|
|
68
|
+
}
|
|
69
|
+
|
|
57
70
|
/**
|
|
58
71
|
* Runs the effect, or throws a boxed error.
|
|
59
72
|
*
|
|
@@ -61,24 +74,18 @@ Some code is correct _because_ it isn't FP-shaped: a bridge to a host whose cont
|
|
|
61
74
|
*/
|
|
62
75
|
const runBoxed = async <E, A>(effect: () => IO<never, E, A>): Promise<A> => { … }
|
|
63
76
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
if (step < 0) throw new Error("step must be non-negative")
|
|
67
|
-
…
|
|
68
|
-
}
|
|
77
|
+
// A host throw built from the failure, with no tag at all:
|
|
78
|
+
const value = either.orThrow((left) => new StepError(left.message))
|
|
69
79
|
```
|
|
70
80
|
|
|
71
|
-
|
|
72
|
-
| --------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
|
73
|
-
| `@interop <reason>` | `prefer-either`, `prefer-option`, `prefer-fold`, `prefer-try` | This declaration bridges functype to a host (React, React Query, an SDK) whose contract requires the non-FP shape. |
|
|
74
|
-
| `@invariant <reason>` | `prefer-either` | This declaration throws only for programmer errors, never for expected failures. |
|
|
81
|
+
`invariant()` covers one statement and narrows the condition for the code after it, so a function can mix bug checks with `Either`-returning failures. `@interop` rules:
|
|
75
82
|
|
|
76
|
-
- **Scope:** the tagged declaration and everything nested in it. That can be a function, `const`, method, class field, object property, type alias or interface. A sibling declaration is not covered.
|
|
83
|
+
- **Scope:** the tagged declaration and everything nested in it. That can be a function, `const`, method, class field, object property, type alias or interface. A sibling declaration is not covered. Honored by `prefer-either`, `prefer-option`, `prefer-fold` and `prefer-try`.
|
|
77
84
|
- **The reason is required**, on the same line as the tag. A bare `@interop` exempts nothing.
|
|
78
85
|
- **Only JSDoc (`/** … */`) counts.** A `//` comment mentioning the tag does not.
|
|
79
|
-
- **Opt out** per rule with `allowInteropMarker: false
|
|
86
|
+
- **Opt out** per rule with `allowInteropMarker: false`.
|
|
80
87
|
|
|
81
|
-
Prefer
|
|
88
|
+
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.
|
|
82
89
|
|
|
83
90
|
## Rule options
|
|
84
91
|
|
|
@@ -158,6 +165,18 @@ Not followed: aliases (`const t = s; t.add(x)`), `useRef(new Set()).current.add(
|
|
|
158
165
|
|
|
159
166
|
functype's collections are immutable, so a cache, registry or in-place accumulator can't use them. A native collection that is only read (`.has`, `.get`, iteration) is still reported.
|
|
160
167
|
|
|
168
|
+
**A declared native read-only contract is also exempt.** The rules never report a `ReadonlyMap` / `ReadonlySet` annotation, so they don't report the constructor such an annotation requires. A `new Map(...)` / `new Set(...)` is skipped when its value flows directly into:
|
|
169
|
+
|
|
170
|
+
- a `return` in the nearest function declared to return `ReadonlyMap<…>` (or `Promise<ReadonlyMap<…>>`);
|
|
171
|
+
- the expression body of an arrow function with that return type;
|
|
172
|
+
- a variable, class field or parameter default annotated `ReadonlyMap<…>`;
|
|
173
|
+
- an `as ReadonlyMap<…>` / `satisfies ReadonlyMap<…>` assertion;
|
|
174
|
+
- any of the above through a ternary branch or a `??` / `||` / `&&` operand.
|
|
175
|
+
|
|
176
|
+
This is the escape for an interface that takes a native `ReadonlyMap` — declare the type, don't disable the rule. A callback nested inside such a function doesn't inherit its signature, and a mutable `Map<K, V>` annotation is still reported. To hand a functype `Map` to such an interface, put the conversion in one typed helper: `const toReadonly = <K, V>(m: FMap<K, V>): ReadonlyMap<K, V> => new Map(m)`.
|
|
177
|
+
|
|
178
|
+
**Imports are resolved where `Map` / `Set` is used.** `import { Map as FMap } from "functype"` no longer silences the file: the bare `Map` there is still the native one and is reported, and the suggestions use your name (`FMap(entries)`, `FMap.empty()`) without adding a second import.
|
|
179
|
+
|
|
161
180
|
### `functype/no-imperative-loops` / `functype/prefer-map`
|
|
162
181
|
|
|
163
182
|
These rules don't report loops that have no functional equivalent:
|
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
*
|
|
8
8
|
* Still `warn`, and why:
|
|
9
9
|
* - prefer-option / prefer-either / prefer-try: fire on correct code at serialization boundaries
|
|
10
|
-
* (JSON rows, DTOs) and on
|
|
10
|
+
* (JSON rows, DTOs) and on throws that are correct (bug checks, host contracts). Wire<T> (#325 B),
|
|
11
|
+
* invariant() and @interop (#342) close those; graduating them is a measured decision.
|
|
11
12
|
* - prefer-flatmap / prefer-do-notation: heuristics without type information; precision unmeasured.
|
|
12
13
|
*
|
|
13
14
|
* Graduated with a precision condition: prefer-fold checks functype predicate calls (`isSome()`,
|
|
@@ -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
|
|
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 */\nconst recommendedRules = {\n \"functype/no-let\": \"error\",\n \"functype/no-imperative-loops\": \"error\",\n \"functype/prefer-functype-map\": \"error\",\n \"functype/prefer-functype-set\": \"error\",\n \"functype/prefer-map\": \"error\",\n \"functype/prefer-fold\": \"error\",\n \"functype/prefer-option\": \"warn\",\n \"functype/prefer-either\": \"warn\",\n \"functype/prefer-try\": \"warn\",\n \"functype/prefer-flatmap\": \"warn\",\n \"functype/prefer-do-notation\": \"warn\",\n \"functype/no-get-unsafe\": \"off\",\n \"functype/prefer-list\": \"off\",\n}\n\nexport default recommendedRules\n"],"mappings":"AAiBA,MAAMA,EAAmB,CACvB,kBAAmB,QACnB,+BAAgC,QAChC,+BAAgC,QAChC,+BAAgC,QAChC,sBAAuB,QACvB,uBAAwB,QACxB,yBAA0B,OAC1B,yBAA0B,OAC1B,sBAAuB,OACvB,0BAA2B,OAC3B,8BAA+B,OAC/B,yBAA0B,MAC1B,uBAAwB,KAC1B"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{createImportFixer as t,hasFunctypeSymbol as n}from"../utils/import-fixer.js";function r(e){let t=e?.parent;return t?t.type===`CatchClause`||r(t):!1}const i={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},
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{createImportFixer as t,hasFunctypeSymbol as n}from"../utils/import-fixer.js";function r(e){let t=e?.parent;return t?t.type===`CatchClause`||r(t):!1}const i={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}},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(i){let a=i.options[0]||{},o=a.allowInteropMarker!==!1,s=t=>o&&e(t,`interop`,i.sourceCode),c=a.allowThrowInTests!==!1;function l(){let e=i.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}function u(e){let t=e.parent;return t?f(t)?t:u(t):null}function d(e){let t=e?.returnType?.typeAnnotation;if(!t)return null;let n=i.sourceCode.getText(t);return n.includes(`Either`)?null:n}function f(e){return e?[`FunctionDeclaration`,`FunctionExpression`,`ArrowFunctionExpression`].includes(e.type):!1}function p(e){let t=e.parent;if(!t)return!1;if(t.type===`BlockStatement`&&f(t.parent))return!0;if(t.type===`BlockStatement`&&t.parent?.type===`IfStatement`){let e=t.parent.parent;return e?.type===`BlockStatement`&&f(e.parent)}return!1}return{ThrowStatement(e){if(s(e)||c&&l()||r(e))return;let a=i.sourceCode,o=[];if(p(e)){let r=e.argument,i=a.getText(r),s=r?.type===`NewExpression`&&r.callee?.type===`Identifier`&&r.callee.name===`Error`?i:`new Error(String(${i}))`;o.push({messageId:`suggestEitherLeft`,fix(t){return t.replaceText(e,`return Either.left(${s})`)}}),n(a,`Either`)||o.push({messageId:`suggestAddImport`,data:{symbol:`Either`},fix:t(a,`Either`)})}let f=d(u(e));i.report({node:e,...f===null?{messageId:`preferEitherOverThrow`}:{messageId:`preferEitherReturn`,data:{type:f}},suggest:o})}}}};export{i 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","
|
|
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":"0JAOA,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,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,sBACE,8IACF,mBACE,8JACF,kBAAmB,gCACnB,iBAAkB,qCACpB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QA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6C,CAAC,EAEpD,GAAIH,EAAuBhB,CAAI,EAAG,CAChC,IAAMoB,EAAWpB,EAAK,SAChBqB,EAAUH,EAAW,QAAQE,CAAQ,EAKrCE,EAHJF,GAAU,OAAS,iBACnBA,EAAS,QAAQ,OAAS,cAC1BA,EAAS,OAAO,OAAS,QACKC,EAAU,oBAAoBA,EAAQ,IAEtEF,EAAQ,KAAK,CACX,UAAW,oBACX,IAAI,EAAO,CACT,OAAOI,EAAM,YAAYvB,EAAM,sBAAsBsB,EAAU,EAAE,CACnE,CACF,CAAC,EAEIE,EAAkBN,EAAY,QAAQ,GACzCC,EAAQ,KAAK,CACX,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKM,EAAkBP,EAAY,QAAQ,CAC7C,CAAC,CAEL,CAIA,IAAML,EAAaD,EAAoBF,EAAkBV,CAAI,CAAC,EAC9DG,EAAQ,OAAO,CACb,OACA,GAAIU,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{getFunctypeImportsLegacy as e,isAlreadyUsingFunctype as t}from"../utils/functype-detection.js";import{createImportFixer as n,
|
|
1
|
+
import{getFunctypeImportsLegacy as e,isAlreadyUsingFunctype as t}from"../utils/functype-detection.js";import{createImportFixer as n}from"../utils/import-fixer.js";import{bindingOf as r,functypeLocalName as i}from"../utils/collection-binding.js";import{MAP_MUTATORS as a,annotatesMutatedBinding as o,isMutatedCollection as s}from"../utils/mutable-collection.js";import{flowsIntoReadonlyContract as c}from"../utils/readonly-contract.js";const l={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer functype Map<K, V> over native Map for immutable key-value collections`,recommended:!0},schema:[{type:`object`,properties:{allowInTests:{type:`boolean`,default:!0},allowMutable:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferFunctypeMap:`Prefer functype Map<{{keyType}}, {{valueType}}> over native Map`,preferFunctypeMapLiteral:`Prefer Map.of(...) or Map.empty() over new Map()`,suggestMapEmpty:`Replace with {{name}}.empty()`,suggestMapOf:`Replace with {{name}}.of(...)`,suggestMapFrom:`Replace with {{name}}(...)`,suggestUseLocalName:`Replace with {{name}}`,suggestAddImport:`Add {{symbol}} import from functype`}},create(l){let u=l.options[0]||{},d=u.allowInTests!==!1,f=u.allowMutable!==!1;function p(){let e=l.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}let m=e(l);return{NewExpression(e){if(d&&p()||!e.callee||e.callee.type!==`Identifier`||e.callee.name!==`Map`||f&&s(e,a,l.sourceCode)||r(e.callee,`Map`,l.sourceCode)!==`native`||c(e,`ReadonlyMap`)||t(e,m))return;let o=l.sourceCode,u=i(o,`Map`),h=u??`Map`,g=e.arguments,_=[];if(g.length===0)_.push({messageId:`suggestMapEmpty`,data:{name:h},fix(t){return t.replaceText(e,`${h}.empty()`)}});else if(g.length===1&&g[0].type===`ArrayExpression`){let t=g[0].elements.map(e=>o.getText(e)).join(`, `);_.push({messageId:`suggestMapOf`,data:{name:h},fix(n){return n.replaceText(e,`${h}.of(${t})`)}})}else if(g.length===1){let t=o.getText(g[0]);_.push({messageId:`suggestMapFrom`,data:{name:h},fix(n){return n.replaceText(e,`${h}(${t})`)}})}else _.push({messageId:`suggestMapEmpty`,data:{name:h},fix(t){return t.replaceText(e,`${h}.empty()`)}});u===null&&_.push({messageId:`suggestAddImport`,data:{symbol:`Map`},fix:n(o,`Map`)}),l.report({node:e,messageId:`preferFunctypeMapLiteral`,suggest:_})},TSTypeReference(e){if(d&&p()||!e.typeName)return;let t=l.sourceCode;if((e.typeName.type===`Identifier`?e.typeName.name:t.getText(e.typeName))!==`Map`||f&&o(e,a,l.sourceCode)||e.typeName.type===`Identifier`&&r(e.typeName,`Map`,l.sourceCode)!==`native`)return;let s=e.typeArguments?.params??e.typeParameters?.params,c=s?.[0]?t.getText(s[0]):`K`,u=s&&s.length>=2?t.getText(s[1]):`V`,m=i(t,`Map`),h=m===null?[{messageId:`suggestAddImport`,data:{symbol:`Map`},fix:n(t,`Map`)}]:[{messageId:`suggestUseLocalName`,data:{name:m},fix:t=>t.replaceText(e.typeName,m)}];l.report({node:e,messageId:`preferFunctypeMap`,data:{keyType:c,valueType:u},suggest:h})}}}};export{l as default};
|
|
2
2
|
//# sourceMappingURL=prefer-functype-map.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-functype-map.js","names":["rule","options","context","allowInTests","allowMutable","isInTestFile","filename","functypeImports","getFunctypeImportsLegacy","isMapImportedFromFunctype","hasFunctypeSymbol","node","isMutatedCollection","MAP_MUTATORS","isAlreadyUsingFunctype","sourceCode","args","suggestions","fixer","mapOfArgs","el","argText","createImportFixer","annotatesMutatedBinding","typeParams","keyType","valueType"],"sources":["../../src/rules/prefer-functype-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, MAP_MUTATORS } from \"../utils/mutable-collection\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functype Map<K, V> over native Map for immutable key-value collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowMutable: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFunctypeMap: \"Prefer functype Map<{{keyType}}, {{valueType}}> over native Map\",\n preferFunctypeMapLiteral: \"Prefer Map.of(...) or Map.empty() over new Map()\",\n suggestMapEmpty: \"Replace with Map.empty()\",\n suggestMapOf: \"Replace with Map.of(...)\",\n suggestMapFrom: \"Replace with Map(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n // A native Map the code mutates on purpose (cache, registry, accumulator) is a deliberate choice —\n // functype's Map is immutable and cannot express it (#324).\n const allowMutable = options.allowMutable !== 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 const functypeImports = getFunctypeImportsLegacy(context)\n\n function isMapImportedFromFunctype(): boolean {\n return hasFunctypeSymbol(context.sourceCode, \"Map\")\n }\n\n return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // Only flag `new Map(...)` calls\n if (!node.callee || node.callee.type !== \"Identifier\" || node.callee.name !== \"Map\") return\n\n if (allowMutable && isMutatedCollection(node, MAP_MUTATORS, context.sourceCode)) return\n\n // Skip if Map is already imported from functype\n if (isMapImportedFromFunctype()) return\n\n // Skip if already using functype\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const args = node.arguments as ASTNode[]\n\n const suggestions: Rule.SuggestionReportDescriptor[] = []\n\n if (args.length === 0) {\n // new Map() → Map.empty()\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n fix(fixer) {\n return fixer.replaceText(node, \"Map.empty()\")\n },\n })\n } else if (args.length === 1 && args[0].type === \"ArrayExpression\") {\n // new Map([[\"a\", 1], [\"b\", 2]]) → Map.of([\"a\", 1], [\"b\", 2])\n const arrayArg = args[0] as ASTNode\n const elements = arrayArg.elements as ASTNode[]\n const tupleTexts = elements.map((el: ASTNode) => sourceCode.getText(el))\n const mapOfArgs = tupleTexts.join(\", \")\n suggestions.push({\n messageId: \"suggestMapOf\",\n fix(fixer) {\n return fixer.replaceText(node, `Map.of(${mapOfArgs})`)\n },\n })\n } else if (args.length === 1) {\n // new Map(someVar) → Map(someVar)\n const argText = sourceCode.getText(args[0])\n suggestions.push({\n messageId: \"suggestMapFrom\",\n fix(fixer) {\n return fixer.replaceText(node, `Map(${argText})`)\n },\n })\n } else {\n // Generic fallback for any other args\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n fix(fixer) {\n return fixer.replaceText(node, \"Map.empty()\")\n },\n })\n }\n\n if (!isMapImportedFromFunctype()) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Map\" },\n fix: createImportFixer(sourceCode, \"Map\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferFunctypeMapLiteral\",\n suggest: suggestions,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (!node.typeName) return\n\n const sourceCode = context.sourceCode\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Map\") return\n\n if (allowMutable && annotatesMutatedBinding(node, MAP_MUTATORS, context.sourceCode)) return\n\n // Skip if Map is already imported from functype\n if (isMapImportedFromFunctype()) return\n\n // Extract key/value type params if present (typeArguments for newer TS-ESLint, typeParameters for older)\n const typeParams = node.typeArguments?.params ?? node.typeParameters?.params\n const keyType = typeParams?.[0] ? sourceCode.getText(typeParams[0]) : \"K\"\n const valueType = typeParams && typeParams.length >= 2 ? sourceCode.getText(typeParams[1]) : \"V\"\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestAddImport\",\n data: { symbol: \"Map\" },\n fix: createImportFixer(sourceCode, \"Map\"),\n },\n ]\n\n context.report({\n node,\n messageId: \"preferFunctypeMap\",\n data: { keyType, valueType },\n suggest: suggestions,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"8SAOA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CAC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AEAb,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,UAAS,WAAU,EAC3B,QAASe,CACX,CAAC,CACH,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-functype-map.js","names":["rule","options","context","allowInTests","allowMutable","isInTestFile","filename","functypeImports","getFunctypeImportsLegacy","node","isMutatedCollection","MAP_MUTATORS","bindingOf","flowsIntoReadonlyContract","isAlreadyUsingFunctype","sourceCode","imported","functypeLocalName","name","args","suggestions","fixer","mapOfArgs","el","argText","createImportFixer","annotatesMutatedBinding","typeParams","keyType","valueType"],"sources":["../../src/rules/prefer-functype-map.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { bindingOf, functypeLocalName } from \"../utils/collection-binding\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, MAP_MUTATORS } from \"../utils/mutable-collection\"\nimport { flowsIntoReadonlyContract } from \"../utils/readonly-contract\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functype Map<K, V> over native Map for immutable key-value collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowMutable: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFunctypeMap: \"Prefer functype Map<{{keyType}}, {{valueType}}> over native Map\",\n preferFunctypeMapLiteral: \"Prefer Map.of(...) or Map.empty() over new Map()\",\n suggestMapEmpty: \"Replace with {{name}}.empty()\",\n suggestMapOf: \"Replace with {{name}}.of(...)\",\n suggestMapFrom: \"Replace with {{name}}(...)\",\n suggestUseLocalName: \"Replace with {{name}}\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n // A native Map the code mutates on purpose (cache, registry, accumulator) is a deliberate choice —\n // functype's Map is immutable and cannot express it (#324).\n const allowMutable = options.allowMutable !== 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 const functypeImports = getFunctypeImportsLegacy(context)\n\n return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // Only flag `new Map(...)` calls\n if (!node.callee || node.callee.type !== \"Identifier\" || node.callee.name !== \"Map\") return\n\n if (allowMutable && isMutatedCollection(node, MAP_MUTATORS, context.sourceCode)) return\n\n // `Map` may be functype's import (under any name), a local shadow, or the native built-in (#350).\n if (bindingOf(node.callee, \"Map\", context.sourceCode) !== \"native\") return\n\n // A native Map flowing into a declared `ReadonlyMap` contract is what that contract requires (#350).\n if (flowsIntoReadonlyContract(node, \"ReadonlyMap\")) return\n\n // Skip if already using functype\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const imported = functypeLocalName(sourceCode, \"Map\")\n const name = imported ?? \"Map\"\n const args = node.arguments as ASTNode[]\n\n const suggestions: Rule.SuggestionReportDescriptor[] = []\n\n if (args.length === 0) {\n // new Map() → Map.empty()\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n } else if (args.length === 1 && args[0].type === \"ArrayExpression\") {\n // new Map([[\"a\", 1], [\"b\", 2]]) → Map.of([\"a\", 1], [\"b\", 2])\n const arrayArg = args[0] as ASTNode\n const elements = arrayArg.elements as ASTNode[]\n const tupleTexts = elements.map((el: ASTNode) => sourceCode.getText(el))\n const mapOfArgs = tupleTexts.join(\", \")\n suggestions.push({\n messageId: \"suggestMapOf\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.of(${mapOfArgs})`)\n },\n })\n } else if (args.length === 1) {\n // new Map(someVar) → Map(someVar)\n const argText = sourceCode.getText(args[0])\n suggestions.push({\n messageId: \"suggestMapFrom\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}(${argText})`)\n },\n })\n } else {\n // Generic fallback for any other args\n suggestions.push({\n messageId: \"suggestMapEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n }\n\n if (imported === null) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Map\" },\n fix: createImportFixer(sourceCode, \"Map\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferFunctypeMapLiteral\",\n suggest: suggestions,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (!node.typeName) return\n\n const sourceCode = context.sourceCode\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Map\") return\n\n if (allowMutable && annotatesMutatedBinding(node, MAP_MUTATORS, context.sourceCode)) return\n\n if (node.typeName.type === \"Identifier\" && bindingOf(node.typeName, \"Map\", context.sourceCode) !== \"native\")\n return\n\n // Extract key/value type params if present (typeArguments for newer TS-ESLint, typeParameters for older)\n const typeParams = node.typeArguments?.params ?? node.typeParameters?.params\n const keyType = typeParams?.[0] ? sourceCode.getText(typeParams[0]) : \"K\"\n const valueType = typeParams && typeParams.length >= 2 ? sourceCode.getText(typeParams[1]) : \"V\"\n\n // Already imported under another name (`Map as FMap`): point at that name instead of adding a\n // second import that would shadow the native `Map` the rest of the file uses.\n const imported = functypeLocalName(sourceCode, \"Map\")\n const suggestions: Rule.SuggestionReportDescriptor[] =\n imported === null\n ? [{ messageId: \"suggestAddImport\", data: { symbol: \"Map\" }, fix: createImportFixer(sourceCode, \"Map\") }]\n : [\n {\n messageId: \"suggestUseLocalName\",\n data: { name: imported },\n fix: (fixer) => fixer.replaceText(node.typeName, imported),\n },\n ]\n\n context.report({\n node,\n messageId: \"preferFunctypeMap\",\n data: { keyType, valueType },\n suggest: suggestions,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"mbASA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,gFACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,EACA,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,kBAAmB,kEACnB,yBAA0B,mDAC1B,gBAAiB,gCACjB,aAAc,gCACd,eAAgB,6BAChB,oBAAqB,wBACrB,iBAAkB,qCACpB,CACF,EAEA,OAAO,EAAS,CACd,IAAMC,EAAUC,EAAQ,QAAQ,IAAM,CAAC,EACjCC,EAAeF,EAAQ,eAAiB,GAGxCG,EAAeH,EAAQ,eAAiB,GAE9C,SAASI,GAAe,CACtB,IAAMC,EAAWJ,EAAQ,SACzB,MACE,kCAAkC,KAAKI,CAAQ,GAC/CA,EAAS,SAAS,WAAW,GAC7BA,EAAS,SAAS,QAAQ,GAC1BA,EAAS,SAAS,SAAS,CAE/B,CAEA,IAAMC,EAAkBC,EAAyBN,CAAO,EAExD,MAAO,CACL,cAAc,EAAe,CAe3B,GAdIC,GAAgBE,EAAa,GAG7B,CAACI,EAAK,QAAUA,EAAK,OAAO,OAAS,cAAgBA,EAAK,OAAO,OAAS,OAE1EL,GAAgBM,EAAoBD,EAAME,EAAcT,EAAQ,UAAU,GAG1EU,EAAUH,EAAK,OAAQ,MAAOP,EAAQ,UAAU,IAAM,UAGtDW,EAA0BJ,EAAM,aAAa,GAG7CK,EAAuBL,EAAMF,CAAe,EAAG,OAEnD,IAAMQ,EAAab,EAAQ,WACrBc,EAAWC,EAAkBF,EAAY,KAAK,EAC9CG,EAAOF,GAAY,MAC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S,aAAeA,EAAK,SAAS,KAAOM,EAAW,QAAQN,EAAK,QAAQ,KAE3F,OAEbL,GAAgBsB,EAAwBjB,EAAME,EAAcT,EAAQ,UAAU,GAE9EO,EAAK,SAAS,OAAS,cAAgBG,EAAUH,EAAK,SAAU,MAAOP,EAAQ,UAAU,IAAM,SACjG,OAGF,IAAMyB,EAAalB,EAAK,eAAe,QAAUA,EAAK,gBAAgB,OAChEmB,EAAUD,IAAa,GAAKZ,EAAW,QAAQY,EAAW,EAAE,EAAI,IAChEE,EAAYF,GAAcA,EAAW,QAAU,EAAIZ,EAAW,QAAQY,EAAW,EAAE,EAAI,IAIvFX,EAAWC,EAAkBF,EAAY,KAAK,EAC9CK,EACJJ,IAAa,KACT,CAAC,CAAE,UAAW,mBAAoB,KAAM,CAAE,OAAQ,KAAM,EAAG,IAAKS,EAAkBV,EAAY,KAAK,CAAE,CAAC,EACtG,CACE,CACE,UAAW,sBACX,KAAM,CAAE,KAAMC,CAAS,EACvB,IAAM,GAAUK,EAAM,YAAYZ,EAAK,SAAUO,CAAQ,CAC3D,CACF,EAENd,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,UAAS,WAAU,EAC3B,QAASkB,CACX,CAAC,CACH,CACF,CACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getFunctypeImportsLegacy as e,isAlreadyUsingFunctype as t}from"../utils/functype-detection.js";import{createImportFixer as n,
|
|
1
|
+
import{getFunctypeImportsLegacy as e,isAlreadyUsingFunctype as t}from"../utils/functype-detection.js";import{createImportFixer as n}from"../utils/import-fixer.js";import{bindingOf as r,functypeLocalName as i}from"../utils/collection-binding.js";import{SET_MUTATORS as a,annotatesMutatedBinding as o,isMutatedCollection as s}from"../utils/mutable-collection.js";import{flowsIntoReadonlyContract as c}from"../utils/readonly-contract.js";const l={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer functype Set<T> over native Set for immutable collections`,recommended:!0},schema:[{type:`object`,properties:{allowInTests:{type:`boolean`,default:!0},allowMutable:{type:`boolean`,default:!0}},additionalProperties:!1}],messages:{preferFunctypeSet:`Prefer functype Set<{{type}}> over native Set`,preferFunctypeSetLiteral:`Prefer Set.of(...) or Set.empty() over new Set()`,suggestSetEmpty:`Replace with {{name}}.empty()`,suggestSetOf:`Replace with {{name}}.of(...)`,suggestSetFrom:`Replace with {{name}}(...)`,suggestUseLocalName:`Replace with {{name}}`,suggestAddImport:`Add {{symbol}} import from functype`}},create(l){let u=l.options[0]||{},d=u.allowInTests!==!1,f=u.allowMutable!==!1;function p(){let e=l.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}let m=e(l);return{NewExpression(e){if(d&&p()||!e.callee||e.callee.type!==`Identifier`||e.callee.name!==`Set`||f&&s(e,a,l.sourceCode)||r(e.callee,`Set`,l.sourceCode)!==`native`||c(e,`ReadonlySet`)||t(e,m))return;let o=l.sourceCode,u=i(o,`Set`),h=u??`Set`,g=e.arguments||[],_=[];if(g.length===0)_.push({messageId:`suggestSetEmpty`,data:{name:h},fix(t){return t.replaceText(e,`${h}.empty()`)}});else if(g.length===1&&g[0].type===`ArrayExpression`){let t=(g[0].elements||[]).map(e=>o.getText(e)).join(`, `);_.push({messageId:`suggestSetOf`,data:{name:h},fix(n){return n.replaceText(e,`${h}.of(${t})`)}})}else if(g.length===1){let t=o.getText(g[0]);_.push({messageId:`suggestSetFrom`,data:{name:h},fix(n){return n.replaceText(e,`${h}(${t})`)}})}else _.push({messageId:`suggestSetEmpty`,data:{name:h},fix(t){return t.replaceText(e,`${h}.empty()`)}});u===null&&_.push({messageId:`suggestAddImport`,data:{symbol:`Set`},fix:n(o,`Set`)}),l.report({node:e,messageId:`preferFunctypeSetLiteral`,suggest:_})},TSTypeReference(e){if(d&&p()||!e.typeName)return;let t=l.sourceCode;if((e.typeName.type===`Identifier`?e.typeName.name:t.getText(e.typeName))!==`Set`||f&&o(e,a,l.sourceCode)||e.typeName.type===`Identifier`&&r(e.typeName,`Set`,l.sourceCode)!==`native`)return;let s=e.typeParameters?.params?.[0]??e.typeArguments?.params?.[0],c=s?t.getText(s):`T`,u=i(t,`Set`),m=u===null?[{messageId:`suggestAddImport`,data:{symbol:`Set`},fix:n(t,`Set`)}]:[{messageId:`suggestUseLocalName`,data:{name:u},fix:t=>t.replaceText(e.typeName,u)}];l.report({node:e,messageId:`preferFunctypeSet`,data:{type:c},suggest:m})}}}};export{l as default};
|
|
2
2
|
//# sourceMappingURL=prefer-functype-set.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-functype-set.js","names":["rule","options","context","allowInTests","allowMutable","isInTestFile","filename","functypeImports","getFunctypeImportsLegacy","isSetImportedFromFunctype","hasFunctypeSymbol","node","isMutatedCollection","SET_MUTATORS","isAlreadyUsingFunctype","sourceCode","args","suggestions","fixer","argsText","el","argText","createImportFixer","annotatesMutatedBinding","typeParamNode","typeParam"],"sources":["../../src/rules/prefer-functype-set.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, SET_MUTATORS } from \"../utils/mutable-collection\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functype Set<T> over native Set for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowMutable: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFunctypeSet: \"Prefer functype Set<{{type}}> over native Set\",\n preferFunctypeSetLiteral: \"Prefer Set.of(...) or Set.empty() over new Set()\",\n suggestSetEmpty: \"Replace with Set.empty()\",\n suggestSetOf: \"Replace with Set.of(...)\",\n suggestSetFrom: \"Replace with Set(...)\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n // A native Set the code mutates on purpose (cache, registry, accumulator) is a deliberate choice —\n // functype's Set is immutable and cannot express it (#324).\n const allowMutable = options.allowMutable !== 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 const functypeImports = getFunctypeImportsLegacy(context)\n\n function isSetImportedFromFunctype() {\n return hasFunctypeSymbol(context.sourceCode, \"Set\")\n }\n\n return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // Only handle `new Set(...)` calls\n if (!node.callee || node.callee.type !== \"Identifier\" || node.callee.name !== \"Set\") return\n\n if (allowMutable && isMutatedCollection(node, SET_MUTATORS, context.sourceCode)) return\n\n // Skip if Set is already imported from functype\n if (isSetImportedFromFunctype()) return\n\n // Skip if already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const args = node.arguments || []\n const suggestions: Rule.SuggestionReportDescriptor[] = []\n\n if (args.length === 0) {\n // new Set() → Set.empty()\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n fix(fixer) {\n return fixer.replaceText(node, \"Set.empty()\")\n },\n })\n } else if (args.length === 1 && args[0].type === \"ArrayExpression\") {\n // new Set([\"a\", \"b\", \"c\"]) → Set.of(\"a\", \"b\", \"c\")\n const arrayNode = args[0]\n const elements = arrayNode.elements || []\n const elementTexts = elements.map((el: ASTNode) => sourceCode.getText(el))\n const argsText = elementTexts.join(\", \")\n suggestions.push({\n messageId: \"suggestSetOf\",\n fix(fixer) {\n return fixer.replaceText(node, `Set.of(${argsText})`)\n },\n })\n } else if (args.length === 1) {\n // new Set(someVar) → Set(someVar)\n const argText = sourceCode.getText(args[0])\n suggestions.push({\n messageId: \"suggestSetFrom\",\n fix(fixer) {\n return fixer.replaceText(node, `Set(${argText})`)\n },\n })\n } else {\n // Fallback for unexpected cases\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n fix(fixer) {\n return fixer.replaceText(node, \"Set.empty()\")\n },\n })\n }\n\n if (!isSetImportedFromFunctype()) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Set\" },\n fix: createImportFixer(sourceCode, \"Set\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferFunctypeSetLiteral\",\n suggest: suggestions,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (!node.typeName) return\n\n const sourceCode = context.sourceCode\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Set\") return\n\n if (allowMutable && annotatesMutatedBinding(node, SET_MUTATORS, context.sourceCode)) return\n\n // Skip if Set is already imported from functype\n if (isSetImportedFromFunctype()) return\n\n // Extract type parameter if present (typeArguments for newer TS-ESLint, typeParameters for older)\n const typeParamNode = node.typeParameters?.params?.[0] ?? node.typeArguments?.params?.[0]\n const typeParam = typeParamNode ? sourceCode.getText(typeParamNode) : \"T\"\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestAddImport\",\n data: { symbol: \"Set\" },\n fix: createImportFixer(sourceCode, \"Set\"),\n },\n ]\n\n context.report({\n node,\n messageId: \"preferFunctypeSet\",\n data: { type: typeParam },\n suggest: suggestions,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"8SAOA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,mEACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QA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":"prefer-functype-set.js","names":["rule","options","context","allowInTests","allowMutable","isInTestFile","filename","functypeImports","getFunctypeImportsLegacy","node","isMutatedCollection","SET_MUTATORS","bindingOf","flowsIntoReadonlyContract","isAlreadyUsingFunctype","sourceCode","imported","functypeLocalName","name","args","suggestions","fixer","argsText","el","argText","createImportFixer","annotatesMutatedBinding","typeParamNode","typeParam"],"sources":["../../src/rules/prefer-functype-set.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { bindingOf, functypeLocalName } from \"../utils/collection-binding\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype } from \"../utils/functype-detection\"\nimport { createImportFixer } from \"../utils/import-fixer\"\nimport { annotatesMutatedBinding, isMutatedCollection, SET_MUTATORS } from \"../utils/mutable-collection\"\nimport { flowsIntoReadonlyContract } from \"../utils/readonly-contract\"\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer functype Set<T> over native Set for immutable collections\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInTests: {\n type: \"boolean\",\n default: true,\n },\n allowMutable: {\n type: \"boolean\",\n default: true,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferFunctypeSet: \"Prefer functype Set<{{type}}> over native Set\",\n preferFunctypeSetLiteral: \"Prefer Set.of(...) or Set.empty() over new Set()\",\n suggestSetEmpty: \"Replace with {{name}}.empty()\",\n suggestSetOf: \"Replace with {{name}}.of(...)\",\n suggestSetFrom: \"Replace with {{name}}(...)\",\n suggestUseLocalName: \"Replace with {{name}}\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowInTests = options.allowInTests !== false\n // A native Set the code mutates on purpose (cache, registry, accumulator) is a deliberate choice —\n // functype's Set is immutable and cannot express it (#324).\n const allowMutable = options.allowMutable !== 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 const functypeImports = getFunctypeImportsLegacy(context)\n\n return {\n NewExpression(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n // Only handle `new Set(...)` calls\n if (!node.callee || node.callee.type !== \"Identifier\" || node.callee.name !== \"Set\") return\n\n if (allowMutable && isMutatedCollection(node, SET_MUTATORS, context.sourceCode)) return\n\n // `Set` may be functype's import (under any name), a local shadow, or the native built-in (#350).\n if (bindingOf(node.callee, \"Set\", context.sourceCode) !== \"native\") return\n\n // A native Set flowing into a declared `ReadonlySet` contract is what that contract requires (#350).\n if (flowsIntoReadonlyContract(node, \"ReadonlySet\")) return\n\n // Skip if already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const imported = functypeLocalName(sourceCode, \"Set\")\n const name = imported ?? \"Set\"\n const args = node.arguments || []\n const suggestions: Rule.SuggestionReportDescriptor[] = []\n\n if (args.length === 0) {\n // new Set() → Set.empty()\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n } else if (args.length === 1 && args[0].type === \"ArrayExpression\") {\n // new Set([\"a\", \"b\", \"c\"]) → Set.of(\"a\", \"b\", \"c\")\n const arrayNode = args[0]\n const elements = arrayNode.elements || []\n const elementTexts = elements.map((el: ASTNode) => sourceCode.getText(el))\n const argsText = elementTexts.join(\", \")\n suggestions.push({\n messageId: \"suggestSetOf\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.of(${argsText})`)\n },\n })\n } else if (args.length === 1) {\n // new Set(someVar) → Set(someVar)\n const argText = sourceCode.getText(args[0])\n suggestions.push({\n messageId: \"suggestSetFrom\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}(${argText})`)\n },\n })\n } else {\n // Fallback for unexpected cases\n suggestions.push({\n messageId: \"suggestSetEmpty\",\n data: { name },\n fix(fixer) {\n return fixer.replaceText(node, `${name}.empty()`)\n },\n })\n }\n\n if (imported === null) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Set\" },\n fix: createImportFixer(sourceCode, \"Set\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferFunctypeSetLiteral\",\n suggest: suggestions,\n })\n },\n\n TSTypeReference(node: ASTNode) {\n if (allowInTests && isInTestFile()) return\n\n if (!node.typeName) return\n\n const sourceCode = context.sourceCode\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Set\") return\n\n if (allowMutable && annotatesMutatedBinding(node, SET_MUTATORS, context.sourceCode)) return\n\n if (node.typeName.type === \"Identifier\" && bindingOf(node.typeName, \"Set\", context.sourceCode) !== \"native\")\n return\n\n // Extract type parameter if present (typeArguments for newer TS-ESLint, typeParameters for older)\n const typeParamNode = node.typeParameters?.params?.[0] ?? node.typeArguments?.params?.[0]\n const typeParam = typeParamNode ? sourceCode.getText(typeParamNode) : \"T\"\n\n // Already imported under another name (`Set as FSet`): point at that name instead of adding a\n // second import that would shadow the native `Set` the rest of the file uses.\n const imported = functypeLocalName(sourceCode, \"Set\")\n const suggestions: Rule.SuggestionReportDescriptor[] =\n imported === null\n ? [{ messageId: \"suggestAddImport\", data: { symbol: \"Set\" }, fix: createImportFixer(sourceCode, \"Set\") }]\n : [\n {\n messageId: \"suggestUseLocalName\",\n data: { name: imported },\n fix: (fixer) => fixer.replaceText(node.typeName, imported),\n },\n ]\n\n context.report({\n node,\n messageId: \"preferFunctypeSet\",\n data: { type: typeParam },\n suggest: suggestions,\n })\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"mbASA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,mEACb,YAAa,EACf,EACA,OAA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gBlB,EAAK,gBAAgB,SAAS,IAAMA,EAAK,eAAe,SAAS,GACjFmB,EAAYD,EAAgBZ,EAAW,QAAQY,CAAa,EAAI,IAIhEX,EAAWC,EAAkBF,EAAY,KAAK,EAC9CK,EACJJ,IAAa,KACT,CAAC,CAAE,UAAW,mBAAoB,KAAM,CAAE,OAAQ,KAAM,EAAG,IAAKS,EAAkBV,EAAY,KAAK,CAAE,CAAC,EACtG,CACE,CACE,UAAW,sBACX,KAAM,CAAE,KAAMC,CAAS,EACvB,IAAM,GAAUK,EAAM,YAAYZ,EAAK,SAAUO,CAAQ,CAC3D,CACF,EAENd,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,KAAM0B,CAAU,EACxB,QAASR,CACX,CAAC,CACH,CACF,CACF,CACF"}
|
|
@@ -4,18 +4,19 @@ import { SourceCode } from "eslint";
|
|
|
4
4
|
/**
|
|
5
5
|
* Structural exemptions recorded in JSDoc, instead of `eslint-disable` (#241).
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
7
|
+
* `@interop <reason>` — the enclosing declaration bridges functype to a host whose contract is the
|
|
8
|
+
* non-FP shape: React's `use()` needs a throw, React Query needs a rejected promise, a hook that converts
|
|
9
|
+
* nullables into `Option` must accept nullables.
|
|
10
|
+
*
|
|
11
|
+
* Bug checks are not tagged: they are `invariant(cond, msg)` calls from functype, which narrow types and
|
|
12
|
+
* cover one statement. (An `@invariant` tag shipped in 1.10.0 and was removed in #342 — it exempted a
|
|
13
|
+
* whole function, including any expected-failure throw added to it later.)
|
|
12
14
|
*
|
|
13
15
|
* Why a tag rather than a disable comment: it covers one declaration (and what is nested inside it), not
|
|
14
16
|
* a whole file; it must carry a reason on the same line, so a bare tag exempts nothing; and it is
|
|
15
17
|
* greppable — `rg '@interop'` is the inventory of every place the code touches a throw-based host.
|
|
16
18
|
*/
|
|
17
19
|
export declare const INTEROP_TAG = "interop";
|
|
18
|
-
export declare const INVARIANT_TAG = "invariant";
|
|
19
20
|
/**
|
|
20
21
|
* Is `node` inside a declaration whose JSDoc carries `@<tag> <reason>`? Every enclosing documentable
|
|
21
22
|
* declaration is checked, so a tag on a function covers the callbacks nested inside it.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=`interop`,t
|
|
1
|
+
const e=`interop`,t=/* @__PURE__ */ new Set([`FunctionDeclaration`,`VariableDeclaration`,`MethodDefinition`,`PropertyDefinition`,`Property`,`TSTypeAliasDeclaration`,`TSInterfaceDeclaration`,`TSPropertySignature`,`TSMethodSignature`]),n=/* @__PURE__ */ new Set([`ExportNamedDeclaration`,`ExportDefaultDeclaration`]),r=(e,t)=>{let r=e.parent&&n.has(e.parent.type)?e.parent:e,i=t.getCommentsBefore(r),a=i[i.length-1];return a?.type===`Block`&&a.value.startsWith(`*`)?a.value:null},i=(e,t)=>RegExp(`(^|[\\s*])@${t}[ \\t]+\\S`,`m`).test(e),a=(e,n,a)=>{let o=e=>{if(!e)return!1;if(t.has(e.type)){let t=r(e,a);if(t!==null&&i(t,n))return!0}return o(e.parent)};return o(e)};export{e as INTEROP_TAG,a as isInsideTaggedDeclaration};
|
|
2
2
|
//# sourceMappingURL=boundary-tags.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"boundary-tags.js","names":["INTEROP_TAG","
|
|
1
|
+
{"version":3,"file":"boundary-tags.js","names":["INTEROP_TAG","DOCUMENTABLE","EXPORT_WRAPPERS","leadingJSDoc","anchor","node","comments","sourceCode","last","hasTagWithReason","tag","jsdoc","isInsideTaggedDeclaration","check","current"],"sources":["../../src/utils/boundary-tags.ts"],"sourcesContent":["import type { SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * Structural exemptions recorded in JSDoc, instead of `eslint-disable` (#241).\n *\n * `@interop <reason>` — the enclosing declaration bridges functype to a host whose contract is the\n * non-FP shape: React's `use()` needs a throw, React Query needs a rejected promise, a hook that converts\n * nullables into `Option` must accept nullables.\n *\n * Bug checks are not tagged: they are `invariant(cond, msg)` calls from functype, which narrow types and\n * cover one statement. (An `@invariant` tag shipped in 1.10.0 and was removed in #342 — it exempted a\n * whole function, including any expected-failure throw added to it later.)\n *\n * Why a tag rather than a disable comment: it covers one declaration (and what is nested inside it), not\n * a whole file; it must carry a reason on the same line, so a bare tag exempts nothing; and it is\n * greppable — `rg '@interop'` is the inventory of every place the code touches a throw-based host.\n */\n\nexport const INTEROP_TAG = \"interop\"\n\n/** Declarations whose leading JSDoc can carry a tag. */\nconst DOCUMENTABLE: ReadonlySet<string> = new Set([\n \"FunctionDeclaration\",\n \"VariableDeclaration\",\n \"MethodDefinition\",\n \"PropertyDefinition\",\n \"Property\",\n \"TSTypeAliasDeclaration\",\n \"TSInterfaceDeclaration\",\n \"TSPropertySignature\",\n \"TSMethodSignature\",\n])\n\nconst EXPORT_WRAPPERS: ReadonlySet<string> = new Set([\"ExportNamedDeclaration\", \"ExportDefaultDeclaration\"])\n\n/** The JSDoc block (`/** … *\\/`) directly before `node`, or before its `export` wrapper. */\nconst leadingJSDoc = (node: ASTNode, sourceCode: SourceCode): string | null => {\n const anchor = node.parent && EXPORT_WRAPPERS.has(node.parent.type) ? node.parent : node\n const comments = sourceCode.getCommentsBefore(anchor)\n const last = comments[comments.length - 1]\n return last?.type === \"Block\" && last.value.startsWith(\"*\") ? last.value : null\n}\n\n/** `@tag` followed by a reason on the same line. A bare tag carries no reason and exempts nothing. */\nconst hasTagWithReason = (jsdoc: string, tag: string): boolean =>\n new RegExp(`(^|[\\\\s*])@${tag}[ \\\\t]+\\\\S`, \"m\").test(jsdoc)\n\n/**\n * Is `node` inside a declaration whose JSDoc carries `@<tag> <reason>`? Every enclosing documentable\n * declaration is checked, so a tag on a function covers the callbacks nested inside it.\n */\nexport const isInsideTaggedDeclaration = (node: ASTNode, tag: string, sourceCode: SourceCode): boolean => {\n const check = (current: ASTNode | null | undefined): boolean => {\n if (!current) return false\n if (DOCUMENTABLE.has(current.type)) {\n const jsdoc = leadingJSDoc(current, sourceCode)\n if (jsdoc !== null && hasTagWithReason(jsdoc, tag)) return true\n }\n return check(current.parent)\n }\n return check(node)\n}\n"],"mappings":"AAoBA,MAAaA,EAAc,UAGrBC,kBAAoC,IAAI,IAAI,CAChD,sBACA,sBACA,mBACA,qBACA,WACA,yBACA,yBACA,sBACA,mBACF,CAAC,EAEKC,kBAAuC,IAAI,IAAI,CAAC,yBAA0B,0BAA0B,CAAC,EAGrGC,GAAgB,EAAe,IAA0C,CAC7E,IAAMC,EAASC,EAAK,QAAUH,EAAgB,IAAIG,EAAK,OAAO,IAAI,EAAIA,EAAK,OAASA,EAC9EC,EAAWC,EAAW,kBAAkBH,CAAM,EAC9CI,EAAOF,EAASA,EAAS,OAAS,GACxC,OAAOE,GAAM,OAAS,SAAWA,EAAK,MAAM,WAAW,GAAG,EAAIA,EAAK,MAAQ,IAC7E,EAGMC,GAAoB,EAAe,IACnC,OAAO,cAAcC,EAAI,YAAa,GAAG,CAAC,CAAC,KAAKC,CAAK,EAM9CC,GAA6B,EAAe,EAAa,IAAoC,CACxG,IAAMC,EAAS,GAAiD,CAC9D,GAAI,CAACC,EAAS,MAAO,GACrB,GAAIb,EAAa,IAAIa,EAAQ,IAAI,EAAG,CAClC,IAAMH,EAAQR,EAAaW,EAASP,CAAU,EAC9C,GAAII,IAAU,MAAQF,EAAiBE,EAAOD,CAAG,EAAG,MAAO,EAC7D,CACA,OAAOG,EAAMC,EAAQ,MAAM,CAC7B,EACA,OAAOD,EAAMR,CAAI,CACnB"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { ASTNode } from "../types/ast.js";
|
|
2
|
+
import { SourceCode } from "eslint";
|
|
3
|
+
//#region src/utils/collection-binding.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* What `Map` / `Set` means at a use site (#350). Deciding from the file's import list was wrong both ways:
|
|
6
|
+
* `import { Map as FMap } from "functype"` silenced the whole file even though the bare `Map` there is still
|
|
7
|
+
* the native one. Resolving the identifier through scope asks the question that matters.
|
|
8
|
+
*
|
|
9
|
+
* - `functype` — it is functype's import (under any local name), so there is nothing to report;
|
|
10
|
+
* - `shadowed` — a local declaration or a non-functype import, so it isn't the native collection;
|
|
11
|
+
* - `native` — unresolved, or a global / lib binding with no declaration: the built-in.
|
|
12
|
+
*/
|
|
13
|
+
export type CollectionBinding = "native" | "functype" | "shadowed";
|
|
14
|
+
export declare const bindingOf: (node: ASTNode, name: string, sourceCode: SourceCode) => CollectionBinding;
|
|
15
|
+
/**
|
|
16
|
+
* The name this file already uses for functype's `name`: `"FMap"` for `import { Map as FMap }`,
|
|
17
|
+
* `"F.Map"` for `import * as F`, or null when it isn't imported (so the fix must add the import).
|
|
18
|
+
*/
|
|
19
|
+
export declare const functypeLocalName: (sourceCode: SourceCode, name: string) => string | null;
|
|
20
|
+
//#endregion
|
|
21
|
+
//# sourceMappingURL=collection-binding.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=e=>typeof e==`string`&&(e===`functype`||e.startsWith(`functype/`)),t=(e,t,n)=>{let r=e=>e===null?null:e.set.get(t)??r(e.upper);return r(n.getScope(e))},n=(n,r,i)=>{let a=t(n,r,i);if(a===null||a.defs.length===0)return`native`;let o=a.defs[0];return o.type===`ImportBinding`&&e(o.parent?.source?.value)?`functype`:`shadowed`},r=(t,n)=>t.ast.body.filter(t=>t.type===`ImportDeclaration`&&e(t.source?.value)).flatMap(e=>e.specifiers??[]).flatMap(e=>e.type===`ImportSpecifier`&&e.imported?.type===`Identifier`&&e.imported.name===n?[e.local.name]:e.type===`ImportNamespaceSpecifier`?[`${e.local.name}.${n}`]:[])[0]??null;export{n as bindingOf,r as functypeLocalName};
|
|
2
|
+
//# sourceMappingURL=collection-binding.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"collection-binding.js","names":["isFunctypeSource","value","resolve","lookup","scope","name","sourceCode","node","bindingOf","variable","def","functypeLocalName","n","decl","spec"],"sources":["../../src/utils/collection-binding.ts"],"sourcesContent":["import type { Scope, SourceCode } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\n\n/**\n * What `Map` / `Set` means at a use site (#350). Deciding from the file's import list was wrong both ways:\n * `import { Map as FMap } from \"functype\"` silenced the whole file even though the bare `Map` there is still\n * the native one. Resolving the identifier through scope asks the question that matters.\n *\n * - `functype` — it is functype's import (under any local name), so there is nothing to report;\n * - `shadowed` — a local declaration or a non-functype import, so it isn't the native collection;\n * - `native` — unresolved, or a global / lib binding with no declaration: the built-in.\n */\nexport type CollectionBinding = \"native\" | \"functype\" | \"shadowed\"\n\nconst isFunctypeSource = (value: unknown): boolean =>\n typeof value === \"string\" && (value === \"functype\" || value.startsWith(\"functype/\"))\n\nconst resolve = (node: ASTNode, name: string, sourceCode: SourceCode): Scope.Variable | null => {\n const lookup = (scope: Scope.Scope | null): Scope.Variable | null =>\n scope === null ? null : (scope.set.get(name) ?? lookup(scope.upper))\n return lookup(sourceCode.getScope(node))\n}\n\nexport const bindingOf = (node: ASTNode, name: string, sourceCode: SourceCode): CollectionBinding => {\n const variable = resolve(node, name, sourceCode)\n if (variable === null || variable.defs.length === 0) return \"native\"\n const def = variable.defs[0] as unknown as { readonly type: string; readonly parent?: ASTNode }\n if (def.type === \"ImportBinding\") return isFunctypeSource(def.parent?.source?.value) ? \"functype\" : \"shadowed\"\n return \"shadowed\"\n}\n\n/**\n * The name this file already uses for functype's `name`: `\"FMap\"` for `import { Map as FMap }`,\n * `\"F.Map\"` for `import * as F`, or null when it isn't imported (so the fix must add the import).\n */\nexport const functypeLocalName = (sourceCode: SourceCode, name: string): string | null => {\n const names = (sourceCode.ast.body as ReadonlyArray<ASTNode>)\n .filter((n) => n.type === \"ImportDeclaration\" && isFunctypeSource(n.source?.value))\n .flatMap((decl) => (decl.specifiers ?? []) as ReadonlyArray<ASTNode>)\n .flatMap((spec): ReadonlyArray<string> => {\n if (spec.type === \"ImportSpecifier\" && spec.imported?.type === \"Identifier\" && spec.imported.name === name) {\n return [spec.local.name]\n }\n if (spec.type === \"ImportNamespaceSpecifier\") return [`${spec.local.name}.${name}`]\n return []\n })\n return names[0] ?? null\n}\n"],"mappings":"AAeA,MAAMA,EAAoB,GACxB,OAAOC,GAAU,WAAaA,IAAU,YAAcA,EAAM,WAAW,WAAW,GAE9EC,GAAW,EAAe,EAAc,IAAkD,CAC9F,IAAMC,EAAU,GACdC,IAAU,KAAO,KAAQA,EAAM,IAAI,IAAIC,CAAI,GAAKF,EAAOC,EAAM,KAAK,EACpE,OAAOD,EAAOG,EAAW,SAASC,CAAI,CAAC,CACzC,EAEaC,GAAa,EAAe,EAAc,IAA8C,CACnG,IAAMC,EAAWP,EAAQK,EAAMF,EAAMC,CAAU,EAC/C,GAAIG,IAAa,MAAQA,EAAS,KAAK,SAAW,EAAG,MAAO,SAC5D,IAAMC,EAAMD,EAAS,KAAK,GAE1B,OADIC,EAAI,OAAS,iBAAwBV,EAAiBU,EAAI,QAAQ,QAAQ,KAAK,EAAI,WAAa,UAEtG,EAMaC,GAAqB,EAAwB,IACzCL,EAAW,IAAI,KAC3B,OAAQ,GAAMM,EAAE,OAAS,qBAAuBZ,EAAiBY,EAAE,QAAQ,KAAK,CAAC,CAAC,CAClF,QAAS,GAAUC,EAAK,YAAc,CAAC,CAA4B,CAAC,CACpE,QAAS,GACJC,EAAK,OAAS,mBAAqBA,EAAK,UAAU,OAAS,cAAgBA,EAAK,SAAS,OAAST,EAC7F,CAACS,EAAK,MAAM,IAAI,EAErBA,EAAK,OAAS,2BAAmC,CAAC,GAAGA,EAAK,MAAM,KAAK,GAAGT,GAAM,EAC3E,CAAC,CAED,CAAC,CAAC,IAAM"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=/* @__PURE__ */ new Set([`FunctionDeclaration`,`FunctionExpression`,`ArrowFunctionExpression`]),t=(e,t)=>e?.type===`TSTypeReference`&&e.typeName?.type===`Identifier`&&e.typeName.name===t,n=e=>e.typeArguments?.params??e.typeParameters?.params??[],r=(e,i)=>t(e,i)||t(e,`Promise`)&&r(n(e)[0],i),i=e=>e?.typeAnnotation?.typeAnnotation,a=t=>t==null?void 0:e.has(t.type)?t:a(t.parent),o=(e,t)=>{let n=e.parent;if(!n)return!1;switch(n.type){case`ConditionalExpression`:return n.test!==e&&o(n,t);case`LogicalExpression`:return o(n,t);case`TSAsExpression`:case`TSSatisfiesExpression`:return r(n.typeAnnotation,t)||o(n,t);case`ReturnStatement`:return r(a(n)?.returnType?.typeAnnotation,t);case`ArrowFunctionExpression`:return n.body===e&&r(n.returnType?.typeAnnotation,t);case`VariableDeclarator`:return n.init===e&&r(i(n.id),t);case`PropertyDefinition`:return n.value===e&&r(i(n),t);case`AssignmentPattern`:return n.right===e&&r(i(n.left),t);default:return!1}};export{o as flowsIntoReadonlyContract};
|
|
2
|
+
//# sourceMappingURL=readonly-contract.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"readonly-contract.js","names":["FUNCTIONS","isNamed","type","name","typeArgs","isReadonlyContract","readonlyName","annotationOf","node","nearestFunction","flowsIntoReadonlyContract","parent"],"sources":["../../src/utils/readonly-contract.ts"],"sourcesContent":["import type { ASTNode } from \"../types/ast\"\n\n/**\n * Does this expression flow straight into a declared native read-only contract (#350)?\n *\n * `prefer-functype-map` / `-set` never report a `ReadonlyMap` / `ReadonlySet` annotation, so they must not\n * report the constructor that annotation requires: when a function is declared to return\n * `ReadonlyMap<K, V>` — typically because a callee's interface takes one — the native `new Map(...)` it\n * returns is the contract, not an oversight. Recognized positions:\n *\n * - `return` in the nearest enclosing function whose declared return type is `R` or `Promise<R>`\n * (a callback nested inside such a function does not inherit its signature);\n * - the expression body of an arrow function with that return type;\n * - the initializer of a variable, class field, or parameter default annotated `R`;\n * - an `as R` / `satisfies R` assertion;\n * and through ternary branches and `??` / `||` / `&&` operands on the way there.\n */\n\nconst FUNCTIONS: ReadonlySet<string> = new Set([\"FunctionDeclaration\", \"FunctionExpression\", \"ArrowFunctionExpression\"])\n\nconst isNamed = (type: ASTNode | undefined, name: string): boolean =>\n type?.type === \"TSTypeReference\" && type.typeName?.type === \"Identifier\" && type.typeName.name === name\n\nconst typeArgs = (type: ASTNode): ReadonlyArray<ASTNode> =>\n (type.typeArguments?.params ?? type.typeParameters?.params ?? []) as ReadonlyArray<ASTNode>\n\n/** `R<…>` or `Promise<R<…>>`. */\nconst isReadonlyContract = (type: ASTNode | undefined, readonlyName: string): boolean =>\n isNamed(type, readonlyName) || (isNamed(type, \"Promise\") && isReadonlyContract(typeArgs(type!)[0], readonlyName))\n\nconst annotationOf = (node: ASTNode | undefined): ASTNode | undefined => node?.typeAnnotation?.typeAnnotation\n\nconst nearestFunction = (node: ASTNode | undefined): ASTNode | undefined =>\n node === undefined || node === null ? undefined : FUNCTIONS.has(node.type) ? node : nearestFunction(node.parent)\n\nexport const flowsIntoReadonlyContract = (node: ASTNode, readonlyName: string): boolean => {\n const parent = node.parent\n if (!parent) return false\n switch (parent.type) {\n case \"ConditionalExpression\":\n return parent.test !== node && flowsIntoReadonlyContract(parent, readonlyName)\n case \"LogicalExpression\":\n return flowsIntoReadonlyContract(parent, readonlyName)\n case \"TSAsExpression\":\n case \"TSSatisfiesExpression\":\n return isReadonlyContract(parent.typeAnnotation, readonlyName) || flowsIntoReadonlyContract(parent, readonlyName)\n case \"ReturnStatement\":\n return isReadonlyContract(nearestFunction(parent)?.returnType?.typeAnnotation, readonlyName)\n case \"ArrowFunctionExpression\":\n return parent.body === node && isReadonlyContract(parent.returnType?.typeAnnotation, readonlyName)\n case \"VariableDeclarator\":\n return parent.init === node && isReadonlyContract(annotationOf(parent.id), readonlyName)\n case \"PropertyDefinition\":\n return parent.value === node && isReadonlyContract(annotationOf(parent), readonlyName)\n case \"AssignmentPattern\":\n return parent.right === node && isReadonlyContract(annotationOf(parent.left), readonlyName)\n default:\n return false\n }\n}\n"],"mappings":"AAkBA,MAAMA,kB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5F,QACE,MAAO,EACX,CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-functype",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.111.1",
|
|
4
4
|
"description": "Custom ESLint rules for functional TypeScript programming with functype library patterns including Do notation (ESLint 10+)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"@types/node": "^24.19.0",
|
|
43
43
|
"@typescript-eslint/rule-tester": "^8.71.0",
|
|
44
44
|
"eslint-config-prettier": "^10.1.8",
|
|
45
|
-
"functype": "^1.
|
|
45
|
+
"functype": "^1.11.1",
|
|
46
46
|
"ts-builds": "^3.4.3",
|
|
47
47
|
"tsdown": "^0.23.0"
|
|
48
48
|
},
|