@lbdudc/linea-git 0.0.0-stage → 0.1.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.
Files changed (152) hide show
  1. package/README.md +47 -2
  2. package/dist/access.d.ts +18 -0
  3. package/dist/access.js +18 -0
  4. package/dist/access.js.map +1 -0
  5. package/dist/auth.d.ts +11 -0
  6. package/dist/auth.js +16 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/changelog/generate.d.ts +18 -0
  9. package/dist/changelog/generate.js +166 -0
  10. package/dist/changelog/generate.js.map +1 -0
  11. package/dist/changelog/index.d.ts +5 -0
  12. package/dist/changelog/index.js +3 -0
  13. package/dist/changelog/index.js.map +1 -0
  14. package/dist/changelog/parse.d.ts +43 -0
  15. package/dist/changelog/parse.js +91 -0
  16. package/dist/changelog/parse.js.map +1 -0
  17. package/dist/changelog/types.d.ts +85 -0
  18. package/dist/changelog/types.js +2 -0
  19. package/dist/changelog/types.js.map +1 -0
  20. package/dist/checkout/credential.d.ts +14 -0
  21. package/dist/checkout/credential.js +29 -0
  22. package/dist/checkout/credential.js.map +1 -0
  23. package/dist/checkout/git.d.ts +78 -0
  24. package/dist/checkout/git.js +191 -0
  25. package/dist/checkout/git.js.map +1 -0
  26. package/dist/checkout/index.d.ts +3 -0
  27. package/dist/checkout/index.js +4 -0
  28. package/dist/checkout/index.js.map +1 -0
  29. package/dist/checkout/sync.d.ts +156 -0
  30. package/dist/checkout/sync.js +211 -0
  31. package/dist/checkout/sync.js.map +1 -0
  32. package/dist/closing.d.ts +1 -0
  33. package/dist/closing.js +14 -0
  34. package/dist/closing.js.map +1 -0
  35. package/dist/config.d.ts +53 -0
  36. package/dist/config.js +40 -0
  37. package/dist/config.js.map +1 -0
  38. package/dist/deletion.d.ts +19 -0
  39. package/dist/deletion.js +27 -0
  40. package/dist/deletion.js.map +1 -0
  41. package/dist/errors.d.ts +26 -0
  42. package/dist/errors.js +47 -0
  43. package/dist/errors.js.map +1 -0
  44. package/dist/factory.d.ts +20 -0
  45. package/dist/factory.js +46 -0
  46. package/dist/factory.js.map +1 -0
  47. package/dist/github/client.d.ts +44 -0
  48. package/dist/github/client.js +145 -0
  49. package/dist/github/client.js.map +1 -0
  50. package/dist/github/config.d.ts +24 -0
  51. package/dist/github/config.js +11 -0
  52. package/dist/github/config.js.map +1 -0
  53. package/dist/github/provider.d.ts +510 -0
  54. package/dist/github/provider.js +1009 -0
  55. package/dist/github/provider.js.map +1 -0
  56. package/dist/gitlab/client.d.ts +50 -0
  57. package/dist/gitlab/client.js +228 -0
  58. package/dist/gitlab/client.js.map +1 -0
  59. package/dist/gitlab/provider.d.ts +487 -0
  60. package/dist/gitlab/provider.js +719 -0
  61. package/dist/gitlab/provider.js.map +1 -0
  62. package/dist/host.d.ts +27 -0
  63. package/dist/host.js +45 -0
  64. package/dist/host.js.map +1 -0
  65. package/dist/index.d.ts +46 -0
  66. package/dist/index.js +31 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/local/diff.d.ts +3 -0
  69. package/dist/local/diff.js +43 -0
  70. package/dist/local/diff.js.map +1 -0
  71. package/dist/local/git.d.ts +24 -0
  72. package/dist/local/git.js +51 -0
  73. package/dist/local/git.js.map +1 -0
  74. package/dist/local/health.d.ts +36 -0
  75. package/dist/local/health.js +57 -0
  76. package/dist/local/health.js.map +1 -0
  77. package/dist/local/hooks.d.ts +2 -0
  78. package/dist/local/hooks.js +44 -0
  79. package/dist/local/hooks.js.map +1 -0
  80. package/dist/local/http.d.ts +35 -0
  81. package/dist/local/http.js +160 -0
  82. package/dist/local/http.js.map +1 -0
  83. package/dist/local/provider.d.ts +571 -0
  84. package/dist/local/provider.js +1237 -0
  85. package/dist/local/provider.js.map +1 -0
  86. package/dist/local/store.d.ts +136 -0
  87. package/dist/local/store.js +171 -0
  88. package/dist/local/store.js.map +1 -0
  89. package/dist/packages/github-source.d.ts +69 -0
  90. package/dist/packages/github-source.js +133 -0
  91. package/dist/packages/github-source.js.map +1 -0
  92. package/dist/packages/gitlab-source.d.ts +59 -0
  93. package/dist/packages/gitlab-source.js +214 -0
  94. package/dist/packages/gitlab-source.js.map +1 -0
  95. package/dist/packages/index.d.ts +30 -0
  96. package/dist/packages/index.js +45 -0
  97. package/dist/packages/index.js.map +1 -0
  98. package/dist/packages/provider-source.d.ts +34 -0
  99. package/dist/packages/provider-source.js +57 -0
  100. package/dist/packages/provider-source.js.map +1 -0
  101. package/dist/packages/repository-files.d.ts +12 -0
  102. package/dist/packages/repository-files.js +16 -0
  103. package/dist/packages/repository-files.js.map +1 -0
  104. package/dist/provider.d.ts +888 -0
  105. package/dist/provider.js +29 -0
  106. package/dist/provider.js.map +1 -0
  107. package/dist/read-cache.d.ts +5 -0
  108. package/dist/read-cache.js +101 -0
  109. package/dist/read-cache.js.map +1 -0
  110. package/dist/registry/catalog.d.ts +55 -0
  111. package/dist/registry/catalog.js +143 -0
  112. package/dist/registry/catalog.js.map +1 -0
  113. package/dist/registry/kinds.d.ts +21 -0
  114. package/dist/registry/kinds.js +43 -0
  115. package/dist/registry/kinds.js.map +1 -0
  116. package/dist/registry/packages.d.ts +165 -0
  117. package/dist/registry/packages.js +290 -0
  118. package/dist/registry/packages.js.map +1 -0
  119. package/dist/registry/publish.d.ts +35 -0
  120. package/dist/registry/publish.js +155 -0
  121. package/dist/registry/publish.js.map +1 -0
  122. package/dist/registry/release.d.ts +63 -0
  123. package/dist/registry/release.js +79 -0
  124. package/dist/registry/release.js.map +1 -0
  125. package/dist/restoration.d.ts +14 -0
  126. package/dist/restoration.js +33 -0
  127. package/dist/restoration.js.map +1 -0
  128. package/dist/templates.d.ts +8 -0
  129. package/dist/templates.js +39 -0
  130. package/dist/templates.js.map +1 -0
  131. package/dist/testing/contract.d.ts +43 -0
  132. package/dist/testing/contract.js +713 -0
  133. package/dist/testing/contract.js.map +1 -0
  134. package/dist/testing/diff.d.ts +1 -0
  135. package/dist/testing/diff.js +65 -0
  136. package/dist/testing/diff.js.map +1 -0
  137. package/dist/testing/git-http.d.ts +12 -0
  138. package/dist/testing/git-http.js +308 -0
  139. package/dist/testing/git-http.js.map +1 -0
  140. package/dist/testing/github-double.d.ts +151 -0
  141. package/dist/testing/github-double.js +1129 -0
  142. package/dist/testing/github-double.js.map +1 -0
  143. package/dist/testing/gitlab-double.d.ts +161 -0
  144. package/dist/testing/gitlab-double.js +1554 -0
  145. package/dist/testing/gitlab-double.js.map +1 -0
  146. package/dist/testing/index.d.ts +7 -0
  147. package/dist/testing/index.js +8 -0
  148. package/dist/testing/index.js.map +1 -0
  149. package/dist/version.d.ts +2 -0
  150. package/dist/version.js +12 -0
  151. package/dist/version.js.map +1 -0
  152. package/package.json +66 -4
