@stateward/core 1.0.1-rc.1 → 1.1.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.
@@ -1,10 +1,10 @@
1
1
  import path from "node:path";
2
2
  import picomatch from "picomatch";
3
3
  import ts from "typescript";
4
- import { computeFingerprints, packageDependencies, packageEntries, packageManifests, packageNames, textHash, } from "./fingerprints.js";
4
+ import { computeFingerprints, declarationTextHash, packageDependencies, packageEntries, packageManifests, packageNames, } from "./fingerprints.js";
5
5
  import { markedComments } from "./comments.js";
6
6
  import { recordInputs, recordingHost, replays } from "./program-record.js";
7
- import { declarationPath } from "./qualified-ids.js";
7
+ import { declarationAtPath, declarationPath } from "./qualified-ids.js";
8
8
  import { displayPath } from "../display-path.js";
9
9
  import { expandTsconfigs } from "../tsconfigs.js";
10
10
  /** The tsconfig could not be read or is invalid. */
@@ -300,9 +300,16 @@ function tryEditsOn(program, host, candidates) {
300
300
  const ranges = new Map();
301
301
  /** Per edited file, the edits placed in it and how an offset of the old text moves. */
302
302
  const moves = new Map();
303
+ /** Files a fix creates: edits at the start of a file that does not exist yet. */
304
+ const created = new Set();
303
305
  for (const [file, placed] of byFile) {
304
306
  const sourceFile = program.getSourceFile(file);
305
- const text = sourceFile?.text;
307
+ const creates = sourceFile === undefined &&
308
+ !host.fileExists(file) &&
309
+ placed.every(({ edit: { location } }) => location.start === 0 && location.end === 0);
310
+ if (creates)
311
+ created.add(file);
312
+ const text = creates ? "" : sourceFile?.text;
306
313
  const fits = placed.every(({ edit: { location } }) => text !== undefined &&
307
314
  location.start >= 0 &&
308
315
  location.start <= location.end &&
@@ -378,6 +385,18 @@ function tryEditsOn(program, host, candidates) {
378
385
  for (const [file, spans] of ranges) {
379
386
  const before = program.getSourceFile(file);
380
387
  const after = copy.getSourceFile(file);
388
+ if (created.has(file) && after !== undefined) {
389
+ // Every error in a file the fix writes is the fix's own.
390
+ const [error] = errorsOf(copy, after);
391
+ if (error === undefined)
392
+ continue;
393
+ for (const { candidate } of spans) {
394
+ if (verdicts[candidate]?.kind === "compiles") {
395
+ verdicts[candidate] = { kind: "breaks", error: firstLine(error) };
396
+ }
397
+ }
398
+ continue;
399
+ }
381
400
  if (before === undefined || after === undefined)
382
401
  continue;
383
402
  // A fix that changes a declaration's type answers for every line of the files it edits.
@@ -474,6 +493,34 @@ function unresolvedImportsOf(program, file) {
474
493
  }
475
494
  return found;
476
495
  }
496
+ /** Whether a project with these options checks with `strictNullChecks` (TypeScript 6: on unless turned off). */
497
+ export function checksNulls(options) {
498
+ return options.strictNullChecks ?? options.strict ?? true;
499
+ }
500
+ const TYPED_EXTENSIONS = new Set([
501
+ ts.Extension.Dts,
502
+ ts.Extension.Dmts,
503
+ ts.Extension.Dcts,
504
+ ts.Extension.Ts,
505
+ ts.Extension.Tsx,
506
+ ts.Extension.Mts,
507
+ ts.Extension.Cts,
508
+ ]);
509
+ /** `ProjectUnit.typesResolve` for a project, remembered by module name. */
510
+ function typesResolver(tsconfig, options) {
511
+ const known = new Map();
512
+ // A file that need not exist: resolution only looks at its folder and above.
513
+ const from = path.join(path.dirname(tsconfig), "__stateward_types__.ts");
514
+ return (module) => {
515
+ const before = known.get(module);
516
+ if (before !== undefined)
517
+ return before;
518
+ const resolved = ts.resolveModuleName(module, from, options, ts.sys).resolvedModule;
519
+ const typed = resolved !== undefined && TYPED_EXTENSIONS.has(resolved.extension);
520
+ known.set(module, typed);
521
+ return typed;
522
+ };
523
+ }
477
524
  function firstSyntaxError(program, file) {
478
525
  const sourceFile = program.getSourceFile(file);
479
526
  if (sourceFile === undefined)
@@ -746,6 +793,54 @@ function isPromiseType(checker, type) {
746
793
  return awaited !== undefined && awaited !== type;
747
794
  }
748
795
  const NULLISH = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
796
+ /** The property a stated guarantee is written in (`TypeQueries.guaranteesOf`). */
797
+ const GUARANTEE_PROPERTY = "__guarantee";
798
+ /** The guarantee names of one type that is not a union: its optional `__guarantee` literals. */
799
+ function memberGuarantees(checker, type) {
800
+ const property = checker.getPropertyOfType(type, GUARANTEE_PROPERTY);
801
+ if (property === undefined || !(property.flags & ts.SymbolFlags.Optional))
802
+ return [];
803
+ const value = checker.getTypeOfSymbol(property);
804
+ const names = [];
805
+ for (const part of value.isUnion() ? value.types : [value]) {
806
+ if (part.flags & NULLISH)
807
+ continue;
808
+ if (!part.isStringLiteral())
809
+ return [];
810
+ names.push(part.value);
811
+ }
812
+ return names;
813
+ }
814
+ /**
815
+ * The guarantees every member of `type` states (`null` and `undefined` left out), sorted. A
816
+ * member that states none makes the whole type state none.
817
+ */
818
+ function guaranteesOfType(checker, found) {
819
+ const type = widened(checker, found);
820
+ if (type === undefined)
821
+ return [];
822
+ const members = (type.isUnion() ? type.types : [type]).filter((member) => (member.flags & NULLISH) === 0);
823
+ let shared;
824
+ for (const member of members) {
825
+ const names = memberGuarantees(checker, member);
826
+ shared = shared === undefined ? [...names] : shared.filter((name) => names.includes(name));
827
+ if (shared.length === 0)
828
+ return [];
829
+ }
830
+ return [...new Set(shared ?? [])].sort();
831
+ }
832
+ /** The declared type of a declaration: a variable's or property's type, or a type alias's. */
833
+ function declaredTypeOf(checker, declaration) {
834
+ const name = ts.isDeclarationStatement(declaration) || ts.isVariableDeclaration(declaration)
835
+ ? ts.getNameOfDeclaration(declaration)
836
+ : undefined;
837
+ const symbol = name === undefined ? undefined : checker.getSymbolAtLocation(name);
838
+ if (symbol === undefined)
839
+ return checker.getTypeAtLocation(declaration);
840
+ return symbol.flags & ts.SymbolFlags.Value
841
+ ? checker.getTypeOfSymbol(symbol)
842
+ : checker.getDeclaredTypeOfSymbol(symbol);
843
+ }
749
844
  /** A string, number or boolean literal, or an enum member: a type with exactly one value. */
750
845
  function isUnitLiteral(type) {
751
846
  return (type.isStringLiteral() ||
@@ -1000,6 +1095,49 @@ function isReadonlyProperty(owner, property) {
1000
1095
  return (declarations.length > 0 &&
1001
1096
  declarations.every((declaration) => (ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Readonly) !== 0));
1002
1097
  }
1098
+ /** An object type with an `aborted: boolean` property: `AbortSignal`, or a library's own signal type. */
1099
+ function isSignal(checker, type) {
1100
+ const members = withoutNullish(type);
1101
+ return (members.length > 0 &&
1102
+ members.every((member) => {
1103
+ if (!(member.flags & ts.TypeFlags.Object))
1104
+ return false;
1105
+ const aborted = checker.getPropertyOfType(member, "aborted");
1106
+ if (aborted === undefined)
1107
+ return false;
1108
+ const value = checker.getTypeOfSymbol(aborted);
1109
+ return withoutNullish(value).every((part) => (part.flags & ts.TypeFlags.BooleanLike) !== 0);
1110
+ }));
1111
+ }
1112
+ /** Where the callee takes a signal: a parameter that is one, or an options object holding one. */
1113
+ function signalParameter(checker, call) {
1114
+ const signature = checker.getResolvedSignature(call);
1115
+ if (signature === undefined)
1116
+ return undefined;
1117
+ for (const [index, parameter] of signature.parameters.entries()) {
1118
+ const declared = parameter.valueDeclaration;
1119
+ if (declared !== undefined &&
1120
+ ts.isParameter(declared) &&
1121
+ declared.dotDotDotToken !== undefined) {
1122
+ return undefined;
1123
+ }
1124
+ const type = widened(checker, checker.getTypeOfSymbol(parameter));
1125
+ if (type === undefined)
1126
+ continue;
1127
+ if (isSignal(checker, type))
1128
+ return { index, property: undefined };
1129
+ // An options object you fill in; a `Request`, which carries its own readonly signal, is not one.
1130
+ const holds = withoutNullish(type).some((member) => {
1131
+ const signal = checker.getPropertyOfType(member, "signal");
1132
+ return (signal !== undefined &&
1133
+ !isReadonlyProperty(member, signal) &&
1134
+ isSignal(checker, checker.getTypeOfSymbol(signal)));
1135
+ });
1136
+ if (holds)
1137
+ return { index, property: "signal" };
1138
+ }
1139
+ return undefined;
1140
+ }
1003
1141
  function withoutNullish(type) {
1004
1142
  const nothing = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
1005
1143
  return (type.isUnion() ? type.types : [type]).filter((member) => !(member.flags & nothing));
@@ -1327,6 +1465,14 @@ root, packageOf, isEntry, dependenciesOf) {
1327
1465
  }
1328
1466
  return [...files].sort();
1329
1467
  },
1468
+ guaranteesOf(target) {
1469
+ const checker = typeChecker();
1470
+ if ("kind" in target)
1471
+ return guaranteesOfType(checker, checker.getTypeAtLocation(target));
1472
+ const declaration = declarations.get(target.id);
1473
+ const type = declaration === undefined ? undefined : declaredTypeOf(checker, declaration);
1474
+ return type === undefined ? [] : guaranteesOfType(checker, type);
1475
+ },
1330
1476
  awaitedAliasOf(node) {
1331
1477
  return aliasOfType(typeChecker(), typeChecker().getTypeAtLocation(node));
1332
1478
  },
@@ -1493,6 +1639,9 @@ root, packageOf, isEntry, dependenciesOf) {
1493
1639
  calleeTags(call) {
1494
1640
  return calleeTags(typeChecker(), call);
1495
1641
  },
1642
+ signalParameterOf(call) {
1643
+ return signalParameter(typeChecker(), call);
1644
+ },
1496
1645
  narrowedBy(reference, test) {
1497
1646
  return narrowedMembers(program, typeChecker(), reference, test);
1498
1647
  },
@@ -1669,9 +1818,26 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1669
1818
  }
1670
1819
  return fingerprints;
1671
1820
  };
1672
- /** What each file's rules were handed, by file. */
1821
+ /** What each file's rules were handed, by file: read ids, with the file each one is in. */
1673
1822
  const reads = new Map();
1674
1823
  const types = createTypeQueries(program, claimed, cwd, packageOf, isEntry, dependenciesOf);
1824
+ const idFileName = idFileNames(cwd);
1825
+ const fileId = (fileName) => `${idFileName(fileName)}#`;
1826
+ /** The read id of a declaration handed out: its own id when that finds it again, else its file's. */
1827
+ const readId = (symbol, found) => {
1828
+ if (!types.isOwnFile(found.file) || ts.isSourceFile(found.node))
1829
+ return fileId(found.file);
1830
+ const sourceFile = program.getSourceFile(found.file);
1831
+ const at = symbol.id.indexOf("#");
1832
+ return sourceFile !== undefined &&
1833
+ at >= 0 &&
1834
+ symbol.id.slice(0, at + 1) === fileId(found.file) &&
1835
+ declarationAtPath(sourceFile, symbol.id.slice(at + 1)) === found.node
1836
+ ? symbol.id
1837
+ : fileId(found.file);
1838
+ };
1839
+ /** Read prints computed in this program, by read id. */
1840
+ const prints = new Map();
1675
1841
  const unit = {
1676
1842
  tsconfig: tsconfigPath,
1677
1843
  files,
@@ -1680,29 +1846,46 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1680
1846
  types,
1681
1847
  fingerprint: (file) => fingerprintsOf().get(file),
1682
1848
  typesFor: (file) => {
1683
- const read = reads.get(file) ?? new Set();
1849
+ const read = reads.get(file) ?? new Map();
1684
1850
  reads.set(file, read);
1685
1851
  return {
1686
1852
  ...types,
1687
1853
  declarationOf(symbol) {
1688
1854
  const found = types.declarationOf(symbol);
1689
- if (found !== undefined && found.file !== file)
1690
- read.add(found.file);
1855
+ if (found !== undefined && found.file !== file) {
1856
+ read.set(readId(symbol, found), found.file);
1857
+ }
1691
1858
  return found;
1692
1859
  },
1693
1860
  };
1694
1861
  },
1695
- readsOf: (file) => [...(reads.get(file) ?? [])].sort(),
1696
- readFingerprint: (file) => {
1697
- const sourceFile = program.getSourceFile(file);
1698
- if (sourceFile === undefined)
1699
- return undefined;
1700
- const print = textHash(sourceFile);
1701
- readPrints[file] = print;
1862
+ readsOf: (file, mentioned) => {
1863
+ const ids = new Set();
1864
+ for (const [id, readFile] of reads.get(file) ?? []) {
1865
+ ids.add(mentioned(readFile) ? fileId(readFile) : id);
1866
+ }
1867
+ return [...ids].sort();
1868
+ },
1869
+ readFingerprint: (read) => {
1870
+ if (prints.has(read))
1871
+ return prints.get(read);
1872
+ const at = read.indexOf("#");
1873
+ const sourceFile = at < 0
1874
+ ? undefined
1875
+ : program.getSourceFile(toTypeScriptPath(path.resolve(cwd, read.slice(0, at))));
1876
+ const node = sourceFile === undefined ? undefined : declarationAtPath(sourceFile, read.slice(at + 1));
1877
+ const print = sourceFile === undefined || node === undefined
1878
+ ? undefined
1879
+ : declarationTextHash(sourceFile, node);
1880
+ prints.set(read, print);
1881
+ if (print !== undefined)
1882
+ readPrints[read] = print;
1702
1883
  return print;
1703
1884
  },
1704
1885
  syntaxError: (file) => firstSyntaxError(program, file),
1705
1886
  unresolvedImports: (file) => unresolvedImportsOf(program, file),
1887
+ strictNullChecks: checksNulls(parsed.options),
1888
+ typesResolve: typesResolver(tsconfigPath, parsed.options),
1706
1889
  bind: () => {
1707
1890
  program.getTypeChecker();
1708
1891
  },
@@ -1735,11 +1918,13 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1735
1918
  },
1736
1919
  fingerprint: (file) => record.fingerprints[file],
1737
1920
  typesFor: (file) => real().typesFor(file),
1738
- readsOf: (file) => (built === undefined ? [] : built.readsOf(file)),
1921
+ readsOf: (file, mentioned) => (built === undefined ? [] : built.readsOf(file, mentioned)),
1739
1922
  // The program is the recorded one: a text hash it recorded is the answer.
1740
1923
  readFingerprint: (file) => record.reads[file] ?? real().readFingerprint(file),
1741
1924
  syntaxError: (file) => real().syntaxError(file),
1742
1925
  unresolvedImports: (file) => real().unresolvedImports(file),
1926
+ strictNullChecks: checksNulls(project.parsed.options),
1927
+ typesResolve: typesResolver(project.tsconfigPath, project.parsed.options),
1743
1928
  bind: () => {
1744
1929
  real().bind();
1745
1930
  },
package/dist/cache.d.ts CHANGED
@@ -5,7 +5,7 @@ import type { Finding, FixVerdict, Json, Rule, Severity } from "./types.js";
5
5
  *
6
6
  * - per own file, under its dependency fingerprint (backend/fingerprints.ts), and per rule under
7
7
  * its rule key (`ruleKey`): the findings the rule reported on that file, and a project rule's
8
- * summary; with the full fingerprint of each other file whose syntax the rules read there. A
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
10
  * - per project rule, under its rule key: a hash of all its summaries, and the findings its check
11
11
  * produced from them. Equal summaries give equal findings (a project rule decides from its
@@ -16,7 +16,7 @@ import type { Finding, FixVerdict, Json, Rule, Severity } from "./types.js";
16
16
  * server save it to disk between runs as a `CacheSnapshot` (disk-cache.ts).
17
17
  */
18
18
  /** Bumped whenever what is stored, or how a key is computed, changes. */
19
- export declare const CACHE_FORMAT = 5;
19
+ export declare const CACHE_FORMAT = 7;
20
20
  /**
21
21
  * A project rule's summary of one file: the hash of its JSON text, and either that text or, once a
22
22
  * rule or a hover needed the value (a run whose summaries are all unchanged never does), the parsed
@@ -56,8 +56,9 @@ export type FileEntry = {
56
56
  fingerprint: string;
57
57
  rules: ReadonlyMap<string, RuleResult>;
58
58
  /**
59
- * The other files whose syntax the rules read on this file (`TypeQueries.declarationOf`), with
60
- * each one's full fingerprint then: the entry holds while each is the same.
59
+ * What the rules on this file read of other files (`TypeQueries.declarationOf`), by read id (a
60
+ * declaration's qualified id, or a file's own id `src/a.ts#` for its whole text:
61
+ * `ProjectUnit.readsOf`), with each one's hash then: the entry holds while each is the same.
61
62
  */
62
63
  reads: ReadonlyMap<string, string>;
63
64
  };
package/dist/cache.js CHANGED
@@ -5,7 +5,7 @@ import { isQueryKind } from "./backend/program-record.js";
5
5
  *
6
6
  * - per own file, under its dependency fingerprint (backend/fingerprints.ts), and per rule under
7
7
  * its rule key (`ruleKey`): the findings the rule reported on that file, and a project rule's
8
- * summary; with the full fingerprint of each other file whose syntax the rules read there. A
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
10
  * - per project rule, under its rule key: a hash of all its summaries, and the findings its check
11
11
  * produced from them. Equal summaries give equal findings (a project rule decides from its
@@ -16,7 +16,7 @@ import { isQueryKind } from "./backend/program-record.js";
16
16
  * server save it to disk between runs as a `CacheSnapshot` (disk-cache.ts).
17
17
  */
18
18
  /** Bumped whenever what is stored, or how a key is computed, changes. */
19
- export const CACHE_FORMAT = 5;
19
+ export const CACHE_FORMAT = 7;
20
20
  /** Frozen all the way down: a cached summary is shared between runs, so no rule may change it. */
21
21
  function deepFreeze(value) {
22
22
  if (typeof value === "object" && value !== null) {
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, RuleSelection, TokenType } from "./types.js";
4
+ import type { CheckResult, Config, EditorAction, EditorHint, Finding, FixForm, FixReview, FixSetReview, LibraryUse, Location, StatedGuarantee, RuleSelection, TokenType } from "./types.js";
5
5
  export type CheckInput = {
6
6
  config: Config;
7
7
  cwd: string;
@@ -101,6 +101,12 @@ export type Checker = {
101
101
  * from the last full check: `stateward deps`. Empty before a check.
102
102
  */
103
103
  libraryFacts(): readonly LibraryUse[];
104
+ /**
105
+ * The guarantees stated in the project, as the plugins that prove them read them
106
+ * (`EditorContributions.guarantees`), from the last full check: no new type checking. Empty
107
+ * before a check. Pair them with that check's findings with `proveGuarantees`.
108
+ */
109
+ guarantees(): readonly StatedGuarantee[];
104
110
  /**
105
111
  * Tries each fix of `findings` on a copy of the code of the last run (fixes.ts) and returns the
106
112
  * findings in the same order, each with only the fixes that compile. Verdicts are kept in the
package/dist/checker.js CHANGED
@@ -145,6 +145,11 @@ export function createChecker({ config, cwd, rules = { kind: "configured" }, cac
145
145
  projectSummaries: (ruleId) => summaries.get(ruleId)?.(),
146
146
  }) ?? []);
147
147
  },
148
+ guarantees() {
149
+ return config.plugins.flatMap((plugin) => plugin.editor?.guarantees?.({
150
+ projectSummaries: (ruleId) => summaries.get(ruleId)?.(),
151
+ }) ?? []);
152
+ },
148
153
  reviewFixes(findings) {
149
154
  const units = (lastUnits ??= backend.open(new Map()));
150
155
  return reviewFixes(findings, units, cache === false ? localVerdicts : cache);
@@ -181,13 +186,24 @@ export function createChecker({ config, cwd, rules = { kind: "configured" }, cac
181
186
  hint: action.title,
182
187
  location: { file, start, end },
183
188
  related: [],
184
- fixes: [{ title: action.title, edits: action.edits }],
189
+ fixes: [
190
+ {
191
+ title: action.title,
192
+ edits: action.edits,
193
+ alternatives: (action.alternatives ?? []).map((form) => ({
194
+ title: action.title,
195
+ edits: form.edits,
196
+ })),
197
+ },
198
+ ],
185
199
  }));
186
200
  const units = (lastUnits ??= backend.open(new Map()));
187
201
  const reviews = reviewFixes(findings, units, cache === false ? localVerdicts : cache);
188
- return offered.filter((_, i) => {
202
+ // Each action as the first of its forms that compiles.
203
+ return offered.flatMap((action, i) => {
189
204
  const reviewed = reviews[i]?.finding;
190
- return reviewed?.kind === "problem" && reviewed.fixes.length > 0;
205
+ const form = reviewed?.kind === "problem" ? reviewed.fixes[0] : undefined;
206
+ return form === undefined ? [] : [{ title: action.title, edits: form.edits }];
191
207
  });
192
208
  },
193
209
  inlayHints(file, enabled = () => true) {
package/dist/config.js CHANGED
@@ -78,6 +78,7 @@ const isSummarize = (value) => typeof value === "function";
78
78
  const isSilentReason = (value) => typeof value === "function";
79
79
  const isHover = (value) => typeof value === "function";
80
80
  const isInlayHints = (value) => typeof value === "function";
81
+ const isGuarantees = (value) => typeof value === "function";
81
82
  const isCodeActions = (value) => typeof value === "function";
82
83
  const isTokens = (value) => typeof value === "function";
83
84
  const isLibraryFacts = (value) => typeof value === "function";
@@ -200,6 +201,19 @@ function parseMeta(value, where, errors) {
200
201
  return undefined;
201
202
  return { ...info, explain: value.explain };
202
203
  }
204
+ /** `RuleInfo.needsTypes` as given: undefined when left out, "invalid" when not a `LibraryTypes`. */
205
+ function parseNeedsTypes(value) {
206
+ if (value === undefined)
207
+ return undefined;
208
+ if (!isRecord(value))
209
+ return "invalid";
210
+ const { library, modules } = value;
211
+ if (typeof library !== "string" || library === "")
212
+ return "invalid";
213
+ if (!isStringArray(modules) || modules.length === 0)
214
+ return "invalid";
215
+ return { library, modules: [...modules] };
216
+ }
203
217
  /** The metadata a pack declares up front (`RuleInfo`): everything but the `explain` text. */
204
218
  function parseInfo(value, where, errors) {
205
219
  const found = parseInfoFields(value, where, errors);
@@ -211,12 +225,29 @@ function parseInfo(value, where, errors) {
211
225
  errors.push(`${where}.meta.sharedOptions must map option names to rule keys of the same pack`);
212
226
  return undefined;
213
227
  }
214
- const info = shared === undefined
228
+ const sharing = shared === undefined
215
229
  ? found
216
230
  : {
217
231
  ...found,
218
232
  sharedOptions: Object.fromEntries(Object.entries(shared).map(([name, rule]) => [name, String(rule)])),
219
233
  };
234
+ const { fixNeedsStrictNulls } = value;
235
+ const needsTypes = parseNeedsTypes(value.needsTypes);
236
+ if (needsTypes === "invalid") {
237
+ errors.push(`${where}.meta.needsTypes must be { library: "<name>", modules: ["<module>", …] } when present`);
238
+ return undefined;
239
+ }
240
+ if (fixNeedsStrictNulls !== undefined && fixNeedsStrictNulls !== true) {
241
+ errors.push(`${where}.meta.fixNeedsStrictNulls must be true when present`);
242
+ return undefined;
243
+ }
244
+ const typed = needsTypes === undefined
245
+ ? sharing
246
+ : {
247
+ ...sharing,
248
+ needsTypes,
249
+ };
250
+ const info = fixNeedsStrictNulls === true ? { ...typed, fixNeedsStrictNulls: true } : typed;
220
251
  if (value.options === undefined)
221
252
  return info;
222
253
  const options = parseOptionSpecs(value.options, where, errors);
@@ -227,12 +258,16 @@ function parseInfoFields(value, where, errors) {
227
258
  errors.push(`${where}.meta must be an object`);
228
259
  return undefined;
229
260
  }
230
- const { description, defaultSeverity, tier, group, addon, heuristic, widenedBy } = value;
261
+ const { description, summary, defaultSeverity, tier, group, addon, heuristic, widenedBy } = value;
231
262
  const { needsJsDoc, listUnknowns, yieldsTo } = value;
232
263
  if (typeof description !== "string") {
233
264
  errors.push(`${where}.meta.description must be a string`);
234
265
  return undefined;
235
266
  }
267
+ if (summary !== undefined && typeof summary !== "string") {
268
+ errors.push(`${where}.meta.summary must be a string when present`);
269
+ return undefined;
270
+ }
236
271
  if (!isSeverity(defaultSeverity)) {
237
272
  errors.push(`${where}.meta.defaultSeverity must be "error", "warning" or "info"`);
238
273
  return undefined;
@@ -257,7 +292,8 @@ function parseInfoFields(value, where, errors) {
257
292
  errors.push(`${where}.meta.group must name the rule's group in kebab-case, e.g. "switches"`);
258
293
  return undefined;
259
294
  }
260
- const base = { description, defaultSeverity, tier, group };
295
+ const described = { description, defaultSeverity, tier, group };
296
+ const base = summary === undefined ? described : { ...described, summary };
261
297
  const guessed = heuristic === true ? { ...base, heuristic: true } : base;
262
298
  const reading = needsJsDoc === true ? { ...guessed, needsJsDoc: true } : guessed;
263
299
  const listing = listUnknowns === true ? { ...reading, listUnknowns: true } : reading;
@@ -329,7 +365,7 @@ function parseEditor(value, where, errors) {
329
365
  errors.push(`${where}.editor must be an object`);
330
366
  return undefined;
331
367
  }
332
- const { hover, tokens, libraryFacts, inlayHints, codeActions } = value;
368
+ const { hover, tokens, libraryFacts, inlayHints, codeActions, guarantees } = value;
333
369
  const editor = {};
334
370
  if (codeActions !== undefined) {
335
371
  if (!isCodeActions(codeActions)) {
@@ -352,6 +388,13 @@ function parseEditor(value, where, errors) {
352
388
  }
353
389
  editor.libraryFacts = libraryFacts;
354
390
  }
391
+ if (guarantees !== undefined) {
392
+ if (!isGuarantees(guarantees)) {
393
+ errors.push(`${where}.editor.guarantees must be a function`);
394
+ return undefined;
395
+ }
396
+ editor.guarantees = guarantees;
397
+ }
355
398
  if (hover !== undefined) {
356
399
  if (!isHover(hover)) {
357
400
  errors.push(`${where}.editor.hover must be a function`);
@@ -9,10 +9,32 @@ import type { ResultCache } from "./cache.js";
9
9
  */
10
10
  /** Where `stateward check` and the language server keep their cache, unless STATEWARD_CACHE_DIR says otherwise. */
11
11
  export declare const CACHE_SUBDIR: string;
12
- /** The cache folder for a project: STATEWARD_CACHE_DIR, else node_modules/.cache/stateward when node_modules exists. */
12
+ /** The folder beside the project used when there is neither node_modules nor a user cache folder. */
13
+ export declare const PROJECT_CACHE_DIR = ".stateward-cache";
14
+ /** What `defaultCacheDir` reads of the machine: the home folder ("" when unknown) and the platform. */
15
+ export type CacheMachine = {
16
+ readonly home: string;
17
+ readonly platform: NodeJS.Platform;
18
+ };
19
+ /**
20
+ * The user's cache folder of the platform: XDG_CACHE_HOME or ~/.cache on Linux and others,
21
+ * ~/Library/Caches on macOS, LOCALAPPDATA on Windows; undefined when none is known.
22
+ */
23
+ export declare function userCacheDir(env: {
24
+ XDG_CACHE_HOME?: string | undefined;
25
+ LOCALAPPDATA?: string | undefined;
26
+ }, machine?: CacheMachine): string | undefined;
27
+ /**
28
+ * The cache folder for a project: STATEWARD_CACHE_DIR; else node_modules/.cache/stateward when
29
+ * node_modules exists; else a folder of the user's cache folder named after the project's path
30
+ * (an app checked before its packages are installed, user trial 1.0.2); else
31
+ * `.stateward-cache` in the project.
32
+ */
13
33
  export declare function defaultCacheDir(project: string, env: {
14
34
  STATEWARD_CACHE_DIR?: string | undefined;
15
- }): string | undefined;
35
+ XDG_CACHE_HOME?: string | undefined;
36
+ LOCALAPPDATA?: string | undefined;
37
+ }, machine?: CacheMachine): string;
16
38
  /** The results cache's size limit unless STATEWARD_CACHE_MAX_MB sets another. */
17
39
  export declare const RESULTS_CACHE_DEFAULT_MB = 200;
18
40
  /** The size limit of a results cache folder in bytes: STATEWARD_CACHE_MAX_MB, else 200 MB. */
@@ -1,5 +1,6 @@
1
1
  import { createHash, randomBytes } from "node:crypto";
2
2
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, rmdirSync, unlinkSync, writeFileSync, } from "node:fs";
3
+ import { homedir } from "node:os";
3
4
  import path from "node:path";
4
5
  import { emptyCache, parseSnapshot, toSnapshot } from "./cache.js";
5
6
  import { cacheEntries, dropLeastRecentlyUsed, limitBytes, markUsed } from "./disk-limits.js";
@@ -15,14 +16,51 @@ import { statewardVersion } from "./package-cache.js";
15
16
  */
16
17
  /** Where `stateward check` and the language server keep their cache, unless STATEWARD_CACHE_DIR says otherwise. */
17
18
  export const CACHE_SUBDIR = path.join("node_modules", ".cache", "stateward");
18
- /** The cache folder for a project: STATEWARD_CACHE_DIR, else node_modules/.cache/stateward when node_modules exists. */
19
- export function defaultCacheDir(project, env) {
19
+ /** The folder beside the project used when there is neither node_modules nor a user cache folder. */
20
+ export const PROJECT_CACHE_DIR = ".stateward-cache";
21
+ function thisMachine() {
22
+ let home = "";
23
+ try {
24
+ home = homedir();
25
+ }
26
+ catch {
27
+ // No home folder (a service account): the project's own folder is used.
28
+ }
29
+ return { home, platform: process.platform };
30
+ }
31
+ /**
32
+ * The user's cache folder of the platform: XDG_CACHE_HOME or ~/.cache on Linux and others,
33
+ * ~/Library/Caches on macOS, LOCALAPPDATA on Windows; undefined when none is known.
34
+ */
35
+ export function userCacheDir(env, machine = thisMachine()) {
36
+ const given = (value) => value !== undefined && path.isAbsolute(value) ? value : undefined;
37
+ if (machine.platform === "win32")
38
+ return given(env.LOCALAPPDATA);
39
+ if (machine.home === "")
40
+ return given(env.XDG_CACHE_HOME);
41
+ if (machine.platform === "darwin")
42
+ return path.join(machine.home, "Library", "Caches");
43
+ return given(env.XDG_CACHE_HOME) ?? path.join(machine.home, ".cache");
44
+ }
45
+ /**
46
+ * The cache folder for a project: STATEWARD_CACHE_DIR; else node_modules/.cache/stateward when
47
+ * node_modules exists; else a folder of the user's cache folder named after the project's path
48
+ * (an app checked before its packages are installed, user trial 1.0.2); else
49
+ * `.stateward-cache` in the project.
50
+ */
51
+ export function defaultCacheDir(project, env, machine = thisMachine()) {
20
52
  const override = env.STATEWARD_CACHE_DIR;
21
53
  if (override !== undefined && override !== "")
22
54
  return path.resolve(project, override);
23
- return existsSync(path.join(project, "node_modules"))
24
- ? path.join(project, CACHE_SUBDIR)
25
- : undefined;
55
+ if (existsSync(path.join(project, "node_modules")))
56
+ return path.join(project, CACHE_SUBDIR);
57
+ const user = userCacheDir(env, machine);
58
+ if (user === undefined)
59
+ return path.join(project, PROJECT_CACHE_DIR);
60
+ const resolved = path.resolve(project);
61
+ const key = createHash("sha256").update(resolved).digest("hex").slice(0, 16);
62
+ const name = path.basename(resolved).replace(/[^\w.-]/g, "_") || "project";
63
+ return path.join(user, "stateward", "results", `${name}-${key}`);
26
64
  }
27
65
  /** The results cache's size limit unless STATEWARD_CACHE_MAX_MB sets another. */
28
66
  export const RESULTS_CACHE_DEFAULT_MB = 200;