@leitwerk-dev/gitlab 0.0.0-bootstrap.0 → 0.2.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 ADDED
@@ -0,0 +1,702 @@
1
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
2
+ import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
3
+
4
+ /** @internal */
5
+ export interface GitLabProfile {
6
+ /** @internal */
7
+ baseUrl: string;
8
+ /** @internal */
9
+ token: string;
10
+ /** @internal */
11
+ gitIdentity?: {
12
+ /** @internal */
13
+ name: string;
14
+ /** @internal */
15
+ email: string;
16
+ };
17
+ }
18
+ /** @public */
19
+ export interface GitLabProject {
20
+ /** @public */
21
+ id: number;
22
+ /** @public */
23
+ path_with_namespace: string;
24
+ /** @public */
25
+ http_url_to_repo: string;
26
+ /** @public */
27
+ web_url: string;
28
+ /** @internal */
29
+ default_branch: string;
30
+ /** @public */
31
+ archived?: boolean;
32
+ /** @internal */
33
+ permissions?: {
34
+ /** @internal */
35
+ project_access?: {
36
+ /** @internal */
37
+ access_level: number;
38
+ } | null;
39
+ /** @internal */
40
+ group_access?: {
41
+ /** @internal */
42
+ access_level: number;
43
+ } | null;
44
+ };
45
+ }
46
+ /** @internal */
47
+ export interface GitLabGroup {
48
+ /** @internal */
49
+ id: number;
50
+ /** @internal */
51
+ full_path: string;
52
+ }
53
+ /** @public */
54
+ export interface GitLabMergeRequest {
55
+ /** @public */
56
+ iid: number;
57
+ /** @public */
58
+ project_id: number;
59
+ /** @public */
60
+ source_project_id: number;
61
+ /** @public */
62
+ target_project_id: number;
63
+ /** @public */
64
+ title: string;
65
+ /** @public */
66
+ description: string | null;
67
+ /** @public */
68
+ state: string;
69
+ /** @public */
70
+ labels: string[];
71
+ /** @public */
72
+ sha: string;
73
+ /** @public */
74
+ source_branch: string;
75
+ /** @public */
76
+ target_branch: string;
77
+ /** @public */
78
+ web_url: string;
79
+ /** @public */
80
+ has_conflicts?: boolean;
81
+ /** @public */
82
+ merge_status?: string;
83
+ /** @public */
84
+ detailed_merge_status?: string;
85
+ /** @internal */
86
+ merge_commit_sha?: string | null;
87
+ /** @internal */
88
+ diff_refs?: {
89
+ /** @internal */
90
+ base_sha: string;
91
+ /** @internal */
92
+ head_sha: string;
93
+ /** @internal */
94
+ start_sha: string;
95
+ };
96
+ }
97
+ /** @public */
98
+ export interface GitLabCommit {
99
+ /** @public */
100
+ id: string;
101
+ /** @internal */
102
+ parent_ids: string[];
103
+ /** @internal */
104
+ message: string;
105
+ /** @internal */
106
+ web_url?: string;
107
+ }
108
+ /** @public */
109
+ export interface GitLabBranch {
110
+ /** @internal */
111
+ name: string;
112
+ /** @public */
113
+ can_push: boolean;
114
+ /** @internal */
115
+ protected: boolean;
116
+ /** @public */
117
+ commit: GitLabCommit;
118
+ }
119
+ /** @public */
120
+ export interface GitLabPipeline {
121
+ /** @public */
122
+ id: number;
123
+ /** @public */
124
+ project_id: number;
125
+ /** @public */
126
+ sha: string;
127
+ /** @public */
128
+ ref: string;
129
+ /** @public */
130
+ status: string;
131
+ /** @internal */
132
+ source?: string;
133
+ /** @public */
134
+ web_url: string;
135
+ }
136
+ /** @public */
137
+ export interface GitLabJob {
138
+ /** @public */
139
+ id: number;
140
+ /** @public */
141
+ name: string;
142
+ /** @internal */
143
+ status: string;
144
+ /** @public */
145
+ web_url: string;
146
+ /** @public */
147
+ failure_reason?: string;
148
+ }
149
+ /** @public */
150
+ export interface GitLabDiff {
151
+ /** @public */
152
+ old_path: string;
153
+ /** @public */
154
+ new_path: string;
155
+ /** @public */
156
+ diff: string;
157
+ /** @public */
158
+ new_file: boolean;
159
+ /** @public */
160
+ deleted_file: boolean;
161
+ /** @public */
162
+ renamed_file: boolean;
163
+ }
164
+ /** @public */
165
+ export interface GitLabNote {
166
+ /** @internal */
167
+ id: number;
168
+ /** @public */
169
+ body: string;
170
+ }
171
+ /** @public */
172
+ export interface GitLabNoteReaction {
173
+ /** @internal */
174
+ id: number;
175
+ /** @internal */
176
+ name: string;
177
+ /** @internal */
178
+ user: {
179
+ /** @internal */
180
+ username: string;
181
+ };
182
+ }
183
+ /** @public */
184
+ export interface GitLabFeedback {
185
+ /** @public */
186
+ id: number;
187
+ /** @public */
188
+ discussionId: string;
189
+ /** @public */
190
+ body: string;
191
+ /** @public */
192
+ author: string;
193
+ /** @public */
194
+ createdAt: string;
195
+ /** @public */
196
+ path?: string;
197
+ /** @public */
198
+ line?: number;
199
+ }
200
+ /** @internal */
201
+ export interface GitLabDiscussion {
202
+ /** @internal */
203
+ id: string;
204
+ /** @internal */
205
+ notes: (GitLabNote & {
206
+ /** @internal */
207
+ system: boolean;
208
+ /** @internal */
209
+ created_at: string;
210
+ /** @internal */
211
+ author: {
212
+ /** @internal */
213
+ username: string;
214
+ /** @internal */
215
+ bot?: boolean;
216
+ };
217
+ /** @internal */
218
+ resolved?: boolean;
219
+ /** @internal */
220
+ position?: {
221
+ /** @internal */
222
+ new_path?: string;
223
+ /** @internal */
224
+ old_path?: string;
225
+ /** @internal */
226
+ new_line?: number;
227
+ /** @internal */
228
+ old_line?: number;
229
+ };
230
+ })[];
231
+ }
232
+ /** @public */
233
+ export interface GitLabIdentity {
234
+ /** @public */
235
+ name: string;
236
+ /** @public */
237
+ email: string;
238
+ /** @public */
239
+ username: string;
240
+ }
241
+ /** @public */
242
+ export interface GitLabObservation {
243
+ /** @public */
244
+ mr: GitLabMergeRequest;
245
+ /** @public */
246
+ pipeline: GitLabPipeline | null;
247
+ /** @public Current target branch tip, not the diff's historical merge base. */
248
+ targetHead?: string;
249
+ }
250
+
251
+ /** @public */
252
+ export function gitLabMergeabilityPending(mr: GitLabMergeRequest): boolean {
253
+ return ["checking", "unchecked", "preparing"].includes(
254
+ mr.detailed_merge_status ?? mr.merge_status ?? "",
255
+ );
256
+ }
257
+
258
+ /** @public Only actionable Git conflicts/rebase requirements, not approvals or CI gates. */
259
+ export function gitLabMergeRepairReason(mr: GitLabMergeRequest): "conflict" | "rebase" | null {
260
+ if (gitLabMergeabilityPending(mr)) return null;
261
+ if (mr.has_conflicts || mr.detailed_merge_status === "conflict") return "conflict";
262
+ return mr.detailed_merge_status === "need_rebase" ? "rebase" : null;
263
+ }
264
+
265
+ /** @internal */
266
+ export class GitLabError extends Error {
267
+ /** @internal */
268
+ constructor(
269
+ /** @internal */
270
+ readonly status: number,
271
+ /** @internal */
272
+ readonly retryable: boolean,
273
+ ) {
274
+ super(
275
+ `GitLab request failed (${status || "network unavailable"})${retryable ? "; retryable" : "; check profile and project access"}`,
276
+ );
277
+ }
278
+ }
279
+ /** @internal */
280
+ export function parseGitLabProfiles(raw: unknown): Map<string, GitLabProfile> {
281
+ const profiles = new Map<string, GitLabProfile>();
282
+ for (const [name, value] of Object.entries(
283
+ asUnknownRecord(asUnknownRecord(raw)?.profiles) ?? {},
284
+ )) {
285
+ const item = asUnknownRecord(value) ?? {};
286
+ const baseUrl = typeof item.base_url === "string" ? item.base_url.replace(/\/+$/, "") : "";
287
+ const url = repositoryHttpsUrl(`${baseUrl}/` === "/" ? "" : `${baseUrl}/repository`);
288
+ if (url.origin !== baseUrl)
289
+ throw new Error(`GitLab profile '${name}' requires an HTTPS origin base_url`);
290
+ const configuredToken = typeof item.token === "string" ? item.token : "";
291
+ const token = configuredToken.startsWith("env:")
292
+ ? (process.env[configuredToken.slice(4)] ?? "")
293
+ : configuredToken;
294
+ if (!token || /[\r\n\0]/.test(token))
295
+ throw new Error(`GitLab profile '${name}' requires a token`);
296
+ const identity = asUnknownRecord(item.git_identity);
297
+ if (
298
+ identity &&
299
+ [identity.name, identity.email].some(
300
+ (v) => typeof v !== "string" || !v.trim() || /[\r\n<>]/.test(v),
301
+ )
302
+ )
303
+ throw new Error(`GitLab profile '${name}' requires a valid git_identity name and email`);
304
+ profiles.set(name, {
305
+ baseUrl,
306
+ token,
307
+ ...(identity
308
+ ? { gitIdentity: { name: String(identity.name), email: String(identity.email) } }
309
+ : {}),
310
+ });
311
+ }
312
+ return profiles;
313
+ }
314
+ const projectPath = (id: number | string) => `/projects/${encodeURIComponent(id)}`;
315
+ const mrPath = (id: number, iid: number) => `${projectPath(id)}/merge_requests/${iid}`;
316
+
317
+ /** GitLab v4 API. Errors deliberately omit response bodies, headers and tokens. @public */
318
+ export class GitLabClient {
319
+ /** @public */
320
+ readonly baseUrl: string;
321
+ readonly #profile: GitLabProfile;
322
+ readonly #fetch: typeof fetch;
323
+ readonly #sleep: (ms: number) => Promise<unknown>;
324
+ /** @internal */
325
+ constructor(
326
+ profile: GitLabProfile,
327
+ options: {
328
+ /** @internal */
329
+ fetch?: typeof fetch;
330
+ /** @internal */
331
+ sleep?: (ms: number) => Promise<unknown>;
332
+ } = {},
333
+ ) {
334
+ if (repositoryHttpsUrl(`${profile.baseUrl}/repository`).origin !== profile.baseUrl)
335
+ throw new Error("GitLab requires an HTTPS origin baseUrl");
336
+ if (!profile.token || /[\r\n\0]/.test(profile.token))
337
+ throw new Error("GitLab requires a valid token");
338
+ this.#profile = profile;
339
+ this.baseUrl = profile.baseUrl;
340
+ this.#fetch = options.fetch ?? fetch;
341
+ this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
342
+ }
343
+ private async response(path: string, signal?: AbortSignal, body?: unknown): Promise<Response> {
344
+ for (let attempt = 0; ; attempt++) {
345
+ let response: Response;
346
+ try {
347
+ response = await this.#fetch(`${this.baseUrl}/api/v4${path}`, {
348
+ method: body === undefined ? "GET" : "POST",
349
+ redirect: "error",
350
+ headers: {
351
+ "PRIVATE-TOKEN": this.#profile.token,
352
+ Accept: "application/json",
353
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
354
+ },
355
+ signal: signal
356
+ ? AbortSignal.any([signal, AbortSignal.timeout(30_000)])
357
+ : AbortSignal.timeout(30_000),
358
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
359
+ });
360
+ } catch {
361
+ if (signal?.aborted) throw new GitLabError(0, true);
362
+ if (body !== undefined || attempt >= 2) throw new GitLabError(0, true);
363
+ await this.#sleep(1_000 * 2 ** attempt);
364
+ continue;
365
+ }
366
+ if (response.ok) return response;
367
+ const retryable =
368
+ response.status === 429 || response.status >= 500 || response.status === 408;
369
+ await response.body?.cancel();
370
+ if (!retryable || body !== undefined || attempt >= 2)
371
+ throw new GitLabError(response.status, retryable);
372
+ const seconds = Number(response.headers.get("retry-after"));
373
+ await this.#sleep(Math.min(30_000, seconds > 0 ? seconds * 1_000 : 1_000 * 2 ** attempt));
374
+ }
375
+ }
376
+ private async request<T>(path: string, signal?: AbortSignal, body?: unknown): Promise<T> {
377
+ return this.json<T>(await this.response(path, signal, body));
378
+ }
379
+ private async json<T>(response: Response): Promise<T> {
380
+ try {
381
+ return (await response.json()) as T;
382
+ } catch {
383
+ throw new GitLabError(502, true);
384
+ }
385
+ }
386
+ private async pages<T>(path: string, signal?: AbortSignal): Promise<T[]> {
387
+ const rows: T[] = [];
388
+ let page = 1;
389
+ for (let n = 0; n < 10_000; n++) {
390
+ const response = await this.response(
391
+ `${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`,
392
+ signal,
393
+ );
394
+ const batch = await this.json<T[]>(response);
395
+ if (!Array.isArray(batch)) throw new Error("Invalid GitLab list response");
396
+ rows.push(...batch);
397
+ const next = response.headers.get("x-next-page");
398
+ if (next === "" || (next === null && batch.length < 100)) return rows;
399
+ const nextPage = next === null ? page + 1 : Number(next);
400
+ if (!Number.isInteger(nextPage) || nextPage <= page)
401
+ throw new Error("Invalid GitLab pagination");
402
+ page = nextPage;
403
+ }
404
+ throw new Error("GitLab pagination limit exceeded; discovery incomplete");
405
+ }
406
+ /** @public */
407
+ getProject(id: number | string, signal?: AbortSignal): Promise<GitLabProject> {
408
+ return this.request(projectPath(id), signal);
409
+ }
410
+ /** @internal */
411
+ listProjects(signal?: AbortSignal): Promise<GitLabProject[]> {
412
+ return this.pages("/projects?archived=false", signal);
413
+ }
414
+ /** @internal */
415
+ getGroup(id: number | string, signal?: AbortSignal): Promise<GitLabGroup> {
416
+ return this.request(`/groups/${encodeURIComponent(id)}`, signal);
417
+ }
418
+ /** @internal */
419
+ listGroupProjects(id: number | string, signal?: AbortSignal): Promise<GitLabProject[]> {
420
+ return this.pages(
421
+ `/groups/${encodeURIComponent(id)}/projects?include_subgroups=true&with_shared=false&archived=false`,
422
+ signal,
423
+ );
424
+ }
425
+ /** @public */
426
+ listMergeRequests(
427
+ id: number,
428
+ label: string,
429
+ signal?: AbortSignal,
430
+ ): Promise<GitLabMergeRequest[]> {
431
+ return this.pages(
432
+ `${projectPath(id)}/merge_requests?state=opened&labels=${encodeURIComponent(label)}`,
433
+ signal,
434
+ );
435
+ }
436
+ /** @internal */
437
+ getMergeRequest(id: number, iid: number, signal?: AbortSignal): Promise<GitLabMergeRequest> {
438
+ return this.request(mrPath(id, iid), signal);
439
+ }
440
+ /** @public */
441
+ getChanges(id: number, iid: number, signal?: AbortSignal): Promise<GitLabDiff[]> {
442
+ return this.pages(`${mrPath(id, iid)}/diffs`, signal);
443
+ }
444
+ /** @public */
445
+ getBranch(id: number, branch: string, signal?: AbortSignal): Promise<GitLabBranch> {
446
+ return this.request(
447
+ `${projectPath(id)}/repository/branches/${encodeURIComponent(branch)}`,
448
+ signal,
449
+ );
450
+ }
451
+ /** @internal */
452
+ getCommit(id: number, sha: string, signal?: AbortSignal): Promise<GitLabCommit> {
453
+ return this.request(`${projectPath(id)}/repository/commits/${encodeURIComponent(sha)}`, signal);
454
+ }
455
+ /** @internal */
456
+ listMergeRequestPipelines(
457
+ id: number,
458
+ iid: number,
459
+ signal?: AbortSignal,
460
+ ): Promise<GitLabPipeline[]> {
461
+ return this.pages(`${mrPath(id, iid)}/pipelines`, signal);
462
+ }
463
+ /** @internal */
464
+ listBranchPipelines(
465
+ id: number,
466
+ branch: string,
467
+ sha: string,
468
+ signal?: AbortSignal,
469
+ ): Promise<GitLabPipeline[]> {
470
+ return this.pages(
471
+ `${projectPath(id)}/pipelines?ref=${encodeURIComponent(branch)}&sha=${encodeURIComponent(sha)}&source=push`,
472
+ signal,
473
+ );
474
+ }
475
+ /** @internal */
476
+ getPipeline(id: number, pipeline: number, signal?: AbortSignal): Promise<GitLabPipeline> {
477
+ return this.request(`${projectPath(id)}/pipelines/${pipeline}`, signal);
478
+ }
479
+ /** @public */
480
+ listFailedJobs(id: number, pipeline: number, signal?: AbortSignal): Promise<GitLabJob[]> {
481
+ return this.pages(
482
+ `${projectPath(id)}/pipelines/${pipeline}/jobs?scope[]=failed&include_retried=false`,
483
+ signal,
484
+ );
485
+ }
486
+ /** @internal */
487
+ listNotes(id: number, iid: number, signal?: AbortSignal): Promise<GitLabNote[]> {
488
+ return this.pages(`${mrPath(id, iid)}/notes`, signal);
489
+ }
490
+ /** @internal */
491
+ getDiscussion(
492
+ id: number,
493
+ iid: number,
494
+ discussionId: string,
495
+ signal?: AbortSignal,
496
+ ): Promise<GitLabDiscussion> {
497
+ return this.request(
498
+ `${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}`,
499
+ signal,
500
+ );
501
+ }
502
+ /** @internal */
503
+ replyToDiscussion(
504
+ id: number,
505
+ iid: number,
506
+ discussionId: string,
507
+ body: string,
508
+ signal?: AbortSignal,
509
+ ): Promise<GitLabNote> {
510
+ return this.request(
511
+ `${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}/notes`,
512
+ signal,
513
+ { body },
514
+ );
515
+ }
516
+ /** @internal */
517
+ listNoteReactions(
518
+ id: number,
519
+ iid: number,
520
+ noteId: number,
521
+ signal?: AbortSignal,
522
+ ): Promise<GitLabNoteReaction[]> {
523
+ return this.pages(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal);
524
+ }
525
+ /** @internal */
526
+ addNoteReaction(
527
+ id: number,
528
+ iid: number,
529
+ noteId: number,
530
+ name: string,
531
+ signal?: AbortSignal,
532
+ ): Promise<GitLabNoteReaction> {
533
+ return this.request(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal, { name });
534
+ }
535
+ /** @public */
536
+ async listMergeRequestFeedback(
537
+ id: number,
538
+ iid: number,
539
+ signal?: AbortSignal,
540
+ ): Promise<GitLabFeedback[]> {
541
+ const [discussions, identity] = await Promise.all([
542
+ this.pages<GitLabDiscussion>(`${mrPath(id, iid)}/discussions`, signal),
543
+ this.resolveGitIdentity(signal),
544
+ ]);
545
+ const feedback: GitLabFeedback[] = [];
546
+ for (const discussion of discussions) {
547
+ for (const note of discussion.notes) {
548
+ if (
549
+ note.system ||
550
+ note.resolved ||
551
+ note.author.bot ||
552
+ note.author.username === identity.username ||
553
+ !note.body.trim() ||
554
+ !Number.isFinite(Date.parse(note.created_at))
555
+ )
556
+ continue;
557
+ const position = note.position ?? discussion.notes[0]?.position;
558
+ feedback.push({
559
+ id: note.id,
560
+ discussionId: discussion.id,
561
+ body: note.body,
562
+ author: note.author.username,
563
+ createdAt: note.created_at,
564
+ ...(position
565
+ ? {
566
+ path: position.new_path ?? position.old_path,
567
+ line: position.new_line ?? position.old_line,
568
+ }
569
+ : {}),
570
+ });
571
+ }
572
+ }
573
+ return feedback.sort((a, b) => a.id - b.id);
574
+ }
575
+ /** @internal */
576
+ addNote(id: number, iid: number, body: string, signal?: AbortSignal): Promise<GitLabNote> {
577
+ return this.request(`${mrPath(id, iid)}/notes`, signal, { body });
578
+ }
579
+ /** @public */
580
+ async resolveGitIdentity(signal?: AbortSignal): Promise<GitLabIdentity> {
581
+ const user = await this.request<{
582
+ name?: string;
583
+ username?: string;
584
+ email?: string;
585
+ commit_email?: string;
586
+ }>("/user", signal);
587
+ const name = this.#profile.gitIdentity?.name ?? user.name;
588
+ const email = this.#profile.gitIdentity?.email ?? user.commit_email ?? user.email;
589
+ if (!user.username || !name?.trim() || !email?.includes("@") || /[\r\n<>]/.test(name + email))
590
+ throw new Error(
591
+ "GitLab bot Git identity is unavailable; configure git_identity on the profile",
592
+ );
593
+ return { name, email, username: user.username };
594
+ }
595
+ /** @public */
596
+ async getJobTrace(
597
+ id: number,
598
+ job: number,
599
+ maxBytes = 65_536,
600
+ signal?: AbortSignal,
601
+ ): Promise<{
602
+ /** @internal */
603
+ text: string;
604
+ /** @internal */
605
+ truncated: boolean;
606
+ }> {
607
+ const limit = Math.min(262_144, Math.max(1, Math.floor(maxBytes) || 65_536));
608
+ const response = await this.response(`${projectPath(id)}/jobs/${job}/trace`, signal);
609
+ const reader = response.body?.getReader();
610
+ if (!reader) return { text: "", truncated: false };
611
+ const chunks: Uint8Array[] = [];
612
+ let size = 0;
613
+ let truncated = false;
614
+ try {
615
+ while (true) {
616
+ const item = await reader.read();
617
+ if (item.done) break;
618
+ const take = Math.min(item.value.length, limit - size);
619
+ chunks.push(item.value.slice(0, take));
620
+ size += take;
621
+ if (size >= limit) {
622
+ truncated = true;
623
+ break;
624
+ }
625
+ }
626
+ } finally {
627
+ await reader.cancel();
628
+ }
629
+ return { text: Buffer.concat(chunks).toString("utf8"), truncated };
630
+ }
631
+ }
632
+ /** @public */
633
+ export type GitLabClientLike = Pick<
634
+ GitLabClient,
635
+ | "addNote"
636
+ | "addNoteReaction"
637
+ | "baseUrl"
638
+ | "getBranch"
639
+ | "getChanges"
640
+ | "getCommit"
641
+ | "getDiscussion"
642
+ | "getGroup"
643
+ | "getJobTrace"
644
+ | "getMergeRequest"
645
+ | "getPipeline"
646
+ | "getProject"
647
+ | "listBranchPipelines"
648
+ | "listFailedJobs"
649
+ | "listGroupProjects"
650
+ | "listMergeRequestFeedback"
651
+ | "listMergeRequestPipelines"
652
+ | "listMergeRequests"
653
+ | "listNoteReactions"
654
+ | "listNotes"
655
+ | "listProjects"
656
+ | "replyToDiscussion"
657
+ | "resolveGitIdentity"
658
+ >;
659
+
660
+ /** A pending current pipeline supersedes every older result. Synthetic merges must contain this source head. @public */
661
+ export async function observeMergeRequest(
662
+ client: GitLabClientLike,
663
+ projectId: number,
664
+ iid: number,
665
+ signal?: AbortSignal,
666
+ ): Promise<GitLabObservation> {
667
+ const mr = await client.getMergeRequest(projectId, iid, signal);
668
+ if (mr.state !== "opened") return { mr, pipeline: null };
669
+ const targetHead = (await client.getBranch(mr.target_project_id, mr.target_branch, signal)).commit
670
+ .id;
671
+ const associated = (await client.listMergeRequestPipelines(projectId, iid, signal)).sort(
672
+ (a, b) => b.id - a.id,
673
+ );
674
+ for (const candidate of associated) {
675
+ const id = candidate.project_id ?? projectId;
676
+ let matches = candidate.sha === mr.sha;
677
+ if (
678
+ !matches &&
679
+ (candidate.ref === `refs/merge-requests/${iid}/merge` ||
680
+ candidate.sha === mr.merge_commit_sha)
681
+ ) {
682
+ const commit = await client.getCommit(id, candidate.sha, signal);
683
+ matches = commit.parent_ids.includes(mr.sha);
684
+ }
685
+ if (matches)
686
+ return { mr, targetHead, pipeline: await client.getPipeline(id, candidate.id, signal) };
687
+ }
688
+ const candidates = await client.listBranchPipelines(
689
+ mr.source_project_id,
690
+ mr.source_branch,
691
+ mr.sha,
692
+ signal,
693
+ );
694
+ const latest = candidates
695
+ .filter((p) => p.sha === mr.sha && p.ref === mr.source_branch && p.source === "push")
696
+ .sort((a, b) => b.id - a.id)[0];
697
+ return {
698
+ mr,
699
+ targetHead,
700
+ pipeline: latest ? await client.getPipeline(mr.source_project_id, latest.id, signal) : null,
701
+ };
702
+ }