import { projectRef } from "@/lib/projects"; import { refuseCaller } from "@/lib/report/caller"; import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs"; import { postsReel } from "@/lib/report/postReel.mjs"; export const dynamic = "force-dynamic"; // ADD POSTS to a cut of posts (lane/ui-simplify, 5 Nov; terminal-only before: `umtool posts reel`): the // channel archive's posts the cut does not play yet, as post items, in one write (postReel.mjs postsReel, // the CLI's own). `dryRun` answers what it would add. // // POST { project, channels: [slug…], own?, since?, until?, withMedia?, after?, limit?, dryRun? } // -> { added, selected, already, entries: [{ id, date, text, … }], dryRun } export async function POST(request: Request) { const refused = refuseCaller(request, "/api/report/add-posts"); if (refused) return refused; const b = (await request.json().catch(() => null)) as Record | null; if (!b) return Response.json({ error: "bad json" }, { status: 400 }); const project = await projectRef(String(b.project ?? "")); if (!project) return Response.json({ error: "no such project" }, { status: 404 }); const channels = Array.isArray(b.channels) ? b.channels.filter((c): c is string => typeof c === "string" && c.length > 0) : []; if (!channels.length) return Response.json({ error: "name a channel whose posts to add" }, { status: 400 }); const str = (k: string) => (typeof b[k] === "string" && b[k] ? (b[k] as string) : null); const limit = Number.isInteger(b.limit) && (b.limit as number) > 0 ? (b.limit as number) : null; try { const r = await postsReel(project, { channels, since: str("since"), until: str("until"), own: b.own === true, withMedia: b.withMedia === true, replies: "include", order: "chrono", limit, after: str("after"), dryRun: b.dryRun === true, }); const entries = ((r.entries ?? []) as Record[]).map((e) => ({ id: e.id, date: typeof e.date === "string" ? e.date.slice(0, 10) : null, handle: e.handle ?? null, text: String(e.text ?? "").replace(/\s+/g, " ").slice(0, 140), media: Array.isArray(e.media) ? e.media.length : 0, })); return Response.json({ ok: true, added: r.added, selected: r.selected, already: r.already, dryRun: !!r.dryRun, entries }, { headers: { "cache-control": "no-store" } }); } catch (e) { if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 }); if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); } }