@diffci.com/diffci 0.3.38 → 0.3.39

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 (57) hide show
  1. package/README.md +3 -3
  2. package/dist-client/src/client/agent-setup.d.ts +1 -1
  3. package/dist-client/src/client/agent-setup.js +1 -1
  4. package/node_modules/@diffci.com/core/README.md +15 -4
  5. package/node_modules/@diffci.com/core/dist/cache/economics-context.d.ts +4 -1
  6. package/node_modules/@diffci.com/core/dist/cache/economics-context.js +7 -3
  7. package/node_modules/@diffci.com/core/dist/cache/economics-context.js.map +1 -1
  8. package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
  9. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +5 -1
  10. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js.map +1 -1
  11. package/node_modules/@diffci.com/core/dist/ci-inference/evidence.js +1 -1
  12. package/node_modules/@diffci.com/core/dist/ci-inference/evidence.js.map +1 -1
  13. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +2 -0
  14. package/node_modules/@diffci.com/core/dist/git/git-diff.js +7 -6
  15. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  16. package/node_modules/@diffci.com/core/dist/repo/adapters/go.js +24 -7
  17. package/node_modules/@diffci.com/core/dist/repo/adapters/go.js.map +1 -1
  18. package/node_modules/@diffci.com/core/dist/repo/analyzer.js +16 -1
  19. package/node_modules/@diffci.com/core/dist/repo/analyzer.js.map +1 -1
  20. package/node_modules/@diffci.com/core/dist/repo/export-reach.d.ts +16 -0
  21. package/node_modules/@diffci.com/core/dist/repo/export-reach.js +113 -0
  22. package/node_modules/@diffci.com/core/dist/repo/export-reach.js.map +1 -0
  23. package/node_modules/@diffci.com/core/dist/repo/file-references.js +2 -1
  24. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  25. package/node_modules/@diffci.com/core/dist/repo/graph.js +429 -39
  26. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  27. package/node_modules/@diffci.com/core/dist/repo/impact-types.d.ts +1 -1
  28. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +51 -0
  29. package/node_modules/@diffci.com/core/dist/repo/impact.js +296 -9
  30. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  31. package/node_modules/@diffci.com/core/dist/repo/lockfiles.d.ts +5 -0
  32. package/node_modules/@diffci.com/core/dist/repo/lockfiles.js +12 -0
  33. package/node_modules/@diffci.com/core/dist/repo/lockfiles.js.map +1 -1
  34. package/node_modules/@diffci.com/core/dist/repo/repo-config.d.ts +5 -0
  35. package/node_modules/@diffci.com/core/dist/repo/repo-config.js +3 -1
  36. package/node_modules/@diffci.com/core/dist/repo/repo-config.js.map +1 -1
  37. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +35 -1
  38. package/node_modules/@diffci.com/core/dist/repo/workspace-sources.d.ts +35 -0
  39. package/node_modules/@diffci.com/core/dist/repo/workspace-sources.js +292 -0
  40. package/node_modules/@diffci.com/core/dist/repo/workspace-sources.js.map +1 -0
  41. package/node_modules/@diffci.com/core/package.json +1 -1
  42. package/node_modules/@diffci.com/core/src/cache/economics-context.ts +7 -3
  43. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +5 -1
  44. package/node_modules/@diffci.com/core/src/ci-inference/evidence.ts +1 -1
  45. package/node_modules/@diffci.com/core/src/git/git-diff.ts +7 -6
  46. package/node_modules/@diffci.com/core/src/repo/adapters/go.ts +23 -7
  47. package/node_modules/@diffci.com/core/src/repo/analyzer.ts +15 -1
  48. package/node_modules/@diffci.com/core/src/repo/export-reach.ts +92 -0
  49. package/node_modules/@diffci.com/core/src/repo/file-references.ts +2 -1
  50. package/node_modules/@diffci.com/core/src/repo/graph.ts +365 -35
  51. package/node_modules/@diffci.com/core/src/repo/impact-types.ts +2 -0
  52. package/node_modules/@diffci.com/core/src/repo/impact.ts +267 -9
  53. package/node_modules/@diffci.com/core/src/repo/lockfiles.ts +13 -0
  54. package/node_modules/@diffci.com/core/src/repo/repo-config.ts +8 -1
  55. package/node_modules/@diffci.com/core/src/repo/types.ts +32 -1
  56. package/node_modules/@diffci.com/core/src/repo/workspace-sources.ts +273 -0
  57. package/package.json +3 -3
@@ -1,13 +1,15 @@
1
1
  import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
2
2
  import { createTestFileMatcher, DEFAULT_TEST_FILE_MATCHER, testFileMatcherForProfile } from "./test-discovery.js";
3
3
  import { isBuiltin } from "node:module";
4
- import { dirname, extname, join, normalize, relative, resolve, sep } from "node:path";
4
+ import { dirname, extname, isAbsolute, join, normalize, posix, relative, resolve, sep } from "node:path";
5
5
  import ts from "typescript";
6
6
  import { adapterFiles, REPOSITORY_ADAPTERS } from "./adapters/index.js";
7
7
  import { pythonAdapter } from "./adapters/python.js";
8
8
  import { analyzeRepository } from "./analyzer.js";
9
9
  import { applyVueScope, inVuePackage } from "./vue-scope.js";
10
10
  import { declaredWorkspaceRoots } from "./workspaces.js";
11
+ import { infrastructureRole } from "./file-references.js";
12
+ import { WorkspaceSources } from "./workspace-sources.js";
11
13
  /** Test-runner calls whose literal first argument names a module the test depends on. */
