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, 08:30 UTC
feat(issues): add GitLab, Azure DevOps, and Forgejo issue trackers (#19261)
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Julius Marminge committed
Nov 16, 2026 at 22:00 UTC
adffb3623fa283e3a7db4f1fe1386c16c001162f
16 files changed
+3784
-6
apps/server/src/issue/IssueService.ts
+4
-4
@@ -60,7 +60,6 @@ function trackerDetail(error: IssueTrackerError): string {
60
61
/** One project's resolved tracker: which driver, where it is served from, and its container. */
62
interface ProjectTrackerBinding {
63
- readonly canonicalKey: string;
63
readonly tracker: IssueTrackerKind;
64
readonly host: string;
65
readonly scope: string;
@@ -82,7 +81,6 @@ function resolveGitHostBinding(project: OrchestrationProjectShell): ProjectTrack
81
const kind = identity?.provider;
82
if (!identity || kind === undefined || kind === "unknown" || scope === null) return null;
83
return {
85
- canonicalKey: identity.canonicalKey,
84
tracker: IssueTrackerKind.make(kind),
85
host: sourceControlDefinitions.changeRequestHost(identity, kind),
86
scope,
@@ -244,10 +242,12 @@ const make = Effect.gen(function* () {
242
const list: IssueService["Service"]["list"] = Effect.fn("IssueService.list")(function* (input) {
243
const { supported, unimplemented } = yield* listProjects(input);
244
const limit = input.limit ?? DEFAULT_LIST_LIMIT;
247
- // Worktrees of one repository are separate projects; read each scope once.
245
+ // Worktrees of one repository are separate projects, and every repository of an Azure
246
+ // DevOps project shares its work items; read each scope once.
247
const scopes = new Map<string, SupportedProject>();
248
for (const project of supported) {
250
- if (!scopes.has(project.canonicalKey)) scopes.set(project.canonicalKey, project);
249
+ const key = listCursorKey(project.host, project.scope).toLowerCase();
250
+ if (!scopes.has(key)) scopes.set(key, project);
251
}
252
const continuing = input.cursors;
253
const viewers = new Map<string, string>();
docs/user/source-control.md
+2
-2
@@ -352,8 +352,8 @@ out from the matching organization and repository.
352
353
## Issues
354
355
-The Issues page lists the issues of every project whose remote is on a supported tracker
356
-(GitHub today), grouped per tracker account. Open it from the sidebar's utility row or with
355
+The Issues page lists the issues of every project whose remote is on GitHub, GitLab, Azure
356
+DevOps or Forgejo, grouped per tracker account. Open it from the sidebar's utility row or with
357
**Open issues** in the command palette. Filter by open or closed, by your involvement
358
(assigned, opened by you, mentioning you), and by tracker; the search box asks the tracker
359
itself where it can search. Press **Load more** at the end of a group to read further back.
packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.test.ts
new
+278
@@ -0,0 +1,278 @@
1
+import { describe, expect, it } from "@effect/vitest";
2
+import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
3
+import * as Effect from "effect/Effect";
4
+import * as FileSystem from "effect/FileSystem";
5
+import * as PlatformError from "effect/PlatformError";
6
+import * as Layer from "effect/Layer";
7
+import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
8
+
9
+import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
10
+import * as AzureDevOpsIssueTracker from "./AzureDevOpsIssueTracker.ts";
11
+
12
+const encode = (value: unknown) => JSON.stringify(value);
13
+
14
+const WORK_ITEM = {
15
+ id: 7,
16
+ url: "https://dev.azure.com/acme/_apis/wit/workItems/7",
17
+ fields: {
18
+ "System.Title": "Composer loses focus",
19
+ "System.State": "Shipped",
20
+ "System.CreatedDate": "2026-07-01T00:00:00Z",
21
+ "System.ChangedDate": "2026-07-03T00:00:00Z",
22
+ "Microsoft.VSTS.Common.ClosedDate": "2026-07-03T00:00:00Z",
23
+ "System.CreatedBy": { uniqueName: "octo@acme.test", displayName: "Octo Cat" },
24
+ "System.AssignedTo": "Theo <theo@acme.test>",
25
+ "System.Tags": "bug; ui; bug",
26
+ "System.TeamProject": "Web App",
27
+ "System.CommentCount": 2,
28
+ "System.Description": "<p>Typing drops focus.</p>",
29
+ },
30
+ relations: [
31
+ { rel: "ArtifactLink", url: "vstfs:///Git/PullRequestId/p-guid%2Fr-guid%2F50" },
32
+ { rel: "System.LinkTypes.Related", url: "https://dev.azure.com/acme/_apis/wit/workItems/8" },
33
+ ],
34
+};
35
+
36
+/** A custom process: "Shipped" is finished only because its category says so. */
37
+const WORK_ITEM_TYPES = {
38
+ value: [
39
+ {
40
+ name: "Bug",
41
+ states: [
42
+ { name: "Active", category: "InProgress" },
43
+ { name: "Shipped", category: "Completed" },
44
+ ],
45
+ },
46
+ ],
47
+};
48
+
49
+/** Every `az` command the detail read runs, told apart by its first few arguments. */
50
+function answer(args: ReadonlyArray<string>): string {
51
+ const resource = args[args.indexOf("--resource") + 1];
52
+ if (args[0] === "boards") return encode(WORK_ITEM);
53
+ if (resource === "workitemtypes") return encode(WORK_ITEM_TYPES);
54
+ if (args[0] === "repos") {
55
+ return encode({
56
+ pullRequestId: 50,
57
+ title: "fix(web): keep composer focus",
58
+ status: "completed",
59
+ isDraft: false,
60
+ sourceRefName: "refs/heads/fix",
61
+ targetRefName: "refs/heads/main",
62
+ creationDate: "2026-07-02T00:00:00Z",
63
+ closedDate: "2026-07-03T00:00:00Z",
64
+ mergeStatus: "succeeded",
65
+ repository: {
66
+ id: "r-guid",
67
+ name: "web",
68
+ webUrl: "https://dev.azure.com/acme/Web%20App/_git/web",
69
+ project: { id: "p-guid", name: "Web App" },
70
+ },
71
+ createdBy: { uniqueName: "theo@acme.test", displayName: "Theo" },
72
+ description: "",
73
+ reviewers: [],
74
+ _links: { web: { href: "https://dev.azure.com/acme/Web%20App/_git/web/pullrequest/50" } },
75
+ });
76
+ }
77
+ if (resource === "comments") {
78
+ return encode({
79
+ continuationToken: "next-token",
80
+ comments: [
81
+ {
82
+ id: 1,
83
+ text: "Repro attached.",
84
+ createdDate: "2026-07-02T00:00:00Z",
85
+ createdBy: { uniqueName: "julius@acme.test", displayName: "Julius" },
86
+ reactions: [
87
+ { type: "like", count: 2, isCurrentUserEngaged: true },
88
+ { type: "dislike", count: 0 },
89
+ ],
90
+ },
91
+ { id: 2, text: "gone", createdDate: "2026-07-02T00:00:00Z", isDeleted: true },
92
+ ],
93
+ });
94
+ }
95
+ if (resource === "updates") {
96
+ return encode({
97
+ value: [
98
+ {
99
+ id: 1,
100
+ revisedDate: "2026-07-01T00:00:00Z",
101
+ fields: { "System.Title": { newValue: "x" } },
102
+ },
103
+ {
104
+ id: 2,
105
+ revisedDate: "2026-07-03T00:00:00Z",
106
+ revisedBy: { uniqueName: "theo@acme.test" },
107
+ fields: {
108
+ "System.State": { oldValue: "Active", newValue: "Shipped" },
109
+ "System.Tags": { oldValue: "ui", newValue: "bug; ui" },
110
+ },
111
+ },
112
+ ],
113
+ });
114
+ }
115
+ throw new Error(`unexpected az invocation ${args.join(" ")}`);
116
+}
117
+
118
+function tracker(onExecute: (args: ReadonlyArray<string>) => string) {
119
+ return AzureDevOpsIssueTracker.make.pipe(
120
+ Effect.provide(
121
+ Layer.mergeAll(
122
+ NodeFileSystem.layer,
123
+ Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
124
+ execute: ({ args }) =>
125
+ Effect.succeed(TestSourceControlHost.processOutput(onExecute(args))),
126
+ }),
127
+ ),
128
+ ),
129
+ );
130
+}
131
+
132
+describe("AzureDevOpsIssueTracker", () => {
133
+ it.effect("maps a work item, its conversation and revisions to the neutral issue shape", () =>
134
+ Effect.gen(function* () {
135
+ const seen: string[][] = [];
136
+ const api = yield* tracker((args) => {
137
+ seen.push([...args]);
138
+ return answer(args);
139
+ });
140
+ const issue = yield* api.getIssue({
141
+ cwd: "/w",
142
+ host: "dev.azure.com",
143
+ scope: "acme/Web App",
144
+ key: "7",
145
+ });
146
+ // Every command names the organization rather than detecting it from the checkout.
147
+ for (const args of seen) {
148
+ expect(args).toContain("https://dev.azure.com/acme");
149
+ }
150
+ expect(issue).toMatchObject({
151
+ key: "7",
152
+ displayKey: "#7",
153
+ title: "Composer loses focus",
154
+ url: "https://dev.azure.com/acme/Web%20App/_workitems/edit/7",
155
+ // The project's own state name survives; the category is what the list filters by.
156
+ state: { category: "closed", name: "Shipped" },
157
+ author: { login: "octo@acme.test", name: "Octo Cat" },
158
+ assignees: [{ login: "Theo <theo@acme.test>" }],
159
+ labels: [
160
+ { name: "bug", color: null },
161
+ { name: "ui", color: null },
162
+ ],
163
+ commentCount: 2,
164
+ body: "<p>Typing drops focus.</p>",
165
+ commentsCursor: "next-token",
166
+ viewerPermissions: { setState: true, edit: true, labels: true, assignees: true },
167
+ });
168
+ expect(issue.comments).toEqual([
169
+ {
170
+ id: "1",
171
+ author: { login: "julius@acme.test", name: "Julius", avatarUrl: null },
172
+ body: "Repro attached.",
173
+ createdAt: "2026-07-02T00:00:00Z",
174
+ url: null,
175
+ reactions: [{ content: "thumbs-up", count: 2, actors: [], viewerHasReacted: true }],
176
+ },
177
+ ]);
178
+ // The first revision is the creation; a state move across the category line is a close.
179
+ expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
180
+ ["closed", "Shipped"],
181
+ ["labeled", "bug"],
182
+ ]);
183
+ expect(issue.linkedPullRequests).toEqual([
184
+ {
185
+ repository: "Web App/web",
186
+ number: 50,
187
+ title: "fix(web): keep composer focus",
188
+ url: "https://dev.azure.com/acme/Web%20App/_git/web/pullrequest/50",
189
+ state: "merged",
190
+ isDraft: false,
191
+ closesIssue: false,
192
+ },
193
+ ]);
194
+ }),
195
+ );
196
+
197
+ it.effect("filters open work items by the project's own finished states", () =>
198
+ Effect.gen(function* () {
199
+ const fs = yield* FileSystem.FileSystem;
200
+ const bodies: string[] = [];
201
+ const api = yield* AzureDevOpsIssueTracker.make.pipe(
202
+ Effect.provide(
203
+ Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
204
+ execute: ({ args }) =>
205
+ args[args.indexOf("--resource") + 1] === "wiql"
206
+ ? fs.readFileString(args[args.indexOf("--in-file") + 1]!).pipe(
207
+ Effect.orDie,
208
+ Effect.map((body) => {
209
+ bodies.push(body);
210
+ return TestSourceControlHost.processOutput(encode({ workItems: [] }));
211
+ }),
212
+ )
213
+ : Effect.succeed(TestSourceControlHost.processOutput(answer(args))),
214
+ }),
215
+ ),
216
+ );
217
+ yield* api.listIssues({
218
+ cwd: "/w",
219
+ host: "dev.azure.com",
220
+ scope: "acme/Web App",
221
+ state: "open",
222
+ involvement: "all",
223
+ viewer: "octo@acme.test",
224
+ limit: 10,
225
+ });
226
+ expect(bodies).toHaveLength(1);
227
+ expect(bodies[0]).toContain("AND [System.State] NOT IN ('shipped')");
228
+ }).pipe(Effect.provide(NodeFileSystem.layer)),
229
+ );
230
+
231
+ it.effect("refuses a scope that is not organization/project without a request", () =>
232
+ Effect.gen(function* () {
233
+ let requests = 0;
234
+ const api = yield* tracker(() => {
235
+ requests += 1;
236
+ return "{}";
237
+ });
238
+ const error = yield* Effect.flip(
239
+ api.getIssue({ cwd: "/w", host: "dev.azure.com", scope: "web", key: "7" }),
240
+ );
241
+ expect(error.reason).toBe("failed");
242
+ expect(requests).toBe(0);
243
+ }),
244
+ );
245
+
246
+ it.effect("keeps a failure's own text in the cause, out of the detail a caller reads", () =>
247
+ Effect.gen(function* () {
248
+ const denied = PlatformError.systemError({
249
+ _tag: "PermissionDenied",
250
+ module: "FileSystem",
251
+ method: "makeTempFileScoped",
252
+ pathOrDescriptor: "/private/tmp/secret-dir",
253
+ });
254
+ const api = yield* AzureDevOpsIssueTracker.make.pipe(
255
+ Effect.provide(
256
+ Layer.mergeAll(
257
+ Layer.succeed(
258
+ FileSystem.FileSystem,
259
+ FileSystem.makeNoop({ makeTempFileScoped: () => Effect.fail(denied) }),
260
+ ),
261
+ Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),
262
+ ),
263
+ ),
264
+ );
265
+ const error = yield* Effect.flip(
266
+ api.comment!({
267
+ cwd: "/w",
268
+ host: "dev.azure.com",
269
+ scope: "acme/Web App",
270
+ key: "7",
271
+ body: "x",
272
+ }),
273
+ );
274
+ expect(error.detail).toBe("Could not write the Azure DevOps request body.");
275
+ expect(error.cause).toBe(denied);
276
+ }),
277
+ );
278
+});
packages/source-control-azure-devops/src/server/AzureDevOpsIssueTracker.ts
new
+911
@@ -0,0 +1,911 @@
1
+/**
2
+ * Azure DevOps work items as an issue tracker, over `az`. Work items belong to a project, so the
3
+ * scope is `organization/project` and every call names the organization. Listing is a WIQL
4
+ * query paged by a `(changedDate, id)` keyset cursor, because WIQL has no offset.
5
+ */
6
+import * as Effect from "effect/Effect";
7
+import * as FileSystem from "effect/FileSystem";
8
+import * as Result from "effect/Result";
9
+import * as Schema from "effect/Schema";
10
+import {
11
+ IssueTrackerKind,
12
+ type IssueCapabilities,
13
+ type IssueInvolvement,
14
+ type IssueLinkedPullRequest,
15
+ type IssueViewerPermissions,
16
+} from "@t3tools/contracts";
17
+import {
18
+ IssueTrackerError,
19
+ type IssueTrackerApi,
20
+} from "@t3tools/source-control-core/server/IssueTracker";
21
+
22
+import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
23
+import {
24
+ azureDevOpsReactionType,
25
+ closedStateNames,
26
+ decodeCommentsJson,
27
+ decodeProfileJson,
28
+ decodeUpdatesJson,
29
+ decodeWorkItemJson,
30
+ decodeWorkItemsJson,
31
+ pullRequestNumberOf,
32
+ type AzureDevOpsWorkItem,
33
+ type ClosedStates,
34
+} from "./azureDevOpsIssueJson.ts";
35
+import { decodePullRequestJson } from "./azureDevOpsPullRequestJson.ts";
36
+
37
+const KIND = IssueTrackerKind.make("azure-devops");
38
+
39
+/**
40
+ * The states the stock Basic, Agile and Scrum processes carry, which is what a project that has
41
+ * not customised its workflow can be moved between. A project with states of its own refuses a
42
+ * name it lacks at write time, with Azure's own message.
43
+ */
44
+const CAPABILITIES: IssueCapabilities = {
45
+ create: true,
46
+ edit: true,
47
+ comment: true,
48
+ labels: true,
49
+ assignees: true,
50
+ // On comments only; a work item itself takes none, and `setReaction` says so.
51
+ reactions: true,
52
+ // Azure has no issue templates. Its work item types are picked here, not by the reader.
53
+ templates: false,
54
+ linkedPullRequests: true,
55
+ events: true,
56
+ search: true,
57
+ states: [
58
+ { category: "open", name: "New" },
59
+ { category: "open", name: "To Do" },
60
+ { category: "open", name: "Active" },
61
+ { category: "open", name: "Doing" },
62
+ { category: "closed", name: "Resolved" },
63
+ { category: "closed", name: "Done" },
64
+ { category: "closed", name: "Closed" },
65
+ { category: "closed", name: "Removed" },
66
+ ],
67
+ closeReasons: [],
68
+};
69
+
70
+/**
71
+ * Everything granted. Azure states no permission anywhere `az boards` reaches: the answer lives
72
+ * in the security namespaces, behind identity descriptors that would be several calls per work
73
+ * item to resolve. Controls stay live and a viewer who may not use one is told so by Azure.
74
+ */
75
+const VIEWER_PERMISSIONS: IssueViewerPermissions = {
76
+ setState: true,
77
+ comment: true,
78
+ edit: true,
79
+ labels: true,
80
+ assignees: true,
81
+};
82
+
83
+const REST_API_VERSION = "7.1";
84
+const PAGE_SIZE = 100;
85
+/** Linked pull requests are read one `az` process each, so a work item's links are bounded. */
86
+const LINKED_PULL_REQUEST_LIMIT = 10;
87
+/** Which work item type a new issue is filed as, in order of preference across the stock processes. */
88
+const CREATE_TYPES = ["Issue", "Bug", "Task", "User Story", "Product Backlog Item"];
89
+
90
+const LIST_FIELDS = [
91
+ "System.Id",
92
+ "System.Title",
93
+ "System.State",
94
+ "System.CreatedDate",
95
+ "System.ChangedDate",
96
+ "System.CreatedBy",
97
+ "System.AssignedTo",
98
+ "System.CommentCount",
99
+ "System.Tags",
100
+ "System.TeamProject",
101
+ "Microsoft.VSTS.Common.ClosedDate",
102
+];
103
+
104
+const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
105
+const decodeWiql = Schema.decodeUnknownResult(
106
+ Schema.Struct({
107
+ workItems: Schema.optional(Schema.NullOr(Schema.Array(Schema.Struct({ id: Schema.Int })))),
108
+ }),
109
+);
110
+const decodeTypes = Schema.decodeUnknownResult(
111
+ Schema.Struct({
112
+ value: Schema.Array(
113
+ Schema.Struct({
114
+ name: Schema.String,
115
+ isDisabled: Schema.optional(Schema.Boolean),
116
+ states: Schema.optional(
117
+ Schema.Array(Schema.Struct({ name: Schema.String, category: Schema.String })),
118
+ ),
119
+ }),
120
+ ),
121
+ }),
122
+);
123
+const decodeTags = Schema.decodeUnknownResult(
124
+ Schema.Struct({ value: Schema.Array(Schema.Struct({ name: Schema.String })) }),
125
+);
126
+const decodeTeams = Schema.decodeUnknownResult(Schema.Array(Schema.Struct({ id: Schema.String })));
127
+const decodeMembers = Schema.decodeUnknownResult(
128
+ Schema.Array(
129
+ Schema.Struct({
130
+ identity: Schema.Struct({
131
+ uniqueName: Schema.String,
132
+ displayName: Schema.optional(Schema.NullOr(Schema.String)),
133
+ imageUrl: Schema.optional(Schema.NullOr(Schema.String)),
134
+ isContainer: Schema.optional(Schema.Boolean),
135
+ }),
136
+ }),
137
+ ),
138
+);
139
+const decodeUnknown = Schema.decodeUnknownResult(Schema.fromJsonString(Schema.Unknown));
140
+
141
+/** The parts of an `organization/project` scope, as the organization URL and the project name. */
142
+function parseScope(
143
+ host: string,
144
+ scope: string,
145
+): { readonly organization: string; readonly project: string } | null {
146
+ const parts = scope.split("/").flatMap((part) => part.trim() || []);
147
+ if (parts.length !== 2) return null;
148
+ const [organization, project] = parts as [string, string];
149
+ return {
150
+ organization: host.toLowerCase().endsWith(".visualstudio.com")
151
+ ? `https://${host}`
152
+ : `https://${host}/${encodeURIComponent(organization)}`,
153
+ project,
154
+ };
155
+}
156
+
157
+function parseNumber(key: string): number | null {
158
+ return /^[1-9]\d{0,9}$/.test(key) ? Number(key) : null;
159
+}
160
+
161
+/** WIQL string literals are single-quoted and escape a quote by doubling it. */
162
+function quoted(value: string): string {
163
+ return `'${value.replaceAll("'", "''")}'`;
164
+}
165
+
166
+function involvementClause(involvement: IssueInvolvement): string {
167
+ switch (involvement) {
168
+ case "assigned":
169
+ return " AND [System.AssignedTo] = @Me";
170
+ case "authored":
171
+ return " AND [System.CreatedBy] = @Me";
172
+ // Azure records no mention of a person on a work item, so a mention filter has nothing to narrow by.
173
+ case "mentioned":
174
+ case "all":
175
+ return "";
176
+ }
177
+}
178
+
179
+function stateClause(state: "all" | "open" | "closed", closedStates: ClosedStates): string {
180
+ const closed = `(${[...closedStates].map(quoted).join(", ")})`;
181
+ switch (state) {
182
+ case "open":
183
+ return ` AND [System.State] NOT IN ${closed}`;
184
+ case "closed":
185
+ return ` AND [System.State] IN ${closed}`;
186
+ case "all":
187
+ return "";
188
+ }
189
+}
190
+
191
+/** `<iso changed date>|<id>` of the last row handed over, which is where the next page starts. */
192
+function parseCursor(cursor: string): { readonly changedAt: string; readonly id: number } | null {
193
+ const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)\|([1-9]\d{0,9})$/.exec(cursor);
194
+ return match === null ? null : { changedAt: match[1]!, id: Number(match[2]) };
195
+}
196
+
197
+function reasonFor(error: AzureDevOpsCli.AzureDevOpsCliError): IssueTrackerError["reason"] {
198
+ switch (error._tag) {
199
+ case "AzureDevOpsCliUnavailableError":
200
+ return "missing-tool";
201
+ case "AzureDevOpsCliAuthenticationError":
202
+ return "unauthenticated";
203
+ case "AzureDevOpsCliRateLimitError":
204
+ return "rate-limited";
205
+ case "AzureDevOpsPullRequestNotFoundError":
206
+ return "not-found";
207
+ default:
208
+ return "failed";
209
+ }
210
+}
211
+
212
+export const make: Effect.Effect<
213
+ IssueTrackerApi,
214
+ never,
215
+ AzureDevOpsCli.AzureDevOpsCli | FileSystem.FileSystem
216
+> = Effect.gen(function* () {
217
+ const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
218
+ const fs = yield* FileSystem.FileSystem;
219
+
220
+ const fail = (operation: string) => (error: AzureDevOpsCli.AzureDevOpsCliError) =>
221
+ new IssueTrackerError({
222
+ tracker: KIND,
223
+ operation,
224
+ reason: reasonFor(error),
225
+ detail: error.detail,
226
+ cause: error,
227
+ });
228
+
229
+ const refused = (operation: string, detail: string, cause?: unknown) =>
230
+ new IssueTrackerError({
231
+ tracker: KIND,
232
+ operation,
233
+ reason: "failed",
234
+ detail,
235
+ ...(cause === undefined ? {} : { cause }),
236
+ });
237
+
238
+ const unreadable = (operation: string, cause: unknown) =>
239
+ refused(operation, `Azure DevOps returned an unreadable ${operation} response.`, cause);
240
+
241
+ const notFound = (operation: string) =>
242
+ new IssueTrackerError({
243
+ tracker: KIND,
244
+ operation,
245
+ reason: "not-found",
246
+ detail: "Azure DevOps could not find the requested work item.",
247
+ });
248
+
249
+ const scoped = (
250
+ operation: string,
251
+ input: { readonly host: string; readonly scope: string },
252
+ ): Effect.Effect<
253
+ { readonly organization: string; readonly project: string },
254
+ IssueTrackerError
255
+ > => {
256
+ const parsed = parseScope(input.host, input.scope);
257
+ return parsed === null
258
+ ? Effect.fail(refused(operation, "An Azure DevOps scope is named `organization/project`."))
259
+ : Effect.succeed(parsed);
260
+ };
261
+
262
+ const run = (input: {
263
+ readonly cwd: string;
264
+ readonly operation: string;
265
+ readonly args: ReadonlyArray<string>;
266
+ }) =>
267
+ azure
268
+ .execute({ cwd: input.cwd, args: [...input.args, "--only-show-errors", "--output", "json"] })
269
+ .pipe(
270
+ Effect.map((result) => result.stdout.trim()),
271
+ Effect.mapError(fail(input.operation)),
272
+ );
273
+
274
+ const read = <A>(input: {
275
+ readonly cwd: string;
276
+ readonly operation: string;
277
+ readonly args: ReadonlyArray<string>;
278
+ readonly decode: (raw: string) => Result.Result<A, unknown>;
279
+ }): Effect.Effect<A, IssueTrackerError> =>
280
+ run(input).pipe(
281
+ Effect.flatMap((raw) => {
282
+ const decoded = input.decode(raw);
283
+ return Result.isSuccess(decoded)
284
+ ? Effect.succeed(decoded.success)
285
+ : Effect.fail(unreadable(input.operation, decoded.failure));
286
+ }),
287
+ );
288
+
289
+ const decodeAs =
290
+ <A>(schema: (value: unknown) => Result.Result<A, unknown>) =>
291
+ (raw: string): Result.Result<A, unknown> =>
292
+ Result.flatMap(decodeUnknown(raw), schema);
293
+
294
+ /** A `wit` REST route, addressed by resource and route parameters rather than by URL. */
295
+ const invokeArgs = (input: {
296
+ readonly organization: string;
297
+ readonly project: string;
298
+ readonly resource: string;
299
+ readonly route?: ReadonlyArray<string>;
300
+ readonly query?: ReadonlyArray<string>;
301
+ readonly method?: string;
302
+ readonly apiVersion?: string;
303
+ }) => [
304
+ "devops",
305
+ "invoke",
306
+ "--detect",
307
+ "false",
308
+ "--organization",
309
+ input.organization,
310
+ "--area",
311
+ "wit",
312
+ "--resource",
313
+ input.resource,
314
+ "--api-version",
315
+ input.apiVersion ?? REST_API_VERSION,
316
+ "--route-parameters",
317
+ `project=${input.project}`,
318
+ ...(input.route ?? []),
319
+ ...(input.query === undefined || input.query.length === 0
320
+ ? []
321
+ : ["--query-parameters", ...input.query]),
322
+ ...(input.method === undefined ? [] : ["--http-method", input.method]),
323
+ ];
324
+
325
+ /** A request with a body, which `az devops invoke` only takes from a file. */
326
+ const invokeWithBody = Effect.fn("AzureDevOpsIssueTracker.invokeWithBody")(function* (input: {
327
+ readonly cwd: string;
328
+ readonly operation: string;
329
+ readonly args: ReadonlyArray<string>;
330
+ readonly body: unknown;
331
+ }) {
332
+ const unwritable = (cause: unknown) =>
333
+ refused(input.operation, "Could not write the Azure DevOps request body.", cause);
334
+ const file = yield* fs
335
+ .makeTempFileScoped({ prefix: "t3-azure-issue-" })
336
+ .pipe(Effect.mapError(unwritable));
337
+ yield* fs.writeFileString(file, encodeJson(input.body)).pipe(Effect.mapError(unwritable));
338
+ return yield* run({
339
+ cwd: input.cwd,
340
+ operation: input.operation,
341
+ args: [...input.args, "--in-file", file, "--media-type", "application/json"],
342
+ });
343
+ }, Effect.scoped);
344
+
345
+ const workItemTypes = (input: {
346
+ readonly cwd: string;
347
+ readonly operation: string;
348
+ readonly organization: string;
349
+ readonly project: string;
350
+ }) =>
351
+ read({
352
+ cwd: input.cwd,
353
+ operation: input.operation,
354
+ args: invokeArgs({ ...input, resource: "workitemtypes" }),
355
+ decode: decodeAs(decodeTypes),
356
+ }).pipe(Effect.map((types) => types.value));
357
+
358
+ const closedStates = (input: Parameters<typeof workItemTypes>[0]) =>
359
+ workItemTypes(input).pipe(Effect.map(closedStateNames));
360
+
361
+ const workItem = (input: {
362
+ readonly cwd: string;
363
+ readonly operation: string;
364
+ readonly organization: string;
365
+ readonly number: number;
366
+ readonly closed: ClosedStates;
367
+ }): Effect.Effect<AzureDevOpsWorkItem, IssueTrackerError> =>
368
+ read({
369
+ cwd: input.cwd,
370
+ operation: input.operation,
371
+ args: [
372
+ "boards",
373
+ "work-item",
374
+ "show",
375
+ "--detect",
376
+ "false",
377
+ "--organization",
378
+ input.organization,
379
+ "--id",
380
+ String(input.number),
381
+ "--expand",
382
+ "relations",
383
+ ],
384
+ decode: (raw) => decodeWorkItemJson(raw, input.closed),
385
+ }).pipe(
386
+ Effect.filterOrFail(
387
+ (item) => item !== null,
388
+ () => notFound(input.operation),
389
+ ),
390
+ );
391
+
392
+ /** The work item as `az` addresses it, or a not-found for a key that names no id. */
393
+ const target = (
394
+ operation: string,
395
+ input: { readonly host: string; readonly scope: string; readonly key: string },
396
+ ) =>
397
+ scoped(operation, input).pipe(
398
+ Effect.flatMap((scope) => {
399
+ const number = parseNumber(input.key);
400
+ return number === null
401
+ ? Effect.fail(notFound(operation))
402
+ : Effect.succeed({ ...scope, number });
403
+ }),
404
+ );
405
+
406
+ const comments = (input: {
407
+ readonly cwd: string;
408
+ readonly operation: string;
409
+ readonly organization: string;
410
+ readonly project: string;
411
+ readonly number: number;
412
+ readonly cursor?: string | undefined;
413
+ }) =>
414
+ read({
415
+ cwd: input.cwd,
416
+ operation: input.operation,
417
+ args: invokeArgs({
418
+ ...input,
419
+ resource: "comments",
420
+ route: [`workItemId=${input.number}`],
421
+ apiVersion: "7.1-preview",
422
+ query: [
423
+ `$top=${PAGE_SIZE}`,
424
+ "order=asc",
425
+ "$expand=reactions",
426
+ "api-version=7.1-preview.4",
427
+ ...(input.cursor === undefined ? [] : [`continuationToken=${input.cursor}`]),
428
+ ],
429
+ }),
430
+ decode: decodeCommentsJson,
431
+ });
432
+
433
+ const linkedPullRequests = (input: {
434
+ readonly cwd: string;
435
+ readonly organization: string;
436
+ readonly item: AzureDevOpsWorkItem;
437
+ }): Effect.Effect<ReadonlyArray<IssueLinkedPullRequest>, IssueTrackerError> => {
438
+ const numbers = [
439
+ ...new Set(input.item.relations.flatMap((relation) => pullRequestNumberOf(relation) ?? [])),
440
+ ].slice(0, LINKED_PULL_REQUEST_LIMIT);
441
+ return Effect.forEach(
442
+ numbers,
443
+ (number) =>
444
+ read({
445
+ cwd: input.cwd,
446
+ operation: "getIssue",
447
+ args: [
448
+ "repos",
449
+ "pr",
450
+ "show",
451
+ "--detect",
452
+ "false",
453
+ "--organization",
454
+ input.organization,
455
+ "--id",
456
+ String(number),
457
+ ],
458
+ decode: decodePullRequestJson,
459
+ }).pipe(
460
+ Effect.map((pullRequest) =>
461
+ pullRequest === null || pullRequest.location === null
462
+ ? []
463
+ : [
464
+ {
465
+ repository: `${pullRequest.location.project}/${pullRequest.location.repository}`,
466
+ number: pullRequest.number,
467
+ title: pullRequest.title,
468
+ url: pullRequest.url,
469
+ state: pullRequest.state,
470
+ isDraft: pullRequest.isDraft,
471
+ // Azure links a pull request to a work item but never says whether completing
472
+ // it resolves the item; that lives in a completion option nothing reports.
473
+ closesIssue: false,
474
+ },
475
+ ],
476
+ ),
477
+ // A link to a pull request this account cannot see is left out, not a failed detail.
478
+ Effect.catchIf(
479
+ (error) => error.reason === "not-found",
480
+ () => Effect.succeed([]),
481
+ ),
482
+ ),
483
+ { concurrency: 2 },
484
+ ).pipe(Effect.map((links) => links.flat()));
485
+ };
486
+
487
+ const update = (input: {
488
+ readonly cwd: string;
489
+ readonly operation: string;
490
+ readonly organization: string;
491
+ readonly number: number;
492
+ readonly args: ReadonlyArray<string>;
493
+ }) =>
494
+ run({
495
+ cwd: input.cwd,
496
+ operation: input.operation,
497
+ args: [
498
+ "boards",
499
+ "work-item",
500
+ "update",
501
+ "--detect",
502
+ "false",
503
+ "--organization",
504
+ input.organization,
505
+ "--id",
506
+ String(input.number),
507
+ ...input.args,
508
+ ],
509
+ }).pipe(Effect.asVoid);
510
+
511
+ /** Azure keeps tags as one `; `-joined field and takes exactly one assignee. */
512
+ const fieldArgs = (input: {
513
+ readonly labels?: ReadonlyArray<string> | undefined;
514
+ readonly assignees?: ReadonlyArray<string> | undefined;
515
+ }): ReadonlyArray<string> => {
516
+ const fields = [
517
+ ...(input.labels === undefined ? [] : [`System.Tags=${input.labels.join("; ")}`]),
518
+ ...(input.assignees === undefined ? [] : [`System.AssignedTo=${input.assignees[0] ?? ""}`]),
519
+ ];
520
+ return fields.length === 0 ? [] : ["--fields", ...fields];
521
+ };
522
+
523
+ return {
524
+ kind: KIND,
525
+ capabilities: CAPABILITIES,
526
+
527
+ // The profile the token belongs to, which is what WIQL's `@Me` resolves to. Its email is the
528
+ // `uniqueName` every identity on a work item carries, so the two compare.
529
+ getViewer: (input) =>
530
+ read({
531
+ cwd: input.cwd,
532
+ operation: "getViewer",
533
+ args: [
534
+ "devops",
535
+ "invoke",
536
+ "--detect",
537
+ "true",
538
+ "--area",
539
+ "profile",
540
+ "--resource",
541
+ "profiles",
542
+ "--api-version",
543
+ REST_API_VERSION,
544
+ "--route-parameters",
545
+ "id=me",
546
+ ],
547
+ decode: decodeProfileJson,
548
+ }).pipe(
549
+ Effect.filterOrFail(
550
+ (login) => login !== null,
551
+ () => refused("getViewer", "Azure DevOps could not name the signed-in account."),
552
+ ),
553
+ ),
554
+
555
+ listIssues: (input) => {
556
+ const cursor = input.cursor === undefined ? undefined : parseCursor(input.cursor);
557
+ if (cursor === null) {
558
+ return Effect.fail(
559
+ refused("listIssues", "The cursor was not one Azure DevOps handed out."),
560
+ );
561
+ }
562
+ const limit = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
563
+ const text = input.query?.trim() ?? "";
564
+ return scoped("listIssues", input).pipe(
565
+ Effect.flatMap((scope) =>
566
+ closedStates({ ...scope, cwd: input.cwd, operation: "listIssues" }).pipe(
567
+ Effect.map((closed) => ({ scope, closed })),
568
+ ),
569
+ ),
570
+ Effect.flatMap(({ scope, closed }) =>
571
+ invokeWithBody({
572
+ cwd: input.cwd,
573
+ operation: "listIssues",
574
+ args: invokeArgs({
575
+ ...scope,
576
+ resource: "wiql",
577
+ method: "POST",
578
+ // One more than the page, which is how a next page reveals itself.
579
+ query: ["timePrecision=true", `$top=${limit + 1}`],
580
+ }),
581
+ body: {
582
+ query:
583
+ `SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = ${quoted(scope.project)}` +
584
+ stateClause(input.state, closed) +
585
+ involvementClause(input.involvement) +
586
+ (text.length === 0 ? "" : ` AND [System.Title] CONTAINS ${quoted(text)}`) +
587
+ (cursor === undefined
588
+ ? ""
589
+ : ` AND ([System.ChangedDate] < ${quoted(cursor.changedAt)} OR ([System.ChangedDate] = ${quoted(cursor.changedAt)} AND [System.Id] < ${cursor.id}))`) +
590
+ " ORDER BY [System.ChangedDate] DESC, [System.Id] DESC",
591
+ },
592
+ }).pipe(
593
+ Effect.flatMap((raw) => {
594
+ const decoded = decodeAs(decodeWiql)(raw);
595
+ return Result.isSuccess(decoded)
596
+ ? Effect.succeed(decoded.success.workItems ?? [])
597
+ : Effect.fail(unreadable("listIssues", decoded.failure));
598
+ }),
599
+ Effect.flatMap((ids) =>
600
+ ids.length === 0
601
+ ? Effect.succeed({ items: [], nextCursor: null })
602
+ : read({
603
+ cwd: input.cwd,
604
+ operation: "listIssues",
605
+ args: invokeArgs({
606
+ ...scope,
607
+ resource: "workitems",
608
+ query: [
609
+ `ids=${ids
610
+ .slice(0, limit)
611
+ .map((row) => row.id)
612
+ .join(",")}`,
613
+ `fields=${LIST_FIELDS.join(",")}`,
614
+ ],
615
+ }),
616
+ decode: (raw) => decodeWorkItemsJson(raw, closed),
617
+ }).pipe(
618
+ Effect.map((items) => {
619
+ const last = items.at(-1);
620
+ return {
621
+ items,
622
+ nextCursor:
623
+ ids.length > limit && last !== undefined
624
+ ? `${last.updatedAt}|${last.key}`
625
+ : null,
626
+ };
627
+ }),
628
+ ),
629
+ ),
630
+ ),
631
+ ),
632
+ );
633
+ },
634
+
635
+ getIssue: (input) =>
636
+ target("getIssue", input).pipe(
637
+ Effect.flatMap((scope) =>
638
+ closedStates({ ...scope, cwd: input.cwd, operation: "getIssue" }).pipe(
639
+ Effect.flatMap((closed) =>
640
+ workItem({ ...scope, cwd: input.cwd, operation: "getIssue", closed }).pipe(
641
+ Effect.map((item) => ({ item, closed })),
642
+ ),
643
+ ),
644
+ Effect.flatMap(({ item, closed }) =>
645
+ Effect.all(
646
+ [
647
+ comments({ ...scope, cwd: input.cwd, operation: "getIssue" }),
648
+ read({
649
+ cwd: input.cwd,
650
+ operation: "getIssue",
651
+ args: invokeArgs({
652
+ ...scope,
653
+ resource: "updates",
654
+ route: [`id=${scope.number}`],
655
+ query: [`$top=${PAGE_SIZE}`],
656
+ }),
657
+ decode: (raw) => decodeUpdatesJson(raw, closed),
658
+ }),
659
+ linkedPullRequests({ cwd: input.cwd, organization: scope.organization, item }),
660
+ ],
661
+ { concurrency: 3 },
662
+ ).pipe(
663
+ Effect.map(([conversation, events, links]) => ({
664
+ ...item,
665
+ // Nothing cheap names the viewer here; the service already read it per host.
666
+ viewer: null,
667
+ viewerPermissions: VIEWER_PERMISSIONS,
668
+ comments: conversation.comments,
669
+ commentsCursor: conversation.nextCursor,
670
+ events,
671
+ linkedPullRequests: links,
672
+ })),
673
+ ),
674
+ ),
675
+ ),
676
+ ),
677
+ ),
678
+
679
+ getComments: (input) =>
680
+ target("getComments", input).pipe(
681
+ Effect.flatMap((scope) =>
682
+ comments({ ...scope, cwd: input.cwd, operation: "getComments", cursor: input.cursor }),
683
+ ),
684
+ ),
685
+
686
+ create: (input) =>
687
+ scoped("create", input).pipe(
688
+ Effect.flatMap((scope) =>
689
+ workItemTypes({ ...scope, cwd: input.cwd, operation: "create" }).pipe(
690
+ Effect.flatMap((types) => {
691
+ const names = types.flatMap((type) => (type.isDisabled ? [] : [type.name]));
692
+ const type = CREATE_TYPES.find((name) => names.includes(name)) ?? names[0];
693
+ return type === undefined
694
+ ? Effect.fail(refused("create", "The project offers no work item type to file."))
695
+ : Effect.succeed({ type, closed: closedStateNames(types) });
696
+ }),
697
+ Effect.flatMap(({ type, closed }) =>
698
+ read({
699
+ cwd: input.cwd,
700
+ operation: "create",
701
+ args: [
702
+ "boards",
703
+ "work-item",
704
+ "create",
705
+ "--detect",
706
+ "false",
707
+ "--organization",
708
+ scope.organization,
709
+ "--project",
710
+ scope.project,
711
+ "--type",
712
+ type,
713
+ "--title",
714
+ input.title,
715
+ ...(input.body.length === 0 ? [] : ["--description", input.body]),
716
+ ...fieldArgs({
717
+ ...(input.labels.length === 0 ? {} : { labels: input.labels }),
718
+ ...(input.assignees.length === 0 ? {} : { assignees: input.assignees }),
719
+ }),
720
+ ],
721
+ decode: (raw) => decodeWorkItemJson(raw, closed),
722
+ }),
723
+ ),
724
+ Effect.filterOrFail(
725
+ (item) => item !== null,
726
+ () => unreadable("create", "incomplete-response"),
727
+ ),
728
+ Effect.map((item) => ({ key: item.key, displayKey: item.displayKey, url: item.url })),
729
+ ),
730
+ ),
731
+ ),
732
+
733
+ comment: (input) =>
734
+ target("comment", input).pipe(
735
+ Effect.flatMap((scope) =>
736
+ invokeWithBody({
737
+ cwd: input.cwd,
738
+ operation: "comment",
739
+ args: invokeArgs({
740
+ ...scope,
741
+ resource: "comments",
742
+ route: [`workItemId=${scope.number}`],
743
+ method: "POST",
744
+ apiVersion: "7.1-preview",
745
+ query: ["format=markdown", "api-version=7.1-preview.4"],
746
+ }),
747
+ body: { text: input.body },
748
+ }),
749
+ ),
750
+ Effect.asVoid,
751
+ ),
752
+
753
+ update: (input) =>
754
+ target("update", input).pipe(
755
+ Effect.flatMap((scope) =>
756
+ update({
757
+ ...scope,
758
+ cwd: input.cwd,
759
+ operation: "update",
760
+ args: [
761
+ ...(input.title === undefined ? [] : ["--title", input.title]),
762
+ ...(input.body === undefined ? [] : ["--description", input.body]),
763
+ ...fieldArgs(input),
764
+ ],
765
+ }),
766
+ ),
767
+ ),
768
+
769
+ setState: (input) =>
770
+ target("setState", input).pipe(
771
+ Effect.flatMap((scope) =>
772
+ update({
773
+ ...scope,
774
+ cwd: input.cwd,
775
+ operation: "setState",
776
+ args: ["--state", input.state],
777
+ }),
778
+ ),
779
+ ),
780
+
781
+ setReaction: (input) =>
782
+ target("setReaction", input).pipe(
783
+ Effect.flatMap((scope) => {
784
+ const type = azureDevOpsReactionType(input.content);
785
+ if (input.subjectId === undefined) {
786
+ return Effect.fail(
787
+ refused("setReaction", "Azure DevOps reactions go on comments only."),
788
+ );
789
+ }
790
+ if (!/^[1-9]\d{0,9}$/.test(input.subjectId)) {
791
+ return Effect.fail(
792
+ refused("setReaction", "The comment id names no Azure DevOps comment."),
793
+ );
794
+ }
795
+ if (type === null) {
796
+ return Effect.fail(refused("setReaction", "Azure DevOps has no such reaction."));
797
+ }
798
+ return run({
799
+ cwd: input.cwd,
800
+ operation: "setReaction",
801
+ args: invokeArgs({
802
+ ...scope,
803
+ resource: "commentsReactions",
804
+ route: [
805
+ `workItemId=${scope.number}`,
806
+ `commentId=${input.subjectId}`,
807
+ `reactionType=${type}`,
808
+ ],
809
+ method: input.reacted ? "PUT" : "DELETE",
810
+ apiVersion: "7.1-preview",
811
+ query: ["api-version=7.1-preview.1"],
812
+ }),
813
+ }).pipe(Effect.asVoid);
814
+ }),
815
+ ),
816
+
817
+ listCandidates: (input) =>
818
+ scoped("listCandidates", input).pipe(
819
+ Effect.flatMap((scope) =>
820
+ Effect.all(
821
+ [
822
+ read({
823
+ cwd: input.cwd,
824
+ operation: "listCandidates",
825
+ args: invokeArgs({ ...scope, resource: "tags" }),
826
+ decode: decodeAs(decodeTags),
827
+ }).pipe(
828
+ Effect.map((tags) =>
829
+ tags.value.map((tag) => ({ name: tag.name, color: null, description: null })),
830
+ ),
831
+ ),
832
+ // Nothing in `az boards` lists who a work item may go to; the project's teams are
833
+ // the nearest thing, read a handful at a time.
834
+ read({
835
+ cwd: input.cwd,
836
+ operation: "listCandidates",
837
+ args: [
838
+ "devops",
839
+ "team",
840
+ "list",
841
+ "--detect",
842
+ "false",
843
+ "--organization",
844
+ scope.organization,
845
+ "--project",
846
+ scope.project,
847
+ "--top",
848
+ "10",
849
+ ],
850
+ decode: decodeAs(decodeTeams),
851
+ }).pipe(
852
+ Effect.flatMap((teams) =>
853
+ Effect.forEach(
854
+ teams,
855
+ (team) =>
856
+ read({
857
+ cwd: input.cwd,
858
+ operation: "listCandidates",
859
+ args: [
860
+ "devops",
861
+ "team",
862
+ "list-member",
863
+ "--detect",
864
+ "false",
865
+ "--organization",
866
+ scope.organization,
867
+ "--project",
868
+ scope.project,
869
+ "--team",
870
+ team.id,
871
+ "--top",
872
+ String(PAGE_SIZE),
873
+ ],
874
+ decode: decodeAs(decodeMembers),
875
+ }),
876
+ { concurrency: 3 },
877
+ ),
878
+ ),
879
+ Effect.map((members) => {
880
+ const byLogin = new Map<
881
+ string,
882
+ { id: string; login: string; name: string | null; avatarUrl: string | null }
883
+ >();
884
+ for (const { identity } of members.flat()) {
885
+ const login = identity.uniqueName.trim();
886
+ if (
887
+ identity.isContainer ||
888
+ login.length === 0 ||
889
+ byLogin.has(login.toLowerCase())
890
+ ) {
891
+ continue;
892
+ }
893
+ byLogin.set(login.toLowerCase(), {
894
+ id: login,
895
+ login,
896
+ name: identity.displayName?.trim() || null,
897
+ avatarUrl: identity.imageUrl?.trim() || null,
898
+ });
899
+ }
900
+ return [...byLogin.values()];
901
+ }),
902
+ ),
903
+ ],
904
+ { concurrency: 2 },
905
+ ),
906
+ ),
907
+ // Teams are a sample of who can be assigned, so somebody missing is not ineligible.
908
+ Effect.map(([labels, assignees]) => ({ labels, assignees, truncated: true })),
909
+ ),
910
+ };
911
+});
packages/source-control-azure-devops/src/server/azureDevOpsIssueJson.ts
new
+389
@@ -0,0 +1,389 @@
1
+/**
2
+ * Decoders for Azure DevOps work items as `az boards` and the `wit` REST area answer them. Azure
3
+ * keeps everything under `fields`, keyed by reference name, and a project may add fields of its
4
+ * own, so only the ones every work item type carries are read.
5
+ *
6
+ * @module source-control-azure-devops/server/azureDevOpsIssueJson
7
+ */
8
+import * as Exit from "effect/Exit";
9
+import * as Result from "effect/Result";
10
+import * as Schema from "effect/Schema";
11
+import type {
12
+ IssueActor,
13
+ IssueComment,
14
+ IssueEvent,
15
+ IssueLabel,
16
+ IssueReaction,
17
+ IssueReactionContent,
18
+ IssueState,
19
+} from "@t3tools/contracts";
20
+import { decodeJsonResult } from "@t3tools/shared/schemaJson";
21
+import type { TrackerIssueSummary } from "@t3tools/source-control-core/server/IssueTracker";
22
+
23
+/** Lowercased names of the states a project treats as finished, read by `closedStateNames`. */
24
+export type ClosedStates = ReadonlySet<string>;
25
+
26
+/** The finished states of Azure's stock processes, for a project whose types report none. */
27
+const STOCK_CLOSED_STATES: ClosedStates = new Set([
28
+ "closed",
29
+ "done",
30
+ "removed",
31
+ "resolved",
32
+ "completed",
33
+]);
34
+
35
+const FINISHED_CATEGORIES: ReadonlySet<string> = new Set(["Resolved", "Completed", "Removed"]);
36
+
37
+/**
38
+ * A project's finished states, from its work item types' state categories. Custom processes
39
+ * name their own columns, so the category, not the name, says whether one is finished.
40
+ */
41
+export function closedStateNames(
42
+ types: ReadonlyArray<{
43
+ readonly states?:
44
+ | ReadonlyArray<{ readonly name: string; readonly category: string }>
45
+ | undefined;
46
+ }>,
47
+): ClosedStates {
48
+ const names = types.flatMap((type) =>
49
+ (type.states ?? []).flatMap((state) =>
50
+ FINISHED_CATEGORIES.has(state.category) ? [state.name.toLowerCase()] : [],
51
+ ),
52
+ );
53
+ return names.length === 0 ? STOCK_CLOSED_STATES : new Set(names);
54
+}
55
+
56
+const Identity = Schema.Struct({
57
+ displayName: Schema.optional(Schema.NullOr(Schema.String)),
58
+ uniqueName: Schema.optional(Schema.NullOr(Schema.String)),
59
+ imageUrl: Schema.optional(Schema.NullOr(Schema.String)),
60
+});
61
+
62
+/** WIQL answers an identity as an object; a project rule can leave a plain "Name <email>" string. */
63
+const IdentityValue = Schema.NullOr(Schema.Union([Identity, Schema.String]));
64
+
65
+const Fields = Schema.Struct({
66
+ "System.CommentCount": Schema.optional(Schema.NullOr(Schema.Int)),
67
+ "System.Title": Schema.optional(Schema.NullOr(Schema.String)),
68
+ "System.State": Schema.optional(Schema.NullOr(Schema.String)),
69
+ "System.CreatedDate": Schema.optional(Schema.NullOr(Schema.String)),
70
+ "System.ChangedDate": Schema.optional(Schema.NullOr(Schema.String)),
71
+ "Microsoft.VSTS.Common.ClosedDate": Schema.optional(Schema.NullOr(Schema.String)),
72
+ "System.Description": Schema.optional(Schema.NullOr(Schema.String)),
73
+ "System.Tags": Schema.optional(Schema.NullOr(Schema.String)),
74
+ "System.TeamProject": Schema.optional(Schema.NullOr(Schema.String)),
75
+ "System.CreatedBy": Schema.optional(IdentityValue),
76
+ "System.AssignedTo": Schema.optional(IdentityValue),
77
+});
78
+
79
+const Relation = Schema.Struct({ rel: Schema.String, url: Schema.String });
80
+
81
+const WorkItem = Schema.Struct({
82
+ id: Schema.Int,
83
+ url: Schema.optional(Schema.NullOr(Schema.String)),
84
+ fields: Schema.optional(Schema.NullOr(Fields)),
85
+ relations: Schema.optional(Schema.NullOr(Schema.Array(Relation))),
86
+});
87
+
88
+const decodeWorkItemEntry = Schema.decodeUnknownExit(WorkItem);
89
+const decodeUnknownList = decodeJsonResult(Schema.NullOr(Schema.Array(Schema.Unknown)));
90
+const decodeWorkItem = decodeJsonResult(WorkItem);
91
+
92
+type DecodeFailure =
93
+ ReturnType<typeof decodeWorkItem> extends Result.Result<unknown, infer E> ? E : never;
94
+
95
+function trimmed(value: string | null | undefined): string | null {
96
+ const text = value?.trim() ?? "";
97
+ return text.length > 0 ? text : null;
98
+}
99
+
100
+/**
101
+ * The organization link `az` returns addresses the REST resource, which is not a page anybody can
102
+ * open. The one a reader wants is the board's own item, which Azure spells this way.
103
+ */
104
+function browserUrl(
105
+ apiUrl: string | null | undefined,
106
+ id: number,
107
+ project: string | null,
108
+): string | null {
109
+ if (apiUrl === null || apiUrl === undefined || project === null) return null;
110
+ const match = /^(https?:\/\/[^/]+\/[^/]+)\/(?:[^/]+\/)?_apis\/wit\/workItems\//i.exec(apiUrl);
111
+ return match === null ? null : `${match[1]}/${encodeURIComponent(project)}/_workitems/edit/${id}`;
112
+}
113
+
114
+function toActor(value: typeof IdentityValue.Type | undefined): IssueActor | null {
115
+ if (value === null || value === undefined) return null;
116
+ if (typeof value === "string") {
117
+ const login = trimmed(value);
118
+ return login === null ? null : { login, name: null, avatarUrl: null };
119
+ }
120
+ const login = trimmed(value.uniqueName) ?? trimmed(value.displayName);
121
+ return login === null
122
+ ? null
123
+ : { login, name: trimmed(value.displayName), avatarUrl: trimmed(value.imageUrl) };
124
+}
125
+
126
+function toIssueState(name: string | null | undefined, closed: ClosedStates): IssueState {
127
+ const state = trimmed(name) ?? "New";
128
+ return { category: closed.has(state.toLowerCase()) ? "closed" : "open", name: state };
129
+}
130
+
131
+/** Azure keeps tags as one `; `-separated string, with no colour anywhere. */
132
+function toLabels(tags: string | null | undefined): ReadonlyArray<IssueLabel> {
133
+ return [...new Set((tags ?? "").split(";").flatMap((tag) => trimmed(tag) ?? []))].map((name) => ({
134
+ name,
135
+ color: null,
136
+ }));
137
+}
138
+
139
+export interface AzureDevOpsWorkItem extends TrackerIssueSummary {
140
+ readonly body: string;
141
+ readonly project: string | null;
142
+ readonly relations: ReadonlyArray<typeof Relation.Type>;
143
+}
144
+
145
+/** Null for a row this cannot place: no title, no dates, or no project to build a link from. */
146
+function toWorkItem(raw: typeof WorkItem.Type, closed: ClosedStates): AzureDevOpsWorkItem | null {
147
+ const fields = raw.fields ?? {};
148
+ const title = trimmed(fields["System.Title"]);
149
+ const createdAt = trimmed(fields["System.CreatedDate"]);
150
+ const updatedAt = trimmed(fields["System.ChangedDate"]) ?? createdAt;
151
+ const project = trimmed(fields["System.TeamProject"]);
152
+ const url = browserUrl(raw.url, raw.id, project);
153
+ if (raw.id <= 0 || title === null || createdAt === null || updatedAt === null || url === null) {
154
+ return null;
155
+ }
156
+ const assignee = toActor(fields["System.AssignedTo"]);
157
+ return {
158
+ key: String(raw.id),
159
+ displayKey: `#${raw.id}`,
160
+ title,
161
+ url,
162
+ author: toActor(fields["System.CreatedBy"]),
163
+ state: toIssueState(fields["System.State"], closed),
164
+ createdAt,
165
+ updatedAt,
166
+ closedAt: trimmed(fields["Microsoft.VSTS.Common.ClosedDate"]),
167
+ assignees: assignee === null ? [] : [assignee],
168
+ labels: toLabels(fields["System.Tags"]),
169
+ commentCount: Math.max(0, fields["System.CommentCount"] ?? 0),
170
+ body: fields["System.Description"] ?? "",
171
+ project,
172
+ relations: raw.relations ?? [],
173
+ };
174
+}
175
+
176
+/** A flat WIQL answer; a row this cannot place is skipped rather than failing the page. */
177
+export function decodeWorkItemsJson(
178
+ raw: string,
179
+ closed: ClosedStates,
180
+): Result.Result<ReadonlyArray<AzureDevOpsWorkItem>, DecodeFailure> {
181
+ return Result.map(decodeUnknownList(raw.trim().length === 0 ? "[]" : raw), (rows) =>
182
+ (rows ?? []).flatMap((entry) => {
183
+ const item = decodeWorkItemEntry(entry);
184
+ if (Exit.isFailure(item)) return [];
185
+ return toWorkItem(item.value, closed) ?? [];
186
+ }),
187
+ );
188
+}
189
+
190
+/** Null where az answered with a work item this cannot place, which the caller reports as such. */
191
+export function decodeWorkItemJson(
192
+ raw: string,
193
+ closed: ClosedStates,
194
+): Result.Result<AzureDevOpsWorkItem | null, DecodeFailure> {
195
+ return Result.map(decodeWorkItem(raw), (item) => toWorkItem(item, closed));
196
+}
197
+
198
+/** Azure names comment reactions after its own icons; the six it has map onto the contract's. */
199
+const CONTENT_BY_REACTION: Readonly<Record<string, IssueReactionContent>> = {
200
+ like: "thumbs-up",
201
+ dislike: "thumbs-down",
202
+ heart: "heart",
203
+ hooray: "hooray",
204
+ smile: "laugh",
205
+ confused: "confused",
206
+};
207
+
208
+export function azureDevOpsReactionType(content: IssueReactionContent): string | null {
209
+ return Object.entries(CONTENT_BY_REACTION).find(([, mapped]) => mapped === content)?.[0] ?? null;
210
+}
211
+
212
+const Comment = Schema.Struct({
213
+ id: Schema.Int,
214
+ text: Schema.optional(Schema.NullOr(Schema.String)),
215
+ createdDate: Schema.String,
216
+ createdBy: Schema.optional(Schema.NullOr(Identity)),
217
+ isDeleted: Schema.optional(Schema.Boolean),
218
+ reactions: Schema.optional(
219
+ Schema.NullOr(
220
+ Schema.Array(
221
+ Schema.Struct({
222
+ type: Schema.String,
223
+ count: Schema.Int,
224
+ isCurrentUserEngaged: Schema.optional(Schema.Boolean),
225
+ }),
226
+ ),
227
+ ),
228
+ ),
229
+});
230
+
231
+const CommentsPage = Schema.Struct({
232
+ comments: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))),
233
+ continuationToken: Schema.optional(Schema.NullOr(Schema.String)),
234
+});
235
+
236
+const decodeCommentsPage = decodeJsonResult(CommentsPage);
237
+const decodeCommentEntry = Schema.decodeUnknownExit(Comment);
238
+
239
+function toReactions(raw: (typeof Comment.Type)["reactions"]): ReadonlyArray<IssueReaction> {
240
+ return (raw ?? []).flatMap((reaction) => {
241
+ const content = CONTENT_BY_REACTION[reaction.type.toLowerCase()];
242
+ return content === undefined || reaction.count <= 0
243
+ ? []
244
+ : [
245
+ {
246
+ content,
247
+ count: reaction.count,
248
+ // Azure counts reactions and says whether the reader is among them, but names nobody.
249
+ actors: [],
250
+ viewerHasReacted: reaction.isCurrentUserEngaged ?? false,
251
+ },
252
+ ];
253
+ });
254
+}
255
+
256
+export function decodeCommentsJson(
257
+ raw: string,
258
+): Result.Result<
259
+ { readonly comments: ReadonlyArray<IssueComment>; readonly nextCursor: string | null },
260
+ DecodeFailure
261
+> {
262
+ return Result.map(decodeCommentsPage(raw), (page) => ({
263
+ comments: (page.comments ?? []).flatMap((entry) => {
264
+ const comment = decodeCommentEntry(entry);
265
+ if (Exit.isFailure(comment) || comment.value.isDeleted === true) return [];
266
+ return [
267
+ {
268
+ id: String(comment.value.id),
269
+ author: toActor(comment.value.createdBy),
270
+ body: comment.value.text ?? "",
271
+ createdAt: comment.value.createdDate,
272
+ url: null,
273
+ reactions: toReactions(comment.value.reactions),
274
+ },
275
+ ];
276
+ }),
277
+ nextCursor: trimmed(page.continuationToken),
278
+ }));
279
+}
280
+
281
+const FieldChange = Schema.Struct({
282
+ oldValue: Schema.optional(Schema.Unknown),
283
+ newValue: Schema.optional(Schema.Unknown),
284
+});
285
+
286
+const Update = Schema.Struct({
287
+ id: Schema.Int,
288
+ revisedDate: Schema.String,
289
+ revisedBy: Schema.optional(Schema.NullOr(Identity)),
290
+ fields: Schema.optional(Schema.NullOr(Schema.Record(Schema.String, FieldChange))),
291
+});
292
+
293
+const decodeUpdatesPage = decodeJsonResult(
294
+ Schema.Struct({ value: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))) }),
295
+);
296
+const decodeUpdateEntry = Schema.decodeUnknownExit(Update);
297
+const decodeIdentityValue = Schema.decodeUnknownExit(IdentityValue);
298
+
299
+function identityLogin(value: unknown): string | null {
300
+ const decoded = decodeIdentityValue(value);
301
+ return Exit.isSuccess(decoded) ? (toActor(decoded.value)?.login ?? null) : null;
302
+}
303
+
304
+/**
305
+ * The timeline, read out of each revision's field changes. Azure reads `9999-01-01` as the changed
306
+ * date of the newest revision, so the revision's own date is what every event carries.
307
+ */
308
+export function decodeUpdatesJson(
309
+ raw: string,
310
+ closed: ClosedStates,
311
+): Result.Result<ReadonlyArray<IssueEvent>, DecodeFailure> {
312
+ return Result.map(decodeUpdatesPage(raw), (page) =>
313
+ (page.value ?? []).flatMap((entry) => {
314
+ const update = decodeUpdateEntry(entry);
315
+ if (Exit.isFailure(update) || update.value.id === 1) return [];
316
+ const { id, revisedBy, revisedDate } = update.value;
317
+ const fields = update.value.fields ?? {};
318
+ const events: IssueEvent[] = [];
319
+ const add = (kind: IssueEvent["kind"], detail: string | null) =>
320
+ events.push({
321
+ id: `update-${id}-${events.length}`,
322
+ kind,
323
+ actor: toActor(revisedBy),
324
+ createdAt: revisedDate,
325
+ detail,
326
+ });
327
+ const state = fields["System.State"];
328
+ if (typeof state?.oldValue === "string" && typeof state.newValue === "string") {
329
+ const was = toIssueState(state.oldValue, closed);
330
+ const now = toIssueState(state.newValue, closed);
331
+ add(
332
+ was.category === now.category
333
+ ? "state-changed"
334
+ : now.category === "closed"
335
+ ? "closed"
336
+ : "reopened",
337
+ now.name,
338
+ );
339
+ }
340
+ const title = fields["System.Title"];
341
+ if (typeof title?.oldValue === "string" && typeof title.newValue === "string") {
342
+ add("renamed", trimmed(title.newValue));
343
+ }
344
+ const tags = fields["System.Tags"];
345
+ if (tags !== undefined) {
346
+ const before = toLabels(typeof tags.oldValue === "string" ? tags.oldValue : null);
347
+ const after = toLabels(typeof tags.newValue === "string" ? tags.newValue : null);
348
+ for (const tag of before)
349
+ if (!after.some((label) => label.name === tag.name)) add("unlabeled", tag.name);
350
+ for (const tag of after)
351
+ if (!before.some((label) => label.name === tag.name)) add("labeled", tag.name);
352
+ }
353
+ const assigned = fields["System.AssignedTo"];
354
+ if (assigned !== undefined) {
355
+ const before = identityLogin(assigned.oldValue);
356
+ const after = identityLogin(assigned.newValue);
357
+ if (before !== after) {
358
+ if (before !== null) add("unassigned", before);
359
+ if (after !== null) add("assigned", after);
360
+ }
361
+ }
362
+ return events;
363
+ }),
364
+ );
365
+}
366
+
367
+/** A relation that links a pull request, as Azure spells it: `vstfs:///Git/PullRequestId/{project}/{repo}/{id}`. */
368
+export function pullRequestNumberOf(relation: typeof Relation.Type): number | null {
369
+ if (relation.rel !== "ArtifactLink") return null;
370
+ const match = /^vstfs:\/\/\/Git\/PullRequestId\/(.+)$/.exec(relation.url);
371
+ if (match === null) return null;
372
+ const number = decodeURIComponent(match[1]!).split("/").at(-1) ?? "";
373
+ return /^[1-9]\d{0,9}$/.test(number) ? Number(number) : null;
374
+}
375
+
376
+const Profile = Schema.Struct({
377
+ emailAddress: Schema.optional(Schema.NullOr(Schema.String)),
378
+ displayName: Schema.optional(Schema.NullOr(Schema.String)),
379
+});
380
+
381
+const decodeProfile = decodeJsonResult(Profile);
382
+
383
+/** `GET profile/profiles/me` names the signed-in account, which WIQL's `@Me` compares against. */
384
+export function decodeProfileJson(raw: string): Result.Result<string | null, DecodeFailure> {
385
+ return Result.map(
386
+ decodeProfile(raw),
387
+ (profile) => trimmed(profile.emailAddress) ?? trimmed(profile.displayName),
388
+ );
389
+}
packages/source-control-azure-devops/src/server/driver.ts
+2
@@ -9,6 +9,7 @@ import { definition } from "../shared/definition.ts";
9
10
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
11
import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
12
+import * as AzureDevOpsIssueTracker from "./AzureDevOpsIssueTracker.ts";
13
import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";
14
import * as AzureDevOpsSourceControlProvider from "./AzureDevOpsSourceControlProvider.ts";
15
@@ -18,6 +19,7 @@ const makeInstance = Effect.all({
19
sourceControl: AzureDevOpsSourceControlProvider.make,
20
discovery: Effect.succeed(AzureDevOpsSourceControlProvider.discovery),
21
pullRequests: AzureDevOpsPullRequestProvider.make,
22
+ issues: AzureDevOpsIssueTracker.make,
23
});
24
25
export const driver = defineSourceControlDriver({
packages/source-control-azure-devops/src/shared/definition.test.ts
+10
@@ -252,3 +252,13 @@ describe("Azure DevOps repository selector", () => {
252
).toBe("checkout (eu)");
253
});
254
});
255
+
256
+describe("Azure DevOps issue scope", () => {
257
+ it("places work items in the project rather than the repository", () => {
258
+ const kind = SourceControlProviderKind.make("azure-devops");
259
+ expect(
260
+ definition.issueScope?.({ provider: kind, displayName: "acme/Web%20App/_git/web" }),
261
+ ).toBe("acme/Web App");
262
+ expect(definition.issueScope?.({ provider: kind, displayName: "web" })).toBeNull();
263
+ });
264
+});
packages/source-control-azure-devops/src/shared/definition.ts
+9
@@ -153,6 +153,15 @@ export const definition = defineSourceControl({
153
const name = identity.name || segments.at(-1);
154
return name ? decodeUrlPathSegment(name) : null;
155
},
156
+ // Work items belong to the project: `organization/project` out of the remote's
157
+ // `organization/project/_git/repository`.
158
+ issueScope: (identity) => {
159
+ const segments = (identity.displayName ?? "").split("/").filter((part) => part !== "");
160
+ const [organization, project] = segments.indexOf("_git") === 2 ? segments : [];
161
+ return organization && project
162
+ ? `${decodeUrlPathSegment(organization)}/${decodeUrlPathSegment(project)}`
163
+ : null;
164
+ },
165
repositoryKeyFromRemote,
166
canonicalRepositoryKey,
167
isChangeRequestInRepository: (identity, link) => {
packages/source-control-forgejo/src/server/ForgejoIssueTracker.test.ts
new
+221
@@ -0,0 +1,221 @@
1
+import { describe, expect, it } from "@effect/vitest";
2
+import * as Effect from "effect/Effect";
3
+import * as Layer from "effect/Layer";
4
+import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
5
+
6
+import * as ForgejoCli from "./ForgejoCli.ts";
7
+import * as ForgejoIssueTracker from "./ForgejoIssueTracker.ts";
8
+
9
+const encode = (value: unknown) => JSON.stringify(value);
10
+
11
+const ISSUE = {
12
+ number: 42,
13
+ title: "Composer loses focus",
14
+ body: "Typing drops focus.",
15
+ html_url: "https://forgejo.test:3000/acme/web/issues/42",
16
+ user: { login: "octocat", full_name: "Octo Cat", avatar_url: "" },
17
+ state: "open",
18
+ created_at: "2026-07-01T00:00:00+02:00",
19
+ updated_at: "2026-07-03T00:00:00Z",
20
+ closed_at: null,
21
+ assignees: [{ login: "theo" }],
22
+ labels: [{ id: 3, name: "bug", color: "d73a4a" }],
23
+ comments: 1,
24
+ is_locked: true,
25
+};
26
+
27
+/** Every endpoint the detail read touches, answered by path; stderr carries the `Link` header. */
28
+function answer(path: string): { readonly stdout: string; readonly stderr?: string } {
29
+ const [route] = path.split("?");
30
+ switch (route) {
31
+ case "user":
32
+ return { stdout: encode({ login: "julius" }) };
33
+ case "repos/acme/web":
34
+ return {
35
+ stdout: encode({ full_name: "acme/web", permissions: { push: false, admin: false } }),
36
+ };
37
+ case "repos/acme/web/issues/42":
38
+ return { stdout: encode(ISSUE) };
39
+ case "repos/acme/web/issues/42/timeline":
40
+ return {
41
+ stdout: encode([
42
+ {
43
+ id: 1,
44
+ type: "label",
45
+ body: "1",
46
+ user: { login: "theo" },
47
+ created_at: "2026-07-01T01:00:00Z",
48
+ label: { id: 3, name: "bug" },
49
+ },
50
+ {
51
+ id: 2,
52
+ type: "comment",
53
+ body: "Repro attached.",
54
+ user: { login: "julius" },
55
+ created_at: "2026-07-02T00:00:00Z",
56
+ },
57
+ {
58
+ id: 3,
59
+ type: "pull_ref",
60
+ user: { login: "theo" },
61
+ created_at: "2026-07-02T01:00:00Z",
62
+ ref_issue: {
63
+ number: 50,
64
+ html_url: "https://forgejo.test:3000/acme/web/pulls/50",
65
+ pull_request: { merged: false },
66
+ },
67
+ },
68
+ { id: 4, type: "milestone", user: { login: "theo" }, created_at: "2026-07-02T02:00:00Z" },
69
+ ]),
70
+ };
71
+ case "repos/acme/web/issues/42/reactions":
72
+ return { stdout: encode([{ content: "eyes", user: { login: "theo" } }]) };
73
+ case "repos/acme/web/issues/42/comments":
74
+ return {
75
+ stdout: encode([
76
+ {
77
+ id: 7,
78
+ body: "Repro attached.",
79
+ user: { login: "julius" },
80
+ created_at: "2026-07-02T00:00:00Z",
81
+ html_url: "https://forgejo.test:3000/acme/web/issues/42#issuecomment-7",
82
+ },
83
+ ]),
84
+ stderr:
85
+ 'HTTP/1.1 200\nlink: <https://forgejo.test:3000/api/v1/repos/acme/web/issues/42/comments?page=2>; rel="next"\n',
86
+ };
87
+ case "repos/acme/web/issues/comments/7/reactions":
88
+ return {
89
+ stdout: encode([
90
+ { content: "+1", user: { login: "julius" } },
91
+ { content: "+1", user: { login: "theo" } },
92
+ ]),
93
+ };
94
+ case "repos/acme/web/pulls/50":
95
+ return {
96
+ stdout: encode({
97
+ number: 50,
98
+ title: "fix(web): keep composer focus",
99
+ html_url: "https://forgejo.test:3000/acme/web/pulls/50",
100
+ state: "open",
101
+ merged: false,
102
+ draft: true,
103
+ }),
104
+ };
105
+ default:
106
+ throw new Error(`unexpected path ${path}`);
107
+ }
108
+}
109
+
110
+function tracker(
111
+ onApi: (input: ForgejoCli.ForgejoApiInput) => {
112
+ readonly stdout: string;
113
+ readonly stderr?: string;
114
+ },
115
+) {
116
+ return ForgejoIssueTracker.make.pipe(
117
+ Effect.provide(
118
+ Layer.mock(ForgejoCli.ForgejoCli)({
119
+ api: (input) => {
120
+ const { stdout, stderr } = onApi(input);
121
+ return Effect.succeed(
122
+ TestSourceControlHost.processOutput(stdout, { stderr: stderr ?? "" }),
123
+ );
124
+ },
125
+ }),
126
+ ),
127
+ );
128
+}
129
+
130
+describe("ForgejoIssueTracker", () => {
131
+ it.effect("joins the issue, timeline and conversation into the neutral issue shape", () =>
132
+ Effect.gen(function* () {
133
+ const hosts = new Set<string | undefined>();
134
+ const api = yield* tracker((input) => {
135
+ hosts.add(input.host);
136
+ return answer(input.path);
137
+ });
138
+ const issue = yield* api.getIssue({
139
+ cwd: "/w",
140
+ host: "forgejo.test:3000",
141
+ scope: "acme/web",
142
+ key: "42",
143
+ });
144
+ // The custom host and port reach the CLI, which resolves the login for them.
145
+ expect([...hosts]).toEqual(["forgejo.test:3000"]);
146
+ expect(issue).toMatchObject({
147
+ key: "42",
148
+ displayKey: "#42",
149
+ state: { category: "open", name: "open" },
150
+ author: { login: "octocat", name: "Octo Cat", avatarUrl: null },
151
+ createdAt: "2026-06-30T22:00:00.000Z",
152
+ labels: [{ name: "bug", color: "d73a4a" }],
153
+ viewer: "julius",
154
+ // No push and not the author: nothing but reading. Locked, so not even a comment.
155
+ viewerPermissions: {
156
+ setState: false,
157
+ comment: false,
158
+ edit: false,
159
+ labels: false,
160
+ assignees: false,
161
+ },
162
+ reactions: [{ content: "eyes", count: 1, actors: ["theo"], viewerHasReacted: false }],
163
+ commentsCursor: "2",
164
+ });
165
+ expect(issue.comments).toEqual([
166
+ {
167
+ id: "7",
168
+ author: { login: "julius", name: null, avatarUrl: null },
169
+ body: "Repro attached.",
170
+ createdAt: "2026-07-02T00:00:00.000Z",
171
+ url: "https://forgejo.test:3000/acme/web/issues/42#issuecomment-7",
172
+ reactions: [{ content: "thumbs-up", count: 2, actors: ["theo"], viewerHasReacted: true }],
173
+ },
174
+ ]);
175
+ // Comments and milestones on the timeline are not events in the shared vocabulary.
176
+ expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
177
+ ["labeled", "bug"],
178
+ ["referenced", "#50"],
179
+ ]);
180
+ expect(issue.linkedPullRequests).toEqual([
181
+ {
182
+ repository: "acme/web",
183
+ number: 50,
184
+ title: "fix(web): keep composer focus",
185
+ url: "https://forgejo.test:3000/acme/web/pulls/50",
186
+ state: "open",
187
+ isDraft: true,
188
+ closesIssue: false,
189
+ },
190
+ ]);
191
+ }),
192
+ );
193
+
194
+ it.effect("lists issues by page and leaves pull requests out of the rows", () =>
195
+ Effect.gen(function* () {
196
+ const paths: string[] = [];
197
+ const api = yield* tracker((input) => {
198
+ paths.push(input.path);
199
+ return {
200
+ stdout: encode([ISSUE, { ...ISSUE, number: 43, pull_request: { merged: false } }]),
201
+ };
202
+ });
203
+ const page = yield* api.listIssues({
204
+ cwd: "/w",
205
+ host: "forgejo.test:3000",
206
+ scope: "acme/web",
207
+ state: "open",
208
+ involvement: "authored",
209
+ viewer: "julius",
210
+ limit: 50,
211
+ cursor: "2",
212
+ });
213
+ expect(paths).toEqual([
214
+ "repos/acme/web/issues?type=issues&state=open&sort=recentupdate&created_by=julius&limit=50&page=2",
215
+ ]);
216
+ expect(page.items.map((item) => item.key)).toEqual(["42"]);
217
+ // No `Link` header at all means the server may still have more; a full page carries on.
218
+ expect(page.nextCursor).toBe("3");
219
+ }),
220
+ );
221
+});
packages/source-control-forgejo/src/server/ForgejoIssueTracker.ts
new
+581
@@ -0,0 +1,581 @@
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 every cursor here is the next page number.
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 IssueLinkedPullRequest,
13
+ type IssueViewerPermissions,
14
+} from "@t3tools/contracts";
15
+import { decodeJsonResult } from "@t3tools/shared/schemaJson";
16
+import {
17
+ IssueTrackerError,
18
+ type IssueTrackerApi,
19
+} from "@t3tools/source-control-core/server/IssueTracker";
20
+
21
+import * as ForgejoCli from "./ForgejoCli.ts";
22
+import {
23
+ ForgejoIssue,
24
+ ForgejoIssueConfig,
25
+ ForgejoIssueRepository,
26
+ ForgejoIssueTemplate,
27
+ ForgejoTimelineEntry,
28
+ forgejoIssue,
29
+ forgejoIssueComment,
30
+ forgejoIssueEvent,
31
+ forgejoIssueTemplate,
32
+} from "./forgejoIssueJson.ts";
33
+import {
34
+ FORGEJO_REACTIONS,
35
+ ForgejoComment,
36
+ ForgejoLabel,
37
+ ForgejoReaction,
38
+ ForgejoUser,
39
+ forgejoActor,
40
+ forgejoReactions,
41
+} from "./forgejoPullRequestJson.ts";
42
+
43
+const KIND = IssueTrackerKind.make("forgejo");
44
+
45
+const CAPABILITIES: IssueCapabilities = {
46
+ create: true,
47
+ edit: true,
48
+ comment: true,
49
+ labels: true,
50
+ assignees: true,
51
+ reactions: true,
52
+ templates: true,
53
+ linkedPullRequests: true,
54
+ events: true,
55
+ search: true,
56
+ states: [
57
+ { category: "open", name: "open" },
58
+ { category: "closed", name: "closed" },
59
+ ],
60
+ closeReasons: [],
61
+};
62
+
63
+/** Forgejo's own ceiling on a page, which a self-hosted server may lower. */
64
+const PAGE_SIZE = 50;
65
+/** Comment reactions are a request each, so only the first page's are read with the detail. */
66
+const COMMENT_REACTION_LIMIT = 50;
67
+
68
+const repoPath = (scope: string) => `repos/${scope.split("/").map(encodeURIComponent).join("/")}`;
69
+const issuePath = (scope: string, number: number) => `${repoPath(scope)}/issues/${number}`;
70
+
71
+function parseNumber(key: string): number | null {
72
+ return /^[1-9]\d*$/.test(key) ? Number(key) : null;
73
+}
74
+
75
+function parsePage(cursor: string | undefined): number | null {
76
+ if (cursor === undefined) return 1;
77
+ return /^[1-9]\d{0,6}$/.test(cursor) ? Number(cursor) : null;
78
+}
79
+
80
+function reasonFor(error: ForgejoCli.ForgejoCliError): IssueTrackerError["reason"] {
81
+ switch (error.reason) {
82
+ case "missing-cli":
83
+ return "missing-tool";
84
+ case "authentication":
85
+ return "unauthenticated";
86
+ case "rate-limit":
87
+ return "rate-limited";
88
+ case "not-found":
89
+ return "not-found";
90
+ default:
91
+ return "failed";
92
+ }
93
+}
94
+
95
+/**
96
+ * What the signed-in account may do. Forgejo reports push access on the repository, and an
97
+ * issue's author may edit and close their own; an archived repository takes everything away, and
98
+ * a locked issue takes commenting away from anyone without push.
99
+ */
100
+function permissions(
101
+ repository: typeof ForgejoIssueRepository.Type,
102
+ issue: typeof ForgejoIssue.Type,
103
+ viewer: string,
104
+): IssueViewerPermissions {
105
+ const active = !repository.archived;
106
+ const canWrite = repository.permissions?.push ?? false;
107
+ const canEdit = canWrite || issue.user?.login === viewer;
108
+ return {
109
+ setState: active && canEdit,
110
+ comment: active && (!issue.is_locked || canWrite),
111
+ edit: active && canEdit,
112
+ labels: active && canWrite,
113
+ assignees: active && canWrite,
114
+ };
115
+}
116
+
117
+export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli> = Effect.gen(
118
+ function* () {
119
+ const cli = yield* ForgejoCli.ForgejoCli;
120
+
121
+ const refused = (operation: string, detail: string, cause?: unknown) =>
122
+ new IssueTrackerError({
123
+ tracker: KIND,
124
+ operation,
125
+ reason: "failed",
126
+ detail,
127
+ ...(cause === undefined ? {} : { cause }),
128
+ });
129
+
130
+ const notFound = (operation: string) =>
131
+ new IssueTrackerError({
132
+ tracker: KIND,
133
+ operation,
134
+ reason: "not-found",
135
+ detail: "Forgejo could not find the requested issue.",
136
+ });
137
+
138
+ type Target = { readonly cwd: string; readonly host: string; readonly scope: string };
139
+
140
+ const request = (
141
+ target: Target,
142
+ operation: string,
143
+ input: Omit<ForgejoCli.ForgejoApiInput, "cwd" | "repository" | "host">,
144
+ ) =>
145
+ cli.api({ cwd: target.cwd, repository: target.scope, host: target.host, ...input }).pipe(
146
+ Effect.mapError(
147
+ (error) =>
148
+ new IssueTrackerError({
149
+ tracker: KIND,
150
+ operation,
151
+ reason: reasonFor(error),
152
+ detail: error.detail,
153
+ cause: error,
154
+ }),
155
+ ),
156
+ );
157
+
158
+ const read = <A>(
159
+ target: Target,
160
+ operation: string,
161
+ input: Omit<ForgejoCli.ForgejoApiInput, "cwd" | "repository" | "host">,
162
+ schema: Schema.Codec<A, unknown, never, never>,
163
+ ): Effect.Effect<A, IssueTrackerError> =>
164
+ request(target, operation, input).pipe(
165
+ Effect.flatMap((result) => {
166
+ if (result.stdoutTruncated) {
167
+ return Effect.fail(refused(operation, "Forgejo response exceeded the output limit."));
168
+ }
169
+ const decoded = decodeJsonResult(schema)(result.stdout);
170
+ return Result.isSuccess(decoded)
171
+ ? Effect.succeed(decoded.success)
172
+ : Effect.fail(
173
+ refused(operation, "Forgejo returned an invalid response.", decoded.failure),
174
+ );
175
+ }),
176
+ );
177
+
178
+ const readArray = <A>(
179
+ target: Target,
180
+ operation: string,
181
+ path: string,
182
+ schema: Schema.Codec<A, unknown, never, never>,
183
+ ) =>
184
+ read(target, operation, { path }, Schema.NullOr(Schema.Array(schema))).pipe(
185
+ Effect.map((rows) => rows ?? []),
186
+ );
187
+
188
+ /** One page of a listing, and whether Forgejo's `Link` header announced another. */
189
+ const readPage = <A>(
190
+ target: Target,
191
+ operation: string,
192
+ path: string,
193
+ page: number,
194
+ schema: Schema.Codec<A, unknown, never, never>,
195
+ ): Effect.Effect<
196
+ { readonly rows: ReadonlyArray<A>; readonly nextCursor: string | null },
197
+ IssueTrackerError
198
+ > =>
199
+ request(target, operation, {
200
+ path: `${path}${path.includes("?") ? "&" : "?"}limit=${PAGE_SIZE}&page=${page}`,
201
+ }).pipe(
202
+ Effect.flatMap((result) => {
203
+ const decoded = decodeJsonResult(Schema.NullOr(Schema.Array(schema)))(result.stdout);
204
+ if (Result.isFailure(decoded)) {
205
+ return Effect.fail(
206
+ refused(operation, "Forgejo returned an invalid response.", decoded.failure),
207
+ );
208
+ }
209
+ const rows = decoded.success ?? [];
210
+ const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1];
211
+ const more = rows.length > 0 && (links === undefined || /rel="?next"?/i.test(links));
212
+ return Effect.succeed({ rows, nextCursor: more ? String(page + 1) : null });
213
+ }),
214
+ );
215
+
216
+ const write = (
217
+ target: Target,
218
+ operation: string,
219
+ input: Omit<ForgejoCli.ForgejoApiInput, "cwd" | "repository" | "host">,
220
+ ) => request(target, operation, input).pipe(Effect.asVoid);
221
+
222
+ const getViewer = (target: Target, operation: string) =>
223
+ read(target, operation, { path: "user" }, ForgejoUser).pipe(Effect.map((user) => user.login));
224
+
225
+ const getRepository = (target: Target, operation: string) =>
226
+ read(target, operation, { path: repoPath(target.scope) }, ForgejoIssueRepository);
227
+
228
+ /** The issue as the API addresses it, or a not-found for a key that names no number. */
229
+ const issueTarget = (
230
+ operation: string,
231
+ input: Target & { readonly key: string },
232
+ ): Effect.Effect<{ readonly number: number; readonly path: string }, IssueTrackerError> => {
233
+ const number = parseNumber(input.key);
234
+ return number === null
235
+ ? Effect.fail(notFound(operation))
236
+ : Effect.succeed({ number, path: issuePath(input.scope, number) });
237
+ };
238
+
239
+ const getIssue = (target: Target, operation: string, path: string) =>
240
+ read(target, operation, { path }, ForgejoIssue).pipe(
241
+ // The issues API answers for a pull request's number too; that is not an issue here.
242
+ Effect.filterOrFail(
243
+ (issue) => !issue.pull_request,
244
+ () => notFound(operation),
245
+ ),
246
+ );
247
+
248
+ const commentsPage = (
249
+ target: Target,
250
+ operation: string,
251
+ path: string,
252
+ page: number,
253
+ viewer: string,
254
+ ) =>
255
+ readPage(target, operation, `${path}/comments`, page, ForgejoComment).pipe(
256
+ Effect.flatMap(({ rows, nextCursor }) =>
257
+ Effect.forEach(
258
+ rows.slice(0, COMMENT_REACTION_LIMIT),
259
+ (comment) =>
260
+ readArray(
261
+ target,
262
+ operation,
263
+ `${repoPath(target.scope)}/issues/comments/${comment.id}/reactions`,
264
+ ForgejoReaction,
265
+ ).pipe(
266
+ Effect.map((reactions) => ({
267
+ ...forgejoIssueComment(comment),
268
+ reactions: forgejoReactions(reactions, viewer),
269
+ })),
270
+ ),
271
+ { concurrency: 4 },
272
+ ).pipe(Effect.map((comments) => ({ comments, nextCursor }))),
273
+ ),
274
+ );
275
+
276
+ /** Pull requests the timeline shows citing this issue, each read once for its state. */
277
+ const linkedPullRequests = (
278
+ target: Target,
279
+ timeline: ReadonlyArray<typeof ForgejoTimelineEntry.Type>,
280
+ ): Effect.Effect<ReadonlyArray<IssueLinkedPullRequest>, IssueTrackerError> => {
281
+ const numbers = [
282
+ ...new Set(
283
+ timeline.flatMap((entry) =>
284
+ entry.type === "pull_ref" && entry.ref_issue?.pull_request
285
+ ? [entry.ref_issue.number]
286
+ : [],
287
+ ),
288
+ ),
289
+ ];
290
+ return Effect.forEach(
291
+ numbers,
292
+ (number) =>
293
+ read(
294
+ target,
295
+ "getIssue",
296
+ { path: `${repoPath(target.scope)}/pulls/${number}` },
297
+ Schema.Struct({
298
+ number: Schema.Int,
299
+ title: Schema.String,
300
+ html_url: Schema.String,
301
+ state: Schema.String,
302
+ merged: Schema.Boolean,
303
+ draft: Schema.optional(Schema.Boolean),
304
+ }),
305
+ ).pipe(
306
+ Effect.map((pull) => [
307
+ {
308
+ repository: target.scope,
309
+ number: pull.number,
310
+ title: pull.title,
311
+ url: pull.html_url,
312
+ state: pull.merged
313
+ ? ("merged" as const)
314
+ : pull.state === "closed"
315
+ ? ("closed" as const)
316
+ : ("open" as const),
317
+ isDraft: pull.draft ?? false,
318
+ // Forgejo's timeline cites the pull request without saying whether it closes the issue.
319
+ closesIssue: false,
320
+ },
321
+ ]),
322
+ Effect.catchIf(
323
+ (error) => error.reason === "not-found",
324
+ () => Effect.succeed([]),
325
+ ),
326
+ ),
327
+ { concurrency: 2 },
328
+ ).pipe(Effect.map((links) => links.flat()));
329
+ };
330
+
331
+ return {
332
+ kind: KIND,
333
+ capabilities: CAPABILITIES,
334
+
335
+ getViewer: (input) => getViewer({ ...input, scope: "" }, "getViewer"),
336
+
337
+ listIssues: Effect.fn("ForgejoIssueTracker.listIssues")(function* (input) {
338
+ const page = parsePage(input.cursor);
339
+ if (page === null) {
340
+ return yield* refused("listIssues", "The cursor was not one Forgejo handed out.");
341
+ }
342
+ const params = new URLSearchParams({
343
+ type: "issues",
344
+ state: input.state,
345
+ sort: "recentupdate",
346
+ });
347
+ const text = input.query?.trim() ?? "";
348
+ if (text.length > 0) params.set("q", text);
349
+ const involvement =
350
+ input.involvement === "assigned"
351
+ ? "assigned_by"
352
+ : input.involvement === "authored"
353
+ ? "created_by"
354
+ : input.involvement === "mentioned"
355
+ ? "mentioned_by"
356
+ : null;
357
+ if (involvement !== null) params.set(involvement, input.viewer);
358
+ const { rows, nextCursor } = yield* readPage(
359
+ input,
360
+ "listIssues",
361
+ `${repoPath(input.scope)}/issues?${params}`,
362
+ page,
363
+ ForgejoIssue,
364
+ );
365
+ return {
366
+ items: rows.flatMap((issue) => (issue.pull_request ? [] : [forgejoIssue(issue)])),
367
+ nextCursor,
368
+ };
369
+ }),
370
+
371
+ getIssue: (input) =>
372
+ issueTarget("getIssue", input).pipe(
373
+ Effect.flatMap(({ path }) =>
374
+ Effect.all(
375
+ [
376
+ getIssue(input, "getIssue", path),
377
+ getRepository(input, "getIssue"),
378
+ getViewer(input, "getIssue"),
379
+ readPage(input, "getIssue", `${path}/timeline`, 1, ForgejoTimelineEntry),
380
+ readArray(input, "getIssue", `${path}/reactions`, ForgejoReaction),
381
+ ],
382
+ { concurrency: 3 },
383
+ ),
384
+ ),
385
+ Effect.flatMap(([issue, repository, viewer, timeline, reactions]) =>
386
+ Effect.all([
387
+ commentsPage(input, "getIssue", issuePath(input.scope, issue.number), 1, viewer),
388
+ linkedPullRequests(input, timeline.rows),
389
+ ]).pipe(
390
+ Effect.map(([conversation, links]) => ({
391
+ ...forgejoIssue(issue),
392
+ body: issue.body ?? "",
393
+ viewer,
394
+ viewerPermissions: permissions(repository, issue, viewer),
395
+ reactions: forgejoReactions(reactions, viewer),
396
+ comments: conversation.comments,
397
+ commentsCursor: conversation.nextCursor,
398
+ events: timeline.rows.flatMap((entry) => forgejoIssueEvent(entry) ?? []),
399
+ linkedPullRequests: links,
400
+ })),
401
+ ),
402
+ ),
403
+ ),
404
+
405
+ getComments: (input) => {
406
+ const page = parsePage(input.cursor);
407
+ return page === null
408
+ ? Effect.fail(refused("getComments", "The cursor was not one Forgejo handed out."))
409
+ : Effect.all([issueTarget("getComments", input), getViewer(input, "getComments")]).pipe(
410
+ Effect.flatMap(([{ path }, viewer]) =>
411
+ commentsPage(input, "getComments", path, page, viewer),
412
+ ),
413
+ );
414
+ },
415
+
416
+ create: (input) =>
417
+ // Labels are written by id, so the names are resolved against the repository's own first.
418
+ readArray(
419
+ input,
420
+ "create",
421
+ `${repoPath(input.scope)}/labels?limit=${PAGE_SIZE}`,
422
+ ForgejoLabel,
423
+ ).pipe(
424
+ Effect.flatMap((labels) =>
425
+ read(
426
+ input,
427
+ "create",
428
+ {
429
+ path: `${repoPath(input.scope)}/issues`,
430
+ method: "POST",
431
+ body: {
432
+ title: input.title,
433
+ body: input.body,
434
+ labels: labels.flatMap((label) =>
435
+ input.labels.includes(label.name) ? [label.id] : [],
436
+ ),
437
+ assignees: input.assignees,
438
+ },
439
+ },
440
+ ForgejoIssue,
441
+ ),
442
+ ),
443
+ Effect.map((issue) => ({
444
+ key: String(issue.number),
445
+ displayKey: `#${issue.number}`,
446
+ url: issue.html_url,
447
+ })),
448
+ ),
449
+
450
+ comment: (input) =>
451
+ issueTarget("comment", input).pipe(
452
+ Effect.flatMap(({ path }) =>
453
+ write(input, "comment", {
454
+ path: `${path}/comments`,
455
+ method: "POST",
456
+ body: { body: input.body },
457
+ }),
458
+ ),
459
+ ),
460
+
461
+ update: (input) =>
462
+ issueTarget("update", input).pipe(
463
+ Effect.flatMap(({ path }) =>
464
+ Effect.all([
465
+ input.title === undefined && input.body === undefined && input.assignees === undefined
466
+ ? Effect.void
467
+ : write(input, "update", {
468
+ path,
469
+ method: "PATCH",
470
+ body: {
471
+ ...(input.title === undefined ? {} : { title: input.title }),
472
+ ...(input.body === undefined ? {} : { body: input.body }),
473
+ ...(input.assignees === undefined ? {} : { assignees: input.assignees }),
474
+ },
475
+ }),
476
+ input.labels === undefined
477
+ ? Effect.void
478
+ : readArray(
479
+ input,
480
+ "update",
481
+ `${repoPath(input.scope)}/labels?limit=${PAGE_SIZE}`,
482
+ ForgejoLabel,
483
+ ).pipe(
484
+ Effect.flatMap((labels) =>
485
+ write(input, "update", {
486
+ path: `${path}/labels`,
487
+ method: "PUT",
488
+ body: {
489
+ labels: labels.flatMap((label) =>
490
+ input.labels!.includes(label.name) ? [label.id] : [],
491
+ ),
492
+ },
493
+ }),
494
+ ),
495
+ ),
496
+ ]),
497
+ ),
498
+ Effect.asVoid,
499
+ ),
500
+
501
+ setState: (input) =>
502
+ issueTarget("setState", input).pipe(
503
+ Effect.flatMap(({ path }) =>
504
+ write(input, "setState", { path, method: "PATCH", body: { state: input.state } }),
505
+ ),
506
+ ),
507
+
508
+ setReaction: (input) =>
509
+ issueTarget("setReaction", input).pipe(
510
+ Effect.flatMap(({ path }) => {
511
+ if (input.subjectId !== undefined && !/^[1-9]\d*$/.test(input.subjectId)) {
512
+ return Effect.fail(
513
+ refused("setReaction", "The comment id names no Forgejo comment."),
514
+ );
515
+ }
516
+ return write(input, "setReaction", {
517
+ path:
518
+ input.subjectId === undefined
519
+ ? `${path}/reactions`
520
+ : `${repoPath(input.scope)}/issues/comments/${input.subjectId}/reactions`,
521
+ method: input.reacted ? "POST" : "DELETE",
522
+ body: { content: FORGEJO_REACTIONS[input.content] },
523
+ });
524
+ }),
525
+ ),
526
+
527
+ listTemplates: (input) =>
528
+ Effect.all(
529
+ [
530
+ readArray(
531
+ input,
532
+ "listTemplates",
533
+ `${repoPath(input.scope)}/issue_templates`,
534
+ ForgejoIssueTemplate,
535
+ ),
536
+ // A repository with no config leaves the blank issue where Forgejo puts it.
537
+ read(
538
+ input,
539
+ "listTemplates",
540
+ { path: `${repoPath(input.scope)}/issue_config` },
541
+ ForgejoIssueConfig,
542
+ ).pipe(
543
+ Effect.map((config) => config.blank_issues_enabled !== false),
544
+ Effect.catchIf(
545
+ (error) => error.reason === "not-found" || error.reason === "failed",
546
+ () => Effect.succeed(true),
547
+ ),
548
+ ),
549
+ ],
550
+ { concurrency: 2 },
551
+ ).pipe(
552
+ Effect.map(([templates, blankIssuesEnabled]) => ({
553
+ templates: templates.flatMap((template) => forgejoIssueTemplate(template) ?? []),
554
+ blankIssuesEnabled,
555
+ })),
556
+ ),
557
+
558
+ listCandidates: (input) =>
559
+ Effect.all(
560
+ [
561
+ readPage(input, "listCandidates", `${repoPath(input.scope)}/labels`, 1, ForgejoLabel),
562
+ readPage(input, "listCandidates", `${repoPath(input.scope)}/assignees`, 1, ForgejoUser),
563
+ ],
564
+ { concurrency: 2 },
565
+ ).pipe(
566
+ Effect.map(([labels, assignees]) => ({
567
+ labels: labels.rows.map((label) => ({
568
+ name: label.name,
569
+ color: label.color ?? null,
570
+ description: label.description ?? null,
571
+ })),
572
+ assignees: assignees.rows.flatMap((user) => {
573
+ const actor = forgejoActor(user);
574
+ return actor === null ? [] : [{ ...actor, id: actor.login }];
575
+ }),
576
+ truncated: labels.nextCursor !== null || assignees.nextCursor !== null,
577
+ })),
578
+ ),
579
+ };
580
+ },
581
+);
packages/source-control-forgejo/src/server/driver.ts
+2
@@ -7,6 +7,7 @@ import * as Effect from "effect/Effect";
7
import { definition } from "../shared/definition.ts";
8
9
import * as ForgejoCli from "./ForgejoCli.ts";
10
+import * as ForgejoIssueTracker from "./ForgejoIssueTracker.ts";
11
import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
12
import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts";
13
@@ -16,6 +17,7 @@ const makeInstance = Effect.all({
17
sourceControl: ForgejoSourceControlProvider.make,
18
discovery: ForgejoSourceControlProvider.makeDiscovery,
19
pullRequests: ForgejoPullRequestProvider.make,
20
+ issues: ForgejoIssueTracker.make,
21
});
22
23
export const driver = defineSourceControlDriver({
packages/source-control-forgejo/src/server/forgejoIssueJson.ts
new
+164
@@ -0,0 +1,164 @@
1
+/**
2
+ * Forgejo's issue shapes, beside the pull request ones they share users, labels and comments
3
+ * with. Gitea answers the same API, so a Gitea server reads through this too.
4
+ *
5
+ * @module source-control-forgejo/server/forgejoIssueJson
6
+ */
7
+import * as DateTime from "effect/DateTime";
8
+import * as Option from "effect/Option";
9
+import * as Schema from "effect/Schema";
10
+import type { IssueComment, IssueEvent, IssueTemplate } from "@t3tools/contracts";
11
+import type { TrackerIssueSummary } from "@t3tools/source-control-core/server/IssueTracker";
12
+
13
+import {
14
+ ForgejoComment,
15
+ ForgejoLabel,
16
+ ForgejoRepository,
17
+ ForgejoUser,
18
+ forgejoActor,
19
+} from "./forgejoPullRequestJson.ts";
20
+
21
+export const ForgejoIssue = Schema.Struct({
22
+ number: Schema.Int,
23
+ title: Schema.String,
24
+ body: Schema.optional(Schema.NullOr(Schema.String)),
25
+ html_url: Schema.String,
26
+ user: Schema.NullOr(ForgejoUser),
27
+ state: Schema.String,
28
+ created_at: Schema.String,
29
+ updated_at: Schema.String,
30
+ closed_at: Schema.optional(Schema.NullOr(Schema.String)),
31
+ assignees: Schema.optional(Schema.NullOr(Schema.Array(ForgejoUser))),
32
+ labels: Schema.optional(Schema.NullOr(Schema.Array(ForgejoLabel))),
33
+ comments: Schema.optional(Schema.Int),
34
+ is_locked: Schema.optional(Schema.Boolean),
35
+ /** Present on a row that is really a pull request, which the issue listing also returns. */
36
+ pull_request: Schema.optional(Schema.NullOr(Schema.Struct({ merged: Schema.Boolean }))),
37
+});
38
+
39
+export const ForgejoIssueRepository = Schema.Struct({
40
+ ...ForgejoRepository.fields,
41
+ has_issues: Schema.optional(Schema.Boolean),
42
+});
43
+
44
+/** One row of `/issues/{index}/timeline`, which is a comment with a type and a subject. */
45
+export const ForgejoTimelineEntry = Schema.Struct({
46
+ id: Schema.Int,
47
+ type: Schema.String,
48
+ body: Schema.optional(Schema.NullOr(Schema.String)),
49
+ user: Schema.optional(Schema.NullOr(ForgejoUser)),
50
+ created_at: Schema.String,
51
+ html_url: Schema.optional(Schema.NullOr(Schema.String)),
52
+ assignee: Schema.optional(Schema.NullOr(ForgejoUser)),
53
+ removed_assignee: Schema.optional(Schema.Boolean),
54
+ new_title: Schema.optional(Schema.NullOr(Schema.String)),
55
+ label: Schema.optional(Schema.NullOr(ForgejoLabel)),
56
+ ref_issue: Schema.optional(
57
+ Schema.NullOr(
58
+ Schema.Struct({
59
+ number: Schema.Int,
60
+ html_url: Schema.String,
61
+ pull_request: Schema.optional(Schema.NullOr(Schema.Struct({ merged: Schema.Boolean }))),
62
+ }),
63
+ ),
64
+ ),
65
+});
66
+
67
+export const ForgejoIssueTemplate = Schema.Struct({
68
+ file_name: Schema.String,
69
+ name: Schema.optional(Schema.NullOr(Schema.String)),
70
+ about: Schema.optional(Schema.NullOr(Schema.String)),
71
+ title: Schema.optional(Schema.NullOr(Schema.String)),
72
+ content: Schema.optional(Schema.NullOr(Schema.String)),
73
+ labels: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
74
+ assignees: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
75
+});
76
+
77
+export const ForgejoIssueConfig = Schema.Struct({
78
+ blank_issues_enabled: Schema.optional(Schema.Boolean),
79
+});
80
+
81
+function toIsoUtc(value: string): string {
82
+ return Option.match(DateTime.make(value), { onNone: () => value, onSome: DateTime.formatIso });
83
+}
84
+
85
+export function forgejoIssue(issue: typeof ForgejoIssue.Type): TrackerIssueSummary {
86
+ return {
87
+ key: String(issue.number),
88
+ displayKey: `#${issue.number}`,
89
+ title: issue.title,
90
+ url: issue.html_url,
91
+ author: forgejoActor(issue.user),
92
+ state:
93
+ issue.state === "closed"
94
+ ? { category: "closed", name: "closed" }
95
+ : { category: "open", name: "open" },
96
+ createdAt: toIsoUtc(issue.created_at),
97
+ updatedAt: toIsoUtc(issue.updated_at),
98
+ closedAt: issue.closed_at ? toIsoUtc(issue.closed_at) : null,
99
+ assignees: (issue.assignees ?? []).flatMap((user) => forgejoActor(user) ?? []),
100
+ labels: (issue.labels ?? []).map((label) => ({ name: label.name, color: label.color ?? null })),
101
+ commentCount: Math.max(0, issue.comments ?? 0),
102
+ };
103
+}
104
+
105
+export function forgejoIssueComment(comment: typeof ForgejoComment.Type): IssueComment {
106
+ return {
107
+ id: String(comment.id),
108
+ author: forgejoActor(comment.user),
109
+ body: comment.body,
110
+ createdAt: toIsoUtc(comment.created_at),
111
+ url: comment.html_url || null,
112
+ };
113
+}
114
+
115
+/** Null for a timeline entry with no kind in the shared vocabulary, which is dropped. */
116
+export function forgejoIssueEvent(entry: typeof ForgejoTimelineEntry.Type): IssueEvent | null {
117
+ const event = (kind: IssueEvent["kind"], detail: string | null = null): IssueEvent => ({
118
+ id: String(entry.id),
119
+ kind,
120
+ actor: forgejoActor(entry.user),
121
+ createdAt: toIsoUtc(entry.created_at),
122
+ detail,
123
+ });
124
+ switch (entry.type) {
125
+ case "close":
126
+ return event("closed");
127
+ case "reopen":
128
+ return event("reopened");
129
+ case "assignees":
130
+ return event(
131
+ entry.removed_assignee ? "unassigned" : "assigned",
132
+ entry.assignee?.login || null,
133
+ );
134
+ case "change_title":
135
+ return event("renamed", entry.new_title || null);
136
+ case "label":
137
+ // Forgejo writes `1` into the body of a labelling and nothing into a removal.
138
+ return event(entry.body === "1" ? "labeled" : "unlabeled", entry.label?.name || null);
139
+ case "issue_ref":
140
+ case "commit_ref":
141
+ case "comment_ref":
142
+ case "pull_ref":
143
+ return event("referenced", entry.ref_issue ? `#${entry.ref_issue.number}` : null);
144
+ default:
145
+ return null;
146
+ }
147
+}
148
+
149
+/** Only markdown templates carry a body; a YAML form is a questionnaire this cannot flatten. */
150
+export function forgejoIssueTemplate(
151
+ template: typeof ForgejoIssueTemplate.Type,
152
+): IssueTemplate | null {
153
+ const key = template.file_name.trim();
154
+ if (key.length === 0 || !/\.md$/i.test(key)) return null;
155
+ return {
156
+ key,
157
+ name: template.name?.trim() || key,
158
+ about: template.about ?? "",
159
+ title: template.title ?? "",
160
+ body: template.content ?? "",
161
+ labels: template.labels ?? [],
162
+ assignees: template.assignees ?? [],
163
+ };
164
+}
packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts
new
+221
@@ -0,0 +1,221 @@
1
+import { describe, expect, it } from "@effect/vitest";
2
+import * as Effect from "effect/Effect";
3
+import * as Layer from "effect/Layer";
4
+import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
5
+
6
+import * as GitLabCli from "./GitLabCli.ts";
7
+import * as GitLabIssueTracker from "./GitLabIssueTracker.ts";
8
+
9
+const encode = (value: unknown) => JSON.stringify(value);
10
+
11
+const ISSUE = {
12
+ iid: 42,
13
+ title: "Composer loses focus",
14
+ web_url: "https://gitlab.com/acme/web/-/issues/42",
15
+ description: "Typing in the composer drops focus after a paste.",
16
+ author: { id: 1, username: "octocat", name: "Octo Cat", avatar_url: "https://avatars/octocat" },
17
+ state: "closed",
18
+ created_at: "2026-07-01T00:00:00Z",
19
+ updated_at: "2026-07-03T00:00:00Z",
20
+ closed_at: "2026-07-03T00:00:00Z",
21
+ assignees: [{ id: 2, username: "theo", name: null }],
22
+ labels: ["bug", " "],
23
+ user_notes_count: 3,
24
+};
25
+
26
+/** Every endpoint the detail read touches, answered by the path `glab api` is given. */
27
+function answer(path: string): string {
28
+ if (path === "user") return encode({ username: "julius" });
29
+ if (path === "projects/acme%2Fweb/issues/42") return encode(ISSUE);
30
+ if (path.startsWith("projects/acme%2Fweb/issues/42/notes")) {
31
+ return encode([
32
+ {
33
+ id: 7,
34
+ body: "Repro attached.",
35
+ author: { username: "julius" },
36
+ created_at: "2026-07-02T00:00:00Z",
37
+ },
38
+ {
39
+ id: 8,
40
+ body: "closed",
41
+ author: { username: "theo" },
42
+ created_at: "2026-07-03T00:00:00Z",
43
+ system: true,
44
+ },
45
+ {
46
+ id: 9,
47
+ body: "added ~7 label",
48
+ author: { username: "theo" },
49
+ created_at: "2026-07-03T00:00:00Z",
50
+ system: true,
51
+ },
52
+ ]);
53
+ }
54
+ if (path.startsWith("projects/acme%2Fweb/issues/42/resource_label_events")) {
55
+ return encode([
56
+ {
57
+ id: 3,
58
+ action: "add",
59
+ created_at: "2026-07-01T01:00:00Z",
60
+ user: { username: "theo" },
61
+ label: { name: "bug" },
62
+ },
63
+ ]);
64
+ }
65
+ if (path.startsWith("projects/acme%2Fweb/issues/42/closed_by")) {
66
+ return encode([
67
+ {
68
+ iid: 50,
69
+ title: "fix(web): keep composer focus",
70
+ web_url: "https://gitlab.com/acme/web/-/merge_requests/50",
71
+ state: "merged",
72
+ references: { full: "acme/web!50" },
73
+ },
74
+ ]);
75
+ }
76
+ if (path.startsWith("projects/acme%2Fweb/issues/42/related_merge_requests")) {
77
+ return encode([
78
+ {
79
+ iid: 50,
80
+ title: "fix(web): keep composer focus",
81
+ web_url: "https://gitlab.com/acme/web/-/merge_requests/50",
82
+ state: "merged",
83
+ references: { full: "acme/web!50" },
84
+ },
85
+ {
86
+ iid: 51,
87
+ title: "chore: mention",
88
+ web_url: "https://gitlab.com/acme/web/-/merge_requests/51",
89
+ state: "opened",
90
+ draft: true,
91
+ references: { full: "acme/web!51" },
92
+ },
93
+ ]);
94
+ }
95
+ if (path === "graphql") {
96
+ return encode({
97
+ data: {
98
+ currentUser: { username: "julius" },
99
+ project: {
100
+ mergeRequest: {
101
+ awardEmoji: { nodes: [{ name: "eyes", user: { username: "theo" } }] },
102
+ notes: {
103
+ pageInfo: { hasNextPage: false },
104
+ nodes: [
105
+ {
106
+ id: "gid://gitlab/Note/7",
107
+ awardEmoji: {
108
+ nodes: [
109
+ { name: "thumbsup", user: { username: "julius" } },
110
+ { name: "thumbsup", user: { username: "theo" } },
111
+ ],
112
+ },
113
+ },
114
+ ],
115
+ },
116
+ },
117
+ },
118
+ },
119
+ });
120
+ }
121
+ throw new Error(`unexpected path ${path}`);
122
+}
123
+
124
+function tracker(onExecute: (args: ReadonlyArray<string>) => string) {
125
+ return GitLabIssueTracker.make.pipe(
126
+ Effect.provide(
127
+ Layer.mock(GitLabCli.GitLabCli)({
128
+ execute: ({ args }) => Effect.succeed(TestSourceControlHost.processOutput(onExecute(args))),
129
+ }),
130
+ ),
131
+ );
132
+}
133
+
134
+describe("GitLabIssueTracker", () => {
135
+ it.effect("joins the detail's endpoints into the neutral issue shape", () =>
136
+ Effect.gen(function* () {
137
+ const api = yield* tracker((args) => answer(args[1]!));
138
+ const issue = yield* api.getIssue({
139
+ cwd: "/w",
140
+ host: "gitlab.com",
141
+ scope: "acme/web",
142
+ key: "42",
143
+ });
144
+ expect(issue).toMatchObject({
145
+ key: "42",
146
+ displayKey: "#42",
147
+ state: { category: "closed", name: "closed" },
148
+ author: { login: "octocat", name: "Octo Cat" },
149
+ assignees: [{ login: "theo" }],
150
+ labels: [{ name: "bug", color: null }],
151
+ commentCount: 3,
152
+ viewer: "julius",
153
+ viewerPermissions: { setState: true, edit: true, labels: true, assignees: true },
154
+ commentsCursor: null,
155
+ reactions: [{ content: "eyes", count: 1, actors: ["theo"], viewerHasReacted: false }],
156
+ });
157
+ expect(issue.comments).toEqual([
158
+ {
159
+ id: "7",
160
+ author: { login: "julius", name: null, avatarUrl: null },
161
+ body: "Repro attached.",
162
+ createdAt: "2026-07-02T00:00:00Z",
163
+ url: null,
164
+ reactions: [{ content: "thumbs-up", count: 2, actors: ["theo"], viewerHasReacted: true }],
165
+ },
166
+ ]);
167
+ // System notes become events; label notes are dropped in favour of the label events.
168
+ expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([
169
+ ["labeled", "bug"],
170
+ ["closed", null],
171
+ ]);
172
+ // A closing merge request is not repeated as a related one.
173
+ expect(
174
+ issue.linkedPullRequests.map((link) => [link.number, link.closesIssue, link.isDraft]),
175
+ ).toEqual([
176
+ [50, true, false],
177
+ [51, false, true],
178
+ ]);
179
+ }),
180
+ );
181
+
182
+ it.effect("pages a listing by GitLab's page number and stops on a short page", () =>
183
+ Effect.gen(function* () {
184
+ const paths: string[] = [];
185
+ const api = yield* tracker((args) => {
186
+ paths.push(args[1]!);
187
+ return encode([ISSUE]);
188
+ });
189
+ const page = yield* api.listIssues({
190
+ cwd: "/w",
191
+ host: "gitlab.com",
192
+ scope: "acme/web",
193
+ state: "open",
194
+ involvement: "assigned",
195
+ viewer: "julius",
196
+ limit: 1,
197
+ cursor: "3",
198
+ });
199
+ expect(paths[0]).toBe(
200
+ "projects/acme%2Fweb/issues?state=opened&assignee_username=julius&order_by=updated_at&sort=desc&per_page=1&page=3",
201
+ );
202
+ expect(page.items[0]?.key).toBe("42");
203
+ expect(page.nextCursor).toBe("4");
204
+ }),
205
+ );
206
+
207
+ it.effect("refuses a key that names no GitLab issue without a request", () =>
208
+ Effect.gen(function* () {
209
+ let requests = 0;
210
+ const api = yield* tracker(() => {
211
+ requests += 1;
212
+ return "{}";
213
+ });
214
+ const error = yield* Effect.flip(
215
+ api.getIssue({ cwd: "/w", host: "gitlab.com", scope: "acme/web", key: "ENG-42" }),
216
+ );
217
+ expect(error.reason).toBe("not-found");
218
+ expect(requests).toBe(0);
219
+ }),
220
+ );
221
+});
packages/source-control-gitlab/src/server/GitLabIssueTracker.ts
new
+578
@@ -0,0 +1,578 @@
1
+/**
2
+ * GitLab's issue tracker over `glab api`. GitLab pages by offset and reports no total, so every
3
+ * cursor is a page number and a full page is the only sign that more exists. Notes, label
4
+ * events, linked merge requests and awards are separate endpoints, joined 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 IssueInvolvement,
13
+ type IssueViewerPermissions,
14
+} from "@t3tools/contracts";
15
+import {
16
+ IssueTrackerError,
17
+ type IssueTrackerApi,
18
+} from "@t3tools/source-control-core/server/IssueTracker";
19
+
20
+import * as GitLabCli from "./GitLabCli.ts";
21
+import {
22
+ decodeCreatedIssueJson,
23
+ decodeIssueDetailJson,
24
+ decodeIssueListJson,
25
+ decodeIssueNotesJson,
26
+ decodeLabelEventsJson,
27
+ decodeLinkedMergeRequestsJson,
28
+ decodeProjectLabelsJson,
29
+ decodeProjectMembersJson,
30
+ decodeTemplateEntriesJson,
31
+ decodeTemplateJson,
32
+ ISSUE_AWARD_EMOJI_GRAPHQL_QUERY,
33
+ PAGE_SIZE,
34
+ type GitLabTemplateEntry,
35
+} from "./gitLabIssueJson.ts";
36
+import {
37
+ decodeAwardEmojiJson,
38
+ decodeOwnAwardIdJson,
39
+ decodeViewerJson,
40
+ gitLabAwardName,
41
+} from "./gitLabMergeRequestJson.ts";
42
+
43
+const KIND = IssueTrackerKind.make("gitlab");
44
+
45
+const CAPABILITIES: IssueCapabilities = {
46
+ create: true,
47
+ edit: true,
48
+ comment: true,
49
+ labels: true,
50
+ assignees: true,
51
+ reactions: true,
52
+ templates: true,
53
+ linkedPullRequests: true,
54
+ events: true,
55
+ search: true,
56
+ states: [
57
+ { category: "open", name: "open" },
58
+ { category: "closed", name: "closed" },
59
+ ],
60
+ // GitLab records nothing about why an issue was closed.
61
+ closeReasons: [],
62
+};
63
+
64
+/**
65
+ * Everything granted. GitLab's REST API reports the viewer's role on the project but never whether
66
+ * they opened this issue, and an issue's author may close, reopen and edit it whatever their role.
67
+ * Withholding those controls from the one person entitled to them is the worse mistake, so they
68
+ * are offered and GitLab explains any refusal itself.
69
+ */
70
+const VIEWER_PERMISSIONS: IssueViewerPermissions = {
71
+ setState: true,
72
+ comment: true,
73
+ edit: true,
74
+ labels: true,
75
+ assignees: true,
76
+};
77
+
78
+/** How many of a scope's templates are read in full; each one is a request of its own. */
79
+const TEMPLATE_LIMIT = 20;
80
+
81
+const encodeBody = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
82
+
83
+/** The REST API addresses a project by its URL-encoded full path. */
84
+function projectPath(scope: string): string {
85
+ return encodeURIComponent(scope.trim());
86
+}
87
+
88
+/** An issue key is its iid; anything else names no GitLab issue. */
89
+function parseNumber(key: string): number | null {
90
+ return /^[1-9]\d*$/.test(key) ? Number(key) : null;
91
+}
92
+
93
+/** A page cursor this tracker handed out, or null for anything it could not have issued. */
94
+function parsePage(cursor: string | undefined): number | null {
95
+ if (cursor === undefined) return 1;
96
+ return /^[1-9]\d{0,6}$/.test(cursor) ? Number(cursor) : null;
97
+}
98
+
99
+function query(params: ReadonlyArray<readonly [string, string]>): string {
100
+ return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
101
+}
102
+
103
+function involvementParams(input: {
104
+ readonly involvement: IssueInvolvement;
105
+ readonly viewer: string;
106
+}): ReadonlyArray<readonly [string, string]> {
107
+ switch (input.involvement) {
108
+ case "authored":
109
+ return [["author_username", input.viewer]];
110
+ case "assigned":
111
+ return [["assignee_username", input.viewer]];
112
+ // GitLab's `my_reaction_emoji` and `iteration` filters aside, nothing narrows to mentions, so
113
+ // the listing stays as wide as `all` rather than guessing.
114
+ case "mentioned":
115
+ case "all":
116
+ return [];
117
+ }
118
+}
119
+
120
+function reasonFor(error: GitLabCli.GitLabCliError): IssueTrackerError["reason"] {
121
+ switch (error._tag) {
122
+ case "GitLabCliUnavailableError":
123
+ return "missing-tool";
124
+ case "GitLabCliAuthenticationError":
125
+ return "unauthenticated";
126
+ case "GitLabCliRateLimitError":
127
+ return "rate-limited";
128
+ default:
129
+ return "failed";
130
+ }
131
+}
132
+
133
+export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> = Effect.gen(
134
+ function* () {
135
+ const gitlab = yield* GitLabCli.GitLabCli;
136
+
137
+ const fail = (operation: string) => (error: GitLabCli.GitLabCliError) =>
138
+ new IssueTrackerError({
139
+ tracker: KIND,
140
+ operation,
141
+ reason: reasonFor(error),
142
+ detail: error.detail,
143
+ cause: error,
144
+ });
145
+
146
+ const unreadable = (operation: string, cause: unknown) =>
147
+ new IssueTrackerError({
148
+ tracker: KIND,
149
+ operation,
150
+ reason: "failed",
151
+ detail: `GitLab returned an unreadable ${operation} response.`,
152
+ cause,
153
+ });
154
+
155
+ const notFound = (operation: string) =>
156
+ new IssueTrackerError({
157
+ tracker: KIND,
158
+ operation,
159
+ reason: "not-found",
160
+ detail: "GitLab could not find the requested issue.",
161
+ });
162
+
163
+ const refused = (operation: string, detail: string) =>
164
+ new IssueTrackerError({ tracker: KIND, operation, reason: "failed", detail });
165
+
166
+ const api = (input: {
167
+ readonly cwd: string;
168
+ readonly operation: string;
169
+ readonly path: string;
170
+ readonly method?: string;
171
+ readonly body?: unknown;
172
+ }) =>
173
+ gitlab
174
+ .execute({
175
+ cwd: input.cwd,
176
+ args: [
177
+ "api",
178
+ input.path,
179
+ ...(input.method === undefined ? [] : ["--method", input.method]),
180
+ // A JSON body from stdin: argv is visible in process listings, and `glab api --input`
181
+ // sends no Content-Type of its own, which GitLab answers with HTTP 415.
182
+ ...(input.body === undefined
183
+ ? []
184
+ : ["--input", "-", "--header", "Content-Type: application/json"]),
185
+ ],
186
+ ...(input.body === undefined ? {} : { stdin: encodeBody(input.body) }),
187
+ })
188
+ .pipe(
189
+ Effect.map((result) => result.stdout.trim()),
190
+ Effect.mapError(fail(input.operation)),
191
+ );
192
+
193
+ const read = <A>(input: {
194
+ readonly cwd: string;
195
+ readonly operation: string;
196
+ readonly path: string;
197
+ readonly method?: string;
198
+ readonly body?: unknown;
199
+ readonly decode: (raw: string) => Result.Result<A, unknown>;
200
+ }): Effect.Effect<A, IssueTrackerError> =>
201
+ api(input).pipe(
202
+ Effect.flatMap((raw) => {
203
+ const decoded = input.decode(raw);
204
+ return Result.isSuccess(decoded)
205
+ ? Effect.succeed(decoded.success)
206
+ : Effect.fail(unreadable(input.operation, decoded.failure));
207
+ }),
208
+ );
209
+
210
+ const write = (input: {
211
+ readonly cwd: string;
212
+ readonly operation: string;
213
+ readonly path: string;
214
+ readonly method: string;
215
+ readonly body?: unknown;
216
+ }) => api(input).pipe(Effect.asVoid);
217
+
218
+ /** The signed-in account; an answer naming nobody is a failure, since every comparison needs a login. */
219
+ const viewer = (input: {
220
+ readonly cwd: string;
221
+ readonly operation: string;
222
+ }): Effect.Effect<string, IssueTrackerError> =>
223
+ read({
224
+ cwd: input.cwd,
225
+ operation: input.operation,
226
+ path: "user",
227
+ decode: decodeViewerJson,
228
+ }).pipe(
229
+ Effect.filterOrFail(
230
+ (login) => login !== null,
231
+ () => refused(input.operation, "GitLab returned no username for the signed-in account."),
232
+ ),
233
+ );
234
+
235
+ /** The issue as REST addresses it, or a not-found for a key that names no iid. */
236
+ const issuePath = (
237
+ input: { readonly scope: string; readonly key: string },
238
+ operation: string,
239
+ ): Effect.Effect<{ readonly number: number; readonly path: string }, IssueTrackerError> => {
240
+ const number = parseNumber(input.key);
241
+ return number === null
242
+ ? Effect.fail(notFound(operation))
243
+ : Effect.succeed({ number, path: `projects/${projectPath(input.scope)}/issues/${number}` });
244
+ };
245
+
246
+ /** GitLab names assignees by numeric id, which is what the candidates carry as `id`. */
247
+ const assigneeIds = (
248
+ operation: string,
249
+ assignees: ReadonlyArray<string>,
250
+ ): Effect.Effect<ReadonlyArray<number>, IssueTrackerError> => {
251
+ const ids = assignees.map((id) => (/^[1-9]\d*$/.test(id) ? Number(id) : null));
252
+ return ids.every((id) => id !== null)
253
+ ? Effect.succeed(ids)
254
+ : Effect.fail(refused(operation, "GitLab assignees are named by their user id."));
255
+ };
256
+
257
+ const paged = (path: string, page: number) =>
258
+ `${path}?${query([
259
+ ["per_page", String(PAGE_SIZE)],
260
+ ["page", String(page)],
261
+ ])}`;
262
+
263
+ const notesPage = (input: {
264
+ readonly cwd: string;
265
+ readonly path: string;
266
+ readonly page: number;
267
+ readonly operation: string;
268
+ }) =>
269
+ read({
270
+ cwd: input.cwd,
271
+ operation: input.operation,
272
+ path: `${input.path}/notes?${query([
273
+ ["per_page", String(PAGE_SIZE)],
274
+ ["page", String(input.page)],
275
+ ["order_by", "created_at"],
276
+ ["sort", "asc"],
277
+ ])}`,
278
+ decode: decodeIssueNotesJson,
279
+ }).pipe(
280
+ Effect.map((notes) => ({
281
+ ...notes,
282
+ nextCursor: notes.rawCount < PAGE_SIZE ? null : String(input.page + 1),
283
+ })),
284
+ );
285
+
286
+ const awards = (input: {
287
+ readonly cwd: string;
288
+ readonly scope: string;
289
+ readonly number: number;
290
+ readonly operation: string;
291
+ }) =>
292
+ read({
293
+ cwd: input.cwd,
294
+ operation: input.operation,
295
+ path: "graphql",
296
+ method: "POST",
297
+ body: {
298
+ query: ISSUE_AWARD_EMOJI_GRAPHQL_QUERY,
299
+ variables: { fullPath: input.scope.trim(), iid: String(input.number) },
300
+ },
301
+ decode: decodeAwardEmojiJson,
302
+ });
303
+
304
+ const linked = (input: {
305
+ readonly cwd: string;
306
+ readonly path: string;
307
+ readonly endpoint: "closed_by" | "related_merge_requests";
308
+ }) =>
309
+ read({
310
+ cwd: input.cwd,
311
+ operation: "getIssue",
312
+ path: paged(`${input.path}/${input.endpoint}`, 1),
313
+ decode: (raw) => decodeLinkedMergeRequestsJson(raw, input.endpoint === "closed_by"),
314
+ });
315
+
316
+ const template =
317
+ (input: { readonly cwd: string; readonly scope: string }) => (entry: GitLabTemplateEntry) =>
318
+ read({
319
+ cwd: input.cwd,
320
+ operation: "listTemplates",
321
+ path: `projects/${projectPath(input.scope)}/templates/issues/${encodeURIComponent(entry.key)}`,
322
+ decode: (raw) => decodeTemplateJson(entry, raw),
323
+ });
324
+
325
+ return {
326
+ kind: KIND,
327
+ capabilities: CAPABILITIES,
328
+
329
+ getViewer: (input) => viewer({ cwd: input.cwd, operation: "getViewer" }),
330
+
331
+ listIssues: (input) => {
332
+ const page = parsePage(input.cursor);
333
+ if (page === null) {
334
+ return Effect.fail(refused("listIssues", "The cursor was not one GitLab handed out."));
335
+ }
336
+ const perPage = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
337
+ const text = input.query?.trim() ?? "";
338
+ return read({
339
+ cwd: input.cwd,
340
+ operation: "listIssues",
341
+ path: `projects/${projectPath(input.scope)}/issues?${query([
342
+ ["state", input.state === "open" ? "opened" : input.state],
343
+ ...involvementParams(input),
344
+ // GitLab's own `search` matches title and description, URL-encoded like every other
345
+ // value here, so no text in it can become a parameter of its own.
346
+ ...(text.length === 0 ? [] : [["search", text] as const]),
347
+ ["order_by", "updated_at"],
348
+ ["sort", "desc"],
349
+ ["per_page", String(perPage)],
350
+ ["page", String(page)],
351
+ ])}`,
352
+ decode: decodeIssueListJson,
353
+ }).pipe(
354
+ Effect.map((list) => ({
355
+ items: list.items,
356
+ nextCursor: list.rawCount < perPage ? null : String(page + 1),
357
+ })),
358
+ );
359
+ },
360
+
361
+ getIssue: (input) =>
362
+ issuePath(input, "getIssue").pipe(
363
+ Effect.flatMap(({ number, path }) =>
364
+ Effect.all(
365
+ [
366
+ read({
367
+ cwd: input.cwd,
368
+ operation: "getIssue",
369
+ path,
370
+ decode: decodeIssueDetailJson,
371
+ }),
372
+ viewer({ cwd: input.cwd, operation: "getIssue" }),
373
+ notesPage({ cwd: input.cwd, path, page: 1, operation: "getIssue" }),
374
+ read({
375
+ cwd: input.cwd,
376
+ operation: "getIssue",
377
+ path: paged(`${path}/resource_label_events`, 1),
378
+ decode: decodeLabelEventsJson,
379
+ }),
380
+ linked({ cwd: input.cwd, path, endpoint: "closed_by" }),
381
+ linked({ cwd: input.cwd, path, endpoint: "related_merge_requests" }),
382
+ awards({ cwd: input.cwd, scope: input.scope, number, operation: "getIssue" }),
383
+ ],
384
+ { concurrency: 4 },
385
+ ),
386
+ ),
387
+ Effect.map(([issue, viewerLogin, notes, labelEvents, closing, related, awardPage]) => {
388
+ const closingKeys = new Set(closing.map((link) => `${link.repository}!${link.number}`));
389
+ return {
390
+ ...issue,
391
+ viewer: viewerLogin,
392
+ viewerPermissions: VIEWER_PERMISSIONS,
393
+ reactions: awardPage.reactions,
394
+ comments: notes.comments.map((comment) => ({
395
+ ...comment,
396
+ reactions: awardPage.reactionsByNoteId.get(comment.id) ?? [],
397
+ })),
398
+ commentsCursor: notes.nextCursor,
399
+ events: [...notes.events, ...labelEvents].sort((left, right) =>
400
+ left.createdAt.localeCompare(right.createdAt),
401
+ ),
402
+ // A merge request that closes the issue outranks its sighting as a mere mention.
403
+ linkedPullRequests: [
404
+ ...closing,
405
+ ...related.filter((link) => !closingKeys.has(`${link.repository}!${link.number}`)),
406
+ ],
407
+ };
408
+ }),
409
+ ),
410
+
411
+ getComments: (input) => {
412
+ const page = parsePage(input.cursor);
413
+ return page === null
414
+ ? Effect.fail(refused("getComments", "The cursor was not one GitLab handed out."))
415
+ : issuePath(input, "getComments").pipe(
416
+ Effect.flatMap(({ path }) =>
417
+ notesPage({ cwd: input.cwd, path, page, operation: "getComments" }),
418
+ ),
419
+ Effect.map((notes) => ({ comments: notes.comments, nextCursor: notes.nextCursor })),
420
+ );
421
+ },
422
+
423
+ create: (input) =>
424
+ assigneeIds("create", input.assignees).pipe(
425
+ Effect.flatMap((assignee_ids) =>
426
+ read({
427
+ cwd: input.cwd,
428
+ operation: "create",
429
+ path: `projects/${projectPath(input.scope)}/issues`,
430
+ method: "POST",
431
+ body: {
432
+ title: input.title,
433
+ description: input.body,
434
+ labels: input.labels.join(","),
435
+ assignee_ids,
436
+ },
437
+ decode: decodeCreatedIssueJson,
438
+ }),
439
+ ),
440
+ Effect.map((issue) => ({
441
+ key: String(issue.number),
442
+ displayKey: `#${issue.number}`,
443
+ url: issue.url,
444
+ })),
445
+ ),
446
+
447
+ comment: (input) =>
448
+ issuePath(input, "comment").pipe(
449
+ Effect.flatMap(({ path }) =>
450
+ write({
451
+ cwd: input.cwd,
452
+ operation: "comment",
453
+ path: `${path}/notes`,
454
+ method: "POST",
455
+ body: { body: input.body },
456
+ }),
457
+ ),
458
+ ),
459
+
460
+ update: (input) =>
461
+ Effect.all([
462
+ issuePath(input, "update"),
463
+ input.assignees === undefined ? Effect.void : assigneeIds("update", input.assignees),
464
+ ]).pipe(
465
+ Effect.flatMap(([{ path }, assignee_ids]) =>
466
+ write({
467
+ cwd: input.cwd,
468
+ operation: "update",
469
+ path,
470
+ method: "PUT",
471
+ body: {
472
+ ...(input.title === undefined ? {} : { title: input.title }),
473
+ ...(input.body === undefined ? {} : { description: input.body }),
474
+ ...(input.labels === undefined ? {} : { labels: input.labels.join(",") }),
475
+ ...(assignee_ids === undefined ? {} : { assignee_ids }),
476
+ },
477
+ }),
478
+ ),
479
+ ),
480
+
481
+ setState: (input) =>
482
+ issuePath(input, "setState").pipe(
483
+ Effect.flatMap(({ path }) =>
484
+ write({
485
+ cwd: input.cwd,
486
+ operation: "setState",
487
+ path,
488
+ method: "PUT",
489
+ body: { state_event: input.state === "closed" ? "close" : "reopen" },
490
+ }),
491
+ ),
492
+ ),
493
+
494
+ setReaction: (input) =>
495
+ issuePath(input, "setReaction").pipe(
496
+ Effect.flatMap(({ path }) => {
497
+ if (input.subjectId !== undefined && !/^[1-9]\d*$/.test(input.subjectId)) {
498
+ return Effect.fail(refused("setReaction", "The comment id names no GitLab note."));
499
+ }
500
+ const subject =
501
+ input.subjectId === undefined
502
+ ? `${path}/award_emoji`
503
+ : `${path}/notes/${input.subjectId}/award_emoji`;
504
+ if (input.reacted) {
505
+ return write({
506
+ cwd: input.cwd,
507
+ operation: "setReaction",
508
+ path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
509
+ method: "POST",
510
+ });
511
+ }
512
+ // GitLab deletes an award by its id and takes no emoji name there, so the reader's own
513
+ // award of that name is looked up first. Nothing to delete is success.
514
+ return viewer({ cwd: input.cwd, operation: "setReaction" }).pipe(
515
+ Effect.flatMap((login) =>
516
+ read({
517
+ cwd: input.cwd,
518
+ operation: "setReaction",
519
+ path: paged(subject, 1),
520
+ decode: (raw) =>
521
+ decodeOwnAwardIdJson(raw, { content: input.content, viewer: login }),
522
+ }),
523
+ ),
524
+ Effect.flatMap((own) =>
525
+ own === null
526
+ ? Effect.void
527
+ : write({
528
+ cwd: input.cwd,
529
+ operation: "setReaction",
530
+ path: `${subject}/${own}`,
531
+ method: "DELETE",
532
+ }),
533
+ ),
534
+ );
535
+ }),
536
+ ),
537
+
538
+ listTemplates: (input) =>
539
+ read({
540
+ cwd: input.cwd,
541
+ operation: "listTemplates",
542
+ path: `projects/${projectPath(input.scope)}/templates/issues`,
543
+ decode: decodeTemplateEntriesJson,
544
+ }).pipe(
545
+ Effect.flatMap((entries) =>
546
+ Effect.forEach(entries.slice(0, TEMPLATE_LIMIT), template(input), { concurrency: 4 }),
547
+ ),
548
+ // GitLab has no switch that forbids an issue filed from nothing.
549
+ Effect.map((templates) => ({ templates, blankIssuesEnabled: true })),
550
+ ),
551
+
552
+ listCandidates: (input) =>
553
+ Effect.all(
554
+ [
555
+ read({
556
+ cwd: input.cwd,
557
+ operation: "listCandidates",
558
+ path: paged(`projects/${projectPath(input.scope)}/labels`, 1),
559
+ decode: decodeProjectLabelsJson,
560
+ }),
561
+ read({
562
+ cwd: input.cwd,
563
+ operation: "listCandidates",
564
+ path: paged(`projects/${projectPath(input.scope)}/members/all`, 1),
565
+ decode: decodeProjectMembersJson,
566
+ }),
567
+ ],
568
+ { concurrency: 2 },
569
+ ).pipe(
570
+ Effect.map(([labels, assignees]) => ({
571
+ labels,
572
+ assignees,
573
+ truncated: labels.length >= PAGE_SIZE || assignees.length >= PAGE_SIZE,
574
+ })),
575
+ ),
576
+ };
577
+ },
578
+);
packages/source-control-gitlab/src/server/driver.ts
+2
@@ -9,6 +9,7 @@ import { definition } from "../shared/definition.ts";
9
10
import * as GitLabCli from "./GitLabCli.ts";
11
import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
12
+import * as GitLabIssueTracker from "./GitLabIssueTracker.ts";
13
import * as GitLabPullRequestProvider from "./GitLabPullRequestProvider.ts";
14
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
15
@@ -18,6 +19,7 @@ const makeInstance = Effect.all({
19
sourceControl: GitLabSourceControlProvider.make,
20
discovery: Effect.succeed(GitLabSourceControlProvider.discovery),
21
pullRequests: GitLabPullRequestProvider.make,
22
+ issues: GitLabIssueTracker.make,
23
});
24
25
export const driver = defineSourceControlDriver({
packages/source-control-gitlab/src/server/gitLabIssueJson.ts
new
+410
@@ -0,0 +1,410 @@
1
+/**
2
+ * Decoders for GitLab issues as `glab api` answers them. REST enums are decoded as plain strings
3
+ * and normalized here, so a GitLab release that adds a state or a label action never fails a
4
+ * whole payload; a row that cannot be read is skipped rather than failing its page.
5
+ *
6
+ * @module source-control-gitlab/server/gitLabIssueJson
7
+ */
8
+import * as Exit from "effect/Exit";
9
+import * as Result from "effect/Result";
10
+import * as Schema from "effect/Schema";
11
+import type {
12
+ IssueActor,
13
+ IssueAssigneeCandidate,
14
+ IssueComment,
15
+ IssueEvent,
16
+ IssueEventKind,
17
+ IssueLabel,
18
+ IssueLabelCandidate,
19
+ IssueLinkedPullRequest,
20
+ IssueTemplate,
21
+ PullRequestState,
22
+} from "@t3tools/contracts";
23
+import { decodeJsonResult } from "@t3tools/shared/schemaJson";
24
+import type { TrackerIssueSummary } from "@t3tools/source-control-core/server/IssueTracker";
25
+
26
+/** GitLab's ceiling on `per_page`, which is what every bounded read asks for. */
27
+export const PAGE_SIZE = 100;
28
+
29
+const RawUserSchema = Schema.Struct({
30
+ /** GitLab writes an issue's assignees as numeric ids, so the id travels with the handle. */
31
+ id: Schema.optional(Schema.Int),
32
+ username: Schema.String,
33
+ name: Schema.optional(Schema.NullOr(Schema.String)),
34
+ avatar_url: Schema.optional(Schema.NullOr(Schema.String)),
35
+});
36
+
37
+const RawIssueSchema = Schema.Struct({
38
+ iid: Schema.Int,
39
+ title: Schema.String,
40
+ web_url: Schema.String,
41
+ description: Schema.optional(Schema.NullOr(Schema.String)),
42
+ author: Schema.optional(Schema.NullOr(RawUserSchema)),
43
+ state: Schema.optional(Schema.NullOr(Schema.String)),
44
+ created_at: Schema.String,
45
+ updated_at: Schema.String,
46
+ closed_at: Schema.optional(Schema.NullOr(Schema.String)),
47
+ assignees: Schema.optional(Schema.NullOr(Schema.Array(RawUserSchema))),
48
+ labels: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
49
+ user_notes_count: Schema.optional(Schema.NullOr(Schema.Int)),
50
+});
51
+
52
+const RawNoteSchema = Schema.Struct({
53
+ id: Schema.Int,
54
+ body: Schema.optional(Schema.NullOr(Schema.String)),
55
+ author: Schema.optional(Schema.NullOr(RawUserSchema)),
56
+ created_at: Schema.String,
57
+ /** True for the notes GitLab writes itself ("closed", "assigned to @x"), which are events. */
58
+ system: Schema.optional(Schema.Boolean),
59
+});
60
+
61
+const RawLabelEventSchema = Schema.Struct({
62
+ id: Schema.Int,
63
+ action: Schema.String,
64
+ created_at: Schema.String,
65
+ user: Schema.optional(Schema.NullOr(RawUserSchema)),
66
+ /** Null once the label itself has been deleted, which leaves the event with no subject. */
67
+ label: Schema.optional(Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.String) }))),
68
+});
69
+
70
+const RawLinkedMergeRequestSchema = Schema.Struct({
71
+ iid: Schema.Int,
72
+ title: Schema.String,
73
+ web_url: Schema.String,
74
+ state: Schema.optional(Schema.NullOr(Schema.String)),
75
+ draft: Schema.optional(Schema.Boolean),
76
+ work_in_progress: Schema.optional(Schema.Boolean),
77
+ /** `full` is `group/project!12`, which is the only place the merge request names its project. */
78
+ references: Schema.optional(
79
+ Schema.NullOr(Schema.Struct({ full: Schema.optional(Schema.NullOr(Schema.String)) })),
80
+ ),
81
+});
82
+
83
+const RawProjectLabelSchema = Schema.Struct({
84
+ name: Schema.String,
85
+ color: Schema.optional(Schema.NullOr(Schema.String)),
86
+ description: Schema.optional(Schema.NullOr(Schema.String)),
87
+});
88
+
89
+/** A row of `GET /projects/:id/templates/issues`, which names a template but carries none of it. */
90
+const RawTemplateEntrySchema = Schema.Struct({
91
+ key: Schema.String,
92
+ name: Schema.optional(Schema.NullOr(Schema.String)),
93
+});
94
+
95
+const RawTemplateSchema = Schema.Struct({ content: Schema.optional(Schema.NullOr(Schema.String)) });
96
+
97
+const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
98
+const decodeIssue = decodeJsonResult(RawIssueSchema);
99
+const decodeIssueEntry = Schema.decodeUnknownExit(RawIssueSchema);
100
+const decodeNoteEntry = Schema.decodeUnknownExit(RawNoteSchema);
101
+const decodeLabelEventEntry = Schema.decodeUnknownExit(RawLabelEventSchema);
102
+const decodeLinkedMergeRequestEntry = Schema.decodeUnknownExit(RawLinkedMergeRequestSchema);
103
+const decodeProjectLabelEntry = Schema.decodeUnknownExit(RawProjectLabelSchema);
104
+const decodeUserEntry = Schema.decodeUnknownExit(RawUserSchema);
105
+const decodeTemplateEntry = Schema.decodeUnknownExit(RawTemplateEntrySchema);
106
+const decodeTemplate = decodeJsonResult(RawTemplateSchema);
107
+
108
+type DecodeFailure =
109
+ ReturnType<typeof decodeIssue> extends Result.Result<unknown, infer E> ? E : never;
110
+
111
+function trimmed(value: string | null | undefined): string | null {
112
+ const text = value?.trim() ?? "";
113
+ return text.length > 0 ? text : null;
114
+}
115
+
116
+function toActor(raw: typeof RawUserSchema.Type | null | undefined): IssueActor | null {
117
+ const login = trimmed(raw?.username);
118
+ return login === null
119
+ ? null
120
+ : { login, name: trimmed(raw?.name), avatarUrl: trimmed(raw?.avatar_url) };
121
+}
122
+
123
+/** GitLab returns label names only on an issue, so there is no colour to carry. */
124
+function toLabels(raw: ReadonlyArray<string> | null | undefined): ReadonlyArray<IssueLabel> {
125
+ return (raw ?? []).flatMap((label) => {
126
+ const name = trimmed(label);
127
+ return name === null ? [] : [{ name, color: null }];
128
+ });
129
+}
130
+
131
+function toSummary(raw: typeof RawIssueSchema.Type): TrackerIssueSummary {
132
+ return {
133
+ key: String(raw.iid),
134
+ displayKey: `#${raw.iid}`,
135
+ title: raw.title,
136
+ url: raw.web_url,
137
+ author: toActor(raw.author),
138
+ // GitLab has exactly the two states, calls the open one `opened`, and records no reason.
139
+ state:
140
+ raw.state?.trim().toLowerCase() === "closed"
141
+ ? { category: "closed", name: "closed" }
142
+ : { category: "open", name: "open" },
143
+ createdAt: raw.created_at,
144
+ updatedAt: raw.updated_at,
145
+ closedAt: trimmed(raw.closed_at),
146
+ assignees: (raw.assignees ?? []).flatMap((user) => toActor(user) ?? []),
147
+ labels: toLabels(raw.labels),
148
+ commentCount: Math.max(0, raw.user_notes_count ?? 0),
149
+ };
150
+}
151
+
152
+interface GitLabIssueList {
153
+ readonly items: ReadonlyArray<TrackerIssueSummary>;
154
+ /** Rows GitLab returned, counted before decoding, so a skipped row cannot hide a next page. */
155
+ readonly rawCount: number;
156
+}
157
+
158
+export function decodeIssueListJson(raw: string): Result.Result<GitLabIssueList, DecodeFailure> {
159
+ return Result.map(decodeUnknownList(raw), (rows) => ({
160
+ items: rows.flatMap((entry) => {
161
+ const issue = decodeIssueEntry(entry);
162
+ return Exit.isSuccess(issue) ? [toSummary(issue.value)] : [];
163
+ }),
164
+ rawCount: rows.length,
165
+ }));
166
+}
167
+
168
+interface GitLabIssueDetail extends TrackerIssueSummary {
169
+ readonly body: string;
170
+}
171
+
172
+export function decodeIssueDetailJson(
173
+ raw: string,
174
+): Result.Result<GitLabIssueDetail, DecodeFailure> {
175
+ return Result.map(decodeIssue(raw), (issue) => ({
176
+ ...toSummary(issue),
177
+ body: issue.description ?? "",
178
+ }));
179
+}
180
+
181
+export function decodeCreatedIssueJson(
182
+ raw: string,
183
+): Result.Result<{ readonly number: number; readonly url: string }, DecodeFailure> {
184
+ return Result.map(decodeIssue(raw), (issue) => ({ number: issue.iid, url: issue.web_url }));
185
+}
186
+
187
+/**
188
+ * The events GitLab records as notes of its own. A label note names its labels by id ("added ~7
189
+ * label"), which is why labellings come from `/resource_label_events` instead and are dropped here.
190
+ */
191
+function toSystemEvent(
192
+ body: string,
193
+): { readonly kind: IssueEventKind; readonly detail: string | null } | null {
194
+ const text = body.trim();
195
+ if (text === "closed") return { kind: "closed", detail: null };
196
+ if (text === "reopened") return { kind: "reopened", detail: null };
197
+ if (text.startsWith("assigned to ")) {
198
+ return {
199
+ kind: "assigned",
200
+ detail: trimmed(text.slice("assigned to ".length).replace(/^@/, "")),
201
+ };
202
+ }
203
+ if (text.startsWith("unassigned ")) {
204
+ return {
205
+ kind: "unassigned",
206
+ detail: trimmed(text.slice("unassigned ".length).replace(/^@/, "")),
207
+ };
208
+ }
209
+ if (text.startsWith("mentioned in ")) {
210
+ return { kind: "referenced", detail: trimmed(text.slice("mentioned in ".length)) };
211
+ }
212
+ if (text.startsWith("changed title")) {
213
+ // GitLab marks the new title with its own inline-diff braces.
214
+ return { kind: "renamed", detail: trimmed(/\{\+(.+)\+\}/.exec(text)?.[1]) };
215
+ }
216
+ return null;
217
+}
218
+
219
+interface GitLabIssueNotes {
220
+ readonly comments: ReadonlyArray<IssueComment>;
221
+ readonly events: ReadonlyArray<IssueEvent>;
222
+ readonly rawCount: number;
223
+}
224
+
225
+/** One page of notes, split into what people wrote and what GitLab wrote about the issue. */
226
+export function decodeIssueNotesJson(raw: string): Result.Result<GitLabIssueNotes, DecodeFailure> {
227
+ return Result.map(decodeUnknownList(raw), (rows) => {
228
+ const comments: IssueComment[] = [];
229
+ const events: IssueEvent[] = [];
230
+ for (const entry of rows) {
231
+ const note = decodeNoteEntry(entry);
232
+ if (Exit.isFailure(note)) continue;
233
+ const value = note.value;
234
+ const body = value.body ?? "";
235
+ if (value.system === true) {
236
+ const event = toSystemEvent(body);
237
+ if (event === null) continue;
238
+ events.push({
239
+ // Notes and label events are numbered separately, so each carries where it came from.
240
+ id: `note-${value.id}`,
241
+ kind: event.kind,
242
+ actor: toActor(value.author),
243
+ createdAt: value.created_at,
244
+ detail: event.detail,
245
+ });
246
+ continue;
247
+ }
248
+ comments.push({
249
+ id: String(value.id),
250
+ author: toActor(value.author),
251
+ body,
252
+ createdAt: value.created_at,
253
+ url: null,
254
+ });
255
+ }
256
+ return { comments, events, rawCount: rows.length };
257
+ });
258
+}
259
+
260
+export function decodeLabelEventsJson(
261
+ raw: string,
262
+): Result.Result<ReadonlyArray<IssueEvent>, DecodeFailure> {
263
+ return Result.map(decodeUnknownList(raw), (rows) =>
264
+ rows.flatMap((entry) => {
265
+ const event = decodeLabelEventEntry(entry);
266
+ if (Exit.isFailure(event)) return [];
267
+ const action = event.value.action.trim().toLowerCase();
268
+ if (action !== "add" && action !== "remove") return [];
269
+ return [
270
+ {
271
+ id: `label-${event.value.id}`,
272
+ kind: action === "add" ? ("labeled" as const) : ("unlabeled" as const),
273
+ actor: toActor(event.value.user),
274
+ createdAt: event.value.created_at,
275
+ detail: trimmed(event.value.label?.name),
276
+ },
277
+ ];
278
+ }),
279
+ );
280
+}
281
+
282
+function toPullRequestState(value: string | null | undefined): PullRequestState {
283
+ switch (value?.trim().toLowerCase()) {
284
+ case "merged":
285
+ return "merged";
286
+ case "closed":
287
+ return "closed";
288
+ default:
289
+ // `locked` is an open merge request whose discussion is locked.
290
+ return "open";
291
+ }
292
+}
293
+
294
+export function decodeLinkedMergeRequestsJson(
295
+ raw: string,
296
+ closesIssue: boolean,
297
+): Result.Result<ReadonlyArray<IssueLinkedPullRequest>, DecodeFailure> {
298
+ return Result.map(decodeUnknownList(raw), (rows) =>
299
+ rows.flatMap((entry) => {
300
+ const mergeRequest = decodeLinkedMergeRequestEntry(entry);
301
+ if (Exit.isFailure(mergeRequest)) return [];
302
+ const value = mergeRequest.value;
303
+ const repository = trimmed(value.references?.full?.split("!")[0]);
304
+ const title = trimmed(value.title);
305
+ const url = trimmed(value.web_url);
306
+ if (repository === null || title === null || url === null || value.iid <= 0) return [];
307
+ return [
308
+ {
309
+ repository,
310
+ number: value.iid,
311
+ title,
312
+ url,
313
+ state: toPullRequestState(value.state),
314
+ isDraft: value.draft ?? value.work_in_progress ?? false,
315
+ closesIssue,
316
+ },
317
+ ];
318
+ }),
319
+ );
320
+}
321
+
322
+export function decodeProjectLabelsJson(
323
+ raw: string,
324
+): Result.Result<ReadonlyArray<IssueLabelCandidate>, DecodeFailure> {
325
+ return Result.map(decodeUnknownList(raw), (rows) =>
326
+ rows.flatMap((entry) => {
327
+ const label = decodeProjectLabelEntry(entry);
328
+ if (Exit.isFailure(label)) return [];
329
+ const name = trimmed(label.value.name);
330
+ return name === null
331
+ ? []
332
+ : [
333
+ {
334
+ name,
335
+ color: trimmed(label.value.color),
336
+ description: label.value.description ?? null,
337
+ },
338
+ ];
339
+ }),
340
+ );
341
+}
342
+
343
+/**
344
+ * The people with access to the project as assignees. GitLab addresses an assignment by numeric
345
+ * id and by nothing else, so a member it named no id for is dropped rather than offered under a
346
+ * handle the write would discard.
347
+ */
348
+export function decodeProjectMembersJson(
349
+ raw: string,
350
+): Result.Result<ReadonlyArray<IssueAssigneeCandidate>, DecodeFailure> {
351
+ return Result.map(decodeUnknownList(raw), (rows) =>
352
+ rows.flatMap((entry) => {
353
+ const user = decodeUserEntry(entry);
354
+ if (Exit.isFailure(user) || user.value.id === undefined) return [];
355
+ const actor = toActor(user.value);
356
+ return actor === null ? [] : [{ ...actor, id: String(user.value.id) }];
357
+ }),
358
+ );
359
+}
360
+
361
+export interface GitLabTemplateEntry {
362
+ readonly key: string;
363
+ readonly name: string;
364
+}
365
+
366
+export function decodeTemplateEntriesJson(
367
+ raw: string,
368
+): Result.Result<ReadonlyArray<GitLabTemplateEntry>, DecodeFailure> {
369
+ return Result.map(decodeUnknownList(raw), (rows) =>
370
+ rows.flatMap((entry) => {
371
+ const template = decodeTemplateEntry(entry);
372
+ if (Exit.isFailure(template)) return [];
373
+ const key = trimmed(template.value.key);
374
+ return key === null ? [] : [{ key, name: trimmed(template.value.name) ?? key }];
375
+ }),
376
+ );
377
+}
378
+
379
+/** One template's own answer is the markdown a description starts out as; GitLab adds nothing else. */
380
+export function decodeTemplateJson(
381
+ entry: GitLabTemplateEntry,
382
+ raw: string,
383
+): Result.Result<IssueTemplate, DecodeFailure> {
384
+ return Result.map(decodeTemplate(raw), (template) => ({
385
+ key: entry.key,
386
+ name: entry.name,
387
+ about: "",
388
+ title: "",
389
+ body: template.content ?? "",
390
+ labels: [],
391
+ assignees: [],
392
+ }));
393
+}
394
+
395
+/**
396
+ * Awards on the issue and on every note of it, in one read, shaped exactly like the merge request
397
+ * query so its decoder answers for both: `mergeRequest` is an alias for the issue field.
398
+ */
399
+export const ISSUE_AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
400
+ currentUser { username }
401
+ project(fullPath: $fullPath) {
402
+ mergeRequest: issue(iid: $iid) {
403
+ awardEmoji { nodes { name user { username } } }
404
+ notes(first: ${PAGE_SIZE}, after: $cursor) {
405
+ pageInfo { hasNextPage endCursor }
406
+ nodes { id awardEmoji { nodes { name user { username } } } }
407
+ }
408
+ }
409
+ }
410
+}`;