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

main
ts 412 lines 14 KB
Raw
1 import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3tools/contracts";
2 import * as Effect from "effect/Effect";
3 import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
4
5 import * as BitbucketApi from "./BitbucketApi.ts";
6 import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
7 import {
8 PullRequestProviderError,
9 type PullRequestProviderFailure,
10 type ProviderChangeRequest,
11 type ProviderChangeRequestActivity,
12 type ProviderChangeRequestDetail,
13 type ProviderChangeRequestSummary,
14 type PullRequestProviderApi,
15 } from "@t3tools/source-control-core/server/PullRequestProvider";
16 import type { BitbucketPullRequest } from "./bitbucketPullRequestJson.ts";
17 import { definition } from "../shared/definition.ts";
18
19 const CAPABILITIES: PullRequestCapabilities = {
20 diff: true,
21 comment: true,
22 actions: [...definition.changeRequestActions],
23 mergeMethods: ["merge", "squash", "rebase"],
24 search: true,
25 reactions: false,
26 mentions: false,
27 referenceSigils: [],
28 review: {
29 inlineComment: true,
30 reply: true,
31 resolve: true,
32 verdicts: ["comment", "approve", "request-changes"],
33 },
34 reviewers: { request: true, listCandidates: true, searchCandidates: false },
35 edit: { changeRequest: true, comment: true },
36 // Bitbucket PR properties are shared, not per-reader viewed marks.
37 viewedFiles: "environment",
38 };
39
40 const UNAVAILABLE_REQUIREMENT = {
41 missing:
42 "Bitbucket needs API credentials on the server. Add them in Settings → Source control & issues.",
43 unauthenticated:
44 "Bitbucket rejected the configured credentials. Check them in Settings → Source control & issues.",
45 };
46
47 /**
48 * Bitbucket lets the author of a pull request decline their own with no more than read access,
49 * and the permission response says nothing about who opened this one — so withholding the
50 * control from the one person entitled to it is the worse of the two mistakes.
51 */
52 export function bitbucketViewerPermissions(input: {
53 readonly canWrite: boolean;
54 }): PullRequestViewerPermissions {
55 return {
56 actions: CAPABILITIES.actions.filter((action) => action !== "merge" || input.canWrite),
57 comment: true,
58 resolve: true,
59 verdicts: CAPABILITIES.review.verdicts,
60 requestReviewers: true,
61 };
62 }
63
64 export function bitbucketProviderFailure(
65 error: BitbucketPullRequestApi.BitbucketPullRequestApiError,
66 ): PullRequestProviderFailure {
67 if (
68 (error._tag === "BitbucketResponseError" && error.status === 401) ||
69 error._tag === "SettingsSecretUnresolvedError"
70 ) {
71 return { reason: "unauthenticated" };
72 }
73 if (error._tag === "SourceControlRateLimitPausedError") {
74 return { reason: "rate-limited", retryAt: error.retryAt };
75 }
76 if (
77 (error._tag === "BitbucketResponseError" || error._tag === "BitbucketResponseBodyReadError") &&
78 error.status === 429
79 ) {
80 return {
81 reason: "rate-limited",
82 ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
83 };
84 }
85 if (
86 (error._tag === "BitbucketResponseError" || error._tag === "BitbucketResponseBodyReadError") &&
87 error.status === 404
88 ) {
89 return { reason: "not-found" };
90 }
91 return { reason: "failed" };
92 }
93
94 function toChangeRequest(pullRequest: BitbucketPullRequest): ProviderChangeRequest {
95 return {
96 number: pullRequest.number,
97 title: pullRequest.title,
98 url: pullRequest.url,
99 author: pullRequest.author,
100 headBranch: pullRequest.headBranch,
101 ...(pullRequest.headSha ? { headSha: pullRequest.headSha } : {}),
102 ...(pullRequest.headRepositoryNameWithOwner
103 ? { headRepositoryNameWithOwner: pullRequest.headRepositoryNameWithOwner }
104 : {}),
105 baseBranch: pullRequest.baseBranch,
106 state: pullRequest.state,
107 isDraft: pullRequest.isDraft,
108 mergeability: pullRequest.mergeability,
109 additions: 0,
110 deletions: 0,
111 createdAt: pullRequest.createdAt,
112 updatedAt: pullRequest.updatedAt,
113 reviewRequestLogins: pullRequest.reviewRequestLogins,
114 labels: [],
115 };
116 }
117
118 /** The write's reply has no `closed_on`, line counts, or conflict state, so those stay absent. */
119 function toActionSummary(pullRequest: BitbucketPullRequest): ProviderChangeRequestSummary {
120 return {
121 number: pullRequest.number,
122 title: pullRequest.title,
123 url: pullRequest.url,
124 author: pullRequest.author,
125 headBranch: pullRequest.headBranch,
126 baseBranch: pullRequest.baseBranch,
127 state: pullRequest.state,
128 isDraft: pullRequest.isDraft,
129 updatedAt: pullRequest.updatedAt,
130 ...(pullRequest.headSha ? { headSha: pullRequest.headSha } : {}),
131 };
132 }
133
134 export const make = Effect.gen(function* () {
135 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
136 const servesHost = yield* BitbucketApi.BitbucketServesHost.pipe(Effect.orDie);
137
138 const fail =
139 (operation: string) => (error: BitbucketPullRequestApi.BitbucketPullRequestApiError) =>
140 new PullRequestProviderError({
141 provider: SourceControlProviderKind.make("bitbucket"),
142 operation,
143 ...bitbucketProviderFailure(error),
144 detail: error._tag === "SettingsSecretUnresolvedError" ? error.message : error.detail,
145 cause: error,
146 });
147
148 const recoverRead = <A>(
149 read: Effect.Effect<A, BitbucketPullRequestApi.BitbucketPullRequestApiError>,
150 fallback: A,
151 ) => {
152 const recover = () => Effect.succeed(fallback);
153 return Effect.catchTags(read, {
154 BitbucketResponseError: (error) => (error.status === 429 ? Effect.fail(error) : recover()),
155 BitbucketUntrustedUrlError: recover,
156 BitbucketRepositoryLocatorError: recover,
157 BitbucketRequestError: recover,
158 BitbucketResponseBodyReadError: (error) =>
159 error.status === 429 ? Effect.fail(error) : recover(),
160 BitbucketResponseDecodeError: recover,
161 BitbucketRepositoryVcsResolveError: recover,
162 BitbucketRepositoryRemotesListError: recover,
163 BitbucketRepositoryRemoteNotFoundError: recover,
164 BitbucketPullRequestBodyReadError: recover,
165 BitbucketCheckoutError: recover,
166 BitbucketPullRequestReadError: recover,
167 BitbucketViewerUnavailableError: recover,
168 BitbucketRepositoryUnsupportedError: recover,
169 BitbucketDiffCommitError: recover,
170 });
171 };
172
173 const provider: PullRequestProviderApi = {
174 kind: SourceControlProviderKind.make("bitbucket"),
175 capabilities: CAPABILITIES,
176 servesHost,
177 unavailableRequirement: UNAVAILABLE_REQUIREMENT,
178 readsPublicHostWithoutCheckout: true,
179
180 getViewer: () => api.getViewer().pipe(Effect.mapError(fail("getViewer"))),
181
182 listChangeRequests: (input) =>
183 api
184 .listPullRequests({
185 repository: input.repository,
186 state: input.state,
187 limit: input.limit,
188 query: input.query,
189 cursor: input.cursor,
190 author:
191 input.filters?.author === undefined
192 ? undefined
193 : resolvePullRequestAuthorFilter(input.filters.author, input.viewer),
194 draft: input.filters?.draft === undefined ? undefined : input.filters.draft === "only",
195 })
196 .pipe(
197 Effect.mapError(fail("listChangeRequests")),
198 Effect.map((batch) => ({
199 items: batch.items.map(toChangeRequest),
200 truncated: batch.truncated,
201 continues: true,
202 })),
203 ),
204
205 getChangeRequestChecks: (input) =>
206 Effect.all([api.getPullRequest(input), api.listChecks(input)], { concurrency: 2 }).pipe(
207 Effect.map(([pullRequest, checks]) => ({ state: pullRequest.state, checks })),
208 Effect.mapError(fail("getChangeRequestChecks")),
209 ),
210
211 getChangeRequestPreview: (input) =>
212 api.getPullRequest({ repository: input.repository, number: input.number }).pipe(
213 Effect.mapError(fail("getChangeRequestPreview")),
214 Effect.map((pullRequest) => ({
215 number: pullRequest.number,
216 title: pullRequest.title,
217 url: pullRequest.url,
218 author: pullRequest.author,
219 state: pullRequest.state,
220 isDraft: pullRequest.isDraft,
221 createdAt: pullRequest.createdAt,
222 })),
223 ),
224
225 getChangeRequest: (input) => {
226 const target = { repository: input.repository, number: input.number };
227 return Effect.all(
228 [
229 api.getPullRequest(target),
230 api.getDiffStat(target),
231 recoverRead(api.getMergeability(target), "unknown" as const),
232 recoverRead(api.listChecks(target), []),
233 recoverRead(api.getRepositoryPermission(target), true),
234 ],
235 { concurrency: 5 },
236 ).pipe(
237 Effect.mapError(fail("getChangeRequest")),
238 Effect.map(
239 ([
240 pullRequest,
241 diffStat,
242 mergeability,
243 checks,
244 canWrite,
245 ]): ProviderChangeRequestDetail => ({
246 ...toChangeRequest(pullRequest),
247 mergeability,
248 additions: diffStat.additions,
249 deletions: diffStat.deletions,
250 changedFiles: diffStat.changedFiles,
251 body: pullRequest.body,
252 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
253 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
254 reviewers: pullRequest.reviewers,
255 checks,
256 // Bitbucket exposes no strategy permissions; unsupported strategies fail at merge.
257 mergeCapabilities: { merge: true, squash: true, rebase: true },
258 viewerPermissions: bitbucketViewerPermissions({ canWrite }),
259 }),
260 ),
261 );
262 },
263
264 getChangeRequestActivity: (input) => {
265 const target = { repository: input.repository, number: input.number };
266 return Effect.all(
267 [
268 api.getPullRequest(target),
269 recoverRead(api.listComments(target), { comments: [], threads: [], truncated: true }),
270 recoverRead(api.listCommits(target), []),
271 ],
272 { concurrency: 3 },
273 ).pipe(
274 Effect.mapError(fail("getChangeRequestActivity")),
275 Effect.map(([pullRequest, comments, commits]): ProviderChangeRequestActivity => ({
276 comments: [...comments.comments, ...pullRequest.reviews].toSorted((left, right) =>
277 left.createdAt.localeCompare(right.createdAt),
278 ),
279 commentCount: comments.comments.length + pullRequest.reviews.length,
280 commentsTruncated: comments.truncated,
281 reviewThreads: comments.threads,
282 commits,
283 })),
284 );
285 },
286
287 getViewerPermissions: (input) =>
288 api.getRepositoryPermission({ repository: input.repository }).pipe(
289 Effect.mapError(fail("getViewerPermissions")),
290 Effect.map((canWrite) => bitbucketViewerPermissions({ canWrite })),
291 ),
292
293 // `/diff` returns the whole patch without pagination.
294 getDiff: (input) =>
295 api
296 .getPullRequestDiff({
297 repository: input.repository,
298 number: input.number,
299 ...(input.commit === undefined ? {} : { commit: input.commit }),
300 })
301 .pipe(
302 Effect.mapError(fail("getDiff")),
303 Effect.map((diff) => ({ ...diff, nextCursor: null })),
304 ),
305
306 getFileRevisions: (input) =>
307 api
308 .getFileRevisions({
309 repository: input.repository,
310 number: input.number,
311 paths: input.paths,
312 })
313 .pipe(Effect.mapError(fail("getFileRevisions"))),
314
315 // Bitbucket supports user reviewers only.
316 listReviewerCandidates: (input) =>
317 api
318 .listReviewerCandidates({ repository: input.repository, number: input.number })
319 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
320
321 setReviewerRequest: (input) =>
322 api
323 .setReviewerRequest({
324 repository: input.repository,
325 number: input.number,
326 reviewers: input.reviewers,
327 requested: input.requested,
328 })
329 .pipe(Effect.mapError(fail("setReviewerRequest"))),
330
331 runAction: (input) =>
332 api
333 .runAction({
334 repository: input.repository,
335 number: input.number,
336 action: input.action,
337 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
338 })
339 .pipe(
340 Effect.mapError(fail("runAction")),
341 Effect.map((pullRequest) => pullRequest && toActionSummary(pullRequest)),
342 ),
343
344 updateChangeRequest: (input) =>
345 api
346 .updateChangeRequest({
347 repository: input.repository,
348 number: input.number,
349 title: input.title,
350 body: input.body,
351 })
352 .pipe(Effect.mapError(fail("updateChangeRequest"))),
353
354 comment: (input) =>
355 api
356 .comment({ repository: input.repository, number: input.number, body: input.body })
357 .pipe(Effect.mapError(fail("comment"))),
358
359 updateComment: (input) =>
360 api
361 .updateComment({
362 repository: input.repository,
363 number: input.number,
364 commentId: input.commentId,
365 body: input.body,
366 })
367 .pipe(Effect.mapError(fail("updateComment"))),
368
369 submitReview: (input) =>
370 api
371 .submitReview({
372 repository: input.repository,
373 number: input.number,
374 verdict: input.verdict,
375 body: input.body,
376 comments: input.comments,
377 })
378 .pipe(Effect.mapError(fail("submitReview"))),
379
380 replyToThread: (input) =>
381 api
382 .replyToComment({
383 repository: input.repository,
384 number: input.number,
385 commentId: input.threadId,
386 body: input.body,
387 })
388 .pipe(Effect.mapError(fail("replyToThread"))),
389
390 setReaction: () =>
391 Effect.fail(
392 new PullRequestProviderError({
393 provider: SourceControlProviderKind.make("bitbucket"),
394 operation: "setReaction",
395 reason: "failed",
396 detail: "Bitbucket does not support reactions.",
397 }),
398 ),
399
400 setThreadResolution: (input) =>
401 api
402 .setCommentResolution({
403 repository: input.repository,
404 number: input.number,
405 commentId: input.threadId,
406 resolved: input.resolved,
407 })
408 .pipe(Effect.mapError(fail("setThreadResolution"))),
409 };
410
411 return provider;
412 });