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

ForgejoIssueTracker.ts

733 lines26.8 KB

1/**
2 * Forgejo's issue tracker over `ForgejoCli.api`, which resolves the server and login from the
3 * checkout's remote. Forgejo pages by number and announces a next page in a `Link` header the
4 * CLI surfaces on stderr, so a listing's cursor is the next page number. Comments are not paged by
5 * the server; their cursor names the oldest comment already shown.
6 */
7import * as DateTime from "effect/DateTime";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import * as Result from "effect/Result";
11import * as Schema from "effect/Schema";
12import {
13 IssueTrackerKind,
14 type IssueCapabilities,
15 type IssueInvolvement,
16 type IssueLinkedPullRequest,
17 type IssueViewerPermissions,
18} from "@t3tools/contracts";
19import { decodeJsonResult } from "@t3tools/shared/schemaJson";
20import {
21 IssueTrackerError,
22 type IssueTrackerApi,
23} from "@t3tools/source-control-core/server/IssueTracker";
24​
25import * as ForgejoCli from "./ForgejoCli.ts";
26import {
27 ForgejoIssue,
28 ForgejoIssueConfig,
29 ForgejoIssueRepository,
30 ForgejoIssueTemplate,
31 ForgejoTimelineEntry,
32 ISSUE_STATES,
33 forgejoIssue,
34 forgejoIssueComment,
35 forgejoIssueEvent,
36 forgejoIssueTemplate,
37} from "./forgejoIssueJson.ts";
38import {
39 FORGEJO_REACTIONS,
40 ForgejoComment,
41 ForgejoLabel,
42 ForgejoReaction,
43 ForgejoUser,
44 forgejoActor,
45 forgejoReactions,
46} from "./forgejoPullRequestJson.ts";
47​
48const KIND = IssueTrackerKind.make("forgejo");
49​
50const CAPABILITIES: IssueCapabilities = {
51 create: true,
52 edit: true,
53 comment: true,
54 labels: true,
55 assignees: true,
56 reactions: true,
57 templates: true,
58 linkedPullRequests: true,
59 events: true,
60 search: true,
61};
62​
63/** Forgejo's own ceiling on a page, which a self-hosted server may lower. */
64const PAGE_SIZE = 50;
65/** How many pages of a listing with no cursor of its own are read before giving up on the rest. */
66const MAX_PAGES = 10;
67​
68const INVOLVEMENT_PARAM: Record<Exclude<IssueInvolvement, "all">, string> = {
69 assigned: "assigned_by",
70 authored: "created_by",
71 mentioned: "mentioned_by",
72};
73​
74const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError);
75const repoPath = (scope: string) => `repos/${scope.split("/").map(encodeURIComponent).join("/")}`;
76const orgPath = (scope: string) => `orgs/${encodeURIComponent(scope.split("/").at(-2) ?? "")}`;
77const issuePath = (scope: string, number: number) => `${repoPath(scope)}/issues/${number}`;
78const isNoOrg = (error: IssueTrackerError) =>
79 error.reason === "not-found" ||
80 (isForgejoCliError(error.cause) && error.cause.reason === "forbidden");
81const dedupeLabels = <T extends { readonly name: string }>(rows: ReadonlyArray<T>) =>
82 rows.filter((label, index) => rows.findIndex((other) => other.name === label.name) === index);
83​
84function parseNumber(key: string): number | null {
85 return /^[1-9]\d*$/.test(key) ? Number(key) : null;
87​
88/**
89 * A comments cursor is `<epoch ms>.<id>` of the oldest comment a page showed; the next page is the
90 * comments strictly before it in the server's order (creation time, then id), deleted or not.
91 */
92interface CommentKey {
93 readonly at: number;
94 readonly id: number;
96​
97function parseCommentsCursor(cursor: string): CommentKey | null {
98 const match = /^(0|-?[1-9]\d{0,15})\.([1-9]\d{0,15})$/.exec(cursor);
99 if (match === null) return null;
100 const key = { at: Number(match[1]), id: Number(match[2]) };
101 return Number.isSafeInteger(key.at) && Number.isSafeInteger(key.id) ? key : null;
103​
104const commentKey = (comment: typeof ForgejoComment.Type): CommentKey => ({
105 at: Option.match(DateTime.make(comment.created_at), {
106 onNone: () => 0,
107 onSome: DateTime.toEpochMillis,
108 }),
109 id: comment.id,
110});
111​
112const isBefore = (a: CommentKey, b: CommentKey) => a.at < b.at || (a.at === b.at && a.id < b.id);
113​
114/** An issue-list cursor is `page:rows-before-it`; a bare page is from before rows were counted. */
115function parseIssuesCursor(cursor: string | undefined) {
116 if (cursor === undefined) return { page: 1, seen: 0 };
117 const match = /^([1-9]\d{0,6})(?::(\d{1,9}))?$/.exec(cursor);
118 if (match === null) return null;
119 const page = Number(match[1]);
120 return { page, seen: match[2] === undefined ? (page - 1) * PAGE_SIZE : Number(match[2]) };
122​
123function reasonFor(error: ForgejoCli.ForgejoCliError): IssueTrackerError["reason"] {
124 switch (error.reason) {
125 case "missing-cli":
126 case "wrong-cli":
127 return "missing-tool";
128 case "authentication":
129 return "unauthenticated";
130 case "rate-limit":
131 return "rate-limited";
132 case "not-found":
133 return "not-found";
134 default:
135 return "failed";
136 }
138​
139/**
140 * What the signed-in account may do. Forgejo reports push access on the repository, and an
141 * issue's author may edit and close their own; an archived repository takes everything away, and
142 * a locked issue takes commenting away from anyone without push.
143 */
144function permissions(
145 repository: typeof ForgejoIssueRepository.Type,
146 issue: typeof ForgejoIssue.Type,
147 viewer: string,
148): IssueViewerPermissions {
149 const active = !repository.archived;
150 const canWrite = repository.permissions?.push ?? false;
151 const canEdit = canWrite || issue.user?.login === viewer;
152 return {
153 setState: active && canEdit,
154 comment: active && (!issue.is_locked || canWrite),
155 edit: active && canEdit,
156 labels: active && canWrite,
157 assignees: active && canWrite,
158 };
160​
161export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli> = Effect.gen(
162 function* () {
163 const cli = yield* ForgejoCli.ForgejoCli;
164​
165 const refused = (operation: string, detail: string, cause?: unknown) =>
166 new IssueTrackerError({
167 tracker: KIND,
168 operation,
169 reason: "failed",
170 detail,
171 ...(cause === undefined ? {} : { cause }),
172 });
173​
174 const notFound = (operation: string) =>
175 new IssueTrackerError({
176 tracker: KIND,
177 operation,
178 reason: "not-found",
179 detail: "Forgejo could not find the requested issue.",
180 });
181​
182 type Target = { readonly cwd: string; readonly host: string; readonly scope: string };
183​
184 const request = (
185 target: Target,
186 operation: string,
187 input: Omit<ForgejoCli.ForgejoApiInput, "cwd" | "repository" | "host">,
188 ) =>
189 cli.api({ cwd: target.cwd, repository: target.scope, host: target.host, ...input }).pipe(
190 Effect.mapError(
191 (error) =>
192 new IssueTrackerError({
193 tracker: KIND,
194 operation,
195 reason: reasonFor(error),
196 detail: error.detail,
197 cause: error,
198 }),
199 ),
200 );
201​
202 const read = <A>(
203 target: Target,
204 operation: string,
205 input: Omit<ForgejoCli.ForgejoApiInput, "cwd" | "repository" | "host">,
206 schema: Schema.Codec<A, unknown, never, never>,
207 ): Effect.Effect<A, IssueTrackerError> =>
208 request(target, operation, input).pipe(
209 Effect.flatMap((result) => {
210 if (result.stdoutTruncated) {
211 return Effect.fail(refused(operation, "Forgejo response exceeded the output limit."));
212 }
213 const decoded = decodeJsonResult(schema)(result.stdout);
214 return Result.isSuccess(decoded)
215 ? Effect.succeed(decoded.success)
216 : Effect.fail(
217 refused(operation, "Forgejo returned an invalid response.", decoded.failure),
218 );
219 }),
220 );
221​
222 const readArray = <A>(
223 target: Target,
224 operation: string,
225 path: string,
226 schema: Schema.Codec<A, unknown, never, never>,
227 ) =>
228 read(target, operation, { path }, Schema.NullOr(Schema.Array(schema))).pipe(
229 Effect.map((rows) => rows ?? []),
230 );
231​
232 /** One page of a listing, and whether another page follows. */
233 const readPage = <A>(
234 target: Target,
235 operation: string,
236 path: string,
237 page: number,
238 schema: Schema.Codec<A, unknown, never, never>,
239 {
240 seen = (page - 1) * PAGE_SIZE,
241 assumeMoreWithoutLink = false,
242 }: {
243 /** Rows on the pages before this one; a server capping `limit` below `PAGE_SIZE` has fewer. */
244 readonly seen?: number;
245 readonly assumeMoreWithoutLink?: boolean;
246 } = {},
247 ): Effect.Effect<
248 { readonly rows: ReadonlyArray<A>; readonly nextCursor: string | null },
249 IssueTrackerError
250 > =>
251 request(target, operation, {
252 path: `${path}${path.includes("?") ? "&" : "?"}limit=${PAGE_SIZE}&page=${page}`,
253 }).pipe(
254 Effect.flatMap((result) => {
255 const decoded = decodeJsonResult(Schema.NullOr(Schema.Array(schema)))(result.stdout);
256 if (Result.isFailure(decoded)) {
257 return Effect.fail(
258 refused(operation, "Forgejo returned an invalid response.", decoded.failure),
259 );
260 }
261 const rows = decoded.success ?? [];
262 const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1];
263 const total = /^x-total-count:\s*(\d+)\s*$/im.exec(result.stderr)?.[1];
264 const more =
265 rows.length > 0 &&
266 (links !== undefined
267 ? /rel="?next"?/i.test(links)
268 : assumeMoreWithoutLink ||
269 (total !== undefined
270 ? seen + rows.length < Number(total)
271 : rows.length >= PAGE_SIZE));
272 return Effect.succeed({ rows, nextCursor: more ? String(page + 1) : null });
273 }),
274 );
275 // A personal owner answers 404 and a token without the organization scope 403: no org labels.
276 const orgLabelsPage = (target: Target, operation: string, page: number, seen: number) =>
277 readPage(target, operation, `${orgPath(target.scope)}/labels`, page, ForgejoLabel, {
278 seen,
279 }).pipe(Effect.catchIf(isNoOrg, () => Effect.succeed({ rows: [], nextCursor: null })));
280​
281 const write = (
282 target: Target,
283 operation: string,
284 input: Omit<ForgejoCli.ForgejoApiInput, "cwd" | "repository" | "host">,
285 ) => request(target, operation, input).pipe(Effect.asVoid);
286​
287 const getViewer = (target: Target, operation: string) =>
288 read(target, operation, { path: "user" }, ForgejoUser).pipe(Effect.map((user) => user.login));
289​
290 const getRepository = (target: Target, operation: string) =>
291 read(target, operation, { path: repoPath(target.scope) }, ForgejoIssueRepository);
292​
293 /** The issue as the API addresses it, or a not-found for a key that names no number. */
294 const issueTarget = (
295 operation: string,
296 input: Target & { readonly key: string },
297 ): Effect.Effect<{ readonly number: number; readonly path: string }, IssueTrackerError> => {
298 const number = parseNumber(input.key);
299 return number === null
300 ? Effect.fail(notFound(operation))
301 : Effect.succeed({ number, path: issuePath(input.scope, number) });
302 };
303​
304 const getIssue = (target: Target, operation: string, path: string) =>
305 read(target, operation, { path }, ForgejoIssue).pipe(
306 // The issues API answers for a pull request's number too; that is not an issue here.
307 Effect.filterOrFail(
308 (issue) => !issue.pull_request,
309 () => notFound(operation),
310 ),
311 );
312​
313 /** Every page of a listing the caller gets no cursor for, up to `MAX_PAGES`. */
314 const readEveryPage = Effect.fn("ForgejoIssueTracker.readEveryPage")(function* <A>(
315 target: Target,
316 operation: string,
317 path: string,
318 schema: Schema.Codec<A, unknown, never, never>,
319 ) {
320 const rows: A[] = [];
321 for (let page = 1; page <= MAX_PAGES; page++) {
322 // Forgejo /timeline omits Link and sets X-Total-Count to the page length, not the full list.
323 const next = yield* readPage(target, operation, path, page, schema, {
324 assumeMoreWithoutLink: true,
325 });
326 rows.push(...next.rows);
327 if (next.nextCursor === null) break;
328 }
329 return rows;
330 });
331​
332 /**
333 * Names resolve to repository labels first, then org labels; an unknown name refuses the write.
334 */
335 const labelIds = Effect.fn("ForgejoIssueTracker.labelIds")(function* (
336 target: Target,
337 operation: string,
338 names: ReadonlyArray<string>,
339 ) {
340 const ids = new Map<string, number>();
341 let seen = 0;
342 for (let page = 1; ids.size < new Set(names).size && page <= MAX_PAGES; page++) {
343 const next = yield* readPage(
344 target,
345 operation,
346 `${repoPath(target.scope)}/labels`,
347 page,
348 ForgejoLabel,
349 { seen },
350 );
351 seen += next.rows.length;
352 for (const label of next.rows) {
353 if (names.includes(label.name)) ids.set(label.name, label.id);
354 }
355 if (next.nextCursor === null) break;
356 }
357 seen = 0;
358 for (let page = 1; ids.size < new Set(names).size && page <= MAX_PAGES; page++) {
359 const next = yield* orgLabelsPage(target, operation, page, seen);
360 seen += next.rows.length;
361 for (const label of next.rows)
362 if (names.includes(label.name) && !ids.has(label.name)) ids.set(label.name, label.id);
363 if (next.nextCursor === null) break;
364 }
365 if (names.some((name) => !ids.has(name))) {
366 return yield* refused(operation, "Forgejo found no label by one of the names given.");
367 }
368 return [...ids.values()];
369 });
370​
371 /** `/comments` takes no page and answers with every comment, oldest first, so pages are cut here. */
372 const commentsPage = (
373 target: Target,
374 operation: string,
375 path: string,
376 before: CommentKey | undefined,
377 viewer: string,
378 ) =>
379 readArray(target, operation, `${path}/comments`, ForgejoComment).pipe(
380 Effect.flatMap((rows) => {
381 const boundary =
382 before === undefined ? -1 : rows.findIndex((row) => row.id === before.id);
383 // The server's order is stored seconds, then id. `created_at` carries a minute-precision
384 // offset that can misorder historical rows, so it is compared only once the boundary
385 // comment has been deleted.
386 const earlier =
387 before === undefined
388 ? rows
389 : boundary >= 0
390 ? rows.slice(0, boundary)
391 : rows.filter((row) => isBefore(commentKey(row), before));
392 const selected = earlier.slice(-PAGE_SIZE);
393 const oldest = selected[0];
394 const nextCursor =
395 oldest !== undefined && earlier.length > selected.length
396 ? `${commentKey(oldest).at}.${oldest.id}`
397 : null;
398 return Effect.forEach(
399 selected,
400 (comment) =>
401 readArray(
402 target,
403 operation,
404 `${repoPath(target.scope)}/issues/comments/${comment.id}/reactions`,
405 ForgejoReaction,
406 ).pipe(
407 Effect.map((reactions) => ({
408 ...forgejoIssueComment(comment),
409 reactions: forgejoReactions(reactions, viewer),
410 })),
411 ),
412 { concurrency: 4 },
413 ).pipe(Effect.map((comments) => ({ comments, nextCursor })));
414 }),
415 );
416​
417 /** Pull requests the timeline shows citing this issue, each read once for its state. */
418 const linkedPullRequests = (
419 target: Target,
420 timeline: ReadonlyArray<typeof ForgejoTimelineEntry.Type>,
421 ): Effect.Effect<ReadonlyArray<IssueLinkedPullRequest>, IssueTrackerError> => {
422 // A reference may come from another repository, which is where that pull request is read.
423 const cited = new Map<string, { readonly repository: string; readonly number: number }>();
424 for (const entry of timeline) {
425 if (entry.type !== "pull_ref" || !entry.ref_issue?.pull_request) continue;
426 const named = entry.ref_issue.repository?.full_name;
427 // The scope may carry the server's mount path in front of the same repository.
428 const repository =
429 named === undefined || target.scope.endsWith(`/${named}`) ? target.scope : named;
430 cited.set(`${repository}#${entry.ref_issue.number}`, {
431 repository,
432 number: entry.ref_issue.number,
433 });
434 }
435 return Effect.forEach(
436 cited.values(),
437 ({ repository, number }) =>
438 read(
439 target,
440 "getIssue",
441 { path: `${repoPath(repository)}/pulls/${number}` },
442 Schema.Struct({
443 number: Schema.Int,
444 title: Schema.String,
445 html_url: Schema.String,
446 state: Schema.String,
447 merged: Schema.Boolean,
448 draft: Schema.optional(Schema.Boolean),
449 }),
450 ).pipe(
451 Effect.map((pull) => [
452 {
453 repository,
454 number: pull.number,
455 title: pull.title,
456 url: pull.html_url,
457 state: pull.merged
458 ? ("merged" as const)
459 : pull.state === "closed"
460 ? ("closed" as const)
461 : ("open" as const),
462 isDraft: pull.draft ?? false,
463 // Forgejo's timeline cites the pull request without saying whether it closes the issue.
464 closesIssue: false,
465 },
466 ]),
467 Effect.catchIf(
468 (error) => error.reason === "not-found",
469 () => Effect.succeed([]),
470 ),
471 ),
472 { concurrency: 2 },
473 ).pipe(Effect.map((links) => links.flat()));
474 };
475​
476 return {
477 kind: KIND,
478 capabilities: CAPABILITIES,
479​
480 getViewer: (input) => getViewer({ ...input, scope: "" }, "getViewer"),
481​
482 listIssues: Effect.fn("ForgejoIssueTracker.listIssues")(function* (input) {
483 const cursor = parseIssuesCursor(input.cursor);
484 if (cursor === null) {
485 return yield* refused("listIssues", "The cursor was not one Forgejo handed out.");
486 }
487 const params = new URLSearchParams({
488 type: "issues",
489 state: input.state,
490 sort: input.sort === "created" ? "latest" : "recentupdate",
491 });
492 const labels = input.labels ?? [];
493 if (labels.length > 0) params.set("labels", labels.join(","));
494 const text = input.query?.trim() ?? "";
495 if (text.length > 0) params.set("q", text);
496 if (input.involvement !== "all") {
497 params.set(INVOLVEMENT_PARAM[input.involvement], input.viewer);
498 }
499 if (input.assignee !== undefined) params.set("assigned_by", input.assignee);
500 // `assigned_by` names one person, so "assigned to me" is kept here beside a named assignee.
501 const alsoAssignedTo =
502 input.involvement === "assigned" && input.assignee !== undefined
503 ? input.viewer.toLowerCase()
504 : null;
505 const { rows, nextCursor } = yield* readPage(
506 input,
507 "listIssues",
508 `${repoPath(input.scope)}/issues?${params}`,
509 cursor.page,
510 ForgejoIssue,
511 { seen: cursor.seen },
512 );
513 return {
514 items: rows
515 .flatMap((issue) => (issue.pull_request ? [] : [forgejoIssue(issue)]))
516 // Forgejo documents `labels` as matching any of them; every one is what was asked.
517 .filter(
518 (issue) =>
519 labels.every((label) => issue.labels.some((carried) => carried.name === label)) &&
520 (alsoAssignedTo === null ||
521 issue.assignees.some((actor) => actor.login.toLowerCase() === alsoAssignedTo)),
522 ),
523 nextCursor: nextCursor === null ? null : `${nextCursor}:${cursor.seen + rows.length}`,
524 };
525 }),
526​
527 getIssue: (input) =>
528 issueTarget("getIssue", input).pipe(
529 Effect.flatMap(({ path }) =>
530 Effect.all(
531 [
532 getIssue(input, "getIssue", path),
533 getRepository(input, "getIssue"),
534 getViewer(input, "getIssue"),
535 readEveryPage(input, "getIssue", `${path}/timeline`, ForgejoTimelineEntry),
536 readArray(input, "getIssue", `${path}/reactions`, ForgejoReaction),
537 ],
538 { concurrency: 3 },
539 ),
540 ),
541 Effect.flatMap(([issue, repository, viewer, timeline, reactions]) =>
542 Effect.all([
543 commentsPage(
544 input,
545 "getIssue",
546 issuePath(input.scope, issue.number),
547 undefined,
548 viewer,
549 ),
550 linkedPullRequests(input, timeline),
551 ]).pipe(
552 Effect.map(([conversation, links]) => ({
553 ...forgejoIssue(issue),
554 body: issue.body ?? "",
555 viewer,
556 viewerPermissions: permissions(repository, issue, viewer),
557 states: ISSUE_STATES,
558 reactions: forgejoReactions(reactions, viewer),
559 comments: conversation.comments,
560 commentsCursor: conversation.nextCursor,
561 events: timeline.flatMap((entry) => forgejoIssueEvent(entry) ?? []),
562 linkedPullRequests: links,
563 })),
564 ),
565 ),
566 ),
567​
568 getComments: (input) => {
569 const before = parseCommentsCursor(input.cursor);
570 return before === null
571 ? Effect.fail(refused("getComments", "The cursor was not one Forgejo handed out."))
572 : Effect.all([issueTarget("getComments", input), getViewer(input, "getComments")]).pipe(
573 Effect.flatMap(([{ path }, viewer]) =>
574 commentsPage(input, "getComments", path, before, viewer),
575 ),
576 );
577 },
578​
579 create: (input) =>
580 labelIds(input, "create", input.labels).pipe(
581 Effect.flatMap((labels) =>
582 read(
583 input,
584 "create",
585 {
586 path: `${repoPath(input.scope)}/issues`,
587 method: "POST",
588 body: {
589 title: input.title,
590 body: input.body,
591 labels,
592 assignees: input.assignees,
593 },
594 },
595 ForgejoIssue,
596 ),
597 ),
598 Effect.map((issue) => ({
599 key: String(issue.number),
600 displayKey: `#${issue.number}`,
601 url: issue.html_url,
602 })),
603 ),
604​
605 comment: (input) =>
606 issueTarget("comment", input).pipe(
607 Effect.flatMap(({ path }) =>
608 write(input, "comment", {
609 path: `${path}/comments`,
610 method: "POST",
611 body: { body: input.body },
612 }),
613 ),
614 ),
615​
616 update: (input) =>
617 Effect.all([
618 issueTarget("update", input),
619 // Resolved before anything is written, so an unknown label changes nothing.
620 input.labels === undefined ? Effect.void : labelIds(input, "update", input.labels),
621 ]).pipe(
622 Effect.flatMap(([{ path }, labels]) =>
623 Effect.all([
624 input.title === undefined && input.body === undefined && input.assignees === undefined
625 ? Effect.void
626 : write(input, "update", {
627 path,
628 method: "PATCH",
629 body: {
630 ...(input.title === undefined ? {} : { title: input.title }),
631 ...(input.body === undefined ? {} : { body: input.body }),
632 ...(input.assignees === undefined ? {} : { assignees: input.assignees }),
633 },
634 }),
635 labels === undefined
636 ? Effect.void
637 : write(input, "update", {
638 path: `${path}/labels`,
639 method: "PUT",
640 body: { labels },
641 }),
642 ]),
643 ),
644 Effect.asVoid,
645 ),
646​
647 setState: (input) => {
648 const wanted = ISSUE_STATES.find((state) => state.name === input.state);
649 if (wanted === undefined) {
650 return Effect.fail(refused("setState", `A Forgejo issue has no "${input.state}" state.`));
651 }
652 return issueTarget("setState", input).pipe(
653 Effect.flatMap(({ path }) =>
654 write(input, "setState", { path, method: "PATCH", body: { state: wanted.category } }),
655 ),
656 );
657 },
658​
659 setReaction: (input) =>
660 issueTarget("setReaction", input).pipe(
661 Effect.flatMap(({ path }) => {
662 if (input.subjectId !== undefined && !/^[1-9]\d*$/.test(input.subjectId)) {
663 return Effect.fail(
664 refused("setReaction", "The comment id names no Forgejo comment."),
665 );
666 }
667 return write(input, "setReaction", {
668 path:
669 input.subjectId === undefined
670 ? `${path}/reactions`
671 : `${repoPath(input.scope)}/issues/comments/${input.subjectId}/reactions`,
672 method: input.reacted ? "POST" : "DELETE",
673 body: { content: FORGEJO_REACTIONS[input.content] },
674 });
675 }),
676 ),
677​
678 listTemplates: (input) =>
679 Effect.all(
680 [
681 readArray(
682 input,
683 "listTemplates",
684 `${repoPath(input.scope)}/issue_templates`,
685 ForgejoIssueTemplate,
686 ),
687 // A repository with no config leaves the blank issue where Forgejo puts it.
688 read(
689 input,
690 "listTemplates",
691 { path: `${repoPath(input.scope)}/issue_config` },
692 ForgejoIssueConfig,
693 ).pipe(
694 Effect.map((config) => config.blank_issues_enabled !== false),
695 Effect.catchIf(
696 (error) => error.reason === "not-found" || error.reason === "failed",
697 () => Effect.succeed(true),
698 ),
699 ),
700 ],
701 { concurrency: 2 },
702 ).pipe(
703 Effect.map(([templates, blankIssuesEnabled]) => ({
704 templates: templates.flatMap((template) => forgejoIssueTemplate(template) ?? []),
705 blankIssuesEnabled,
706 })),
707 ),
708​
709 listCandidates: (input) =>
710 Effect.all(
711 [
712 readPage(input, "listCandidates", `${repoPath(input.scope)}/labels`, 1, ForgejoLabel),
713 orgLabelsPage(input, "listCandidates", 1, 0),
714 readArray(input, "listCandidates", `${repoPath(input.scope)}/assignees`, ForgejoUser),
715 ],
716 { concurrency: 2 },
717 ).pipe(
718 Effect.map(([repo, org, assignees]) => ({
719 labels: dedupeLabels([...repo.rows, ...org.rows]).map((label) => ({
720 name: label.name,
721 color: label.color ?? null,
722 description: label.description ?? null,
723 })),
724 assignees: assignees.flatMap((user) => {
725 const actor = forgejoActor(user);
726 return actor === null ? [] : [{ ...actor, id: actor.login }];
727 }),
728 truncated: repo.nextCursor !== null || org.nextCursor !== null,
729 })),
730 ),
731 };
732 },
733);