import type { CodeGraph } from "../contract/views.ts"; import { readCommit, readTree } from "../diff.ts"; import { buildGraph, join, type SourceFile, type WorkspacePackage } from "./graph.ts"; export const MAX_SOURCE_FILES = 3000; export const MAX_SOURCE_FILE_BYTES = 256 * 1024; const MAX_TREE_ENTRIES = 60_000; const MAX_PACKAGE_FILES = 200; const READ_CONCURRENCY = 16; const SOURCE_FILE = /\.(tsx?|mts|cts|jsx?|mjs|cjs)$/; const NOT_SOURCE = /(\.d\.(m|c)?ts|\.min\.js)$/; const SKIPPED_FOLDERS = new Set(["node_modules", "dist", "build", "out", "coverage", "vendor", ".git", ".next", ".react-router", ".wrangler", ".turbo", ".cache"]); export class CommitNotFoundError extends Error { readonly commit: string; constructor(commit: string) { super(`Commit ${commit} was not found.`); this.commit = commit; this.name = "CommitNotFoundError"; } } interface TreeFile { readonly path: string; readonly hash: string; } /** Builds the code map of one commit from its TypeScript and JavaScript files. Commits never change, so the result never does either. */ export async function indexCommit(handle: ArtifactsRepo, commitSha: string): Promise { const commit = await readCommit(handle, commitSha); if (!commit) throw new CommitNotFoundError(commitSha); const files = await walk(handle, commit.treeHash); const candidates = files.filter((file) => SOURCE_FILE.test(file.path) && !NOT_SOURCE.test(file.path)); const chosen = candidates.slice(0, MAX_SOURCE_FILES); const [read, packages] = await Promise.all([readSources(handle, chosen), readPackages(handle, files.filter((file) => file.path === "package.json" || file.path.endsWith("/package.json")).slice(0, MAX_PACKAGE_FILES))]); const sources = read.filter((file): file is SourceFile => file !== null); return buildGraph(commitSha, sources, packages, candidates.length - sources.length); } async function walk(handle: ArtifactsRepo, treeHash: string): Promise { const found: TreeFile[] = []; let level: { hash: string; prefix: string }[] = [{ hash: treeHash, prefix: "" }]; let seen = 0; while (level.length && seen < MAX_TREE_ENTRIES) { const trees = await Promise.all(level.map(async (tree) => ({ tree, entries: (await readTree(handle, tree.hash)) ?? [] }))); level = []; for (const { tree, entries } of trees) { for (const entry of entries) { seen++; const path = tree.prefix ? `${tree.prefix}/${entry.name}` : entry.name; if (entry.type === "tree") { if (!SKIPPED_FOLDERS.has(entry.name)) level.push({ hash: entry.hash, prefix: path }); } else if (entry.type === "blob" || entry.type === "exec") found.push({ path, hash: entry.hash }); } } } return found.sort((a, b) => a.path.localeCompare(b.path)); } async function readSources(handle: ArtifactsRepo, files: readonly TreeFile[]): Promise<(SourceFile | null)[]> { return pool(files, async (file) => { const blob = await handle.readBlob(file.hash); if (!blob || blob.size > MAX_SOURCE_FILE_BYTES) return null; return { path: file.path, text: await blob.text() }; }); } async function readPackages(handle: ArtifactsRepo, files: readonly TreeFile[]): Promise { const read = await pool(files, async (file) => { const blob = await handle.readBlob(file.hash); return blob ? toPackage(file.path, await blob.text()) : null; }); return read.filter((entry): entry is WorkspacePackage => entry !== null); } /** A package's name and the files its `exports` map names, from its package.json text. */ export function toPackage(path: string, text: string): WorkspacePackage | null { let manifest: unknown; try { manifest = JSON.parse(text); } catch { return null; } if (typeof manifest !== "object" || manifest === null) return null; const { name, exports, main } = manifest as { name?: unknown; exports?: unknown; main?: unknown }; if (typeof name !== "string") return null; const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : ""; const mapped = new Map(); const target = (value: unknown): string | null => { if (typeof value === "string") return value; if (typeof value === "object" && value !== null) { const conditions = value as Record; return target(conditions.import ?? conditions.default ?? conditions.types ?? conditions.require ?? null); } return null; }; if (typeof exports === "string") mapped.set(".", exports); else if (typeof exports === "object" && exports !== null) { const entries = Object.entries(exports as Record); if (entries.every(([key]) => key.startsWith("."))) for (const [key, value] of entries) { const file = target(value); if (file) mapped.set(key, file); } else { const file = target(exports); if (file) mapped.set(".", file); } } if (!mapped.has(".") && typeof main === "string") mapped.set(".", main); return { name, dir, exports: new Map([...mapped].map(([key, value]) => [key, join("", value)])) }; } async function pool(items: readonly T[], work: (item: T) => Promise): Promise { const results = new Array(items.length); let next = 0; const worker = async () => { while (next < items.length) { const index = next++; results[index] = await work(items[index]); } }; await Promise.all(Array.from({ length: Math.min(READ_CONCURRENCY, items.length) }, worker)); return results; }