Add depth-limited filesystem browsing

This commit is contained in:
Shantur Rathore
2025-11-17 21:16:10 +00:00
parent 719a9c9c74
commit f53564bb06
4 changed files with 215 additions and 25 deletions

View File

@@ -13,7 +13,14 @@ export class FileSystemBrowser {
this.root = path.resolve(options.rootDir)
}
list(relativePath: string): FileSystemEntry[] {
list(relativePath: string, depth = 2): FileSystemEntry[] {
if (depth < 1) {
throw new Error("Depth must be at least 1")
}
return this.walk(relativePath, depth)
}
private walk(relativePath: string, remainingDepth: number): FileSystemEntry[] {
const resolved = this.toAbsolute(relativePath)
const entries = fs.readdirSync(resolved, { withFileTypes: true })
@@ -30,8 +37,8 @@ export class FileSystemBrowser {
modifiedAt: stats.mtime.toISOString(),
}
if (entry.isDirectory()) {
const nested = this.list(entryPath)
if (entry.isDirectory() && remainingDepth > 1) {
const nested = this.walk(entryPath, remainingDepth - 1)
return [current, ...nested]
}

View File

@@ -8,6 +8,7 @@ interface RouteDeps {
const FilesystemQuerySchema = z.object({
path: z.string().optional(),
depth: z.coerce.number().int().min(1).max(10).default(2),
})
export function registerFilesystemRoutes(app: FastifyInstance, deps: RouteDeps) {
@@ -16,7 +17,7 @@ export function registerFilesystemRoutes(app: FastifyInstance, deps: RouteDeps)
const targetPath = query.path ?? "."
try {
return deps.fileSystemBrowser.list(targetPath)
return deps.fileSystemBrowser.list(targetPath, query.depth)
} catch (error) {
reply.code(400)
return { error: (error as Error).message }