eslint-plugin-functype 2.111.0 → 2.112.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -27,21 +27,22 @@ export default [functype.configs.strict]
27
27
 
28
28
  ## Rules
29
29
 
30
- | Rule | Recommended | Strict | Description |
31
- | ------------------------------ | :---------: | :----: | ---------------------------------------------------------- |
32
- | `functype/no-let` | error | error | Use `const`; no reassignment |
33
- | `functype/no-imperative-loops` | error | error | Use `List`/array methods or `IO.forEach` instead of loops |
34
- | `functype/prefer-functype-map` | error | error | Use functype `Map` instead of a native `Map` you only read |
35
- | `functype/prefer-functype-set` | error | error | Use functype `Set` instead of a native `Set` you only read |
36
- | `functype/prefer-map` | error | error | Use `map` instead of pushing inside `forEach` |
37
- | `functype/prefer-fold` | error | error | Use `fold` instead of branching on `isSome()`/`isLeft()`/… |
38
- | `functype/prefer-option` | warn | error | Use `Option` instead of `null`/`undefined` |
39
- | `functype/prefer-either` | warn | error | Use `Either` for typed domain errors instead of `throw` |
40
- | `functype/prefer-try` | warn | error | Use `Try` / `Try.fromPromise` instead of try/catch |
41
- | `functype/prefer-flatmap` | warn | warn | Use `flatMap` instead of `map().flat()` |
42
- | `functype/prefer-do-notation` | warn | warn | Use `Do` notation for chained operations |
43
- | `functype/no-get-unsafe` | off | error | Disallow unsafe extraction (`.orThrow()`, `.expect()`) |
44
- | `functype/prefer-list` | off | warn | Use `List` instead of native arrays |
30
+ | Rule | Recommended | Strict | Description |
31
+ | ------------------------------ | :---------: | :----: | ---------------------------------------------------------------------------------------- |
32
+ | `functype/no-let` | error | error | Use `const`; no reassignment |
33
+ | `functype/no-imperative-loops` | error | error | Use `List`/array methods or `IO.forEach` instead of loops |
34
+ | `functype/prefer-functype-map` | error | error | Use functype `Map` instead of a native `Map` you only read |
35
+ | `functype/prefer-functype-set` | error | error | Use functype `Set` instead of a native `Set` you only read |
36
+ | `functype/collection-naming` | error | error | Import functype's `Map`/`Set` under their own names; spell the built-in `globalThis.Map` |
37
+ | `functype/prefer-map` | error | error | Use `map` instead of pushing inside `forEach` |
38
+ | `functype/prefer-fold` | error | error | Use `fold` instead of branching on `isSome()`/`isLeft()`/… |
39
+ | `functype/prefer-option` | warn | error | Use `Option` instead of `null`/`undefined` |
40
+ | `functype/prefer-either` | warn | error | Use `Either` for typed domain errors instead of `throw` |
41
+ | `functype/prefer-try` | warn | error | Use `Try` / `Try.fromPromise` instead of try/catch |
42
+ | `functype/prefer-flatmap` | warn | warn | Use `flatMap` instead of `map().flat()` |
43
+ | `functype/prefer-do-notation` | warn | warn | Use `Do` notation for chained operations |
44
+ | `functype/no-get-unsafe` | off | error | Disallow unsafe extraction (`.orThrow()`, `.expect()`) |
45
+ | `functype/prefer-list` | off | warn | Use `List` instead of native arrays |
45
46
 
46
47
  ### Severity policy
47
48
 
@@ -165,6 +166,31 @@ Not followed: aliases (`const t = s; t.add(x)`), `useRef(new Set()).current.add(
165
166
 
166
167
  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.
167
168
 
169
+ **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:
170
+
171
+ - a `return` in the nearest function declared to return `ReadonlyMap<…>` (or `Promise<ReadonlyMap<…>>`);
172
+ - the expression body of an arrow function with that return type;
173
+ - a variable, class field or parameter default annotated `ReadonlyMap<…>`;
174
+ - an `as ReadonlyMap<…>` / `satisfies ReadonlyMap<…>` assertion;
175
+ - any of the above through a ternary branch or a `??` / `||` / `&&` operand.
176
+
177
+ 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: Map<K, V>): ReadonlyMap<K, V> => new globalThis.Map(m)`.
178
+
179
+ **The built-in is spelled `globalThis.Map` / `globalThis.Set`.** `new globalThis.Map()` and `new ESMap()` are reported like a bare `new Map()`, with the same exemptions. Imports are resolved where `Map` / `Set` is used: functype's import (any name) or a local shadow isn't the built-in.
180
+
181
+ ### `functype/collection-naming`
182
+
183
+ functype's `Map` / `Set` are the default collections (the Scala convention: the immutable collection owns the plain name). This rule reports:
184
+
185
+ - `new Map()` on functype's `Map` (or `Set`). It's a factory, so TypeScript only says TS7009 ("target lacks a construct signature"). The message says to write `Map(…)` / `Map.empty()`, or `new globalThis.Map(…)` for the built-in.
186
+ - `import { Map as FMap } from "functype"`. An alias lets the plain name keep meaning the built-in, which inverts the convention and drifts between files.
187
+
188
+ | Option | Default | Description |
189
+ | ------------ | ------- | -------------------------------------------------------------------------------------------------------------------- |
190
+ | `allowAlias` | `false` | Accept aliased imports of functype's `Map` / `Set`, for a codebase that prefers the built-ins under the plain names. |
191
+
192
+ It applies in test files too: tests are read as examples.
193
+
168
194
  ### `functype/no-imperative-loops` / `functype/prefer-map`
169
195
 
170
196
  These rules don't report loops that have no functional equivalent:
@@ -15,6 +15,9 @@
15
15
  * `isLeft()`) only; its null-check heuristic is opt-in (`checkNullable`) because it fired on plain
16
16
  * nullables — 31 of 31 hits in CivalaOS. prefer-map leaves loops to no-imperative-loops (`checkForLoops`
17
17
  * off), so one loop is one error.
18
+ *
19
+ * collection-naming is a convention, not a heuristic — functype's Map/Set imported under their own names,
20
+ * the built-in spelled globalThis.Map — so it has no false-positive class and starts at error.
18
21
  */
