@diffci.com/diffci 0.3.23 → 0.3.25
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/dist-client/src/client/agent-setup.d.ts +23 -0
- package/dist-client/src/client/agent-setup.js +111 -0
- package/dist-client/src/client/cli.js +26 -8
- package/dist-client/src/client/failure-baseline.js +0 -0
- package/dist-client/src/client/full-command.d.ts +10 -0
- package/dist-client/src/client/full-command.js +22 -0
- package/dist-client/src/client/hook.d.ts +1 -0
- package/dist-client/src/client/hook.js +9 -0
- package/dist-client/src/client/mcp.js +10 -4
- package/dist-client/src/client/observe.js +10 -5
- package/dist-client/src/client/verify.js +18 -3
- package/dist-client/src/client/workflow-templates.d.ts +2 -2
- package/dist-client/src/client/workflow-templates.js +2 -2
- package/node_modules/@diffci.com/core/README.md +7 -0
- package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
- package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +3 -1
- package/node_modules/@diffci.com/core/dist/cache/graph-cache.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/git/git-diff.js +16 -0
- package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/planner/test-command.d.ts +4 -0
- package/node_modules/@diffci.com/core/dist/planner/test-command.js +127 -20
- package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/analyzer.js +9 -2
- package/node_modules/@diffci.com/core/dist/repo/analyzer.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +22 -2
- package/node_modules/@diffci.com/core/dist/repo/file-references.js +70 -10
- package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/graph.js +231 -28
- package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +28 -0
- package/node_modules/@diffci.com/core/dist/repo/impact.js +167 -11
- package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/test-discovery.d.ts +5 -1
- package/node_modules/@diffci.com/core/dist/repo/test-discovery.js +55 -6
- package/node_modules/@diffci.com/core/dist/repo/test-discovery.js.map +1 -1
- package/node_modules/@diffci.com/core/dist/repo/types.d.ts +7 -0
- package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.d.ts +2 -2
- package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js +7 -5
- package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js.map +1 -1
- package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +3 -1
- package/node_modules/@diffci.com/core/src/git/git-diff.ts +13 -0
- package/node_modules/@diffci.com/core/src/planner/test-command.ts +125 -16
- package/node_modules/@diffci.com/core/src/repo/analyzer.ts +9 -2
- package/node_modules/@diffci.com/core/src/repo/file-references.ts +74 -11
- package/node_modules/@diffci.com/core/src/repo/graph.ts +206 -30
- package/node_modules/@diffci.com/core/src/repo/impact.ts +169 -12
- package/node_modules/@diffci.com/core/src/repo/test-discovery.ts +52 -8
- package/node_modules/@diffci.com/core/src/repo/types.ts +7 -0
- package/node_modules/@diffci.com/core/src/repo/workflow-test-steps.ts +8 -6
- package/node_modules/source-map-js/lib/quick-sort.js +10 -1
- package/node_modules/source-map-js/lib/source-map-consumer.js +51 -3
- package/node_modules/source-map-js/lib/source-map-generator.js +6 -4
- package/node_modules/source-map-js/lib/source-node.js +7 -0
- package/node_modules/source-map-js/package.json +1 -1
- package/package.json +2 -2
|
@@ -142,7 +142,7 @@ export interface ReferenceResolutionInput {
|
|
|
142
142
|
isCodeFile: (path: string) => boolean;
|
|
143
143
|
/** Whether something a workflow names can reach the test suite through it, given a pattern matching
|
|
144
144
|
* the name (src/repo/workflow-test-steps.ts, workflowFeedsTests). */
|
|
145
|
-
workflowFeedsTests: (content: string, names:
|
|
145
|
+
workflowFeedsTests: (content: string, names: (text: string) => boolean) => boolean;
|
|
146
146
|
/** Changed files whose content analyzeGitDelta proved cannot change how tests run
|
|
147
147
|
* (GitDeltaAnalysis.referenceResolvedPaths); a workflow reading them does not block. */
|
|
148
148
|
contentCleared?: ReadonlySet<string>;
|
|
@@ -156,6 +156,10 @@ export interface ReferenceResolutionInput {
|
|
|
156
156
|
/** Treat a reader that tooling loads implicitly (wrangler config, Dockerfile, `*.config.*`) as
|
|
157
157
|
* unresolvable. Used for code: such a reader can run the file without anything naming it. */
|
|
158
158
|
implicitReadersUnresolvable?: boolean;
|
|
159
|
+
/** The file is gone at HEAD and the graph has shown nothing can still import it (ImpactAnalyzer's
|
|
160
|
+
* resolveRemovedFile). Only a reader naming the file itself, not its directories, can observe its
|
|
161
|
+
* absence, and finding none is not a gap; an unreadable file is skipped as in any other resolution. */
|
|
162
|
+
removed?: boolean;
|
|
159
163
|
/** Resolve a file the root test script runs directly (`node scripts/test-security.js`) to that phase
|
|
160
164
|
* of the script instead of failing closed (ReferenceResolution.phases). Off by default: a caller
|
|
161
165
|
* that does not run the returned phases must keep the fallback. */
|
|
@@ -182,7 +186,7 @@ const LOCKFILES = new Set(["package-lock.json", "yarn.lock", "pnpm-lock.yaml", "
|
|
|
182
186
|
const TEST_LIFECYCLE = ["pretest", "test", "posttest", "prepare", "preinstall", "install", "postinstall"];
|
|
183
187
|
/** Non-code files that can run something or direct what code reads: shell and interpreter scripts,
|
|
184
188
|
* and structured manifests. Only these are followed to their own readers. */
|
|
185
|
-
const DIRECTING_EXTENSIONS = /\.(?:sh|bash|zsh|ps1|psm1|bat|cmd|py|rb|pl|json|jsonc|json5|ya?ml|toml|ini|cfg|conf)$/i;
|
|
189
|
+
export const DIRECTING_EXTENSIONS = /\.(?:sh|bash|zsh|ps1|psm1|bat|cmd|py|rb|pl|json|jsonc|json5|ya?ml|toml|ini|cfg|conf)$/i;
|
|
186
190
|
|
|
187
191
|
/** Script names reachable from `npm test`, including lifecycle hooks and any script one of those bodies
|
|
188
192
|
* names. Over-inclusive by design: a script name appearing anywhere in a reachable body is followed. */
|
|
@@ -255,7 +259,8 @@ const CONTENT_PATH_WORD = /[A-Za-z0-9._\-/@+~*?{}[\]!,$]+/g;
|
|
|
255
259
|
* matches on the basename, so every `wrangler.jsonc` with `"main": "./src/index.js"` named every
|
|
256
260
|
* `src/index.js` in the repository, and `ops/cloudflare/src/a.js` named `ops/cloudflare/src/b.json` by
|
|
257
261
|
* sharing its directory. A word that resolves - from the reader's directory or the repository root - to
|
|
258
|
-
* a different file names that file
|
|
262
|
+
* a different file names that file, and a glob names only what it matches (2026-11-04). Bare names and
|
|
263
|
+
* variables inside a path keep the conservative answer.
|
|
259
264
|
*/
|
|
260
265
|
export function contentNamesPath(content: string, readerPath: string, target: string, pattern: RegExp, ancestors: boolean): boolean {
|
|
261
266
|
if (!pattern.test(content)) return false;
|
|
@@ -264,9 +269,29 @@ export function contentNamesPath(content: string, readerPath: string, target: st
|
|
|
264
269
|
const names = [target, ...dirs];
|
|
265
270
|
const readerDir = posix.dirname(readerPath);
|
|
266
271
|
for (const match of content.matchAll(CONTENT_PATH_WORD)) {
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
272
|
+
let word = match[0].replace(/[,.]+$/, "");
|
|
273
|
+
// Judged with the characters around it, so a bare directory name in prose (`the overlay packages,`
|
|
274
|
+
// in a workflow comment) does not count, as the reference pattern intends (2026-11-04).
|
|
275
|
+
if (!pattern.test(content.slice(Math.max(0, match.index - 1), match.index + word.length + 1))) continue;
|
|
276
|
+
// A leading variable is a directory the content does not name (`$GITHUB_ACTION_PATH/../../scripts/x.sh`
|
|
277
|
+
// names `scripts/x.sh` somewhere, not the repository's `scripts/`), so the rest is a path relative to
|
|
278
|
+
// an unknown directory (2026-11-04: a LobeHub composite action blocked every changed file under scripts/).
|
|
279
|
+
const variable = /^\$(?:\{[\w.]+\}|\w+)\/(.+)$/.exec(word);
|
|
280
|
+
if (variable && !/[*?{}[\]!$]/.test(variable[1]!)) {
|
|
281
|
+
const rest = variable[1]!.replace(/^(?:\.\.?\/)+/, "").replace(/\/+$/, "");
|
|
282
|
+
if (names.some((name) => name === rest || name.endsWith(`/${rest}`) || rest.endsWith(`/${name}`))) return true;
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
if (!word.includes("/") || /[!$]/.test(word)) return true;
|
|
286
|
+
if (/[*?{}[\]]/.test(word)) {
|
|
287
|
+
if (word.startsWith("../")) return true;
|
|
288
|
+
// A glob names what it matches, from the reader's directory, the root, or any directory below the
|
|
289
|
+
// root; `packages/sdk/**` in a workflow's `paths` filter does not name `packages/database/`.
|
|
290
|
+
word = word.replace(/\[[^\]]*\]/g, "?").replace(/^\/+/, "");
|
|
291
|
+
const globs = word.startsWith("./") ? [posix.join(readerDir, word), word.slice(2)] : [word, posix.join(readerDir, word), `**/${word}`];
|
|
292
|
+
if (names.some((name) => globs.some((glob) => matchesGlob(name, glob)))) return true;
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
270
295
|
const trimmed = word.replace(/\/+$/, "");
|
|
271
296
|
const resolved = [posix.normalize(posix.join(readerDir, trimmed))];
|
|
272
297
|
if (!trimmed.startsWith("../")) resolved.push(posix.normalize(trimmed.replace(/^\/+/, "")));
|
|
@@ -278,16 +303,49 @@ export function contentNamesPath(content: string, readerPath: string, target: st
|
|
|
278
303
|
return false;
|
|
279
304
|
}
|
|
280
305
|
|
|
306
|
+
/** Calls that list a directory's contents, in the languages Core analyses and the scripts tests run. */
|
|
307
|
+
const DIRECTORY_WALK = /\b(?:readdir(?:Sync)?|opendir(?:Sync)?|globSync|glob|fastGlob|fg|globby|walk(?:Sync)?|scandir|listdir|iterdir|rglob|WalkDir|Walk|ReadDir|Files\.(?:walk|list|find)|listFiles)\s*\(/;
|
|
308
|
+
|
|
309
|
+
/** Whether `content` calls a directory-listing API; callers pre-filter tests with it once per analysis. */
|
|
310
|
+
export function listsDirectories(content: string | undefined): boolean {
|
|
311
|
+
return content !== undefined && DIRECTORY_WALK.test(content);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Tests that list a directory containing `filePath` (2026-11-04). The CI replay's one miss: a commit
|
|
316
|
+
* added `scripts/ci-reproduction.ts`, and a test that reads every file under `scripts/` failed. Nothing
|
|
317
|
+
* imports a new script, so the graph selected nothing for it, and no fallback said so. A test that calls a
|
|
318
|
+
* directory-listing API and names one of the file's ancestor directories now counts as reading it.
|
|
319
|
+
* Additive only: it never narrows a selection. A walk that starts at the repository root without naming
|
|
320
|
+
* a directory is still invisible, as in resolveFileReferences.
|
|
321
|
+
*/
|
|
322
|
+
export function directoryWalkers(filePath: string, tests: readonly string[], read: (path: string) => string | undefined): string[] {
|
|
323
|
+
const pattern = referencePattern(referenceTokens(filePath));
|
|
324
|
+
return tests.filter((test) => {
|
|
325
|
+
const content = read(test);
|
|
326
|
+
return listsDirectories(content) && contentNamesPath(content!, test, filePath, pattern, true);
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
|
|
281
330
|
/** Configs that tooling loads by their default name and that can run a repository file - a Worker
|
|
282
331
|
* entry point, a container command, a test setup file, a bundler plugin - without a test naming
|
|
283
332
|
* either. `tsconfig.json`, `.gitignore` and lint or style configs list paths but run nothing; a
|
|
284
333
|
* non-default `wrangler.validation.json` is used only when a command names it. */
|
|
285
334
|
const RUNS_FILES_WITHOUT_NAMING = /^(?:wrangler\.(?:toml|json|jsonc)|dockerfile.*|docker-compose.*|compose\.ya?ml|procfile|makefile|justfile|taskfile\.ya?ml|(?:vitest|vite|jest|playwright|cypress|ava|babel|webpack|rollup|esbuild|vue|nuxt|svelte|astro|next)\.config\..+|\.mocharc.*|\.babelrc.*|\.c8rc.*|\.nycrc.*)$/i;
|
|
286
335
|
|
|
287
|
-
function loadsWithoutNaming(path: string): boolean {
|
|
336
|
+
export function loadsWithoutNaming(path: string): boolean {
|
|
288
337
|
return RUNS_FILES_WITHOUT_NAMING.test(posix.basename(path));
|
|
289
338
|
}
|
|
290
339
|
|
|
340
|
+
/** A root dependency manifest that a Dockerfile names only in `COPY`/`ADD` instructions, which put it
|
|
341
|
+
* into the image for a package manager to install from. Any other instruction naming it (a `RUN` that
|
|
342
|
+
* reads it) does not qualify. */
|
|
343
|
+
function copiesOnly(content: string, target: string): boolean {
|
|
344
|
+
if (target.includes("/") || !["package.json", ...LOCKFILES].includes(target)) return false;
|
|
345
|
+
const lines = content.split(/\r?\n/).filter((line) => new RegExp(`(?:^|[\\s/"'])${target.replace(/[.]/g, "\\.")}(?=$|[\\s"',\\]])`).test(line));
|
|
346
|
+
return lines.length > 0 && lines.every((line) => /^\s*(?:COPY|ADD)\s/i.test(line));
|
|
347
|
+
}
|
|
348
|
+
|
|
291
349
|
/** A Cloudflare Workers deployment config (`wrangler.toml`, `wrangler.product.jsonc`). */
|
|
292
350
|
export function isWorkerConfig(filePath: string): boolean {
|
|
293
351
|
return /^wrangler(?:\.[^./]+)?\.(?:toml|json|jsonc)$/i.test(posix.basename(filePath));
|
|
@@ -409,7 +467,7 @@ export function resolveFileReferences(filePath: string, input: ReferenceResoluti
|
|
|
409
467
|
// directory. A reader reached through the changed file (a script, a manifest) matters only if
|
|
410
468
|
// something runs or reads it by name; matching its directories as well made `"tests"` and
|
|
411
469
|
// `"fixtures"` match nearly every file and no generic name (package.json) could resolve.
|
|
412
|
-
const ancestors = target.path === filePath;
|
|
470
|
+
const ancestors = target.path === filePath && !input.removed;
|
|
413
471
|
const pattern = referencePattern(referenceTokens(target.path, { ancestors }));
|
|
414
472
|
for (const candidate of input.files) {
|
|
415
473
|
if (visited.has(candidate) || candidate === target.path || LOCKFILES.has(posix.basename(candidate))) continue;
|
|
@@ -438,7 +496,12 @@ export function resolveFileReferences(filePath: string, input: ReferenceResoluti
|
|
|
438
496
|
}
|
|
439
497
|
if (content === undefined || !contentNamesPath(content, candidate, target.path, pattern, ancestors)) continue;
|
|
440
498
|
visited.add(candidate);
|
|
441
|
-
if (input.
|
|
499
|
+
if (input.allowNoReaders && /^dockerfile/i.test(base) && copiesOnly(content, target.path)) {
|
|
500
|
+
// The caller modelled what the file does when installed (dependency selection); a Dockerfile
|
|
501
|
+
// that only copies it into the image to install from it adds nothing (2026-11-04: DentalPresence's
|
|
502
|
+
// `COPY package.json package-lock.json ./` made every dependency bump a full run).
|
|
503
|
+
resolution.readers.push({ path: candidate, kind: "documentation", via: target.path });
|
|
504
|
+
} else if (input.implicitReadersUnresolvable && loadsWithoutNaming(candidate)) {
|
|
442
505
|
resolution.readers.push({ path: candidate, kind: "unresolvable", via: target.path });
|
|
443
506
|
resolution.unresolvable.push(`${candidate} is loaded by tooling and names ${target.path}`);
|
|
444
507
|
} else if (candidate.startsWith(".github/")) {
|
|
@@ -447,7 +510,7 @@ export function resolveFileReferences(filePath: string, input: ReferenceResoluti
|
|
|
447
510
|
// A change content inspection already showed cannot alter how tests run (a version bump)
|
|
448
511
|
// stays that way when a workflow reads the file.
|
|
449
512
|
const executes = candidate.startsWith(".github/actions/")
|
|
450
|
-
|| (/^\.github\/workflows\//.test(candidate) && !input.contentCleared?.has(target.path) && input.workflowFeedsTests(content, pattern));
|
|
513
|
+
|| (/^\.github\/workflows\//.test(candidate) && !input.contentCleared?.has(target.path) && input.workflowFeedsTests(content, (text) => contentNamesPath(text, candidate, target.path, pattern, ancestors)));
|
|
451
514
|
if (!executes) continue;
|
|
452
515
|
resolution.readers.push({ path: candidate, kind: "unresolvable", via: target.path });
|
|
453
516
|
resolution.unresolvable.push(`${candidate} names ${target.path}`);
|
|
@@ -479,7 +542,7 @@ export function resolveFileReferences(filePath: string, input: ReferenceResoluti
|
|
|
479
542
|
// script or test-feeding workflow step reaches: the suite cannot observe the file. Finding no such
|
|
480
543
|
// reader at all is different - the file's reader is unknown, so it stays unknown.
|
|
481
544
|
const executableReaders = resolution.readers.some((reader) => reader.kind === "transitive");
|
|
482
|
-
if (resolution.unresolvable.length === 0 && tests.size === 0 && code.size === 0 && !executableReaders && !input.allowNoReaders && !loadedOnlyOutsideTests(filePath, input, read)) {
|
|
545
|
+
if (resolution.unresolvable.length === 0 && tests.size === 0 && code.size === 0 && !executableReaders && !input.allowNoReaders && !input.removed && !loadedOnlyOutsideTests(filePath, input, read)) {
|
|
483
546
|
resolution.unresolvable.push(`no test or source file names ${filePath}`);
|
|
484
547
|
}
|
|
485
548
|
resolution.phases = resolution.unresolvable.length === 0 ? [...phases].sort() : [];
|
|
@@ -16,6 +16,7 @@ import type {
|
|
|
16
16
|
GraphIntegrityFinding,
|
|
17
17
|
GraphIntegrityReport,
|
|
18
18
|
GraphPerformanceMetrics,
|
|
19
|
+
RepositoryProfile,
|
|
19
20
|
ResolutionReference,
|
|
20
21
|
SourceRoot,
|
|
21
22
|
UnresolvedDependency,
|
|
@@ -26,6 +27,76 @@ interface ImportRef {
|
|
|
26
27
|
kind: DependencyEdgeKind;
|
|
27
28
|
dynamic: boolean;
|
|
28
29
|
computed?: boolean;
|
|
30
|
+
/** For a computed load whose target set is still bounded by literal text: `` import(`./x/${a}.json`) ``
|
|
31
|
+
* or `import.meta.glob("./x/*.json")`. `base` is the literal directory prefix (a specifier ending in
|
|
32
|
+
* "/"); `regex` matches paths relative to it. Unresolvable patterns keep the load computed. */
|
|
33
|
+
patterns?: { base: string; regex: string; negated: boolean }[];
|
|
34
|
+
/** `import { type A, type B }` or `export { type A } from`: every specifier is inline `type`, so the
|
|
35
|
+
* statement is erased unless the importer's tsconfig preserves imports (see `keepsTypeOnlyImports`). */
|
|
36
|
+
inlineTypeOnly?: boolean;
|
|
37
|
+
/** A `vi.mock("./x")` / `jest.mock("./x")` target. Vitest counts these as dependencies of the test;
|
|
38
|
+
* an unresolvable one (a virtual or aliased module) is dropped rather than made unsafe. */
|
|
39
|
+
mock?: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Test-runner calls whose literal first argument names a module the test depends on. */
|
|
43
|
+
const MOCK_MODULE_CALLS = new Set([
|
|
44
|
+
"vi.mock", "vi.doMock", "vi.unmock", "vi.doUnmock", "vi.importActual", "vi.importMock",
|
|
45
|
+
"jest.mock", "jest.doMock", "jest.unmock", "jest.dontMock", "jest.requireActual", "jest.requireMock", "jest.createMockFromModule",
|
|
46
|
+
]);
|
|
47
|
+
|
|
48
|
+
/** Whether this importer's emit keeps statements whose specifiers are all inline `type`. Without these
|
|
49
|
+
* options TypeScript, esbuild and oxc drop the whole statement, so it never loads the target. */
|
|
50
|
+
function keepsTypeOnlyImports(options: ts.CompilerOptions): boolean {
|
|
51
|
+
return Boolean(options.verbatimModuleSyntax || options.preserveValueImports || options.importsNotUsedAsValues === ts.ImportsNotUsedAsValues.Preserve);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function allInlineType(elements: readonly (ts.ImportSpecifier | ts.ExportSpecifier)[]): boolean {
|
|
55
|
+
return elements.length > 0 && elements.every((element) => element.isTypeOnly);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
59
|
+
// A specifier may omit the extension or name a directory's index module.
|
|
60
|
+
const OPTIONAL_MODULE_SUFFIX = "(?:\\.[A-Za-z0-9]+|/index\\.[A-Za-z0-9]+)?";
|
|
61
|
+
|
|
62
|
+
/** `` `@/../locales/${lng}/${ns}.json` `` -> base "@/../locales/", each substitution matching any text. A
|
|
63
|
+
* substitution can hold "/" so it matches across directories, which can only over-select. */
|
|
64
|
+
function templatePattern(template: ts.TemplateExpression): ImportRef["patterns"] {
|
|
65
|
+
const head = template.head.text;
|
|
66
|
+
const cut = head.lastIndexOf("/");
|
|
67
|
+
if (cut < 0) return undefined;
|
|
68
|
+
const regex = escapeRegex(head.slice(cut + 1)) + template.templateSpans.map((span) => `.*${escapeRegex(span.literal.text)}`).join("");
|
|
69
|
+
return [{ base: head.slice(0, cut + 1), regex: `${regex}${OPTIONAL_MODULE_SUFFIX}`, negated: false }];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** One Vite `import.meta.glob` pattern; `[...]` classes are not translated and keep the load computed. */
|
|
73
|
+
function globPattern(glob: string): NonNullable<ImportRef["patterns"]>[number] | undefined {
|
|
74
|
+
const negated = glob.startsWith("!");
|
|
75
|
+
const body = negated ? glob.slice(1) : glob;
|
|
76
|
+
const firstWild = body.search(/[*?{[]/);
|
|
77
|
+
const cut = body.lastIndexOf("/", firstWild < 0 ? body.length : firstWild);
|
|
78
|
+
if (cut < 0 || body.includes("[")) return undefined;
|
|
79
|
+
let regex = "";
|
|
80
|
+
const rest = body.slice(cut + 1);
|
|
81
|
+
for (let i = 0; i < rest.length; i++) {
|
|
82
|
+
const char = rest[i]!;
|
|
83
|
+
if (rest.startsWith("**/", i)) { regex += "(?:.*/)?"; i += 2; }
|
|
84
|
+
else if (rest.startsWith("**", i)) { regex += ".*"; i += 1; }
|
|
85
|
+
else if (char === "*") regex += "[^/]*";
|
|
86
|
+
else if (char === "?") regex += "[^/]";
|
|
87
|
+
else if (char === "{") {
|
|
88
|
+
const close = rest.indexOf("}", i);
|
|
89
|
+
if (close < 0) return undefined;
|
|
90
|
+
regex += `(?:${rest.slice(i + 1, close).split(",").map(escapeRegex).join("|")})`;
|
|
91
|
+
i = close;
|
|
92
|
+
} else regex += escapeRegex(char);
|
|
93
|
+
}
|
|
94
|
+
return { base: body.slice(0, cut + 1), regex, negated };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function isImportMetaGlob(expression: ts.Expression): boolean {
|
|
98
|
+
return ts.isPropertyAccessExpression(expression) && /^glob(?:Eager)?$/.test(expression.name.text)
|
|
99
|
+
&& ts.isMetaProperty(expression.expression) && expression.expression.keywordToken === ts.SyntaxKind.ImportKeyword;
|
|
29
100
|
}
|
|
30
101
|
|
|
31
102
|
const SOURCE_EXTENSIONS = new Set([
|
|
@@ -126,9 +197,12 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
|
|
|
126
197
|
if (ts.isImportDeclaration(node)) {
|
|
127
198
|
const specifier = node.moduleSpecifier;
|
|
128
199
|
if (ts.isStringLiteral(specifier)) {
|
|
129
|
-
const
|
|
200
|
+
const clause = node.importClause;
|
|
201
|
+
const isTypeOnly = clause?.isTypeOnly ?? false;
|
|
130
202
|
const kind: DependencyEdgeKind = isTypeOnly ? "type-import" : "import";
|
|
131
|
-
|
|
203
|
+
const inlineTypeOnly = !isTypeOnly && !!clause && !clause.name && !!clause.namedBindings
|
|
204
|
+
&& ts.isNamedImports(clause.namedBindings) && allInlineType(clause.namedBindings.elements);
|
|
205
|
+
refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}) });
|
|
132
206
|
}
|
|
133
207
|
} else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
|
|
134
208
|
const specifier = node.moduleReference.expression;
|
|
@@ -139,7 +213,8 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
|
|
|
139
213
|
const specifier = node.moduleSpecifier;
|
|
140
214
|
if (ts.isStringLiteral(specifier)) {
|
|
141
215
|
const kind: DependencyEdgeKind = node.isTypeOnly ? "type-import" : "re-export";
|
|
142
|
-
|
|
216
|
+
const inlineTypeOnly = !node.isTypeOnly && !!node.exportClause && ts.isNamedExports(node.exportClause) && allInlineType(node.exportClause.elements);
|
|
217
|
+
refs.push({ specifier: specifier.text, kind, dynamic: false, ...(inlineTypeOnly ? { inlineTypeOnly } : {}) });
|
|
143
218
|
}
|
|
144
219
|
} else if (ts.isCallExpression(node)) {
|
|
145
220
|
const firstArg = node.arguments[0];
|
|
@@ -147,11 +222,29 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
|
|
|
147
222
|
const isRequire = ts.isIdentifier(node.expression) && node.expression.text === "require" && shadowDepth === 0;
|
|
148
223
|
if ((isImport || isRequire) && firstArg) {
|
|
149
224
|
const literal = ts.isStringLiteral(firstArg) || ts.isNoSubstitutionTemplateLiteral(firstArg);
|
|
225
|
+
const patterns = ts.isTemplateExpression(firstArg) ? templatePattern(firstArg) : undefined;
|
|
150
226
|
refs.push({
|
|
151
227
|
specifier: literal ? firstArg.text : firstArg.getText(sourceFile).slice(0, 200),
|
|
152
228
|
kind: isImport ? "dynamic-import" : "require",
|
|
153
229
|
dynamic: isImport || !literal,
|
|
154
230
|
computed: !literal,
|
|
231
|
+
...(patterns ? { patterns } : {}),
|
|
232
|
+
});
|
|
233
|
+
} else if (firstArg && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression)
|
|
234
|
+
&& MOCK_MODULE_CALLS.has(`${node.expression.expression.text}.${node.expression.name.text}`)
|
|
235
|
+
&& (ts.isStringLiteral(firstArg) || ts.isNoSubstitutionTemplateLiteral(firstArg))) {
|
|
236
|
+
refs.push({ specifier: firstArg.text, kind: "import", dynamic: false, mock: true });
|
|
237
|
+
} else if (isImportMetaGlob(node.expression) && firstArg) {
|
|
238
|
+
// Vite expands these at build time; without them a file loaded only through a glob had no edge.
|
|
239
|
+
const items = ts.isArrayLiteralExpression(firstArg) ? [...firstArg.elements] : [firstArg];
|
|
240
|
+
const globs = items.map((item) => ts.isStringLiteral(item) || ts.isNoSubstitutionTemplateLiteral(item) ? item.text : undefined);
|
|
241
|
+
const patterns = globs.every((glob) => glob !== undefined) ? globs.map((glob) => globPattern(glob!)) : [];
|
|
242
|
+
refs.push({
|
|
243
|
+
specifier: firstArg.getText(sourceFile).slice(0, 200),
|
|
244
|
+
kind: "dynamic-import",
|
|
245
|
+
dynamic: true,
|
|
246
|
+
computed: true,
|
|
247
|
+
...(patterns.length && patterns.every(Boolean) ? { patterns: patterns as NonNullable<ImportRef["patterns"]> } : {}),
|
|
155
248
|
});
|
|
156
249
|
}
|
|
157
250
|
}
|
|
@@ -169,6 +262,8 @@ class DependencyGraphImpl implements DependencyGraph {
|
|
|
169
262
|
readonly edges: DependencyEdge[];
|
|
170
263
|
readonly forward: Record<string, string[]> = {};
|
|
171
264
|
readonly reverse: Record<string, string[]> = {};
|
|
265
|
+
/** `reverse` without `import type` edges, which TypeScript erases before anything runs. */
|
|
266
|
+
private readonly reverseRuntime: Record<string, string[]> = {};
|
|
172
267
|
|
|
173
268
|
constructor(
|
|
174
269
|
sourcePaths: ReadonlySet<string>,
|
|
@@ -199,6 +294,7 @@ class DependencyGraphImpl implements DependencyGraph {
|
|
|
199
294
|
for (const node of this.nodes) {
|
|
200
295
|
this.forward[node.path] = [];
|
|
201
296
|
this.reverse[node.path] = [];
|
|
297
|
+
this.reverseRuntime[node.path] = [];
|
|
202
298
|
}
|
|
203
299
|
|
|
204
300
|
for (const edge of this.edges) {
|
|
@@ -207,14 +303,14 @@ class DependencyGraphImpl implements DependencyGraph {
|
|
|
207
303
|
}
|
|
208
304
|
if (this.reverse[edge.to] !== undefined) {
|
|
209
305
|
this.reverse[edge.to]!.push(edge.from);
|
|
306
|
+
if (edge.kind !== "type-import") this.reverseRuntime[edge.to]!.push(edge.from);
|
|
210
307
|
}
|
|
211
308
|
}
|
|
212
309
|
|
|
213
|
-
for (const
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
this.reverse[key] = [...new Set(this.reverse[key]!)].sort();
|
|
310
|
+
for (const adjacency of [this.forward, this.reverse, this.reverseRuntime]) {
|
|
311
|
+
for (const key of Object.keys(adjacency)) {
|
|
312
|
+
adjacency[key] = [...new Set(adjacency[key]!)].sort();
|
|
313
|
+
}
|
|
218
314
|
}
|
|
219
315
|
}
|
|
220
316
|
|
|
@@ -237,34 +333,31 @@ class DependencyGraphImpl implements DependencyGraph {
|
|
|
237
333
|
}
|
|
238
334
|
|
|
239
335
|
transitiveDependenciesOf(filePath: string): string[] {
|
|
240
|
-
return this.transitiveTraversal(filePath,
|
|
336
|
+
return this.transitiveTraversal(filePath, this.forward);
|
|
241
337
|
}
|
|
242
338
|
|
|
243
339
|
transitiveDependentsOf(filePath: string): string[] {
|
|
244
|
-
return this.transitiveTraversal(filePath,
|
|
340
|
+
return this.transitiveTraversal(filePath, this.reverse);
|
|
245
341
|
}
|
|
246
342
|
|
|
247
|
-
|
|
248
|
-
filePath
|
|
249
|
-
|
|
250
|
-
|
|
343
|
+
transitiveRuntimeDependentsOf(filePath: string): string[] {
|
|
344
|
+
return this.transitiveTraversal(filePath, this.reverseRuntime);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
private transitiveTraversal(filePath: string, adjacency: Record<string, string[]>): string[] {
|
|
251
348
|
const rel = this.normalizeQuery(filePath);
|
|
252
|
-
const visited = new Set<string>();
|
|
349
|
+
const visited = new Set<string>([rel]);
|
|
350
|
+
// An index, not shift(): shift() is O(n) and made dependents of hub modules quadratic (2026-11-03,
|
|
351
|
+
// 379 s of impact analysis on one LobeHub commit whose changed files had ~14k dependents).
|
|
253
352
|
const queue: string[] = [rel];
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
if (visited.has(current)) continue;
|
|
260
|
-
visited.add(current);
|
|
261
|
-
if (current !== rel) result.push(current);
|
|
262
|
-
for (const next of adjacency[current] ?? []) {
|
|
263
|
-
if (!visited.has(next)) queue.push(next);
|
|
353
|
+
for (let head = 0; head < queue.length; head++) {
|
|
354
|
+
for (const next of adjacency[queue[head]!] ?? []) {
|
|
355
|
+
if (visited.has(next)) continue;
|
|
356
|
+
visited.add(next);
|
|
357
|
+
queue.push(next);
|
|
264
358
|
}
|
|
265
359
|
}
|
|
266
|
-
|
|
267
|
-
return result.sort();
|
|
360
|
+
return queue.slice(1).sort();
|
|
268
361
|
}
|
|
269
362
|
|
|
270
363
|
private normalizeQuery(filePath: string): string {
|
|
@@ -771,6 +864,7 @@ export async function buildDependencyGraph(
|
|
|
771
864
|
ref: ImportRef,
|
|
772
865
|
reason: string,
|
|
773
866
|
): void {
|
|
867
|
+
if (ref.mock) return;
|
|
774
868
|
unresolved.push({
|
|
775
869
|
importer: importerRel,
|
|
776
870
|
specifier: ref.specifier,
|
|
@@ -786,6 +880,7 @@ export async function buildDependencyGraph(
|
|
|
786
880
|
importer: string,
|
|
787
881
|
ref: ImportRef,
|
|
788
882
|
): void {
|
|
883
|
+
if (ref.mock && resolution === "unresolved") return;
|
|
789
884
|
references.push({
|
|
790
885
|
resolution,
|
|
791
886
|
specifier: ref.specifier,
|
|
@@ -800,6 +895,35 @@ export async function buildDependencyGraph(
|
|
|
800
895
|
addEdge(importerRel, assetRel, "asset");
|
|
801
896
|
}
|
|
802
897
|
|
|
898
|
+
/** Every repository file a bounded computed load can name, or undefined to keep it computed: the
|
|
899
|
+
* base directory does not resolve, nothing matches, or a match is neither analyzed source nor an
|
|
900
|
+
* asset. Alias directories resolve as in findAssetCandidate, and all candidates are unioned. */
|
|
901
|
+
function resolvePatternTargets(importerAbs: string, patterns: NonNullable<ImportRef["patterns"]>, importerOptions: ts.CompilerOptions): string[] | undefined {
|
|
902
|
+
const compilerAliases = Object.entries(importerOptions.paths ?? {}).map(([pattern, substitutions]) => ({ pattern, substitutions }));
|
|
903
|
+
const aliasRoot = importerOptions.baseUrl ?? (importerOptions as { pathsBasePath?: string }).pathsBasePath ?? repoPath;
|
|
904
|
+
const included = new Set<string>();
|
|
905
|
+
const excluded = new Set<string>();
|
|
906
|
+
for (const pattern of patterns) {
|
|
907
|
+
const base = pattern.base.replace(/\/+$/, "") || ".";
|
|
908
|
+
if (base.startsWith("/")) return undefined;
|
|
909
|
+
const directories = base.startsWith(".") ? [resolve(dirname(importerAbs), base)]
|
|
910
|
+
: [...expandAliasCandidates(base, compilerAliases, aliasRoot), ...expandAliasCandidates(base, profile.pathAliases, repoPath)];
|
|
911
|
+
const matcher = new RegExp(`^${pattern.regex}$`);
|
|
912
|
+
for (const directory of directories) {
|
|
913
|
+
const rel = toRelativeInternal(repoPath, directory);
|
|
914
|
+
if (rel === undefined) continue;
|
|
915
|
+
const prefix = rel === "." ? "" : `${rel}/`;
|
|
916
|
+
for (const file of files) {
|
|
917
|
+
if (file.startsWith(prefix) && matcher.test(file.slice(prefix.length))) (pattern.negated ? excluded : included).add(file);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
const importerRel = toRelativeInternal(repoPath, importerAbs);
|
|
922
|
+
const targets = [...included].filter((file) => !excluded.has(file) && file !== importerRel).sort();
|
|
923
|
+
if (!targets.length || targets.some((file) => !internalSourcePaths.has(file) && !isAssetFileName(file))) return undefined;
|
|
924
|
+
return targets;
|
|
925
|
+
}
|
|
926
|
+
|
|
803
927
|
let filesParsed = sourceFiles.length;
|
|
804
928
|
let followedImplementationFiles = 0;
|
|
805
929
|
|
|
@@ -861,11 +985,23 @@ export async function buildDependencyGraph(
|
|
|
861
985
|
|
|
862
986
|
const importerOptions = optionsFor(sf.fileName);
|
|
863
987
|
|
|
864
|
-
const
|
|
988
|
+
const keepsTypeImports = keepsTypeOnlyImports(importerOptions);
|
|
989
|
+
const refs = extractImportRefs(sf).map((ref) => ref.inlineTypeOnly && !keepsTypeImports ? { ...ref, kind: "type-import" as const } : ref);
|
|
865
990
|
if (scope && sf.referencedFiles.length) adapterBlockers.push(`Triple-slash file references in the scoped suite require full validation: ${importerRel}`);
|
|
866
991
|
for (const ref of refs) {
|
|
867
992
|
// Expression text is not a module name. In particular, import(name) must
|
|
868
993
|
// not be classified as an external package called "name".
|
|
994
|
+
if (ref.computed && ref.patterns) {
|
|
995
|
+
const targets = resolvePatternTargets(sf.fileName, ref.patterns, importerOptions);
|
|
996
|
+
if (targets) {
|
|
997
|
+
for (const target of targets) {
|
|
998
|
+
if (internalSourcePaths.has(target)) addEdge(importerRel, target, ref.kind);
|
|
999
|
+
else recordAssetEdge(importerRel, target);
|
|
1000
|
+
}
|
|
1001
|
+
recordReference(targets.some((target) => internalSourcePaths.has(target)) ? "internal-source" : "internal-asset", importerRel, ref);
|
|
1002
|
+
continue;
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
869
1005
|
if (ref.computed) {
|
|
870
1006
|
recordUnresolved(importerRel, ref, "computed module specifier requires full validation");
|
|
871
1007
|
recordReference("unresolved", importerRel, ref);
|
|
@@ -1123,6 +1259,7 @@ export async function buildDependencyGraph(
|
|
|
1123
1259
|
confidence,
|
|
1124
1260
|
integrity,
|
|
1125
1261
|
resolvedViaProjectReferences,
|
|
1262
|
+
runtimeTestSelection: runtimeTestSelectionEligible(repoPath, files, profile),
|
|
1126
1263
|
};
|
|
1127
1264
|
}
|
|
1128
1265
|
|
|
@@ -1291,6 +1428,35 @@ export function validateDependencyGraph(graph: DependencyGraph): GraphIntegrityR
|
|
|
1291
1428
|
};
|
|
1292
1429
|
}
|
|
1293
1430
|
|
|
1431
|
+
/**
|
|
1432
|
+
* Whether an `import type` edge can be ignored when selecting tests (2026-11-03). Vitest transpiles
|
|
1433
|
+
* without type checking, so a type-only change cannot alter a runtime test's outcome; ts-jest, tsd,
|
|
1434
|
+
* tstyche and Vitest's typecheck mode do check types. Any sign of them anywhere in the repository,
|
|
1435
|
+
* including workspace packages, keeps type-only edges selecting tests. Type tests (`*.test-d.ts`) are
|
|
1436
|
+
* selected through every edge either way (impact.ts).
|
|
1437
|
+
*/
|
|
1438
|
+
function runtimeTestSelectionEligible(repoPath: string, files: readonly string[], profile: RepositoryProfile): boolean {
|
|
1439
|
+
const configs = profile.testRunnerConfigs ?? [];
|
|
1440
|
+
if (!configs.length || configs.some((config) => config.runner !== "vitest")) return false;
|
|
1441
|
+
const read = (path: string) => { try { return readFileSync(join(repoPath, path), "utf8"); } catch { return undefined; } };
|
|
1442
|
+
for (const file of files) {
|
|
1443
|
+
if (file.split("/").includes("node_modules")) continue;
|
|
1444
|
+
const name = file.slice(file.lastIndexOf("/") + 1);
|
|
1445
|
+
if (/^jest\.config\./.test(name)) return false;
|
|
1446
|
+
if (/^vit(?:e|est)[\w.-]*\.(?:config|workspace|projects)\.[cm]?[jt]s$/.test(name)) {
|
|
1447
|
+
const text = read(file);
|
|
1448
|
+
if (text === undefined || /\btypecheck\b/.test(text)) return false;
|
|
1449
|
+
} else if (name === "package.json") {
|
|
1450
|
+
let manifest: { scripts?: Record<string, unknown>; dependencies?: object; devDependencies?: object; peerDependencies?: object; optionalDependencies?: object };
|
|
1451
|
+
try { manifest = JSON.parse(read(file) ?? ""); } catch { return false; }
|
|
1452
|
+
const packages = [manifest.dependencies, manifest.devDependencies, manifest.peerDependencies, manifest.optionalDependencies].flatMap((group) => Object.keys(group ?? {}));
|
|
1453
|
+
if (packages.some((name) => ["jest", "ts-jest", "tsd", "tstyche"].includes(name))) return false;
|
|
1454
|
+
if (Object.values(manifest.scripts ?? {}).some((script) => typeof script !== "string" || /(?:^|[\s&;|(])(?:jest|tsd|tstyche)(?:\s|$)|--typecheck/.test(script))) return false;
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
return true;
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1294
1460
|
function computeConfidence(
|
|
1295
1461
|
unresolvedCount: number,
|
|
1296
1462
|
dynamicUnresolvedCount: number,
|
|
@@ -1372,13 +1538,23 @@ export function refineConfidenceForDelta(result: DependencyGraphResult, changedF
|
|
|
1372
1538
|
if (result.unresolved.length === 0) return result.confidence;
|
|
1373
1539
|
|
|
1374
1540
|
const reachableFromChanged = new Set<string>();
|
|
1541
|
+
const dependents = new Set<string>();
|
|
1542
|
+
const runtimeDependents = new Set<string>();
|
|
1543
|
+
const runtimeOnly = result.runtimeTestSelection === true && typeof result.graph.transitiveRuntimeDependentsOf === "function";
|
|
1375
1544
|
for (const file of changedFiles) {
|
|
1376
1545
|
for (const dep of result.graph.transitiveDependenciesOf(file)) reachableFromChanged.add(dep);
|
|
1377
|
-
for (const dep of result.graph.transitiveDependentsOf(file)) reachableFromChanged.add(dep);
|
|
1546
|
+
for (const dep of result.graph.transitiveDependentsOf(file)) { reachableFromChanged.add(dep); dependents.add(dep); }
|
|
1547
|
+
if (runtimeOnly) for (const dep of result.graph.transitiveRuntimeDependentsOf!(file)) runtimeDependents.add(dep);
|
|
1378
1548
|
}
|
|
1379
1549
|
const changedSet = new Set(changedFiles);
|
|
1380
1550
|
|
|
1381
|
-
|
|
1551
|
+
// An importer that already depends on a changed file is affected, and so is everything depending on
|
|
1552
|
+
// it: whatever its missing edge points at, following that edge cannot reach a test that is not already
|
|
1553
|
+
// selected (2026-11-03: one broken `import type` in a LobeHub test file made 35 of 40 commits UNSAFE).
|
|
1554
|
+
// "Already depends" means through the edges that select tests: runtime edges when type-only ones do
|
|
1555
|
+
// not select (runtimeTestSelection), unless the missing edge is itself type-only.
|
|
1556
|
+
const alreadyAffected = (u: UnresolvedDependency) => (runtimeOnly && !u.typeOnly ? runtimeDependents : dependents).has(u.importer);
|
|
1557
|
+
const relevantUnresolved = result.unresolved.some((u) => !u.computed && !alreadyAffected(u) && (changedSet.has(u.importer) || reachableFromChanged.has(u.importer)));
|
|
1382
1558
|
if (relevantUnresolved) return "UNSAFE";
|
|
1383
1559
|
|
|
1384
1560
|
// None of the unresolved imports are reachable from this delta's changed files - narrow to what
|