Open History to see the last commit
1import {
2 resolvePullRequestAuthorFilter,
3 type PullRequestCapabilities,
4 type PullRequestListState,
5 type PullRequestViewerPermissions,
6} from "@t3tools/contracts";
7import {
8 PullRequestProviderError,
9 tailLogLines,
10 type ProviderChangeRequestDetail,
11 type ProviderCheckLog,
12 type ProviderCheckRerun,
13 type ProviderRepositoryRef,
14 type PullRequestProviderApi,
15} from "@t3tools/source-control-core/server/PullRequestProvider";
16import * as Cache from "effect/Cache";
17import * as Duration from "effect/Duration";
18import * as Effect from "effect/Effect";
19import * as Exit from "effect/Exit";
20import * as Schema from "effect/Schema";
21
22import { definition } from "../shared/definition.ts";
23import * as TanStackSourceApi from "./TanStackSourceApi.ts";
24import * as Events from "./tanStackSourceEvents.ts";
25import * as Hosts from "./tanStackSourceHosts.ts";
26import * as Json from "./tanStackSourceJson.ts";
27import * as Listing from "./tanStackSourceListing.ts";
28
29const KIND = definition.kind;
30
31const CAPABILITIES: PullRequestCapabilities = {
32 diff: true,
33 comment: true,
34 actions: [...definition.changeRequestActions],
35 mergeMethods: ["merge", "squash"],
36 updateMethods: ["merge", "rebase"],
37 search: true,
38 stacks: true,
39 // A merge lands every layer below it on its own; there is no separate stack action.
40 stackActions: false,
41 reactions: false,
42 labels: true,
43 review: {
44 inlineComment: true,
45 rangeComment: true,
46 reply: true,
47 resolve: true,
48 verdicts: ["approve", "request-changes", "comment"],
49 },
50 // Source lists no collaborators to pick from; reviewers are requested by username.
51 reviewers: { request: true, listCandidates: false },
52 edit: { changeRequest: true, comment: true },
53};
54
55const PAGE_LIMIT = 5;
56const VIEWER_TTL = Duration.minutes(5);
57/** Runs of a pull request are listed newest first, a page at a time. */
58const CI_RUNS_LIMIT = 30;
59const CI_RUN_PAGES = 3;
60/** Runs at one head whose jobs are read, re-runs included. */
61const MAX_CI_RUNS = 12;
62/** Strips the terminal colour codes CI logs keep. */
63const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/gu;
64
65const LogSteps = Schema.Array(Schema.Struct({ lines: Schema.Int }));
66const decodeLogSteps = Schema.decodeUnknownOption(Schema.fromJsonString(LogSteps));
67
68type PullRef = ProviderRepositoryRef & { readonly number: number };
69
70export const make = Effect.gen(function* () {
71 const api = yield* TanStackSourceApi.TanStackSourceApi;
72 const events = yield* Events.make;
73
74 const failure = (operation: string, detail: string, cause?: unknown) =>
75 new PullRequestProviderError({
76 provider: KIND,
77 operation,
78 reason: "failed",
79 detail,
80 ...(cause === undefined ? {} : { cause }),
81 });
82
83 const repositoryPath = (
84 operation: string,
85 input: ProviderRepositoryRef,
86 ): Effect.Effect<string, PullRequestProviderError> => {
87 const repository = Hosts.tanStackSourceRepositoryPath(input.repository);
88 return Hosts.tanStackSourceHost(input.host) !== null && repository !== null
89 ? Effect.succeed(`/repos/${repository}`)
90 : Effect.fail(
91 failure(
92 operation,
93 `TanStack Source serves owner/name repositories on ${Hosts.TANSTACK_SOURCE_HOSTS.join(" and ")}.`,
94 ),
95 );
96 };
97
98 const toProviderError =
99 (operation: string) => (error: TanStackSourceApi.TanStackSourceApiError) =>
100 new PullRequestProviderError({
101 provider: KIND,
102 operation,
103 reason: error.reason,
104 detail: error.detail,
105 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
106 cause: error,
107 });
108
109 const send = (
110 operation: string,
111 input: Pick<ProviderRepositoryRef, "host">,
112 request: Omit<TanStackSourceApi.TanStackSourceApiRequest, "operation" | "host">,
113 ) =>
114 api
115 .request({ ...request, host: input.host, operation })
116 .pipe(Effect.mapError(toProviderError(operation)));
117
118 const decode =
119 <S extends Schema.Codec<unknown, unknown, never, never>>(operation: string, schema: S) =>
120 (raw: string) =>
121 Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
122 Effect.mapError((cause) =>
123 failure(operation, "TanStack Source returned an unreadable response.", cause),
124 ),
125 );
126
127 const read = <S extends Schema.Codec<unknown, unknown, never, never>>(
128 operation: string,
129 input: Pick<ProviderRepositoryRef, "host">,
130 request: Omit<TanStackSourceApi.TanStackSourceApiRequest, "operation" | "host">,
131 schema: S,
132 ) => send(operation, input, request).pipe(Effect.flatMap(decode(operation, schema)));
133
134 const pullPath = (operation: string, input: PullRef) =>
135 repositoryPath(operation, input).pipe(Effect.map((base) => `${base}/pulls/${input.number}`));
136
137 const readPull = (operation: string, input: PullRef) =>
138 pullPath(operation, input).pipe(
139 Effect.flatMap((path) => read(operation, input, { path }, Json.SourcePullDetail)),
140 );
141
142 const viewers = yield* Cache.makeWith(
143 (host: string) =>
144 read("getViewer", { host }, { path: "/user" }, Json.SourceUser).pipe(
145 Effect.map((user) => user.username),
146 ),
147 {
148 capacity: 4,
149 timeToLive: (exit) => (Exit.isSuccess(exit) ? VIEWER_TTL : Duration.zero),
150 },
151 );
152 const viewerOf = (host: string) => Cache.get(viewers, host.toLowerCase());
153
154 const permissionsOf = (
155 pull: Json.SourcePullDetail,
156 viewer: string | null,
157 ): PullRequestViewerPermissions => {
158 const open = pull.state === "open";
159 const authored = viewer !== null && pull.author?.toLowerCase() === viewer.toLowerCase();
160 return {
161 actions: open
162 ? [
163 pull.draft ? "ready" : "draft",
164 "close",
165 ...(pull.draft ? [] : (["merge"] as const)),
166 "update-branch",
167 pull.autoMerge == null ? "enable-auto-merge" : "disable-auto-merge",
168 ]
169 : pull.state === "closed"
170 ? ["reopen"]
171 : [],
172 comment: pull.locked !== true,
173 resolve: true,
174 // Source refuses an author's approval and request for changes, as GitHub does.
175 verdicts: authored ? ["comment"] : ["approve", "request-changes", "comment"],
176 requestReviewers: open,
177 labels: true,
178 editChangeRequest: true,
179 updateMethods: open ? ["merge", "rebase"] : [],
180 };
181 };
182
183 /**
184 * The Source CI jobs of every run at `headSha`, by job id, so each check links to its run and
185 * log and a re-run's jobs group with the ones they replace. Runs come newest first.
186 */
187 const readCiJobs = Effect.fn("TanStackSourcePullRequestProvider.readCiJobs")(function* (
188 operation: string,
189 input: PullRef,
190 headSha: string,
191 ) {
192 const base = yield* repositoryPath(operation, input);
193 const runs: Array<Json.SourceCiRun> = [];
194 let cursor: string | null = null;
195 for (let page = 0; page < CI_RUN_PAGES; page++) {
196 const query = new URLSearchParams({
197 pull: String(input.number),
198 limit: String(CI_RUNS_LIMIT),
199 });
200 if (cursor !== null) query.set("cursor", cursor);
201 const listed: typeof Json.SourceCiRuns.Type = yield* read(
202 operation,
203 input,
204 { path: `${base}/ci/runs?${query}` },
205 Json.SourceCiRuns,
206 );
207 const atHead = listed.items.filter((run) => run.headSha === headSha);
208 runs.push(...atHead);
209 // Runs of older heads follow the head's own, so a page past them ends the search.
210 if (listed.next === null || (atHead.length === 0 && runs.length > 0)) break;
211 cursor = listed.next;
212 }
213 const details = yield* Effect.forEach(
214 runs.slice(0, MAX_CI_RUNS),
215 (run) =>
216 read(operation, input, { path: `${base}/ci/runs/${run.id}` }, Json.SourceCiRunDetail).pipe(
217 Effect.map((detail) => ({ run, detail })),
218 ),
219 { concurrency: 4 },
220 );
221 const jobs = new Map<string, Json.SourceCiJob>();
222 for (const { run, detail } of details)
223 for (const job of detail.jobs)
224 if (job.jobId !== null)
225 jobs.set(job.jobId, {
226 runId: run.id,
227 workflow: run.workflow,
228 key: job.key,
229 runUrl: run.htmlUrl,
230 });
231 return jobs;
232 });
233
234 const readChecks = Effect.fn("TanStackSourcePullRequestProvider.readChecks")(function* (
235 operation: string,
236 input: PullRef,
237 headSha: string | null,
238 ) {
239 if (headSha === null) return { checks: [], merge: null };
240 const base = yield* repositoryPath(operation, input);
241 const path = yield* pullPath(operation, input);
242 const [runs, jobs, merge] = yield* Effect.all(
243 [
244 read(
245 operation,
246 input,
247 { path: `${base}/check-runs?${new URLSearchParams({ sha: headSha })}` },
248 Json.SourceCheckRuns,
249 ),
250 // Without its run a job still shows; it just links to no log.
251 readCiJobs(operation, input, headSha).pipe(
252 Effect.orElseSucceed(() => new Map<string, Json.SourceCiJob>()),
253 ),
254 read(operation, input, { path: `${path}/checks` }, Json.SourceMergeChecks),
255 ],
256 { concurrency: 3 },
257 );
258 const required = new Set(merge.checks.map((check) => check.name));
259 return { checks: Json.toChecks({ runs, jobs, required }), merge };
260 });
261
262 const toSummary = (pull: Json.SourcePullDetail, input: ProviderRepositoryRef) => ({
263 ...Json.toChangeRequest(pull, input),
264 ...(pull.headSha === null ? {} : { headSha: pull.headSha }),
265 mergedAt: pull.mergedAt === null ? null : Json.iso(pull.mergedAt),
266 mergeability:
267 pull.mergeable === true
268 ? ("mergeable" as const)
269 : pull.mergeable === false
270 ? ("conflicting" as const)
271 : ("unknown" as const),
272 autoMergeEnabled: pull.autoMerge != null,
273 ...(pull.autoMerge?.method === "merge" || pull.autoMerge?.method === "squash"
274 ? { autoMergeMethod: pull.autoMerge.method }
275 : {}),
276 });
277
278 const readStack = Effect.fn("TanStackSourcePullRequestProvider.readStack")(function* (
279 operation: string,
280 input: PullRef,
281 ) {
282 const path = yield* pullPath(operation, input);
283 return yield* read(operation, input, { path: `${path}/stack` }, Json.SourceStack);
284 });
285
286 const listState = (state: PullRequestListState) =>
287 // Source lists open or closed rows; closed ones include the merged.
288 state === "all"
289 ? (["open", "closed"] as const)
290 : state === "open"
291 ? (["open"] as const)
292 : (["closed"] as const);
293
294 const merge = Effect.fn("TanStackSourcePullRequestProvider.merge")(function* (
295 input: Parameters<PullRequestProviderApi["runAction"]>[0],
296 ) {
297 const pull = yield* readPull("merge", input);
298 if (pull.state === "merged") return;
299 const sha = input.expectedHeadSha ?? pull.headSha;
300 if (sha === null)
301 return yield* failure(
302 "merge",
303 "TanStack Source has not reported the pull request's head yet.",
304 );
305 const path = yield* pullPath("merge", input);
306 yield* send("merge", input, {
307 method: "PUT",
308 path: `${path}/merge`,
309 body: { merge_method: input.mergeMethod === "squash" ? "squash" : "merge", sha },
310 });
311 });
312
313 const provider: PullRequestProviderApi = {
314 kind: KIND,
315 capabilities: CAPABILITIES,
316 unavailableRequirement: {
317 missing:
318 "Install the src CLI and run `src auth login --web`, save a TanStack Source token in Settings, or set SRC_TOKEN on the server.",
319 unauthenticated:
320 "TanStack Source refused the server's credential. Run `src auth login --web` again, or replace the token saved in Settings.",
321 },
322 readsPublicHostWithoutCheckout: true,
323 servesHost: (host) => Hosts.tanStackSourceHost(host) !== null,
324 getViewer: (input) => viewerOf(input.host ?? definition.publicHost ?? ""),
325
326 listChangeRequests: Effect.fn("TanStackSourcePullRequestProvider.listChangeRequests")(
327 function* (input) {
328 const base = yield* repositoryPath("listChangeRequests", input);
329 const filters = new URLSearchParams();
330 if (input.query?.trim()) filters.set("query", input.query.trim());
331 if (input.involvement === "authored") filters.set("author", "@me");
332 if (input.involvement === "reviewing") filters.set("reviewRequested", "@me");
333 if (input.filters?.author !== undefined && input.involvement !== "authored")
334 filters.set("author", resolvePullRequestAuthorFilter(input.filters.author, input.viewer));
335 const label = input.filters?.labels?.[0];
336 if (label?.length === 1) filters.set("label", label[0]!);
337 if (input.filters?.draft !== undefined)
338 filters.set("draft", input.filters.draft === "only" ? "true" : "false");
339 const limit = Math.max(1, input.limit);
340 const readListing = (cursor: string | undefined) =>
341 Listing.readMerged({
342 states: listState(input.state),
343 cursor,
344 limit,
345 maxPages: PAGE_LIMIT,
346 readPage: (state, page) => {
347 const query = new URLSearchParams(filters);
348 query.set("state", state);
349 if (page !== null) query.set("cursor", page);
350 return read(
351 "listChangeRequests",
352 input,
353 { path: `${base}/pulls?${query}` },
354 Json.SourcePulls,
355 );
356 },
357 keep: (pull) => input.state !== "merged" || pull.state === "merged",
358 });
359 // The service ends a listing at a page without rows, so a page a filter emptied reads on.
360 let listing = yield* readListing(input.cursor?.resumeAfter);
361 for (let scans = 1; listing.items.length === 0 && listing.next !== null; scans++) {
362 if (scans >= PAGE_LIMIT) break;
363 listing = yield* readListing(listing.next);
364 }
365 // List rows name no base, which the list shows, so each delivered row is read in full.
366 const details = yield* Effect.forEach(
367 listing.items,
368 (pull) => readPull("listChangeRequests", { ...input, number: pull.number }),
369 { concurrency: 8 },
370 );
371 return {
372 ...(listing.next === null ? {} : { resumeAfter: listing.next }),
373 items: details.map((pull) => toSummary(pull, input)),
374 truncated: listing.next !== null,
375 continues: listing.next !== null,
376 };
377 },
378 ),
379
380 getChangeRequestSummary: Effect.fn("TanStackSourcePullRequestProvider.getChangeRequestSummary")(
381 function* (input) {
382 const pull = yield* readPull("getChangeRequestSummary", input);
383 const { checks } = yield* readChecks("getChangeRequestSummary", input, pull.headSha).pipe(
384 Effect.orElseSucceed(() => ({ checks: [] })),
385 );
386 const { additions: _additions, deletions: _deletions, ...summary } = toSummary(pull, input);
387 const checksState = Json.checksStateOf(checks);
388 return {
389 ...summary,
390 ...(pull.changedFiles === null ? {} : { changedFiles: pull.changedFiles }),
391 ...(checksState === null ? {} : { checksState }),
392 };
393 },
394 ),
395
396 getChangeRequest: Effect.fn("TanStackSourcePullRequestProvider.getChangeRequest")(
397 function* (input) {
398 const operation = "getChangeRequest";
399 const pull = yield* readPull(operation, input);
400 const path = yield* pullPath(operation, input);
401 const [{ checks, merge: mergeChecks }, files, viewer, stack] = yield* Effect.all(
402 [
403 readChecks(operation, input, pull.headSha),
404 read(operation, input, { path: `${path}/files` }, Json.SourceFiles).pipe(
405 Effect.orElseSucceed(() => null),
406 ),
407 viewerOf(input.host).pipe(Effect.orElseSucceed(() => null)),
408 readStack(operation, input).pipe(Effect.orElseSucceed(() => null)),
409 ],
410 { concurrency: 4 },
411 );
412 const counted = files?.files ?? null;
413 const permissions = permissionsOf(pull, viewer);
414 const mayMerge = mergeChecks?.mayMerge !== false;
415 const checksState = Json.checksStateOf(checks);
416 const index = stack?.members.findIndex((member) => member.number === pull.number) ?? -1;
417 const detail: ProviderChangeRequestDetail = {
418 ...toSummary(pull, input),
419 ...(stack !== null && stack.members.length > 1 && index >= 0
420 ? {
421 stack: {
422 number: stack.members[0]!.number,
423 position: index + 1,
424 size: stack.members.length,
425 base: stack.members[0]!.baseRef,
426 },
427 }
428 : {}),
429 baseBranch: pull.base,
430 headRepositoryNameWithOwner: pull.headRepo,
431 reviewRequestLogins: pull.reviewRequests ?? [],
432 body: pull.body ?? "",
433 additions: counted?.reduce((total, file) => total + (file.additions ?? 0), 0) ?? 0,
434 deletions: counted?.reduce((total, file) => total + (file.deletions ?? 0), 0) ?? 0,
435 changedFiles: pull.changedFiles ?? counted?.length ?? 0,
436 mergedAt: pull.mergedAt === null ? null : Json.iso(pull.mergedAt),
437 mergeCommitSha: pull.mergeCommitSha,
438 mergedBy: Json.toActor(pull.mergedBy, input.host),
439 closedAt: null,
440 reviewers: [],
441 checks,
442 ...(checksState === null ? {} : { checksState }),
443 mergeCapabilities: { merge: mayMerge, squash: mayMerge, rebase: false },
444 baseComparison:
445 mergeChecks?.upToDate === true
446 ? "up-to-date"
447 : mergeChecks?.upToDate === false
448 ? "behind"
449 : "unknown",
450 viewerPermissions: mayMerge
451 ? permissions
452 : {
453 ...permissions,
454 actions: permissions.actions.filter((action) => action !== "merge"),
455 },
456 };
457 return detail;
458 },
459 ),
460
461 getChangeRequestChecks: Effect.fn("TanStackSourcePullRequestProvider.getChangeRequestChecks")(
462 function* (input) {
463 const pull = yield* readPull("getChangeRequestChecks", input);
464 const { checks } = yield* readChecks("getChangeRequestChecks", input, pull.headSha);
465 return { checks, state: pull.state };
466 },
467 ),
468
469 changeRequestEvents: (input) => events(input),
470
471 getChangeRequestStack: Effect.fn("TanStackSourcePullRequestProvider.getChangeRequestStack")(
472 function* (input) {
473 const stack = yield* readStack("getChangeRequestStack", input);
474 if (stack.members.length < 2) return null;
475 // The stack names no states; a merged layer leaves it, so the rest are open.
476 return Json.toStack(stack, input, new Map());
477 },
478 ),
479
480 getChangeRequestActivity: Effect.fn(
481 "TanStackSourcePullRequestProvider.getChangeRequestActivity",
482 )(function* (input) {
483 const operation = "getChangeRequestActivity";
484 const base = yield* repositoryPath(operation, input);
485 const path = yield* pullPath(operation, input);
486 const [timeline, threads, commits] = yield* Effect.all(
487 [
488 read(operation, input, { path: `${base}/issues/${input.number}` }, Json.SourceTimeline),
489 read(operation, input, { path: `${path}/comments` }, Json.SourceThreads),
490 read(operation, input, { path: `${path}/commits` }, Json.SourceCommits).pipe(
491 Effect.orElseSucceed(() => ({
492 baseSha: null,
493 headSha: null,
494 mergeBaseSha: null,
495 available: false,
496 commitsTruncated: null,
497 commits: null,
498 })),
499 ),
500 ],
501 { concurrency: 3 },
502 );
503 return Json.toActivity({
504 timeline,
505 threads,
506 commits,
507 host: input.host,
508 repository: input.repository,
509 number: input.number,
510 });
511 }),
512
513 getViewerPermissions: Effect.fn("TanStackSourcePullRequestProvider.getViewerPermissions")(
514 function* (input) {
515 const [pull, viewer] = yield* Effect.all(
516 [readPull("getViewerPermissions", input), viewerOf(input.host)],
517 { concurrency: 2 },
518 );
519 return permissionsOf(pull, viewer);
520 },
521 ),
522
523 getDiff: Effect.fn("TanStackSourcePullRequestProvider.getDiff")(function* (input) {
524 if (input.commit !== undefined)
525 return yield* failure("getDiff", "TanStack Source cannot show one commit's diff here yet.");
526 const path = yield* pullPath("getDiff", input);
527 const [diff, files] = yield* Effect.all(
528 [
529 read("getDiff", input, { path: `${path}/diff` }, Json.SourceDiff),
530 read("getDiff", input, { path: `${path}/files` }, Json.SourceFiles).pipe(
531 Effect.orElseSucceed(() => null),
532 ),
533 ],
534 { concurrency: 2 },
535 );
536 if (!diff.available || diff.patch === null)
537 return yield* failure(
538 "getDiff",
539 "TanStack Source has no diff for this pull request right now.",
540 );
541 const sections = Json.patchSections(diff.patch);
542 // Files the cut-off patch leaves out still show, as counts.
543 const omittedFileStats = (files?.files ?? [])
544 .filter((file) => !sections.has(file.path))
545 .map((file) => ({
546 path: file.path,
547 additions: file.additions ?? 0,
548 deletions: file.deletions ?? 0,
549 }));
550 if (input.path !== undefined) {
551 const section = sections.get(input.path);
552 return {
553 patch: section ?? "",
554 truncated: section === undefined && diff.truncated === true,
555 nextCursor: null,
556 };
557 }
558 return {
559 patch: diff.patch,
560 truncated: diff.truncated === true || omittedFileStats.length > 0,
561 nextCursor: null,
562 ...(omittedFileStats.length === 0 ? {} : { omittedFileStats }),
563 };
564 }),
565
566 getDiffFilePaths: Effect.fn("TanStackSourcePullRequestProvider.getDiffFilePaths")(
567 function* (input) {
568 if (input.commit !== undefined)
569 return yield* failure(
570 "getDiffFilePaths",
571 "TanStack Source cannot list one commit's files here yet.",
572 );
573 const path = yield* pullPath("getDiffFilePaths", input);
574 const files = yield* read(
575 "getDiffFilePaths",
576 input,
577 { path: `${path}/files` },
578 Json.SourceFiles,
579 );
580 return {
581 files: (files.files ?? []).map((file) => ({
582 oldPath: file.oldPath ?? file.path,
583 newPath: file.path,
584 })),
585 nextCursor: null,
586 };
587 },
588 ),
589
590 getFileStats: Effect.fn("TanStackSourcePullRequestProvider.getFileStats")(function* (input) {
591 const path = yield* pullPath("getFileStats", input);
592 const files = yield* read("getFileStats", input, { path: `${path}/files` }, Json.SourceFiles);
593 return {
594 files: (files.files ?? []).map((file) => ({
595 path: file.path,
596 additions: file.additions ?? 0,
597 deletions: file.deletions ?? 0,
598 })),
599 truncated: files.truncated === true,
600 };
601 }),
602
603 getDiffFileContents: Effect.fn("TanStackSourcePullRequestProvider.getDiffFileContents")(
604 function* (input) {
605 const operation = "getDiffFileContents";
606 if (input.commit !== undefined)
607 return yield* failure(
608 operation,
609 "TanStack Source cannot read one commit's files here yet.",
610 );
611 const path = yield* pullPath(operation, input);
612 const [pull, files] = yield* Effect.all(
613 [
614 readPull(operation, input),
615 read(operation, input, { path: `${path}/files` }, Json.SourceFiles),
616 ],
617 { concurrency: 2 },
618 );
619 const oldRevision = files.mergeBaseSha;
620 const newRevision = files.headSha;
621 if (oldRevision === null || newRevision === null)
622 return yield* failure(operation, "TanStack Source has not reported the diff's commits.");
623 const readFile = (repository: string, revision: string, filePath: string) =>
624 repositoryPath(operation, { ...input, repository }).pipe(
625 Effect.flatMap((base) =>
626 read(
627 operation,
628 input,
629 {
630 path: `${base}/contents/${filePath.split("/").map(encodeURIComponent).join("/")}?${new URLSearchParams({ ref: revision })}`,
631 },
632 Json.SourceContents,
633 ),
634 ),
635 Effect.flatMap((file) =>
636 file.binary || file.truncated || file.content === null
637 ? Effect.fail(failure(operation, `${filePath} is too large or binary to show.`))
638 : Effect.succeed(file.content),
639 ),
640 );
641 const [oldContents, newContents] = yield* Effect.all(
642 [
643 input.changeType === "new"
644 ? Effect.succeed("")
645 : readFile(input.repository, oldRevision, input.oldPath),
646 input.changeType === "deleted"
647 ? Effect.succeed("")
648 : readFile(pull.headRepo ?? input.repository, newRevision, input.newPath),
649 ],
650 { concurrency: 2 },
651 );
652 return { oldContents, newContents };
653 },
654 ),
655
656 getCheckLogs: Effect.fn("TanStackSourcePullRequestProvider.getCheckLogs")(function* (input) {
657 const base = yield* repositoryPath("getCheckLogs", input);
658 return yield* Effect.forEach(
659 input.checks,
660 (check): Effect.Effect<ProviderCheckLog, PullRequestProviderError> => {
661 const job = Json.parseCiJobUrl(check.url, input.host);
662 if (job === null)
663 return Effect.succeed({
664 ...check,
665 log: null,
666 truncated: false,
667 detail:
668 "This check did not run on TanStack Source CI, which holds no log for it. Open its url.",
669 });
670 const logs = `${base}/ci/runs/${encodeURIComponent(job.runId)}/jobs/${encodeURIComponent(job.job)}/logs`;
671 return Effect.gen(function* () {
672 // The first line's answer names every step's line count, so the tail is one more read.
673 const head = yield* api
674 .response({
675 host: input.host,
676 operation: "getCheckLogs",
677 path: `${logs}?from=1&to=1`,
678 accept: "text/plain",
679 })
680 .pipe(Effect.mapError(toProviderError("getCheckLogs")));
681 const steps = decodeLogSteps(head.headers["x-log-steps"] ?? "");
682 const total =
683 steps._tag === "Some" ? steps.value.reduce((sum, step) => sum + step.lines, 0) : 0;
684 const from = Math.max(1, total - input.tailLines + 1);
685 const text =
686 total <= 1
687 ? head.text
688 : yield* send("getCheckLogs", input, {
689 path: `${logs}?from=${from}&to=${total}`,
690 accept: "text/plain",
691 });
692 const tail = tailLogLines(text.replace(ANSI, ""), input.tailLines);
693 return { ...check, log: tail.log, truncated: tail.truncated || from > 1, detail: null };
694 }).pipe(
695 // Sign-in and rate-limit failures fail the call; the rest are this check's.
696 Effect.catchIf(
697 (error) => error.reason !== "unauthenticated" && error.reason !== "rate-limited",
698 (error) =>
699 Effect.succeed({ ...check, log: null, truncated: false, detail: error.detail }),
700 ),
701 );
702 },
703 { concurrency: 4 },
704 );
705 }),
706
707 rerunChecks: Effect.fn("TanStackSourcePullRequestProvider.rerunChecks")(function* (input) {
708 const base = yield* repositoryPath("rerunChecks", input);
709 const located = input.checks.map((check) => ({
710 check,
711 runId: Json.parseCiJobUrl(check.url, input.host)?.runId ?? null,
712 }));
713 const runIds = new Set(located.flatMap(({ runId }) => (runId === null ? [] : [runId])));
714 const outcomes = new Map<string, string | null>();
715 yield* Effect.forEach(
716 runIds,
717 (runId) =>
718 send("rerunChecks", input, {
719 method: "POST",
720 path: `${base}/ci/runs/${encodeURIComponent(runId)}/rerun`,
721 body: { failedOnly: true },
722 }).pipe(
723 Effect.as<string | null>(null),
724 Effect.catchIf(
725 (error) => error.reason !== "unauthenticated" && error.reason !== "rate-limited",
726 (error) => Effect.succeed(error.detail),
727 ),
728 Effect.map((detail) => outcomes.set(runId, detail)),
729 ),
730 { concurrency: 2, discard: true },
731 );
732 return located.map(({ check, runId }): ProviderCheckRerun => {
733 if (runId === null)
734 return {
735 name: check.name,
736 rerun: false,
737 detail: "This check did not run on TanStack Source CI, so it cannot be re-run here.",
738 };
739 const detail = outcomes.get(runId) ?? null;
740 return { name: check.name, rerun: detail === null, detail };
741 });
742 }),
743
744 runAction: Effect.fn("TanStackSourcePullRequestProvider.runAction")(function* (input) {
745 const path = yield* pullPath(input.action, input);
746 switch (input.action) {
747 case "merge":
748 return yield* merge(input);
749 case "ready":
750 case "draft":
751 yield* send(input.action, input, {
752 method: input.action === "ready" ? "PUT" : "DELETE",
753 path: `${path}/ready`,
754 });
755 return;
756 case "close":
757 case "reopen":
758 yield* send(input.action, input, {
759 method: "PATCH",
760 path,
761 body: { state: input.action === "close" ? "closed" : "open" },
762 });
763 return;
764 case "update-branch": {
765 const pull = yield* readPull(input.action, input);
766 yield* send(input.action, input, {
767 method: "POST",
768 path: `${path}/update-branch`,
769 body: {
770 rebase: input.updateMethod === "rebase",
771 ...(pull.headSha === null ? {} : { sha: input.expectedHeadSha ?? pull.headSha }),
772 },
773 });
774 return;
775 }
776 case "enable-auto-merge":
777 yield* send(input.action, input, {
778 method: "PUT",
779 path: `${path}/auto-merge`,
780 body: { merge_method: input.mergeMethod === "squash" ? "squash" : "merge" },
781 });
782 return;
783 case "disable-auto-merge":
784 yield* send(input.action, input, { method: "DELETE", path: `${path}/auto-merge` });
785 return;
786 default:
787 return yield* failure(
788 input.action,
789 `TanStack Source cannot ${input.action} from T3 Code.`,
790 );
791 }
792 }),
793
794 updateChangeRequest: Effect.fn("TanStackSourcePullRequestProvider.updateChangeRequest")(
795 function* (input) {
796 const path = yield* pullPath("updateChangeRequest", input);
797 yield* send("updateChangeRequest", input, {
798 method: "PATCH",
799 path,
800 body: {
801 ...(input.title === undefined ? {} : { title: input.title }),
802 ...(input.body === undefined ? {} : { body: input.body }),
803 },
804 });
805 },
806 ),
807
808 comment: Effect.fn("TanStackSourcePullRequestProvider.comment")(function* (input) {
809 const base = yield* repositoryPath("comment", input);
810 yield* send("comment", input, {
811 method: "POST",
812 path: `${base}/issues/${input.number}/comments`,
813 body: { body: input.body },
814 });
815 }),
816
817 updateComment: Effect.fn("TanStackSourcePullRequestProvider.updateComment")(function* (input) {
818 if (!/^\d+$/u.test(input.commentId))
819 return yield* failure("updateComment", "TanStack Source comment ids are numbers.");
820 const base = yield* repositoryPath("updateComment", input);
821 yield* send("updateComment", input, {
822 method: "PATCH",
823 path: `${base}/issues/comments/${input.commentId}`,
824 body: { body: input.body },
825 });
826 }),
827
828 submitReview: Effect.fn("TanStackSourcePullRequestProvider.submitReview")(function* (input) {
829 const pull = yield* readPull("submitReview", input);
830 if (input.comments.length > 0 && pull.headSha === null)
831 return yield* failure(
832 "submitReview",
833 "TanStack Source has not reported the pull request's head, which line comments pin to.",
834 );
835 const path = yield* pullPath("submitReview", input);
836 yield* send("submitReview", input, {
837 method: "POST",
838 path: `${path}/reviews`,
839 body: {
840 verdict:
841 input.verdict === "approve"
842 ? "approved"
843 : input.verdict === "request-changes"
844 ? "changes_requested"
845 : "commented",
846 ...(input.body.length === 0 ? {} : { body: input.body }),
847 ...(input.comments.length === 0
848 ? {}
849 : {
850 comments: input.comments.map((comment) =>
851 Json.toReviewComment(comment, pull.headSha!),
852 ),
853 }),
854 },
855 });
856 }),
857
858 listReviewerCandidates: () => Effect.succeed({ candidates: [], truncated: false }),
859
860 setReviewerRequest: Effect.fn("TanStackSourcePullRequestProvider.setReviewerRequest")(
861 function* (input) {
862 const path = yield* pullPath("setReviewerRequest", input);
863 const usernames = input.reviewers.map((reviewer) => reviewer.id);
864 yield* send("setReviewerRequest", input, {
865 method: "POST",
866 path: `${path}/reviewers`,
867 body: input.requested ? { add: usernames } : { remove: usernames },
868 });
869 },
870 ),
871
872 listLabelCandidates: Effect.fn("TanStackSourcePullRequestProvider.listLabelCandidates")(
873 function* (input) {
874 const base = yield* repositoryPath("listLabelCandidates", input);
875 const [labels, pull] = yield* Effect.all(
876 [
877 read("listLabelCandidates", input, { path: `${base}/labels` }, Json.SourceLabels),
878 readPull("listLabelCandidates", input),
879 ],
880 { concurrency: 2 },
881 );
882 const applied = new Set(pull.labels ?? []);
883 return {
884 candidates: labels.map((label) => ({
885 name: label.name,
886 color: label.color,
887 description: label.description ?? null,
888 isApplied: applied.has(label.name),
889 })),
890 truncated: false,
891 };
892 },
893 ),
894
895 listRepositoryLabels: Effect.fn("TanStackSourcePullRequestProvider.listRepositoryLabels")(
896 function* (input) {
897 const base = yield* repositoryPath("listRepositoryLabels", input);
898 const labels = yield* read(
899 "listRepositoryLabels",
900 input,
901 { path: `${base}/labels` },
902 Json.SourceLabels,
903 );
904 return {
905 items: labels.map((label) => ({ name: label.name, color: label.color })),
906 truncated: false,
907 };
908 },
909 ),
910
911 setLabels: Effect.fn("TanStackSourcePullRequestProvider.setLabels")(function* (input) {
912 const base = yield* repositoryPath("setLabels", input);
913 const path = `${base}/issues/${input.number}/labels`;
914 if (input.applied) {
915 yield* send("setLabels", input, { method: "POST", path, body: { labels: input.labels } });
916 return;
917 }
918 yield* Effect.forEach(
919 input.labels,
920 (label) =>
921 send("setLabels", input, {
922 method: "DELETE",
923 path: `${path}/${encodeURIComponent(label)}`,
924 }),
925 { concurrency: 2, discard: true },
926 );
927 }),
928
929 replyToThread: Effect.fn("TanStackSourcePullRequestProvider.replyToThread")(function* (input) {
930 if (!/^\d+$/u.test(input.threadId))
931 return yield* failure("replyToThread", "TanStack Source thread ids are numbers.");
932 const path = yield* pullPath("replyToThread", input);
933 yield* send("replyToThread", input, {
934 method: "POST",
935 path: `${path}/comments`,
936 body: { replyTo: Number(input.threadId), body: input.body },
937 });
938 }),
939
940 setReaction: () =>
941 Effect.fail(failure("setReaction", "TanStack Source reactions are not supported here yet.")),
942
943 setThreadResolution: Effect.fn("TanStackSourcePullRequestProvider.setThreadResolution")(
944 function* (input) {
945 if (!/^\d+$/u.test(input.threadId))
946 return yield* failure("setThreadResolution", "TanStack Source thread ids are numbers.");
947 const path = yield* pullPath("setThreadResolution", input);
948 yield* send("setThreadResolution", input, {
949 method: "PUT",
950 path: `${path}/threads/${input.threadId}`,
951 body: { resolved: input.resolved },
952 });
953 },
954 ),
955 };
956 return provider;
957});