98 lines · 6.2 KBRaw
| 1 | import type { Actor, Person } from "./contract/actor.ts"; |
| 2 | import type { Outcome } from "./contract/common.ts"; |
| 3 | import { refsErrorCode, refsErrorDescription } from "./contract/errors.ts"; |
| 4 | import type { Refs } from "./contract/handles.ts"; |
| 5 | import { openRefs } from "./handles/refs.ts"; |
| 6 | import { Policy } from "./policy.ts"; |
| 7 | import { memberNamespaces, namespaceBySlug, namespacePolicy } from "./repos.ts"; |
| 8 | import { recordRunFinished } from "./sessions.ts"; |
| 9 | |
| 10 | const REPO_ROUTE = /^\/api\/cli\/repos\/([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)\/(pulls|tasks|runs)(?:\/([^/]+))?(?:\/([a-z]+))?(?:\/([^/]+))?$/; |
| 11 | |
| 12 | type Json = Record<string, unknown>; |
| 13 | |
| 14 | const text = (value: unknown): string => (typeof value === "string" ? value : ""); |
| 15 | |
| 16 | function settled<T>(outcome: Outcome<T>): Response { |
| 17 | return outcome.ok ? Response.json(outcome.value ?? {}) : Response.json({ error: outcome.problem.message }, { status: 422 }); |
| 18 | } |
| 19 | |
| 20 | /** The refs handle of the signed-in person, at home in `namespace`, under the same rules as the web. */ |
| 21 | async function refsFor(env: Env, ctx: ExecutionContext, origin: string, person: Person, namespace: string): Promise<Refs> { |
| 22 | const actor: Actor = { kind: "human", person, via: "cli" }; |
| 23 | const base = new Policy(actor, null); |
| 24 | const [mine, home] = await Promise.all([memberNamespaces(env.DB, actor), namespaceBySlug(env.DB, namespace)]); |
| 25 | const policy = home ? await namespacePolicy(env.DB, base, home.id) : base; |
| 26 | return openRefs({ env, ctx, origin }, policy, home, mine); |
| 27 | } |
| 28 | |
| 29 | /** The `gh`-style commands of the refs CLI: pull requests, tasks and CI runs of one repository. */ |
| 30 | async function repoApi(refs: Refs, name: string, method: string, url: URL, route: (string | undefined)[], input: () => Promise<Json>): Promise<Response> { |
| 31 | const [kind, id, action, extra] = route; |
| 32 | const repo = await refs.repo(name); |
| 33 | const state = url.searchParams.get("state") === "closed" ? "closed" : "open"; |
| 34 | if (kind === "pulls" && !id && method === "GET") return Response.json(await repo.pulls({ status: state })); |
| 35 | if (kind === "pulls" && !id && method === "POST") { |
| 36 | const body = await input(); |
| 37 | const base = text(body.base) || (await repo.refs()).defaultRef || ""; |
| 38 | return settled(await repo.openPull({ title: text(body.title), body: text(body.body), base, head: text(body.head) })); |
| 39 | } |
| 40 | if (kind === "pulls" && id && !action && method === "GET") { |
| 41 | const pull = await repo.pull(Number(id)); |
| 42 | const [threads, mergeability, checks] = await Promise.all([pull.threads(), pull.detail.status === "open" ? pull.mergeability() : null, repo.ci().runs({ pull: pull.detail.number, limit: 5 })]); |
| 43 | return Response.json({ ...pull.detail, threads: threads.filter((thread) => thread.status !== "resolved").length, mergeability, checks }); |
| 44 | } |
| 45 | if (kind === "pulls" && id && action === "merge" && method === "POST") return settled(await (await repo.pull(Number(id))).merge()); |
| 46 | if (kind === "tasks" && !id && method === "GET") return Response.json(await refs.tasks({ status: state, repo: name })); |
| 47 | if (kind === "tasks" && !id && method === "POST") { |
| 48 | const body = await input(); |
| 49 | return settled(await refs.createTask({ title: text(body.title), body: text(body.body), repo: name, assignee: null, labels: [] })); |
| 50 | } |
| 51 | if (kind === "tasks" && id && !action && method === "GET") return Response.json((await refs.task(name, Number(id))).detail); |
| 52 | if (kind === "runs" && id && !action && method === "GET") return Response.json(await repo.ci().run(id)); |
| 53 | if (kind === "runs" && id && action === "logs" && extra && method === "GET") return Response.json(await repo.ci().logs(id, decodeURIComponent(extra))); |
| 54 | return new Response("Not found\n", { status: 404 }); |
| 55 | } |
| 56 | |
| 57 | /** The refs CLI's API. Every request carries an OAuth access token, checked before this handler runs. */ |
| 58 | export const cliApi = { |
| 59 | async fetch(request, env, ctx) { |
| 60 | const { props, auth } = ctx as ExecutionContext & { props?: { userId?: string }; auth?: { scope?: string[] } }; |
| 61 | const userId = props?.userId; |
| 62 | if (!userId) return new Response("Unauthorized\n", { status: 401 }); |
| 63 | const url = new URL(request.url); |
| 64 | const { pathname } = url; |
| 65 | |
| 66 | if (pathname === "/api/cli/connect") { |
| 67 | const headers = new Headers(request.headers); |
| 68 | headers.set("x-refs-user", userId); |
| 69 | return env.USER_HUB.get(env.USER_HUB.idFromName(userId)).fetch(new Request(request, { headers })); |
| 70 | } |
| 71 | const person = await env.DB.prepare("SELECT id, name, email FROM users WHERE id = ?").bind(userId).first<Person>(); |
| 72 | if (!person) return new Response("Not found\n", { status: 404 }); |
| 73 | if (pathname === "/api/cli/whoami") return Response.json(person); |
| 74 | if (pathname === "/api/cli/runs/finished" && request.method === "POST") { |
| 75 | const recorded = await recordRunFinished(env, userId, (await request.json().catch(() => ({}))) as Json); |
| 76 | return recorded ? new Response(null, { status: 204 }) : new Response("No such run\n", { status: 404 }); |
| 77 | } |
| 78 | const route = REPO_ROUTE.exec(pathname); |
| 79 | const creating = pathname === "/api/cli/repos" && request.method === "POST"; |
| 80 | if (!route && !creating) return new Response("Not found\n", { status: 404 }); |
| 81 | if (!auth?.scope?.includes("git")) return Response.json({ error: "This sign-in cannot act as you. Run `refs login`." }, { status: 403 }); |
| 82 | if (!route) { |
| 83 | const body = await request.json<Json>().catch((): Json => ({})); |
| 84 | const owner = text(body.owner) || (await memberNamespaces(env.DB, { kind: "human", person, via: "cli" }))[0]?.slug || ""; |
| 85 | const refs = await refsFor(env, ctx, url.origin, person, owner); |
| 86 | return settled(await refs.createRepo({ owner, name: text(body.name), description: text(body.description), visibility: body.visibility === "public" ? "public" : "private", setUp: body.setUp !== false })); |
| 87 | } |
| 88 | const [, namespace, repo, ...rest] = route; |
| 89 | try { |
| 90 | const refs = await refsFor(env, ctx, url.origin, person, namespace!); |
| 91 | return await repoApi(refs, `${namespace}/${repo}`, request.method, url, rest, () => request.json<Json>().catch(() => ({}))); |
| 92 | } catch (error) { |
| 93 | const code = refsErrorCode(error); |
| 94 | if (!code) throw error; |
| 95 | return Response.json({ error: refsErrorDescription(error) }, { status: code === "not_found" ? 404 : 403 }); |
| 96 | } |
| 97 | }, |
| 98 | } satisfies ExportedHandler<Env>; |