@@ -0,0 +1,1554 @@
1
+ import express from 'express';
2
+ import crypto from 'crypto';
3
+ import JSZip from 'jszip';
4
+ import { createGitHttp } from './git-http.js';
5
+ import { unifiedDiff } from './diff.js';
6
+ const CLIENT_ERROR_JSON = (message) => ({ error: message, message });
7
+ const sha1For = (seedText) => crypto.createHash('sha1').update(seedText).digest('hex');
8
+ const shortId = (sha) => sha.slice(0, 8);
9
+ const slugify = (name) => String(name)
10
+ .trim()
11
+ .replace(/\s+/g, '-')
12
+ .replace(/[^A-Za-z0-9._-]+/g, '-')
13
+ .replace(/^-+|-+$/g, '') || 'project';
14
+ // How long each job of a double pipeline takes, and what makes the next ones fail: `POST /api/v4/__dev/fail-next-pipeline`.
15
+ const PIPELINE_STAGES = ['build', 'test', 'deploy'];
16
+ const JOB_MS = Number(process.env.GITLAB_DOUBLE_JOB_MS ?? 6000);
17
+ const pipelineControl = { failNext: 0 };
18
+ class ProjectState {
19
+ constructor({ id, name, namespace, topics, defaultBranch, initializeWithReadme, webBase, description }) {
20
+ this.id = id;
21
+ this.description = description ?? '';
22
+ this.name = name;
23
+ this.path = slugify(name);
24
+ this.namespace = namespace;
25
+ this.path_with_namespace = namespace.full_path ? `${namespace.full_path}/${this.path}` : this.path;
26
+ this.topics = topics ?? [];
27
+ this.default_branch = defaultBranch ?? 'main';
28
+ this.archived = false;
29
+ this.marked_for_deletion_at = null;
30
+ this.web_url = `${webBase}/${this.path_with_namespace}`;
31
+ this.members = [];
32
+ this.hooks = [];
33
+ this.nextHookId = 1;
34
+ this.nextMrIid = 1;
35
+ this.mergeRequests = new Map();
36
+ this.issues = new Map();
37
+ this.nextIssueIid = 1;
38
+ this.milestones = [];
39
+ this.labels = [];
40
+ this.tags = new Map();
41
+ this.releases = new Map();
42
+ this.pipelines = [];
43
+ this.nextPipelineId = 1;
44
+ // the annotation of the tags that were given one
45
+ this.tagMessages = new Map();
46
+ this.commits = new Map();
47
+ this.branches = new Map();
48
+ const initialTree = new Map();
49
+ if (initializeWithReadme)
50
+ initialTree.set('README.md', Buffer.from(`# ${name}\n`, 'utf8'));
51
+ const initialCommit = this.#newCommit({ tree: initialTree, parent: null, message: 'Initial commit' });
52
+ this.branches.set(this.default_branch, initialCommit.id);
53
+ }
54
+ #newCommit({ tree, parent, message }) {
55
+ const seq = this.commits.size + 1;
56
+ const id = sha1For(`${this.id}|${seq}|${message}`);
57
+ const commit = {
58
+ id,
59
+ short_id: shortId(id),
60
+ title: message.split(/\r?\n/)[0],
61
+ message,
62
+ parent_ids: parent ? [parent] : [],
63
+ created_at: new Date().toISOString(),
64
+ author_name: 'gitlab-double',
65
+ web_url: `${this.web_url}/-/commit/${id}`,
66
+ tree,
67
+ };
68
+ this.commits.set(id, commit);
69
+ return commit;
70
+ }
71
+ headSha(branch) {
72
+ return this.branches.get(branch);
73
+ }
74
+ resolveRef(ref) {
75
+ if (this.branches.has(ref))
76
+ return this.branches.get(ref);
77
+ if (this.tags.has(ref))
78
+ return this.tags.get(ref);
79
+ if (this.commits.has(ref))
80
+ return ref;
81
+ return null;
82
+ }
83
+ treeAt(ref) {
84
+ const sha = this.resolveRef(ref);
85
+ if (!sha)
86
+ return null;
87
+ return this.commits.get(sha).tree;
88
+ }
89
+ commit({ branch, actions, message, expectedLastCommitId }) {
90
+ const headSha = this.branches.get(branch);
91
+ if (!headSha)
92
+ throw { status: 404, body: CLIENT_ERROR_JSON(`404 Branch Not Found`) };
93
+ if (expectedLastCommitId !== undefined && expectedLastCommitId !== null && expectedLastCommitId !== headSha) {
94
+ throw {
95
+ status: 400,
96
+ body: CLIENT_ERROR_JSON(`last_commit_id (${expectedLastCommitId}) is not HEAD of ${branch} (${headSha}) — someone else committed first`),
97
+ };
98
+ }
99
+ const baseTree = this.commits.get(headSha).tree;
100
+ const newTree = new Map(baseTree);
101
+ for (const action of actions ?? []) {
102
+ const filePath = action.file_path;
103
+ const exists = newTree.has(filePath);
104
+ if (['update', 'move', 'delete'].includes(action.action) &&
105
+ action.last_commit_id !== undefined && action.last_commit_id !== null &&
106
+ action.last_commit_id !== headSha) {
107
+ throw {
108
+ status: 400,
109
+ body: CLIENT_ERROR_JSON(`last_commit_id (${action.last_commit_id}) is not HEAD of ${branch} (${headSha}) for ${filePath} — someone else committed first`),
110
+ };
111
+ }
112
+ if (action.action === 'create') {
113
+ if (exists)
114
+ throw { status: 400, body: CLIENT_ERROR_JSON(`A file with this name already exists (${filePath})`) };
115
+ newTree.set(filePath, decodeActionContent(action));
116
+ }
117
+ else if (action.action === 'update') {
118
+ if (!exists)
119
+ throw { status: 400, body: CLIENT_ERROR_JSON(`A file with this name doesn't exist (${filePath})`) };
120
+ newTree.set(filePath, decodeActionContent(action));
121
+ }
122
+ else if (action.action === 'delete') {
123
+ if (!exists)
124
+ throw { status: 400, body: CLIENT_ERROR_JSON(`A file with this name doesn't exist (${filePath})`) };
125
+ newTree.delete(filePath);
126
+ }
127
+ else if (action.action === 'move') {
128
+ if (!exists)
129
+ throw { status: 400, body: CLIENT_ERROR_JSON(`A file with this name doesn't exist (${filePath})`) };
130
+ const content = action.content !== undefined ? decodeActionContent(action) : newTree.get(filePath);
131
+ newTree.delete(filePath);
132
+ newTree.set(action.previous_path ? filePath : action.file_path, content);
133
+ }
134
+ else {
135
+ throw { status: 400, body: CLIENT_ERROR_JSON(`Unknown action "${action.action}"`) };
136
+ }
137
+ }
138
+ const commit = this.#newCommit({ tree: newTree, parent: headSha, message });
139
+ this.branches.set(branch, commit.id);
140
+ this.#startPipeline({ ref: branch, sha: commit.id });
141
+ return commit;
142
+ }
143
+ // a pipeline per commit: build, test and deploy, one after the other, JOB_MS each; the clock is the wall clock
144
+ #startPipeline({ ref, sha }) {
145
+ const failing = pipelineControl.failNext > 0 || /fail/i.test(this.name);
146
+ if (pipelineControl.failNext > 0)
147
+ pipelineControl.failNext--;
148
+ this.pipelines.push({ id: this.nextPipelineId++, ref, sha, createdAt: Date.now(), attemptAt: Date.now(), willFail: failing });
149
+ }
150
+ retryPipeline(id) {
151
+ const pipeline = this.pipelines.find((p) => p.id === Number(id));
152
+ if (!pipeline)
153
+ return null;
154
+ pipeline.attemptAt = Date.now();
155
+ pipeline.willFail = false;
156
+ return pipeline;
157
+ }
158
+ cancelPipeline(id) {
159
+ const pipeline = this.pipelines.find((p) => p.id === Number(id));
160
+ if (!pipeline)
161
+ return null;
162
+ pipeline.canceledAt ??= Date.now();
163
+ return pipeline;
164
+ }
165
+ pipelineView(pipeline, now = Date.now()) {
166
+ const jobs = PIPELINE_STAGES.map((stage, index) => {
167
+ const start = pipeline.attemptAt + index * JOB_MS;
168
+ const end = start + JOB_MS;
169
+ const failsHere = pipeline.willFail && stage === 'test';
170
+ const earlierFailed = pipeline.willFail && index > PIPELINE_STAGES.indexOf('test') && now >= pipeline.attemptAt + (PIPELINE_STAGES.indexOf('test') + 1) * JOB_MS;
171
+ let status = 'created';
172
+ if (pipeline.canceledAt && !(now >= end && end <= pipeline.canceledAt))
173
+ status = 'canceled';
174
+ else if (earlierFailed)
175
+ status = 'skipped';
176
+ else if (now >= end)
177
+ status = failsHere ? 'failed' : 'success';
178
+ else if (now >= start)
179
+ status = 'running';
180
+ return {
181
+ id: pipeline.id * 100 + index,
182
+ name: stage,
183
+ stage,
184
+ status,
185
+ duration: status === 'created' || status === 'skipped' ? null : Math.max(1, Math.round((Math.min(now, end) - start) / 1000)),
186
+ web_url: `${this.web_url}/-/jobs/${pipeline.id * 100 + index}`,
187
+ };
188
+ });
189
+ const status = jobs.some((j) => j.status === 'canceled') ? 'canceled'
190
+ : jobs.some((j) => j.status === 'failed') ? 'failed'
191
+ : jobs.every((j) => j.status === 'success') ? 'success'
192
+ : jobs.some((j) => j.status === 'running') ? 'running' : 'pending';
193
+ return {
194
+ id: pipeline.id, status, ref: pipeline.ref, sha: pipeline.sha,
195
+ created_at: new Date(pipeline.createdAt).toISOString(),
196
+ web_url: `${this.web_url}/-/pipelines/${pipeline.id}`,
197
+ jobs,
198
+ };
199
+ }
200
+ /** Every commit reachable from `sha` (itself included). */
201
+ ancestorsOf(sha) { return this.#ancestorsOf(sha); }
202
+ #ancestorsOf(sha) {
203
+ const seen = new Set();
204
+ const queue = [sha];
205
+ while (queue.length) {
206
+ const next = queue.shift();
207
+ if (!next || seen.has(next))
208
+ continue;
209
+ seen.add(next);
210
+ queue.push(...(this.commits.get(next)?.parent_ids ?? []));
211
+ }
212
+ return seen;
213
+ }
214
+ /**
215
+ * Merges the commit `sourceSha` into `targetBranch` the way a merge does: what the source changed since the two last had a
216
+ * commit in common is applied to the target, and what only the target has stays. (A change both made goes to the source's side:
217
+ * there are no conflicts here.)
218
+ */
219
+ mergeInto(targetBranch, sourceSha, message, { squash = false } = {}) {
220
+ const targetSha = this.branches.get(targetBranch);
221
+ const inTarget = this.#ancestorsOf(targetSha);
222
+ if (inTarget.has(sourceSha))
223
+ return this.commits.get(targetSha); // nothing new in the source
224
+ // the nearest commit of the source's history that is also in the target's
225
+ let base = null;
226
+ const queue = [sourceSha];
227
+ const seen = new Set();
228
+ while (queue.length) {
229
+ const next = queue.shift();
230
+ if (seen.has(next))
231
+ continue;
232
+ seen.add(next);
233
+ if (inTarget.has(next)) {
234
+ base = next;
235
+ break;
236
+ }
237
+ queue.push(...(this.commits.get(next)?.parent_ids ?? []));
238
+ }
239
+ const baseTree = base ? this.commits.get(base).tree : new Map();
240
+ const sourceTree = this.commits.get(sourceSha).tree;
241
+ const tree = new Map(this.commits.get(targetSha).tree);
242
+ for (const [filePath, content] of sourceTree) {
243
+ if (!baseTree.has(filePath) || !baseTree.get(filePath).equals(content))
244
+ tree.set(filePath, content);
245
+ }
246
+ for (const filePath of baseTree.keys())
247
+ if (!sourceTree.has(filePath))
248
+ tree.delete(filePath);
249
+ const commit = this.#newCommit({ tree, parent: targetSha, message: message ?? `Merge ${sourceSha.slice(0, 8)} into ${targetBranch}` });
250
+ // a squash leaves one commit whose only parent is the target
251
+ if (!squash)
252
+ commit.parent_ids.push(sourceSha);
253
+ this.branches.set(targetBranch, commit.id);
254
+ return commit;
255
+ }
256
+ /** The files the source brought since it left the target: each as GitLab's `changes` has it. */
257
+ changesOf(targetBranch, sourceSha) {
258
+ const targetSha = this.branches.get(targetBranch);
259
+ const inTarget = this.#ancestorsOf(targetSha);
260
+ let base = null;
261
+ const queue = [sourceSha];
262
+ const seen = new Set();
263
+ while (queue.length) {
264
+ const next = queue.shift();
265
+ if (seen.has(next))
266
+ continue;
267
+ seen.add(next);
268
+ if (inTarget.has(next)) {
269
+ base = next;
270
+ break;
271
+ }
272
+ queue.push(...(this.commits.get(next)?.parent_ids ?? []));
273
+ }
274
+ const baseTree = base ? this.commits.get(base).tree : new Map();
275
+ const sourceTree = this.commits.get(sourceSha).tree;
276
+ const out = [];
277
+ for (const filePath of [...new Set([...baseTree.keys(), ...sourceTree.keys()])].sort()) {
278
+ const [before, after] = [baseTree.get(filePath), sourceTree.get(filePath)];
279
+ if (before && after && before.equals(after))
280
+ continue;
281
+ out.push({
282
+ old_path: filePath, new_path: filePath, new_file: !before, deleted_file: !after, renamed_file: false,
283
+ diff: unifiedDiff(before?.toString('utf8') ?? '', after?.toString('utf8') ?? ''),
284
+ });
285
+ }
286
+ return out;
287
+ }
288
+ /** Whether merging `sourceSha` into `targetBranch` has a conflict: a file both sides changed since their common commit, differently. */
289
+ conflictsWith(targetBranch, sourceSha) {
290
+ const targetSha = this.branches.get(targetBranch);
291
+ if (!targetSha || !sourceSha)
292
+ return false;
293
+ const inTarget = this.#ancestorsOf(targetSha);
294
+ if (inTarget.has(sourceSha))
295
+ return false;
296
+ let base = null;
297
+ const queue = [sourceSha];
298
+ const seen = new Set();
299
+ while (queue.length) {
300
+ const next = queue.shift();
301
+ if (seen.has(next))
302
+ continue;
303
+ seen.add(next);
304
+ if (inTarget.has(next)) {
305
+ base = next;
306
+ break;
307
+ }
308
+ queue.push(...(this.commits.get(next)?.parent_ids ?? []));
309
+ }
310
+ const baseTree = base ? this.commits.get(base).tree : new Map();
311
+ const sourceTree = this.commits.get(sourceSha).tree;
312
+ const targetTree = this.commits.get(targetSha).tree;
313
+ const changed = (tree, filePath) => {
314
+ const before = baseTree.get(filePath);
315
+ const after = tree.get(filePath);
316
+ return !(before === undefined ? after === undefined : after !== undefined && before.equals(after));
317
+ };
318
+ for (const filePath of new Set([...sourceTree.keys(), ...targetTree.keys()])) {
319
+ if (!changed(sourceTree, filePath) || !changed(targetTree, filePath))
320
+ continue;
321
+ const [a, b] = [sourceTree.get(filePath), targetTree.get(filePath)];
322
+ if (!(a !== undefined && b !== undefined && a.equals(b)) && !(a === undefined && b === undefined))
323
+ return true;
324
+ }
325
+ return false;
326
+ }
327
+ createBranch(name, ref) {
328
+ if (this.branches.has(name)) {
329
+ throw { status: 400, body: CLIENT_ERROR_JSON(`Branch already exists`) };
330
+ }
331
+ const sha = this.resolveRef(ref);
332
+ if (!sha)
333
+ throw { status: 404, body: CLIENT_ERROR_JSON(`404 Ref Not Found`) };
334
+ this.branches.set(name, sha);
335
+ return { name, commit: this.commits.get(sha) };
336
+ }
337
+ }
338
+ const decodeActionContent = (action) => {
339
+ if (action.encoding === 'base64')
340
+ return Buffer.from(action.content ?? '', 'base64');
341
+ return Buffer.from(action.content ?? '', 'utf8');
342
+ };
343
+ class GitLabDoubleState {
344
+ constructor(webBase) {
345
+ this.webBase = webBase;
346
+ this.groups = new Map();
347
+ this.projects = new Map();
348
+ this.nextGroupId = 1;
349
+ this.nextProjectId = 1;
350
+ this.requestLog = [];
351
+ this.graphqlAnswer = null;
352
+ }
353
+ createGroup({ name, path, parent_id }) {
354
+ const id = this.nextGroupId++;
355
+ const parent = parent_id ? this.groups.get(parent_id) : null;
356
+ const groupPath = path || slugify(name);
357
+ const full_path = parent ? `${parent.full_path}/${groupPath}` : groupPath;
358
+ const group = {
359
+ id, name, path: groupPath, full_path,
360
+ parent_id: parent_id ?? null,
361
+ web_url: `${this.webBase}/${full_path}`,
362
+ members: [],
363
+ };
364
+ this.groups.set(id, group);
365
+ return group;
366
+ }
367
+ createProject({ name, namespace_id, topics, default_branch, initialize_with_readme, description }) {
368
+ const namespaceGroup = namespace_id === undefined || namespace_id === null
369
+ ? ([...this.groups.values()].find((g) => g.path === 'root') ?? this.createGroup({ name: 'root' }))
370
+ : this.groups.get(namespace_id);
371
+ if (!namespaceGroup)
372
+ throw { status: 404, body: CLIENT_ERROR_JSON('404 Group Not Found') };
373
+ const id = this.nextProjectId++;
374
+ const project = new ProjectState({
375
+ id, name,
376
+ namespace: { id: namespaceGroup.id, full_path: namespaceGroup.full_path, parent_id: namespaceGroup.parent_id },
377
+ topics, defaultBranch: default_branch, initializeWithReadme: initialize_with_readme,
378
+ webBase: this.webBase, description,
379
+ });
380
+ this.projects.set(id, project);
381
+ return project;
382
+ }
383
+ reset() {
384
+ this.groups.clear();
385
+ this.projects.clear();
386
+ this.nextGroupId = 1;
387
+ this.nextProjectId = 1;
388
+ this.requestLog = [];
389
+ this.graphqlAnswer = null;
390
+ }
391
+ }
392
+ const projectJson = (p) => ({
393
+ id: p.id,
394
+ name: p.name,
395
+ path: p.path,
396
+ path_with_namespace: p.path_with_namespace,
397
+ namespace: { id: p.namespace.id, full_path: p.namespace.full_path, parent_id: p.namespace.parent_id ?? null },
398
+ topics: p.topics,
399
+ tag_list: p.topics,
400
+ shared_runners_enabled: p.shared_runners_enabled ?? true,
401
+ builds_access_level: p.builds_access_level ?? 'enabled',
402
+ default_branch: p.default_branch,
403
+ archived: p.archived,
404
+ marked_for_deletion_at: p.marked_for_deletion_at,
405
+ ...(p.marked_for_deletion_on ? { marked_for_deletion_on: p.marked_for_deletion_on } : {}),
406
+ ...(p.created_at ? { created_at: p.created_at } : {}),
407
+ web_url: p.web_url,
408
+ description: p.description ?? '',
409
+ });
410
+ const mrJson = (project, mr) => ({
411
+ id: mr.iid,
412
+ iid: mr.iid,
413
+ project_id: project.id,
414
+ title: mr.title,
415
+ source_branch: mr.source_branch,
416
+ target_branch: mr.target_branch,
417
+ state: mr.state,
418
+ merge_status: mr.state === 'merged' ? 'merged' : 'can_be_merged',
419
+ detailed_merge_status: mr.detailed_merge_status,
420
+ has_conflicts: mr.state === 'opened' && project.conflictsWith(mr.target_branch, project.branches.get(mr.source_branch) ?? mr.sha),
421
+ web_url: `${project.web_url}/-/merge_requests/${mr.iid}`,
422
+ sha: mr.sha,
423
+ description: mr.description ?? '',
424
+ author: { id: 1, username: mr.author ?? 'dev', name: mr.author ?? 'dev' },
425
+ labels: mr.labels ?? [],
426
+ reviewers: (mr.reviewers ?? []).map((username) => ({ username })),
427
+ assignees: [],
428
+ created_at: mr.created_at ?? new Date(0).toISOString(),
429
+ updated_at: mr.updated_at ?? mr.created_at ?? new Date(0).toISOString(),
430
+ merged_at: mr.merged_at ?? null,
431
+ user_notes_count: (mr.discussions ?? []).reduce((sum, d) => sum + d.notes.filter((n) => !n.system).length, 0),
432
+ diff_refs: { base_sha: mr.sha, start_sha: mr.sha, head_sha: mr.sha },
433
+ });
434
+ const fileJson = (project, branchOrRef, filePath, sha, content) => ({
435
+ file_name: filePath.split('/').pop(),
436
+ file_path: filePath,
437
+ size: content.length,
438
+ encoding: 'base64',
439
+ content_sha256: sha1For(content),
440
+ ref: branchOrRef,
441
+ blob_id: sha1For(`${filePath}@${sha}`),
442
+ commit_id: sha,
443
+ last_commit_id: sha,
444
+ content: content.toString('base64'),
445
+ });
446
+ /** How git over HTTP (git-http.js) reads and writes a project's commits, branches and tags. */
447
+ const gitlabAdapter = (project) => ({
448
+ defaultBranch: () => project.default_branch,
449
+ commits: () => [...project.commits.values()].map((c) => ({
450
+ id: c.id, parents: c.parent_ids, message: c.message, date: c.created_at, authorName: c.author_name, authorEmail: 'gitlab-double@example.com', files: c.tree,
451
+ })),
452
+ heads: () => new Map(project.branches),
453
+ tags: () => new Map(project.tags),
454
+ addCommit: ({ id, parents, message, date, authorName, files }) => {
455
+ project.commits.set(id, {
456
+ id, short_id: shortId(id), title: message.split(/\r?\n/)[0], message, parent_ids: parents, created_at: date,
457
+ author_name: authorName, web_url: `${project.web_url}/-/commit/${id}`, tree: files,
458
+ });
459
+ return id;
460
+ },
461
+ setHead: (name, id) => (id ? project.branches.set(name, id) : project.branches.delete(name)),
462
+ setTag: (name, id) => (id ? project.tags.set(name, id) : project.tags.delete(name)),
463
+ });
464
+ export function createGitlabDoubleApp(webBase = 'http://gitlab-double.local') {
465
+ const state = new GitLabDoubleState(webBase);
466
+ const app = express();
467
+ // `git clone/push` against `<web url>/<group>/<project>.git`: served before anything reads a body
468
+ const gitHttp = createGitHttp({
469
+ find: (fullPath) => [...state.projects.values()].find((p) => p.path_with_namespace === fullPath),
470
+ adapterOf: gitlabAdapter,
471
+ });
472
+ app.use(gitHttp.router);
473
+ app.use(express.json({ limit: '20mb' }));
474
+ app.use((req, res, next) => {
475
+ state.requestLog.push({
476
+ method: req.method,
477
+ path: req.originalUrl.replace(/^\/api\/v4\//, ''),
478
+ body: req.body && Object.keys(req.body).length > 0 ? req.body : undefined,
479
+ });
480
+ next();
481
+ });
482
+ const router = express.Router();
483
+ const sendError = (res, status, message) => res.status(status).json(CLIENT_ERROR_JSON(message));
484
+ const projectOr404 = (req, res) => {
485
+ const key = String(req.params.id);
486
+ // GitLab takes either the numeric id or the URL-encoded `path_with_namespace`
487
+ const project = /^\d+$/.test(key)
488
+ ? state.projects.get(Number(key))
489
+ : [...state.projects.values()].find((p) => p.path_with_namespace === key);
490
+ if (!project) {
491
+ sendError(res, 404, '404 Project Not Found');
492
+ return null;
493
+ }
494
+ return project;
495
+ };
496
+ const groupOr404 = (req, res) => {
497
+ const key = String(req.params.id);
498
+ // by numeric id, or by (URL-decoded) full path, as GitLab takes either
499
+ const group = /^\d+$/.test(key) ? state.groups.get(Number(key)) : [...state.groups.values()].find((g) => g.full_path === key);
500
+ if (!group) {
501
+ sendError(res, 404, '404 Group Not Found');
502
+ return null;
503
+ }
504
+ return group;
505
+ };
506
+ router.post('/groups', (req, res) => {
507
+ const group = state.createGroup(req.body ?? {});
508
+ res.status(201).json(group);
509
+ });
510
+ router.get('/groups/:id', (req, res) => {
511
+ const group = groupOr404(req, res);
512
+ if (group)
513
+ res.status(200).json(group);
514
+ });
515
+ router.put('/groups/:id', (req, res) => {
516
+ const group = groupOr404(req, res);
517
+ if (!group)
518
+ return;
519
+ if (req.body?.name !== undefined)
520
+ group.name = req.body.name;
521
+ res.status(200).json(group);
522
+ });
523
+ router.delete('/groups/:id', (req, res) => {
524
+ const group = groupOr404(req, res);
525
+ if (!group)
526
+ return;
527
+ // a group goes with its subgroups, and everything in them
528
+ const doomed = new Set([group.id]);
529
+ for (let grew = true; grew;) {
530
+ grew = false;
531
+ for (const other of state.groups.values()) {
532
+ if (!doomed.has(other.id) && doomed.has(other.parent_id)) {
533
+ doomed.add(other.id);
534
+ grew = true;
535
+ }
536
+ }
537
+ }
538
+ for (const id of doomed)
539
+ state.groups.delete(id);
540
+ for (const [id, project] of state.projects) {
541
+ if (doomed.has(project.namespace.id))
542
+ state.projects.delete(id);
543
+ }
544
+ res.status(202).json({ message: '202 Accepted' });
545
+ });
546
+ // who the token is: the one user of the double (the token is not looked at)
547
+ router.get('/user', (_req, res) => res.json({ id: 1, username: 'dev', name: 'Dev User', avatar_url: '' }));
548
+ router.get('/groups', (req, res) => {
549
+ const minAccessLevel = Number(req.query.min_access_level ?? 0);
550
+ const perPage = Number(req.query.per_page ?? 20);
551
+ const page = Number(req.query.page ?? 1);
552
+ void minAccessLevel;
553
+ const all = [...state.groups.values()];
554
+ const start = (page - 1) * perPage;
555
+ res.status(200).json(all.slice(start, start + perPage));
556
+ });
557
+ router.get('/groups/:id/members/all', (req, res) => {
558
+ const group = groupOr404(req, res);
559
+ if (group)
560
+ res.status(200).json(group.members);
561
+ });
562
+ router.post('/projects', (req, res) => {
563
+ try {
564
+ const project = state.createProject(req.body ?? {});
565
+ res.status(201).json(projectJson(project));
566
+ }
567
+ catch (err) {
568
+ res.status(err.status ?? 400).json(err.body ?? CLIENT_ERROR_JSON('create project failed'));
569
+ }
570
+ });
571
+ router.get('/projects/:id', (req, res) => {
572
+ const project = projectOr404(req, res);
573
+ if (project)
574
+ res.status(200).json(projectJson(project));
575
+ });
576
+ router.put('/projects/:id', (req, res) => {
577
+ const project = projectOr404(req, res);
578
+ if (!project)
579
+ return;
580
+ if (req.body?.name !== undefined)
581
+ project.name = req.body.name;
582
+ if (req.body?.default_branch !== undefined)
583
+ project.default_branch = req.body.default_branch;
584
+ if (Array.isArray(req.body?.topics)) {
585
+ project.topics = [...req.body.topics];
586
+ project.tag_list = project.topics;
587
+ }
588
+ if (req.body?.shared_runners_enabled !== undefined)
589
+ project.shared_runners_enabled = Boolean(req.body.shared_runners_enabled);
590
+ if (req.body?.builds_access_level !== undefined)
591
+ project.builds_access_level = req.body.builds_access_level;
592
+ res.status(200).json(projectJson(project));
593
+ });
594
+ router.delete('/projects/:id', (req, res) => {
595
+ const project = projectOr404(req, res);
596
+ if (!project)
597
+ return;
598
+ state.projects.delete(project.id);
599
+ res.status(202).json({ message: 'Accepted' });
600
+ });
601
+ router.get('/projects/:id/members/all', (req, res) => {
602
+ const project = projectOr404(req, res);
603
+ if (project)
604
+ res.status(200).json(project.members);
605
+ });
606
+ router.get('/projects', (req, res) => {
607
+ const perPageRaw = req.query.per_page;
608
+ const perPage = perPageRaw !== undefined ? Number(perPageRaw) : null;
609
+ const page = Number(req.query.page ?? 1);
610
+ let results = [...state.projects.values()];
611
+ if (req.query.topics) {
612
+ const wanted = String(req.query.topics).split(',').map((t) => t.trim()).filter(Boolean);
613
+ results = results.filter((p) => wanted.every((t) => p.topics.includes(t)));
614
+ }
615
+ if (req.query.topic) {
616
+ results = results.filter((p) => p.topics.includes(String(req.query.topic)));
617
+ }
618
+ results = results.filter((p) => !p.archived);
619
+ if (perPage === null) {
620
+ res.status(200).json(results.map(projectJson));
621
+ return;
622
+ }
623
+ const start = (page - 1) * perPage;
624
+ res.status(200).json(results.slice(start, start + perPage).map(projectJson));
625
+ });
626
+ router.get('/projects/:id/repository/files/:path', (req, res) => {
627
+ const project = projectOr404(req, res);
628
+ if (!project)
629
+ return;
630
+ const filePath = decodeURIComponent(req.params.path);
631
+ const ref = req.query.ref ?? project.default_branch;
632
+ const sha = project.resolveRef(ref);
633
+ if (!sha)
634
+ return sendError(res, 404, '404 Commit Not Found');
635
+ const tree = project.commits.get(sha).tree;
636
+ if (!tree.has(filePath))
637
+ return sendError(res, 404, '404 File Not Found');
638
+ res.status(200).json(fileJson(project, ref, filePath, sha, tree.get(filePath)));
639
+ });
640
+ router.get('/projects/:id/repository/files/:path/raw', (req, res) => {
641
+ const project = projectOr404(req, res);
642
+ if (!project)
643
+ return;
644
+ const filePath = decodeURIComponent(req.params.path);
645
+ const sha = project.resolveRef(req.query.ref ?? project.default_branch) ?? project.tags.get(String(req.query.ref));
646
+ if (!sha)
647
+ return sendError(res, 404, '404 Commit Not Found');
648
+ const tree = project.commits.get(sha).tree;
649
+ if (!tree.has(filePath))
650
+ return sendError(res, 404, '404 File Not Found');
651
+ res.status(200).set('Content-Type', 'application/octet-stream').send(tree.get(filePath));
652
+ });
653
+ router.post('/projects/:id/repository/files/:path', (req, res) => {
654
+ const project = projectOr404(req, res);
655
+ if (!project)
656
+ return;
657
+ const filePath = decodeURIComponent(req.params.path);
658
+ const { branch, content, commit_message, encoding } = req.body ?? {};
659
+ try {
660
+ const commit = project.commit({
661
+ branch,
662
+ actions: [{ action: 'create', file_path: filePath, content, encoding }],
663
+ message: commit_message ?? `Added ${filePath}`,
664
+ });
665
+ res.status(201).json({ file_path: filePath, branch, ...fileJson(project, branch, filePath, commit.id, project.commits.get(commit.id).tree.get(filePath)) });
666
+ }
667
+ catch (err) {
668
+ res.status(err.status ?? 400).json(err.body ?? CLIENT_ERROR_JSON('create file failed'));
669
+ }
670
+ });
671
+ router.put('/projects/:id/repository/files/:path', (req, res) => {
672
+ const project = projectOr404(req, res);
673
+ if (!project)
674
+ return;
675
+ const filePath = decodeURIComponent(req.params.path);
676
+ const { branch, content, commit_message, encoding, last_commit_id } = req.body ?? {};
677
+ try {
678
+ const commit = project.commit({
679
+ branch,
680
+ actions: [{ action: 'update', file_path: filePath, content, encoding }],
681
+ message: commit_message ?? `Updated ${filePath}`,
682
+ expectedLastCommitId: last_commit_id,
683
+ });
684
+ res.status(200).json({ file_path: filePath, branch, ...fileJson(project, branch, filePath, commit.id, project.commits.get(commit.id).tree.get(filePath)) });
685
+ }
686
+ catch (err) {
687
+ res.status(err.status ?? 400).json(err.body ?? CLIENT_ERROR_JSON('update file failed'));
688
+ }
689
+ });
690
+ router.post('/projects/:id/repository/commits', (req, res) => {
691
+ const project = projectOr404(req, res);
692
+ if (!project)
693
+ return;
694
+ const { branch, commit_message, actions, last_commit_id } = req.body ?? {};
695
+ try {
696
+ const commit = project.commit({ branch, actions, message: commit_message, expectedLastCommitId: last_commit_id });
697
+ res.status(201).json({
698
+ id: commit.id, short_id: commit.short_id, title: commit.title, message: commit.message,
699
+ created_at: commit.created_at, web_url: commit.web_url, parent_ids: commit.parent_ids,
700
+ });
701
+ }
702
+ catch (err) {
703
+ res.status(err.status ?? 400).json(err.body ?? CLIENT_ERROR_JSON('commit failed'));
704
+ }
705
+ });
706
+ router.get('/projects/:id/repository/commits', (req, res) => {
707
+ const project = projectOr404(req, res);
708
+ if (!project)
709
+ return;
710
+ const refName = req.query.ref_name ?? project.default_branch;
711
+ const perPage = Number(req.query.per_page ?? 20);
712
+ let sha = project.resolveRef(refName);
713
+ const out = [];
714
+ while (sha && out.length < perPage) {
715
+ const commit = project.commits.get(sha);
716
+ out.push(commit);
717
+ sha = commit.parent_ids[0] ?? null;
718
+ }
719
+ res.status(200).json(out.map((c) => ({
720
+ id: c.id, short_id: c.short_id, title: c.title, message: c.message,
721
+ author_name: c.author_name, created_at: c.created_at, web_url: c.web_url,
722
+ })));
723
+ });
724
+ router.get('/projects/:id/repository/compare', (req, res) => {
725
+ const project = projectOr404(req, res);
726
+ if (!project)
727
+ return;
728
+ const [from, to] = [project.resolveRef(req.query.from), project.resolveRef(req.query.to)];
729
+ if (!from || !to)
730
+ return sendError(res, 404, '404 Ref Not Found');
731
+ const inFrom = project.ancestorsOf(from);
732
+ const commits = [];
733
+ for (let sha = to; sha && !inFrom.has(sha); sha = project.commits.get(sha).parent_ids[0] ?? null)
734
+ commits.unshift(project.commits.get(sha));
735
+ const branch = [...project.branches.entries()].find(([, tip]) => tip === from)?.[0];
736
+ res.status(200).json({
737
+ commits: commits.map((c) => ({ id: c.id, short_id: c.short_id, title: c.title, message: c.message, author_name: c.author_name, created_at: c.created_at, web_url: c.web_url })),
738
+ diffs: branch ? project.changesOf(branch, to) : [],
739
+ });
740
+ });
741
+ router.post('/projects/:id/repository/commits/:sha/revert', (req, res) => {
742
+ const project = projectOr404(req, res);
743
+ if (!project)
744
+ return;
745
+ const target = project.commits.get(req.params.sha);
746
+ if (!target)
747
+ return sendError(res, 404, '404 Commit Not Found');
748
+ const { branch, dry_run } = req.body ?? {};
749
+ if (dry_run) {
750
+ res.status(200).json({ dry_run: 'success' });
751
+ return;
752
+ }
753
+ const parentSha = target.parent_ids[0] ?? null;
754
+ const parentTree = parentSha ? project.commits.get(parentSha).tree : new Map();
755
+ const headSha = project.branches.get(branch);
756
+ if (!headSha)
757
+ return sendError(res, 404, '404 Branch Not Found');
758
+ const headTree = project.commits.get(headSha).tree;
759
+ const revertedTree = new Map(headTree);
760
+ for (const [path, content] of target.tree) {
761
+ if (parentTree.has(path))
762
+ revertedTree.set(path, parentTree.get(path));
763
+ else
764
+ revertedTree.delete(path);
765
+ }
766
+ for (const path of parentTree.keys()) {
767
+ if (!target.tree.has(path) && !revertedTree.has(path))
768
+ revertedTree.set(path, parentTree.get(path));
769
+ }
770
+ const seq = project.commits.size + 1;
771
+ const id = sha1For(`${project.id}|revert|${seq}`);
772
+ const revertCommit = {
773
+ id, short_id: shortId(id), title: `Revert "${target.title}"`, message: `Revert "${target.title}"`,
774
+ parent_ids: [headSha], created_at: new Date().toISOString(), author_name: 'gitlab-double',
775
+ web_url: `${project.web_url}/-/commit/${id}`, tree: revertedTree,
776
+ };
777
+ project.commits.set(id, revertCommit);
778
+ project.branches.set(branch, id);
779
+ res.status(200).json({ id, short_id: shortId(id) });
780
+ });
781
+ router.get('/projects/:id/repository/tree', (req, res) => {
782
+ const project = projectOr404(req, res);
783
+ if (!project)
784
+ return;
785
+ const ref = req.query.ref || project.default_branch;
786
+ const tree = project.treeAt(ref);
787
+ if (!tree)
788
+ return sendError(res, 404, '404 Tree Not Found');
789
+ const prefix = req.query.path ? `${req.query.path}/` : '';
790
+ const perPage = Number(req.query.per_page ?? 100);
791
+ const page = Number(req.query.page ?? 1);
792
+ const entries = [...tree.keys()]
793
+ .filter((p) => p.startsWith(prefix))
794
+ .sort()
795
+ .slice((page - 1) * perPage, page * perPage)
796
+ .map((p) => ({
797
+ id: sha1For(`${project.id}:${p}`),
798
+ name: p.split('/').pop(),
799
+ type: 'blob',
800
+ path: p,
801
+ mode: '100644',
802
+ }));
803
+ res.status(200).json(entries);
804
+ });
805
+ router.get('/projects/:id/repository/archive.zip', async (req, res) => {
806
+ const project = projectOr404(req, res);
807
+ if (!project)
808
+ return;
809
+ const ref = req.query.sha || project.default_branch;
810
+ const tree = project.treeAt(ref);
811
+ if (!tree)
812
+ return sendError(res, 404, '404 Tree Not Found');
813
+ const sha = project.resolveRef(ref);
814
+ const rootFolder = `${project.path}-${shortId(sha)}`;
815
+ const zip = new JSZip();
816
+ for (const [filePath, content] of tree) {
817
+ zip.file(`${rootFolder}/${filePath}`, content);
818
+ }
819
+ const buffer = await zip.generateAsync({ type: 'nodebuffer' });
820
+ res.status(200).set('Content-Type', 'application/zip').send(buffer);
821
+ });
822
+ router.get('/projects/:id/repository/branches', (req, res) => {
823
+ const project = projectOr404(req, res);
824
+ if (!project)
825
+ return;
826
+ res.json([...project.branches.keys()].map((name) => ({ name })));
827
+ });
828
+ router.post('/projects/:id/repository/branches', (req, res) => {
829
+ const project = projectOr404(req, res);
830
+ if (!project)
831
+ return;
832
+ const { branch, ref } = req.body ?? {};
833
+ try {
834
+ const created = project.createBranch(branch, ref);
835
+ res.status(201).json({
836
+ name: created.name,
837
+ commit: { id: created.commit.id, short_id: created.commit.short_id },
838
+ default: false, protected: false, merged: false,
839
+ web_url: `${project.web_url}/-/tree/${created.name}`,
840
+ });
841
+ }
842
+ catch (err) {
843
+ res.status(err.status ?? 400).json(err.body ?? CLIENT_ERROR_JSON('create branch failed'));
844
+ }
845
+ });
846
+ router.delete('/projects/:id/repository/branches/:name', (req, res) => {
847
+ const project = projectOr404(req, res);
848
+ if (!project)
849
+ return;
850
+ if (!project.branches.has(req.params.name))
851
+ return sendError(res, 404, '404 Branch Not Found');
852
+ project.branches.delete(req.params.name);
853
+ res.status(204).send();
854
+ });
855
+ router.get('/projects/:id/repository/branches/:name', (req, res) => {
856
+ const project = projectOr404(req, res);
857
+ if (!project)
858
+ return;
859
+ const sha = project.branches.get(req.params.name);
860
+ if (!sha)
861
+ return sendError(res, 404, '404 Branch Not Found');
862
+ const commit = project.commits.get(sha);
863
+ res.status(200).json({
864
+ name: req.params.name, commit: { id: commit.id, short_id: commit.short_id, title: commit.title },
865
+ default: req.params.name === project.default_branch, protected: false, merged: false,
866
+ web_url: `${project.web_url}/-/tree/${req.params.name}`,
867
+ });
868
+ });
869
+ router.get('/projects/:id/repository/branches', (req, res) => {
870
+ const project = projectOr404(req, res);
871
+ if (!project)
872
+ return;
873
+ const search = req.query.search ? String(req.query.search) : null;
874
+ const perPage = Number(req.query.per_page ?? 30);
875
+ let names = [...project.branches.keys()];
876
+ if (search)
877
+ names = names.filter((n) => n.includes(search));
878
+ res.status(200).json(names.slice(0, perPage).map((name) => {
879
+ const commit = project.commits.get(project.branches.get(name));
880
+ return {
881
+ name, commit: { id: commit.id, short_id: commit.short_id },
882
+ default: name === project.default_branch, protected: false, merged: false,
883
+ web_url: `${project.web_url}/-/tree/${name}`,
884
+ };
885
+ }));
886
+ });
887
+ router.get('/projects/:id/repository/compare', (req, res) => {
888
+ const project = projectOr404(req, res);
889
+ if (!project)
890
+ return;
891
+ const fromSha = project.resolveRef(req.query.from);
892
+ const toSha = project.resolveRef(req.query.to);
893
+ if (!fromSha || !toSha)
894
+ return sendError(res, 404, '404 Ref Not Found');
895
+ const commits = [];
896
+ let sha = toSha;
897
+ while (sha && sha !== fromSha && commits.length < 200) {
898
+ const commit = project.commits.get(sha);
899
+ commits.push(commit);
900
+ sha = commit.parent_ids[0] ?? null;
901
+ }
902
+ res.status(200).json({
903
+ commits: commits.reverse().map((c) => ({
904
+ id: c.id, short_id: c.short_id, title: c.title, author_name: c.author_name, created_at: c.created_at,
905
+ })),
906
+ diffs: [],
907
+ compare_same_ref: fromSha === toSha,
908
+ });
909
+ });
910
+ const createMr = (project, { title, source_branch, target_branch }, extra = {}) => {
911
+ if (!project.branches.has(source_branch))
912
+ throw { status: 400, body: CLIENT_ERROR_JSON('source branch does not exist') };
913
+ if (!project.branches.has(target_branch))
914
+ throw { status: 400, body: CLIENT_ERROR_JSON('target branch does not exist') };
915
+ const iid = project.nextMrIid++;
916
+ const now = new Date().toISOString();
917
+ const mr = {
918
+ iid, title, source_branch, target_branch,
919
+ state: 'opened', detailed_merge_status: 'mergeable',
920
+ sha: project.branches.get(source_branch),
921
+ description: extra.description ?? '', author: 'dev', labels: extra.labels ?? [], reviewers: extra.reviewers ?? [],
922
+ created_at: now, updated_at: now, merged_at: null, discussions: [], nextDiscussion: 1, nextNote: 1, approvedBy: [],
923
+ };
924
+ project.mergeRequests.set(iid, mr);
925
+ return mr;
926
+ };
927
+ router.post('/projects/:id/merge_requests', (req, res) => {
928
+ const project = projectOr404(req, res);
929
+ if (!project)
930
+ return;
931
+ const { title, source_branch, target_branch, description, labels, reviewer_ids } = req.body ?? {};
932
+ const existing = [...project.mergeRequests.values()].find((m) => m.state === 'opened' && m.source_branch === source_branch && m.target_branch === target_branch);
933
+ if (existing)
934
+ return sendError(res, 409, 'Another open merge request already exists for this source branch');
935
+ try {
936
+ const mr = createMr(project, { title, source_branch, target_branch }, {
937
+ description, labels: labels ? String(labels).split(',').filter(Boolean) : [], reviewers: (reviewer_ids ?? []).map((id) => usernameOf(id)),
938
+ });
939
+ res.status(201).json(mrJson(project, mr));
940
+ }
941
+ catch (err) {
942
+ res.status(err.status ?? 400).json(err.body ?? CLIENT_ERROR_JSON('create MR failed'));
943
+ }
944
+ });
945
+ router.get('/projects/:id/merge_requests/:iid', (req, res) => {
946
+ const project = projectOr404(req, res);
947
+ if (!project)
948
+ return;
949
+ const mr = project.mergeRequests.get(Number(req.params.iid));
950
+ if (!mr)
951
+ return sendError(res, 404, '404 Merge Request Not Found');
952
+ res.status(200).json(mrJson(project, mr));
953
+ });
954
+ router.get('/projects/:id/merge_requests', (req, res) => {
955
+ const project = projectOr404(req, res);
956
+ if (!project)
957
+ return;
958
+ const { state, target_branch, source_branch, author_username, reviewer_username, labels, search, per_page, page } = req.query;
959
+ let mrs = [...project.mergeRequests.values()].sort((a, b) => b.iid - a.iid);
960
+ if (state && state !== 'all')
961
+ mrs = mrs.filter((m) => m.state === state);
962
+ if (target_branch)
963
+ mrs = mrs.filter((m) => m.target_branch === target_branch);
964
+ if (source_branch)
965
+ mrs = mrs.filter((m) => m.source_branch === source_branch);
966
+ if (author_username)
967
+ mrs = mrs.filter((m) => (m.author ?? 'dev') === author_username);
968
+ if (reviewer_username)
969
+ mrs = mrs.filter((m) => (m.reviewers ?? []).includes(reviewer_username));
970
+ if (labels)
971
+ mrs = mrs.filter((m) => String(labels).split(',').every((l) => (m.labels ?? []).includes(l)));
972
+ if (search)
973
+ mrs = mrs.filter((m) => `${m.title} ${m.description ?? ''}`.toLowerCase().includes(String(search).toLowerCase()));
974
+ if (per_page)
975
+ mrs = mrs.slice((Number(page ?? 1) - 1) * Number(per_page), Number(page ?? 1) * Number(per_page));
976
+ res.status(200).json(mrs.map((m) => mrJson(project, m)));
977
+ });
978
+ router.put('/projects/:id/merge_requests/:iid', (req, res) => {
979
+ const project = projectOr404(req, res);
980
+ if (!project)
981
+ return;
982
+ const mr = project.mergeRequests.get(Number(req.params.iid));
983
+ if (!mr)
984
+ return sendError(res, 404, '404 Merge Request Not Found');
985
+ const body = req.body ?? {};
986
+ if (req.query.title !== undefined)
987
+ mr.title = req.query.title;
988
+ if (body.title !== undefined)
989
+ mr.title = body.title;
990
+ if (body.description !== undefined)
991
+ mr.description = body.description;
992
+ if (body.labels !== undefined)
993
+ mr.labels = String(body.labels).split(',').filter(Boolean);
994
+ if (body.reviewer_ids !== undefined)
995
+ mr.reviewers = body.reviewer_ids.map((id) => usernameOf(id));
996
+ if (req.query.state_event === 'close' || body.state_event === 'close')
997
+ mr.state = 'closed';
998
+ if (req.query.state_event === 'reopen' || body.state_event === 'reopen')
999
+ mr.state = 'opened';
1000
+ mr.updated_at = new Date().toISOString();
1001
+ res.status(200).json(mrJson(project, mr));
1002
+ });
1003
+ router.put('/projects/:id/merge_requests/:iid/merge', (req, res) => {
1004
+ const project = projectOr404(req, res);
1005
+ if (!project)
1006
+ return;
1007
+ const mr = project.mergeRequests.get(Number(req.params.iid));
1008
+ if (!mr)
1009
+ return sendError(res, 404, '404 Merge Request Not Found');
1010
+ if (mr.state !== 'opened') {
1011
+ res.status(406).json(CLIENT_ERROR_JSON('Branch cannot be merged'));
1012
+ return;
1013
+ }
1014
+ const sourceSha = project.branches.get(mr.source_branch) ?? mr.sha;
1015
+ if (project.conflictsWith(mr.target_branch, sourceSha)) {
1016
+ mr.detailed_merge_status = 'conflict';
1017
+ res.status(405).json(CLIENT_ERROR_JSON('Branch cannot be merged: conflicts'));
1018
+ return;
1019
+ }
1020
+ const squash = String(req.body?.squash ?? req.query.squash) === 'true';
1021
+ project.mergeInto(mr.target_branch, sourceSha, req.body?.squash_commit_message ?? req.body?.merge_commit_message ?? (squash ? `${mr.title} (!${mr.iid})` : `Merge branch '${mr.source_branch}' into '${mr.target_branch}'`), { squash });
1022
+ mr.state = 'merged';
1023
+ mr.merged_at = new Date().toISOString();
1024
+ mr.detailed_merge_status = 'not_open';
1025
+ if (String(req.body?.should_remove_source_branch ?? req.query.should_remove_source_branch) === 'true') {
1026
+ project.branches.delete(mr.source_branch);
1027
+ }
1028
+ res.status(200).json(mrJson(project, mr));
1029
+ });
1030
+ router.delete('/projects/:id/merge_requests/:iid', (req, res) => {
1031
+ const project = projectOr404(req, res);
1032
+ if (!project)
1033
+ return;
1034
+ if (!project.mergeRequests.has(Number(req.params.iid)))
1035
+ return sendError(res, 404, '404 Merge Request Not Found');
1036
+ project.mergeRequests.delete(Number(req.params.iid));
1037
+ res.status(204).send();
1038
+ });
1039
+ router.post('/projects/:id/repository/tags', (req, res) => {
1040
+ const project = projectOr404(req, res);
1041
+ if (!project)
1042
+ return;
1043
+ const tagName = req.query.tag_name ?? req.body?.tag_name ?? req.body?.tag;
1044
+ const ref = req.query.ref ?? req.body?.ref;
1045
+ if (project.tags.has(tagName))
1046
+ return sendError(res, 400, 'Tag already exists');
1047
+ const sha = project.resolveRef(ref);
1048
+ if (!sha)
1049
+ return sendError(res, 404, '404 Ref Not Found');
1050
+ project.tags.set(tagName, sha);
1051
+ const message = req.body?.message ?? req.query.message;
1052
+ if (message)
1053
+ project.tagMessages.set(tagName, String(message));
1054
+ res.status(201).json({ name: tagName, target: sha, message: project.tagMessages.get(tagName) ?? null, commit: { id: sha } });
1055
+ });
1056
+ router.get('/projects/:id/repository/tags', (req, res) => {
1057
+ const project = projectOr404(req, res);
1058
+ if (!project)
1059
+ return;
1060
+ const perPage = Number(req.query.per_page ?? 20);
1061
+ const page = Number(req.query.page ?? 1);
1062
+ const tags = [...project.tags].map(([name, sha]) => ({ name, target: sha, message: project.tagMessages.get(name) ?? null, commit: { id: sha, short_id: shortId(sha) } }));
1063
+ res.status(200).json(tags.slice((page - 1) * perPage, page * perPage));
1064
+ });
1065
+ router.get('/projects/:id/repository/tags/:name', (req, res) => {
1066
+ const project = projectOr404(req, res);
1067
+ if (!project)
1068
+ return;
1069
+ const sha = project.tags.get(req.params.name);
1070
+ if (!sha)
1071
+ return sendError(res, 404, '404 Tag Not Found');
1072
+ res.status(200).json({ name: req.params.name, target: sha, message: project.tagMessages.get(req.params.name) ?? null, commit: { id: sha, short_id: shortId(sha) } });
1073
+ });
1074
+ router.delete('/projects/:id/repository/tags/:name', (req, res) => {
1075
+ const project = projectOr404(req, res);
1076
+ if (!project)
1077
+ return;
1078
+ if (!project.tags.has(req.params.name))
1079
+ return sendError(res, 404, '404 Tag Not Found');
1080
+ project.tags.delete(req.params.name);
1081
+ res.status(204).send();
1082
+ });
1083
+ // ── releases ─────────────────────────────────────────────────────────────
1084
+ const releaseJson = (project, release) => ({
1085
+ tag_name: release.tag_name,
1086
+ name: release.name,
1087
+ description: release.description,
1088
+ created_at: release.created_at,
1089
+ released_at: release.created_at,
1090
+ upcoming_release: false,
1091
+ _links: { self: `${project.web_url}/-/releases/${release.tag_name}` },
1092
+ });
1093
+ router.post('/projects/:id/releases', (req, res) => {
1094
+ const project = projectOr404(req, res);
1095
+ if (!project)
1096
+ return;
1097
+ const { tag_name: tag, name, description } = req.body ?? {};
1098
+ if (!tag)
1099
+ return sendError(res, 400, 'tag_name is missing');
1100
+ if (project.releases.has(tag))
1101
+ return sendError(res, 409, 'Release already exists');
1102
+ // (real GitLab would make the tag from `ref`; the provider never asks for that)
1103
+ if (!project.tags.has(tag))
1104
+ return sendError(res, 404, '404 Tag Not Found');
1105
+ const release = { tag_name: tag, name: name || tag, description: description ?? '', created_at: new Date().toISOString() };
1106
+ project.releases.set(tag, release);
1107
+ res.status(201).json(releaseJson(project, release));
1108
+ });
1109
+ router.get('/projects/:id/releases', (req, res) => {
1110
+ const project = projectOr404(req, res);
1111
+ if (!project)
1112
+ return;
1113
+ const perPage = Number(req.query.per_page ?? 20);
1114
+ const page = Number(req.query.page ?? 1);
1115
+ const all = [...project.releases.values()].reverse().map((release) => releaseJson(project, release));
1116
+ res.status(200).json(all.slice((page - 1) * perPage, page * perPage));
1117
+ });
1118
+ router.get('/projects/:id/releases/:tag', (req, res) => {
1119
+ const project = projectOr404(req, res);
1120
+ if (!project)
1121
+ return;
1122
+ const release = project.releases.get(req.params.tag);
1123
+ if (!release)
1124
+ return sendError(res, 404, '404 Not Found');
1125
+ res.status(200).json(releaseJson(project, release));
1126
+ });
1127
+ router.put('/projects/:id/releases/:tag', (req, res) => {
1128
+ const project = projectOr404(req, res);
1129
+ if (!project)
1130
+ return;
1131
+ const release = project.releases.get(req.params.tag);
1132
+ if (!release)
1133
+ return sendError(res, 404, '404 Not Found');
1134
+ for (const key of ['name', 'description'])
1135
+ if (req.body?.[key] !== undefined)
1136
+ release[key] = req.body[key];
1137
+ res.status(200).json(releaseJson(project, release));
1138
+ });
1139
+ router.delete('/projects/:id/releases/:tag', (req, res) => {
1140
+ const project = projectOr404(req, res);
1141
+ if (!project)
1142
+ return;
1143
+ const release = project.releases.get(req.params.tag);
1144
+ if (!release)
1145
+ return sendError(res, 404, '404 Not Found');
1146
+ project.releases.delete(req.params.tag);
1147
+ res.status(200).json(releaseJson(project, release));
1148
+ });
1149
+ router.get('/projects/:id/hooks', (req, res) => {
1150
+ const project = projectOr404(req, res);
1151
+ if (project)
1152
+ res.status(200).json(project.hooks);
1153
+ });
1154
+ router.post('/projects/:id/hooks', (req, res) => {
1155
+ const project = projectOr404(req, res);
1156
+ if (!project)
1157
+ return;
1158
+ const hook = { id: project.nextHookId++, ...req.body };
1159
+ project.hooks.push(hook);
1160
+ res.status(201).json(hook);
1161
+ });
1162
+ // a project with CI/CD off answers for its pipelines as GitLab does
1163
+ router.use(['/projects/:id/pipelines', '/projects/:id/merge_requests/:iid/pipelines'], (req, res, next) => {
1164
+ const project = state.projects.get(Number(req.params.id));
1165
+ if (project?.builds_access_level === 'disabled') {
1166
+ res.status(403).json({ message: '403 Forbidden' });
1167
+ return;
1168
+ }
1169
+ next();
1170
+ });
1171
+ router.get('/projects/:id/pipelines', (req, res) => {
1172
+ const project = projectOr404(req, res);
1173
+ if (!project)
1174
+ return;
1175
+ const { ref } = req.query;
1176
+ const perPage = Number(req.query.per_page ?? 20);
1177
+ const found = project.pipelines.filter((p) => !ref || p.ref === ref).slice(-perPage).reverse();
1178
+ res.status(200).json(found.map((p) => { const { jobs, ...view } = project.pipelineView(p); return view; }));
1179
+ });
1180
+ // the pipelines of a merge request: the ones that ran for the commit at the tip of its source branch
1181
+ router.get('/projects/:id/merge_requests/:iid/pipelines', (req, res) => {
1182
+ const project = projectOr404(req, res);
1183
+ if (!project)
1184
+ return;
1185
+ const mr = project.mergeRequests.get(Number(req.params.iid));
1186
+ if (!mr)
1187
+ return sendError(res, 404, '404 Merge Request Not Found');
1188
+ const found = project.pipelines.filter((p) => p.ref === mr.source_branch).reverse();
1189
+ res.status(200).json(found.map((p) => { const { jobs, ...view } = project.pipelineView(p); return view; }));
1190
+ });
1191
+ // the one instance runner of the double: it takes the jobs of a project that has the instance runners turned on
1192
+ router.get('/projects/:id/runners', (req, res) => {
1193
+ const project = projectOr404(req, res);
1194
+ if (!project)
1195
+ return;
1196
+ res.status(200).json(project.shared_runners_enabled === false ? [] : [{ id: 1, description: 'double-runner', online: true, paused: false, is_shared: true }]);
1197
+ });
1198
+ router.get('/runners/:rid', (req, res) => {
1199
+ res.status(200).json({ id: Number(req.params.rid), description: 'double-runner', tag_list: ['deploy'], run_untagged: false });
1200
+ });
1201
+ router.get('/projects/:id/pipelines/:pid/jobs', (req, res) => {
1202
+ const project = projectOr404(req, res);
1203
+ if (!project)
1204
+ return;
1205
+ const pipeline = project.pipelines.find((p) => p.id === Number(req.params.pid));
1206
+ if (!pipeline)
1207
+ return sendError(res, 404, '404 Pipeline Not Found');
1208
+ // newest first, as GitLab lists them
1209
+ res.status(200).json([...project.pipelineView(pipeline).jobs].reverse());
1210
+ });
1211
+ router.post('/projects/:id/pipelines/:pid/retry', (req, res) => {
1212
+ const project = projectOr404(req, res);
1213
+ if (!project)
1214
+ return;
1215
+ const pipeline = project.retryPipeline(req.params.pid);
1216
+ if (!pipeline)
1217
+ return sendError(res, 404, '404 Pipeline Not Found');
1218
+ const { jobs, ...view } = project.pipelineView(pipeline);
1219
+ res.status(201).json(view);
1220
+ });
1221
+ router.post('/projects/:id/pipelines/:pid/cancel', (req, res) => {
1222
+ const project = projectOr404(req, res);
1223
+ if (!project)
1224
+ return;
1225
+ const pipeline = project.cancelPipeline(req.params.pid);
1226
+ if (!pipeline)
1227
+ return sendError(res, 404, '404 Pipeline Not Found');
1228
+ const { jobs, ...view } = project.pipelineView(pipeline);
1229
+ res.status(200).json(view);
1230
+ });
1231
+ router.post('/projects/:id/jobs/:jid/cancel', (req, res) => {
1232
+ const project = projectOr404(req, res);
1233
+ if (!project)
1234
+ return;
1235
+ const pipeline = project.cancelPipeline(Math.floor(Number(req.params.jid) / 100));
1236
+ if (!pipeline)
1237
+ return sendError(res, 404, '404 Job Not Found');
1238
+ res.status(200).json({ id: Number(req.params.jid), status: 'canceled' });
1239
+ });
1240
+ router.get('/projects/:id/jobs/:jid/trace', (req, res) => {
1241
+ const project = projectOr404(req, res);
1242
+ if (!project)
1243
+ return;
1244
+ const jid = Number(req.params.jid);
1245
+ const pipeline = project.pipelines.find((p) => p.id === Math.floor(jid / 100));
1246
+ const job = pipeline && project.pipelineView(pipeline).jobs.find((j) => j.id === jid);
1247
+ if (!job)
1248
+ return sendError(res, 404, '404 Job Not Found');
1249
+ const lines = [`Running with gitlab-runner (double) on ${project.path}`, `$ npm ci`, 'added 412 packages in 9s', `$ npm run ${job.name}`];
1250
+ if (job.status === 'failed') {
1251
+ lines.push('', ' FAIL src/__tests__/products.test.js', ' ● products › builds the feature model', '', ' expected 3 features, received 2', '', 'Tests: 1 failed, 14 passed, 15 total', 'ERROR: Job failed: exit code 1');
1252
+ }
1253
+ else if (job.status === 'success') {
1254
+ lines.push('All good', 'Job succeeded');
1255
+ }
1256
+ res.status(200).type('text/plain').send(lines.join('\n'));
1257
+ });
1258
+ // dev only: the next `count` pipelines to start fail their test job
1259
+ router.post('/__dev/fail-next-pipeline', (req, res) => {
1260
+ pipelineControl.failNext = Number(req.body?.count ?? 1);
1261
+ res.status(200).json({ failNext: pipelineControl.failNext });
1262
+ });
1263
+ router.get('/projects/:id/merge_requests/:iid/changes', (req, res) => {
1264
+ const project = projectOr404(req, res);
1265
+ if (!project)
1266
+ return;
1267
+ const mr = project.mergeRequests.get(Number(req.params.iid));
1268
+ if (!mr)
1269
+ return sendError(res, 404, '404 Merge Request Not Found');
1270
+ const sourceSha = project.branches.get(mr.source_branch) ?? mr.sha;
1271
+ res.status(200).json({ ...mrJson(project, mr), changes: project.changesOf(mr.target_branch, sourceSha) });
1272
+ });
1273
+ router.post('/projects/:id/merge_requests/:iid/notes', (req, res) => {
1274
+ const project = projectOr404(req, res);
1275
+ if (!project)
1276
+ return;
1277
+ if (!project.mergeRequests.has(Number(req.params.iid)))
1278
+ return sendError(res, 404, '404 Merge Request Not Found');
1279
+ res.status(201).json({ id: 1, body: req.body?.body ?? '' });
1280
+ });
1281
+ // discussions: a thread is a discussion; one about a line of the code has a position and can be resolved
1282
+ const mrOr404 = (req, res) => {
1283
+ const project = projectOr404(req, res);
1284
+ if (!project)
1285
+ return [];
1286
+ const mr = project.mergeRequests.get(Number(req.params.iid));
1287
+ if (!mr) {
1288
+ sendError(res, 404, '404 Merge Request Not Found');
1289
+ return [];
1290
+ }
1291
+ return [project, mr];
1292
+ };
1293
+ const noteJson = (note) => ({ ...note, author: userJson(note.author) });
1294
+ const discussionJson = (d) => ({ id: d.id, individual_note: !d.position, notes: d.notes.map(noteJson) });
1295
+ const addNote = (mr, d, body, system = false) => {
1296
+ const now = new Date().toISOString();
1297
+ const note = {
1298
+ id: mr.nextNote++, body, author: 'dev', system, created_at: now, updated_at: now,
1299
+ resolvable: Boolean(d.position), resolved: false,
1300
+ ...(d.position ? { position: d.position } : {}),
1301
+ };
1302
+ d.notes.push(note);
1303
+ mr.updated_at = now;
1304
+ return note;
1305
+ };
1306
+ router.get('/projects/:id/merge_requests/:iid/discussions', (req, res) => {
1307
+ const [, mr] = mrOr404(req, res);
1308
+ if (!mr)
1309
+ return;
1310
+ const perPage = Number(req.query.per_page ?? 20);
1311
+ const page = Number(req.query.page ?? 1);
1312
+ res.json(mr.discussions.slice((page - 1) * perPage, page * perPage).map(discussionJson));
1313
+ });
1314
+ router.get('/projects/:id/merge_requests/:iid/discussions/:did', (req, res) => {
1315
+ const [, mr] = mrOr404(req, res);
1316
+ if (!mr)
1317
+ return;
1318
+ const d = mr.discussions.find((candidate) => candidate.id === req.params.did);
1319
+ if (!d)
1320
+ return sendError(res, 404, '404 Discussion Not Found');
1321
+ res.json(discussionJson(d));
1322
+ });
1323
+ router.post('/projects/:id/merge_requests/:iid/discussions', (req, res) => {
1324
+ const [, mr] = mrOr404(req, res);
1325
+ if (!mr)
1326
+ return;
1327
+ const { body, position } = req.body ?? {};
1328
+ if (!body)
1329
+ return sendError(res, 400, 'body is missing');
1330
+ const d = { id: `d${mr.nextDiscussion++}`, notes: [], ...(position ? { position: { new_path: position.new_path, old_path: position.old_path, new_line: position.new_line, old_line: position.old_line } } : {}) };
1331
+ mr.discussions.push(d);
1332
+ addNote(mr, d, body);
1333
+ res.status(201).json(discussionJson(d));
1334
+ });
1335
+ router.post('/projects/:id/merge_requests/:iid/discussions/:did/notes', (req, res) => {
1336
+ const [, mr] = mrOr404(req, res);
1337
+ if (!mr)
1338
+ return;
1339
+ const d = mr.discussions.find((candidate) => candidate.id === req.params.did);
1340
+ if (!d)
1341
+ return sendError(res, 404, '404 Discussion Not Found');
1342
+ res.status(201).json(noteJson(addNote(mr, d, req.body?.body ?? '')));
1343
+ });
1344
+ router.put('/projects/:id/merge_requests/:iid/discussions/:did', (req, res) => {
1345
+ const [, mr] = mrOr404(req, res);
1346
+ if (!mr)
1347
+ return;
1348
+ const d = mr.discussions.find((candidate) => candidate.id === req.params.did);
1349
+ if (!d)
1350
+ return sendError(res, 404, '404 Discussion Not Found');
1351
+ for (const note of d.notes)
1352
+ if (note.resolvable)
1353
+ note.resolved = Boolean(req.body?.resolved);
1354
+ res.json(discussionJson(d));
1355
+ });
1356
+ router.get('/projects/:id/merge_requests/:iid/approvals', (req, res) => {
1357
+ const [, mr] = mrOr404(req, res);
1358
+ if (!mr)
1359
+ return;
1360
+ res.json({ approvals_required: 1, approved_by: mr.approvedBy.map((username) => ({ user: userJson(username) })) });
1361
+ });
1362
+ router.post('/projects/:id/merge_requests/:iid/approve', (req, res) => {
1363
+ const [, mr] = mrOr404(req, res);
1364
+ if (!mr)
1365
+ return;
1366
+ if (!mr.approvedBy.includes('dev'))
1367
+ mr.approvedBy.push('dev');
1368
+ res.status(201).json({ id: mr.iid });
1369
+ });
1370
+ // ── issues, labels, milestones ───────────────────────────────────────────
1371
+ const knownUsers = new Map();
1372
+ const userJson = (username) => {
1373
+ const id = 1000 + [...username].reduce((sum, ch) => sum + ch.charCodeAt(0), 0);
1374
+ knownUsers.set(id, username);
1375
+ return { id, username, name: username };
1376
+ };
1377
+ const usernameOf = (id) => knownUsers.get(id) ?? `user-${id}`;
1378
+ const issueJson = (project, issue) => ({
1379
+ id: issue.iid,
1380
+ iid: issue.iid,
1381
+ project_id: project.id,
1382
+ title: issue.title,
1383
+ description: issue.description,
1384
+ state: issue.state,
1385
+ author: userJson(issue.author),
1386
+ assignees: issue.assignees.map(userJson),
1387
+ labels: issue.labels,
1388
+ milestone: issue.milestone ? { id: issue.milestone.id, title: issue.milestone.title } : null,
1389
+ created_at: issue.created_at,
1390
+ updated_at: issue.updated_at,
1391
+ closed_at: issue.closed_at,
1392
+ web_url: `${project.web_url}/-/issues/${issue.iid}`,
1393
+ user_notes_count: issue.notes.filter((note) => !note.system).length,
1394
+ });
1395
+ const issueOr404 = (req, res) => {
1396
+ const project = projectOr404(req, res);
1397
+ if (!project)
1398
+ return [];
1399
+ const issue = project.issues.get(Number(req.params.iid));
1400
+ if (!issue) {
1401
+ sendError(res, 404, '404 Not found');
1402
+ return [];
1403
+ }
1404
+ return [project, issue];
1405
+ };
1406
+ // a user is any name: the double knows no accounts but `dev`
1407
+ router.get('/users', (req, res) => res.json(req.query.username ? [userJson(String(req.query.username))] : []));
1408
+ router.get('/projects/:id/labels', (req, res) => { const project = projectOr404(req, res); if (project)
1409
+ res.json(project.labels); });
1410
+ router.post('/projects/:id/labels', (req, res) => {
1411
+ const project = projectOr404(req, res);
1412
+ if (!project)
1413
+ return;
1414
+ const label = { id: project.labels.length + 1, name: req.body?.name, color: req.body?.color ?? '#428BCA' };
1415
+ project.labels.push(label);
1416
+ res.status(201).json(label);
1417
+ });
1418
+ router.get('/projects/:id/milestones', (req, res) => {
1419
+ const project = projectOr404(req, res);
1420
+ if (!project)
1421
+ return;
1422
+ res.json(project.milestones.filter((m) => !req.query.title || m.title === req.query.title));
1423
+ });
1424
+ router.post('/projects/:id/milestones', (req, res) => {
1425
+ const project = projectOr404(req, res);
1426
+ if (!project)
1427
+ return;
1428
+ const milestone = { id: project.milestones.length + 1, title: req.body?.title, state: 'active', due_date: null };
1429
+ project.milestones.push(milestone);
1430
+ res.status(201).json(milestone);
1431
+ });
1432
+ router.post('/projects/:id/issues', (req, res) => {
1433
+ const project = projectOr404(req, res);
1434
+ if (!project)
1435
+ return;
1436
+ const { title, description, labels, assignee_ids, milestone_id } = req.body ?? {};
1437
+ if (!title)
1438
+ return sendError(res, 400, 'title is missing');
1439
+ const now = new Date().toISOString();
1440
+ const issue = {
1441
+ iid: project.nextIssueIid++, title, description: description ?? '', state: 'opened', author: 'dev', created_at: now, updated_at: now, closed_at: null,
1442
+ labels: labels ? String(labels).split(',').filter(Boolean) : [],
1443
+ assignees: (assignee_ids ?? []).map(usernameOf),
1444
+ milestone: project.milestones.find((m) => m.id === milestone_id) ?? null,
1445
+ notes: [],
1446
+ };
1447
+ project.issues.set(issue.iid, issue);
1448
+ res.status(201).json(issueJson(project, issue));
1449
+ });
1450
+ router.get('/projects/:id/issues', (req, res) => {
1451
+ const project = projectOr404(req, res);
1452
+ if (!project)
1453
+ return;
1454
+ const { state = 'opened', author_username, assignee_username, labels, milestone, search } = req.query;
1455
+ const wanted = labels ? String(labels).split(',') : [];
1456
+ const found = [...project.issues.values()]
1457
+ .filter((i) => (state === 'all' || i.state === state)
1458
+ && (!author_username || i.author === author_username)
1459
+ && (!assignee_username || i.assignees.includes(assignee_username))
1460
+ && wanted.every((l) => i.labels.includes(l))
1461
+ && (!milestone || i.milestone?.title === milestone)
1462
+ && (!search || `${i.title} ${i.description}`.toLowerCase().includes(String(search).toLowerCase())))
1463
+ .sort((a, b) => b.iid - a.iid);
1464
+ const perPage = Number(req.query.per_page ?? 20);
1465
+ const page = Number(req.query.page ?? 1);
1466
+ res.json(found.slice((page - 1) * perPage, page * perPage).map((i) => issueJson(project, i)));
1467
+ });
1468
+ router.get('/projects/:id/issues/:iid', (req, res) => {
1469
+ const [project, issue] = issueOr404(req, res);
1470
+ if (issue)
1471
+ res.json(issueJson(project, issue));
1472
+ });
1473
+ router.put('/projects/:id/issues/:iid', (req, res) => {
1474
+ const [project, issue] = issueOr404(req, res);
1475
+ if (!issue)
1476
+ return;
1477
+ const body = req.body ?? {};
1478
+ if (body.title !== undefined)
1479
+ issue.title = body.title;
1480
+ if (body.description !== undefined)
1481
+ issue.description = body.description;
1482
+ if (body.labels !== undefined)
1483
+ issue.labels = String(body.labels).split(',').filter(Boolean);
1484
+ if (body.assignee_ids !== undefined)
1485
+ issue.assignees = body.assignee_ids.map(usernameOf);
1486
+ if (body.milestone_id !== undefined)
1487
+ issue.milestone = project.milestones.find((m) => m.id === body.milestone_id) ?? null;
1488
+ if (body.state_event === 'close') {
1489
+ issue.state = 'closed';
1490
+ issue.closed_at = new Date().toISOString();
1491
+ }
1492
+ if (body.state_event === 'reopen') {
1493
+ issue.state = 'opened';
1494
+ issue.closed_at = null;
1495
+ }
1496
+ issue.updated_at = new Date().toISOString();
1497
+ res.json(issueJson(project, issue));
1498
+ });
1499
+ router.get('/projects/:id/issues/:iid/notes', (req, res) => {
1500
+ const [, issue] = issueOr404(req, res);
1501
+ if (issue)
1502
+ res.json(issue.notes.map((note) => ({ ...note, author: userJson(note.author) })));
1503
+ });
1504
+ router.post('/projects/:id/issues/:iid/notes', (req, res) => {
1505
+ const [, issue] = issueOr404(req, res);
1506
+ if (!issue)
1507
+ return;
1508
+ // GitLab writes a note of its own when a label or the state changes: the provider has to leave those out
1509
+ const note = { id: issue.notes.length + 1, body: req.body?.body ?? '', author: 'dev', system: false, created_at: new Date().toISOString(), updated_at: new Date().toISOString() };
1510
+ issue.notes.push(note);
1511
+ res.status(201).json({ ...note, author: userJson('dev') });
1512
+ });
1513
+ // GraphQL is not served: a test says what it answers (`state.graphqlAnswer`, with `errors` as the real one does for a field it lacks)
1514
+ app.post('/api/graphql', (req, res) => {
1515
+ res.status(200).json(state.graphqlAnswer ?? { errors: [{ message: 'gitlabDouble: no answer set' }] });
1516
+ });
1517
+ app.use('/api/v4', router);
1518
+ app.use((req, res) => {
1519
+ res.status(501).json(CLIENT_ERROR_JSON(`gitlabDouble: no handler for ${req.method} ${req.originalUrl}`));
1520
+ });
1521
+ return { app, state, gitHttp };
1522
+ }
1523
+ export async function startGitlabDouble() {
1524
+ // the app has to know its own address (the web urls it gives out are what `git clone` is pointed at): it is only known once it listens
1525
+ const holder = {};
1526
+ const server = await new Promise((resolve, reject) => {
1527
+ const placeholder = express();
1528
+ placeholder.use((req, res, next) => holder.app(req, res, next));
1529
+ const s = placeholder.listen(0, '127.0.0.1', () => resolve(s));
1530
+ s.on('error', reject);
1531
+ });
1532
+ const { port } = server.address();
1533
+ const url = `http://127.0.0.1:${port}`;
1534
+ const { app, state, gitHttp } = createGitlabDoubleApp(url);
1535
+ holder.app = app;
1536
+ return {
1537
+ url,
1538
+ state,
1539
+ getProject: (id) => state.projects.get(id),
1540
+ /** @param {{ name: string, groupName?: string, topics?: string[], defaultBranch?: string, initializeWithReadme?: boolean }} options */
1541
+ seedProject: ({ name, groupName, topics, defaultBranch, initializeWithReadme = true }) => {
1542
+ const group = state.createGroup({ name: groupName ?? name });
1543
+ return state.createProject({
1544
+ name, namespace_id: group.id, topics, default_branch: defaultBranch,
1545
+ initialize_with_readme: initializeWithReadme,
1546
+ });
1547
+ },
1548
+ getLog: () => [...state.requestLog],
1549
+ clearLog: () => { state.requestLog = []; },
1550
+ reset: () => { state.reset(); gitHttp.reset(); },
1551
+ close: () => new Promise((resolve) => server.close(() => { gitHttp.dispose(); resolve(); })),
1552
+ };
1553
+ }
1554
+ //# sourceMappingURL=gitlab-double.js.map