carrick 0.3.139 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "carrick",
3
- "version": "0.3.139",
3
+ "version": "0.3.140",
4
4
  "carrickCache": {
5
5
  "cache_version": 22,
6
6
  "intent_cache_version": 2
@@ -115,11 +115,11 @@
115
115
  "zod": "^3.23.0"
116
116
  },
117
117
  "optionalDependencies": {
118
- "@carrick-tools/cli-darwin-arm64": "0.3.139",
119
- "@carrick-tools/cli-darwin-x64": "0.3.139",
120
- "@carrick-tools/cli-linux-arm64": "0.3.139",
121
- "@carrick-tools/cli-linux-x64": "0.3.139",
122
- "@carrick-tools/cli-win32-x64": "0.3.139"
118
+ "@carrick-tools/cli-darwin-arm64": "0.3.140",
119
+ "@carrick-tools/cli-darwin-x64": "0.3.140",
120
+ "@carrick-tools/cli-linux-arm64": "0.3.140",
121
+ "@carrick-tools/cli-linux-x64": "0.3.140",
122
+ "@carrick-tools/cli-win32-x64": "0.3.140"
123
123
  },
124
124
  "devDependencies": {
125
125
  "@types/node": "^24.13.3"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "carrick",
3
3
  "description": "Claude Code plugin for Carrick, which indexes TypeScript codebases across service and repository boundaries. After each edit it adds the file's routes, calls, and cross-service type mismatches to the session, and it registers Carrick's language server. It pairs with the Carrick MCP server, which lets agents search functions by intent rather than name.",
4
- "version": "0.3.139",
4
+ "version": "0.3.140",
5
5
  "author": {
6
6
  "name": "Carrick",
7
7
  "email": "hello@carrick.tools"
@@ -358,6 +358,17 @@ export interface CaptureAliasRecord {
358
358
  * type alone.
359
359
  */
360
360
  absent_body_tolerated?: true;
361
+ /**
362
+ * carrick#3135: lowercase hex SHA-256 of everything the judge reads for
363
+ * this alias from its own stub: the alias's `export type` statement, every
364
+ * tree file its closure reaches, every tree file in global scope (a script,
365
+ * an augmentation, a reference directive), the stub's pinned externals and
366
+ * recorded dependency edges, and the record fields the check reads. Equal
367
+ * hashes on one build mean the judge reads the same input for this alias.
368
+ * Absent on a demoted alias, whose surface line is `unknown` by
369
+ * construction.
370
+ */
371
+ surface_hash?: string;
361
372
  }
362
373
  /** Aggregate fidelity metric, emitted per capture (one service). */
363
374
  export interface CaptureFidelity {
@@ -32,11 +32,14 @@
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';
41
44
  /** The records of each surface, in `args.surfaces` order. */
42
45
  export function selfCheckStub(args) {
@@ -188,10 +191,13 @@ function runSelfCheck(args, treeFiles, repaired) {
188
191
  }
189
192
  // Per-file relative-import adjacency for closure walks.
190
193
  const adjacency = new Map();
194
+ const textOf = new Map();
195
+ const hashAdjacency = new Map();
191
196
  const treeSet = new Set(treeFiles.map((f) => path.resolve(f)));
192
197
  for (const file of treeFiles) {
193
198
  const abs = path.resolve(file);
194
199
  const text = fs.readFileSync(abs, 'utf8');
200
+ textOf.set(abs, text);
195
201
  const neighbors = [];
196
202
  for (const spec of collectSpecifiers(text)) {
197
203
  const resolved = resolveTreeSpecifier(abs, spec, treeSet);
@@ -199,7 +205,21 @@ function runSelfCheck(args, treeFiles, repaired) {
199
205
  neighbors.push(resolved);
200
206
  }
201
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]);
202
221
  }
222
+ const judgeInputs = stubJudgeInputs(args, program, textOf, [...surfaceAt.keys()]);
203
223
  // Demotions (failureReason present) never reached the surface with a real
204
224
  // type; everything else — including successful literal anchors, which sit
205
225
  // at the structural_fallback TIER but did produce text — is classified by
@@ -215,6 +235,9 @@ function runSelfCheck(args, treeFiles, repaired) {
215
235
  adjacency,
216
236
  failuresByFile,
217
237
  surfaceFailuresByAlias: surface.surfaceFailuresByAlias,
238
+ textOf,
239
+ hashAdjacency,
240
+ judgeInputs,
218
241
  })));
