import { type Dirent, existsSync, readdirSync, realpathSync, type Stats, statSync, } from "node:fs"; import path from "node:path"; import process from "node:process"; import { fileURLToPath, pathToFileURL } from "node:url"; import type { LspServerAdapter } from "./types.js"; export function resolveRoot(root?: string) { const resolvedRoot = path.resolve(root?.trim() || process.cwd()); if (!existsSync(resolvedRoot)) throw new Error(`Workspace root does not exist: ${resolvedRoot}`); if (!statSync(resolvedRoot).isDirectory()) { throw new Error( `Expected workspace root to be a directory: ${resolvedRoot}`, ); } return resolvedRoot; } export function directoryUri(directory: string) { return pathToFileURL( directory.endsWith(path.sep) ? directory : `${directory}${path.sep}`, ).href; } // Canonical key for a document URI, shared by the diagnostics cache and the // workspace-edit matcher: a server may answer using a different but // equivalent encoding of the URI the client sent. marksman, like VS Code, // sends `file:///c%3A/dir/a.md` where pathToFileURL produces // `file:///C:/dir/a.md`. normalize() also collapses the doubled separators a // URI may carry. Non-file URIs such as untitled: and jdt: keep their // original text. export function documentKey(uri: string) { try { const filePath = path.normalize(fileURLToPath(uri)); return process.platform === "win32" ? filePath.toLowerCase() : filePath; } catch { return uri; } } export function resolveSupportedFile( adapter: LspServerAdapter, root: string, filePath: string, ) { const resolvedPath = resolveWorkspacePath(root, filePath, "File path"); if (!existsSync(resolvedPath)) throw new Error(`${adapter.name} file does not exist: ${resolvedPath}`); if (!isInsidePath(realpathSync(root), realpathSync(resolvedPath))) { throw new Error(`File resolves outside workspace root: ${resolvedPath}`); } if (!statSync(resolvedPath).isFile()) throw new Error(`Expected a file: ${resolvedPath}`); if (!adapter.isSupportedFile(resolvedPath)) { throw new Error( `Expected a ${adapter.name} supported file: ${resolvedPath}`, ); } return resolvedPath; } export function collectSupportedFiles( adapter: LspServerAdapter, root: string, requestedPaths: string[] | undefined, limit: number, ) { return collectFiles( (filePath) => adapter.isSupportedFile(filePath), adapter.skipDirectories, root, requestedPaths, limit, ); } /** Adapter-independent file walk shared by the LSP lane and the runner lane. */ export function collectFiles( isSupportedFile: (filePath: string) => boolean, skipDirectories: Set, root: string, requestedPaths: string[] | undefined, limit: number, ) { const cappedLimit = Math.max(1, Math.floor(limit)); const files: string[] = []; const seen = new Set(); const visitedDirectories = new Set(); const realRoot = realpathSync(root); const inputs = requestedPaths?.length ? requestedPaths : [root]; for (const input of inputs) { const targetPath = resolveWorkspacePath(root, input, "Requested path"); if (!existsSync(targetPath)) throw new Error(`Requested path does not exist: ${targetPath}`); if (!isInsidePath(realRoot, realpathSync(targetPath))) { throw new Error( `Requested path resolves outside workspace root: ${targetPath}`, ); } collectPath( isSupportedFile, skipDirectories, targetPath, files, seen, visitedDirectories, realRoot, cappedLimit, ); if (files.length >= cappedLimit) break; } return files; } interface WalkEntry { path: string; /** True only for symlinks/junctions: the only nodes that can escape root. */ verify: boolean; } function collectPath( isSupportedFile: (filePath: string) => boolean, skipDirectories: Set, targetPath: string, files: string[], seen: Set, visitedDirectories: Set, realRoot: string, limit: number, ) { // Breadth-first: when the walk hits the cap, the files it collected // spread across the shallowest directories of the whole tree instead of // exhausting one deep lexicographic branch (a depth-first walk on a // repo with src/a/... would spend the entire limit there). // The root entry was already verified by resolveWorkspacePath, and every // queued child comes from readdir of a verified directory, so plain nodes // are lexically inside the root by construction. Only symlinks can point // elsewhere, and only they pay the realpath containment check. A vanished // node (raced delete) is read as a failed stat instead of a separate // existsSync probe: one syscall per node instead of three. const queue: WalkEntry[] = [{ path: targetPath, verify: false }]; while (queue.length > 0 && files.length < limit) { const current = queue.shift(); if (!current) continue; if (current.verify) { try { if (!isInsidePath(realRoot, realpathSync(current.path))) continue; } catch { // A broken symlink is skipped, never allowed to abort the walk. continue; } } let stats: Stats | undefined; try { stats = statSync(current.path); } catch { // Raced with a concurrent delete; skip this node. continue; } if (stats.isFile()) { if (isSupportedFile(current.path) && !seen.has(current.path)) { seen.add(current.path); files.push(current.path); } continue; } if (!stats.isDirectory()) continue; let directoryKey: string; try { directoryKey = realpathSync(current.path); } catch { // Vanished between stat and realpath. continue; } if (visitedDirectories.has(directoryKey)) continue; visitedDirectories.add(directoryKey); let entries: Dirent[] | undefined; try { entries = readdirSync(current.path, { withFileTypes: true }); } catch { // The directory vanished (or is unreadable); skip its subtree. continue; } entries.sort((left, right) => left.name.localeCompare(right.name)); for (const entry of entries) { if (files.length >= limit) break; if ( (entry.isDirectory() || entry.isSymbolicLink()) && skipDirectories.has(entry.name) ) continue; queue.push({ path: path.join(current.path, entry.name), verify: entry.isSymbolicLink(), }); } } } function resolveWorkspacePath(root: string, inputPath: string, label: string) { const resolvedPath = path.resolve(root, inputPath); const realRoot = realpathSync(root); const isLexicallyInsideRoot = isInsidePath(root, resolvedPath); if (existsSync(resolvedPath)) { const realResolvedPath = realpathSync(resolvedPath); if (!isInsidePath(realRoot, realResolvedPath)) { throw new Error( `${label} resolves outside workspace root: ${resolvedPath}`, ); } return isLexicallyInsideRoot ? resolvedPath : path.join(root, path.relative(realRoot, realResolvedPath)); } if (!isLexicallyInsideRoot && !isInsidePath(realRoot, resolvedPath)) { throw new Error(`${label} escapes workspace root: ${resolvedPath}`); } return resolvedPath; } function isInsidePath(parent: string, child: string) { const relativePath = path.relative(parent, child); return ( relativePath === "" || (!relativePath.startsWith("..") && !path.isAbsolute(relativePath)) ); }