19
22
  declare const recommendedRules: {
20
23
  "functype/no-let": string;
@@ -23,6 +26,7 @@ declare const recommendedRules: {
23
26
  "functype/prefer-functype-set": string;
24
27
  "functype/prefer-map": string;
25
28
  "functype/prefer-fold": string;
29
+ "functype/collection-naming": string;
26
30
  "functype/prefer-option": string;
27
31
  "functype/prefer-either": string;
28
32
  "functype/prefer-try": string;
@@ -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/prefer-option":`warn`,"functype/prefer-either":`warn`,"functype/prefer-try":`warn`,"functype/prefer-flatmap":`warn`,"functype/prefer-do-notation":`warn`,"functype/no-get-unsafe":`off`,"functype/prefer-list":`off`};export{e as default};
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`};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 */\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
+ {"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 */\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}\n\nexport default recommendedRules\n"],"mappings":"AAoBA,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,KAC1B"}
@@ -11,6 +11,7 @@ declare const strictRules: {
11
11
  "functype/no-let": string;
12
12
  "functype/prefer-map": string;
13
13
  "functype/prefer-fold": string;
14
+ "functype/collection-naming": string;
14
15
  "functype/prefer-flatmap": string;
15
16
  "functype/prefer-do-notation": string;
16
17
  };
package/dist/index.d.ts CHANGED
@@ -14,6 +14,7 @@ declare const plugin: {
14
14
  "prefer-functype-set": import("eslint").Rule.RuleModule;
15
15
  "no-imperative-loops": import("eslint").Rule.RuleModule;
16
16
  "prefer-do-notation": import("eslint").Rule.RuleModule;
17
+ "collection-naming": import("eslint").Rule.RuleModule;
17
18
  };
18
19
  meta: {
19
20
  name: string;
@@ -0,0 +1,18 @@
1
+ import { Rule } from "eslint";
2
+ //#region src/rules/collection-naming.d.ts
3
+ /**
4
+ * functype's `Map` / `Set` are the default collections (Scala-style): import them under their own names,
5
+ * and spell the built-in `globalThis.Map` / `globalThis.Set` where it is genuinely needed.
6
+ *
7
+ * Two defects:
8
+ * - `new Map()` on functype's Map. It's a factory, so TypeScript only says TS7009 ("target lacks a construct
9
+ * signature, implicitly has an 'any' type"), which doesn't say what to write instead. This message does.
10
+ * - `import { Map as FMap } from "functype"`. Aliases let a file keep the built-in under the plain name,
11
+ * which inverts the convention and drifts (`FMap`, `FMapOf`, `IMap`…). `allowAlias: true` opts out.
12
+ *
13
+ * Applies in test files too: tests are read as examples, by people and agents.
14
+ */
15
+ declare const rule: Rule.RuleModule;
16
+ //#endregion
17
+ export { rule as default };
18
+ //# sourceMappingURL=collection-naming.d.ts.map
@@ -0,0 +1,2 @@
1
+ import{COLLECTION_NAMES as e,functypeCollectionAt as t}from"../utils/collection-binding.js";const n={meta:{type:`problem`,docs:{description:`Use functype's Map/Set under their own names; spell the built-in globalThis.Map/globalThis.Set`,recommended:!0},schema:[{type:`object`,properties:{allowAlias:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{newFunctypeCollection:`functype's {{name}} is a factory, not a class: use {{local}}(…) or {{local}}.empty(). For the built-in, write new globalThis.{{name}}(…)`,aliasedImport:`Import functype's {{name}} as {{name}}, not {{local}}: functype's {{name}} is the default collection. Spell the built-in globalThis.{{name}}`}},create(n){let r=(n.options[0]||{}).allowAlias===!0;return{NewExpression(e){let r=t(e.callee,n.sourceCode);r!==null&&n.report({node:e,messageId:`newFunctypeCollection`,data:r})},ImportDeclaration(t){if(r)return;let i=t.source?.value;typeof i==`string`&&(i===`functype`||i.startsWith(`functype/`))&&t.specifiers.filter(t=>t.type===`ImportSpecifier`&&t.imported?.type===`Identifier`&&e.includes(t.imported.name)&&t.local.name!==t.imported.name).forEach(e=>n.report({node:e,messageId:`aliasedImport`,data:{name:e.imported.name,local:e.local.name}}))}}}};export{n as default};
2
+ //# sourceMappingURL=collection-naming.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collection-naming.js","names":["rule","allowAlias","context","hit","functypeCollectionAt","node","source","spec","COLLECTION_NAMES"],"sources":["../../src/rules/collection-naming.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { COLLECTION_NAMES, functypeCollectionAt } from \"../utils/collection-binding\"\n\n/**\n * functype's `Map` / `Set` are the default collections (Scala-style): import them under their own names,\n * and spell the built-in `globalThis.Map` / `globalThis.Set` where it is genuinely needed.\n *\n * Two defects:\n * - `new Map()` on functype's Map. It's a factory, so TypeScript only says TS7009 (\"target lacks a construct\n * signature, implicitly has an 'any' type\"), which doesn't say what to write instead. This message does.\n * - `import { Map as FMap } from \"functype\"`. Aliases let a file keep the built-in under the plain name,\n * which inverts the convention and drifts (`FMap`, `FMapOf`, `IMap`…). `allowAlias: true` opts out.\n *\n * Applies in test files too: tests are read as examples, by people and agents.\n */\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"problem\",\n docs: {\n description: \"Use functype's Map/Set under their own names; spell the built-in globalThis.Map/globalThis.Set\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowAlias: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n newFunctypeCollection:\n \"functype's {{name}} is a factory, not a class: use {{local}}(…) or {{local}}.empty(). For the built-in, write new globalThis.{{name}}(…)\",\n aliasedImport:\n \"Import functype's {{name}} as {{name}}, not {{local}}: functype's {{name}} is the default collection. Spell the built-in globalThis.{{name}}\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n const allowAlias = options.allowAlias === true\n\n return {\n NewExpression(node: ASTNode) {\n const hit = functypeCollectionAt(node.callee, context.sourceCode)\n if (hit === null) return\n context.report({ node, messageId: \"newFunctypeCollection\", data: hit })\n },\n\n ImportDeclaration(node: ASTNode) {\n if (allowAlias) return\n const source = node.source?.value\n if (typeof source !== \"string\" || !(source === \"functype\" || source.startsWith(\"functype/\"))) return\n ;(node.specifiers as ReadonlyArray<ASTNode>)\n .filter(\n (spec) =>\n spec.type === \"ImportSpecifier\" &&\n spec.imported?.type === \"Identifier\" &&\n COLLECTION_NAMES.includes(spec.imported.name) &&\n spec.local.name !== spec.imported.name,\n )\n .forEach((spec) =>\n context.report({\n node: spec,\n messageId: \"aliasedImport\",\n data: { name: spec.imported.name, local: spec.local.name },\n }),\n )\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"4FAiBA,MAAMA,EAAwB,CAC5B,KAAM,CACJ,KAAM,UACN,KAAM,CACJ,YAAa,iGACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,WAAY,CACV,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,sBACE,2IACF,cACE,8IACJ,CACF,EAEA,OAAO,EAAS,CAEd,IAAMC,GADUC,EAAQ,QAAQ,IAAM,CAAC,EAAA,CACZ,aAAe,GAE1C,MAAO,CACL,cAAc,EAAe,CAC3B,IAAMC,EAAMC,EAAqBC,EAAK,OAAQH,EAAQ,UAAU,EAC5DC,IAAQ,MACZD,EAAQ,OAAO,CAAE,OAAM,UAAW,wBAAyB,KAAMC,CAAI,CAAC,CACxE,EAEA,kBAAkB,EAAe,CAC/B,GAAIF,EAAY,OAChB,IAAMK,EAASD,EAAK,QAAQ,MACxB,OAAOC,GAAW,WAAcA,IAAW,YAAcA,EAAO,WAAW,WAAW,IACzFD,EAAM,WACJ,OACE,GACCE,EAAK,OAAS,mBACdA,EAAK,UAAU,OAAS,cACxBC,EAAiB,SAASD,EAAK,SAAS,IAAI,GAC5CA,EAAK,MAAM,OAASA,EAAK,SAAS,IACtC,CAAC,CACA,QAAS,GACRL,EAAQ,OAAO,CACb,KAAMK,EACN,UAAW,gBACX,KAAM,CAAE,KAAMA,EAAK,SAAS,KAAM,MAAOA,EAAK,MAAM,IAAK,CAC3D,CAAC,CACH,CACJ,CACF,CACF,CACF"}
@@ -1,16 +1,17 @@
1
- import rule from "./no-get-unsafe.js";
2
- import rule$1 from "./no-imperative-loops.js";
3
- import rule$2 from "./no-let.js";
4
- import rule$3 from "./prefer-do-notation.js";
5
- import rule$4 from "./prefer-either.js";
6
- import rule$5 from "./prefer-flatmap.js";
7
- import rule$6 from "./prefer-fold.js";
8
- import rule$7 from "./prefer-functype-map.js";
9
- import rule$8 from "./prefer-functype-set.js";
10
- import rule$9 from "./prefer-list.js";
11
- import rule$10 from "./prefer-map.js";
12
- import rule$11 from "./prefer-option.js";
13
- import rule$12 from "./prefer-try.js";
1
+ import rule from "./collection-naming.js";
2
+ import rule$1 from "./no-get-unsafe.js";
3
+ import rule$2 from "./no-imperative-loops.js";
4
+ import rule$3 from "./no-let.js";
5
+ import rule$4 from "./prefer-do-notation.js";
6
+ import rule$5 from "./prefer-either.js";
7
+ import rule$6 from "./prefer-flatmap.js";
8
+ import rule$7 from "./prefer-fold.js";
9
+ import rule$8 from "./prefer-functype-map.js";
10
+ import rule$9 from "./prefer-functype-set.js";
11
+ import rule$10 from "./prefer-list.js";
12
+ import rule$11 from "./prefer-map.js";
13
+ import rule$12 from "./prefer-option.js";
14
+ import rule$13 from "./prefer-try.js";
14
15
  //#region src/rules/index.d.ts
15
16
  declare const _default: {
16
17
  "prefer-option": import("eslint").Rule.RuleModule;
@@ -26,7 +27,8 @@ declare const _default: {
26
27
  "prefer-functype-set": import("eslint").Rule.RuleModule;
27
28
  "no-imperative-loops": import("eslint").Rule.RuleModule;
28
29
  "prefer-do-notation": import("eslint").Rule.RuleModule;
30
+ "collection-naming": import("eslint").Rule.RuleModule;
29
31
  };
30
32
  //#endregion
31
- export { _default as default, rule as noGetUnsafe, rule$1 as noImperativeLoops, rule$2 as noLet, rule$3 as preferDoNotation, rule$4 as preferEither, rule$5 as preferFlatmap, rule$6 as preferFold, rule$7 as preferFunctypeMap, rule$8 as preferFunctypeSet, rule$9 as preferList, rule$10 as preferMap, rule$11 as preferOption, rule$12 as preferTry };
33
+ export { rule as collectionNaming, _default as default, rule$1 as noGetUnsafe, rule$2 as noImperativeLoops, rule$3 as noLet, rule$4 as preferDoNotation, rule$5 as preferEither, rule$6 as preferFlatmap, rule$7 as preferFold, rule$8 as preferFunctypeMap, rule$9 as preferFunctypeSet, rule$10 as preferList, rule$11 as preferMap, rule$12 as preferOption, rule$13 as preferTry };
32
34
  //# sourceMappingURL=index.d.ts.map
@@ -1,2 +1,2 @@
1
- import e from"./no-get-unsafe.js";import t from"./no-imperative-loops.js";import n from"./no-let.js";import r from"./prefer-do-notation.js";import i from"./prefer-either.js";import a from"./prefer-flatmap.js";import o from"./prefer-fold.js";import s from"./prefer-functype-map.js";import c from"./prefer-functype-set.js";import l from"./prefer-list.js";import u from"./prefer-map.js";import d from"./prefer-option.js";import f from"./prefer-try.js";var p={"prefer-option":d,"prefer-either":i,"prefer-try":f,"prefer-list":l,"no-get-unsafe":e,"no-let":n,"prefer-fold":o,"prefer-map":u,"prefer-flatmap":a,"prefer-functype-map":s,"prefer-functype-set":c,"no-imperative-loops":t,"prefer-do-notation":r};export{p as default,e as noGetUnsafe,t as noImperativeLoops,n as noLet,r as preferDoNotation,i as preferEither,a as preferFlatmap,o as preferFold,s as preferFunctypeMap,c as preferFunctypeSet,l as preferList,u as preferMap,d as preferOption,f as preferTry};
1
+ import e from"./collection-naming.js";import t from"./no-get-unsafe.js";import n from"./no-imperative-loops.js";import r from"./no-let.js";import i from"./prefer-do-notation.js";import a from"./prefer-either.js";import o from"./prefer-flatmap.js";import s from"./prefer-fold.js";import c from"./prefer-functype-map.js";import l from"./prefer-functype-set.js";import u from"./prefer-list.js";import d from"./prefer-map.js";import f from"./prefer-option.js";import p from"./prefer-try.js";var m={"prefer-option":f,"prefer-either":a,"prefer-try":p,"prefer-list":u,"no-get-unsafe":t,"no-let":r,"prefer-fold":s,"prefer-map":d,"prefer-flatmap":o,"prefer-functype-map":c,"prefer-functype-set":l,"no-imperative-loops":n,"prefer-do-notation":i,"collection-naming":e};export{e as collectionNaming,m as default,t as noGetUnsafe,n as noImperativeLoops,r as noLet,i as preferDoNotation,a as preferEither,o as preferFlatmap,s as preferFold,c as preferFunctypeMap,l as preferFunctypeSet,u as preferList,d as preferMap,f as preferOption,p as preferTry};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["preferOption","preferEither","preferTry","preferList","noGetUnsafe","noLet","preferFold","preferMap","preferFlatmap","preferFunctypeMap","preferFunctypeSet","noImperativeLoops","preferDoNotation","rule","rule$1","rule$2","rule$3","rule$4","rule$5","rule$6","rule$7","rule$8","rule$9","rule$10","rule$11","rule$12","rules_default"],"sources":["../../src/rules/index.ts"],"sourcesContent":["import noGetUnsafe from \"./no-get-unsafe\"\nimport noImperativeLoops from \"./no-imperative-loops\"\nimport noLet from \"./no-let\"\nimport preferDoNotation from \"./prefer-do-notation\"\nimport preferEither from \"./prefer-either\"\nimport preferFlatmap from \"./prefer-flatmap\"\nimport preferFold from \"./prefer-fold\"\nimport preferFunctypeMap from \"./prefer-functype-map\"\nimport preferFunctypeSet from \"./prefer-functype-set\"\nimport preferList from \"./prefer-list\"\nimport preferMap from \"./prefer-map\"\nimport preferOption from \"./prefer-option\"\nimport preferTry from \"./prefer-try\"\n\nexport {\n noGetUnsafe,\n noImperativeLoops,\n noLet,\n preferDoNotation,\n preferEither,\n preferFlatmap,\n preferFold,\n preferFunctypeMap,\n preferFunctypeSet,\n preferList,\n preferMap,\n preferOption,\n preferTry,\n}\n\nexport default {\n \"prefer-option\": preferOption,\n \"prefer-either\": preferEither,\n \"prefer-try\": preferTry,\n \"prefer-list\": preferList,\n \"no-get-unsafe\": noGetUnsafe,\n \"no-let\": noLet,\n \"prefer-fold\": preferFold,\n \"prefer-map\": preferMap,\n \"prefer-flatmap\": preferFlatmap,\n \"prefer-functype-map\": preferFunctypeMap,\n \"prefer-functype-set\": preferFunctypeSet,\n \"no-imperative-loops\": noImperativeLoops,\n \"prefer-do-notation\": preferDoNotation,\n}\n"],"mappings":"icA8BA,IAAA0B,EAAe,CACb,gBAAiB1B,EACjB,gBAAiBC,EACjB,aAAcC,EACd,cAAeC,EACf,gBAAiBC,EACjB,SAAUC,EACV,cAAeC,EACf,aAAcC,EACd,iBAAkBC,EAClB,sBAAuBC,EACvB,sBAAuBC,EACvB,sBAAuBC,EACvB,qBAAsBC,CACxB"}
1
+ {"version":3,"file":"index.js","names":["preferOption","preferEither","preferTry","preferList","noGetUnsafe","noLet","preferFold","preferMap","preferFlatmap","preferFunctypeMap","preferFunctypeSet","noImperativeLoops","preferDoNotation","collectionNaming","rule","rule$1","rule$2","rule$3","rule$4","rule$5","rule$6","rule$7","rule$8","rule$9","rule$10","rule$11","rule$12","rule$13","rules_default"],"sources":["../../src/rules/index.ts"],"sourcesContent":["import collectionNaming from \"./collection-naming\"\nimport noGetUnsafe from \"./no-get-unsafe\"\nimport noImperativeLoops from \"./no-imperative-loops\"\nimport noLet from \"./no-let\"\nimport preferDoNotation from \"./prefer-do-notation\"\nimport preferEither from \"./prefer-either\"\nimport preferFlatmap from \"./prefer-flatmap\"\nimport preferFold from \"./prefer-fold\"\nimport preferFunctypeMap from \"./prefer-functype-map\"\nimport preferFunctypeSet from \"./prefer-functype-set\"\nimport preferList from \"./prefer-list\"\nimport preferMap from \"./prefer-map\"\nimport preferOption from \"./prefer-option\"\nimport preferTry from \"./prefer-try\"\n\nexport {\n collectionNaming,\n noGetUnsafe,\n noImperativeLoops,\n noLet,\n preferDoNotation,\n preferEither,\n preferFlatmap,\n preferFold,\n preferFunctypeMap,\n preferFunctypeSet,\n preferList,\n preferMap,\n preferOption,\n preferTry,\n}\n\nexport default {\n \"prefer-option\": preferOption,\n \"prefer-either\": preferEither,\n \"prefer-try\": preferTry,\n \"prefer-list\": preferList,\n \"no-get-unsafe\": noGetUnsafe,\n \"no-let\": noLet,\n \"prefer-fold\": preferFold,\n \"prefer-map\": preferMap,\n \"prefer-flatmap\": preferFlatmap,\n \"prefer-functype-map\": preferFunctypeMap,\n \"prefer-functype-set\": preferFunctypeSet,\n \"no-imperative-loops\": noImperativeLoops,\n \"prefer-do-notation\": preferDoNotation,\n \"collection-naming\": collectionNaming,\n}\n"],"mappings":"ueAgCA,IAAA4B,EAAe,CACb,gBAAiB5B,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,CACvB"}
@@ -1,2 +1,2 @@
1
- import{getFunctypeImportsLegacy as e,isAlreadyUsingFunctype as t}from"../utils/functype-detection.js";import{createImportFixer as n,hasFunctypeSymbol as r}from"../utils/import-fixer.js";import{MAP_MUTATORS as i,annotatesMutatedBinding as a,isMutatedCollection as o}from"../utils/mutable-collection.js";const s={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 Map.empty()`,suggestMapOf:`Replace with Map.of(...)`,suggestMapFrom:`Replace with Map(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(s){let c=s.options[0]||{},l=c.allowInTests!==!1,u=c.allowMutable!==!1;function d(){let e=s.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}let f=e(s);function p(){return r(s.sourceCode,`Map`)}return{NewExpression(e){if(l&&d()||!e.callee||e.callee.type!==`Identifier`||e.callee.name!==`Map`||u&&o(e,i,s.sourceCode)||p()||t(e,f))return;let r=s.sourceCode,a=e.arguments,c=[];if(a.length===0)c.push({messageId:`suggestMapEmpty`,fix(t){return t.replaceText(e,`Map.empty()`)}});else if(a.length===1&&a[0].type===`ArrayExpression`){let t=a[0].elements.map(e=>r.getText(e)).join(`, `);c.push({messageId:`suggestMapOf`,fix(n){return n.replaceText(e,`Map.of(${t})`)}})}else if(a.length===1){let t=r.getText(a[0]);c.push({messageId:`suggestMapFrom`,fix(n){return n.replaceText(e,`Map(${t})`)}})}else c.push({messageId:`suggestMapEmpty`,fix(t){return t.replaceText(e,`Map.empty()`)}});p()||c.push({messageId:`suggestAddImport`,data:{symbol:`Map`},fix:n(r,`Map`)}),s.report({node:e,messageId:`preferFunctypeMapLiteral`,suggest:c})},TSTypeReference(e){if(l&&d()||!e.typeName)return;let t=s.sourceCode;if((e.typeName.type===`Identifier`?e.typeName.name:t.getText(e.typeName))!==`Map`||u&&a(e,i,s.sourceCode)||p())return;let r=e.typeArguments?.params??e.typeParameters?.params,o=r?.[0]?t.getText(r[0]):`K`,c=r&&r.length>=2?t.getText(r[1]):`V`,f=[{messageId:`suggestAddImport`,data:{symbol:`Map`},fix:n(t,`Map`)}];s.report({node:e,messageId:`preferFunctypeMap`,data:{keyType:o,valueType:c},suggest:f})}}}};export{s as default};
1
+ import{bindingOf as e,functypeLocalName as t,isExplicitNativeCollection as n}from"../utils/collection-binding.js";import{getFunctypeImportsLegacy as r,isAlreadyUsingFunctype as i}from"../utils/functype-detection.js";import{createImportFixer as a}from"../utils/import-fixer.js";import{MAP_MUTATORS as o,annotatesMutatedBinding as s,isMutatedCollection as c}from"../utils/mutable-collection.js";import{flowsIntoReadonlyContract as l}from"../utils/readonly-contract.js";const u={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(u){let d=u.options[0]||{},f=d.allowInTests!==!1,p=d.allowMutable!==!1;function m(){let e=u.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}let h=r(u);return{NewExpression(r){if(f&&m()||(r.callee?.type!==`Identifier`||r.callee.name!==`Map`||e(r.callee,`Map`,u.sourceCode)!==`native`)&&!n(r.callee,`Map`,u.sourceCode)||p&&c(r,o,u.sourceCode)||l(r,`ReadonlyMap`)||i(r,h))return;let s=u.sourceCode,d=t(s,`Map`),g=d??`Map`,_=r.arguments,v=[];if(_.length===0)v.push({messageId:`suggestMapEmpty`,data:{name:g},fix(e){return e.replaceText(r,`${g}.empty()`)}});else if(_.length===1&&_[0].type===`ArrayExpression`){let e=_[0].elements.map(e=>s.getText(e)).join(`, `);v.push({messageId:`suggestMapOf`,data:{name:g},fix(t){return t.replaceText(r,`${g}.of(${e})`)}})}else if(_.length===1){let e=s.getText(_[0]);v.push({messageId:`suggestMapFrom`,data:{name:g},fix(t){return t.replaceText(r,`${g}(${e})`)}})}else v.push({messageId:`suggestMapEmpty`,data:{name:g},fix(e){return e.replaceText(r,`${g}.empty()`)}});d===null&&v.push({messageId:`suggestAddImport`,data:{symbol:`Map`},fix:a(s,`Map`)}),u.report({node:r,messageId:`preferFunctypeMapLiteral`,suggest:v})},TSTypeReference(n){if(f&&m()||!n.typeName)return;let r=u.sourceCode,i=n.typeName.type===`Identifier`?n.typeName.name:r.getText(n.typeName);if(i!==`Map`&&i!==`globalThis.Map`||p&&s(n,o,u.sourceCode)||n.typeName.type===`Identifier`&&e(n.typeName,`Map`,u.sourceCode)!==`native`)return;let c=n.typeArguments?.params??n.typeParameters?.params,l=c?.[0]?r.getText(c[0]):`K`,d=c&&c.length>=2?r.getText(c[1]):`V`,h=t(r,`Map`),g=h===null?[{messageId:`suggestAddImport`,data:{symbol:`Map`},fix:a(r,`Map`)}]:[{messageId:`suggestUseLocalName`,data:{name:h},fix:e=>e.replaceText(n.typeName,h)}];u.report({node:n,messageId:`preferFunctypeMap`,data:{keyType:l,valueType:d},suggest:g})}}}};export{u 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,CACJ,YAAa,gFACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,aAAc,CACZ,KAAM,UACN,QAAS,EACX,E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ACF"}
1
+ {"version":3,"file":"prefer-functype-map.js","names":["rule","options","context","allowInTests","allowMutable","isInTestFile","filename","functypeImports","getFunctypeImportsLegacy","node","bindingOf","isExplicitNativeCollection","isMutatedCollection","MAP_MUTATORS","flowsIntoReadonlyContract","isAlreadyUsingFunctype","sourceCode","imported","functypeLocalName","name","args","suggestions","fixer","mapOfArgs","el","argText","createImportFixer","typeName","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, isExplicitNativeCollection } 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 // The built-in, however it's spelled: bare `Map` that resolves to the global (functype's import\n // or a local shadow doesn't count, #350), or explicit `globalThis.Map` — the spelling the\n // functype-by-default convention uses, which must not be an escape hatch (#349).\n const isBareNative =\n node.callee?.type === \"Identifier\" &&\n node.callee.name === \"Map\" &&\n bindingOf(node.callee, \"Map\", context.sourceCode) === \"native\"\n if (!isBareNative && !isExplicitNativeCollection(node.callee, \"Map\", context.sourceCode)) return\n\n if (allowMutable && isMutatedCollection(node, MAP_MUTATORS, context.sourceCode)) 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 // `Map<…>` or the explicit `globalThis.Map<…>`.\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Map\" && typeName !== \"globalThis.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":"mdASA,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,CAkB3B,GAjBIC,GAAgBE,EAAa,IAM/BI,EAAK,QAAQ,OAAS,cACtBA,EAAK,OAAO,OAAS,OACrBC,EAAUD,EAAK,OAAQ,MAAOP,EAAQ,UAAU,IAAM,WACnC,CAACS,EAA2BF,EAAK,OAAQ,MAAOP,EAAQ,UAAU,GAEnFE,GAAgBQ,EAAoBH,EAAMI,EAAcX,EAAQ,UAAU,GAG1EY,EAA0BL,EAAM,aAAa,G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Ae,CAG7B,GAFIlB,GAAgBE,EAAa,GAE7B,CAACI,EAAK,SAAU,OAEpB,IAAMO,EAAad,EAAQ,WAErByB,EAAWlB,EAAK,SAAS,OAAS,aAAeA,EAAK,SAAS,KAAOO,EAAW,QAAQP,EAAK,QAAQ,EAM5G,GAJIkB,IAAa,OAASA,IAAa,kBAEnCvB,GAAgBwB,EAAwBnB,EAAMI,EAAcX,EAAQ,UAAU,GAE9EO,EAAK,SAAS,OAAS,cAAgBC,EAAUD,EAAK,SAAU,MAAOP,EAAQ,UAAU,IAAM,SACjG,OAGF,IAAM2B,EAAapB,EAAK,eAAe,QAAUA,EAAK,gBAAgB,OAChEqB,EAAUD,IAAa,GAAKb,EAAW,QAAQa,EAAW,EAAE,EAAI,IAChEE,EAAYF,GAAcA,EAAW,QAAU,EAAIb,EAAW,QAAQa,EAAW,EAAE,EAAI,IAIvFZ,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,YAAYb,EAAK,SAAUQ,CAAQ,CAC3D,CACF,EAENf,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,UAAS,WAAU,EAC3B,QAASmB,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,hasFunctypeSymbol as r}from"../utils/import-fixer.js";import{SET_MUTATORS as i,annotatesMutatedBinding as a,isMutatedCollection as o}from"../utils/mutable-collection.js";const s={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 Set.empty()`,suggestSetOf:`Replace with Set.of(...)`,suggestSetFrom:`Replace with Set(...)`,suggestAddImport:`Add {{symbol}} import from functype`}},create(s){let c=s.options[0]||{},l=c.allowInTests!==!1,u=c.allowMutable!==!1;function d(){let e=s.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}let f=e(s);function p(){return r(s.sourceCode,`Set`)}return{NewExpression(e){if(l&&d()||!e.callee||e.callee.type!==`Identifier`||e.callee.name!==`Set`||u&&o(e,i,s.sourceCode)||p()||t(e,f))return;let r=s.sourceCode,a=e.arguments||[],c=[];if(a.length===0)c.push({messageId:`suggestSetEmpty`,fix(t){return t.replaceText(e,`Set.empty()`)}});else if(a.length===1&&a[0].type===`ArrayExpression`){let t=(a[0].elements||[]).map(e=>r.getText(e)).join(`, `);c.push({messageId:`suggestSetOf`,fix(n){return n.replaceText(e,`Set.of(${t})`)}})}else if(a.length===1){let t=r.getText(a[0]);c.push({messageId:`suggestSetFrom`,fix(n){return n.replaceText(e,`Set(${t})`)}})}else c.push({messageId:`suggestSetEmpty`,fix(t){return t.replaceText(e,`Set.empty()`)}});p()||c.push({messageId:`suggestAddImport`,data:{symbol:`Set`},fix:n(r,`Set`)}),s.report({node:e,messageId:`preferFunctypeSetLiteral`,suggest:c})},TSTypeReference(e){if(l&&d()||!e.typeName)return;let t=s.sourceCode;if((e.typeName.type===`Identifier`?e.typeName.name:t.getText(e.typeName))!==`Set`||u&&a(e,i,s.sourceCode)||p())return;let r=e.typeParameters?.params?.[0]??e.typeArguments?.params?.[0],o=r?t.getText(r):`T`,c=[{messageId:`suggestAddImport`,data:{symbol:`Set`},fix:n(t,`Set`)}];s.report({node:e,messageId:`preferFunctypeSet`,data:{type:o},suggest:c})}}}};export{s as default};
1
+ import{bindingOf as e,functypeLocalName as t,isExplicitNativeCollection as n}from"../utils/collection-binding.js";import{getFunctypeImportsLegacy as r,isAlreadyUsingFunctype as i}from"../utils/functype-detection.js";import{createImportFixer as a}from"../utils/import-fixer.js";import{SET_MUTATORS as o,annotatesMutatedBinding as s,isMutatedCollection as c}from"../utils/mutable-collection.js";import{flowsIntoReadonlyContract as l}from"../utils/readonly-contract.js";const u={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(u){let d=u.options[0]||{},f=d.allowInTests!==!1,p=d.allowMutable!==!1;function m(){let e=u.filename;return/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(e)||e.includes(`__tests__`)||e.includes(`/test/`)||e.includes(`/tests/`)}let h=r(u);return{NewExpression(r){if(f&&m()||(r.callee?.type!==`Identifier`||r.callee.name!==`Set`||e(r.callee,`Set`,u.sourceCode)!==`native`)&&!n(r.callee,`Set`,u.sourceCode)||p&&c(r,o,u.sourceCode)||l(r,`ReadonlySet`)||i(r,h))return;let s=u.sourceCode,d=t(s,`Set`),g=d??`Set`,_=r.arguments||[],v=[];if(_.length===0)v.push({messageId:`suggestSetEmpty`,data:{name:g},fix(e){return e.replaceText(r,`${g}.empty()`)}});else if(_.length===1&&_[0].type===`ArrayExpression`){let e=(_[0].elements||[]).map(e=>s.getText(e)).join(`, `);v.push({messageId:`suggestSetOf`,data:{name:g},fix(t){return t.replaceText(r,`${g}.of(${e})`)}})}else if(_.length===1){let e=s.getText(_[0]);v.push({messageId:`suggestSetFrom`,data:{name:g},fix(t){return t.replaceText(r,`${g}(${e})`)}})}else v.push({messageId:`suggestSetEmpty`,data:{name:g},fix(e){return e.replaceText(r,`${g}.empty()`)}});d===null&&v.push({messageId:`suggestAddImport`,data:{symbol:`Set`},fix:a(s,`Set`)}),u.report({node:r,messageId:`preferFunctypeSetLiteral`,suggest:v})},TSTypeReference(n){if(f&&m()||!n.typeName)return;let r=u.sourceCode,i=n.typeName.type===`Identifier`?n.typeName.name:r.getText(n.typeName);if(i!==`Set`&&i!==`globalThis.Set`||p&&s(n,o,u.sourceCode)||n.typeName.type===`Identifier`&&e(n.typeName,`Set`,u.sourceCode)!==`native`)return;let c=n.typeParameters?.params?.[0]??n.typeArguments?.params?.[0],l=c?r.getText(c):`T`,d=t(r,`Set`),h=d===null?[{messageId:`suggestAddImport`,data:{symbol:`Set`},fix:a(r,`Set`)}]:[{messageId:`suggestUseLocalName`,data:{name:d},fix:e=>e.replaceText(n.typeName,d)}];u.report({node:n,messageId:`preferFunctypeSet`,data:{type:l},suggest:h})}}}};export{u 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,QAAS,EACX,EACA,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,kBAAmB,gDACnB,yBAA0B,mDAC1B,gBAAiB,2BACjB,aAAc,2BACd,eAAgB,wBAChB,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,SAASO,GAA4B,CACnC,OAAOC,EAAkBR,EAAQ,WAAY,KAAK,CACpD,CAEA,MAAO,CACL,cAAc,EAAe,CAY3B,GAXIC,GAAgBE,EAAa,GAG7B,CAACM,EAAK,QAAUA,EAAK,OAAO,OAAS,cAAgBA,EAAK,OAAO,OAAS,OAE1EP,GAAgBQ,EAAoBD,EAAME,EAAcX,EAAQ,UAAU,GAG1EO,EAA0B,GAG1BK,EAAuBH,EAAMJ,C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AAgBmB,EAAwBZ,EAAME,EAAcX,EAAQ,UAAU,GAG9EO,EAA0B,EAAG,OAGjC,IAAMe,EAAgBb,EAAK,gBAAgB,SAAS,IAAMA,EAAK,eAAe,SAAS,GACjFc,EAAYD,EAAgBT,EAAW,QAAQS,CAAa,EAAI,IAEhEP,EAAiD,CACrD,CACE,UAAW,mBACX,KAAM,CAAE,OAAQ,KAAM,EACtB,IAAKK,EAAkBP,EAAY,KAAK,CAC1C,CACF,EAEAb,EAAQ,OAAO,CACb,OACA,UAAW,oBACX,KAAM,CAAE,KAAMuB,CAAU,EACxB,QAASR,CACX,CAAC,CACH,CACF,CACF,CACF"}
1
+ {"version":3,"file":"prefer-functype-set.js","names":["rule","options","context","allowInTests","allowMutable","isInTestFile","filename","functypeImports","getFunctypeImportsLegacy","node","bindingOf","isExplicitNativeCollection","isMutatedCollection","SET_MUTATORS","flowsIntoReadonlyContract","isAlreadyUsingFunctype","sourceCode","imported","functypeLocalName","name","args","suggestions","fixer","argsText","el","argText","createImportFixer","typeName","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, isExplicitNativeCollection } 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 // The built-in, however it's spelled: bare `Set` that resolves to the global (functype's import\n // or a local shadow doesn't count, #350), or explicit `globalThis.Set` — the spelling the\n // functype-by-default convention uses, which must not be an escape hatch (#349).\n const isBareNative =\n node.callee?.type === \"Identifier\" &&\n node.callee.name === \"Set\" &&\n bindingOf(node.callee, \"Set\", context.sourceCode) === \"native\"\n if (!isBareNative && !isExplicitNativeCollection(node.callee, \"Set\", context.sourceCode)) return\n\n if (allowMutable && isMutatedCollection(node, SET_MUTATORS, context.sourceCode)) 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 // `Set<…>` or the explicit `globalThis.Set<…>`.\n const typeName = node.typeName.type === \"Identifier\" ? node.typeName.name : sourceCode.getText(node.typeName)\n\n if (typeName !== \"Set\" && typeName !== \"globalThis.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":"mdASA,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,QAAS,EACX,EACA,aAAc,CACZ,KAAM,UACN,QAAS,EACX,CACF,EACA,qBAAsB,EACxB,CACF,EACA,SAAU,CACR,kBAAmB,gDACnB,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,EA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Code } 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
+ export declare const COLLECTION_NAMES: ReadonlyArray<string>;
21
+ /**
22
+ * If `expr` names functype's `Map` / `Set` — an identifier bound to its import (any local name), or a
23
+ * namespace member like `F.Map` — returns the imported name and how this file spells it; else null.
24
+ */
25
+ export declare const functypeCollectionAt: (expr: ASTNode, sourceCode: SourceCode) => {
26
+ readonly name: string;
27
+ readonly local: string;
28
+ } | null;
29
+ /**
30
+ * Is `callee` the built-in constructor spelled explicitly — `globalThis.Map` / `globalThis.Set`, or
31
+ * functype's `ESMap` re-export of the native Map? Bare `Map` is handled by {@link bindingOf}.
32
+ */
33
+ export declare const isExplicitNativeCollection: (callee: ASTNode, name: string, sourceCode: SourceCode) => boolean;
34
+ //#endregion
35
+ //# 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,i=[`Map`,`Set`],a=(n,r)=>{if(n?.type===`Identifier`){let a=t(n,n.name,r)?.defs[0];if(a?.type!==`ImportBinding`||!e(a.parent?.source?.value))return null;let o=a.node;return o?.type!==`ImportSpecifier`||o.imported?.type!==`Identifier`?null:i.includes(o.imported.name)?{name:o.imported.name,local:n.name}:null}if(n?.type===`MemberExpression`&&!n.computed&&n.object.type===`Identifier`&&n.property.type===`Identifier`&&i.includes(n.property.name)){let i=t(n.object,n.object.name,r)?.defs[0];return i?.type===`ImportBinding`&&i.node?.type===`ImportNamespaceSpecifier`&&e(i.parent?.source?.value)?{name:n.property.name,local:`${n.object.name}.${n.property.name}`}:null}return null},o=(n,r,i)=>{if(n?.type===`MemberExpression`&&!n.computed&&n.object.type===`Identifier`&&n.object.name===`globalThis`&&n.property.type===`Identifier`&&n.property.name===r)return!t(n.object,`globalThis`,i)?.defs.length;if(n?.type===`Identifier`&&r===`Map`){let r=t(n,n.name,i)?.defs[0];return r?.type===`ImportBinding`&&e(r.parent?.source?.value)&&r.node?.type===`ImportSpecifier`&&r.node.imported?.name===`ESMap`}return!1};export{i as COLLECTION_NAMES,n as bindingOf,a as functypeCollectionAt,r as functypeLocalName,o as isExplicitNativeCollection};
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","COLLECTION_NAMES","functypeCollectionAt","expr","isExplicitNativeCollection","callee"],"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\nexport const COLLECTION_NAMES: ReadonlyArray<string> = [\"Map\", \"Set\"]\n\n/**\n * If `expr` names functype's `Map` / `Set` — an identifier bound to its import (any local name), or a\n * namespace member like `F.Map` — returns the imported name and how this file spells it; else null.\n */\nexport const functypeCollectionAt = (\n expr: ASTNode,\n sourceCode: SourceCode,\n): { readonly name: string; readonly local: string } | null => {\n if (expr?.type === \"Identifier\") {\n const def = resolve(expr, expr.name, sourceCode)?.defs[0] as\n { readonly type: string; readonly node?: ASTNode; readonly parent?: ASTNode } | undefined\n if (def?.type !== \"ImportBinding\" || !isFunctypeSource(def.parent?.source?.value)) return null\n const spec = def.node\n if (spec?.type !== \"ImportSpecifier\" || spec.imported?.type !== \"Identifier\") return null\n return COLLECTION_NAMES.includes(spec.imported.name) ? { name: spec.imported.name, local: expr.name } : null\n }\n if (\n expr?.type === \"MemberExpression\" &&\n !expr.computed &&\n expr.object.type === \"Identifier\" &&\n expr.property.type === \"Identifier\" &&\n COLLECTION_NAMES.includes(expr.property.name)\n ) {\n const def = resolve(expr.object, expr.object.name, sourceCode)?.defs[0] as\n { readonly type: string; readonly node?: ASTNode; readonly parent?: ASTNode } | undefined\n const isNamespace =\n def?.type === \"ImportBinding\" &&\n def.node?.type === \"ImportNamespaceSpecifier\" &&\n isFunctypeSource(def.parent?.source?.value)\n return isNamespace ? { name: expr.property.name, local: `${expr.object.name}.${expr.property.name}` } : null\n }\n return null\n}\n\n/**\n * Is `callee` the built-in constructor spelled explicitly — `globalThis.Map` / `globalThis.Set`, or\n * functype's `ESMap` re-export of the native Map? Bare `Map` is handled by {@link bindingOf}.\n */\nexport const isExplicitNativeCollection = (callee: ASTNode, name: string, sourceCode: SourceCode): boolean => {\n if (\n callee?.type === \"MemberExpression\" &&\n !callee.computed &&\n callee.object.type === \"Identifier\" &&\n callee.object.name === \"globalThis\" &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === name\n ) {\n // A local binding named `globalThis` would shadow the real one.\n return resolve(callee.object, \"globalThis\", sourceCode)?.defs.length ? false : true\n }\n if (callee?.type === \"Identifier\" && name === \"Map\") {\n const def = resolve(callee, callee.name, sourceCode)?.defs[0] as\n { readonly type: string; readonly node?: ASTNode; readonly parent?: ASTNode } | undefined\n return (\n def?.type === \"ImportBinding\" &&\n isFunctypeSource(def.parent?.source?.value) &&\n def.node?.type === \"ImportSpecifier\" &&\n def.node.imported?.name === \"ESMap\"\n )\n }\n return false\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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d,IAAS,MAAO,CACnD,IAAMK,EAAMR,EAAQiB,EAAQA,EAAO,KAAMb,CAAU,CAAC,EAAE,KAAK,GAE3D,OACEI,GAAK,OAAS,iBACdV,EAAiBU,EAAI,QAAQ,QAAQ,KAAK,GAC1CA,EAAI,MAAM,OAAS,mBACnBA,EAAI,KAAK,UAAU,OAAS,OAEhC,CACA,MAAO,EACT"}
@@ -0,0 +1,5 @@
1
+ import { ASTNode } from "../types/ast.js";
2
+ //#region src/utils/readonly-contract.d.ts
3
+ export declare const flowsIntoReadonlyContract: (node: ASTNode, readonlyName: string) => boolean;
4
+ //#endregion
5
+ //# sourceMappingURL=readonly-contract.d.ts.map
@@ -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,kBAAiC,IAAI,IAAI,CAAC,sBAAuB,qBAAsB,yBAAyB,CAAC,EAEjHC,GAAW,EAA2B,IAC1CC,GAAM,OAAS,mBAAqBA,EAAK,UAAU,OAAS,cAAgBA,EAAK,SAAS,OAASC,EAE/FC,EAAY,GACfF,EAAK,eAAe,QAAUA,EAAK,gBAAgB,QAAU,CAAC,EAG3DG,GAAsB,EAA2B,IACrDJ,EAAQC,EAAMI,CAAY,GAAML,EAAQC,EAAM,SAAS,GAAKG,EAAmBD,EAASF,CAAK,CAAC,CAAC,GAAII,CAAY,EAE3GC,EAAgB,GAAmDC,GAAM,gBAAgB,eAEzFC,EAAmB,GACvBD,GAA+B,KAAO,IAAA,GAAYR,EAAU,IAAIQ,EAAK,IAAI,EAAIA,EAAOC,EAAgBD,EAAK,MAAM,EAEpGE,GAA6B,EAAe,IAAkC,CACzF,IAAMC,EAASH,EAAK,OACpB,GAAI,CAACG,EAAQ,MAAO,GACpB,OAAQA,EAAO,KAAf,CACE,IAAK,wBACH,OAAOA,EAAO,OAASH,GAAQE,EAA0BC,EAAQL,CAAY,EAC/E,IAAK,oBACH,OAAOI,EAA0BC,EAAQL,CAAY,EACvD,IAAK,iBACL,IAAK,wBACH,OAAOD,EAAmBM,EAAO,eAAgBL,CAAY,GAAKI,EAA0BC,EAAQL,CAAY,EAClH,IAAK,kBACH,OAAOD,EAAmBI,EAAgBE,CAAM,CAAC,EAAE,YAAY,eAAgBL,CAAY,EAC7F,IAAK,0BACH,OAAOK,EAAO,OAASH,GAAQH,EAAmBM,EAAO,YAAY,eAAgBL,CAAY,EACnG,IAAK,qBACH,OAAOK,EAAO,OAASH,GAAQH,EAAmBE,EAAaI,EAAO,EAAE,EAAGL,CAAY,EACzF,IAAK,qBACH,OAAOK,EAAO,QAAUH,GAAQH,EAAmBE,EAAaI,CAAM,EAAGL,CAAY,EACvF,IAAK,oBACH,OAAOK,EAAO,QAAUH,GAAQH,EAAmBE,EAAaI,EAAO,IAAI,EAAGL,CAAY,EAC5F,QACE,MAAO,EACX,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-functype",
3
- "version": "2.111.0",
3
+ "version": "2.112.0",
4
4
  "description": "Custom ESLint rules for functional TypeScript programming with functype library patterns including Do notation (ESLint 10+)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -42,7 +42,7 @@
42
42
  "@types/node": "^24.19.0",
43
43
  "@typescript-eslint/rule-tester": "^8.71.0",
44
44
  "eslint-config-prettier": "^10.1.8",
45
- "functype": "^1.11.0",
45
+ "functype": "^1.12.0",
46
46
  "ts-builds": "^3.4.3",
47
47
  "tsdown": "^0.23.0"
48
48
  },