@stateward/core 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,6 +5,7 @@ import { codeOnOneLine } from "../code-text.js";
5
5
  import { computeFingerprints, declarationTextHash, packageDependencies, packageEntries, packageManifests, packageNames, } from "./fingerprints.js";
6
6
  import { markedComments } from "./comments.js";
7
7
  import { recordInputs, recordingHost, replays } from "./program-record.js";
8
+ import { programSize } from "./program-size.js";
8
9
  import { declarationAtPath, declarationPath } from "./qualified-ids.js";
9
10
  import { displayPath } from "../display-path.js";
10
11
  import { expandTsconfigs } from "../tsconfigs.js";
@@ -643,6 +644,25 @@ function readTsconfig(given) {
643
644
  * dominates a check of a small project, so one parse serves every later check.
644
645
  */
645
646
  const libraryCache = new Map();
647
+ /**
648
+ * Drops the parsed library files no program in `live` holds. After a program is let go (a check
649
+ * that builds one project at a time), its libraries would otherwise stay parsed and bound for the
650
+ * rest of the run, so the projects' libraries add up instead of the largest one counting.
651
+ */
652
+ function keepLibrariesOf(live) {
653
+ const used = new Set();
654
+ for (const program of live)
655
+ for (const sourceFile of program.getSourceFiles())
656
+ used.add(sourceFile);
657
+ for (const [key, cached] of libraryCache) {
658
+ if (!used.has(cached.sourceFile))
659
+ libraryCache.delete(key);
660
+ }
661
+ }
662
+ /** The library files parsed and kept for later programs (tests). */
663
+ export function cachedLibraryFiles() {
664
+ return [...libraryCache.values()].map((cached) => cached.sourceFile.fileName);
665
+ }
646
666
  const DEFAULT_LIB_DIRECTORY = toTypeScriptPath(path.dirname(ts.getDefaultLibFilePath({})));
647
667
  function isLibraryFile(fileName) {
648
668
  return fileName.startsWith(DEFAULT_LIB_DIRECTORY) || fileName.includes("/node_modules/");
@@ -856,7 +876,7 @@ function genericBaseOfType(checker, start, inPackage, names) {
856
876
  declaration !== undefined &&
857
877
  instance === checker.getDeclaredTypeOfSymbol(symbol)
858
878
  ? { kind: "class", name: symbol.getName(), declaration }
859
- : { kind: "other", text: checker.typeToString(type) };
879
+ : { kind: "other", text: stableTypeText(checker, type) };
860
880
  };
861
881
  const seen = new Set();
862
882
  let level = [{ type: only, given: new Map() }];
@@ -1902,7 +1922,7 @@ function typeShape(isPlatformFile, checker, type, inside) {
1902
1922
  // The type's identity: two types of one name (`billing.Address`, `shipping.Address`) differ.
1903
1923
  const first = declarations[0];
1904
1924
  const id = first === undefined
1905
- ? checker.typeToString(type, undefined, ts.TypeFormatFlags.NoTruncation)
1925
+ ? stableTypeText(checker, type, "whole")
1906
1926
  : `${first.getSourceFile().fileName}:${String(first.pos)}`;
1907
1927
  if (inside.includes(type)) {
1908
1928
  return name === undefined ? undefined : { kind: "recursive", id, name };
@@ -1930,7 +1950,7 @@ function typeShape(isPlatformFile, checker, type, inside) {
1930
1950
  shape,
1931
1951
  });
1932
1952
  }
1933
- const text = name ?? checker.typeToString(type, undefined, ts.TypeFormatFlags.NoTruncation);
1953
+ const text = name ?? stableTypeText(checker, type, "whole");
1934
1954
  return { kind: "object", id, name, text: text.replace(/\s+/g, " ").trim(), properties };
1935
1955
  }
1936
1956
  function withoutNullish(type) {
@@ -4165,6 +4185,81 @@ function decoratorMetadata(options, context, node) {
4165
4185
  withoutNullish: serializedTypeNode({ ...context, keepsNullish: false }, typeNode),
4166
4186
  };
4167
4187
  }
4188
+ /**
4189
+ * The first declaration of `symbol`. A symbol the checker made (a property of a union of object
4190
+ * types) lists its declarations in the order of the union's members, which follows what the
4191
+ * checker created first (see `stableTypeText`): its first by place (file, then offset) instead.
4192
+ */
4193
+ function placedFirst(symbol) {
4194
+ const all = symbol.declarations ?? [];
4195
+ if ((symbol.flags & ts.SymbolFlags.Transient) === 0 || all.length < 2)
4196
+ return all[0];
4197
+ return all.reduce((first, one) => {
4198
+ const a = first.getSourceFile().fileName;
4199
+ const b = one.getSourceFile().fileName;
4200
+ return b < a || (b === a && one.pos < first.pos) ? one : first;
4201
+ });
4202
+ }
4203
+ /** `typeToString`'s own limit: printed text this long or longer ends in "...". */
4204
+ const TYPE_TEXT_LIMIT = 320;
4205
+ /** The file a printed type node is printed against: it has no text of its own to read. */
4206
+ const PRINTED_TYPE_FILE = ts.createSourceFile("type.ts", "", ts.ScriptTarget.Latest);
4207
+ const typePrinter = ts.createPrinter({ removeComments: true });
4208
+ /** Where a union member goes: `null`, then `undefined`, after every other member. */
4209
+ function nullishRank(node) {
4210
+ if (ts.isLiteralTypeNode(node) && node.literal.kind === ts.SyntaxKind.NullKeyword)
4211
+ return 1;
4212
+ return node.kind === ts.SyntaxKind.UndefinedKeyword ? 2 : 0;
4213
+ }
4214
+ function printedType(node) {
4215
+ return typePrinter.printNode(ts.EmitHint.Unspecified, node, PRINTED_TYPE_FILE);
4216
+ }
4217
+ /** Every union in `node`, at any depth, with its members in `stableTypeText`'s order. */
4218
+ function withSortedUnions(node) {
4219
+ const sorting = (context) => {
4220
+ const visit = (child) => {
4221
+ const inner = ts.visitEachChild(child, visit, context);
4222
+ if (!ts.isUnionTypeNode(inner))
4223
+ return inner;
4224
+ const keyed = inner.types.map((member) => ({
4225
+ member,
4226
+ rank: nullishRank(member),
4227
+ text: printedType(member),
4228
+ }));
4229
+ keyed.sort((a, b) => a.rank - b.rank || (a.text < b.text ? -1 : a.text > b.text ? 1 : 0));
4230
+ return context.factory.updateUnionTypeNode(inner, context.factory.createNodeArray(keyed.map(({ member }) => member)));
4231
+ };
4232
+ return visit;
4233
+ };
4234
+ const result = ts.transform(node, [sorting]);
4235
+ const [sorted] = result.transformed;
4236
+ result.dispose();
4237
+ return sorted ?? node;
4238
+ }
4239
+ /**
4240
+ * A type as `typeToString` prints it, except that the members of every union are in a fixed
4241
+ * order: by their own printed text, with `null` and `undefined` last. TypeScript prints a union's
4242
+ * members in the order their types were created, which follows what the checker was asked before:
4243
+ * the same code printed `J | I` after another file mentioned `J` first, and `I | J` with a new
4244
+ * checker. Text that rules show must be the same for the same code (SW5).
4245
+ *
4246
+ * The type is built whole and cut at the end: TypeScript's own shortening drops members past a
4247
+ * length, and which ones depends on that same order.
4248
+ */
4249
+ function stableTypeText(checker, type,
4250
+ /** `whole`: never cut (`TypeFormatFlags.NoTruncation`), for text a fix writes into the code. */
4251
+ length = "cut") {
4252
+ const node = checker.typeToTypeNode(type, undefined, ts.NodeBuilderFlags.AllowUniqueESSymbolType |
4253
+ ts.NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope |
4254
+ ts.NodeBuilderFlags.IgnoreErrors |
4255
+ ts.NodeBuilderFlags.NoTruncation);
4256
+ if (node === undefined)
4257
+ return checker.typeToString(type);
4258
+ const text = printedType(withSortedUnions(node));
4259
+ return length === "cut" && text.length >= TYPE_TEXT_LIMIT
4260
+ ? `${text.slice(0, TYPE_TEXT_LIMIT - 3)}...`
4261
+ : text;
4262
+ }
4168
4263
  export function createTypeQueries(program, own,
4169
4264
  /** The project folder qualified ids are relative to. */
4170
4265
  root, packageOf, isEntry, dependenciesOf,
@@ -4202,7 +4297,7 @@ platform = []) {
4202
4297
  const refsByNode = new WeakMap();
4203
4298
  const refsBySymbol = new WeakMap();
4204
4299
  const refOfSymbol = (symbol) => {
4205
- const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0];
4300
+ const declaration = symbol.valueDeclaration ?? placedFirst(symbol);
4206
4301
  if (declaration === undefined)
4207
4302
  return undefined;
4208
4303
  const id = `${idFileName(declaration.getSourceFile().fileName)}#${declarationPath(declaration)}`;
@@ -4478,16 +4573,15 @@ platform = []) {
4478
4573
  (checker.isTypeAssignableTo(left, right) && checker.isTypeAssignableTo(right, left)));
4479
4574
  },
