@leitwerk-dev/gitlab 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { asUnknownRecord } from "@leitwerk-dev/domain";
2
2
  import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
3
+ import { preflightGitLabRepository } from "./preflight.js";
3
4
 
4
5
  /** @internal */
5
6
  export interface GitLabProfile {
@@ -51,7 +52,32 @@ export interface GitLabGroup {
51
52
  full_path: string;
52
53
  }
53
54
  /** @public */
55
+ export interface GitLabIssue {
56
+ /** @public */
57
+ id: number;
58
+ /** @public */
59
+ iid: number;
60
+ /** @public */
61
+ project_id: number;
62
+ /** @public */
63
+ title: string;
64
+ /** @public */
65
+ description: string | null;
66
+ /** @public */
67
+ web_url: string;
68
+ /** @public */
69
+ state: string;
70
+ /** @public */
71
+ labels: string[];
72
+ }
73
+ /** @public */
54
74
  export interface GitLabMergeRequest {
75
+ /** @public */
76
+ detailed_merge_status?: string;
77
+ /** @public */
78
+ has_conflicts?: boolean;
79
+ /** @public */
80
+ merge_status?: string;
55
81
  /** @public */
56
82
  iid: number;
57
83
  /** @public */
@@ -76,12 +102,6 @@ export interface GitLabMergeRequest {
76
102
  target_branch: string;
77
103
  /** @public */
78
104
  web_url: string;
79
- /** @public */
80
- has_conflicts?: boolean;
81
- /** @public */
82
- merge_status?: string;
83
- /** @public */
84
- detailed_merge_status?: string;
85
105
  /** @internal */
86
106
  merge_commit_sha?: string | null;
87
107
  /** @internal */
@@ -135,7 +155,7 @@ export interface GitLabPipeline {
135
155
  }
136
156
  /** @public */
137
157
  export interface GitLabJob {
138
- /** @public */
158
+ /** @internal */
139
159
  id: number;
140
160
  /** @public */
141
161
  name: string;
@@ -170,7 +190,7 @@ export interface GitLabNote {
170
190
  }
171
191
  /** @public */
172
192
  export interface GitLabNoteReaction {
173
- /** @internal */
193
+ /** @public */
174
194
  id: number;
175
195
  /** @internal */
176
196
  name: string;
@@ -244,7 +264,7 @@ export interface GitLabObservation {
244
264
  mr: GitLabMergeRequest;
245
265
  /** @public */
246
266
  pipeline: GitLabPipeline | null;
247
- /** @public Current target branch tip, not the diff's historical merge base. */
267
+ /** @public */
248
268
  targetHead?: string;
249
269
  }
250
270
 
@@ -314,7 +334,8 @@ export function parseGitLabProfiles(raw: unknown): Map<string, GitLabProfile> {
314
334
  const projectPath = (id: number | string) => `/projects/${encodeURIComponent(id)}`;
315
335
  const mrPath = (id: number, iid: number) => `${projectPath(id)}/merge_requests/${iid}`;
316
336
 
317
- /** GitLab v4 API. Errors deliberately omit response bodies, headers and tokens. @public */
337
+ /** GitLab v4 API. Errors deliberately omit response bodies, headers and tokens. */
338
+ /** @public */
318
339
  export class GitLabClient {
319
340
  /** @public */
320
341
  readonly baseUrl: string;
@@ -324,6 +345,8 @@ export class GitLabClient {
324
345
  /** @internal */
325
346
  constructor(
326
347
  profile: GitLabProfile,
348
+ /** @public */
349
+ /** @public */
327
350
  options: {
328
351
  /** @internal */
329
352
  fetch?: typeof fetch;
@@ -340,12 +363,17 @@ export class GitLabClient {
340
363
  this.#fetch = options.fetch ?? fetch;
341
364
  this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
342
365
  }
343
- private async response(path: string, signal?: AbortSignal, body?: unknown): Promise<Response> {
366
+ private async response(
367
+ path: string,
368
+ signal?: AbortSignal,
369
+ body?: unknown,
370
+ method?: string,
371
+ ): Promise<Response> {
344
372
  for (let attempt = 0; ; attempt++) {
345
373
  let response: Response;
346
374
  try {
347
375
  response = await this.#fetch(`${this.baseUrl}/api/v4${path}`, {
348
- method: body === undefined ? "GET" : "POST",
376
+ method: method ?? (body === undefined ? "GET" : "POST"),
349
377
  redirect: "error",
350
378
  headers: {
351
379
  "PRIVATE-TOKEN": this.#profile.token,
@@ -373,8 +401,13 @@ export class GitLabClient {
373
401
  await this.#sleep(Math.min(30_000, seconds > 0 ? seconds * 1_000 : 1_000 * 2 ** attempt));
374
402
  }
375
403
  }
376
- private async request<T>(path: string, signal?: AbortSignal, body?: unknown): Promise<T> {
377
- return this.json<T>(await this.response(path, signal, body));
404
+ private async request<T>(
405
+ path: string,
406
+ signal?: AbortSignal,
407
+ body?: unknown,
408
+ method?: string,
409
+ ): Promise<T> {
410
+ return this.json<T>(await this.response(path, signal, body, method));
378
411
  }
379
412
  private async json<T>(response: Response): Promise<T> {
380
413
  try {
@@ -403,6 +436,113 @@ export class GitLabClient {
403
436
  }
404
437
  throw new Error("GitLab pagination limit exceeded; discovery incomplete");
405
438
  }
439
+ /** @public */
440
+ listIssues(id: number, signal?: AbortSignal): Promise<GitLabIssue[]> {
441
+ return this.pages(`${projectPath(id)}/issues?state=opened&scope=all`, signal);
442
+ }
443
+ /** @public */
444
+ getIssue(id: number, iid: number, signal?: AbortSignal): Promise<GitLabIssue> {
445
+ return this.request(`${projectPath(id)}/issues/${iid}`, signal);
446
+ }
447
+ /** @public */
448
+ updateIssue(
449
+ id: number,
450
+ iid: number,
451
+ /** @public */
452
+ /** @public */
453
+ patch: {
454
+ /** @public */
455
+ labels?: string;
456
+ /** @public */
457
+ state_event?: "close";
458
+ },
459
+ signal?: AbortSignal,
460
+ ): Promise<GitLabIssue> {
461
+ return this.request(`${projectPath(id)}/issues/${iid}`, signal, patch, "PUT");
462
+ }
463
+ /** @public */
464
+ listIssueNotes(id: number, iid: number, signal?: AbortSignal): Promise<GitLabNote[]> {
465
+ return this.pages(`${projectPath(id)}/issues/${iid}/notes`, signal);
466
+ }
467
+ /** @public */
468
+ addIssueNote(id: number, iid: number, body: string, signal?: AbortSignal): Promise<GitLabNote> {
469
+ return this.request(`${projectPath(id)}/issues/${iid}/notes`, signal, { body });
470
+ }
471
+ /** @public */
472
+ /** @public */
473
+ listLabels(
474
+ id: number,
475
+ signal?: AbortSignal,
476
+ ): Promise<
477
+ Array<{
478
+ /** @public */ name: string;
479
+ }>
480
+ > {
481
+ return this.pages(`${projectPath(id)}/labels`, signal);
482
+ }
483
+ /** @public */
484
+ /** @public */
485
+ createLabel(
486
+ id: number,
487
+ name: string,
488
+ signal?: AbortSignal,
489
+ ): Promise<{
490
+ /** @public */ name: string;
491
+ }> {
492
+ return this.request(`${projectPath(id)}/labels`, signal, { name, color: "#2da44e" });
493
+ }
494
+ /** @public */
495
+ listBranchMergeRequests(
496
+ id: number,
497
+ source: string,
498
+ target: string,
499
+ signal?: AbortSignal,
500
+ ): Promise<GitLabMergeRequest[]> {
501
+ return this.pages(
502
+ `${projectPath(id)}/merge_requests?state=all&source_branch=${encodeURIComponent(source)}&target_branch=${encodeURIComponent(target)}`,
503
+ signal,
504
+ );
505
+ }
506
+ /** @public */
507
+ createMergeRequest(
508
+ id: number,
509
+ /** @public */
510
+ /** @public */
511
+ input: {
512
+ /** @public */
513
+ title: string;
514
+ /** @public */
515
+ description: string;
516
+ /** @public */
517
+ source_branch: string;
518
+ /** @public */
519
+ target_branch: string;
520
+ },
521
+ signal?: AbortSignal,
522
+ ): Promise<GitLabMergeRequest> {
523
+ return this.request(`${projectPath(id)}/merge_requests`, signal, {
524
+ ...input,
525
+ remove_source_branch: false,
526
+ });
527
+ }
528
+ /** @public */
529
+ async preflightRepository(
530
+ projectId: number,
531
+ baseBranch: string,
532
+ workBranch: string,
533
+ signal?: AbortSignal,
534
+ ): Promise<void> {
535
+ const project = await this.getProject(projectId, signal);
536
+ await preflightGitLabRepository({
537
+ url: project.http_url_to_repo,
538
+ origin: this.baseUrl,
539
+ token: this.#profile.token,
540
+ baseBranch,
541
+ workBranch,
542
+ signal,
543
+ });
544
+ }
545
+
406
546
  /** @public */
407
547
  getProject(id: number | string, signal?: AbortSignal): Promise<GitLabProject> {
408
548
  return this.request(projectPath(id), signal);
@@ -538,10 +678,10 @@ export class GitLabClient {
538
678
  iid: number,
539
679
  signal?: AbortSignal,
540
680
  ): Promise<GitLabFeedback[]> {
541
- const [discussions, identity] = await Promise.all([
542
- this.pages<GitLabDiscussion>(`${mrPath(id, iid)}/discussions`, signal),
543
- this.resolveGitIdentity(signal),
544
- ]);
681
+ const discussions = await this.pages<GitLabDiscussion>(
682
+ `${mrPath(id, iid)}/discussions`,
683
+ signal,
684
+ );
545
685
  const feedback: GitLabFeedback[] = [];
546
686
  for (const discussion of discussions) {
547
687
  for (const note of discussion.notes) {
@@ -549,7 +689,7 @@ export class GitLabClient {
549
689
  note.system ||
550
690
  note.resolved ||
551
691
  note.author.bot ||
552
- note.author.username === identity.username ||
692
+ /<!-- leitwerk:gitlab:[a-f0-9]{64} -->/.test(note.body) ||
553
693
  !note.body.trim() ||
554
694
  !Number.isFinite(Date.parse(note.created_at))
555
695
  )
@@ -598,10 +738,12 @@ export class GitLabClient {
598
738
  job: number,
599
739
  maxBytes = 65_536,
600
740
  signal?: AbortSignal,
741
+ /** @public */
742
+ /** @public */
601
743
  ): Promise<{
602
- /** @internal */
744
+ /** @public */
603
745
  text: string;
604
- /** @internal */
746
+ /** @public */
605
747
  truncated: boolean;
606
748
  }> {
607
749
  const limit = Math.min(262_144, Math.max(1, Math.floor(maxBytes) || 65_536));
@@ -632,6 +774,16 @@ export class GitLabClient {
632
774
  /** @public */
633
775
  export type GitLabClientLike = Pick<
634
776
  GitLabClient,
777
+ | "listIssues"
778
+ | "getIssue"
779
+ | "updateIssue"
780
+ | "listIssueNotes"
781
+ | "addIssueNote"
782
+ | "listLabels"
783
+ | "createLabel"
784
+ | "listBranchMergeRequests"
785
+ | "createMergeRequest"
786
+ | "preflightRepository"
635
787
  | "addNote"
636
788
  | "addNoteReaction"
637
789
  | "baseUrl"
@@ -657,7 +809,8 @@ export type GitLabClientLike = Pick<
657
809
  | "resolveGitIdentity"
658
810
  >;
659
811
 
660
- /** A pending current pipeline supersedes every older result. Synthetic merges must contain this source head. @public */
812
+ /** A pending current pipeline supersedes every older result. Synthetic merges must contain this source head. */
813
+ /** @public */
661
814
  export async function observeMergeRequest(
662
815
  client: GitLabClientLike,
663
816
  projectId: number,
@@ -0,0 +1,226 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ numberArg,
4
+ type ProcessProjectRepoLike,
5
+ projectParameters,
6
+ type ServerExtensionAPI,
7
+ stringArg,
8
+ } from "@leitwerk-dev/process-sdk";
9
+ import type { GitLabIntegration } from "./capability.js";
10
+ import {
11
+ ensureGitLabSeenReaction,
12
+ resolveGitLabBinding,
13
+ resolveGitLabRepositoryBinding,
14
+ } from "./tools.js";
15
+
16
+ export function registerGitLabDeliveryTools(
17
+ api: ServerExtensionAPI,
18
+ integration: GitLabIntegration,
19
+ projects: ProcessProjectRepoLike,
20
+ ) {
21
+ api.tool<Record<string, unknown>>({
22
+ name: "gitlab_ensure_merge_request",
23
+ description: "Create or reconcile and pin the process merge request",
24
+ parameters: projectParameters({ title: { type: "string" }, body: { type: "string" } }, [
25
+ "title",
26
+ "body",
27
+ ]),
28
+ async execute(ctx, args) {
29
+ const binding = resolveGitLabRepositoryBinding(ctx);
30
+ const client = integration.client(binding.profile);
31
+ const project = projects.getByInstanceAndKey(ctx.process.id, ctx.project?.key ?? "");
32
+ if (!project?.workBranch || project.workBranch === project.baseBranch)
33
+ throw new Error("A process feature branch is required");
34
+ const workBranch = project.workBranch;
35
+ const identity = {
36
+ writeType: "gitlab.ensure_mr",
37
+ dedupKey: `${binding.projectId}:${project.key}:${workBranch}:${project.baseBranch}`,
38
+ };
39
+ const marker = `<!-- leitwerk:gitlab:merge-request:${ctx.process.id}:${project.key} -->`;
40
+ const find = async () =>
41
+ (
42
+ await client.listBranchMergeRequests(
43
+ binding.projectId,
44
+ workBranch,
45
+ project.baseBranch,
46
+ ctx.signal,
47
+ )
48
+ ).find(
49
+ (mr) =>
50
+ mr.source_project_id === binding.projectId &&
51
+ mr.target_project_id === binding.projectId &&
52
+ mr.source_branch === project.workBranch &&
53
+ mr.target_branch === project.baseBranch &&
54
+ mr.description?.includes(marker),
55
+ );
56
+ const request = await ctx.externalWrites.ensure(identity, {
57
+ reconcile: async () => (await find()) ?? null,
58
+ execute: () =>
59
+ client.createMergeRequest(
60
+ binding.projectId,
61
+ {
62
+ title: stringArg(args, "title"),
63
+ description: `${stringArg(args, "body")}\n\n${marker}`,
64
+ source_branch: workBranch,
65
+ target_branch: project.baseBranch,
66
+ },
67
+ ctx.signal,
68
+ ),
69
+ toMetadata: (mr) => ({ iid: mr.iid, url: mr.web_url }),
70
+ });
71
+ const latest = projects.getByInstanceAndKey(ctx.process.id, project.key);
72
+ if (
73
+ !latest ||
74
+ latest.workBranch !== project.workBranch ||
75
+ latest.baseBranch !== project.baseBranch
76
+ )
77
+ throw new Error("Process repository binding changed during publication");
78
+ const metadata = latest.metadata ?? {};
79
+ const previous = metadata.gitlab as { iid?: number };
80
+ if (previous.iid && previous.iid !== request.iid)
81
+ throw new Error("Process is already bound to another merge request");
82
+ projects.update(latest.id, {
83
+ metadata: { ...metadata, gitlab: { ...previous, ...binding, iid: request.iid } },
84
+ externalId: String(request.iid),
85
+ externalUrl: request.web_url,
86
+ });
87
+ return request;
88
+ },
89
+ });
90
+ api.tool({
91
+ name: "gitlab_list_merge_request_feedback",
92
+ description: "Read human discussion feedback on the bound merge request",
93
+ parameters: projectParameters(),
94
+ async execute(ctx) {
95
+ const b = resolveGitLabBinding(ctx);
96
+ return integration.client(b.profile).listMergeRequestFeedback(b.projectId, b.iid, ctx.signal);
97
+ },
98
+ });
99
+ api.tool<Record<string, unknown>>({
100
+ name: "gitlab_acknowledge_feedback",
101
+ description: "Reconcile the bot's seen reaction on bound merge request feedback",
102
+ parameters: projectParameters({ noteId: { type: "integer" } }, ["noteId"]),
103
+ async execute(ctx, args) {
104
+ const b = resolveGitLabBinding(ctx);
105
+ const client = integration.client(b.profile);
106
+ const noteId = numberArg(args, "noteId");
107
+ if (
108
+ !(await client.listMergeRequestFeedback(b.projectId, b.iid, ctx.signal)).some(
109
+ (n) => n.id === noteId,
110
+ )
111
+ )
112
+ throw new Error("Note is not actionable feedback on the bound merge request");
113
+ await ensureGitLabSeenReaction({
114
+ client,
115
+ writes: ctx.externalWrites,
116
+ instanceId: ctx.process.id,
117
+ projectId: b.projectId,
118
+ iid: b.iid,
119
+ noteId,
120
+ signal: ctx.signal,
121
+ });
122
+ return { ok: true };
123
+ },
124
+ });
125
+ for (const name of [
126
+ "gitlab_get_issue",
127
+ "gitlab_add_issue_comment",
128
+ "gitlab_finalize_source_issue",
129
+ ] as const) {
130
+ api.tool<Record<string, unknown>>({
131
+ name,
132
+ description: "Read or reconcile the process source issue",
133
+ parameters: projectParameters(
134
+ {
135
+ issueNumber: { type: "integer" },
136
+ body: { type: "string" },
137
+ writeKey: { type: "string" },
138
+ merged: { type: "boolean" },
139
+ triggerLabel: { type: "string" },
140
+ doneLabel: { type: "string" },
141
+ },
142
+ ["issueNumber"],
143
+ ),
144
+ async execute(ctx, args) {
145
+ const b = resolveGitLabRepositoryBinding(ctx);
146
+ const client = integration.client(b.profile);
147
+ const iid = numberArg(args, "issueNumber");
148
+ const bound = (ctx.project?.metadata?.gitlab as { issueIid?: number })?.issueIid;
149
+ if (bound !== iid) throw new Error("Issue does not match the process source issue");
150
+ if (name === "gitlab_get_issue") return client.getIssue(b.projectId, iid, ctx.signal);
151
+ const key = stringArg(args, "writeKey");
152
+ const digest = createHash("sha256")
153
+ .update(JSON.stringify([client.baseUrl, b.projectId, iid, ctx.process.id, key]))
154
+ .digest("hex");
155
+ if (name === "gitlab_add_issue_comment") {
156
+ const marker = `<!-- leitwerk:gitlab:issue:${digest} -->`;
157
+ const note = await ctx.externalWrites.ensure(
158
+ { writeType: name, dedupKey: digest },
159
+ {
160
+ reconcile: async () =>
161
+ (await client.listIssueNotes(b.projectId, iid, ctx.signal)).find((n) =>
162
+ n.body.includes(marker),
163
+ ) ?? null,
164
+ execute: () =>
165
+ client.addIssueNote(
166
+ b.projectId,
167
+ iid,
168
+ `${stringArg(args, "body")}\n\n${marker}`,
169
+ ctx.signal,
170
+ ),
171
+ toMetadata: (note) => ({ noteId: note.id }),
172
+ },
173
+ );
174
+ return { noteId: note.id };
175
+ }
176
+ const merged = args.merged === true;
177
+ const trigger = stringArg(args, "triggerLabel");
178
+ const done = stringArg(args, "doneLabel");
179
+ if (merged) {
180
+ await ctx.externalWrites.ensure(
181
+ {
182
+ writeType: "gitlab.ensure_label",
183
+ dedupKey: JSON.stringify([client.baseUrl, b.projectId, done]),
184
+ },
185
+ {
186
+ reconcile: async () =>
187
+ (await client.listLabels(b.projectId, ctx.signal)).find((l) => l.name === done) ??
188
+ null,
189
+ execute: () => client.createLabel(b.projectId, done, ctx.signal),
190
+ toMetadata: (label) => ({ name: label.name }),
191
+ },
192
+ );
193
+ }
194
+ await ctx.externalWrites.ensure(
195
+ { writeType: name, dedupKey: digest },
196
+ {
197
+ reconcile: async () => {
198
+ const fresh = await client.getIssue(b.projectId, iid, ctx.signal);
199
+ return !fresh.labels.includes(trigger) &&
200
+ (!merged || (fresh.state === "closed" && fresh.labels.includes(done)))
201
+ ? fresh
202
+ : null;
203
+ },
204
+ execute: async () => {
205
+ const issue = await client.getIssue(b.projectId, iid, ctx.signal);
206
+ const labels = [
207
+ ...new Set([
208
+ ...issue.labels.filter((l) => l !== trigger),
209
+ ...(merged ? [done] : []),
210
+ ]),
211
+ ];
212
+ return client.updateIssue(
213
+ b.projectId,
214
+ iid,
215
+ { labels: labels.join(","), ...(merged ? { state_event: "close" as const } : {}) },
216
+ ctx.signal,
217
+ );
218
+ },
219
+ toMetadata: () => ({ issueIid: iid, merged }),
220
+ },
221
+ );
222
+ return { issueIid: iid, merged };
223
+ },
224
+ });
225
+ }
226
+ }