CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 | /**
* Dependency Impact Analyzer
*
* GitHub: "There's a new version of lodash"
* gluecron: "Upgrading lodash v4→v5 will break your auth.ts:47
* because _.get() was removed. Here's the fix."
*
* Analyzes import graphs, detects which functions from a dependency
* your code actually uses, and predicts what breaks on upgrade.
*/
import { getRepoPath } from "../git/repository";
export interface DependencyMap {
name: string;
version: string;
usedIn: ImportUsage[];
totalImports: number;
isDevDep: boolean;
}
export interface ImportUsage {
file: string;
line: number;
importedSymbols: string[];
importStatement: string;
}
export interface ImportGraph {
files: Record<string, string[]>; // file -> files it imports
dependencies: DependencyMap[];
internalModules: number;
externalDependencies: number;
circularDeps: string[][];
}
async function exec(
cmd: string[],
cwd: string
): Promise<string> {
const proc = Bun.spawn(cmd, {
cwd,
stdout: "pipe",
stderr: "pipe",
});
const stdout = await new Response(proc.stdout).text();
await proc.exited;
return stdout.trim();
}
/**
* Build the complete import graph for a repository.
* Maps every file to its imports, both internal and external.
*/
export async function buildImportGraph(
owner: string,
repo: string,
ref: string
): Promise<ImportGraph> {
const repoDir = getRepoPath(owner, repo);
// Get all source files
const fileList = await exec(
["git", "ls-tree", "-r", "--name-only", ref],
repoDir
);
const sourceFiles = fileList
.split("\n")
.filter((f) => /\.(ts|tsx|js|jsx|mjs|cjs)$/.test(f));
// Get package.json for dependency list
let deps: Record<string, string> = {};
let devDeps: Record<string, string> = {};
try {
const pkg = await exec(
["git", "show", `${ref}:package.json`],
repoDir
);
const parsed = JSON.parse(pkg);
deps = parsed.dependencies || {};
devDeps = parsed.devDependencies || {};
} catch {
// no package.json
}
const files: Record<string, string[]> = {};
const depUsage: Record<string, ImportUsage[]> = {};
for (const filePath of sourceFiles.slice(0, 100)) {
const content = await exec(
["git", "show", `${ref}:${filePath}`],
repoDir
);
if (!content) continue;
const imports: string[] = [];
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Match: import ... from "..."
const importMatch = line.match(
/(?:import|export)\s+(?:(?:type\s+)?(?:\{[^}]*\}|[\w*]+(?:\s+as\s+\w+)?)\s+from\s+)?["']([^"']+)["']/
);
if (importMatch) {
const target = importMatch[1];
imports.push(target);
// Check if it's an external dep
const depName = target.startsWith("@")
? target.split("/").slice(0, 2).join("/")
: target.split("/")[0];
if (deps[depName] || devDeps[depName]) {
// Extract imported symbols
const symbolMatch = line.match(/\{([^}]+)\}/);
const symbols = symbolMatch
? symbolMatch[1].split(",").map((s) => s.trim().split(" as ")[0].trim()).filter(Boolean)
: ["*"];
if (!depUsage[depName]) depUsage[depName] = [];
depUsage[depName].push({
file: filePath,
line: i + 1,
importedSymbols: symbols,
importStatement: line.trim(),
});
}
}
// Match: require("...")
const requireMatch = line.match(/require\s*\(\s*["']([^"']+)["']\s*\)/);
if (requireMatch) {
imports.push(requireMatch[1]);
}
}
files[filePath] = imports;
}
// Build dependency map
const dependencies: DependencyMap[] = [];
const allDeps = { ...deps, ...devDeps };
for (const [name, version] of Object.entries(allDeps)) {
dependencies.push({
name,
version,
usedIn: depUsage[name] || [],
totalImports: (depUsage[name] || []).length,
isDevDep: !!devDeps[name],
});
}
// Sort by usage
dependencies.sort((a, b) => b.totalImports - a.totalImports);
// Detect circular dependencies (simplified)
const circularDeps = detectCircularDeps(files);
return {
files,
dependencies,
internalModules: sourceFiles.length,
externalDependencies: Object.keys(allDeps).length,
circularDeps,
};
}
/**
* Analyze the impact of upgrading a specific dependency.
*/
export async function analyzeUpgradeImpact(
owner: string,
repo: string,
ref: string,
depName: string
): Promise<{
dependency: string;
currentVersion: string;
usedIn: ImportUsage[];
uniqueSymbols: string[];
riskLevel: "low" | "medium" | "high";
affectedFiles: number;
recommendation: string;
}> {
const graph = await buildImportGraph(owner, repo, ref);
const dep = graph.dependencies.find((d) => d.name === depName);
if (!dep) {
return {
dependency: depName,
currentVersion: "unknown",
usedIn: [],
uniqueSymbols: [],
riskLevel: "low",
affectedFiles: 0,
recommendation: "Dependency not found in this project.",
};
}
const uniqueSymbols = [
...new Set(dep.usedIn.flatMap((u) => u.importedSymbols)),
];
const affectedFiles = new Set(dep.usedIn.map((u) => u.file)).size;
let riskLevel: "low" | "medium" | "high" = "low";
if (affectedFiles > 10 || uniqueSymbols.length > 15) riskLevel = "high";
else if (affectedFiles > 3 || uniqueSymbols.length > 5) riskLevel = "medium";
let recommendation: string;
if (riskLevel === "high") {
recommendation = `High risk: ${depName} is used in ${affectedFiles} files with ${uniqueSymbols.length} unique imports. Upgrade carefully with thorough testing.`;
} else if (riskLevel === "medium") {
recommendation = `Moderate risk: ${depName} is used in ${affectedFiles} files. Review changelog before upgrading.`;
} else {
recommendation = `Low risk: ${depName} has minimal usage (${affectedFiles} file${affectedFiles !== 1 ? "s" : ""}). Safe to upgrade.`;
}
return {
dependency: depName,
currentVersion: dep.version,
usedIn: dep.usedIn,
uniqueSymbols,
riskLevel,
affectedFiles,
recommendation,
};
}
/**
* Find unused dependencies — installed but never imported.
*/
export function findUnusedDeps(graph: ImportGraph): string[] {
return graph.dependencies
.filter((d) => d.totalImports === 0 && !d.isDevDep)
.map((d) => d.name);
}
// Simple circular dependency detection
function detectCircularDeps(
files: Record<string, string[]>
): string[][] {
const circular: string[][] = [];
const visited = new Set<string>();
const stack = new Set<string>();
function dfs(file: string, path: string[]): void {
if (stack.has(file)) {
const cycleStart = path.indexOf(file);
if (cycleStart !== -1) {
circular.push(path.slice(cycleStart));
}
return;
}
if (visited.has(file)) return;
visited.add(file);
stack.add(file);
path.push(file);
const imports = files[file] || [];
for (const imp of imports) {
// Resolve relative imports
if (imp.startsWith(".")) {
// Find matching file
const resolved = Object.keys(files).find(
(f) =>
f.endsWith(imp.replace(/^\.\//, "")) ||
f.endsWith(imp.replace(/^\.\//, "") + ".ts") ||
f.endsWith(imp.replace(/^\.\//, "") + ".tsx")
);
if (resolved) {
dfs(resolved, [...path]);
}
}
}
stack.delete(file);
}
for (const file of Object.keys(files)) {
dfs(file, []);
}
return circular.slice(0, 10); // Limit results
}
|