carrick 0.3.138 → 0.3.140

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 (33) hide show
  1. package/package.json +7 -6
  2. package/plugin/.claude-plugin/plugin.json +1 -1
  3. package/sidecar/dist/src/affected-set.d.ts +172 -0
  4. package/sidecar/dist/src/affected-set.js +936 -0
  5. package/sidecar/dist/src/capture/api.d.ts +34 -0
  6. package/sidecar/dist/src/capture/backfill.d.ts +37 -0
  7. package/sidecar/dist/src/capture/backfill.js +75 -0
  8. package/sidecar/dist/src/capture/index.js +419 -133
  9. package/sidecar/dist/src/capture/installed-package.js +36 -29
  10. package/sidecar/dist/src/capture/self-check.d.ts +14 -3
  11. package/sidecar/dist/src/capture/self-check.js +168 -30
  12. package/sidecar/dist/src/index.js +84 -14
  13. package/sidecar/dist/src/infer-cache.d.ts +0 -8
  14. package/sidecar/dist/src/infer-cache.js +0 -14
  15. package/sidecar/dist/src/library-claims.js +4 -3
  16. package/sidecar/dist/src/module-format.d.ts +13 -2
  17. package/sidecar/dist/src/module-format.js +31 -1
  18. package/sidecar/dist/src/origin.d.ts +10 -7
  19. package/sidecar/dist/src/origin.js +10 -7
  20. package/sidecar/dist/src/program-files.d.ts +34 -11
  21. package/sidecar/dist/src/program-files.js +52 -10
  22. package/sidecar/dist/src/project-loader.d.ts +7 -0
  23. package/sidecar/dist/src/project-loader.js +20 -0
  24. package/sidecar/dist/src/retype-deferred.d.ts +34 -0
  25. package/sidecar/dist/src/retype-deferred.js +326 -0
  26. package/sidecar/dist/src/retype-selector.d.ts +43 -0
  27. package/sidecar/dist/src/retype-selector.js +217 -0
  28. package/sidecar/dist/src/retype.d.ts +28 -3
  29. package/sidecar/dist/src/retype.js +106 -41
  30. package/sidecar/dist/src/type-inferrer.js +3 -2
  31. package/sidecar/dist/src/types.d.ts +113 -3
  32. package/sidecar/dist/src/validators.d.ts +413 -4
  33. package/sidecar/dist/src/validators.js +41 -1
@@ -245,20 +245,8 @@ function entrySubpaths(manifest) {
245
245
  }
246
246
  return [''];
247
247
  }
