Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

GitHubIssueTracker.test.ts

914 lines32.8 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4​
5import * as Redacted from "effect/Redacted";
6import * as Schema from "effect/Schema";
7import { HttpClient, HttpClientResponse } from "effect/http";
8import { IssueTemplateList } from "@t3tools/contracts";
9import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
10import * as GitHubCredentials from "./GitHubCredentials.ts";
11import * as GitHubRest from "./GitHubRest.ts";
12import * as GitHubQuota from "./GitHubQuota.ts";
13import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
14import * as GitHubIssueTracker from "./GitHubIssueTracker.ts";
15​
16const DETAIL_RESPONSE = JSON.stringify({
17 data: {
18 viewer: { login: "julius" },
19 repository: {
20 viewerPermission: "TRIAGE",
21 planningStatuses: null,
22 issue: {
23 __typename: "Issue",
24 viewerCanSetStatus: true,
25 status: null,
26 number: 42,
27 title: "Composer loses focus",
28 url: "https://github.com/acme/web/issues/42",
29 author: {
30 __typename: "User",
31 login: "octocat",
32 avatarUrl: "https://avatars/octocat",
33 name: "Octo Cat",
34 },
35 state: "CLOSED",
36 stateReason: "DUPLICATE",
37 createdAt: "2026-07-01T00:00:00Z",
38 updatedAt: "2026-07-03T00:00:00Z",
39 closedAt: "2026-07-03T00:00:00Z",
40 comments: {
41 totalCount: 3,
42 pageInfo: { hasPreviousPage: true, startCursor: "Y3Vyc29y" },
43 nodes: [
44 {
45 __typename: "IssueComment",
46 id: "IC_1",
47 author: { __typename: "User", login: "julius", avatarUrl: "https://avatars/julius" },
48 body: "Repro attached.",
49 createdAt: "2026-07-02T00:00:00Z",
50 url: "https://github.com/acme/web/issues/42#issuecomment-1",
51 reactionGroups: [
52 {
53 content: "THUMBS_UP",
54 viewerHasReacted: true,
55 reactors: {
56 totalCount: 2,
57 nodes: [
58 { __typename: "User", login: "julius" },
59 { __typename: "User", login: "theo" },
60 ],
61 },
62 },
63 {
64 content: "EYES",
65 viewerHasReacted: false,
66 reactors: { totalCount: 0, nodes: [] },
67 },
68 ],
69 },
70 ],
71 },
72 assignees: {
73 pageInfo: { hasNextPage: false, endCursor: null },
74 nodes: [{ login: "theo", name: null, avatarUrl: "https://avatars/julius" }],
75 },
76 labels: {
77 pageInfo: { hasNextPage: true, endCursor: "labels-next" },
78 nodes: [{ name: "bug", color: "d73a4a" }, null],
79 },
80 body: "Typing in the composer drops focus after a paste.",
81 viewerCanUpdate: false,
82 viewerCanClose: false,
83 viewerCanReopen: true,
84 reactionGroups: [],
85 closedByPullRequestsReferences: {
86 pageInfo: { hasNextPage: true, endCursor: "links-next" },
87 nodes: [
88 {
89 number: 50,
90 title: "fix(web): keep composer focus",
91 url: "https://github.com/acme/web/pull/50",
92 state: "MERGED",
93 isDraft: false,
94 repository: { nameWithOwner: "acme/web" },
95 },
96 ],
97 },
98 timelineItems: {
99 nodes: [
100 {
101 __typename: "LabeledEvent",
102 id: "LE_1",
103 createdAt: "2026-07-01T01:00:00Z",
104 actor: { __typename: "User", login: "theo", avatarUrl: "https://avatars/theo" },
105 label: { name: "bug" },
106 },
107 {
108 __typename: "CrossReferencedEvent",
109 id: "CRE_1",
110 createdAt: "2026-07-02T01:00:00Z",
111 actor: { __typename: "User", login: "julius", avatarUrl: "https://avatars/julius" },
112 source: {
113 __typename: "PullRequest",
114 number: 50,
115 title: "fix(web): keep composer focus",
116 url: "https://github.com/acme/web/pull/50",
117 state: "MERGED",
118 isDraft: false,
119 repository: { nameWithOwner: "acme/web" },
120 },
121 },
122 { __typename: "MentionedEvent", id: "ME_1", createdAt: "2026-07-02T02:00:00Z" },
123 {
124 __typename: "ClosedEvent",
125 id: "CE_1",
126 createdAt: "2026-07-03T00:00:00Z",
127 actor: null,
128 },
129 ],
130 },
131 },
132 },
133 },
134});
135​
136/** A repository GitHub has not given issue statuses yet. */
137const NO_STATUSES = {
138 data: {
139 repository: { planningStatuses: null, issue: { viewerCanSetStatus: true, status: null } },
140 },
141};
142​
143const decodeVariables = Schema.decodeUnknownSync(
144 Schema.fromJsonString(
145 Schema.Struct({
146 query: Schema.String,
147 variables: Schema.Record(Schema.String, Schema.Unknown),
148 }),
149 ),
150);
151​
152function transport(httpClient: HttpClient.HttpClient) {
153 return GitHubRest.layer.pipe(
154 Layer.provideMerge(
155 Layer.mergeAll(
156 GitHubQuota.layer,
157 SourceControlRateLimit.layer,
158 Layer.mock(GitHubCredentials.GitHubCredentials)({
159 saved: () => Effect.succeedNone,
160 get: (host) =>
161 Effect.succeed({
162 host,
163 token: Redacted.make("test-token"),
164 source: "gh" as const,
165 fingerprint: "test",
166 }),
167 }),
168 Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
169 enabled: false,
170 token: () => Effect.succeedNone,
171 invalidate: () => Effect.void,
172 }),
173 Layer.succeed(HttpClient.HttpClient, httpClient),
174 ),
175 ),
176 );
178​
179function tracker(onRequest: (variables: unknown) => void, templateRepository?: unknown) {
180 return GitHubIssueTracker.make.pipe(
181 Effect.provide(
182 transport(
183 HttpClient.make((request) => {
184 if (request.body._tag !== "Uint8Array")
185 return Effect.die("Expected a GraphQL JSON request.");
186 const { query, variables } = decodeVariables(new TextDecoder().decode(request.body.body));
187 const statusRead = query.includes("query IssueStatuses");
188 if (!statusRead) onRequest(variables);
189 const body = statusRead
190 ? JSON.stringify(NO_STATUSES)
191 : templateRepository !== undefined
192 ? JSON.stringify({ data: { repository: templateRepository } })
193 : "labelsCursor" in variables
194 ? JSON.stringify({
195 data: {
196 repository: {
197 issue: {
198 labels: {
199 pageInfo: { hasNextPage: false, endCursor: null },
200 nodes: [{ name: "needs repro", color: "ffffff" }],
201 },
202 closedByPullRequestsReferences: {
203 pageInfo: { hasNextPage: false, endCursor: null },
204 nodes: [
205 {
206 number: 61,
207 title: "fix(web): restore focus after paste",
208 url: "https://github.com/acme/web/pull/61",
209 state: "OPEN",
210 isDraft: true,
211 repository: { nameWithOwner: "acme/web" },
212 },
213 ],
214 },
215 },
216 },
217 },
218 })
219 : DETAIL_RESPONSE;
220 return Effect.succeed(
221 HttpClientResponse.fromWeb(
222 request,
223 new Response(body, {
224 headers: { "content-type": "application/json" },
225 }),
226 ),
227 );
228 }),
229 ),
230 ),
231 );
233​
234const encodeTemplateList = Schema.encodeSync(IssueTemplateList);
235​
236const decodeBody = Schema.decodeUnknownSync(
237 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
238);
239​
240describe("GitHubIssueTracker", () => {
241 it.effect("reads only the fields needed to link a GitHub issue and rejects missing issues", () =>
242 Effect.gen(function* () {
243 const requests: unknown[] = [];
244 const target = { cwd: "/w", host: "github.com", scope: "acme/web", key: "42" };
245 const url = "https://github.com/acme/web/issues/42";
246 const found = yield* tracker((input) => requests.push(input), {
247 issue: { number: 42, title: "Fixture issue", url },
248 });
249 expect(yield* found.getIssueLink(target)).toEqual({
250 displayKey: "#42",
251 title: "Fixture issue",
252 url,
253 });
254​
255 const missing = yield* tracker((input) => requests.push(input), { issue: null });
256 expect(yield* Effect.flip(missing.getIssueLink(target))).toMatchObject({
257 reason: "not-found",
258 });
259 expect(requests).toEqual([
260 { owner: "acme", name: "web", number: 42 },
261 { owner: "acme", name: "web", number: 42 },
262 ]);
263 }),
264 );
265​
266 it.effect("writes an issue lifecycle without mutating pull requests or foreign comments", () =>
267 Effect.gen(function* () {
268 const writes: unknown[] = [];
269 let issueState: { state: string; stateReason: string | null } = {
270 state: "OPEN",
271 stateReason: null,
272 };
273 const http = HttpClient.make((request) => {
274 if (request.body._tag !== "Uint8Array") return Effect.die("Expected a JSON request.");
275 const text = new TextDecoder().decode(request.body.body);
276 let response: unknown = {};
277 if (request.url === "https://api.github.com/graphql") {
278 const { query, variables } = decodeVariables(text);
279 expect(request.method).toBe("POST");
280 const operation = query.match(/(?:query|mutation)\s+(\w+)/)?.[1];
281 if (operation === "IssueStatuses") {
282 response = NO_STATUSES;
283 } else if (operation === "IssueNodeId" || operation === "IssueCommentScope") {
284 expect(variables).toMatchObject({ owner: "acme", name: "web" });
285 response = {
286 data: {
287 repository: {
288 issue: variables["number"] === 42 ? { id: "I_42", ...issueState } : null,
289 },
290 ...(operation === "IssueCommentScope"
291 ? { node: { __typename: "IssueComment", issue: { id: "I_other" } } }
292 : {}),
293 },
294 };
295 } else {
296 expect(["AddReaction", "RemoveReaction"]).toContain(operation);
297 expect(variables).toEqual({ subjectId: "I_42", content: "THUMBS_UP" });
298 writes.push(operation);
299 response = {
300 data: {
301 [operation === "AddReaction" ? "addReaction" : "removeReaction"]: {
302 reaction: { content: "THUMBS_UP" },
303 },
304 },
305 };
306 }
307 } else {
308 const body = decodeBody(text);
309 writes.push([request.method, request.url, body]);
310 if (typeof body["state"] === "string") {
311 issueState = {
312 state: body["state"].toUpperCase(),
313 stateReason:
314 typeof body["state_reason"] === "string"
315 ? body["state_reason"].toUpperCase()
316 : null,
317 };
318 }
319 if (request.url.endsWith("/issues")) {
320 response = { number: 42, html_url: "https://github.com/acme/web/issues/42" };
321 } else if (request.method === "PATCH" && body["title"] === "Dropped") {
322 // What GitHub answers a caller without triage access: success, metadata untouched.
323 response = { labels: [{ name: "Bug" }], assignees: [] };
324 } else if (request.method === "PATCH") {
325 response = { labels: [], assignees: [] };
326 }
327 }
328 return Effect.succeed(
329 HttpClientResponse.fromWeb(
330 request,
331 new Response(JSON.stringify(response), {
332 headers: { "content-type": "application/json" },
333 }),
334 ),
335 );
336 });
337 const api = yield* GitHubIssueTracker.make.pipe(Effect.provide(transport(http)));
338 const target = { cwd: "/w", host: "github.com", scope: "acme/web", key: "42" };
339 expect(
340 yield* api.create({
341 ...target,
342 title: "Fixture",
343 body: "Body",
344 labels: ["bug"],
345 assignees: ["octocat"],
346 }),
347 ).toEqual({
348 key: "42",
349 displayKey: "#42",
350 url: "https://github.com/acme/web/issues/42",
351 });
352 yield* api.comment({ ...target, body: "Comment" });
353 yield* api.update({ ...target, title: "Updated", body: "Edited", labels: [], assignees: [] });
354 expect(
355 yield* Effect.flip(api.update({ ...target, title: "Dropped", labels: ["bug", "p1"] })),
356 ).toMatchObject({ operation: "update", reason: "failed" });
357 yield* api.update({ ...target, title: "Dropped", labels: ["bug"], assignees: [] });
358 expect(yield* Effect.flip(api.setState({ ...target, state: "closed" }))).toMatchObject({
359 operation: "setState",
360 reason: "failed",
361 });
362 yield* api.setState({ ...target, state: "Not planned" });
363 // GitHub ignores a new reason on a closed issue, so it is refused instead of sent.
364 expect(
365 yield* api.setState({ ...target, state: "Completed" }).pipe(Effect.result),
366 ).toMatchObject({ _tag: "Failure", failure: { operation: "setState", reason: "failed" } });
367 yield* api.setState({ ...target, state: "Open" });
368 yield* api.setState({ ...target, state: "Duplicate" });
369 yield* api.setState({ ...target, state: "Open" });
370 yield* api.setReaction({ ...target, content: "thumbs-up", reacted: true });
371 yield* api.setReaction({ ...target, content: "thumbs-up", reacted: false });
372​
373 const pullRequest = { ...target, key: "50" };
374 expect(
375 yield* api.update({ ...pullRequest, title: "Do not edit" }).pipe(Effect.result),
376 ).toMatchObject({ _tag: "Failure", failure: { operation: "update", reason: "not-found" } });
377 expect(
378 yield* api.setState({ ...pullRequest, state: "Completed" }).pipe(Effect.result),
379 ).toMatchObject({
380 _tag: "Failure",
381 failure: { operation: "setState", reason: "not-found" },
382 });
383 expect(
384 yield* api.comment({ ...pullRequest, body: "Do not comment" }).pipe(Effect.result),
385 ).toMatchObject({ _tag: "Failure", failure: { operation: "comment", reason: "not-found" } });
386 expect(
387 yield* Effect.flip(
388 api.setReaction({
389 ...target,
390 subjectId: "IC_other",
391 content: "thumbs-up",
392 reacted: true,
393 }),
394 ),
395 ).toMatchObject({ operation: "setReaction", reason: "failed" });
396​
397 expect(writes).toEqual([
398 [
399 "POST",
400 "https://api.github.com/repos/acme/web/issues",
401 { title: "Fixture", body: "Body", labels: ["bug"], assignees: ["octocat"] },
402 ],
403 ["POST", "https://api.github.com/repos/acme/web/issues/42/comments", { body: "Comment" }],
404 [
405 "PATCH",
406 "https://api.github.com/repos/acme/web/issues/42",
407 { title: "Updated", body: "Edited", labels: [], assignees: [] },
408 ],
409 [
410 "PATCH",
411 "https://api.github.com/repos/acme/web/issues/42",
412 { title: "Dropped", labels: ["bug", "p1"] },
413 ],
414 [
415 "PATCH",
416 "https://api.github.com/repos/acme/web/issues/42",
417 { title: "Dropped", labels: ["bug"], assignees: [] },
418 ],
419 [
420 "PATCH",
421 "https://api.github.com/repos/acme/web/issues/42",
422 { state: "closed", state_reason: "not_planned" },
423 ],
424 ["PATCH", "https://api.github.com/repos/acme/web/issues/42", { state: "open" }],
425 [
426 "PATCH",
427 "https://api.github.com/repos/acme/web/issues/42",
428 { state: "closed", state_reason: "duplicate" },
429 ],
430 ["PATCH", "https://api.github.com/repos/acme/web/issues/42", { state: "open" }],
431 "AddReaction",
432 "RemoveReaction",
433 ]);
434 }),
435 );
436​
437 it.effect("moves an issue between the repository's issue statuses", () =>
438 Effect.gen(function* () {
439 const status = (id: string, name: string, key: string, stateReason: string | null) => ({
440 id,
441 name,
442 category: { key, state: stateReason === null ? "OPEN" : "CLOSED", stateReason },
443 });
444 const planningStatuses = {
445 nodes: [
446 status("IS_1", "Backlog", "backlog", null),
447 status("IS_2", "In review", "started", null),
448 status("IS_3", "Done", "completed", "COMPLETED"),
449 status("IS_4", "Duplicate", "duplicate", "DUPLICATE"),
450 ],
451 };
452 const fixture = JSON.parse(DETAIL_RESPONSE);
453 const page = { hasNextPage: false, endCursor: null };
454 Object.assign(fixture.data.repository.issue, {
455 state: "OPEN",
456 stateReason: null,
457 labels: { pageInfo: page, nodes: [] },
458 closedByPullRequestsReferences: { pageInfo: page, nodes: [] },
459 });
460 const writes: unknown[] = [];
461 const http = HttpClient.make((request) => {
462 if (request.body._tag !== "Uint8Array") return Effect.die("Expected a JSON request.");
463 const text = new TextDecoder().decode(request.body.body);
464 let response: unknown = {};
465 if (request.url === "https://api.github.com/graphql") {
466 const { query, variables } = decodeVariables(text);
467 const operation = query.match(/(?:query|mutation)\s+(\w+)/)?.[1];
468 if (operation === "IssueDetailWithStatus") {
469 fixture.data.repository.planningStatuses = planningStatuses;
470 Object.assign(fixture.data.repository.issue, {
471 viewerCanSetStatus: false,
472 status: planningStatuses.nodes[1],
473 });
474 response = fixture;
475 } else if (operation === "IssueStatuses") {
476 response = {
477 data: {
478 repository: {
479 planningStatuses,
480 issue: { viewerCanSetStatus: false, status: planningStatuses.nodes[1] },
481 },
482 },
483 };
484 } else if (operation === "IssueNodeId") {
485 response = {
486 data: {
487 repository: { issue: { id: "I_42", state: "OPEN", stateReason: null } },
488 },
489 };
490 } else {
491 writes.push([operation, variables]);
492 response = { data: { setIssueStatus: { clientMutationId: null } } };
493 }
494 } else {
495 writes.push([request.method, request.url, decodeBody(text)]);
496 }
497 return Effect.succeed(
498 HttpClientResponse.fromWeb(
499 request,
500 new Response(JSON.stringify(response), {
501 headers: { "content-type": "application/json" },
502 }),
503 ),
504 );
505 });
506 const api = yield* GitHubIssueTracker.make.pipe(Effect.provide(transport(http)));
507 const target = { cwd: "/w", host: "github.com", scope: "acme/web", key: "42" };
508​
509 const issue = yield* api.getIssue(target);
510 expect(issue.state).toEqual({ category: "open", name: "In review" });
511 expect(issue.states).toEqual([
512 { category: "open", name: "Backlog" },
513 { category: "open", name: "In review" },
514 { category: "closed", name: "Done", closeReason: "completed" },
515 { category: "closed", name: "Duplicate", closeReason: "duplicate" },
516 ]);
517 expect(issue.viewerPermissions.setState).toBe(false);
518​
519 yield* api.setState({ ...target, state: "Backlog" });
520 // Closing as a duplicate through a status needs the original issue, so it closes over REST.
521 yield* api.setState({ ...target, state: "Duplicate" });
522 expect(yield* Effect.flip(api.setState({ ...target, state: "Open" }))).toMatchObject({
523 operation: "setState",
524 reason: "failed",
525 });
526 expect(writes).toEqual([
527 ["SetIssueStatus", { issueId: "I_42", statusId: "IS_1" }],
528 [
529 "PATCH",
530 "https://api.github.com/repos/acme/web/issues/42",
531 { state: "closed", state_reason: "duplicate" },
532 ],
533 ]);
534 }),
535 );
536​
537 it.effect("never names issue statuses to an Enterprise server", () =>
538 Effect.gen(function* () {
539 const queries: string[] = [];
540 const http = HttpClient.make((request) => {
541 if (request.body._tag !== "Uint8Array") return Effect.die("Expected a JSON request.");
542 const { query } = decodeVariables(new TextDecoder().decode(request.body.body));
543 queries.push(query);
544 const page = { hasNextPage: false, endCursor: null };
545 const detail = JSON.parse(DETAIL_RESPONSE);
546 Object.assign(detail.data.repository.issue, {
547 labels: { pageInfo: page, nodes: [] },
548 closedByPullRequestsReferences: { pageInfo: page, nodes: [] },
549 });
550 const body = query.includes("query IssueSearch")
551 ? { data: { search: { pageInfo: page, nodes: [] } } }
552 : detail;
553 return Effect.succeed(
554 HttpClientResponse.fromWeb(
555 request,
556 new Response(JSON.stringify(body), {
557 headers: { "content-type": "application/json" },
558 }),
559 ),
560 );
561 });
562 const api = yield* GitHubIssueTracker.make.pipe(Effect.provide(transport(http)));
563 const target = { cwd: "/w", host: "ghe.example.com", scope: "acme/web" };
564 yield* api.listIssues({
565 ...target,
566 state: "open",
567 involvement: "all",
568 sort: "updated",
569 limit: 10,
570 });
571 yield* api.getIssue({ ...target, key: "42" });
572 expect(queries).toHaveLength(2);
573 for (const query of queries) expect(query).not.toMatch(/status|planningStatuses/i);
574 }),
575 );
576​
577 it.effect("reads an issue on github.com in one GraphQL query", () =>
578 Effect.gen(function* () {
579 const operations: string[] = [];
580 const http = HttpClient.make((request) => {
581 if (request.body._tag !== "Uint8Array") return Effect.die("Expected a JSON request.");
582 const { query } = decodeVariables(new TextDecoder().decode(request.body.body));
583 const operation = query.match(/(?:query|mutation)\s+(\w+)/)?.[1] ?? "";
584 operations.push(operation);
585 const page = { hasNextPage: false, endCursor: null };
586 const detail = JSON.parse(DETAIL_RESPONSE);
587 Object.assign(detail.data.repository.issue, {
588 labels: { pageInfo: page, nodes: [] },
589 closedByPullRequestsReferences: { pageInfo: page, nodes: [] },
590 });
591 const body = operation === "IssueStatuses" ? NO_STATUSES : detail;
592 return Effect.succeed(
593 HttpClientResponse.fromWeb(
594 request,
595 new Response(JSON.stringify(body), {
596 headers: { "content-type": "application/json" },
597 }),
598 ),
599 );
600 });
601 const api = yield* GitHubIssueTracker.make.pipe(Effect.provide(transport(http)));
602 yield* api.getIssue({ cwd: "/w", host: "github.com", scope: "acme/web", key: "42" });
603 // Each query spends the viewer's shared GraphQL allowance; the sidebar reads every linked issue.
604 expect(operations).toHaveLength(1);
605 }),
606 );
607​
608 it.effect("reads and lists issues without statuses when GitHub refuses the status fields", () =>
609 Effect.gen(function* () {
610 const operations: string[] = [];
611 const http = HttpClient.make((request) => {
612 if (request.body._tag !== "Uint8Array") return Effect.die("Expected a JSON request.");
613 const { query } = decodeVariables(new TextDecoder().decode(request.body.body));
614 const operation = query.match(/query\s+(\w+)/)?.[1] ?? "";
615 operations.push(operation);
616 const page = { hasNextPage: false, endCursor: null };
617 const detail = JSON.parse(DETAIL_RESPONSE);
618 Object.assign(detail.data.repository.issue, {
619 labels: { pageInfo: page, nodes: [] },
620 closedByPullRequestsReferences: { pageInfo: page, nodes: [] },
621 });
622 const body =
623 operation === "IssueSearchWithStatus" || operation === "IssueDetailWithStatus"
624 ? {
625 data: null,
626 errors: [{ message: "Field 'status' doesn't exist on type 'Issue'" }],
627 }
628 : operation === "IssueDetail"
629 ? detail
630 : { data: { search: { pageInfo: page, nodes: [] } } };
631 return Effect.succeed(
632 HttpClientResponse.fromWeb(
633 request,
634 new Response(JSON.stringify(body), {
635 headers: { "content-type": "application/json" },
636 }),
637 ),
638 );
639 });
640 const api = yield* GitHubIssueTracker.make.pipe(Effect.provide(transport(http)));
641 const listing = yield* api.listIssues({
642 cwd: "/w",
643 host: "github.com",
644 scope: "acme/web",
645 state: "open",
646 involvement: "all",
647 sort: "updated",
648 limit: 10,
649 });
650 expect(listing.items).toEqual([]);
651 const issue = yield* api.getIssue({
652 cwd: "/w",
653 host: "github.com",
654 scope: "acme/web",
655 key: "42",
656 });
657 expect(issue.key).toBe("42");
658 expect(operations).toEqual([
659 "IssueSearchWithStatus",
660 "IssueSearch",
661 "IssueDetailWithStatus",
662 "IssueDetail",
663 ]);
664 }),
665 );
666​
667 it.effect("asks search for the labels, assignee and order a listing names", () =>
668 Effect.gen(function* () {
669 const seen: unknown[] = [];
670 const api = yield* tracker((variables) => seen.push(variables));
671 // The canned answer is not a search result; only the query sent matters here.
672 yield* api
673 .listIssues({
674 cwd: "/w",
675 host: "github.com",
676 scope: "acme/web",
677 state: "open",
678 involvement: "all",
679 labels: ['needs "repro"'],
680 assignee: "theo",
681 sort: "created",
682 limit: 10,
683 })
684 .pipe(Effect.exit);
685 expect(seen[0]).toMatchObject({
686 q: 'is:issue repo:acme/web is:open label:"needs \\"repro\\"" assignee:"theo" sort:created-desc',
687 });
688 }),
689 );
690​
691 it.effect("offers YAML issue forms when blank issues are disabled", () =>
692 Effect.gen(function* () {
693 const form = {
694 __typename: "Blob",
695 isTruncated: false,
696 text: `name: Bug report
697description: Report broken behavior.
698title: "[Bug]: "
699labels: [bug, needs-triage]
700assignees: "octocat, theo"
701body:
702 - type: markdown
703 attributes:
704 value: Search existing issues first.
705 - type: checkboxes
706 attributes:
707 label: Before submitting
708 options:
709 - label: I searched existing issues.
710 required: true
711 - type: dropdown
712 attributes:
713 label: Area
714 description: Which part is affected?
715 options: [Web, Server]
716 default: 1
717 validations:
718 required: true
719 - type: textarea
720 attributes:
721 label: Steps to reproduce
722 placeholder: Start the app.
723 - type: input
724 attributes:
725 label: Version
726 value: main
727 - type: upload
728 attributes:
729 label: Supporting files
730 description: Redact secrets before uploading.
731`,
732 };
733 const config = {
734 __typename: "Blob",
735 isTruncated: false,
736 text: '"blank_issues_enabled": false # use a template',
737 };
738 const repository = {
739 issueTemplates: [],
740 templateDirectory: {
741 __typename: "Tree",
742 entries: [
743 { name: "config.yml", object: config },
744 { name: "bug_report.yml", object: form },
745 {
746 name: "empty_name.yml",
747 object: { ...form, text: 'name: ""\ndescription: Empty name\nbody: []' },
748 },
749 {
750 name: "blank_name.yml",
751 object: { ...form, text: 'name: " "\ndescription: Blank name\nbody: []' },
752 },
753 {
754 name: "invalid.yml",
755 object: { ...form, text: "name: Missing required metadata\nbody: []" },
756 },
757 ],
758 },
759 };
760 const api = yield* tracker(() => {}, repository);
761 const input = { cwd: "/w", host: "github.com", scope: "acme/web" };
762 const result = yield* api.listTemplates!(input);
763 expect(encodeTemplateList(result)).toEqual(result);
764 expect(result.blankIssuesEnabled).toBe(false);
765 expect(result.templates).toHaveLength(1);
766 expect(result.templates[0]).toMatchObject({
767 key: "bug_report.yml",
768 name: "Bug report",
769 about: "Report broken behavior.",
770 title: "[Bug]: ",
771 labels: ["bug", "needs-triage"],
772 assignees: ["octocat", "theo"],
773 });
774 expect(result.templates[0]?.body).toBe(`Search existing issues first.
775​
776### Before submitting
777​
778- [ ] I searched existing issues. (required)
779​
780### Area
781​
782Which part is affected?
783​
784Required.
785​
786Choose one:
787​
788- Web
789- Server (default)
790​
791### Steps to reproduce
792​
793Example:
794> Start the app.
795​
796### Version
797​
798main
799​
800### Supporting files
801​
802Redact secrets before uploading.`);
803 config.isTruncated = true;
804 expect(yield* Effect.flip(api.listTemplates!(input))).toMatchObject({
805 reason: "failed",
806 detail: "GitHub returned incomplete issue template contents.",
807 });
808 }),
809 );
810​
811 it.effect("maps a detail read to the neutral issue shape", () =>
812 Effect.gen(function* () {
813 const seen: unknown[] = [];
814 const api = yield* tracker((variables) => {
815 seen.push(variables);
816 });
817 const issue = yield* api.getIssue({
818 cwd: "/w",
819 host: "github.com",
820 scope: "acme/web",
821 key: "42",
822 });
823 expect(seen).toEqual([
824 { owner: "acme", name: "web", number: 42 },
825 {
826 owner: "acme",
827 name: "web",
828 number: 42,
829 labelsCursor: "labels-next",
830 assigneesCursor: null,
831 closingPullRequestsCursor: "links-next",
832 withLabels: true,
833 withAssignees: false,
834 withClosingPullRequests: true,
835 },
836 ]);
837 expect(issue).toMatchObject({
838 key: "42",
839 displayKey: "#42",
840 title: "Composer loses focus",
841 body: "Typing in the composer drops focus after a paste.",
842 state: { category: "closed", name: "Duplicate", closeReason: "duplicate" },
843 states: [
844 { category: "open", name: "Open" },
845 { category: "closed", name: "Completed", closeReason: "completed" },
846 { category: "closed", name: "Not planned", closeReason: "not-planned" },
847 { category: "closed", name: "Duplicate", closeReason: "duplicate" },
848 ],
849 author: {
850 login: "octocat",
851 name: "Octo Cat",
852 avatarUrl: "https://avatars/octocat",
853 },
854 assignees: [{ login: "theo" }],
855 labels: [
856 { name: "bug", color: "d73a4a" },
857 { name: "needs repro", color: "ffffff" },
858 ],
859 commentCount: 3,
860 viewer: "julius",
861 // Triage may label, assign, close and reopen; `viewerCanUpdate: false` withholds edits.
862 viewerPermissions: {
863 setState: true,
864 edit: false,
865 labels: true,
866 assignees: true,
867 comment: true,
868 },
869 commentsCursor: "Y3Vyc29y",
870 });
871 // The viewer is left out of `actors` and shown as "You"; an empty group is dropped.
872 expect(issue.comments[0]?.reactions).toEqual([
873 { content: "thumbs-up", count: 2, actors: ["theo"], viewerHasReacted: true },
874 ]);
875 // The closing reference wins over the cross-reference sighting of the same pull request.
876 expect(issue.linkedPullRequests).toEqual([
877 {
878 repository: "acme/web",
879 number: 50,
880 title: "fix(web): keep composer focus",
881 url: "https://github.com/acme/web/pull/50",
882 state: "merged",
883 isDraft: false,
884 closesIssue: true,
885 },
886 // A closing reference past the first page, with no timeline sighting, still shows.
887 {
888 repository: "acme/web",
889 number: 61,
890 title: "fix(web): restore focus after paste",
891 url: "https://github.com/acme/web/pull/61",
892 state: "open",
893 isDraft: true,
894 closesIssue: true,
895 },
896 ]);
897 // An event kind this page has no vocabulary for is dropped rather than guessed at.
898 expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
899 ["labeled", "bug"],
900 ["referenced", "acme/web#50"],
901 ["closed", null],
902 ]);
903 // A cross-reference keeps what a surface needs to open its source, not only a label.
904 expect(issue.events.find((event) => event.kind === "referenced")).toMatchObject({
905 reference: {
906 repository: "acme/web",
907 number: 50,
908 kind: "pull-request",
909 url: "https://github.com/acme/web/pull/50",
910 },
911 });
912 }),
913 );
914});