@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 806 lines 27.7 KB
Raw
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 */
6 import * as Effect from "effect/Effect";
7 import * as Result from "effect/Result";
8 import * as Schema from "effect/Schema";
9 import {
10 IssueTrackerKind,
11 type IssueCapabilities,
12 type IssueEvent,
13 type IssueViewerPermissions,
14 } from "@t3tools/contracts";
15 import {
16 IssueTrackerError,
17 type IssueInvolvementFilter,
18 type IssueTrackerApi,
19 } from "@t3tools/source-control-core/server/IssueTracker";
20
21 import * as GitLabCli from "./GitLabCli.ts";
22 import {
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";
39 import {
40 awardReactions,
41 decodeAwardEmojiJson,
42 decodeAwardListJson,
43 decodeOwnAwardIdJson,
44 decodeViewerJson,
45 gitLabAwardName,
46 } from "./gitLabMergeRequestJson.ts";
47
48 const KIND = IssueTrackerKind.make("gitlab");
49 /** How many pages of system notes the timeline reads before giving up on the rest. */
50 const MAX_ACTIVITY_PAGES = 20;
51
52 const 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 */
71 const 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. */
80 const TEMPLATE_LIMIT = 20;
81
82 const encodeBody = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
83
84 /** The REST API addresses a project by its URL-encoded full path. */
85 function projectPath(scope: string): string {
86 return encodeURIComponent(scope.trim());
87 }
88
89 /** An issue key is its iid; anything else names no GitLab issue. */
90 function parseNumber(key: string): number | null {
91 return /^[1-9]\d*$/.test(key) ? Number(key) : null;
92 }
93
94 /** A page cursor this tracker handed out, or null for anything it could not have issued. */
95 function parsePage(cursor: string | undefined): number | null {
96 if (cursor === undefined) return 1;
97 return /^[1-9]\d{0,6}$/.test(cursor) ? Number(cursor) : null;
98 }
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 */
104 function 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 };
109 }
110
111 function commentsCursor(notesNext: string | null, awardsNext: string | null): string | null {
112 if (notesNext === null) return null;
113 return awardsNext === null ? notesNext : `${notesNext}:${awardsNext}`;
114 }
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 */
121 function 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 };
134 }
135
136 function query(params: ReadonlyArray<readonly [string, string]>): string {
137 return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
138 }
139
140 function 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 }
156 }
157
158 function 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 }
169 }
170
171 export 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 }).pipe(
406 // GitLab before 16.1 has no `Note.awardEmoji`; comments then load without reactions.
407 Effect.catchIf(
408 (error) => error.reason === "failed",
409 () => Effect.succeed(null),
410 ),
411 );
412
413 const linked = (input: {
414 readonly cwd: string;
415 readonly host: string;
416 readonly path: string;
417 readonly endpoint: "closed_by" | "related_merge_requests";
418 }) =>
419 read({
420 cwd: input.cwd,
421 host: input.host,
422 operation: "getIssue",
423 path: paged(`${input.path}/${input.endpoint}`, 1),
424 decode: (raw) => decodeLinkedMergeRequestsJson(raw, input.endpoint === "closed_by"),
425 });
426
427 const template =
428 (input: { readonly cwd: string; readonly host: string; readonly scope: string }) =>
429 (entry: GitLabTemplateEntry) =>
430 read({
431 cwd: input.cwd,
432 host: input.host,
433 operation: "listTemplates",
434 path: `projects/${projectPath(input.scope)}/templates/issues/${encodeURIComponent(entry.key)}`,
435 decode: (raw) => decodeTemplateJson(entry, raw),
436 });
437
438 return {
439 kind: KIND,
440 capabilities: CAPABILITIES,
441
442 getViewer: (input) => viewer({ cwd: input.cwd, host: input.host, operation: "getViewer" }),
443
444 listIssues: Effect.fn("GitLabIssueTracker.listIssues")(function* (input) {
445 const page = parsePage(input.cursor);
446 if (page === null) {
447 return yield* refused("listIssues", "The cursor was not one GitLab handed out.");
448 }
449 const perPage = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
450 const text = input.query?.trim() ?? "";
451 const alsoAssignedTo =
452 input.involvement === "assigned" && input.assignee !== undefined
453 ? input.viewer.toLowerCase()
454 : null;
455 return yield* read({
456 cwd: input.cwd,
457 host: input.host,
458 operation: "listIssues",
459 path: `projects/${projectPath(input.scope)}/issues?${query([
460 ["state", input.state === "open" ? "opened" : input.state],
461 ...involvementParams(input),
462 // GitLab's own `search` matches title and description, URL-encoded like every other
463 // value here, so no text in it can become a parameter of its own.
464 ...(text.length === 0 ? [] : [["search", text] as const]),
465 ...(input.labels === undefined || input.labels.length === 0
466 ? []
467 : [["labels", input.labels.join(",")] as const]),
468 ...(input.assignee === undefined
469 ? []
470 : [["assignee_username", input.assignee] as const]),
471 ["order_by", input.sort === "created" ? "created_at" : "updated_at"],
472 ["sort", "desc"],
473 ["with_labels_details", "true"],
474 ["per_page", String(perPage)],
475 ["page", String(page)],
476 ])}`,
477 decode: decodeIssueListJson,
478 }).pipe(
479 Effect.map((list) => ({
480 items:
481 alsoAssignedTo === null
482 ? list.items
483 : list.items.filter((issue) =>
484 issue.assignees.some((actor) => actor.login.toLowerCase() === alsoAssignedTo),
485 ),
486 nextCursor: list.rawCount < perPage ? null : String(page + 1),
487 })),
488 );
489 }),
490
491 getIssue: (input) =>
492 issuePath(input, "getIssue").pipe(
493 Effect.flatMap(({ number, path }) =>
494 Effect.all(
495 [
496 read({
497 cwd: input.cwd,
498 host: input.host,
499 operation: "getIssue",
500 path: `projects/${projectPath(input.scope)}/issues?${query([
501 ["iids[]", String(number)],
502 ["with_labels_details", "true"],
503 ["per_page", "1"],
504 ])}`,
505 decode: decodeIssueDetailListJson,
506 }).pipe(
507 Effect.filterOrFail(
508 (issue) => issue !== null,
509 () => notFound("getIssue"),
510 ),
511 ),
512 viewer({ cwd: input.cwd, host: input.host, operation: "getIssue" }),
513 notesPage({
514 cwd: input.cwd,
515 host: input.host,
516 path,
517 page: 1,
518 operation: "getIssue",
519 }),
520 activity({ cwd: input.cwd, host: input.host, path }),
521 read({
522 cwd: input.cwd,
523 host: input.host,
524 operation: "getIssue",
525 path: paged(`${path}/resource_label_events`, 1),
526 decode: decodeLabelEventsJson,
527 }),
528 linked({ cwd: input.cwd, host: input.host, path, endpoint: "closed_by" }),
529 linked({
530 cwd: input.cwd,
531 host: input.host,
532 path,
533 endpoint: "related_merge_requests",
534 }),
535 awards({
536 cwd: input.cwd,
537 host: input.host,
538 scope: input.scope,
539 number,
540 operation: "getIssue",
541 }),
542 read({
543 cwd: input.cwd,
544 host: input.host,
545 operation: "getIssue",
546 path: paged(`${path}/award_emoji`, 1),
547 decode: decodeAwardListJson,
548 }),
549 ],
550 { concurrency: 4 },
551 ),
552 ),
553 Effect.map(
554 ([
555 issue,
556 viewerLogin,
557 notes,
558 systemEvents,
559 labelEvents,
560 closing,
561 related,
562 awardPage,
563 issueAwards,
564 ]) => {
565 const closingKeys = new Set(
566 closing.map((link) => `${link.repository}!${link.number}`),
567 );
568 return {
569 ...issue,
570 viewer: viewerLogin,
571 viewerPermissions: VIEWER_PERMISSIONS,
572 states: ISSUE_STATES,
573 reactions: awardReactions(issueAwards, viewerLogin),
574 comments: notes.comments.map((comment) => ({
575 ...comment,
576 reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [],
577 })),
578 commentsCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null),
579 events: [...systemEvents, ...labelEvents].sort((left, right) =>
580 left.createdAt.localeCompare(right.createdAt),
581 ),
582 // A merge request that closes the issue outranks its sighting as a mere mention.
583 linkedPullRequests: [
584 ...closing,
585 ...related.filter(
586 (link) => !closingKeys.has(`${link.repository}!${link.number}`),
587 ),
588 ],
589 };
590 },
591 ),
592 ),
593
594 getComments: (input) => {
595 const cursor = parseCommentsCursor(input.cursor);
596 return cursor === null
597 ? Effect.fail(refused("getComments", "The cursor was not one GitLab handed out."))
598 : issuePath(input, "getComments").pipe(
599 Effect.flatMap(({ number, path }) =>
600 Effect.all(
601 [
602 notesPage({
603 cwd: input.cwd,
604 host: input.host,
605 path,
606 page: cursor.page,
607 operation: "getComments",
608 }),
609 // Without its awards cursor a later page's awards cannot be found.
610 cursor.awards === null && cursor.page > 1
611 ? Effect.succeed(null)
612 : awards({
613 cwd: input.cwd,
614 host: input.host,
615 scope: input.scope,
616 number,
617 operation: "getComments",
618 cursor: cursor.awards ?? undefined,
619 }),
620 ],
621 { concurrency: 2 },
622 ),
623 ),
624 Effect.map(([notes, awardPage]) => ({
625 comments: notes.comments.map((comment) => ({
626 ...comment,
627 reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [],
628 })),
629 nextCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null),
630 })),
631 );
632 },
633
634 create: (input) =>
635 assigneeIds(input, "create", input.assignees).pipe(
636 Effect.flatMap((assignee_ids) =>
637 read({
638 cwd: input.cwd,
639 host: input.host,
640 operation: "create",
641 path: `projects/${projectPath(input.scope)}/issues`,
642 method: "POST",
643 body: {
644 title: input.title,
645 description: input.body,
646 labels: input.labels.join(","),
647 assignee_ids,
648 },
649 decode: decodeCreatedIssueJson,
650 }),
651 ),
652 Effect.map((issue) => ({
653 key: String(issue.number),
654 displayKey: `#${issue.number}`,
655 url: issue.url,
656 })),
657 ),
658
659 comment: (input) =>
660 issuePath(input, "comment").pipe(
661 Effect.flatMap(({ path }) =>
662 write({
663 cwd: input.cwd,
664 host: input.host,
665 operation: "comment",
666 path: `${path}/notes`,
667 method: "POST",
668 body: { body: input.body },
669 }),
670 ),
671 ),
672
673 update: (input) =>
674 Effect.all([
675 issuePath(input, "update"),
676 input.assignees === undefined
677 ? Effect.void
678 : assigneeIds(input, "update", input.assignees),
679 ]).pipe(
680 Effect.flatMap(([{ path }, assignee_ids]) =>
681 write({
682 cwd: input.cwd,
683 host: input.host,
684 operation: "update",
685 path,
686 method: "PUT",
687 body: {
688 ...(input.title === undefined ? {} : { title: input.title }),
689 ...(input.body === undefined ? {} : { description: input.body }),
690 ...(input.labels === undefined ? {} : { labels: input.labels.join(",") }),
691 ...(assignee_ids === undefined ? {} : { assignee_ids }),
692 },
693 }),
694 ),
695 ),
696
697 setState: (input) => {
698 const wanted = ISSUE_STATES.find((state) => state.name === input.state);
699 if (wanted === undefined) {
700 return Effect.fail(refused("setState", `A GitLab issue has no "${input.state}" state.`));
701 }
702 return issuePath(input, "setState").pipe(
703 Effect.flatMap(({ path }) =>
704 write({
705 cwd: input.cwd,
706 host: input.host,
707 operation: "setState",
708 path,
709 method: "PUT",
710 body: { state_event: wanted.category === "closed" ? "close" : "reopen" },
711 }),
712 ),
713 );
714 },
715
716 setReaction: Effect.fn("GitLabIssueTracker.setReaction")(function* (input) {
717 const { path } = yield* issuePath(input, "setReaction");
718 if (input.subjectId !== undefined && !/^[1-9]\d*$/.test(input.subjectId)) {
719 return yield* refused("setReaction", "The comment id names no GitLab note.");
720 }
721 const subject =
722 input.subjectId === undefined
723 ? `${path}/award_emoji`
724 : `${path}/notes/${input.subjectId}/award_emoji`;
725 if (input.reacted) {
726 return yield* write({
727 cwd: input.cwd,
728 host: input.host,
729 operation: "setReaction",
730 path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
731 method: "POST",
732 });
733 }
734 // GitLab deletes an award by its id and takes no emoji name there, so the reader's own
735 // award of that name is looked up first. Nothing to delete is success.
736 const login = yield* viewer({
737 cwd: input.cwd,
738 host: input.host,
739 operation: "setReaction",
740 });
741 for (let page = 1; ; page++) {
742 const own = yield* read({
743 cwd: input.cwd,
744 host: input.host,
745 operation: "setReaction",
746 path: paged(subject, page),
747 decode: (raw) => decodeOwnAwardIdJson(raw, { content: input.content, viewer: login }),
748 });
749 if (own.id !== null) {
750 return yield* write({
751 cwd: input.cwd,
752 host: input.host,
753 operation: "setReaction",
754 path: `${subject}/${own.id}`,
755 method: "DELETE",
756 });
757 }
758 // An empty raw page establishes exhaustion even when the host caps page size.
759 if (own.empty) return;
760 }
761 }),
762
763 listTemplates: (input) =>
764 read({
765 cwd: input.cwd,
766 host: input.host,
767 operation: "listTemplates",
768 path: `projects/${projectPath(input.scope)}/templates/issues`,
769 decode: decodeTemplateEntriesJson,
770 }).pipe(
771 Effect.flatMap((entries) =>
772 Effect.forEach(entries.slice(0, TEMPLATE_LIMIT), template(input), { concurrency: 4 }),
773 ),
774 // GitLab has no switch that forbids an issue filed from nothing.
775 Effect.map((templates) => ({ templates, blankIssuesEnabled: true })),
776 ),
777
778 listCandidates: (input) =>
779 Effect.all(
780 [
781 read({
782 cwd: input.cwd,
783 host: input.host,
784 operation: "listCandidates",
785 path: paged(`projects/${projectPath(input.scope)}/labels`, 1),
786 decode: decodeProjectLabelsJson,
787 }),
788 read({
789 cwd: input.cwd,
790 host: input.host,
791 operation: "listCandidates",
792 path: paged(`projects/${projectPath(input.scope)}/members/all`, 1),
793 decode: decodeProjectMembersJson,
794 }),
795 ],
796 { concurrency: 2 },
797 ).pipe(
798 Effect.map(([labels, assignees]) => ({
799 labels,
800 assignees,
801 truncated: labels.length >= PAGE_SIZE || assignees.length >= PAGE_SIZE,
802 })),
803 ),
804 };
805 },
806 );