12
14
  const MOCK_MODULE_CALLS = new Set([
13
15
  "vi.mock", "vi.doMock", "vi.unmock", "vi.doUnmock", "vi.importActual", "vi.importMock",
@@ -251,10 +253,24 @@ function extractImportRefs(sourceFile) {
251
253
  const refs = [];
252
254
  let shadowDepth = 0;
253
255
  let consts;
256
+ // A function body runs when called, not when the module loads; an immediately invoked one runs at load.
257
+ // Program source files have no parent pointers, so a call marks the function it invokes on the way down.
258
+ let functionDepth = 0;
259
+ const invokedAtOnce = new Set();
254
260
  function visit(node) {
255
261
  const shadows = scopeShadowsRequire(node);
256
262
  if (shadows)
257
263
  shadowDepth++;
264
+ if (ts.isCallExpression(node)) {
265
+ let callee = node.expression;
266
+ while (ts.isParenthesizedExpression(callee))
267
+ callee = callee.expression;
268
+ if (ts.isFunctionLike(callee))
269
+ invokedAtOnce.add(callee);
270
+ }
271
+ const body = ts.isFunctionLike(node) && !invokedAtOnce.has(node);
272
+ if (body)
273
+ functionDepth++;
258
274
  if (ts.isImportDeclaration(node)) {
259
275
  const specifier = node.moduleSpecifier;
260
276
  if (ts.isStringLiteral(specifier)) {
@@ -263,7 +279,11 @@ function extractImportRefs(sourceFile) {
263
279
  const kind = isTypeOnly ? "type-import" : "import";
264
280
  const inlineTypeOnly = !isTypeOnly && !!clause && !clause.name && !!clause.namedBindings
265
281
  && ts.isNamedImports(clause.namedBindings) && allInlineType(clause.namedBindings.elements);
266
- refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}) });
282
+ const bindings = clause && !(clause.namedBindings && ts.isNamespaceImport(clause.namedBindings))
283
+ ? [...(clause.name ? ["default"] : []), ...(clause.namedBindings && ts.isNamedImports(clause.namedBindings)
284
+ ? clause.namedBindings.elements.filter((el) => !el.isTypeOnly).map((el) => (el.propertyName ?? el.name).text) : [])]
285
+ : undefined;
286
+ refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}), ...(bindings ? { names: bindings } : {}) });
267
287
  }
268
288
  }
269
289
  else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
@@ -277,7 +297,11 @@ function extractImportRefs(sourceFile) {
277
297
  if (ts.isStringLiteral(specifier)) {
278
298
  const kind = node.isTypeOnly ? "type-import" : "re-export";
279
299
  const inlineTypeOnly = !node.isTypeOnly && !!node.exportClause && ts.isNamedExports(node.exportClause) && allInlineType(node.exportClause.elements);
280
- refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}) });
300
+ const clause = node.exportClause;
301
+ const reexport = !clause ? { star: true }
302
+ : ts.isNamespaceExport(clause) ? { namespace: clause.name.text }
303
+ : { pairs: clause.elements.filter((el) => !el.isTypeOnly).map((el) => [el.name.text, (el.propertyName ?? el.name).text]) };
304
+ refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}), reexport });
281
305
  }
282
306
  }
283
307
  else if (ts.isCallExpression(node)) {
@@ -295,6 +319,7 @@ function extractImportRefs(sourceFile) {
295
319
  dynamic: isImport || !syntaxLiteral,
296
320
  computed: !literal,
297
321
  ...(patterns ? { patterns } : {}),
322
+ ...(!literal && functionDepth === 0 ? { atLoad: true } : {}),
298
323
  });
299
324
  }
300
325
  else if (firstArg && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression)
@@ -313,16 +338,135 @@ function extractImportRefs(sourceFile) {
313
338
  dynamic: true,
314
339
  computed: true,
315
340
  ...(patterns.length && patterns.every(Boolean) ? { patterns: patterns } : {}),
341
+ ...(functionDepth === 0 ? { atLoad: true } : {}),
316
342
  });
317
343
  }
318
344
  }
319
345
  ts.forEachChild(node, visit);
346
+ if (body)
347
+ functionDepth--;
320
348
  if (shadows)
321
349
  shadowDepth--;
322
350
  }
323
351
  visit(sourceFile);
324
352
  return refs;
325
353
  }
