Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
6import {
7 NonNegativeInt,
8 TrimmedNonEmptyString,
9 type PullRequestCapabilities,
10 type PullRequestStackHead,
11} from "@t3tools/contracts";
12import {
13 PullRequestProviderError,
14 type ProviderRepositoryRef,
15 type PullRequestProviderApi,
16} from "@t3tools/source-control-core/server/PullRequestProvider";
17
18import * as GitCafeApi from "./GitCafeApi.ts";
19import * as GitCafeHosts from "./gitCafeHosts.ts";
20import * as Json from "./gitCafePullRequestJson.ts";
21import { definition } from "../client/definition.ts";
22
23const CAPABILITIES: PullRequestCapabilities = {
24 diff: true,
25 comment: true,
26 actions: [...definition.changeRequestActions],
27 mergeMethods: ["merge", "squash", "rebase"],
28 // Only through a stack: GitCafe's one branch update restacks every layer above it.
29 updateMethods: ["rebase"],
30 search: true,
31 stacks: true,
32 stackActions: true,
33 reactions: true,
34 labels: false,
35 // Line comments go through GitCafe's review drafts, which arrive with revision fencing.
36 review: {
37 inlineComment: false,
38 reply: true,
39 resolve: true,
40 verdicts: ["approve", "request-changes", "comment"],
41 },
42 reviewers: { request: false, listCandidates: false },
43 edit: { changeRequest: true, comment: true },
44};
45
46const PAGE_SIZE = 100;
47const MAX_PAGES = 10;
48/** GitCafe's cap on paths per `/diff-files` read, and so one diff page. */
49const DIFF_FILES_BATCH = 64;
50/**
51 * Line totals cost one hunk read per batch, so a pull request larger than this reports none
52 * rather than reading every file.
53 */
54const LINE_STATS_MAX_FILES = DIFF_FILES_BATCH * 4;
55const MAX_CHANGE_PAGES = 20;
56const LINE_STATS_CACHE_SIZE = 256;
57
58const chunk = <A>(items: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> =>
59 Array.from({ length: Math.ceil(items.length / size) }, (_, index) =>
60 items.slice(index * size, (index + 1) * size),
61 );
62
63const detailablePaths = (files: ReadonlyArray<Json.GitCafeDiffFile>) =>
64 files.filter((file) => !file.binary && !file.tooLarge).map((file) => file.path);
65
66const mergeStrategyOpen = (status: typeof Status.Type, strategy: string) =>
67 status.merge.permitted !== false &&
68 status.merge.strategies.includes(strategy) &&
69 !(status.merge.blockers ?? []).some((blocker) =>
70 (blocker.blockedStrategies ?? []).includes(strategy),
71 );
72
73const Id = TrimmedNonEmptyString.check(Schema.isPattern(/^[A-Za-z0-9_-]+$/u));
74const isId = Schema.is(Id);
75const Principal = Schema.Struct({ handle: TrimmedNonEmptyString });
76const Written = Schema.Struct({ id: Id });
77const Versioned = Schema.Struct({ version: NonNegativeInt });
78const CommentDetail = Schema.Struct({ id: Id, version: NonNegativeInt });
79const Status = Schema.Struct({
80 merge: Schema.Struct({
81 conflicts: Schema.Literals(["unknown", "conflicting"]),
82 fastForward: Schema.NullOr(Schema.Boolean),
83 strategies: Schema.Array(Schema.String),
84 permitted: Schema.optional(Schema.Boolean),
85 blockers: Schema.optional(
86 Schema.Array(
87 Schema.Struct({ blockedStrategies: Schema.optional(Schema.Array(Schema.String)) }),
88 ),
89 ),
90 }),
91 checks: Schema.Struct({
92 pending: NonNegativeInt,
93 failing: NonNegativeInt,
94 total: NonNegativeInt,
95 }),
96});
97const FilterOptions = Schema.Struct({
98 actors: Schema.Array(
99 Schema.Struct({ actorId: TrimmedNonEmptyString, handle: TrimmedNonEmptyString }),
100 ),
101});
102const encodeActorIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
103const BranchCommit = Schema.Struct({ oid: TrimmedNonEmptyString });
104const Snapshot = {
105 version: NonNegativeInt,
106 headOid: TrimmedNonEmptyString,
107 comparisonBaseOid: TrimmedNonEmptyString,
108};
109const Changes = Schema.Struct({
110 ...Snapshot,
111 items: Json.GitCafeDiffFiles,
112 next: Schema.NullOr(TrimmedNonEmptyString),
113});
114const DiffFiles = Schema.Struct({ ...Snapshot, items: Json.GitCafeDiffFiles });
115const DiffCursor = Schema.Struct({
116 version: NonNegativeInt,
117 headOid: TrimmedNonEmptyString,
118 baseOid: TrimmedNonEmptyString,
119 after: TrimmedNonEmptyString,
120});
121const encodeDiffCursor = Schema.encodeSync(Schema.fromJsonString(DiffCursor));
122const decodeDiffCursor = Schema.decodeEffect(Schema.fromJsonString(DiffCursor));
123const MergeOutcome = Schema.Struct({
124 id: Schema.String,
125 state: Schema.Literals(["accepted", "completed", "failed"]),
126 reason: Schema.optional(Schema.String),
127});
128const StackOutcome = Schema.Struct({ id: Schema.String, state: Schema.String });
129const FAILED_STACK_STATES = new Set(["failed", "stopped", "cancelled", "reconciliation_required"]);
130
131type PullRef = ProviderRepositoryRef & { readonly number: number };
132type Paged<A> = { readonly items: ReadonlyArray<A>; readonly next: string | null };
133
134function stackHeadsCurrent(
135 stack: Json.GitCafeStack,
136 input: { readonly number: number; readonly merge: boolean },
137 expected: ReadonlyArray<PullRequestStackHead>,
138): boolean {
139 const members = stack.members.toSorted((a, b) => a.position - b.position);
140 const index = members.findIndex((member) => member.pullRequestNumber === input.number);
141 if (index === -1) return false;
142 const moved = (input.merge ? members.slice(0, index + 1) : members).filter(
143 (member) => member.state !== "merged",
144 );
145 return (
146 moved.length === expected.length &&
147 moved.every(
148 (member) =>
149 member.headOid !== undefined &&
150 expected.some(
151 (head) => head.number === member.pullRequestNumber && head.headSha === member.headOid,
152 ),
153 )
154 );
155}
156
157const withDetails = (
158 files: ReadonlyArray<Json.GitCafeDiffFile>,
159 details: ReadonlyArray<Json.GitCafeDiffFile>,
160) => {
161 const byPath = new Map(details.map((file) => [file.path, file]));
162 return files.map((file) => byPath.get(file.path) ?? file);
163};
164
165/** @public Service construction is part of the canonical Effect module API. */
166export const make = Effect.gen(function* () {
167 const api = yield* GitCafeApi.GitCafeApi;
168
169 const failure = (operation: string, detail: string, cause?: unknown) =>
170 new PullRequestProviderError({
171 provider: SourceControlProviderKind.make("gitcafe"),
172 operation,
173 reason: "failed",
174 detail,
175 ...(cause === undefined ? {} : { cause }),
176 });
177
178 const repositoryPath = (
179 operation: string,
180 input: ProviderRepositoryRef,
181 ): Effect.Effect<string, PullRequestProviderError> =>
182 GitCafeHosts.isGitCafeHost(input.host) &&
183 GitCafeHosts.gitCafeRepositoryPath(input.repository) === input.repository
184 ? Effect.succeed(`/repos/${input.repository}`)
185 : Effect.fail(
186 failure(
187 operation,
188 `GitCafe serves owner/name repositories on ${GitCafeHosts.GITCAFE_HOSTS.join(" and ")}.`,
189 ),
190 );
191
192 const send = (
193 operation: string,
194 input: Pick<ProviderRepositoryRef, "host">,
195 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
196 ) =>
197 api.request({ ...request, host: input.host, operation }).pipe(
198 Effect.mapError(
199 (error) =>
200 new PullRequestProviderError({
201 provider: SourceControlProviderKind.make("gitcafe"),
202 operation,
203 reason: error.reason,
204 detail: error.detail,
205 cause: error,
206 }),
207 ),
208 );
209
210 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
211 operation: string,
212 input: Pick<ProviderRepositoryRef, "host">,
213 request: Omit<GitCafeApi.GitCafeApiRequest, "operation" | "host">,
214 schema: S,
215 ) =>
216 send(operation, input, request).pipe(
217 Effect.flatMap((raw) =>
218 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
219 Effect.mapError((cause) =>
220 failure(operation, "GitCafe returned an unreadable response.", cause),
221 ),
222 ),
223 ),
224 );
225
226 const pullPath = (operation: string, input: PullRef) =>
227 repositoryPath(operation, input).pipe(Effect.map((base) => `${base}/pulls/${input.number}`));
228
229 const readPull = (operation: string, input: PullRef) =>
230 pullPath(operation, input).pipe(
231 Effect.flatMap((path) => read(operation, input, { path }, Json.GitCafePullDetail)),
232 );
233
234 const readPages = Effect.fn("GitCafePullRequestProvider.readPages")(function* <
235 S extends Schema.Codec<Paged<unknown>, unknown, never, never>,
236 >(operation: string, input: Pick<ProviderRepositoryRef, "host">, path: string, schema: S) {
237 const items: Array<S["Type"]["items"][number]> = [];
238 let next: string | null = null;
239 for (let page = 0; page < MAX_PAGES; page++) {
240 const query = new URLSearchParams({ limit: String(PAGE_SIZE) });
241 if (next !== null) query.set("after", next);
242 const batch: S["Type"] = yield* read(operation, input, { path: `${path}?${query}` }, schema);
243 items.push(...batch.items);
244 const previous: string | null = next;
245 next = batch.next;
246 if (next === null || next === previous || batch.items.length === 0) break;
247 }
248 return { items, next };
249 });
250
251 const readComments = (operation: string, input: PullRef) =>
252 pullPath(operation, input).pipe(
253 Effect.flatMap((path) =>
254 readPages(operation, input, `${path}/comments`, Json.GitCafeComments),
255 ),
256 );
257
258 /**
259 * GitCafe's stack lists no heads, and they are what a land or restack is fenced on, so each
260 * open layer's pull is read.
261 */
262 const readStack = Effect.fn("GitCafePullRequestProvider.readStack")(function* (
263 operation: string,
264 input: PullRef,
265 ) {
266 const path = yield* pullPath(operation, input);
267 const { stack } = yield* read(
268 operation,
269 input,
270 { path: `${path}/stack` },
271 Json.GitCafeStackEnvelope,
272 );
273 if (stack === null) return null;
274 const members = yield* Effect.forEach(
275 stack.members,
276 (member) =>
277 member.state === "merged"
278 ? Effect.succeed(member)
279 : readPull(operation, { ...input, number: member.pullRequestNumber }).pipe(
280 Effect.map((pull) =>
281 pull.headOid == null ? member : { ...member, headOid: pull.headOid },
282 ),
283 ),
284 { concurrency: 4 },
285 );
286 return { ...stack, members };
287 });
288
289 const readDiffFiles = Effect.fn("GitCafePullRequestProvider.readDiffFiles")(function* (
290 input: PullRef,
291 revision: { readonly version: number; readonly headOid: string; readonly baseOid: string },
292 paths: ReadonlyArray<string>,
293 ) {
294 if (paths.length === 0) return [];
295 const path = yield* pullPath("getDiff", input);
296 const files = yield* read(
297 "getDiff",
298 input,
299 {
300 method: "POST",
301 path: `${path}/diff-files`,
302 body: { paths, expectedVersion: revision.version },
303 },
304 DiffFiles,
305 );
306 if (
307 files.version !== revision.version ||
308 files.headOid !== revision.headOid ||
309 files.comparisonBaseOid !== revision.baseOid
310 )
311 return yield* failure(
312 "getDiff",
313 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
314 );
315 return files.items;
316 });
317
318 const runStackAction = Effect.fn("GitCafePullRequestProvider.runStackAction")(function* (
319 input: Parameters<PullRequestProviderApi["runAction"]>[0] & { readonly stackNumber: number },
320 ) {
321 const land = input.action === "merge";
322 const operation = land ? "landStackThrough" : "restackStack";
323 if (!land && input.action !== "update-branch")
324 return yield* failure(operation, `GitCafe cannot ${input.action} a stack.`);
325 const stack = yield* readStack(operation, input);
326 if (
327 stack === null ||
328 stack.number !== input.stackNumber ||
329 input.expectedStackHeads === undefined ||
330 !stackHeadsCurrent(stack, { number: input.number, merge: land }, input.expectedStackHeads)
331 )
332 return yield* failure(
333 operation,
334 "The stack changed since it was read. Refresh it and try again.",
335 );
336 const base = yield* repositoryPath(operation, input);
337 const outcome = yield* read(
338 operation,
339 input,
340 {
341 method: "POST",
342 path: `${base}/pulls/stacks/${stack.number}/${land ? "land-through" : "restack"}`,
343 body: land
344 ? {
345 expectedRevision: stack.revision,
346 requestId: yield* randomUuidV4,
347 throughPullRequestNumber: input.number,
348 strategy: input.mergeMethod ?? "merge",
349 }
350 : { expectedRevision: stack.revision, requestId: yield* randomUuidV4 },
351 },
352 StackOutcome,
353 );
354 if (FAILED_STACK_STATES.has(outcome.state))
355 return yield* failure(operation, `GitCafe's stack operation ${outcome.state}.`);
356 });
357
358 // GitCafe's pulls carry no line totals, and linked pull requests are summarized every minute,
359 // so hunk totals are held per compared pair of commits. The file list that names the pair is
360 // cheap; a retarget or a landed parent layer moves the base without moving the head.
361 const lineTotals = new Map<string, { readonly additions: number; readonly deletions: number }>();
362
363 const readLineStats = Effect.fn("GitCafePullRequestProvider.readLineStats")(function* (
364 input: PullRef,
365 version: number,
366 ) {
367 const path = yield* pullPath("getChangeRequest", input);
368 const files: Array<Json.GitCafeDiffFile> = [];
369 let revision: { version: number; headOid: string; baseOid: string } | undefined;
370 let after: string | null = null;
371 for (let page = 0; page < MAX_CHANGE_PAGES; page++) {
372 const query = new URLSearchParams({ expectedVersion: String(version), limit: "500" });
373 if (after !== null) query.set("after", after);
374 const batch: typeof Changes.Type = yield* read(
375 "getChangeRequest",
376 input,
377 { path: `${path}/changes?${query}` },
378 Changes,
379 );
380 revision ??= {
381 version: batch.version,
382 headOid: batch.headOid,
383 baseOid: batch.comparisonBaseOid,
384 };
385 files.push(...batch.items);
386 const previous: string | null = after;
387 after = batch.next;
388 if (after === null || after === previous || batch.items.length === 0) break;
389 }
390 if (revision === undefined) return { changedFiles: 0, additions: 0, deletions: 0 };
391 const key = `${input.host} ${input.repository.toLowerCase()} ${input.number} ${revision.baseOid} ${revision.headOid}`;
392 const held = lineTotals.get(key);
393 if (held !== undefined) return { changedFiles: files.length, ...held };
394 const details = files.some((file) => file.additions !== undefined)
395 ? Option.some(files)
396 : files.length > LINE_STATS_MAX_FILES
397 ? Option.none()
398 : yield* Effect.forEach(
399 chunk(detailablePaths(files), DIFF_FILES_BATCH),
400 (paths) => readDiffFiles(input, revision, paths),
401 { concurrency: 4 },
402 ).pipe(
403 Effect.map((batches) => batches.flat()),
404 Effect.option,
405 );
406 // Unread hunks leave the lines unknown rather than zero; the file count still stands.
407 if (Option.isNone(details)) return { changedFiles: files.length };
408 const counted = details.value;
409 const totals = {
410 additions: counted.reduce((total, file) => total + (file.additions ?? 0), 0),
411 deletions: counted.reduce((total, file) => total + (file.deletions ?? 0), 0),
412 };
413 if (lineTotals.size >= LINE_STATS_CACHE_SIZE)
414 lineTotals.delete(lineTotals.keys().next().value!);
415 lineTotals.set(key, totals);
416 return { changedFiles: files.length, ...totals };
417 });
418
419 const merge = Effect.fn("GitCafePullRequestProvider.merge")(function* (
420 input: Parameters<PullRequestProviderApi["runAction"]>[0],
421 ) {
422 const pull = yield* readPull("merge", input);
423 if (pull.state === "merged") return;
424 if (pull.mergeRoute === "unsupported")
425 return yield* failure("merge", "This GitCafe pull request has no supported merge route.");
426 const base = yield* repositoryPath("merge", input);
427 // GitCafe observes the base only for merges it routes to the provider; a native merge is
428 // fenced on the target branch's current commit.
429 const baseOid =
430 pull.mergeRoute === "provider"
431 ? pull.observedBaseOid
432 : (yield* read(
433 "merge",
434 input,
435 {
436 path: `${base}/commit?ref=${encodeURIComponent(`refs/heads/${pull.targetBranch}`)}`,
437 },
438 BranchCommit,
439 )).oid;
440 if (pull.headOid === null || baseOid == null)
441 return yield* failure(
442 "merge",
443 "GitCafe has not reported the pull request's head and base yet. Refresh and try again.",
444 );
445 const path = yield* pullPath("merge", input);
446 const outcome = yield* read(
447 "merge",
448 input,
449 {
450 method: "POST",
451 path: `${path}/merge`,
452 body: {
453 requestId: yield* randomUuidV4,
454 expectedVersion: pull.version,
455 headOid: pull.headOid,
456 baseOid,
457 strategy: input.mergeMethod ?? "merge",
458 },
459 },
460 MergeOutcome,
461 );
462 if (outcome.state === "failed")
463 return yield* failure("merge", outcome.reason ?? "GitCafe could not merge the pull request.");
464 });
465
466 const provider: PullRequestProviderApi = {
467 kind: SourceControlProviderKind.make("gitcafe"),
468 capabilities: CAPABILITIES,
469 getViewer: (input) =>
470 read(
471 "getViewer",
472 { host: input.host ?? "git.cafe" },
473 { path: "/auth/principal" },
474 Principal,
475 ).pipe(Effect.map((principal) => principal.handle)),
476 listChangeRequests: Effect.fn("GitCafePullRequestProvider.listChangeRequests")(
477 function* (input) {
478 const base = yield* repositoryPath("listChangeRequests", input);
479 const involved = input.involvement === "authored" || input.involvement === "reviewing";
480 let actorId: string | undefined;
481 if (involved) {
482 // A host narrows as far as it can: when the actor list can't be read, the listing comes
483 // back unnarrowed and the page's own involvement filter does the rest. A refused token
484 // or a rate limit still fails, since the service acts on those for the whole host.
485 const options = yield* read(
486 "listChangeRequests",
487 input,
488 { path: `${base}/filter-options` },
489 FilterOptions,
490 ).pipe(
491 Effect.map(Option.some),
492 Effect.catchTags({
493 PullRequestProviderError: (error) =>
494 error.reason === "unauthenticated" || error.reason === "rate-limited"
495 ? Effect.fail(error)
496 : Effect.succeed(Option.none()),
497 }),
498 );
499 if (Option.isSome(options)) {
500 actorId = options.value.actors.find(
501 (actor) => actor.handle.toLowerCase() === input.viewer.toLowerCase(),
502 )?.actorId;
503 if (actorId === undefined) return { items: [], truncated: false, continues: false };
504 }
505 }
506 const limit = Math.max(1, input.limit);
507 const items: Array<Json.GitCafePull> = [];
508 let next: string | null = null;
509 do {
510 const query = new URLSearchParams({
511 limit: String(Math.min(PAGE_SIZE, limit - items.length)),
512 sort: "newest",
513 });
514 if (input.state !== "all") query.set("state", input.state);
515 if (input.query?.trim()) query.set("q", input.query.trim());
516 if (actorId !== undefined)
517 query.set(
518 input.involvement === "reviewing" ? "reviewers" : "authors",
519 encodeActorIds([actorId]),
520 );
521 if (next !== null) query.set("after", next);
522 const page: typeof Json.GitCafePulls.Type = yield* read(
523 "listChangeRequests",
524 input,
525 { path: `${base}/pulls?${query}` },
526 Json.GitCafePulls,
527 );
528 items.push(...page.items);
529 next = page.items.length === 0 ? null : page.next;
530 } while (next !== null && items.length < limit);
531 return {
532 items: items.slice(0, limit).map((pull) => {
533 const item = Json.toChangeRequest(pull, input);
534 return input.involvement === "reviewing" && actorId !== undefined
535 ? {
536 ...item,
537 reviewRequestLogins: [...new Set([...item.reviewRequestLogins, input.viewer])],
538 }
539 : item;
540 }),
541 truncated: next !== null,
542 continues: false,
543 };
544 },
545 ),
546 getChangeRequestSummary: Effect.fn("GitCafePullRequestProvider.getChangeRequestSummary")(
547 function* (input) {
548 const pull = yield* readPull("getChangeRequestSummary", input);
549 const changes =
550 pull.headOid === null
551 ? null
552 : yield* readLineStats(input, pull.version).pipe(Effect.orElseSucceed(() => null));
553 // A count that could not be read is absent rather than zero.
554 const {
555 additions: _additions,
556 deletions: _deletions,
557 ...summary
558 } = Json.toChangeRequest(pull, input);
559 return {
560 ...summary,
561 ...(changes === null ? {} : changes),
562 closedAt: pull.closedAt,
563 mergedAt: pull.mergedAt,
564 };
565 },
566 ),
567 getChangeRequest: Effect.fn("GitCafePullRequestProvider.getChangeRequest")(function* (input) {
568 const pull = yield* readPull("getChangeRequest", input);
569 const path = yield* pullPath("getChangeRequest", input);
570 const base = yield* repositoryPath("getChangeRequest", input);
571 const [status, checks, changes] = yield* Effect.all(
572 [
573 read("getChangeRequest", input, { path: `${path}/status` }, Status),
574 pull.headOid === null
575 ? Effect.succeed(null)
576 : readPages(
577 "getChangeRequest",
578 input,
579 `${base}/commits/${encodeURIComponent(pull.headOid)}/checks`,
580 Json.GitCafeChecks,
581 ),
582 pull.headOid === null
583 ? Effect.succeed(null)
584 : readLineStats(input, pull.version).pipe(Effect.orElseSucceed(() => null)),
585 ],
586 { concurrency: 3 },
587 );
588 const permissions = Json.toViewerPermissions(pull);
589 return {
590 ...Json.toChangeRequest(pull, input),
591 headSha: pull.headOid,
592 body: pull.description ?? "",
593 ...(pull.sourceRepo === null
594 ? {}
595 : { headRepositoryNameWithOwner: `${pull.sourceRepo.owner}/${pull.sourceRepo.name}` }),
596 additions: changes?.additions ?? 0,
597 deletions: changes?.deletions ?? 0,
598 changedFiles: changes?.changedFiles ?? 0,
599 closedAt: pull.closedAt,
600 mergedAt: pull.mergedAt,
601 reviewers: Json.toReviewers(pull, input.host),
602 checks: checks === null ? [] : Json.toChecks(checks),
603 ...(status.checks.total === 0
604 ? {}
605 : {
606 checksState:
607 status.checks.failing > 0
608 ? ("failing" as const)
609 : status.checks.pending > 0
610 ? ("pending" as const)
611 : ("passing" as const),
612 }),
613 mergeability:
614 status.merge.conflicts === "conflicting"
615 ? ("conflicting" as const)
616 : ("unknown" as const),
617 baseComparison:
618 status.merge.fastForward === null
619 ? ("unknown" as const)
620 : status.merge.fastForward
621 ? ("up-to-date" as const)
622 : ("behind" as const),
623 mergeCapabilities: {
624 merge: mergeStrategyOpen(status, "merge"),
625 squash: mergeStrategyOpen(status, "squash"),
626 rebase: mergeStrategyOpen(status, "rebase"),
627 },
628 viewerPermissions:
629 status.merge.permitted === false
630 ? { ...permissions, actions: permissions.actions.filter((a) => a !== "merge") }
631 : permissions,
632 };
633 }),
634 getChangeRequestStack: (input) =>
635 readStack("getChangeRequestStack", input).pipe(
636 Effect.map((stack) => (stack === null ? null : Json.toStack(stack, input))),
637 ),
638 getChangeRequestActivity: Effect.fn("GitCafePullRequestProvider.getChangeRequestActivity")(
639 function* (input) {
640 const pull = yield* readPull("getChangeRequestActivity", input);
641 const path = yield* pullPath("getChangeRequestActivity", input);
642 const operation = "getChangeRequestActivity";
643 const [comments, reviews, commits, reactions] = yield* Effect.all(
644 [
645 readComments(operation, input),
646 readPages(operation, input, `${path}/reviews`, Json.GitCafeReviews),
647 pull.headOid === null
648 ? Effect.succeed({ items: [], next: null })
649 : readPages(operation, input, `${path}/commits`, Json.GitCafeCommits),
650 readPages(operation, input, `${path}/reactions/`, Json.GitCafeReactions).pipe(
651 Effect.orElseSucceed(() => undefined),
652 ),
653 ],
654 { concurrency: 4 },
655 );
656 return Json.toActivity({
657 comments,
658 reviews,
659 commits: { ...commits, truncated: commits.next !== null, headOid: pull.headOid ?? "" },
660 host: input.host,
661 ...(pull.headOid === null ? {} : { headOid: pull.headOid }),
662 ...(reactions === undefined ? {} : { reactions }),
663 });
664 },
665 ),
666 getViewerPermissions: (input) =>
667 readPull("getViewerPermissions", input).pipe(Effect.map(Json.toViewerPermissions)),
668 getDiff: Effect.fn("GitCafePullRequestProvider.getDiff")(function* (input) {
669 if (input.commit !== undefined)
670 return yield* failure("getDiff", "GitCafe commit diffs are not supported yet.");
671 const cursor =
672 input.cursor === undefined
673 ? null
674 : yield* decodeDiffCursor(input.cursor).pipe(
675 Effect.mapError((cause) => failure("getDiff", "Invalid GitCafe diff cursor.", cause)),
676 );
677 const version = cursor?.version ?? (yield* readPull("getDiff", input)).version;
678 const path = yield* pullPath("getDiff", input);
679 const query = new URLSearchParams({
680 expectedVersion: String(version),
681 limit: String(DIFF_FILES_BATCH),
682 });
683 if (cursor !== null) query.set("after", cursor.after);
684 const page = yield* read("getDiff", input, { path: `${path}/changes?${query}` }, Changes);
685 if (
686 page.version !== version ||
687 (cursor !== null &&
688 (cursor.headOid !== page.headOid || cursor.baseOid !== page.comparisonBaseOid))
689 )
690 return yield* failure(
691 "getDiff",
692 "GitCafe answered from a different revision of the pull request. Refresh the diff.",
693 );
694 const revision = { version, headOid: page.headOid, baseOid: page.comparisonBaseOid };
695 const details = yield* readDiffFiles(input, revision, detailablePaths(page.items));
696 return {
697 ...Json.toDiff({ items: withDetails(page.items, details) }),
698 nextCursor: page.next === null ? null : encodeDiffCursor({ ...revision, after: page.next }),
699 };
700 }),
701 runAction: Effect.fn("GitCafePullRequestProvider.runAction")(function* (input) {
702 if (input.stackNumber !== undefined)
703 return yield* runStackAction({ ...input, stackNumber: input.stackNumber });
704 switch (input.action) {
705 case "merge":
706 return yield* merge(input);
707 case "ready":
708 case "draft":
709 case "close":
710 case "reopen": {
711 const pull = yield* readPull(input.action, input);
712 const path = yield* pullPath(input.action, input);
713 yield* send(input.action, input, {
714 method: "POST",
715 path: `${path}/${input.action}`,
716 body: { expectedVersion: pull.version },
717 });
718 return;
719 }
720 default:
721 return yield* failure(input.action, `GitCafe cannot ${input.action} from T3 Code.`);
722 }
723 }),
724 updateChangeRequest: Effect.fn("GitCafePullRequestProvider.updateChangeRequest")(
725 function* (input) {
726 const pull = yield* readPull("updateChangeRequest", input);
727 const path = yield* pullPath("updateChangeRequest", input);
728 yield* read(
729 "updateChangeRequest",
730 input,
731 {
732 method: "PATCH",
733 path,
734 body: {
735 expectedVersion: pull.version,
736 ...(input.title === undefined ? {} : { title: input.title }),
737 ...(input.body === undefined ? {} : { description: input.body }),
738 },
739 },
740 Versioned,
741 );
742 },
743 ),
744 comment: (input) =>
745 pullPath("comment", input).pipe(
746 Effect.flatMap((path) =>
747 read(
748 "comment",
749 input,
750 { method: "POST", path: `${path}/comments/`, body: { body: input.body } },
751 Written,
752 ),
753 ),
754 Effect.asVoid,
755 ),
756 updateComment: Effect.fn("GitCafePullRequestProvider.updateComment")(function* (input) {
757 if (!isId(input.commentId))
758 return yield* failure("updateComment", "GitCafe comment ids are opaque slugs.");
759 const path = `${yield* pullPath("updateComment", input)}/comments/${input.commentId}`;
760 const detail = yield* read("updateComment", input, { path: `${path}/detail` }, CommentDetail);
761 yield* read(
762 "updateComment",
763 input,
764 { method: "PATCH", path, body: { body: input.body, expectedVersion: detail.version } },
765 Written,
766 );
767 }),
768 submitReview: Effect.fn("GitCafePullRequestProvider.submitReview")(function* (input) {
769 if (input.comments.length > 0)
770 return yield* failure("submitReview", "GitCafe line comments are not supported yet.");
771 const pull = yield* readPull("submitReview", input);
772 if (pull.headOid === null)
773 return yield* failure("submitReview", "GitCafe has not reported the pull request's head.");
774 const path = yield* pullPath("submitReview", input);
775 yield* read(
776 "submitReview",
777 input,
778 {
779 method: "POST",
780 path: `${path}/reviews`,
781 body: {
782 verdict: input.verdict === "request-changes" ? "request_changes" : input.verdict,
783 ...(input.body.length === 0 ? {} : { body: input.body }),
784 commitOid: pull.headOid,
785 expectedVersion: pull.version,
786 requestId: yield* randomUuidV4,
787 },
788 },
789 Written,
790 );
791 }),
792 listReviewerCandidates: () =>
793 Effect.fail(
794 failure("listReviewerCandidates", "GitCafe reviewer requests are not supported."),
795 ),
796 setReviewerRequest: () =>
797 Effect.fail(failure("setReviewerRequest", "GitCafe reviewer requests are not supported.")),
798 replyToThread: Effect.fn("GitCafePullRequestProvider.replyToThread")(function* (input) {
799 if (!isId(input.threadId))
800 return yield* failure("replyToThread", "GitCafe thread ids are opaque slugs.");
801 const path = yield* pullPath("replyToThread", input);
802 yield* read(
803 "replyToThread",
804 input,
805 {
806 method: "POST",
807 path: `${path}/comments/${input.threadId}/replies`,
808 body: { body: input.body },
809 },
810 Written,
811 );
812 }),
813 setReaction: Effect.fn("GitCafePullRequestProvider.setReaction")(function* (input) {
814 const path = `${yield* pullPath("setReaction", input)}/reactions/`;
815 const subject =
816 input.subjectId === undefined
817 ? { kind: "pull_request" as const, id: (yield* readPull("setReaction", input)).id }
818 : { kind: "pull_request_comment" as const, id: input.subjectId };
819 const reactions = yield* readPages("setReaction", input, path, Json.GitCafeReactions);
820 const mine = reactions.items.find(
821 (item) =>
822 item.subject.kind === subject.kind &&
823 item.subject.id === subject.id &&
824 item.emoji.kind === "unicode" &&
825 Json.reactionContent(item.emoji.value) === input.content,
826 )?.viewerReactionId;
827 if (input.reacted === (mine != null)) return;
828 if (input.reacted) {
829 yield* send("setReaction", input, {
830 method: "POST",
831 path,
832 body: { subject, emoji: { kind: "unicode", value: Json.REACTION_EMOJI[input.content] } },
833 });
834 return;
835 }
836 if (mine == null) return;
837 if (!isId(mine))
838 return yield* failure("setReaction", "GitCafe returned an unreadable reaction id.");
839 yield* send("setReaction", input, { method: "DELETE", path: `${path}${mine}` });
840 }),
841 setThreadResolution: Effect.fn("GitCafePullRequestProvider.setThreadResolution")(
842 function* (input) {
843 const comments = yield* readComments("setThreadResolution", input);
844 const root = comments.items.find(
845 (comment) => comment.id === input.threadId && comment.threadId === input.threadId,
846 );
847 if (root === undefined || root.version === undefined || !isId(root.id))
848 return yield* failure("setThreadResolution", "GitCafe did not return the thread root.");
849 if (input.resolved === (root.resolvedAt !== null)) return;
850 const path = yield* pullPath("setThreadResolution", input);
851 yield* read(
852 "setThreadResolution",
853 input,
854 {
855 method: "POST",
856 path: `${path}/comments/${root.id}/${input.resolved ? "resolve" : "unresolve"}`,
857 body: { expectedVersion: root.version },
858 },
859 Written,
860 );
861 },
862 ),
863 };
864 return provider;
865});