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