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 legacy = client.IssueDetail({ owner, name, number }).pipe(
269 graphql(input.host, "getIssue"),
270 Effect.map((result) => ({ result, statusRead: null })),
271 );
272 const { result, statusRead } = yield* asksStatuses(input.host)
273 ? client.IssueDetailWithStatus({ owner, name, number }).pipe(
274 graphql(input.host, "getIssue"),
275 Effect.map((result) => ({ result, statusRead: result.repository })),
276 Effect.catchIf(statusesRefused, () => legacy),
277 )
278 : legacy;
279 const repository = result.repository;
280 const raw = repository?.issue;
281 if (repository == null || raw == null) return yield* notFound("getIssue");
282 // Editing replaces labels and assignees, and a closing reference can sit past the first
283 // page. Finish their pages before handing the issue to a client.
284 let labels = raw.labels;
285 let assignees = raw.assignees;
286 let closing = raw.closedByPullRequestsReferences;
287 const seen = new Set<string>();
288 const moreLabels: IssueLabel[] = [];
289 const moreAssignees: IssueActor[] = [];
290 const allClosing = [...(closing?.nodes ?? [])];
291 while (
292 labels?.pageInfo.hasNextPage === true ||
293 assignees.pageInfo.hasNextPage ||
294 closing?.pageInfo.hasNextPage === true
295 ) {
296 const labelsCursor = labels?.pageInfo.hasNextPage ? labels.pageInfo.endCursor : null;
297 const assigneesCursor = assignees.pageInfo.hasNextPage
298 ? assignees.pageInfo.endCursor
299 : null;
300 const closingPullRequestsCursor = closing?.pageInfo.hasNextPage
301 ? closing.pageInfo.endCursor
302 : null;
303 const key = `${labelsCursor ?? ""} ${assigneesCursor ?? ""} ${closingPullRequestsCursor ?? ""}`;
304 if (
305 (labels?.pageInfo.hasNextPage && labelsCursor === null) ||
306 (assignees.pageInfo.hasNextPage && assigneesCursor === null) ||
307 (closing?.pageInfo.hasNextPage && closingPullRequestsCursor === null) ||
308 seen.has(key)
309 ) {
310 return yield* invalid(
311 "getIssue",
312 "GitHub did not return complete issue labels, assignees or linked pull requests.",
313 );
314 }
315 seen.add(key);
316 const page = yield* client
317 .IssueCollections({
318 owner,
319 name,
320 number,
321 labelsCursor,
322 assigneesCursor,
323 closingPullRequestsCursor,
324 withLabels: labelsCursor !== null,
325 withAssignees: assigneesCursor !== null,
326 withClosingPullRequests: closingPullRequestsCursor !== null,
327 })
328 .pipe(graphql(input.host, "getIssue"));
329 const next = page.repository?.issue;
330 if (next == null) return yield* notFound("getIssue");
331 if (labelsCursor !== null) {
332 if (next.labels == null) {
333 return yield* invalid("getIssue", "GitHub did not return complete issue labels.");
334 }
335 labels = next.labels;
336 moreLabels.push(
337 ...(next.labels.nodes ?? []).flatMap((node) =>
338 node === null ? [] : [{ name: node.name, color: node.color }],
339 ),
340 );
341 }
342 if (assigneesCursor !== null) {
343 if (next.assignees === undefined) {
344 return yield* invalid("getIssue", "GitHub did not return complete issue assignees.");
345 }
346 assignees = next.assignees;
347 moreAssignees.push(
348 ...(next.assignees.nodes ?? []).flatMap((node) =>
349 node === null
350 ? []
351 : [{ login: node.login, name: node.name, avatarUrl: node.avatarUrl }],
352 ),
353 );
354 }
355 if (closingPullRequestsCursor !== null) {
356 if (next.closedByPullRequestsReferences == null) {
357 return yield* invalid(
358 "getIssue",
359 "GitHub did not return complete linked pull requests.",
360 );
361 }
362 closing = next.closedByPullRequestsReferences;
363 allClosing.push(...(closing.nodes ?? []));
364 }
365 }
366 const detail = toIssueDetail(
367 {
368 ...result,
369 repository: {
370 ...repository,
371 issue: {
372 ...raw,
373 closedByPullRequestsReferences:
374 raw.closedByPullRequestsReferences === null
375 ? null
376 : { ...raw.closedByPullRequestsReferences, nodes: allClosing },
377 },
378 },
379 },
380 statusRead,
381 );
382 if (detail === null) return yield* notFound("getIssue");
383 return {
384 ...detail,
385 labels: [...detail.labels, ...moreLabels],
386 assignees: [...detail.assignees, ...moreAssignees],
387 };
388 }),
389
390 getIssueLink: Effect.fn("GitHubIssueTracker.getIssueLink")(function* (input) {
391 const { owner, name, number } = yield* issue(input, "getIssue");
392 const result = yield* client
393 .IssueLinkMetadata({ owner, name, number })
394 .pipe(graphql(input.host, "getIssue"));
395 const found = result.repository?.issue;
396 if (found == null) return yield* notFound("getIssue");
397 return { displayKey: `#${found.number}`, title: found.title, url: found.url };
398 }),
399
400 getComments: (input) =>
401 issue(input, "getComments").pipe(
402 Effect.flatMap(({ owner, name, number }) =>
403 client
404 .IssueComments({ owner, name, number, cursor: input.cursor })
405 .pipe(graphql(input.host, "getComments")),
406 ),
407 Effect.flatMap((result) =>
408 result.repository?.issue == null
409 ? Effect.fail(notFound("getComments"))
410 : Effect.succeed(toIssueComments(result)),
411 ),
412 ),
413
414 create: (input) =>
415 repository(input.scope, "create").pipe(
416 Effect.flatMap(({ owner, name }) =>
417 api
418 .rest({
419 host: input.host,
420 operation: "create",
421 method: "POST",
422 path: `repos/${owner}/${name}/issues`,
423 body: {
424 title: input.title,
425 body: input.body,
426 labels: input.labels,
427 assignees: input.assignees,
428 },
429 })
430 .pipe(Effect.mapError(fail("create"))),
431 ),
432 Effect.flatMap((response) => {
433 const decoded = decodeCreatedIssueJson(response.body);
434 return Result.isSuccess(decoded)
435 ? Effect.succeed({
436 key: String(decoded.success.number),
437 displayKey: `#${decoded.success.number}`,
438 url: decoded.success.url,
439 })
440 : Effect.fail(
441 new IssueTrackerError({
442 tracker: KIND,
443 operation: "create",
444 reason: "failed",
445 detail: "GitHub returned an unreadable create response.",
446 cause: decoded.failure,
447 }),
448 );
449 }),
450 ),
451
452 comment: (input) =>
453 verifiedIssue(input, "comment").pipe(
454 Effect.flatMap(({ path }) =>
455 api
456 .rest({
457 host: input.host,
458 operation: "comment",
459 method: "POST",
460 path: `${path}/comments`,
461 body: { body: input.body },
462 })
463 .pipe(Effect.asVoid, Effect.mapError(fail("comment"))),
464 ),
465 ),
466
467 update: Effect.fn("GitHubIssueTracker.update")(function* (input) {
468 const { path } = yield* verifiedIssue(input, "update");
469 const response = yield* api
470 .rest({
471 host: input.host,
472 operation: "update",
473 method: "PATCH",
474 path,
475 body: {
476 ...(input.title === undefined ? {} : { title: input.title }),
477 ...(input.body === undefined ? {} : { body: input.body }),
478 ...(input.labels === undefined ? {} : { labels: input.labels }),
479 ...(input.assignees === undefined ? {} : { assignees: input.assignees }),
480 },
481 })
482 .pipe(Effect.mapError(fail("update")));
483 // Without triage access GitHub drops labels and assignees and still answers with success.
484 const applied = decodeIssueMetadataJson(response.body);
485 if (
486 Result.isSuccess(applied) &&
487 ((input.labels !== undefined && !sameNames(input.labels, applied.success.labels)) ||
488 (input.assignees !== undefined && !sameNames(input.assignees, applied.success.assignees)))
489 ) {
490 return yield* invalid(
491 "update",
492 "GitHub did not apply the labels or assignees. Changing them needs triage access to the repository.",
493 );
494 }
495 }),
496
497 setState: Effect.fn("GitHubIssueTracker.setState")(function* (input) {
498 const { path, id, state, stateReason, owner, name, number } = yield* verifiedIssue(
499 input,
500 "setState",
501 );
502 const statuses = planningStatusesOf(
503 (yield* issueStatuses(input, owner, name, number, "setState"))?.planningStatuses,
504 );
505 const status = statuses.find((candidate) => candidate.name === input.state);
506 // Closing as a duplicate through a status needs the original issue, which nothing here
507 // names; closing it over REST leaves GitHub to pick the duplicate status.
508 if (status !== undefined && status.category.key !== "duplicate") {
509 return yield* client
510 .SetIssueStatus({ issueId: id, statusId: status.id })
511 .pipe(graphql(input.host, "setState"), Effect.asVoid);
512 }
513 if (status === undefined && statuses.length > 0) {
514 return yield* invalid("setState", `This repository has no "${input.state}" issue status.`);
515 }
516 const wanted =
517 status === undefined
518 ? ISSUE_STATES.find((candidate) => candidate.name === input.state)
519 : toPlanningState(status);
520 if (wanted === undefined) {
521 return yield* invalid("setState", `A GitHub issue has no "${input.state}" state.`);
522 }
523 const reason = wanted.closeReason?.replace("-", "_");
524 // GitHub ignores `state_reason` unless the state changes, and would answer with success.
525 if (reason !== undefined && state === "CLOSED" && stateReason?.toLowerCase() !== reason) {
526 return yield* invalid(
527 "setState",
528 "GitHub cannot change why a closed issue was closed. Reopen it, then close it again.",
529 );
530 }
531 yield* api
532 .rest({
533 host: input.host,
534 operation: "setState",
535 method: "PATCH",
536 path,
537 body: {
538 state: wanted.category,
539 ...(reason === undefined ? {} : { state_reason: reason }),
540 },
541 })
542 .pipe(Effect.mapError(fail("setState")));
543 }),
544
545 setReaction: Effect.fn("GitHubIssueTracker.setReaction")(function* (input) {
546 let subjectId: string;
547 if (input.subjectId === undefined) {
548 const target = yield* verifiedIssue(input, "setReaction");
549 subjectId = target.id;
550 } else {
551 const { owner, name, number } = yield* issue(input, "setReaction");
552 // Node ids are global: prove the comment belongs to this issue before writing.
553 const result = yield* client
554 .IssueCommentScope({ owner, name, number, commentId: input.subjectId })
555 .pipe(graphql(input.host, "setReaction"));
556 const expected = result.repository?.issue?.id;
557 if (
558 expected === undefined ||
559 result.node?.__typename !== "IssueComment" ||
560 result.node.issue.id !== expected
561 ) {
562 return yield* invalid(
563 "setReaction",
564 "The comment does not belong to the selected issue.",
565 );
566 }
567 subjectId = input.subjectId;
568 }
569 const variables = { subjectId, content: gitHubReactionContent(input.content) };
570 yield* (
571 input.reacted
572 ? client.AddReaction(variables).pipe(Effect.asVoid)
573 : client.RemoveReaction(variables).pipe(Effect.asVoid)
574 ).pipe(graphql(input.host, "setReaction"));
575 }),
576
577 listTemplates: (input) =>
578 repository(input.scope, "listTemplates").pipe(
579 Effect.flatMap(({ owner, name }) =>
580 client.IssueTemplates({ owner, name }).pipe(graphql(input.host, "listTemplates")),
581 ),
582 Effect.flatMap(({ repository }) =>
583 repository === null
584 ? Effect.fail(notFound("listTemplates"))
585 : readIssueTemplates(repository),
586 ),
587 ),
588
589 listCandidates: (input) =>
590 repository(input.scope, "listCandidates").pipe(
591 Effect.flatMap(({ owner, name }) =>
592 client.IssueCandidates({ owner, name }).pipe(graphql(input.host, "listCandidates")),
593 ),
594 Effect.flatMap(({ repository }) =>
595 repository === null
596 ? Effect.fail(notFound("listCandidates"))
597 : Effect.succeed(toIssueCandidates(repository)),
598 ),
599 ),
600 } satisfies IssueTrackerApi;
601});