@stateward/core 1.2.1 → 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 (75) 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 +35 -32
  5. package/dist/backend/typescript6.js +3804 -163
  6. package/dist/baseline.d.ts +1 -1
  7. package/dist/baseline.js +14 -10
  8. package/dist/cache.d.ts +89 -5
  9. package/dist/cache.js +271 -40
  10. package/dist/checker.d.ts +11 -1
  11. package/dist/checker.js +32 -2
  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 +541 -49
  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 +51 -1
  23. package/dist/engine.js +517 -42
  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 +9 -4
  29. package/dist/guarantees.d.ts +63 -11
  30. package/dist/guarantees.js +151 -21
  31. package/dist/ignores.d.ts +11 -0
  32. package/dist/ignores.js +74 -27
  33. package/dist/implementation.d.ts +0 -6
  34. package/dist/implementation.js +0 -17
  35. package/dist/index.d.ts +10 -9
  36. package/dist/index.js +14 -7
  37. package/dist/internal.d.ts +9 -5
  38. package/dist/internal.js +6 -3
  39. package/dist/lazy.d.ts +8 -1
  40. package/dist/lazy.js +27 -2
  41. package/dist/ledger.d.ts +77 -0
  42. package/dist/ledger.js +423 -0
  43. package/dist/off-by-default.d.ts +13 -0
  44. package/dist/off-by-default.js +15 -0
  45. package/dist/options.d.ts +21 -5
  46. package/dist/options.js +22 -7
  47. package/dist/package-facts.d.ts +211 -17
  48. package/dist/package-facts.js +520 -38
  49. package/dist/plan.d.ts +1 -1
  50. package/dist/plan.js +7 -2
  51. package/dist/release.d.ts +12 -21
  52. package/dist/release.js +28 -38
  53. package/dist/renamed.d.ts +22 -3
  54. package/dist/renamed.js +50 -16
  55. package/dist/rollout.js +7 -4
  56. package/dist/safe-calls.d.ts +26 -0
  57. package/dist/safe-calls.js +345 -0
  58. package/dist/severity.d.ts +1 -1
  59. package/dist/severity.js +17 -3
  60. package/dist/stated.d.ts +37 -0
  61. package/dist/stated.js +123 -0
  62. package/dist/test-runner.d.ts +18 -0
  63. package/dist/test-runner.js +483 -0
  64. package/dist/testing-tsc.d.ts +16 -0
  65. package/dist/testing-tsc.js +86 -0
  66. package/dist/testing.d.ts +5 -4
  67. package/dist/testing.js +6 -6
  68. package/dist/timing.d.ts +15 -0
  69. package/dist/timing.js +41 -2
  70. package/dist/types.d.ts +1068 -16
  71. package/dist/unread.d.ts +90 -0
  72. package/dist/unread.js +405 -0
  73. package/dist/vocabulary.d.ts +1 -1
  74. package/dist/vocabulary.js +1 -1
  75. 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, 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, Rule, Severity } from "./types.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,7 +19,7 @@ import type { Finding, FixVerdict, Json, Rule, Severity } from "./types.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 declare const CACHE_FORMAT = 7;
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
@@ -33,11 +36,23 @@ export type CachedSummary = {
33
36
  readonly value: Json;
34
37
  };
35
38
  };
