From da420368b1dad367723e78d6d50a94d4be1d1f5d Mon Sep 17 00:00:00 2001 From: Andrey Rychkov Date: Mon, 30 Nov 2026 15:56:24 +0000 Subject: [PATCH 1/2] fix: trace runtime module edges in 0.3.3 Respect local require bindings and the compiler setting for inline type-only imports so entry paths reflect module loading. --- package-lock.json | 4 ++-- package.json | 2 +- src/compiler.ts | 34 ++++++++++++++++++++++++++--- test/module-edges.test.ts | 46 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 80 insertions(+), 6 deletions(-) create mode 100644 test/module-edges.test.ts diff --git a/package-lock.json b/package-lock.json index a622d80..6fbbbd7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "code-inventory", - "version": "0.3.2", + "version": "0.3.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "code-inventory", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "dependencies": { "typescript": "npm:@typescript/typescript6@6.0.2" diff --git a/package.json b/package.json index 91b8054..355e43e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "code-inventory", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "type": "module", "description": "Static code inventory for JavaScript and TypeScript. Find symbol usages and trace paths from entry points.", diff --git a/src/compiler.ts b/src/compiler.ts index 06bc524..4803339 100644 --- a/src/compiler.ts +++ b/src/compiler.ts @@ -465,11 +465,39 @@ function analyze( }); } + function isCommonJsRequire(expression: ts.Expression): boolean { + if (!ts.isIdentifier(expression) || expression.text !== 'require') return false; + const binding = checker.getSymbolAtLocation(expression); + return ( + !binding?.declarations?.length || + binding.declarations.every( + (decl) => + decl.getSourceFile().isDeclarationFile && + ts.isVariableDeclaration(decl) && + !!decl.parent.parent.parent && + (ts.isSourceFile(decl.parent.parent.parent) || + (ts.isModuleBlock(decl.parent.parent.parent) && + !!(decl.parent.parent.parent.parent.flags & ts.NodeFlags.GlobalAugmentation))), + ) + ); + } + function visit(node: ts.Node, callerId: string | null, callTargetNode?: ts.Node): void { const declaration = byNode.get(node); if (declaration) callerId = declaration.id; - if (ts.isImportDeclaration(node)) - addModule(node, node.moduleSpecifier, 'import', callerId, node.importClause?.isTypeOnly ?? false); + if (ts.isImportDeclaration(node)) { + const clause = node.importClause; + const bindings = clause?.namedBindings; + const erased = + clause?.isTypeOnly || + (!options.verbatimModuleSyntax && + !clause?.name && + bindings && + ts.isNamedImports(bindings) && + bindings.elements.length > 0 && + bindings.elements.every((item) => item.isTypeOnly)); + addModule(node, node.moduleSpecifier, 'import', callerId, Boolean(erased)); + } if (ts.isExportDeclaration(node) && node.moduleSpecifier) addModule(node, node.moduleSpecifier, 'export', callerId, node.isTypeOnly); if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) { @@ -479,7 +507,7 @@ function analyze( const expression = unwrap(node.expression); if (expression.kind === ts.SyntaxKind.ImportKeyword) addModule(node, node.arguments?.[0], 'dynamic-import', callerId); - else if (ts.isIdentifier(expression) && expression.text === 'require' && !resolveExpression(expression)) { + else if (isCommonJsRequire(expression)) { addModule(node, node.arguments?.[0], 'require', callerId); } else { const target = resolveExpression(expression); diff --git a/test/module-edges.test.ts b/test/module-edges.test.ts new file mode 100644 index 0000000..976fd20 --- /dev/null +++ b/test/module-edges.test.ts @@ -0,0 +1,46 @@ +import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { expect, it, onTestFinished } from 'vitest'; +import { reachability, scan } from '../src/index.ts'; + +function fixture(files: Record) { + const root = mkdtempSync(join(tmpdir(), 'inventory-edges-')); + onTestFinished(() => rmSync(root, { recursive: true, force: true })); + for (const [file, content] of Object.entries(files)) writeFileSync(join(root, file), content); + return root; +} + +it('distinguishes a CommonJS loader from parameter and import bindings named require', () => { + const root = fixture({ + 'settings.cjs': 'exports.ready = true;', + 'loader.cjs': "require('./settings.cjs');", + 'callback.ts': 'export function custom(name: string) { return name; }', + 'shadow.ts': "export function call(require: (name: string) => void) { require('./settings.cjs'); }", + 'alias.ts': "import { custom as require } from './callback'; require('./settings.cjs');", + }); + const inventory = scan(root); + expect(inventory.modules.filter((edge) => edge.kind === 'require').map((edge) => edge.location.file)).toEqual([ + 'loader.cjs', + ]); +}); + +it.each([false, true])('follows inline type imports according to verbatimModuleSyntax=%s', (verbatimModuleSyntax) => { + const root = fixture({ + 'tsconfig.json': JSON.stringify({ + compilerOptions: { module: 'esnext', moduleResolution: 'bundler', verbatimModuleSyntax }, + }), + 'settings.ts': 'export type Options = {}; export const value = 1;', + 'entry.ts': "import { type Options } from './settings'; export type Config = Options;", + 'whole.ts': "import type { Options } from './settings'; export type Config = Options;", + 'mixed.ts': "import { type Options, value } from './settings'; export const pair: [Options, number] = [{}, value];", + 'side.ts': "import './settings';", + }); + const inventory = scan(root); + const loadsSettings = (entry: string) => + reachability(inventory, [entry]).reached.some((node) => node.id === 'module:settings.ts'); + expect(loadsSettings('entry.ts')).toBe(verbatimModuleSyntax); + expect(loadsSettings('whole.ts')).toBe(false); + expect(loadsSettings('mixed.ts')).toBe(true); + expect(loadsSettings('side.ts')).toBe(true); +}); From d858121d283963df97948b0af500b0feeb649ed7 Mon Sep 17 00:00:00 2001 From: Andrey Rychkov Date: Mon, 30 Nov 2026 16:00:49 +0000 Subject: [PATCH 2/2] feat: trace indirect test impact and discover entries in 0.4.0 Show the call sites connecting changed declarations to candidate tests, expose change reports to CI, and explain the roots chosen from workspace manifests and Next.js handlers. --- README.md | 5 +- docs/reference.html | 29 ++++-- docs/report-schema.json | 167 ++++++++++++++++++++++++++++++++++- package-lock.json | 4 +- package.json | 2 +- src/change-impact.ts | 104 ++++++++++++++++++---- src/cli.ts | 40 +++++++-- src/discovery.ts | 4 +- src/index.ts | 4 +- src/next-routes.ts | 23 +++++ src/package-entries.ts | 83 ++++++++++++----- src/reachability.ts | 2 + src/report.ts | 1 + test/change-impact.test.ts | 33 +++++++ test/entry-discovery.test.ts | 48 ++++++++++ 15 files changed, 492 insertions(+), 57 deletions(-) create mode 100644 src/next-routes.ts create mode 100644 test/entry-discovery.test.ts diff --git a/README.md b/README.md index b3a9146..8535dd5 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,10 @@ The lines that follow identify each reference by file, line, column, kind, and s In a Git checkout, run `npx code-inventory . --changed-since main` to see the declarations touched by tracked source changes, their exports, and references grouped by caller or test file. Deleted files and removed base lines -appear separately. The query uses the current checkout, including staged and unstaged edits. +appear separately. Add `--format json` to consume one shortest call path per candidate test and changed declaration. The query uses the current checkout, including staged and unstaged edits. + +Use `--workspace-entries` to trace npm workspace packages and identify which manifest selected each file. +Use `--next-routes` at a Next.js app root to trace exported HTTP handlers. For convention-based entry points, use a quoted pattern such as `--entry-glob 'src/routes/**/+page.ts'`. Combine it with `--package-entries` to include a package’s public entry files. diff --git a/docs/reference.html b/docs/reference.html index 6973ded..e7cc52f 100644 --- a/docs/reference.html +++ b/docs/reference.html @@ -68,7 +68,21 @@