4480
4575
  typeTextOf(node) {
4481
- return typeChecker()
4482
- .typeToString(typeChecker().getTypeAtLocation(node))
4483
- .replace(/\s+/g, " ")
4484
- .trim();
4576
+ const checker = typeChecker();
4577
+ return stableTypeText(checker, checker.getTypeAtLocation(node)).replace(/\s+/g, " ").trim();
4485
4578
  },
4486
4579
  contextualTypeTextOf(node) {
4487
- const type = typeChecker().getContextualType(node);
4580
+ const checker = typeChecker();
4581
+ const type = checker.getContextualType(node);
4488
4582
  return type === undefined
4489
4583
  ? undefined
4490
- : typeChecker().typeToString(type).replace(/\s+/g, " ").trim();
4584
+ : stableTypeText(checker, type).replace(/\s+/g, " ").trim();
4491
4585
  },
4492
4586
  expectsPromiseReturn(node) {
4493
4587
  const checker = typeChecker();
@@ -5096,7 +5190,7 @@ platform = []) {
5096
5190
  return undefined;
5097
5191
  return {
5098
5192
  keyKind: stringInfo === undefined ? "number" : "string",
5099
- valueText: typeChecker().typeToString(info.type, undefined, ts.TypeFormatFlags.NoTruncation),
5193
+ valueText: stableTypeText(typeChecker(), info.type, "whole"),
5100
5194
  valueCanBeUndefined: includesUndefined(info.type),
5101
5195
  };
5102
5196
  },
