import * as Sentry from "@sentry/nextjs"; import { NextResponse } from "next/server"; import { nextcloud } from "@/lib/webdav"; import { normalizePath } from "@/lib/paths"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; function json(data: T, init?: { status?: number } & ResponseInit) { return NextResponse.json(data, init); } // GET ?path=/abs/path -> { content, mimeType } export async function GET(req: Request) { try { const { searchParams } = new URL(req.url); const rawPath = searchParams.get("path"); if (!rawPath) { return json({ error: "path is required" }, { status: 400 }); } const path = normalizePath(rawPath); const result = await Sentry.startSpan( { op: "function", name: "api.files.content.get" }, async (span) => { span.setAttribute("path", path); const res = await nextcloud.readText(path); return res; }, ); return json(result); } catch (error: unknown) { Sentry.captureException(error); const message = error instanceof Error ? error.message : String(error); const status = /404/.test(message) ? 404 : 500; return json({ error: "Failed to read file content", message }, { status }); } } // PUT { path, content, mimeType? } -> { ok, etag? } export async function PUT(req: Request) { try { const body = (await req.json().catch(() => ({}))) as { path?: string; content?: string; mimeType?: string; }; if (!body?.path || typeof body.content !== "string") { return json({ error: "path and content are required" }, { status: 400 }); } const path = normalizePath(body.path); const mime = body.mimeType || "text/markdown"; const result = await Sentry.startSpan( { op: "function", name: "api.files.content.put" }, async (span) => { span.setAttribute("path", path); span.setAttribute("content.length", body.content!.length); span.setAttribute("mimeType", mime); const res = await nextcloud.writeText(path, body.content!, mime); return res; }, ); return json(result); } catch (error: unknown) { Sentry.captureException(error); const message = error instanceof Error ? error.message : String(error); const status = /409|conflict/i.test(message) ? 409 : /423|locked/i.test(message) ? 423 : 500; return json({ error: "Failed to write file content", message }, { status }); } }