Open History to see the last commit
1import fs from "node:fs/promises";
2import type { Dirent } from "node:fs";
3import path from "node:path";
4import { runProcess } from "./processRunner";
5
6import {
7 projectSearchEntriesInputSchema,
8 type ProjectEntry,
9 type ProjectSearchEntriesInput,
10 type ProjectSearchEntriesResult,
11} from "@t3tools/contracts";
12
13const WORKSPACE_CACHE_TTL_MS = 15_000;
14const WORKSPACE_CACHE_MAX_KEYS = 4;
15const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
16const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32;
17const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
18const IGNORED_DIRECTORY_NAMES = new Set([
19 ".git",
20 ".convex",
21 "node_modules",
22 ".next",
23 ".turbo",
24 "dist",
25 "build",
26 "out",
27 ".cache",
28]);
29
30interface WorkspaceIndex {
31 scannedAt: number;
32 entries: ProjectEntry[];
33 truncated: boolean;
34}
35
36const workspaceIndexCache = new Map<string, WorkspaceIndex>();
37const inFlightWorkspaceIndexBuilds = new Map<string, Promise<WorkspaceIndex>>();
38
39function toPosixPath(input: string): string {
40 return input.split(path.sep).join("/");
41}
42
43function parentPathOf(input: string): string | undefined {
44 const separatorIndex = input.lastIndexOf("/");
45 if (separatorIndex === -1) {
46 return undefined;
47 }
48 return input.slice(0, separatorIndex);
49}
50
51function basenameOf(input: string): string {
52 const separatorIndex = input.lastIndexOf("/");
53 if (separatorIndex === -1) {
54 return input;
55 }
56 return input.slice(separatorIndex + 1);
57}
58
59function normalizeQuery(input: string): string {
60 return input
61 .trim()
62 .replace(/^[@./]+/, "")
63 .toLowerCase();
64}
65
66function scoreEntry(entry: ProjectEntry, query: string): number {
67 if (!query) {
68 return entry.kind === "directory" ? 0 : 1;
69 }
70
71 const normalizedPath = entry.path.toLowerCase();
72 const normalizedName = basenameOf(normalizedPath);
73
74 if (normalizedName === query) return 0;
75 if (normalizedPath === query) return 1;
76 if (normalizedName.startsWith(query)) return 2;
77 if (normalizedPath.startsWith(query)) return 3;
78 if (normalizedPath.includes(`/${query}`)) return 4;
79 return 5;
80}
81
82function isPathInIgnoredDirectory(relativePath: string): boolean {
83 const firstSegment = relativePath.split("/")[0];
84 if (!firstSegment) return false;
85 return IGNORED_DIRECTORY_NAMES.has(firstSegment);
86}
87
88function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
89 const parts = input.split("\0");
90 if (parts.length === 0) return [];
91
92 // If output was truncated, the final token can be partial.
93 if (truncated && parts[parts.length - 1]?.length) {
94 parts.pop();
95 }
96
97 return parts.filter((value) => value.length > 0);
98}
99
100function directoryAncestorsOf(relativePath: string): string[] {
101 const segments = relativePath.split("/").filter((segment) => segment.length > 0);
102 if (segments.length <= 1) return [];
103 const directories: string[] = [];
104 for (let index = 1; index < segments.length; index += 1) {
105 directories.push(segments.slice(0, index).join("/"));
106 }
107 return directories;
108}
109
110async function mapWithConcurrency<TInput, TOutput>(
111 items: readonly TInput[],
112 concurrency: number,
113 mapper: (item: TInput, index: number) => Promise<TOutput>,
114): Promise<TOutput[]> {
115 if (items.length === 0) {
116 return [];
117 }
118
119 const boundedConcurrency = Math.max(1, Math.min(concurrency, items.length));
120 const results = Array.from({ length: items.length }) as TOutput[];
121 let nextIndex = 0;
122
123 const workers = Array.from({ length: boundedConcurrency }, async () => {
124 while (nextIndex < items.length) {
125 const currentIndex = nextIndex;
126 nextIndex += 1;
127 results[currentIndex] = await mapper(items[currentIndex] as TInput, currentIndex);
128 }
129 });
130
131 await Promise.all(workers);
132 return results;
133}
134
135async function isInsideGitWorkTree(cwd: string): Promise<boolean> {
136 const insideWorkTree = await runProcess("git", ["rev-parse", "--is-inside-work-tree"], {
137 cwd,
138 allowNonZeroExit: true,
139 timeoutMs: 5_000,
140 maxBufferBytes: 4_096,
141 }).catch(() => null);
142 return Boolean(
143 insideWorkTree && insideWorkTree.code === 0 && insideWorkTree.stdout.trim() === "true",
144 );
145}
146
147async function filterGitIgnoredPaths(cwd: string, relativePaths: string[]): Promise<string[]> {
148 if (relativePaths.length === 0) {
149 return relativePaths;
150 }
151
152 const ignoredPaths = new Set<string>();
153 let chunk: string[] = [];
154 let chunkBytes = 0;
155
156 const flushChunk = async (): Promise<boolean> => {
157 if (chunk.length === 0) {
158 return true;
159 }
160
161 const checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], {
162 cwd,
163 allowNonZeroExit: true,
164 timeoutMs: 20_000,
165 maxBufferBytes: 16 * 1024 * 1024,
166 outputMode: "truncate",
167 stdin: `${chunk.join("\0")}\0`,
168 }).catch(() => null);
169 chunk = [];
170 chunkBytes = 0;
171
172 if (!checkIgnore) {
173 return false;
174 }
175
176 // git-check-ignore exits with 1 when no paths match.
177 if (checkIgnore.code !== 0 && checkIgnore.code !== 1) {
178 return false;
179 }
180
181 const matchedIgnoredPaths = splitNullSeparatedPaths(
182 checkIgnore.stdout,
183 Boolean(checkIgnore.stdoutTruncated),
184 );
185 for (const ignoredPath of matchedIgnoredPaths) {
186 ignoredPaths.add(ignoredPath);
187 }
188 return true;
189 };
190
191 for (const relativePath of relativePaths) {
192 const relativePathBytes = Buffer.byteLength(relativePath) + 1;
193 if (
194 chunk.length > 0 &&
195 chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES &&
196 !(await flushChunk())
197 ) {
198 return relativePaths;
199 }
200
201 chunk.push(relativePath);
202 chunkBytes += relativePathBytes;
203
204 if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES && !(await flushChunk())) {
205 return relativePaths;
206 }
207 }
208
209 if (!(await flushChunk())) {
210 return relativePaths;
211 }
212
213 if (ignoredPaths.size === 0) {
214 return relativePaths;
215 }
216
217 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
218}
219
220async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex | null> {
221 if (!(await isInsideGitWorkTree(cwd))) {
222 return null;
223 }
224
225 const listedFiles = await runProcess(
226 "git",
227 ["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
228 {
229 cwd,
230 allowNonZeroExit: true,
231 timeoutMs: 20_000,
232 maxBufferBytes: 16 * 1024 * 1024,
233 outputMode: "truncate",
234 },
235 ).catch(() => null);
236 if (!listedFiles || listedFiles.code !== 0) {
237 return null;
238 }
239
240 const listedPaths = splitNullSeparatedPaths(
241 listedFiles.stdout,
242 Boolean(listedFiles.stdoutTruncated),
243 )
244 .map((entry) => toPosixPath(entry))
245 .filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
246 const filePaths = await filterGitIgnoredPaths(cwd, listedPaths);
247
248 const directorySet = new Set<string>();
249 for (const filePath of filePaths) {
250 for (const directoryPath of directoryAncestorsOf(filePath)) {
251 if (!isPathInIgnoredDirectory(directoryPath)) {
252 directorySet.add(directoryPath);
253 }
254 }
255 }
256
257 const directoryEntries: ProjectEntry[] = [...directorySet]
258 .toSorted((left, right) => left.localeCompare(right))
259 .map((directoryPath) => ({
260 path: directoryPath,
261 kind: "directory",
262 parentPath: parentPathOf(directoryPath),
263 }));
264 const fileEntries: ProjectEntry[] = [...new Set(filePaths)]
265 .toSorted((left, right) => left.localeCompare(right))
266 .map((filePath) => ({
267 path: filePath,
268 kind: "file",
269 parentPath: parentPathOf(filePath),
270 }));
271
272 const entries = [...directoryEntries, ...fileEntries];
273 return {
274 scannedAt: Date.now(),
275 entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
276 truncated: Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
277 };
278}
279
280async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
281 const gitIndexed = await buildWorkspaceIndexFromGit(cwd);
282 if (gitIndexed) {
283 return gitIndexed;
284 }
285 const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd);
286
287 let pendingDirectories: string[] = [""];
288 const entries: ProjectEntry[] = [];
289 let truncated = false;
290
291 while (pendingDirectories.length > 0 && !truncated) {
292 const currentDirectories = pendingDirectories;
293 pendingDirectories = [];
294 const directoryEntries = await mapWithConcurrency(
295 currentDirectories,
296 WORKSPACE_SCAN_READDIR_CONCURRENCY,
297 async (relativeDir) => {
298 const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
299 try {
300 const dirents = await fs.readdir(absoluteDir, { withFileTypes: true });
301 return { relativeDir, dirents };
302 } catch (error) {
303 if (!relativeDir) {
304 throw new Error(
305 `Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`,
306 { cause: error },
307 );
308 }
309 return { relativeDir, dirents: null };
310 }
311 },
312 );
313
314 const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
315 const { relativeDir, dirents } = directoryEntry;
316 if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
317
318 dirents.sort((left, right) => left.name.localeCompare(right.name));
319 const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
320 for (const dirent of dirents) {
321 if (!dirent.name || dirent.name === "." || dirent.name === "..") {
322 continue;
323 }
324 if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
325 continue;
326 }
327 if (!dirent.isDirectory() && !dirent.isFile()) {
328 continue;
329 }
330
331 const relativePath = toPosixPath(
332 relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
333 );
334 if (isPathInIgnoredDirectory(relativePath)) {
335 continue;
336 }
337 candidates.push({ dirent, relativePath });
338 }
339 return candidates;
340 });
341
342 const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) =>
343 candidateEntries.map((entry) => entry.relativePath),
344 );
345 const allowedPathSet = shouldFilterWithGitIgnore
346 ? new Set(await filterGitIgnoredPaths(cwd, candidatePaths))
347 : null;
348
349 for (const candidateEntries of candidateEntriesByDirectory) {
350 for (const candidate of candidateEntries) {
351 if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) {
352 continue;
353 }
354
355 const entry: ProjectEntry = {
356 path: candidate.relativePath,
357 kind: candidate.dirent.isDirectory() ? "directory" : "file",
358 parentPath: parentPathOf(candidate.relativePath),
359 };
360 entries.push(entry);
361
362 if (candidate.dirent.isDirectory()) {
363 pendingDirectories.push(candidate.relativePath);
364 }
365
366 if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) {
367 truncated = true;
368 break;
369 }
370 }
371
372 if (truncated) {
373 break;
374 }
375 }
376 }
377
378 return {
379 scannedAt: Date.now(),
380 entries,
381 truncated,
382 };
383}
384
385async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
386 const cached = workspaceIndexCache.get(cwd);
387 if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) {
388 return cached;
389 }
390
391 const inFlight = inFlightWorkspaceIndexBuilds.get(cwd);
392 if (inFlight) {
393 return inFlight;
394 }
395
396 const nextPromise = buildWorkspaceIndex(cwd)
397 .then((next) => {
398 workspaceIndexCache.set(cwd, next);
399 while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
400 const oldestKey = workspaceIndexCache.keys().next().value;
401 if (!oldestKey) break;
402 workspaceIndexCache.delete(oldestKey);
403 }
404 return next;
405 })
406 .finally(() => {
407 inFlightWorkspaceIndexBuilds.delete(cwd);
408 });
409 inFlightWorkspaceIndexBuilds.set(cwd, nextPromise);
410 return nextPromise;
411}
412
413export async function searchWorkspaceEntries(
414 input: ProjectSearchEntriesInput,
415): Promise<ProjectSearchEntriesResult> {
416 const parsed = projectSearchEntriesInputSchema.parse(input);
417 const index = await getWorkspaceIndex(parsed.cwd);
418 const normalizedQuery = normalizeQuery(parsed.query);
419 const candidates = normalizedQuery
420 ? index.entries.filter((entry) => entry.path.toLowerCase().includes(normalizedQuery))
421 : index.entries;
422
423 const ranked = candidates.toSorted((left, right) => {
424 const scoreDelta = scoreEntry(left, normalizedQuery) - scoreEntry(right, normalizedQuery);
425 if (scoreDelta !== 0) return scoreDelta;
426 return left.path.localeCompare(right.path);
427 });
428
429 return {
430 entries: ranked.slice(0, parsed.limit),
431 truncated: index.truncated || ranked.length > parsed.limit,
432 };
433}