@@ -5163,7 +5257,7 @@ platform = []) {
5163
5257
  const members = own.isUnion() ? own.types : [own];
5164
5258
  return {
5165
5259
  name: property.getName(),
5166
- text: checker.typeToString(own).replace(/\s+/g, " ").trim(),
5260
+ text: stableTypeText(checker, own).replace(/\s+/g, " ").trim(),
5167
5261
  optional: (property.flags & ts.SymbolFlags.Optional) !== 0,
5168
5262
  open: (own.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0,
5169
5263
  platform: platformNameOf(own) ?? null,
@@ -5341,6 +5435,8 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
5341
5435
  /** The last program of each project, what it was built from, and its unit. */
5342
5436
  const previous = new Map();
5343
5437
  const caches = new Map();
5438
+ /** A program was let go since the last build: the next build drops the libraries only it held. */
5439
+ let released = false;
5344
5440
  /** What the last `open` found: the projects, their own files, and every own file of all of them. */
5345
5441
  let last;
5346
5442
  /** The program of one project, built now, as a unit; recorded for the next run when it can be. */
@@ -5363,12 +5459,16 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
5363
5459
  const packageOf = packageNames(host);
5364
5460
  const isEntry = packageEntries(host);
5365
5461
  const dependenciesOf = packageDependencies(host);
5366
- const program = ts.createProgram({
5462
+ let program = ts.createProgram({
5367
5463
  rootNames: parsed.fileNames,
5368
5464
  options: parsed.options,
5369
5465
  host,
5370
5466
  ...(oldProgram === undefined ? {} : { oldProgram: oldProgram.program }),
5371
5467
  });
5468
+ if (released) {
5469
+ released = false;
5470
+ keepLibrariesOf([program, ...[...previous.values()].map((kept) => kept.program)]);
5471
+ }
5372
5472
  const inputs = programInputs(parsed, claimed);
5373
5473
  // Nothing changed (the full pass right after a fast pass on the same text): keep the old
5374
5474
  // program, its type checker and what that checker already computed, instead of a second
@@ -5419,7 +5519,14 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
5419
5519
  };
5420
5520
  /** What each file's rules were handed, by file: read ids, with the file each one is in. */
5421
5521
  const reads = new Map();
5422
- const types = createTypeQueries(program, claimed, cwd, packageOf, isEntry, dependenciesOf, config.platform);
5522
+ const queriesOf = (built) => createTypeQueries(built, claimed, cwd, packageOf, isEntry, dependenciesOf, config.platform);
5523
+ let types = queriesOf(program);
5524
+ /** Whether something may have asked `types` a question (creating the checker) since it started. */
5525
+ let asked = false;
5526
+ const askedTypes = () => {
5527
+ asked = true;
5528
+ return types;
5529
+ };
5423
5530
  const idFileName = idFileNames(cwd);
5424
5531
  const fileId = (fileName) => `${idFileName(fileName)}#`;
5425
5532
  /** The read id of a declaration handed out: its own id when that finds it again, else its file's. */
@@ -5442,15 +5549,18 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
5442
5549
  files,
5443
5550
  listedElsewhere: (file) => shared.has(file),
5444
5551
  sourceFile: (file) => program.getSourceFile(file),
5445
- types,
5552
+ get types() {
5553
+ return askedTypes();
5554
+ },
5446
5555
  fingerprint: (file) => fingerprintsOf().get(file),
5447
5556
  typesFor: (file) => {
5448
5557
  const read = reads.get(file) ?? new Map();
5449
5558
  reads.set(file, read);
5559
+ const fileTypes = askedTypes();
5450
5560
  return {
5451
- ...types,
5561
+ ...fileTypes,
5452
5562
  declarationOf(symbol) {
5453
- const found = types.declarationOf(symbol);
5563
+ const found = fileTypes.declarationOf(symbol);
5454
5564
  if (found !== undefined && found.file !== file) {
5455
5565
  read.set(readId(symbol, found), found.file);
5456
5566
  }
@@ -5487,14 +5597,34 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
5487
5597
  unreadTestConfigs,
5488
5598
  typesResolve: typesResolver(tsconfigPath, parsed.options),
5489
5599
  factKeys: (facts) => {
5490
- const checks = checkFactKeys(facts, types);
5600
+ const checks = checkFactKeys(facts, askedTypes());
5491
5601
  factChecks[factKeysDigest(facts)] = JSON.stringify(checks);
5492
5602
  return checks;
5493
5603
  },
5494
5604
  importsModule: (module) => importsModuleIn(importsOf(), module),
5495
5605
  bind: () => {
5606
+ asked = true;
5496
5607
  program.getTypeChecker();
5497
5608
  },
5609
+ renewChecker: () => {
5610
+ if (!asked)
5611
+ return;
5612
+ asked = false;
5613
+ // Served from the parsed files kept for this project (trusted, so nothing is read from
5614
+ // disk again): every file is the same object, so TypeScript reuses the whole structure
5615
+ // and binds nothing again. Only the checker is new.
5616
+ program = ts.createProgram({
5617
+ rootNames: parsed.fileNames,
5618
+ options: parsed.options,
5619
+ host: hostWithOverlays(parsed.options, overlays, sources, true, jsDoc),
5620
+ oldProgram: program,
5621
+ });
5622
+ types = queriesOf(program);
5623
+ // The next `open` builds on the newest program; the old one, and its checker, can go.
5624
+ const kept = previous.get(tsconfigPath);
5625
+ if (kept?.unit === unit)
5626
+ previous.set(tsconfigPath, { ...kept, program });
5627
+ },
5498
5628
  ignoreComments: (file) => {
5499
5629
  const sourceFile = program.getSourceFile(file);
5500
5630
  return sourceFile === undefined
@@ -5548,28 +5678,47 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
5548
5678
  bind: () => {
5549
5679
  real().bind();
5550
5680
  },
5681
+ renewChecker: () => {
5682
+ built?.renewChecker();
5683
+ },
5551
5684
  ignoreComments: (file) => real().ignoreComments(file),
5552
5685
  tryEdits: (candidates) => real().tryEdits(candidates),
5553
5686
  };
5554
5687
  };
5555
- const build = (projects, claimed, overlays, trustCache) => {
5688
+ const unitOf = (project, claimed, overlays, trustCache) => {
5689
+ const record = cache?.programs.get(project.tsconfigPath);
5690
+ const replayable = record !== undefined &&
5691
+ !previous.has(project.tsconfigPath) &&
5692
+ !trustCache &&
5693
+ record.inputs ===
5694
+ recordInputs(programInputs(project.parsed, claimed), project.parsed.options) &&
5695
+ replays(record.queries, replayHost(project.parsed.options, overlays));
5696
+ return replayable
5697
+ ? recordedUnit(project, claimed, record, overlays)
5698
+ : buildUnit(project, claimed, overlays, trustCache);
5699
+ };
5700
+ const pendingUnits = (projects, claimed, overlays, trustCache) => {
5556
5701
  const normalized = new Map([...overlays].map(([file, text]) => [toTypeScriptPath(file), text]));
5557
5702
  return projects
5558
5703
  .filter((project) => project.own.length > 0)
5559
5704
  .map((project) => {
5560
- const record = cache?.programs.get(project.tsconfigPath);
5561
- const replayable = record !== undefined &&
5562
- !previous.has(project.tsconfigPath) &&
5563
- !trustCache &&
5564
- record.inputs ===
5565
- recordInputs(programInputs(project.parsed, claimed), project.parsed.options) &&
5566
- replays(record.queries, replayHost(project.parsed.options, normalized));
5567
- return replayable
5568
- ? recordedUnit(project, claimed, record, normalized)
5569
- : buildUnit(project, claimed, normalized, trustCache);
5705
+ let unit;
5706
+ let size;
5707
+ return {
5708
+ tsconfig: project.tsconfigPath,
5709
+ size: () => (size ??= programSize(project.parsed, project.own, normalized)),
5710
+ open: () => (unit ??= unitOf(project, claimed, normalized, trustCache)),
5711
+ release: () => {
5712
+ unit = undefined;
5713
+ previous.delete(project.tsconfigPath);
5714
+ caches.delete(project.tsconfigPath);
5715
+ released = true;
5716
+ },
5717
+ };
5570
5718
  });
5571
5719
  };
5572
- const open = (overlays) => {
5720
+ const build = (projects, claimed, overlays, trustCache) => pendingUnits(projects, claimed, overlays, trustCache).map((pending) => pending.open());
5721
+ const pending = (overlays) => {
5573
5722
  const entries = config.tsconfig.map((entry) => path.resolve(cwd, entry));
5574
5723
  const named = entries.map((entry) => displayPath(cwd, entry)).join("`, `");
5575
5724
  const { files: roots, unmatched } = expandTsconfigs(entries);
@@ -5596,13 +5745,16 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
5596
5745
  if (claimed.size === 0)
5597
5746
  throw new NothingToCheckError(named);
5598
5747
  last = { projects, claimed };
5599
- return build(projects, claimed, overlays, false);
5748
+ return pendingUnits(projects, claimed, overlays, false);
5600
5749
  };
5750
+ const open = (overlays) => pending(overlays).map((unit) => unit.open());
5601
5751
  return {
5602
5752
  open,
5753
+ pending,
5603
5754
  release: () => {
5604
5755
  previous.clear();
5605
5756
  caches.clear();
5757
+ released = true;
5606
5758
  },
5607
5759
  reopen: (overlays) => last === undefined ? open(overlays) : build(last.projects, last.claimed, overlays, true),
5608
5760
  };
package/dist/cache.d.ts CHANGED
@@ -19,7 +19,7 @@ import type { UnstatedPlace, Finding, FixVerdict, Json, PluginAnalysis, ReadOutc
19
19
  * server save it to disk between runs as a `CacheSnapshot` (disk-cache.ts).
20
20
  */
21
21
  /** Bumped whenever what is stored, or how a key is computed, changes. */
22
- export declare const CACHE_FORMAT = 17;
22
+ export declare const CACHE_FORMAT = 18;
23
23
  /**
24
24
  * A project rule's summary of one file: the hash of its JSON text, and either that text or, once a
25
25
  * rule or a hover needed the value (a run whose summaries are all unchanged never does), the parsed
@@ -62,6 +62,12 @@ export declare function summaryOf(value: Json): CachedSummary;
62
62
  export declare function summaryFromText(text: string, hash: string): CachedSummary;
63
63
  /** The summary's value, parsed from its text once and frozen; the text is then let go. */
64
64
  export declare function summaryValue(summary: CachedSummary): Json;
65
+ /**
66
+ * The hash of the JSON text of a summary the engine handed to a project rule's `check`, an
67
+ * analysis's `solve` or an editor contribution: equal hashes are equal summaries. Undefined for a
68
+ * value the engine did not hand out (one a test built), and for `null` or a primitive.
69
+ */
70
+ export declare function summaryHash(value: Json): string | undefined;
65
71
  /**
66
72
  * The summary's JSON text: kept, or written again from the parsed value. JSON text parsed and
67
73
  * written again is the same text (`JSON.stringify` wrote it), so the hash still matches it.
@@ -99,6 +105,12 @@ export type AnalysisEntry = {
99
105
  fingerprint: string;
100
106
  /** That value, kept in memory only (undefined when the entry came from disk). */
101
107
  value?: Json;
108
+ /**
109
+ * The summaries it was solved from, as `solve` and the publisher's own rules received them:
110
+ * the same map while they are unchanged, so a solver's memo keyed by the map holds. Kept in
111
+ * memory only.
112
+ */
113
+ summaries?: ReadonlyMap<string, Json>;
102
114
  };
103
115
  export type ResultCache = {
104
116
  files: Map<string, FileEntry>;
@@ -123,17 +135,29 @@ export type ResultCache = {
123
135
  * Entries under a key no recent run used are dropped when the cache is saved (`pruneUnused`).
124
136
  */
125
137
  used: Map<string, number>;
138
+ /**
139
+ * Told of each file as the file phase starts it and once its results are final, so a run that
140
+ * dies keeps what it finished (the CLI's journal, disk-cache.ts). Absent: nobody is told.
141
+ */
142
+ progress?: FileProgress | undefined;
143
+ };
144
+ /** What the file phase tells of each file (`ResultCache.progress`). */
145
+ export type FileProgress = {
146
+ started(file: string): void;
147
+ /** `entry` holds `file`'s results of this run, final. */
148
+ finished(file: string, entry: FileEntry): void;
126
149
  };
127
150
  /** Entries no run among the last this many used are dropped when the cache is saved. */
128
151
  export declare const KEEP_RUNS = 3;
129
152
  /** Notes that this run uses the entries under `key`, so a save keeps them. */
130
153
  export declare function useKey(cache: ResultCache, key: string): void;
131
154
  /**
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.
155
+ * Drops the entries under keys that none of the last `runs` runs used (`KEEP_RUNS` by default):
156
+ * the results of a rule or an analysis under an earlier config or code, and verdicts of fixes no
157
+ * longer shown. Without it, a cache kept every key it ever held and grew past what can be written.
158
+ * `runs = 1` keeps only what this run used. Returns whether anything was dropped.
135
159
  */
136
- export declare function pruneUnused(cache: ResultCache): void;
160
+ export declare function pruneUnused(cache: ResultCache, runs?: number): boolean;
137
161
  export declare function emptyCache(): ResultCache;
138
162
  export declare function sha1(text: string): string;
139
163
  /**
@@ -195,29 +219,23 @@ export type CacheSnapshot = {
195
219
  /** `ResultCache.used`. */
196
220
  used: Record<string, number>;
197
221
  };
222
+ type FileSnapshot = CacheSnapshot["files"][string];
223
+ /** One file's results as plain JSON (`CacheSnapshot.files`); read back with `parseFileEntry`. */
224
+ export declare function fileSnapshot(entry: FileEntry): FileSnapshot;
198
225
  export declare function toSnapshot(cache: ResultCache): CacheSnapshot;
199
226
  /**
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.
227
+ * The snapshot's JSON text in pieces, for a writer that never holds the whole text (a large
228
+ * project's is more than one string can hold): `toSnapshot`'s value, one file's results per piece.
212
229
  */
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 = "}}";
230
+ export declare function snapshotChunks(cache: ResultCache): Generator<string>;
216
231
  export declare function isJson(value: unknown): value is Json;
217
232
  export declare function parseFinding(value: unknown): Finding | undefined;
233
+ /** One file's results as `fileSnapshot` wrote them; undefined when anything has another shape. */
234
+ export declare function parseFileEntry(entry: unknown): FileEntry | undefined;
218
235
  /**
219
236
  * A cache read back from JSON. Anything that does not have the expected shape, or another format,
220
237
  * is an empty cache: a broken cache costs a cold run, never findings (workspace C35).
221
238
  */
222
239
  export declare function parseSnapshot(value: unknown): ResultCache;
240
+ export {};
223
241
  //# sourceMappingURL=cache.d.ts.map
package/dist/cache.js CHANGED
@@ -19,7 +19,7 @@ import { isQueryKind } from "./backend/program-record.js";
19
19
  * server save it to disk between runs as a `CacheSnapshot` (disk-cache.ts).
20
20
  */
21
21
  /** Bumped whenever what is stored, or how a key is computed, changes. */
22
- export const CACHE_FORMAT = 17;
22
+ export const CACHE_FORMAT = 18;
23
23
  /** Frozen all the way down: a cached summary is shared between runs, so no rule may change it. */
24
24
  export function deepFreeze(value) {
25
25
  if (typeof value === "object" && value !== null) {
@@ -41,6 +41,8 @@ export function summaryOf(value) {
41
41
  export function summaryFromText(text, hash) {
42
42
  return { hash, form: { kind: "text", text } };
43
43
  }
44
+ /** The hash of each summary value handed out (`summaryValue`), by the value. */
45
+ const hashes = new WeakMap();
44
46
  /** The summary's value, parsed from its text once and frozen; the text is then let go. */
45
47
  export function summaryValue(summary) {
46
48
  const { form } = summary;
@@ -48,9 +50,19 @@ export function summaryValue(summary) {
48
50
  return form.value;
49
51
  const parsed = JSON.parse(form.text);
50
52
  const value = deepFreeze(isJson(parsed) ? parsed : null);
53
+ if (typeof value === "object" && value !== null)
54
+ hashes.set(value, summary.hash);
51
55
  summary.form = { kind: "parsed", value };
52
56
  return value;
53
57
  }
58
+ /**
59
+ * The hash of the JSON text of a summary the engine handed to a project rule's `check`, an
60
+ * analysis's `solve` or an editor contribution: equal hashes are equal summaries. Undefined for a
61
+ * value the engine did not hand out (one a test built), and for `null` or a primitive.
62
+ */
63
+ export function summaryHash(value) {
64
+ return typeof value === "object" && value !== null ? hashes.get(value) : undefined;
65
+ }
54
66
  /**
55
67
  * The summary's JSON text: kept, or written again from the parsed value. JSON text parsed and
56
68
  * written again is the same text (`JSON.stringify` wrote it), so the hash still matches it.
@@ -67,15 +79,16 @@ export function useKey(cache, key) {
67
79
  cache.used.set(key, cache.run);
68
80
  }
69
81
  /**
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.
82
+ * Drops the entries under keys that none of the last `runs` runs used (`KEEP_RUNS` by default):
83
+ * the results of a rule or an analysis under an earlier config or code, and verdicts of fixes no
84
+ * longer shown. Without it, a cache kept every key it ever held and grew past what can be written.
85
+ * `runs = 1` keeps only what this run used. Returns whether anything was dropped.
73
86
  */
74
- export function pruneUnused(cache) {
75
- const oldest = cache.run - KEEP_RUNS + 1;
87
+ export function pruneUnused(cache, runs = KEEP_RUNS) {
88
+ const oldest = cache.run - runs + 1;
76
89
  const stale = new Set([...cache.used].filter(([, last]) => last < oldest).map(([key]) => key));
77
90
  if (stale.size === 0)
78
- return;
91
+ return false;
79
92
  for (const key of stale)
80
93
  cache.used.delete(key);
81
94
  // A key no run stamps (a file's own entries, such as its ignore comments) is kept with its file.
@@ -89,6 +102,7 @@ export function pruneUnused(cache) {
89
102
  if (stale.has(key))
90
103
  map.delete(key);
91
104
  }
105
+ return true;
92
106
  }
93
107
  export function emptyCache() {
94
108
  return {
@@ -145,7 +159,8 @@ export function analysisKey(input) {
145
159
  function byKey(entries) {
146
160
  return [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
147
161
  }
148
- function fileSnapshot(entry) {
162
+ /** One file's results as plain JSON (`CacheSnapshot.files`); read back with `parseFileEntry`. */
163
+ export function fileSnapshot(entry) {
149
164
  const rules = {};
150
165
  for (const [key, result] of entry.rules) {
151
166
  rules[key] = {
@@ -194,28 +209,25 @@ export function toSnapshot(cache) {
194
209
  return { ...smallParts(cache), files, projects };
195
210
  }
196
211
  /**
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.
212
+ * The snapshot's JSON text in pieces, for a writer that never holds the whole text (a large
213
+ * project's is more than one string can hold): `toSnapshot`'s value, one file's results per piece.
199
214
  */
200
215
  export function* snapshotChunks(cache) {
201
216
  const small = JSON.stringify(smallParts(cache));
202
- yield { kind: "part", text: `${small.slice(0, -1)},"projects":{` };
217
+ yield `${small.slice(0, -1)},"projects":{`;
203
218
  let first = true;
204
219
  for (const [key, entry] of byKey(cache.projects)) {
205
- yield {
206
- kind: "part",
207
- text: `${first ? "" : ","}${JSON.stringify(key)}:${JSON.stringify(projectSnapshot(entry))}`,
208
- };
220
+ yield `${first ? "" : ","}${JSON.stringify(key)}:${JSON.stringify(projectSnapshot(entry))}`;
209
221
  first = false;
210
222
  }
211
- yield { kind: "part", text: '},"files":{' };
223
+ yield '},"files":{';
224
+ first = true;
212
225
  for (const [file, entry] of byKey(cache.files)) {
213
- yield { kind: "entry", text: `${JSON.stringify(file)}:${JSON.stringify(fileSnapshot(entry))}` };
226
+ yield `${first ? "" : ","}${JSON.stringify(file)}:${JSON.stringify(fileSnapshot(entry))}`;
227
+ first = false;
214
228
  }
215
- yield { kind: "end", text: END_TEXT };
229
+ yield "}}";
216
230
  }
217
- /** The text that closes a snapshot's JSON: its files, then the snapshot. */
218
- export const END_TEXT = "}}";
219
231
  function isFields(value) {
220
232
  return typeof value === "object" && value !== null && !Array.isArray(value);
221
233
  }
@@ -477,6 +489,37 @@ export function parseFinding(value) {
477
489
  ...(guarantees === undefined ? {} : { guarantees }),
478
490
  };
479
491
  }
492
+ /** One file's results as `fileSnapshot` wrote them; undefined when anything has another shape. */
493
+ export function parseFileEntry(entry) {
494
+ if (!isFields(entry) || typeof entry.fingerprint !== "string" || !isFields(entry.rules)) {
495
+ return undefined;
496
+ }
497
+ const reads = stringRecord(entry.reads);
498
+ if (reads === undefined)
499
+ return undefined;
500
+ const rules = new Map();
501
+ for (const [key, result] of Object.entries(entry.rules)) {
502
+ if (!isFields(result))
503
+ return undefined;
504
+ const findings = parseList(result.findings, parseFinding);
505
+ if (findings === undefined)
506
+ return undefined;
507
+ const { summary, hash } = result;
508
+ const marks = parseMarks(result.marks);
509
+ if (marks === undefined)
510
+ return undefined;
511
+ if (summary === undefined && hash === undefined) {
512
+ rules.set(key, { findings, ...marks });
513
+ }
514
+ else if (typeof summary === "string" && typeof hash === "string") {
515
+ rules.set(key, { findings, summary: summaryFromText(summary, hash), ...marks });
516
+ }
517
+ else {
518
+ return undefined;
519
+ }
520
+ }
521
+ return { fingerprint: entry.fingerprint, rules, reads: new Map(Object.entries(reads)) };
522
+ }
480
523
  /**
481
524
  * A cache read back from JSON. Anything that does not have the expected shape, or another format,
482
525
  * is an empty cache: a broken cache costs a cold run, never findings (workspace C35).
@@ -524,38 +567,10 @@ export function parseSnapshot(value) {
524
567
  cache.programs.set(tsconfig, parsed);
525
568
  }
526
569
  for (const [file, entry] of Object.entries(files)) {
527
- if (!isFields(entry) || typeof entry.fingerprint !== "string" || !isFields(entry.rules)) {
528
- return emptyCache();
529
- }
530
- const reads = stringRecord(entry.reads);
531
- if (reads === undefined)
570
+ const parsed = parseFileEntry(entry);
571
+ if (parsed === undefined)
532
572
  return emptyCache();
533
- const rules = new Map();
534
- for (const [key, result] of Object.entries(entry.rules)) {
535
- if (!isFields(result))
536
- return emptyCache();
537
- const findings = parseList(result.findings, parseFinding);
538
- if (findings === undefined)
539
- return emptyCache();
540
- const { summary, hash } = result;
541
- const marks = parseMarks(result.marks);
542
- if (marks === undefined)
543
- return emptyCache();
544
- if (summary === undefined && hash === undefined) {
545
- rules.set(key, { findings, ...marks });
546
- }
547
- else if (typeof summary === "string" && typeof hash === "string") {
548
- rules.set(key, { findings, summary: summaryFromText(summary, hash), ...marks });
549
- }
550
- else {
551
- return emptyCache();
552
- }
553
- }
554
- cache.files.set(file, {
555
- fingerprint: entry.fingerprint,
556
- rules,
557
- reads: new Map(Object.entries(reads)),
558
- });
573
+ cache.files.set(file, parsed);
559
574
  }
560
575
  for (const [key, entry] of Object.entries(projects)) {
561
576
  if (!isFields(entry) || typeof entry.inputs !== "string")