@inflexa-ai/typecheck 0.5.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.
@@ -0,0 +1,54 @@
1
+ import type { ReportData, RuleModule, RuleOptions } from './rule.ts';
2
+ /** A case: the code of one file of the fixture folder, its name, and the options of the rule. */
3
+ export type TestCase = {
4
+ code: string;
5
+ /** The name of the file in the fixture folder, `case.ts` by default. The tsconfig of the folder must include it. */
6
+ filename?: string;
7
+ /** The options of the rule, merged over its defaults and checked as the configuration checks them. */
8
+ options?: RuleOptions;
9
+ /** The title of the test, the code by default. */
10
+ name?: string;
11
+ };
12
+ /** A report that an invalid case expects. `data`, `line` and `column` are compared when a case gives them. */
13
+ export type ExpectedReport = {
14
+ messageId: string;
15
+ data?: ReportData;
16
+ line?: number;
17
+ column?: number;
18
+ };
19
+ export type ValidCase = string | TestCase;
20
+ export type InvalidCase = TestCase & {
21
+ errors: ExpectedReport[];
22
+ };
23
+ export type TestCases = {
24
+ valid: ValidCase[];
25
+ invalid: InvalidCase[];
26
+ };
27
+ /** The shape of `describe` and `it` of a test framework, as the tester calls them. */
28
+ export type TestFunction = (name: string, fn: () => void) => unknown;
29
+ /**
30
+ * Runs the valid and the invalid cases of a typed rule against a fixture
31
+ * folder. The code of each case is a file of that folder, served through the
32
+ * file system callbacks of the API, so the tsconfig of the folder must include
33
+ * the file names of the cases. One API serves each `run`, and each case takes
34
+ * a new snapshot after the cache of source files is cleared, because the API
35
+ * otherwise gives the old AST of a changed file.
36
+ *
37
+ * `RuleTester.describe` and `RuleTester.it` take the functions of the test
38
+ * framework, as the RuleTester of oxlint does. `RuleTester.afterAll`, when
39
+ * given, closes the API when a case of the run did not run.
40
+ */
41
+ export declare class RuleTester {
42
+ #private;
43
+ static describe: TestFunction | undefined;
44
+ static it: TestFunction | undefined;
45
+ static afterAll: ((fn: () => void) => unknown) | undefined;
46
+ constructor({ fixtures }: {
47
+ fixtures: string;
48
+ });
49
+ run<Options extends RuleOptions>(name: string, rule: RuleModule<Options>, { valid, invalid }: TestCases): void;
50
+ }
51
+ /** A tester for the rules whose cases are files of the fixture folder `fixtures`. */
52
+ export declare function createRuleTester({ fixtures }: {
53
+ fixtures: string;
54
+ }): RuleTester;
@@ -0,0 +1,126 @@
1
+ import { AssertionError } from 'node:assert';
2
+ import { readdirSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { isDeepStrictEqual } from 'node:util';
5
+ import { API } from 'typescript/unstable/sync';
6
+ import { mergeRuleOptions } from './config.js';
7
+ import { runRules } from './engine.js';
8
+ const DEFAULT_FILENAME = 'case.ts';
9
+ function describeReport(report) {
10
+ return `${String(report.line)}:${String(report.column)} ${report.messageId} ${JSON.stringify(report.data)}: ${report.message}`;
11
+ }
12
+ function compareReports(reports, expected) {
13
+ if (reports.length !== expected.length) {
14
+ return `The rule gave ${String(reports.length)} reports and the case expects ${String(expected.length)}:\n${reports.map(describeReport).join('\n')}`;
15
+ }
16
+ const problems = expected.flatMap((want, index) => {
17
+ const report = reports[index];
18
+ const differences = [
19
+ report.messageId === want.messageId ? undefined : `message id ${report.messageId}, expected ${want.messageId}`,
20
+ want.data === undefined || isDeepStrictEqual(report.data, want.data) ? undefined : `data ${JSON.stringify(report.data)}, expected ${JSON.stringify(want.data)}`,
21
+ want.line === undefined || report.line === want.line ? undefined : `line ${String(report.line)}, expected ${String(want.line)}`,
22
+ want.column === undefined || report.column === want.column ? undefined : `column ${String(report.column)}, expected ${String(want.column)}`,
23
+ ].filter((difference) => difference !== undefined);
24
+ return differences.length === 0 ? [] : [`Report ${String(index + 1)} (${describeReport(report)}): ${differences.join(', ')}`];
25
+ });
26
+ return problems.length === 0 ? undefined : problems.join('\n');
27
+ }
28
+ export class RuleTester {
29
+ static describe;
30
+ static it;
31
+ static afterAll;
32
+ #fixtures;
33
+ constructor({ fixtures }) {
34
+ this.#fixtures = fixtures;
35
+ }
36
+ run(name, rule, { valid, invalid }) {
37
+ const { describe, it, afterAll } = RuleTester;
38
+ if (describe === undefined || it === undefined)
39
+ throw new Error('Set RuleTester.describe and RuleTester.it to the functions of the test framework.');
40
+ const fixtures = this.#fixtures;
41
+ const tsconfig = path.join(fixtures, 'tsconfig.json');
42
+ const total = valid.length + invalid.length;
43
+ let finished = 0;
44
+ let api;
45
+ let snapshot;
46
+ let current = { file: '', code: '' };
47
+ const close = () => {
48
+ api?.close();
49
+ api = undefined;
50
+ };
51
+ const reportsOf = (testCase) => {
52
+ const file = path.join(fixtures, testCase.filename ?? DEFAULT_FILENAME);
53
+ const previous = current.file;
54
+ current = { file, code: testCase.code };
55
+ if (api === undefined) {
56
+ api = new API({
57
+ cwd: fixtures,
58
+ fs: {
59
+ readFile: (fileName) => (fileName === current.file ? current.code : undefined),
60
+ fileExists: (fileName) => (fileName === current.file ? true : undefined),
61
+ getAccessibleEntries: (directory) => {
62
+ if (directory !== path.dirname(current.file))
63
+ return undefined;
64
+ const entries = readdirSync(directory, { withFileTypes: true });
65
+ return {
66
+ files: [...entries.filter((entry) => entry.isFile()).map((entry) => entry.name), path.basename(current.file)],
67
+ directories: entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name),
68
+ };
69
+ },
70
+ },
71
+ });
72
+ snapshot = api.updateSnapshot({ openProjects: [tsconfig] });
73
+ }
74
+ else {
75
+ snapshot?.dispose();
76
+ api.clearSourceFileCache();
77
+ snapshot = api.updateSnapshot({ fileChanges: previous === file ? { changed: [file] } : { deleted: [previous], created: [file] } });
78
+ }
79
+ const project = snapshot.getProject(tsconfig);
80
+ if (project === undefined)
81
+ throw new Error(`The API opened no project for ${tsconfig}.`);
82
+ const sourceFile = project.program.getSourceFile(file);
83
+ if (sourceFile === undefined)
84
+ throw new Error(`The project of ${tsconfig} does not include ${file}. Include the file names of the cases in its tsconfig.`);
85
+ const options = mergeRuleOptions(name, rule, testCase.options ?? {});
86
+ return runRules(sourceFile, project.program, project.checker, [{ id: name, rule, options }]);
87
+ };
88
+ const test = (title, body) => {
89
+ it(title, () => {
90
+ try {
91
+ body();
92
+ }
93
+ finally {
94
+ finished += 1;
95
+ if (finished === total)
96
+ close();
97
+ }
98
+ });
99
+ };
100
+ describe(name, () => {
101
+ afterAll?.(close);
102
+ describe('valid', () => {
103
+ for (const entry of valid) {
104
+ const testCase = typeof entry === 'string' ? { code: entry } : entry;
105
+ test(testCase.name ?? testCase.code, () => {
106
+ const reports = reportsOf(testCase);
107
+ if (reports.length > 0)
108
+ throw new AssertionError({ message: `A valid case gave ${String(reports.length)} reports:\n${reports.map(describeReport).join('\n')}` });
109
+ });
110
+ }
111
+ });
112
+ describe('invalid', () => {
113
+ for (const testCase of invalid) {
114
+ test(testCase.name ?? testCase.code, () => {
115
+ const problem = compareReports(reportsOf(testCase), testCase.errors);
116
+ if (problem !== undefined)
117
+ throw new AssertionError({ message: problem });
118
+ });
119
+ }
120
+ });
121
+ });
122
+ }
123
+ }
124
+ export function createRuleTester({ fixtures }) {
125
+ return new RuleTester({ fixtures });
126
+ }
package/dist/rule.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import type { Node, SourceFile, SyntaxKind } from 'typescript/unstable/ast';
2
+ import type { Checker, Program } from 'typescript/unstable/sync';
3
+ /** A value of an option, as JSON writes it. */
4
+ export type OptionValue = string | number | boolean | null | OptionValue[] | {
5
+ [key: string]: OptionValue;
6
+ };
7
+ /** The options of a rule: one object, which the configuration merges over the defaults of the rule. */
8
+ export type RuleOptions = {
9
+ [key: string]: OptionValue;
10
+ };
11
+ /** The data of a report, which fills the `{{name}}` placeholders of its message. */
12
+ export type ReportData = Record<string, string | number>;
13
+ export type Report = {
14
+ node: Node;
15
+ messageId: string;
16
+ data?: ReportData;
17
+ };
18
+ /** What a rule receives for one file of a project. */
19
+ export type RuleContext<Options extends RuleOptions = RuleOptions> = {
20
+ /** The id of the rule in the configuration, for example `must-use-result` or `himmel/no-raw-date`. */
21
+ id: string;
22
+ /** The options of the rule for this file, merged over `meta.defaultOptions`. */
23
+ options: Options;
24
+ sourceFile: SourceFile;
25
+ program: Program;
26
+ checker: Checker;
27
+ /** Reports a node at its start, without its leading trivia. */
28
+ report(report: Report): void;
29
+ };
30
+ /** The functions that a rule calls for the nodes of each syntax kind, in the order of one walk of the file. */
31
+ export type Visitor = {
32
+ [Kind in SyntaxKind]?: (node: Node) => void;
33
+ };
34
+ export type RuleMeta<Options extends RuleOptions = RuleOptions> = {
35
+ docs: {
36
+ description: string;
37
+ url: string;
38
+ };
39
+ messages: Record<string, string>;
40
+ defaultOptions: Options;
41
+ };
42
+ /**
43
+ * A typed rule. `create` and `checkOptions` are methods, so that a rule with
44
+ * its own options type is a `RuleModule` of the options of any rule, as a
45
+ * plugin holds it.
46
+ */
47
+ export type RuleModule<Options extends RuleOptions = RuleOptions> = {
48
+ meta: RuleMeta<Options>;
49
+ create(context: RuleContext<Options>): Visitor;
50
+ /** The problem with the merged options, or `undefined` when there is none. */
51
+ checkOptions?(options: Options): string | undefined;
52
+ };
53
+ /** Rule modules under one name. The id of each rule is `<name>/<rule name>`. */
54
+ export type Plugin = {
55
+ name: string;
56
+ rules: Record<string, RuleModule>;
57
+ };
package/dist/rule.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ import type { RuleModule } from '../rule.ts';
2
+ /** The typed rules of this package, by their ids, which have no prefix. */
3
+ export declare const rules: Record<string, RuleModule>;
@@ -0,0 +1,8 @@
1
+ import { mustUseResult } from './must-use-result.js';
2
+ import { noGeneratedEmptyObjectType } from './no-generated-empty-object-type.js';
3
+ import { requireAbortSignal } from './require-abort-signal.js';
4
+ export const rules = {
5
+ 'must-use-result': mustUseResult,
6
+ 'no-generated-empty-object-type': noGeneratedEmptyObjectType,
7
+ 'require-abort-signal': requireAbortSignal,
8
+ };
@@ -0,0 +1,16 @@
1
+ import type { RuleModule } from '../rule.ts';
2
+ type Options = {
3
+ consumers: string[];
4
+ };
5
+ /**
6
+ * A port of `must-use-result` of `@ninoseki/eslint-plugin-neverthrow` 0.3.2
7
+ * (MIT) to the AST and the checker of TypeScript 7, with the extensions of the
8
+ * inflexa subsystems: `isOk`, `isErr` and `_unsafeUnwrapErr` as handled calls,
9
+ * the reads of `error`, `value`, `isOk` and `isErr`, and the functions of the
10
+ * option `consumers`, which take a Result and handle it.
11
+ *
12
+ * A Result that nothing reads is an error that nothing handles: the failure it
13
+ * carries goes away in silence, which is what the type was chosen to prevent.
14
+ */
15
+ export declare const mustUseResult: RuleModule<Options>;
16
+ export {};
@@ -0,0 +1,206 @@
1
+ import { isArrayLiteralExpression, isArrowFunction, isAwaitExpression, isBinaryExpression, isCallExpression, isFunctionExpression, isIdentifier, isParenthesizedExpression, isPropertyAccessExpression, isSourceFile, isVariableDeclaration, isYieldExpression, SyntaxKind, } from 'typescript/unstable/ast';
2
+ import { isUnionType } from 'typescript/unstable/sync';
3
+ import { stringArraysOnly } from '../rule-options.js';
4
+ const RESULT_PROPERTIES = ['mapErr', 'map', 'andThen', 'orElse', 'match', 'unwrapOr'];
5
+ const HANDLED_METHODS = new Set(['match', 'unwrapOr', '_unsafeUnwrap', '_unsafeUnwrapErr', 'isOk', 'isErr']);
6
+ const HANDLED_PROPERTIES = new Set(['error', 'value', 'isOk', 'isErr']);
7
+ const CHECKED_METHODS = new Set(['isOk', 'isErr']);
8
+ const FORWARDING_METHODS = new Set(['orElse', 'map', 'mapErr', 'andThen']);
9
+ const IGNORED_PARENTS = new Set([
10
+ SyntaxKind.AsExpression,
11
+ SyntaxKind.SatisfiesExpression,
12
+ SyntaxKind.TypeAssertionExpression,
13
+ SyntaxKind.NonNullExpression,
14
+ SyntaxKind.ClassDeclaration,
15
+ SyntaxKind.FunctionDeclaration,
16
+ SyntaxKind.MethodDeclaration,
17
+ SyntaxKind.PropertyDeclaration,
18
+ ]);
19
+ const END_OF_WALK = new Set([SyntaxKind.Block, SyntaxKind.SourceFile]);
20
+ function parentOf(node) {
21
+ if (isSourceFile(node))
22
+ return undefined;
23
+ let parent = node.parent;
24
+ while (isParenthesizedExpression(parent))
25
+ parent = parent.parent;
26
+ return parent;
27
+ }
28
+ function unwrap(node) {
29
+ let current = node;
30
+ while (isParenthesizedExpression(current))
31
+ current = current.expression;
32
+ return current;
33
+ }
34
+ function memberName(node) {
35
+ return isPropertyAccessExpression(node) && isIdentifier(node.name) ? node.name.text : undefined;
36
+ }
37
+ function isCallee(node) {
38
+ const parent = parentOf(node);
39
+ return parent !== undefined && isCallExpression(parent) && unwrap(parent.expression) === node;
40
+ }
41
+ function isSafeTryCallee(callee) {
42
+ const target = unwrap(callee);
43
+ if (isIdentifier(target))
44
+ return target.text === 'safeTry';
45
+ return memberName(target) === 'safeTry';
46
+ }
47
+ function isInsideSafeTryYield(node) {
48
+ let current = node;
49
+ let foundYieldDelegate = false;
50
+ for (let parent = parentOf(current); parent !== undefined; parent = parentOf(current)) {
51
+ if (isYieldExpression(parent) && parent.expression !== undefined && unwrap(parent.expression) === current) {
52
+ if (parent.asteriskToken === undefined)
53
+ return false;
54
+ foundYieldDelegate = true;
55
+ }
56
+ if (foundYieldDelegate && (isFunctionExpression(parent) || isArrowFunction(parent))) {
57
+ const call = parentOf(parent);
58
+ if (call === undefined || !isCallExpression(call) || !call.arguments.some((argument) => unwrap(argument) === parent))
59
+ return false;
60
+ return isSafeTryCallee(call.expression);
61
+ }
62
+ if (parent.kind === SyntaxKind.SourceFile)
63
+ return false;
64
+ current = parent;
65
+ }
66
+ return false;
67
+ }
68
+ function isHandledResult(node) {
69
+ const parent = parentOf(node);
70
+ if (parent !== undefined && isAwaitExpression(parent))
71
+ return isHandledResult(parent);
72
+ if (parent !== undefined && (isPropertyAccessExpression(parent) || parent.kind === SyntaxKind.ElementAccessExpression)) {
73
+ const name = memberName(parent);
74
+ if (name !== undefined && HANDLED_METHODS.has(name) && isCallee(parent))
75
+ return true;
76
+ if (name !== undefined && HANDLED_PROPERTIES.has(name))
77
+ return true;
78
+ const above = parentOf(parent);
79
+ if (above !== undefined && above.kind !== SyntaxKind.ExpressionStatement)
80
+ return isHandledResult(above);
81
+ }
82
+ return false;
83
+ }
84
+ function isCheckedResult(node) {
85
+ const parent = parentOf(node);
86
+ if (!isIdentifier(node) || parent === undefined)
87
+ return false;
88
+ const name = memberName(parent);
89
+ const above = parentOf(parent);
90
+ return name !== undefined && CHECKED_METHODS.has(name) && above !== undefined && isCallExpression(above);
91
+ }
92
+ function isReturned(node) {
93
+ for (let current = node; !END_OF_WALK.has(current.kind); current = current.parent) {
94
+ if (isArrowFunction(current) || current.kind === SyntaxKind.ReturnStatement)
95
+ return true;
96
+ }
97
+ return false;
98
+ }
99
+ function isConsumed(node, consumers) {
100
+ if (consumers.size === 0)
101
+ return false;
102
+ let current = node;
103
+ for (let parent = parentOf(current); parent !== undefined; parent = parentOf(current)) {
104
+ if (isCallExpression(parent) && isIdentifier(parent.expression) && consumers.has(parent.expression.text) && parent.arguments.some((argument) => unwrap(argument) === current))
105
+ return true;
106
+ const name = memberName(parent);
107
+ const above = parentOf(parent);
108
+ if (name !== undefined && FORWARDING_METHODS.has(name) && above !== undefined && isCallExpression(above) && unwrap(above.expression) === parent) {
109
+ current = above;
110
+ continue;
111
+ }
112
+ const forwards = isAwaitExpression(parent) || parent.kind === SyntaxKind.AsExpression || parent.kind === SyntaxKind.NonNullExpression;
113
+ if (!forwards)
114
+ return false;
115
+ current = parent;
116
+ }
117
+ return false;
118
+ }
119
+ export const mustUseResult = {
120
+ meta: {
121
+ docs: {
122
+ description: 'Require each neverthrow Result to be used',
123
+ url: 'https://github.com/inflexa-ai/lint/blob/main/docs/rules/must-use-result.md',
124
+ },
125
+ messages: {
126
+ mustUseResult: 'Result must be handled with either of match, unwrapOr, _unsafeUnwrap or _unsafeUnwrapErr.',
127
+ },
128
+ defaultOptions: { consumers: [] },
129
+ },
130
+ checkOptions: stringArraysOnly,
131
+ create(context) {
132
+ const { checker, sourceFile } = context;
133
+ const consumers = new Set(context.options.consumers);
134
+ const resultLike = new Map();
135
+ function typeIsResult(type) {
136
+ const cached = resultLike.get(type.id);
137
+ if (cached !== undefined)
138
+ return cached;
139
+ const apparent = checker.getApparentType(type) ?? type;
140
+ const members = isUnionType(apparent) ? apparent.getTypes() : [apparent];
141
+ const result = members.some((member) => RESULT_PROPERTIES.every((property) => checker.getPropertyOfType(member, property) !== undefined));
142
+ resultLike.set(type.id, result);
143
+ return result;
144
+ }
145
+ function isResultLike(node) {
146
+ if (node === undefined)
147
+ return false;
148
+ const type = checker.getTypeAtLocation(node);
149
+ return type !== undefined && typeIsResult(type);
150
+ }
151
+ function isInResultCall(node) {
152
+ const array = parentOf(node);
153
+ if (array === undefined || !isArrayLiteralExpression(array) || !array.elements.some((element) => unwrap(element) === node))
154
+ return false;
155
+ const call = parentOf(array);
156
+ return call !== undefined && isCallExpression(call) && call.arguments.some((argument) => unwrap(argument) === array) && isResultLike(call);
157
+ }
158
+ function assignedName(node) {
159
+ for (let child, current = node; !END_OF_WALK.has(current.kind); child = current, current = current.parent) {
160
+ if (isVariableDeclaration(current) && isResultLike(current.initializer) && isIdentifier(current.name))
161
+ return current.name;
162
+ if (isBinaryExpression(current) && current.operatorToken.kind === SyntaxKind.EqualsToken && child === current.right && isResultLike(current.right)) {
163
+ const target = unwrap(current.left);
164
+ if (isIdentifier(target))
165
+ return target;
166
+ }
167
+ }
168
+ return undefined;
169
+ }
170
+ function isUsedThroughVariable(node, followed) {
171
+ const name = assignedName(node);
172
+ if (name === undefined)
173
+ return false;
174
+ const symbol = checker.getSymbolAtLocation(name);
175
+ if (symbol === undefined || followed.has(symbol.id))
176
+ return false;
177
+ const path = new Set(followed).add(symbol.id);
178
+ return checker.getReferencesToSymbolInFile(sourceFile.fileName, symbol).some((handle) => {
179
+ const reference = handle.resolve();
180
+ if (reference === undefined || (reference.pos === name.pos && reference.end === name.end))
181
+ return false;
182
+ return !isUnused(reference, true, path);
183
+ });
184
+ }
185
+ function isUnused(node, isReference, followed) {
186
+ const parent = parentOf(node);
187
+ if (parent !== undefined && IGNORED_PARENTS.has(parent.kind))
188
+ return false;
189
+ if (!isResultLike(node))
190
+ return false;
191
+ if (isCallExpression(node) && parent !== undefined && isAwaitExpression(parent))
192
+ return false;
193
+ if (isHandledResult(node) || isInsideSafeTryYield(node) || isCheckedResult(node) || isReturned(node) || isInResultCall(node) || isConsumed(node, consumers))
194
+ return false;
195
+ if (isUsedThroughVariable(node, followed))
196
+ return false;
197
+ if (!isReference)
198
+ context.report({ node, messageId: 'mustUseResult' });
199
+ return true;
200
+ }
201
+ const visit = (node) => {
202
+ isUnused(node, false, new Set());
203
+ };
204
+ return { [SyntaxKind.CallExpression]: visit, [SyntaxKind.NewExpression]: visit, [SyntaxKind.AwaitExpression]: visit };
205
+ },
206
+ };
@@ -0,0 +1,12 @@
1
+ import type { RuleModule } from '../rule.ts';
2
+ /**
3
+ * `Omit<{ a: string }, 'a'>` and `{ a: 1 } & Record<never, 1>` read as shapes
4
+ * and resolve to `{}`, which accepts every value but `null` and `undefined`.
5
+ * Such a type is almost always a mistake of a type operation, and nothing at
6
+ * the use says so.
7
+ *
8
+ * A port of `no-generated-empty-object-type` of typescript-eslint (MIT) to the
9
+ * API of TypeScript 7. It reads the type of an intersection, and of a type
10
+ * reference with type arguments that is not a member of an intersection.
11
+ */
12
+ export declare const noGeneratedEmptyObjectType: RuleModule;
@@ -0,0 +1,47 @@
1
+ import { isTypeReferenceNode, SyntaxKind } from 'typescript/unstable/ast';
2
+ import { isObjectType, isUnionType, ObjectFlags, SignatureKind } from 'typescript/unstable/sync';
3
+ export const noGeneratedEmptyObjectType = {
4
+ meta: {
5
+ docs: {
6
+ description: 'Disallow type operations that resolve to the "empty object" type',
7
+ url: 'https://github.com/inflexa-ai/lint/blob/main/docs/rules/no-generated-empty-object-type.md',
8
+ },
9
+ messages: {
10
+ noGeneratedEmptyObjectType: 'This type resolves to `{}`, the empty object type. This was likely not intentional.',
11
+ },
12
+ defaultOptions: {},
13
+ },
14
+ create(context) {
15
+ const { checker } = context;
16
+ function isEmptyObjectType(type) {
17
+ return (isObjectType(type) &&
18
+ (type.objectFlags & (ObjectFlags.Class | ObjectFlags.Interface)) === 0 &&
19
+ checker.getPropertiesOfType(type).length === 0 &&
20
+ checker.getIndexInfosOfType(type).length === 0 &&
21
+ checker.getSignaturesOfType(type, SignatureKind.Call).length === 0 &&
22
+ checker.getSignaturesOfType(type, SignatureKind.Construct).length === 0 &&
23
+ checker.isTypeAssignableTo(checker.getNumberType(), type) &&
24
+ checker.isTypeAssignableTo(checker.getStringType(), type));
25
+ }
26
+ function check(node) {
27
+ const type = checker.getTypeAtLocation(node);
28
+ if (type === undefined)
29
+ return;
30
+ if (isEmptyObjectType(type) || (isUnionType(type) && type.getTypes().some(isEmptyObjectType))) {
31
+ context.report({ node, messageId: 'noGeneratedEmptyObjectType' });
32
+ }
33
+ }
34
+ return {
35
+ [SyntaxKind.IntersectionType]: check,
36
+ [SyntaxKind.TypeReference]: (node) => {
37
+ if (!isTypeReferenceNode(node) || node.typeArguments === undefined)
38
+ return;
39
+ let parent = node.parent;
40
+ while (parent.kind === SyntaxKind.ParenthesizedType)
41
+ parent = parent.parent;
42
+ if (parent.kind !== SyntaxKind.IntersectionType)
43
+ check(node);
44
+ },
45
+ };
46
+ },
47
+ };
@@ -0,0 +1,22 @@
1
+ import type { RuleModule } from '../rule.ts';
2
+ type Options = {
3
+ declaredIn: string[];
4
+ };
5
+ /**
6
+ * A request nobody can end outlives whatever asked for it: a query function
7
+ * that forgets its signal keeps fetching after its component is gone and writes
8
+ * the answer into the cache, and a throttled call sits through a wait of up to
9
+ * thirty seconds per attempt that nothing can cut short.
10
+ *
11
+ * The call is recognised by where its signature is declared, not by what the
12
+ * variable holding the client is called. A client is built once and passed
13
+ * around under whatever name the feature gives it, so a rule that matched
14
+ * `api.get` would miss `org.get` and would report `map.get`.
15
+ *
16
+ * Only the leaf is checked. A wrapper whose own `signal` is optional is
17
+ * reported inside it, and the moment it declares `signal: AbortSignal` the
18
+ * compiler makes every caller supply one; the obligation then climbs, by
19
+ * ordinary types, to a query's context, a loader's controller or a deadline.
20
+ */
21
+ export declare const requireAbortSignal: RuleModule<Options>;
22
+ export {};
@@ -0,0 +1,103 @@
1
+ import { isCallExpression, isIdentifier, isSignatureDeclaration, SyntaxKind } from 'typescript/unstable/ast';
2
+ import { isUnionType, SignatureKind, SymbolFlags, TypeFlags } from 'typescript/unstable/sync';
3
+ import { indirectionOf } from '../helpers/reflective-calls.js';
4
+ import { stringArraysOnly } from '../rule-options.js';
5
+ const DECLARATION_FILE = /\.d\.[cm]?ts$/i;
6
+ function declarationName(declaration) {
7
+ if (!isSignatureDeclaration(declaration) || !('name' in declaration))
8
+ return undefined;
9
+ const { name } = declaration;
10
+ return name !== undefined && isIdentifier(name) ? name.text : undefined;
11
+ }
12
+ export const requireAbortSignal = {
13
+ meta: {
14
+ docs: {
15
+ description: 'Require an AbortSignal on every call into the API client and on every fetch',
16
+ url: 'https://github.com/inflexa-ai/lint/blob/main/docs/rules/require-abort-signal.md',
17
+ },
18
+ defaultOptions: { declaredIn: [] },
19
+ messages: {
20
+ indirectCall: 'This call goes through `{{through}}`, where the options cannot be read, so nothing here can tell whether the request carries a `signal`. Call the method directly, `api.get(path, { signal })`: app code has no need for the indirection, and reaching for it is how a request ends up with nothing to cancel it.',
21
+ missingSignal: 'This call cannot be cancelled: {{problem}}. Pass a `signal` typed `AbortSignal`, not `AbortSignal | undefined`. Inside a query function it is the `signal` of the context the library hands you. Where nothing can cancel the call, a mutation among them, it is a deadline: `AbortSignal.timeout(ms)`. Where both exist, combine them with `AbortSignal.any([signal, AbortSignal.timeout(ms)])`. A wrapper declares `signal: AbortSignal` in its own options and the compiler asks its callers.',
22
+ },
23
+ },
24
+ checkOptions: stringArraysOnly,
25
+ create(context) {
26
+ const { checker } = context;
27
+ const { declaredIn } = context.options;
28
+ if (declaredIn.length === 0)
29
+ return {};
30
+ const clientFiles = declaredIn.map((pattern) => new RegExp(pattern));
31
+ const clientPaths = declaredIn.map((pattern) => new RegExp(pattern, 'i'));
32
+ function optionsTypeOf(signature) {
33
+ const last = signature.getParameters().at(-1);
34
+ if (last === undefined || last.valueDeclaration === undefined)
35
+ return undefined;
36
+ const type = checker.getTypeOfSymbol(last);
37
+ return type === undefined ? undefined : checker.getNonNullableType(type);
38
+ }
39
+ function signatureIsTarget(signature) {
40
+ const handle = signature.declaration;
41
+ if (handle === undefined)
42
+ return false;
43
+ const inLibrary = DECLARATION_FILE.test(handle.path);
44
+ if (!inLibrary && !clientPaths.some((pattern) => pattern.test(handle.path)))
45
+ return false;
46
+ const declaration = handle.resolve();
47
+ if (declaration === undefined)
48
+ return false;
49
+ const source = declaration.getSourceFile();
50
+ const named = source.isDeclarationFile && declarationName(declaration) === 'fetch';
51
+ if (!named && !clientFiles.some((pattern) => pattern.test(source.fileName)))
52
+ return false;
53
+ const options = optionsTypeOf(signature);
54
+ return options !== undefined && checker.getPropertyOfType(options, 'signal') !== undefined;
55
+ }
56
+ function typeIsTarget(node) {
57
+ const type = checker.getTypeAtLocation(node);
58
+ return type !== undefined && checker.getSignaturesOfType(type, SignatureKind.Call).some((signature) => signatureIsTarget(signature));
59
+ }
60
+ function problemWith(call, signature) {
61
+ const at = signature.getParameters().length - 1;
62
+ const argument = call.arguments.at(at);
63
+ if (at < 0 || argument === undefined)
64
+ return 'it was given no options to put one in';
65
+ const type = checker.getTypeAtLocation(argument);
66
+ if (type === undefined || (type.flags & TypeFlags.Any) !== 0)
67
+ return 'its options are typed `any`, which promises no `signal` at all';
68
+ const signal = checker.getPropertyOfType(type, 'signal');
69
+ if (signal === undefined)
70
+ return 'its options carry no `signal`';
71
+ if ((signal.flags & SymbolFlags.Optional) !== 0)
72
+ return 'its `signal` is optional, so it may be missing';
73
+ const signalType = checker.getTypeOfSymbolAtLocation(signal, argument);
74
+ if (signalType.id === checker.getNonNullableType(signalType)?.id)
75
+ return undefined;
76
+ const parts = isUnionType(signalType) ? signalType.getTypes() : [signalType];
77
+ const absent = [
78
+ parts.some((part) => (part.flags & TypeFlags.Null) !== 0) ? '`null`' : undefined,
79
+ parts.some((part) => (part.flags & TypeFlags.Undefined) !== 0) ? '`undefined`' : undefined,
80
+ ].filter((word) => word !== undefined);
81
+ return `its \`signal\` may be ${absent.join(' or ')}`;
82
+ }
83
+ return {
84
+ [SyntaxKind.CallExpression]: (call) => {
85
+ if (!isCallExpression(call))
86
+ return;
87
+ const signature = checker.getResolvedSignature(call);
88
+ if (signature === undefined)
89
+ return;
90
+ const through = indirectionOf(call, signature, typeIsTarget);
91
+ if (through !== undefined) {
92
+ context.report({ node: call, messageId: 'indirectCall', data: { through } });
93
+ return;
94
+ }
95
+ if (!signatureIsTarget(signature))
96
+ return;
97
+ const problem = problemWith(call, signature);
98
+ if (problem !== undefined)
99
+ context.report({ node: call, messageId: 'missingSignal', data: { problem } });
100
+ },
101
+ };
102
+ },
103
+ };