@cepharum/mcp-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.
Files changed (44) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +21 -0
  3. package/README.md +170 -2
  4. package/package.json +50 -5
  5. package/src/audit.js +185 -0
  6. package/src/cli.js +411 -0
  7. package/src/connect.js +335 -0
  8. package/src/consent.js +115 -0
  9. package/src/downloads.js +94 -0
  10. package/src/errors.js +13 -0
  11. package/src/git.js +94 -0
  12. package/src/gitlab/client.js +406 -0
  13. package/src/gitlab/diff.js +79 -0
  14. package/src/hosts.js +228 -0
  15. package/src/paths.js +71 -0
  16. package/src/permissions/catalog.js +75 -0
  17. package/src/permissions/policy.js +230 -0
  18. package/src/permissions/profiles.js +66 -0
  19. package/src/pins.js +36 -0
  20. package/src/platform/index.js +76 -0
  21. package/src/platform/macos.js +129 -0
  22. package/src/platform/service.js +2 -0
  23. package/src/process.js +56 -0
  24. package/src/refs.js +146 -0
  25. package/src/secrets.js +51 -0
  26. package/src/server.js +146 -0
  27. package/src/session.js +140 -0
  28. package/src/text.js +68 -0
  29. package/src/tools/artifacts.js +288 -0
  30. package/src/tools/audit.js +53 -0
  31. package/src/tools/environments.js +147 -0
  32. package/src/tools/files.js +101 -0
  33. package/src/tools/index.js +33 -0
  34. package/src/tools/issues.js +465 -0
  35. package/src/tools/merge-requests.js +698 -0
  36. package/src/tools/packages.js +322 -0
  37. package/src/tools/pipelines.js +415 -0
  38. package/src/tools/registry.js +107 -0
  39. package/src/tools/repositories.js +174 -0
  40. package/src/tools/schedules.js +521 -0
  41. package/src/tools/shared.js +93 -0
  42. package/src/tools/variables.js +294 -0
  43. package/src/tools/wikis.js +168 -0
  44. package/src/zip.js +178 -0