36
- /** What one rule produced on one file. */
39
+ /** A rule's mark on a reference of the ledger (`FileContext.read`), as its results keep it. */
40
+ export type RuleMark = {
41
+ readonly ref: string;
42
+ readonly trait: string;
43
+ readonly outcome: ReadOutcome;
44
+ };
45
+ /**
46
+ * What one rule produced on one file: its findings, its summary, and its marks on the references of
47
+ * the ledger (absent when it made none).
48
+ */
37
49
  export type RuleResult = {
38
50
  findings: readonly Finding[];
39
51
  summary?: CachedSummary;
52
+ marks?: readonly RuleMark[];
40
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;
41
56
  /**
42
57
  * A summary as JSON stores it (a Map becomes `{}`, `undefined` members disappear): a project rule
43
58
  * cannot depend on a value JSON drops, and equal texts are equal summaries.
@@ -66,15 +81,29 @@ export type ProjectEntry = {
66
81
  /** Hash of the rule's summaries, by file. */
67
82
  inputs: string;
68
83
  findings: readonly Finding[];
84
+ /** The places the rule judged leaving out unstated package calls (`ProjectContext.unstated`). */
85
+ unstated?: readonly UnstatedPlace[];
86
+ /** The rule's marks on the references its file sides handed on (`ProjectContext.read`). */
87
+ marks?: readonly RuleMark[];
69
88
  /**
70
89
  * The summaries as the rule received them, handed to hovers (the same object while unchanged);
71
90
  * undefined until asked for when the entry came from disk.
72
91
  */
73
92
  summaries?: ReadonlyMap<string, Json>;
74
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
+ };
75
103
  export type ResultCache = {
76
104
  files: Map<string, FileEntry>;
77
105
  projects: Map<string, ProjectEntry>;
106
+ analyses: Map<string, AnalysisEntry>;
78
107
  /** By tsconfig path: what its program was built from (backend/program-record.ts). */
79
108
  programs: Map<string, ProgramRecord>;
80
109
  /**
@@ -87,7 +116,24 @@ export type ResultCache = {
87
116
  }>>;
88
117
  /** Set when a run stored or dropped anything: only then is there something new to save. */
89
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>;
90
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;
91
137
  export declare function emptyCache(): ResultCache;
92
138
  export declare function sha1(text: string): string;
93
139
  /**
@@ -106,6 +152,15 @@ export declare function ruleKey(input: {
106
152
  /** The config's facts about packages: a rule that reads them decides differently when they change. */
107
153
  facts?: unknown;
108
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;
109
164
  /** The cache as plain JSON. Read back with `parseSnapshot`, which checks every field. */
110
165
  export type CacheSnapshot = {
111
166
  format: number;
@@ -116,6 +171,7 @@ export type CacheSnapshot = {
116
171
  findings: readonly Finding[];
117
172
  summary?: string;
118
173
  hash?: string;
174
+ marks?: readonly RuleMark[];
119
175
  }>;
120
176
  /** `FileEntry.reads`. */
121
177
  reads: Record<string, string>;
@@ -123,12 +179,40 @@ export type CacheSnapshot = {
123
179
  projects: Record<string, {
124
180
  inputs: string;
125
181
  findings: readonly Finding[];
182
+ unstated?: readonly UnstatedPlace[];
183
+ marks?: readonly RuleMark[];
184
+ }>;
185
+ /** `ResultCache.analyses`, without the values. */
186
+ analyses?: Record<string, {
187
+ inputs: string;
188
+ fingerprint: string;
126
189
  }>;
127
190
  programs: Record<string, ProgramRecord>;
128
191
  /** `ResultCache.verdicts`: `null` for a fix that compiles, else TypeScript's message. */
129
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>;
130
197
  };
131
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 = "}}";
132
216
  export declare function isJson(value: unknown): value is Json;
133
217
  export declare function parseFinding(value: unknown): Finding | undefined;
134
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 = 7;
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,40 +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
- result.summary === undefined
102
- ? { findings: result.findings }
103
- : {
104
- findings: result.findings,
105
- summary: summaryText(result.summary),
106
- hash: result.summary.hash,
107
- };
108
- }
109
- files[file] = {
110
- fingerprint: entry.fingerprint,
111
- rules,
112
- 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 }),
113
157
  };
114
158
  }
115
- const projects = {};
116
- for (const [key, entry] of cache.projects) {
117
- projects[key] = { inputs: entry.inputs, findings: entry.findings };
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 };
118
174
  }
119
175
  return {
120
176
  format: CACHE_FORMAT,
121
- files,
122
- projects,
177
+ run: cache.run,
178
+ used: Object.fromEntries(byKey(cache.used)),
179
+ analyses,
123
180
  programs: Object.fromEntries([...cache.programs]),
124
- verdicts: Object.fromEntries([...cache.verdicts]
125
- .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
126
- .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
+ ])),
127
185
  };
128
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 = "}}";
129
219
  function isFields(value) {
130
220
  return typeof value === "object" && value !== null && !Array.isArray(value);
131
221
  }
@@ -218,9 +308,18 @@ function parseProgramRecord(value) {
218
308
  fingerprints[file] = fingerprint;
219
309
  }
220
310
  const reads = stringRecord(value.reads);
221
- 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) {
222
316
  return undefined;
223
- 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 };
224
323
  }
225
324
  /** A JSON object of strings, as a record; undefined when anything else. */
226
325
  function stringRecord(value) {
@@ -234,6 +333,88 @@ function stringRecord(value) {
234
333
  }
235
334
  return record;
236
335
  }
