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

GitLabIssueTracker.ts

800 lines27.4 KB

1/**
2 * GitLab's issue tracker over `glab api`. GitLab pages by offset, so every cursor is a page
3 * number. Notes, label events, linked merge requests and awards are separate endpoints, joined
4 * into the detail.
5 */
6import * as Effect from "effect/Effect";
7import * as Result from "effect/Result";
8import * as Schema from "effect/Schema";
9import {
10 IssueTrackerKind,
11 type IssueCapabilities,
12 type IssueEvent,
13 type IssueViewerPermissions,
14} from "@t3tools/contracts";
15import {
16 IssueTrackerError,
17 type IssueInvolvementFilter,
18 type IssueTrackerApi,
19} from "@t3tools/source-control-core/server/IssueTracker";
20​
21import * as GitLabCli from "./GitLabCli.ts";
22import {
23 decodeCreatedIssueJson,
24 decodeUserIdsJson,
25 decodeIssueDetailListJson,
26 decodeIssueListJson,
27 decodeIssueNotesJson,
28 decodeLabelEventsJson,
29 decodeLinkedMergeRequestsJson,
30 decodeProjectLabelsJson,
31 decodeProjectMembersJson,
32 decodeTemplateEntriesJson,
33 decodeTemplateJson,
34 ISSUE_AWARD_EMOJI_GRAPHQL_QUERY,
35 ISSUE_STATES,
36 PAGE_SIZE,
37 type GitLabTemplateEntry,
38} from "./gitLabIssueJson.ts";
39import {
40 awardReactions,
41 decodeAwardEmojiJson,
42 decodeAwardListJson,
43 decodeOwnAwardIdJson,
44 decodeViewerJson,
45 gitLabAwardName,
46} from "./gitLabMergeRequestJson.ts";
47​
48const KIND = IssueTrackerKind.make("gitlab");
49/** How many pages of system notes the timeline reads before giving up on the rest. */
50const MAX_ACTIVITY_PAGES = 20;
51​
52const CAPABILITIES: IssueCapabilities = {
53 create: true,
54 edit: true,
55 comment: true,
56 labels: true,
57 assignees: true,
58 reactions: true,
59 templates: true,
60 linkedPullRequests: true,
61 events: true,
62 search: true,
63};
64​
65/**
66 * Everything granted. GitLab's REST API reports the viewer's role on the project but never whether
67 * they opened this issue, and an issue's author may close, reopen and edit it whatever their role.
68 * Withholding those controls from the one person entitled to them is the worse mistake, so they
69 * are offered and GitLab explains any refusal itself.
70 */
71const VIEWER_PERMISSIONS: IssueViewerPermissions = {
72 setState: true,
73 comment: true,
74 edit: true,
75 labels: true,
76 assignees: true,
77};
78​
79/** How many of a scope's templates are read in full; each one is a request of its own. */
80const TEMPLATE_LIMIT = 20;
81​
82const encodeBody = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
83​
84/** The REST API addresses a project by its URL-encoded full path. */
85function projectPath(scope: string): string {
86 return encodeURIComponent(scope.trim());
88​
89/** An issue key is its iid; anything else names no GitLab issue. */
90function parseNumber(key: string): number | null {
91 return /^[1-9]\d*$/.test(key) ? Number(key) : null;
93​
94/** A page cursor this tracker handed out, or null for anything it could not have issued. */
95function parsePage(cursor: string | undefined): number | null {
96 if (cursor === undefined) return 1;
97 return /^[1-9]\d{0,6}$/.test(cursor) ? Number(cursor) : null;
99​
100/**
101 * A comments cursor: the next REST page of notes and, after a colon, where GraphQL's awards for
102 * that page start. The two page alike, so a page of comments is joined with its own awards.
103 */
104function parseCommentsCursor(
105 cursor: string,
106): { readonly page: number; readonly awards: string | null } | null {
107 const match = /^([1-9]\d{0,6})(?::(.{1,512}))?$/.exec(cursor);
108 return match === null ? null : { page: Number(match[1]), awards: match[2] ?? null };
110​
111function commentsCursor(notesNext: string | null, awardsNext: string | null): string | null {
112 if (notesNext === null) return null;
113 return awardsNext === null ? notesNext : `${notesNext}:${awardsNext}`;
115​
116/**
117 * `glab api --include` output split into the body and GitLab's next page. GitLab can return a
118 * short page when it hides notes the viewer may not see, so only `X-Next-Page` says whether more
119 * exists; without headers a full page is taken as the sign.
120 */
121function splitPagedResponse(raw: string): {
122 readonly body: string;
123 readonly nextPage: number | null | undefined;
124} {
125 if (!raw.startsWith("HTTP/")) return { body: raw, nextPage: undefined };
126 const end = /\r?\n\r?\n/.exec(raw);
127 const headers = end === null ? raw : raw.slice(0, end.index);
128 const body = end === null ? "" : raw.slice(end.index + end[0].length);
129 const next = /^x-next-page:[ \t]*([1-9]\d{0,6})?[ \t]*\r?$/im.exec(headers);
130 return {
131 body,
132 nextPage: next === null ? undefined : next[1] === undefined ? null : Number(next[1]),
133 };
135​
136function query(params: ReadonlyArray<readonly [string, string]>): string {
137 return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
139​
140function involvementParams(
141 input: IssueInvolvementFilter & { readonly assignee?: string | undefined },
142): ReadonlyArray<readonly [string, string]> {
143 switch (input.involvement) {
144 case "authored":
145 return [["author_username", input.viewer]];
146 case "assigned":
147 // A named assignee takes the one assignee parameter GitLab reads; `listIssues` keeps the
148 // viewer by dropping rows.
149 return input.assignee === undefined ? [["assignee_username", input.viewer]] : [];
150 // GitLab's `my_reaction_emoji` and `iteration` filters aside, nothing narrows to mentions, so
151 // the listing stays as wide as `all` rather than guessing.
152 case "mentioned":
153 case "all":
154 return [];
155 }
157​
158function reasonFor(error: GitLabCli.GitLabCliError): IssueTrackerError["reason"] {
159 switch (error._tag) {
160 case "GitLabCliUnavailableError":
161 return "missing-tool";
162 case "GitLabCliAuthenticationError":
163 return "unauthenticated";
164 case "GitLabCliRateLimitError":
165 return "rate-limited";
166 default:
167 return "failed";
168 }
170​
171export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> = Effect.gen(
172 function* () {
173 const gitlab = yield* GitLabCli.GitLabCli;
174​
175 const fail = (operation: string) => (error: GitLabCli.GitLabCliError) =>
176 new IssueTrackerError({
177 tracker: KIND,
178 operation,
179 reason: reasonFor(error),
180 detail: error.detail,
181 cause: error,
182 });
183​
184 const unreadable = (operation: string, cause: unknown) =>
185 new IssueTrackerError({
186 tracker: KIND,
187 operation,
188 reason: "failed",
189 detail: `GitLab returned an unreadable ${operation} response.`,
190 cause,
191 });
192​
193 const notFound = (operation: string) =>
194 new IssueTrackerError({
195 tracker: KIND,
196 operation,
197 reason: "not-found",
198 detail: "GitLab could not find the requested issue.",
199 });
200​
201 const refused = (operation: string, detail: string) =>
202 new IssueTrackerError({ tracker: KIND, operation, reason: "failed", detail });
203​
204 const api = (input: {
205 readonly cwd: string;
206 readonly host: string;
207 readonly operation: string;
208 readonly path: string;
209 readonly method?: string;
210 readonly body?: unknown;
211 readonly includeHeaders?: boolean;
212 }) =>
213 gitlab
214 .execute({
215 cwd: input.cwd,
216 host: input.host,
217 args: [
218 "api",
219 input.path,
220 ...(input.includeHeaders === true ? ["--include"] : []),
221 ...(input.method === undefined ? [] : ["--method", input.method]),
222 // A JSON body from stdin: argv is visible in process listings, and `glab api --input`
223 // sends no Content-Type of its own, which GitLab answers with HTTP 415.
224 ...(input.body === undefined
225 ? []
226 : ["--input", "-", "--header", "Content-Type: application/json"]),
227 ],
228 ...(input.body === undefined ? {} : { stdin: encodeBody(input.body) }),
229 })
230 .pipe(
231 Effect.map((result) => result.stdout.trim()),
232 Effect.mapError(fail(input.operation)),
233 );
234​
235 const read = <A>(input: {
236 readonly cwd: string;
237 readonly host: string;
238 readonly operation: string;
239 readonly path: string;
240 readonly method?: string;
241 readonly body?: unknown;
242 readonly includeHeaders?: boolean;
243 readonly decode: (raw: string) => Result.Result<A, unknown>;
244 }): Effect.Effect<A, IssueTrackerError> =>
245 api(input).pipe(
246 Effect.flatMap((raw) => {
247 const decoded = input.decode(raw);
248 return Result.isSuccess(decoded)
249 ? Effect.succeed(decoded.success)
250 : Effect.fail(unreadable(input.operation, decoded.failure));
251 }),
252 );
253​
254 const write = (input: {
255 readonly cwd: string;
256 readonly host: string;
257 readonly operation: string;
258 readonly path: string;
259 readonly method: string;
260 readonly body?: unknown;
261 }) => api(input).pipe(Effect.asVoid);
262​
263 /** The signed-in account; an answer naming nobody is a failure, since every comparison needs a login. */
264 const viewer = (input: {
265 readonly cwd: string;
266 readonly host: string;
267 readonly operation: string;
268 }): Effect.Effect<string, IssueTrackerError> =>
269 read({
270 cwd: input.cwd,
271 host: input.host,
272 operation: input.operation,
273 path: "user",
274 decode: decodeViewerJson,
275 }).pipe(
276 Effect.filterOrFail(
277 (login) => login !== null,
278 () => refused(input.operation, "GitLab returned no username for the signed-in account."),
279 ),
280 );
281​
282 /** The issue as REST addresses it, or a not-found for a key that names no iid. */
283 const issuePath = (
284 input: { readonly scope: string; readonly key: string },
285 operation: string,
286 ): Effect.Effect<{ readonly number: number; readonly path: string }, IssueTrackerError> => {
287 const number = parseNumber(input.key);
288 return number === null
289 ? Effect.fail(notFound(operation))
290 : Effect.succeed({ number, path: `projects/${projectPath(input.scope)}/issues/${number}` });
291 };
292​
293 /**
294 * GitLab writes assignees by numeric id, which is what the candidates carry as `id`. An issue
295 * names the people it already has by username, so a kept assignee is looked up.
296 */
297 const assigneeIds = (
298 input: { readonly cwd: string; readonly host: string },
299 operation: string,
300 assignees: ReadonlyArray<string>,
301 ): Effect.Effect<ReadonlyArray<number>, IssueTrackerError> =>
302 Effect.forEach(assignees, (assignee) =>
303 /^[1-9]\d*$/.test(assignee)
304 ? Effect.succeed(Number(assignee))
305 : read({
306 cwd: input.cwd,
307 host: input.host,
308 operation,
309 path: `users?${query([["username", assignee]])}`,
310 decode: decodeUserIdsJson,
311 }).pipe(
312 Effect.flatMap(([id]) =>
313 id === undefined
314 ? Effect.fail(refused(operation, `GitLab has no user named ${assignee}.`))
315 : Effect.succeed(id),
316 ),
317 ),
318 );
319​
320 const paged = (path: string, page: number) =>
321 `${path}?${query([
322 ["per_page", String(PAGE_SIZE)],
323 ["page", String(page)],
324 ])}`;
325​
326 const notesPage = (input: {
327 readonly cwd: string;
328 readonly host: string;
329 readonly path: string;
330 readonly page: number;
331 readonly operation: string;
332 readonly onlyActivity?: boolean;
333 }) =>
334 read({
335 cwd: input.cwd,
336 host: input.host,
337 operation: input.operation,
338 path: `${input.path}/notes?${query([
339 ["per_page", String(PAGE_SIZE)],
340 ["page", String(input.page)],
341 ["order_by", "created_at"],
342 ["sort", "asc"],
343 ...(input.onlyActivity === true ? [["activity_filter", "only_activity"] as const] : []),
344 ])}`,
345 includeHeaders: true,
346 decode: (raw) => {
347 const { body, nextPage } = splitPagedResponse(raw);
348 return Result.map(decodeIssueNotesJson(body), (notes) => {
349 const next =
350 nextPage === undefined
351 ? notes.rawCount < PAGE_SIZE
352 ? null
353 : input.page + 1
354 : nextPage;
355 return { ...notes, nextCursor: next === null ? null : String(next) };
356 });
357 },
358 });
359​
360 /** Every system note, wherever it falls among the comments, for the issue's timeline. */
361 const activity = Effect.fn("GitLabIssueTracker.activity")(function* (input: {
362 readonly cwd: string;
363 readonly host: string;
364 readonly path: string;
365 }) {
366 const events: Array<IssueEvent> = [];
367 let page = 1;
368 for (let count = 0; count < MAX_ACTIVITY_PAGES; count++) {
369 const notes = yield* notesPage({
370 ...input,
371 page,
372 operation: "getIssue",
373 onlyActivity: true,
374 });
375 events.push(...notes.events);
376 if (notes.nextCursor === null) break;
377 page = Number(notes.nextCursor);
378 }
379 return events;
380 });
381​
382 const awards = (input: {
383 readonly cwd: string;
384 readonly host: string;
385 readonly scope: string;
386 readonly number: number;
387 readonly operation: string;
388 readonly cursor?: string | undefined;
389 }) =>
390 read({
391 cwd: input.cwd,
392 host: input.host,
393 operation: input.operation,
394 path: "graphql",
395 method: "POST",
396 body: {
397 query: ISSUE_AWARD_EMOJI_GRAPHQL_QUERY,
398 variables: {
399 fullPath: input.scope.trim(),
400 iid: String(input.number),
401 cursor: input.cursor ?? null,
402 },
403 },
404 decode: decodeAwardEmojiJson,
405 });
406​
407 const linked = (input: {
408 readonly cwd: string;
409 readonly host: string;
410 readonly path: string;
411 readonly endpoint: "closed_by" | "related_merge_requests";
412 }) =>
413 read({
414 cwd: input.cwd,
415 host: input.host,
416 operation: "getIssue",
417 path: paged(`${input.path}/${input.endpoint}`, 1),
418 decode: (raw) => decodeLinkedMergeRequestsJson(raw, input.endpoint === "closed_by"),
419 });
420​
421 const template =
422 (input: { readonly cwd: string; readonly host: string; readonly scope: string }) =>
423 (entry: GitLabTemplateEntry) =>
424 read({
425 cwd: input.cwd,
426 host: input.host,
427 operation: "listTemplates",
428 path: `projects/${projectPath(input.scope)}/templates/issues/${encodeURIComponent(entry.key)}`,
429 decode: (raw) => decodeTemplateJson(entry, raw),
430 });
431​
432 return {
433 kind: KIND,
434 capabilities: CAPABILITIES,
435​
436 getViewer: (input) => viewer({ cwd: input.cwd, host: input.host, operation: "getViewer" }),
437​
438 listIssues: Effect.fn("GitLabIssueTracker.listIssues")(function* (input) {
439 const page = parsePage(input.cursor);
440 if (page === null) {
441 return yield* refused("listIssues", "The cursor was not one GitLab handed out.");
442 }
443 const perPage = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
444 const text = input.query?.trim() ?? "";
445 const alsoAssignedTo =
446 input.involvement === "assigned" && input.assignee !== undefined
447 ? input.viewer.toLowerCase()
448 : null;
449 return yield* read({
450 cwd: input.cwd,
451 host: input.host,
452 operation: "listIssues",
453 path: `projects/${projectPath(input.scope)}/issues?${query([
454 ["state", input.state === "open" ? "opened" : input.state],
455 ...involvementParams(input),
456 // GitLab's own `search` matches title and description, URL-encoded like every other
457 // value here, so no text in it can become a parameter of its own.
458 ...(text.length === 0 ? [] : [["search", text] as const]),
459 ...(input.labels === undefined || input.labels.length === 0
460 ? []
461 : [["labels", input.labels.join(",")] as const]),
462 ...(input.assignee === undefined
463 ? []
464 : [["assignee_username", input.assignee] as const]),
465 ["order_by", input.sort === "created" ? "created_at" : "updated_at"],
466 ["sort", "desc"],
467 ["with_labels_details", "true"],
468 ["per_page", String(perPage)],
469 ["page", String(page)],
470 ])}`,
471 decode: decodeIssueListJson,
472 }).pipe(
473 Effect.map((list) => ({
474 items:
475 alsoAssignedTo === null
476 ? list.items
477 : list.items.filter((issue) =>
478 issue.assignees.some((actor) => actor.login.toLowerCase() === alsoAssignedTo),
479 ),
480 nextCursor: list.rawCount < perPage ? null : String(page + 1),
481 })),
482 );
483 }),
484​
485 getIssue: (input) =>
486 issuePath(input, "getIssue").pipe(
487 Effect.flatMap(({ number, path }) =>
488 Effect.all(
489 [
490 read({
491 cwd: input.cwd,
492 host: input.host,
493 operation: "getIssue",
494 path: `projects/${projectPath(input.scope)}/issues?${query([
495 ["iids[]", String(number)],
496 ["with_labels_details", "true"],
497 ["per_page", "1"],
498 ])}`,
499 decode: decodeIssueDetailListJson,
500 }).pipe(
501 Effect.filterOrFail(
502 (issue) => issue !== null,
503 () => notFound("getIssue"),
504 ),
505 ),
506 viewer({ cwd: input.cwd, host: input.host, operation: "getIssue" }),
507 notesPage({
508 cwd: input.cwd,
509 host: input.host,
510 path,
511 page: 1,
512 operation: "getIssue",
513 }),
514 activity({ cwd: input.cwd, host: input.host, path }),
515 read({
516 cwd: input.cwd,
517 host: input.host,
518 operation: "getIssue",
519 path: paged(`${path}/resource_label_events`, 1),
520 decode: decodeLabelEventsJson,
521 }),
522 linked({ cwd: input.cwd, host: input.host, path, endpoint: "closed_by" }),
523 linked({
524 cwd: input.cwd,
525 host: input.host,
526 path,
527 endpoint: "related_merge_requests",
528 }),
529 awards({
530 cwd: input.cwd,
531 host: input.host,
532 scope: input.scope,
533 number,
534 operation: "getIssue",
535 }),
536 read({
537 cwd: input.cwd,
538 host: input.host,
539 operation: "getIssue",
540 path: paged(`${path}/award_emoji`, 1),
541 decode: decodeAwardListJson,
542 }),
543 ],
544 { concurrency: 4 },
545 ),
546 ),
547 Effect.map(
548 ([
549 issue,
550 viewerLogin,
551 notes,
552 systemEvents,
553 labelEvents,
554 closing,
555 related,
556 awardPage,
557 issueAwards,
558 ]) => {
559 const closingKeys = new Set(
560 closing.map((link) => `${link.repository}!${link.number}`),
561 );
562 return {
563 ...issue,
564 viewer: viewerLogin,
565 viewerPermissions: VIEWER_PERMISSIONS,
566 states: ISSUE_STATES,
567 reactions: awardReactions(issueAwards, viewerLogin),
568 comments: notes.comments.map((comment) => ({
569 ...comment,
570 reactions: awardPage.reactionsByNoteId.get(comment.id) ?? [],
571 })),
572 commentsCursor: commentsCursor(notes.nextCursor, awardPage.nextCursor),
573 events: [...systemEvents, ...labelEvents].sort((left, right) =>
574 left.createdAt.localeCompare(right.createdAt),
575 ),
576 // A merge request that closes the issue outranks its sighting as a mere mention.
577 linkedPullRequests: [
578 ...closing,
579 ...related.filter(
580 (link) => !closingKeys.has(`${link.repository}!${link.number}`),
581 ),
582 ],
583 };
584 },
585 ),
586 ),
587​
588 getComments: (input) => {
589 const cursor = parseCommentsCursor(input.cursor);
590 return cursor === null
591 ? Effect.fail(refused("getComments", "The cursor was not one GitLab handed out."))
592 : issuePath(input, "getComments").pipe(
593 Effect.flatMap(({ number, path }) =>
594 Effect.all(
595 [
596 notesPage({
597 cwd: input.cwd,
598 host: input.host,
599 path,
600 page: cursor.page,
601 operation: "getComments",
602 }),
603 // Without its awards cursor a later page's awards cannot be found.
604 cursor.awards === null && cursor.page > 1
605 ? Effect.succeed(null)
606 : awards({
607 cwd: input.cwd,
608 host: input.host,
609 scope: input.scope,
610 number,
611 operation: "getComments",
612 cursor: cursor.awards ?? undefined,
613 }),
614 ],
615 { concurrency: 2 },
616 ),
617 ),
618 Effect.map(([notes, awardPage]) => ({
619 comments: notes.comments.map((comment) => ({
620 ...comment,
621 reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [],
622 })),
623 nextCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null),
624 })),
625 );
626 },
627​
628 create: (input) =>
629 assigneeIds(input, "create", input.assignees).pipe(
630 Effect.flatMap((assignee_ids) =>
631 read({
632 cwd: input.cwd,
633 host: input.host,
634 operation: "create",
635 path: `projects/${projectPath(input.scope)}/issues`,
636 method: "POST",
637 body: {
638 title: input.title,
639 description: input.body,
640 labels: input.labels.join(","),
641 assignee_ids,
642 },
643 decode: decodeCreatedIssueJson,
644 }),
645 ),
646 Effect.map((issue) => ({
647 key: String(issue.number),
648 displayKey: `#${issue.number}`,
649 url: issue.url,
650 })),
651 ),
652​
653 comment: (input) =>
654 issuePath(input, "comment").pipe(
655 Effect.flatMap(({ path }) =>
656 write({
657 cwd: input.cwd,
658 host: input.host,
659 operation: "comment",
660 path: `${path}/notes`,
661 method: "POST",
662 body: { body: input.body },
663 }),
664 ),
665 ),
666​
667 update: (input) =>
668 Effect.all([
669 issuePath(input, "update"),
670 input.assignees === undefined
671 ? Effect.void
672 : assigneeIds(input, "update", input.assignees),
673 ]).pipe(
674 Effect.flatMap(([{ path }, assignee_ids]) =>
675 write({
676 cwd: input.cwd,
677 host: input.host,
678 operation: "update",
679 path,
680 method: "PUT",
681 body: {
682 ...(input.title === undefined ? {} : { title: input.title }),
683 ...(input.body === undefined ? {} : { description: input.body }),
684 ...(input.labels === undefined ? {} : { labels: input.labels.join(",") }),
685 ...(assignee_ids === undefined ? {} : { assignee_ids }),
686 },
687 }),
688 ),
689 ),
690​
691 setState: (input) => {
692 const wanted = ISSUE_STATES.find((state) => state.name === input.state);
693 if (wanted === undefined) {
694 return Effect.fail(refused("setState", `A GitLab issue has no "${input.state}" state.`));
695 }
696 return issuePath(input, "setState").pipe(
697 Effect.flatMap(({ path }) =>
698 write({
699 cwd: input.cwd,
700 host: input.host,
701 operation: "setState",
702 path,
703 method: "PUT",
704 body: { state_event: wanted.category === "closed" ? "close" : "reopen" },
705 }),
706 ),
707 );
708 },
709​
710 setReaction: Effect.fn("GitLabIssueTracker.setReaction")(function* (input) {
711 const { path } = yield* issuePath(input, "setReaction");
712 if (input.subjectId !== undefined && !/^[1-9]\d*$/.test(input.subjectId)) {
713 return yield* refused("setReaction", "The comment id names no GitLab note.");
714 }
715 const subject =
716 input.subjectId === undefined
717 ? `${path}/award_emoji`
718 : `${path}/notes/${input.subjectId}/award_emoji`;
719 if (input.reacted) {
720 return yield* write({
721 cwd: input.cwd,
722 host: input.host,
723 operation: "setReaction",
724 path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
725 method: "POST",
726 });
727 }
728 // GitLab deletes an award by its id and takes no emoji name there, so the reader's own
729 // award of that name is looked up first. Nothing to delete is success.
730 const login = yield* viewer({
731 cwd: input.cwd,
732 host: input.host,
733 operation: "setReaction",
734 });
735 for (let page = 1; ; page++) {
736 const own = yield* read({
737 cwd: input.cwd,
738 host: input.host,
739 operation: "setReaction",
740 path: paged(subject, page),
741 decode: (raw) => decodeOwnAwardIdJson(raw, { content: input.content, viewer: login }),
742 });
743 if (own.id !== null) {
744 return yield* write({
745 cwd: input.cwd,
746 host: input.host,
747 operation: "setReaction",
748 path: `${subject}/${own.id}`,
749 method: "DELETE",
750 });
751 }
752 // An empty raw page establishes exhaustion even when the host caps page size.
753 if (own.empty) return;
754 }
755 }),
756​
757 listTemplates: (input) =>
758 read({
759 cwd: input.cwd,
760 host: input.host,
761 operation: "listTemplates",
762 path: `projects/${projectPath(input.scope)}/templates/issues`,
763 decode: decodeTemplateEntriesJson,
764 }).pipe(
765 Effect.flatMap((entries) =>
766 Effect.forEach(entries.slice(0, TEMPLATE_LIMIT), template(input), { concurrency: 4 }),
767 ),
768 // GitLab has no switch that forbids an issue filed from nothing.
769 Effect.map((templates) => ({ templates, blankIssuesEnabled: true })),
770 ),
771​
772 listCandidates: (input) =>
773 Effect.all(
774 [
775 read({
776 cwd: input.cwd,
777 host: input.host,
778 operation: "listCandidates",
779 path: paged(`projects/${projectPath(input.scope)}/labels`, 1),
780 decode: decodeProjectLabelsJson,
781 }),
782 read({
783 cwd: input.cwd,
784 host: input.host,
785 operation: "listCandidates",
786 path: paged(`projects/${projectPath(input.scope)}/members/all`, 1),
787 decode: decodeProjectMembersJson,
788 }),
789 ],
790 { concurrency: 2 },
791 ).pipe(
792 Effect.map(([labels, assignees]) => ({
793 labels,
794 assignees,
795 truncated: labels.length >= PAGE_SIZE || assignees.length >= PAGE_SIZE,
796 })),
797 ),
798 };
799 },
800);