import { recordRunFinished } from "./sessions.ts"; /** The refs CLI's API. Every request carries an OAuth access token, checked before this handler runs. */ export const cliApi = { async fetch(request, env, ctx) { const userId = (ctx as ExecutionContext & { props?: { userId?: string } }).props?.userId; if (!userId) return new Response("Unauthorized\n", { status: 401 }); const { pathname } = new URL(request.url); if (pathname === "/api/cli/connect") { const headers = new Headers(request.headers); headers.set("x-refs-user", userId); return env.USER_HUB.get(env.USER_HUB.idFromName(userId)).fetch(new Request(request, { headers })); } if (pathname === "/api/cli/whoami") { const person = await env.DB.prepare("SELECT id, name, email FROM users WHERE id = ?").bind(userId).first<{ id: string; name: string; email: string }>(); return person ? Response.json(person) : new Response("Not found\n", { status: 404 }); } if (pathname === "/api/cli/runs/finished" && request.method === "POST") { const recorded = await recordRunFinished(env, userId, (await request.json().catch(() => ({}))) as Record); return recorded ? new Response(null, { status: 204 }) : new Response("No such run\n", { status: 404 }); } return new Response("Not found\n", { status: 404 }); }, } satisfies ExportedHandler;