336
+ function parseOutcome(value) {
337
+ if (!isFields(value))
338
+ return undefined;
339
+ const { kind } = value;
340
+ if (kind === "decided" || kind === "irrelevant")
341
+ return { kind };
342
+ if (kind === "handed-on" && typeof value.to === "string")
343
+ return { kind, to: value.to };
344
+ if (kind === "unchecked" && typeof value.reason === "string") {
345
+ return { kind, reason: value.reason };
346
+ }
347
+ return undefined;
348
+ }
349
+ function parseMark(value) {
350
+ if (!isFields(value) || typeof value.ref !== "string" || typeof value.trait !== "string") {
351
+ return undefined;
352
+ }
353
+ const outcome = parseOutcome(value.outcome);
354
+ return outcome && { ref: value.ref, trait: value.trait, outcome };
355
+ }
356
+ /** A result's marks: absent stays absent; anything that is not a list of marks is undefined. */
357
+ function parseMarks(value) {
358
+ if (value === undefined)
359
+ return {};
360
+ const marks = parseList(value, parseMark);
361
+ return marks && { marks };
362
+ }
363
+ /** A JSON list of strings; undefined when it is anything else. */
364
+ function parseStrings(value) {
365
+ if (!Array.isArray(value))
366
+ return undefined;
367
+ const found = [];
368
+ for (const item of value) {
369
+ if (typeof item !== "string")
370
+ return undefined;
371
+ found.push(item);
372
+ }
373
+ return found;
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
+ }
237
418
  export function parseFinding(value) {
238
419
  if (!isFields(value))
239
420
  return undefined;
@@ -247,10 +428,27 @@ export function parseFinding(value) {
247
428
  }
248
429
  if (kind === "failure")
249
430
  return { kind, ruleId, message, hint, location };
431
+ const guarantees = parseStrings(value.guarantees);
432
+ if (value.guarantees !== undefined && guarantees === undefined)
433
+ return undefined;
250
434
  if (kind === "unknown") {
251
- return value.listed === true
252
- ? { kind, ruleId, message, hint, location, listed: true }
253
- : { kind, ruleId, message, hint, location };
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;
441
+ return {
442
+ kind,
443
+ ruleId,
444
+ message,
445
+ hint,
446
+ location,
447
+ ...(value.listed === true ? { listed: true } : {}),
448
+ ...(guarantees === undefined ? {} : { guarantees }),
449
+ ...(needs === undefined ? {} : { needs }),
450
+ ...(unnamed === undefined ? {} : { unnamed }),
451
+ };
254
452
  }
255
453
  if (kind !== "problem" || !isSeverity(value.severity))
256
454
  return undefined;
@@ -275,6 +473,8 @@ export function parseFinding(value) {
275
473
  fixes,
276
474
  ...(findingKind === undefined ? {} : { findingKind }),
277
475
  ...(about === undefined ? {} : { about }),
476
+ ...(value.against === true ? { against: true } : {}),
477
+ ...(guarantees === undefined ? {} : { guarantees }),
278
478
  };
279
479
  }
280
480
  /**
@@ -285,9 +485,28 @@ export function parseSnapshot(value) {
285
485
  const cache = emptyCache();
286
486
  if (!isFields(value) || value.format !== CACHE_FORMAT)
287
487
  return cache;
288
- const { files, projects, programs, verdicts } = value;
488
+ const { files, projects, programs, verdicts, analyses, run, used } = value;
289
489
  if (!isFields(files) || !isFields(projects) || !isFields(programs))
290
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
+ }
291
510
  if (verdicts !== undefined && !isFields(verdicts))
292
511
  return cache;
293
512
  for (const [key, verdict] of Object.entries(verdicts ?? {})) {
@@ -319,11 +538,14 @@ export function parseSnapshot(value) {
319
538
  if (findings === undefined)
320
539
  return emptyCache();
321
540
  const { summary, hash } = result;
541
+ const marks = parseMarks(result.marks);
542
+ if (marks === undefined)
543
+ return emptyCache();
322
544
  if (summary === undefined && hash === undefined) {
323
- rules.set(key, { findings });
545
+ rules.set(key, { findings, ...marks });
324
546
  }
325
547
  else if (typeof summary === "string" && typeof hash === "string") {
326
- rules.set(key, { findings, summary: summaryFromText(summary, hash) });
548
+ rules.set(key, { findings, summary: summaryFromText(summary, hash), ...marks });
327
549
  }
328
550
  else {
329
551
  return emptyCache();
@@ -339,10 +561,19 @@ export function parseSnapshot(value) {
339
561
  if (!isFields(entry) || typeof entry.inputs !== "string")
340
562
  return emptyCache();
341
563
  const findings = parseList(entry.findings, parseFinding);
342
- if (findings === undefined)
564
+ const marks = parseMarks(entry.marks);
565
+ const unstated = entry.unstated === undefined ? undefined : parseList(entry.unstated, parseUnstated);
566
+ if (findings === undefined || marks === undefined)
567
+ return emptyCache();
568
+ if (entry.unstated !== undefined && unstated === undefined)
343
569
  return emptyCache();
344
570
  // The summaries are rebuilt from the file entries when the rule runs.
345
- cache.projects.set(key, { inputs: entry.inputs, findings });
571
+ cache.projects.set(key, {
572
+ inputs: entry.inputs,
573
+ findings,
574
+ ...(unstated === undefined ? {} : { unstated }),
575
+ ...marks,
576
+ });
346
577
  }
347
578
  return cache;
348
579
  }