// PEP-143: «Сообщить о проблеме» — the form posts text, screenshots and what the page knows // (multipart: a server action's body is capped at 1 MB, screenshots are bigger). import { FEEDBACK_MAX_BYTES, FEEDBACK_MAX_SHOTS, PeppaError, submitFeedback } from "@peppa/core"; import { m } from "@peppa/shared/i18n"; import { asWebActor, currentUser, uiMode } from "@/lib/auth"; import { db } from "@/lib/db"; import { getLocale, getT } from "@/lib/i18n"; export const dynamic = "force-dynamic"; const MAX_BODY = FEEDBACK_MAX_SHOTS * FEEDBACK_MAX_BYTES + 512 * 1024; export async function POST(req: Request) { const t = await getT(); const fail = (status: number, error: string) => Response.json({ error }, { status }); const me = await currentUser(); if (!me) return fail(401, t("Нужен вход")); const user = asWebActor(me); if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY) return fail(413, t("Скриншоты слишком большие. Приложите файлы поменьше.")); let form: FormData; try { form = await req.formData(); } catch { return fail(400, t("Не получилось прочитать форму. Попробуйте ещё раз.")); } const shots = form.getAll("shots").filter((v): v is File => typeof v !== "string"); let context: Record = {}; try { context = JSON.parse(String(form.get("context") ?? "{}")) as Record; } catch {} try { // Oversized files are refused before their bytes are read into memory. if (shots.some((s) => s.size > FEEDBACK_MAX_BYTES)) throw new PeppaError(m("Скриншот больше 5 МБ. Приложите файл поменьше.")); const files = await Promise.all(shots.slice(0, FEEDBACK_MAX_SHOTS + 1).map(async (s) => new Uint8Array(await s.arrayBuffer()))); const f = await submitFeedback(db, user, { text: String(form.get("text") ?? ""), via: "web", files, // The view and the language are the server's knowledge, not the page's claim. context: { ...context, mode: await uiMode(), locale: await getLocale(), userAgent: req.headers.get("user-agent") ?? undefined }, }); return Response.json({ ok: true, id: f.id }); } catch (e) { if (e instanceof PeppaError) return fail(400, t.text(e.message)); throw e; } }