Open History to see the last commit
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 */
8import * as Exit from "effect/Exit";
9import * as Result from "effect/Result";
10import * as Schema from "effect/Schema";
11import type {
12 IssueActor,
13 IssueAssigneeCandidate,
14 IssueComment,
15 IssueEvent,
16 IssueEventKind,
17 IssueLabel,
18 IssueLabelCandidate,
19 IssueLinkedPullRequest,
20 IssueState,
21 IssueTemplate,
22 PullRequestState,
23} from "@t3tools/contracts";
24import { decodeJsonResult } from "@t3tools/shared/schemaJson";
25import type { TrackerIssueSummary } from "@t3tools/source-control-core/server/IssueTracker";
26
27/** GitLab's ceiling on `per_page`, which is what every bounded read asks for. */
28export const PAGE_SIZE = 100;
29
30const RawUserSchema = Schema.Struct({
31 /** GitLab writes an issue's assignees as numeric ids, so the id travels with the handle. */
32 id: Schema.optional(Schema.Int),
33 username: Schema.String,
34 name: Schema.optional(Schema.NullOr(Schema.String)),
35 avatar_url: Schema.optional(Schema.NullOr(Schema.String)),
36});
37
38const RawIssueSchema = Schema.Struct({
39 iid: Schema.Int,
40 title: Schema.String,
41 web_url: Schema.String,
42 description: Schema.optional(Schema.NullOr(Schema.String)),
43 author: Schema.optional(Schema.NullOr(RawUserSchema)),
44 state: Schema.optional(Schema.NullOr(Schema.String)),
45 created_at: Schema.String,
46 updated_at: Schema.String,
47 closed_at: Schema.optional(Schema.NullOr(Schema.String)),
48 assignees: Schema.optional(Schema.NullOr(Schema.Array(RawUserSchema))),
49 labels: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
50 user_notes_count: Schema.optional(Schema.NullOr(Schema.Int)),
51});
52
53const RawNoteSchema = Schema.Struct({
54 id: Schema.Int,
55 body: Schema.optional(Schema.NullOr(Schema.String)),
56 author: Schema.optional(Schema.NullOr(RawUserSchema)),
57 created_at: Schema.String,
58 /** True for the notes GitLab writes itself ("closed", "assigned to @x"), which are events. */
59 system: Schema.optional(Schema.Boolean),
60});
61
62const RawLabelEventSchema = Schema.Struct({
63 id: Schema.Int,
64 action: Schema.String,
65 created_at: Schema.String,
66 user: Schema.optional(Schema.NullOr(RawUserSchema)),
67 /** Null once the label itself has been deleted, which leaves the event with no subject. */
68 label: Schema.optional(Schema.NullOr(Schema.Struct({ name: Schema.optional(Schema.String) }))),
69});
70
71const RawLinkedMergeRequestSchema = Schema.Struct({
72 iid: Schema.Int,
73 title: Schema.String,
74 web_url: Schema.String,
75 state: Schema.optional(Schema.NullOr(Schema.String)),
76 draft: Schema.optional(Schema.Boolean),
77 work_in_progress: Schema.optional(Schema.Boolean),
78 /** `full` is `group/project!12`, which is the only place the merge request names its project. */
79 references: Schema.optional(
80 Schema.NullOr(Schema.Struct({ full: Schema.optional(Schema.NullOr(Schema.String)) })),
81 ),
82});
83
84const RawProjectLabelSchema = Schema.Struct({
85 name: Schema.String,
86 color: Schema.optional(Schema.NullOr(Schema.String)),
87 description: Schema.optional(Schema.NullOr(Schema.String)),
88});
89
90/** A row of `GET /projects/:id/templates/issues`, which names a template but carries none of it. */
91const RawTemplateEntrySchema = Schema.Struct({
92 key: Schema.String,
93 name: Schema.optional(Schema.NullOr(Schema.String)),
94});
95
96const RawTemplateSchema = Schema.Struct({ content: Schema.optional(Schema.NullOr(Schema.String)) });
97
98const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
99const decodeIssue = decodeJsonResult(RawIssueSchema);
100const decodeIssueEntry = Schema.decodeUnknownExit(RawIssueSchema);
101const decodeNoteEntry = Schema.decodeUnknownExit(RawNoteSchema);
102const decodeLabelEventEntry = Schema.decodeUnknownExit(RawLabelEventSchema);
103const decodeLinkedMergeRequestEntry = Schema.decodeUnknownExit(RawLinkedMergeRequestSchema);
104const decodeProjectLabelEntry = Schema.decodeUnknownExit(RawProjectLabelSchema);
105const decodeUserEntry = Schema.decodeUnknownExit(RawUserSchema);
106const decodeTemplateEntry = Schema.decodeUnknownExit(RawTemplateEntrySchema);
107const decodeTemplate = decodeJsonResult(RawTemplateSchema);
108
109type DecodeFailure =
110 ReturnType<typeof decodeIssue> extends Result.Result<unknown, infer E> ? E : never;
111
112function trimmed(value: string | null | undefined): string | null {
113 const text = value?.trim() ?? "";
114 return text.length > 0 ? text : null;
115}
116
117function toActor(raw: typeof RawUserSchema.Type | null | undefined): IssueActor | null {
118 const login = trimmed(raw?.username);
119 return login === null
120 ? null
121 : { login, name: trimmed(raw?.name), avatarUrl: trimmed(raw?.avatar_url) };
122}
123
124/** GitLab returns label names only on an issue, so there is no colour to carry. */
125function toLabels(raw: ReadonlyArray<string> | null | undefined): ReadonlyArray<IssueLabel> {
126 return (raw ?? []).flatMap((label) => {
127 const name = trimmed(label);
128 return name === null ? [] : [{ name, color: null }];
129 });
130}
131
132const OPEN: IssueState = { category: "open", name: "Open" };
133const CLOSED: IssueState = { category: "closed", name: "Closed" };
134
135/** GitLab has exactly the two states and records no reason for a close. */
136export const ISSUE_STATES: ReadonlyArray<IssueState> = [OPEN, CLOSED];
137
138function toSummary(raw: typeof RawIssueSchema.Type): TrackerIssueSummary {
139 return {
140 key: String(raw.iid),
141 displayKey: `#${raw.iid}`,
142 title: raw.title,
143 url: raw.web_url,
144 author: toActor(raw.author),
145 // GitLab calls the open one `opened`.
146 state: raw.state?.trim().toLowerCase() === "closed" ? CLOSED : OPEN,
147 createdAt: raw.created_at,
148 updatedAt: raw.updated_at,
149 closedAt: trimmed(raw.closed_at),
150 assignees: (raw.assignees ?? []).flatMap((user) => toActor(user) ?? []),
151 labels: toLabels(raw.labels),
152 commentCount: Math.max(0, raw.user_notes_count ?? 0),
153 };
154}
155
156interface GitLabIssueList {
157 readonly items: ReadonlyArray<TrackerIssueSummary>;
158 /** Rows GitLab returned, counted before decoding, so a skipped row cannot hide a next page. */
159 readonly rawCount: number;
160}
161
162export function decodeIssueListJson(raw: string): Result.Result<GitLabIssueList, DecodeFailure> {
163 return Result.map(decodeUnknownList(raw), (rows) => ({
164 items: rows.flatMap((entry) => {
165 const issue = decodeIssueEntry(entry);
166 return Exit.isSuccess(issue) ? [toSummary(issue.value)] : [];
167 }),
168 rawCount: rows.length,
169 }));
170}
171
172interface GitLabIssueDetail extends TrackerIssueSummary {
173 readonly body: string;
174}
175
176export function decodeIssueDetailJson(
177 raw: string,
178): Result.Result<GitLabIssueDetail, DecodeFailure> {
179 return Result.map(decodeIssue(raw), (issue) => ({
180 ...toSummary(issue),
181 body: issue.description ?? "",
182 }));
183}
184
185/** The ids of the users a `/users?username=` lookup answered with: one, or none. */
186export function decodeUserIdsJson(
187 raw: string,
188): Result.Result<ReadonlyArray<number>, DecodeFailure> {
189 return Result.map(decodeUnknownList(raw), (rows) =>
190 rows.flatMap((entry) => {
191 const user = decodeUserEntry(entry);
192 return Exit.isSuccess(user) && user.value.id !== undefined ? [user.value.id] : [];
193 }),
194 );
195}
196
197export function decodeCreatedIssueJson(
198 raw: string,
199): Result.Result<{ readonly number: number; readonly url: string }, DecodeFailure> {
200 return Result.map(decodeIssue(raw), (issue) => ({ number: issue.iid, url: issue.web_url }));
201}
202
203/**
204 * The events GitLab records as notes of its own. A label note names its labels by id ("added ~7
205 * label"), which is why labellings come from `/resource_label_events` instead and are dropped here.
206 */
207function toSystemEvent(
208 body: string,
209): { readonly kind: IssueEventKind; readonly detail: string | null } | null {
210 const text = body.trim();
211 if (text === "closed") return { kind: "closed", detail: null };
212 if (text === "reopened") return { kind: "reopened", detail: null };
213 if (text.startsWith("assigned to ")) {
214 return {
215 kind: "assigned",
216 detail: trimmed(text.slice("assigned to ".length).replace(/^@/, "")),
217 };
218 }
219 if (text.startsWith("unassigned ")) {
220 return {
221 kind: "unassigned",
222 detail: trimmed(text.slice("unassigned ".length).replace(/^@/, "")),
223 };
224 }
225 if (text.startsWith("mentioned in ")) {
226 return { kind: "referenced", detail: trimmed(text.slice("mentioned in ".length)) };
227 }
228 if (text.startsWith("changed title")) {
229 // GitLab marks the new title with its own inline-diff braces.
230 return { kind: "renamed", detail: trimmed(/\{\+(.+)\+\}/.exec(text)?.[1]) };
231 }
232 return null;
233}
234
235interface GitLabIssueNotes {
236 readonly comments: ReadonlyArray<IssueComment>;
237 readonly events: ReadonlyArray<IssueEvent>;
238 readonly rawCount: number;
239}
240
241/** One page of notes, split into what people wrote and what GitLab wrote about the issue. */
242export function decodeIssueNotesJson(raw: string): Result.Result<GitLabIssueNotes, DecodeFailure> {
243 return Result.map(decodeUnknownList(raw), (rows) => {
244 const comments: IssueComment[] = [];
245 const events: IssueEvent[] = [];
246 for (const entry of rows) {
247 const note = decodeNoteEntry(entry);
248 if (Exit.isFailure(note)) continue;
249 const value = note.value;
250 const body = value.body ?? "";
251 if (value.system === true) {
252 const event = toSystemEvent(body);
253 if (event === null) continue;
254 events.push({
255 // Notes and label events are numbered separately, so each carries where it came from.
256 id: `note-${value.id}`,
257 kind: event.kind,
258 actor: toActor(value.author),
259 createdAt: value.created_at,
260 detail: event.detail,
261 });
262 continue;
263 }
264 comments.push({
265 id: String(value.id),
266 author: toActor(value.author),
267 body,
268 createdAt: value.created_at,
269 url: null,
270 });
271 }
272 return { comments, events, rawCount: rows.length };
273 });
274}
275
276export function decodeLabelEventsJson(
277 raw: string,
278): Result.Result<ReadonlyArray<IssueEvent>, DecodeFailure> {
279 return Result.map(decodeUnknownList(raw), (rows) =>
280 rows.flatMap((entry) => {
281 const event = decodeLabelEventEntry(entry);
282 if (Exit.isFailure(event)) return [];
283 const action = event.value.action.trim().toLowerCase();
284 if (action !== "add" && action !== "remove") return [];
285 return [
286 {
287 id: `label-${event.value.id}`,
288 kind: action === "add" ? ("labeled" as const) : ("unlabeled" as const),
289 actor: toActor(event.value.user),
290 createdAt: event.value.created_at,
291 detail: trimmed(event.value.label?.name),
292 },
293 ];
294 }),
295 );
296}
297
298function toPullRequestState(value: string | null | undefined): PullRequestState {
299 switch (value?.trim().toLowerCase()) {
300 case "merged":
301 return "merged";
302 case "closed":
303 return "closed";
304 default:
305 // `locked` is an open merge request whose discussion is locked.
306 return "open";
307 }
308}
309
310export function decodeLinkedMergeRequestsJson(
311 raw: string,
312 closesIssue: boolean,
313): Result.Result<ReadonlyArray<IssueLinkedPullRequest>, DecodeFailure> {
314 return Result.map(decodeUnknownList(raw), (rows) =>
315 rows.flatMap((entry) => {
316 const mergeRequest = decodeLinkedMergeRequestEntry(entry);
317 if (Exit.isFailure(mergeRequest)) return [];
318 const value = mergeRequest.value;
319 const repository = trimmed(value.references?.full?.split("!")[0]);
320 const title = trimmed(value.title);
321 const url = trimmed(value.web_url);
322 if (repository === null || title === null || url === null || value.iid <= 0) return [];
323 return [
324 {
325 repository,
326 number: value.iid,
327 title,
328 url,
329 state: toPullRequestState(value.state),
330 isDraft: value.draft ?? value.work_in_progress ?? false,
331 closesIssue,
332 },
333 ];
334 }),
335 );
336}
337
338export function decodeProjectLabelsJson(
339 raw: string,
340): Result.Result<ReadonlyArray<IssueLabelCandidate>, DecodeFailure> {
341 return Result.map(decodeUnknownList(raw), (rows) =>
342 rows.flatMap((entry) => {
343 const label = decodeProjectLabelEntry(entry);
344 if (Exit.isFailure(label)) return [];
345 const name = trimmed(label.value.name);
346 return name === null
347 ? []
348 : [
349 {
350 name,
351 color: trimmed(label.value.color),
352 description: label.value.description ?? null,
353 },
354 ];
355 }),
356 );
357}
358
359/**
360 * The people with access to the project as assignees. GitLab addresses an assignment by numeric
361 * id and by nothing else, so a member it named no id for is dropped rather than offered under a
362 * handle the write would discard.
363 */
364export function decodeProjectMembersJson(
365 raw: string,
366): Result.Result<ReadonlyArray<IssueAssigneeCandidate>, DecodeFailure> {
367 return Result.map(decodeUnknownList(raw), (rows) =>
368 rows.flatMap((entry) => {
369 const user = decodeUserEntry(entry);
370 if (Exit.isFailure(user) || user.value.id === undefined) return [];
371 const actor = toActor(user.value);
372 return actor === null ? [] : [{ ...actor, id: String(user.value.id) }];
373 }),
374 );
375}
376
377export interface GitLabTemplateEntry {
378 readonly key: string;
379 readonly name: string;
380}
381
382export function decodeTemplateEntriesJson(
383 raw: string,
384): Result.Result<ReadonlyArray<GitLabTemplateEntry>, DecodeFailure> {
385 return Result.map(decodeUnknownList(raw), (rows) =>
386 rows.flatMap((entry) => {
387 const template = decodeTemplateEntry(entry);
388 if (Exit.isFailure(template)) return [];
389 const key = trimmed(template.value.key);
390 return key === null ? [] : [{ key, name: trimmed(template.value.name) ?? key }];
391 }),
392 );
393}
394
395/** One template's own answer is the markdown a description starts out as; GitLab adds nothing else. */
396export function decodeTemplateJson(
397 entry: GitLabTemplateEntry,
398 raw: string,
399): Result.Result<IssueTemplate, DecodeFailure> {
400 return Result.map(decodeTemplate(raw), (template) => ({
401 key: entry.key,
402 name: entry.name,
403 about: "",
404 title: "",
405 body: template.content ?? "",
406 labels: [],
407 assignees: [],
408 }));
409}
410
411/**
412 * Awards on the issue and on every note of it, in one read, shaped exactly like the merge request
413 * query so its decoder answers for both: `mergeRequest` is an alias for the issue field.
414 */
415export const ISSUE_AWARD_EMOJI_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!, $cursor: String) {
416 currentUser { username }
417 project(fullPath: $fullPath) {
418 mergeRequest: issue(iid: $iid) {
419 awardEmoji { nodes { name user { username } } }
420 notes(first: ${PAGE_SIZE}, after: $cursor) {
421 pageInfo { hasNextPage endCursor }
422 nodes { id awardEmoji { nodes { name user { username } } } }
423 }
424 }
425 }
426}`;