Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Result from "effect/Result";
3import { GraphQLClient, GraphQLClientError, GraphQLGroup } from "effect/graphql";
4import {
5 IssueTrackerKind,
6 type IssueCapabilities,
7 type IssueActor,
8 type IssueInvolvement,
9 type IssueLabel,
10 type IssueListSort,
11} from "@t3tools/contracts";
12import {
13 IssueTrackerError,
14 type IssueInvolvementFilter,
15 type IssueTrackerApi,
16} from "@t3tools/source-control-core/server/IssueTracker";
17
18import * as GitHubRest from "./GitHubRest.ts";
19import { readIssueTemplates } from "./gitHubIssueTemplates.ts";
20import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
21import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
22import { IssuesGraphQLGroup } from "./issues.graphql.ts";
23import { AddReaction, RemoveReaction } from "./pullRequestMutations.graphql.ts";
24import { gitHubReactionContent } from "./gitHubPullRequestJson.ts";
25import {
26 ISSUE_STATES,
27 decodeCreatedIssueJson,
28 decodeIssueMetadataJson,
29 toIssueCandidates,
30 toIssueComments,
31 toIssueDetail,
32 toIssueSearch,
33} from "./gitHubIssueJson.ts";
34
35const KIND = IssueTrackerKind.make("github");
36
37const 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
50const 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. */
53function quotedTerm(value: string): string {
54 return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
55}
56
57function searchTerms(query: string): ReadonlyArray<string> {
58 return query
59 .split(/\s+/)
60 .filter((word) => word.length > 0)
61 .map(quotedTerm);
62}
63
64const INVOLVEMENT_QUALIFIER: Record<Exclude<IssueInvolvement, "all">, string> = {
65 assigned: "assignee",
66 authored: "author",
67 mentioned: "mentions",
68};
69
70function 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
94function 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
114const 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
122const group = GraphQLGroup.merge(
123 IssuesGraphQLGroup,
124 GraphQLGroup.make(AddReaction, RemoveReaction),
125).middleware(GitHubGraphQlClient.GitHubGraphQlAuth);
126
127export 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 getIssueLink: Effect.fn("GitHubIssueTracker.getIssueLink")(function* (input) {
341 const { owner, name, number } = yield* issue(input, "getIssue");
342 const result = yield* client
343 .IssueLinkMetadata({ owner, name, number })
344 .pipe(graphql(input.host, "getIssue"));
345 const found = result.repository?.issue;
346 if (found == null) return yield* notFound("getIssue");
347 return { displayKey: `#${found.number}`, title: found.title, url: found.url };
348 }),
349
350 getComments: (input) =>
351 issue(input, "getComments").pipe(
352 Effect.flatMap(({ owner, name, number }) =>
353 client
354 .IssueComments({ owner, name, number, cursor: input.cursor })
355 .pipe(graphql(input.host, "getComments")),
356 ),
357 Effect.flatMap((result) =>
358 result.repository?.issue == null
359 ? Effect.fail(notFound("getComments"))
360 : Effect.succeed(toIssueComments(result)),
361 ),
362 ),
363
364 create: (input) =>
365 repository(input.scope, "create").pipe(
366 Effect.flatMap(({ owner, name }) =>
367 api
368 .rest({
369 host: input.host,
370 operation: "create",
371 method: "POST",
372 path: `repos/${owner}/${name}/issues`,
373 body: {
374 title: input.title,
375 body: input.body,
376 labels: input.labels,
377 assignees: input.assignees,
378 },
379 })
380 .pipe(Effect.mapError(fail("create"))),
381 ),
382 Effect.flatMap((response) => {
383 const decoded = decodeCreatedIssueJson(response.body);
384 return Result.isSuccess(decoded)
385 ? Effect.succeed({
386 key: String(decoded.success.number),
387 displayKey: `#${decoded.success.number}`,
388 url: decoded.success.url,
389 })
390 : Effect.fail(
391 new IssueTrackerError({
392 tracker: KIND,
393 operation: "create",
394 reason: "failed",
395 detail: "GitHub returned an unreadable create response.",
396 cause: decoded.failure,
397 }),
398 );
399 }),
400 ),
401
402 comment: (input) =>
403 verifiedIssue(input, "comment").pipe(
404 Effect.flatMap(({ path }) =>
405 api
406 .rest({
407 host: input.host,
408 operation: "comment",
409 method: "POST",
410 path: `${path}/comments`,
411 body: { body: input.body },
412 })
413 .pipe(Effect.asVoid, Effect.mapError(fail("comment"))),
414 ),
415 ),
416
417 update: Effect.fn("GitHubIssueTracker.update")(function* (input) {
418 const { path } = yield* verifiedIssue(input, "update");
419 const response = yield* api
420 .rest({
421 host: input.host,
422 operation: "update",
423 method: "PATCH",
424 path,
425 body: {
426 ...(input.title === undefined ? {} : { title: input.title }),
427 ...(input.body === undefined ? {} : { body: input.body }),
428 ...(input.labels === undefined ? {} : { labels: input.labels }),
429 ...(input.assignees === undefined ? {} : { assignees: input.assignees }),
430 },
431 })
432 .pipe(Effect.mapError(fail("update")));
433 // Without triage access GitHub drops labels and assignees and still answers with success.
434 const applied = decodeIssueMetadataJson(response.body);
435 if (
436 Result.isSuccess(applied) &&
437 ((input.labels !== undefined && !sameNames(input.labels, applied.success.labels)) ||
438 (input.assignees !== undefined && !sameNames(input.assignees, applied.success.assignees)))
439 ) {
440 return yield* invalid(
441 "update",
442 "GitHub did not apply the labels or assignees. Changing them needs triage access to the repository.",
443 );
444 }
445 }),
446
447 setState: Effect.fn("GitHubIssueTracker.setState")(function* (input) {
448 const { path, state, stateReason } = yield* verifiedIssue(input, "setState");
449 const wanted = ISSUE_STATES.find((candidate) => candidate.name === input.state);
450 if (wanted === undefined) {
451 return yield* invalid("setState", `A GitHub issue has no "${input.state}" state.`);
452 }
453 const reason = wanted.closeReason?.replace("-", "_");
454 // GitHub ignores `state_reason` unless the state changes, and would answer with success.
455 if (reason !== undefined && state === "CLOSED" && stateReason?.toLowerCase() !== reason) {
456 return yield* invalid(
457 "setState",
458 "GitHub cannot change why a closed issue was closed. Reopen it, then close it again.",
459 );
460 }
461 yield* api
462 .rest({
463 host: input.host,
464 operation: "setState",
465 method: "PATCH",
466 path,
467 body: {
468 state: wanted.category,
469 ...(reason === undefined ? {} : { state_reason: reason }),
470 },
471 })
472 .pipe(Effect.mapError(fail("setState")));
473 }),
474
475 setReaction: Effect.fn("GitHubIssueTracker.setReaction")(function* (input) {
476 let subjectId: string;
477 if (input.subjectId === undefined) {
478 const target = yield* verifiedIssue(input, "setReaction");
479 subjectId = target.id;
480 } else {
481 const { owner, name, number } = yield* issue(input, "setReaction");
482 // Node ids are global: prove the comment belongs to this issue before writing.
483 const result = yield* client
484 .IssueCommentScope({ owner, name, number, commentId: input.subjectId })
485 .pipe(graphql(input.host, "setReaction"));
486 const expected = result.repository?.issue?.id;
487 if (
488 expected === undefined ||
489 result.node?.__typename !== "IssueComment" ||
490 result.node.issue.id !== expected
491 ) {
492 return yield* invalid(
493 "setReaction",
494 "The comment does not belong to the selected issue.",
495 );
496 }
497 subjectId = input.subjectId;
498 }
499 const variables = { subjectId, content: gitHubReactionContent(input.content) };
500 yield* (
501 input.reacted
502 ? client.AddReaction(variables).pipe(Effect.asVoid)
503 : client.RemoveReaction(variables).pipe(Effect.asVoid)
504 ).pipe(graphql(input.host, "setReaction"));
505 }),
506
507 listTemplates: (input) =>
508 repository(input.scope, "listTemplates").pipe(
509 Effect.flatMap(({ owner, name }) =>
510 client.IssueTemplates({ owner, name }).pipe(graphql(input.host, "listTemplates")),
511 ),
512 Effect.flatMap(({ repository }) =>
513 repository === null
514 ? Effect.fail(notFound("listTemplates"))
515 : readIssueTemplates(repository),
516 ),
517 ),
518
519 listCandidates: (input) =>
520 repository(input.scope, "listCandidates").pipe(
521 Effect.flatMap(({ owner, name }) =>
522 client.IssueCandidates({ owner, name }).pipe(graphql(input.host, "listCandidates")),
523 ),
524 Effect.flatMap(({ repository }) =>
525 repository === null
526 ? Effect.fail(notFound("listCandidates"))
527 : Effect.succeed(toIssueCandidates(repository)),
528 ),
529 ),
530 } satisfies IssueTrackerApi;
531});