@leitwerk-dev/gitlab 0.2.0 → 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/README.md +45 -5
- package/dist/capability.d.ts +5 -1
- package/dist/capability.d.ts.map +1 -1
- package/dist/chunk-H4JCQNDY.js +1162 -0
- package/dist/chunk-H4JCQNDY.js.map +1 -0
- package/dist/client.d.ts +230 -3
- package/dist/client.d.ts.map +1 -1
- package/dist/delivery-tools.d.ts +4 -0
- package/dist/delivery-tools.d.ts.map +1 -0
- package/dist/external.d.ts +80 -5
- package/dist/external.d.ts.map +1 -1
- package/dist/index.d.ts +13 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +40 -20
- package/dist/index.js.map +1 -1
- package/dist/issue-watcher.d.ts +42 -0
- package/dist/issue-watcher.d.ts.map +1 -0
- package/dist/preflight.d.ts +10 -0
- package/dist/preflight.d.ts.map +1 -0
- package/dist/selection.d.ts +11 -1
- package/dist/selection.d.ts.map +1 -1
- package/dist/setup.d.ts +11 -0
- package/dist/setup.d.ts.map +1 -0
- package/dist/testing.d.ts +43 -4
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +139 -1
- package/dist/testing.js.map +1 -1
- package/dist/tools.d.ts +35 -4
- package/dist/tools.d.ts.map +1 -1
- package/package.json +7 -6
- package/src/capability.ts +5 -1
- package/src/client.ts +392 -20
- package/src/delivery-tools.ts +226 -0
- package/src/external.ts +200 -8
- package/src/index.ts +42 -26
- package/src/issue-watcher.ts +152 -0
- package/src/preflight.ts +70 -0
- package/src/selection.ts +19 -3
- package/src/setup.ts +22 -0
- package/src/testing.ts +161 -7
- package/src/tools.ts +106 -54
- package/dist/chunk-5GBBPAG5.js +0 -656
- package/dist/chunk-5GBBPAG5.js.map +0 -1
package/dist/chunk-5GBBPAG5.js
DELETED
|
@@ -1,656 +0,0 @@
|
|
|
1
|
-
// src/index.ts
|
|
2
|
-
import {
|
|
3
|
-
coreHostCapabilities
|
|
4
|
-
} from "@leitwerk-dev/process-sdk";
|
|
5
|
-
|
|
6
|
-
// src/capability.ts
|
|
7
|
-
import {
|
|
8
|
-
createCapabilityToken
|
|
9
|
-
} from "@leitwerk-dev/process-sdk";
|
|
10
|
-
var gitlabIntegration = createCapabilityToken(
|
|
11
|
-
"@leitwerk-dev/gitlab.integration"
|
|
12
|
-
);
|
|
13
|
-
function gitlabRepositoryCredentials(profile, projects) {
|
|
14
|
-
return projects.map((project) => ({
|
|
15
|
-
projectKey: project.key,
|
|
16
|
-
kind: "git_https",
|
|
17
|
-
credentialRef: `gitlab:${profile}`
|
|
18
|
-
}));
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
// src/client.ts
|
|
22
|
-
import { asUnknownRecord } from "@leitwerk-dev/domain";
|
|
23
|
-
import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
|
|
24
|
-
var GitLabError = class extends Error {
|
|
25
|
-
constructor(status, retryable) {
|
|
26
|
-
super(
|
|
27
|
-
`GitLab request failed (${status || "network unavailable"})${retryable ? "; retryable" : "; check profile and project access"}`
|
|
28
|
-
);
|
|
29
|
-
this.status = status;
|
|
30
|
-
this.retryable = retryable;
|
|
31
|
-
}
|
|
32
|
-
status;
|
|
33
|
-
retryable;
|
|
34
|
-
};
|
|
35
|
-
function parseGitLabProfiles(raw) {
|
|
36
|
-
const profiles = /* @__PURE__ */ new Map();
|
|
37
|
-
for (const [name, value] of Object.entries(
|
|
38
|
-
asUnknownRecord(asUnknownRecord(raw)?.profiles) ?? {}
|
|
39
|
-
)) {
|
|
40
|
-
const item = asUnknownRecord(value) ?? {};
|
|
41
|
-
const baseUrl = typeof item.base_url === "string" ? item.base_url.replace(/\/+$/, "") : "";
|
|
42
|
-
const url = repositoryHttpsUrl(`${baseUrl}/` === "/" ? "" : `${baseUrl}/repository`);
|
|
43
|
-
if (url.origin !== baseUrl)
|
|
44
|
-
throw new Error(`GitLab profile '${name}' requires an HTTPS origin base_url`);
|
|
45
|
-
const configuredToken = typeof item.token === "string" ? item.token : "";
|
|
46
|
-
const token = configuredToken.startsWith("env:") ? process.env[configuredToken.slice(4)] ?? "" : configuredToken;
|
|
47
|
-
if (!token || /[\r\n\0]/.test(token))
|
|
48
|
-
throw new Error(`GitLab profile '${name}' requires a token`);
|
|
49
|
-
const identity = asUnknownRecord(item.git_identity);
|
|
50
|
-
if (identity && [identity.name, identity.email].some(
|
|
51
|
-
(v) => typeof v !== "string" || !v.trim() || /[\r\n<>]/.test(v)
|
|
52
|
-
))
|
|
53
|
-
throw new Error(`GitLab profile '${name}' requires a valid git_identity name and email`);
|
|
54
|
-
profiles.set(name, {
|
|
55
|
-
baseUrl,
|
|
56
|
-
token,
|
|
57
|
-
...identity ? { gitIdentity: { name: String(identity.name), email: String(identity.email) } } : {}
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
return profiles;
|
|
61
|
-
}
|
|
62
|
-
var projectPath = (id) => `/projects/${encodeURIComponent(id)}`;
|
|
63
|
-
var mrPath = (id, iid) => `${projectPath(id)}/merge_requests/${iid}`;
|
|
64
|
-
var GitLabClient = class {
|
|
65
|
-
baseUrl;
|
|
66
|
-
#profile;
|
|
67
|
-
#fetch;
|
|
68
|
-
#sleep;
|
|
69
|
-
constructor(profile, options = {}) {
|
|
70
|
-
if (repositoryHttpsUrl(`${profile.baseUrl}/repository`).origin !== profile.baseUrl)
|
|
71
|
-
throw new Error("GitLab requires an HTTPS origin baseUrl");
|
|
72
|
-
if (!profile.token || /[\r\n\0]/.test(profile.token))
|
|
73
|
-
throw new Error("GitLab requires a valid token");
|
|
74
|
-
this.#profile = profile;
|
|
75
|
-
this.baseUrl = profile.baseUrl;
|
|
76
|
-
this.#fetch = options.fetch ?? fetch;
|
|
77
|
-
this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
78
|
-
}
|
|
79
|
-
async response(path, signal, body) {
|
|
80
|
-
for (let attempt = 0; ; attempt++) {
|
|
81
|
-
let response;
|
|
82
|
-
try {
|
|
83
|
-
response = await this.#fetch(`${this.baseUrl}/api/v4${path}`, {
|
|
84
|
-
method: body === void 0 ? "GET" : "POST",
|
|
85
|
-
redirect: "error",
|
|
86
|
-
headers: {
|
|
87
|
-
"PRIVATE-TOKEN": this.#profile.token,
|
|
88
|
-
Accept: "application/json",
|
|
89
|
-
...body === void 0 ? {} : { "Content-Type": "application/json" }
|
|
90
|
-
},
|
|
91
|
-
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4),
|
|
92
|
-
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
93
|
-
});
|
|
94
|
-
} catch {
|
|
95
|
-
if (signal?.aborted) throw new GitLabError(0, true);
|
|
96
|
-
if (body !== void 0 || attempt >= 2) throw new GitLabError(0, true);
|
|
97
|
-
await this.#sleep(1e3 * 2 ** attempt);
|
|
98
|
-
continue;
|
|
99
|
-
}
|
|
100
|
-
if (response.ok) return response;
|
|
101
|
-
const retryable = response.status === 429 || response.status >= 500 || response.status === 408;
|
|
102
|
-
await response.body?.cancel();
|
|
103
|
-
if (!retryable || body !== void 0 || attempt >= 2)
|
|
104
|
-
throw new GitLabError(response.status, retryable);
|
|
105
|
-
const seconds = Number(response.headers.get("retry-after"));
|
|
106
|
-
await this.#sleep(Math.min(3e4, seconds > 0 ? seconds * 1e3 : 1e3 * 2 ** attempt));
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
async request(path, signal, body) {
|
|
110
|
-
return this.json(await this.response(path, signal, body));
|
|
111
|
-
}
|
|
112
|
-
async json(response) {
|
|
113
|
-
try {
|
|
114
|
-
return await response.json();
|
|
115
|
-
} catch {
|
|
116
|
-
throw new GitLabError(502, true);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
async pages(path, signal) {
|
|
120
|
-
const rows = [];
|
|
121
|
-
let page = 1;
|
|
122
|
-
for (let n = 0; n < 1e4; n++) {
|
|
123
|
-
const response = await this.response(
|
|
124
|
-
`${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`,
|
|
125
|
-
signal
|
|
126
|
-
);
|
|
127
|
-
const batch = await this.json(response);
|
|
128
|
-
if (!Array.isArray(batch)) throw new Error("Invalid GitLab list response");
|
|
129
|
-
rows.push(...batch);
|
|
130
|
-
const next = response.headers.get("x-next-page");
|
|
131
|
-
if (next === "" || next === null && batch.length < 100) return rows;
|
|
132
|
-
const nextPage = next === null ? page + 1 : Number(next);
|
|
133
|
-
if (!Number.isInteger(nextPage) || nextPage <= page)
|
|
134
|
-
throw new Error("Invalid GitLab pagination");
|
|
135
|
-
page = nextPage;
|
|
136
|
-
}
|
|
137
|
-
throw new Error("GitLab pagination limit exceeded; discovery incomplete");
|
|
138
|
-
}
|
|
139
|
-
getProject(id, signal) {
|
|
140
|
-
return this.request(projectPath(id), signal);
|
|
141
|
-
}
|
|
142
|
-
listProjects(signal) {
|
|
143
|
-
return this.pages("/projects?archived=false", signal);
|
|
144
|
-
}
|
|
145
|
-
getGroup(id, signal) {
|
|
146
|
-
return this.request(`/groups/${encodeURIComponent(id)}`, signal);
|
|
147
|
-
}
|
|
148
|
-
listGroupProjects(id, signal) {
|
|
149
|
-
return this.pages(
|
|
150
|
-
`/groups/${encodeURIComponent(id)}/projects?include_subgroups=true&with_shared=false&archived=false`,
|
|
151
|
-
signal
|
|
152
|
-
);
|
|
153
|
-
}
|
|
154
|
-
listMergeRequests(id, label, signal) {
|
|
155
|
-
return this.pages(
|
|
156
|
-
`${projectPath(id)}/merge_requests?state=opened&labels=${encodeURIComponent(label)}`,
|
|
157
|
-
signal
|
|
158
|
-
);
|
|
159
|
-
}
|
|
160
|
-
getMergeRequest(id, iid, signal) {
|
|
161
|
-
return this.request(mrPath(id, iid), signal);
|
|
162
|
-
}
|
|
163
|
-
getChanges(id, iid, signal) {
|
|
164
|
-
return this.pages(`${mrPath(id, iid)}/diffs`, signal);
|
|
165
|
-
}
|
|
166
|
-
getBranch(id, branch, signal) {
|
|
167
|
-
return this.request(
|
|
168
|
-
`${projectPath(id)}/repository/branches/${encodeURIComponent(branch)}`,
|
|
169
|
-
signal
|
|
170
|
-
);
|
|
171
|
-
}
|
|
172
|
-
getCommit(id, sha, signal) {
|
|
173
|
-
return this.request(`${projectPath(id)}/repository/commits/${encodeURIComponent(sha)}`, signal);
|
|
174
|
-
}
|
|
175
|
-
listMergeRequestPipelines(id, iid, signal) {
|
|
176
|
-
return this.pages(`${mrPath(id, iid)}/pipelines`, signal);
|
|
177
|
-
}
|
|
178
|
-
listBranchPipelines(id, branch, sha, signal) {
|
|
179
|
-
return this.pages(
|
|
180
|
-
`${projectPath(id)}/pipelines?ref=${encodeURIComponent(branch)}&sha=${encodeURIComponent(sha)}&source=push`,
|
|
181
|
-
signal
|
|
182
|
-
);
|
|
183
|
-
}
|
|
184
|
-
getPipeline(id, pipeline, signal) {
|
|
185
|
-
return this.request(`${projectPath(id)}/pipelines/${pipeline}`, signal);
|
|
186
|
-
}
|
|
187
|
-
listFailedJobs(id, pipeline, signal) {
|
|
188
|
-
return this.pages(
|
|
189
|
-
`${projectPath(id)}/pipelines/${pipeline}/jobs?scope[]=failed&include_retried=false`,
|
|
190
|
-
signal
|
|
191
|
-
);
|
|
192
|
-
}
|
|
193
|
-
listNotes(id, iid, signal) {
|
|
194
|
-
return this.pages(`${mrPath(id, iid)}/notes`, signal);
|
|
195
|
-
}
|
|
196
|
-
getDiscussion(id, iid, discussionId, signal) {
|
|
197
|
-
return this.request(
|
|
198
|
-
`${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}`,
|
|
199
|
-
signal
|
|
200
|
-
);
|
|
201
|
-
}
|
|
202
|
-
replyToDiscussion(id, iid, discussionId, body, signal) {
|
|
203
|
-
return this.request(
|
|
204
|
-
`${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}/notes`,
|
|
205
|
-
signal,
|
|
206
|
-
{ body }
|
|
207
|
-
);
|
|
208
|
-
}
|
|
209
|
-
listNoteReactions(id, iid, noteId, signal) {
|
|
210
|
-
return this.pages(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal);
|
|
211
|
-
}
|
|
212
|
-
addNoteReaction(id, iid, noteId, name, signal) {
|
|
213
|
-
return this.request(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal, { name });
|
|
214
|
-
}
|
|
215
|
-
async listMergeRequestFeedback(id, iid, signal) {
|
|
216
|
-
const [discussions, identity] = await Promise.all([
|
|
217
|
-
this.pages(`${mrPath(id, iid)}/discussions`, signal),
|
|
218
|
-
this.resolveGitIdentity(signal)
|
|
219
|
-
]);
|
|
220
|
-
const feedback = [];
|
|
221
|
-
for (const discussion of discussions) {
|
|
222
|
-
for (const note of discussion.notes) {
|
|
223
|
-
if (note.system || note.resolved || note.author.bot || note.author.username === identity.username || !note.body.trim() || !Number.isFinite(Date.parse(note.created_at)))
|
|
224
|
-
continue;
|
|
225
|
-
const position = note.position ?? discussion.notes[0]?.position;
|
|
226
|
-
feedback.push({
|
|
227
|
-
id: note.id,
|
|
228
|
-
discussionId: discussion.id,
|
|
229
|
-
body: note.body,
|
|
230
|
-
author: note.author.username,
|
|
231
|
-
createdAt: note.created_at,
|
|
232
|
-
...position ? {
|
|
233
|
-
path: position.new_path ?? position.old_path,
|
|
234
|
-
line: position.new_line ?? position.old_line
|
|
235
|
-
} : {}
|
|
236
|
-
});
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
return feedback.sort((a, b) => a.id - b.id);
|
|
240
|
-
}
|
|
241
|
-
addNote(id, iid, body, signal) {
|
|
242
|
-
return this.request(`${mrPath(id, iid)}/notes`, signal, { body });
|
|
243
|
-
}
|
|
244
|
-
async resolveGitIdentity(signal) {
|
|
245
|
-
const user = await this.request("/user", signal);
|
|
246
|
-
const name = this.#profile.gitIdentity?.name ?? user.name;
|
|
247
|
-
const email = this.#profile.gitIdentity?.email ?? user.commit_email ?? user.email;
|
|
248
|
-
if (!user.username || !name?.trim() || !email?.includes("@") || /[\r\n<>]/.test(name + email))
|
|
249
|
-
throw new Error(
|
|
250
|
-
"GitLab bot Git identity is unavailable; configure git_identity on the profile"
|
|
251
|
-
);
|
|
252
|
-
return { name, email, username: user.username };
|
|
253
|
-
}
|
|
254
|
-
async getJobTrace(id, job, maxBytes = 65536, signal) {
|
|
255
|
-
const limit = Math.min(262144, Math.max(1, Math.floor(maxBytes) || 65536));
|
|
256
|
-
const response = await this.response(`${projectPath(id)}/jobs/${job}/trace`, signal);
|
|
257
|
-
const reader = response.body?.getReader();
|
|
258
|
-
if (!reader) return { text: "", truncated: false };
|
|
259
|
-
const chunks = [];
|
|
260
|
-
let size = 0;
|
|
261
|
-
let truncated = false;
|
|
262
|
-
try {
|
|
263
|
-
while (true) {
|
|
264
|
-
const item = await reader.read();
|
|
265
|
-
if (item.done) break;
|
|
266
|
-
const take = Math.min(item.value.length, limit - size);
|
|
267
|
-
chunks.push(item.value.slice(0, take));
|
|
268
|
-
size += take;
|
|
269
|
-
if (size >= limit) {
|
|
270
|
-
truncated = true;
|
|
271
|
-
break;
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
} finally {
|
|
275
|
-
await reader.cancel();
|
|
276
|
-
}
|
|
277
|
-
return { text: Buffer.concat(chunks).toString("utf8"), truncated };
|
|
278
|
-
}
|
|
279
|
-
};
|
|
280
|
-
async function observeMergeRequest(client, projectId, iid, signal) {
|
|
281
|
-
const mr = await client.getMergeRequest(projectId, iid, signal);
|
|
282
|
-
if (mr.state !== "opened") return { mr, pipeline: null };
|
|
283
|
-
const associated = (await client.listMergeRequestPipelines(projectId, iid, signal)).sort(
|
|
284
|
-
(a, b) => b.id - a.id
|
|
285
|
-
);
|
|
286
|
-
for (const candidate of associated) {
|
|
287
|
-
const id = candidate.project_id ?? projectId;
|
|
288
|
-
let matches = candidate.sha === mr.sha;
|
|
289
|
-
if (!matches && (candidate.ref === `refs/merge-requests/${iid}/merge` || candidate.sha === mr.merge_commit_sha)) {
|
|
290
|
-
const commit = await client.getCommit(id, candidate.sha, signal);
|
|
291
|
-
matches = commit.parent_ids.includes(mr.sha);
|
|
292
|
-
}
|
|
293
|
-
if (matches) return { mr, pipeline: await client.getPipeline(id, candidate.id, signal) };
|
|
294
|
-
}
|
|
295
|
-
const candidates = await client.listBranchPipelines(
|
|
296
|
-
mr.source_project_id,
|
|
297
|
-
mr.source_branch,
|
|
298
|
-
mr.sha,
|
|
299
|
-
signal
|
|
300
|
-
);
|
|
301
|
-
const latest = candidates.filter((p) => p.sha === mr.sha && p.ref === mr.source_branch && p.source === "push").sort((a, b) => b.id - a.id)[0];
|
|
302
|
-
return {
|
|
303
|
-
mr,
|
|
304
|
-
pipeline: latest ? await client.getPipeline(mr.source_project_id, latest.id, signal) : null
|
|
305
|
-
};
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
// src/external.ts
|
|
309
|
-
import {
|
|
310
|
-
createExternalSourcePollReporter
|
|
311
|
-
} from "@leitwerk-dev/process-sdk";
|
|
312
|
-
import { emptyPollResult, parseDurationMs } from "@leitwerk-dev/watcher-utils";
|
|
313
|
-
var GITLAB_MR_KIND = "@leitwerk-dev/gitlab.merge-request";
|
|
314
|
-
function pendingGitLabFeedback(items, afterId, since) {
|
|
315
|
-
const start = since ? Date.parse(since) : 0;
|
|
316
|
-
return items.filter((item) => item.id > afterId && Date.parse(item.createdAt) >= start);
|
|
317
|
-
}
|
|
318
|
-
function gitLabFeedbackReadyAt(items, quietPeriodMs) {
|
|
319
|
-
return items.length ? Math.max(...items.map((item) => Date.parse(item.createdAt))) + quietPeriodMs : null;
|
|
320
|
-
}
|
|
321
|
-
var observationKey = ({ mr, pipeline }) => JSON.stringify([
|
|
322
|
-
mr.state,
|
|
323
|
-
mr.sha,
|
|
324
|
-
[...mr.labels].sort(),
|
|
325
|
-
pipeline?.project_id,
|
|
326
|
-
pipeline?.id,
|
|
327
|
-
pipeline?.status
|
|
328
|
-
]);
|
|
329
|
-
var gitlabExternal = {
|
|
330
|
-
mergeRequest(resolve) {
|
|
331
|
-
return {
|
|
332
|
-
kind: GITLAB_MR_KIND,
|
|
333
|
-
label: "GitLab merge request",
|
|
334
|
-
description: "Observe MR state, current source head and revision-correlated CI",
|
|
335
|
-
config: {},
|
|
336
|
-
inputMode: "none",
|
|
337
|
-
resolve
|
|
338
|
-
};
|
|
339
|
-
}
|
|
340
|
-
};
|
|
341
|
-
function createGitLabProvider(deps, integration, options = {}) {
|
|
342
|
-
const schedule = /* @__PURE__ */ new Map();
|
|
343
|
-
const now = options.now ?? Date.now;
|
|
344
|
-
return deps.polling.create({
|
|
345
|
-
id: "gitlab",
|
|
346
|
-
pollInterval: () => "5s",
|
|
347
|
-
isEnabled: () => true,
|
|
348
|
-
defaultIntervalMs: 5e3,
|
|
349
|
-
async pollOnce() {
|
|
350
|
-
const result = emptyPollResult();
|
|
351
|
-
const report = createExternalSourcePollReporter(deps.externalSources, result);
|
|
352
|
-
await report.poll(GITLAB_MR_KIND, async (armed) => {
|
|
353
|
-
const c = armed.resolved;
|
|
354
|
-
if (!c || typeof c.profile !== "string" || !Number.isInteger(c.projectId) || !Number.isInteger(c.iid))
|
|
355
|
-
throw new Error("Invalid GitLab external source");
|
|
356
|
-
const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
|
|
357
|
-
const previous = schedule.get(key);
|
|
358
|
-
if (previous && previous.at > now()) return;
|
|
359
|
-
try {
|
|
360
|
-
const observation = await observeMergeRequest(
|
|
361
|
-
integration.client(c.profile),
|
|
362
|
-
c.projectId,
|
|
363
|
-
c.iid
|
|
364
|
-
);
|
|
365
|
-
const observedKey = observationKey(observation);
|
|
366
|
-
const feedback = c.feedback && observation.mr.state === "opened" ? pendingGitLabFeedback(
|
|
367
|
-
await integration.client(c.profile).listMergeRequestFeedback(c.projectId, c.iid),
|
|
368
|
-
c.feedback.afterId,
|
|
369
|
-
c.feedback.since
|
|
370
|
-
) : [];
|
|
371
|
-
const feedbackReadyAt = gitLabFeedbackReadyAt(
|
|
372
|
-
feedback,
|
|
373
|
-
c.feedback?.quietPeriodMs ?? 12e4
|
|
374
|
-
);
|
|
375
|
-
const feedbackReady = feedbackReadyAt !== null && feedbackReadyAt <= now();
|
|
376
|
-
await report.observe(armed, {
|
|
377
|
-
observation: {
|
|
378
|
-
summary: `${observation.mr.state} \xB7 ${observation.pipeline?.status ?? "no current pipeline"}`,
|
|
379
|
-
observedAt: new Date(now()).toISOString(),
|
|
380
|
-
subject: observation.mr.web_url,
|
|
381
|
-
revision: observation.mr.sha
|
|
382
|
-
}
|
|
383
|
-
});
|
|
384
|
-
if (observedKey !== c.afterKey || feedbackReady || c.wakeAt !== void 0 && c.wakeAt <= now())
|
|
385
|
-
await report.fire(
|
|
386
|
-
armed,
|
|
387
|
-
{ ...observation },
|
|
388
|
-
`${observedKey}:${c.wakeAt ?? ""}:${feedbackReady ? feedback.map((item) => item.id).join(",") : ""}`
|
|
389
|
-
);
|
|
390
|
-
schedule.set(key, {
|
|
391
|
-
at: now() + parseDurationMs(c.pollInterval ?? "30s", 3e4),
|
|
392
|
-
failures: 0
|
|
393
|
-
});
|
|
394
|
-
} catch (error) {
|
|
395
|
-
const failures = (previous?.failures ?? 0) + 1;
|
|
396
|
-
schedule.set(key, {
|
|
397
|
-
at: now() + Math.min(3e5, 3e4 * 2 ** Math.min(failures - 1, 4)),
|
|
398
|
-
failures
|
|
399
|
-
});
|
|
400
|
-
await report.observe(armed, {
|
|
401
|
-
refreshError: error instanceof Error ? error.message : "GitLab observation unavailable"
|
|
402
|
-
});
|
|
403
|
-
throw error;
|
|
404
|
-
}
|
|
405
|
-
});
|
|
406
|
-
return result;
|
|
407
|
-
}
|
|
408
|
-
});
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
// src/tools.ts
|
|
412
|
-
import { createHash } from "crypto";
|
|
413
|
-
import {
|
|
414
|
-
createWriteIdentity,
|
|
415
|
-
ensureWrite
|
|
416
|
-
} from "@leitwerk-dev/external-writes";
|
|
417
|
-
import {
|
|
418
|
-
numberArg,
|
|
419
|
-
projectParameters,
|
|
420
|
-
stringArg
|
|
421
|
-
} from "@leitwerk-dev/process-sdk";
|
|
422
|
-
function resolveGitLabBinding(ctx) {
|
|
423
|
-
if (!ctx.project || ctx.project.instanceId !== ctx.process.id)
|
|
424
|
-
throw new Error("An authorized GitLab process project is required");
|
|
425
|
-
const binding = ctx.project.metadata?.gitlab;
|
|
426
|
-
if (!binding || typeof binding.profile !== "string" || typeof binding.projectId !== "number" || typeof binding.iid !== "number")
|
|
427
|
-
throw new Error("Invalid GitLab project binding");
|
|
428
|
-
return { profile: binding.profile, projectId: binding.projectId, iid: binding.iid };
|
|
429
|
-
}
|
|
430
|
-
async function findOrCreate(find, create) {
|
|
431
|
-
const existing = await find();
|
|
432
|
-
if (existing) return existing;
|
|
433
|
-
try {
|
|
434
|
-
return await create();
|
|
435
|
-
} catch (error) {
|
|
436
|
-
const recovered = await find();
|
|
437
|
-
if (!recovered) throw error;
|
|
438
|
-
return recovered;
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
async function ensureGitLabComment(input) {
|
|
442
|
-
const { client, writes, instanceId, projectId, iid, writeKey, signal } = input;
|
|
443
|
-
const identity = [client.baseUrl, projectId, iid, instanceId, writeKey];
|
|
444
|
-
if (input.discussionId) identity.push(input.discussionId);
|
|
445
|
-
const digest = createHash("sha256").update(JSON.stringify(identity)).digest("hex");
|
|
446
|
-
const marker = `<!-- leitwerk:gitlab:${digest} -->`;
|
|
447
|
-
const find = async () => {
|
|
448
|
-
const notes = input.discussionId ? (await client.getDiscussion(projectId, iid, input.discussionId, signal)).notes : await client.listNotes(projectId, iid, signal);
|
|
449
|
-
return notes.find((note) => note.body.includes(marker));
|
|
450
|
-
};
|
|
451
|
-
await ensureWrite(writes, instanceId, createWriteIdentity("gitlab.comment", digest), async () => {
|
|
452
|
-
const note = await findOrCreate(find, () => {
|
|
453
|
-
const body = `${input.body}
|
|
454
|
-
|
|
455
|
-
${marker}`;
|
|
456
|
-
return input.discussionId ? client.replyToDiscussion(projectId, iid, input.discussionId, body, signal) : client.addNote(projectId, iid, body, signal);
|
|
457
|
-
});
|
|
458
|
-
return { projectId, iid, noteId: note.id, marker };
|
|
459
|
-
});
|
|
460
|
-
return { marker };
|
|
461
|
-
}
|
|
462
|
-
async function ensureGitLabSeenReaction(input) {
|
|
463
|
-
const { client, writes, instanceId, projectId, iid, noteId, signal } = input;
|
|
464
|
-
const digest = createHash("sha256").update(JSON.stringify([client.baseUrl, projectId, iid, instanceId, "eyes", noteId])).digest("hex");
|
|
465
|
-
await ensureWrite(
|
|
466
|
-
writes,
|
|
467
|
-
instanceId,
|
|
468
|
-
createWriteIdentity("gitlab.reaction", digest),
|
|
469
|
-
async () => {
|
|
470
|
-
const identity = await client.resolveGitIdentity(signal);
|
|
471
|
-
const find = async () => (await client.listNoteReactions(projectId, iid, noteId, signal)).find(
|
|
472
|
-
(reaction2) => reaction2.name === "eyes" && reaction2.user.username === identity.username
|
|
473
|
-
);
|
|
474
|
-
const reaction = await findOrCreate(
|
|
475
|
-
find,
|
|
476
|
-
() => client.addNoteReaction(projectId, iid, noteId, "eyes", signal)
|
|
477
|
-
);
|
|
478
|
-
return { projectId, iid, noteId, reactionId: reaction.id, name: "eyes" };
|
|
479
|
-
}
|
|
480
|
-
);
|
|
481
|
-
}
|
|
482
|
-
function registerGitLabTools(api, integration, writes) {
|
|
483
|
-
for (const [name, description, required] of [
|
|
484
|
-
["gitlab_observe_merge_request", "Read the current MR source revision and its latest CI", []],
|
|
485
|
-
["gitlab_get_changes", "Read the MR changes", []],
|
|
486
|
-
["gitlab_get_identity", "Resolve the authenticated GitLab bot Git identity", []],
|
|
487
|
-
["gitlab_list_failed_jobs", "Read failed jobs from an MR-associated pipeline", ["pipelineId"]],
|
|
488
|
-
[
|
|
489
|
-
"gitlab_get_job_trace",
|
|
490
|
-
"Read a bounded trace from a failed MR pipeline job",
|
|
491
|
-
["pipelineId", "jobId"]
|
|
492
|
-
],
|
|
493
|
-
["gitlab_comment", "Post a retry-safe MR comment", ["body", "writeKey"]],
|
|
494
|
-
[
|
|
495
|
-
"gitlab_reply",
|
|
496
|
-
"Post a retry-safe reply in an MR discussion",
|
|
497
|
-
["body", "writeKey", "discussionId"]
|
|
498
|
-
]
|
|
499
|
-
]) {
|
|
500
|
-
api.tool({
|
|
501
|
-
name,
|
|
502
|
-
description,
|
|
503
|
-
parameters: projectParameters(
|
|
504
|
-
{
|
|
505
|
-
pipelineId: { type: "integer" },
|
|
506
|
-
jobId: { type: "integer" },
|
|
507
|
-
maxBytes: { type: "integer" },
|
|
508
|
-
body: { type: "string" },
|
|
509
|
-
writeKey: { type: "string" },
|
|
510
|
-
discussionId: { type: "string" }
|
|
511
|
-
},
|
|
512
|
-
[...required]
|
|
513
|
-
),
|
|
514
|
-
async execute(ctx, args) {
|
|
515
|
-
const b = resolveGitLabBinding(ctx);
|
|
516
|
-
const client = integration.client(b.profile);
|
|
517
|
-
if (name === "gitlab_observe_merge_request")
|
|
518
|
-
return observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
|
|
519
|
-
if (name === "gitlab_get_changes") return client.getChanges(b.projectId, b.iid, ctx.signal);
|
|
520
|
-
if (name === "gitlab_get_identity") return client.resolveGitIdentity(ctx.signal);
|
|
521
|
-
if (name === "gitlab_comment" || name === "gitlab_reply")
|
|
522
|
-
return ensureGitLabComment({
|
|
523
|
-
client,
|
|
524
|
-
writes,
|
|
525
|
-
instanceId: ctx.process.id,
|
|
526
|
-
projectId: b.projectId,
|
|
527
|
-
iid: b.iid,
|
|
528
|
-
writeKey: stringArg(args, "writeKey"),
|
|
529
|
-
body: stringArg(args, "body"),
|
|
530
|
-
...name === "gitlab_reply" ? { discussionId: stringArg(args, "discussionId") } : {},
|
|
531
|
-
signal: ctx.signal
|
|
532
|
-
});
|
|
533
|
-
const observation = await observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
|
|
534
|
-
if (!observation.pipeline || observation.pipeline.id !== numberArg(args, "pipelineId"))
|
|
535
|
-
throw new Error("Pipeline is not current for the authorized MR");
|
|
536
|
-
const jobs = await client.listFailedJobs(
|
|
537
|
-
observation.pipeline.project_id,
|
|
538
|
-
observation.pipeline.id,
|
|
539
|
-
ctx.signal
|
|
540
|
-
);
|
|
541
|
-
if (name === "gitlab_list_failed_jobs") return jobs;
|
|
542
|
-
const job = jobs.find((job2) => job2.id === numberArg(args, "jobId"));
|
|
543
|
-
if (!job) throw new Error("Job is not a failed job of the authorized MR pipeline");
|
|
544
|
-
return client.getJobTrace(
|
|
545
|
-
observation.pipeline.project_id,
|
|
546
|
-
job.id,
|
|
547
|
-
typeof args.maxBytes === "number" ? args.maxBytes : void 0,
|
|
548
|
-
ctx.signal
|
|
549
|
-
);
|
|
550
|
-
}
|
|
551
|
-
});
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
// src/selection.ts
|
|
556
|
-
function parseGitLabSelection(raw) {
|
|
557
|
-
const list = (value) => {
|
|
558
|
-
if (value === void 0) return [];
|
|
559
|
-
if (!Array.isArray(value) || value.some(
|
|
560
|
-
(v) => typeof v !== "string" || !/^[a-zA-Z0-9_.-]+(?:\/[a-zA-Z0-9_.-]+)*$/.test(v) || v.split("/").some((p) => p === "." || p === "..")
|
|
561
|
-
))
|
|
562
|
-
throw new Error("GitLab selectors require exact namespace paths");
|
|
563
|
-
return [...new Set(value)];
|
|
564
|
-
};
|
|
565
|
-
const pair = (value) => {
|
|
566
|
-
if (value !== void 0 && (!value || typeof value !== "object" || Array.isArray(value)))
|
|
567
|
-
throw new Error("GitLab selectors must be objects");
|
|
568
|
-
const item = value;
|
|
569
|
-
return { include: list(item?.include), exclude: list(item?.exclude) };
|
|
570
|
-
};
|
|
571
|
-
if (raw.all_accessible !== void 0 && typeof raw.all_accessible !== "boolean")
|
|
572
|
-
throw new Error("all_accessible must be a boolean");
|
|
573
|
-
const parsed = {
|
|
574
|
-
projects: pair(raw.projects),
|
|
575
|
-
groups: pair(raw.groups),
|
|
576
|
-
allAccessible: raw.all_accessible === true
|
|
577
|
-
};
|
|
578
|
-
if (!parsed.allAccessible && !parsed.projects.include.length && !parsed.groups.include.length)
|
|
579
|
-
throw new Error("GitLab requires explicit project/group includes or all_accessible: true");
|
|
580
|
-
return parsed;
|
|
581
|
-
}
|
|
582
|
-
function projectExcluded(selection, name) {
|
|
583
|
-
return selection.projects.exclude.includes(name) || selection.groups.exclude.some((group) => name.startsWith(`${group}/`));
|
|
584
|
-
}
|
|
585
|
-
async function selectGitLabProjects(client, selection) {
|
|
586
|
-
const candidates = selection.allAccessible ? await client.listProjects() : [];
|
|
587
|
-
for (const name of selection.projects.include) candidates.push(await client.getProject(name));
|
|
588
|
-
for (const group of selection.groups.include)
|
|
589
|
-
candidates.push(...await client.listGroupProjects(group));
|
|
590
|
-
return [
|
|
591
|
-
...new Map(
|
|
592
|
-
candidates.filter((p) => !p.archived && !projectExcluded(selection, p.path_with_namespace)).map((p) => [p.id, p])
|
|
593
|
-
).values()
|
|
594
|
-
];
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
// src/index.ts
|
|
598
|
-
var manifest = { id: "gitlab", version: "0.1.9" };
|
|
599
|
-
function setupGitLabIntegration(api, integration, options = {}) {
|
|
600
|
-
api.provide(gitlabIntegration, integration);
|
|
601
|
-
const deps = api.get(coreHostCapabilities.serverSetup);
|
|
602
|
-
if (!deps || Array.isArray(deps)) return;
|
|
603
|
-
registerGitLabTools(api, integration, deps.externalWrites);
|
|
604
|
-
return createGitLabProvider(deps, integration, options);
|
|
605
|
-
}
|
|
606
|
-
var extension = {
|
|
607
|
-
manifest,
|
|
608
|
-
setupServer(api, config) {
|
|
609
|
-
const profiles = parseGitLabProfiles(config);
|
|
610
|
-
const clients = new Map([...profiles].map(([id, profile]) => [id, new GitLabClient(profile)]));
|
|
611
|
-
setupGitLabIntegration(api, {
|
|
612
|
-
profiles: () => [...profiles.keys()],
|
|
613
|
-
client: (profile) => {
|
|
614
|
-
const client = clients.get(profile);
|
|
615
|
-
if (!client) throw new Error(`Unknown GitLab profile '${profile}'`);
|
|
616
|
-
return client;
|
|
617
|
-
}
|
|
618
|
-
});
|
|
619
|
-
const deps = api.get(coreHostCapabilities.serverSetup);
|
|
620
|
-
if (!deps || Array.isArray(deps)) return;
|
|
621
|
-
deps.repositoryCredentials.register({
|
|
622
|
-
kind: "git_https",
|
|
623
|
-
resolve(ref) {
|
|
624
|
-
const profile = ref.startsWith("gitlab:") ? profiles.get(ref.slice(7)) : void 0;
|
|
625
|
-
return profile ? { origin: profile.baseUrl, username: "oauth2", password: profile.token } : null;
|
|
626
|
-
}
|
|
627
|
-
});
|
|
628
|
-
}
|
|
629
|
-
};
|
|
630
|
-
var index_default = extension;
|
|
631
|
-
|
|
632
|
-
export {
|
|
633
|
-
gitlabIntegration,
|
|
634
|
-
gitlabRepositoryCredentials,
|
|
635
|
-
GitLabError,
|
|
636
|
-
parseGitLabProfiles,
|
|
637
|
-
GitLabClient,
|
|
638
|
-
observeMergeRequest,
|
|
639
|
-
GITLAB_MR_KIND,
|
|
640
|
-
pendingGitLabFeedback,
|
|
641
|
-
gitLabFeedbackReadyAt,
|
|
642
|
-
observationKey,
|
|
643
|
-
gitlabExternal,
|
|
644
|
-
createGitLabProvider,
|
|
645
|
-
resolveGitLabBinding,
|
|
646
|
-
ensureGitLabComment,
|
|
647
|
-
ensureGitLabSeenReaction,
|
|
648
|
-
registerGitLabTools,
|
|
649
|
-
parseGitLabSelection,
|
|
650
|
-
projectExcluded,
|
|
651
|
-
selectGitLabProjects,
|
|
652
|
-
manifest,
|
|
653
|
-
setupGitLabIntegration,
|
|
654
|
-
index_default
|
|
655
|
-
};
|
|
656
|
-
//# sourceMappingURL=chunk-5GBBPAG5.js.map
|