354
+ /**
355
+ * Whether the nearest package.json at or above `path` (inside the repository) declares its JavaScript free of
356
+ * side effects: `"sideEffects": false`, or a list naming only stylesheets. This is the contract bundlers
357
+ * rely on to drop unused re-exports; without it a module's evaluation may matter, so imports stay whole.
358
+ */
359
+ function sideEffectFreePackage(repoPath, path, cache) {
360
+ let dir = dirname(path);
361
+ while (true) {
362
+ let declared = cache.get(dir);
363
+ if (!cache.has(dir)) {
364
+ declared = undefined;
365
+ try {
366
+ const pkg = JSON.parse(readFileSync(join(repoPath, dir, "package.json"), "utf8"));
367
+ const se = pkg.sideEffects;
368
+ declared = se === false || (Array.isArray(se) && se.length > 0 && se.every((glob) => typeof glob === "string" && /\.(s?css|sass|less|styl)$/.test(glob)));
369
+ }
370
+ catch (error) {
371
+ if (error.code !== "ENOENT")
372
+ declared = false;
373
+ }
374
+ cache.set(dir, declared);
375
+ }
376
+ if (declared !== undefined)
377
+ return declared;
378
+ if (dir === "." || dir === "" || dirname(dir) === dir)
379
+ return false;
380
+ dir = dirname(dir);
381
+ }
382
+ }
383
+ /**
384
+ * Runtime names a module defines itself, for export-level selection. `opaque` when they cannot be listed
385
+ * (CommonJS `module.exports`/`exports.x`, `export =`, destructured `export const { a } = ...`): an import of
386
+ * such a module always counts as the whole module.
387
+ */
388
+ function exportedLocals(sourceFile) {
389
+ const locals = new Set();
390
+ let opaque = false;
391
+ const has = (node, kind) => ts.canHaveModifiers(node) && (ts.getModifiers(node) ?? []).some((m) => m.kind === kind);
392
+ for (const st of sourceFile.statements) {
393
+ if (ts.isExportDeclaration(st)) {
394
+ if (!st.moduleSpecifier && !st.isTypeOnly && st.exportClause && ts.isNamedExports(st.exportClause)) {
395
+ for (const el of st.exportClause.elements)
396
+ if (!el.isTypeOnly)
397
+ locals.add(el.name.text);
398
+ }
399
+ }
400
+ else if (ts.isExportAssignment(st)) {
401
+ locals.add("default");
402
+ if (st.isExportEquals)
403
+ opaque = true;
404
+ }
405
+ else if (has(st, ts.SyntaxKind.ExportKeyword)) {
406
+ if (ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st))
407
+ continue;
408
+ if (has(st, ts.SyntaxKind.DefaultKeyword))
409
+ locals.add("default");
410
+ else if (ts.isVariableStatement(st)) {
411
+ for (const d of st.declarationList.declarations) {
412
+ if (ts.isIdentifier(d.name))
413
+ locals.add(d.name.text);
414
+ else
415
+ opaque = true;
416
+ }
417
+ }
418
+ else if ((ts.isFunctionDeclaration(st) || ts.isClassDeclaration(st) || ts.isEnumDeclaration(st) || ts.isModuleDeclaration(st)) && st.name && ts.isIdentifier(st.name)) {
419
+ locals.add(st.name.text);
420
+ }
421
+ else
422
+ opaque = true;
423
+ }
424
+ }
425
+ const visit = (node) => {
426
+ if (opaque)
427
+ return;
428
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)
429
+ && (node.expression.text === "exports" || (node.expression.text === "module" && node.name.text === "exports")))
430
+ opaque = true;
431
+ else
432
+ ts.forEachChild(node, visit);
433
+ };
434
+ visit(sourceFile);
435
+ return { locals: [...locals].sort(), opaque };
436
+ }
437
+ /** A string that reads as a relative path to a code file: `./x`, `../x`, or a relative path ending in a code
438
+ * extension (`config.ts`, `jobs/handler.js`). */
439
+ const PATH_LITERAL = /^(?:\.{1,2}\/[^\s:*?"<>|]+|(?:[\w@.-]+\/)*[\w@.-]+\.[cm]?[jt]sx?)$/;
440
+ /**
441
+ * Strings that name a code file by path, outside import and require specifiers, which already are edges
442
+ * (2026-11-10). payloadcms/payload's integration tests pass `{ config: './config.ts' }` to a helper that
443
+ * `import()`s it; the string is the only trace of that dependency. Type positions are skipped.
444
+ */
445
+ function extractPathLiterals(sourceFile) {
446
+ const found = new Set();
447
+ const specifiers = new Set();
448
+ const visit = (node) => {
449
+ if (ts.isTypeNode(node))
450
+ return;
451
+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier)
452
+ specifiers.add(node.moduleSpecifier);
453
+ if (ts.isExternalModuleReference(node))
454
+ specifiers.add(node.expression);
455
+ if (ts.isCallExpression(node) && node.arguments[0]) {
456
+ const e = node.expression;
457
+ const loads = e.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(e) && e.text === "require")
458
+ || (ts.isPropertyAccessExpression(e) && ts.isIdentifier(e.expression) && MOCK_MODULE_CALLS.has(`${e.expression.text}.${e.name.text}`));
459
+ if (loads)
460
+ specifiers.add(node.arguments[0]);
461
+ }
462
+ if ((ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) && !specifiers.has(node) && node.text.length < 300 && PATH_LITERAL.test(node.text)) {
463
+ found.add(node.text);
464
+ }
465
+ ts.forEachChild(node, visit);
466
+ };
467
+ visit(sourceFile);
468
+ return [...found];
469
+ }
326
470
  class DependencyGraphImpl {
327
471
  repoPath;
328
472
  nodes;
@@ -826,6 +970,20 @@ export async function buildDependencyGraph(options = {}) {
826
970
  const packageDirectories = new Map();
827
971
  const packageScope = (path) => nearestPackageDirectory(repoPath, path, packageDirectories);
828
972
  const workspaceRoots = new Set(declaredWorkspaceRoots(repoPath));
973
+ const workspaceSources = new WorkspaceSources(repoPath, workspaceRoots);
974
+ // The package manager links workspace packages only into workspace members (and the root project).
975
+ const inWorkspace = (rel) => { const directory = packageScope(rel); return directory === "" || workspaceRoots.has(directory); };
976
+ let realRepoRoot;
977
+ const physicalRelative = (file) => {
978
+ try {
979
+ realRepoRoot ??= realpathSync.native(repoPath);
980
+ const rel = relative(realRepoRoot, realpathSync.native(file)).replace(/\\/g, "/");
981
+ return rel && !rel.startsWith("../") && rel !== ".." && !isAbsolute(rel) ? rel : undefined;
982
+ }
983
+ catch {
984
+ return undefined;
985
+ }
986
+ };
829
987
  for (const item of contributions)
830
988
  for (const { path, reason } of [...(item.fileBlockers ?? []), ...(item.subjectBlockers ?? [])])
831
989
  addScope(reason, packageScope(path));
@@ -899,7 +1057,36 @@ export async function buildDependencyGraph(options = {}) {
899
1057
  for (const path of item.sourcePaths)
900
1058
  internalSourcePaths.add(path);
901
1059
  const edgeKeys = new Set(edges.map((edge) => `${edge.from}|${edge.to}|${edge.kind}`));
902
- function addEdge(from, to, kind) {
1060
+ const bindings = {};
1061
+ const bindingsOf = (path) => (bindings[path] ??= { locals: [], imports: {}, reexports: {} });
1062
+ /** Records what a runtime edge binds; an edge without a parsed statement binds the whole module. */
1063
+ function recordBinding(from, to, kind, ref) {
1064
+ if (kind === "asset")
1065
+ return;
1066
+ const b = bindingsOf(from);
1067
+ if (kind === "type-import") {
1068
+ if (!(b.typeImports ??= []).includes(to))
1069
+ b.typeImports.push(to);
1070
+ return;
1071
+ }
1072
+ if (ref?.reexport) {
1073
+ const r = (b.reexports[to] ??= { pairs: [], star: false, namespaces: [] });
1074
+ if (ref.reexport.star)
1075
+ r.star = true;
1076
+ if (ref.reexport.namespace)
1077
+ r.namespaces.push(ref.reexport.namespace);
1078
+ for (const pair of ref.reexport.pairs ?? [])
1079
+ r.pairs.push(pair);
1080
+ return;
1081
+ }
1082
+ const current = b.imports[to];
1083
+ if (!ref?.names || current === "*")
1084
+ b.imports[to] = "*";
1085
+ else
1086
+ b.imports[to] = [...new Set([...(current ?? []), ...ref.names])];
1087
+ }
1088
+ function addEdge(from, to, kind, ref) {
1089
+ recordBinding(from, to, kind, ref);
903
1090
  const key = `${from}|${to}|${kind}`;
904
1091
  if (edgeKeys.has(key))
905
1092
  return;
@@ -1072,6 +1259,42 @@ export async function buildDependencyGraph(options = {}) {
1072
1259
  }
1073
1260
  return compilerOptions;
1074
1261
  }
1262
+ /** The existing code file a path string names, relative to the file holding it. */
1263
+ function pathLiteralTarget(importerRel, literal) {
1264
+ const base = posix.normalize(posix.join(posix.dirname(importerRel), literal));
1265
+ if (base.startsWith("../") || base === "..")
1266
+ return undefined;
1267
+ const stem = base.replace(/\.[cm]?jsx?$/, "");
1268
+ const candidates = [base, ...[".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"].map((ext) => stem + ext), ...["index.ts", "index.tsx", "index.js"].map((name) => `${base}/${name}`)];
1269
+ for (const candidate of candidates) {
1270
+ if (!isSourceFileName(candidate) || candidate.endsWith(".d.ts") || isExcludedPath(candidate, options.excludeDirs ?? []))
1271
+ continue;
1272
+ if (internalSourcePaths.has(candidate) || existsSync(join(repoPath, candidate)))
1273
+ return candidate;
1274
+ }
1275
+ return undefined;
1276
+ }
1277
+ /** Parses an implementation file an import reaches outside the initial walk, rather than silently dropping
1278
+ * the edge or loading every TypeScript declaration library again; false, with a blocker, past the budget. */
1279
+ function followImplementation(absolute, rel) {
1280
+ if (internalSourcePaths.has(rel))
1281
+ return true;
1282
+ try {
1283
+ if (isExcludedPath(rel, options.excludeDirs ?? []) || followedImplementationFiles >= followBudget || statSync(absolute).size > 5 * 1024 * 1024)
1284
+ throw new Error("excluded or exceeds parse budget");
1285
+ const followed = ts.createSourceFile(absolute, readFileSync(absolute, "utf8"), ts.ScriptTarget.Latest, true);
1286
+ if (followed.parseDiagnostics?.length)
1287
+ throw new Error("invalid implementation syntax");
1288
+ sourceFiles.push(followed);
1289
+ followedImplementationFiles++;
1290
+ }
1291
+ catch {
1292
+ adapterBlockers.push(`Resolved implementation cannot be included in the scoped source inventory: ${rel}`);
1293
+ return false;
1294
+ }
1295
+ internalSourcePaths.add(rel);
1296
+ return true;
1297
+ }
1075
1298
  for (const sf of sourceFiles) {
1076
1299
  const importerRel = toRelativeInternal(repoPath, sf.fileName);
1077
1300
  if (!importerRel || !isSourceFileName(sf.fileName))
@@ -1081,17 +1304,36 @@ export async function buildDependencyGraph(options = {}) {
1081
1304
  const importerOptions = optionsFor(sf.fileName);
1082
1305
  const keepsTypeImports = keepsTypeOnlyImports(importerOptions);
1083
1306
  const refs = extractImportRefs(sf).map((ref) => ref.inlineTypeOnly && !keepsTypeImports ? { ...ref, kind: "type-import" } : ref);
1307
+ const { locals, opaque } = exportedLocals(sf);
1308
+ const own = bindingsOf(importerRel);
1309
+ own.locals = locals;
1310
+ if (opaque)
1311
+ own.opaque = true;
1312
+ for (const literal of extractPathLiterals(sf)) {
1313
+ const target = pathLiteralTarget(importerRel, literal);
1314
+ if (!target || target === importerRel)
1315
+ continue;
1316
+ // Infrastructure code outside the graph (ops/, a Worker entry) is resolved through the tests that read
1317
+ // it, and stays global when a deployment definition runs it (ImpactAnalyzer, INFRASTRUCTURE_GLOBAL); a
1318
+ // string naming it must not pull it into the graph and around that rule.
1319
+ if (!internalSourcePaths.has(target) && infrastructureRole(target) === "code")
1320
+ continue;
1321
+ if (followImplementation(join(repoPath, target), target))
1322
+ addEdge(importerRel, target, "path-literal");
1323
+ }
1084
1324
  if (scope && sf.referencedFiles.length)
1085
1325
  adapterBlockers.push(`Triple-slash file references in the scoped suite require full validation: ${importerRel}`);
1086
1326
  for (const ref of refs) {
1087
1327
  // Expression text is not a module name. In particular, import(name) must
1088
1328
  // not be classified as an external package called "name".
1329
+ if (ref.computed && ref.atLoad)
1330
+ bindingsOf(importerRel).computedAtLoad = true;
1089
1331
  if (ref.computed && ref.patterns) {
1090
1332
  const targets = resolvePatternTargets(sf.fileName, ref.patterns, importerOptions);
1091
1333
  if (targets) {
1092
1334
  for (const target of targets) {
1093
1335
  if (internalSourcePaths.has(target))
1094
- addEdge(importerRel, target, ref.kind);
1336
+ addEdge(importerRel, target, ref.kind, ref);
1095
1337
  else
1096
1338
  recordAssetEdge(importerRel, target);
1097
1339
  }
@@ -1121,7 +1363,7 @@ export async function buildDependencyGraph(options = {}) {
1121
1363
  const candidate = findAssetCandidate(sf.fileName, resolvableSpecifier, compilerAliases.length ? compilerAliases : profile.pathAliases, importerOptions.baseUrl ?? dirname(sf.fileName));
1122
1364
  const target = candidate && toRelativeInternal(repoPath, candidate);
1123
1365
  if (target && internalSourcePaths.has(target)) {
1124
- addEdge(importerRel, target, ref.kind);
1366
+ addEdge(importerRel, target, ref.kind, ref);
1125
1367
  recordReference("internal-source", importerRel, ref);
1126
1368
  continue;
1127
1369
  }
@@ -1130,6 +1372,39 @@ export async function buildDependencyGraph(options = {}) {
1130
1372
  continue;
1131
1373
  }
1132
1374
  const resolution = ts.resolveModuleName(resolvableSpecifier, sf.fileName, importerOptions, resolutionHost, moduleResolutionCache);
1375
+ // A workspace package's build output is not its source (2026-11-09, Sentry: `@sentry/server-utils`
1376
+ // resolves to nothing before a build and to build/types/index.d.ts after one). Map the import to the
1377
+ // package's source file, or leave it external so the workspace guard falls back.
1378
+ const workspaceImport = !scope && specifierCategory === "package" && workspaceSources.size && inWorkspace(importerRel)
1379
+ ? workspaceSources.packageFor(resolvableSpecifier)
1380
+ : undefined;
1381
+ if (workspaceImport) {
1382
+ const { pkg, subpath } = workspaceImport;
1383
+ const resolvedFile = resolution.resolvedModule?.resolvedFileName;
1384
+ // Through real paths: a workspace link, or a repository path spelled differently (a Windows 8.3
1385
+ // short name), must still land inside the package.
1386
+ const resolvedRel = resolvedFile ? physicalRelative(resolvedFile) : undefined;
1387
+ const insidePackage = resolvedRel !== undefined && resolvedRel.startsWith(`${pkg.root}/`);
1388
+ if (!resolvedFile || (insidePackage && (/\.d\.[mc]?ts$/.test(resolvedRel) || !internalSourcePaths.has(resolvedRel)))) {
1389
+ const source = (insidePackage ? workspaceSources.sourceForFile(pkg, resolvedRel) : undefined) ?? workspaceSources.sourceForSubpath(pkg, subpath);
1390
+ const asset = source ? undefined : workspaceSources.assetForSubpath(pkg, subpath);
1391
+ if (asset) {
1392
+ recordAssetEdge(importerRel, asset);
1393
+ recordReference("internal-asset", importerRel, ref);
1394
+ continue;
1395
+ }
1396
+ // The package's source may sit outside the tsconfig inventory (payloadcms/payload's solution tsconfig
1397
+ // references only some packages): parse it like any other followed implementation.
1398
+ if (source && (internalSourcePaths.has(source) || (!/\.d\.[mc]?ts$/.test(source) && followImplementation(join(repoPath, source), source)))) {
1399
+ addEdge(importerRel, source, ref.kind, ref);
1400
+ recordReference("internal-source", importerRel, ref);
1401
+ }
1402
+ else {
1403
+ recordReference("external-package", importerRel, ref);
1404
+ }
1405
+ continue;
1406
+ }
1407
+ }
1133
1408
  if (!resolution.resolvedModule || !resolution.resolvedModule.resolvedFileName) {
1134
1409
  const category = classifySpecifier(ref.specifier);
1135
1410
  if (category === "relative" || category === "absolute" || category === "alias") {
@@ -1142,6 +1417,19 @@ export async function buildDependencyGraph(options = {}) {
1142
1417
  continue;
1143
1418
  }
1144
1419
  }
1420
+ // Build output a fresh checkout does not have, inside a workspace package whose tsconfig maps it back:
1421
+ // payloadcms/payload's packages/payload/bin.js does `import('./dist/cli/index.js')`, compiled from
1422
+ // src/cli/index.ts. The import depends on that source, so follow it rather than leave it unresolved.
1423
+ if (category === "relative") {
1424
+ const built = posix.normalize(posix.join(posix.dirname(importerRel), resolvableSpecifier));
1425
+ const pkg = workspaceSources.packageContaining(built);
1426
+ const source = pkg ? workspaceSources.sourceForFile(pkg, built) : undefined;
1427
+ if (source && source !== built && followImplementation(join(repoPath, source), source)) {
1428
+ addEdge(importerRel, source, ref.kind, ref);
1429
+ recordReference("internal-source", importerRel, ref);
1430
+ continue;
1431
+ }
1432
+ }
1145
1433
  recordUnresolved(importerRel, ref, "unresolved internal module");
1146
1434
  recordReference("unresolved", importerRel, ref);
1147
1435
  }
@@ -1164,26 +1452,10 @@ export async function buildDependencyGraph(options = {}) {
1164
1452
  continue;
1165
1453
  }
1166
1454
  if (targetRel && isSourceFileName(resolved)) {
1167
- if (!resolved.endsWith(".d.ts") && !internalSourcePaths.has(targetRel)) {
1168
- // A real import can reach generated implementation excluded from the
1169
- // initial walk. Parse it (and its imports) rather than silently dropping
1170
- // the edge or loading every TypeScript declaration library again.
1171
- try {
1172
- if (isExcludedPath(targetRel, options.excludeDirs ?? []) || followedImplementationFiles >= followBudget || statSync(resolved).size > 5 * 1024 * 1024)
1173
- throw new Error("excluded or exceeds parse budget");
1174
- const followed = ts.createSourceFile(resolved, readFileSync(resolved, "utf8"), ts.ScriptTarget.Latest, true);
1175
- if (followed.parseDiagnostics?.length)
1176
- throw new Error("invalid implementation syntax");
1177
- sourceFiles.push(followed);
1178
- followedImplementationFiles++;
1179
- }
1180
- catch {
1181
- adapterBlockers.push(`Resolved implementation cannot be included in the scoped source inventory: ${targetRel}`);
1182
- continue;
1183
- }
1184
- }
1455
+ if (!resolved.endsWith(".d.ts") && !followImplementation(resolved, targetRel))
1456
+ continue;
1185
1457
  internalSourcePaths.add(targetRel);
1186
- addEdge(importerRel, targetRel, ref.kind);
1458
+ addEdge(importerRel, targetRel, ref.kind, ref);
1187
1459
  recordReference("internal-source", importerRel, ref);
1188
1460
  continue;
1189
1461
  }
@@ -1270,7 +1542,30 @@ export async function buildDependencyGraph(options = {}) {
1270
1542
  if (scope && edges.some(edge => outsideScope(edge.from) || outsideScope(edge.to)))
1271
1543
  adapterBlockers.push("Vue asset or macro dependency crosses the declared package boundary");
1272
1544
  const scopedAdapterBlockers = scopeAdapterBlockers(adapterBlockers, blockerScopes);
1273
- scopedAdapterBlockers.push(...uninstalledWorkspaceBlockers(repoPath, references, workspaceRoots));
1545
+ // A type-only import of a subpath the package neither exports nor contains resolves nowhere, installed or not
1546
+ // (payloadcms/payload's stale `import type { ... } from 'payload/types'`): it hides no edge a change can reach.
1547
+ const namesNothing = (ref) => {
1548
+ if (ref.kind !== "type-import")
1549
+ return false;
1550
+ const target = workspaceSources.packageFor(stripImportQuery(ref.specifier));
1551
+ return target !== undefined && !workspaceSources.names(target.pkg, target.subpath);
1552
+ };
1553
+ // A file only path strings point at (payloadcms/payload's codemod fixtures `basic.input.ts`, read as text
1554
+ // and full of deliberately stale imports) may never run. Its unmapped workspace imports are unresolved
1555
+ // imports of that file, which matter to a change that reaches it (refineConfidenceForDelta), rather than a
1556
+ // blocker on every change that reaches the imported package.
1557
+ const testFiles = new Set(profile.testFilePaths);
1558
+ const incomingKinds = new Map();
1559
+ for (const edge of edges)
1560
+ (incomingKinds.get(edge.to) ?? incomingKinds.set(edge.to, new Set()).get(edge.to)).add(edge.kind);
1561
+ const pathLiteralOnly = new Set([...incomingKinds].filter(([file, kinds]) => !testFiles.has(file) && kinds.has("path-literal") && [...kinds].every((kind) => kind === "path-literal")).map(([file]) => file));
1562
+ const workspaceRefs = references.filter((ref) => inWorkspace(ref.importer) && !namesNothing(ref));
1563
+ for (const ref of workspaceRefs) {
1564
+ if (!pathLiteralOnly.has(ref.importer) || ref.resolution !== "external-package" || !workspaceSources.packageFor(stripImportQuery(ref.specifier)))
1565
+ continue;
1566
+ unresolved.push({ importer: ref.importer, specifier: ref.specifier, reason: "workspace import not mapped to source, in a file only path strings name", dynamic: ref.dynamic, typeOnly: ref.kind === "type-import" });
1567
+ }
1568
+ scopedAdapterBlockers.push(...uninstalledWorkspaceBlockers(repoPath, workspaceRefs.filter((ref) => !pathLiteralOnly.has(ref.importer)), workspaceRoots));
1274
1569
  profile.adapterBlockers = [...adapterBlockers];
1275
1570
  markPhase("importExtractionAndResolution");
1276
1571
  // Nested-package test visibility (2026-08-24, biomejs/biome finding): `internalSourcePaths` above is
@@ -1339,8 +1634,13 @@ export async function buildDependencyGraph(options = {}) {
1339
1634
  filesDiscovered: filesParsed,
1340
1635
  filesParsed: filesParsed,
1341
1636
  };
1637
+ const sideEffectsByDir = new Map();
1638
+ for (const [path, b] of Object.entries(bindings))
1639
+ if (sideEffectFreePackage(repoPath, path, sideEffectsByDir))
1640
+ b.sideEffectFree = true;
1342
1641
  return {
1343
1642
  graph,
1643
+ bindings,
1344
1644
  adapterBlockers,
1345
1645
  ...(scopedAdapterBlockers.length ? { scopedAdapterBlockers, confidenceWithoutScopedBlockers } : {}),
1346
1646
  profile,
@@ -1355,6 +1655,7 @@ export async function buildDependencyGraph(options = {}) {
1355
1655
  integrity,
1356
1656
  resolvedViaProjectReferences,
1357
1657
  runtimeTestSelection: runtimeTestSelectionEligible(repoPath, files, profile),
1658
+ typeTestGlobs: typeTestGlobs(repoPath, files),
1358
1659
  };
1359
1660
  }
1360
1661
  /** Product eligibility includes native adapters; legacy TS corpus classification stays separate. */
@@ -1512,10 +1813,10 @@ export function validateDependencyGraph(graph) {
1512
1813
  }
1513
1814
  /**
1514
1815
  * Whether an `import type` edge can be ignored when selecting tests (2026-11-03). Vitest transpiles
1515
- * without type checking, so a type-only change cannot alter a runtime test's outcome; ts-jest, tsd,
1516
- * tstyche and Vitest's typecheck mode do check types. Any sign of them anywhere in the repository,
1517
- * including workspace packages, keeps type-only edges selecting tests. Type tests (`*.test-d.ts`) are
1518
- * selected through every edge either way (impact.ts).
1816
+ * without type checking, so a type-only change cannot alter a runtime test's outcome; ts-jest and Vitest's
1817
+ * typecheck mode check every test's types. Vitest typecheck mode anywhere, or Jest at the repository root,
1818
+ * keeps type-only edges selecting every test. Jest in a sub-package, tsd and tstyche check only their own
1819
+ * files (typeTestGlobs), and those tests are selected through every edge either way (impact.ts).
1519
1820
  */
1520
1821
  function runtimeTestSelectionEligible(repoPath, files, profile) {
1521
1822
  const configs = profile.testRunnerConfigs ?? [];
@@ -1531,8 +1832,13 @@ function runtimeTestSelectionEligible(repoPath, files, profile) {
1531
1832
  if (file.split("/").includes("node_modules"))
1532
1833
  continue;
1533
1834
  const name = file.slice(file.lastIndexOf("/") + 1);
1534
- if (/^jest\.config\./.test(name))
1535
- return false;
1835
+ // Jest inside a sub-package governs that package's tests only (typeCheckedPackageDirs, typeTestGlobs).
1836
+ const atRoot = !file.includes("/");
1837
+ if (/^jest\.config\./.test(name)) {
1838
+ if (atRoot)
1839
+ return false;
1840
+ continue;
1841
+ }
1536
1842
  if (/^vit(?:e|est)[\w.-]*\.(?:config|workspace|projects)\.[cm]?[jt]s$/.test(name)) {
1537
1843
  const text = read(file);
1538
1844
  if (text === undefined || /\btypecheck\b/.test(text))
@@ -1547,14 +1853,97 @@ function runtimeTestSelectionEligible(repoPath, files, profile) {
1547
1853
  return false;
1548
1854
  }
1549
1855
  const packages = [manifest.dependencies, manifest.devDependencies, manifest.peerDependencies, manifest.optionalDependencies].flatMap((group) => Object.keys(group ?? {}));
1550
- if (packages.some((name) => ["jest", "ts-jest", "tsd", "tstyche"].includes(name)))
1856
+ // tsd and tstyche check types only in their own test files (typeTestGlobs), which keep type edges;
1857
+ // Jest (ts-jest) and `--typecheck` type-check every test they run (2026-11-10: tstyche alone turned
1858
+ // off runtime selection for all of payloadcms/payload's Vitest tests).
1859
+ const scripts = Object.values(manifest.scripts ?? {});
1860
+ if (scripts.some((script) => typeof script !== "string" || /--typecheck/.test(script)))
1551
1861
  return false;
1552
- if (Object.values(manifest.scripts ?? {}).some((script) => typeof script !== "string" || /(?:^|[\s&;|(])(?:jest|tsd|tstyche)(?:\s|$)|--typecheck/.test(script)))
1862
+ if (atRoot && (packages.some((name) => ["jest", "ts-jest"].includes(name)) || scripts.some((script) => /(?:^|[\s&;|(])jest(?:\s|$)/.test(String(script)))))
1553
1863
  return false;
1554
1864
  }
1555
1865
  }
1556
1866
  return true;
1557
1867
  }
1868
+ /** The files tstyche or tsd check, when either is installed: tstyche.json's `testFileMatch` or tstyche's
1869
+ * defaults, and tsd's `*.test-d.ts`. */
1870
+ function typeTestGlobs(repoPath, files) {
1871
+ const read = (path) => { try {
1872
+ return readFileSync(join(repoPath, path), "utf8");
1873
+ }
1874
+ catch {
1875
+ return undefined;
1876
+ } };
1877
+ let tstyche = false, tsd = false;
1878
+ for (const file of files) {
1879
+ if (file.split("/").includes("node_modules") || !file.endsWith("package.json"))
1880
+ continue;
1881
+ let manifest;
1882
+ try {
1883
+ manifest = JSON.parse(read(file) ?? "");
1884
+ }
1885
+ catch {
1886
+ continue;
1887
+ }
1888
+ const packages = [manifest.dependencies, manifest.devDependencies, manifest.peerDependencies, manifest.optionalDependencies].flatMap((group) => Object.keys(group ?? {}));
1889
+ const scripts = Object.values(manifest.scripts ?? {}).filter((script) => typeof script === "string");
1890
+ if (packages.includes("tstyche") || scripts.some((script) => /(?:^|[\s&;|(])tstyche(?:\s|$)/.test(script)))
1891
+ tstyche = true;
1892
+ if (packages.includes("tsd") || scripts.some((script) => /(?:^|[\s&;|(])tsd(?:\s|$)/.test(script)))
1893
+ tsd = true;
1894
+ }
1895
+ const globs = [];
1896
+ if (tstyche) {
1897
+ let match;
1898
+ for (const name of ["tstyche.config.json", "tstyche.json"]) {
1899
+ const text = read(name);
1900
+ if (text === undefined)
1901
+ continue;
1902
+ const parsed = ts.parseConfigFileTextToJson(name, text);
1903
+ match = parsed.config?.testFileMatch;
1904
+ break;
1905
+ }
1906
+ globs.push(...(Array.isArray(match) && match.every((glob) => typeof glob === "string") ? match
1907
+ : ["**/*.tst.*", "**/__typetests__/*.test.*", "**/typetests/*.test.*"]));
1908
+ }
1909
+ if (tsd)
1910
+ globs.push("**/*.test-d.ts", "**/*.test-d.tsx");
1911
+ for (const dir of typeCheckedPackageDirs(repoPath, files))
1912
+ globs.push(`${dir}/**`);
1913
+ return globs;
1914
+ }
1915
+ /**
1916
+ * Sub-package directories whose own tests Jest (or ts-jest) may type-check as they run: a jest.config there, or
1917
+ * a package.json depending on jest/ts-jest or running `jest`. 2026-11-10: payloadcms/payload's
1918
+ * `.github/actions/triage` (a GitHub Action with its own Jest setup) and `packages/payload-cloud` (a `jest`
1919
+ * test script) had turned off runtime selection for the whole Vitest suite. A repository-root signal still
1920
+ * turns it off everywhere (runtimeTestSelectionEligible).
1921
+ */
1922
+ function typeCheckedPackageDirs(repoPath, files) {
1923
+ const dirs = new Set();
1924
+ for (const file of files) {
1925
+ if (file.split("/").includes("node_modules") || !file.includes("/"))
1926
+ continue;
1927
+ const name = file.slice(file.lastIndexOf("/") + 1);
1928
+ const dir = file.slice(0, file.lastIndexOf("/"));
1929
+ if (/^jest\.config\./.test(name))
1930
+ dirs.add(dir);
1931
+ else if (name === "package.json") {
1932
+ let manifest;
1933
+ try {
1934
+ manifest = JSON.parse(readFileSync(join(repoPath, file), "utf8"));
1935
+ }
1936
+ catch {
1937
+ dirs.add(dir);
1938
+ continue;
1939
+ }
1940
+ const packages = [manifest.dependencies, manifest.devDependencies, manifest.peerDependencies, manifest.optionalDependencies].flatMap((group) => Object.keys(group ?? {}));
1941
+ if (packages.some((pkg) => pkg === "jest" || pkg === "ts-jest") || Object.values(manifest.scripts ?? {}).some((script) => /(?:^|[\s&;|(])jest(?:\s|$)/.test(String(script))))
1942
+ dirs.add(dir);
1943
+ }
1944
+ }
1945
+ return [...dirs].sort();
1946
+ }
1558
1947
  function computeConfidence(unresolvedCount, dynamicUnresolvedCount, integrityCriticalCount, sourceFileCount, resolvedViaProjectReferences) {
1559
1948
  // An empty graph has nothing to flag as unresolved and nothing to violate integrity
1560
1949
  // checks, so without this it would fall through to "COMPLETE" — the worst possible
@@ -1768,10 +2157,11 @@ function scopeAdapterBlockers(adapterBlockers, scopes) {
1768
2157
  adapterBlockers.splice(i, 1);
1769
2158
  return [...scoped].map(([reason, directories]) => ({ reason, directories: [...directories].sort() }));
1770
2159
  }
1771
- /** A declared workspace package imported by name that resolves to no repository file, typically because
1772
- * dependencies are not installed, hides every edge into that package (2026-11-08: in an uninstalled
1773
- * Sentry checkout, 18 packages import `@sentry/server-utils`, and none of those edges existed). A change
1774
- * reaching the package then falls back instead of skipping its dependents. */
2160
+ /** A declared workspace package imported by name from a workspace member whose import could not be mapped
2161
+ * to the package's source files hides every edge into that package (2026-11-08: in an uninstalled Sentry
2162
+ * checkout, 18 packages import `@sentry/server-utils`, and none of those edges existed). A change reaching
2163
+ * the package then falls back instead of skipping its dependents. Imports from outside the workspace get
2164
+ * the package from elsewhere (a registry or a tarball) and are left out by the caller. */
1775
2165
  function uninstalledWorkspaceBlockers(repoPath, references, workspaceRoots) {
1776
2166
  const external = references.filter((ref) => ref.resolution === "external-package");
1777
2167
  if (!external.length)
@@ -1799,7 +2189,7 @@ function uninstalledWorkspaceBlockers(repoPath, references, workspaceRoots) {
1799
2189
  set.add(ref.importer);
1800
2190
  }
1801
2191
  return [...importers].sort(([a], [b]) => a.localeCompare(b)).map(([name, files]) => ({
1802
- reason: `Workspace package ${name} is imported by ${files.size} file${files.size === 1 ? "" : "s"} but does not resolve to its repository sources; install and link dependencies before analysis`,
2192
+ reason: `Workspace package ${name} is imported by ${files.size} file${files.size === 1 ? "" : "s"} but DiffCI cannot map the import to the package's source files; point the package's types entry at a tsconfig outDir or declarationDir with a rootDir, or at source`,
1803
2193
  directories: [packages.get(name)],
1804
2194
  }));
1805
2195
  }