import { askEditor, EditorError, readDraftJob } from "@/lib/articles/generation"; import { channelsDirFor } from "@/lib/projects/report.mjs"; import { PostsRefused, StaleToken, manifestToken, updatePosts } from "@/lib/report/manifest.mjs"; import { postChannels, postWarnings, searchPostArchive } from "@/lib/report/postCards.mjs"; import { addPostFromArchive, findPostId, findPostRow } from "@/lib/report/postsCli.mjs"; import { citedChannels } from "@/lib/report/sourceBacklog.mjs"; import { withEditNotes } from "@/lib/report/guard"; import { resolveReport } from "@/lib/report/serve.mjs"; import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; // ADD POST, from Play the cut (UI notes item 13; lib/report/postCards.mjs, // postsCli.mjs addPostFromArchive). The chain it replaces -- `pnpm ops // capture-posts` → `umtool posts add` → `umtool look deck.posts` -- in one panel: // // GET ?project= { channels, posts: [the cut's posts, each with its warnings], token } // GET ?project=&channel=&q= { hits: [{ id, date, text, warnings, captured, inCut, … }], total } // GET ?project=&job= a capture's job (the editor's) // POST { project, op: "capture", channel, ids } the editor's capture-posts (paced there, on the // platform's own queue) → { jobId } // POST { project, op: "add", channel, id, attach?, crop? } the card, through `posts add`'s write // POST { project, op: "crop", post, crop, token? } the post's own crop (shotMaxHeight; null: none) const headers = { "cache-control": "no-store" }; const SLUG_RE = /^[A-Za-z0-9._-]+$/; const ID_RE = /^[A-Za-z0-9_-]{1,64}$/; /** The archive channel and native id a manifest post came from, when it says. */ function sourceOf(p: Record): { slug: string; id: string } | null { const shot = typeof p.shot === "string" ? /^posts-media\/([^/]+)\/([^/]+)\//.exec(p.shot) : null; const slug = typeof p.siteChannel === "string" ? p.siteChannel : shot?.[1]; const id = typeof p.postId === "string" ? p.postId : shot?.[2] ?? (typeof p.id === "string" ? p.id.replace(/^(x|bsky|post)-/, "") : null); return slug && id && SLUG_RE.test(slug) && ID_RE.test(id) ? { slug, id } : null; } export async function GET(request: Request) { const url = new URL(request.url); const r = await resolveReport(url.searchParams.get("project") ?? ""); if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers }); const m = r.manifest as Record; const channelsDir = channelsDirFor(r.project.dir, m) as string | null; if (!channelsDir) return Response.json({ error: "this project reads no corpus (no channels directory)" }, { status: 400, headers }); const job = url.searchParams.get("job"); try { if (job) { const j = await readDraftJob(job, 6); return Response.json({ ...j, ended: ["done", "failed", "cancelled", "error"].includes(j.status) }, { headers }); } const channel = url.searchParams.get("channel"); if (channel) { if (!SLUG_RE.test(channel)) return Response.json({ error: "not a channel slug" }, { status: 400, headers }); return Response.json(await searchPostArchive(channelsDir, channel, url.searchParams.get("q") ?? "", { manifest: m }), { headers }); } const cited = (citedChannels(m) as { slug: string }[]).map((c) => c.slug); const posts = await Promise.all( ((Array.isArray(m.posts) ? m.posts : []) as Record[]).map(async (p) => { const src = sourceOf(p); const row = src ? (await findPostRow(channelsDir, src.slug, src.id).catch(() => null))?.row ?? null : null; return { id: String(p.id ?? ""), date: typeof p.date === "string" ? p.date : null, text: typeof p.text === "string" ? p.text : "", attachTo: typeof p.attachTo === "string" ? p.attachTo : null, shot: typeof p.shot === "string" ? p.shot : null, shotMaxHeight: Number.isInteger(p.shotMaxHeight) ? (p.shotMaxHeight as number) : null, hide: p.hide === true, source: src, warnings: postWarnings(row), }; }), ); return Response.json({ channels: await postChannels(channelsDir, m, cited), posts, token: await manifestToken(r.project.dir) }, { headers }); } catch (e) { const status = e instanceof EditorError ? e.status : 400; return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); } } export async function POST(request: Request) { const refused = refuseCaller(request, "/api/report/post-cards"); if (refused) return refused; const body = (await request.json().catch(() => null)) as Record | null; if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); const r = await resolveReport(String(body.project ?? "")); if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers }); try { if (body.op === "capture") { const slug = String(body.channel ?? ""); const ids = Array.isArray(body.ids) ? body.ids.map(String).filter((x) => ID_RE.test(x)) : []; if (!SLUG_RE.test(slug) || !ids.length) return Response.json({ error: "a capture names a channel and its post ids" }, { status: 400, headers }); // The editor's own capture: paced there (a pause before every contact // after the first), on the platform's download queue, refused for an id // not in the channel's archive. const answer = await askEditor<{ jobId?: string }>("/api/ops/capture-posts", { method: "POST", body: { slug, ids } }); return Response.json({ ok: true, jobId: answer.jobId ?? null }, { headers }); } if (body.op === "add") { const crop = body.crop === undefined || body.crop === null || body.crop === "" ? null : Number(body.crop); if (crop !== null && !Number.isInteger(crop)) return Response.json({ error: "crop is a whole number of pixels" }, { status: 400, headers }); const out = await addPostFromArchive(r.project, { slug: String(body.channel ?? ""), postId: String(body.id ?? ""), attach: typeof body.attach === "string" && body.attach ? body.attach : null, crop, }); return Response.json({ ok: true, post: out.result.post, created: out.result.created, warnings: out.warnings, copied: out.copied, editNotes: out.editNotes, token: await manifestToken(r.project.dir) }, { headers }); } if (body.op === "crop") { const found = findPostId(r.manifest, String(body.post ?? "")); const id = found === null ? null : String(found); if (!id) return Response.json({ error: `no post ${String(body.post ?? "")} in the cut` }, { status: 404, headers }); const crop = body.crop === undefined || body.crop === null || body.crop === "" ? null : Number(body.crop); const token = typeof body.token === "string" ? body.token : await manifestToken(r.project.dir); const { result, editNotes } = await withEditNotes(r.project, () => updatePosts(r.project.dir, { [id]: { shotMaxHeight: crop } }, { token })); return Response.json({ ok: true, id, post: (result as { posts: Record }).posts[id], token: (result as { token: string }).token, editNotes }, { headers }); } return Response.json({ error: 'op is "capture", "add" or "crop"' }, { status: 400, headers }); } catch (e) { if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409, headers }); if (e instanceof PostsRefused) return Response.json({ error: e.message, errors: (e as PostsRefused & { errors: string[] }).errors }, { status: 400, headers }); const status = e instanceof EditorError ? e.status : 400; return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); } }