@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
package/dist/lazy.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { isDeepStrictEqual } from "node:util";
2
+ import { readTarget, readsProblem, unpublishedRead } from "./analyses.js";
2
3
  import { ruleIsOn } from "./severity.js";
3
4
  /** Wraps a dynamic `import()`. A failed import is not kept: the next `load` tries again. */
4
5
  export function moduleLoader(importModule) {
@@ -55,6 +56,16 @@ export class RuleDeclarationError extends Error {
55
56
  this.name = "RuleDeclarationError";
56
57
  }
57
58
  }
59
+ /**
60
+ * A rule's `reads` is malformed, or names an analysis that the publisher in the config does not
61
+ * publish: what the config check says of a rule given directly, found once a lazy rule's code loads.
62
+ */
63
+ export class RuleReadsError extends Error {
64
+ constructor(message) {
65
+ super(message);
66
+ this.name = "RuleReadsError";
67
+ }
68
+ }
58
69
  /** A rule's module could not be imported (a broken install). */
59
70
  export class RuleLoadError extends Error {
60
71
  constructor(ruleId, reason) {
@@ -78,6 +89,10 @@ function verify(ruleId, declared, rule) {
78
89
  const differs = keys.filter((key) => !isDeepStrictEqual(before.get(key), after.get(key)));
79
90
  if (differs.length > 0)
80
91
  throw new RuleDeclarationError(ruleId, `meta.${differs.join(", meta.")}`);
92
+ // A loaded rule's `reads` was not seen by the config check: checked here, as `parseRule` does.
93
+ const reads = rule.kind === "project" ? readsProblem(rule.reads) : undefined;
94
+ if (reads !== undefined)
95
+ throw new RuleReadsError(`${ruleId}: ${reads}`);
81
96
  verified.add(rule);
82
97
  return rule;
83
98
  }
@@ -109,9 +124,19 @@ export async function loadRule(ruleId, rule) {
109
124
  * or a `RuleDeclarationError`.
110
125
  */
111
126
  export async function loadRules(config) {
112
- await Promise.all(config.plugins.flatMap((plugin) => Object.entries(plugin.rules)
127
+ const loads = config.plugins.flatMap((plugin) => Object.entries(plugin.rules)
113
128
  .filter(([key, rule]) => rule.kind === "lazy" && ruleIsOn(config, plugin.name, key, rule.meta))
114
- .map(([key, rule]) => loadRule(`${plugin.name}/${key}`, rule))));
129
+ .map(async ([key, rule]) => {
130
+ const loaded = await loadRule(`${plugin.name}/${key}`, rule);
131
+ // As the config check of a rule given directly (config.ts `unpublishedReads`).
132
+ for (const id of loaded.kind === "project" ? (loaded.reads ?? []) : []) {
133
+ const target = readTarget(config.plugins, id);
134
+ if (target.kind === "no-analysis") {
135
+ throw new RuleReadsError(unpublishedRead(plugin.name, key, id, target.plugin));
136
+ }
137
+ }
138
+ }));
139
+ await Promise.all(loads);
115
140
  }
116
141
  /** Loads every rule of the plugins, on or off: for the docs and for tests. */
117
142
  export async function loadAllRules(plugins) {
@@ -0,0 +1,77 @@
1
+ import type { RuleMark, RuleResult } from "./cache.js";
2
+ import type { LedgerMark, LedgerRef, RuleProves, StatedGuarantee, TypeQueries, UncheckedPlace } from "./types.js";
3
+ import type ts from "typescript";
4
+ /** The traits the active rules prove, joined and sorted: what the ledger lists references for. */
5
+ export type JoinedProves = {
6
+ readonly traits: readonly string[];
7
+ readonly returns: readonly string[];
8
+ readonly made: readonly string[];
9
+ readonly holders: readonly string[];
10
+ readonly flows: {
11
+ readonly produced: readonly string[];
12
+ readonly decided: readonly string[];
13
+ readonly escaped: readonly string[];
14
+ };
15
+ /** JSDoc tag names, without `@` (`RuleProves.tags`). */
16
+ readonly tags: readonly string[];
17
+ };
18
+ /** The trait a JSDoc tag states in the ledger: `@neverRejects`. */
19
+ export declare function tagTrait(tag: string): string;
20
+ /** The traits the active rules prove, joined and sorted: what the ledger lists references for. */
21
+ export declare function provesOf(all: readonly (RuleProves | undefined)[]): JoinedProves;
22
+ /**
23
+ * The rule that proves each tag trait: the first of `rules` (sorted by id) whose `proves.tags`
24
+ * lists the tag.
25
+ */
26
+ export declare function tagRulesOf(rules: readonly {
27
+ readonly id: string;
28
+ readonly proves: RuleProves | undefined;
29
+ }[]): Readonly<Record<string, string>> | undefined;
30
+ /** Every trait of `proves`, sorted and each once. */
31
+ export declare function ledgerTraits(proves: JoinedProves): readonly string[];
32
+ /** The key of a file's ledger in its cache entry: it changes with the traits it lists. */
33
+ export declare function ledgerKey(proves: JoinedProves): string;
34
+ /**
35
+ * The ledger of one file, read from its cache entry when it has it, else from the program (`read`
36
+ * gives the file's queries and source, and is only called then). A reference to a declaration of
37
+ * another file asks for that declaration (`declarationOf`), so the entry holds only while the
38
+ * declaring file is as it was: its offsets are in the ledger. `stored` is true when this call added
39
+ * it to `results`; a ledger of other traits is dropped then.
40
+ */
41
+ export declare function fileLedger(results: Map<string, RuleResult>, key: string, read: () => {
42
+ types: TypeQueries;
43
+ sourceFile: ts.SourceFile;
44
+ } | undefined, proves: JoinedProves): {
45
+ refs: readonly LedgerRef[];
46
+ stored: boolean;
47
+ };
48
+ /** Whether a cache entry's key is a ledger's, not a rule's result. */
49
+ export declare function isLedgerKey(key: string): boolean;
50
+ /** A rule's marks with its id, for the run's ledger. */
51
+ export declare function withRule(ruleId: string, marks: readonly RuleMark[]): LedgerMark[];
52
+ /** Why a place past where the file's scan stopped is not checked: the uses after it are not read. */
53
+ export declare function stoppedReason(ref: LedgerRef): string;
54
+ /**
55
+ * "`w = settings` (another name for it) is a use of `settings` that stateward does not read
56
+ * for `Owned`: write it the way `stateward explain ownership/state-written-outside-owner` shows".
57
+ */
58
+ export declare function unreadReason(ref: LedgerRef, ruleId: string): string;
59
+ /** The ledger as a proof reads it: the references of each declaration, and the marks on each. */
60
+ export type LedgerIndex = {
61
+ readonly traits: ReadonlySet<string>;
62
+ refsOf(declaration: string, trait: string): readonly LedgerRef[];
63
+ /** The places of a guarantee's references that its rule did not read. */
64
+ uncheckedOf(guarantee: StatedGuarantee, refs: readonly LedgerRef[]): readonly UncheckedPlace[];
65
+ };
66
+ export declare function indexLedger(ledger: {
67
+ readonly traits: readonly string[];
68
+ readonly refs: readonly LedgerRef[];
69
+ readonly marks: readonly LedgerMark[];
70
+ }): LedgerIndex;
71
+ /**
72
+ * A guarantee for each declaration the ledger has references to and no plugin or core scan lists
73
+ * (by its id and trait): it reads "not checked" (never "unused", never "proven") until a rule lists
74
+ * it. A tag trait's declaration is listed for the rule that proves the tag (`tagRules`).
75
+ */
76
+ export declare function ledgerGuarantees(refs: readonly LedgerRef[], listed: readonly StatedGuarantee[], tagRules?: Readonly<Record<string, string>>): StatedGuarantee[];
77
+ //# sourceMappingURL=ledger.d.ts.map
package/dist/ledger.js ADDED
@@ -0,0 +1,423 @@
1
+ import { sha1, summaryOf, summaryValue } from "./cache.js";
2
+ import { noRuleChecks, STATED_RULE_ID } from "./stated.js";
3
+ /**
4
+ * The reference ledger: every reference in a file to a declaration that states a trait an active
5
+ * rule proves, kept in the file's entry of the cache under the same fingerprint as its findings,
6
+ * keyed also by the traits it lists (`ledgerKey`). A rule marks the references it reads
7
+ * (`FileContext.read`); a proof reads every other one as not checked.
8
+ */
9
+ const LEDGER_PREFIX = "stateward/ledger:";
10
+ /** The trait a JSDoc tag states in the ledger: `@neverRejects`. */
11
+ export function tagTrait(tag) {
12
+ return `@${tag}`;
13
+ }
14
+ /** The traits the active rules prove, joined and sorted: what the ledger lists references for. */
15
+ export function provesOf(all) {
16
+ const joined = (pick) => [
17
+ ...new Set(all.flatMap((proves) => (proves === undefined ? [] : (pick(proves) ?? [])))),
18
+ ].sort();
19
+ return {
20
+ traits: joined((proves) => proves.traits),
21
+ returns: joined((proves) => proves.returns),
22
+ made: joined((proves) => proves.made),
23
+ holders: joined((proves) => proves.holders),
24
+ flows: {
25
+ produced: joined((proves) => proves.flows?.produced),
26
+ decided: joined((proves) => proves.flows?.decided),
27
+ escaped: joined((proves) => proves.flows?.escaped),
28
+ },
29
+ tags: joined((proves) => proves.tags),
30
+ };
31
+ }
32
+ /**
33
+ * The rule that proves each tag trait: the first of `rules` (sorted by id) whose `proves.tags`
34
+ * lists the tag.
35
+ */
36
+ export function tagRulesOf(rules) {
37
+ const found = new Map();
38
+ for (const rule of [...rules].sort((a, b) => compareText(a.id, b.id))) {
39
+ for (const tag of rule.proves?.tags ?? []) {
40
+ if (!found.has(tagTrait(tag)))
41
+ found.set(tagTrait(tag), rule.id);
42
+ }
43
+ }
44
+ return found.size === 0
45
+ ? undefined
46
+ : Object.fromEntries([...found].sort(([a], [b]) => compareText(a, b)));
47
+ }
48
+ /** Every trait of `proves`, sorted and each once. */
49
+ export function ledgerTraits(proves) {
50
+ return [
51
+ ...new Set([
52
+ ...proves.traits,
53
+ ...proves.returns,
54
+ ...proves.made,
55
+ ...proves.holders,
56
+ ...proves.flows.produced,
57
+ ...proves.flows.decided,
58
+ ...proves.flows.escaped,
59
+ ...proves.tags.map(tagTrait),
60
+ ]),
61
+ ].sort();
62
+ }
63
+ /** The key of a file's ledger in its cache entry: it changes with the traits it lists. */
64
+ export function ledgerKey(proves) {
65
+ const { flows } = proves;
66
+ const lists = [proves.traits, proves.returns, proves.made, proves.holders];
67
+ // The key of a ledger without flows stays what it was before flows were listed.
68
+ const flowLists = [flows.produced, flows.decided, flows.escaped];
69
+ const flowed = flowLists.some((list) => list.length > 0) ? [...lists, ...flowLists] : lists;
70
+ // Nor does the key of a ledger without tags.
71
+ const keyed = proves.tags.length > 0 ? [...lists, ...flowLists, proves.tags] : flowed;
72
+ return `${LEDGER_PREFIX}${sha1(JSON.stringify(keyed))}`;
73
+ }
74
+ const FORMS = new Set([
75
+ "call",
76
+ "read",
77
+ "write",
78
+ "alias",
79
+ "import",
80
+ "export",
81
+ "argument",
82
+ "stored",
83
+ "returned",
84
+ "jsx-tag",
85
+ "jsx-attribute",
86
+ "type",
87
+ "computed",
88
+ "other",
89
+ "tag",
90
+ "produced",
91
+ "decided",
92
+ "escaped",
93
+ ]);
94
+ const VIAS = new Set([
95
+ "value",
96
+ "cast",
97
+ "any",
98
+ "overload",
99
+ "override",
100
+ "function-type",
101
+ "generic-call",
102
+ "indirect-call",
103
+ "spread",
104
+ "reflect",
105
+ "literal",
106
+ "for-of",
107
+ "derived",
108
+ "call",
109
+ "stopped",
110
+ ]);
111
+ function isVia(value) {
112
+ return typeof value === "string" && VIAS.has(value);
113
+ }
114
+ function isForm(value) {
115
+ return typeof value === "string" && FORMS.has(value);
116
+ }
117
+ function isRecord(value) {
118
+ return typeof value === "object" && value !== null && !Array.isArray(value);
119
+ }
120
+ function parseRef(value) {
121
+ if (!isRecord(value))
122
+ return undefined;
123
+ const { id, declaration, name, marker, trait, form, via, location, text } = value;
124
+ if (typeof id !== "string" ||
125
+ typeof declaration !== "string" ||
126
+ typeof name !== "string" ||
127
+ typeof marker !== "string" ||
128
+ typeof trait !== "string" ||
129
+ !isForm(form) ||
130
+ typeof text !== "string" ||
131
+ (via !== undefined && !isVia(via)) ||
132
+ !isRecord(location)) {
133
+ return undefined;
134
+ }
135
+ const { file, start, end } = location;
136
+ if (typeof file !== "string" || typeof start !== "number" || typeof end !== "number") {
137
+ return undefined;
138
+ }
139
+ return {
140
+ id,
141
+ declaration,
142
+ name,
143
+ marker,
144
+ trait,
145
+ form,
146
+ ...(isVia(via) ? { via } : {}),
147
+ location: { file, start, end },
148
+ text,
149
+ };
150
+ }
151
+ function isList(value) {
152
+ return Array.isArray(value);
153
+ }
154
+ function parseRefs(value) {
155
+ if (!isList(value))
156
+ return undefined;
157
+ const found = [];
158
+ for (const item of value) {
159
+ const one = parseRef(item);
160
+ if (one === undefined)
161
+ return undefined;
162
+ found.push(one);
163
+ }
164
+ return found;
165
+ }
166
+ /**
167
+ * The ledger of one file, read from its cache entry when it has it, else from the program (`read`
168
+ * gives the file's queries and source, and is only called then). A reference to a declaration of
169
+ * another file asks for that declaration (`declarationOf`), so the entry holds only while the
170
+ * declaring file is as it was: its offsets are in the ledger. `stored` is true when this call added
171
+ * it to `results`; a ledger of other traits is dropped then.
172
+ */
173
+ export function fileLedger(results, key, read, proves) {
174
+ const kept = results.get(key);
175
+ if (kept !== undefined) {
176
+ if (kept.summary === undefined)
177
+ return { refs: [], stored: false };
178
+ const parsed = parseRefs(summaryValue(kept.summary));
179
+ if (parsed !== undefined)
180
+ return { refs: parsed, stored: false };
181
+ }
182
+ const opened = read();
183
+ const refs = [];
184
+ if (opened !== undefined && ledgerTraits(proves).length > 0) {
185
+ const { types, sourceFile } = opened;
186
+ const file = sourceFile.fileName;
187
+ const asked = new Set();
188
+ const flows = proves.flows;
189
+ const listsFlows = flows.produced.length > 0 || flows.decided.length > 0 || flows.escaped.length > 0;
190
+ const found = [
191
+ ...types.statedReferencesIn(sourceFile, proves),
192
+ ...(listsFlows ? types.typedFlowsIn(sourceFile, proves) : []),
193
+ ];
194
+ for (const one of found) {
195
+ const start = one.node.getStart(sourceFile);
196
+ if (!one.declaration.startsWith(`${file}#`) && !asked.has(one.symbol.id)) {
197
+ asked.add(one.symbol.id);
198
+ types.declarationOf(one.symbol);
199
+ }
200
+ // A flow is named by its whole expression: one may start where a reference or another flow does.
201
+ const flow = one.via !== undefined;
202
+ refs.push({
203
+ id: flow ? `${file}#${String(start)}-${String(one.node.end)}` : `${file}#${String(start)}`,
204
+ declaration: one.declaration,
205
+ name: one.name,
206
+ marker: one.marker,
207
+ trait: one.trait,
208
+ form: one.form,
209
+ ...(one.via === undefined ? {} : { via: one.via }),
210
+ location: { file, start, end: one.node.end },
211
+ text: one.text,
212
+ });
213
+ }
214
+ refs.sort((a, b) => a.location.start - b.location.start ||
215
+ a.location.end - b.location.end ||
216
+ compareText(a.declaration, b.declaration) ||
217
+ compareText(a.trait, b.trait) ||
218
+ compareText(a.id, b.id));
219
+ }
220
+ for (const other of results.keys()) {
221
+ if (other.startsWith(LEDGER_PREFIX) && other !== key)
222
+ results.delete(other);
223
+ }
224
+ results.set(key, refs.length === 0
225
+ ? { findings: [] }
226
+ : {
227
+ findings: [],
228
+ summary: summaryOf(refs.map((ref) => ({
229
+ id: ref.id,
230
+ declaration: ref.declaration,
231
+ name: ref.name,
232
+ marker: ref.marker,
233
+ trait: ref.trait,
234
+ form: ref.form,
235
+ ...(ref.via === undefined ? {} : { via: ref.via }),
236
+ location: { ...ref.location },
237
+ text: ref.text,
238
+ }))),
239
+ });
240
+ return { refs, stored: true };
241
+ }
242
+ function compareText(a, b) {
243
+ return a < b ? -1 : a > b ? 1 : 0;
244
+ }
245
+ /** Whether a cache entry's key is a ledger's, not a rule's result. */
246
+ export function isLedgerKey(key) {
247
+ return key.startsWith(LEDGER_PREFIX);
248
+ }
249
+ /** A rule's marks with its id, for the run's ledger. */
250
+ export function withRule(ruleId, marks) {
251
+ return marks.map((mark) => ({ ruleId, ...mark }));
252
+ }
253
+ /** What a reference does, after its code: "(another name for it)". */
254
+ const FORM_WORDS = {
255
+ call: "a call",
256
+ read: "a read",
257
+ write: "a write",
258
+ alias: "another name for it",
259
+ import: "an import",
260
+ export: "an export",
261
+ argument: "given as an argument",
262
+ stored: "stored in an object or array literal",
263
+ returned: "returned",
264
+ "jsx-tag": "a JSX tag",
265
+ "jsx-attribute": "a JSX attribute",
266
+ type: "a type",
267
+ computed: "a computed key",
268
+ other: "a use",
269
+ tag: "the tag on its declaration",
270
+ produced: "a value of the type made here",
271
+ decided: "a decision by a value of the type",
272
+ escaped: "a write to an object that holds it",
273
+ };
274
+ /** Where the reader finds the ways a guarantee's rule reads: its page, when a rule proves it. */
275
+ function shownBy(ruleId) {
276
+ return ruleId === STATED_RULE_ID
277
+ ? "write it the way its pack's page shows"
278
+ : `write it the way \`stateward explain ${ruleId}\` shows`;
279
+ }
280
+ /** Why a place past where the file's scan stopped is not checked: the uses after it are not read. */
281
+ export function stoppedReason(ref) {
282
+ return `the file is too large to read past \`${ref.text}\`, so the uses of \`${ref.name}\` after it are not checked: split the file`;
283
+ }
284
+ /**
285
+ * "`w = settings` (another name for it) is a use of `settings` that stateward does not read
286
+ * for `Owned`: write it the way `stateward explain ownership/state-written-outside-owner` shows".
287
+ */
288
+ export function unreadReason(ref, ruleId) {
289
+ return `\`${ref.text}\` (${FORM_WORDS[ref.form]}) is a use of \`${ref.name}\` that stateward does not read for \`${ref.marker}\`: ${shownBy(ruleId)}`;
290
+ }
291
+ const RANK = {
292
+ irrelevant: 0,
293
+ decided: 1,
294
+ "handed-on": 2,
295
+ unchecked: 3,
296
+ };
297
+ /**
298
+ * One rule's word on a reference from all its marks: a place it cannot follow wins; a reference
299
+ * its project side settled is read, whatever the file side handed on.
300
+ */
301
+ function settled(marks) {
302
+ const unchecked = marks
303
+ .map((mark) => mark.outcome)
304
+ .filter((outcome) => outcome.kind === "unchecked")
305
+ .sort((a, b) => (a.reason < b.reason ? -1 : a.reason > b.reason ? 1 : 0));
306
+ if (unchecked[0] !== undefined)
307
+ return unchecked[0];
308
+ const read = marks.find((mark) => mark.outcome.kind === "decided" || mark.outcome.kind === "irrelevant");
309
+ if (read !== undefined)
310
+ return read.outcome;
311
+ return [...marks].sort((a, b) => RANK[b.outcome.kind] - RANK[a.outcome.kind])[0]?.outcome;
312
+ }
313
+ export function indexLedger(ledger) {
314
+ const byDeclaration = new Map();
315
+ for (const ref of ledger.refs) {
316
+ const key = `${ref.declaration}\u0000${ref.trait}`;
317
+ const list = byDeclaration.get(key) ?? [];
318
+ list.push(ref);
319
+ byDeclaration.set(key, list);
320
+ }
321
+ const marksOf = new Map();
322
+ for (const mark of ledger.marks) {
323
+ const key = `${mark.ruleId}\u0000${mark.ref}\u0000${mark.trait}`;
324
+ const list = marksOf.get(key) ?? [];
325
+ list.push(mark);
326
+ marksOf.set(key, list);
327
+ }
328
+ return {
329
+ traits: new Set(ledger.traits),
330
+ refsOf: (declaration, trait) => byDeclaration.get(`${declaration}\u0000${trait}`) ?? [],
331
+ uncheckedOf(guarantee, refs) {
332
+ const places = [];
333
+ for (const ref of refs) {
334
+ const outcome = settled(marksOf.get(`${guarantee.ruleId}\u0000${ref.id}\u0000${ref.trait}`) ?? []);
335
+ // Past the flow scan's budget nothing after this place is listed: no mark makes it read.
336
+ const reason = ref.via === "stopped"
337
+ ? stoppedReason(ref)
338
+ : outcome === undefined
339
+ ? unreadReason(ref, guarantee.ruleId)
340
+ : outcome.kind === "unchecked"
341
+ ? outcome.reason
342
+ : outcome.kind === "handed-on"
343
+ ? `\`${ref.text}\` is passed to ${outcome.to}, which stateward does not check for \`${ref.marker}\`: ${shownBy(guarantee.ruleId)}`
344
+ : undefined;
345
+ if (reason !== undefined)
346
+ places.push({ location: ref.location, reason });
347
+ }
348
+ return places;
349
+ },
350
+ };
351
+ }
352
+ /** The forms that run nothing: a declaration only they name is unused. */
353
+ function runsNothing(ref) {
354
+ return ref.form === "import" || ref.form === "export" || ref.form === "type";
355
+ }
356
+ /**
357
+ * The guarantee a JSDoc tag states (`RuleProves.tags`), proven by `ruleId`: its places are the
358
+ * tag itself (the declaration's body) and every reference that runs something.
359
+ */
360
+ function tagGuarantee(first, refs, location, ruleId) {
361
+ const tag = first.trait.slice(1);
362
+ return {
363
+ guarantee: first.trait,
364
+ source: { kind: "tag", tag },
365
+ marker: first.marker,
366
+ name: first.name,
367
+ declaration: first.declaration,
368
+ location,
369
+ ruleId,
370
+ promise: `\`${first.name}\` keeps what \`@${tag}\` states, in its own code and at every use`,
371
+ covers: { one: "place", many: "places" },
372
+ covered: refs
373
+ .filter((ref) => ref.declaration === first.declaration && ref.trait === first.trait && !runsNothing(ref))
374
+ .map((ref) => ({ name: `\`${ref.text}\``, location: ref.location })),
375
+ };
376
+ }
377
+ /**
378
+ * A guarantee for each declaration the ledger has references to and no plugin or core scan lists
379
+ * (by its id and trait): it reads "not checked" (never "unused", never "proven") until a rule lists
380
+ * it. A tag trait's declaration is listed for the rule that proves the tag (`tagRules`).
381
+ */
382
+ export function ledgerGuarantees(refs, listed, tagRules = {}) {
383
+ const known = new Set(listed.map((one) => `${one.declaration}\u0000${one.guarantee}`));
384
+ const found = [];
385
+ for (const ref of refs) {
386
+ const key = `${ref.declaration}\u0000${ref.trait}`;
387
+ if (known.has(key))
388
+ continue;
389
+ known.add(key);
390
+ const at = ref.declaration.lastIndexOf("#");
391
+ const start = Number(ref.declaration.slice(at + 1));
392
+ const location = { file: ref.declaration.slice(0, at), start, end: start };
393
+ // Core lists a declaration it found by its written type from where it starts: a property
394
+ // with a modifier (`static x: Owned<…>`) is listed there, and the ledger names it at its name.
395
+ const scanned = listed.some((one) => one.ruleId === STATED_RULE_ID &&
396
+ one.guarantee === ref.trait &&
397
+ one.location.file === location.file &&
398
+ one.location.start <= start &&
399
+ start <= one.location.end);
400
+ if (scanned)
401
+ continue;
402
+ const prover = tagRules[ref.trait];
403
+ if (prover !== undefined) {
404
+ found.push(tagGuarantee(ref, refs, location, prover));
405
+ continue;
406
+ }
407
+ found.push({
408
+ guarantee: ref.trait,
409
+ source: { kind: "marker" },
410
+ marker: ref.marker,
411
+ name: ref.name,
412
+ declaration: ref.declaration,
413
+ location,
414
+ ruleId: STATED_RULE_ID,
415
+ promise: "nothing yet: no rule proves it",
416
+ covers: { one: "place", many: "places" },
417
+ covered: [],
418
+ unchecked: [{ location, reason: noRuleChecks(ref.marker) }],
419
+ });
420
+ }
421
+ return found;
422
+ }
423
+ //# sourceMappingURL=ledger.js.map
@@ -0,0 +1,13 @@
1
+ /**
2
+ * A rule a release made off by default because too few of its findings were right on real
3
+ * projects (`RuleInfo.offByDefault`). Its page and the config notice give the same figure, from
4
+ * here.
5
+ */
6
+ import type { OffByDefault } from "./types.js";
7
+ /** The share of its findings a rule needs right on real projects to be on by default. */
8
+ export declare const ON_BY_DEFAULT_SHARE = 86;
9
+ /** The sentence of the rule's page that says why it is off by default. */
10
+ export declare function offByDefaultText(off: OffByDefault): string;
11
+ /** The notice for a config that turns the rule on in `rules`. */
12
+ export declare function offByDefaultNotice(ruleId: string, off: OffByDefault): string;
13
+ //# sourceMappingURL=off-by-default.d.ts.map
@@ -0,0 +1,15 @@
1
+ /** The share of its findings a rule needs right on real projects to be on by default. */
2
+ export const ON_BY_DEFAULT_SHARE = 86;
3
+ /** The share of the findings checked that were right, in whole percent. */
4
+ function rightShare(off) {
5
+ return Math.round((off.right / off.checked) * 100);
6
+ }
7
+ /** The sentence of the rule's page that says why it is off by default. */
8
+ export function offByDefaultText(off) {
9
+ return `It is off by default because ${String(rightShare(off))}% of its findings on real projects were right (${String(off.right)} of ${String(off.checked)} checked), under the ${String(ON_BY_DEFAULT_SHARE)}% a rule needs to be on by default.`;
10
+ }
11
+ /** The notice for a config that turns the rule on in `rules`. */
12
+ export function offByDefaultNotice(ruleId, off) {
13
+ return `\`${ruleId}\` is off by default since ${off.since} (right ${String(rightShare(off))}% of the time on real projects); your config turns it on`;
14
+ }
15
+ //# sourceMappingURL=off-by-default.js.map
package/dist/options.d.ts CHANGED
@@ -6,7 +6,13 @@ type SpecsOf<R extends PluginRule> = NonNullable<R["meta"]["options"]>;
6
6
  * (the union of `oneOf` for a string option). A rule that declares none takes no names at all; a
7
7
  * rule typed as the wide `Rule` takes any name, because nothing says which exist.
8
8
  */
9
- export type ConfigOptionsOf<R extends PluginRule> = SpecsOf<R> extends NoOptions ? NoOptions : Partial<OptionsOf<SpecsOf<R>>>;
9
+ export type ConfigOptionsOf<R extends PluginRule> = SpecsOf<R> extends NoOptions ? NoOptions : Partial<OptionsOf<UserSpecs<SpecsOf<R>>>>;
10
+ /** The specs a config may set: all but those only stateward sets (`internal`). */
11
+ type UserSpecs<S extends OptionSpecs> = {
12
+ [K in keyof S as S[K] extends {
13
+ internal: true;
14
+ } ? never : K]: S[K];
15
+ };
10
16
  /** The rule of `P` (a plugin, or a union of plugins) whose id is `Id`. */
11
17
  type RuleById<P extends Plugin, Id extends string> = P extends Plugin ? Id extends `${P["name"]}/${infer Key}` ? Key extends keyof P["rules"] ? P["rules"][Key] extends infer R extends PluginRule ? R : never : never : never : never;
12
18
  /** The `rules` of a config for plugin type `P`: its rule ids as keys, each with its own options. */
@@ -31,10 +37,16 @@ declare function optionString(input: {
31
37
  description: string;
32
38
  }): StringOption;
33
39
  export declare const option: {
34
- boolean(input: {
40
+ /**
41
+ * With `convention: true`, `conventions: true` in the config turns it on; with `internal: true`,
42
+ * only stateward sets it (`BooleanOption`).
43
+ */
44
+ boolean<const I extends {
35
45
  default: boolean;
36
46
  description: string;
37
- }): BooleanOption;
47
+ convention?: true;
48
+ internal?: true;
49
+ }>(input: I): BooleanOption & Pick<I, "internal">;
38
50
  number(input: {
39
51
  default: number;
40
52
  description: string;
@@ -79,11 +91,15 @@ export declare function expectation(spec: OptionSpec): string;
79
91
  /** Why `value` is not a valid value of `spec`, as "must be …, got …"; undefined when it is. */
80
92
  export declare function optionProblem(spec: OptionSpec, value: unknown): string | undefined;
81
93
  /** The default of every option: what a rule receives when the config sets nothing. */
82
- export declare function defaultOptions(specs: OptionSpecs | undefined): Options;
94
+ /**
95
+ * Every option at its default; with `conventions` (the config's `conventions: true`), an option
96
+ * marked `convention` is true.
97
+ */
98
+ export declare function defaultOptions(specs: OptionSpecs | undefined, conventions?: boolean): Options;
83
99
  /**
84
100
  * The options of rule `ruleId` from what the config gave (`given`, untrusted): defaults filled
85
101
  * in, and one error per unknown name or value that does not fit, each naming rule and option.
86
102
  */
87
- export declare function parseRuleOptions(ruleId: string, specs: OptionSpecs | undefined, given: unknown, errors: string[]): Options;
103
+ export declare function parseRuleOptions(ruleId: string, specs: OptionSpecs | undefined, given: unknown, errors: string[], conventions?: boolean): Options;
88
104
  export {};
89
105
  //# sourceMappingURL=options.d.ts.map