import { z } from "zod"; import { guarded, json, body } from "@/lib/api"; import { sql } from "@/lib/db"; import { newId } from "@/lib/ids"; export const GET = guarded(async (req) => { const p = req.nextUrl.searchParams; const conv = p.get("conversation"); const project = p.get("project"); const saved = p.get("saved") === "1"; const rows = await sql`SELECT id, conversation_id, message_id, project_id, root_id, version, type, language, title, saved, created_at, length(content) AS size FROM artifacts WHERE (${!conv} OR conversation_id = ${conv ?? ""}) AND (${!project} OR project_id = ${project ?? ""}) AND (${!saved} OR saved) ORDER BY created_at DESC LIMIT 300`; return json({ artifacts: rows }); }); /** Create a new version of an artifact (edited content) or a brand-new artifact. */ export const POST = guarded(async (req) => { const b = await body(req, z.object({ rootId: z.string().optional(), conversationId: z.string().nullable().optional(), projectId: z.string().nullable().optional(), type: z.string(), language: z.string().optional(), title: z.string().min(1).max(120), content: z.string().max(2_000_000), saved: z.boolean().optional() })); const id = newId("art"); let version = 1; let root = id; if (b.rootId) { const prev = await sql<{ version: number }[]>`SELECT max(version)::int AS version FROM artifacts WHERE root_id = ${b.rootId}`; version = (prev[0]?.version ?? 0) + 1; root = b.rootId; } await sql`INSERT INTO artifacts (id, conversation_id, project_id, root_id, version, type, language, title, content, saved) VALUES (${id}, ${b.conversationId ?? null}, ${b.projectId ?? null}, ${root}, ${version}, ${b.type}, ${b.language ?? null}, ${b.title}, ${b.content}, ${b.saved ?? false})`; return json({ id, rootId: root, version }, { status: 201 }); });