@leitwerk-dev/gitlab 0.2.1 → 0.3.1

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,7 @@ export class GitLabClient {
324
345
  /** @internal */
325
346
  constructor(
326
347
  profile: GitLabProfile,
348
+ /** @public */
327
349
  options: {
328
350
  /** @internal */
329
351
  fetch?: typeof fetch;
@@ -340,12 +362,17 @@ export class GitLabClient {
340
362
  this.#fetch = options.fetch ?? fetch;
341
363
  this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
342
364
  }
343
- private async response(path: string, signal?: AbortSignal, body?: unknown): Promise<Response> {
365
+ private async response(
366
+ path: string,
367
+ signal?: AbortSignal,
368
+ body?: unknown,
369
+ method?: string,
370
+ ): Promise<Response> {
344
371
  for (let attempt = 0; ; attempt++) {
345
372
  let response: Response;
346
373
  try {
347
374
  response = await this.#fetch(`${this.baseUrl}/api/v4${path}`, {
348
- method: body === undefined ? "GET" : "POST",
375
+ method: method ?? (body === undefined ? "GET" : "POST"),
349
376
  redirect: "error",
350
377
  headers: {
351
378
  "PRIVATE-TOKEN": this.#profile.token,
@@ -373,8 +400,13 @@ export class GitLabClient {
373
400
  await this.#sleep(Math.min(30_000, seconds > 0 ? seconds * 1_000 : 1_000 * 2 ** attempt));
374
401
  }
375
402
  }
376
- private async request<T>(path: string, signal?: AbortSignal, body?: unknown): Promise<T> {
377
- return this.json<T>(await this.response(path, signal, body));
403
+ private async request<T>(
404
+ path: string,
405
+ signal?: AbortSignal,
406
+ body?: unknown,
407
+ method?: string,
408
+ ): Promise<T> {
409
+ return this.json<T>(await this.response(path, signal, body, method));
378
410
  }
379
411
  private async json<T>(response: Response): Promise<T> {
380
412
  try {
@@ -403,6 +435,109 @@ export class GitLabClient {
403
435
  }
404
436
  throw new Error("GitLab pagination limit exceeded; discovery incomplete");
405
437
  }
438
+ /** @public */
439
+ listIssues(id: number, signal?: AbortSignal): Promise<GitLabIssue[]> {
440
+ return this.pages(`${projectPath(id)}/issues?state=opened&scope=all`, signal);
441
+ }
442
+ /** @public */
443
+ getIssue(id: number, iid: number, signal?: AbortSignal): Promise<GitLabIssue> {
444
+ return this.request(`${projectPath(id)}/issues/${iid}`, signal);
445
+ }
446
+ /** @public */
447
+ updateIssue(
448
+ id: number,
449
+ iid: number,
450
+ /** @public */
451
+ patch: {
452
+ /** @public */
453
+ labels?: string;
454
+ /** @public */
455
+ state_event?: "close";
456
+ },
457
+ signal?: AbortSignal,
458
+ ): Promise<GitLabIssue> {
459
+ return this.request(`${projectPath(id)}/issues/${iid}`, signal, patch, "PUT");
460
+ }
461
+ /** @public */
462
+ listIssueNotes(id: number, iid: number, signal?: AbortSignal): Promise<GitLabNote[]> {
463
+ return this.pages(`${projectPath(id)}/issues/${iid}/notes`, signal);
464
+ }
465
+ /** @public */
466
+ addIssueNote(id: number, iid: number, body: string, signal?: AbortSignal): Promise<GitLabNote> {
467
+ return this.request(`${projectPath(id)}/issues/${iid}/notes`, signal, { body });
468
+ }
469
+ /** @public */
470
+ listLabels(
471
+ id: number,
472
+ signal?: AbortSignal,
473
+ ): Promise<
474
+ Array<{
475
+ /** @public */ name: string;
476
+ }>
477
+ > {
478
+ return this.pages(`${projectPath(id)}/labels`, signal);
479
+ }
480
+ /** @public */
481
+ createLabel(
482
+ id: number,
483
+ name: string,
484
+ signal?: AbortSignal,
485
+ ): Promise<{
486
+ /** @public */ name: string;
487
+ }> {
488
+ return this.request(`${projectPath(id)}/labels`, signal, { name, color: "#2da44e" });
489
+ }
490
+ /** @public */
491
+ listBranchMergeRequests(
492
+ id: number,
493
+ source: string,
494
+ target: string,
495
+ signal?: AbortSignal,
496
+ ): Promise<GitLabMergeRequest[]> {
497
+ return this.pages(
498
+ `${projectPath(id)}/merge_requests?state=all&source_branch=${encodeURIComponent(source)}&target_branch=${encodeURIComponent(target)}`,
499
+ signal,
500
+ );
501
+ }
502
+ /** @public */
503
+ createMergeRequest(
504
+ id: number,
505
+ /** @public */
506
+ input: {
507
+ /** @public */
508
+ title: string;
509
+ /** @public */
510
+ description: string;
511
+ /** @public */
512
+ source_branch: string;
513
+ /** @public */
514
+ target_branch: string;
515
+ },
516
+ signal?: AbortSignal,
517
+ ): Promise<GitLabMergeRequest> {
518
+ return this.request(`${projectPath(id)}/merge_requests`, signal, {
519
+ ...input,
520
+ remove_source_branch: false,
521
+ });
522
+ }
523
+ /** @public */
524
+ async preflightRepository(
525
+ projectId: number,
526
+ baseBranch: string,
527
+ workBranch: string,
528
+ signal?: AbortSignal,
529
+ ): Promise<void> {
530
+ const project = await this.getProject(projectId, signal);
531
+ await preflightGitLabRepository({
532
+ url: project.http_url_to_repo,
533
+ origin: this.baseUrl,
534
+ token: this.#profile.token,
535
+ baseBranch,
536
+ workBranch,
537
+ signal,
538
+ });
539
+ }
540
+
406
541
  /** @public */
407
542
  getProject(id: number | string, signal?: AbortSignal): Promise<GitLabProject> {
408
543
  return this.request(projectPath(id), signal);
@@ -538,10 +673,10 @@ export class GitLabClient {
538
673
  iid: number,
539
674
  signal?: AbortSignal,
540
675
  ): Promise<GitLabFeedback[]> {
541
- const [discussions, identity] = await Promise.all([
542
- this.pages<GitLabDiscussion>(`${mrPath(id, iid)}/discussions`, signal),
543
- this.resolveGitIdentity(signal),
544
- ]);
676
+ const discussions = await this.pages<GitLabDiscussion>(
677
+ `${mrPath(id, iid)}/discussions`,
678
+ signal,
679
+ );
545
680
  const feedback: GitLabFeedback[] = [];
546
681
  for (const discussion of discussions) {
547
682
  for (const note of discussion.notes) {
@@ -549,7 +684,7 @@ export class GitLabClient {
549
684
  note.system ||
550
685
  note.resolved ||
551
686
  note.author.bot ||
552
- note.author.username === identity.username ||
687
+ /<!-- leitwerk:gitlab:[a-f0-9]{64} -->/.test(note.body) ||
553
688
  !note.body.trim() ||
554
689
  !Number.isFinite(Date.parse(note.created_at))
555
690
  )
@@ -598,10 +733,11 @@ export class GitLabClient {
598
733
  job: number,
599
734
  maxBytes = 65_536,
600
735
  signal?: AbortSignal,
736
+ /** @public */
601
737
  ): Promise<{
602
- /** @internal */
738
+ /** @public */
603
739
  text: string;
604
- /** @internal */
740
+ /** @public */
605
741
  truncated: boolean;
606
742
  }> {
607
743
  const limit = Math.min(262_144, Math.max(1, Math.floor(maxBytes) || 65_536));
@@ -632,6 +768,16 @@ export class GitLabClient {
632
768
  /** @public */
633
769
  export type GitLabClientLike = Pick<
634
770
  GitLabClient,
771
+ | "listIssues"
772
+ | "getIssue"
773
+ | "updateIssue"
774
+ | "listIssueNotes"
775
+ | "addIssueNote"
776
+ | "listLabels"
777
+ | "createLabel"
778
+ | "listBranchMergeRequests"
779
+ | "createMergeRequest"
780
+ | "preflightRepository"
635
781
  | "addNote"
636
782
  | "addNoteReaction"
637
783
  | "baseUrl"
@@ -657,7 +803,8 @@ export type GitLabClientLike = Pick<
657
803
  | "resolveGitIdentity"
658
804
  >;
659
805
 
660
- /** A pending current pipeline supersedes every older result. Synthetic merges must contain this source head. @public */
806
+ /** A pending current pipeline supersedes every older result. Synthetic merges must contain this source head. */
807
+ /** @public */
661
808
  export async function observeMergeRequest(
662
809
  client: GitLabClientLike,
663
810
  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
+ }