@stateward/core 1.2.2 → 1.3.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 (67) hide show
  1. package/dist/analyses.d.ts +37 -0
  2. package/dist/analyses.js +57 -0
  3. package/dist/backend/program-record.d.ts +7 -0
  4. package/dist/backend/typescript6.d.ts +33 -32
  5. package/dist/backend/typescript6.js +1438 -139
  6. package/dist/baseline.d.ts +1 -1
  7. package/dist/baseline.js +14 -10
  8. package/dist/cache.d.ts +74 -4
  9. package/dist/cache.js +211 -37
  10. package/dist/checker.d.ts +6 -1
  11. package/dist/checker.js +10 -0
  12. package/dist/class-id.d.ts +34 -0
  13. package/dist/class-id.js +93 -0
  14. package/dist/code-text.d.ts +8 -0
  15. package/dist/code-text.js +66 -0
  16. package/dist/config-file.js +7 -5
  17. package/dist/config.d.ts +10 -2
  18. package/dist/config.js +490 -48
  19. package/dist/define.d.ts +8 -2
  20. package/dist/disk-cache.d.ts +2 -0
  21. package/dist/disk-cache.js +77 -11
  22. package/dist/engine.d.ts +33 -1
  23. package/dist/engine.js +344 -24
  24. package/dist/fact-lines.d.ts +31 -0
  25. package/dist/fact-lines.js +197 -0
  26. package/dist/facts-versions.d.ts +27 -0
  27. package/dist/facts-versions.js +99 -0
  28. package/dist/fixes.js +4 -1
  29. package/dist/ignores.d.ts +11 -0
  30. package/dist/ignores.js +74 -27
  31. package/dist/implementation.d.ts +0 -6
  32. package/dist/implementation.js +0 -17
  33. package/dist/index.d.ts +8 -9
  34. package/dist/index.js +10 -7
  35. package/dist/internal.d.ts +7 -4
  36. package/dist/internal.js +5 -3
  37. package/dist/lazy.d.ts +8 -1
  38. package/dist/lazy.js +27 -2
  39. package/dist/ledger.d.ts +2 -2
  40. package/dist/ledger.js +2 -2
  41. package/dist/off-by-default.d.ts +13 -0
  42. package/dist/off-by-default.js +15 -0
  43. package/dist/options.d.ts +21 -5
  44. package/dist/options.js +22 -7
  45. package/dist/package-facts.d.ts +211 -17
  46. package/dist/package-facts.js +520 -38
  47. package/dist/plan.d.ts +1 -1
  48. package/dist/plan.js +7 -2
  49. package/dist/release.d.ts +12 -21
  50. package/dist/release.js +26 -38
  51. package/dist/renamed.d.ts +22 -3
  52. package/dist/renamed.js +50 -16
  53. package/dist/rollout.js +7 -4
  54. package/dist/severity.d.ts +1 -1
  55. package/dist/severity.js +17 -3
  56. package/dist/test-runner.d.ts +18 -0
  57. package/dist/test-runner.js +483 -0
  58. package/dist/testing.d.ts +3 -3
  59. package/dist/testing.js +5 -5
  60. package/dist/timing.d.ts +8 -0
  61. package/dist/timing.js +35 -1
  62. package/dist/types.d.ts +692 -19
  63. package/dist/unread.d.ts +90 -0
  64. package/dist/unread.js +405 -0
  65. package/dist/vocabulary.d.ts +1 -1
  66. package/dist/vocabulary.js +1 -1
  67. package/package.json +4 -2
