import { NextResponse } from 'next/server'; import path from 'node:path'; import fs from 'node:fs/promises'; const BASE_DIR = '/app/files'; export async function GET(req: Request) { try { const url = new URL(req.url); const raw = url.searchParams.get('path') ?? '/'; const safe = path.normalize('/' + raw).replace(/^\/+/, '/'); // normalize & ensure leading slash const target = path.resolve(BASE_DIR, '.' + safe); if (!target.startsWith(BASE_DIR)) { return NextResponse.json({ error: 'Invalid path' }, { status: 400 }); } const st = await fs.stat(target).catch(() => null); if (!st || !st.isDirectory()) { return NextResponse.json({ error: 'Not a directory' }, { status: 400 }); } const entries = await fs.readdir(target, { withFileTypes: true }); const items = await Promise.all(entries.map(async (d) => { const full = path.join(target, d.name); const rel = path.posix.join(safe, d.name).replaceAll('\\', '/'); const s = await fs.stat(full); return { name: d.name, path: rel, type: d.isDirectory() ? 'dir' : 'file', size: s.size, mtime: s.mtimeMs, }; })); return NextResponse.json({ path: safe, items }); } catch (e: any) { return NextResponse.json({ error: e?.message ?? 'Unknown error' }, { status: 500 }); } }