248
- /**
249
- * Declaration keys (`file\0declaredName`) of what `file` exports as `name`.
250
- * A chunk can declare a type under its public name and export it under a
251
- * short one (`export { type OmitKeyof as O }`), so the name read off the
252
- * import is not the name the declaration carries.
253
- */
254
- function declarationKeysOfExport(file, name) {
255
- const program = ts.createProgram([file], RESOLUTION_OPTIONS);
256
- const checker = program.getTypeChecker();
257
- const source = program.getSourceFile(file);
258
- const moduleSymbol = source && checker.getSymbolAtLocation(source);
259
- const symbol = moduleSymbol && checker.getExportsOfModule(moduleSymbol).find((s) => s.getName() === name);
260
- if (!symbol)
261
- return [];
248
+ /** Alias chain of an exported symbol followed to the symbol that declares it. */
249
+ function resolveAliasTarget(checker, symbol) {
262
250
  let target = symbol;
263
251
  for (let hops = 0; target.flags & ts.SymbolFlags.Alias && hops < 16; hops++) {
264
252
  const next = checker.getAliasedSymbol(target);
@@ -266,16 +254,41 @@ function declarationKeysOfExport(file, name) {
266
254
  break;
267
255
  target = next;
268
256
  }
269
- const keys = [];
270
- for (const declaration of target.declarations ?? []) {
271
- try {
272
- keys.push(`${fs.realpathSync(declaration.getSourceFile().fileName)}\0${target.getName()}`);
273
- }
274
- catch {
275
- // declaration outside the real file system: ignore
257
+ return target;
258
+ }
259
+ const declarationKeysCache = new Map();
260
+ /**
261
+ * Declaration keys (`file\0declaredName`) of what `file` exports as `name`.
262
+ * A chunk can declare a type under its public name and export it under a
263
+ * short one (`export { type OmitKeyof as O }`), so the name read off the
264
+ * import is not the name the declaration carries. One program per file answers
265
+ * every name asked of it (carrick#3117).
266
+ */
267
+ function declarationKeysOfExport(file, name) {
268
+ let byName = declarationKeysCache.get(file);
269
+ if (!byName) {
270
+ byName = new Map();
271
+ const program = ts.createProgram([file], RESOLUTION_OPTIONS);
272
+ const checker = program.getTypeChecker();
273
+ const source = program.getSourceFile(file);
274
+ const moduleSymbol = source && checker.getSymbolAtLocation(source);
275
+ for (const symbol of moduleSymbol ? checker.getExportsOfModule(moduleSymbol) : []) {
276
+ const target = resolveAliasTarget(checker, symbol);
277
+ const keys = [];
278
+ for (const declaration of target.declarations ?? []) {
279
+ try {
280
+ keys.push(`${fs.realpathSync(declaration.getSourceFile().fileName)}\0${target.getName()}`);
281
+ }
282
+ catch {
283
+ // declaration outside the real file system: ignore
284
+ }
285
+ }
286
+ if (!byName.has(symbol.getName()))
287
+ byName.set(symbol.getName(), keys);
276
288
  }
289
+ declarationKeysCache.set(file, byName);
277
290
  }
278
- return keys;
291
+ return byName.get(name) ?? [];
279
292
  }
280
293
  const moduleExportsCache = new Map();
281
294
  /**
@@ -293,14 +306,8 @@ function exportsOf(entryFile) {
293
306
  const source = program.getSourceFile(entryFile);
294
307
  const moduleSymbol = source && checker.getSymbolAtLocation(source);
295
308
  for (const symbol of moduleSymbol ? checker.getExportsOfModule(moduleSymbol) : []) {
296
- let target = symbol;
297
309
  // Follow the alias chain until it stops (an entry can re-export a re-export).
298
- for (let hops = 0; target.flags & ts.SymbolFlags.Alias && hops < 16; hops++) {
299
- const next = checker.getAliasedSymbol(target);
300
- if (next === target)
301
- break;
302
- target = next;
303
- }
310
+ const target = resolveAliasTarget(checker, symbol);
304
311
  const files = new Set();
305
312
  for (const declaration of target.declarations ?? []) {
306
313
  try {
@@ -35,19 +35,30 @@ import ts from 'typescript';
35
35
  import type { CaptureAliasRecord } from './api.js';
36
36
  import type { ResolvedAnchor } from './anchors.js';
37
37
  import type { WriteGuard } from './guarded-fs.js';
38
+ /** One surface entry of the tree and the anchors its aliases came from. */
39
+ export interface SelfCheckSurface {
40
+ surfaceAbsPath: string;
41
+ resolved: ResolvedAnchor[];
42
+ }
38
43
  export interface SelfCheckArgs {
39
44
  /** Writes are held to the stub (carrick#1748). */
40
45
  guard: WriteGuard;
41
46
  stubDir: string;
42
- surfaceAbsPath: string;
43
- resolved: ResolvedAnchor[];
47
+ /**
48
+ * The surfaces checked over the tree, each with records of its own. Two when
49
+ * a capture's literal backfill holds the same tree as its first surface
50
+ * (carrick#2041): the second sits beside the first, a module nothing
51
+ * imports, so neither changes what the other's aliases read.
52
+ */
53
+ surfaces: SelfCheckSurface[];
44
54
  pinned: Record<string, string>;
45
55
  bareCheckout: boolean;
46
56
  /** Producer repo root; its node_modules (if any) backs resolution. */
47
57
  repoRoot: string;
48
58
  compilerHost?: (options: ts.CompilerOptions) => ts.CompilerHost;
49
59
  }
50
- export declare function selfCheckStub(args: SelfCheckArgs): CaptureAliasRecord[];
60
+ /** The records of each surface, in `args.surfaces` order. */
61
+ export declare function selfCheckStub(args: SelfCheckArgs): CaptureAliasRecord[][];
51
62
  /**
52
63
  * The options of every self-check program.
53
64
  *
@@ -32,12 +32,16 @@
32
32
  * service-wide bucket.
33
33
  */
34
34
  import ts from 'typescript';
35
+ import { createHash } from 'node:crypto';
35
36
  import * as fs from 'node:fs';
36
37
  import * as path from 'node:path';
38
+ import { findAugmentationFiles } from './augmentations.js';
37
39
  import { sidecarCompilerOptions } from './compiler-options.js';
38
40
  import { collectSpecifiers, declarationCandidates, isDeclarationFileName, isRelative, packageNameOf, } from './specifiers.js';
39
41
  import { repairDanglingImports } from './repair-dangling.js';
42
+ import { RESOLUTION_FILE } from './resolution-edges.js';
40
43
  import { findDisqualifyingTopTypes, findUnresolvedPlaceholders, isErrorPlaceholder, provenanceOf, unemittedModuleProvenance, unresolvedInTreeProvenance, } from './deep-walk.js';
44
+ /** The records of each surface, in `args.surfaces` order. */
41
45
  export function selfCheckStub(args) {
42
46
  const typesDir = path.join(args.stubDir, 'types');
43
47
  const treeFiles = [];
@@ -110,17 +114,26 @@ function runSelfCheck(args, treeFiles, repaired) {
110
114
  const program = ts.createProgram(treeFiles, SELF_CHECK_OPTIONS, args.compilerHost?.(SELF_CHECK_OPTIONS));
111
115
  const checker = program.getTypeChecker();
112
116
  const diagnostics = ts.getPreEmitDiagnostics(program);
113
- const surfaceAbs = path.resolve(args.surfaceAbsPath);
114
- const surfaceSource = program.getSourceFile(surfaceAbs);
115
- // The surface holds EVERY alias, and every alias's closure starts there, so
117
+ // A surface holds EVERY alias, and every alias's closure starts there, so
116
118
  // a file-granular failure bucket on it blames the whole service for one
117
119
  // alias's dangling specifier (cloud#1184). Attribute by `export type`
118
120
  // statement span, exactly as check-poison.ts contains poison.
119
- const aliasAtSurfacePosition = buildSurfaceSpanIndex(surfaceSource);
121
+ const surfaces = args.surfaces.map((surface) => {
122
+ const surfaceAbs = path.resolve(surface.surfaceAbsPath);
123
+ const surfaceSource = program.getSourceFile(surfaceAbs);
124
+ return {
125
+ surfaceAbs,
126
+ surfaceSource,
127
+ resolved: surface.resolved,
128
+ aliasAtSurfacePosition: buildSurfaceSpanIndex(surfaceSource),
129
+ // Failed module specifiers on the surface, per ALIAS.
130
+ surfaceFailuresByAlias: new Map(),
131
+ };
132
+ });
133
+ const surfaceAt = new Map(surfaces.map((surface) => [surface.surfaceAbs, surface]));
120
134
  // Failed module specifiers, split external-pinned vs internal, per FILE —
121
- // except on the surface, where they are per ALIAS.
135
+ // except on a surface, where they are per ALIAS.
122
136
  const failuresByFile = new Map();
123
- const surfaceFailuresByAlias = new Map();
124
137
  const emptyFailures = () => ({
125
138
  externalPinned: new Set(),
126
139
  internal: new Set(),
@@ -139,8 +152,9 @@ function runSelfCheck(args, treeFiles, repaired) {
139
152
  // service-wide file bucket: soundness over precision, the same fallback
140
153
  // check-poison.ts makes.
141
154
  const bucketFor = (abs, start) => {
142
- const owner = abs === surfaceAbs ? aliasAtSurfacePosition(start) : undefined;
143
- return owner ? bucketIn(surfaceFailuresByAlias, owner) : bucketIn(failuresByFile, abs);
155
+ const surface = surfaceAt.get(abs);
156
+ const owner = surface?.aliasAtSurfacePosition(start);
157
+ return surface && owner ? bucketIn(surface.surfaceFailuresByAlias, owner) : bucketIn(failuresByFile, abs);
144
158
  };
145
159
  for (const d of diagnostics) {
146
160
  if (!d.file)
@@ -177,10 +191,13 @@ function runSelfCheck(args, treeFiles, repaired) {
177
191
  }
178
192
  // Per-file relative-import adjacency for closure walks.
179
193
  const adjacency = new Map();
194
+ const textOf = new Map();
195
+ const hashAdjacency = new Map();
180
196
  const treeSet = new Set(treeFiles.map((f) => path.resolve(f)));
181
197
  for (const file of treeFiles) {
182
198
  const abs = path.resolve(file);
183
199
  const text = fs.readFileSync(abs, 'utf8');
200
+ textOf.set(abs, text);
184
201
  const neighbors = [];
185
202
  for (const spec of collectSpecifiers(text)) {
186
203
  const resolved = resolveTreeSpecifier(abs, spec, treeSet);
@@ -188,31 +205,45 @@ function runSelfCheck(args, treeFiles, repaired) {
188
205
  neighbors.push(resolved);
189
206
  }
190
207
  adjacency.set(abs, neighbors);
208
+ // The hash's closure (carrick#3135) also follows what `collectSpecifiers`
209
+ // does not read: `import x = require("./y")` and reference paths. It
210
+ // must hold every file the judge loads for the alias.
211
+ const more = [];
212
+ for (const re of [/require\s*\(\s*["']([^"']+)["']/g, /<reference\s+path\s*=\s*["']([^"']+)["']/g]) {
213
+ for (const m of text.matchAll(re)) {
214
+ const resolved = resolveTreeSpecifier(abs, m[1], treeSet) ??
215
+ (treeSet.has(path.resolve(path.dirname(abs), m[1])) ? path.resolve(path.dirname(abs), m[1]) : undefined);
216
+ if (resolved)
217
+ more.push(resolved);
218
+ }
219
+ }
220
+ hashAdjacency.set(abs, [...neighbors, ...more]);
191
221
  }
192
- const records = [];
193
- for (const anchor of args.resolved) {
194
- // Demotions (failureReason present) never reached the surface with a
195
- // real type; everything else — including successful literal anchors,
196
- // which sit at the structural_fallback TIER but did produce text — is
197
- // classified by the real self-check.
198
- records.push(anchor.failureReason !== undefined
199
- ? demotedRecord(anchor)
200
- : checkedRecord(anchor, {
201
- args,
202
- program,
203
- checker,
204
- surfaceAbs,
205
- surfaceSource,
206
- adjacency,
207
- failuresByFile,
208
- surfaceFailuresByAlias,
209
- }));
210
- }
222
+ const judgeInputs = stubJudgeInputs(args, program, textOf, [...surfaceAt.keys()]);
223
+ // Demotions (failureReason present) never reached the surface with a real
224
+ // type; everything else — including successful literal anchors, which sit
225
+ // at the structural_fallback TIER but did produce text — is classified by
226
+ // the real self-check.
227
+ const records = surfaces.map((surface) => surface.resolved.map((anchor) => anchor.failureReason !== undefined
228
+ ? demotedRecord(anchor)
229
+ : checkedRecord(anchor, {
230
+ args,
231
+ program,
232
+ checker,
233
+ surfaceAbs: surface.surfaceAbs,
234
+ surfaceSource: surface.surfaceSource,
235
+ adjacency,
236
+ failuresByFile,
237
+ surfaceFailuresByAlias: surface.surfaceFailuresByAlias,
238
+ textOf,
239
+ hashAdjacency,
240
+ judgeInputs,
241
+ })));
211
242
  const internalFailuresByFile = new Map();
212
243
  for (const [file, failures] of failuresByFile) {
213
- // The surface's own failures are a literal anchor's pasted text
244
+ // A surface's own failures are a literal anchor's pasted text
214
245
  // (carrick#1361), not a declaration with an import to drop.
215
- if (file === surfaceAbs || failures.internal.size === 0)
246
+ if (surfaceAt.has(file) || failures.internal.size === 0)
216
247
  continue;
217
248
  // A file already repaired has had its turn: repairing it again would chase
218
249
  // its own leftover diagnostics.
@@ -328,10 +359,12 @@ function checkedRecord(anchor, ctx) {
328
359
  // publishes is this tree, so the record says where it does not resolve.
329
360
  let unresolvedPaths = [];
330
361
  const seeds = [];
362
+ let statementText;
331
363
  if (ctx.surfaceSource) {
332
364
  for (const stmt of ctx.surfaceSource.statements) {
333
365
  if (!ts.isTypeAliasDeclaration(stmt) || stmt.name.text !== alias)
334
366
  continue;
367
+ statementText = stmt.getText(ctx.surfaceSource);
335
368
  const type = ctx.checker.getTypeAtLocation(stmt.name);
336
369
  topType =
337
370
  (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) !== 0;
@@ -466,7 +499,7 @@ function checkedRecord(anchor, ctx) {
466
499
  detail = unresolvedExternalDetail(blamedExternal);
467
500
  }
468
501
  }
469
- return {
502
+ const record = {
470
503
  alias,
471
504
  anchor_kind: anchor.request.kind,
472
505
  symbol_name: 'symbol_name' in anchor.request ? anchor.request.symbol_name : undefined,
@@ -499,6 +532,111 @@ function checkedRecord(anchor, ctx) {
499
532
  : {}),
500
533
  ...literalMarks(anchor.request),
501
534
  };
535
+ return statementText === undefined
536
+ ? record
537
+ : {
538
+ ...record,
539
+ surface_hash: surfaceHash(record, statementText, closure, ctx),
540
+ };
541
+ }
542
+ /**
543
+ * A tree file in global scope reaches every alias the judge loads beside
544
+ * it, closure or not: a script (no import or export), a file that declares
545
+ * a global or module augmentation, and a file with a reference directive.
546
+ */
547
+ function stubJudgeInputs(args, program, textOf, surfaces) {
548
+ const augmenting = new Set(findAugmentationFiles([...textOf.keys()]).map((f) => path.resolve(f)));
549
+ const globals = [];
550
+ for (const [abs, text] of textOf) {
551
+ if (surfaces.includes(abs))
552
+ continue;
553
+ const source = program.getSourceFile(abs);
554
+ const global = augmenting.has(abs) ||
555
+ /^\s*\/\/\/\s*<reference\b/m.test(text) ||
556
+ (source !== undefined && !ts.isExternalModule(source));
557
+ if (global)
558
+ globals.push([stubRelative(args.stubDir, abs), text]);
559
+ }
560
+ globals.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
561
+ const surfaceRest = new Map();
562
+ for (const surface of surfaces) {
563
+ const source = program.getSourceFile(surface);
564
+ surfaceRest.set(surface, [
565
+ ...(source?.statements ?? [])
566
+ .filter((stmt) => !ts.isTypeAliasDeclaration(stmt))
567
+ .map((stmt) => stmt.getText(source)),
568
+ ...(source?.referencedFiles ?? []).map((ref) => `path:${ref.fileName}`),
569
+ ...(source?.typeReferenceDirectives ?? []).map((ref) => `types:${ref.fileName}`),
570
+ ...(source?.libReferenceDirectives ?? []).map((ref) => `lib:${ref.fileName}`),
571
+ ]);
572
+ }
573
+ let resolution = null;
574
+ try {
575
+ resolution = fs.readFileSync(path.join(args.stubDir, RESOLUTION_FILE), 'utf8');
576
+ }
577
+ catch {
578
+ // No recorded edges: the check resolves every transitive from the registry.
579
+ }
580
+ return {
581
+ surfaceRest,
582
+ globals,
583
+ pinned: Object.entries(args.pinned).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
584
+ resolution,
585
+ bareCheckout: args.bareCheckout,
586
+ };
587
+ }
588
+ function stubRelative(stubDir, abs) {
589
+ return path.relative(stubDir, abs).split(path.sep).join('/');
590
+ }
591
+ /**
592
+ * carrick#3135: the hash of everything the judge reads for one alias from its
593
+ * stub. No machine path enters it, so two scans of one tree at different
594
+ * checkout paths hash alike. File-granular: the closure's files are hashed
595
+ * whole, so an unrelated declaration in a reached file moves the hash (fails
596
+ * toward judging). A closure file that imports the surface itself reaches
597
+ * every alias, so the whole surface is hashed then.
598
+ */
599
+ function surfaceHash(record, statementText, closure, ctx) {
600
+ const reached = new Set(closure);
601
+ const queue = [...closure].filter((file) => file !== ctx.surfaceAbs);
602
+ while (queue.length > 0) {
603
+ for (const next of ctx.hashAdjacency.get(queue.pop()) ?? []) {
604
+ if (reached.has(next))
605
+ continue;
606
+ reached.add(next);
607
+ queue.push(next);
608
+ }
609
+ }
610
+ const files = [];
611
+ let surfaceReached = false;
612
+ for (const file of reached) {
613
+ if (file === ctx.surfaceAbs)
614
+ continue;
615
+ if ((ctx.hashAdjacency.get(file) ?? []).includes(ctx.surfaceAbs))
616
+ surfaceReached = true;
617
+ files.push([stubRelative(ctx.args.stubDir, file), ctx.textOf.get(file) ?? '']);
618
+ }
619
+ files.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
620
+ const inputs = ctx.judgeInputs;
621
+ const preimage = {
622
+ statement: statementText,
623
+ surface_rest: inputs.surfaceRest.get(ctx.surfaceAbs) ?? [],
624
+ whole_surface: surfaceReached ? (ctx.textOf.get(ctx.surfaceAbs) ?? '') : null,
625
+ files,
626
+ globals: inputs.globals,
627
+ pinned: inputs.pinned,
628
+ resolution: inputs.resolution,
629
+ bare_checkout: inputs.bareCheckout,
630
+ // The record fields the check reads (`check.ts`): the pre-gate's
631
+ // findings, and the two marks a probe is built from.
632
+ any_provenance: (record.any_provenance ?? []).map((p) => [p.path, p.kind, p.reason]),
633
+ raw_text_read: record.raw_text_read === true,
634
+ absent_body_tolerated: record.absent_body_tolerated === true,
635
+ };
636
+ return createHash('sha256')
637
+ .update('carrick-surface/1\n')
638
+ .update(JSON.stringify(preimage))
639
+ .digest('hex');
502
640
  }
503
641
  /** Resolve a relative specifier from `fromAbs` to a tree file, if present. */
504
642
  function resolveTreeSpecifier(fromAbs, spec, tree) {
@@ -30,9 +30,10 @@ import { readServerLabels } from './server-labels.js';
30
30
  import { PROGRESS_INTERVAL_MS, atMostEvery } from './progress.js';
31
31
  import { mergeInferTimings } from './infer-timing.js';
32
32
  import { addProgramFiles, listProgramFiles } from './program-files.js';
33
- import { changedSource, inferCacheDir, keepable, programDifference, programRecord, rebuildProgram, readEntry, requestDigest, writeEntry, } from './infer-cache.js';
33
+ import { changedSource, inferCacheDir, keepable, programDifference, programRecord, readEntry, requestDigest, writeEntry, } from './infer-cache.js';
34
34
  import { writePositionRows } from './position-rows.js';
35
35
  import { findImplementations } from './implementations.js';
36
+ import { importGraphOf, mergeGraphs, reach, serialiseGraph } from './affected-set.js';
36
37
  // ===========================================================================
37
38
  // Module-level state
38
39
  // ===========================================================================
@@ -265,6 +266,8 @@ function handleCaptureV2(request) {
265
266
  outDir: request.out_dir,
266
267
  tsconfigPath: request.tsconfig_path,
267
268
  scanRoot: request.scan_root,
269
+ backfillTexts: request.backfill_texts,
270
+ backfillOutDir: request.backfill_out_dir,
268
271
  onProgress: (phase, message) => {
269
272
  if (phase === stage)
270
273
  return withinStage(phase, message);
@@ -430,11 +433,10 @@ function inferAnswerKey(request, groups) {
430
433
  /**
431
434
  * carrick#2843: the kept answer for `key` when every program it was read in
432
435
  * is, built again now, the same program. Each is built from its tsconfig and
433
- * given the roots the kept one had, in order, and rebuilt once more when the
434
- * kept one had been, so a match leaves the program the inference would have
435
- * left. A program that does not match is dropped
436
- * again, so the inference that follows builds it as it would have with no
437
- * cache.
436
+ * given the roots the kept one had, in order. A rebuild does not change a
437
+ * program's roots (carrick#3146), so a match leaves the program the inference
438
+ * would have left. A program that does not match is dropped again, so the
439
+ * inference that follows builds it as it would have with no cache.
438
440
  */
439
441
  function servedAnswer(key) {
440
442
  const entry = readEntry(key);
@@ -460,14 +462,7 @@ function servedAnswer(key) {
460
462
  });
461
463
  if (!same)
462
464
  break;
463
- let now = programRecord(kept.key, project);
464
- if (now.roots.length < kept.roots.length) {
465
- // The inference's own rewrites rebuilt the program after its first
466
- // build, and a rebuild names every file the first one reached as a
467
- // root. Rebuilt once more here, it names the same.
468
- rebuildProgram(project);
469
- now = programRecord(kept.key, project);
470
- }
465
+ const now = programRecord(kept.key, project);
471
466
  const difference = programDifference(kept, now);
472
467
  if (difference) {
473
468
  same = false;
@@ -570,6 +565,37 @@ function handleRetypeCheck(request) {
570
565
  return { request_id: request.request_id, status: 'error', errors: [error] };
571
566
  }
572
567
  }
568
+ /**
569
+ * Handle the 'retype_prescreen' action - say, per consumer call, the reason
570
+ * the retype abstains for before any rewrite, read in the program the scan
571
+ * analysed (carrick#3132)
572
+ */
573
+ function handleRetypePrescreen(request) {
574
+ try {
575
+ const groups = byProject(request.items.map((item, index) => ({ item, index })), ({ item }) => item.file_path);
576
+ const answers = new Array(request.items.length);
577
+ for (const [key, entries] of groups) {
578
+ projectComponents(key)
579
+ .retyper.prescreen(entries.map(({ item }) => item))
580
+ .forEach((answer, position) => {
581
+ answers[entries[position].index] = answer;
582
+ });
583
+ }
584
+ return {
585
+ request_id: request.request_id,
586
+ status: 'success',
587
+ prescreens: request.items.map((item, index) => ({
588
+ item_id: item.item_id,
589
+ ...answers[index],
590
+ })),
591
+ };
592
+ }
593
+ catch (err) {
594
+ const error = err instanceof Error ? err.message : String(err);
595
+ logError(`Retype prescreen failed: ${error}`);
596
+ return { request_id: request.request_id, status: 'error', errors: [error] };
597
+ }
598
+ }
573
599
  /**
574
600
  * How long one verify_client_semantics or verify_library_claims request may
575
601
  * spend before the checks it has not reached come back `unchecked` with reason
@@ -703,6 +729,44 @@ function handleListProgramFiles(request) {
703
729
  return { request_id: request.request_id, status: 'error', errors: [error] };
704
730
  }
705
731
  }
732
+ /**
733
+ * Handle the 'reach_graph' action - the import graph of every program the
734
+ * process has built, the default one and each owning project's (carrick#3100).
735
+ * A process that has built none builds the default one, so a replay can ask
736
+ * after `init` alone. Paths are relative to the scan root.
737
+ */
738
+ function handleReachGraph(request) {
739
+ try {
740
+ const loader = initializedLoader();
741
+ const startTime = performance.now();
742
+ if (loader.builtProjects().length === 0)
743
+ loader.getProject();
744
+ const root = loader.getScanRoot();
745
+ const graph = serialiseGraph(mergeGraphs(loader.builtProjects().map((project) => importGraphOf(project.getProgram().compilerObject, root))));
746
+ log(`Read the import graph of ${graph.files.length} file(s) in ${Math.round(performance.now() - startTime)}ms`);
747
+ return { request_id: request.request_id, status: 'success', version: 1, graph };
748
+ }
749
+ catch (err) {
750
+ const error = err instanceof Error ? err.message : String(err);
751
+ logError(`Reading the import graph failed: ${error}`);
752
+ return { request_id: request.request_id, status: 'error', errors: [error] };
753
+ }
754
+ }
755
+ /**
756
+ * Handle the 'reach' action - the files a set of edits can reach in a graph
757
+ * `reach_graph` wrote (carrick#3100). Reads no program.
758
+ */
759
+ function handleReach(request) {
760
+ try {
761
+ const answer = reach(request.graph, request.changes);
762
+ return { request_id: request.request_id, status: 'success', ...answer };
763
+ }
764
+ catch (err) {
765
+ const error = err instanceof Error ? err.message : String(err);
766
+ logError(`Reach failed: ${error}`);
767
+ return { request_id: request.request_id, status: 'error', errors: [error] };
768
+ }
769
+ }
706
770
  /**
707
771
  * Handle the 'add_program_files' action - add the given files to the default
708
772
  * project's program in the given order, rebuilding it at most once
@@ -838,6 +902,8 @@ function handleRequest(request) {
838
902
  return handleResolveDefinitions(request);
839
903
  case 'retype_check':
840
904
  return handleRetypeCheck(request);
905
+ case 'retype_prescreen':
906
+ return handleRetypePrescreen(request);
841
907
  case 'verify_client_semantics':
842
908
  return handleVerifyClientSemantics(request);
843
909
  case 'verify_library_claims':
@@ -846,6 +912,10 @@ function handleRequest(request) {
846
912
  return handleListLibrarySurface(request);
847
913
  case 'list_program_files':
848
914
  return handleListProgramFiles(request);
915
+ case 'reach_graph':
916
+ return handleReachGraph(request);
917
+ case 'reach':
918
+ return handleReach(request);
849
919
  case 'add_program_files':
850
920
  return handleAddProgramFiles(request);
851
921
  case 'position_rows':
@@ -109,14 +109,6 @@ export declare function programRecord(key: string, project: Project): ProgramRec
109
109
  * this.
110
110
  */
111
111
  export declare function changedSource(kept: ProgramRecord): string | undefined;
112
- /**
113
- * Build `project`'s program again with nothing in it changed. ts-morph builds
114
- * a program only after a change, and roots it at every file the project has
115
- * loaded, the ones earlier builds reached among them: a program built again
116
- * after its first build has more roots than the first. Setting one file's
117
- * text to the text it has is the change.
118
- */
119
- export declare function rebuildProgram(project: Project): void;
120
112
  /**
121
113
  * Keep `answer` for `key`, read in `programs`. Written to a temporary file
122
114
  * and renamed, so a reader never sees half an entry. Entries not written to
@@ -194,20 +194,6 @@ export function changedSource(kept) {
194
194
  }
195
195
  return undefined;
196
196
  }
197
- /**
198
- * Build `project`'s program again with nothing in it changed. ts-morph builds
199
- * a program only after a change, and roots it at every file the project has
200
- * loaded, the ones earlier builds reached among them: a program built again
201
- * after its first build has more roots than the first. Setting one file's
202
- * text to the text it has is the change.
203
- */
204
- export function rebuildProgram(project) {
205
- const file = project.getSourceFiles()[0];
206
- if (!file)
207
- return;
208
- file.replaceWithText(file.getFullText());
209
- project.getProgram().compilerObject;
210
- }
211
197
  /**
212
198
  * Keep `answer` for `key`, read in `programs`. Written to a temporary file
213
199
  * and renamed, so a reader never sees half an entry. Entries not written to
@@ -1540,9 +1540,10 @@ class DeclarationReader {
1540
1540
  * installed dependency. A `paths` alias to the service's own code, or a
1541
1541
  * `declare module` block the service writes, stands in for the package and
1542
1542
  * says nothing about it (`module_local`). The resolver's flag is read, not
1543
- * `program.isSourceFileFromExternalLibrary`: once ts-morph has loaded a
1544
- * dependency, the next program lists it as a root file and the program no
1545
- * longer calls it external. `resolved_file` and `installed_version` both
1543
+ * `program.isSourceFileFromExternalLibrary`: a program names a
1544
+ * dependency a project loaded itself (a file added through the project API)
1545
+ * as a root file, and the program does not call a root file external. The
1546
+ * loader's own rebuilds no longer add dependencies to the roots (carrick#3146). `resolved_file` and `installed_version` both
1546
1547
  * come from that one agreeing answer.
1547
1548
  */
1548
1549
  readModule(pkg, declaration, runtimeModules = false) {
@@ -28,7 +28,18 @@
28
28
  * reusing earlier answers) and their modes differ, the entry cannot be placed
29
29
  * and is left unresolved rather than given another import's mode.
30
30
  */
31
- import { type ResolutionHostFactory } from 'ts-morph';
31
+ import { ts, type ResolutionHost } from 'ts-morph';
32
+ /**
33
+ * A resolution host that also hands the compiler a module resolution cache.
34
+ * ts-morph's `ResolutionHost` has no such member, and its `createHosts`
35
+ * copies only the three it declares onto the compiler host, so a host with
36
+ * its own `resolveModuleNames` left every program without a cache: the
37
+ * compiler then read the `package.json` scope above every file again on
38
+ * every rebuild (37% of a retyped call in a large program).
39
+ */
40
+ export interface CachingResolutionHost extends ResolutionHost {
41
+ getModuleResolutionCache(): ts.ModuleResolutionCache;
42
+ }
32
43
  /**
33
44
  * The editor's project-reference rule for the program's owner config
34
45
  * (`ReferenceRedirect` in `capture/reference-redirect.ts`, carrick#2418),
@@ -47,4 +58,4 @@ export interface ResolutionRedirect {
47
58
  * The resolution host factory, resolving through `redirect` when the owner
48
59
  * config references other projects.
49
60
  */
50
- export declare const moduleFormatResolutionHost: (redirect?: ResolutionRedirect) => ResolutionHostFactory;
61
+ export declare const moduleFormatResolutionHost: (redirect?: ResolutionRedirect) => (host: ts.ModuleResolutionHost, getOptions: () => ts.CompilerOptions) => CachingResolutionHost;