219
242
  const internalFailuresByFile = new Map();
220
243
  for (const [file, failures] of failuresByFile) {
@@ -336,10 +359,12 @@ function checkedRecord(anchor, ctx) {
336
359
  // publishes is this tree, so the record says where it does not resolve.
337
360
  let unresolvedPaths = [];
338
361
  const seeds = [];
362
+ let statementText;
339
363
  if (ctx.surfaceSource) {
340
364
  for (const stmt of ctx.surfaceSource.statements) {
341
365
  if (!ts.isTypeAliasDeclaration(stmt) || stmt.name.text !== alias)
342
366
  continue;
367
+ statementText = stmt.getText(ctx.surfaceSource);
343
368
  const type = ctx.checker.getTypeAtLocation(stmt.name);
344
369
  topType =
345
370
  (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) !== 0;
@@ -474,7 +499,7 @@ function checkedRecord(anchor, ctx) {
474
499
  detail = unresolvedExternalDetail(blamedExternal);
475
500
  }
476
501
  }
477
- return {
502
+ const record = {
478
503
  alias,
479
504
  anchor_kind: anchor.request.kind,
480
505
  symbol_name: 'symbol_name' in anchor.request ? anchor.request.symbol_name : undefined,
@@ -507,6 +532,111 @@ function checkedRecord(anchor, ctx) {
507
532
  : {}),
508
533
  ...literalMarks(anchor.request),
509
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');
510
640
  }
511
641
  /** Resolve a relative specifier from `fromAbs` to a tree file, if present. */
512
642
  function resolveTreeSpecifier(fromAbs, spec, tree) {
@@ -30,7 +30,7 @@ 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
36
  import { importGraphOf, mergeGraphs, reach, serialiseGraph } from './affected-set.js';
@@ -433,11 +433,10 @@ function inferAnswerKey(request, groups) {
433
433
  /**
434
434
  * carrick#2843: the kept answer for `key` when every program it was read in
435
435
  * is, built again now, the same program. Each is built from its tsconfig and
436
- * given the roots the kept one had, in order, and rebuilt once more when the
437
- * kept one had been, so a match leaves the program the inference would have
438
- * left. A program that does not match is dropped
439
- * again, so the inference that follows builds it as it would have with no
440
- * 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.
441
440
  */
442
441
  function servedAnswer(key) {
443
442
  const entry = readEntry(key);
@@ -463,14 +462,7 @@ function servedAnswer(key) {
463
462
  });
464
463
  if (!same)
465
464
  break;
466
- let now = programRecord(kept.key, project);
467
- if (now.roots.length < kept.roots.length) {
468
- // The inference's own rewrites rebuilt the program after its first
469
- // build, and a rebuild names every file the first one reached as a
470
- // root. Rebuilt once more here, it names the same.
471
- rebuildProgram(project);
472
- now = programRecord(kept.key, project);
473
- }
465
+ const now = programRecord(kept.key, project);
474
466
  const difference = programDifference(kept, now);
475
467
  if (difference) {
476
468
  same = false;
@@ -581,20 +573,21 @@ function handleRetypeCheck(request) {
581
573
  function handleRetypePrescreen(request) {
582
574
  try {
583
575
  const groups = byProject(request.items.map((item, index) => ({ item, index })), ({ item }) => item.file_path);
584
- const reasons = new Array(request.items.length);
576
+ const answers = new Array(request.items.length);
585
577
  for (const [key, entries] of groups) {
586
578
  projectComponents(key)
587
579
  .retyper.prescreen(entries.map(({ item }) => item))
588
- .forEach((reason, position) => {
589
- reasons[entries[position].index] = reason;
580
+ .forEach((answer, position) => {
581
+ answers[entries[position].index] = answer;
590
582
  });
591
583
  }
592
584
  return {
593
585
  request_id: request.request_id,
594
586
  status: 'success',
595
- prescreens: request.items.map((item, index) => reasons[index] === undefined
596
- ? { item_id: item.item_id }
597
- : { item_id: item.item_id, reason: reasons[index] }),
587
+ prescreens: request.items.map((item, index) => ({
588
+ item_id: item.item_id,
589
+ ...answers[index],
590
+ })),
598
591
  };
599
592
  }
600
593
  catch (err) {
@@ -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) {
@@ -54,13 +54,16 @@ export declare function isExternalOrigin(program: ts.Program, sourceFile: ts.Sou
54
54
  * The compiler keeps that verdict on each program (rule 4 of
55
55
  * `isExternalOrigin`), but ts-morph rebuilds the program after any edit to the
56
56
  * project, such as a probe file created and removed or a file rewritten and
57
- * restored, and passes every file it has loaded as a ROOT file. The compiler
58
- * marks no root file as external, so after the first edit no dependency is.
59
- * Where a path test cannot answer (a Deno project serves npm types from its own
60
- * cache), every library type then read as the user's: framework machinery was
61
- * published as a contract and the printer inlined library types it keeps by
62
- * name. The resolver's answer for a file does not change with the project's
63
- * history, so it is kept here for as long as the project lives.
57
+ * restored, and by default passes every file it has loaded as a ROOT file.
58
+ * The compiler marks no root file as external, so after the first edit no
59
+ * dependency was. Where a path test cannot answer (a Deno project serves npm
60
+ * types from its own cache), every library type then read as the user's:
61
+ * framework machinery was published as a contract and the printer inlined
62
+ * library types it keeps by name. The resolver's answer for a file does not
63
+ * change with the project's history, so it is kept here for as long as the
64
+ * project lives. The loader's projects now pin their roots (carrick#3146), so
65
+ * a rebuild no longer names a dependency as a root; the record stays for the
66
+ * Deno resolver and for any project the loader does not build.
64
67
  *
65
68
  * The compiler's verdict also carries down: a file a library imports, even by
66
69
  * a relative path the resolver answers as not external, is reached while the
@@ -68,13 +68,16 @@ export function isExternalOrigin(program, sourceFile, repoRoot, imports) {
68
68
  * The compiler keeps that verdict on each program (rule 4 of
69
69
  * `isExternalOrigin`), but ts-morph rebuilds the program after any edit to the
70
70
  * project, such as a probe file created and removed or a file rewritten and
71
- * restored, and passes every file it has loaded as a ROOT file. The compiler
72
- * marks no root file as external, so after the first edit no dependency is.
73
- * Where a path test cannot answer (a Deno project serves npm types from its own
74
- * cache), every library type then read as the user's: framework machinery was
75
- * published as a contract and the printer inlined library types it keeps by
76
- * name. The resolver's answer for a file does not change with the project's
77
- * history, so it is kept here for as long as the project lives.
71
+ * restored, and by default passes every file it has loaded as a ROOT file.
72
+ * The compiler marks no root file as external, so after the first edit no
73
+ * dependency was. Where a path test cannot answer (a Deno project serves npm
74
+ * types from its own cache), every library type then read as the user's:
75
+ * framework machinery was published as a contract and the printer inlined
76
+ * library types it keeps by name. The resolver's answer for a file does not
77
+ * change with the project's history, so it is kept here for as long as the
78
+ * project lives. The loader's projects now pin their roots (carrick#3146), so
79
+ * a rebuild no longer names a dependency as a root; the record stays for the
80
+ * Deno resolver and for any project the loader does not build.
78
81
  *
79
82
  * The compiler's verdict also carries down: a file a library imports, even by
80
83
  * a relative path the resolver answers as not external, is reached while the
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The files a program was built from, and files added to a program in an
3
- * order the caller gives (carrick#2027).
3
+ * order the caller gives (carrick#2027, carrick#3146).
4
4
  *
5
5
  * With `stableTypeOrdering` the compiler orders two types of the same name by
6
6
  * where their declarations sit in the program's file list. That list follows
@@ -8,24 +8,47 @@
8
8
  * imports. ts-morph hands the compiler every file it has loaded as a root, in
9
9
  * the order it loaded them, and a process asked about a file outside its
10
10
  * tsconfig loads it when it is asked. Two processes asked the same questions
11
- * in different orders therefore build from roots in different orders, and
12
- * print a union of two same-named types in different orders.
11
+ * in different orders would therefore build from roots in different orders,
12
+ * and print a union of two same-named types in different orders.
13
13
  *
14
14
  * The roots decide the whole program, not only its order. A dependency file
15
15
  * the compiler reached by resolving an import is not the same to it as the
16
16
  * same file named as a root: a second copy of a package reached by resolution
17
17
  * is folded into the first, and named as a root it is read as a file of its
18
- * own and its imports are followed. So the list here is the roots themselves.
19
- * A process that has built only what its tsconfig names, given another
20
- * process's roots in order, ends with the same roots and builds the same
21
- * program.
18
+ * own and its imports are followed. ts-morph names every file it has loaded
19
+ * as a root at each rebuild, the dependencies earlier builds reached among
20
+ * them, so a process's roots grew with its rebuilds (282 to 3,680 in one
21
+ * measured service) and a call's program depended on its process's history.
22
+ * `pinProgramRoots` ends that: a program's roots are the project's own files,
23
+ * never the compiler's library files or installed dependencies, in ts-morph's
24
+ * load order, and a rebuild does not change them.
22
25
  */
23
- import type { Project } from 'ts-morph';
26
+ import { type Project, type SourceFile } from 'ts-morph';
27
+ /**
28
+ * Pin the roots of every program `project` builds (carrick#3146): its own
29
+ * files (ts-morph's in-project files, in load order), less `resolvedByProject`,
30
+ * the files ts-morph's dependency resolution marked in-project when the
31
+ * project was built (a workspace or linked package outside `node_modules`).
32
+ * That is the first build's roots plus every file added through the project
33
+ * API since. The compiler's library files and the dependencies it reached are
34
+ * not roots, so a rebuild after an edit builds the same program and
35
+ * TypeScript can reuse the old one.
36
+ */
37
+ export declare function pinProgramRoots(project: Project, resolvedByProject: readonly SourceFile[]): void;
38
+ /**
39
+ * Set `sourceFile`'s text and keep the module format the project's resolver
40
+ * stamped on it (carrick#3146). Under `node16`..`nodenext` ts-morph's
41
+ * `replaceWithText` makes a fresh node without that format, and TypeScript
42
+ * then reuses only part of the old program. A text edit cannot change a file's
43
+ * format, which comes from its extension and its `package.json` scope, and the
44
+ * resolver stamps the same value in the rebuild, so the program is unchanged
45
+ * and the old one is reused whole.
46
+ */
47
+ export declare function replaceFileText(sourceFile: SourceFile, text: string): void;
24
48
  /**
25
49
  * The root files `project`'s program was built from, in order, as absolute
26
- * paths: every file the project had loaded when the program was last built,
27
- * the compiler's library files and the dependencies earlier builds reached
28
- * among them.
50
+ * paths: the project's own files, never the compiler's library files or
51
+ * installed dependencies (carrick#3146).
29
52
  */
30
53
  export declare function listProgramFiles(project: Project): string[];
31
54
  /**
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The files a program was built from, and files added to a program in an
3
- * order the caller gives (carrick#2027).
3
+ * order the caller gives (carrick#2027, carrick#3146).
4
4
  *
5
5
  * With `stableTypeOrdering` the compiler orders two types of the same name by
6
6
  * where their declarations sit in the program's file list. That list follows
@@ -8,23 +8,65 @@
8
8
  * imports. ts-morph hands the compiler every file it has loaded as a root, in
9
9
  * the order it loaded them, and a process asked about a file outside its
10
10
  * tsconfig loads it when it is asked. Two processes asked the same questions
11
- * in different orders therefore build from roots in different orders, and
12
- * print a union of two same-named types in different orders.
11
+ * in different orders would therefore build from roots in different orders,
12
+ * and print a union of two same-named types in different orders.
13
13
  *
14
14
  * The roots decide the whole program, not only its order. A dependency file
15
15
  * the compiler reached by resolving an import is not the same to it as the
16
16
  * same file named as a root: a second copy of a package reached by resolution
17
17
  * is folded into the first, and named as a root it is read as a file of its
18
- * own and its imports are followed. So the list here is the roots themselves.
19
- * A process that has built only what its tsconfig names, given another
20
- * process's roots in order, ends with the same roots and builds the same
21
- * program.
18
+ * own and its imports are followed. ts-morph names every file it has loaded
19
+ * as a root at each rebuild, the dependencies earlier builds reached among
20
+ * them, so a process's roots grew with its rebuilds (282 to 3,680 in one
21
+ * measured service) and a call's program depended on its process's history.
22
+ * `pinProgramRoots` ends that: a program's roots are the project's own files,
23
+ * never the compiler's library files or installed dependencies, in ts-morph's
24
+ * load order, and a rebuild does not change them.
22
25
  */
26
+ import { Program } from 'ts-morph';
27
+ // `pinProgramRoots` wraps ts-morph's private `_reset`. If an upgrade changes
28
+ // its shape, fail at load rather than bring the growth back silently.
29
+ if (typeof Program.prototype._reset !== 'function' ||
30
+ Program.prototype._reset.length !== 2) {
31
+ throw new Error('ts-morph Program._reset changed: pinProgramRoots must be revisited (carrick#3146)');
32
+ }
33
+ /**
34
+ * Pin the roots of every program `project` builds (carrick#3146): its own
35
+ * files (ts-morph's in-project files, in load order), less `resolvedByProject`,
36
+ * the files ts-morph's dependency resolution marked in-project when the
37
+ * project was built (a workspace or linked package outside `node_modules`).
38
+ * That is the first build's roots plus every file added through the project
39
+ * API since. The compiler's library files and the dependencies it reached are
40
+ * not roots, so a rebuild after an edit builds the same program and
41
+ * TypeScript can reuse the old one.
42
+ */
43
+ export function pinProgramRoots(project, resolvedByProject) {
44
+ const resolved = new Set(resolvedByProject.map((file) => file.getFilePath()));
45
+ const program = project.getProgram();
46
+ const reset = program._reset.bind(program);
47
+ program._reset = (rootNames, host) => {
48
+ const own = new Set(project.getSourceFiles().map((file) => file.getFilePath()));
49
+ reset(rootNames.filter((name) => own.has(name) && !resolved.has(name)), host);
50
+ };
51
+ }
52
+ /**
53
+ * Set `sourceFile`'s text and keep the module format the project's resolver
54
+ * stamped on it (carrick#3146). Under `node16`..`nodenext` ts-morph's
55
+ * `replaceWithText` makes a fresh node without that format, and TypeScript
56
+ * then reuses only part of the old program. A text edit cannot change a file's
57
+ * format, which comes from its extension and its `package.json` scope, and the
58
+ * resolver stamps the same value in the rebuild, so the program is unchanged
59
+ * and the old one is reused whole.
60
+ */
61
+ export function replaceFileText(sourceFile, text) {
62
+ const format = sourceFile.compilerNode.impliedNodeFormat;
63
+ sourceFile.replaceWithText(text);
64
+ sourceFile.compilerNode.impliedNodeFormat = format;
65
+ }
23
66
  /**
24
67
  * The root files `project`'s program was built from, in order, as absolute
25
- * paths: every file the project had loaded when the program was last built,
26
- * the compiler's library files and the dependencies earlier builds reached
27
- * among them.
68
+ * paths: the project's own files, never the compiler's library files or
69
+ * installed dependencies (carrick#3146).
28
70
  */
29
71
  export function listProgramFiles(project) {
30
72
  return [...project.getProgram().compilerObject.getRootFileNames()];
@@ -16,6 +16,7 @@ import * as fs from 'node:fs';
16
16
  import { DenoProject, findDenoConfig, fileConfigPath, findServiceTsconfig, referenceRedirectOf, serviceConfigPath, sidecarCompilerOptions, untrustedReadBound, } from './capture/index.js';
17
17
  import { moduleFormatResolutionHost } from './module-format.js';
18
18
  import { ExternalImports, registerExternalImports } from './origin.js';
19
+ import { pinProgramRoots } from './program-files.js';
19
20
  /**
20
21
  * Source-file patterns used when the repo declares no tsconfig, relative to
21
22
  * the repo root. `node_modules` is excluded explicitly: a glob that matches
@@ -204,6 +205,7 @@ export class ProjectLoader {
204
205
  compilerOptions: sidecarCompilerOptions(optionsFor(kind, this.snapshotToCompilerOptions(snapshot))),
205
206
  skipAddingFilesFromTsConfig: true,
206
207
  });
208
+ pinProgramRoots(project, []);
207
209
  if (kind === 'listed')
208
210
  this.addDefaultSourceFiles(project);
209
211
  return project;
@@ -231,6 +233,7 @@ export class ProjectLoader {
231
233
  })),
232
234
  });
233
235
  registerExternalImports(project, imports);
236
+ pinProgramRoots(project, []);
234
237
  if (kind === 'listed') {
235
238
  for (const file of deno.parsed.fileNames)
236
239
  project.addSourceFileAtPath(file);
@@ -254,6 +257,7 @@ export class ProjectLoader {
254
257
  compilerOptions: sidecarCompilerOptions(optionsFor(kind, DEFAULT_COMPILER_OPTIONS)),
255
258
  skipAddingFilesFromTsConfig: true,
256
259
  });
260
+ pinProgramRoots(project, []);
257
261
  // Add source files from common locations
258
262
  if (kind === 'listed')
259
263
  this.addDefaultSourceFiles(project, (file) => this.projectKeyFor(file) === '');
@@ -377,13 +381,18 @@ export class ProjectLoader {
377
381
  // Over the tsconfig's own options: ts-morph lays these on top.
378
382
  compilerOptions: sidecarCompilerOptions(optionsFor(kind, options)),
379
383
  skipAddingFilesFromTsConfig: kind === 'scripts',
384
+ // The dependency pass is run below, so the files it marks in-project
385
+ // can be kept out of the program's roots (carrick#3146).
386
+ skipFileDependencyResolution: true,
380
387
  // Each import resolves in its file's own module format (carrick#1619),
381
388
  // a referenced project's unbuilt output reads as its source, under its
382
389
  // own options (carrick#2418), and every external-library answer is kept
383
390
  // past the program rebuilds that drop it (carrick#1731).
384
391
  resolutionHost: imports.recording(moduleFormatResolutionHost(referenceRedirectOf(configPath, this.repoRoot))),
385
392
  });
393
+ const resolved = kind === 'listed' ? project.resolveSourceFileDependencies() : [];
386
394
  registerExternalImports(project, imports);
395
+ pinProgramRoots(project, resolved);
387
396
  return project;
388
397
  }
389
398
  /**