@leed-ai/git-gateway-backend-gitlab 0.0.0-stage → 0.1.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.
@@ -0,0 +1,106 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import type { FetchLike } from '@leed-ai/git-gateway-core/smart-http/git-http-client';
3
+ import type { z } from 'zod';
4
+
5
+ import { GitLabErrorBody } from './schemas/gitlab-responses.ts';
6
+
7
+ /** A GitLab API call that answered with an error status. */
8
+ export class GitLabHttpError extends Error {
9
+ override readonly name = 'GitLabHttpError';
10
+ readonly status: number;
11
+ /** GitLab's message, flattened to text ("404 Project Not Found", "path has already been taken"). */
12
+ readonly detail: string;
13
+
14
+ constructor(status: number, detail: string, what: string) {
15
+ super(`GitLab ${what} answered ${status}: ${detail}`);
16
+ this.status = status;
17
+ this.detail = detail;
18
+ }
19
+
20
+ /** A 404 about the project itself, as opposed to a missing branch, commit, file or blob in it. */
21
+ get projectMissing(): boolean {
22
+ return this.status === 404 && /project not found/i.test(this.detail);
23
+ }
24
+ }
25
+
26
+ function flatten(body: GitLabErrorBody): string {
27
+ if (typeof body.message === 'string') return body.message;
28
+ if (body.message !== undefined) {
29
+ return Object.entries(body.message)
30
+ .map(([field, problems]) => `${field} ${problems.join(', ')}`)
31
+ .join('; ');
32
+ }
33
+ return body.error ?? 'no message';
34
+ }
35
+
36
+ /** Options of one API request. */
37
+ export interface GitLabRequest {
38
+ readonly method?: 'GET' | 'POST' | 'DELETE';
39
+ readonly query?: Readonly<Record<string, string | number | boolean>>;
40
+ readonly body?: unknown;
41
+ }
42
+
43
+ /**
44
+ * The GitLab REST API (v4) over `fetch`, authenticated with a PRIVATE-TOKEN header. Error
45
+ * statuses throw {@link GitLabHttpError}; successful JSON is parsed with a Zod schema.
46
+ */
47
+ export class GitLabApi {
48
+ readonly #base: string;
49
+ readonly #token: string;
50
+ readonly #fetch: FetchLike;
51
+
52
+ constructor(baseUrl: string, token: string, fetch: FetchLike) {
53
+ this.#base = `${baseUrl.replace(/\/$/, '')}/api/v4`;
54
+ this.#token = token;
55
+ this.#fetch = fetch;
56
+ }
57
+
58
+ /** Sends a request and returns the successful response. */
59
+ async request(path: string, options: GitLabRequest = {}): Promise<Response> {
60
+ const url = new URL(`${this.#base}${path}`);
61
+ for (const [key, value] of Object.entries(options.query ?? {})) url.searchParams.set(key, String(value));
62
+ const headers = new Headers({ 'PRIVATE-TOKEN': this.#token, Accept: 'application/json' });
63
+ if (options.body !== undefined) headers.set('Content-Type', 'application/json');
64
+ const response = await this.#fetch(
65
+ new Request(url, {
66
+ method: options.method ?? 'GET',
67
+ headers,
68
+ ...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),
69
+ }),
70
+ );
71
+ if (response.ok) return response;
72
+ const text = await response.text();
73
+ let detail = text.slice(0, 200) || response.statusText;
74
+ try {
75
+ const parsed = GitLabErrorBody.safeParse(JSON.parse(text));
76
+ if (parsed.success) detail = flatten(parsed.data);
77
+ } catch {
78
+ // Not JSON: keep the text.
79
+ }
80
+ throw new GitLabHttpError(
81
+ response.status,
82
+ detail,
83
+ `${options.method ?? 'GET'} ${path.split('?')[0] ?? path}`,
84
+ );
85
+ }
86
+
87
+ /** Sends a request and parses the JSON body with `schema`. */
88
+ async json<S extends z.ZodType>(
89
+ schema: S,
90
+ path: string,
91
+ options: GitLabRequest = {},
92
+ ): Promise<z.output<S>> {
93
+ const response = await this.request(path, options);
94
+ return schema.parse(await response.json());
95
+ }
96
+
97
+ /** Sends a GET and returns the body bytes, or null on a 404 that is not about the project. */
98
+ async bytesOrNull(path: string, query: GitLabRequest['query'] = {}): Promise<Uint8Array | null> {
99
+ try {
100
+ return new Uint8Array(await (await this.request(path, { query })).arrayBuffer());
101
+ } catch (error) {
102
+ if (error instanceof GitLabHttpError && error.status === 404 && !error.projectMissing) return null;
103
+ throw error;
104
+ }
105
+ }
106
+ }
@@ -0,0 +1,293 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { isGatewayError } from '@leed-ai/git-gateway-contract/gateway-error';
3
+ import type { Commit } from '@leed-ai/git-gateway-contract/schemas/commit';
4
+ import { FilePath, RepoName, Revision } from '@leed-ai/git-gateway-contract/schemas/names';
5
+ import { Sha } from '@leed-ai/git-gateway-contract/schemas/sha';
6
+ import { GitAccess, GitRemote } from '@leed-ai/git-gateway-contract/storage/git-remote';
7
+ import type { StorageBackend } from '@leed-ai/git-gateway-contract/storage/storage-backend';
8
+ import {
9
+ repoExists,
10
+ repoNotFound,
11
+ storageUnavailable,
12
+ } from '@leed-ai/git-gateway-contract/storage/storage-errors';
13
+ import { parseStorageInput } from '@leed-ai/git-gateway-contract/storage/storage-input';
14
+ import { StorageLogOptions, StorageRef } from '@leed-ai/git-gateway-contract/storage/storage-read';
15
+ import {
16
+ CreateStorageRepoOptions,
17
+ StorageRepoInfo,
18
+ } from '@leed-ai/git-gateway-contract/storage/storage-repo-info';
19
+ import type { StorageTreeEntry } from '@leed-ai/git-gateway-contract/storage/storage-tree-entry';
20
+ import { GitHttpClient, type FetchLike } from '@leed-ai/git-gateway-core/smart-http/git-http-client';
21
+ import { z } from 'zod';
22
+
23
+ import { GitLabApi, GitLabHttpError } from './gitlab-api.ts';
24
+ import { FrontedProjects, frontedLifecycleRefused } from './gitlab-fronted.ts';
25
+ import { readCommitsOverGit, readTreeOverGit } from './gitlab-git-reads.ts';
26
+ import { isAncestorOnGitLab } from './gitlab-merge-base.ts';
27
+ import { GitLabBackendConfig } from './schemas/gitlab-config.ts';
28
+ import { GitLabCommitSummary, GitLabGroup, GitLabProject, GitLabRef } from './schemas/gitlab-responses.ts';
29
+
30
+ /** Options of a {@link GitLabBackend}: its configuration and, optionally, how requests are sent. */
31
+ export type GitLabBackendOptions = GitLabBackendConfig & {
32
+ /** Sends API and git requests; default the global fetch. */
33
+ readonly fetch?: FetchLike;
34
+ };
35
+
36
+ const PAGE = 100;
37
+ const enc = encodeURIComponent;
38
+
39
+ /**
40
+ * A {@link StorageBackend} over a GitLab instance, so the gateway can front repositories that
41
+ * still live on GitLab. Each repository is a private project in one group. Lifecycle, refs,
42
+ * blobs, files and history use the REST API (v4); commits and trees are read as git objects over
43
+ * the smart-HTTP transport (GitLab's API reports neither tree ids nor raw messages), and writes
44
+ * are git pushes to {@link gitRemote}. It offers the optional `isAncestor` capability through
45
+ * GitLab's merge-base API, so the gateway proves fast-forwards in one call. Every API response is parsed with Zod.
46
+ *
47
+ * With `frontedProjects`, a reserved name `<prefix><projectId>` addresses an existing project by
48
+ * id, wherever it lives under `frontedProjects.namespace`, so the gateway can front repositories
49
+ * that predate it without moving them. Those names can be read and pushed but never created or
50
+ * deleted.
51
+ */
52
+ export class GitLabBackend implements StorageBackend {
53
+ readonly #config: z.output<typeof GitLabBackendConfig>;
54
+ readonly #api: GitLabApi;
55
+ readonly #fetch: FetchLike;
56
+ #namespaceId: number | undefined;
57
+ readonly #fronted: FrontedProjects;
58
+
59
+ constructor(options: GitLabBackendOptions) {
60
+ const { fetch, ...config } = options;
61
+ this.#config = GitLabBackendConfig.parse(config);
62
+ this.#fetch = fetch ?? (async (request) => globalThis.fetch(request));
63
+ this.#api = new GitLabApi(this.#config.baseUrl, this.#config.token, this.#fetch);
64
+ this.#namespaceId = this.#config.namespaceId;
65
+ this.#fronted = new FrontedProjects(this.#config.frontedProjects);
66
+ }
67
+
68
+ async createRepo(name: string, options: CreateStorageRepoOptions = {}): Promise<StorageRepoInfo> {
69
+ const repo = parseStorageInput(RepoName, name);
70
+ const { defaultBranch } = parseStorageInput(CreateStorageRepoOptions, options);
71
+ if (this.#fronted.idOf(repo) !== null) throw frontedLifecycleRefused(repo, 'created');
72
+ return this.#call(repo, 'createRepo', async () => {
73
+ const namespaceId = await this.#resolveNamespaceId();
74
+ try {
75
+ const body = {
76
+ name: repo,
77
+ path: repo,
78
+ namespace_id: namespaceId,
79
+ default_branch: defaultBranch,
80
+ visibility: 'private',
81
+ initialize_with_readme: false,
82
+ };
83
+ return this.#info(
84
+ await this.#api.json(GitLabProject, '/projects', { method: 'POST', body }),
85
+ defaultBranch,
86
+ );
87
+ } catch (error) {
88
+ if (
89
+ error instanceof GitLabHttpError &&
90
+ error.status === 400 &&
91
+ /already been taken/i.test(error.detail)
92
+ )
93
+ throw repoExists(repo);
94
+ throw error;
95
+ }
96
+ });
97
+ }
98
+
99
+ async deleteRepo(name: string): Promise<void> {
100
+ const repo = parseStorageInput(RepoName, name);
101
+ if (this.#fronted.idOf(repo) !== null) throw frontedLifecycleRefused(repo, 'deleted');
102
+ await this.#call(repo, 'deleteRepo', async () => {
103
+ const project = await this.#projectOrNull(repo);
104
+ if (project === null) return;
105
+ await this.#api.request(`/projects/${project.id}`, { method: 'DELETE' });
106
+ // With delayed deletion the project is only marked (and renamed); remove it for good so the
107
+ // name is free again. Instances without delayed deletion have already removed it.
108
+ const marked = await this.#api.json(GitLabProject, `/projects/${project.id}`).catch(() => null);
109
+ if (marked !== null) {
110
+ await this.#api.request(`/projects/${project.id}`, {
111
+ method: 'DELETE',
112
+ query: { permanently_remove: true, full_path: marked.path_with_namespace },
113
+ });
114
+ }
115
+ });
116
+ }
117
+
118
+ async repoInfo(name: string): Promise<StorageRepoInfo | null> {
119
+ const repo = parseStorageInput(RepoName, name);
120
+ return this.#call(repo, 'repoInfo', async () => {
121
+ const project = await this.#projectOrNull(repo);
122
+ return project === null ? null : this.#info(project, 'main', repo);
123
+ });
124
+ }
125
+
126
+ async resolveRef(name: string, ref: string): Promise<string | null> {
127
+ const repo = parseStorageInput(RepoName, name);
128
+ const parsed = parseStorageInput(StorageRef, ref);
129
+ const [kind, short] = parsed.startsWith('refs/tags/')
130
+ ? ['tags', parsed.slice(10)]
131
+ : ['branches', parsed.replace(/^refs\/heads\//, '')];
132
+ return this.#call(repo, 'resolveRef', async () => {
133
+ try {
134
+ return (
135
+ await this.#api.json(GitLabRef, `${await this.#projectPath(repo)}/repository/${kind}/${enc(short)}`)
136
+ ).commit.id;
137
+ } catch (error) {
138
+ if (error instanceof GitLabHttpError && error.status === 404 && !error.projectMissing) return null;
139
+ throw error;
140
+ }
141
+ });
142
+ }
143
+
144
+ async readCommit(name: string, sha: string): Promise<Commit | null> {
145
+ const repo = parseStorageInput(RepoName, name);
146
+ const id = parseStorageInput(Sha, sha);
147
+ return this.#call(repo, 'readCommit', async () => {
148
+ const found = await this.#api.bytesOrNull(`${await this.#projectPath(repo)}/repository/commits/${id}`);
149
+ if (found === null) return null;
150
+ const [commit] = await readCommitsOverGit(await this.#client(repo), [id]);
151
+ return commit ?? null;
152
+ });
153
+ }
154
+
155
+ async readTree(name: string, sha: string): Promise<StorageTreeEntry[] | null> {
156
+ const repo = parseStorageInput(RepoName, name);
157
+ const id = parseStorageInput(Sha, sha);
158
+ return this.#call(repo, 'readTree', async () => readTreeOverGit(await this.#client(repo), id));
159
+ }
160
+
161
+ async readBlob(name: string, sha: string): Promise<Uint8Array | null> {
162
+ const repo = parseStorageInput(RepoName, name);
163
+ const id = parseStorageInput(Sha, sha);
164
+ return this.#call(repo, 'readBlob', async () =>
165
+ this.#api.bytesOrNull(`${await this.#projectPath(repo)}/repository/blobs/${id}/raw`),
166
+ );
167
+ }
168
+
169
+ async readFile(name: string, ref: string, path: string): Promise<Uint8Array | null> {
170
+ const repo = parseStorageInput(RepoName, name);
171
+ const revision = parseStorageInput(Revision, ref);
172
+ const file = parseStorageInput(FilePath, path);
173
+ return this.#call(repo, 'readFile', async () =>
174
+ this.#api.bytesOrNull(`${await this.#projectPath(repo)}/repository/files/${enc(file)}/raw`, {
175
+ ref: revision,
176
+ }),
177
+ );
178
+ }
179
+
180
+ async log(name: string, ref: string, options: StorageLogOptions): Promise<Commit[]> {
181
+ const repo = parseStorageInput(RepoName, name);
182
+ const revision = parseStorageInput(Revision, ref);
183
+ const { limit, offset } = parseStorageInput(StorageLogOptions, options);
184
+ return this.#call(repo, 'log', async () => {
185
+ const shas = await this.#listFirstParents(repo, revision, offset + limit);
186
+ return readCommitsOverGit(await this.#client(repo), shas.slice(offset, offset + limit));
187
+ });
188
+ }
189
+
190
+ /** One merge-base API call: `ancestor` is an ancestor exactly when it is the merge base. */
191
+ async isAncestor(name: string, ancestor: string, descendant: string): Promise<boolean | null> {
192
+ const repo = parseStorageInput(RepoName, name);
193
+ const older = parseStorageInput(Sha, ancestor);
194
+ const newer = parseStorageInput(Sha, descendant);
195
+ return this.#call(repo, 'isAncestor', async () =>
196
+ isAncestorOnGitLab(this.#api, await this.#projectPath(repo), older, newer),
197
+ );
198
+ }
199
+
200
+ async gitRemote(name: string, access: string): Promise<GitRemote> {
201
+ const repo = parseStorageInput(RepoName, name);
202
+ parseStorageInput(GitAccess, access);
203
+ return this.#call(repo, 'gitRemote', async () => {
204
+ const project = await this.#projectOrNull(repo);
205
+ if (project === null) throw repoNotFound(repo);
206
+ const basic = btoa(`${this.#config.gitUsername}:${this.#config.token}`);
207
+ // GitLab access tokens are not scoped per request: read and write remotes carry the same
208
+ // credential, and the gateway's own policy decides who may push.
209
+ return GitRemote.parse({
210
+ url: project.http_url_to_repo,
211
+ headers: { Authorization: `Basic ${basic}` },
212
+ expiresAt: null,
213
+ });
214
+ });
215
+ }
216
+
217
+ /** The ids along the first-parent chain from `revision`, newest first, at most `count`. */
218
+ async #listFirstParents(repo: string, revision: string, count: number): Promise<string[]> {
219
+ const shas: string[] = [];
220
+ for (let page = 1; shas.length < count; page += 1) {
221
+ let listed: GitLabCommitSummary[];
222
+ try {
223
+ const query = { ref_name: revision, first_parent: true, per_page: PAGE, page };
224
+ listed = await this.#api.json(
225
+ z.array(GitLabCommitSummary),
226
+ `${await this.#projectPath(repo)}/repository/commits`,
227
+ { query },
228
+ );
229
+ } catch (error) {
230
+ if (error instanceof GitLabHttpError && error.status === 404 && !error.projectMissing) return [];
231
+ throw error;
232
+ }
233
+ shas.push(...listed.map((commit) => commit.id));
234
+ if (listed.length < PAGE) break;
235
+ }
236
+ return shas.slice(0, count);
237
+ }
238
+
239
+ async #client(repo: string): Promise<GitHttpClient> {
240
+ return new GitHttpClient(await this.gitRemote(repo, 'read'), { fetch: this.#fetch });
241
+ }
242
+
243
+ /**
244
+ * The API path of `repo`'s project. A fronted name is checked to lie under the fronted namespace
245
+ * first (once per id), so a project elsewhere is repo_not_found rather than reachable by id.
246
+ */
247
+ async #projectPath(repo: string): Promise<string> {
248
+ const id = this.#fronted.idOf(repo);
249
+ if (id === null) return `/projects/${enc(`${this.#config.namespace}/${repo}`)}`;
250
+ if (!this.#fronted.verified(id) && (await this.#projectOrNull(repo)) === null) throw repoNotFound(repo);
251
+ return `/projects/${id}`;
252
+ }
253
+
254
+ async #projectOrNull(repo: string): Promise<GitLabProject | null> {
255
+ const id = this.#fronted.idOf(repo);
256
+ const path = id === null ? `/projects/${enc(`${this.#config.namespace}/${repo}`)}` : `/projects/${id}`;
257
+ try {
258
+ const project = await this.#api.json(GitLabProject, path);
259
+ if (project.marked_for_deletion_on !== null && project.marked_for_deletion_on !== undefined)
260
+ return null;
261
+ if (id === null) return project;
262
+ return this.#fronted.admits(id, project) ? project : null;
263
+ } catch (error) {
264
+ if (error instanceof GitLabHttpError && error.status === 404) return null;
265
+ throw error;
266
+ }
267
+ }
268
+
269
+ async #resolveNamespaceId(): Promise<number> {
270
+ this.#namespaceId ??= (await this.#api.json(GitLabGroup, `/groups/${enc(this.#config.namespace)}`)).id;
271
+ return this.#namespaceId;
272
+ }
273
+
274
+ /** The StorageRepoInfo of `project`; a fronted project is named by the reserved `name` it was opened by. */
275
+ #info(project: GitLabProject, fallbackBranch: string, name?: string): StorageRepoInfo {
276
+ return StorageRepoInfo.parse({
277
+ name: name !== undefined && this.#fronted.idOf(name) !== null ? name : project.path,
278
+ defaultBranch: project.default_branch ?? fallbackBranch,
279
+ createdAt: new Date(project.created_at).toISOString(),
280
+ });
281
+ }
282
+
283
+ /** Runs one call: GatewayErrors pass through, a 404 for the project is repo_not_found, anything else storage_unavailable. */
284
+ async #call<T>(repo: string, what: string, work: () => Promise<T>): Promise<T> {
285
+ try {
286
+ return await work();
287
+ } catch (error) {
288
+ if (isGatewayError(error)) throw error;
289
+ if (error instanceof GitLabHttpError && error.projectMissing) throw repoNotFound(repo);
290
+ throw storageUnavailable(`GitLab ${what}`, error);
291
+ }
292
+ }
293
+ }
@@ -0,0 +1,62 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { gatewayError, type GatewayError } from '@leed-ai/git-gateway-contract/gateway-error';
3
+
4
+ import type { GitLabProject } from './schemas/gitlab-responses.ts';
5
+
6
+ /** How existing projects are fronted by id (GitLabBackendConfig.frontedProjects, parsed). */
7
+ export interface FrontedProjectsConfig {
8
+ readonly prefix: string;
9
+ readonly namespace: string;
10
+ }
11
+
12
+ /**
13
+ * The reserved names `<prefix><projectId>` of a GitLab backend's fronted projects: which names are
14
+ * reserved, which project id each addresses, and whether a project may be fronted (it lives under
15
+ * the fronted namespace). Ids already confirmed are remembered for the life of the backend.
16
+ */
17
+ export class FrontedProjects {
18
+ readonly #pattern: RegExp | undefined;
19
+ readonly #namespace: string | undefined;
20
+ readonly #verified = new Set<number>();
21
+
22
+ constructor(config: FrontedProjectsConfig | undefined) {
23
+ this.#namespace = config?.namespace.toLowerCase();
24
+ this.#pattern =
25
+ config === undefined
26
+ ? undefined
27
+ : new RegExp(`^${config.prefix.replace(/[.*+?^${}()|[\]\\/-]/g, '\\$&')}([1-9][0-9]{0,15})$`);
28
+ }
29
+
30
+ /** The project id `repo` addresses when it is a reserved name; null for an ordinary name. */
31
+ idOf(repo: string): number | null {
32
+ const match = this.#pattern?.exec(repo);
33
+ return match?.[1] === undefined ? null : Number(match[1]);
34
+ }
35
+
36
+ /** True once {@link admits} has accepted project `id`. */
37
+ verified(id: number): boolean {
38
+ return this.#verified.has(id);
39
+ }
40
+
41
+ /** True when `project` is project `id` and lives under the fronted namespace, at any depth; remembered. */
42
+ admits(id: number, project: GitLabProject): boolean {
43
+ const ok =
44
+ this.#namespace !== undefined &&
45
+ project.id === id &&
46
+ project.path_with_namespace.toLowerCase().startsWith(`${this.#namespace}/`);
47
+ if (ok) this.#verified.add(id);
48
+ return ok;
49
+ }
50
+ }
51
+
52
+ /** The invalid_input error createRepo and deleteRepo answer for a fronted project's reserved name. */
53
+ export function frontedLifecycleRefused(repo: string, what: 'created' | 'deleted'): GatewayError {
54
+ return gatewayError('invalid_input', 'Invalid input', {
55
+ issues: [
56
+ {
57
+ path: 'name',
58
+ message: `${repo} addresses an existing GitLab project by id; it cannot be ${what} through the gateway`,
59
+ },
60
+ ],
61
+ });
62
+ }
@@ -0,0 +1,62 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import type { Commit } from '@leed-ai/git-gateway-contract/schemas/commit';
3
+ import { StorageTreeEntry } from '@leed-ai/git-gateway-contract/storage/storage-tree-entry';
4
+ import { isCoreError } from '@leed-ai/git-gateway-core/core-error';
5
+ import { decodeCommit } from '@leed-ai/git-gateway-core/objects/commit-object';
6
+ import { decodeTree } from '@leed-ai/git-gateway-core/objects/tree-object';
7
+ import type { GitObject } from '@leed-ai/git-gateway-core/schemas/git-object';
8
+ import type { GitHttpClient } from '@leed-ai/git-gateway-core/smart-http/git-http-client';
9
+
10
+ const KIND_OF_MODE = { '040000': 'tree', '160000': 'commit' } as const;
11
+
12
+ /**
13
+ * Fetches exactly the named objects over git: each want with one generation of history and a
14
+ * partial-clone filter that leaves out everything below it ("tree:0" for commits — the commit
15
+ * objects alone; "tree:1" for a tree — that tree alone). Returns null only when the server refuses
16
+ * a want in-protocol (an "ERR" pkt-line in an HTTP 200 answer: an unknown id), so the caller can
17
+ * tell a missing object from a failure. An HTTP failure (remote_http_error: an outage, an expired
18
+ * token) propagates, so the backend reports it as storage_unavailable.
19
+ */
20
+ async function fetchExact(
21
+ client: GitHttpClient,
22
+ wants: readonly string[],
23
+ filter: 'tree:0' | 'tree:1',
24
+ ): Promise<Map<string, GitObject> | null> {
25
+ try {
26
+ const { objects } = await client.fetchPack({ wants: [...wants], depth: 1, filter });
27
+ return new Map(objects.map((object) => [object.sha, object]));
28
+ } catch (error) {
29
+ if (isCoreError(error, 'remote_error')) return null;
30
+ throw error;
31
+ }
32
+ }
33
+
34
+ /**
35
+ * The commit objects for `shas`, decoded exactly as stored (GitLab's Commits API reports neither
36
+ * the tree id nor the raw message, so they are read from the objects themselves). Throws when the
37
+ * server does not send one of them.
38
+ */
39
+ export async function readCommitsOverGit(client: GitHttpClient, shas: readonly string[]): Promise<Commit[]> {
40
+ if (shas.length === 0) return [];
41
+ const objects = await fetchExact(client, shas, 'tree:0');
42
+ return shas.map((sha) => {
43
+ const object = objects?.get(sha);
44
+ if (object?.type !== 'commit') throw new Error(`GitLab did not send commit ${sha}`);
45
+ return decodeCommit(sha, object.data);
46
+ });
47
+ }
48
+
49
+ /** One level of the tree `sha`, read over git; null when the server has no such object or it is not a tree. */
50
+ export async function readTreeOverGit(
51
+ client: GitHttpClient,
52
+ sha: string,
53
+ ): Promise<StorageTreeEntry[] | null> {
54
+ const object = (await fetchExact(client, [sha], 'tree:1'))?.get(sha);
55
+ if (object?.type !== 'tree') return null;
56
+ return decodeTree(object.data, sha).map((entry) =>
57
+ StorageTreeEntry.parse({
58
+ ...entry,
59
+ type: entry.mode === '040000' || entry.mode === '160000' ? KIND_OF_MODE[entry.mode] : 'blob',
60
+ }),
61
+ );
62
+ }
@@ -0,0 +1,30 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { GitLabHttpError, type GitLabApi } from './gitlab-api.ts';
3
+ import { GitLabCommitSummary } from './schemas/gitlab-responses.ts';
4
+
5
+ /**
6
+ * Whether `ancestor` is `descendant` or one of its ancestors, from one call to GitLab's merge-base
7
+ * API (`GET /projects/:id/repository/merge_base?refs[]=…&refs[]=…`): it is exactly when the merge
8
+ * base of the two is `ancestor` itself. Null when GitLab cannot find either commit (400 "Could not
9
+ * find ref"); false when the two share no history (404 "Merge Base Not Found"). Any other error is
10
+ * thrown for the backend to map. Both ids must already be validated 40-character hex ids, which
11
+ * git resolves as object ids before any ref name.
12
+ */
13
+ export async function isAncestorOnGitLab(
14
+ api: GitLabApi,
15
+ projectPath: string,
16
+ ancestor: string,
17
+ descendant: string,
18
+ ): Promise<boolean | null> {
19
+ const refs = [ancestor, descendant].map((sha) => `refs%5B%5D=${sha}`).join('&');
20
+ try {
21
+ const base = await api.json(GitLabCommitSummary, `${projectPath}/repository/merge_base?${refs}`);
22
+ return base.id === ancestor;
23
+ } catch (error) {
24
+ if (error instanceof GitLabHttpError && !error.projectMissing) {
25
+ if (error.status === 400 && /could not find/i.test(error.detail)) return null;
26
+ if (error.status === 404 && /merge base/i.test(error.detail)) return false;
27
+ }
28
+ throw error;
29
+ }
30
+ }
@@ -0,0 +1,4 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ /** The npm name this package is published under. */
4
+ export const packageName = '@leed-ai/git-gateway-backend-gitlab' as const;
@@ -0,0 +1,91 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { z } from 'zod';
3
+
4
+ /** How the GitLab backend reaches its GitLab instance. */
5
+ export const GitLabBackendConfig = z
6
+ .object({
7
+ baseUrl: z
8
+ .url({ protocol: /^https?$/ })
9
+ .default('https://gitlab.com')
10
+ .describe(
11
+ 'Base URL of the GitLab instance, without a trailing "/api/v4". Default "https://gitlab.com".',
12
+ ),
13
+ token: z
14
+ .string()
15
+ .min(1)
16
+ .describe(
17
+ 'A GitLab access token (personal, group or project access token, or OAuth) with the api, read_repository and write_repository scopes on the namespace. Secret: sent as a PRIVATE-TOKEN header to the API and as the HTTP Basic password to git.',
18
+ ),
19
+ namespace: z
20
+ .string()
21
+ .min(1)
22
+ .max(255)
23
+ .regex(/^[A-Za-z0-9_.][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9_.][A-Za-z0-9_.-]*)*$/)
24
+ .describe(
25
+ 'Full path of the group the repositories live in, e.g. "acme/sites". A repository named <repo> is the project <namespace>/<repo>.',
26
+ ),
27
+ namespaceId: z
28
+ .int()
29
+ .positive()
30
+ .optional()
31
+ .describe(
32
+ 'Numeric id of that group. Absent: looked up from `namespace` the first time a repository is created.',
33
+ ),
34
+ frontedProjects: z
35
+ .object({
36
+ prefix: z
37
+ .string()
38
+ .min(1)
39
+ .max(20)
40
+ .regex(/^[A-Za-z][A-Za-z0-9_.]*-$/)
41
+ .default('gl-')
42
+ .describe(
43
+ 'Prefix of the reserved repository names that address an existing project by id: <prefix><projectId>, e.g. "gl-1234" for project 1234. 1–20 characters, starting with a letter and ending in "-". Default "gl-".',
44
+ ),
45
+ namespace: z
46
+ .string()
47
+ .min(1)
48
+ .max(255)
49
+ .regex(/^[A-Za-z0-9_.][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9_.][A-Za-z0-9_.-]*)*$/)
50
+ .describe(
51
+ 'Full path of the group whose projects (at any depth below it) may be fronted, e.g. "acme/customers". A project id outside it answers repo_not_found, so the token\'s other projects stay unreachable.',
52
+ ),
53
+ })
54
+ .strict()
55
+ .optional()
56
+ .describe(
57
+ 'Fronts projects that already exist outside `namespace`, addressed by project id instead of by name. A repository named <prefix><projectId> is project <projectId>, provided it lives under `frontedProjects.namespace`; createRepo and deleteRepo refuse such names with invalid_input, since the gateway did not create those projects and must not remove them. Absent: every name is a project in `namespace`.',
58
+ ),
59
+ gitUsername: z
60
+ .string()
61
+ .min(1)
62
+ .default('oauth2')
63
+ .describe(
64
+ 'HTTP Basic username sent with the token to git; GitLab ignores it for access tokens. Default "oauth2".',
65
+ ),
66
+ })
67
+ .strict()
68
+ .meta({
69
+ id: 'GitLabBackendConfig',
70
+ title: 'GitLab backend configuration',
71
+ description:
72
+ 'Where the GitLab storage backend keeps repositories and the credential it uses. Each repository is a private project in one group.',
73
+ examples: [
74
+ {
75
+ baseUrl: 'https://gitlab.com',
76
+ token: 'glpat-example',
77
+ namespace: 'acme/sites',
78
+ gitUsername: 'oauth2',
79
+ },
80
+ {
81
+ baseUrl: 'https://gitlab.com',
82
+ token: 'glpat-example',
83
+ namespace: 'acme/sites',
84
+ frontedProjects: { prefix: 'gl-', namespace: 'acme/customers' },
85
+ gitUsername: 'oauth2',
86
+ },
87
+ ],
88
+ });
89
+
90
+ /** GitLab backend configuration as accepted (defaults optional). */
91
+ export type GitLabBackendConfig = z.input<typeof GitLabBackendConfig>;