@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 521 lines 18.7 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as Result from "effect/Result";
3 import { GraphQLClient, GraphQLClientError, GraphQLGroup } from "effect/graphql";
4 import {
5 IssueTrackerKind,
6 type IssueCapabilities,
7 type IssueActor,
8 type IssueInvolvement,
9 type IssueLabel,
10 type IssueListSort,
11 } from "@t3tools/contracts";
12 import {
13 IssueTrackerError,
14 type IssueInvolvementFilter,
15 type IssueTrackerApi,
16 } from "@t3tools/source-control-core/server/IssueTracker";
17
18 import * as GitHubRest from "./GitHubRest.ts";
19 import { readIssueTemplates } from "./gitHubIssueTemplates.ts";
20 import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
21 import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
22 import { IssuesGraphQLGroup } from "./issues.graphql.ts";
23 import { AddReaction, RemoveReaction } from "./pullRequestMutations.graphql.ts";
24 import { gitHubReactionContent } from "./gitHubPullRequestJson.ts";
25 import {
26 ISSUE_STATES,
27 decodeCreatedIssueJson,
28 decodeIssueMetadataJson,
29 toIssueCandidates,
30 toIssueComments,
31 toIssueDetail,
32 toIssueSearch,
33 } from "./gitHubIssueJson.ts";
34
35 const KIND = IssueTrackerKind.make("github");
36
37 const CAPABILITIES: IssueCapabilities = {
38 create: true,
39 edit: true,
40 comment: true,
41 labels: true,
42 assignees: true,
43 reactions: true,
44 templates: true,
45 linkedPullRequests: true,
46 events: true,
47 search: true,
48 };
49
50 const REPOSITORY = /^[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+$/;
51
52 /** Quoted, so no character in it can start a qualifier of its own. */
53 function quotedTerm(value: string): string {
54 return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
55 }
56
57 function searchTerms(query: string): ReadonlyArray<string> {
58 return query
59 .split(/\s+/)
60 .filter((word) => word.length > 0)
61 .map(quotedTerm);
62 }
63
64 const INVOLVEMENT_QUALIFIER: Record<Exclude<IssueInvolvement, "all">, string> = {
65 assigned: "assignee",
66 authored: "author",
67 mentioned: "mentions",
68 };
69
70 function searchQuery(
71 input: IssueInvolvementFilter & {
72 readonly scope: string;
73 readonly state: "all" | "open" | "closed";
74 readonly query?: string | undefined;
75 readonly labels?: ReadonlyArray<string> | undefined;
76 readonly assignee?: string | undefined;
77 readonly sort: IssueListSort;
78 },
79 ): string {
80 return [
81 "is:issue",
82 `repo:${input.scope.trim()}`,
83 ...(input.state === "all" ? [] : [`is:${input.state}`]),
84 ...(input.involvement === "all"
85 ? []
86 : [`${INVOLVEMENT_QUALIFIER[input.involvement]}:${input.viewer}`]),
87 ...(input.labels ?? []).map((label) => `label:${quotedTerm(label)}`),
88 ...(input.assignee === undefined ? [] : [`assignee:${quotedTerm(input.assignee)}`]),
89 `sort:${input.sort}-desc`,
90 ...searchTerms(input.query ?? ""),
91 ].join(" ");
92 }
93
94 function reasonFor(
95 error: GitHubRequestPolicy.GitHubApiError | GraphQLClientError.GraphQLClientError,
96 ): IssueTrackerError["reason"] {
97 switch (error._tag) {
98 case "GitHubCliMissingError":
99 return "missing-tool";
100 case "GitHubNotSignedInError":
101 case "GitHubHostDisabledError":
102 case "GitHubApiAuthenticationError":
103 return "unauthenticated";
104 case "GitHubApiRateLimitError":
105 case "SourceControlRateLimitPausedError":
106 return "rate-limited";
107 case "GitHubApiNotFoundError":
108 return "not-found";
109 default:
110 return "failed";
111 }
112 }
113
114 const FAILURE_DETAIL: Record<IssueTrackerError["reason"], string> = {
115 "missing-tool": "GitHub CLI is not installed.",
116 unauthenticated: "GitHub authentication is unavailable. Sign in and retry.",
117 "rate-limited": "GitHub API rate limit exceeded.",
118 "not-found": "GitHub could not find the requested issue.",
119 failed: "The GitHub issue request failed.",
120 };
121
122 const group = GraphQLGroup.merge(
123 IssuesGraphQLGroup,
124 GraphQLGroup.make(AddReaction, RemoveReaction),
125 ).middleware(GitHubGraphQlClient.GitHubGraphQlAuth);
126
127 export const make = Effect.gen(function* () {
128 const api = yield* GitHubRest.GitHubRest;
129 const client = yield* GraphQLClient.make(group).pipe(Effect.provide(GitHubGraphQlClient.layer));
130
131 const fail =
132 (operation: string) =>
133 (error: GitHubRequestPolicy.GitHubApiError | GraphQLClientError.GraphQLClientError) =>
134 new IssueTrackerError({
135 tracker: KIND,
136 operation,
137 reason: reasonFor(error),
138 detail: GraphQLClientError.isGraphQLClientError(error)
139 ? `GitHub returned an unreadable ${operation} response.`
140 : FAILURE_DETAIL[reasonFor(error)],
141 ...("retryAt" in error && error.retryAt !== undefined ? { retryAt: error.retryAt } : {}),
142 cause: error,
143 });
144
145 const invalid = (operation: string, detail: string, reason: "failed" | "not-found" = "failed") =>
146 new IssueTrackerError({ tracker: KIND, operation, reason, detail });
147
148 const notFound = (operation: string) =>
149 invalid(operation, "GitHub could not find the requested issue.", "not-found");
150
151 const repository = Effect.fn("GitHubIssueTracker.repository")(function* (
152 scope: string,
153 operation: string,
154 ) {
155 if (!REPOSITORY.test(scope) || scope.endsWith("/.") || scope.endsWith("/..")) {
156 return yield* invalid(operation, "A repository was named that GitHub cannot address.");
157 }
158 const [owner = "", name = ""] = scope.split("/");
159 return { owner, name };
160 });
161
162 const issue = Effect.fn("GitHubIssueTracker.issue")(function* (
163 input: { readonly scope: string; readonly key: string },
164 operation: string,
165 ) {
166 const repo = yield* repository(input.scope, operation);
167 const number = Number(input.key);
168 if (!/^[1-9]\d*$/.test(input.key) || !Number.isSafeInteger(number) || number > 2_147_483_647) {
169 return yield* notFound(operation);
170 }
171 return { ...repo, number, path: `repos/${repo.owner}/${repo.name}/issues/${number}` };
172 });
173
174 const graphql =
175 (host: string, operation: string) =>
176 <A, E extends GitHubRequestPolicy.GitHubApiError | GraphQLClientError.GraphQLClientError, R>(
177 effect: Effect.Effect<A, E, R>,
178 ) =>
179 effect.pipe(GitHubGraphQlClient.call({ host, operation }), Effect.mapError(fail(operation)));
180
181 const verifiedIssue = Effect.fn("GitHubIssueTracker.verifiedIssue")(function* (
182 input: { readonly host: string; readonly scope: string; readonly key: string },
183 operation: string,
184 ) {
185 const target = yield* issue(input, operation);
186 const { owner, name, number } = target;
187 // REST issue endpoints also accept pull requests; resolve an Issue before writing.
188 const result = yield* client
189 .IssueNodeId({ owner, name, number })
190 .pipe(graphql(input.host, operation));
191 const found = result.repository?.issue;
192 if (found == null) return yield* notFound(operation);
193 return { ...target, id: found.id, state: found.state, stateReason: found.stateReason };
194 });
195
196 // As sets: GitHub applies a name asked for twice once.
197 const sameNames = (wanted: ReadonlyArray<string>, applied: ReadonlyArray<string>) => {
198 const names = new Set(wanted.map((name) => name.trim().toLowerCase()));
199 return (
200 names.size === new Set(applied).size && [...names].every((name) => applied.includes(name))
201 );
202 };
203
204 return {
205 kind: KIND,
206 capabilities: CAPABILITIES,
207
208 getViewer: (input) =>
209 client.IssueViewer({}).pipe(
210 graphql(input.host, "getViewer"),
211 Effect.map(({ viewer }) => viewer.login),
212 ),
213
214 listIssues: (input) =>
215 repository(input.scope, "listIssues").pipe(
216 Effect.flatMap(() =>
217 client
218 .IssueSearch({
219 q: searchQuery(input),
220 cursor: input.cursor,
221 rows: Math.min(Math.max(Math.trunc(input.limit), 1), 100),
222 })
223 .pipe(graphql(input.host, "listIssues"), Effect.map(toIssueSearch)),
224 ),
225 ),
226
227 getIssue: Effect.fn("GitHubIssueTracker.getIssue")(function* (input) {
228 const { owner, name, number } = yield* issue(input, "getIssue");
229 const result = yield* client
230 .IssueDetail({ owner, name, number })
231 .pipe(graphql(input.host, "getIssue"));
232 const repository = result.repository;
233 const raw = repository?.issue;
234 if (repository == null || raw == null) return yield* notFound("getIssue");
235 // Editing replaces labels and assignees, and a closing reference can sit past the first
236 // page. Finish their pages before handing the issue to a client.
237 let labels = raw.labels;
238 let assignees = raw.assignees;
239 let closing = raw.closedByPullRequestsReferences;
240 const seen = new Set<string>();
241 const moreLabels: IssueLabel[] = [];
242 const moreAssignees: IssueActor[] = [];
243 const allClosing = [...(closing?.nodes ?? [])];
244 while (
245 labels?.pageInfo.hasNextPage === true ||
246 assignees.pageInfo.hasNextPage ||
247 closing?.pageInfo.hasNextPage === true
248 ) {
249 const labelsCursor = labels?.pageInfo.hasNextPage ? labels.pageInfo.endCursor : null;
250 const assigneesCursor = assignees.pageInfo.hasNextPage
251 ? assignees.pageInfo.endCursor
252 : null;
253 const closingPullRequestsCursor = closing?.pageInfo.hasNextPage
254 ? closing.pageInfo.endCursor
255 : null;
256 const key = `${labelsCursor ?? ""} ${assigneesCursor ?? ""} ${closingPullRequestsCursor ?? ""}`;
257 if (
258 (labels?.pageInfo.hasNextPage && labelsCursor === null) ||
259 (assignees.pageInfo.hasNextPage && assigneesCursor === null) ||
260 (closing?.pageInfo.hasNextPage && closingPullRequestsCursor === null) ||
261 seen.has(key)
262 ) {
263 return yield* invalid(
264 "getIssue",
265 "GitHub did not return complete issue labels, assignees or linked pull requests.",
266 );
267 }
268 seen.add(key);
269 const page = yield* client
270 .IssueCollections({
271 owner,
272 name,
273 number,
274 labelsCursor,
275 assigneesCursor,
276 closingPullRequestsCursor,
277 withLabels: labelsCursor !== null,
278 withAssignees: assigneesCursor !== null,
279 withClosingPullRequests: closingPullRequestsCursor !== null,
280 })
281 .pipe(graphql(input.host, "getIssue"));
282 const next = page.repository?.issue;
283 if (next == null) return yield* notFound("getIssue");
284 if (labelsCursor !== null) {
285 if (next.labels == null) {
286 return yield* invalid("getIssue", "GitHub did not return complete issue labels.");
287 }
288 labels = next.labels;
289 moreLabels.push(
290 ...(next.labels.nodes ?? []).flatMap((node) =>
291 node === null ? [] : [{ name: node.name, color: node.color }],
292 ),
293 );
294 }
295 if (assigneesCursor !== null) {
296 if (next.assignees === undefined) {
297 return yield* invalid("getIssue", "GitHub did not return complete issue assignees.");
298 }
299 assignees = next.assignees;
300 moreAssignees.push(
301 ...(next.assignees.nodes ?? []).flatMap((node) =>
302 node === null
303 ? []
304 : [{ login: node.login, name: node.name, avatarUrl: node.avatarUrl }],
305 ),
306 );
307 }
308 if (closingPullRequestsCursor !== null) {
309 if (next.closedByPullRequestsReferences == null) {
310 return yield* invalid(
311 "getIssue",
312 "GitHub did not return complete linked pull requests.",
313 );
314 }
315 closing = next.closedByPullRequestsReferences;
316 allClosing.push(...(closing.nodes ?? []));
317 }
318 }
319 const detail = toIssueDetail({
320 ...result,
321 repository: {
322 ...repository,
323 issue: {
324 ...raw,
325 closedByPullRequestsReferences:
326 raw.closedByPullRequestsReferences === null
327 ? null
328 : { ...raw.closedByPullRequestsReferences, nodes: allClosing },
329 },
330 },
331 });
332 if (detail === null) return yield* notFound("getIssue");
333 return {
334 ...detail,
335 labels: [...detail.labels, ...moreLabels],
336 assignees: [...detail.assignees, ...moreAssignees],
337 };
338 }),
339
340 getComments: (input) =>
341 issue(input, "getComments").pipe(
342 Effect.flatMap(({ owner, name, number }) =>
343 client
344 .IssueComments({ owner, name, number, cursor: input.cursor })
345 .pipe(graphql(input.host, "getComments")),
346 ),
347 Effect.flatMap((result) =>
348 result.repository?.issue == null
349 ? Effect.fail(notFound("getComments"))
350 : Effect.succeed(toIssueComments(result)),
351 ),
352 ),
353
354 create: (input) =>
355 repository(input.scope, "create").pipe(
356 Effect.flatMap(({ owner, name }) =>
357 api
358 .rest({
359 host: input.host,
360 operation: "create",
361 method: "POST",
362 path: `repos/${owner}/${name}/issues`,
363 body: {
364 title: input.title,
365 body: input.body,
366 labels: input.labels,
367 assignees: input.assignees,
368 },
369 })
370 .pipe(Effect.mapError(fail("create"))),
371 ),
372 Effect.flatMap((response) => {
373 const decoded = decodeCreatedIssueJson(response.body);
374 return Result.isSuccess(decoded)
375 ? Effect.succeed({
376 key: String(decoded.success.number),
377 displayKey: `#${decoded.success.number}`,
378 url: decoded.success.url,
379 })
380 : Effect.fail(
381 new IssueTrackerError({
382 tracker: KIND,
383 operation: "create",
384 reason: "failed",
385 detail: "GitHub returned an unreadable create response.",
386 cause: decoded.failure,
387 }),
388 );
389 }),
390 ),
391
392 comment: (input) =>
393 verifiedIssue(input, "comment").pipe(
394 Effect.flatMap(({ path }) =>
395 api
396 .rest({
397 host: input.host,
398 operation: "comment",
399 method: "POST",
400 path: `${path}/comments`,
401 body: { body: input.body },
402 })
403 .pipe(Effect.asVoid, Effect.mapError(fail("comment"))),
404 ),
405 ),
406
407 update: Effect.fn("GitHubIssueTracker.update")(function* (input) {
408 const { path } = yield* verifiedIssue(input, "update");
409 const response = yield* api
410 .rest({
411 host: input.host,
412 operation: "update",
413 method: "PATCH",
414 path,
415 body: {
416 ...(input.title === undefined ? {} : { title: input.title }),
417 ...(input.body === undefined ? {} : { body: input.body }),
418 ...(input.labels === undefined ? {} : { labels: input.labels }),
419 ...(input.assignees === undefined ? {} : { assignees: input.assignees }),
420 },
421 })
422 .pipe(Effect.mapError(fail("update")));
423 // Without triage access GitHub drops labels and assignees and still answers with success.
424 const applied = decodeIssueMetadataJson(response.body);
425 if (
426 Result.isSuccess(applied) &&
427 ((input.labels !== undefined && !sameNames(input.labels, applied.success.labels)) ||
428 (input.assignees !== undefined && !sameNames(input.assignees, applied.success.assignees)))
429 ) {
430 return yield* invalid(
431 "update",
432 "GitHub did not apply the labels or assignees. Changing them needs triage access to the repository.",
433 );
434 }
435 }),
436
437 setState: Effect.fn("GitHubIssueTracker.setState")(function* (input) {
438 const { path, state, stateReason } = yield* verifiedIssue(input, "setState");
439 const wanted = ISSUE_STATES.find((candidate) => candidate.name === input.state);
440 if (wanted === undefined) {
441 return yield* invalid("setState", `A GitHub issue has no "${input.state}" state.`);
442 }
443 const reason = wanted.closeReason?.replace("-", "_");
444 // GitHub ignores `state_reason` unless the state changes, and would answer with success.
445 if (reason !== undefined && state === "CLOSED" && stateReason?.toLowerCase() !== reason) {
446 return yield* invalid(
447 "setState",
448 "GitHub cannot change why a closed issue was closed. Reopen it, then close it again.",
449 );
450 }
451 yield* api
452 .rest({
453 host: input.host,
454 operation: "setState",
455 method: "PATCH",
456 path,
457 body: {
458 state: wanted.category,
459 ...(reason === undefined ? {} : { state_reason: reason }),
460 },
461 })
462 .pipe(Effect.mapError(fail("setState")));
463 }),
464
465 setReaction: Effect.fn("GitHubIssueTracker.setReaction")(function* (input) {
466 let subjectId: string;
467 if (input.subjectId === undefined) {
468 const target = yield* verifiedIssue(input, "setReaction");
469 subjectId = target.id;
470 } else {
471 const { owner, name, number } = yield* issue(input, "setReaction");
472 // Node ids are global: prove the comment belongs to this issue before writing.
473 const result = yield* client
474 .IssueCommentScope({ owner, name, number, commentId: input.subjectId })
475 .pipe(graphql(input.host, "setReaction"));
476 const expected = result.repository?.issue?.id;
477 if (
478 expected === undefined ||
479 result.node?.__typename !== "IssueComment" ||
480 result.node.issue.id !== expected
481 ) {
482 return yield* invalid(
483 "setReaction",
484 "The comment does not belong to the selected issue.",
485 );
486 }
487 subjectId = input.subjectId;
488 }
489 const variables = { subjectId, content: gitHubReactionContent(input.content) };
490 yield* (
491 input.reacted
492 ? client.AddReaction(variables).pipe(Effect.asVoid)
493 : client.RemoveReaction(variables).pipe(Effect.asVoid)
494 ).pipe(graphql(input.host, "setReaction"));
495 }),
496
497 listTemplates: (input) =>
498 repository(input.scope, "listTemplates").pipe(
499 Effect.flatMap(({ owner, name }) =>
500 client.IssueTemplates({ owner, name }).pipe(graphql(input.host, "listTemplates")),
501 ),
502 Effect.flatMap(({ repository }) =>
503 repository === null
504 ? Effect.fail(notFound("listTemplates"))
505 : readIssueTemplates(repository),
506 ),
507 ),
508
509 listCandidates: (input) =>
510 repository(input.scope, "listCandidates").pipe(
511 Effect.flatMap(({ owner, name }) =>
512 client.IssueCandidates({ owner, name }).pipe(graphql(input.host, "listCandidates")),
513 ),
514 Effect.flatMap(({ repository }) =>
515 repository === null
516 ? Effect.fail(notFound("listCandidates"))
517 : Effect.succeed(toIssueCandidates(repository)),
518 ),
519 ),
520 } satisfies IssueTrackerApi;
521 });