CLI options

declarations, including an enclosing declaration when the line also contains its own code. Reads include callback arguments. Test references identify source sites and do not establish runtime coverage. Removed lines use base coordinates. Deleted files and the old side of renames have no current declaration to query. - Use this option on its own with summary output. + Each candidate test has one shortest chain of resolved calls or constructions to the changed declaration. + Paths start at a site in a test file. An unexecuted helper in a test file may supply such a site. Use + summary or JSON output. The JSON report has kind change-impact, schemaVersion 1, baseTree, + snapshotId, diagnostics, changes and diff notes. Within each change, tests[].path lists located references + from the test toward the declaration. + +
--workspace-entries
+
+ Read the root and member manifests matched by the root npm workspaces array. Each entry origin lists the + manifest, field and analyzed file. Use --project for any required compiler output mapping. +
+
--next-routes
+
+ Select route.js and route.ts files under app or src/app in the scan root, excluding private folders. Model + both module initialization and invocation of exported HTTP methods identified in each route file.
--package-entries
@@ -210,16 +224,19 @@

Consuming the 0.x API

The package root exports scan, usages, findings, reachability, packageEntries and entryPath. scan reads a directory synchronously. The other queries operate on its inventory or reachability report, except - packageEntries(directory, inventory), which also reads the matching manifest and build configuration. Pass its - result to reachability. entryPath(report, symbolId) returns the ordered nodes of one shortest path, including - the selected file or invocation root and target, or null for an unreached ID. Select the ID with usages. Each - non-root node carries the edge kind and source location. summary, usageText and markdown render display text. + packageEntries(directory, inventory), which also reads the matching manifest and build configuration. + workspaceEntries(directory, inventory) returns manifest origins. nextRouteEntries(inventory) returns route + files and handler IDs. changeImpact(directory, base, inventory) queries Git against the current matching scan + and returns the structured change report. Pass the packageEntries result to reachability. entryPath(report, + symbolId) returns the ordered nodes of one shortest path, including the selected file or invocation root and + target, or null for an unreached ID. Select the ID with usages. Each non-root node carries the edge kind and + source location. summary, usageText and markdown render display text.

Saved reports and 0.x upgrades

Use --format json for scripts. The packaged JSON Schema lists the required properties, types, allowed values and nullable fields for each report. Summary, Markdown, - diagnostic messages and limitation text are for display. --changed-since produces a text summary. + diagnostic messages and limitation text are for display.