@@ -94,7 +94,7 @@ export declare function applyBaseline(baseline: Baseline | undefined, result: Ch
94
94
  * The baseline, or undefined when there is no file. A file that cannot be read or understood
95
95
  * throws `BaselineError`, never "no baseline" (C35).
96
96
  */
97
- export declare function readBaseline(config: Pick<Config, "configDir">): Baseline | undefined;
97
+ export declare function readBaseline(config: Pick<Config, "configDir" | "plugins">): Baseline | undefined;
98
98
  /**
99
99
  * Saves the baseline, sorted, in the current version (legacy entries kept, marked `"legacy"`).
100
100
  * Atomic: the text goes to a temp file beside the target, then one rename replaces it, so a crash
package/dist/baseline.js CHANGED
@@ -2,7 +2,8 @@ import { createHash } from "node:crypto";
2
2
  import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { limitFindings } from "./engine.js";
5
- import { renamedRule } from "./renamed.js";
5
+ import { IGNORE_RULE_ID } from "./ignores.js";
6
+ import { renamedRule, renamesOf } from "./renamed.js";
6
7
  export const BASELINE_FILE = "stateward.baseline.json";
7
8
  /**
8
9
  * Version 2 fingerprints a finding by its rule, file and code only, so rewording a message never
@@ -118,11 +119,13 @@ function fingerprinter(context) {
118
119
  };
119
120
  }
120
121
  /**
121
- * Only problems are accepted. A place not checked (an unknown) is not a problem to accept, and a
122
- * rule failure means stateward is broken there.
122
+ * Only problems of the rules are accepted. A place not checked (an unknown) is not a problem to
123
+ * accept, and a rule failure means stateward is broken there. A finding about an ignore comment
124
+ * (`stateward/ignore`) is not accepted either: the comment is the developer's own, and its fix is
125
+ * an edit of it, which `check --fix` makes.
123
126
  */
124
127
  function isAcceptable(finding) {
125
- return finding.kind === "problem";
128
+ return finding.kind === "problem" && finding.ruleId !== IGNORE_RULE_ID;
126
129
  }
127
130
  /** The baseline that accepts exactly the problems in `findings` (unknowns and failures are left out). */
128
131
  export function baselineOf(findings, context) {
@@ -148,7 +151,8 @@ export function baselineOf(findings, context) {
148
151
  * not run this time (off, or not yet on in the rollout) keep what they had.
149
152
  */
150
153
  export function mergeBaseline(existing, ran, built) {
151
- const kept = (existing?.entries ?? []).filter((entry) => !ran.has(entry.ruleId));
154
+ // Entries of ignore comments an older stateward wrote never match (`isAcceptable`): dropped.
155
+ const kept = (existing?.entries ?? []).filter((entry) => !ran.has(entry.ruleId) && entry.ruleId !== IGNORE_RULE_ID);
152
156
  return { entries: [...kept, ...built.entries].sort(compareEntries) };
153
157
  }
154
158
  /** How many findings a baseline accepts and in how many files. */
@@ -213,7 +217,7 @@ export function applyBaseline(baseline, result, context) {
213
217
  });
214
218
  return { fresh: capped(fresh), baselined, fixed, pruned: { entries } };
215
219
  }
216
- function parseEntry(value, file, version) {
220
+ function parseEntry(value, file, version, renames) {
217
221
  if (!isRecord(value)) {
218
222
  throw broken(file, "has a finding that is not an object", REPAIR);
219
223
  }
@@ -249,7 +253,7 @@ function parseEntry(value, file, version) {
249
253
  ]);
250
254
  // An entry of a renamed rule: its fingerprint hashed the old id, so it is matched by rule and
251
255
  // file, under the new id, until the next `baseline` writes it again.
252
- const renamed = renamedRule(ruleId);
256
+ const renamed = renamedRule(renames, ruleId);
253
257
  if (renamed !== undefined) {
254
258
  return {
255
259
  entry: { kind: "legacy", ruleId: renamed, file: entryFile, message, count },
@@ -279,7 +283,7 @@ function combineLegacy(entries) {
279
283
  }
280
284
  return [...combined.values()];
281
285
  }
282
- function parseBaseline(text, file) {
286
+ function parseBaseline(text, file, renames) {
283
287
  let parsed;
284
288
  try {
285
289
  parsed = JSON.parse(text);
@@ -302,7 +306,7 @@ function parseBaseline(text, file) {
302
306
  throw broken(file, '"findings" must be a list', REPAIR);
303
307
  const seen = new Set();
304
308
  const entries = findings.map((value) => {
305
- const { entry, key } = parseEntry(value, file, version);
309
+ const { entry, key } = parseEntry(value, file, version, renames);
306
310
  if (seen.has(key)) {
307
311
  throw broken(file, `lists the same ${entry.ruleId} finding in ${entry.file} twice`, 'remove one of the two and raise "count" on the other, or run `stateward baseline` to write the file again');
308
312
  }
@@ -326,7 +330,7 @@ export function readBaseline(config) {
326
330
  return undefined;
327
331
  throw new BaselineError(`${path.basename(file)} cannot be read (${reasonOf(error)}); fix the file or its permissions, then run again`, { cause: error });
328
332
  }
329
- return parseBaseline(text, file);
333
+ return parseBaseline(text, file, renamesOf(config.plugins));
330
334
  }
331
335
  function writtenEntry(entry) {
332
336
  const count = entry.count > 1 ? { count: entry.count } : {};
package/dist/cache.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { ProgramRecord } from "./backend/program-record.js";
2
- import type { Finding, FixVerdict, Json, ReadOutcome, Rule, Severity } from "./types.js";
2
+ import type { UnstatedPlace, Finding, FixVerdict, Json, PluginAnalysis, ReadOutcome, Rule, Severity } from "./types.js";
3
3
  /**
4
4
  * The results a checker keeps between runs, by content:
5
5
  *
@@ -7,8 +7,11 @@ import type { Finding, FixVerdict, Json, ReadOutcome, Rule, Severity } from "./t
7
7
  * its rule key (`ruleKey`): the findings the rule reported on that file, and a project rule's
8
8
  * summary; with the hash of each declaration (or whole file) of another file the rules read there. A
9
9
  * file whose fingerprint and reads are unchanged is not looked at again.
10
- * - per project rule, under its rule key: a hash of all its summaries, and the findings its check
11
- * produced from them. Equal summaries give equal findings (a project rule decides from its
10
+ * - per analysis a rule reads (`Plugin.analyses`), under its key (`analysisKey`): a hash of its
11
+ * summaries, and the fingerprint of what it solved from them; a project rule that reads it has
12
+ * that fingerprint in its inputs, so it is checked again only when the analysis changes.
13
+ * - per project rule, under its rule key: a hash of all its summaries (and of the analyses it
14
+ * reads), and the findings its check produced from them. Equal summaries give equal findings (a project rule decides from its
12
15
  * summaries and options alone), so an edit that leaves every summary as it was does not run
13
16
  * the check again (early cut-off).
14
17
  *
@@ -16,7 +19,7 @@ import type { Finding, FixVerdict, Json, ReadOutcome, Rule, Severity } from "./t
16
19
  * server save it to disk between runs as a `CacheSnapshot` (disk-cache.ts).
17
20
  */
18
21
  /** Bumped whenever what is stored, or how a key is computed, changes. */
19
- export declare const CACHE_FORMAT = 10;
22
+ export declare const CACHE_FORMAT = 17;
20
23
  /**
21
24
  * A project rule's summary of one file: the hash of its JSON text, and either that text or, once a
22
25
  * rule or a hover needed the value (a run whose summaries are all unchanged never does), the parsed
@@ -48,6 +51,8 @@ export type RuleResult = {
48
51
  summary?: CachedSummary;
49
52
  marks?: readonly RuleMark[];
50
53
  };
54
+ /** Frozen all the way down: a cached summary is shared between runs, so no rule may change it. */
55
+ export declare function deepFreeze(value: Json): Json;
51
56
  /**
52
57
  * A summary as JSON stores it (a Map becomes `{}`, `undefined` members disappear): a project rule
53
58
  * cannot depend on a value JSON drops, and equal texts are equal summaries.
@@ -76,6 +81,8 @@ export type ProjectEntry = {
76
81
  /** Hash of the rule's summaries, by file. */
77
82
  inputs: string;
78
83
  findings: readonly Finding[];
84
+ /** The places the rule judged leaving out unstated package calls (`ProjectContext.unstated`). */
85
+ unstated?: readonly UnstatedPlace[];
79
86
  /** The rule's marks on the references its file sides handed on (`ProjectContext.read`). */
80
87
  marks?: readonly RuleMark[];
81
88
  /**
@@ -84,9 +91,19 @@ export type ProjectEntry = {
84
91
  */
85
92
  summaries?: ReadonlyMap<string, Json>;
86
93
  };
94
+ /** An analysis's last result (`ResultCache.analyses`). */
95
+ export type AnalysisEntry = {
96
+ /** Hash of the analysis's summaries, by file. */
97
+ inputs: string;
98
+ /** Hash of the JSON text of what `solve` returned from them. */
99
+ fingerprint: string;
100
+ /** That value, kept in memory only (undefined when the entry came from disk). */
101
+ value?: Json;
102
+ };
87
103
  export type ResultCache = {
88
104
  files: Map<string, FileEntry>;
89
105
  projects: Map<string, ProjectEntry>;
106
+ analyses: Map<string, AnalysisEntry>;
90
107
  /** By tsconfig path: what its program was built from (backend/program-record.ts). */
91
108
  programs: Map<string, ProgramRecord>;
92
109
  /**
@@ -99,7 +116,24 @@ export type ResultCache = {
99
116
  }>>;
100
117
  /** Set when a run stored or dropped anything: only then is there something new to save. */
101
118
  changed: boolean;
119
+ /** This run's number: one more than the run that saved the cache read back, 1 for a new one. */
120
+ run: number;
121
+ /**
122
+ * The last run that used each key (`useKey`): a rule's key, an analysis's, a fix verdict's.
123
+ * Entries under a key no recent run used are dropped when the cache is saved (`pruneUnused`).
124
+ */
125
+ used: Map<string, number>;
102
126
  };
127
+ /** Entries no run among the last this many used are dropped when the cache is saved. */
128
+ export declare const KEEP_RUNS = 3;
129
+ /** Notes that this run uses the entries under `key`, so a save keeps them. */
130
+ export declare function useKey(cache: ResultCache, key: string): void;
131
+ /**
132
+ * Drops the entries under keys that none of the last `KEEP_RUNS` runs used: the results of a
133
+ * rule or an analysis under an earlier config or code, and verdicts of fixes no longer shown.
134
+ * Without it, a cache kept every key it ever held and grew past what can be written.
135
+ */
136
+ export declare function pruneUnused(cache: ResultCache): void;
103
137
  export declare function emptyCache(): ResultCache;
104
138
  export declare function sha1(text: string): string;
105
139
  /**
@@ -118,6 +152,15 @@ export declare function ruleKey(input: {
118
152
  /** The config's facts about packages: a rule that reads them decides differently when they change. */
119
153
  facts?: unknown;
120
154
  }): string;
155
+ /**
156
+ * What an analysis's results depend on besides the files: its id, its code, the facts about
157
+ * packages its `summarize` reads, and the cache format.
158
+ */
159
+ export declare function analysisKey(input: {
160
+ id: string;
161
+ analysis: PluginAnalysis;
162
+ facts: unknown;
163
+ }): string;
121
164
  /** The cache as plain JSON. Read back with `parseSnapshot`, which checks every field. */
122
165
  export type CacheSnapshot = {
123
166
  format: number;
@@ -136,13 +179,40 @@ export type CacheSnapshot = {
136
179
  projects: Record<string, {
137
180
  inputs: string;
138
181
  findings: readonly Finding[];
182
+ unstated?: readonly UnstatedPlace[];
139
183
  marks?: readonly RuleMark[];
140
184
  }>;
185
+ /** `ResultCache.analyses`, without the values. */
186
+ analyses?: Record<string, {
187
+ inputs: string;
188
+ fingerprint: string;
189
+ }>;
141
190
  programs: Record<string, ProgramRecord>;
142
191
  /** `ResultCache.verdicts`: `null` for a fix that compiles, else TypeScript's message. */
143
192
  verdicts?: Record<string, string | null>;
193
+ /** `ResultCache.run` of the run that saved it. */
194
+ run: number;
195
+ /** `ResultCache.used`. */
196
+ used: Record<string, number>;
144
197
  };
145
198
  export declare function toSnapshot(cache: ResultCache): CacheSnapshot;
199
+ /**
200
+ * A piece of the snapshot's JSON text, for a writer that never holds the whole text (a large
201
+ * project's is more than one string can hold). `entry`: one file's results, `"<file>":{…}`, which
202
+ * a writer may leave out (with the comma it places between entries) to keep the file under its
203
+ * size limit; `end`: the closing text, `END_TEXT`; `part`: the rest. Parts are written as given.
204
+ */
205
+ export type SnapshotChunk = {
206
+ readonly kind: "part" | "entry" | "end";
207
+ readonly text: string;
208
+ };
209
+ /**
210
+ * The snapshot's JSON text in pieces: `toSnapshot`'s value, with the files last so a writer that
211
+ * stops adding them still writes a whole snapshot.
212
+ */
213
+ export declare function snapshotChunks(cache: ResultCache): Generator<SnapshotChunk>;
214
+ /** The text that closes a snapshot's JSON: its files, then the snapshot. */
215
+ export declare const END_TEXT = "}}";
146
216
  export declare function isJson(value: unknown): value is Json;
147
217
  export declare function parseFinding(value: unknown): Finding | undefined;
148
218
  /**
package/dist/cache.js CHANGED
@@ -7,8 +7,11 @@ import { isQueryKind } from "./backend/program-record.js";
7
7
  * its rule key (`ruleKey`): the findings the rule reported on that file, and a project rule's
8
8
  * summary; with the hash of each declaration (or whole file) of another file the rules read there. A
9
9
  * file whose fingerprint and reads are unchanged is not looked at again.
10
- * - per project rule, under its rule key: a hash of all its summaries, and the findings its check
11
- * produced from them. Equal summaries give equal findings (a project rule decides from its
10
+ * - per analysis a rule reads (`Plugin.analyses`), under its key (`analysisKey`): a hash of its
11
+ * summaries, and the fingerprint of what it solved from them; a project rule that reads it has
12
+ * that fingerprint in its inputs, so it is checked again only when the analysis changes.
13
+ * - per project rule, under its rule key: a hash of all its summaries (and of the analyses it
14
+ * reads), and the findings its check produced from them. Equal summaries give equal findings (a project rule decides from its
12
15
  * summaries and options alone), so an edit that leaves every summary as it was does not run
13
16
  * the check again (early cut-off).
14
17
  *
@@ -16,9 +19,9 @@ import { isQueryKind } from "./backend/program-record.js";
16
19
  * server save it to disk between runs as a `CacheSnapshot` (disk-cache.ts).
17
20
  */
18
21
  /** Bumped whenever what is stored, or how a key is computed, changes. */
19
- export const CACHE_FORMAT = 10;
22
+ export const CACHE_FORMAT = 17;
20
23
  /** Frozen all the way down: a cached summary is shared between runs, so no rule may change it. */
21
- function deepFreeze(value) {
24
+ export function deepFreeze(value) {
22
25
  if (typeof value === "object" && value !== null) {
23
26
  for (const member of Object.values(value))
24
27
  deepFreeze(member);
@@ -56,13 +59,47 @@ export function summaryText(summary) {
56
59
  const { form } = summary;
57
60
  return form.kind === "text" ? form.text : JSON.stringify(form.value);
58
61
  }
62
+ /** Entries no run among the last this many used are dropped when the cache is saved. */
63
+ export const KEEP_RUNS = 3;
64
+ /** Notes that this run uses the entries under `key`, so a save keeps them. */
65
+ export function useKey(cache, key) {
66
+ if (cache.used.get(key) !== cache.run)
67
+ cache.used.set(key, cache.run);
68
+ }
69
+ /**
70
+ * Drops the entries under keys that none of the last `KEEP_RUNS` runs used: the results of a
71
+ * rule or an analysis under an earlier config or code, and verdicts of fixes no longer shown.
72
+ * Without it, a cache kept every key it ever held and grew past what can be written.
73
+ */
74
+ export function pruneUnused(cache) {
75
+ const oldest = cache.run - KEEP_RUNS + 1;
76
+ const stale = new Set([...cache.used].filter(([, last]) => last < oldest).map(([key]) => key));
77
+ if (stale.size === 0)
78
+ return;
79
+ for (const key of stale)
80
+ cache.used.delete(key);
81
+ // A key no run stamps (a file's own entries, such as its ignore comments) is kept with its file.
82
+ for (const entry of cache.files.values()) {
83
+ const rules = [...entry.rules].filter(([key]) => !stale.has(key));
84
+ if (rules.length !== entry.rules.size)
85
+ entry.rules = new Map(rules);
86
+ }
87
+ for (const map of [cache.projects, cache.analyses, cache.verdicts]) {
88
+ for (const key of [...map.keys()])
89
+ if (stale.has(key))
90
+ map.delete(key);
91
+ }
92
+ }
59
93
  export function emptyCache() {
60
94
  return {
61
95
  files: new Map(),
62
96
  projects: new Map(),
97
+ analyses: new Map(),
63
98
  programs: new Map(),
64
99
  verdicts: new Map(),
65
100
  changed: false,
101
+ run: 1,
102
+ used: new Map(),
66
103
  };
67
104
  }
68
105
  export function sha1(text) {
@@ -92,43 +129,93 @@ export function ruleKey(input) {
92
129
  code,
93
130
  ]));
94
131
  }
95
- export function toSnapshot(cache) {
96
- const files = {};
97
- for (const [file, entry] of [...cache.files].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
98
- const rules = {};
99
- for (const [key, result] of entry.rules) {
100
- rules[key] = {
101
- findings: result.findings,
102
- ...(result.summary === undefined
103
- ? {}
104
- : { summary: summaryText(result.summary), hash: result.summary.hash }),
105
- ...(result.marks === undefined ? {} : { marks: result.marks }),
106
- };
107
- }
108
- files[file] = {
109
- fingerprint: entry.fingerprint,
110
- rules,
111
- reads: Object.fromEntries([...entry.reads].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),
132
+ /**
133
+ * What an analysis's results depend on besides the files: its id, its code, the facts about
134
+ * packages its `summarize` reads, and the cache format.
135
+ */
136
+ export function analysisKey(input) {
137
+ return sha1(JSON.stringify([
138
+ CACHE_FORMAT,
139
+ "analysis",
140
+ input.id,
141
+ input.facts,
142
+ [input.analysis.summarize.toString(), input.analysis.solve.toString()],
143
+ ]));
144
+ }
145
+ function byKey(entries) {
146
+ return [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
147
+ }
148
+ function fileSnapshot(entry) {
149
+ const rules = {};
150
+ for (const [key, result] of entry.rules) {
151
+ rules[key] = {
152
+ findings: result.findings,
153
+ ...(result.summary === undefined
154
+ ? {}
155
+ : { summary: summaryText(result.summary), hash: result.summary.hash }),
156
+ ...(result.marks === undefined ? {} : { marks: result.marks }),
112
157
  };
113
158
  }
114
- const projects = {};
115
- for (const [key, entry] of cache.projects) {
116
- projects[key] = {
117
- inputs: entry.inputs,
118
- findings: entry.findings,
119
- ...(entry.marks === undefined ? {} : { marks: entry.marks }),
120
- };
159
+ return { fingerprint: entry.fingerprint, rules, reads: Object.fromEntries(byKey(entry.reads)) };
160
+ }
161
+ function projectSnapshot(entry) {
162
+ return {
163
+ inputs: entry.inputs,
164
+ findings: entry.findings,
165
+ ...(entry.unstated === undefined ? {} : { unstated: entry.unstated }),
166
+ ...(entry.marks === undefined ? {} : { marks: entry.marks }),
167
+ };
168
+ }
169
+ /** Everything but the files and the projects, which can be large and are written one by one. */
170
+ function smallParts(cache) {
171
+ const analyses = {};
172
+ for (const [key, entry] of cache.analyses) {
173
+ analyses[key] = { inputs: entry.inputs, fingerprint: entry.fingerprint };
121
174
  }
122
175
  return {
123
176
  format: CACHE_FORMAT,
124
- files,
125
- projects,
177
+ run: cache.run,
178
+ used: Object.fromEntries(byKey(cache.used)),
179
+ analyses,
126
180
  programs: Object.fromEntries([...cache.programs]),
127
- verdicts: Object.fromEntries([...cache.verdicts]
128
- .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
129
- .map(([key, verdict]) => [key, verdict.kind === "compiles" ? null : verdict.error])),
181
+ verdicts: Object.fromEntries(byKey(cache.verdicts).map(([key, verdict]) => [
182
+ key,
183
+ verdict.kind === "compiles" ? null : verdict.error,
184
+ ])),
130
185
  };
131
186
  }
187
+ export function toSnapshot(cache) {
188
+ const files = {};
189
+ for (const [file, entry] of byKey(cache.files))
190
+ files[file] = fileSnapshot(entry);
191
+ const projects = {};
192
+ for (const [key, entry] of cache.projects)
193
+ projects[key] = projectSnapshot(entry);
194
+ return { ...smallParts(cache), files, projects };
195
+ }
196
+ /**
197
+ * The snapshot's JSON text in pieces: `toSnapshot`'s value, with the files last so a writer that
198
+ * stops adding them still writes a whole snapshot.
199
+ */
200
+ export function* snapshotChunks(cache) {
201
+ const small = JSON.stringify(smallParts(cache));
202
+ yield { kind: "part", text: `${small.slice(0, -1)},"projects":{` };
203
+ let first = true;
204
+ for (const [key, entry] of byKey(cache.projects)) {
205
+ yield {
206
+ kind: "part",
207
+ text: `${first ? "" : ","}${JSON.stringify(key)}:${JSON.stringify(projectSnapshot(entry))}`,
208
+ };
209
+ first = false;
210
+ }
211
+ yield { kind: "part", text: '},"files":{' };
212
+ for (const [file, entry] of byKey(cache.files)) {
213
+ yield { kind: "entry", text: `${JSON.stringify(file)}:${JSON.stringify(fileSnapshot(entry))}` };
214
+ }
215
+ yield { kind: "end", text: END_TEXT };
216
+ }
217
+ /** The text that closes a snapshot's JSON: its files, then the snapshot. */
218
+ export const END_TEXT = "}}";
132
219
  function isFields(value) {
133
220
  return typeof value === "object" && value !== null && !Array.isArray(value);
134
221
  }
@@ -221,9 +308,18 @@ function parseProgramRecord(value) {
221
308
  fingerprints[file] = fingerprint;
222
309
  }
223
310
  const reads = stringRecord(value.reads);
224
- if (queries === undefined || files === undefined || reads === undefined)
311
+ const imports = parseList(value.imports, (name) => (typeof name === "string" ? name : undefined));
312
+ if (queries === undefined ||
313
+ files === undefined ||
314
+ reads === undefined ||
315
+ imports === undefined) {
225
316
  return undefined;
226
- return { inputs: value.inputs, queries, files, fingerprints, reads };
317
+ }
318
+ // A record of a build before facts were resolved through the program has none: they are asked again.
319
+ const facts = value.facts === undefined ? {} : stringRecord(value.facts);
320
+ if (facts === undefined)
321
+ return undefined;
322
+ return { inputs: value.inputs, queries, files, fingerprints, reads, imports, facts };
227
323
  }
228
324
  /** A JSON object of strings, as a record; undefined when anything else. */
229
325
  function stringRecord(value) {
@@ -276,6 +372,49 @@ function parseStrings(value) {
276
372
  }
277
373
  return found;
278
374
  }
375
+ const SIDES = ["throws", "rejects"];
376
+ /** A `facts` line a finding needs (`FactNeed`); undefined when it has another shape. */
377
+ function parseNeed(value) {
378
+ if (!isFields(value))
379
+ return undefined;
380
+ const { module, name, version } = value;
381
+ const states = parseStrings(value.states);
382
+ if (typeof module !== "string" || typeof name !== "string" || states === undefined) {
383
+ return undefined;
384
+ }
385
+ if (version !== undefined && typeof version !== "string")
386
+ return undefined;
387
+ const sides = SIDES.filter((side) => states.includes(side));
388
+ if (sides.length !== states.length)
389
+ return undefined;
390
+ return { module, name, ...(version === undefined ? {} : { version }), states: sides };
391
+ }
392
+ /** A call no `facts` key can name (`UnnamedFact`); undefined when it has another shape. */
393
+ function parseUnnamed(value) {
394
+ if (!isFields(value))
395
+ return undefined;
396
+ const { name, reason } = value;
397
+ return typeof name === "string" && typeof reason === "string" ? { name, reason } : undefined;
398
+ }
399
+ /** A place judged leaving out unstated package calls (`UnstatedPlace`); undefined for another shape. */
400
+ function parseUnstated(value) {
401
+ if (!isFields(value) || typeof value.ruleId !== "string")
402
+ return undefined;
403
+ const location = parseLocation(value.location);
404
+ const needs = value.needs === undefined ? undefined : parseList(value.needs, parseNeed);
405
+ const unnamed = value.unnamed === undefined ? undefined : parseList(value.unnamed, parseUnnamed);
406
+ if (location === undefined ||
407
+ (value.needs !== undefined && needs === undefined) ||
408
+ (value.unnamed !== undefined && unnamed === undefined)) {
409
+ return undefined;
410
+ }
411
+ return {
412
+ ruleId: value.ruleId,
413
+ location,
414
+ ...(needs === undefined ? {} : { needs }),
415
+ ...(unnamed === undefined ? {} : { unnamed }),
416
+ };
417
+ }
279
418
  export function parseFinding(value) {
280
419
  if (!isFields(value))
281
420
  return undefined;
@@ -293,6 +432,12 @@ export function parseFinding(value) {
293
432
  if (value.guarantees !== undefined && guarantees === undefined)
294
433
  return undefined;
295
434
  if (kind === "unknown") {
435
+ const needs = value.needs === undefined ? undefined : parseList(value.needs, parseNeed);
436
+ if (value.needs !== undefined && needs === undefined)
437
+ return undefined;
438
+ const unnamed = value.unnamed === undefined ? undefined : parseList(value.unnamed, parseUnnamed);
439
+ if (value.unnamed !== undefined && unnamed === undefined)
440
+ return undefined;
296
441
  return {
297
442
  kind,
298
443
  ruleId,
@@ -301,6 +446,8 @@ export function parseFinding(value) {
301
446
  location,
302
447
  ...(value.listed === true ? { listed: true } : {}),
303
448
  ...(guarantees === undefined ? {} : { guarantees }),
449
+ ...(needs === undefined ? {} : { needs }),
450
+ ...(unnamed === undefined ? {} : { unnamed }),
304
451
  };
305
452
  }
306
453
  if (kind !== "problem" || !isSeverity(value.severity))
@@ -338,9 +485,28 @@ export function parseSnapshot(value) {
338
485
  const cache = emptyCache();
339
486
  if (!isFields(value) || value.format !== CACHE_FORMAT)
340
487
  return cache;
341
- const { files, projects, programs, verdicts } = value;
488
+ const { files, projects, programs, verdicts, analyses, run, used } = value;
342
489
  if (!isFields(files) || !isFields(projects) || !isFields(programs))
343
490
  return cache;
491
+ if (typeof run !== "number" || !Number.isSafeInteger(run) || !isFields(used))
492
+ return cache;
493
+ for (const [key, last] of Object.entries(used)) {
494
+ if (typeof last !== "number")
495
+ return emptyCache();
496
+ cache.used.set(key, last);
497
+ }
498
+ // A new run: what it uses is stamped with this number, what it does not keeps the older one.
499
+ cache.run = run + 1;
500
+ if (analyses !== undefined && !isFields(analyses))
501
+ return cache;
502
+ for (const [key, entry] of Object.entries(analyses ?? {})) {
503
+ if (!isFields(entry))
504
+ return emptyCache();
505
+ const { inputs, fingerprint } = entry;
506
+ if (typeof inputs !== "string" || typeof fingerprint !== "string")
507
+ return emptyCache();
508
+ cache.analyses.set(key, { inputs, fingerprint });
509
+ }
344
510
  if (verdicts !== undefined && !isFields(verdicts))
345
511
  return cache;
346
512
  for (const [key, verdict] of Object.entries(verdicts ?? {})) {
@@ -396,10 +562,18 @@ export function parseSnapshot(value) {
396
562
  return emptyCache();
397
563
  const findings = parseList(entry.findings, parseFinding);
398
564
  const marks = parseMarks(entry.marks);
565
+ const unstated = entry.unstated === undefined ? undefined : parseList(entry.unstated, parseUnstated);
399
566
  if (findings === undefined || marks === undefined)
400
567
  return emptyCache();
568
+ if (entry.unstated !== undefined && unstated === undefined)
569
+ return emptyCache();
401
570
  // The summaries are rebuilt from the file entries when the rule runs.
402
- cache.projects.set(key, { inputs: entry.inputs, findings, ...marks });
571
+ cache.projects.set(key, {
572
+ inputs: entry.inputs,
573
+ findings,
574
+ ...(unstated === undefined ? {} : { unstated }),
575
+ ...marks,
576
+ });
403
577
  }
404
578
  return cache;
405
579
  }
package/dist/checker.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { ResultCache } from "./cache.js";
2
2
  import type { TimingRecorder } from "./timing.js";
3
3
  import type { CheckProgress } from "./engine.js";
4
- import type { CheckResult, Config, EditorAction, EditorHint, Finding, FixForm, FixReview, FixSetReview, LibraryUse, Location, StatedGuarantee, RuleSelection, TokenType } from "./types.js";
4
+ import type { CheckResult, Config, EditorAction, EditorHint, Finding, FixForm, FixReview, FixSetReview, LibraryUse, Location, StatedGuarantee, RuleSelection, TokenType, ReportOutput, ReportPlace } from "./types.js";
5
5
  export type CheckInput = {
6
6
  config: Config;
7
7
  cwd: string;
@@ -107,6 +107,11 @@ export type Checker = {
107
107
  * before a check. Pair them with that check's findings with `proveGuarantees`.
108
108
  */
109
109
  guarantees(): readonly StatedGuarantee[];
110
+ /**
111
+ * Runs the report `report` of `plugin` (`Plugin.reports`) on the summaries of the last full
112
+ * check; undefined when that plugin has no such report.
113
+ */
114
+ report(plugin: string, report: string, place: (location: Location) => ReportPlace): ReportOutput | undefined;
110
115
  /**
111
116
  * Tries each fix of `findings` on a copy of the code of the last run (fixes.ts) and returns the
112
117
  * findings in the same order, each with only the fixes that compile. Verdicts are kept in the
package/dist/checker.js CHANGED
@@ -167,6 +167,16 @@ export function createChecker({ config, cwd, rules = { kind: "configured" }, cac
167
167
  const known = [...listed, ...unlistedGuarantees(stated, listed)];
168
168
  return [...known, ...ledgerGuarantees(ledgerRefs, known, tagRules)];
169
169
  },
170
+ report(pluginName, reportName, place) {
171
+ const plugin = config.plugins.find((one) => one.name === pluginName);
172
+ const reports = plugin?.reports;
173
+ if (reports === undefined || !Object.hasOwn(reports, reportName))
174
+ return undefined;
175
+ return reports[reportName]?.run({
176
+ projectSummaries: (ruleId) => summaries.get(ruleId)?.(),
177
+ place,
178
+ });
179
+ },
170
180
  reviewFixes(findings) {
171
181
  const units = (lastUnits ??= backend.open(new Map()));
172
182
  return reviewFixes(findings, units, cache === false ? localVerdicts : cache);
@@ -0,0 +1,34 @@
1
+ /**
2
+ * How a class is named across packs: by the language, never by a library. A class of the project
3
+ * is its declaration's symbol id; a class of the platform (TypeScript's lib, a global in a
4
+ * declaration file) is `builtin:<Name>`; a package's class is `package:<name>#<Class>`, the same
5
+ * from its types, its source and the config. The errors pack's `errors/throws` names classes so,
6
+ * and a pack that reads it names the classes in its own code with `classIdOf`.
7
+ */
8
+ import ts from "typescript";
9
+ import type { TypeQueries } from "./types.js";
10
+ /** A declaration of the platform: TypeScript's lib, or a global in a declaration file. */
11
+ export declare function isPlatformDeclaration(node: ts.Node, file: string): boolean;
12
+ /**
13
+ * The package a file outside the project belongs to: by its node_modules folder, or, for a
14
+ * package linked from elsewhere (a workspace package, whose real path has no node_modules), by
15
+ * the name in its package.json.
16
+ */
17
+ export declare function packageNameOf(types: Pick<TypeQueries, "packageOf">, file: string): string | undefined;
18
+ /**
19
+ * The package a declaration outside the project belongs to: the `declare module "x"` it sits in,
20
+ * by the name it is written with, else its file's package (`packageNameOf`); undefined when
21
+ * neither names one.
22
+ */
23
+ export declare function declaredPackageOf(types: Pick<TypeQueries, "packageOf">, declaration: {
24
+ readonly file: string;
25
+ readonly node: ts.Node;
26
+ }): string | undefined;
27
+ /**
28
+ * The id of the class a name refers to (`X` in `throw new X()`, `ns.X`, `@Catch(X)`):
29
+ * `builtin:<Name>` for a class of the platform, `package:<name>#<Class>` for a package's class,
30
+ * the symbol id (`SymbolRef.id`) for a class of the project. Undefined when the name resolves to
31
+ * nothing, or to a declaration outside the project whose package is not known.
32
+ */
33
+ export declare function classIdOf(types: TypeQueries, node: ts.Node): string | undefined;
34
+ //# sourceMappingURL=class-id.d.ts.map