@stateward/core 1.1.0 → 1.2.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/dist/index.d.ts CHANGED
@@ -10,11 +10,15 @@ export { createPropagationMemo, propagate } from "./graph.js";
10
10
  export type { Propagation, PropagationMemo } from "./graph.js";
11
11
  export { highestUncovered, shortestPath } from "./tree.js";
12
12
  export type { TreeEdge, Uncovered, WalkDown } from "./tree.js";
13
+ export { describeRelease, describeTraitSource, releaseCandidates, releaseTraitOf, } from "./release.js";
14
+ export { neverRejectsFactOf } from "./package-facts.js";
15
+ export type { FactContext, PackageFact } from "./package-facts.js";
16
+ export type { ReleaseCandidate, ReleaseOptions, ReleaseTrait, ReleaseWay } from "./release.js";
13
17
  export { packageCodeId } from "./implementation.js";
14
18
  export { readPackageCache, writePackageCache } from "./package-cache.js";
15
19
  export type { PackageCacheKey } from "./package-cache.js";
16
20
  export { findPackageRoot, reparsedWithJsDoc } from "./backend/package-source.js";
17
21
  export { openPackageSource } from "./backend/typescript6.js";
18
22
  export type { PackageSource } from "./backend/typescript6.js";
19
- export type { BooleanOption, CheckNotes, CheckResult, Config, ConfigOverride, CoveredPlace, EditorAction, EditorContributions, EditorHint, ExtendedConfig, FileContext, FactSource, FileRule, Finding, FunctionFacts, LibraryTypes, LibraryUse, MissingTypes, PackageFactsConfig, Fix, FixForm, FixReview, FixSetReview, FixVerdict, RejectedFix, GroupIdOf, HiddenFindings, IgnoreOptions, IgnoredFinding, Json, Literal, NarrowedMembers, SignalParameter, StatedGuarantee, NoOptions, NumberOption, OptionSpec, RecordOption, SeveritiesOption, SeverityMap, StringListRecord, OptionSpecs, OptionValue, OptionValueOf, Options, OptionsOf, NarrowingTest, OverrideOf, Location, ParseResult, Plugin, PluginOf, PluginsOf, Preset, ProjectContext, ProjectRule, RelatedLocation, ReportProblem, LazyRule, PluginRule, Rule, RuleConfig, RuleDeclaration, RuleIdOf, RuleInfo, RuleMeta, RuleSelection, RuleSetting, RuleTier, Severity, StringOption, StringsOption, SymbolRef, AliasRef, TextEdit, TokenType, TypeQueries, UnknownsSetting, UserConfig, } from "./types.js";
23
+ export type { BooleanOption, CheckNotes, CheckResult, Config, ConfigOverride, CoveredNoun, CoveredPlace, EditorAction, EditorContributions, EditorHint, ExtendedConfig, FileContext, FactSource, FileRule, Finding, FunctionFacts, LibraryTypes, LibraryUse, MissingTypes, PackageFactsConfig, Fix, FixForm, FixReview, FixSetReview, FixVerdict, RejectedFix, GroupIdOf, HiddenFindings, IgnoreOptions, IgnoredFinding, Json, Literal, NarrowedMembers, SignalParameter, StatedGuarantee, TraitSource, ReleaseFact, NoOptions, NumberOption, OptionSpec, RecordOption, SeveritiesOption, SeverityMap, StringListRecord, OptionSpecs, OptionValue, OptionValueOf, Options, OptionsOf, NarrowingTest, OverrideOf, Location, ParseResult, Plugin, PluginOf, PluginsOf, Preset, ProjectContext, ProjectRule, RelatedLocation, ReportProblem, LazyRule, PluginRule, Rule, RuleConfig, RuleDeclaration, RuleIdOf, RuleInfo, RuleMeta, RuleSelection, RuleSetting, RuleTier, Severity, StringOption, StringsOption, SymbolRef, AliasRef, TextEdit, TokenType, TypeQueries, UnknownsSetting, UserConfig, } from "./types.js";
20
24
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -10,6 +10,10 @@ export { check, createChecker } from "./checker.js";
10
10
  // Helpers for project rules that follow calls across files.
11
11
  export { createPropagationMemo, propagate } from "./graph.js";
12
12
  export { highestUncovered, shortestPath } from "./tree.js";
13
+ // The release trait: where a call's result is stated to need releasing (type, marker, facts).
14
+ export { describeRelease, describeTraitSource, releaseCandidates, releaseTraitOf, } from "./release.js";
15
+ // Facts about packages: the config's and the shipped lines, and the promises they say never reject.
16
+ export { neverRejectsFactOf } from "./package-facts.js";
13
17
  // What a pack learns about a library's code, cached outside the project.
