| 13 | }; |
| 14 | |
| 15 | export async function GET(request: NextRequest) { |
| 16 | const filePath = request.nextUrl.searchParams.get("path"); |
| 17 | if (!filePath) { |
| 18 | return NextResponse.json({ error: "path parameter required" }, { status: 400 }); |
| 19 | } |
| 20 | |
| 21 | const resolvedPath = path.resolve(filePath); |
| 22 | |
| 23 | try { |
| 24 | const stats = await fs.stat(resolvedPath); |
| 25 | if (stats.isDirectory()) { |
| 26 | return NextResponse.json({ error: "path is a directory" }, { status: 400 }); |
| 27 | } |
| 28 | |
| 29 | const ext = resolvedPath.split(".").pop()?.toLowerCase() ?? ""; |
| 30 | |
| 31 | // Binary images: return base64 data URL |
| 32 | if (ext in IMAGE_MIME) { |
| 33 | const buffer = await fs.readFile(resolvedPath); |
| 34 | const base64 = buffer.toString("base64"); |
| 35 | return NextResponse.json({ |
| 36 | content: `data:${IMAGE_MIME[ext]};base64,${base64}`, |
| 37 | isImage: true, |
| 38 | size: stats.size, |
| 39 | modified: stats.mtime.toISOString(), |
| 40 | }); |
| 41 | } |
| 42 | |
| 43 | // Text (including SVG) |
| 44 | const content = await fs.readFile(resolvedPath, "utf-8"); |
| 45 | return NextResponse.json({ |
| 46 | content, |
| 47 | isImage: ext === "svg", |
| 48 | size: stats.size, |
| 49 | modified: stats.mtime.toISOString(), |
| 50 | }); |
| 51 | } catch (err) { |
| 52 | const message = err instanceof Error ? err.message : "Unknown error"; |
| 53 | return NextResponse.json({ error: message }, { status: 404 }); |
| 54 | } |
| 55 | } |