Full inventory
diff --git a/docs/report-schema.json b/docs/report-schema.json index d096a56..be0eb4c 100644 --- a/docs/report-schema.json +++ b/docs/report-schema.json @@ -10,6 +10,9 @@ }, { "$ref": "#/definitions/entryReport" + }, + { + "$ref": "#/definitions/impactReport" } ], "definitions": { @@ -444,7 +447,9 @@ }, "entrySymbols": { "type": "array", - "items": { "type": "string" } + "items": { + "type": "string" + } }, "reached": { "type": "array", @@ -506,6 +511,166 @@ "items": { "type": "string" } + }, + "entryOrigins": { + "type": "array", + "items": { + "type": "object", + "required": ["file", "manifest", "field"], + "properties": { + "file": { + "type": "string" + }, + "manifest": { + "type": "string" + }, + "field": { + "type": "string" + } + } + } + } + } + }, + "impactReport": { + "type": "object", + "required": [ + "kind", + "schemaVersion", + "base", + "baseTree", + "snapshotId", + "completeness", + "diagnostics", + "notes", + "changes" + ], + "properties": { + "kind": { + "const": "change-impact" + }, + "schemaVersion": { + "const": 1 + }, + "base": { + "type": "string" + }, + "baseTree": { + "type": "string" + }, + "snapshotId": { + "type": "string" + }, + "completeness": { + "enum": ["partial", "complete"] + }, + "diagnostics": { + "type": "array", + "items": { + "$ref": "#/definitions/diagnostic" + } + }, + "notes": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "object", + "required": ["kind", "file", "first", "last"], + "properties": { + "kind": { + "enum": ["removed-lines", "outside-declaration"] + }, + "file": { + "type": "string" + }, + "first": { + "type": "integer", + "minimum": 1 + }, + "last": { + "type": "integer", + "minimum": 1 + } + } + }, + { + "type": "object", + "required": ["kind", "file"], + "properties": { + "kind": { + "enum": ["deleted-file", "no-hunks"] + }, + "file": { + "type": "string" + } + } + }, + { + "type": "object", + "required": ["kind", "file", "reason"], + "properties": { + "kind": { + "const": "outside-scan" + }, + "file": { + "type": "string" + }, + "reason": { + "type": "string" + } + } + } + ] + } + }, + "changes": { + "type": "array", + "items": { + "type": "object", + "required": ["symbol", "references", "tests"], + "properties": { + "symbol": { + "$ref": "#/definitions/symbol" + }, + "references": { + "type": "array", + "items": { + "$ref": "#/definitions/reference" + } + }, + "tests": { + "type": "array", + "items": { + "type": "object", + "required": ["file", "path"], + "properties": { + "file": { + "type": "string" + }, + "path": { + "type": "array", + "items": { + "allOf": [ + { + "$ref": "#/definitions/reference" + }, + { + "properties": { + "kind": { + "enum": ["call", "construct"] + } + } + } + ] + }, + "minItems": 1 + } + } + } + } + } + } } } } diff --git a/package-lock.json b/package-lock.json index 6fbbbd7..9d47ec6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "code-inventory", - "version": "0.3.3", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "code-inventory", - "version": "0.3.3", + "version": "0.4.0", "license": "MIT", "dependencies": { "typescript": "npm:@typescript/typescript6@6.0.2" diff --git a/package.json b/package.json index 355e43e..b8de672 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "code-inventory", - "version": "0.3.3", + "version": "0.4.0", "license": "MIT", "type": "module", "description": "Static code inventory for JavaScript and TypeScript. Find symbol usages and trace paths from entry points.", diff --git a/src/change-impact.ts b/src/change-impact.ts index e535b46..20ab830 100644 --- a/src/change-impact.ts +++ b/src/change-impact.ts @@ -14,6 +14,30 @@ function git(directory: string, ...args: string[]): string { }); } +type DiffNote = + | { kind: 'removed-lines' | 'outside-declaration'; file: string; first: number; last: number } + | { kind: 'deleted-file' | 'no-hunks'; file: string } + | { kind: 'outside-scan'; file: string; reason: string }; + +function noteText(note: DiffNote): string { + switch (note.kind) { + case 'deleted-file': + return 'Deleted file: ' + note.file; + case 'no-hunks': + return 'No text hunks: ' + note.file; + case 'outside-scan': + return 'Outside scan: ' + note.file + ' (' + note.reason + ')'; + case 'removed-lines': + case 'outside-declaration': + return ( + (note.kind === 'removed-lines' ? 'Removed base lines: ' : 'Outside a declaration: ') + + note.file + + ':' + + range(note.first, note.last) + ); + } +} + function range(first: number, last: number): string { return first === last ? String(first) : `${first}-${last}`; } @@ -36,7 +60,7 @@ function mapHunks( source: string, declarations: CodeSymbol[], changed: Set, - notes: string[], + notes: DiffNote[], ): void { const starts = [0]; for (const newline of source.matchAll(/\n/g)) starts.push(newline.index + 1); @@ -50,7 +74,7 @@ function mapHunks( const oldCount = Number(hunk[2] ?? 1); const first = Number(hunk[3]); const count = Number(hunk[4] ?? 1); - if (oldCount) notes.push(`Removed base lines: ${file}:${range(oldStart, oldStart + oldCount - 1)}`); + if (oldCount) notes.push({ kind: 'removed-lines', file, first: oldStart, last: oldStart + oldCount - 1 }); let outsideStart: number | undefined; // A pure deletion has a zero-width position between two surviving lines. for (let line = first; line < first + Math.max(1, count); line++) { @@ -67,12 +91,12 @@ function mapHunks( } if (count && !active.length) outsideStart ??= line; if (outsideStart !== undefined && (active.length || line === first + count - 1)) { - notes.push(`Outside a declaration: ${file}:${range(outsideStart, active.length ? line - 1 : line)}`); + notes.push({ kind: 'outside-declaration', file, first: outsideStart, last: active.length ? line - 1 : line }); outsideStart = undefined; } } } - if (!hunks) notes.push(`No text hunks: ${file}`); + if (!hunks) notes.push({ kind: 'no-hunks', file }); } function groupBy(items: T[], keyOf: (item: T) => K): Map { @@ -105,8 +129,33 @@ function referenceGroups(references: Reference[], byId: Map) return Array.from(groups.values(), ({ label, sites }) => ` ${label}: ${sites.join(', ')}`); } +function testPaths(target: string, byTarget: Map) { + const queue = [target]; + const towardTarget = new Map(); + const tests = new Map(); + for (let index = 0; index < queue.length; index++) { + for (const ref of byTarget.get(queue[index]!) ?? []) { + if (ref.kind !== 'call' && ref.kind !== 'construct') continue; + if (ref.scope === 'test' && !tests.has(ref.location.file)) { + const path = [ref]; + let step = towardTarget.get(ref.targetId); + while (step) { + path.push(step); + step = towardTarget.get(step.targetId); + } + tests.set(ref.location.file, path); + } + if (ref.callerId && ref.callerId !== target && !towardTarget.has(ref.callerId)) { + towardTarget.set(ref.callerId, ref); + queue.push(ref.callerId); + } + } + } + return Array.from(tests, ([file, path]) => ({ file, path })); +} + /** Compare a tree to the tracked working tree, resolving references only in the current inventory. */ -export function changeImpactText(directory: string, base: string, inventory: Inventory): string { +export function changeImpact(directory: string, base: string, inventory: Inventory) { if (!base) throw new Error('Provide a Git revision for --changed-since.'); const tree = git(directory, 'rev-parse', '--verify', '--end-of-options', base + '^{tree}').trim(); const diff = ['diff', '--relative', '--no-ext-diff', '--no-textconv', '--no-renames', '--no-color']; @@ -114,18 +163,18 @@ export function changeImpactText(directory: string, base: string, inventory: Inv const files = new Map(inventory.files.map((file) => [file.path, file])); const symbolsByFile = groupBy(inventory.symbols, (symbol) => symbol.location.file); const changed = new Set(); - const notes: string[] = []; + const notes: DiffNote[] = []; for (let i = 0; i + 1 < fields.length; i += 2) { const status = fields[i]; const path = fields[i + 1]!; if (!sourceExtension.test(path)) continue; if (status === 'D') { - notes.push(`Deleted file: ${path}`); + notes.push({ kind: 'deleted-file', file: path }); continue; } const file = files.get(path); if (file?.status !== 'analyzed') { - notes.push(`Outside scan: ${path} (${file?.reason ?? 'not inventoried'})`); + notes.push({ kind: 'outside-scan', file: path, reason: file?.reason ?? 'not inventoried' }); continue; } const patch = git(directory, ...diff, '--unified=0', '--inter-hunk-context=0', tree, '--', path); @@ -133,20 +182,45 @@ export function changeImpactText(directory: string, base: string, inventory: Inv if (source === undefined) throw new Error(`Cannot read changed file: ${path}`); mapHunks(patch, path, source, symbolsByFile.get(path) ?? [], changed, notes); } - const byId = new Map(inventory.symbols.map((symbol) => [symbol.id, symbol])); const byTarget = groupBy(inventory.references, (ref) => ref.targetId); - const lines = [`Change impact since ${base}`]; - for (const symbol of changed) { + return { + schemaVersion: 1 as const, + kind: 'change-impact' as const, + base, + baseTree: tree, + snapshotId: inventory.snapshotId, + completeness: inventory.completeness, + diagnostics: inventory.diagnostics, + changes: Array.from(changed, (symbol) => ({ + symbol, + references: byTarget.get(symbol.id) ?? [], + tests: testPaths(symbol.id, byTarget), + })), + notes, + }; +} + +export function changeImpactText(report: ReturnType, inventory: Inventory): string { + const byId = new Map(inventory.symbols.map((symbol) => [symbol.id, symbol])); + const lines = [`Change impact since ${report.base}`]; + for (const { symbol, references, tests } of report.changes) { lines.push('', `${symbol.kind} ${symbol.name} (${symbol.location.file}:${symbol.location.line})`); if (symbol.exportedAs.length) lines.push(` Exports: ${symbol.exportedAs.join(', ')}`); - const groups = referenceGroups(byTarget.get(symbol.id) ?? [], byId); + const groups = referenceGroups(references, byId); lines.push(...(groups.length ? groups : [' No references found in this scan.'])); + for (const test of tests) { + const path = test.path.map((ref) => { + const at = ref.location; + return `${at.file}:${at.line}:${at.column} → ${byId.get(ref.targetId)?.name ?? ref.targetId}`; + }); + lines.push(' Candidate test ' + test.file + ': ' + path.join(', ')); + } } - if (!changed.size && !notes.length) lines.push('No tracked source changes.'); + if (!report.changes.length && !report.notes.length) lines.push('No tracked source changes.'); return [ ...lines, - ...notes, - `Analysis: ${inventory.completeness}; ${inventory.diagnostics.length} diagnostics`, + ...report.notes.map(noteText), + `Analysis: ${report.completeness}; ${report.diagnostics.length} diagnostics`, '', ].join('\n'); } diff --git a/src/cli.ts b/src/cli.ts index af2d844..a9f738e 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1,9 +1,19 @@ #!/usr/bin/env node import { parseArgs } from 'node:util'; import { writeFileSync } from 'node:fs'; -import { packageEntries, reachability, scan, markdown, summary, usages, usageText } from './index.ts'; +import { + workspaceEntries, + nextRouteEntries, + packageEntries, + reachability, + scan, + markdown, + summary, + usages, + usageText, +} from './index.ts'; -import { changeImpactText } from './change-impact.ts'; +import { changeImpact, changeImpactText } from './change-impact.ts'; import { reachabilityText } from './report.ts'; /** Run a read-only scan; output files must be new paths to avoid overwriting user work. */ @@ -11,6 +21,8 @@ function main(): void { const { values, positionals } = parseArgs({ allowPositionals: true, options: { + 'workspace-entries': { type: 'boolean' }, + 'next-routes': { type: 'boolean' }, 'package-entries': { type: 'boolean' }, 'entry-glob': { type: 'string', multiple: true }, 'entry-symbol': { type: 'string', multiple: true }, @@ -30,19 +42,25 @@ function main(): void { }); if (values.help) { process.stdout.write( - 'Usage: code-inventory [directory] [--entry source-file] [--entry-glob glob] [--entry-symbol name-or-id] [--package-entries] [--project config] [--exclude glob] [--test glob] [--tooling glob] [--production glob] [--format summary|json|markdown] [--symbol name-or-id] [--changed-since revision] [--output new-file] [--strict]\n', + 'Usage: code-inventory [directory] [--entry source-file] [--entry-glob glob] [--entry-symbol name-or-id] [--package-entries] [--workspace-entries] [--next-routes] [--project config] [--exclude glob] [--test glob] [--tooling glob] [--production glob] [--format summary|json|markdown] [--symbol name-or-id] [--changed-since revision] [--output new-file] [--strict]\n', ); return; } if (positionals.length > 1) throw new Error('Provide at most one directory.'); if (!['summary', 'json', 'markdown'].includes(values.format)) throw new Error(`Unknown format: ${values.format}`); const directory = positionals[0] ?? '.'; - const entryQuery = values.entry || values['entry-glob'] || values['entry-symbol'] || values['package-entries']; + const entryQuery = + values.entry || + values['entry-glob'] || + values['entry-symbol'] || + values['package-entries'] || + values['workspace-entries'] || + values['next-routes']; if (values.symbol && entryQuery) throw new Error('Select either entry points or --symbol.'); if (values.symbol && values.format === 'markdown') throw new Error('--symbol supports summary and json formats.'); const base = values['changed-since']; - if (base !== undefined && (entryQuery || values.symbol !== undefined || values.format !== 'summary')) - throw new Error('--changed-since is a standalone summary query.'); + if (base !== undefined && (entryQuery || values.symbol !== undefined || values.format === 'markdown')) + throw new Error('--changed-since is summary and json formats as a standalone query.'); const inventory = scan(directory, { projects: values.project ?? [], exclude: values.exclude ?? [], @@ -50,18 +68,24 @@ function main(): void { }); let output: string; if (base !== undefined) { - output = changeImpactText(directory, base, inventory); + const report = changeImpact(directory, base, inventory); + output = values.format === 'json' ? JSON.stringify(report, null, 2) + '\n' : changeImpactText(report, inventory); } else { + const origins = values['workspace-entries'] ? workspaceEntries(directory, inventory) : []; + const routes = values['next-routes'] ? nextRouteEntries(inventory) : { files: [], symbols: [] }; const entries = [ + ...origins.map((origin) => origin.file), + ...routes.files, ...(values.entry ?? []), ...(values['package-entries'] ? packageEntries(directory, inventory) : []), ]; const paths = entryQuery ? reachability(inventory, entries, { entryGlobs: values['entry-glob'] ?? [], - entrySymbols: values['entry-symbol'] ?? [], + entrySymbols: [...(values['entry-symbol'] ?? []), ...routes.symbols], }) : null; + if (paths && origins.length) paths.entryOrigins = origins; const selected = values.symbol ? usages(inventory, values.symbol) : null; output = values.format === 'json' diff --git a/src/discovery.ts b/src/discovery.ts index 425e498..a5ad52a 100644 --- a/src/discovery.ts +++ b/src/discovery.ts @@ -7,13 +7,13 @@ const excludedDirectories = new Set(['node_modules', '.git', 'dist', 'build', 'c export const sourceExtension = /\.(?:[cm]?[jt]s|[jt]sx)$/; /** Return sorted source paths without following symlinks or traversing build/dependency folders. */ -export function discover(root: string): string[] { +export function discover(root: string, matches = (name: string) => sourceExtension.test(name)): string[] { const files: string[] = []; function walk(directory: string): void { for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => compare(a.name, b.name))) { const path = resolve(directory, entry.name); if (entry.isDirectory() && !excludedDirectories.has(entry.name)) walk(path); - else if (entry.isFile() && sourceExtension.test(entry.name)) files.push(path); + else if (entry.isFile() && matches(entry.name)) files.push(path); } } walk(root); diff --git a/src/index.ts b/src/index.ts index c52d0d4..53e6af3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,4 +14,6 @@ export type { export type { ScanOptions } from './projects.ts'; export { entryPath, reachability } from './reachability.ts'; export type { Reachability } from './reachability.ts'; -export { packageEntries } from './package-entries.ts'; +export { packageEntries, workspaceEntries } from './package-entries.ts'; +export { changeImpact } from './change-impact.ts'; +export { nextRouteEntries } from './next-routes.ts'; diff --git a/src/next-routes.ts b/src/next-routes.ts new file mode 100644 index 0000000..4c8065c --- /dev/null +++ b/src/next-routes.ts @@ -0,0 +1,23 @@ +import type { Inventory } from './model.ts'; + +const methods = new Set(['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS']); + +export function nextRouteEntries(inventory: Inventory) { + const files = inventory.files + .filter( + (file) => + file.status === 'analyzed' && + /^(?:src\/)?app\/(?:[^/]+\/)*route\.[jt]s$/.test(file.path) && + !file.path.split('/').some((segment) => segment.startsWith('_')), + ) + .map((file) => file.path); + if (!files.length) throw new Error('No analyzed Next.js App Router route files.'); + const routes = new Set(files); + const symbols = new Set(); + for (const entry of inventory.exports) { + if (!routes.has(entry.file) || !methods.has(entry.name)) continue; + if (!entry.targetId) throw new Error('Cannot resolve route handler ' + entry.file + '#' + entry.name); + symbols.add(entry.targetId); + } + return { files, symbols: [...symbols].sort() }; +} diff --git a/src/package-entries.ts b/src/package-entries.ts index a989b89..f6784e2 100644 --- a/src/package-entries.ts +++ b/src/package-entries.ts @@ -1,7 +1,7 @@ import ts from 'typescript'; import type { Inventory } from './model.ts'; import { loadProjects } from './projects.ts'; -import { portablePath } from './discovery.ts'; +import { discover, portablePath } from './discovery.ts'; import { readFileSync } from 'node:fs'; import { resolve, posix } from 'node:path'; @@ -15,6 +15,8 @@ function capture(parts: string[], path: string): string | null { return parts.join(value) === path ? value : null; } +export type EntryOrigin = { file: string; manifest: string; field: string }; + type ExportPattern = { key: string; target: string }; function* expandPatterns(patterns: ExportPattern[], subpaths: string[], candidates: Set) { @@ -35,7 +37,7 @@ function* expandPatterns(patterns: ExportPattern[], subpaths: string[], candidat const subpath = key.replaceAll('*', () => value); if (exact.has(subpath)) continue; const winner = keys.find(({ parts }) => capture(parts, subpath) !== null); - if (winner?.key === key) yield path; + if (winner?.key === key) yield { path, key }; } if (!matched) throw new Error( @@ -48,15 +50,52 @@ function* expandPatterns(patterns: ExportPattern[], subpaths: string[], candidat /** Collect explicit runtime entry files from one package, across its declared conditions. */ export function packageEntries(directory: string, inventory: Inventory): string[] { - const manifest = JSON.parse(readFileSync(resolve(directory, 'package.json'), 'utf8')); - const files = new Set(); + return [...new Set(manifestEntries(directory, inventory, '', false).map((origin) => origin.file))].sort(); +} + +export function workspaceEntries(directory: string, inventory: Inventory): EntryOrigin[] { + const root = JSON.parse(readFileSync(resolve(directory, 'package.json'), 'utf8')); + const patterns: unknown = root.workspaces?.packages ?? root.workspaces; + if (!Array.isArray(patterns) || !patterns.every((p) => typeof p === 'string')) { + throw new Error('Expected an npm workspaces array in package.json.'); + } + const entries = manifestEntries(directory, inventory, '', true); + const manifests = discover(directory, (name) => name === 'package.json').map((path) => portablePath(directory, path)); + for (const manifest of manifests) { + if (manifest === 'package.json') continue; + const member = posix.dirname(manifest); + const selected = patterns.reduce((included: boolean, pattern: string) => { + const prefix = pattern.match(/^!*/)?.[0].length ?? 0; + const glob = pattern + .slice(prefix) + .replace(/^\.?\/+/, '') + .replace(/\/+$/, ''); + return posix.matchesGlob(member, glob) ? prefix % 2 === 0 : included; + }, false); + if (selected) { + entries.push(...manifestEntries(directory, inventory, member, true)); + } + } + if (!entries.length) throw new Error('No explicit runtime entries found in the selected workspaces.'); + return entries; +} + +function manifestEntries(directory: string, inventory: Inventory, member: string, allowEmpty: boolean): EntryOrigin[] { + const manifestPath = posix.join(member, 'package.json'); + const manifest = JSON.parse(readFileSync(resolve(directory, manifestPath), 'utf8')); + const files = new Map>(); + function remember(path: string, field: string) { + const fields = files.get(path) ?? new Set(); + fields.add(field); + files.set(path, fields); + } const patterns: ExportPattern[] = []; const exports = manifest.exports; const subpaths = exports && typeof exports === 'object' && Object.keys(exports).some((key) => key.startsWith('.')) ? Object.keys(exports) : []; - function add(target: unknown, key = ''): void { + function add(target: unknown, field: string, key = ''): void { if ( typeof target !== 'string' || !target || @@ -68,9 +107,9 @@ export function packageEntries(directory: string, inventory: Inventory): string[ throw new Error('Package entry requires an explicit local source path. Use --entry to select it.'); } if (/\.json$|\.d\.[cm]?ts$/.test(target)) return; - const path = posix.normalize(target); + const path = posix.join(member, target); if (path.includes('*')) patterns.push({ key, target: path }); - else files.add(path); + else remember(path, field); } function collect(target: unknown, key = ''): void { if (target === null) return; @@ -80,21 +119,23 @@ export function packageEntries(directory: string, inventory: Inventory): string[ for (const [condition, value] of Object.entries(target)) { if (condition !== 'types' && !condition.startsWith('types@')) collect(value, key); } - } else add(target, key); + } else add(target, key ? 'exports[' + key + ']' : 'exports', key); } if (subpaths.length) { for (const key of subpaths) collect(exports[key], key); } else if ('exports' in manifest) collect(exports); - else if ('main' in manifest) add(manifest.main); - if (typeof manifest.bin === 'string') add(manifest.bin); - else if (manifest.bin) Object.values(manifest.bin).forEach((target) => add(target)); + else if ('main' in manifest) add(manifest.main, 'main'); + if (typeof manifest.bin === 'string') add(manifest.bin, 'bin'); + else if (manifest.bin) Object.entries(manifest.bin).forEach(([name, target]) => add(target, 'bin.' + name)); const analyzed = new Set(inventory.files.filter((file) => file.status === 'analyzed').map((file) => file.path)); if (!patterns.length) { + if (!files.size && allowEmpty) return []; if (!files.size) throw new Error('No explicit package entries. Select a source file with --entry.'); - if ([...files].every((file) => analyzed.has(file))) return [...files].sort(); } const sources = new Map>(); - for (const project of loadProjects(directory, inventory.config.entries).ordered) { + for (const project of patterns.length || [...files.keys()].some((file) => !analyzed.has(file)) + ? loadProjects(directory, inventory.config.entries).ordered + : []) { if (!project.path || project.options.noEmit || project.options.emitDeclarationOnly) continue; const config = { options: project.options, fileNames: [...project.files], errors: [] }; for (const input of project.files) { @@ -110,13 +151,14 @@ export function packageEntries(directory: string, inventory: Inventory): string[ } } if (patterns.length) { - for (const file of expandPatterns(patterns, subpaths, new Set([...analyzed, ...sources.keys()]))) files.add(file); + for (const { path, key } of expandPatterns(patterns, subpaths, new Set([...analyzed, ...sources.keys()]))) + remember(path, 'exports[' + key + ']'); if (!files.size) throw new Error('No analyzed files are exposed by these package entries.'); } - const roots = new Set(); - for (const file of files) { - if (analyzed.has(file)) roots.add(file); - else { + const roots: EntryOrigin[] = []; + for (const [file, fields] of files) { + let source = file; + if (!analyzed.has(file)) { const candidates = [...(sources.get(file) ?? [])]; if (candidates.length !== 1) throw new Error( @@ -124,8 +166,9 @@ export function packageEntries(directory: string, inventory: Inventory): string[ file + '. Select the build config with --project or use --entry.', ); - roots.add(candidates[0]!); + source = candidates[0]!; } + for (const field of fields) roots.push({ file: source, manifest: manifestPath, field }); } - return [...roots].sort(); + return roots; } diff --git a/src/reachability.ts b/src/reachability.ts index ca83ba4..00ed918 100644 --- a/src/reachability.ts +++ b/src/reachability.ts @@ -1,4 +1,5 @@ import { posix } from 'node:path'; +import type { EntryOrigin } from './package-entries.ts'; import { selectSymbol } from './query.ts'; import type { CodeSymbol, Inventory, Location, ModuleReference } from './model.ts'; @@ -12,6 +13,7 @@ export interface Reachability { snapshotId: string; entries: string[]; entrySymbols?: string[]; + entryOrigins?: EntryOrigin[]; completeness: Inventory['completeness']; diagnostics: Inventory['diagnostics']; /** One shortest-path predecessor per reached module or declaration. Roots have no predecessor. */ diff --git a/src/report.ts b/src/report.ts index 4a45dbc..1d4571a 100644 --- a/src/report.ts +++ b/src/report.ts @@ -100,6 +100,7 @@ export function reachabilityText(report: Reachability, detailed: boolean): strin const missing = report.declarations.filter((symbol) => symbol.status === 'no-known-path'); const lines = [ ...(report.entries.length ? ['Entry files: ' + report.entries.join(', ')] : []), + ...(report.entryOrigins ?? []).map((origin) => origin.file + ' from ' + origin.manifest + ' ' + origin.field), ...(report.entrySymbols?.length ? ['Assumed invocations: ' + report.entrySymbols.join(', ')] : []), report.declarations.length - missing.length + ' reachable declarations, ' + missing.length + ' with no known path', 'Analysis: ' + report.completeness + '; ' + report.diagnostics.length + ' diagnostics', diff --git a/test/change-impact.test.ts b/test/change-impact.test.ts index f77ccee..991b121 100644 --- a/test/change-impact.test.ts +++ b/test/change-impact.test.ts @@ -1,3 +1,4 @@ +import Ajv from 'ajv'; import { execFileSync, spawnSync } from 'node:child_process'; import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -83,3 +84,35 @@ it('keeps the enclosing function when a changed line also contains a callback', expect(result.stdout).toContain('function outer (nested.ts:1)'); expect(result.stdout).toContain('call nested.ts:2:1'); }); + +it('traces a shortest test path through a recursive wrapper and excludes reads and unrelated callers', () => { + const { directory, git, run } = repository(); + writeFileSync(join(directory, 'leaf.ts'), 'export function leaf(){return 1;}\nexport function other(){return 0;}\n'); + writeFileSync( + join(directory, 'wrapper.ts'), + "import {leaf} from './leaf'; export function wrap(n:number):number{return n ? wrap(n-1) : leaf();}", + ); + writeFileSync(join(directory, 'indirect.test.ts'), "import {wrap} from './wrapper'; wrap(1);"); + writeFileSync(join(directory, 'other.test.ts'), "import {leaf,other} from './leaf'; void leaf; other();"); + git('add', '--', 'package'); + const base = git('write-tree'); + writeFileSync(join(directory, 'leaf.ts'), 'export function leaf(){return 2;}\nexport function other(){return 0;}\n'); + const result = run(base, '--format', 'json'); + expect(result.status).toBe(0); + const report = JSON.parse(result.stdout); + const validate = new Ajv().compile( + JSON.parse(readFileSync(new URL('../docs/report-schema.json', import.meta.url), 'utf8')), + ); + expect(validate(report), JSON.stringify(validate.errors)).toBe(true); + expect(report.changes).toHaveLength(1); + expect(report.changes[0].tests).toHaveLength(1); + expect(report.changes[0].tests[0]).toMatchObject({ + file: 'indirect.test.ts', + path: [{ location: { file: 'indirect.test.ts' } }, { location: { file: 'wrapper.ts' } }], + }); + expect(run(base).stdout).toContain('Candidate test indirect.test.ts'); + writeFileSync(join(directory, 'broken.ts'), "import './missing';"); + const partial = run(base, '--format', 'json', '--strict'); + expect(partial.status).toBe(2); + expect(JSON.parse(partial.stdout).diagnostics.length).toBeGreaterThan(0); +}); diff --git a/test/entry-discovery.test.ts b/test/entry-discovery.test.ts new file mode 100644 index 0000000..7a18709 --- /dev/null +++ b/test/entry-discovery.test.ts @@ -0,0 +1,48 @@ +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { expect, it, onTestFinished } from 'vitest'; + +it('reports workspace manifest origins and scopes HTTP handler invocations to each route', () => { + const root = mkdtempSync(join(tmpdir(), 'workspace-entries-')); + onTestFinished(() => rmSync(root, { recursive: true, force: true })); + const files: Record = { + 'package.json': JSON.stringify({ private: true, workspaces: ['packages/*', '!packages/ignored'] }), + 'packages/ignored/package.json': JSON.stringify({ main: './absent.ts' }), + 'packages/lib/package.json': JSON.stringify({ exports: { '.': './service.ts' } }), + 'packages/lib/service.ts': 'export function serve() {}', + 'packages/cli/package.json': JSON.stringify({ bin: { example: './cli.ts' } }), + 'packages/cli/cli.ts': "import {serve} from '../lib/service'; serve();", + 'app/a/route.ts': 'export function GET(){ one(); } function one() {} export function helper() {}', + 'app/b/route.ts': 'export function GET(){ two(); } function two() {}', + 'app/_private/route.ts': 'export function GET(){}', + }; + for (const [path, content] of Object.entries(files)) { + mkdirSync(dirname(join(root, path)), { recursive: true }); + writeFileSync(join(root, path), content); + } + const result = spawnSync( + process.execPath, + [resolve(import.meta.dirname, '../dist/cli.js'), root, '--workspace-entries', '--next-routes', '--format', 'json'], + { encoding: 'utf8' }, + ); + expect(result.stderr).toBe(''); + const report = JSON.parse(result.stdout); + expect(report.entryOrigins).toEqual([ + { file: 'packages/cli/cli.ts', manifest: 'packages/cli/package.json', field: 'bin.example' }, + { file: 'packages/lib/service.ts', manifest: 'packages/lib/package.json', field: 'exports[.]' }, + ]); + expect(report.entries).toEqual([ + 'app/a/route.ts', + 'app/b/route.ts', + 'packages/cli/cli.ts', + 'packages/lib/service.ts', + ]); + expect( + report.declarations + .filter((s: { status: string }) => s.status === 'reachable') + .map((s: { name: string }) => s.name) + .sort(), + ).toEqual(['GET', 'GET', 'one', 'serve', 'two']); +});