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