The best way to control Claude Code, Codex and more from any computer or phone

main
ts 631 lines 24.8 KB
Raw
1 import type { RuntimeContext } from "alchemy/RuntimeContext";
2 /**
3 * GitHub REST v3 compatibility facade (`/api/v3/**`) — DESIGN.md "Tier 1".
4 *
5 * Lets GitHub-flavored tooling talk to the service unmodified. The target
6 * consumers are `gh api` (via `GH_HOST=<host>` + `GH_ENTERPRISE_TOKEN`,
7 * which sends REST to `https://<host>/api/v3/...`) and Octokit-style SDKs
8 * pointed at a GitHub Enterprise `baseUrl`. Only the REST plane is
9 * mimicked — the `gh pr`/`gh issue` porcelain commands speak GraphQL and
10 * are out of scope (use `gh api` paths instead).
11 *
12 * This module is a pure TRANSLATION layer: every route parses GitHub's
13 * request shapes, calls the same Repo-DO RPCs the native `/api/v1` plane
14 * uses (auth enforcement stays in the DO), and re-shapes responses into
15 * GitHub's JSON. GitHub-isms handled here:
16 *
17 * - `Authorization: token <t>` (gh's scheme) — parsed by `Auth.ts`
18 * alongside Bearer/Basic.
19 * - A merged PR is `state: "closed"` with `merged: true` (our tri-state
20 * `merged` collapses into GitHub's boolean).
21 * - Errors are `{ message }` with GitHub's status conventions (401
22 * "Requires authentication", 404 "Not Found", 405 for unsupported merge
23 * methods, 409 for conflicts).
24 * - List pagination is RFC-5988 `Link: <...>; rel="next"` headers. The
25 * next URL carries an opaque `cursor` (not a page number) — `gh api
26 * --paginate` and Octokit follow the URL verbatim, so keyset cursors
27 * work transparently.
28 *
29 * Deliberately absent (documented, not accidental): issues, reviews,
30 * comments, checks, search, GraphQL, rename detection in file lists, and
31 * additions/deletions line counts (reported as 0 — the server does not
32 * compute content diffs; fetch blobs and diff client-side).
33 */
34 import * as Effect from "effect/Effect";
35 import { Base64 } from "effect/encoding";
36 import * as HttpRouter from "effect/http/HttpRouter";
37 import * as HttpServerRequest from "effect/http/HttpServerRequest";
38 import * as HttpServerResponse from "effect/http/HttpServerResponse";
39 import type { DiffEntryData } from "./Protocol/TreeDiff.ts";
40 import type { RegistryEntry } from "./RegistryObject.ts";
41 import type {
42 CommitData,
43 CommitDiffData,
44 CompareData,
45 FileData,
46 MergePullResult,
47 PullData,
48 PullDetailData,
49 PullsPage,
50 RefsPage,
51 RepoMetaData,
52 CommitLogPage,
53 SignatureData,
54 } from "./RepoObject.ts";
55
56 // ─────────────────────────────────────────────────────────────────────────────
57 // Dependencies injected by the Worker
58 // ─────────────────────────────────────────────────────────────────────────────
59
60 /** Outcome of the Worker's shared owner/repo + credential prelude. */
61 export type CompatPrelude =
62 | { readonly kind: "halt"; readonly response: HttpServerResponse.HttpServerResponse }
63 | { readonly kind: "ok"; readonly entry: RegistryEntry };
64
65 /** The slice of the Repo-DO stub the facade calls. */
66 export interface CompatRepoStub {
67 readonly getRepoMeta: () => Effect.Effect<
68 RepoMetaData,
69 { readonly _tag: string },
70 RuntimeContext
71 >;
72 readonly listRefs: (
73 prefix?: string,
74 ) => Effect.Effect<RefsPage, { readonly _tag: string }, RuntimeContext>;
75 readonly readCommitLog: (input: {
76 readonly ref?: string | undefined;
77 readonly cursor?: string | undefined;
78 readonly limit?: number | undefined;
79 }) => Effect.Effect<CommitLogPage, { readonly _tag: string }, RuntimeContext>;
80 readonly readCommitDiff: (input: {
81 readonly oid: string;
82 }) => Effect.Effect<CommitDiffData, { readonly _tag: string }, RuntimeContext>;
83 readonly compareCommits: (input: {
84 readonly base: string;
85 readonly head: string;
86 }) => Effect.Effect<CompareData, { readonly _tag: string }, RuntimeContext>;
87 readonly readFileAtPath: (input: {
88 readonly ref?: string | undefined;
89 readonly path: string;
90 }) => Effect.Effect<FileData, { readonly _tag: string }, RuntimeContext>;
91 readonly createPull: (input: {
92 readonly title: string;
93 readonly body?: string | undefined;
94 readonly base: string;
95 readonly head: string;
96 }) => Effect.Effect<PullData, { readonly _tag: string }, RuntimeContext>;
97 readonly listPulls: (input: {
98 readonly state?: "open" | "closed" | "merged" | "all" | undefined;
99 readonly cursor?: string | undefined;
100 readonly limit?: number | undefined;
101 }) => Effect.Effect<PullsPage, { readonly _tag: string }, RuntimeContext>;
102 readonly getPull: (
103 number: number,
104 ) => Effect.Effect<PullDetailData, { readonly _tag: string }, RuntimeContext>;
105 readonly updatePull: (input: {
106 readonly number: number;
107 readonly title?: string | undefined;
108 readonly body?: string | null | undefined;
109 readonly state?: "open" | "closed" | undefined;
110 }) => Effect.Effect<PullData, { readonly _tag: string }, RuntimeContext>;
111 readonly mergePull: (input: {
112 readonly number: number;
113 readonly message?: string | undefined;
114 readonly expectedHeadOid?: string | undefined;
115 }) => Effect.Effect<MergePullResult, { readonly _tag: string }, RuntimeContext>;
116 }
117
118 export interface GitHubCompatOptions {
119 /**
120 * The Worker's `rawRestPrelude`: resolves `owner/repo`, parses
121 * credentials (anonymous allowed — public repos), and 404s/500s early.
122 */
123 readonly prelude: (
124 owner: string,
125 repo: string,
126 ) => Effect.Effect<CompatPrelude, never, HttpServerRequest.HttpServerRequest | RuntimeContext>;
127 /** Repo-DO stub by repoId (the Worker's `repos.getByName`). */
128 readonly stub: (repoId: string) => CompatRepoStub;
129 }
130
131 // ─────────────────────────────────────────────────────────────────────────────
132 // Small helpers
133 // ─────────────────────────────────────────────────────────────────────────────
134
135 const OID_RE = /^[0-9a-f]{40}$/;
136
137 const iso = (epochMs: number): string => new Date(epochMs).toISOString();
138
139 const isoSeconds = (sig: SignatureData): string => new Date(sig.date * 1000).toISOString();
140
141 /** Stable 48-bit integer id from a string (GitHub ids are numbers). */
142 const intId = (value: string): number => {
143 let hash = 0xcbf29ce484222325n;
144 for (let index = 0; index < value.length; index++) {
145 hash ^= BigInt(value.charCodeAt(index));
146 hash = (hash * 0x100000001b3n) & 0xffffffffffffn;
147 }
148 return Number(hash);
149 };
150
151 const shortRef = (ref: string): string => ref.replace(/^refs\/heads\//, "");
152
153 /** `https://host` of the incoming request (same derivation as remotes). */
154 const originOf = Effect.gen(function* () {
155 const request = yield* HttpServerRequest.HttpServerRequest;
156 const host = request.headers.host;
157 const proto = request.headers["x-forwarded-proto"] ?? "https";
158 return host === undefined ? "" : `${proto}://${host}`;
159 });
160
161 const ghJson = (
162 value: unknown,
163 options?: { readonly status?: number; readonly headers?: Record<string, string> },
164 ) =>
165 HttpServerResponse.json(value, {
166 status: options?.status ?? 200,
167 headers: options?.headers,
168 }).pipe(Effect.orDie);
169
170 const ghError = (status: number, message: string) => ghJson({ message }, { status });
171
172 const ghNotFound = ghError(404, "Not Found");
173
174 /**
175 * Maps the DO's typed error union onto GitHub's status conventions. Every
176 * facade route ends with this — unknown tags become 500s via `Effect.die`
177 * (defects, not silent 200s).
178 */
179 const ghCatch = <A, R>(
180 effect: Effect.Effect<A, { readonly _tag: string; readonly message?: string }, R>,
181 ): Effect.Effect<A | HttpServerResponse.HttpServerResponse, never, R> =>
182 effect.pipe(
183 Effect.catchIf(
184 (error): error is { _tag: string } => typeof error?._tag === "string",
185 (error) => {
186 switch (error._tag) {
187 case "RepoNotFound":
188 case "RefNotFound":
189 case "ObjectNotFound":
190 case "PullNotFound":
191 case "BranchMissing":
192 return ghNotFound;
193 case "WrongObjectType":
194 case "ValidationError":
195 case "NoMergeBase":
196 return ghError(422, "Validation Failed");
197 case "PullExists":
198 return ghError(
199 422,
200 "Validation Failed: a pull request already exists for this head/base",
201 );
202 case "PullStateConflict":
203 case "NothingToMerge":
204 return ghError(405, "Pull Request is not mergeable");
205 case "MergeConflict":
206 return ghError(409, "Merge conflict");
207 case "RefConflict":
208 return ghError(409, "Head branch was modified. Review and try the merge again.");
209 case "ReadOnlyRepo":
210 return ghError(403, "Repository is archived (read-only)");
211 case "StoreError":
212 return ghError(500, "Internal error");
213 default:
214 return Effect.die(error);
215 }
216 },
217 ),
218 );
219
220 // ─────────────────────────────────────────────────────────────────────────────
221 // Shape mappers (our data → GitHub JSON)
222 // ─────────────────────────────────────────────────────────────────────────────
223
224 const ghUser = (login: string) => ({
225 login,
226 id: intId(login),
227 node_id: `U_${login}`,
228 type: "User",
229 site_admin: false,
230 });
231
232 const ghRepo = (meta: RepoMetaData, origin: string) => ({
233 id: intId(meta.repoId),
234 node_id: meta.repoId,
235 name: meta.name,
236 full_name: `${meta.owner}/${meta.name}`,
237 owner: ghUser(meta.owner),
238 private: !meta.public,
239 visibility: meta.public ? "public" : "private",
240 html_url: `${origin}/${meta.owner}/${meta.name}`,
241 description: meta.description,
242 fork: meta.forkOf !== null,
243 url: `${origin}/api/v3/repos/${meta.owner}/${meta.name}`,
244 clone_url: `${origin}/${meta.owner}/${meta.name}.git`,
245 git_url: `${origin}/${meta.owner}/${meta.name}.git`,
246 ssh_url: `${origin}/${meta.owner}/${meta.name}.git`,
247 default_branch: meta.defaultBranch,
248 created_at: iso(meta.createdAt),
249 updated_at: iso(meta.createdAt),
250 pushed_at: iso(meta.createdAt),
251 archived: meta.readOnly,
252 disabled: false,
253 size: Math.ceil(meta.objects.bytes / 1024),
254 });
255
256 const ghCommit = (commit: CommitData, origin: string, repoUrl: string) => ({
257 sha: commit.oid,
258 node_id: commit.oid,
259 url: `${repoUrl}/commits/${commit.oid}`,
260 html_url: `${origin.replace("/api/v3", "")}`,
261 commit: {
262 message: commit.message,
263 author: {
264 name: commit.author.name,
265 email: commit.author.email,
266 date: isoSeconds(commit.author),
267 },
268 committer: {
269 name: commit.committer.name,
270 email: commit.committer.email,
271 date: isoSeconds(commit.committer),
272 },
273 tree: { sha: commit.tree },
274 },
275 author: null,
276 committer: null,
277 parents: commit.parents.map((sha) => ({ sha, url: `${repoUrl}/commits/${sha}` })),
278 });
279
280 /**
281 * One changed file, GitHub `pulls/:n/files` shape. `additions`/`deletions`
282 * are 0 by design: the server never computes content diffs (DESIGN.md
283 * §"content diffs are client-side").
284 */
285 const ghFile = (entry: DiffEntryData) => ({
286 sha: entry.newOid ?? entry.oldOid ?? "",
287 filename: entry.path,
288 status: entry.status,
289 additions: 0,
290 deletions: 0,
291 changes: 0,
292 previous_filename: undefined,
293 });
294
295 const ghPullState = (state: PullData["state"]): "open" | "closed" =>
296 state === "open" ? "open" : "closed";
297
298 const ghPull = (pull: PullData & Partial<PullDetailData>, meta: RepoMetaData, origin: string) => {
299 const repoUrl = `${origin}/api/v3/repos/${meta.owner}/${meta.name}`;
300 return {
301 id: intId(`${meta.repoId}#${pull.number}`),
302 node_id: `PR_${meta.repoId}_${pull.number}`,
303 number: pull.number,
304 state: ghPullState(pull.state),
305 merged: pull.state === "merged",
306 locked: false,
307 draft: false,
308 title: pull.title,
309 body: pull.body,
310 user: ghUser(meta.owner),
311 html_url: `${origin}/${meta.owner}/${meta.name}/pulls/${pull.number}`,
312 url: `${repoUrl}/pulls/${pull.number}`,
313 created_at: iso(pull.createdAt),
314 updated_at: iso(pull.updatedAt),
315 closed_at: pull.state === "open" ? null : iso(pull.updatedAt),
316 merged_at: pull.mergedAt === null ? null : iso(pull.mergedAt ?? 0),
317 merge_commit_sha: pull.mergeCommit,
318 base: {
319 ref: shortRef(pull.baseRef),
320 label: `${meta.owner}:${shortRef(pull.baseRef)}`,
321 sha: pull.baseOid ?? "",
322 repo: { full_name: `${meta.owner}/${meta.name}` },
323 },
324 head: {
325 ref: shortRef(pull.headRef),
326 label: `${meta.owner}:${shortRef(pull.headRef)}`,
327 sha: pull.headOid ?? "",
328 repo: { full_name: `${meta.owner}/${meta.name}` },
329 },
330 mergeable: pull.mergeable ?? null,
331 mergeable_state:
332 pull.mergeableReason === "conflict" ? "dirty" : pull.mergeable === true ? "clean" : "unknown",
333 };
334 };
335
336 // ─────────────────────────────────────────────────────────────────────────────
337 // The routes
338 // ─────────────────────────────────────────────────────────────────────────────
339
340 /**
341 * Builds the `/api/v3` route layer. Mounted by the GitWorker next to the
342 * git wire routes; every repo-scoped route flows through the same
343 * `prelude` (owner/name resolution)
344 * as the raw REST routes.
345 */
346 export const gitHubCompatRoutes = (options: GitHubCompatOptions) => {
347 const { prelude, stub } = options;
348
349 /** Repo-scoped route body: prelude, then handler with entry+auth. */
350 const withRepo = <R>(
351 handler: (context: {
352 readonly entry: RegistryEntry;
353 readonly repo: CompatRepoStub;
354 readonly origin: string;
355 readonly repoUrl: string;
356 readonly request: HttpServerRequest.HttpServerRequest;
357 readonly url: URL;
358 readonly params: Readonly<Record<string, string | undefined>>;
359 }) => Effect.Effect<HttpServerResponse.HttpServerResponse, { readonly _tag: string }, R>,
360 ) =>
361 Effect.gen(function* () {
362 const request = yield* HttpServerRequest.HttpServerRequest;
363 const params = yield* HttpRouter.params;
364 const owner = (params.owner ?? "").toLowerCase();
365 const name = (params.repo ?? "").toLowerCase();
366 const resolved = yield* prelude(owner, name);
367 if (resolved.kind === "halt") {
368 // The prelude's plain-text halts become GitHub JSON errors.
369 const status = resolved.response.status;
370 return yield* status === 404 ? ghNotFound : ghError(status, "Internal error");
371 }
372 const origin = yield* originOf;
373 const result = yield* ghCatch(
374 handler({
375 entry: resolved.entry,
376 repo: stub(resolved.entry.repoId),
377 origin,
378 repoUrl: `${origin}/api/v3/repos/${owner}/${name}`,
379 request,
380 url: new URL(request.url, "http://internal"),
381 params,
382 }),
383 );
384 return result as HttpServerResponse.HttpServerResponse;
385 });
386
387 /** `Link: <…>; rel="next"` for cursor pages, GitHub-style. */
388 const linkHeaders = (
389 base: string,
390 query: URLSearchParams,
391 nextCursor: string | null,
392 ): Record<string, string> => {
393 if (nextCursor === null) return {};
394 const next = new URLSearchParams(query);
395 next.set("cursor", nextCursor);
396 return { link: `<${base}?${next}>; rel="next"` };
397 };
398
399 const perPage = (url: URL): number => {
400 const raw = Number.parseInt(url.searchParams.get("per_page") ?? "30", 10);
401 return Number.isFinite(raw) ? Math.max(1, Math.min(raw, 100)) : 30;
402 };
403
404 /** Resolves `:sha` path segments that may be refs (GitHub allows both). */
405 const resolveSha = (repo: CompatRepoStub, revision: string) =>
406 OID_RE.test(revision)
407 ? Effect.succeed(revision)
408 : repo
409 .readCommitLog({ ref: revision, limit: 1 })
410 .pipe(Effect.map((page) => page.items[0]?.oid ?? revision));
411
412 return {
413 /** `GET /api/v3/user` — the credential probe; override the `user` handler in your `github` group to answer from your users. */
414 user: () => ghJson(ghUser("git")),
415 /** `GET /api/v3/repos/:owner/:repo` */
416 repo: () =>
417 withRepo(({ repo, origin }) =>
418 repo.getRepoMeta().pipe(Effect.flatMap((meta) => ghJson(ghRepo(meta, origin)))),
419 ),
420 /** `GET /api/v3/repos/:owner/:repo/branches` */
421 branches: () =>
422 withRepo(({ repo }) =>
423 repo.listRefs("refs/heads/").pipe(
424 Effect.flatMap((page) =>
425 ghJson(
426 page.refs.map((ref) => ({
427 name: shortRef(ref.name),
428 commit: { sha: ref.oid },
429 protected: false,
430 })),
431 ),
432 ),
433 ),
434 ),
435 /** `GET /api/v3/repos/:owner/:repo/commits` */
436 commits: () =>
437 withRepo(({ repo, origin, repoUrl, url }) =>
438 repo
439 .readCommitLog({
440 ref: url.searchParams.get("sha") ?? undefined,
441 cursor: url.searchParams.get("cursor") ?? undefined,
442 limit: perPage(url),
443 })
444 .pipe(
445 Effect.flatMap((page) =>
446 ghJson(
447 page.items.map((commit) => ghCommit(commit, origin, repoUrl)),
448 {
449 headers: linkHeaders(
450 `${repoUrl}/commits`,
451 url.searchParams,
452 page.hasMore ? page.nextCursor : null,
453 ),
454 },
455 ),
456 ),
457 ),
458 ),
459 /** `GET /api/v3/repos/:owner/:repo/commits/:sha` */
460 commit: () =>
461 withRepo(({ repo, origin, repoUrl, params }) =>
462 Effect.gen(function* () {
463 const oid = yield* resolveSha(repo, params.sha ?? "");
464 const log = yield* repo.readCommitLog({ ref: oid, limit: 1 });
465 const commit = log.items[0];
466 if (commit === undefined) return yield* ghNotFound;
467 const diff = yield* repo.readCommitDiff({ oid });
468 return yield* ghJson({
469 ...ghCommit(commit, origin, repoUrl),
470 files: diff.files.map(ghFile),
471 });
472 }),
473 ),
474 /** `GET /api/v3/repos/:owner/:repo/contents/*` */
475 contents: () =>
476 withRepo(({ repo, url, repoUrl }) =>
477 Effect.gen(function* () {
478 const marker = "/contents/";
479 const at = url.pathname.indexOf(marker);
480 const path = decodeURIComponent(url.pathname.slice(at + marker.length));
481 if (path.length === 0) return yield* ghNotFound;
482 const ref = url.searchParams.get("ref") ?? undefined;
483 const file = yield* repo.readFileAtPath({ ref, path });
484 return yield* ghJson({
485 type: "file",
486 encoding: "base64",
487 size: file.size,
488 name: path.split("/").pop(),
489 path,
490 sha: file.oid,
491 url: `${repoUrl}/contents/${path}`,
492 content: Base64.encode(file.content),
493 });
494 }),
495 ),
496 /** `GET /api/v3/repos/:owner/:repo/pulls` */
497 pulls: () =>
498 withRepo(({ repo, origin, repoUrl, url }) =>
499 Effect.gen(function* () {
500 // GitHub's `closed` includes merged; our store distinguishes.
501 const requested = url.searchParams.get("state") ?? "open";
502 const state =
503 requested === "open"
504 ? ("open" as const)
505 : requested === "all"
506 ? ("all" as const)
507 : ("all" as const);
508 const page = yield* repo.listPulls({
509 state,
510 cursor: url.searchParams.get("cursor") ?? undefined,
511 limit: perPage(url),
512 });
513 const meta = yield* repo.getRepoMeta();
514 const items = page.items.filter((pull) =>
515 requested === "all"
516 ? true
517 : requested === "open"
518 ? pull.state === "open"
519 : pull.state !== "open",
520 );
521 return yield* ghJson(
522 items.map((pull) => ghPull(pull, meta, origin)),
523 {
524 headers: linkHeaders(
525 `${repoUrl}/pulls`,
526 url.searchParams,
527 page.hasMore ? page.nextCursor : null,
528 ),
529 },
530 );
531 }),
532 ),
533 /** `POST /api/v3/repos/:owner/:repo/pulls` */
534 createPull: () =>
535 withRepo(({ repo, origin, request }) =>
536 Effect.gen(function* () {
537 const body = (yield* request.json.pipe(
538 Effect.mapError(() => ({ _tag: "ValidationError" as const })),
539 )) as { title?: string; head?: string; base?: string; body?: string };
540 if (!body.title || !body.head || !body.base) {
541 return yield* ghError(422, "Validation Failed: title, head and base are required");
542 }
543 const pull = yield* repo.createPull({
544 title: body.title,
545 body: body.body,
546 base: body.base,
547 head: body.head,
548 });
549 const meta = yield* repo.getRepoMeta();
550 return yield* ghJson(ghPull(pull, meta, origin), { status: 201 });
551 }),
552 ),
553 /** `GET /api/v3/repos/:owner/:repo/pulls/:number` */
554 pull: () =>
555 withRepo(({ repo, origin, params }) =>
556 Effect.gen(function* () {
557 const number = Number.parseInt(params.number ?? "", 10);
558 if (!Number.isFinite(number)) return yield* ghNotFound;
559 const pull = yield* repo.getPull(number);
560 const meta = yield* repo.getRepoMeta();
561 return yield* ghJson(ghPull(pull, meta, origin));
562 }),
563 ),
564 /** `PATCH /api/v3/repos/:owner/:repo/pulls/:number` */
565 updatePull: () =>
566 withRepo(({ repo, origin, params, request }) =>
567 Effect.gen(function* () {
568 const number = Number.parseInt(params.number ?? "", 10);
569 if (!Number.isFinite(number)) return yield* ghNotFound;
570 const body = (yield* request.json.pipe(
571 Effect.mapError(() => ({ _tag: "ValidationError" as const })),
572 )) as { title?: string; body?: string | null; state?: string };
573 if (body.state !== undefined && body.state !== "open" && body.state !== "closed") {
574 return yield* ghError(422, "Validation Failed: invalid state");
575 }
576 const pull = yield* repo.updatePull({
577 number,
578 title: body.title,
579 body: body.body,
580 state: body.state as "open" | "closed" | undefined,
581 });
582 const meta = yield* repo.getRepoMeta();
583 return yield* ghJson(ghPull(pull, meta, origin));
584 }),
585 ),
586 /** `PUT /api/v3/repos/:owner/:repo/pulls/:number/merge` */
587 mergePull: () =>
588 withRepo(({ repo, params, request }) =>
589 Effect.gen(function* () {
590 const number = Number.parseInt(params.number ?? "", 10);
591 if (!Number.isFinite(number)) return yield* ghNotFound;
592 const raw = yield* request.json.pipe(Effect.orElseSucceed(() => ({})));
593 const body = raw as { commit_message?: string; sha?: string; merge_method?: string };
594 if (body.merge_method !== undefined && body.merge_method !== "merge") {
595 // squash/rebase rewrite history server-side — not supported.
596 return yield* ghError(405, `Merge method '${body.merge_method}' is not supported`);
597 }
598 const result = yield* repo.mergePull({
599 number,
600 message: body.commit_message,
601 expectedHeadOid: body.sha,
602 });
603 return yield* ghJson({
604 sha: result.oid,
605 merged: true,
606 message: "Pull Request successfully merged",
607 });
608 }),
609 ),
610 /** `GET /api/v3/repos/:owner/:repo/pulls/:number/files` */
611 pullFiles: () =>
612 withRepo(({ repo, params }) =>
613 Effect.gen(function* () {
614 const number = Number.parseInt(params.number ?? "", 10);
615 if (!Number.isFinite(number)) return yield* ghNotFound;
616 const pull = yield* repo.getPull(number);
617 // Open PR with live branches: three-dot compare. Merged PR: the
618 // merge commit's first-parent diff is the canonical record.
619 if (pull.baseOid !== null && pull.headOid !== null) {
620 const compare = yield* repo.compareCommits({ base: pull.baseRef, head: pull.headRef });
621 return yield* ghJson(compare.files.map(ghFile));
622 }
623 if (pull.mergeCommit !== null) {
624 const diff = yield* repo.readCommitDiff({ oid: pull.mergeCommit });
625 return yield* ghJson(diff.files.map(ghFile));
626 }
627 return yield* ghJson([]);
628 }),
629 ),
630 };
631 };