14
18
  export { packageCodeId } from "./implementation.js";
15
19
  export { readPackageCache, writePackageCache } from "./package-cache.js";
@@ -15,7 +15,7 @@ export { findConfigFile, findConfigUpward, loadConfig, loadConfigFile, reloadsLo
15
15
  export { LOOSE_NULLS_FIX, MAX_FINDINGS_PER_RULE_PER_FILE, STRICT_NULLS_REMEDY, activeRuleIds, compareFindings, explain, limitFindings, } from "./engine.js";
16
16
  export type { CheckProgress } from "./engine.js";
17
17
  export { SLICE_MS } from "./checker.js";
18
- export { describeStatus, guaranteeAt, proveGuarantees } from "./guarantees.js";
18
+ export { counted, describeStatus, guaranteeAt, proveGuarantees } from "./guarantees.js";
19
19
  export type { GuaranteeProof, GuaranteeStatus } from "./guarantees.js";
20
20
  export type { LongestStep, SliceOptions, SlicedCheck } from "./checker.js";
21
21
  export { IGNORE_FIX_TITLE, IGNORE_RULE_ID, ignoreFix } from "./ignores.js";
@@ -32,4 +32,7 @@ export { CACHE_SUBDIR, PROJECT_CACHE_DIR, RESULTS_CACHE_DEFAULT_MB, cleanResults
32
32
  export type { DiskCache, ResultsCacheStats } from "./disk-cache.js";
33
33
  export type { CacheEntry } from "./disk-limits.js";
34
34
  export type { RuleCost, RunTiming, TimingRecorder } from "./timing.js";
35
+ export { hintLines, hintWithoutExamples, laidOutHint } from "./hint-lines.js";
36
+ export type { HintLine } from "./hint-lines.js";
37
+ export { renameNotice, renamedIdsIn, renamedRule } from "./renamed.js";
35
38
  //# sourceMappingURL=internal.d.ts.map
package/dist/internal.js CHANGED
@@ -14,7 +14,7 @@ export { advance, buildPlan, describeNotChecked, describeTurnOn, isClean } from
14
14
  export { findConfigFile, findConfigUpward, loadConfig, loadConfigFile, reloadsLocalImports, } from "./config-file.js";
15
15
  export { LOOSE_NULLS_FIX, MAX_FINDINGS_PER_RULE_PER_FILE, STRICT_NULLS_REMEDY, activeRuleIds, compareFindings, explain, limitFindings, } from "./engine.js";
16
16
  export { SLICE_MS } from "./checker.js";
17
- export { describeStatus, guaranteeAt, proveGuarantees } from "./guarantees.js";
17
+ export { counted, describeStatus, guaranteeAt, proveGuarantees } from "./guarantees.js";
18
18
  export { IGNORE_FIX_TITLE, IGNORE_RULE_ID, ignoreFix } from "./ignores.js";
19
19
  export { CACHE_FORMAT, emptyCache, parseSnapshot, toSnapshot } from "./cache.js";
20
20
  export { stronglyConnectedComponents } from "./graph.js";
@@ -24,4 +24,6 @@ export { NothingToCheckError, TsconfigError, TypeScriptLibMissingError, missingD
24
24
  export { createTimingRecorder } from "./timing.js";
25
25
  export { cacheEntries, dropLeastRecentlyUsed, limitBytes, markUsed } from "./disk-limits.js";
26
26
  export { CACHE_SUBDIR, PROJECT_CACHE_DIR, RESULTS_CACHE_DEFAULT_MB, cleanResultsCache, defaultCacheDir, userCacheDir, openDiskCache, resultsCacheLimit, resultsCacheStats, } from "./disk-cache.js";
27
+ export { hintLines, hintWithoutExamples, laidOutHint } from "./hint-lines.js";
28
+ export { renameNotice, renamedIdsIn, renamedRule } from "./renamed.js";
27
29
  //# sourceMappingURL=internal.js.map
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The `facts` line for a package function or property: the config's first, then the facts the
3
+ * loaded plugins ship. Core reads the lines and knows no library; each line names a declaration
4
+ * by its path in the package's types (`Observable.subscribe`) or by its own name (`onSnapshot`).
5
+ */
6
+ import ts from "typescript";
7
+ import type { FileContext, FunctionFacts } from "./types.js";
8
+ /** What a lookup reads: the program's types, both sets of facts, and the file the code is in. */
9
+ export type FactContext = Pick<FileContext, "types" | "facts" | "shippedFacts" | "sourceFile">;
10
+ /** The facts line a declaration has, the package it is listed under, and which set it is from. */
11
+ export type PackageFact = {
12
+ readonly package: string;
13
+ readonly fact: FunctionFacts;
14
+ readonly source: "config" | "shipped";
15
+ };
16
+ /** The declaration's path in its package's types: `["Observable", "subscribe"]`. */
17
+ export declare function pathOf(node: ts.Node): string[];
18
+ /** The name the call is made through: `onSnapshot` of `onSnapshot(…)`, `subscribe` of `a.subscribe(…)`. */
19
+ export declare function calleeName(call: ts.CallExpression | ts.NewExpression): ts.Identifier | undefined;
20
+ /** The module a file imports a name from: `"firebase/firestore"` for `onSnapshot`. */
21
+ export declare function importedFrom(sourceFile: ts.SourceFile, name: string): string | undefined;
22
+ /** The leftmost name of a callee: `db` of `db.users.watch`. */
23
+ export declare function rootName(expression: ts.Expression): string | undefined;
24
+ /**
25
+ * The facts line for `declared`, a declaration in a package's types, reached in the file through
26
+ * `through` (the callee or the object a property is read from, whose import names the package):
27
+ * the config's line when it has one for the declaration, else a shipped one. Undefined for a
28
+ * declaration of the project, or one no line names.
29
+ */
30
+ export declare function packageFactOf(declared: {
31
+ readonly file: string;
32
+ readonly node: ts.Node;
33
+ }, through: ts.Expression | undefined, ctx: FactContext): PackageFact | undefined;
34
+ /**
35
+ * The package function a name of the project stands for: `listen` in `const listen = onSnapshot`,
36
+ * `const listen = db.onSnapshot` or `const { onSnapshot: listen } = firestore`. Only a name or a
37
+ * property read is followed, never a call: `const stop = onSnapshot(…)` holds what the call
38
+ * returned, not the function.
39
+ */
40
+ export declare function packageFunctionOf(name: ts.Identifier, ctx: FactContext): {
41
+ declared: {
42
+ file: string;
43
+ node: ts.Node;
44
+ };
45
+ through: ts.Expression | undefined;
46
+ } | undefined;
47
+ /**
48
+ * The facts line that says an awaited promise never rejects (`neverRejects: true`), when one
49
+ * does: an `await` of it is then not a way out of the function. Undefined otherwise.
50
+ */
51
+ export declare function neverRejectsFactOf(expression: ts.Expression, ctx: FactContext): PackageFact | undefined;
52
+ //# sourceMappingURL=package-facts.d.ts.map
@@ -0,0 +1,213 @@
1
+ /**
2
+ * The `facts` line for a package function or property: the config's first, then the facts the
3
+ * loaded plugins ship. Core reads the lines and knows no library; each line names a declaration
4
+ * by its path in the package's types (`Observable.subscribe`) or by its own name (`onSnapshot`).
5
+ */
6
+ import ts from "typescript";
7
+ function unwrapped(expression) {
8
+ let node = expression;
9
+ while (ts.isParenthesizedExpression(node) ||
10
+ ts.isNonNullExpression(node) ||
11
+ ts.isAsExpression(node) ||
12
+ ts.isSatisfiesExpression(node)) {
13
+ node = node.expression;
14
+ }
15
+ return node;
16
+ }
17
+ function declarationName(node) {
18
+ if (ts.isFunctionDeclaration(node) ||
19
+ ts.isClassDeclaration(node) ||
20
+ ts.isInterfaceDeclaration(node) ||
21
+ ts.isMethodDeclaration(node) ||
22
+ ts.isMethodSignature(node) ||
23
+ ts.isPropertyDeclaration(node) ||
24
+ ts.isPropertySignature(node) ||
25
+ ts.isVariableDeclaration(node) ||
26
+ ts.isTypeAliasDeclaration(node)) {
27
+ return node.name !== undefined && ts.isIdentifier(node.name) ? node.name.text : undefined;
28
+ }
29
+ if (ts.isModuleDeclaration(node))
30
+ return ts.isIdentifier(node.name) ? node.name.text : undefined;
31
+ return undefined;
32
+ }
33
+ /** The declaration's path in its package's types: `["Observable", "subscribe"]`. */
34
+ export function pathOf(node) {
35
+ const names = [];
36
+ for (let at = node; !ts.isSourceFile(at); at = at.parent) {
37
+ const name = declarationName(at);
38
+ if (name !== undefined)
39
+ names.unshift(name);
40
+ }
41
+ return names;
42
+ }
43
+ /** The name the call is made through: `onSnapshot` of `onSnapshot(…)`, `subscribe` of `a.subscribe(…)`. */
44
+ export function calleeName(call) {
45
+ const callee = unwrapped(call.expression);
46
+ if (ts.isIdentifier(callee))
47
+ return callee;
48
+ if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.name))
49
+ return callee.name;
50
+ return undefined;
51
+ }
52
+ /** The module a file imports a name from: `"firebase/firestore"` for `onSnapshot`. */
53
+ export function importedFrom(sourceFile, name) {
54
+ for (const statement of sourceFile.statements) {
55
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) {
56
+ continue;
57
+ }
58
+ const clause = statement.importClause;
59
+ if (clause === undefined)
60
+ continue;
61
+ const bindings = clause.namedBindings;
62
+ const named = clause.name?.text === name ||
63
+ (bindings !== undefined &&
64
+ (ts.isNamespaceImport(bindings)
65
+ ? bindings.name.text === name
66
+ : bindings.elements.some((element) => element.name.text === name)));
67
+ if (named)
68
+ return statement.moduleSpecifier.text;
69
+ }
70
+ return undefined;
71
+ }
72
+ /** The leftmost name of a callee: `db` of `db.users.watch`. */
73
+ export function rootName(expression) {
74
+ const node = unwrapped(expression);
75
+ if (ts.isIdentifier(node))
76
+ return node.text;
77
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) {
78
+ return rootName(node.expression);
79
+ }
80
+ if (ts.isCallExpression(node))
81
+ return rootName(node.expression);
82
+ return undefined;
83
+ }
84
+ function factOf(facts, packages, path) {
85
+ for (const name of packages) {
86
+ const functions = facts[name];
87
+ if (functions === undefined)
88
+ continue;
89
+ const fact = functions[path.join(".")] ?? functions[path.at(-1) ?? ""];
90
+ if (fact !== undefined)
91
+ return { package: name, fact };
92
+ }
93
+ return undefined;
94
+ }
95
+ /**
96
+ * The facts line for `declared`, a declaration in a package's types, reached in the file through
97
+ * `through` (the callee or the object a property is read from, whose import names the package):
98
+ * the config's line when it has one for the declaration, else a shipped one. Undefined for a
99
+ * declaration of the project, or one no line names.
100
+ */
101
+ export function packageFactOf(declared, through, ctx) {
102
+ const { types } = ctx;
103
+ if (types.isOwnFile(declared.file))
104
+ return undefined;
105
+ const root = through === undefined ? undefined : rootName(through);
106
+ const specifier = root === undefined ? undefined : importedFrom(ctx.sourceFile, root);
107
+ const owner = types.packageOf(declared.file);
108
+ const packages = [
109
+ ...new Set([specifier, owner].filter((item) => item !== undefined)),
110
+ ];
111
+ const path = pathOf(declared.node);
112
+ const fromConfig = factOf(ctx.facts, packages, path);
113
+ if (fromConfig !== undefined)
114
+ return { ...fromConfig, source: "config" };
115
+ const shipped = factOf(ctx.shippedFacts, packages, path);
116
+ return shipped === undefined ? undefined : { ...shipped, source: "shipped" };
117
+ }
118
+ /** How many `const` names are followed back to the promise they hold. */
119
+ const MAX_ALIASES = 4;
120
+ /**
121
+ * The package function a name of the project stands for: `listen` in `const listen = onSnapshot`,
122
+ * `const listen = db.onSnapshot` or `const { onSnapshot: listen } = firestore`. Only a name or a
123
+ * property read is followed, never a call: `const stop = onSnapshot(…)` holds what the call
124
+ * returned, not the function.
125
+ */
126
+ export function packageFunctionOf(name, ctx) {
127
+ const { types } = ctx;
128
+ let current = name;
129
+ for (let depth = 0; depth <= MAX_ALIASES; depth++) {
130
+ const node = unwrapped(current);
131
+ const id = ts.isIdentifier(node)
132
+ ? node
133
+ : ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name)
134
+ ? node.name
135
+ : undefined;
136
+ if (id === undefined)
137
+ return undefined;
138
+ const symbol = types.symbolAt(id);
139
+ const declared = symbol === undefined ? undefined : types.declarationOf(symbol);
140
+ if (declared === undefined)
141
+ return undefined;
142
+ if (!types.isOwnFile(declared.file)) {
143
+ return { declared, through: ts.isPropertyAccessExpression(node) ? node.expression : node };
144
+ }
145
+ const local = declared.node;
146
+ if (ts.isBindingElement(local)) {
147
+ const property = types.bindingPropertyOf(local);
148
+ const source = property === undefined ? undefined : types.declarationOf(property);
149
+ return source === undefined || types.isOwnFile(source.file)
150
+ ? undefined
151
+ : { declared: source, through: undefined };
152
+ }
153
+ if (!ts.isVariableDeclaration(local) ||
154
+ (ts.getCombinedNodeFlags(local) & ts.NodeFlags.Const) === 0 ||
155
+ local.initializer === undefined) {
156
+ return undefined;
157
+ }
158
+ current = local.initializer;
159
+ }
160
+ return undefined;
161
+ }
162
+ /**
163
+ * The package declaration an awaited expression comes from: the function of a call, the property
164
+ * read (`api.cacheEntryRemoved`), or, for a name, the property it was destructured from
165
+ * (`{ cacheEntryRemoved }` of a parameter) or the `const` it was given.
166
+ */
167
+ function promiseSource(expression, ctx, depth) {
168
+ const { types } = ctx;
169
+ const node = unwrapped(expression);
170
+ const name = ts.isCallExpression(node)
171
+ ? calleeName(node)
172
+ : ts.isPropertyAccessExpression(node) || ts.isIdentifier(node)
173
+ ? ts.isIdentifier(node)
174
+ ? node
175
+ : node.name
176
+ : undefined;
177
+ if (name === undefined || !ts.isIdentifier(name))
178
+ return undefined;
179
+ const symbol = types.symbolAt(name);
180
+ const declared = symbol === undefined ? undefined : types.declarationOf(symbol);
181
+ if (declared === undefined)
182
+ return undefined;
183
+ const through = ts.isCallExpression(node)
184
+ ? node.expression
185
+ : ts.isPropertyAccessExpression(node)
186
+ ? node.expression
187
+ : node;
188
+ if (!ts.isIdentifier(node) || !types.isOwnFile(declared.file))
189
+ return { declared, through };
190
+ const local = declared.node;
191
+ if (ts.isBindingElement(local)) {
192
+ const property = types.bindingPropertyOf(local);
193
+ const source = property === undefined ? undefined : types.declarationOf(property);
194
+ return source === undefined ? undefined : { declared: source, through: undefined };
195
+ }
196
+ if (ts.isVariableDeclaration(local) &&
197
+ (ts.getCombinedNodeFlags(local) & ts.NodeFlags.Const) !== 0 &&
198
+ local.initializer !== undefined &&
199
+ depth < MAX_ALIASES) {
200
+ return promiseSource(local.initializer, ctx, depth + 1);
201
+ }
202
+ return undefined;
203
+ }
204
+ /**
205
+ * The facts line that says an awaited promise never rejects (`neverRejects: true`), when one
206
+ * does: an `await` of it is then not a way out of the function. Undefined otherwise.
207
+ */
208
+ export function neverRejectsFactOf(expression, ctx) {
209
+ const source = promiseSource(expression, ctx, 0);
210
+ const found = source === undefined ? undefined : packageFactOf(source.declared, source.through, ctx);
211
+ return found?.fact.neverRejects === true ? found : undefined;
212
+ }
213
+ //# sourceMappingURL=package-facts.js.map
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The release trait: a value that must be released once it is no longer used (a subscription, a
3
+ * listener, a connection). Core reads where the trait is stated, in the plainest form first, and
4
+ * knows no library: a standard `Disposable` type, the project's `Release<T>` marker, a `facts`
5
+ * line in the config, or the facts a plugin ships (`Plugin.facts`).
6
+ */
7
+ import ts from "typescript";
8
+ import { type FactContext } from "./package-facts.js";
9
+ import type { TraitSource } from "./types.js";
10
+ /** The trait name the `Release<T>` marker states: `"__guarantee:release"?: true`. */
11
+ export declare const RELEASE = "release";
12
+ /**
13
+ * How a value with the release trait is released: calling it (`unsubscribe()`), calling a method
14
+ * on it (`subscription.unsubscribe()`), or disposing of it (`using`, `[Symbol.dispose]()`).
15
+ */
16
+ export type ReleaseWay = {
17
+ readonly kind: "call";
18
+ } | {
19
+ readonly kind: "method";
20
+ readonly name: string;
21
+ } | {
22
+ readonly kind: "dispose";
23
+ readonly async: boolean;
24
+ };
25
+ /** The release trait of a call's result, and where it is stated. */
26
+ export type ReleaseTrait = {
27
+ readonly way: ReleaseWay;
28
+ readonly source: TraitSource;
29
+ /** The function called, as the note names it: `onSnapshot`, `Observable.subscribe`. */
30
+ readonly callee: string;
31
+ };
32
+ /**
33
+ * What a rule tells `releaseTraitOf`: `platformPackages`, packages whose `Disposable` types do not
34
+ * state the trait (Node's types add `[Symbol.dispose]` to child processes, streams and timers,
35
+ * which end by themselves).
36
+ */
37
+ export type ReleaseOptions = {
38
+ readonly platformPackages?: readonly string[];
39
+ };
40
+ /**
41
+ * The release trait of what a call returns, from the plainest statement of it: the project's
42
+ * `Release<T>` marker on the return type, the config's `facts` line for the package function, the
43
+ * facts a plugin ships for it, then a standard `Disposable` or `AsyncDisposable` type. Undefined
44
+ * when nothing states it. A `Disposable` declared in one of `options.platformPackages` is left
45
+ * out, and so is a method that returns its own receiver (`stream.on(…)`).
46
+ */
47
+ export declare function releaseTraitOf(call: ts.CallExpression | ts.NewExpression, ctx: FactContext, options?: ReleaseOptions): ReleaseTrait | undefined;
48
+ /** A call `releaseCandidates` keeps or drops. */
49
+ export type ReleaseCandidate = (call: ts.CallExpression | ts.NewExpression) => boolean;
50
+ /**
51
+ * A test, from the syntax alone, of whether `releaseTraitOf` can find the trait for a call of the
52
+ * file, so a rule asks no type question about the others. When the program states `Release`
53
+ * somewhere, or a project file declares a `[Symbol.dispose]` or `[Symbol.asyncDispose]` member,
54
+ * every call is kept. Otherwise only a `facts` line with `returns` can state the trait, and a call
55
+ * is kept when its callee's name (`onSnapshot`, `store.subscribe`) is the last part of such a
56
+ * line's name or a name the project gives it with `as`, or when the call is made through a name
57
+ * imported from a package such a line is listed under. Built once per file.
58
+ */
59
+ export declare function releaseCandidates(ctx: FactContext): ReleaseCandidate;
60
+ /** Where a trait is stated, in words, for a note: "stateward's facts for rxjs". */
61
+ export declare function describeTraitSource(source: TraitSource): string;
62
+ /**
63
+ * The note on a finding about a value with the release trait: what the call returns and where
64
+ * that is stated. "`onSnapshot` returns a release function (stateward's facts for
65
+ * firebase/firestore)".
66
+ */
67
+ export declare function describeRelease(trait: ReleaseTrait): string;
68
+ //# sourceMappingURL=release.d.ts.map
@@ -0,0 +1,172 @@
1
+ /**
2
+ * The release trait: a value that must be released once it is no longer used (a subscription, a
3
+ * listener, a connection). Core reads where the trait is stated, in the plainest form first, and
4
+ * knows no library: a standard `Disposable` type, the project's `Release<T>` marker, a `facts`
5
+ * line in the config, or the facts a plugin ships (`Plugin.facts`).
6
+ */
7
+ import ts from "typescript";
8
+ import { calleeName, importedFrom, packageFactOf, packageFunctionOf, pathOf, rootName, } from "./package-facts.js";
9
+ /** The trait name the `Release<T>` marker states: `"__guarantee:release"?: true`. */
10
+ export const RELEASE = "release";
11
+ function unwrapped(expression) {
12
+ let node = expression;
13
+ while (ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node)) {
14
+ node = node.expression;
15
+ }
16
+ return node;
17
+ }
18
+ function wayOf(fact) {
19
+ return fact === "release" ? { kind: "call" } : { kind: "method", name: fact.release };
20
+ }
21
+ /**
22
+ * The release trait of what a call returns, from the plainest statement of it: the project's
23
+ * `Release<T>` marker on the return type, the config's `facts` line for the package function, the
24
+ * facts a plugin ships for it, then a standard `Disposable` or `AsyncDisposable` type. Undefined
25
+ * when nothing states it. A `Disposable` declared in one of `options.platformPackages` is left
26
+ * out, and so is a method that returns its own receiver (`stream.on(…)`).
27
+ */
28
+ export function releaseTraitOf(call, ctx, options = {}) {
29
+ const { types } = ctx;
30
+ const name = calleeName(call);
31
+ const symbol = name === undefined ? undefined : types.symbolAt(name);
32
+ const declared = symbol === undefined ? undefined : types.declarationOf(symbol);
33
+ const path = declared === undefined ? [] : pathOf(declared.node);
34
+ const calleeText = path.length > 0 ? path.join(".") : (name?.text ?? "the call");
35
+ if (types.guaranteesOf(call).includes(RELEASE)) {
36
+ const kind = types.disposeOf(call)?.kind;
37
+ const way = types.isCallable(call)
38
+ ? { kind: "call" }
39
+ : kind === undefined
40
+ ? undefined
41
+ : { kind: "dispose", async: kind === "async" };
42
+ if (way !== undefined)
43
+ return { way, source: { kind: "marker" }, callee: calleeText };
44
+ }
45
+ // A name the project gives a package function (`const listen = onSnapshot`) is followed to it.
46
+ const aliased = declared !== undefined && types.isOwnFile(declared.file) && ts.isIdentifier(call.expression)
47
+ ? packageFunctionOf(call.expression, ctx)
48
+ : undefined;
49
+ const found = aliased !== undefined
50
+ ? packageFactOf(aliased.declared, aliased.through, ctx)
51
+ : declared === undefined
52
+ ? undefined
53
+ : packageFactOf(declared, call.expression, ctx);
54
+ if (found?.fact.returns !== undefined) {
55
+ return {
56
+ way: wayOf(found.fact.returns),
57
+ source: { kind: found.source, package: found.package },
58
+ callee: calleeText,
59
+ };
60
+ }
61
+ const disposed = types.disposeOf(call);
62
+ if (disposed === undefined)
63
+ return undefined;
64
+ // Only a dispose method the project declares states the trait. TypeScript's own library and
65
+ // packages add `[Symbol.dispose]` to values that never need a release (iterators, generators,
66
+ // test mocks, Node's timers and streams): a package's value has the trait only through `facts`.
67
+ if (!types.isOwnFile(disposed.file))
68
+ return undefined;
69
+ const platform = types.packageOf(disposed.file);
70
+ if (platform !== undefined && (options.platformPackages ?? []).includes(platform)) {
71
+ return undefined;
72
+ }
73
+ // `stream.on(…)`, `hash.update(…)`: a method that returns its receiver starts nothing new.
74
+ const callee = unwrapped(call.expression);
75
+ if (ts.isPropertyAccessExpression(callee) &&
76
+ types.typeTextOf(callee.expression) === types.typeTextOf(call)) {
77
+ return undefined;
78
+ }
79
+ const kind = disposed.kind;
80
+ return {
81
+ way: { kind: "dispose", async: kind === "async" },
82
+ source: { kind: "type", name: kind === "async" ? "AsyncDisposable" : "Disposable" },
83
+ callee: calleeText,
84
+ };
85
+ }
86
+ /**
87
+ * A test, from the syntax alone, of whether `releaseTraitOf` can find the trait for a call of the
88
+ * file, so a rule asks no type question about the others. When the program states `Release`
89
+ * somewhere, or a project file declares a `[Symbol.dispose]` or `[Symbol.asyncDispose]` member,
90
+ * every call is kept. Otherwise only a `facts` line with `returns` can state the trait, and a call
91
+ * is kept when its callee's name (`onSnapshot`, `store.subscribe`) is the last part of such a
92
+ * line's name or a name the project gives it with `as`, or when the call is made through a name
93
+ * imported from a package such a line is listed under. Built once per file.
94
+ */
95
+ export function releaseCandidates(ctx) {
96
+ const { types } = ctx;
97
+ if (types.declaresTrait(RELEASE) || types.declaresDispose())
98
+ return () => true;
99
+ const names = new Set();
100
+ const packages = new Set();
101
+ for (const facts of [ctx.facts, ctx.shippedFacts]) {
102
+ for (const [name, functions] of Object.entries(facts)) {
103
+ for (const [key, fact] of Object.entries(functions)) {
104
+ if (fact.returns === undefined)
105
+ continue;
106
+ packages.add(name);
107
+ names.add(key.slice(key.lastIndexOf(".") + 1));
108
+ }
109
+ }
110
+ }
111
+ if (names.size === 0)
112
+ return () => false;
113
+ const renamed = types.renamedBindings();
114
+ for (const name of names) {
115
+ // A Set visits what is added while it is iterated: a chain of renames is followed to its end.
116
+ for (const alias of renamed.get(name) ?? [])
117
+ names.add(alias);
118
+ }
119
+ const imported = new Map();
120
+ const fromFactsPackage = (root) => {
121
+ let known = imported.get(root);
122
+ if (known === undefined) {
123
+ const specifier = importedFrom(ctx.sourceFile, root);
124
+ known = specifier !== undefined && packages.has(specifier);
125
+ imported.set(root, known);
126
+ }
127
+ return known;
128
+ };
129
+ return (call) => {
130
+ const name = calleeName(call);
131
+ if (name !== undefined && names.has(name.text))
132
+ return true;
133
+ const root = rootName(call.expression);
134
+ return root !== undefined && fromFactsPackage(root);
135
+ };
136
+ }
137
+ /** Where a trait is stated, in words, for a note: "stateward's facts for rxjs". */
138
+ export function describeTraitSource(source) {
139
+ switch (source.kind) {
140
+ case "type":
141
+ return `its type, \`${source.name}\``;
142
+ case "marker":
143
+ return "the project's marker";
144
+ case "config":
145
+ return `the config's facts for ${source.package}`;
146
+ case "shipped":
147
+ return `stateward's facts for ${source.package}`;
148
+ default: {
149
+ const unreachable = source;
150
+ return unreachable;
151
+ }
152
+ }
153
+ }
154
+ /**
155
+ * The note on a finding about a value with the release trait: what the call returns and where
156
+ * that is stated. "`onSnapshot` returns a release function (stateward's facts for
157
+ * firebase/firestore)".
158
+ */
159
+ export function describeRelease(trait) {
160
+ const what = trait.way.kind === "call"
161
+ ? "a release function"
162
+ : trait.way.kind === "method"
163
+ ? `a value released with \`${trait.way.name}()\``
164
+ : trait.way.async
165
+ ? "a value released with `await using` or `[Symbol.asyncDispose]()`"
166
+ : "a value released with `using` or `[Symbol.dispose]()`";
167
+ const stated = trait.source.kind === "marker"
168
+ ? "its return type is stated `Release`"
169
+ : describeTraitSource(trait.source);
170
+ return `\`${trait.callee}\` returns ${what} (${stated})`;
171
+ }
172
+ //# sourceMappingURL=release.js.map
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Rule ids a release renamed, so that a rule's name says what is wrong. The old id keeps working:
3
+ * a config, an ignore comment, the rollout file and the baseline that still use one are read under
4
+ * the new id, with a warning that says what to rename. Ids only: core still knows no library.
5
+ */
6
+ /** The id a renamed rule has now, or undefined when `ruleId` was not renamed. */
7
+ export declare function renamedRule(ruleId: string): string | undefined;
8
+ /** What a config that names an old id is told: `a` is now `b`; rename it in `where`. */
9
+ export declare function renameNotice(before: string, now: string, where: string): string;
10
+ /**
11
+ * What a config that names an old id is told when the rule moved to a pack it does not load
12
+ * (`react/a` is now `react-context/a`): the entry is ignored until the pack is added.
13
+ */
14
+ export declare function movedNotice(before: string, now: string, where: string): string;
15
+ /** An old rule id written in quotes in a file's text: the id's span, its line, and the new id. */
16
+ export type RenamedIdPlace = {
17
+ readonly before: string;
18
+ readonly now: string;
19
+ readonly start: number;
20
+ readonly end: number;
21
+ readonly line: number;
22
+ };
23
+ /**
24
+ * Every old id a text names as a string (`"records/table-type-too-loose"`), in order: what a
25
+ * config file has to rename, and where. Only whole quoted ids count, so a longer id or a comment
26
+ * that mentions one in other words is left alone.
27
+ */
28
+ export declare function renamedIdsIn(text: string): RenamedIdPlace[];
29
+ //# sourceMappingURL=renamed.d.ts.map
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Rule ids a release renamed, so that a rule's name says what is wrong. The old id keeps working:
3
+ * a config, an ignore comment, the rollout file and the baseline that still use one are read under
4
+ * the new id, with a warning that says what to rename. Ids only: core still knows no library.
5
+ */
6
+ const RULES = new Map(Object.entries({
7
+ // 1.2.0
8
+ "unions/default-hides-cases": "unions/non-exhaustive-switch",
9
+ "unions/tag-does-not-discriminate": "unions/ambiguous-discriminant",
10
+ "records/table-type-too-loose": "records/ambiguous-table",
11
+ "react/provider-value-changes-every-render": "react-context/provider-value-changes-every-render",
12
+ }));
13
+ /** The id a renamed rule has now, or undefined when `ruleId` was not renamed. */
14
+ export function renamedRule(ruleId) {
15
+ return RULES.get(ruleId);
16
+ }
17
+ /** What a config that names an old id is told: `a` is now `b`; rename it in `where`. */
18
+ export function renameNotice(before, now, where) {
19
+ return `\`${before}\` is now \`${now}\`; rename it in ${where}`;
20
+ }
21
+ /**
22
+ * What a config that names an old id is told when the rule moved to a pack it does not load
23
+ * (`react/a` is now `react-context/a`): the entry is ignored until the pack is added.
24
+ */
25
+ export function movedNotice(before, now, where) {
26
+ const pack = now.split("/")[0] ?? now;
27
+ return `\`${before}\` is now \`${now}\`, in the ${pack} pack, which the config does not load; add that pack, or remove the line in ${where}`;
28
+ }
29
+ /**
30
+ * Every old id a text names as a string (`"records/table-type-too-loose"`), in order: what a
31
+ * config file has to rename, and where. Only whole quoted ids count, so a longer id or a comment
32
+ * that mentions one in other words is left alone.
33
+ */
34
+ export function renamedIdsIn(text) {
35
+ const places = [];
36
+ const quoted = /(["'`])([^"'`\n]+)\1/g;
37
+ for (const match of text.matchAll(quoted)) {
38
+ const id = match[2];
39
+ const now = id === undefined ? undefined : RULES.get(id);
40
+ if (id === undefined || now === undefined)
41
+ continue;
42
+ const start = match.index + 1;
43
+ const line = text.slice(0, start).split("\n").length;
44
+ places.push({ before: id, now, start, end: start + id.length, line });
45
+ }
46
+ return places;
47
+ }
48
+ //# sourceMappingURL=renamed.js.map