Skip to content
refs
125 lines · 5.4 KBRaw
1import type { CodeGraph } from "../contract/views.ts";
2import { readCommit, readTree } from "../diff.ts";
3import { buildGraph, join, type SourceFile, type WorkspacePackage } from "./graph.ts";
4
5export const MAX_SOURCE_FILES = 3000;
6export const MAX_SOURCE_FILE_BYTES = 256 * 1024;
7const MAX_TREE_ENTRIES = 60_000;
8const MAX_PACKAGE_FILES = 200;
9const READ_CONCURRENCY = 16;
10const SOURCE_FILE = /\.(tsx?|mts|cts|jsx?|mjs|cjs)$/;
11const NOT_SOURCE = /(\.d\.(m|c)?ts|\.min\.js)$/;
12const SKIPPED_FOLDERS = new Set(["node_modules", "dist", "build", "out", "coverage", "vendor", ".git", ".next", ".react-router", ".wrangler", ".turbo", ".cache"]);
13
14export class CommitNotFoundError extends Error {
15 readonly commit: string;
16
17 constructor(commit: string) {
18 super(`Commit ${commit} was not found.`);
19 this.commit = commit;
20 this.name = "CommitNotFoundError";
21 }
22}
23
24interface TreeFile {
25 readonly path: string;
26 readonly hash: string;
27}
28
29/** Builds the code map of one commit from its TypeScript and JavaScript files. Commits never change, so the result never does either. */
30export async function indexCommit(handle: ArtifactsRepo, commitSha: string): Promise<CodeGraph> {
31 const commit = await readCommit(handle, commitSha);
32 if (!commit) throw new CommitNotFoundError(commitSha);
33 const files = await walk(handle, commit.treeHash);
34 const candidates = files.filter((file) => SOURCE_FILE.test(file.path) && !NOT_SOURCE.test(file.path));
35 const chosen = candidates.slice(0, MAX_SOURCE_FILES);
36 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))]);
37 const sources = read.filter((file): file is SourceFile => file !== null);
38 return buildGraph(commitSha, sources, packages, candidates.length - sources.length);
39}
40
41async function walk(handle: ArtifactsRepo, treeHash: string): Promise<TreeFile[]> {
42 const found: TreeFile[] = [];
43 let level: { hash: string; prefix: string }[] = [{ hash: treeHash, prefix: "" }];
44 let seen = 0;
45 while (level.length && seen < MAX_TREE_ENTRIES) {
46 const trees = await Promise.all(level.map(async (tree) => ({ tree, entries: (await readTree(handle, tree.hash)) ?? [] })));
47 level = [];
48 for (const { tree, entries } of trees) {
49 for (const entry of entries) {
50 seen++;
51 const path = tree.prefix ? `${tree.prefix}/${entry.name}` : entry.name;
52 if (entry.type === "tree") {
53 if (!SKIPPED_FOLDERS.has(entry.name)) level.push({ hash: entry.hash, prefix: path });
54 } else if (entry.type === "blob" || entry.type === "exec") found.push({ path, hash: entry.hash });
55 }
56 }
57 }
58 return found.sort((a, b) => a.path.localeCompare(b.path));
59}
60
61async function readSources(handle: ArtifactsRepo, files: readonly TreeFile[]): Promise<(SourceFile | null)[]> {
62 return pool(files, async (file) => {
63 const blob = await handle.readBlob(file.hash);
64 if (!blob || blob.size > MAX_SOURCE_FILE_BYTES) return null;
65 return { path: file.path, text: await blob.text() };
66 });
67}
68
69async function readPackages(handle: ArtifactsRepo, files: readonly TreeFile[]): Promise<WorkspacePackage[]> {
70 const read = await pool(files, async (file) => {
71 const blob = await handle.readBlob(file.hash);
72 return blob ? toPackage(file.path, await blob.text()) : null;
73 });
74 return read.filter((entry): entry is WorkspacePackage => entry !== null);
75}
76
77/** A package's name and the files its `exports` map names, from its package.json text. */
78export function toPackage(path: string, text: string): WorkspacePackage | null {
79 let manifest: unknown;
80 try {
81 manifest = JSON.parse(text);
82 } catch {
83 return null;
84 }
85 if (typeof manifest !== "object" || manifest === null) return null;
86 const { name, exports, main } = manifest as { name?: unknown; exports?: unknown; main?: unknown };
87 if (typeof name !== "string") return null;
88 const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
89 const mapped = new Map<string, string>();
90 const target = (value: unknown): string | null => {
91 if (typeof value === "string") return value;
92 if (typeof value === "object" && value !== null) {
93 const conditions = value as Record<string, unknown>;
94 return target(conditions.import ?? conditions.default ?? conditions.types ?? conditions.require ?? null);
95 }
96 return null;
97 };
98 if (typeof exports === "string") mapped.set(".", exports);
99 else if (typeof exports === "object" && exports !== null) {
100 const entries = Object.entries(exports as Record<string, unknown>);
101 if (entries.every(([key]) => key.startsWith("."))) for (const [key, value] of entries) {
102 const file = target(value);
103 if (file) mapped.set(key, file);
104 }
105 else {
106 const file = target(exports);
107 if (file) mapped.set(".", file);
108 }
109 }
110 if (!mapped.has(".") && typeof main === "string") mapped.set(".", main);
111 return { name, dir, exports: new Map([...mapped].map(([key, value]) => [key, join("", value)])) };
112}
113
114async function pool<T, R>(items: readonly T[], work: (item: T) => Promise<R>): Promise<R[]> {
115 const results = new Array<R>(items.length);
116 let next = 0;
117 const worker = async () => {
118 while (next < items.length) {
119 const index = next++;
120 results[index] = await work(items[index]);
121 }
122 };
123 await Promise.all(Array.from({ length: Math.min(READ_CONCURRENCY, items.length) }, worker));
124 return results;
125}