@@ -0,0 +1,406 @@
1
+ import { createReadStream, createWriteStream } from "node:fs";
2
+ import { rename, rm } from "node:fs/promises";
3
+ import { Readable } from "node:stream";
4
+ import { pipeline } from "node:stream/promises";
5
+ import { matchesHostname } from "../hosts.js";
6
+
7
+ const USER_AGENT = "mcp-gitlab";
8
+
9
+ /**
10
+ * A request GitLab refused or that failed on the way.
11
+ */
12
+ export class GitLabError extends Error {
13
+ /**
14
+ * @param {string} message
15
+ * @param {number} status HTTP status, 0 if there was no response
16
+ */
17
+ constructor( message, status ) {
18
+ super( message );
19
+ this.name = "GitLabError";
20
+ this.status = status;
21
+ }
22
+ }
23
+
24
+ /**
25
+ * @typedef {Record<string, string|number|boolean|undefined|null|Array<string|number>>} Query
26
+ */
27
+
28
+ /**
29
+ * @typedef {object} Page
30
+ * @property {any[]} items
31
+ * @property {number|null} nextPage
32
+ * @property {number|null} total number of items, if GitLab tells it
33
+ */
34
+
35
+ /**
36
+ * Talks to the REST API (v4) of registered GitLab instances.
37
+ *
38
+ * Fetch keeps custom headers such as PRIVATE-TOKEN when following a redirect
39
+ * to another host. Redirects are therefore never followed automatically: API
40
+ * requests refuse them, downloads follow one to the same instance (with token)
41
+ * or to a storage host configured for the instance (without token).
42
+ *
43
+ * @param {object} dependencies
44
+ * @param {{ tokenFor: (host: import("../hosts.js").Host) => Promise<string>, forget: (host: import("../hosts.js").Host) => void }} dependencies.secrets
45
+ * @param {{ approveHost: (host: import("../hosts.js").Host) => Promise<void> }} dependencies.consent
46
+ * @param {typeof fetch} [dependencies.fetch]
47
+ * @param {number} [dependencies.timeoutMs]
48
+ */
49
+ export function createGitLabClient( { secrets, consent, fetch = globalThis.fetch, timeoutMs = 30_000 } ) {
50
+ /**
51
+ * @param {import("../hosts.js").Host} host
52
+ * @param {string} endpoint path below /api/v4, with parameters already encoded
53
+ * @param {Query} [query]
54
+ * @returns {URL}
55
+ */
56
+ function urlOf( host, endpoint, query = {} ) {
57
+ const url = new URL( `${host.url}/api/v4/${endpoint.replace( /^\/+/, "" )}` );
58
+
59
+ for ( const [ name, value ] of Object.entries( query ) ) {
60
+ if ( value === undefined || value === null ) {
61
+ continue;
62
+ }
63
+
64
+ if ( Array.isArray( value ) ) {
65
+ value.forEach( item => url.searchParams.append( `${name}[]`, String( item ) ) );
66
+ } else {
67
+ url.searchParams.set( name, String( value ) );
68
+ }
69
+ }
70
+
71
+ return url;
72
+ }
73
+
74
+ /**
75
+ * @param {import("../hosts.js").Host} host
76
+ * @returns {Promise<Record<string, string>>}
77
+ */
78
+ async function headersFor( host ) {
79
+ await consent.approveHost( host );
80
+
81
+ return { "PRIVATE-TOKEN": await secrets.tokenFor( host ), "User-Agent": USER_AGENT };
82
+ }
83
+
84
+ /**
85
+ * @param {URL} url
86
+ * @param {RequestInit} init
87
+ * @param {import("../hosts.js").Host} host
88
+ * @param {number} [timeout] milliseconds
89
+ * @returns {Promise<Response>}
90
+ */
91
+ async function send( url, init, host, timeout = timeoutMs ) {
92
+ try {
93
+ return await fetch( url, { ...init, redirect: "manual", signal: AbortSignal.timeout( timeout ) } );
94
+ } catch ( cause ) {
95
+ const reason = cause.name === "TimeoutError" ? `no response within ${timeout / 1000} seconds` : cause.cause?.message ?? cause.message;
96
+
97
+ throw new GitLabError( `GitLab at ${host.url} can't be reached: ${reason}`, 0 );
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Converts a failed response into an error an agent can act on.
103
+ *
104
+ * @param {Response} response
105
+ * @param {import("../hosts.js").Host} host
106
+ * @returns {Promise<GitLabError>}
107
+ */
108
+ async function failure( response, host ) {
109
+ let detail = "";
110
+
111
+ try {
112
+ const body = await response.json();
113
+ const message = body?.message ?? body?.error_description ?? body?.error;
114
+
115
+ detail = typeof message === "string" ? message : message ? JSON.stringify( message ) : "";
116
+ } catch {
117
+ // no JSON body
118
+ }
119
+
120
+ const suffix = detail ? `: ${detail.slice( 0, 500 )}` : "";
121
+
122
+ switch ( response.status ) {
123
+ case 401 :
124
+ secrets.forget( host );
125
+
126
+ return new GitLabError( `GitLab at ${host.name} rejected the access token (expired or revoked?), the user has to run "mcp-gitlab token set ${host.name}"`, 401 );
127
+ case 403 :
128
+ return new GitLabError( `GitLab at ${host.name} denied this: the token lacks a scope or its user lacks the role${suffix}`, 403 );
129
+ case 404 :
130
+ return new GitLabError( `not found at ${host.name}, or the user of the token can't see it${suffix}`, 404 );
131
+ case 429 :
132
+ return new GitLabError( `GitLab at ${host.name} limits requests, try again in ${response.headers.get( "retry-after" ) ?? "a few"} seconds`, 429 );
133
+ default :
134
+ if ( response.status >= 300 && response.status < 400 ) {
135
+ return new GitLabError( `GitLab at ${host.name} redirected the request, which isn't followed: is the URL of the host right?`, response.status );
136
+ }
137
+
138
+ return new GitLabError( `GitLab at ${host.name} answered ${response.status}${suffix}`, response.status );
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Sends a request to the API and returns the parsed JSON response.
144
+ *
145
+ * @param {import("../hosts.js").Host} host
146
+ * @param {string} method
147
+ * @param {string} endpoint
148
+ * @param {{ query?: Query, body?: unknown }} [options]
149
+ * @returns {Promise<{ data: any, headers: Headers }>}
150
+ */
151
+ async function request( host, method, endpoint, { query, body } = {} ) {
152
+ const headers = { ...await headersFor( host ), Accept: "application/json" };
153
+
154
+ if ( body !== undefined ) {
155
+ headers["Content-Type"] = "application/json";
156
+ }
157
+
158
+ const response = await send( urlOf( host, endpoint, query ), { method, headers, body: body === undefined ? undefined : JSON.stringify( body ) }, host );
159
+
160
+ if ( !response.ok ) {
161
+ throw await failure( response, host );
162
+ }
163
+
164
+ const text = await response.text();
165
+
166
+ try {
167
+ return { data: text ? JSON.parse( text ) : null, headers: response.headers };
168
+ } catch {
169
+ throw new GitLabError( `GitLab at ${host.name} sent a response that isn't JSON`, response.status );
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Requests content, following at most one redirect as described above.
175
+ *
176
+ * @param {import("../hosts.js").Host} host
177
+ * @param {string} endpoint
178
+ * @param {{ query?: Query, range?: string }} options
179
+ * @returns {Promise<Response>}
180
+ */
181
+ async function open( host, endpoint, { query, range } ) {
182
+ const headers = { ...await headersFor( host ), ...range ? { Range: range } : {} };
183
+ const origin = new URL( host.url ).origin;
184
+ let response = await send( urlOf( host, endpoint, query ), { headers }, host );
185
+
186
+ if ( response.status >= 300 && response.status < 400 && response.headers.has( "location" ) ) {
187
+ const target = new URL( /** @type {string} */ ( response.headers.get( "location" ) ), urlOf( host, endpoint ) );
188
+
189
+ if ( target.origin === origin ) {
190
+ response = await send( target, { headers }, host );
191
+ } else if ( target.protocol === "https:" && matchesHostname( target.hostname, host.storageHosts ) ) {
192
+ response = await send( target, { headers: { "User-Agent": USER_AGENT, ...range ? { Range: range } : {} } }, host );
193
+ } else {
194
+ throw new GitLabError( `GitLab at ${host.name} redirected the download to ${target.hostname}, which isn't a storage host of "${host.name}": the user can add it with "mcp-gitlab host add ${host.url} --name ${host.name} --storage-host ${target.hostname}"`, response.status );
195
+ }
196
+ }
197
+
198
+ if ( !response.ok ) {
199
+ throw await failure( response, host );
200
+ }
201
+
202
+ const declared = Number( response.headers.get( "content-length" ) );
203
+
204
+ return Object.assign( response, { declared: declared > 0 ? declared : null } );
205
+ }
206
+
207
+ /**
208
+ * Yields the chunks of a response, failing once they exceed a size.
209
+ *
210
+ * @param {Response & { declared: number|null }} response
211
+ * @param {number} maxBytes
212
+ * @returns {AsyncGenerator<Uint8Array>}
213
+ */
214
+ async function* limited( response, maxBytes ) {
215
+ if ( response.declared > maxBytes ) {
216
+ await response.body?.cancel();
217
+ throw new GitLabError( `the file has ${response.declared} bytes, more than the ${maxBytes} bytes allowed here`, 413 );
218
+ }
219
+
220
+ let size = 0;
221
+
222
+ for await ( const chunk of /** @type {AsyncIterable<Uint8Array>} */ ( response.body ?? [] ) ) {
223
+ size += chunk.length;
224
+
225
+ if ( size > maxBytes ) {
226
+ throw new GitLabError( `the file has more than the ${maxBytes} bytes allowed here`, 413 );
227
+ }
228
+
229
+ yield chunk;
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Reads binary content into memory.
235
+ *
236
+ * @param {import("../hosts.js").Host} host
237
+ * @param {string} endpoint
238
+ * @param {{ query?: Query, maxBytes: number, range?: string }} options
239
+ * `range` asks for a part only, e.g. "bytes=-1024", which servers may ignore: check `partial`
240
+ * @returns {Promise<{ bytes: Buffer, headers: Headers, partial: boolean }>}
241
+ */
242
+ async function download( host, endpoint, { query, maxBytes, range } ) {
243
+ const response = await open( host, endpoint, { query, range } );
244
+ const chunks = [];
245
+
246
+ for await ( const chunk of limited( response, maxBytes ) ) {
247
+ chunks.push( chunk );
248
+ }
249
+
250
+ return { bytes: Buffer.concat( chunks ), headers: response.headers, partial: response.status === 206 };
251
+ }
252
+
253
+ /**
254
+ * Writes binary content into a file, replacing it only once complete.
255
+ *
256
+ * @param {import("../hosts.js").Host} host
257
+ * @param {string} endpoint
258
+ * @param {{ query?: Query, maxBytes: number, file: string }} options
259
+ * @returns {Promise<{ size: number, headers: Headers }>}
260
+ */
261
+ async function save( host, endpoint, { query, maxBytes, file } ) {
262
+ const response = await open( host, endpoint, { query } );
263
+ const partial = `${file}.${process.pid}.part`;
264
+ let size = 0;
265
+
266
+ try {
267
+ await pipeline( Readable.from( ( async function* count() {
268
+ for await ( const chunk of limited( response, maxBytes ) ) {
269
+ size += chunk.length;
270
+ yield chunk;
271
+ }
272
+ } )() ), createWriteStream( partial, { mode: 0o600 } ) );
273
+ await rename( partial, file );
274
+ } catch ( error ) {
275
+ await rm( partial, { force: true } );
276
+ throw error;
277
+ }
278
+
279
+ return { size, headers: response.headers };
280
+ }
281
+
282
+ /**
283
+ * Sends a local file as body of a PUT request, e.g. to upload a file of a
284
+ * generic package. Redirects are refused like those of API requests.
285
+ *
286
+ * @param {import("../hosts.js").Host} host
287
+ * @param {string} endpoint
288
+ * @param {{ query?: Query, file: string, size: number }} options
289
+ * @returns {Promise<any>} the parsed JSON response, null if there is none
290
+ */
291
+ async function upload( host, endpoint, { query, file, size } ) {
292
+ const headers = {
293
+ ...await headersFor( host ),
294
+ Accept: "application/json",
295
+ "Content-Type": "application/octet-stream",
296
+ "Content-Length": String( size ),
297
+ };
298
+ const body = /** @type {ReadableStream} */ ( Readable.toWeb( createReadStream( file ) ) );
299
+
300
+ // sending may take longer than an API request: allow a minute per 50 MB
301
+ const response = await send( urlOf( host, endpoint, query ), { method: "PUT", headers, body, duplex: "half" }, host, Math.max( timeoutMs, Math.ceil( size / 50e6 ) * 60_000 ) );
302
+
303
+ if ( !response.ok ) {
304
+ throw await failure( response, host );
305
+ }
306
+
307
+ const text = await response.text();
308
+
309
+ try {
310
+ return text ? JSON.parse( text ) : null;
311
+ } catch {
312
+ return null;
313
+ }
314
+ }
315
+
316
+ /** @type {Map<string, Promise<any>>} */
317
+ const users = new Map();
318
+
319
+ return {
320
+ request,
321
+ download,
322
+ save,
323
+ upload,
324
+
325
+ /**
326
+ * The user the token of a host belongs to, asked once per session.
327
+ *
328
+ * @param {import("../hosts.js").Host} host
329
+ * @returns {Promise<{ id: number, username: string, name: string }>}
330
+ */
331
+ currentUser( host ) {
332
+ if ( !users.has( host.name ) ) {
333
+ const pending = request( host, "GET", "user" ).then( ( { data } ) => data );
334
+
335
+ pending.catch( () => users.delete( host.name ) );
336
+ users.set( host.name, pending );
337
+ }
338
+
339
+ return users.get( host.name );
340
+ },
341
+
342
+ /**
343
+ * @param {import("../hosts.js").Host} host
344
+ * @param {string} endpoint
345
+ * @param {unknown} [body]
346
+ * @returns {Promise<any>}
347
+ */
348
+ async post( host, endpoint, body ) {
349
+ return ( await request( host, "POST", endpoint, { body } ) ).data;
350
+ },
351
+
352
+ /**
353
+ * @param {import("../hosts.js").Host} host
354
+ * @param {string} endpoint
355
+ * @param {unknown} [body]
356
+ * @returns {Promise<any>}
357
+ */
358
+ async put( host, endpoint, body ) {
359
+ return ( await request( host, "PUT", endpoint, { body } ) ).data;
360
+ },
361
+
362
+ /**
363
+ * @param {import("../hosts.js").Host} host
364
+ * @param {string} endpoint
365
+ * @param {Query} [query]
366
+ * @returns {Promise<any>}
367
+ */
368
+ async get( host, endpoint, query ) {
369
+ return ( await request( host, "GET", endpoint, { query } ) ).data;
370
+ },
371
+
372
+ /**
373
+ * Reads one page of a list.
374
+ *
375
+ * @param {import("../hosts.js").Host} host
376
+ * @param {string} endpoint
377
+ * @param {{ query?: Query, page?: number, perPage?: number }} [options]
378
+ * @returns {Promise<Page>}
379
+ */
380
+ async list( host, endpoint, { query = {}, page = 1, perPage = 20 } = {} ) {
381
+ const { data, headers } = await request( host, "GET", endpoint, { query: { ...query, page, per_page: perPage } } );
382
+ const next = Number( headers.get( "x-next-page" ) );
383
+ const total = headers.get( "x-total" );
384
+
385
+ return {
386
+ items: Array.isArray( data ) ? data : [],
387
+ nextPage: next > 0 ? next : null,
388
+ total: total ? Number( total ) : null,
389
+ };
390
+ },
391
+ };
392
+ }
393
+
394
+ /**
395
+ * Encodes the path of a project for use as its ID in API paths.
396
+ *
397
+ * @param {import("../refs.js").RepoRef} repo
398
+ * @returns {string}
399
+ */
400
+ export function projectId( repo ) {
401
+ return encodeURIComponent( repo.path );
402
+ }
403
+
404
+ /**
405
+ * @typedef {ReturnType<typeof createGitLabClient>} GitLabClient
406
+ */
@@ -0,0 +1,79 @@
1
+ import { createTwoFilesPatch, OMIT_HEADERS } from "diff";
2
+ import { decodeText } from "../text.js";
3
+ import { projectId } from "./client.js";
4
+
5
+ /** Largest version of a file diffs are computed for. */
6
+ const MAX_FILE_BYTES = 1024 * 1024;
7
+
8
+ /** Time a diff may take before it is given up. */
9
+ const DIFF_TIMEOUT_MS = 2000;
10
+
11
+ /**
12
+ * Reads a version of a file, null if it doesn't exist in that version.
13
+ *
14
+ * @param {import("./client.js").GitLabClient} gitlab
15
+ * @param {import("../refs.js").RepoRef} repo
16
+ * @param {string} path
17
+ * @param {string} sha
18
+ * @returns {Promise<Buffer|null>}
19
+ */
20
+ async function version( gitlab, repo, path, sha ) {
21
+ try {
22
+ return ( await gitlab.download( repo.host, `projects/${projectId( repo )}/repository/files/${encodeURIComponent( path )}/raw`, { query: { ref: sha }, maxBytes: MAX_FILE_BYTES } ) ).bytes;
23
+ } catch ( error ) {
24
+ if ( error.status === 404 ) {
25
+ return null;
26
+ }
27
+
28
+ throw error;
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Computes the diff of a changed file from both of its versions, for when
34
+ * GitLab's diff doesn't do: other amounts of context, or files GitLab
35
+ * leaves out for their size.
36
+ *
37
+ * @param {import("./client.js").GitLabClient} gitlab
38
+ * @param {import("../refs.js").RepoRef} repo
39
+ * @param {{ oldPath: string, newPath: string, added?: boolean, deleted?: boolean }} file
40
+ * @param {{ base: string, head: string }} versions commits to compare
41
+ * @param {number} context lines of context around changes
42
+ * @returns {Promise<{ diff?: string, binary?: boolean, omitted?: string }>}
43
+ */
44
+ export async function computeDiff( gitlab, repo, file, versions, context ) {
45
+ let before;
46
+ let after;
47
+
48
+ try {
49
+ [ before, after ] = await Promise.all( [
50
+ file.added ? null : version( gitlab, repo, file.oldPath, versions.base ),
51
+ file.deleted ? null : version( gitlab, repo, file.newPath, versions.head ),
52
+ ] );
53
+ } catch ( error ) {
54
+ if ( error.status === 413 ) {
55
+ return { omitted: `a version of the file is larger than ${MAX_FILE_BYTES} bytes` };
56
+ }
57
+
58
+ throw error;
59
+ }
60
+
61
+ const oldText = before ? decodeText( before ) : { text: "" };
62
+ const newText = after ? decodeText( after ) : { text: "" };
63
+
64
+ if ( !oldText || !newText ) {
65
+ return { binary: true };
66
+ }
67
+
68
+ const patch = createTwoFilesPatch( file.oldPath, file.newPath, oldText.text, newText.text, undefined, undefined, {
69
+ context,
70
+ headerOptions: OMIT_HEADERS,
71
+ timeout: DIFF_TIMEOUT_MS,
72
+ } );
73
+
74
+ if ( patch === undefined ) {
75
+ return { omitted: "the changes are too large to compute a diff" };
76
+ }
77
+
78
+ return { diff: patch };
79
+ }
package/src/hosts.js ADDED
@@ -0,0 +1,228 @@
1
+ import { readJsonFile, writeJsonFile } from "./paths.js";
2
+
3
+ /**
4
+ * A GitLab instance the user registered. Only registered instances are ever
5
+ * contacted, an agent can't make the server talk to any other host.
6
+ *
7
+ * @typedef {object} Host
8
+ * @property {string} name short name used in repository references, e.g. "gitlab.com"
9
+ * @property {string} url base URL of the web interface, e.g. "https://git.example.com" or "https://example.com/gitlab"
10
+ * @property {string[]} sshHosts additional host names used in SSH clone URLs, e.g. "ssh.git.example.com"
11
+ * @property {string[]} storageHosts host name patterns downloads may be redirected to, e.g. "*.gitlab-static.net"
12
+ * @property {boolean} [default] marks the host used for references without host name
13
+ */
14
+
15
+ const FILE = "hosts.json";
16
+
17
+ const NAME_PATTERN = /^[a-z0-9](?:[a-z0-9.-]{0,98}[a-z0-9])?(?::\d{1,5})?$/;
18
+
19
+ const HOSTNAME_PATTERN = /^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;
20
+
21
+ /** Storage gitlab.com redirects downloads of artifacts and packages to. */
22
+ const GITLAB_COM_STORAGE = ["*.gitlab-static.net"];
23
+
24
+ /**
25
+ * Normalizes the base URL of a GitLab instance. HTTPS is required, plain HTTP
26
+ * is accepted for the local machine only.
27
+ *
28
+ * @param {string} input
29
+ * @returns {string} URL without trailing slash
30
+ */
31
+ export function normalizeUrl( input ) {
32
+ let url;
33
+
34
+ try {
35
+ url = new URL( input.includes( "://" ) ? input : `https://${input}` );
36
+ } catch {
37
+ throw new Error( `"${input}" isn't a valid URL` );
38
+ }
39
+
40
+ const loopback = [ "localhost", "127.0.0.1", "[::1]" ].includes( url.hostname );
41
+
42
+ if ( url.protocol !== "https:" && !( url.protocol === "http:" && loopback ) ) {
43
+ throw new Error( `"${input}" has to use https` );
44
+ }
45
+
46
+ if ( url.username || url.password || url.search || url.hash ) {
47
+ throw new Error( `"${input}" must not contain credentials, a query or a fragment` );
48
+ }
49
+
50
+ return `${url.origin}${url.pathname.replace( /\/+$/, "" )}`;
51
+ }
52
+
53
+ /**
54
+ * @param {string} value
55
+ * @returns {boolean}
56
+ */
57
+ export function isValidHostName( value ) {
58
+ return NAME_PATTERN.test( value );
59
+ }
60
+
61
+ /**
62
+ * Entries are checked, so a damaged or edited file can't make the server
63
+ * contact anything unexpected.
64
+ *
65
+ * @param {any} entry
66
+ * @returns {entry is Host}
67
+ */
68
+ function isHost( entry ) {
69
+ if ( !entry || typeof entry !== "object" || typeof entry.name !== "string" || !isValidHostName( entry.name ) || typeof entry.url !== "string" ) {
70
+ return false;
71
+ }
72
+
73
+ try {
74
+ if ( normalizeUrl( entry.url ) !== entry.url ) {
75
+ return false;
76
+ }
77
+ } catch {
78
+ return false;
79
+ }
80
+
81
+ const hostnames = list => list === undefined || ( Array.isArray( list ) && list.every( item => typeof item === "string" && HOSTNAME_PATTERN.test( item ) ) );
82
+
83
+ return hostnames( entry.sshHosts ) && hostnames( entry.storageHosts );
84
+ }
85
+
86
+ /**
87
+ * @param {any} entry
88
+ * @returns {Host}
89
+ */
90
+ function plain( entry ) {
91
+ return {
92
+ name: entry.name,
93
+ url: entry.url,
94
+ sshHosts: entry.sshHosts ?? [],
95
+ storageHosts: entry.storageHosts ?? [],
96
+ ...entry.default === true ? { default: true } : {},
97
+ };
98
+ }
99
+
100
+ /**
101
+ * Lists the registered hosts.
102
+ *
103
+ * @returns {Promise<Host[]>}
104
+ */
105
+ export async function loadHosts() {
106
+ const entries = await readJsonFile( FILE, [] );
107
+
108
+ return Array.isArray( entries ) ? entries.filter( isHost ).map( plain ) : [];
109
+ }
110
+
111
+ /**
112
+ * The host used for references without a host name: the only one registered
113
+ * or the one marked as default.
114
+ *
115
+ * @param {Host[]} hosts
116
+ * @returns {Host|null}
117
+ */
118
+ export function defaultHost( hosts ) {
119
+ return hosts.length === 1 ? hosts[0] : hosts.find( host => host.default ) ?? null;
120
+ }
121
+
122
+ /**
123
+ * Looks up a registered host by its name, case-insensitively.
124
+ *
125
+ * @param {Host[]} hosts
126
+ * @param {string} name
127
+ * @returns {Host|null}
128
+ */
129
+ export function findHost( hosts, name ) {
130
+ const wanted = name.trim().toLowerCase();
131
+
132
+ return hosts.find( host => host.name === wanted ) ?? null;
133
+ }
134
+
135
+ /**
136
+ * Registers a host or updates the registration of a host with the same name.
137
+ *
138
+ * @param {{ url: string, name?: string, sshHosts?: string[], storageHosts?: string[], makeDefault?: boolean }} options
139
+ * @returns {Promise<Host>}
140
+ */
141
+ export async function addHost( { url, name, sshHosts = [], storageHosts, makeDefault = false } ) {
142
+ const normalized = normalizeUrl( url );
143
+ const hostName = ( name ?? new URL( normalized ).host ).toLowerCase();
144
+
145
+ if ( !isValidHostName( hostName ) ) {
146
+ throw new Error( `"${hostName}" isn't a valid name for a host, use letters, digits, dots and dashes` );
147
+ }
148
+
149
+ const lower = list => list.map( item => item.trim().toLowerCase() );
150
+ const ssh = lower( sshHosts );
151
+ const storage = lower( storageHosts ?? ( new URL( normalized ).hostname === "gitlab.com" ? GITLAB_COM_STORAGE : [] ) );
152
+
153
+ for ( const item of [ ...ssh, ...storage ] ) {
154
+ if ( !HOSTNAME_PATTERN.test( item ) ) {
155
+ throw new Error( `"${item}" isn't a valid host name` );
156
+ }
157
+ }
158
+
159
+ if ( ssh.some( item => item.startsWith( "*." ) ) ) {
160
+ throw new Error( "SSH host names can't contain wildcards" );
161
+ }
162
+
163
+ /** @type {Host} */
164
+ const host = { name: hostName, url: normalized, sshHosts: ssh, storageHosts: storage };
165
+ const hosts = ( await loadHosts() ).filter( existing => existing.name !== hostName );
166
+
167
+ if ( makeDefault ) {
168
+ hosts.forEach( existing => delete existing.default );
169
+ host.default = true;
170
+ }
171
+
172
+ await writeJsonFile( FILE, [ ...hosts, host ] );
173
+
174
+ return host;
175
+ }
176
+
177
+ /**
178
+ * Removes a host from the registry.
179
+ *
180
+ * @param {string} name
181
+ * @returns {Promise<boolean>} false if there was no such host
182
+ */
183
+ export async function removeHost( name ) {
184
+ const hosts = await loadHosts();
185
+ const remaining = hosts.filter( host => host.name !== name.toLowerCase() );
186
+
187
+ if ( remaining.length === hosts.length ) {
188
+ return false;
189
+ }
190
+
191
+ await writeJsonFile( FILE, remaining );
192
+
193
+ return true;
194
+ }
195
+
196
+ /**
197
+ * Marks a registered host as the default one.
198
+ *
199
+ * @param {string} name
200
+ * @returns {Promise<void>}
201
+ */
202
+ export async function setDefaultHost( name ) {
203
+ const hosts = await loadHosts();
204
+
205
+ if ( !findHost( hosts, name ) ) {
206
+ throw new Error( `there is no host "${name}"` );
207
+ }
208
+
209
+ await writeJsonFile( FILE, hosts.map( host => {
210
+ const { default: _, ...rest } = host;
211
+
212
+ return host.name === name.toLowerCase() ? { ...rest, default: true } : rest;
213
+ } ) );
214
+ }
215
+
216
+ /**
217
+ * Tells whether a host name matches one of the patterns, where "*.example.com"
218
+ * matches any subdomain of example.com.
219
+ *
220
+ * @param {string} hostname
221
+ * @param {string[]} patterns
222
+ * @returns {boolean}
223
+ */
224
+ export function matchesHostname( hostname, patterns ) {
225
+ const name = hostname.toLowerCase();
226
+
227
+ return patterns.some( pattern => ( pattern.startsWith( "*." ) ? name.endsWith( pattern.slice( 1 ) ) : name === pattern ) );
228
+ }