oxlint-plugin-samdotci 0.0.0-stage → 0.1.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.
Files changed (33) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +53 -2
  3. package/dist/index.d.ts +12 -0
  4. package/dist/index.js +25 -0
  5. package/dist/production-file.d.ts +1 -0
  6. package/dist/production-file.js +7 -0
  7. package/dist/rules/no-chained-type-assertions.d.ts +2 -0
  8. package/dist/rules/no-chained-type-assertions.js +55 -0
  9. package/dist/rules/no-discarded-map-error.d.ts +2 -0
  10. package/dist/rules/no-discarded-map-error.js +152 -0
  11. package/dist/rules/no-known-value-widening.d.ts +3 -0
  12. package/dist/rules/no-known-value-widening.js +306 -0
  13. package/dist/rules/no-runtime-typeof.d.ts +2 -0
  14. package/dist/rules/no-runtime-typeof.js +48 -0
  15. package/dist/rules/no-unannotated-any.d.ts +2 -0
  16. package/dist/rules/no-unannotated-any.js +25 -0
  17. package/dist/rules/no-unknown-parameters.d.ts +2 -0
  18. package/dist/rules/no-unknown-parameters.js +57 -0
  19. package/dist/rules/no-unsafe-dictionary-type.d.ts +3 -0
  20. package/dist/rules/no-unsafe-dictionary-type.js +122 -0
  21. package/dist/rules/no-widen-then-assert.d.ts +2 -0
  22. package/dist/rules/no-widen-then-assert.js +274 -0
  23. package/dist/shared/dictionary-types.d.ts +19 -0
  24. package/dist/shared/dictionary-types.js +338 -0
  25. package/dist/shared/function-parameters.d.ts +8 -0
  26. package/dist/shared/function-parameters.js +40 -0
  27. package/dist/shared/lexical-type-parameters.d.ts +5 -0
  28. package/dist/shared/lexical-type-parameters.js +44 -0
  29. package/dist/shared/scope.d.ts +3 -0
  30. package/dist/shared/scope.js +6 -0
  31. package/dist/shared/type-alias-resolution.d.ts +20 -0
  32. package/dist/shared/type-alias-resolution.js +114 -0
  33. package/package.json +62 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sam Stewart
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # oxlint-plugin-samdotci
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shared Oxlint rules for TypeScript and Effect, built with [`effect-oxlint`](https://github.com/mpsuesser/effect-oxlint).
4
+
5
+ ## Usage
6
+
7
+ Install `oxlint-plugin-samdotci` as a dev dependency alongside Oxlint (1.91 or newer in the 1.x series). To try an unpublished checkout, build it and run `bun link` here, then run `bun link oxlint-plugin-samdotci` in the consumer. Rebuild this checkout after editing a rule.
8
+
9
+ Register the plugin and enable the rules you want in `oxlint.config.ts`:
10
+
11
+ ```ts
12
+ import { defineConfig } from "oxlint";
13
+
14
+ export default defineConfig({
15
+ jsPlugins: [{ name: "samdotci", specifier: "oxlint-plugin-samdotci" }],
16
+ rules: {
17
+ "samdotci/no-discarded-map-error": "error",
18
+ "samdotci/no-chained-type-assertions": "error",
19
+ },
20
+ });
21
+ ```
22
+
23
+ You can also import the default export and use `extends: [plugin.configs.recommended]`. That preset enables only `no-discarded-map-error`; `plugin.configs.all` enables all eight rules. Use Oxlint's native `typescript/no-non-null-assertion` and type-aware `typescript/no-unsafe-type-assertion` if you also want those checks.
24
+
25
+ ## Rules
26
+
27
+ | Rule | What it checks |
28
+ | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
29
+ | `samdotci/no-chained-type-assertions` | Rejects chains of assertions unless every assertion is `as const` or `<const>`. |
30
+ | `samdotci/no-discarded-map-error` | Requires inline `Effect.mapError` callbacks to preserve the original error. |
31
+ | `samdotci/no-known-value-widening` | Rejects explicitly broad types that discard information about an already known value. |
32
+ | `samdotci/no-runtime-typeof` | Rejects runtime `typeof` checks except comparisons against `"undefined"`. Set `allowInTypeGuards: true` to also allow them in type guards. |
33
+ | `samdotci/no-unannotated-any` | Requires `// intentional: <reason>` on the same line as explicit `any` in `src/` files. Skips test directories and `.test.*` or `.spec.*` files. |
34
+ | `samdotci/no-unknown-parameters` | Rejects explicit `unknown` parameters except `cause` and type predicate subjects. Set `allowInTypeGuards: true` to exempt all parameters in type guards. |
35
+ | `samdotci/no-unsafe-dictionary-type` | Rejects open object dictionaries with broad value types such as `unknown`, `any`, `object`, or `{}`. |
36
+ | `samdotci/no-widen-then-assert` | Rejects widening a known `const` binding and then asserting it back to a narrower type. |
37
+
38
+ ### Preserving mapped errors
39
+
40
+ `no-discarded-map-error` resolves Effect imports and parameter bindings, including aliases and shadowing. It supports piped and data-first calls.
41
+
42
+ Return the original error or pass it intact to the returned constructor or factory, directly or through an object property. The rule checks each explicit return and conditional-expression branch. Logging the error, forwarding only its message, or overwriting the parameter in a standalone assignment before forwarding it does not satisfy the rule.
43
+
44
+ The rule trusts factories to retain forwarded errors. It does not follow named callbacks, local aliases of the error, or intermediate result variables, and does not analyze nested assignments or implicit fallthrough. It does not offer an autofix because factory argument positions vary.
45
+
46
+ ## Development
47
+
48
+ Review `mise.toml`, then run `mise trust`, `mise install`, and `mise exec -- bun install`. With Mise activated:
49
+
50
+ - `bun run build` emits JavaScript and declarations. The package exposes `dist/index.js` so Node can load it from `node_modules` without TypeScript stripping.
51
+ - `bun run verify` checks formatting, lint, types, and tests, then runs Fallow. CI and the pre-commit hook use this command. Locally it checks the working tree, not just staged files, and doesn't change the index.
52
+ - `bun run test` runs the rule fixtures through Oxlint's `RuleTester` and runs one CLI smoke test that loads the built package by name. For one rule, run `bun run test -- test/rules/<rule>.test.ts`.
53
+ - `bun pm pack` builds and packs the library for testing in a clean consumer. It does not publish anything.
54
+ - Vitest writes `coverage/coverage-final.json` for Fallow's complexity scoring. Run the full suite before a standalone `bun run fallow audit --base HEAD`.
@@ -0,0 +1,12 @@
1
+ import { Plugin } from "effect-oxlint";
2
+ declare const _default: Plugin.DefinedPlugin<{
3
+ "no-chained-type-assertions": import("effect-oxlint").CreateRule;
4
+ "no-discarded-map-error": import("effect-oxlint").CreateRule;
5
+ "no-known-value-widening": import("effect-oxlint").CreateRule;
6
+ "no-runtime-typeof": import("effect-oxlint").CreateRule;
7
+ "no-unannotated-any": import("effect-oxlint").CreateRule;
8
+ "no-unknown-parameters": import("effect-oxlint").CreateRule;
9
+ "no-unsafe-dictionary-type": import("effect-oxlint").CreateRule;
10
+ "no-widen-then-assert": import("effect-oxlint").CreateRule;
11
+ }>;
12
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,25 @@
1
+ import { Plugin } from "effect-oxlint";
2
+ import noChainedTypeAssertions from "./rules/no-chained-type-assertions.js";
3
+ import noDiscardedMapError from "./rules/no-discarded-map-error.js";
4
+ import noKnownValueWidening from "./rules/no-known-value-widening.js";
5
+ import noRuntimeTypeof from "./rules/no-runtime-typeof.js";
6
+ import noUnannotatedAny from "./rules/no-unannotated-any.js";
7
+ import noUnknownParameters from "./rules/no-unknown-parameters.js";
8
+ import noUnsafeDictionaryType from "./rules/no-unsafe-dictionary-type.js";
9
+ import noWidenThenAssert from "./rules/no-widen-then-assert.js";
10
+ const rules = {
11
+ "no-chained-type-assertions": noChainedTypeAssertions,
12
+ "no-discarded-map-error": noDiscardedMapError,
13
+ "no-known-value-widening": noKnownValueWidening,
14
+ "no-runtime-typeof": noRuntimeTypeof,
15
+ "no-unannotated-any": noUnannotatedAny,
16
+ "no-unknown-parameters": noUnknownParameters,
17
+ "no-unsafe-dictionary-type": noUnsafeDictionaryType,
18
+ "no-widen-then-assert": noWidenThenAssert,
19
+ };
20
+ export default Plugin.define({
21
+ name: "samdotci",
22
+ specifier: "oxlint-plugin-samdotci",
23
+ rules,
24
+ recommended: { rules: ["no-discarded-map-error"] },
25
+ });
@@ -0,0 +1 @@
1
+ export declare function isProductionFile(cwd: string, filename: string): boolean;
@@ -0,0 +1,7 @@
1
+ import { relative, sep } from "node:path";
2
+ export function isProductionFile(cwd, filename) {
3
+ const parts = relative(cwd, filename).split(sep);
4
+ return (parts.includes("src") &&
5
+ !parts.some((part) => part === "test" || part === "tests" || part === "__tests__") &&
6
+ !/\.(?:test|spec)\.[^.]+$/.test(filename));
7
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: import("effect-oxlint").CreateRule;
2
+ export default _default;
@@ -0,0 +1,55 @@
1
+ import { Effect } from "effect";
2
+ import { Diagnostic, Rule, RuleContext, Visitor } from "effect-oxlint";
3
+ function isTypeAssertionExpression(node) {
4
+ return node.type === "TSAsExpression" || node.type === "TSTypeAssertion";
5
+ }
6
+ function unwrapParenthesizedExpression(expression) {
7
+ let current = expression;
8
+ while (current.type === "ParenthesizedExpression") {
9
+ current = current.expression;
10
+ }
11
+ return current;
12
+ }
13
+ function isConstAssertion(node) {
14
+ const { typeAnnotation } = node;
15
+ return (typeAnnotation.type === "TSTypeReference" &&
16
+ typeAnnotation.typeName.type === "Identifier" &&
17
+ typeAnnotation.typeName.name === "const");
18
+ }
19
+ function isOutermostAssertionInChain(node) {
20
+ let current = node;
21
+ let parent = node.parent;
22
+ while (parent.type === "ParenthesizedExpression" && parent.expression === current) {
23
+ current = parent;
24
+ parent = parent.parent;
25
+ }
26
+ return !isTypeAssertionExpression(parent) || parent.expression !== current;
27
+ }
28
+ function isForbiddenAssertionChain(node) {
29
+ let assertionCount = 0;
30
+ let hasNonConstAssertion = false;
31
+ let current = node;
32
+ while (isTypeAssertionExpression(current)) {
33
+ assertionCount += 1;
34
+ hasNonConstAssertion ||= !isConstAssertion(current);
35
+ current = unwrapParenthesizedExpression(current.expression);
36
+ }
37
+ return assertionCount > 1 && hasNonConstAssertion;
38
+ }
39
+ export default Rule.define({
40
+ name: "no-chained-type-assertions",
41
+ meta: Rule.meta({
42
+ type: "problem",
43
+ description: "Disallow chained TypeScript as and angle-bracket assertions, including parenthesized chains.",
44
+ messages: {
45
+ chained: "This assertion chain discards type evidence. Keep the original precise type, or parse untrusted input at its boundary before narrowing it.",
46
+ },
47
+ }),
48
+ create: function* () {
49
+ const ctx = yield* RuleContext;
50
+ const checkTypeAssertion = (node) => isOutermostAssertionInChain(node) && isForbiddenAssertionChain(node)
51
+ ? ctx.report(Diagnostic.fromId({ node, messageId: "chained" }))
52
+ : Effect.void;
53
+ return Visitor.merge(Visitor.on("TSAsExpression", checkTypeAssertion), Visitor.on("TSTypeAssertion", checkTypeAssertion));
54
+ },
55
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("effect-oxlint").CreateRule;
2
+ export default _default;
@@ -0,0 +1,152 @@
1
+ import { Effect, Option } from "effect";
2
+ import { Diagnostic, Rule, RuleContext, Scope, Visitor, } from "effect-oxlint";
3
+ function matchesImport(specifier, name) {
4
+ if (specifier.type === "ImportSpecifier") {
5
+ const imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
6
+ return specifier.importKind !== "type" && imported === name;
7
+ }
8
+ return (name === "*" &&
9
+ (specifier.type === "ImportNamespaceSpecifier" || specifier.type === "ImportDefaultSpecifier"));
10
+ }
11
+ function importedFrom(ctx, identifier, module, name) {
12
+ const variable = Scope.findVariableUp(ctx.sourceCode.getScope(identifier), identifier.name);
13
+ return (Option.isSome(variable) &&
14
+ variable.value.defs.some((definition) => {
15
+ const specifier = definition.node;
16
+ const declaration = specifier.parent;
17
+ if (declaration?.type !== "ImportDeclaration" || declaration.source.value !== module)
18
+ return false;
19
+ if (declaration.importKind === "type")
20
+ return false;
21
+ return matchesImport(specifier, name);
22
+ }));
23
+ }
24
+ function isMapErrorCallback(ctx, node) {
25
+ const call = node.parent;
26
+ if (call.type !== "CallExpression" ||
27
+ (call.arguments.length !== 1 && call.arguments.length !== 2) ||
28
+ call.arguments.at(-1) !== node)
29
+ return false;
30
+ return isMapErrorCallee(ctx, call.callee);
31
+ }
32
+ function isMapErrorCallee(ctx, callee) {
33
+ if (callee.type === "Identifier")
34
+ return importedFrom(ctx, callee, "effect/Effect", "mapError");
35
+ return (callee.type === "MemberExpression" &&
36
+ !callee.computed &&
37
+ callee.property.type === "Identifier" &&
38
+ callee.property.name === "mapError" &&
39
+ callee.object.type === "Identifier" &&
40
+ (importedFrom(ctx, callee.object, "effect", "Effect") ||
41
+ importedFrom(ctx, callee.object, "effect/Effect", "*")));
42
+ }
43
+ // Only intact values count: accessing .message, interpolation, and calls that
44
+ // transform an argument do not preserve the original error. Factories are trusted.
45
+ function intact(node, references) {
46
+ if (references.has(node))
47
+ return true;
48
+ if (node.type === "TSAsExpression" ||
49
+ node.type === "TSSatisfiesExpression" ||
50
+ node.type === "TSNonNullExpression" ||
51
+ node.type === "TSTypeAssertion") {
52
+ return intact(node.expression, references);
53
+ }
54
+ return (node.type === "ObjectExpression" &&
55
+ node.properties.some((property) => property.type === "Property" && intact(property.value, references)));
56
+ }
57
+ function isStringConversion(callee) {
58
+ if (callee.type === "Identifier")
59
+ return callee.name === "String";
60
+ return (callee.type === "MemberExpression" &&
61
+ !callee.computed &&
62
+ callee.object.type === "Identifier" &&
63
+ callee.object.name === "JSON" &&
64
+ callee.property.type === "Identifier" &&
65
+ callee.property.name === "stringify");
66
+ }
67
+ function preserves(node, references) {
68
+ if (intact(node, references))
69
+ return true;
70
+ if (node.type === "ConditionalExpression") {
71
+ return preserves(node.consequent, references) && preserves(node.alternate, references);
72
+ }
73
+ if (node.type === "CallExpression" || node.type === "NewExpression") {
74
+ // Known string conversions are not error factories.
75
+ if (isStringConversion(node.callee))
76
+ return false;
77
+ return node.arguments.some((argument) => intact(argument, references));
78
+ }
79
+ return false;
80
+ }
81
+ function originalErrorReads(variable, body) {
82
+ const reads = new Set(variable.references
83
+ .filter((reference) => reference.isRead())
84
+ .map((reference) => reference.identifier));
85
+ if (body?.type !== "BlockStatement")
86
+ return reads;
87
+ let firstOverwrite = Infinity;
88
+ // Nested writes need control-flow analysis; only check standalone assignments in the callback body.
89
+ for (const reference of variable.references) {
90
+ const assignment = reference.identifier.parent;
91
+ if (reference.isWrite() &&
92
+ assignment.type === "AssignmentExpression" &&
93
+ assignment.operator === "=" &&
94
+ assignment.left === reference.identifier &&
95
+ assignment.parent.type === "ExpressionStatement" &&
96
+ assignment.parent.parent === body &&
97
+ !reads.has(assignment.right)) {
98
+ firstOverwrite = Math.min(firstOverwrite, assignment.range[0]);
99
+ }
100
+ }
101
+ return new Set([...reads].filter((read) => read.range[0] < firstOverwrite));
102
+ }
103
+ export default Rule.define({
104
+ name: "no-discarded-map-error",
105
+ meta: Rule.meta({
106
+ type: "problem",
107
+ description: "Preserve the original error when mapping Effect failures.",
108
+ }),
109
+ create: function* () {
110
+ const ctx = yield* RuleContext;
111
+ const report = (node) => ctx.report(Diagnostic.make({
112
+ node,
113
+ message: "Forward the original error to the replacement error's constructor or factory instead of discarding it in Effect.mapError. If the replacement uses Schema.TaggedError, consider declaring `cause: Schema.Defect()` in its schema and including `cause` when constructing it.",
114
+ }));
115
+ const checkReturn = (callback, expression, node) => {
116
+ const parameter = callback.params[0];
117
+ if (parameter?.type !== "Identifier")
118
+ return Effect.void;
119
+ const variable = Scope.findVariable(ctx.sourceCode.getScope(callback), parameter.name);
120
+ return expression &&
121
+ Option.isSome(variable) &&
122
+ preserves(expression, originalErrorReads(variable.value, callback.body))
123
+ ? Effect.void
124
+ : report(node);
125
+ };
126
+ const checkCallback = (node) => {
127
+ if (!isMapErrorCallback(ctx, node))
128
+ return Effect.void;
129
+ if (node.params[0]?.type !== "Identifier")
130
+ return report(node);
131
+ return !node.body || node.body.type === "BlockStatement"
132
+ ? Effect.void
133
+ : checkReturn(node, node.body, node);
134
+ };
135
+ return Visitor.merge(Visitor.onExit("ArrowFunctionExpression", checkCallback), Visitor.onExit("FunctionExpression", checkCallback), Visitor.on("ReturnStatement", (node) => {
136
+ const enclosing = (parent) => {
137
+ if (parent.type === "ArrowFunctionExpression" ||
138
+ parent.type === "FunctionExpression" ||
139
+ parent.type === "FunctionDeclaration" ||
140
+ parent.type === "Program")
141
+ return parent;
142
+ return enclosing(parent.parent);
143
+ };
144
+ const callback = enclosing(node.parent);
145
+ return (callback.type === "ArrowFunctionExpression" ||
146
+ callback.type === "FunctionExpression") &&
147
+ isMapErrorCallback(ctx, callback)
148
+ ? checkReturn(callback, node.argument, node)
149
+ : Effect.void;
150
+ }));
151
+ },
152
+ });
@@ -0,0 +1,3 @@
1
+ /** Detect sound syntactic cases where a known value is explicitly widened and loses evidence. */
2
+ declare const _default: import("effect-oxlint").CreateRule;
3
+ export default _default;
@@ -0,0 +1,306 @@
1
+ import { Effect } from "effect";
2
+ import { Diagnostic, Rule, RuleContext, Visitor, } from "effect-oxlint";
3
+ import { classifyUnsafeDictionaryValue, classifyWideningTarget, createTypeEnvironment, isKnownEvidenceExpression, } from "../shared/dictionary-types.js";
4
+ import { containsUnknownType, functionParameterBindingName, functionParameterTypeAnnotation, } from "../shared/function-parameters.js";
5
+ import { lexicalTypeParameterNames } from "../shared/lexical-type-parameters.js";
6
+ import { resolveVariable } from "../shared/scope.js";
7
+ function unwrapExpression(expression) {
8
+ let current = expression;
9
+ while (current.type === "ParenthesizedExpression" ||
10
+ current.type === "TSAsExpression" ||
11
+ current.type === "TSSatisfiesExpression" ||
12
+ current.type === "TSTypeAssertion" ||
13
+ current.type === "TSNonNullExpression") {
14
+ current = current.expression;
15
+ }
16
+ return current;
17
+ }
18
+ function variableDeclarator(variable) {
19
+ if (variable.defs.length !== 1)
20
+ return null;
21
+ const [definition] = variable.defs;
22
+ return definition?.type === "Variable" && definition.node.type === "VariableDeclarator"
23
+ ? definition.node
24
+ : null;
25
+ }
26
+ function isStableConstVariable(variable, declarator) {
27
+ return (declarator.parent.type === "VariableDeclaration" &&
28
+ declarator.parent.kind === "const" &&
29
+ variable.references.every((reference) => reference.init || !reference.isWrite()));
30
+ }
31
+ function hasKnownEvidence(sourceCode, expression, visitedVariables = new Set()) {
32
+ if (isKnownEvidenceExpression(expression))
33
+ return true;
34
+ const unwrapped = unwrapExpression(expression);
35
+ if (unwrapped.type !== "Identifier")
36
+ return false;
37
+ const variable = resolveVariable(sourceCode, unwrapped);
38
+ if (variable === null || visitedVariables.has(variable))
39
+ return false;
40
+ const declarator = variableDeclarator(variable);
41
+ if (declarator === null ||
42
+ declarator.init === null ||
43
+ !isStableConstVariable(variable, declarator)) {
44
+ return false;
45
+ }
46
+ visitedVariables.add(variable);
47
+ return hasKnownEvidence(sourceCode, declarator.init, visitedVariables);
48
+ }
49
+ function isFunctionExpression(node) {
50
+ return (node.type === "ArrowFunctionExpression" ||
51
+ node.type === "FunctionDeclaration" ||
52
+ node.type === "FunctionExpression" ||
53
+ node.type === "TSDeclareFunction" ||
54
+ node.type === "TSEmptyBodyFunctionExpression");
55
+ }
56
+ function localFunctionForCall(sourceCode, callee) {
57
+ const unwrapped = unwrapExpression(callee);
58
+ if (isFunctionExpression(unwrapped))
59
+ return unwrapped;
60
+ if (unwrapped.type !== "Identifier")
61
+ return null;
62
+ const variable = resolveVariable(sourceCode, unwrapped);
63
+ if (variable === null || variable.defs.length !== 1)
64
+ return null;
65
+ const [definition] = variable.defs;
66
+ if (definition === undefined)
67
+ return null;
68
+ if (definition.type === "FunctionName" && isFunctionExpression(definition.node)) {
69
+ return definition.node;
70
+ }
71
+ if (definition.type !== "Variable" || definition.node.type !== "VariableDeclarator") {
72
+ return null;
73
+ }
74
+ const initializer = definition.node.init;
75
+ if (initializer === null)
76
+ return null;
77
+ const unwrappedInitializer = unwrapExpression(initializer);
78
+ return isFunctionExpression(unwrappedInitializer) ? unwrappedInitializer : null;
79
+ }
80
+ function variableTypeAnnotation(sourceCode, variable) {
81
+ if (variable.defs.length !== 1)
82
+ return null;
83
+ const [definition] = variable.defs;
84
+ if (definition === undefined)
85
+ return null;
86
+ if (definition.type === "Variable" &&
87
+ definition.node.type === "VariableDeclarator" &&
88
+ definition.node.id.type === "Identifier") {
89
+ return definition.node.id.typeAnnotation ?? null;
90
+ }
91
+ if (definition.type !== "Parameter" || !isFunctionExpression(definition.node)) {
92
+ return null;
93
+ }
94
+ const parameter = definition.node.params.find((candidate) => functionParameterBindingName(candidate, sourceCode) === variable.name);
95
+ return parameter === undefined ? null : (functionParameterTypeAnnotation(parameter) ?? null);
96
+ }
97
+ function hasInformativeType(type, environment) {
98
+ return classifyUnsafeDictionaryValue(type, environment) === null;
99
+ }
100
+ /**
101
+ * Return whether a type is a bare reference to a generic type parameter that is
102
+ * lexically in scope at `use`. TypeScript resolves those per call site, so the
103
+ * checker sees no concrete type and the value must be treated as unproven.
104
+ */
105
+ function referencesLexicalTypeParameter(type, use, visitorKeys) {
106
+ const unwrapped = type.type === "TSParenthesizedType" ? type.typeAnnotation : type;
107
+ if (unwrapped.type !== "TSTypeReference" || unwrapped.typeName.type !== "Identifier") {
108
+ return false;
109
+ }
110
+ return lexicalTypeParameterNames(use, visitorKeys).has(unwrapped.typeName.name);
111
+ }
112
+ function declaredAnnotationContainsUnknown(sourceCode, expression, visitorKeys) {
113
+ if (expression.type !== "Identifier")
114
+ return false;
115
+ const variable = resolveVariable(sourceCode, expression);
116
+ if (variable === null)
117
+ return false;
118
+ const annotation = variableTypeAnnotation(sourceCode, variable);
119
+ // Fall back to the enclosing generic scope (e.g.
120
+ // `routeEvent<Event>(..., event: Event)`), where oxc cannot resolve a
121
+ // concrete type. Type-predicate rebinding of such a parameter is
122
+ // legitimate control-flow narrowing, not evidence-widening.
123
+ if (annotation === null) {
124
+ return lexicalTypeParameterNames(expression, visitorKeys).size > 0;
125
+ }
126
+ return (containsUnknownType(annotation.typeAnnotation) ||
127
+ referencesLexicalTypeParameter(annotation.typeAnnotation, expression, visitorKeys));
128
+ }
129
+ function hasKnownCallArgumentEvidence(sourceCode, expression, environment, visitorKeys, visitedVariables = new Set()) {
130
+ if (expression.type === "ParenthesizedExpression" || expression.type === "TSNonNullExpression") {
131
+ return hasKnownCallArgumentEvidence(sourceCode, expression.expression, environment, visitorKeys, visitedVariables);
132
+ }
133
+ if (declaredAnnotationContainsUnknown(sourceCode, expression, visitorKeys)) {
134
+ return false;
135
+ }
136
+ if (expression.type === "TSAsExpression" || expression.type === "TSTypeAssertion") {
137
+ return hasInformativeType(expression.typeAnnotation, environment);
138
+ }
139
+ if (expression.type === "TSSatisfiesExpression") {
140
+ return hasKnownCallArgumentEvidence(sourceCode, expression.expression, environment, visitorKeys, visitedVariables);
141
+ }
142
+ if (expression.type === "CallExpression") {
143
+ const owner = localFunctionForCall(sourceCode, expression.callee);
144
+ const returnType = owner?.returnType?.typeAnnotation;
145
+ return returnType !== undefined && hasInformativeType(returnType, environment);
146
+ }
147
+ if (expression.type !== "Identifier")
148
+ return isKnownEvidenceExpression(expression);
149
+ const variable = resolveVariable(sourceCode, expression);
150
+ if (variable === null || visitedVariables.has(variable))
151
+ return false;
152
+ const annotation = variableTypeAnnotation(sourceCode, variable);
153
+ if (annotation !== null) {
154
+ return hasInformativeType(annotation.typeAnnotation, environment);
155
+ }
156
+ const declarator = variableDeclarator(variable);
157
+ if (declarator === null ||
158
+ declarator.init === null ||
159
+ !isStableConstVariable(variable, declarator)) {
160
+ return false;
161
+ }
162
+ visitedVariables.add(variable);
163
+ return hasKnownCallArgumentEvidence(sourceCode, declarator.init, environment, visitorKeys, visitedVariables);
164
+ }
165
+ function typePredicateSubjectIndex(sourceCode, owner) {
166
+ const predicate = owner.returnType?.typeAnnotation;
167
+ if (predicate?.type !== "TSTypePredicate" || predicate.parameterName.type !== "Identifier") {
168
+ return null;
169
+ }
170
+ const predicateParameterName = predicate.parameterName.name;
171
+ const index = owner.params.findIndex((parameter) => functionParameterBindingName(parameter, sourceCode) === predicateParameterName);
172
+ return index === -1 ? null : index;
173
+ }
174
+ function annotationTarget(annotation, environment) {
175
+ return annotation === null || annotation === undefined
176
+ ? null
177
+ : classifyWideningTarget(annotation.typeAnnotation, environment);
178
+ }
179
+ function enclosingFunction(node) {
180
+ let current = node.parent;
181
+ while (current !== null && current.type !== "Program") {
182
+ if (current.type === "ArrowFunctionExpression" ||
183
+ current.type === "FunctionDeclaration" ||
184
+ current.type === "FunctionExpression") {
185
+ return current;
186
+ }
187
+ current = current.parent;
188
+ }
189
+ return null;
190
+ }
191
+ function sourceKeyName(sourceCode, key) {
192
+ if (key.type === "Identifier" || key.type === "PrivateIdentifier")
193
+ return key.name;
194
+ if (key.type === "Literal")
195
+ return String(key.value);
196
+ return sourceCode.getText(key);
197
+ }
198
+ function functionName(sourceCode, owner) {
199
+ if (owner === null)
200
+ return "anonymous function";
201
+ if (owner.id !== null)
202
+ return owner.id.name;
203
+ const parent = owner.parent;
204
+ if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier")
205
+ return parent.id.name;
206
+ if (parent.type === "MethodDefinition")
207
+ return sourceKeyName(sourceCode, parent.key);
208
+ return "anonymous function";
209
+ }
210
+ function isEmptyObjectExpression(expression) {
211
+ const unwrapped = unwrapExpression(expression);
212
+ return unwrapped.type === "ObjectExpression" && unwrapped.properties.length === 0;
213
+ }
214
+ function isDictionaryAccumulatorTarget(destination) {
215
+ return destination.kind === "open dictionary" || destination.kind === "generic container";
216
+ }
217
+ function hasParentAssertion(node) {
218
+ return node.parent?.type === "TSAsExpression" || node.parent?.type === "TSTypeAssertion";
219
+ }
220
+ /** Detect sound syntactic cases where a known value is explicitly widened and loses evidence. */
221
+ export default Rule.define({
222
+ name: "no-known-value-widening",
223
+ meta: Rule.meta({
224
+ type: "problem",
225
+ description: "Disallow syntactically established values from flowing into explicitly broad or anonymous target types that discard useful evidence.",
226
+ messages: {
227
+ widening: "The explicit {{target}} type on {{subject}} discards known type evidence. Keep inference, validate with `satisfies`, or use a named owner contract.",
228
+ },
229
+ }),
230
+ create: function* () {
231
+ const ctx = yield* RuleContext;
232
+ const { sourceCode } = ctx;
233
+ const { ast, visitorKeys } = sourceCode;
234
+ const environment = createTypeEnvironment(ast, visitorKeys);
235
+ const report = (node, subject, target) => ctx.report(Diagnostic.fromId({ node, messageId: "widening", data: { subject, target } }));
236
+ const reportFlow = (expression, destination, subject) => {
237
+ if (destination === null)
238
+ return Effect.void;
239
+ if (isDictionaryAccumulatorTarget(destination) && isEmptyObjectExpression(expression)) {
240
+ return Effect.void;
241
+ }
242
+ if (!hasKnownEvidence(sourceCode, expression))
243
+ return Effect.void;
244
+ return report(expression, subject, destination.kind);
245
+ };
246
+ const targetFromAnnotation = (annotation) => annotationTarget(annotation, environment);
247
+ const visitProperty = (node) => {
248
+ if (node.value === null)
249
+ return Effect.void;
250
+ return reportFlow(node.value, targetFromAnnotation(node.typeAnnotation), `property \`${sourceKeyName(sourceCode, node.key)}\``);
251
+ };
252
+ const visitAssertion = (node) => {
253
+ if (hasParentAssertion(node))
254
+ return Effect.void;
255
+ return reportFlow(node.expression, classifyWideningTarget(node.typeAnnotation, environment), "assertion");
256
+ };
257
+ return Visitor.merge(Visitor.on("VariableDeclarator", (node) => {
258
+ if (node.init === null || node.id.type !== "Identifier")
259
+ return Effect.void;
260
+ return reportFlow(node.init, targetFromAnnotation(node.id.typeAnnotation), `binding \`${node.id.name}\``);
261
+ }), Visitor.on("PropertyDefinition", visitProperty), Visitor.on("AccessorProperty", visitProperty), Visitor.on("AssignmentExpression", (node) => {
262
+ if (node.operator !== "=" || node.left.type !== "Identifier")
263
+ return Effect.void;
264
+ const variable = resolveVariable(sourceCode, node.left);
265
+ if (variable === null)
266
+ return Effect.void;
267
+ const declarator = variableDeclarator(variable);
268
+ if (declarator === null || declarator.id.type !== "Identifier")
269
+ return Effect.void;
270
+ return reportFlow(node.right, targetFromAnnotation(declarator.id.typeAnnotation), `binding \`${declarator.id.name}\``);
271
+ }), Visitor.on("CallExpression", (node) => {
272
+ const owner = localFunctionForCall(sourceCode, node.callee);
273
+ if (owner === null)
274
+ return Effect.void;
275
+ const parameterIndex = typePredicateSubjectIndex(sourceCode, owner);
276
+ if (parameterIndex === null)
277
+ return Effect.void;
278
+ const parameter = owner.params[parameterIndex];
279
+ const argument = node.arguments[parameterIndex];
280
+ if (parameter === undefined ||
281
+ argument === undefined ||
282
+ argument.type === "SpreadElement") {
283
+ return Effect.void;
284
+ }
285
+ const parameterAnnotation = functionParameterTypeAnnotation(parameter);
286
+ if (parameterAnnotation === null ||
287
+ parameterAnnotation === undefined ||
288
+ !containsUnknownType(parameterAnnotation.typeAnnotation)) {
289
+ return Effect.void;
290
+ }
291
+ if (!hasKnownCallArgumentEvidence(sourceCode, argument, environment, visitorKeys)) {
292
+ return Effect.void;
293
+ }
294
+ return report(argument, `argument for parameter \`${functionParameterBindingName(parameter, sourceCode)}\` of \`${functionName(sourceCode, owner)}\``, "unknown");
295
+ }), Visitor.on("ReturnStatement", (node) => {
296
+ if (node.argument === null)
297
+ return Effect.void;
298
+ const owner = enclosingFunction(node);
299
+ return reportFlow(node.argument, targetFromAnnotation(owner?.returnType), `return value of \`${functionName(sourceCode, owner)}\``);
300
+ }), Visitor.on("ArrowFunctionExpression", (node) => {
301
+ if (node.body.type === "BlockStatement")
302
+ return Effect.void;
303
+ return reportFlow(node.body, targetFromAnnotation(node.returnType), `return value of \`${functionName(sourceCode, node)}\``);
304
+ }), Visitor.on("TSAsExpression", visitAssertion), Visitor.on("TSTypeAssertion", visitAssertion));
305
+ },
306
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("effect-oxlint").CreateRule;
2
+ export default _default;