eslint-plugin-functype 2.125.1 → 2.126.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
CHANGED
|
@@ -424,6 +424,12 @@ When the code after the guard awaits, the advice uses `flatMapAsync` / `foldAsyn
|
|
|
424
424
|
|
|
425
425
|
`null` is idiomatic React state, and an `Option` there fights the hook's own API.
|
|
426
426
|
|
|
427
|
+
The message names both ways out, because a nullable type can be a correct boundary shape. Use `Option` when your own code reads the absence, and `Wire<…>` when a serializer, driver, schema or host reads it. [Wire or Option?](https://functype.org/wire#wire-or-option) has the full rule.
|
|
428
|
+
|
|
429
|
+
One union holding both `null` and `undefined`, as a type alias's body or a type-literal or interface member, gets its own message and no `Option` suggestion. So does an optional member that can also be `null` (`a?: T | null`). Left out, cleared and set are three states, and `Option` has two, so the message names both fixes: `Wire<…>` for a row, body or payload, or, for a value that only meant "may be absent", one of the two spellings and `Option`. A parameter's own type, a return type, a variable or a class field with that union keeps the `Option` message. A member inside a parameter's type, such as an options bag, is still a shape, so it gets the three-state message.
|
|
430
|
+
|
|
431
|
+
A union nested in a union, such as `(string | null) | undefined`, is read as one union and reported once.
|
|
432
|
+
|
|
427
433
|
On a type-literal or interface member, and on a parameter, `a?: T` and `a: T | undefined` both mean "may be absent", so both are skipped by default. The caller writes `<X b="v" />` or `f()`, and an `Option` there would make every caller wrap the value. Skipping only one spelling would teach people to rewrite `b: string | undefined` as `b?: string`, which makes a required key optional.
|
|
428
434
|
|
|
429
435
|
```ts
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{getFunctypeImportsLegacy as t,isAlreadyUsingFunctype as n,isFunctypeType as r}from"../utils/functype-detection.js";import{createImportFixer as i,hasFunctypeSymbol as a}from"../utils/import-fixer.js";import{DEFAULT_WIRE_TYPES as o,WIRE_TYPES_SCHEMA as s,isInsideWireType as c}from"../utils/wire-types.js";const l=/* @__PURE__ */ new Set([`useState`,`useRef`]),u=e=>e.type===`TSNullKeyword`||e.type===`TSUndefinedKeyword`;function d(e){let t=e.parent;if(!t)return!1;if(t.type===`AssignmentPattern`&&t.left===e)return d(t);if(t.type===`TSParameterProperty`)return!0;let n=t.params;return Array.isArray(n)&&n.includes(e)}function f(e){let t=e?.type===`TSTypeAnnotation`?e.parent:void 0;if(t)return t.type===`TSPropertySignature`||d(t)?t:void 0}
|
|
1
|
+
import{isInsideTaggedDeclaration as e}from"../utils/boundary-tags.js";import{getFunctypeImportsLegacy as t,isAlreadyUsingFunctype as n,isFunctypeType as r}from"../utils/functype-detection.js";import{createImportFixer as i,hasFunctypeSymbol as a}from"../utils/import-fixer.js";import{DEFAULT_WIRE_TYPES as o,WIRE_TYPES_SCHEMA as s,isInsideWireType as c}from"../utils/wire-types.js";const l=/* @__PURE__ */ new Set([`useState`,`useRef`]),u=e=>e.type===`TSNullKeyword`||e.type===`TSUndefinedKeyword`;function d(e){let t=e.parent;if(!t)return!1;if(t.type===`AssignmentPattern`&&t.left===e)return d(t);if(t.type===`TSParameterProperty`)return!0;let n=t.params;return Array.isArray(n)&&n.includes(e)}function f(e){let t=e?.type===`TSTypeAnnotation`?e.parent:void 0;if(t)return t.type===`TSPropertySignature`||d(t)?t:void 0}function p(e){return e.types.flatMap(e=>e.type===`TSUnionType`?p(e):[e])}function m(e,t){if(!t.some(e=>e.type===`TSNullKeyword`))return;let n=e.parent,r=n?.type===`TSTypeAnnotation`?n.parent:void 0,i=r?.type===`TSPropertySignature`?r:void 0;if(i?.optional===!0)return`the ? or the | null`;if(t.some(e=>e.type===`TSUndefinedKeyword`))return n?.type===`TSTypeAliasDeclaration`||i!==void 0?`the | null or the | undefined`:void 0}const h={meta:{type:`suggestion`,hasSuggestions:!0,docs:{description:`Prefer Option<T> over nullable types (T | null | undefined)`,recommended:!0},schema:[{type:`object`,properties:{allowInteropMarker:{type:`boolean`,default:!0},wireTypes:s,allowNullableIntersections:{type:`boolean`,default:!1},allowUseState:{type:`boolean`,default:!0},checkOptionalMembers:{type:`boolean`,default:!1}},additionalProperties:!1}],messages:{preferOption:`Prefer Option<{{type}}> over nullable type '{{nullable}}'. If this is a row, body or payload shape, wrap the type in Wire<…>`,preferOptionReturn:`Prefer Option<{{type}}> as return type over nullable '{{nullable}}'`,preferOptionOverOptional:`Prefer '{{name}}: Option<{{type}}>' over the optional '{{name}}?'. If this is a row, body or payload shape, wrap the type in Wire<…>`,preferWireForThreeStates:`This type has three states, left out, null and set, and Option holds two. If it's a row, body or payload shape, wrap the type in Wire<…>. If it only meant "may be absent", drop {{drop}} and use Option<{{type}}>`,suggestOptionType:`Replace with Option<{{type}}>`,suggestAddImport:`Add {{symbol}} import from functype`}},create(s){let h=s.options[0]||{},g=h.wireTypes??o,_=h.allowInteropMarker!==!1,v=t=>_&&e(t,`interop`,s.sourceCode),y=h.allowUseState!==!1,b=h.checkOptionalMembers===!0;function x(e){let t=e.parent;if(!t)return!1;if(t.type===`TSTypeParameterInstantiation`&&t.parent?.type===`CallExpression`){let e=t.parent.callee,n=e.type===`Identifier`?e.name:e.type===`MemberExpression`&&e.property.type===`Identifier`?e.property.name:null;if(n!==null&&l.has(n))return!0}return x(t)}let S=t(s);function C(e){if(!b||e.optional!==!0||e.type!==`TSPropertySignature`&&!d(e)||c(e,g)||v(e))return;let t=e.typeAnnotation?.typeAnnotation;if(!t||r(t,S))return;let n=t.type===`TSUnionType`?p(t):[t];if(n.some(e=>e.type===`TSNullKeyword`))return;let i=n.filter(e=>!u(e));if(i.length!==1||r(i[0],S))return;let a=e.type===`TSPropertySignature`?e.key:e,o=a.type===`Identifier`?a.name:a.type===`Literal`?String(a.value):s.sourceCode.getText(a);s.report({node:a,messageId:`preferOptionOverOptional`,data:{name:o,type:s.sourceCode.getText(i[0])}})}return{TSPropertySignature:C,Identifier:C,TSUnionType(e){if(e.parent?.type===`TSUnionType`||c(e,g)||v(e)||!e.types||e.types.length<2)return;let t=e.types;if(!t.some(e=>u(e))||t.filter(e=>!u(e)).length!==1||y&&x(e))return;let o=p(e);if(!o.some(e=>u(e)))return;let l=f(e.parent),d=!o.some(e=>e.type===`TSNullKeyword`);if(l&&d&&(!b||l.optional===!0))return;let h=o.filter(e=>!u(e));if(h.length===1){let t=h[0];if(r(t,S)||n(e,S))return;let c=s.sourceCode,l=c.getText(t),u=c.getText(e);if(l.startsWith(`Option<`))return;let d=m(e,o);if(d!==void 0){s.report({node:e,messageId:`preferWireForThreeStates`,data:{type:l,drop:d}});return}let f=[{messageId:`suggestOptionType`,data:{type:l},fix(t){return t.replaceText(e,`Option<${l}>`)}}];a(c,`Option`)||f.push({messageId:`suggestAddImport`,data:{symbol:`Option`},fix:i(c,`Option`)}),s.report({node:e,messageId:`preferOption`,data:{type:l,nullable:u},suggest:f})}}}}};export{h as default};
|
|
2
2
|
//# sourceMappingURL=prefer-option.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prefer-option.js","names":["REACT_STATE_HOOKS","isNullish","type","isParameter","parent","node","params","memberOrParameterOf","owner","annotation","rule","WIRE_TYPES_SCHEMA","options","context","wireTypes","DEFAULT_WIRE_TYPES","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowUseState","checkOptionalMembers","isInHookTypeArgument","callee","name","functypeImports","getFunctypeImportsLegacy","checkOptional","isInsideWireType","isFunctypeType","t","kept","key","undefinedOnly","nonNullTypes","nonNullType","isAlreadyUsingFunctype","sourceCode","nonNullTypeText","fullType","suggestions","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-option.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype, isFunctypeType } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\n\nconst REACT_STATE_HOOKS: ReadonlySet<string> = new Set([\"useState\", \"useRef\"])\n\nconst isNullish = (type: ASTNode): boolean => type.type === \"TSNullKeyword\" || type.type === \"TSUndefinedKeyword\"\n\n/** Is `node` a parameter: of a function, a method signature or a function type, with or without a default? */\nfunction isParameter(node: ASTNode): boolean {\n const parent = node.parent as ASTNode | undefined\n if (!parent) return false\n if (parent.type === \"AssignmentPattern\" && parent.left === node) return isParameter(parent)\n if (parent.type === \"TSParameterProperty\") return true\n const params = (parent as { readonly params?: ReadonlyArray<ASTNode> }).params\n return Array.isArray(params) && params.includes(node)\n}\n\n/**\n * The member or parameter a type annotation belongs to, when it's the annotation of a type-literal or\n * interface member (`b: string | undefined`) or a parameter (`(x: string | undefined) => …`). Those are\n * the caller's shapes: a prop, an options-bag field, an argument (#446).\n */\nfunction memberOrParameterOf(annotation: ASTNode | undefined): ASTNode | undefined {\n const owner = annotation?.type === \"TSTypeAnnotation\" ? (annotation.parent as ASTNode | undefined) : undefined\n if (!owner) return undefined\n if (owner.type === \"TSPropertySignature\") return owner\n return isParameter(owner) ? owner : undefined\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Option<T> over nullable types (T | null | undefined)\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowNullableIntersections: {\n type: \"boolean\",\n default: false,\n },\n allowUseState: {\n type: \"boolean\",\n default: true,\n },\n checkOptionalMembers: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferOption: \"Prefer Option<{{type}}> over nullable type '{{nullable}}'\",\n preferOptionReturn: \"Prefer Option<{{type}}> as return type over nullable '{{nullable}}'\",\n preferOptionOverOptional: \"Prefer '{{name}}: Option<{{type}}>' over the optional '{{name}}?'\",\n suggestOptionType: \"Replace with Option<{{type}}>\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // Everything inside `Wire<…>` is the declared serialization shape (#325 B).\n const wireTypes: ReadonlyArray<string> = options.wireTypes ?? DEFAULT_WIRE_TYPES\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n // `null` is idiomatic React state (`useState<User | null>(null)`, `useRef<El | null>(null)`); an\n // Option in a hook's type argument buys nothing and fights the hook's own API (#325).\n const allowUseState = options.allowUseState !== false\n // `a?: T` and `a: T | undefined` on a member or parameter both mean \"may be absent\", and the caller\n // writes `<X b=\"v\" />` or `f()`. Skip both unless asked to report them (#446).\n const checkOptionalMembers = options.checkOptionalMembers === true\n\n /** Is `node` inside the type argument of a `useState` / `useRef` call (bare or `React.`-qualified)? */\n function isInHookTypeArgument(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"TSTypeParameterInstantiation\" && parent.parent?.type === \"CallExpression\") {\n const callee = parent.parent.callee\n const name =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (name !== null && REACT_STATE_HOOKS.has(name)) return true\n }\n return isInHookTypeArgument(parent)\n }\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n /** With checkOptionalMembers, `a?: T` on a member or parameter is reported like `a: T | undefined`. */\n function checkOptional(node: ASTNode): void {\n if (!checkOptionalMembers || node.optional !== true) return\n if (node.type !== \"TSPropertySignature\" && !isParameter(node)) return\n if (isInsideWireType(node, wireTypes) || isExemptByMarker(node)) return\n const annotation = (node.typeAnnotation as ASTNode | undefined)?.typeAnnotation as ASTNode | undefined\n if (!annotation || isFunctypeType(annotation, functypeImports)) return\n // `a?: T | null` is reported once, by the union check, which keeps its suggestions.\n if (annotation.type === \"TSUnionType\" && annotation.types.some((t: ASTNode) => t.type === \"TSNullKeyword\")) return\n const kept =\n annotation.type === \"TSUnionType\" ? annotation.types.filter((t: ASTNode) => !isNullish(t)) : [annotation]\n if (kept.length !== 1 || isFunctypeType(kept[0], functypeImports)) return\n const key = (node.type === \"TSPropertySignature\" ? node.key : node) as ASTNode\n const name =\n key.type === \"Identifier\"\n ? key.name\n : key.type === \"Literal\"\n ? String(key.value)\n : context.sourceCode.getText(key)\n context.report({\n node: key,\n messageId: \"preferOptionOverOptional\",\n data: { name, type: context.sourceCode.getText(kept[0]) },\n })\n }\n\n return {\n TSPropertySignature: checkOptional,\n Identifier: checkOptional,\n\n TSUnionType(node: ASTNode) {\n if (isInsideWireType(node, wireTypes)) return\n if (isExemptByMarker(node)) return\n if (!node.types || node.types.length < 2) return\n if (allowUseState && isInHookTypeArgument(node)) return\n\n const hasNull = node.types.some((type: ASTNode) => isNullish(type))\n\n if (!hasNull) return\n\n // On a member or parameter, `T | undefined` is the same \"may be absent\" as `?:`: skipped unless\n // checkOptionalMembers is on, and never reported on an optional one (`c?: T | undefined` is the\n // spelling exactOptionalPropertyTypes needs; the optional-member check reports it, once).\n const owner = memberOrParameterOf(node.parent)\n const undefinedOnly = !node.types.some((type: ASTNode) => type.type === \"TSNullKeyword\")\n if (owner && undefinedOnly && (!checkOptionalMembers || owner.optional === true)) return\n\n const nonNullTypes = node.types.filter((type: ASTNode) => !isNullish(type))\n\n if (nonNullTypes.length === 1) {\n const nonNullType = nonNullTypes[0]\n\n // Skip if it's already an Option type or other functype type\n if (isFunctypeType(nonNullType, functypeImports)) return\n\n // Skip if we're already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const nonNullTypeText = sourceCode.getText(nonNullType)\n const fullType = sourceCode.getText(node)\n\n // Skip if it's already an Option type (fallback check)\n if (nonNullTypeText.startsWith(\"Option<\")) return\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestOptionType\",\n data: { type: nonNullTypeText },\n fix(fixer) {\n return fixer.replaceText(node, `Option<${nonNullTypeText}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"Option\")) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Option\" },\n fix: createImportFixer(sourceCode, \"Option\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferOption\",\n data: {\n type: nonNullTypeText,\n nullable: fullType,\n },\n suggest: suggestions,\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"6XAQA,MAAMA,kBAAyC,IAAI,IAAI,CAAC,WAAY,QAAQ,CAAC,EAEvEC,EAAa,GAA2BC,EAAK,OAAS,iBAAmBA,EAAK,OAAS,qBAG7F,SAASC,EAAY,EAAwB,CAC3C,IAAMC,EAASC,EAAK,OACpB,GAAI,CAACD,EAAQ,MAAO,GACpB,GAAIA,EAAO,OAAS,qBAAuBA,EAAO,OAASC,EAAM,OAAOF,EAAYC,CAAM,EAC1F,GAAIA,EAAO,OAAS,sBAAuB,MAAO,GAClD,IAAME,EAAUF,EAAwD,OACxE,OAAO,MAAM,QAAQE,CAAM,GAAKA,EAAO,SAASD,CAAI,CACtD,CAOA,SAASE,EAAoB,EAAsD,CACjF,IAAMC,EAAQC,GAAY,OAAS,mBAAsBA,EAAW,OAAiC,IAAA,GACrG,GAAKD,EAEL,OADIA,EAAM,OAAS,uBACZL,EAAYK,CAAK,EADyBA,EACb,IAAA,EACtC,CAEA,MAAME,EAAwB,CAC5B,KAAM,CACJ,KAAM,aACN,eAAgB,GAChB,KAAM,CACJ,YAAa,8DACb,YAAa,EACf,EACA,OAAQ,CACN,CACE,KAAM,SACN,WAAY,CACV,mBAAoB,CAClB,KAAM,UACN,QAAS,EACX,EACA,UAAWC,EACX,2BA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CAAW,EAChDI,EAAWF,EAAW,QAAQ/B,CAAI,EAGxC,GAAIgC,EAAgB,WAAW,SAAS,EAAG,OAE3C,IAAME,EAAiD,CACrD,CACE,UAAW,oBACX,KAAM,CAAE,KAAMF,CAAgB,EAC9B,IAAI,EAAO,CACT,OAAOG,EAAM,YAAYnC,EAAM,UAAUgC,EAAgB,EAAE,CAC7D,CACF,CACF,EAEKI,EAAkBL,EAAY,QAAQ,GACzCG,EAAY,KAAK,CACf,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKG,EAAkBN,EAAY,QAAQ,CAC7C,CAAC,EAGHvB,EAAQ,OAAO,CACb,OACA,UAAW,eACX,KAAM,CACJ,KAAMwB,EACN,SAAUC,CACZ,EACA,QAASC,CACX,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"prefer-option.js","names":["REACT_STATE_HOOKS","isNullish","type","isParameter","parent","node","params","memberOrParameterOf","owner","annotation","unionMembers","union","t","threeStateSpellings","members","member","rule","WIRE_TYPES_SCHEMA","options","context","wireTypes","DEFAULT_WIRE_TYPES","allowInteropMarker","isExemptByMarker","isInsideTaggedDeclaration","allowUseState","checkOptionalMembers","isInHookTypeArgument","callee","name","functypeImports","getFunctypeImportsLegacy","checkOptional","isInsideWireType","isFunctypeType","kept","key","direct","undefinedOnly","nonNullTypes","nonNullType","isAlreadyUsingFunctype","sourceCode","nonNullTypeText","fullType","drop","suggestions","fixer","hasFunctypeSymbol","createImportFixer"],"sources":["../../src/rules/prefer-option.ts"],"sourcesContent":["import type { Rule } from \"eslint\"\n\nimport type { ASTNode } from \"../types/ast\"\nimport { INTEROP_TAG, isInsideTaggedDeclaration } from \"../utils/boundary-tags\"\nimport { getFunctypeImportsLegacy, isAlreadyUsingFunctype, isFunctypeType } from \"../utils/functype-detection\"\nimport { createImportFixer, hasFunctypeSymbol } from \"../utils/import-fixer\"\nimport { DEFAULT_WIRE_TYPES, isInsideWireType, WIRE_TYPES_SCHEMA } from \"../utils/wire-types\"\n\nconst REACT_STATE_HOOKS: ReadonlySet<string> = new Set([\"useState\", \"useRef\"])\n\nconst isNullish = (type: ASTNode): boolean => type.type === \"TSNullKeyword\" || type.type === \"TSUndefinedKeyword\"\n\n/** Is `node` a parameter: of a function, a method signature or a function type, with or without a default? */\nfunction isParameter(node: ASTNode): boolean {\n const parent = node.parent as ASTNode | undefined\n if (!parent) return false\n if (parent.type === \"AssignmentPattern\" && parent.left === node) return isParameter(parent)\n if (parent.type === \"TSParameterProperty\") return true\n const params = (parent as { readonly params?: ReadonlyArray<ASTNode> }).params\n return Array.isArray(params) && params.includes(node)\n}\n\n/**\n * The member or parameter a type annotation belongs to, when it's the annotation of a type-literal or\n * interface member (`b: string | undefined`) or a parameter (`(x: string | undefined) => …`). Those are\n * the caller's shapes: a prop, an options-bag field, an argument (#446).\n */\nfunction memberOrParameterOf(annotation: ASTNode | undefined): ASTNode | undefined {\n const owner = annotation?.type === \"TSTypeAnnotation\" ? (annotation.parent as ASTNode | undefined) : undefined\n if (!owner) return undefined\n if (owner.type === \"TSPropertySignature\") return owner\n return isParameter(owner) ? owner : undefined\n}\n\n/**\n * A union's members, with nested unions spread in. The parser drops parentheses, so `(A | null) | undefined`\n * is a union holding a union; spread, it holds A, null and undefined.\n */\nfunction unionMembers(union: ASTNode): ReadonlyArray<ASTNode> {\n return union.types.flatMap((t: ASTNode) => (t.type === \"TSUnionType\" ? unionMembers(t) : [t]))\n}\n\n/**\n * Does a nullable union describe a three-state shape? Left out, cleared and set are three states, and\n * `Option` has two (#448). That's a type alias's body or a type-literal or interface member holding both\n * `null` and `undefined`, or an optional member that can also be `null` (`a?: T | null`). A parameter is a\n * converter's input and a return type is a result, so neither counts.\n *\n * Returns the two spellings of \"absent\" the type uses, for the message to say which to drop, or `undefined`\n * when the union isn't a three-state shape.\n */\nfunction threeStateSpellings(union: ASTNode, members: ReadonlyArray<ASTNode>): string | undefined {\n if (!members.some((t) => t.type === \"TSNullKeyword\")) return undefined\n const parent = union.parent as ASTNode | undefined\n const owner = parent?.type === \"TSTypeAnnotation\" ? (parent.parent as ASTNode | undefined) : undefined\n const member = owner?.type === \"TSPropertySignature\" ? owner : undefined\n if (member?.optional === true) return \"the ? or the | null\"\n if (!members.some((t) => t.type === \"TSUndefinedKeyword\")) return undefined\n return parent?.type === \"TSTypeAliasDeclaration\" || member !== undefined ? \"the | null or the | undefined\" : undefined\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: \"suggestion\",\n hasSuggestions: true,\n docs: {\n description: \"Prefer Option<T> over nullable types (T | null | undefined)\",\n recommended: true,\n },\n schema: [\n {\n type: \"object\",\n properties: {\n allowInteropMarker: {\n type: \"boolean\",\n default: true,\n },\n wireTypes: WIRE_TYPES_SCHEMA,\n allowNullableIntersections: {\n type: \"boolean\",\n default: false,\n },\n allowUseState: {\n type: \"boolean\",\n default: true,\n },\n checkOptionalMembers: {\n type: \"boolean\",\n default: false,\n },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n preferOption:\n \"Prefer Option<{{type}}> over nullable type '{{nullable}}'. If this is a row, body or payload shape, wrap the type in Wire<…>\",\n preferOptionReturn: \"Prefer Option<{{type}}> as return type over nullable '{{nullable}}'\",\n preferOptionOverOptional:\n \"Prefer '{{name}}: Option<{{type}}>' over the optional '{{name}}?'. If this is a row, body or payload shape, wrap the type in Wire<…>\",\n preferWireForThreeStates:\n 'This type has three states, left out, null and set, and Option holds two. If it\\'s a row, body or payload shape, wrap the type in Wire<…>. If it only meant \"may be absent\", drop {{drop}} and use Option<{{type}}>',\n suggestOptionType: \"Replace with Option<{{type}}>\",\n suggestAddImport: \"Add {{symbol}} import from functype\",\n },\n },\n\n create(context) {\n const options = context.options[0] || {}\n // Everything inside `Wire<…>` is the declared serialization shape (#325 B).\n const wireTypes: ReadonlyArray<string> = options.wireTypes ?? DEFAULT_WIRE_TYPES\n // `@interop <reason>` on an enclosing declaration marks a host-contract boundary (#241).\n const allowInteropMarker = options.allowInteropMarker !== false\n const isExemptByMarker = (node: ASTNode): boolean =>\n allowInteropMarker && isInsideTaggedDeclaration(node, INTEROP_TAG, context.sourceCode)\n // `null` is idiomatic React state (`useState<User | null>(null)`, `useRef<El | null>(null)`); an\n // Option in a hook's type argument buys nothing and fights the hook's own API (#325).\n const allowUseState = options.allowUseState !== false\n // `a?: T` and `a: T | undefined` on a member or parameter both mean \"may be absent\", and the caller\n // writes `<X b=\"v\" />` or `f()`. Skip both unless asked to report them (#446).\n const checkOptionalMembers = options.checkOptionalMembers === true\n\n /** Is `node` inside the type argument of a `useState` / `useRef` call (bare or `React.`-qualified)? */\n function isInHookTypeArgument(node: ASTNode): boolean {\n const parent = node.parent\n if (!parent) return false\n if (parent.type === \"TSTypeParameterInstantiation\" && parent.parent?.type === \"CallExpression\") {\n const callee = parent.parent.callee\n const name =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null\n if (name !== null && REACT_STATE_HOOKS.has(name)) return true\n }\n return isInHookTypeArgument(parent)\n }\n\n // Get functype imports if available (but still apply rule even without explicit import)\n const functypeImports = getFunctypeImportsLegacy(context)\n\n /** With checkOptionalMembers, `a?: T` on a member or parameter is reported like `a: T | undefined`. */\n function checkOptional(node: ASTNode): void {\n if (!checkOptionalMembers || node.optional !== true) return\n if (node.type !== \"TSPropertySignature\" && !isParameter(node)) return\n if (isInsideWireType(node, wireTypes) || isExemptByMarker(node)) return\n const annotation = (node.typeAnnotation as ASTNode | undefined)?.typeAnnotation as ASTNode | undefined\n if (!annotation || isFunctypeType(annotation, functypeImports)) return\n const members = annotation.type === \"TSUnionType\" ? unionMembers(annotation) : [annotation]\n // `a?: T | null` is reported once, by the union check.\n if (members.some((t) => t.type === \"TSNullKeyword\")) return\n const kept = members.filter((t) => !isNullish(t))\n if (kept.length !== 1 || isFunctypeType(kept[0], functypeImports)) return\n const key = (node.type === \"TSPropertySignature\" ? node.key : node) as ASTNode\n const name =\n key.type === \"Identifier\"\n ? key.name\n : key.type === \"Literal\"\n ? String(key.value)\n : context.sourceCode.getText(key)\n context.report({\n node: key,\n messageId: \"preferOptionOverOptional\",\n data: { name, type: context.sourceCode.getText(kept[0]) },\n })\n }\n\n return {\n TSPropertySignature: checkOptional,\n Identifier: checkOptional,\n\n TSUnionType(node: ASTNode) {\n // A union nested in a union is part of the outer one, which reports for both.\n if ((node.parent as ASTNode | undefined)?.type === \"TSUnionType\") return\n if (isInsideWireType(node, wireTypes)) return\n if (isExemptByMarker(node)) return\n if (!node.types || node.types.length < 2) return\n // The gate the rule always had: a nullish member of its own beside exactly one other. Spreading\n // nested unions below only refines what that one member is, so nothing new gets reported.\n const direct: ReadonlyArray<ASTNode> = node.types\n if (!direct.some((t) => isNullish(t)) || direct.filter((t) => !isNullish(t)).length !== 1) return\n if (allowUseState && isInHookTypeArgument(node)) return\n\n const members = unionMembers(node)\n const hasNull = members.some((type) => isNullish(type))\n\n if (!hasNull) return\n\n // On a member or parameter, `T | undefined` is the same \"may be absent\" as `?:`: skipped unless\n // checkOptionalMembers is on, and never reported on an optional one (`c?: T | undefined` is the\n // spelling exactOptionalPropertyTypes needs; the optional-member check reports it, once).\n const owner = memberOrParameterOf(node.parent)\n const undefinedOnly = !members.some((type) => type.type === \"TSNullKeyword\")\n if (owner && undefinedOnly && (!checkOptionalMembers || owner.optional === true)) return\n\n const nonNullTypes = members.filter((type) => !isNullish(type))\n\n if (nonNullTypes.length === 1) {\n const nonNullType = nonNullTypes[0]\n\n // Skip if it's already an Option type or other functype type\n if (isFunctypeType(nonNullType, functypeImports)) return\n\n // Skip if we're already in a functype context\n if (isAlreadyUsingFunctype(node, functypeImports)) return\n\n const sourceCode = context.sourceCode\n const nonNullTypeText = sourceCode.getText(nonNullType)\n const fullType = sourceCode.getText(node)\n\n // Skip if it's already an Option type (fallback check)\n if (nonNullTypeText.startsWith(\"Option<\")) return\n\n const drop = threeStateSpellings(node, members)\n if (drop !== undefined) {\n context.report({ node, messageId: \"preferWireForThreeStates\", data: { type: nonNullTypeText, drop } })\n return\n }\n\n const suggestions: Rule.SuggestionReportDescriptor[] = [\n {\n messageId: \"suggestOptionType\",\n data: { type: nonNullTypeText },\n fix(fixer) {\n return fixer.replaceText(node, `Option<${nonNullTypeText}>`)\n },\n },\n ]\n\n if (!hasFunctypeSymbol(sourceCode, \"Option\")) {\n suggestions.push({\n messageId: \"suggestAddImport\",\n data: { symbol: \"Option\" },\n fix: createImportFixer(sourceCode, \"Option\"),\n })\n }\n\n context.report({\n node,\n messageId: \"preferOption\",\n data: {\n type: nonNullTypeText,\n nullable: fullType,\n },\n suggest: suggestions,\n })\n }\n },\n }\n },\n}\n\nexport default rule\n"],"mappings":"6XAQA,MAAMA,kBAAyC,IAAI,IAAI,CAAC,WAAY,QAAQ,CAAC,EAEvEC,EAAa,GAA2BC,EAAK,OAAS,iBAAmBA,EAAK,OAAS,qBAG7F,SAASC,EAAY,EAAwB,CAC3C,IAAMC,EAASC,EAAK,OACpB,GAAI,CAACD,EAAQ,MAAO,GACpB,GAAIA,EAAO,OAAS,qBAAuBA,EAAO,OAASC,EAAM,OAAOF,EAAYC,CAAM,EAC1F,GAAIA,EAAO,OAAS,sBAAuB,MAAO,GAClD,IAAME,EAAUF,EAAwD,OACxE,OAAO,MAAM,QAAQE,CAAM,GAAKA,EAAO,SAASD,CAAI,CACtD,CAOA,SAASE,EAAoB,EAAsD,CACjF,IAAMC,EAAQC,GAAY,OAAS,mBAAsBA,EAAW,OAAiC,IAAA,GACrG,GAAKD,EAEL,OADIA,EAAM,OAAS,uBACZL,EAAYK,CAAK,EADyBA,EACb,IAAA,EACtC,CAMA,SAASE,EAAa,EAAwC,CAC5D,OAAOC,EAAM,MAAM,QAAS,GAAgBC,EAAE,OAAS,cAAgBF,EAAaE,CAAC,EAAI,CAACA,CAAC,CAAE,CAC/F,CAWA,SAASC,EAAoB,EAAgB,EAAqD,CAChG,GAAI,CAACC,EAAQ,KAAM,GAAMF,EAAE,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ACf,UAAW,mBACX,KAAM,CAAE,OAAQ,QAAS,EACzB,IAAKG,EAAkBP,EAAY,QAAQ,CAC7C,CAAC,EAGHvB,EAAQ,OAAO,CACb,OACA,UAAW,eACX,KAAM,CACJ,KAAMwB,EACN,SAAUC,CACZ,EACA,QAASE,CACX,CAAC,CACH,CACF,CACF,CACF,CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-functype",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.126.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,8 +42,8 @@
|
|
|
42
42
|
"@types/node": "^24.19.1",
|
|
43
43
|
"@typescript-eslint/rule-tester": "^8.71.0",
|
|
44
44
|
"eslint-config-prettier": "^10.1.8",
|
|
45
|
-
"functype": "^1.
|
|
46
|
-
"ts-builds": "^
|
|
45
|
+
"functype": "^1.26.1",
|
|
46
|
+
"ts-builds": "^4.5.0",
|
|
47
47
|
"tsdown": "^0.23.0"
|
|
48
48
|
},
|
|
49
49
|
"publishConfig": {
|