@charles7c/git-forge 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.
package/dist/index.cjs ADDED
@@ -0,0 +1,4873 @@
1
+ 'use strict';
2
+
3
+ var buffer = require('buffer');
4
+
5
+ // src/adapters/issues.ts
6
+ function selectIssueRows(http, response, isPullRequest) {
7
+ const raw = response.json;
8
+ if (!Array.isArray(raw)) {
9
+ throw http.invalidResponse(response, "The provider Issue list response must be an array.");
10
+ }
11
+ const rows = raw;
12
+ const states = http.provider === "gitee" ? GITEE_ISSUE_STATES : DEFAULT_ISSUE_STATES;
13
+ for (const row of rows) {
14
+ if (isPullRequest?.(row)) continue;
15
+ const record = row;
16
+ const number = record?.number;
17
+ if (!(typeof number === "string" && number.trim().length > 0) && !(typeof number === "number" && Number.isSafeInteger(number) && number > 0)) {
18
+ throw http.invalidResponse(response, "A provider Issue list entry has no valid number.");
19
+ }
20
+ if (typeof record?.state !== "string" || !states.includes(record.state)) {
21
+ throw http.invalidResponse(response, "A provider Issue list entry has an unknown state.");
22
+ }
23
+ }
24
+ return rows;
25
+ }
26
+ var DEFAULT_ISSUE_STATES = ["open", "closed"];
27
+ var GITEE_ISSUE_STATES = [...DEFAULT_ISSUE_STATES, "progressing", "rejected"];
28
+
29
+ // src/core/redact.ts
30
+ var REDACTED = "***";
31
+ var SENSITIVE_QUERY_KEYS = ["access_token", "token"];
32
+ var SECRET_ASSIGNMENT = /\b(access_token|token|authorization)(\s*[:=]\s*)(bearer\s+)?([^\s&"',;]+)/gi;
33
+ function maskAssignment(_match, key, separator, scheme) {
34
+ return `${key}${separator}${scheme ?? ""}${REDACTED}`;
35
+ }
36
+ function redactUrl(url) {
37
+ if (typeof url !== "string" || url.length === 0) {
38
+ return url;
39
+ }
40
+ let redacted = url.replace(
41
+ /([?&](?:access_token|token)=)([^&#\s]*)/gi,
42
+ (_match, prefix) => `${prefix}${REDACTED}`
43
+ );
44
+ redacted = redacted.replace(SECRET_ASSIGNMENT, maskAssignment);
45
+ return redacted;
46
+ }
47
+ function scrubSecrets(text, secrets = []) {
48
+ if (typeof text !== "string" || text.length === 0) {
49
+ return text;
50
+ }
51
+ let scrubbed = text;
52
+ const known = secrets.filter((secret) => typeof secret === "string" && secret.length > 0).sort((a, b) => b.length - a.length);
53
+ for (const secret of known) {
54
+ scrubbed = scrubbed.split(secret).join(REDACTED);
55
+ }
56
+ scrubbed = scrubbed.replace(SECRET_ASSIGNMENT, maskAssignment);
57
+ return scrubbed;
58
+ }
59
+ function isSensitiveKey(key) {
60
+ return SENSITIVE_QUERY_KEYS.includes(key.toLowerCase());
61
+ }
62
+
63
+ // src/core/errors.ts
64
+ var ERROR_CODES = [
65
+ "UNSUPPORTED_ON_PROVIDER",
66
+ "AUTH_MISSING",
67
+ "AUTH_INVALID",
68
+ "NOT_FOUND",
69
+ "RATE_LIMITED",
70
+ "PROVIDER_ERROR",
71
+ "INVALID_ARGUMENT",
72
+ "NETWORK_ERROR",
73
+ "READONLY_BLOCKED",
74
+ "PAGINATION_LIMIT"
75
+ ];
76
+ var DEFAULT_RETRYABLE = {
77
+ UNSUPPORTED_ON_PROVIDER: false,
78
+ AUTH_MISSING: false,
79
+ AUTH_INVALID: false,
80
+ NOT_FOUND: false,
81
+ RATE_LIMITED: true,
82
+ PROVIDER_ERROR: false,
83
+ INVALID_ARGUMENT: false,
84
+ NETWORK_ERROR: true,
85
+ READONLY_BLOCKED: false,
86
+ PAGINATION_LIMIT: false
87
+ };
88
+ function defaultRetryable(code) {
89
+ return DEFAULT_RETRYABLE[code];
90
+ }
91
+ var GitForgeError = class _GitForgeError extends Error {
92
+ code;
93
+ provider;
94
+ status;
95
+ requestId;
96
+ capability;
97
+ retryable;
98
+ cause;
99
+ constructor(init) {
100
+ super(truncate(scrubSecrets(init.message, init.secrets), 1024));
101
+ this.name = "GitForgeError";
102
+ this.code = init.code;
103
+ this.provider = init.provider;
104
+ this.status = init.status;
105
+ this.requestId = init.requestId === void 0 ? void 0 : truncate(scrubSecrets(init.requestId, init.secrets), 128);
106
+ this.capability = init.capability;
107
+ this.retryable = init.retryable ?? DEFAULT_RETRYABLE[init.code];
108
+ this.cause = init.cause === void 0 ? void 0 : "Underlying failure (details omitted)";
109
+ Object.setPrototypeOf(this, _GitForgeError.prototype);
110
+ }
111
+ /**
112
+ * Serializes the error without headers, token values or the cause chain.
113
+ *
114
+ * Optional fields are omitted rather than set to `undefined`, so a JSON
115
+ * round-trip cannot reintroduce a key that was never known.
116
+ */
117
+ toJSON() {
118
+ const json = {
119
+ code: this.code,
120
+ message: this.message,
121
+ retryable: this.retryable
122
+ };
123
+ if (this.provider !== void 0) {
124
+ json.provider = this.provider;
125
+ }
126
+ if (this.status !== void 0) {
127
+ json.status = this.status;
128
+ }
129
+ if (this.requestId !== void 0) {
130
+ json.requestId = this.requestId;
131
+ }
132
+ if (this.capability !== void 0) {
133
+ json.capability = this.capability;
134
+ }
135
+ return json;
136
+ }
137
+ };
138
+ function isGitForgeError(value) {
139
+ return value instanceof GitForgeError;
140
+ }
141
+ var REQUEST_ID_HEADER_KEYS = ["x-github-request-id", "x-request-id"];
142
+ function extractRequestId(headers, body) {
143
+ if (headers !== void 0) {
144
+ for (const key of REQUEST_ID_HEADER_KEYS) {
145
+ const value = readHeader(headers, key);
146
+ if (value !== void 0 && value.length > 0) {
147
+ return value;
148
+ }
149
+ }
150
+ }
151
+ if (body !== null && typeof body === "object" && "trace_id" in body) {
152
+ const traceId = body.trace_id;
153
+ if (typeof traceId === "string" && traceId.length > 0) {
154
+ return traceId;
155
+ }
156
+ }
157
+ return void 0;
158
+ }
159
+ function readHeader(headers, key) {
160
+ if (typeof headers.get === "function") {
161
+ const value = headers.get(key);
162
+ return value === null ? void 0 : value;
163
+ }
164
+ const record = headers;
165
+ return record[key] ?? record[key.toLowerCase()];
166
+ }
167
+ function extractUpstreamMessage(body, maxLength = 200, secrets) {
168
+ if (body === null || typeof body !== "object") {
169
+ return void 0;
170
+ }
171
+ const record = body;
172
+ for (const key of ["message", "error_message", "error", "errors"]) {
173
+ const value = record[key];
174
+ if (typeof value === "string" && value.length > 0) {
175
+ return truncate(scrubSecrets(value, secrets), maxLength);
176
+ }
177
+ }
178
+ return void 0;
179
+ }
180
+ function truncate(value, maxLength) {
181
+ return value.length <= maxLength ? value : `${value.slice(0, maxLength)}\u2026`;
182
+ }
183
+ function isRateLimitResponse(status, headers) {
184
+ if (status === 429) {
185
+ return true;
186
+ }
187
+ if (status !== 403 || headers === void 0) {
188
+ return false;
189
+ }
190
+ const remaining = readHeader(headers, "x-ratelimit-remaining");
191
+ return remaining !== void 0 && remaining.trim() === "0";
192
+ }
193
+ function describeProvider(provider) {
194
+ return provider === void 0 ? "the provider" : `provider=${provider}`;
195
+ }
196
+ function errorFromResponse(params) {
197
+ const { provider, status, headers, body, context, secrets } = params;
198
+ const code = mapStatusToCode(status, headers);
199
+ const requestId = extractRequestId(headers, body);
200
+ const upstream = extractUpstreamMessage(body, 200, secrets);
201
+ const detail = upstream === void 0 ? "" : `: ${upstream}`;
202
+ const message = `${context} failed with HTTP ${status} (${describeProvider(provider)})${detail}`;
203
+ return new GitForgeError({
204
+ code,
205
+ message,
206
+ provider,
207
+ status,
208
+ requestId,
209
+ retryable: retryableForStatus(code, status),
210
+ secrets
211
+ });
212
+ }
213
+ function mapStatusToCode(status, headers) {
214
+ if (status === 401) {
215
+ return "AUTH_INVALID";
216
+ }
217
+ if (isRateLimitResponse(status, headers)) {
218
+ return "RATE_LIMITED";
219
+ }
220
+ if (status === 403) {
221
+ return "AUTH_INVALID";
222
+ }
223
+ if (status === 404) {
224
+ return "NOT_FOUND";
225
+ }
226
+ if (status === 400 || status === 422) {
227
+ return "INVALID_ARGUMENT";
228
+ }
229
+ return "PROVIDER_ERROR";
230
+ }
231
+ function retryableForStatus(code, status) {
232
+ if (code === "RATE_LIMITED") {
233
+ return true;
234
+ }
235
+ if (code === "PROVIDER_ERROR") {
236
+ return status >= 500;
237
+ }
238
+ if (code === "NETWORK_ERROR") {
239
+ return true;
240
+ }
241
+ return DEFAULT_RETRYABLE[code];
242
+ }
243
+ function errorFromNetwork(params) {
244
+ const { provider, context, cause, secrets, timeoutMs } = params;
245
+ const reason = describeNetworkCause(cause, timeoutMs);
246
+ return new GitForgeError({
247
+ code: "NETWORK_ERROR",
248
+ status: params.response?.status,
249
+ requestId: extractRequestId(params.response?.headers),
250
+ message: `${context} failed: ${reason} (${describeProvider(provider)})`,
251
+ provider,
252
+ retryable: params.retryable ?? true,
253
+ cause,
254
+ secrets
255
+ });
256
+ }
257
+ function describeNetworkCause(cause, timeoutMs) {
258
+ if (timeoutMs !== void 0) {
259
+ const name = cause instanceof Error ? cause.name : "";
260
+ if (name === "TimeoutError" || name === "AbortError") {
261
+ return `request timed out after ${timeoutMs}ms`;
262
+ }
263
+ }
264
+ if (cause instanceof Error && cause.message.length > 0) {
265
+ return `network error (${cause.name})`;
266
+ }
267
+ return "network error";
268
+ }
269
+ function unsupportedCapabilityError(provider, capability) {
270
+ return new GitForgeError({
271
+ code: "UNSUPPORTED_ON_PROVIDER",
272
+ message: `${String(capability)} is not supported on provider=${provider}`,
273
+ provider,
274
+ capability
275
+ });
276
+ }
277
+ function authMissingError(provider, envVar) {
278
+ return new GitForgeError({
279
+ code: "AUTH_MISSING",
280
+ message: `No token configured for provider=${provider}. Set ${envVar} and retry.`,
281
+ provider
282
+ });
283
+ }
284
+ function readonlyBlockedError(provider, capability, method) {
285
+ return new GitForgeError({
286
+ code: "READONLY_BLOCKED",
287
+ message: `${method} is a write operation (${capability}) and was blocked because the client is read-only. Construct the client without \`readonly\` to allow writes.`,
288
+ provider,
289
+ capability
290
+ });
291
+ }
292
+ function invalidArgumentError(message, provider, capability) {
293
+ return new GitForgeError({ code: "INVALID_ARGUMENT", message, provider, capability });
294
+ }
295
+
296
+ // src/core/paginate.ts
297
+ var DEFAULT_PER_PAGE = 100;
298
+ var MAX_PER_PAGE = 100;
299
+ var DEFAULT_MAX_PAGES = 10;
300
+ var MAX_PAGES_LIMIT = 100;
301
+ var LINK_ENTRY = /<([^>]+)>\s*;\s*rel\s*=\s*['"]?([^'";,]+?)['"]?\s*(?:,|$)/g;
302
+ function parseLinkHeader(header) {
303
+ const result = {};
304
+ if (header === null || header === void 0) {
305
+ return result;
306
+ }
307
+ LINK_ENTRY.lastIndex = 0;
308
+ let match = LINK_ENTRY.exec(header);
309
+ while (match !== null) {
310
+ const url = match[1];
311
+ const rel = match[2];
312
+ if (url !== void 0 && rel !== void 0) {
313
+ for (const token of rel.toLowerCase().split(/\s+/)) {
314
+ if (token.length > 0 && result[token] === void 0) {
315
+ result[token] = url;
316
+ }
317
+ }
318
+ }
319
+ match = LINK_ENTRY.exec(header);
320
+ }
321
+ return result;
322
+ }
323
+ function positivePageNumber(raw) {
324
+ if (raw === void 0 || !/^\d+$/.test(raw)) return null;
325
+ const value = Number(raw);
326
+ return Number.isSafeInteger(value) && value > 0 ? value : null;
327
+ }
328
+ function strictLinkHint(header, page) {
329
+ if (!header?.trim()) return void 0;
330
+ const link = /<([^<>\s]+)>[ \t]*/y;
331
+ const param = /;[ \t]*([\w!#$%&'*+.^`|~-]+)(?:[ \t]*=[ \t]*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([\w!#$%&*+.^`|~-][\w!#$%&'*+.^`|~-]*)))?[ \t]*/y;
332
+ const separator = /(?:,[ \t]*)+/y;
333
+ const field = header.trim();
334
+ let cursor = separator.test(field) ? separator.lastIndex : 0;
335
+ if (cursor === field.length) return void 0;
336
+ let terminal = true;
337
+ while (cursor < field.length) {
338
+ link.lastIndex = cursor;
339
+ const target = link.exec(field)?.[1];
340
+ if (target === void 0) return void 0;
341
+ cursor = link.lastIndex;
342
+ let relations = [];
343
+ let anchored = false;
344
+ while (field[cursor] === ";") {
345
+ param.lastIndex = cursor;
346
+ const attribute = param.exec(field);
347
+ const name = attribute?.[1]?.toLowerCase();
348
+ if (name === void 0) return void 0;
349
+ cursor = param.lastIndex;
350
+ if (name === "anchor") anchored = true;
351
+ if (name === "rel" && relations.length === 0) {
352
+ const value = attribute?.[2] ?? attribute?.[3] ?? attribute?.[4];
353
+ if (!value?.trim()) return void 0;
354
+ relations = value.trim().toLowerCase().split(/\s+/);
355
+ }
356
+ }
357
+ if (cursor < field.length) {
358
+ separator.lastIndex = cursor;
359
+ if (!separator.test(field)) return void 0;
360
+ cursor = separator.lastIndex;
361
+ }
362
+ if (!anchored && relations.includes("next")) return true;
363
+ if (!anchored && relations.includes("last")) {
364
+ const query = /^[^?#]*\?([^#]*)/.exec(target)?.[1];
365
+ const pages = new URLSearchParams(query).getAll("page");
366
+ const last = pages.length === 1 ? positivePageNumber(pages[0]) : null;
367
+ if (last !== null && last > page) return true;
368
+ if (last !== page) terminal = false;
369
+ } else if (anchored || relations.length === 0 || !relations.every(isBackwardRelation)) {
370
+ terminal = false;
371
+ }
372
+ }
373
+ return terminal ? false : void 0;
374
+ }
375
+ function isBackwardRelation(relation) {
376
+ return relation === "prev" || relation === "first";
377
+ }
378
+ function resolveNextPage(signals, strict = false) {
379
+ const { link, totalPage, page, itemCount, perPage } = signals;
380
+ if (strict) {
381
+ const linkHint = strictLinkHint(link, page);
382
+ if (linkHint === true) return true;
383
+ if (totalPage !== null && Number.isSafeInteger(totalPage) && totalPage > 0) {
384
+ return page < totalPage;
385
+ }
386
+ if (linkHint === false) return false;
387
+ } else {
388
+ if (parseLinkHeader(link).next !== void 0) return true;
389
+ if (totalPage !== null && Number.isFinite(totalPage)) return page < totalPage;
390
+ }
391
+ return itemCount >= perPage && itemCount > 0;
392
+ }
393
+ function readTotalPage(headers) {
394
+ const raw = readHeader2(headers, "total_page") ?? readHeader2(headers, "x-total-pages");
395
+ if (raw === void 0) {
396
+ return null;
397
+ }
398
+ const value = Number(raw.trim());
399
+ if (!Number.isInteger(value) || value <= 0) {
400
+ return null;
401
+ }
402
+ return value;
403
+ }
404
+ function readStrictTotalPage(headers) {
405
+ const totalPage = positivePageNumber(readHeader2(headers, "total_page")?.trim());
406
+ const alias = positivePageNumber(readHeader2(headers, "x-total-pages")?.trim());
407
+ return totalPage === null || alias === null ? totalPage ?? alias : Math.max(totalPage, alias);
408
+ }
409
+ function readTotalCount(headers) {
410
+ const raw = readHeader2(headers, "total_count") ?? readHeader2(headers, "x-total-count");
411
+ if (raw === void 0) {
412
+ return null;
413
+ }
414
+ const value = Number(raw.trim());
415
+ return Number.isInteger(value) && value >= 0 ? value : null;
416
+ }
417
+ function readHeader2(headers, key) {
418
+ if (headers === void 0) {
419
+ return void 0;
420
+ }
421
+ if (typeof headers.get === "function") {
422
+ const value = headers.get(key);
423
+ return value === null ? void 0 : value;
424
+ }
425
+ const record = headers;
426
+ return record[key] ?? record[key.toLowerCase()];
427
+ }
428
+ function dedupeBy(items, keyOf) {
429
+ const seen = /* @__PURE__ */ new Set();
430
+ const out = [];
431
+ for (const item of items) {
432
+ const key = keyOf(item);
433
+ if (seen.has(key)) {
434
+ continue;
435
+ }
436
+ seen.add(key);
437
+ out.push(item);
438
+ }
439
+ return out;
440
+ }
441
+ function normalizePerPage(value) {
442
+ if (value === void 0 || !Number.isFinite(value)) {
443
+ return DEFAULT_PER_PAGE;
444
+ }
445
+ return Math.min(Math.max(Math.trunc(value), 1), MAX_PER_PAGE);
446
+ }
447
+ function normalizeMaxPages(value) {
448
+ if (value === void 0 || !Number.isFinite(value)) {
449
+ return DEFAULT_MAX_PAGES;
450
+ }
451
+ return Math.min(Math.max(Math.trunc(value), 1), MAX_PAGES_LIMIT);
452
+ }
453
+ async function collectPages(http, spec, options) {
454
+ const perPage = normalizePerPage(options.perPage);
455
+ const maxPages = normalizeMaxPages(options.maxPages);
456
+ const strict = options.requireComplete === true;
457
+ const collected = [];
458
+ const baseQuery = { ...spec.query, ...options.query };
459
+ for (let page = 1; page <= maxPages; page += 1) {
460
+ const response = await http.request({
461
+ ...spec,
462
+ query: {
463
+ ...baseQuery,
464
+ per_page: perPage,
465
+ page
466
+ }
467
+ });
468
+ const items = options.selectItems(response.json, { page, response });
469
+ collected.push(...items);
470
+ const hasNext = resolveNextPage(
471
+ {
472
+ link: readHeader2(response.headers, "link") ?? null,
473
+ totalPage: strict ? readStrictTotalPage(response.headers) : readTotalPage(response.headers),
474
+ page,
475
+ itemCount: items.length,
476
+ perPage
477
+ },
478
+ strict
479
+ );
480
+ if (!hasNext) {
481
+ break;
482
+ }
483
+ if (strict && page === maxPages) {
484
+ throw new GitForgeError({
485
+ code: "PAGINATION_LIMIT",
486
+ provider: http.provider,
487
+ message: `The page budget (maxPages=${maxPages}) ended while more pages were indicated.`
488
+ });
489
+ }
490
+ }
491
+ return dedupeBy(collected, options.keyOf);
492
+ }
493
+
494
+ // src/adapters/pulls.ts
495
+ function decimalPullNumber(value) {
496
+ const n = typeof value === "string" && value.length > 0 && !/\D/.test(value) ? Number(value) : value;
497
+ return typeof n === "number" && Number.isSafeInteger(n) && n > 0 ? n : void 0;
498
+ }
499
+ function requirePullNumber(http, response, raw, expected) {
500
+ const record = raw !== null && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
501
+ const iid = http.provider === "atomgit" ? record.iid : void 0;
502
+ const n = decimalPullNumber(record.number === void 0 ? iid : record.number);
503
+ if (n === void 0 || iid !== void 0 && decimalPullNumber(iid) !== n) {
504
+ throw http.invalidResponse(response, "Pull request is missing a valid, unambiguous number");
505
+ }
506
+ if (expected !== void 0 && n !== expected) {
507
+ throw http.invalidResponse(response, "Detail returned a different pull request number");
508
+ }
509
+ return n;
510
+ }
511
+ function pullFromResponse(map, ctx, params, response, options = {}) {
512
+ const raw = "raw" in options ? options.raw : response.json;
513
+ const number = requirePullNumber(ctx.http, response, raw, options.expectedNumber);
514
+ const base2 = raw?.base;
515
+ if (typeof base2?.ref !== "string" || !base2.ref.trim() || typeof base2.sha !== "string" || !base2.sha.trim()) {
516
+ throw ctx.http.invalidResponse(
517
+ response,
518
+ "Pull request response is missing its required base ref or SHA"
519
+ );
520
+ }
521
+ return map(params.owner, params.repo, raw, { ref: base2.ref, sha: base2.sha }, number);
522
+ }
523
+ async function collectPullRequests(ctx, params, map, options) {
524
+ const collected = /* @__PURE__ */ new Map();
525
+ for (const state of options.states) {
526
+ const rows = await collectPages(
527
+ ctx.http,
528
+ {
529
+ method: "GET",
530
+ path: "/repos/{owner}/{repo}/pulls",
531
+ pathParams: { owner: params.owner, repo: params.repo },
532
+ headers: options.headers,
533
+ query: { ...options.query, state }
534
+ },
535
+ {
536
+ maxPages: params.maxPages,
537
+ selectItems: (raw, { response }) => {
538
+ if (!Array.isArray(raw))
539
+ throw ctx.http.invalidResponse(response, "Expected a pull request list");
540
+ return raw.map((item) => ({
541
+ pull: pullFromResponse(map, ctx, params, response, { raw: item }),
542
+ matches: options.matches?.(item) ?? true
543
+ }));
544
+ },
545
+ keyOf: (row) => String(row.pull.number)
546
+ }
547
+ );
548
+ for (const { pull, matches } of rows) {
549
+ if (matches && (!collected.has(pull.number) || pull.merged)) collected.set(pull.number, pull);
550
+ }
551
+ }
552
+ return [...collected.values()];
553
+ }
554
+ function contentsBase64(content, encoding = "utf8", provider) {
555
+ if (encoding === "utf8") return buffer.Buffer.from(content, "utf8").toString("base64");
556
+ const compact = content.replace(/\s+/g, "");
557
+ const canonical = buffer.Buffer.from(compact, "base64").toString("base64");
558
+ if (encoding !== "base64" || compact !== canonical && compact !== canonical.replace(/=+$/, "")) {
559
+ throw invalidArgumentError("Invalid `content`: expected base64", provider);
560
+ }
561
+ return canonical;
562
+ }
563
+ function confirmedSha(http, response, value) {
564
+ if (typeof value !== "string" || !value.trim()) {
565
+ throw http.invalidResponse(response, "The provider response did not confirm a Git object SHA");
566
+ }
567
+ return value;
568
+ }
569
+
570
+ // src/core/issue-number.ts
571
+ function issueNumberFields(number) {
572
+ if (/^\d+$/.test(number)) {
573
+ const numeric = Number(number);
574
+ if (Number.isSafeInteger(numeric)) {
575
+ return { number, number_as_number: numeric };
576
+ }
577
+ }
578
+ return { number };
579
+ }
580
+
581
+ // src/adapters/github/map.ts
582
+ var PROVIDER = "github";
583
+ var PUSH_ACTIONS = ["create", "update", "delete"];
584
+ function asRecord(value) {
585
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
586
+ }
587
+ function asArray(value) {
588
+ return Array.isArray(value) ? value : [];
589
+ }
590
+ function str(value) {
591
+ return typeof value === "string" && value.length > 0 ? value : void 0;
592
+ }
593
+ function num(value) {
594
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
595
+ }
596
+ function listKey(value) {
597
+ if (typeof value === "string") {
598
+ return value;
599
+ }
600
+ if (typeof value === "number" && Number.isFinite(value)) {
601
+ return String(value);
602
+ }
603
+ return "";
604
+ }
605
+ function bool(value) {
606
+ return typeof value === "boolean" ? value : void 0;
607
+ }
608
+ function normalizeLabels(raw) {
609
+ const out = [];
610
+ for (const entry of asArray(raw)) {
611
+ if (typeof entry === "string" && entry.length > 0) {
612
+ out.push(entry);
613
+ continue;
614
+ }
615
+ const name = str(asRecord(entry).name);
616
+ if (name !== void 0) {
617
+ out.push(name);
618
+ }
619
+ }
620
+ return out;
621
+ }
622
+ function mapUser(raw) {
623
+ const record = asRecord(raw);
624
+ const login = str(record.login) ?? str(record.name);
625
+ if (login === void 0) {
626
+ return void 0;
627
+ }
628
+ const user = { login };
629
+ const name = str(record.name);
630
+ const avatar = str(record.avatar_url);
631
+ if (name !== void 0) {
632
+ user.name = name;
633
+ }
634
+ if (avatar !== void 0) {
635
+ user.avatar_url = avatar;
636
+ }
637
+ return user;
638
+ }
639
+ function mapUsers(raw) {
640
+ const users = asArray(raw).map((entry) => mapUser(entry)).filter((entry) => entry !== void 0);
641
+ return users.length > 0 ? users : void 0;
642
+ }
643
+ function mapIssueState(raw) {
644
+ return raw === "open" ? "open" : "closed";
645
+ }
646
+ function mapPullRequestState(raw) {
647
+ return raw === "open" ? "open" : "closed";
648
+ }
649
+ function isPullRequestEntry(raw) {
650
+ const marker = asRecord(asRecord(raw).pull_request);
651
+ const url = str(marker.url);
652
+ return url !== void 0 && /^https?:\/\//i.test(url) && URL.canParse(url);
653
+ }
654
+ function mapIssue(owner, repo, raw) {
655
+ const record = asRecord(raw);
656
+ const issue = {
657
+ provider: PROVIDER,
658
+ owner,
659
+ repo,
660
+ ...issueNumberFields(listKey(record.number)),
661
+ title: str(record.title) ?? "",
662
+ state: mapIssueState(record.state),
663
+ html_url: str(record.html_url) ?? "",
664
+ labels: normalizeLabels(record.labels),
665
+ created_at: str(record.created_at) ?? "",
666
+ updated_at: str(record.updated_at) ?? ""
667
+ };
668
+ const body = str(record.body);
669
+ if (body !== void 0) {
670
+ issue.body = body;
671
+ }
672
+ const user = mapUser(record.user);
673
+ if (user !== void 0) {
674
+ issue.user = user;
675
+ }
676
+ const assignees = mapUsers(record.assignees);
677
+ if (assignees !== void 0) {
678
+ issue.assignees = assignees;
679
+ }
680
+ const comments = num(record.comments);
681
+ if (comments !== void 0) {
682
+ issue.comments_count = comments;
683
+ }
684
+ const closedAt = str(record.closed_at);
685
+ if (closedAt !== void 0) {
686
+ issue.closed_at = closedAt;
687
+ }
688
+ return issue;
689
+ }
690
+ function mapRef(raw) {
691
+ const record = asRecord(raw);
692
+ const ref = str(record.ref);
693
+ const sha = str(record.sha);
694
+ return ref !== void 0 && sha !== void 0 ? { ref, sha } : void 0;
695
+ }
696
+ function mapPullRequest(owner, repo, raw, base2, number) {
697
+ const record = asRecord(raw);
698
+ const merged = bool(record.merged) ?? str(record.merged_at) !== void 0;
699
+ const draft = {
700
+ base: base2,
701
+ provider: PROVIDER,
702
+ owner,
703
+ repo,
704
+ number,
705
+ title: str(record.title) ?? "",
706
+ state: merged ? "closed" : mapPullRequestState(record.state),
707
+ merged,
708
+ html_url: str(record.html_url) ?? "",
709
+ created_at: str(record.created_at) ?? "",
710
+ updated_at: str(record.updated_at) ?? ""
711
+ };
712
+ const head = mapRef(record.head);
713
+ if (head !== void 0) {
714
+ draft.head = head;
715
+ }
716
+ const mergedAt = str(record.merged_at);
717
+ if (mergedAt !== void 0) {
718
+ draft.merged_at = mergedAt;
719
+ }
720
+ const body = str(record.body);
721
+ if (body !== void 0) {
722
+ draft.body = body;
723
+ }
724
+ const isDraft = bool(record.draft);
725
+ if (isDraft !== void 0) {
726
+ draft.draft = isDraft;
727
+ }
728
+ const mergeable = bool(record.mergeable);
729
+ if (mergeable !== void 0) {
730
+ draft.mergeable = mergeable;
731
+ }
732
+ const user = mapUser(record.user);
733
+ if (user !== void 0) {
734
+ draft.user = user;
735
+ }
736
+ for (const key of ["additions", "deletions", "changed_files"]) {
737
+ const value = num(record[key]);
738
+ if (value !== void 0) {
739
+ draft[key] = value;
740
+ }
741
+ }
742
+ return draft;
743
+ }
744
+ function mapRepository(owner, repo, raw) {
745
+ const record = asRecord(raw);
746
+ const repository = {
747
+ provider: PROVIDER,
748
+ owner: str(asRecord(record.owner).login) ?? owner,
749
+ repo,
750
+ name: str(record.name) ?? repo,
751
+ html_url: str(record.html_url) ?? "",
752
+ private: bool(record.private) === true,
753
+ default_branch: str(record.default_branch) ?? ""
754
+ };
755
+ const fullName = str(record.full_name);
756
+ if (fullName !== void 0) {
757
+ repository.full_name = fullName;
758
+ }
759
+ const description = str(record.description);
760
+ if (description !== void 0) {
761
+ repository.description = description;
762
+ }
763
+ const fork = bool(record.fork);
764
+ if (fork !== void 0) {
765
+ repository.fork = fork;
766
+ }
767
+ const language = str(record.language);
768
+ if (language !== void 0) {
769
+ repository.language = language;
770
+ }
771
+ const createdAt = str(record.created_at);
772
+ if (createdAt !== void 0) {
773
+ repository.created_at = createdAt;
774
+ }
775
+ const updatedAt = str(record.updated_at);
776
+ if (updatedAt !== void 0) {
777
+ repository.updated_at = updatedAt;
778
+ }
779
+ return repository;
780
+ }
781
+ function mapFileContent(owner, repo, raw) {
782
+ const record = asRecord(raw);
783
+ const content = {
784
+ provider: PROVIDER,
785
+ owner,
786
+ repo,
787
+ path: str(record.path) ?? "",
788
+ content: typeof record.content === "string" ? record.content : "",
789
+ encoding: str(record.encoding) ?? "base64"
790
+ };
791
+ const sha = str(record.sha);
792
+ if (sha !== void 0) {
793
+ content.sha = sha;
794
+ }
795
+ const size = num(record.size);
796
+ if (size !== void 0) {
797
+ content.size = size;
798
+ }
799
+ const htmlUrl = str(record.html_url);
800
+ if (htmlUrl !== void 0) {
801
+ content.html_url = htmlUrl;
802
+ }
803
+ const type = str(record.type);
804
+ if (type !== void 0) {
805
+ content.type = type;
806
+ }
807
+ return content;
808
+ }
809
+ function deriveBranchHtmlUrl(webBaseUrl, owner, repo, name) {
810
+ const base2 = webBaseUrl.endsWith("/") ? webBaseUrl.slice(0, -1) : webBaseUrl;
811
+ if (base2.length === 0) {
812
+ return void 0;
813
+ }
814
+ return `${base2}/${owner}/${repo}/tree/${name}`;
815
+ }
816
+ function mapBranch(owner, repo, raw, webBaseUrl) {
817
+ const record = asRecord(raw);
818
+ const name = str(record.name) ?? "";
819
+ const branch = {
820
+ provider: PROVIDER,
821
+ owner,
822
+ repo,
823
+ name,
824
+ commit_sha: str(asRecord(record.commit).sha) ?? ""
825
+ };
826
+ const isProtected = bool(record.protected);
827
+ if (isProtected !== void 0) {
828
+ branch.protected = isProtected;
829
+ }
830
+ const htmlUrl = deriveBranchHtmlUrl(webBaseUrl, owner, repo, name);
831
+ if (htmlUrl !== void 0) {
832
+ branch.html_url = htmlUrl;
833
+ }
834
+ return branch;
835
+ }
836
+ function mapCommitAuthor(raw) {
837
+ const record = asRecord(raw);
838
+ const name = str(record.name);
839
+ if (name === void 0) {
840
+ return void 0;
841
+ }
842
+ return {
843
+ name,
844
+ email: str(record.email) ?? "",
845
+ date: str(record.date) ?? ""
846
+ };
847
+ }
848
+ function mapCommit(owner, repo, raw) {
849
+ const record = asRecord(raw);
850
+ const payload = asRecord(record.commit);
851
+ const commit = {
852
+ provider: PROVIDER,
853
+ owner,
854
+ repo,
855
+ sha: str(record.sha) ?? "",
856
+ message: str(payload.message) ?? "",
857
+ html_url: str(record.html_url) ?? ""
858
+ };
859
+ const author = mapCommitAuthor(payload.author);
860
+ if (author !== void 0) {
861
+ commit.author = author;
862
+ }
863
+ const committer = mapCommitAuthor(payload.committer);
864
+ if (committer !== void 0) {
865
+ commit.committer = committer;
866
+ }
867
+ const parents = asArray(record.parents).map((entry) => str(asRecord(entry).sha)).filter((entry) => entry !== void 0);
868
+ if (parents.length > 0) {
869
+ commit.parents = parents;
870
+ }
871
+ return commit;
872
+ }
873
+ function mapComment(owner, repo, raw, parentUrl) {
874
+ const record = asRecord(raw);
875
+ const comment = {
876
+ provider: PROVIDER,
877
+ owner,
878
+ repo,
879
+ id: num(record.id) ?? Number(str(record.id) ?? 0),
880
+ body: typeof record.body === "string" ? record.body : "",
881
+ created_at: str(record.created_at) ?? ""
882
+ };
883
+ const htmlUrl = str(record.html_url) ?? parentUrl;
884
+ if (htmlUrl !== void 0 && htmlUrl.length > 0) {
885
+ comment.html_url = htmlUrl;
886
+ }
887
+ const updatedAt = str(record.updated_at);
888
+ if (updatedAt !== void 0) {
889
+ comment.updated_at = updatedAt;
890
+ }
891
+ const user = mapUser(record.user);
892
+ if (user !== void 0) {
893
+ comment.user = user;
894
+ }
895
+ return comment;
896
+ }
897
+ function buildFileWriteResult(inputs) {
898
+ const result = {
899
+ provider: PROVIDER,
900
+ owner: inputs.owner,
901
+ repo: inputs.repo,
902
+ commit_sha: inputs.commitSha,
903
+ commit_html_url: inputs.commitHtmlUrl,
904
+ paths: [...inputs.paths],
905
+ branch: inputs.branch ?? ""
906
+ };
907
+ if (inputs.fileHtmlUrls !== void 0) {
908
+ result.file_html_urls = inputs.fileHtmlUrls;
909
+ }
910
+ return result;
911
+ }
912
+ function isShaLike(value) {
913
+ return /^[0-9a-f]{7,40}$/i.test(value);
914
+ }
915
+ var BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
916
+ function isValidBase64(value) {
917
+ const compact = value.replace(/\s+/g, "");
918
+ const body = compact.replace(/={0,2}$/, "");
919
+ if (body.length === 0) {
920
+ return false;
921
+ }
922
+ if (body.length % 4 === 1) {
923
+ return false;
924
+ }
925
+ for (const char of body) {
926
+ if (!BASE64_ALPHABET.includes(char)) {
927
+ return false;
928
+ }
929
+ }
930
+ return true;
931
+ }
932
+ function readPushEntries(files) {
933
+ if (!Array.isArray(files) || files.length === 0) {
934
+ throw invalidArgumentError(
935
+ "Invalid `files`: pushFiles requires at least one entry (an empty batch would create an empty commit).",
936
+ PROVIDER,
937
+ "files.pushFiles"
938
+ );
939
+ }
940
+ return files.map((raw, index) => {
941
+ const file = asRecord(raw);
942
+ const path = file.path;
943
+ if (typeof path !== "string" || path.trim().length === 0) {
944
+ throw invalidArgumentError(
945
+ `Invalid \`files[${index}].path\`: expected a non-empty string.`,
946
+ PROVIDER,
947
+ "files.pushFiles"
948
+ );
949
+ }
950
+ const rawAction = file.action;
951
+ if (typeof rawAction !== "string" || !PUSH_ACTIONS.includes(rawAction)) {
952
+ throw invalidArgumentError(
953
+ `Invalid \`files[${index}].action\`: expected one of ${PUSH_ACTIONS.join(" | ")}, received ${describe(rawAction)}. pushFiles does not provide upsert.`,
954
+ PROVIDER,
955
+ "files.pushFiles"
956
+ );
957
+ }
958
+ const action = rawAction;
959
+ const rawEncoding = file.encoding ?? "utf8";
960
+ if (rawEncoding !== "utf8" && rawEncoding !== "base64") {
961
+ throw invalidArgumentError(
962
+ `Invalid \`files[${index}].encoding\`: expected utf8 | base64, received ${describe(rawEncoding)}.`,
963
+ PROVIDER,
964
+ "files.pushFiles"
965
+ );
966
+ }
967
+ const encoding = rawEncoding;
968
+ if (action === "delete") {
969
+ if (file.content !== void 0) {
970
+ throw invalidArgumentError(
971
+ `Invalid \`files[${index}]\`: action 'delete' must not carry content.`,
972
+ PROVIDER,
973
+ "files.pushFiles"
974
+ );
975
+ }
976
+ return { path, action, encoding };
977
+ }
978
+ const content = file.content;
979
+ if (typeof content !== "string") {
980
+ throw invalidArgumentError(
981
+ `Invalid \`files[${index}].content\`: action '${action}' requires content.`,
982
+ PROVIDER,
983
+ "files.pushFiles"
984
+ );
985
+ }
986
+ if (encoding === "base64" && !isValidBase64(content)) {
987
+ throw invalidArgumentError(
988
+ `Invalid \`files[${index}].content\`: not a valid base64 payload.`,
989
+ PROVIDER,
990
+ "files.pushFiles"
991
+ );
992
+ }
993
+ return { path, action, content, encoding };
994
+ });
995
+ }
996
+ function describe(value) {
997
+ if (value === void 0) {
998
+ return "undefined";
999
+ }
1000
+ if (typeof value === "string") {
1001
+ return value.length === 0 ? "an empty string" : `"${value}"`;
1002
+ }
1003
+ return typeof value;
1004
+ }
1005
+
1006
+ // src/adapters/github/tree.ts
1007
+ function resolveFileModes(http, response, entries) {
1008
+ const tree = asRecord(response.json);
1009
+ if (tree.truncated !== false || !Array.isArray(tree.tree)) {
1010
+ throw http.invalidResponse(response, "Cannot plan file changes without a complete Git tree");
1011
+ }
1012
+ const index = /* @__PURE__ */ new Map();
1013
+ for (const raw of tree.tree) {
1014
+ const item = asRecord(raw);
1015
+ if (typeof item.path !== "string" || !item.path || index.has(item.path)) {
1016
+ throw http.invalidResponse(response, "Ambiguous entries in the parent Git tree");
1017
+ }
1018
+ index.set(item.path, item);
1019
+ }
1020
+ const planned = new Set(entries.map(({ path }) => path));
1021
+ if (planned.size !== entries.length)
1022
+ throw invalidArgumentError("Duplicate paths in file batch", "github");
1023
+ return entries.map(({ path, action }) => {
1024
+ let ancestor = path;
1025
+ while (ancestor.includes("/")) {
1026
+ ancestor = ancestor.slice(0, ancestor.lastIndexOf("/"));
1027
+ const item = index.get(ancestor);
1028
+ if (planned.has(ancestor) || item && item.type !== "tree") {
1029
+ throw invalidArgumentError("A parent path conflicts with a file change", "github");
1030
+ }
1031
+ }
1032
+ const old = index.get(path);
1033
+ if (action === "create" && !old) return "100644";
1034
+ if (!old || action === "create")
1035
+ throw invalidArgumentError("File existence does not match the requested action", "github");
1036
+ if (old.type !== "blob" || old.mode !== "100644" && old.mode !== "100755") {
1037
+ throw invalidArgumentError("Only regular files can be updated or deleted", "github");
1038
+ }
1039
+ return old.mode;
1040
+ });
1041
+ }
1042
+
1043
+ // src/adapters/github/capabilities.ts
1044
+ var capabilities = {
1045
+ "issues.list": "supported",
1046
+ "issues.get": "supported",
1047
+ "issues.create": "supported",
1048
+ "issues.update": "supported",
1049
+ "issues.listComments": "supported",
1050
+ "issues.createComment": "supported",
1051
+ "pulls.list": "supported",
1052
+ "pulls.get": "supported",
1053
+ "pulls.create": "supported",
1054
+ "pulls.merge": "supported",
1055
+ "pulls.listComments": "supported",
1056
+ "pulls.createComment": "supported",
1057
+ "repos.list": "supported",
1058
+ "repos.get": "supported",
1059
+ "repos.create": "supported",
1060
+ "repos.getFileContents": "supported",
1061
+ "files.create": "supported",
1062
+ "files.update": "supported",
1063
+ "files.delete": "supported",
1064
+ "files.pushFiles": "supported",
1065
+ "branches.list": "supported",
1066
+ "branches.create": "supported",
1067
+ "commits.list": "supported",
1068
+ "commits.get": "supported"
1069
+ };
1070
+ var paramCapabilities = {
1071
+ "pulls.list.headFilter": "supported",
1072
+ "pulls.list.milestoneFilter": "supported",
1073
+ "issues.list.milestoneFilter": "supported",
1074
+ "files.pushFiles.atomic": "supported"
1075
+ };
1076
+
1077
+ // src/adapters/github/adapter.ts
1078
+ var GITHUB_HEADERS = {
1079
+ accept: "application/vnd.github+json",
1080
+ "x-github-api-version": "2022-11-28"
1081
+ };
1082
+ var REPO_PATH = "/repos/{owner}/{repo}";
1083
+ function base(owner, repo) {
1084
+ return { pathParams: { owner, repo }, headers: GITHUB_HEADERS };
1085
+ }
1086
+ function joinLabels(labels) {
1087
+ return labels === void 0 || labels.length === 0 ? void 0 : labels.join(",");
1088
+ }
1089
+ function assertCreation(params) {
1090
+ if (params.sha !== void 0) {
1091
+ throw invalidArgumentError(
1092
+ "Invalid `sha`: createFile creates a new file and must not receive a blob sha; use updateFile to replace an existing file.",
1093
+ "github"
1094
+ );
1095
+ }
1096
+ }
1097
+ function assertUpdate(params) {
1098
+ if (params.sha === void 0 || params.sha.length === 0) {
1099
+ throw invalidArgumentError(
1100
+ "Invalid `sha`: updateFile requires the current blob sha of the file being replaced.",
1101
+ "github"
1102
+ );
1103
+ }
1104
+ }
1105
+ function writeResultFromContents(ctx, owner, repo, branch, path, response, keepFileUrl) {
1106
+ const record = asRecord(response.json);
1107
+ const commit = asRecord(record.commit);
1108
+ const contentUrl = keepFileUrl ? str(asRecord(record.content).html_url) : void 0;
1109
+ const result = buildFileWriteResult({
1110
+ owner,
1111
+ repo,
1112
+ branch,
1113
+ paths: [path],
1114
+ commitSha: confirmedSha(ctx.http, response, commit.sha),
1115
+ commitHtmlUrl: str(commit.html_url) ?? ""
1116
+ });
1117
+ if (keepFileUrl) {
1118
+ result.file_html_urls = [contentUrl];
1119
+ }
1120
+ return result;
1121
+ }
1122
+ var GitHubAdapter = class {
1123
+ provider = "github";
1124
+ capabilities = capabilities;
1125
+ paramCapabilities = paramCapabilities;
1126
+ /* ---------------------------------------------------------------------- */
1127
+ /* Issue */
1128
+ /* ---------------------------------------------------------------------- */
1129
+ async listIssues(ctx, params) {
1130
+ const { owner, repo } = params;
1131
+ const entries = await collectPages(
1132
+ ctx.http,
1133
+ { method: "GET", path: `${REPO_PATH}/issues`, ...base(owner, repo) },
1134
+ {
1135
+ maxPages: params.maxPages,
1136
+ requireComplete: params.requireComplete,
1137
+ query: {
1138
+ state: params.state,
1139
+ labels: joinLabels(params.labels),
1140
+ milestone: params.milestone
1141
+ },
1142
+ selectItems: (_raw, { response }) => selectIssueRows(ctx.http, response, isPullRequestEntry),
1143
+ keyOf: (raw) => listKey(asRecord(raw).number)
1144
+ }
1145
+ );
1146
+ return entries.filter((entry) => !isPullRequestEntry(entry)).map((entry) => mapIssue(owner, repo, entry));
1147
+ }
1148
+ async getIssue(ctx, params) {
1149
+ const response = await ctx.http.request({
1150
+ method: "GET",
1151
+ path: `${REPO_PATH}/issues/{number}`,
1152
+ pathParams: { owner: params.owner, repo: params.repo, number: String(params.number) },
1153
+ headers: GITHUB_HEADERS
1154
+ });
1155
+ return mapIssue(params.owner, params.repo, response.json);
1156
+ }
1157
+ async createIssue(ctx, params) {
1158
+ const response = await ctx.http.request({
1159
+ method: "POST",
1160
+ path: `${REPO_PATH}/issues`,
1161
+ ...base(params.owner, params.repo),
1162
+ body: {
1163
+ title: params.title,
1164
+ body: params.body,
1165
+ labels: params.labels,
1166
+ milestone: params.milestone
1167
+ }
1168
+ });
1169
+ return mapIssue(params.owner, params.repo, response.json);
1170
+ }
1171
+ async updateIssue(ctx, params) {
1172
+ const response = await ctx.http.request({
1173
+ method: "PATCH",
1174
+ path: `${REPO_PATH}/issues/{number}`,
1175
+ pathParams: { owner: params.owner, repo: params.repo, number: String(params.number) },
1176
+ headers: GITHUB_HEADERS,
1177
+ body: {
1178
+ title: params.title,
1179
+ body: params.body,
1180
+ state: params.state,
1181
+ labels: params.labels,
1182
+ milestone: params.milestone
1183
+ }
1184
+ });
1185
+ return mapIssue(params.owner, params.repo, response.json);
1186
+ }
1187
+ async listIssueComments(ctx, params) {
1188
+ return this.listComments(ctx, params, `${REPO_PATH}/issues/{number}/comments`);
1189
+ }
1190
+ async createIssueComment(ctx, params) {
1191
+ return this.createComment(ctx, params, `${REPO_PATH}/issues/{number}/comments`);
1192
+ }
1193
+ /* ---------------------------------------------------------------------- */
1194
+ /* Pull request */
1195
+ /* ---------------------------------------------------------------------- */
1196
+ async listPullRequests(ctx, params) {
1197
+ return collectPullRequests(ctx, params, mapPullRequest, {
1198
+ states: [params.state],
1199
+ headers: GITHUB_HEADERS,
1200
+ query: { head: params.head, base: params.base },
1201
+ matches: (entry) => {
1202
+ const record = asRecord(entry);
1203
+ const labels = normalizeLabels(record.labels).map((label) => label.toLowerCase());
1204
+ return (params.milestone === void 0 || asRecord(record.milestone).number === params.milestone) && (params.labels ?? []).every((label) => labels.includes(label.toLowerCase()));
1205
+ }
1206
+ });
1207
+ }
1208
+ async getPullRequest(ctx, params) {
1209
+ const response = await ctx.http.request({
1210
+ method: "GET",
1211
+ path: `${REPO_PATH}/pulls/{number}`,
1212
+ pathParams: { owner: params.owner, repo: params.repo, number: String(params.number) },
1213
+ headers: GITHUB_HEADERS
1214
+ });
1215
+ return pullFromResponse(mapPullRequest, ctx, params, response, {
1216
+ expectedNumber: params.number
1217
+ });
1218
+ }
1219
+ async createPullRequest(ctx, params) {
1220
+ const response = await ctx.http.request({
1221
+ method: "POST",
1222
+ path: `${REPO_PATH}/pulls`,
1223
+ ...base(params.owner, params.repo),
1224
+ body: {
1225
+ title: params.title,
1226
+ head: params.head,
1227
+ base: params.base,
1228
+ body: params.body,
1229
+ draft: params.draft
1230
+ }
1231
+ });
1232
+ return pullFromResponse(mapPullRequest, ctx, params, response);
1233
+ }
1234
+ async mergePullRequest(ctx, params) {
1235
+ await ctx.http.request({
1236
+ method: "PUT",
1237
+ path: `${REPO_PATH}/pulls/{number}/merge`,
1238
+ pathParams: { owner: params.owner, repo: params.repo, number: String(params.number) },
1239
+ headers: GITHUB_HEADERS,
1240
+ body: {
1241
+ merge_method: params.merge_method,
1242
+ commit_title: params.commit_title,
1243
+ commit_message: params.commit_message
1244
+ }
1245
+ });
1246
+ return this.getPullRequest(ctx, params);
1247
+ }
1248
+ async listPullRequestComments(ctx, params) {
1249
+ return this.listComments(ctx, params, `${REPO_PATH}/issues/{number}/comments`);
1250
+ }
1251
+ async createPullRequestComment(ctx, params) {
1252
+ return this.createComment(ctx, params, `${REPO_PATH}/issues/{number}/comments`);
1253
+ }
1254
+ /* ---------------------------------------------------------------------- */
1255
+ /* Repository */
1256
+ /* ---------------------------------------------------------------------- */
1257
+ async listRepositories(ctx, params) {
1258
+ const path = params.org !== void 0 ? "/orgs/{org}/repos" : params.user !== void 0 ? "/users/{user}/repos" : "/user/repos";
1259
+ const pathParams = params.org !== void 0 ? { org: params.org } : params.user !== void 0 ? { user: params.user } : {};
1260
+ const entries = await collectPages(
1261
+ ctx.http,
1262
+ { method: "GET", path, pathParams, headers: GITHUB_HEADERS },
1263
+ {
1264
+ maxPages: params.maxPages,
1265
+ selectItems: (raw) => asArray(raw),
1266
+ keyOf: (raw) => listKey(asRecord(raw).id ?? asRecord(raw).full_name)
1267
+ }
1268
+ );
1269
+ return entries.map((entry) => {
1270
+ const record = asRecord(entry);
1271
+ const fullName = str(record.full_name) ?? "";
1272
+ const [ownerFromPayload, repoFromPayload] = fullName.split("/");
1273
+ const owner = str(asRecord(record.owner).login) ?? ownerFromPayload ?? "";
1274
+ const repo = str(record.name) ?? repoFromPayload ?? "";
1275
+ return mapRepository(owner, repo, record);
1276
+ });
1277
+ }
1278
+ async getRepository(ctx, params) {
1279
+ const response = await ctx.http.request({
1280
+ method: "GET",
1281
+ path: REPO_PATH,
1282
+ ...base(params.owner, params.repo)
1283
+ });
1284
+ const record = asRecord(response.json);
1285
+ const owner = str(asRecord(record.owner).login) ?? params.owner;
1286
+ return mapRepository(owner, params.repo, record);
1287
+ }
1288
+ async createRepository(ctx, params) {
1289
+ const path = params.org !== void 0 ? "/orgs/{org}/repos" : "/user/repos";
1290
+ const pathParams = params.org !== void 0 ? { org: params.org } : {};
1291
+ const response = await ctx.http.request({
1292
+ method: "POST",
1293
+ path,
1294
+ pathParams,
1295
+ headers: GITHUB_HEADERS,
1296
+ body: {
1297
+ name: params.name,
1298
+ description: params.description,
1299
+ private: params.private,
1300
+ auto_init: params.auto_init
1301
+ }
1302
+ });
1303
+ const record = asRecord(response.json);
1304
+ const owner = str(asRecord(record.owner).login) ?? params.org ?? "";
1305
+ const repo = str(record.name) ?? params.name;
1306
+ return mapRepository(owner, repo, record);
1307
+ }
1308
+ async getFileContents(ctx, params) {
1309
+ const response = await ctx.http.request({
1310
+ method: "GET",
1311
+ path: `${REPO_PATH}/contents/{path}`,
1312
+ pathParams: { owner: params.owner, repo: params.repo, path: params.path },
1313
+ query: { ref: params.ref },
1314
+ headers: GITHUB_HEADERS
1315
+ });
1316
+ if (Array.isArray(response.json)) {
1317
+ throw invalidArgumentError(
1318
+ `Invalid \`path\`: "${params.path}" is a directory. v0.1.0 getFileContents reads a single file only.`,
1319
+ "github"
1320
+ );
1321
+ }
1322
+ return mapFileContent(params.owner, params.repo, response.json);
1323
+ }
1324
+ /* ---------------------------------------------------------------------- */
1325
+ /* Files */
1326
+ /* ---------------------------------------------------------------------- */
1327
+ async createFile(ctx, params) {
1328
+ assertCreation(params);
1329
+ return this.putContents(ctx, params);
1330
+ }
1331
+ async updateFile(ctx, params) {
1332
+ assertUpdate(params);
1333
+ return this.putContents(ctx, params);
1334
+ }
1335
+ async deleteFile(ctx, params) {
1336
+ const response = await ctx.http.request({
1337
+ method: "DELETE",
1338
+ path: `${REPO_PATH}/contents/{path}`,
1339
+ pathParams: { owner: params.owner, repo: params.repo, path: params.path },
1340
+ headers: GITHUB_HEADERS,
1341
+ body: { message: params.message, sha: params.sha, branch: params.branch }
1342
+ });
1343
+ return writeResultFromContents(
1344
+ ctx,
1345
+ params.owner,
1346
+ params.repo,
1347
+ params.branch,
1348
+ params.path,
1349
+ response,
1350
+ false
1351
+ );
1352
+ }
1353
+ async pushFiles(ctx, params) {
1354
+ const entries = readPushEntries(params.files);
1355
+ const { owner, repo } = params;
1356
+ const refResponse = await ctx.http.request({
1357
+ method: "GET",
1358
+ path: `${REPO_PATH}/git/ref/heads/{branch}`,
1359
+ pathParams: { owner, repo, branch: params.branch },
1360
+ headers: GITHUB_HEADERS
1361
+ });
1362
+ const commitSha = confirmedSha(
1363
+ ctx.http,
1364
+ refResponse,
1365
+ asRecord(asRecord(refResponse.json).object).sha
1366
+ );
1367
+ const commitResponse = await ctx.http.request({
1368
+ method: "GET",
1369
+ path: `${REPO_PATH}/git/commits/{sha}`,
1370
+ pathParams: { owner, repo, sha: commitSha },
1371
+ headers: GITHUB_HEADERS
1372
+ });
1373
+ const baseTree = confirmedSha(
1374
+ ctx.http,
1375
+ commitResponse,
1376
+ asRecord(asRecord(commitResponse.json).tree).sha
1377
+ );
1378
+ const parentTree = await ctx.http.request({
1379
+ method: "GET",
1380
+ path: `${REPO_PATH}/git/trees/{sha}`,
1381
+ pathParams: { owner, repo, sha: baseTree },
1382
+ headers: GITHUB_HEADERS,
1383
+ query: { recursive: "1" }
1384
+ });
1385
+ const modes = resolveFileModes(ctx.http, parentTree, entries);
1386
+ const tree = [];
1387
+ for (const [index, entry] of entries.entries()) {
1388
+ tree.push(await this.treeEntry(ctx, owner, repo, entry, modes[index]));
1389
+ }
1390
+ const treeResponse = await ctx.http.request({
1391
+ method: "POST",
1392
+ path: `${REPO_PATH}/git/trees`,
1393
+ ...base(owner, repo),
1394
+ body: { base_tree: baseTree, tree }
1395
+ });
1396
+ const newTree = confirmedSha(ctx.http, treeResponse, asRecord(treeResponse.json).sha);
1397
+ const newCommitResponse = await ctx.http.request({
1398
+ method: "POST",
1399
+ path: `${REPO_PATH}/git/commits`,
1400
+ ...base(owner, repo),
1401
+ body: { message: params.message, tree: newTree, parents: [commitSha] }
1402
+ });
1403
+ const newCommit = asRecord(newCommitResponse.json);
1404
+ const newCommitSha = confirmedSha(ctx.http, newCommitResponse, newCommit.sha);
1405
+ const updated = await ctx.http.request({
1406
+ method: "PATCH",
1407
+ path: `${REPO_PATH}/git/refs/heads/{branch}`,
1408
+ pathParams: { owner, repo, branch: params.branch },
1409
+ headers: GITHUB_HEADERS,
1410
+ body: { sha: newCommitSha, force: false }
1411
+ });
1412
+ if (asRecord(asRecord(updated.json).object).sha !== newCommitSha) {
1413
+ throw ctx.http.invalidResponse(
1414
+ updated,
1415
+ "The provider did not confirm the updated branch tip"
1416
+ );
1417
+ }
1418
+ return buildFileWriteResult({
1419
+ owner,
1420
+ repo,
1421
+ branch: params.branch,
1422
+ paths: entries.map((entry) => entry.path),
1423
+ commitSha: newCommitSha,
1424
+ commitHtmlUrl: str(newCommit.html_url) ?? ""
1425
+ });
1426
+ }
1427
+ /* ---------------------------------------------------------------------- */
1428
+ /* Branch / Commit */
1429
+ /* ---------------------------------------------------------------------- */
1430
+ async listBranches(ctx, params) {
1431
+ const entries = await collectPages(
1432
+ ctx.http,
1433
+ { method: "GET", path: `${REPO_PATH}/branches`, ...base(params.owner, params.repo) },
1434
+ {
1435
+ maxPages: params.maxPages,
1436
+ selectItems: (raw) => asArray(raw),
1437
+ keyOf: (raw) => listKey(asRecord(raw).name)
1438
+ }
1439
+ );
1440
+ return entries.map((entry) => mapBranch(params.owner, params.repo, entry, ctx.webBaseUrl));
1441
+ }
1442
+ async createBranch(ctx, params) {
1443
+ const sha = isShaLike(params.from) ? params.from : await this.resolveBranchSha(ctx, params.owner, params.repo, params.from);
1444
+ const response = await ctx.http.request({
1445
+ method: "POST",
1446
+ path: `${REPO_PATH}/git/refs`,
1447
+ ...base(params.owner, params.repo),
1448
+ body: { ref: `refs/heads/${params.name}`, sha }
1449
+ });
1450
+ const objectSha = confirmedSha(
1451
+ ctx.http,
1452
+ response,
1453
+ asRecord(asRecord(response.json).object).sha
1454
+ );
1455
+ const branch = {
1456
+ provider: "github",
1457
+ owner: params.owner,
1458
+ repo: params.repo,
1459
+ name: params.name,
1460
+ commit_sha: objectSha
1461
+ };
1462
+ const htmlUrl = deriveBranchHtmlUrl(ctx.webBaseUrl, params.owner, params.repo, params.name);
1463
+ if (htmlUrl !== void 0) {
1464
+ branch.html_url = htmlUrl;
1465
+ }
1466
+ return branch;
1467
+ }
1468
+ async listCommits(ctx, params) {
1469
+ const entries = await collectPages(
1470
+ ctx.http,
1471
+ { method: "GET", path: `${REPO_PATH}/commits`, ...base(params.owner, params.repo) },
1472
+ {
1473
+ maxPages: params.maxPages,
1474
+ query: { sha: params.branch },
1475
+ selectItems: (raw) => asArray(raw),
1476
+ keyOf: (raw) => listKey(asRecord(raw).sha)
1477
+ }
1478
+ );
1479
+ return entries.map((entry) => mapCommit(params.owner, params.repo, entry));
1480
+ }
1481
+ async getCommit(ctx, params) {
1482
+ const response = await ctx.http.request({
1483
+ method: "GET",
1484
+ path: `${REPO_PATH}/commits/{sha}`,
1485
+ pathParams: { owner: params.owner, repo: params.repo, sha: params.sha },
1486
+ headers: GITHUB_HEADERS
1487
+ });
1488
+ return mapCommit(params.owner, params.repo, response.json);
1489
+ }
1490
+ /* ---------------------------------------------------------------------- */
1491
+ /* Internals */
1492
+ /* ---------------------------------------------------------------------- */
1493
+ /** Shared comment listing used by both issue and pull-request domains. */
1494
+ async listComments(ctx, params, path) {
1495
+ const entries = await collectPages(
1496
+ ctx.http,
1497
+ {
1498
+ method: "GET",
1499
+ path,
1500
+ pathParams: {
1501
+ owner: params.owner,
1502
+ repo: params.repo,
1503
+ number: String(params.number)
1504
+ },
1505
+ headers: GITHUB_HEADERS
1506
+ },
1507
+ {
1508
+ maxPages: params.maxPages,
1509
+ selectItems: (raw) => asArray(raw),
1510
+ keyOf: (raw) => listKey(asRecord(raw).id)
1511
+ }
1512
+ );
1513
+ return entries.map((entry) => mapComment(params.owner, params.repo, entry));
1514
+ }
1515
+ /** Shared comment creation used by both comment domains. */
1516
+ async createComment(ctx, params, path) {
1517
+ const response = await ctx.http.request({
1518
+ method: "POST",
1519
+ path,
1520
+ pathParams: {
1521
+ owner: params.owner,
1522
+ repo: params.repo,
1523
+ number: String(params.number)
1524
+ },
1525
+ headers: GITHUB_HEADERS,
1526
+ body: { body: params.body }
1527
+ });
1528
+ return mapComment(params.owner, params.repo, response.json);
1529
+ }
1530
+ /** PUTs a file through the `contents` upsert endpoint. */
1531
+ async putContents(ctx, params) {
1532
+ const response = await ctx.http.request({
1533
+ method: "PUT",
1534
+ path: `${REPO_PATH}/contents/{path}`,
1535
+ pathParams: { owner: params.owner, repo: params.repo, path: params.path },
1536
+ headers: GITHUB_HEADERS,
1537
+ body: {
1538
+ message: params.message,
1539
+ content: contentsBase64(params.content, params.encoding, "github"),
1540
+ branch: params.branch,
1541
+ sha: params.sha
1542
+ }
1543
+ });
1544
+ return writeResultFromContents(
1545
+ ctx,
1546
+ params.owner,
1547
+ params.repo,
1548
+ params.branch,
1549
+ params.path,
1550
+ response,
1551
+ true
1552
+ );
1553
+ }
1554
+ /** Builds one tree entry, creating a blob first for base64 payloads. */
1555
+ async treeEntry(ctx, owner, repo, entry, mode) {
1556
+ if (entry.action === "delete") {
1557
+ return { path: entry.path, mode, type: "blob", sha: null };
1558
+ }
1559
+ if (entry.encoding === "utf8") {
1560
+ return {
1561
+ path: entry.path,
1562
+ mode,
1563
+ type: "blob",
1564
+ content: entry.content
1565
+ };
1566
+ }
1567
+ const blobResponse = await ctx.http.request({
1568
+ method: "POST",
1569
+ path: `${REPO_PATH}/git/blobs`,
1570
+ ...base(owner, repo),
1571
+ body: { content: entry.content, encoding: "base64" }
1572
+ });
1573
+ const blobSha = confirmedSha(ctx.http, blobResponse, asRecord(blobResponse.json).sha);
1574
+ return { path: entry.path, mode, type: "blob", sha: blobSha };
1575
+ }
1576
+ /** Reads the commit sha a branch currently points at. */
1577
+ async resolveBranchSha(ctx, owner, repo, branch) {
1578
+ const response = await ctx.http.request({
1579
+ method: "GET",
1580
+ path: `${REPO_PATH}/git/ref/heads/{branch}`,
1581
+ pathParams: { owner, repo, branch },
1582
+ headers: GITHUB_HEADERS
1583
+ });
1584
+ const sha = str(asRecord(asRecord(response.json).object).sha);
1585
+ if (sha === void 0) {
1586
+ throw invalidArgumentError(
1587
+ `Cannot resolve "${branch}": the ref response carried no commit sha.`,
1588
+ "github"
1589
+ );
1590
+ }
1591
+ return sha;
1592
+ }
1593
+ };
1594
+ var githubAdapter = new GitHubAdapter();
1595
+
1596
+ // src/adapters/gitee/map.ts
1597
+ var PROVIDER2 = "gitee";
1598
+ var PUSH_ACTIONS2 = ["create", "update", "delete"];
1599
+ function asRecord2(value) {
1600
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
1601
+ }
1602
+ function asArray2(value) {
1603
+ return Array.isArray(value) ? value : [];
1604
+ }
1605
+ function str2(value) {
1606
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1607
+ }
1608
+ function num2(value) {
1609
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
1610
+ }
1611
+ function listKey2(value) {
1612
+ if (typeof value === "string") {
1613
+ return value;
1614
+ }
1615
+ if (typeof value === "number" && Number.isFinite(value)) {
1616
+ return String(value);
1617
+ }
1618
+ return "";
1619
+ }
1620
+ function bool2(value) {
1621
+ return typeof value === "boolean" ? value : void 0;
1622
+ }
1623
+ function normalizeLabels2(raw) {
1624
+ const out = [];
1625
+ for (const entry of asArray2(raw)) {
1626
+ if (typeof entry === "string" && entry.length > 0) {
1627
+ out.push(entry);
1628
+ continue;
1629
+ }
1630
+ const name = str2(asRecord2(entry).name);
1631
+ if (name !== void 0) {
1632
+ out.push(name);
1633
+ }
1634
+ }
1635
+ return out;
1636
+ }
1637
+ function mapUser2(raw) {
1638
+ const record = asRecord2(raw);
1639
+ const login = str2(record.login);
1640
+ const name = str2(record.name);
1641
+ if (login === void 0 && name === void 0) {
1642
+ return void 0;
1643
+ }
1644
+ const user = { login: login ?? name };
1645
+ if (name !== void 0) {
1646
+ user.name = name;
1647
+ }
1648
+ const avatar = str2(record.avatar_url);
1649
+ if (avatar !== void 0) {
1650
+ user.avatar_url = avatar;
1651
+ }
1652
+ return user;
1653
+ }
1654
+ function mapUsers2(raw) {
1655
+ const users = asArray2(raw).map((entry) => mapUser2(entry)).filter((entry) => entry !== void 0);
1656
+ return users.length > 0 ? users : void 0;
1657
+ }
1658
+ function mapIssueState2(raw) {
1659
+ return raw === "open" || raw === "progressing" ? "open" : "closed";
1660
+ }
1661
+ function mapPullRequestState2(raw) {
1662
+ return raw === "open" ? "open" : "closed";
1663
+ }
1664
+ function joinLabels2(labels) {
1665
+ return labels === void 0 || labels.length === 0 ? void 0 : labels.join(",");
1666
+ }
1667
+ function mapIssue2(owner, repo, raw) {
1668
+ const record = asRecord2(raw);
1669
+ const issue = {
1670
+ provider: PROVIDER2,
1671
+ owner,
1672
+ repo,
1673
+ ...issueNumberFields(listKey2(record.number)),
1674
+ title: str2(record.title) ?? "",
1675
+ state: mapIssueState2(record.state),
1676
+ html_url: str2(record.html_url) ?? "",
1677
+ labels: normalizeLabels2(record.labels),
1678
+ created_at: str2(record.created_at) ?? "",
1679
+ updated_at: str2(record.updated_at) ?? ""
1680
+ };
1681
+ const body = str2(record.body);
1682
+ if (body !== void 0) {
1683
+ issue.body = body;
1684
+ }
1685
+ const user = mapUser2(record.user);
1686
+ if (user !== void 0) {
1687
+ issue.user = user;
1688
+ }
1689
+ const assignees = mapUsers2(record.assignees);
1690
+ if (assignees !== void 0) {
1691
+ issue.assignees = assignees;
1692
+ }
1693
+ const comments = num2(record.comments);
1694
+ if (comments !== void 0) {
1695
+ issue.comments_count = comments;
1696
+ }
1697
+ const closedAt = str2(record.finished_at) ?? str2(record.closed_at);
1698
+ if (closedAt !== void 0) {
1699
+ issue.closed_at = closedAt;
1700
+ }
1701
+ return issue;
1702
+ }
1703
+ function mapRef2(raw) {
1704
+ const record = asRecord2(raw);
1705
+ const ref = str2(record.ref);
1706
+ const sha = str2(record.sha);
1707
+ return ref !== void 0 && sha !== void 0 ? { ref, sha } : void 0;
1708
+ }
1709
+ function mapPullRequest2(owner, repo, raw, base2, number) {
1710
+ const record = asRecord2(raw);
1711
+ const mergedAt = str2(record.merged_at);
1712
+ const state = str2(record.state);
1713
+ const merged = mergedAt !== void 0 || state === "merged";
1714
+ const draft = {
1715
+ base: base2,
1716
+ provider: PROVIDER2,
1717
+ owner,
1718
+ repo,
1719
+ number,
1720
+ title: str2(record.title) ?? "",
1721
+ state: merged ? "closed" : mapPullRequestState2(record.state),
1722
+ merged,
1723
+ html_url: str2(record.html_url) ?? "",
1724
+ created_at: str2(record.created_at) ?? "",
1725
+ updated_at: str2(record.updated_at) ?? ""
1726
+ };
1727
+ const head = mapRef2(record.head);
1728
+ if (head !== void 0) {
1729
+ draft.head = head;
1730
+ }
1731
+ if (mergedAt !== void 0) {
1732
+ draft.merged_at = mergedAt;
1733
+ }
1734
+ const body = str2(record.body);
1735
+ if (body !== void 0) {
1736
+ draft.body = body;
1737
+ }
1738
+ const isDraft = bool2(record.draft);
1739
+ if (isDraft !== void 0) {
1740
+ draft.draft = isDraft;
1741
+ }
1742
+ const mergeable = bool2(record.mergeable);
1743
+ if (mergeable !== void 0) {
1744
+ draft.mergeable = mergeable;
1745
+ }
1746
+ const user = mapUser2(record.user);
1747
+ if (user !== void 0) {
1748
+ draft.user = user;
1749
+ }
1750
+ for (const key of ["additions", "deletions", "changed_files"]) {
1751
+ const value = num2(record[key]);
1752
+ if (value !== void 0) {
1753
+ draft[key] = value;
1754
+ }
1755
+ }
1756
+ return draft;
1757
+ }
1758
+ function stripGitSuffix(url) {
1759
+ return url.replace(/\.git$/, "");
1760
+ }
1761
+ function mapRepository2(owner, repo, raw) {
1762
+ const record = asRecord2(raw);
1763
+ const rawHtmlUrl = str2(record.html_url);
1764
+ const repository = {
1765
+ provider: PROVIDER2,
1766
+ owner: str2(asRecord2(record.namespace).path) ?? owner,
1767
+ repo,
1768
+ name: str2(record.name) ?? repo,
1769
+ html_url: rawHtmlUrl === void 0 ? "" : stripGitSuffix(rawHtmlUrl),
1770
+ private: bool2(record.private) === true,
1771
+ default_branch: str2(record.default_branch) ?? ""
1772
+ };
1773
+ const fullName = str2(record.full_name);
1774
+ if (fullName !== void 0) {
1775
+ repository.full_name = fullName;
1776
+ }
1777
+ const description = str2(record.description);
1778
+ if (description !== void 0) {
1779
+ repository.description = description;
1780
+ }
1781
+ const fork = bool2(record.fork);
1782
+ if (fork !== void 0) {
1783
+ repository.fork = fork;
1784
+ }
1785
+ const language = str2(record.language);
1786
+ if (language !== void 0) {
1787
+ repository.language = language;
1788
+ }
1789
+ const createdAt = str2(record.created_at);
1790
+ if (createdAt !== void 0) {
1791
+ repository.created_at = createdAt;
1792
+ }
1793
+ const updatedAt = str2(record.updated_at);
1794
+ if (updatedAt !== void 0) {
1795
+ repository.updated_at = updatedAt;
1796
+ }
1797
+ return repository;
1798
+ }
1799
+ function mapFileContent2(owner, repo, raw) {
1800
+ const record = asRecord2(raw);
1801
+ const content = {
1802
+ provider: PROVIDER2,
1803
+ owner,
1804
+ repo,
1805
+ path: str2(record.path) ?? "",
1806
+ content: typeof record.content === "string" ? record.content : "",
1807
+ encoding: str2(record.encoding) ?? "base64"
1808
+ };
1809
+ const sha = str2(record.sha);
1810
+ if (sha !== void 0) {
1811
+ content.sha = sha;
1812
+ }
1813
+ const size = num2(record.size);
1814
+ if (size !== void 0) {
1815
+ content.size = size;
1816
+ }
1817
+ const htmlUrl = str2(record.html_url);
1818
+ if (htmlUrl !== void 0) {
1819
+ content.html_url = htmlUrl;
1820
+ }
1821
+ const type = str2(record.type);
1822
+ if (type !== void 0) {
1823
+ content.type = type;
1824
+ }
1825
+ return content;
1826
+ }
1827
+ function deriveBranchHtmlUrl2(webBaseUrl, owner, repo, name) {
1828
+ const base2 = webBaseUrl.endsWith("/") ? webBaseUrl.slice(0, -1) : webBaseUrl;
1829
+ if (base2.length === 0) {
1830
+ return void 0;
1831
+ }
1832
+ return `${base2}/${owner}/${repo}/tree/${name}`;
1833
+ }
1834
+ function mapBranch2(owner, repo, raw, webBaseUrl) {
1835
+ const record = asRecord2(raw);
1836
+ const name = str2(record.name) ?? "";
1837
+ const branch = {
1838
+ provider: PROVIDER2,
1839
+ owner,
1840
+ repo,
1841
+ name,
1842
+ commit_sha: str2(asRecord2(record.commit).sha) ?? ""
1843
+ };
1844
+ const isProtected = bool2(record.protected);
1845
+ if (isProtected !== void 0) {
1846
+ branch.protected = isProtected;
1847
+ }
1848
+ const htmlUrl = deriveBranchHtmlUrl2(webBaseUrl, owner, repo, name);
1849
+ if (htmlUrl !== void 0) {
1850
+ branch.html_url = htmlUrl;
1851
+ }
1852
+ return branch;
1853
+ }
1854
+ function mapCommitAuthor2(raw) {
1855
+ const record = asRecord2(raw);
1856
+ const name = str2(record.name);
1857
+ if (name === void 0) {
1858
+ return void 0;
1859
+ }
1860
+ return {
1861
+ name,
1862
+ email: str2(record.email) ?? "",
1863
+ date: str2(record.date) ?? ""
1864
+ };
1865
+ }
1866
+ function mapCommit2(owner, repo, raw) {
1867
+ const record = asRecord2(raw);
1868
+ const payload = asRecord2(record.commit);
1869
+ const commit = {
1870
+ provider: PROVIDER2,
1871
+ owner,
1872
+ repo,
1873
+ sha: str2(record.sha) ?? "",
1874
+ message: str2(payload.message) ?? "",
1875
+ html_url: str2(record.html_url) ?? ""
1876
+ };
1877
+ const author = mapCommitAuthor2(payload.author);
1878
+ if (author !== void 0) {
1879
+ commit.author = author;
1880
+ }
1881
+ const committer = mapCommitAuthor2(payload.committer);
1882
+ if (committer !== void 0) {
1883
+ commit.committer = committer;
1884
+ }
1885
+ const parents = asArray2(record.parents).map((entry) => str2(asRecord2(entry).sha)).filter((entry) => entry !== void 0);
1886
+ if (parents.length > 0) {
1887
+ commit.parents = parents;
1888
+ }
1889
+ return commit;
1890
+ }
1891
+ function mapComment2(owner, repo, raw, parentUrl) {
1892
+ const record = asRecord2(raw);
1893
+ const comment = {
1894
+ provider: PROVIDER2,
1895
+ owner,
1896
+ repo,
1897
+ id: num2(record.id) ?? Number(str2(record.id) ?? 0),
1898
+ body: typeof record.body === "string" ? record.body : "",
1899
+ created_at: str2(record.created_at) ?? ""
1900
+ };
1901
+ const htmlUrl = str2(record.html_url) ?? parentUrl;
1902
+ if (htmlUrl !== void 0 && htmlUrl.length > 0) {
1903
+ comment.html_url = htmlUrl;
1904
+ }
1905
+ const updatedAt = str2(record.updated_at);
1906
+ if (updatedAt !== void 0) {
1907
+ comment.updated_at = updatedAt;
1908
+ }
1909
+ const user = mapUser2(record.user);
1910
+ if (user !== void 0) {
1911
+ comment.user = user;
1912
+ }
1913
+ return comment;
1914
+ }
1915
+ function buildFileWriteResult2(inputs) {
1916
+ const result = {
1917
+ provider: PROVIDER2,
1918
+ owner: inputs.owner,
1919
+ repo: inputs.repo,
1920
+ commit_sha: inputs.commitSha,
1921
+ commit_html_url: inputs.commitHtmlUrl,
1922
+ paths: [...inputs.paths],
1923
+ branch: inputs.branch ?? ""
1924
+ };
1925
+ if (inputs.fileHtmlUrls !== void 0) {
1926
+ result.file_html_urls = inputs.fileHtmlUrls;
1927
+ }
1928
+ return result;
1929
+ }
1930
+ function deriveParentHtmlUrl(webBaseUrl, owner, repo, kind, number) {
1931
+ const base2 = webBaseUrl.endsWith("/") ? webBaseUrl.slice(0, -1) : webBaseUrl;
1932
+ if (base2.length === 0) {
1933
+ return void 0;
1934
+ }
1935
+ return `${base2}/${owner}/${repo}/${kind}/${String(number)}`;
1936
+ }
1937
+ var BASE64_ALPHABET2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1938
+ function isValidBase642(value) {
1939
+ const compact = value.replace(/\s+/g, "");
1940
+ const body = compact.replace(/={0,2}$/, "");
1941
+ if (body.length === 0 || body.length % 4 === 1) {
1942
+ return false;
1943
+ }
1944
+ for (const char of body) {
1945
+ if (!BASE64_ALPHABET2.includes(char)) {
1946
+ return false;
1947
+ }
1948
+ }
1949
+ return true;
1950
+ }
1951
+ function readPushEntries2(files) {
1952
+ if (!Array.isArray(files) || files.length === 0) {
1953
+ throw invalidArgumentError(
1954
+ "Invalid `files`: pushFiles requires at least one entry (an empty batch would create an empty commit).",
1955
+ PROVIDER2,
1956
+ "files.pushFiles"
1957
+ );
1958
+ }
1959
+ return files.map((raw, index) => {
1960
+ const file = asRecord2(raw);
1961
+ const path = file.path;
1962
+ if (typeof path !== "string" || path.trim().length === 0) {
1963
+ throw invalidArgumentError(
1964
+ `Invalid \`files[${index}].path\`: expected a non-empty string.`,
1965
+ PROVIDER2,
1966
+ "files.pushFiles"
1967
+ );
1968
+ }
1969
+ const rawAction = file.action;
1970
+ if (typeof rawAction !== "string" || !PUSH_ACTIONS2.includes(rawAction)) {
1971
+ throw invalidArgumentError(
1972
+ `Invalid \`files[${index}].action\`: expected one of ${PUSH_ACTIONS2.join(" | ")}, received ${describe2(rawAction)}. pushFiles does not provide upsert.`,
1973
+ PROVIDER2,
1974
+ "files.pushFiles"
1975
+ );
1976
+ }
1977
+ const action = rawAction;
1978
+ const rawEncoding = file.encoding ?? "utf8";
1979
+ if (rawEncoding !== "utf8" && rawEncoding !== "base64") {
1980
+ throw invalidArgumentError(
1981
+ `Invalid \`files[${index}].encoding\`: expected utf8 | base64, received ${describe2(rawEncoding)}.`,
1982
+ PROVIDER2,
1983
+ "files.pushFiles"
1984
+ );
1985
+ }
1986
+ const encoding = rawEncoding;
1987
+ if (action === "delete") {
1988
+ if (file.content !== void 0) {
1989
+ throw invalidArgumentError(
1990
+ `Invalid \`files[${index}]\`: action 'delete' must not carry content.`,
1991
+ PROVIDER2,
1992
+ "files.pushFiles"
1993
+ );
1994
+ }
1995
+ return { path, action, encoding };
1996
+ }
1997
+ const content = file.content;
1998
+ if (typeof content !== "string") {
1999
+ throw invalidArgumentError(
2000
+ `Invalid \`files[${index}].content\`: action '${action}' requires content.`,
2001
+ PROVIDER2,
2002
+ "files.pushFiles"
2003
+ );
2004
+ }
2005
+ if (encoding === "base64" && !isValidBase642(content)) {
2006
+ throw invalidArgumentError(
2007
+ `Invalid \`files[${index}].content\`: not a valid base64 payload.`,
2008
+ PROVIDER2,
2009
+ "files.pushFiles"
2010
+ );
2011
+ }
2012
+ return { path, action, content, encoding };
2013
+ });
2014
+ }
2015
+ function toGiteeEncoding(encoding) {
2016
+ return encoding === "base64" ? "base64" : "text";
2017
+ }
2018
+ function describe2(value) {
2019
+ if (value === void 0) {
2020
+ return "undefined";
2021
+ }
2022
+ if (typeof value === "string") {
2023
+ return value.length === 0 ? "an empty string" : `"${value}"`;
2024
+ }
2025
+ return typeof value;
2026
+ }
2027
+
2028
+ // src/adapters/gitee/capabilities.ts
2029
+ var capabilities2 = {
2030
+ "issues.list": "supported",
2031
+ "issues.get": "supported",
2032
+ "issues.create": "supported",
2033
+ "issues.update": "supported",
2034
+ "issues.listComments": "supported",
2035
+ "issues.createComment": "supported",
2036
+ "pulls.list": "supported",
2037
+ "pulls.get": "supported",
2038
+ "pulls.create": "supported",
2039
+ "pulls.merge": "supported",
2040
+ "pulls.listComments": "supported",
2041
+ "pulls.createComment": "supported",
2042
+ "repos.list": "supported",
2043
+ "repos.get": "supported",
2044
+ "repos.create": "supported",
2045
+ "repos.getFileContents": "supported",
2046
+ "files.create": "supported",
2047
+ "files.update": "supported",
2048
+ "files.delete": "supported",
2049
+ "files.pushFiles": "supported",
2050
+ "branches.list": "supported",
2051
+ "branches.create": "supported",
2052
+ "commits.list": "supported",
2053
+ "commits.get": "supported"
2054
+ };
2055
+ var paramCapabilities2 = {
2056
+ "pulls.list.headFilter": "supported",
2057
+ "pulls.list.milestoneFilter": "supported",
2058
+ "issues.list.milestoneFilter": "supported",
2059
+ "files.pushFiles.atomic": "supported"
2060
+ };
2061
+
2062
+ // src/adapters/gitee/adapter.ts
2063
+ var OPEN_STATES = ["open", "progressing"];
2064
+ var CLOSED_STATES = ["closed", "rejected"];
2065
+ var REPO_PATH2 = "/repos/{owner}/{repo}";
2066
+ function repoParams(owner, repo) {
2067
+ return { owner, repo };
2068
+ }
2069
+ function assertCreation2(params) {
2070
+ if (params.sha !== void 0) {
2071
+ throw invalidArgumentError(
2072
+ "Invalid `sha`: createFile creates a new file and must not receive a blob sha; use updateFile to replace an existing file.",
2073
+ "gitee"
2074
+ );
2075
+ }
2076
+ }
2077
+ function assertUpdate2(params) {
2078
+ if (params.sha === void 0 || params.sha.length === 0) {
2079
+ throw invalidArgumentError(
2080
+ "Invalid `sha`: updateFile requires the current blob sha of the file being replaced.",
2081
+ "gitee"
2082
+ );
2083
+ }
2084
+ }
2085
+ function assertIssueMilestoneFilter(milestone) {
2086
+ if (milestone !== void 0) {
2087
+ throw invalidArgumentError(
2088
+ "Invalid `milestone`: Gitee filters issues by milestone title, not by number. Use listPullRequests for a numeric milestone filter, or filter labels instead.",
2089
+ "gitee"
2090
+ );
2091
+ }
2092
+ }
2093
+ var GiteeAdapter = class {
2094
+ provider = "gitee";
2095
+ capabilities = capabilities2;
2096
+ paramCapabilities = paramCapabilities2;
2097
+ /* ---------------------------------------------------------------------- */
2098
+ /* Issue */
2099
+ /* ---------------------------------------------------------------------- */
2100
+ /**
2101
+ * Lists issues, fanning out across the platform's single-value states.
2102
+ *
2103
+ * Gitee's `open` excludes `progressing` and its `closed` excludes `rejected`,
2104
+ * so a single request would silently return a subset. An omitted state
2105
+ * follows GitHub's documented default (`open`) and therefore fans out too,
2106
+ * keeping "no state given" equivalent across providers.
2107
+ *
2108
+ * `maxPages` applies per platform state, so a fan-out can issue up to
2109
+ * `2 * maxPages` requests.
2110
+ */
2111
+ async listIssues(ctx, params) {
2112
+ assertIssueMilestoneFilter(params.milestone);
2113
+ const states = resolveIssueStates(params.state);
2114
+ const collected = [];
2115
+ for (const state of states) {
2116
+ const entries = await this.collectIssues(ctx, params, state);
2117
+ collected.push(...entries);
2118
+ }
2119
+ const merged = dedupeBy(collected, (raw) => listKey2(asRecord2(raw).number));
2120
+ return merged.map((raw) => mapIssue2(params.owner, params.repo, raw));
2121
+ }
2122
+ async getIssue(ctx, params) {
2123
+ const response = await ctx.http.request({
2124
+ method: "GET",
2125
+ path: `${REPO_PATH2}/issues/{number}`,
2126
+ pathParams: { ...repoParams(params.owner, params.repo), number: String(params.number) }
2127
+ });
2128
+ return mapIssue2(params.owner, params.repo, response.json);
2129
+ }
2130
+ async createIssue(ctx, params) {
2131
+ const response = await ctx.http.request({
2132
+ method: "POST",
2133
+ path: "/repos/{owner}/issues",
2134
+ pathParams: { owner: params.owner },
2135
+ body: {
2136
+ repo: params.repo,
2137
+ title: params.title,
2138
+ body: params.body,
2139
+ labels: joinLabels2(params.labels),
2140
+ milestone: params.milestone
2141
+ }
2142
+ });
2143
+ return mapIssue2(params.owner, params.repo, response.json);
2144
+ }
2145
+ async updateIssue(ctx, params) {
2146
+ const response = await ctx.http.request({
2147
+ method: "PATCH",
2148
+ path: "/repos/{owner}/issues/{number}",
2149
+ pathParams: { owner: params.owner, number: String(params.number) },
2150
+ body: {
2151
+ repo: params.repo,
2152
+ title: params.title,
2153
+ body: params.body,
2154
+ state: params.state,
2155
+ labels: joinLabels2(params.labels),
2156
+ milestone: params.milestone
2157
+ }
2158
+ });
2159
+ return mapIssue2(params.owner, params.repo, response.json);
2160
+ }
2161
+ async listIssueComments(ctx, params) {
2162
+ const parentUrl = deriveParentHtmlUrl(
2163
+ ctx.webBaseUrl,
2164
+ params.owner,
2165
+ params.repo,
2166
+ "issues",
2167
+ params.number
2168
+ );
2169
+ return this.listComments(ctx, params, `${REPO_PATH2}/issues/{number}/comments`, parentUrl);
2170
+ }
2171
+ async createIssueComment(ctx, params) {
2172
+ const parentUrl = deriveParentHtmlUrl(
2173
+ ctx.webBaseUrl,
2174
+ params.owner,
2175
+ params.repo,
2176
+ "issues",
2177
+ params.number
2178
+ );
2179
+ return this.createComment(ctx, params, `${REPO_PATH2}/issues/{number}/comments`, parentUrl);
2180
+ }
2181
+ /* ---------------------------------------------------------------------- */
2182
+ /* Pull request */
2183
+ /* ---------------------------------------------------------------------- */
2184
+ async listPullRequests(ctx, params) {
2185
+ return collectPullRequests(ctx, params, mapPullRequest2, {
2186
+ states: params.state === "closed" ? ["closed", "merged"] : [params.state],
2187
+ query: {
2188
+ head: params.head,
2189
+ base: params.base,
2190
+ labels: joinLabels2(params.labels),
2191
+ milestone_number: params.milestone
2192
+ }
2193
+ });
2194
+ }
2195
+ async getPullRequest(ctx, params) {
2196
+ const response = await ctx.http.request({
2197
+ method: "GET",
2198
+ path: `${REPO_PATH2}/pulls/{number}`,
2199
+ pathParams: { ...repoParams(params.owner, params.repo), number: String(params.number) }
2200
+ });
2201
+ return pullFromResponse(mapPullRequest2, ctx, params, response, {
2202
+ expectedNumber: params.number
2203
+ });
2204
+ }
2205
+ async createPullRequest(ctx, params) {
2206
+ const response = await ctx.http.request({
2207
+ method: "POST",
2208
+ path: `${REPO_PATH2}/pulls`,
2209
+ pathParams: repoParams(params.owner, params.repo),
2210
+ body: {
2211
+ title: params.title,
2212
+ head: params.head,
2213
+ base: params.base,
2214
+ body: params.body,
2215
+ draft: params.draft
2216
+ }
2217
+ });
2218
+ return pullFromResponse(mapPullRequest2, ctx, params, response);
2219
+ }
2220
+ async mergePullRequest(ctx, params) {
2221
+ await ctx.http.request({
2222
+ method: "PUT",
2223
+ path: `${REPO_PATH2}/pulls/{number}/merge`,
2224
+ pathParams: { ...repoParams(params.owner, params.repo), number: String(params.number) },
2225
+ body: {
2226
+ merge_method: params.merge_method,
2227
+ title: params.commit_title,
2228
+ description: params.commit_message
2229
+ }
2230
+ });
2231
+ return this.getPullRequest(ctx, params);
2232
+ }
2233
+ async listPullRequestComments(ctx, params) {
2234
+ const parentUrl = deriveParentHtmlUrl(
2235
+ ctx.webBaseUrl,
2236
+ params.owner,
2237
+ params.repo,
2238
+ "pulls",
2239
+ params.number
2240
+ );
2241
+ return this.listComments(ctx, params, `${REPO_PATH2}/pulls/{number}/comments`, parentUrl);
2242
+ }
2243
+ async createPullRequestComment(ctx, params) {
2244
+ const parentUrl = deriveParentHtmlUrl(
2245
+ ctx.webBaseUrl,
2246
+ params.owner,
2247
+ params.repo,
2248
+ "pulls",
2249
+ params.number
2250
+ );
2251
+ return this.createComment(ctx, params, `${REPO_PATH2}/pulls/{number}/comments`, parentUrl);
2252
+ }
2253
+ /* ---------------------------------------------------------------------- */
2254
+ /* Repository */
2255
+ /* ---------------------------------------------------------------------- */
2256
+ async listRepositories(ctx, params) {
2257
+ const path = params.org !== void 0 ? "/orgs/{org}/repos" : params.user !== void 0 ? "/users/{user}/repos" : "/user/repos";
2258
+ const pathParams = params.org !== void 0 ? { org: params.org } : params.user !== void 0 ? { user: params.user } : {};
2259
+ const entries = await collectPages(
2260
+ ctx.http,
2261
+ { method: "GET", path, pathParams },
2262
+ {
2263
+ maxPages: params.maxPages,
2264
+ selectItems: (raw) => asArray2(raw),
2265
+ keyOf: (raw) => listKey2(asRecord2(raw).id ?? asRecord2(raw).full_name)
2266
+ }
2267
+ );
2268
+ return entries.map((entry) => {
2269
+ const record = asRecord2(entry);
2270
+ const owner = str2(asRecord2(record.namespace).path) ?? params.org ?? params.user ?? "";
2271
+ const repo = str2(record.name) ?? str2(record.path) ?? "";
2272
+ return mapRepository2(owner, repo, record);
2273
+ });
2274
+ }
2275
+ async getRepository(ctx, params) {
2276
+ const response = await ctx.http.request({
2277
+ method: "GET",
2278
+ path: REPO_PATH2,
2279
+ pathParams: repoParams(params.owner, params.repo)
2280
+ });
2281
+ return mapRepository2(params.owner, params.repo, response.json);
2282
+ }
2283
+ async createRepository(ctx, params) {
2284
+ const path = params.org !== void 0 ? "/orgs/{org}/repos" : "/user/repos";
2285
+ const pathParams = params.org !== void 0 ? { org: params.org } : {};
2286
+ const response = await ctx.http.request({
2287
+ method: "POST",
2288
+ path,
2289
+ pathParams,
2290
+ body: {
2291
+ name: params.name,
2292
+ description: params.description,
2293
+ private: params.private,
2294
+ auto_init: params.auto_init
2295
+ }
2296
+ });
2297
+ const record = asRecord2(response.json);
2298
+ const owner = str2(asRecord2(record.namespace).path) ?? params.org ?? "";
2299
+ const repo = str2(record.name) ?? params.name;
2300
+ return mapRepository2(owner, repo, record);
2301
+ }
2302
+ async getFileContents(ctx, params) {
2303
+ const response = await ctx.http.request({
2304
+ method: "GET",
2305
+ path: `${REPO_PATH2}/contents/{path}`,
2306
+ pathParams: { owner: params.owner, repo: params.repo, path: params.path },
2307
+ query: { ref: params.ref }
2308
+ });
2309
+ if (Array.isArray(response.json)) {
2310
+ throw invalidArgumentError(
2311
+ `Invalid \`path\`: "${params.path}" is a directory or does not exist (Gitee answers 200 with an array). v0.1.0 getFileContents reads a single file only.`,
2312
+ "gitee"
2313
+ );
2314
+ }
2315
+ return mapFileContent2(params.owner, params.repo, response.json);
2316
+ }
2317
+ /* ---------------------------------------------------------------------- */
2318
+ /* Files */
2319
+ /* ---------------------------------------------------------------------- */
2320
+ async createFile(ctx, params) {
2321
+ assertCreation2(params);
2322
+ return this.writeContents(ctx, params, "POST");
2323
+ }
2324
+ async updateFile(ctx, params) {
2325
+ assertUpdate2(params);
2326
+ return this.writeContents(ctx, params, "PUT");
2327
+ }
2328
+ async deleteFile(ctx, params) {
2329
+ const response = await ctx.http.request({
2330
+ method: "DELETE",
2331
+ path: `${REPO_PATH2}/contents/{path}`,
2332
+ pathParams: { owner: params.owner, repo: params.repo, path: params.path },
2333
+ paramsIn: "query",
2334
+ body: { sha: params.sha, message: params.message, branch: params.branch }
2335
+ });
2336
+ return this.resultFromContents(ctx, params, response, false);
2337
+ }
2338
+ /**
2339
+ * Commits every entry in one request.
2340
+ *
2341
+ * A single `POST /commits` with `actions[]`
2342
+ * produces one commit, so no probe for existence is needed and no GET is
2343
+ * issued. An empty batch is rejected before the request because the platform
2344
+ * would create an empty commit.
2345
+ */
2346
+ async pushFiles(ctx, params) {
2347
+ const entries = readPushEntries2(params.files);
2348
+ const response = await ctx.http.request({
2349
+ method: "POST",
2350
+ path: `${REPO_PATH2}/commits`,
2351
+ pathParams: repoParams(params.owner, params.repo),
2352
+ body: {
2353
+ branch: params.branch,
2354
+ message: params.message,
2355
+ actions: entries.map((entry) => {
2356
+ const action = { action: entry.action, path: entry.path };
2357
+ if (entry.action !== "delete") {
2358
+ action.content = entry.content;
2359
+ action.encoding = toGiteeEncoding(entry.encoding);
2360
+ }
2361
+ return action;
2362
+ })
2363
+ }
2364
+ });
2365
+ const record = asRecord2(response.json);
2366
+ return buildFileWriteResult2({
2367
+ owner: params.owner,
2368
+ repo: params.repo,
2369
+ branch: params.branch,
2370
+ paths: entries.map((entry) => entry.path),
2371
+ commitSha: confirmedSha(ctx.http, response, record.sha),
2372
+ commitHtmlUrl: str2(record.html_url) ?? ""
2373
+ });
2374
+ }
2375
+ /* ---------------------------------------------------------------------- */
2376
+ /* Branch / Commit */
2377
+ /* ---------------------------------------------------------------------- */
2378
+ async listBranches(ctx, params) {
2379
+ const entries = await collectPages(
2380
+ ctx.http,
2381
+ {
2382
+ method: "GET",
2383
+ path: `${REPO_PATH2}/branches`,
2384
+ pathParams: repoParams(params.owner, params.repo)
2385
+ },
2386
+ {
2387
+ maxPages: params.maxPages,
2388
+ selectItems: (raw) => asArray2(raw),
2389
+ keyOf: (raw) => listKey2(asRecord2(raw).name)
2390
+ }
2391
+ );
2392
+ return entries.map((entry) => mapBranch2(params.owner, params.repo, entry, ctx.webBaseUrl));
2393
+ }
2394
+ async createBranch(ctx, params) {
2395
+ const response = await ctx.http.request({
2396
+ method: "POST",
2397
+ path: `${REPO_PATH2}/branches`,
2398
+ pathParams: repoParams(params.owner, params.repo),
2399
+ body: { refs: params.from, branch_name: params.name }
2400
+ });
2401
+ const record = asRecord2(response.json);
2402
+ const name = str2(record.name) ?? params.name;
2403
+ const branch = {
2404
+ provider: "gitee",
2405
+ owner: params.owner,
2406
+ repo: params.repo,
2407
+ name,
2408
+ commit_sha: confirmedSha(ctx.http, response, asRecord2(record.commit).sha)
2409
+ };
2410
+ const isProtected = record.protected;
2411
+ if (typeof isProtected === "boolean") {
2412
+ branch.protected = isProtected;
2413
+ }
2414
+ const htmlUrl = deriveBranchHtmlUrl2(ctx.webBaseUrl, params.owner, params.repo, name);
2415
+ if (htmlUrl !== void 0) {
2416
+ branch.html_url = htmlUrl;
2417
+ }
2418
+ return branch;
2419
+ }
2420
+ async listCommits(ctx, params) {
2421
+ const entries = await collectPages(
2422
+ ctx.http,
2423
+ {
2424
+ method: "GET",
2425
+ path: `${REPO_PATH2}/commits`,
2426
+ pathParams: repoParams(params.owner, params.repo)
2427
+ },
2428
+ {
2429
+ maxPages: params.maxPages,
2430
+ query: { sha: params.branch },
2431
+ selectItems: (raw) => asArray2(raw),
2432
+ keyOf: (raw) => listKey2(asRecord2(raw).sha)
2433
+ }
2434
+ );
2435
+ return entries.map((entry) => mapCommit2(params.owner, params.repo, entry));
2436
+ }
2437
+ async getCommit(ctx, params) {
2438
+ const response = await ctx.http.request({
2439
+ method: "GET",
2440
+ path: `${REPO_PATH2}/commits/{sha}`,
2441
+ pathParams: { ...repoParams(params.owner, params.repo), sha: params.sha }
2442
+ });
2443
+ return mapCommit2(params.owner, params.repo, response.json);
2444
+ }
2445
+ /* ---------------------------------------------------------------------- */
2446
+ /* Internals */
2447
+ /* ---------------------------------------------------------------------- */
2448
+ /** Collects one platform state's issues, one page at a time. */
2449
+ async collectIssues(ctx, params, state) {
2450
+ return collectPages(
2451
+ ctx.http,
2452
+ {
2453
+ method: "GET",
2454
+ path: `${REPO_PATH2}/issues`,
2455
+ pathParams: repoParams(params.owner, params.repo)
2456
+ },
2457
+ {
2458
+ maxPages: params.maxPages,
2459
+ requireComplete: params.requireComplete,
2460
+ query: { state, labels: joinLabels2(params.labels) },
2461
+ selectItems: (_raw, { response }) => selectIssueRows(ctx.http, response),
2462
+ keyOf: (raw) => listKey2(asRecord2(raw).number)
2463
+ }
2464
+ );
2465
+ }
2466
+ /** Shared comment listing used by both issue and pull-request domains. */
2467
+ async listComments(ctx, params, path, parentUrl) {
2468
+ const entries = await collectPages(
2469
+ ctx.http,
2470
+ {
2471
+ method: "GET",
2472
+ path,
2473
+ pathParams: {
2474
+ ...repoParams(params.owner, params.repo),
2475
+ number: String(params.number)
2476
+ }
2477
+ },
2478
+ {
2479
+ maxPages: params.maxPages,
2480
+ selectItems: (raw) => asArray2(raw),
2481
+ keyOf: (raw) => listKey2(asRecord2(raw).id)
2482
+ }
2483
+ );
2484
+ return entries.map((entry) => mapComment2(params.owner, params.repo, entry, parentUrl));
2485
+ }
2486
+ /** Shared comment creation used by both comment domains. */
2487
+ async createComment(ctx, params, path, parentUrl) {
2488
+ const response = await ctx.http.request({
2489
+ method: "POST",
2490
+ path,
2491
+ pathParams: {
2492
+ ...repoParams(params.owner, params.repo),
2493
+ number: String(params.number)
2494
+ },
2495
+ body: { body: params.body }
2496
+ });
2497
+ return mapComment2(params.owner, params.repo, response.json, parentUrl);
2498
+ }
2499
+ /** Creates or replaces one file through the `contents` endpoints. */
2500
+ async writeContents(ctx, params, method) {
2501
+ const response = await ctx.http.request({
2502
+ method,
2503
+ path: `${REPO_PATH2}/contents/{path}`,
2504
+ pathParams: { owner: params.owner, repo: params.repo, path: params.path },
2505
+ body: {
2506
+ content: contentsBase64(params.content, params.encoding, "gitee"),
2507
+ message: params.message,
2508
+ branch: params.branch,
2509
+ sha: params.sha
2510
+ }
2511
+ });
2512
+ return this.resultFromContents(ctx, params, response, true);
2513
+ }
2514
+ /**
2515
+ * Builds a `FileWriteResult` from a single-file write response.
2516
+ *
2517
+ * Gitee's `commit` object has no `html_url` in these responses,
2518
+ * so the commit URL is derived from the web base. That derivation is the
2519
+ * main path here, not a fallback.
2520
+ */
2521
+ resultFromContents(ctx, params, response, keepFileUrl) {
2522
+ const record = asRecord2(response.json);
2523
+ const commit = asRecord2(record.commit);
2524
+ const sha = confirmedSha(ctx.http, response, commit.sha);
2525
+ const webBase = ctx.webBaseUrl.endsWith("/") ? ctx.webBaseUrl.slice(0, -1) : ctx.webBaseUrl;
2526
+ const derivedUrl = webBase.length > 0 && sha.length > 0 ? `${webBase}/${params.owner}/${params.repo}/commit/${sha}` : "";
2527
+ const fileUrl = keepFileUrl ? str2(asRecord2(record.content).html_url) : void 0;
2528
+ const result = buildFileWriteResult2({
2529
+ owner: params.owner,
2530
+ repo: params.repo,
2531
+ branch: params.branch,
2532
+ paths: [params.path],
2533
+ commitSha: sha,
2534
+ commitHtmlUrl: str2(commit.html_url) ?? derivedUrl
2535
+ });
2536
+ if (keepFileUrl) {
2537
+ result.file_html_urls = [fileUrl];
2538
+ }
2539
+ return result;
2540
+ }
2541
+ };
2542
+ function resolveIssueStates(state) {
2543
+ if (state === "all") {
2544
+ return ["all"];
2545
+ }
2546
+ if (state === "closed") {
2547
+ return CLOSED_STATES;
2548
+ }
2549
+ return OPEN_STATES;
2550
+ }
2551
+ var giteeAdapter = new GiteeAdapter();
2552
+
2553
+ // src/core/types.ts
2554
+ var PROVIDERS = ["github", "gitee", "atomgit"];
2555
+ var CAPABILITY_IDS = [
2556
+ // Issue (6)
2557
+ "issues.list",
2558
+ "issues.get",
2559
+ "issues.create",
2560
+ "issues.update",
2561
+ "issues.listComments",
2562
+ "issues.createComment",
2563
+ // Pull request (6)
2564
+ "pulls.list",
2565
+ "pulls.get",
2566
+ "pulls.create",
2567
+ "pulls.merge",
2568
+ "pulls.listComments",
2569
+ "pulls.createComment",
2570
+ // Repository (4)
2571
+ "repos.list",
2572
+ "repos.get",
2573
+ "repos.create",
2574
+ "repos.getFileContents",
2575
+ // Files (4)
2576
+ "files.create",
2577
+ "files.update",
2578
+ "files.delete",
2579
+ "files.pushFiles",
2580
+ // Branch (2)
2581
+ "branches.list",
2582
+ "branches.create",
2583
+ // Commit (2)
2584
+ "commits.list",
2585
+ "commits.get"
2586
+ ];
2587
+ var PARAM_CAPABILITY_IDS = [
2588
+ "pulls.list.headFilter",
2589
+ "pulls.list.milestoneFilter",
2590
+ "issues.list.milestoneFilter",
2591
+ "files.pushFiles.atomic"
2592
+ ];
2593
+
2594
+ // src/adapters/types.ts
2595
+ function unsupported(capability, provider) {
2596
+ return (..._args) => {
2597
+ throw unsupportedCapabilityError(provider, capability);
2598
+ };
2599
+ }
2600
+
2601
+ // src/adapters/atomgit/map.ts
2602
+ var PROVIDER3 = "atomgit";
2603
+ function asRecord3(value) {
2604
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
2605
+ }
2606
+ function asArray3(value) {
2607
+ return Array.isArray(value) ? value : [];
2608
+ }
2609
+ function str3(value) {
2610
+ return typeof value === "string" && value.length > 0 ? value : void 0;
2611
+ }
2612
+ function num3(value) {
2613
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2614
+ }
2615
+ function listKey3(value) {
2616
+ if (typeof value === "string") {
2617
+ return value;
2618
+ }
2619
+ if (typeof value === "number" && Number.isFinite(value)) {
2620
+ return String(value);
2621
+ }
2622
+ return "";
2623
+ }
2624
+ function bool3(value) {
2625
+ return typeof value === "boolean" ? value : void 0;
2626
+ }
2627
+ function normalizeLabels3(raw) {
2628
+ const out = [];
2629
+ for (const entry of asArray3(raw)) {
2630
+ if (typeof entry === "string" && entry.length > 0) {
2631
+ out.push(entry);
2632
+ continue;
2633
+ }
2634
+ const name = str3(asRecord3(entry).name);
2635
+ if (name !== void 0) {
2636
+ out.push(name);
2637
+ }
2638
+ }
2639
+ return out;
2640
+ }
2641
+ function mapUser3(raw) {
2642
+ const record = asRecord3(raw);
2643
+ const login = str3(record.login);
2644
+ const name = str3(record.name);
2645
+ if (login === void 0 && name === void 0) {
2646
+ return void 0;
2647
+ }
2648
+ const user = { login: login ?? name };
2649
+ if (name !== void 0) {
2650
+ user.name = name;
2651
+ }
2652
+ const avatar = str3(record.avatar_url);
2653
+ if (avatar !== void 0) {
2654
+ user.avatar_url = avatar;
2655
+ }
2656
+ return user;
2657
+ }
2658
+ function mapUsers3(raw) {
2659
+ const users = asArray3(raw).map((entry) => mapUser3(entry)).filter((entry) => entry !== void 0);
2660
+ return users.length > 0 ? users : void 0;
2661
+ }
2662
+ function mapIssueState3(raw) {
2663
+ return raw === "open" ? "open" : "closed";
2664
+ }
2665
+ function mapPullRequestState3(raw) {
2666
+ return raw === "open" ? "open" : "closed";
2667
+ }
2668
+ function toAtomGitState(state) {
2669
+ return state === "closed" ? "close" : "reopen";
2670
+ }
2671
+ function joinLabels3(labels) {
2672
+ return labels === void 0 || labels.length === 0 ? void 0 : labels.join(",");
2673
+ }
2674
+ function mapIssue3(owner, repo, raw) {
2675
+ const record = asRecord3(raw);
2676
+ const issue = {
2677
+ provider: PROVIDER3,
2678
+ owner,
2679
+ repo,
2680
+ ...issueNumberFields(listKey3(record.number)),
2681
+ title: str3(record.title) ?? "",
2682
+ state: mapIssueState3(record.state),
2683
+ html_url: str3(record.html_url) ?? "",
2684
+ labels: normalizeLabels3(record.labels),
2685
+ created_at: str3(record.created_at) ?? "",
2686
+ updated_at: str3(record.updated_at) ?? ""
2687
+ };
2688
+ const body = str3(record.body);
2689
+ if (body !== void 0) {
2690
+ issue.body = body;
2691
+ }
2692
+ const user = mapUser3(record.user);
2693
+ if (user !== void 0) {
2694
+ issue.user = user;
2695
+ }
2696
+ const assignees = mapUsers3(record.assignees);
2697
+ if (assignees !== void 0) {
2698
+ issue.assignees = assignees;
2699
+ }
2700
+ const comments = num3(record.comments);
2701
+ if (comments !== void 0) {
2702
+ issue.comments_count = comments;
2703
+ }
2704
+ const closedAt = str3(record.finished_at) ?? str3(record.closed_at);
2705
+ if (closedAt !== void 0) {
2706
+ issue.closed_at = closedAt;
2707
+ }
2708
+ return issue;
2709
+ }
2710
+ function mapRef3(raw) {
2711
+ const record = asRecord3(raw);
2712
+ const ref = str3(record.ref);
2713
+ const sha = str3(record.sha);
2714
+ return ref !== void 0 && sha !== void 0 ? { ref, sha } : void 0;
2715
+ }
2716
+ function mapPullRequest3(owner, repo, raw, base2, number) {
2717
+ const record = asRecord3(raw);
2718
+ const rawState = str3(record.state);
2719
+ const merged = rawState === "merged" || str3(record.merged_at) !== void 0;
2720
+ const draft = {
2721
+ base: base2,
2722
+ provider: PROVIDER3,
2723
+ owner,
2724
+ repo,
2725
+ number,
2726
+ title: str3(record.title) ?? "",
2727
+ state: merged ? "closed" : mapPullRequestState3(rawState),
2728
+ merged,
2729
+ html_url: str3(record.html_url) ?? "",
2730
+ created_at: str3(record.created_at) ?? "",
2731
+ updated_at: str3(record.updated_at) ?? ""
2732
+ };
2733
+ const head = mapRef3(record.head);
2734
+ if (head !== void 0) {
2735
+ draft.head = head;
2736
+ }
2737
+ const mergedAt = str3(record.merged_at);
2738
+ if (mergedAt !== void 0) {
2739
+ draft.merged_at = mergedAt;
2740
+ }
2741
+ const body = str3(record.body);
2742
+ if (body !== void 0) {
2743
+ draft.body = body;
2744
+ }
2745
+ const isDraft = bool3(record.draft);
2746
+ if (isDraft !== void 0) {
2747
+ draft.draft = isDraft;
2748
+ }
2749
+ const mergeable = bool3(record.mergeable);
2750
+ if (mergeable !== void 0) {
2751
+ draft.mergeable = mergeable;
2752
+ }
2753
+ const user = mapUser3(record.user);
2754
+ if (user !== void 0) {
2755
+ draft.user = user;
2756
+ }
2757
+ const additions = num3(record.additions) ?? num3(record.added_lines);
2758
+ if (additions !== void 0) {
2759
+ draft.additions = additions;
2760
+ }
2761
+ const deletions = num3(record.deletions) ?? num3(record.removed_lines);
2762
+ if (deletions !== void 0) {
2763
+ draft.deletions = deletions;
2764
+ }
2765
+ const changedFiles = num3(record.changed_files);
2766
+ if (changedFiles !== void 0) {
2767
+ draft.changed_files = changedFiles;
2768
+ }
2769
+ return draft;
2770
+ }
2771
+ function mapRepository3(owner, repo, raw) {
2772
+ const record = asRecord3(raw);
2773
+ const htmlUrl = str3(record.html_url) ?? str3(record.web_url) ?? "";
2774
+ const repository = {
2775
+ provider: PROVIDER3,
2776
+ // `namespace.path` is the path-safe owner; `human_name` has spaces.
2777
+ owner: str3(asRecord3(record.namespace).path) ?? owner,
2778
+ repo,
2779
+ name: str3(record.name) ?? repo,
2780
+ html_url: htmlUrl,
2781
+ private: bool3(record.private) === true || bool3(record.public) === false,
2782
+ default_branch: str3(record.default_branch) ?? ""
2783
+ };
2784
+ const fullName = str3(record.full_name);
2785
+ if (fullName !== void 0) {
2786
+ repository.full_name = fullName;
2787
+ }
2788
+ const description = str3(record.description);
2789
+ if (description !== void 0) {
2790
+ repository.description = description;
2791
+ }
2792
+ const fork = bool3(record.fork);
2793
+ if (fork !== void 0) {
2794
+ repository.fork = fork;
2795
+ }
2796
+ const language = str3(record.language);
2797
+ if (language !== void 0) {
2798
+ repository.language = language;
2799
+ }
2800
+ const createdAt = str3(record.created_at);
2801
+ if (createdAt !== void 0) {
2802
+ repository.created_at = createdAt;
2803
+ }
2804
+ const updatedAt = str3(record.updated_at);
2805
+ if (updatedAt !== void 0) {
2806
+ repository.updated_at = updatedAt;
2807
+ }
2808
+ return repository;
2809
+ }
2810
+ function mapFileContent3(owner, repo, raw) {
2811
+ const record = asRecord3(raw);
2812
+ const content = {
2813
+ provider: PROVIDER3,
2814
+ owner,
2815
+ repo,
2816
+ path: str3(record.path) ?? "",
2817
+ content: typeof record.content === "string" ? record.content : "",
2818
+ encoding: str3(record.encoding) ?? "base64"
2819
+ };
2820
+ const sha = str3(record.sha);
2821
+ if (sha !== void 0) {
2822
+ content.sha = sha;
2823
+ }
2824
+ const size = num3(record.size);
2825
+ if (size !== void 0) {
2826
+ content.size = size;
2827
+ }
2828
+ const htmlUrl = str3(record.html_url);
2829
+ if (htmlUrl !== void 0) {
2830
+ content.html_url = htmlUrl;
2831
+ }
2832
+ const type = str3(record.type);
2833
+ if (type !== void 0) {
2834
+ content.type = type;
2835
+ }
2836
+ return content;
2837
+ }
2838
+ function deriveBranchHtmlUrl3(webBaseUrl, owner, repo, name) {
2839
+ const base2 = webBaseUrl.endsWith("/") ? webBaseUrl.slice(0, -1) : webBaseUrl;
2840
+ if (base2.length === 0) {
2841
+ return void 0;
2842
+ }
2843
+ return `${base2}/${owner}/${repo}/tree/${name}`;
2844
+ }
2845
+ function mapBranch3(owner, repo, raw, webBaseUrl) {
2846
+ const record = asRecord3(raw);
2847
+ const name = str3(record.name) ?? "";
2848
+ const branch = {
2849
+ provider: PROVIDER3,
2850
+ owner,
2851
+ repo,
2852
+ name,
2853
+ commit_sha: str3(asRecord3(record.commit).sha) ?? ""
2854
+ };
2855
+ const isProtected = bool3(record.protected);
2856
+ if (isProtected !== void 0) {
2857
+ branch.protected = isProtected;
2858
+ }
2859
+ const htmlUrl = deriveBranchHtmlUrl3(webBaseUrl, owner, repo, name);
2860
+ if (htmlUrl !== void 0) {
2861
+ branch.html_url = htmlUrl;
2862
+ }
2863
+ return branch;
2864
+ }
2865
+ function mapCommitAuthor3(raw) {
2866
+ const record = asRecord3(raw);
2867
+ const name = str3(record.name);
2868
+ if (name === void 0) {
2869
+ return void 0;
2870
+ }
2871
+ return {
2872
+ name,
2873
+ email: str3(record.email) ?? "",
2874
+ date: str3(record.date) ?? ""
2875
+ };
2876
+ }
2877
+ function mapCommit3(owner, repo, raw) {
2878
+ const record = asRecord3(raw);
2879
+ const payload = asRecord3(record.commit);
2880
+ const commit = {
2881
+ provider: PROVIDER3,
2882
+ owner,
2883
+ repo,
2884
+ sha: str3(record.sha) ?? "",
2885
+ message: str3(payload.message) ?? "",
2886
+ // AtomGit uses `/commits/detail/<sha>`; kept verbatim.
2887
+ html_url: str3(record.html_url) ?? ""
2888
+ };
2889
+ const author = mapCommitAuthor3(payload.author);
2890
+ if (author !== void 0) {
2891
+ commit.author = author;
2892
+ }
2893
+ const committer = mapCommitAuthor3(payload.committer);
2894
+ if (committer !== void 0) {
2895
+ commit.committer = committer;
2896
+ }
2897
+ const parents = asArray3(record.parents).map((entry) => str3(asRecord3(entry).sha)).filter((entry) => entry !== void 0);
2898
+ if (parents.length > 0) {
2899
+ commit.parents = parents;
2900
+ }
2901
+ return commit;
2902
+ }
2903
+ function mapComment3(owner, repo, raw, parentUrl) {
2904
+ const record = asRecord3(raw);
2905
+ const comment = {
2906
+ provider: PROVIDER3,
2907
+ owner,
2908
+ repo,
2909
+ id: num3(record.id) ?? Number(str3(record.id) ?? 0),
2910
+ body: typeof record.body === "string" ? record.body : "",
2911
+ created_at: str3(record.created_at) ?? ""
2912
+ };
2913
+ const htmlUrl = str3(record.html_url) ?? parentUrl;
2914
+ if (htmlUrl !== void 0 && htmlUrl.length > 0) {
2915
+ comment.html_url = htmlUrl;
2916
+ }
2917
+ const updatedAt = str3(record.updated_at);
2918
+ if (updatedAt !== void 0) {
2919
+ comment.updated_at = updatedAt;
2920
+ }
2921
+ const user = mapUser3(record.user);
2922
+ if (user !== void 0) {
2923
+ comment.user = user;
2924
+ }
2925
+ return comment;
2926
+ }
2927
+ function deriveParentHtmlUrl2(webBaseUrl, owner, repo, kind, number) {
2928
+ const base2 = webBaseUrl.endsWith("/") ? webBaseUrl.slice(0, -1) : webBaseUrl;
2929
+ if (base2.length === 0) {
2930
+ return void 0;
2931
+ }
2932
+ return `${base2}/${owner}/${repo}/${kind}/${String(number)}`;
2933
+ }
2934
+ function headFilterUnsupported() {
2935
+ throw unsupportedCapabilityError(PROVIDER3, "pulls.list.headFilter");
2936
+ }
2937
+
2938
+ // src/adapters/atomgit/capabilities.ts
2939
+ var capabilities3 = {
2940
+ "issues.list": "supported",
2941
+ "issues.get": "supported",
2942
+ "issues.create": "supported",
2943
+ "issues.update": "supported",
2944
+ "issues.listComments": "supported",
2945
+ "issues.createComment": "supported",
2946
+ "pulls.list": "supported",
2947
+ "pulls.get": "supported",
2948
+ "pulls.create": "supported",
2949
+ "pulls.merge": "supported",
2950
+ "pulls.listComments": "supported",
2951
+ "pulls.createComment": "supported",
2952
+ "repos.list": "supported",
2953
+ "repos.get": "supported",
2954
+ "repos.create": "supported",
2955
+ "repos.getFileContents": "supported",
2956
+ "files.create": "supported",
2957
+ "files.update": "supported",
2958
+ "files.delete": "supported",
2959
+ "files.pushFiles": "unsupported",
2960
+ "branches.list": "supported",
2961
+ "branches.create": "supported",
2962
+ "commits.list": "supported",
2963
+ "commits.get": "supported"
2964
+ };
2965
+ var paramCapabilities3 = {
2966
+ "pulls.list.headFilter": "unsupported",
2967
+ "pulls.list.milestoneFilter": "supported",
2968
+ "issues.list.milestoneFilter": "supported",
2969
+ "files.pushFiles.atomic": "unsupported"
2970
+ };
2971
+
2972
+ // src/adapters/atomgit/adapter.ts
2973
+ var REPO_PATH3 = "/repos/{owner}/{repo}";
2974
+ var HEAD_BACKFILL_PER_PAGE = 100;
2975
+ function repoParams2(owner, repo) {
2976
+ return { owner, repo };
2977
+ }
2978
+ function assertCreation3(params) {
2979
+ if (params.sha !== void 0) {
2980
+ throw invalidArgumentError(
2981
+ "Invalid `sha`: createFile creates a new file and must not receive a blob sha; use updateFile to replace an existing file.",
2982
+ "atomgit"
2983
+ );
2984
+ }
2985
+ }
2986
+ function assertUpdate3(params) {
2987
+ if (params.sha === void 0 || params.sha.length === 0) {
2988
+ throw invalidArgumentError(
2989
+ "Invalid `sha`: updateFile requires the current blob sha of the file being replaced.",
2990
+ "atomgit"
2991
+ );
2992
+ }
2993
+ }
2994
+ var AtomGitAdapter = class {
2995
+ provider = "atomgit";
2996
+ capabilities = capabilities3;
2997
+ paramCapabilities = paramCapabilities3;
2998
+ /* ---------------------------------------------------------------------- */
2999
+ /* Issue */
3000
+ /* ---------------------------------------------------------------------- */
3001
+ async listIssues(ctx, params) {
3002
+ const entries = await collectPages(
3003
+ ctx.http,
3004
+ {
3005
+ method: "GET",
3006
+ path: `${REPO_PATH3}/issues`,
3007
+ pathParams: repoParams2(params.owner, params.repo)
3008
+ },
3009
+ {
3010
+ maxPages: params.maxPages,
3011
+ requireComplete: params.requireComplete,
3012
+ query: {
3013
+ state: params.state,
3014
+ labels: joinLabels3(params.labels),
3015
+ // AtomGit's issue filter takes the milestone ordinal.
3016
+ milestone: params.milestone
3017
+ },
3018
+ selectItems: (_raw, { response }) => selectIssueRows(ctx.http, response),
3019
+ keyOf: (raw) => listKey3(asRecord3(raw).number)
3020
+ }
3021
+ );
3022
+ return entries.map((entry) => mapIssue3(params.owner, params.repo, entry));
3023
+ }
3024
+ async getIssue(ctx, params) {
3025
+ const response = await ctx.http.request({
3026
+ method: "GET",
3027
+ path: `${REPO_PATH3}/issues/{number}`,
3028
+ pathParams: { ...repoParams2(params.owner, params.repo), number: String(params.number) }
3029
+ });
3030
+ return mapIssue3(params.owner, params.repo, response.json);
3031
+ }
3032
+ async createIssue(ctx, params) {
3033
+ const response = await ctx.http.request({
3034
+ method: "POST",
3035
+ path: "/repos/{owner}/issues",
3036
+ pathParams: { owner: params.owner },
3037
+ body: {
3038
+ repo: params.repo,
3039
+ title: params.title,
3040
+ body: params.body,
3041
+ labels: joinLabels3(params.labels),
3042
+ milestone: params.milestone
3043
+ }
3044
+ });
3045
+ return mapIssue3(params.owner, params.repo, response.json);
3046
+ }
3047
+ /**
3048
+ * Updates an issue.
3049
+ *
3050
+ * AtomGit requires both `repo` and `title` on this endpoint, so a caller that
3051
+ * omits `title` costs one extra read to fill it in. That is the documented
3052
+ * trade-off: sending the update without a title is a 422.
3053
+ */
3054
+ async updateIssue(ctx, params) {
3055
+ const title = params.title ?? (await this.getIssue(ctx, { ...params, number: params.number })).title;
3056
+ const body = {
3057
+ repo: params.repo,
3058
+ title,
3059
+ body: params.body,
3060
+ labels: joinLabels3(params.labels),
3061
+ milestone: params.milestone
3062
+ };
3063
+ if (params.state !== void 0) {
3064
+ body.state = toAtomGitState(params.state);
3065
+ }
3066
+ const response = await ctx.http.request({
3067
+ method: "PATCH",
3068
+ path: "/repos/{owner}/issues/{number}",
3069
+ pathParams: { owner: params.owner, number: String(params.number) },
3070
+ body
3071
+ });
3072
+ return mapIssue3(params.owner, params.repo, response.json);
3073
+ }
3074
+ async listIssueComments(ctx, params) {
3075
+ const parentUrl = deriveParentHtmlUrl2(
3076
+ ctx.webBaseUrl,
3077
+ params.owner,
3078
+ params.repo,
3079
+ "issues",
3080
+ params.number
3081
+ );
3082
+ return this.listComments(ctx, params, `${REPO_PATH3}/issues/{number}/comments`, parentUrl);
3083
+ }
3084
+ async createIssueComment(ctx, params) {
3085
+ const parentUrl = deriveParentHtmlUrl2(
3086
+ ctx.webBaseUrl,
3087
+ params.owner,
3088
+ params.repo,
3089
+ "issues",
3090
+ params.number
3091
+ );
3092
+ return this.createComment(ctx, params, `${REPO_PATH3}/issues/{number}/comments`, parentUrl);
3093
+ }
3094
+ /* ---------------------------------------------------------------------- */
3095
+ /* Pull request */
3096
+ /* ---------------------------------------------------------------------- */
3097
+ /**
3098
+ * Lists pull requests.
3099
+ *
3100
+ * `head` is rejected before any request: AtomGit has no such filter, and
3101
+ * returning an unfiltered list would let a caller believe it was filtered.
3102
+ */
3103
+ async listPullRequests(ctx, params) {
3104
+ if (params.head !== void 0) {
3105
+ headFilterUnsupported();
3106
+ }
3107
+ return collectPullRequests(ctx, params, mapPullRequest3, {
3108
+ states: params.state === "closed" ? ["closed", "merged", "locked"] : [params.state],
3109
+ query: {
3110
+ base: params.base,
3111
+ labels: joinLabels3(params.labels),
3112
+ milestone_number: params.milestone
3113
+ }
3114
+ });
3115
+ }
3116
+ /**
3117
+ * Reads one pull request. When detail omits the head, try one list page;
3118
+ * if neither response contains it, leave it absent.
3119
+ */
3120
+ async getPullRequest(ctx, params) {
3121
+ const response = await ctx.http.request({
3122
+ method: "GET",
3123
+ path: `${REPO_PATH3}/pulls/{number}`,
3124
+ pathParams: { ...repoParams2(params.owner, params.repo), number: String(params.number) }
3125
+ });
3126
+ requirePullNumber(ctx.http, response, response.json, params.number);
3127
+ const detail = asRecord3(response.json);
3128
+ if (mapRef3(detail.head) && mapRef3(detail.base)) {
3129
+ return pullFromResponse(mapPullRequest3, ctx, params, response);
3130
+ }
3131
+ const other = await this.findPullRefs(ctx, params);
3132
+ return pullFromResponse(mapPullRequest3, ctx, params, response, {
3133
+ raw: {
3134
+ ...detail,
3135
+ head: mapRef3(detail.head) ?? other?.head,
3136
+ base: mapRef3(detail.base) ?? other?.base
3137
+ }
3138
+ });
3139
+ }
3140
+ async createPullRequest(ctx, params) {
3141
+ const response = await ctx.http.request({
3142
+ method: "POST",
3143
+ path: `${REPO_PATH3}/pulls`,
3144
+ pathParams: repoParams2(params.owner, params.repo),
3145
+ body: {
3146
+ title: params.title,
3147
+ head: params.head,
3148
+ base: params.base,
3149
+ body: params.body,
3150
+ draft: params.draft
3151
+ }
3152
+ });
3153
+ return pullFromResponse(mapPullRequest3, ctx, params, response);
3154
+ }
3155
+ async mergePullRequest(ctx, params) {
3156
+ await ctx.http.request({
3157
+ method: "PUT",
3158
+ path: `${REPO_PATH3}/pulls/{number}/merge`,
3159
+ pathParams: { ...repoParams2(params.owner, params.repo), number: String(params.number) },
3160
+ body: {
3161
+ merge_method: params.merge_method,
3162
+ title: params.commit_title,
3163
+ description: params.commit_message
3164
+ }
3165
+ });
3166
+ return this.getPullRequest(ctx, params);
3167
+ }
3168
+ async listPullRequestComments(ctx, params) {
3169
+ const parentUrl = deriveParentHtmlUrl2(
3170
+ ctx.webBaseUrl,
3171
+ params.owner,
3172
+ params.repo,
3173
+ "merge_requests",
3174
+ params.number
3175
+ );
3176
+ return this.listComments(ctx, params, `${REPO_PATH3}/pulls/{number}/comments`, parentUrl);
3177
+ }
3178
+ async createPullRequestComment(ctx, params) {
3179
+ const parentUrl = deriveParentHtmlUrl2(
3180
+ ctx.webBaseUrl,
3181
+ params.owner,
3182
+ params.repo,
3183
+ "merge_requests",
3184
+ params.number
3185
+ );
3186
+ return this.createComment(ctx, params, `${REPO_PATH3}/pulls/{number}/comments`, parentUrl);
3187
+ }
3188
+ /* ---------------------------------------------------------------------- */
3189
+ /* Repository */
3190
+ /* ---------------------------------------------------------------------- */
3191
+ async listRepositories(ctx, params) {
3192
+ const path = params.org !== void 0 ? "/orgs/{org}/repos" : params.user !== void 0 ? "/users/{user}/repos" : "/user/repos";
3193
+ const pathParams = params.org !== void 0 ? { org: params.org } : params.user !== void 0 ? { user: params.user } : {};
3194
+ const entries = await collectPages(
3195
+ ctx.http,
3196
+ { method: "GET", path, pathParams },
3197
+ {
3198
+ maxPages: params.maxPages,
3199
+ selectItems: (raw) => asArray3(raw),
3200
+ keyOf: (raw) => listKey3(asRecord3(raw).id ?? asRecord3(raw).full_name)
3201
+ }
3202
+ );
3203
+ return entries.map((entry) => {
3204
+ const record = asRecord3(entry);
3205
+ const owner = str3(asRecord3(record.namespace).path) ?? params.org ?? params.user ?? "";
3206
+ const repo = str3(record.name) ?? str3(record.path) ?? "";
3207
+ return mapRepository3(owner, repo, record);
3208
+ });
3209
+ }
3210
+ async getRepository(ctx, params) {
3211
+ const response = await ctx.http.request({
3212
+ method: "GET",
3213
+ path: REPO_PATH3,
3214
+ pathParams: repoParams2(params.owner, params.repo)
3215
+ });
3216
+ return mapRepository3(params.owner, params.repo, response.json);
3217
+ }
3218
+ async createRepository(ctx, params) {
3219
+ const path = params.org !== void 0 ? "/orgs/{org}/repos" : "/user/repos";
3220
+ const pathParams = params.org !== void 0 ? { org: params.org } : {};
3221
+ const response = await ctx.http.request({
3222
+ method: "POST",
3223
+ path,
3224
+ pathParams,
3225
+ body: {
3226
+ name: params.name,
3227
+ description: params.description,
3228
+ private: params.private,
3229
+ auto_init: params.auto_init
3230
+ }
3231
+ });
3232
+ const record = asRecord3(response.json);
3233
+ const owner = str3(asRecord3(record.namespace).path) ?? params.org ?? "";
3234
+ const repo = str3(record.name) ?? params.name;
3235
+ return mapRepository3(owner, repo, record);
3236
+ }
3237
+ async getFileContents(ctx, params) {
3238
+ const response = await ctx.http.request({
3239
+ method: "GET",
3240
+ path: `${REPO_PATH3}/contents/{path}`,
3241
+ pathParams: { owner: params.owner, repo: params.repo, path: params.path },
3242
+ query: { ref: params.ref }
3243
+ });
3244
+ if (Array.isArray(response.json)) {
3245
+ throw invalidArgumentError(
3246
+ `Invalid \`path\`: "${params.path}" is a directory. v0.1.0 getFileContents reads a single file only.`,
3247
+ "atomgit"
3248
+ );
3249
+ }
3250
+ return mapFileContent3(params.owner, params.repo, response.json);
3251
+ }
3252
+ /* ---------------------------------------------------------------------- */
3253
+ /* Files */
3254
+ /* ---------------------------------------------------------------------- */
3255
+ async createFile(ctx, params) {
3256
+ assertCreation3(params);
3257
+ return this.writeContents(ctx, params, "POST");
3258
+ }
3259
+ async updateFile(ctx, params) {
3260
+ assertUpdate3(params);
3261
+ return this.writeContents(ctx, params, "PUT");
3262
+ }
3263
+ async deleteFile(ctx, params) {
3264
+ const response = await ctx.http.request({
3265
+ method: "DELETE",
3266
+ path: `${REPO_PATH3}/contents/{path}`,
3267
+ pathParams: { owner: params.owner, repo: params.repo, path: params.path },
3268
+ body: { sha: params.sha, message: params.message, branch: params.branch }
3269
+ });
3270
+ const record = asRecord3(response.json);
3271
+ const commit = asRecord3(record.commit);
3272
+ return {
3273
+ provider: "atomgit",
3274
+ owner: params.owner,
3275
+ repo: params.repo,
3276
+ commit_sha: confirmedSha(ctx.http, response, commit.sha),
3277
+ commit_html_url: str3(commit.html_url) ?? "",
3278
+ paths: [params.path],
3279
+ branch: params.branch ?? ""
3280
+ };
3281
+ }
3282
+ /**
3283
+ * AtomGit has no batch commit endpoint, so this capability is not implemented.
3284
+ *
3285
+ * Splitting the batch into N single-file commits would break the contract's
3286
+ * "one commit" promise and could leave a partial, unrecoverable write.
3287
+ */
3288
+ pushFiles = unsupported("files.pushFiles", "atomgit");
3289
+ /* ---------------------------------------------------------------------- */
3290
+ /* Branch / Commit */
3291
+ /* ---------------------------------------------------------------------- */
3292
+ async listBranches(ctx, params) {
3293
+ const entries = await collectPages(
3294
+ ctx.http,
3295
+ {
3296
+ method: "GET",
3297
+ path: `${REPO_PATH3}/branches`,
3298
+ pathParams: repoParams2(params.owner, params.repo)
3299
+ },
3300
+ {
3301
+ maxPages: params.maxPages,
3302
+ selectItems: (raw) => asArray3(raw),
3303
+ keyOf: (raw) => listKey3(asRecord3(raw).name)
3304
+ }
3305
+ );
3306
+ return entries.map((entry) => mapBranch3(params.owner, params.repo, entry, ctx.webBaseUrl));
3307
+ }
3308
+ async createBranch(ctx, params) {
3309
+ const response = await ctx.http.request({
3310
+ method: "POST",
3311
+ path: `${REPO_PATH3}/branches`,
3312
+ pathParams: repoParams2(params.owner, params.repo),
3313
+ body: { refs: params.from, branch_name: params.name }
3314
+ });
3315
+ const record = asRecord3(response.json);
3316
+ const name = str3(record.name) ?? params.name;
3317
+ const branch = {
3318
+ provider: "atomgit",
3319
+ owner: params.owner,
3320
+ repo: params.repo,
3321
+ name,
3322
+ commit_sha: confirmedSha(ctx.http, response, asRecord3(record.commit).sha)
3323
+ };
3324
+ const isProtected = record.protected;
3325
+ if (typeof isProtected === "boolean") {
3326
+ branch.protected = isProtected;
3327
+ }
3328
+ const htmlUrl = deriveBranchHtmlUrl3(ctx.webBaseUrl, params.owner, params.repo, name);
3329
+ if (htmlUrl !== void 0) {
3330
+ branch.html_url = htmlUrl;
3331
+ }
3332
+ return branch;
3333
+ }
3334
+ async listCommits(ctx, params) {
3335
+ const entries = await collectPages(
3336
+ ctx.http,
3337
+ {
3338
+ method: "GET",
3339
+ path: `${REPO_PATH3}/commits`,
3340
+ pathParams: repoParams2(params.owner, params.repo)
3341
+ },
3342
+ {
3343
+ maxPages: params.maxPages,
3344
+ query: { sha: params.branch },
3345
+ selectItems: (raw) => asArray3(raw),
3346
+ keyOf: (raw) => listKey3(asRecord3(raw).sha)
3347
+ }
3348
+ );
3349
+ return entries.map((entry) => mapCommit3(params.owner, params.repo, entry));
3350
+ }
3351
+ async getCommit(ctx, params) {
3352
+ const response = await ctx.http.request({
3353
+ method: "GET",
3354
+ path: `${REPO_PATH3}/commits/{sha}`,
3355
+ pathParams: { ...repoParams2(params.owner, params.repo), sha: params.sha }
3356
+ });
3357
+ return mapCommit3(params.owner, params.repo, response.json);
3358
+ }
3359
+ /* ---------------------------------------------------------------------- */
3360
+ /* Internals */
3361
+ /* ---------------------------------------------------------------------- */
3362
+ /** Look for refs on one bounded list page; only a verified native identity may supply them. */
3363
+ async findPullRefs(ctx, params) {
3364
+ const response = await ctx.http.request({
3365
+ method: "GET",
3366
+ path: `${REPO_PATH3}/pulls`,
3367
+ pathParams: repoParams2(params.owner, params.repo),
3368
+ query: { state: "all", per_page: HEAD_BACKFILL_PER_PAGE, page: 1 }
3369
+ });
3370
+ if (!Array.isArray(response.json))
3371
+ throw ctx.http.invalidResponse(response, "Expected a pull request list");
3372
+ for (const raw of response.json) {
3373
+ if (requirePullNumber(ctx.http, response, raw) === params.number) {
3374
+ const row = asRecord3(raw);
3375
+ return { head: mapRef3(row.head), base: mapRef3(row.base) };
3376
+ }
3377
+ }
3378
+ return void 0;
3379
+ }
3380
+ /** Shared comment listing used by both issue and pull-request domains. */
3381
+ async listComments(ctx, params, path, parentUrl) {
3382
+ const entries = await collectPages(
3383
+ ctx.http,
3384
+ {
3385
+ method: "GET",
3386
+ path,
3387
+ pathParams: {
3388
+ ...repoParams2(params.owner, params.repo),
3389
+ number: String(params.number)
3390
+ }
3391
+ },
3392
+ {
3393
+ maxPages: params.maxPages,
3394
+ selectItems: (raw) => asArray3(raw),
3395
+ keyOf: (raw) => listKey3(asRecord3(raw).id)
3396
+ }
3397
+ );
3398
+ return entries.map((entry) => mapComment3(params.owner, params.repo, entry, parentUrl));
3399
+ }
3400
+ /** Shared comment creation used by both comment domains. */
3401
+ async createComment(ctx, params, path, parentUrl) {
3402
+ const response = await ctx.http.request({
3403
+ method: "POST",
3404
+ path,
3405
+ pathParams: {
3406
+ ...repoParams2(params.owner, params.repo),
3407
+ number: String(params.number)
3408
+ },
3409
+ body: { body: params.body }
3410
+ });
3411
+ return mapComment3(params.owner, params.repo, response.json, parentUrl);
3412
+ }
3413
+ /** Creates or replaces one file through the `contents` endpoints. */
3414
+ async writeContents(ctx, params, method) {
3415
+ const response = await ctx.http.request({
3416
+ method,
3417
+ path: `${REPO_PATH3}/contents/{path}`,
3418
+ pathParams: { owner: params.owner, repo: params.repo, path: params.path },
3419
+ body: {
3420
+ content: contentsBase64(params.content, params.encoding, "atomgit"),
3421
+ message: params.message,
3422
+ branch: params.branch,
3423
+ sha: params.sha
3424
+ }
3425
+ });
3426
+ const record = asRecord3(response.json);
3427
+ const commit = asRecord3(record.commit);
3428
+ const result = {
3429
+ provider: "atomgit",
3430
+ owner: params.owner,
3431
+ repo: params.repo,
3432
+ commit_sha: confirmedSha(ctx.http, response, commit.sha),
3433
+ // AtomGit's commit objects do carry `html_url`.
3434
+ commit_html_url: str3(commit.html_url) ?? "",
3435
+ paths: [params.path],
3436
+ branch: params.branch ?? ""
3437
+ };
3438
+ const fileUrl = str3(asRecord3(record.content).html_url);
3439
+ result.file_html_urls = [fileUrl];
3440
+ return result;
3441
+ }
3442
+ };
3443
+ var atomgitAdapter = new AtomGitAdapter();
3444
+
3445
+ // src/adapters/index.ts
3446
+ var ADAPTERS = {
3447
+ github: githubAdapter,
3448
+ gitee: giteeAdapter,
3449
+ atomgit: atomgitAdapter
3450
+ };
3451
+ function getAdapter(provider) {
3452
+ return ADAPTERS[provider];
3453
+ }
3454
+
3455
+ // src/core/bulk.ts
3456
+ var DEFAULT_BULK_CONCURRENCY = 4;
3457
+ async function bulk(items, run, options = {}) {
3458
+ if (!Array.isArray(items)) {
3459
+ throw invalidArgumentError("Invalid `items`: expected an array");
3460
+ }
3461
+ if (typeof run !== "function") {
3462
+ throw invalidArgumentError("Invalid `run`: expected a function");
3463
+ }
3464
+ const concurrency = normalizeConcurrency(options.concurrency);
3465
+ if (items.length === 0) {
3466
+ return [];
3467
+ }
3468
+ const results = new Array(items.length);
3469
+ let nextIndex = 0;
3470
+ const claimNext = () => {
3471
+ if (nextIndex >= items.length) {
3472
+ return void 0;
3473
+ }
3474
+ const index = nextIndex;
3475
+ nextIndex += 1;
3476
+ return index;
3477
+ };
3478
+ const processItem = async (item, index) => {
3479
+ try {
3480
+ const value = await run(item, index);
3481
+ results[index] = { ok: true, value, index };
3482
+ } catch (error) {
3483
+ results[index] = { ok: false, error: toErrorJson(error), index };
3484
+ }
3485
+ };
3486
+ const worker = async () => {
3487
+ for (; ; ) {
3488
+ const index = claimNext();
3489
+ if (index === void 0) {
3490
+ return;
3491
+ }
3492
+ const item = items[index];
3493
+ await processItem(item, index);
3494
+ }
3495
+ };
3496
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => worker());
3497
+ await Promise.all(workers);
3498
+ return results;
3499
+ }
3500
+ function normalizeConcurrency(value) {
3501
+ if (value === void 0) {
3502
+ return DEFAULT_BULK_CONCURRENCY;
3503
+ }
3504
+ if (!Number.isFinite(value) || value < 1) {
3505
+ throw invalidArgumentError("Invalid `concurrency`: expected a positive integer");
3506
+ }
3507
+ return Math.trunc(value);
3508
+ }
3509
+ function toErrorJson(error) {
3510
+ if (isGitForgeError(error)) {
3511
+ return error.toJSON();
3512
+ }
3513
+ const detail = error instanceof Error ? error.name : typeof error;
3514
+ return new GitForgeError({
3515
+ code: "PROVIDER_ERROR",
3516
+ message: `Unexpected failure (${detail})`
3517
+ }).toJSON();
3518
+ }
3519
+ function partitionBulk(results) {
3520
+ const succeeded = [];
3521
+ const failed = [];
3522
+ for (const result of results) {
3523
+ if (result.ok) {
3524
+ succeeded.push(result.value);
3525
+ } else {
3526
+ failed.push(result.error);
3527
+ }
3528
+ }
3529
+ return { succeeded, failed };
3530
+ }
3531
+ function allSucceeded(results) {
3532
+ return results.every((result) => result.ok);
3533
+ }
3534
+
3535
+ // src/core/validate.ts
3536
+ var WRITE_CAPABILITIES = /* @__PURE__ */ new Set([
3537
+ "issues.create",
3538
+ "issues.update",
3539
+ "issues.createComment",
3540
+ "pulls.create",
3541
+ "pulls.merge",
3542
+ "pulls.createComment",
3543
+ "repos.create",
3544
+ "files.create",
3545
+ "files.update",
3546
+ "files.delete",
3547
+ "files.pushFiles",
3548
+ "branches.create"
3549
+ ]);
3550
+ function isWriteCapability(capability) {
3551
+ return WRITE_CAPABILITIES.has(capability);
3552
+ }
3553
+ function invalid(field, reason, provider) {
3554
+ throw invalidArgumentError(`Invalid \`${field}\`: ${reason}`, provider);
3555
+ }
3556
+ function assertProvider(value) {
3557
+ if (typeof value !== "string" || !PROVIDERS.includes(value)) {
3558
+ invalid("provider", `expected one of ${PROVIDERS.join(" | ")}, received ${describe3(value)}`);
3559
+ }
3560
+ }
3561
+ function assertNonEmpty(field, value) {
3562
+ if (typeof value !== "string") {
3563
+ invalid(field, `expected a string, received ${describe3(value)}`);
3564
+ }
3565
+ if (value.trim().length === 0) {
3566
+ invalid(field, "must not be empty");
3567
+ }
3568
+ }
3569
+ function assertOptionalNonEmpty(field, value) {
3570
+ if (value === void 0) {
3571
+ return;
3572
+ }
3573
+ assertNonEmpty(field, value);
3574
+ }
3575
+ function assertOneOf(field, value, allowed) {
3576
+ if (typeof value !== "string" || !allowed.includes(value)) {
3577
+ invalid(field, `expected one of ${allowed.join(" | ")}, received ${describe3(value)}`);
3578
+ }
3579
+ }
3580
+ function assertNativeId(field, value) {
3581
+ if (typeof value === "string") {
3582
+ assertPathSegment(field, value);
3583
+ return;
3584
+ }
3585
+ if (typeof value !== "number" || !Number.isFinite(value)) {
3586
+ invalid(field, `expected a string or a finite number, received ${describe3(value)}`);
3587
+ }
3588
+ }
3589
+ function assertPositiveInt(field, value) {
3590
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
3591
+ invalid(field, `expected a positive integer, received ${describe3(value)}`);
3592
+ }
3593
+ }
3594
+ function assertOptionalPositiveInt(field, value) {
3595
+ if (value === void 0) {
3596
+ return;
3597
+ }
3598
+ assertPositiveInt(field, value);
3599
+ }
3600
+ function assertRepoRef(value) {
3601
+ if (value === null || typeof value !== "object") {
3602
+ invalid("owner/repo", `expected an object with owner and repo, received ${describe3(value)}`);
3603
+ }
3604
+ const ref = value;
3605
+ assertPathSegment("owner", ref.owner);
3606
+ assertPathSegment("repo", ref.repo);
3607
+ }
3608
+ function assertStringArray(field, value) {
3609
+ if (value === void 0) {
3610
+ return;
3611
+ }
3612
+ if (!Array.isArray(value)) {
3613
+ invalid(field, `expected an array of strings, received ${describe3(value)}`);
3614
+ }
3615
+ value.forEach((entry, index) => {
3616
+ if (typeof entry !== "string") {
3617
+ invalid(field, `entry ${index} must be a string, received ${describe3(entry)}`);
3618
+ }
3619
+ if (entry.trim().length === 0) {
3620
+ invalid(field, `entry ${index} must not be empty`);
3621
+ }
3622
+ });
3623
+ }
3624
+ function assertOptionalString(field, value) {
3625
+ if (value === void 0) {
3626
+ return;
3627
+ }
3628
+ if (typeof value !== "string") {
3629
+ invalid(field, `expected a string, received ${describe3(value)}`);
3630
+ }
3631
+ }
3632
+ function assertOptionalBoolean(field, value) {
3633
+ if (value === void 0) {
3634
+ return;
3635
+ }
3636
+ if (typeof value !== "boolean") {
3637
+ invalid(field, `expected a boolean, received ${describe3(value)}`);
3638
+ }
3639
+ }
3640
+ function assertOptionalOneOf(field, value, allowed) {
3641
+ if (value === void 0) {
3642
+ return;
3643
+ }
3644
+ assertOneOf(field, value, allowed);
3645
+ }
3646
+ function assertNonEmptyStringArray(field, value) {
3647
+ if (!Array.isArray(value)) {
3648
+ invalid(field, `expected a non-empty array, received ${describe3(value)}`);
3649
+ }
3650
+ if (value.length === 0) {
3651
+ invalid(field, "must contain at least one entry");
3652
+ }
3653
+ assertStringArray(field, value);
3654
+ }
3655
+ function assertPathSegment(field, value) {
3656
+ assertNonEmpty(field, value);
3657
+ if (unsafeSegment(value) || /[/\\?#]/.test(value)) {
3658
+ invalid(field, "must not contain path separators or query characters");
3659
+ }
3660
+ }
3661
+ function assertOptionalPathSegment(field, value) {
3662
+ if (value === void 0) {
3663
+ return;
3664
+ }
3665
+ assertPathSegment(field, value);
3666
+ }
3667
+ function unsafeSegment(value) {
3668
+ return value === "" || value === "." || value === ".." || /%(?:2e|2f|5c|25)/i.test(value) || Array.from(value).some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127);
3669
+ }
3670
+ function assertFilePath(field, value) {
3671
+ assertNonEmpty(field, value);
3672
+ const segments = value.split("/");
3673
+ if (segments.some(unsafeSegment) || value.includes("\\")) {
3674
+ invalid(field, 'must be a relative path and must not contain ".." segments');
3675
+ }
3676
+ }
3677
+ function assertOptionalFilePath(field, value) {
3678
+ if (value === void 0) {
3679
+ return;
3680
+ }
3681
+ assertFilePath(field, value);
3682
+ }
3683
+ function assertMaxPages(value) {
3684
+ if (value === void 0) {
3685
+ return;
3686
+ }
3687
+ assertPositiveInt("maxPages", value);
3688
+ if (value > MAX_PAGES_LIMIT) {
3689
+ invalid("maxPages", `must be <= ${MAX_PAGES_LIMIT}`);
3690
+ }
3691
+ }
3692
+ function assertParamsObject(value, method) {
3693
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
3694
+ invalid(`${method} parameters`, `expected an object, received ${describe3(value)}`);
3695
+ }
3696
+ }
3697
+ function assertCapabilityTableKeys(table) {
3698
+ const expected = new Set(CAPABILITY_IDS);
3699
+ const actual = Object.keys(table);
3700
+ const missing = [...expected].filter((key) => !actual.includes(key));
3701
+ const extra = actual.filter((key) => !expected.has(key));
3702
+ if (missing.length > 0 || extra.length > 0) {
3703
+ throw invalidArgumentError(
3704
+ `Capability table must match CAPABILITY_IDS exactly (missing: [${missing.join(", ")}], unexpected: [${extra.join(", ")}])`
3705
+ );
3706
+ }
3707
+ }
3708
+ var PUSH_FILE_ACTIONS = ["create", "update", "delete"];
3709
+ var PUSH_FILE_ENCODINGS = ["utf8", "base64"];
3710
+ var BASE64_ALPHABET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3711
+ function isValidBase64Payload(value) {
3712
+ const compact = value.replace(/\s+/g, "");
3713
+ const body = compact.replace(/={0,2}$/, "");
3714
+ if (body.length === 0 || body.length % 4 === 1) {
3715
+ return false;
3716
+ }
3717
+ for (const char of body) {
3718
+ if (!BASE64_ALPHABET3.includes(char)) {
3719
+ return false;
3720
+ }
3721
+ }
3722
+ return true;
3723
+ }
3724
+ function assertPushFilesParams(params) {
3725
+ assertParamsObject(params, "pushFiles");
3726
+ const bag = params;
3727
+ assertNonEmpty("branch", bag.branch);
3728
+ assertNonEmpty("message", bag.message);
3729
+ const files = bag.files;
3730
+ if (!Array.isArray(files)) {
3731
+ invalid("files", `expected an array of file entries, received ${describe3(files)}`);
3732
+ }
3733
+ if (files.length === 0) {
3734
+ invalid(
3735
+ "files",
3736
+ "pushFiles requires at least one entry (an empty batch would create an empty commit)"
3737
+ );
3738
+ }
3739
+ files.forEach((raw, index) => {
3740
+ const field = `files[${index}]`;
3741
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
3742
+ invalid(field, `expected an object, received ${describe3(raw)}`);
3743
+ }
3744
+ const entry = raw;
3745
+ assertFilePath(`${field}.path`, entry.path);
3746
+ assertOneOf(`${field}.action`, entry.action, PUSH_FILE_ACTIONS);
3747
+ const encoding = entry.encoding ?? "utf8";
3748
+ assertOneOf(`${field}.encoding`, encoding, PUSH_FILE_ENCODINGS);
3749
+ if (entry.action === "delete") {
3750
+ if (entry.content !== void 0) {
3751
+ invalid(field, `action 'delete' must not carry content`);
3752
+ }
3753
+ return;
3754
+ }
3755
+ if (typeof entry.content !== "string") {
3756
+ invalid(`${field}.content`, `action '${entry.action}' requires content`);
3757
+ }
3758
+ if (encoding === "base64" && !isValidBase64Payload(entry.content)) {
3759
+ invalid(`${field}.content`, "not a valid base64 payload");
3760
+ }
3761
+ });
3762
+ }
3763
+ function describe3(value) {
3764
+ if (value === null) {
3765
+ return "null";
3766
+ }
3767
+ if (value === void 0) {
3768
+ return "undefined";
3769
+ }
3770
+ if (typeof value === "string") {
3771
+ return value.length === 0 ? "an empty string" : `"${truncate2(value)}"`;
3772
+ }
3773
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
3774
+ return String(value);
3775
+ }
3776
+ if (Array.isArray(value)) {
3777
+ return `an array of length ${value.length}`;
3778
+ }
3779
+ return typeof value;
3780
+ }
3781
+ function truncate2(value) {
3782
+ return value.length <= 60 ? value : `${value.slice(0, 60)}\u2026`;
3783
+ }
3784
+
3785
+ // src/core/retry.ts
3786
+ var DEFAULT_RETRY_POLICY = {
3787
+ maxRetries: 3,
3788
+ baseMs: 500,
3789
+ factor: 2,
3790
+ maxDelayMs: 8e3,
3791
+ writes: false,
3792
+ maxRetryAfterMs: 6e4
3793
+ };
3794
+ var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
3795
+ function isIdempotentMethod(method) {
3796
+ return IDEMPOTENT_METHODS.has(method.toUpperCase());
3797
+ }
3798
+ function resolveRetryPolicy(overrides) {
3799
+ if (overrides === void 0) {
3800
+ return { ...DEFAULT_RETRY_POLICY };
3801
+ }
3802
+ return {
3803
+ maxRetries: overrides.maxRetries ?? DEFAULT_RETRY_POLICY.maxRetries,
3804
+ baseMs: overrides.baseMs ?? DEFAULT_RETRY_POLICY.baseMs,
3805
+ factor: overrides.factor ?? DEFAULT_RETRY_POLICY.factor,
3806
+ maxDelayMs: overrides.maxDelayMs ?? DEFAULT_RETRY_POLICY.maxDelayMs,
3807
+ writes: overrides.writes ?? DEFAULT_RETRY_POLICY.writes,
3808
+ maxRetryAfterMs: overrides.maxRetryAfterMs ?? DEFAULT_RETRY_POLICY.maxRetryAfterMs
3809
+ };
3810
+ }
3811
+ function computeDelay(attempt, policy, random, retryAfterMs) {
3812
+ if (retryAfterMs !== void 0) return retryAfterMs;
3813
+ const ceiling = Math.min(
3814
+ policy.baseMs * policy.factor ** Math.max(attempt - 1, 0),
3815
+ policy.maxDelayMs
3816
+ );
3817
+ return Math.floor(random() * ceiling);
3818
+ }
3819
+ function parseRetryAfter(value, maxMs) {
3820
+ if (value === null || value === void 0) {
3821
+ return void 0;
3822
+ }
3823
+ const trimmed = value.trim();
3824
+ if (trimmed.length === 0) {
3825
+ return void 0;
3826
+ }
3827
+ if (/^\d+$/.test(trimmed)) {
3828
+ const ms2 = Number(trimmed) * 1e3;
3829
+ return maxMs === void 0 ? ms2 : Math.min(ms2, maxMs);
3830
+ }
3831
+ const imfDate = /^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/;
3832
+ const rfc850 = /^[A-Za-z]+, \d{2}-[A-Za-z]{3}-\d{2} \d{2}:\d{2}:\d{2} GMT$/;
3833
+ const asctime = /^[A-Za-z]{3} [A-Za-z]{3} [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/;
3834
+ if (!imfDate.test(trimmed) && !rfc850.test(trimmed) && !asctime.test(trimmed)) return void 0;
3835
+ const date = Date.parse(trimmed.endsWith(" GMT") ? trimmed : `${trimmed} GMT`);
3836
+ if (Number.isNaN(date)) {
3837
+ return void 0;
3838
+ }
3839
+ const delta = date - Date.now();
3840
+ const ms = delta <= 0 ? 0 : delta;
3841
+ return maxMs === void 0 ? ms : Math.min(ms, maxMs);
3842
+ }
3843
+ function shouldRetry(input) {
3844
+ const { attempt, method, code, status, retryAfterMs, policy } = input;
3845
+ const maxServerWait = Math.min(policy.maxRetryAfterMs, 2 ** 31 - 1);
3846
+ if (retryAfterMs !== void 0 && !(retryAfterMs <= maxServerWait)) return false;
3847
+ if (attempt > policy.maxRetries) {
3848
+ return false;
3849
+ }
3850
+ if (!isIdempotentMethod(method) && !policy.writes) {
3851
+ return false;
3852
+ }
3853
+ if (code === "NETWORK_ERROR" || code === "RATE_LIMITED") {
3854
+ return true;
3855
+ }
3856
+ if (code === "PROVIDER_ERROR") {
3857
+ return status !== void 0 ? retryableForStatus(code, status) : defaultRetryable(code);
3858
+ }
3859
+ return false;
3860
+ }
3861
+ function retryAfterFromHeaders(headers, maxMs) {
3862
+ if (headers === void 0) {
3863
+ return void 0;
3864
+ }
3865
+ const retryAfter = parseRetryAfter(readHeader3(headers, "retry-after"), maxMs);
3866
+ if (retryAfter !== void 0) {
3867
+ return retryAfter;
3868
+ }
3869
+ if (readHeader3(headers, "x-ratelimit-remaining")?.trim() !== "0") return void 0;
3870
+ const reset = readHeader3(headers, "x-ratelimit-reset");
3871
+ if (reset !== void 0 && /^\d+$/.test(reset.trim())) {
3872
+ const delta = Number(reset.trim()) * 1e3 - Date.now();
3873
+ if (delta > 0) {
3874
+ return maxMs === void 0 ? delta : Math.min(delta, maxMs);
3875
+ }
3876
+ }
3877
+ return void 0;
3878
+ }
3879
+ function readHeader3(headers, key) {
3880
+ if (typeof headers.get === "function") {
3881
+ const value = headers.get(key);
3882
+ return value === null ? void 0 : value;
3883
+ }
3884
+ const record = headers;
3885
+ return record[key] ?? record[key.toLowerCase()];
3886
+ }
3887
+ function isRetryableStatus(status, headers) {
3888
+ if (status === 429) {
3889
+ return true;
3890
+ }
3891
+ if (status >= 500) {
3892
+ return true;
3893
+ }
3894
+ return isRateLimitResponse(status, headers);
3895
+ }
3896
+
3897
+ // src/core/http.ts
3898
+ var DEFAULT_TIMEOUT_MS = 3e4;
3899
+ var DEFAULT_USER_AGENT = "git-forge/0.1.0";
3900
+ var HttpClient = class {
3901
+ #base;
3902
+ get baseUrl() {
3903
+ return stripTrailingSlash(this.#base.href);
3904
+ }
3905
+ timeoutMs;
3906
+ provider;
3907
+ auth;
3908
+ token;
3909
+ defaultHeaders;
3910
+ fetchImpl;
3911
+ sleep;
3912
+ random;
3913
+ policy;
3914
+ userAgent;
3915
+ constructor(options) {
3916
+ try {
3917
+ this.#base = new URL(options.baseUrl);
3918
+ } catch {
3919
+ throw invalidArgumentError("Invalid baseUrl: expected an absolute URL", options.provider);
3920
+ }
3921
+ const { protocol, hostname, username, password, hash } = this.#base;
3922
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(hostname);
3923
+ if (protocol !== "https:" && !(protocol === "http:" && loopback) || username || password || hash) {
3924
+ throw invalidArgumentError(
3925
+ "Invalid baseUrl: expected HTTPS or loopback without userinfo or fragment",
3926
+ options.provider
3927
+ );
3928
+ }
3929
+ this.provider = options.provider;
3930
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
3931
+ this.auth = options.auth;
3932
+ this.token = options.token;
3933
+ this.defaultHeaders = options.defaultHeaders ?? {};
3934
+ const injectedFetch = options.fetch;
3935
+ this.fetchImpl = injectedFetch ?? ((input, init) => globalThis.fetch(input, init));
3936
+ this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
3937
+ this.random = options.random ?? Math.random;
3938
+ this.policy = resolveRetryPolicy(options.retry);
3939
+ this.userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
3940
+ }
3941
+ /** Whether a token was configured on this client. */
3942
+ get hasToken() {
3943
+ return this.token !== void 0 && this.token.length > 0;
3944
+ }
3945
+ /**
3946
+ * Renders a request for diagnostics.
3947
+ *
3948
+ * Query parameters are shown, path parameters are *not* substituted: the
3949
+ * template is what belongs in a message, both because a concrete path can
3950
+ * carry identifying data and because a caller needs the template to find the
3951
+ * endpoint in the platform docs. Under query-style auth the parameter is
3952
+ * present but redacted.
3953
+ */
3954
+ describe(spec) {
3955
+ const params = new URLSearchParams();
3956
+ if (spec.query !== void 0) {
3957
+ for (const [key, value] of Object.entries(spec.query)) {
3958
+ if (value !== void 0) {
3959
+ params.set(key, stringifyScalar(value));
3960
+ }
3961
+ }
3962
+ }
3963
+ if (spec.paramsIn === "query" && spec.body !== void 0 && typeof spec.body === "object") {
3964
+ for (const [key, value] of Object.entries(spec.body)) {
3965
+ if (value !== void 0 && value !== null) {
3966
+ params.set(key, stringifyScalar(value));
3967
+ }
3968
+ }
3969
+ }
3970
+ if (this.auth?.style === "query" && this.token !== void 0 && this.token.length > 0) {
3971
+ params.set(this.auth.param ?? "access_token", REDACTED);
3972
+ }
3973
+ const query = params.toString();
3974
+ const suffix = query.length > 0 ? `?${query}` : "";
3975
+ return scrubSecrets(
3976
+ redactUrl(
3977
+ `${this.#base.origin}${stripTrailingSlash(this.#base.pathname)}${spec.path}${suffix}`
3978
+ ),
3979
+ this.secretValues()
3980
+ ).slice(0, 768);
3981
+ }
3982
+ /**
3983
+ * Performs one logical request, retrying per policy.
3984
+ *
3985
+ * @throws GitForgeError always — a raw `Error` never escapes this method.
3986
+ */
3987
+ async request(spec) {
3988
+ const maxAttempts = this.policy.maxRetries + 1;
3989
+ let lastError;
3990
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
3991
+ const outcome = await this.attempt(spec);
3992
+ if (outcome.kind === "response") {
3993
+ return outcome.response;
3994
+ }
3995
+ const { error, retryAfterMs } = outcome;
3996
+ lastError = error;
3997
+ const retryable = shouldRetry({
3998
+ attempt,
3999
+ method: spec.method,
4000
+ code: error.code,
4001
+ status: error.status,
4002
+ policy: this.policy,
4003
+ retryAfterMs
4004
+ });
4005
+ if (!retryable) {
4006
+ throw error;
4007
+ }
4008
+ const delay = computeDelay(attempt, this.policy, this.random, retryAfterMs);
4009
+ await this.sleep(delay);
4010
+ }
4011
+ throw lastError ?? new Error("request failed without an error");
4012
+ }
4013
+ /** Performs exactly one attempt and reports its outcome without retrying. */
4014
+ async attempt(spec) {
4015
+ const url = this.buildUrl(spec);
4016
+ const headers = this.buildHeaders(spec);
4017
+ const body = this.buildBody(spec);
4018
+ const context = this.describe(spec);
4019
+ const secrets = this.secretValues();
4020
+ const signal = AbortSignal.timeout(this.timeoutMs);
4021
+ let response;
4022
+ let text;
4023
+ try {
4024
+ response = await this.fetchImpl(url, {
4025
+ method: spec.method,
4026
+ headers,
4027
+ body: body ?? null,
4028
+ signal,
4029
+ redirect: "error"
4030
+ });
4031
+ text = await response.text();
4032
+ } catch (cause) {
4033
+ const unconfirmedWrite = spec.method !== "GET" && response?.ok === true;
4034
+ const error = errorFromNetwork({
4035
+ provider: this.provider,
4036
+ context,
4037
+ cause,
4038
+ secrets,
4039
+ response,
4040
+ timeoutMs: this.timeoutMs,
4041
+ retryable: !unconfirmedWrite
4042
+ });
4043
+ if (unconfirmedWrite) throw error;
4044
+ return { kind: "failure", error, retryAfterMs: response && this.serverDelay(response) };
4045
+ }
4046
+ let json;
4047
+ if (text.length > 0) {
4048
+ try {
4049
+ json = JSON.parse(text);
4050
+ } catch {
4051
+ if (response.ok) throw this.invalidResponse(response, "Expected a JSON response");
4052
+ }
4053
+ }
4054
+ if (!text.length && response.ok && response.status !== 204 && response.status !== 205) {
4055
+ throw this.invalidResponse(response, "Expected a JSON response");
4056
+ }
4057
+ if (!response.ok) {
4058
+ const error = errorFromResponse({
4059
+ provider: this.provider,
4060
+ status: response.status,
4061
+ headers: response.headers,
4062
+ body: json,
4063
+ context,
4064
+ secrets
4065
+ });
4066
+ return { kind: "failure", error, retryAfterMs: this.serverDelay(response) };
4067
+ }
4068
+ return {
4069
+ kind: "response",
4070
+ response: { status: response.status, headers: response.headers, json }
4071
+ };
4072
+ }
4073
+ /** Honor delay headers even if reading the response body failed. */
4074
+ serverDelay(response) {
4075
+ return this.provider === "github" && isRateLimitResponse(response.status, response.headers) ? retryAfterFromHeaders(response.headers) : parseRetryAfter(response.headers.get("retry-after"));
4076
+ }
4077
+ /**
4078
+ * Builds the concrete URL, including the token when query-style auth is on.
4079
+ *
4080
+ * `describe()` redacts the result, so the token exists only inside this
4081
+ * function's return value and never reaches a message on its own.
4082
+ */
4083
+ buildUrl(spec) {
4084
+ let path;
4085
+ try {
4086
+ path = substitutePath(spec.path, spec.pathParams);
4087
+ } catch {
4088
+ throw invalidArgumentError("Invalid request path or path parameter", this.provider);
4089
+ }
4090
+ const url = new URL(this.#base.href);
4091
+ const prefix = stripTrailingSlash(this.#base.pathname);
4092
+ url.pathname = prefix + path;
4093
+ if (url.origin !== this.#base.origin || !url.pathname.startsWith(`${prefix}/`) || url.pathname !== prefix + path) {
4094
+ throw invalidArgumentError("Invalid request path for the configured API base", this.provider);
4095
+ }
4096
+ const queryParams = {
4097
+ ...spec.query ?? {}
4098
+ };
4099
+ if (spec.paramsIn === "query" && spec.body !== void 0 && typeof spec.body === "object") {
4100
+ for (const [key, value] of Object.entries(spec.body)) {
4101
+ if (value !== void 0 && value !== null) {
4102
+ queryParams[key] = value;
4103
+ }
4104
+ }
4105
+ }
4106
+ for (const [key, value] of Object.entries(queryParams)) {
4107
+ if (value !== void 0) {
4108
+ url.searchParams.set(key, String(value));
4109
+ }
4110
+ }
4111
+ if (this.auth?.style === "query" && this.token !== void 0 && this.token.length > 0) {
4112
+ url.searchParams.set(this.auth.param ?? "access_token", this.token);
4113
+ }
4114
+ return url.toString();
4115
+ }
4116
+ /** Assembles request headers, injecting auth when bearer-style. */
4117
+ buildHeaders(spec) {
4118
+ const headers = {
4119
+ "user-agent": this.userAgent,
4120
+ ...lowercaseKeys(this.defaultHeaders)
4121
+ };
4122
+ if (this.auth?.style !== "query" && this.token !== void 0 && this.token.length > 0) {
4123
+ headers.authorization = `Bearer ${this.token}`;
4124
+ }
4125
+ const hasBody = spec.body !== void 0 && spec.paramsIn !== "query";
4126
+ if (hasBody && headers["content-type"] === void 0) {
4127
+ headers["content-type"] = spec.paramsIn === "form" ? "application/x-www-form-urlencoded" : "application/json";
4128
+ }
4129
+ if (spec.headers !== void 0) {
4130
+ Object.assign(headers, lowercaseKeys(spec.headers));
4131
+ }
4132
+ return headers;
4133
+ }
4134
+ /** Encodes the body per `paramsIn`. */
4135
+ buildBody(spec) {
4136
+ if (spec.body === void 0 || spec.paramsIn === "query") {
4137
+ return void 0;
4138
+ }
4139
+ if (spec.paramsIn === "form") {
4140
+ const params = new URLSearchParams();
4141
+ for (const [key, value] of Object.entries(spec.body)) {
4142
+ if (value === void 0 || value === null) {
4143
+ continue;
4144
+ }
4145
+ params.set(key, encodeFormValue(value));
4146
+ }
4147
+ return params.toString();
4148
+ }
4149
+ return JSON.stringify(spec.body);
4150
+ }
4151
+ /** Builds a non-replayable error when success cannot be confirmed; uses header metadata only. */
4152
+ invalidResponse(response, message) {
4153
+ return new GitForgeError({
4154
+ code: "PROVIDER_ERROR",
4155
+ provider: this.provider,
4156
+ status: response.status,
4157
+ requestId: extractRequestId(response.headers),
4158
+ message,
4159
+ secrets: this.secretValues()
4160
+ });
4161
+ }
4162
+ /** Known token values, for scrubbing error messages. */
4163
+ secretValues() {
4164
+ if (!this.token) return [];
4165
+ return [
4166
+ this.token,
4167
+ encodeURIComponent(this.token),
4168
+ new URLSearchParams([["v", this.token]]).toString().slice(2)
4169
+ ];
4170
+ }
4171
+ };
4172
+ function substitutePath(template, params) {
4173
+ if (!template.startsWith("/") || /[?#\\]/.test(template))
4174
+ throw invalidArgumentError("Expected an absolute API path without query or fragment");
4175
+ if (template === "/") return template;
4176
+ return "/" + template.slice(1).split("/").map((segment) => {
4177
+ const key = /^\{(\w+)\}$/.exec(segment)?.[1];
4178
+ if (key !== void 0) {
4179
+ const value = params?.[key];
4180
+ if (["path", "ref", "branch"].includes(key)) {
4181
+ assertFilePath(key, value);
4182
+ return value.split("/").map(encodeURIComponent).join("/");
4183
+ }
4184
+ assertPathSegment(key, value);
4185
+ return encodeURIComponent(value);
4186
+ }
4187
+ try {
4188
+ assertPathSegment("path", decodeURIComponent(segment));
4189
+ } catch {
4190
+ throw invalidArgumentError("Invalid API path segment");
4191
+ }
4192
+ return segment;
4193
+ }).join("/");
4194
+ }
4195
+ function lowercaseKeys(record) {
4196
+ const out = {};
4197
+ for (const [key, value] of Object.entries(record)) {
4198
+ out[key.toLowerCase()] = value;
4199
+ }
4200
+ return out;
4201
+ }
4202
+ function encodeFormValue(value) {
4203
+ if (Array.isArray(value)) {
4204
+ return value.map((entry) => stringifyScalar(entry)).join(",");
4205
+ }
4206
+ if (typeof value === "object" && value !== null) {
4207
+ return JSON.stringify(value);
4208
+ }
4209
+ return stringifyScalar(value);
4210
+ }
4211
+ function stringifyScalar(value) {
4212
+ if (typeof value === "string") {
4213
+ return value;
4214
+ }
4215
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
4216
+ return String(value);
4217
+ }
4218
+ if (value === null) {
4219
+ return "";
4220
+ }
4221
+ return JSON.stringify(value) ?? "";
4222
+ }
4223
+ function stripTrailingSlash(value) {
4224
+ return value.endsWith("/") ? value.slice(0, -1) : value;
4225
+ }
4226
+
4227
+ // src/client.ts
4228
+ var DEFAULT_ENDPOINTS = {
4229
+ github: { api: "https://api.github.com", web: "https://github.com" },
4230
+ gitee: { api: "https://gitee.com/api/v5", web: "https://gitee.com" },
4231
+ atomgit: { api: "https://api.atomgit.com/api/v5", web: "https://atomgit.com" }
4232
+ };
4233
+ var TOKEN_ENV_VARS = {
4234
+ github: "GITHUB_TOKEN",
4235
+ gitee: "GITEE_TOKEN",
4236
+ atomgit: "ATOMGIT_TOKEN"
4237
+ };
4238
+ function assertEndpoint(provider, field, value) {
4239
+ if (value === void 0) {
4240
+ return;
4241
+ }
4242
+ if (typeof value !== "string")
4243
+ throw invalidArgumentError(`Invalid ${provider}.${field}: expected a URL string`, provider);
4244
+ let parsed;
4245
+ try {
4246
+ parsed = new URL(value);
4247
+ } catch {
4248
+ throw invalidArgumentError(
4249
+ `Invalid \`${provider}.${field}\`: expected an absolute URL`,
4250
+ provider
4251
+ );
4252
+ }
4253
+ const isLoopback = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1" || parsed.hostname === "[::1]" || parsed.hostname === "::1";
4254
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopback)) {
4255
+ throw invalidArgumentError(
4256
+ `Invalid \`${provider}.${field}\`: must use https: (http: is allowed for localhost only)`,
4257
+ provider
4258
+ );
4259
+ }
4260
+ }
4261
+ function trimSlash(value) {
4262
+ return value.endsWith("/") ? value.slice(0, -1) : value;
4263
+ }
4264
+ function validateListFilters(params) {
4265
+ assertStringArray("labels", params.labels);
4266
+ assertMaxPages(params.maxPages);
4267
+ }
4268
+ function validateListIssues(params) {
4269
+ assertRepoRef(params);
4270
+ assertOptionalBoolean("requireComplete", params.requireComplete);
4271
+ assertOptionalOneOf("state", params.state, ["open", "closed", "all"]);
4272
+ assertOptionalPositiveInt("milestone", params.milestone);
4273
+ validateListFilters(params);
4274
+ }
4275
+ function validateGetIssue(params) {
4276
+ assertRepoRef(params);
4277
+ assertNativeId("number", params.number);
4278
+ }
4279
+ function validateCreateIssue(params) {
4280
+ assertRepoRef(params);
4281
+ assertNonEmpty("title", params.title);
4282
+ assertOptionalString("body", params.body);
4283
+ assertOptionalPositiveInt("milestone", params.milestone);
4284
+ assertStringArray("labels", params.labels);
4285
+ }
4286
+ function validateUpdateIssue(params) {
4287
+ assertRepoRef(params);
4288
+ assertNativeId("number", params.number);
4289
+ assertOptionalNonEmpty("title", params.title);
4290
+ assertOptionalString("body", params.body);
4291
+ assertOptionalOneOf("state", params.state, ["open", "closed"]);
4292
+ assertOptionalPositiveInt("milestone", params.milestone);
4293
+ assertStringArray("labels", params.labels);
4294
+ }
4295
+ function validateListComments(params) {
4296
+ assertRepoRef(params);
4297
+ assertNativeId("number", params.number);
4298
+ assertMaxPages(params.maxPages);
4299
+ }
4300
+ function validateGetPullRequest(params) {
4301
+ assertRepoRef(params);
4302
+ if (!Number.isSafeInteger(params.number) || params.number <= 0) {
4303
+ throw invalidArgumentError("Invalid `number`: expected a positive safe integer");
4304
+ }
4305
+ }
4306
+ function validateListPullRequests(params) {
4307
+ assertRepoRef(params);
4308
+ assertOptionalOneOf("state", params.state, ["open", "closed", "all"]);
4309
+ assertOptionalNonEmpty("head", params.head);
4310
+ assertOptionalNonEmpty("base", params.base);
4311
+ assertOptionalPositiveInt("milestone", params.milestone);
4312
+ validateListFilters(params);
4313
+ }
4314
+ function validateCreatePullRequest(params) {
4315
+ assertRepoRef(params);
4316
+ assertNonEmpty("title", params.title);
4317
+ assertNonEmpty("head", params.head);
4318
+ assertNonEmpty("base", params.base);
4319
+ assertOptionalString("body", params.body);
4320
+ assertOptionalBoolean("draft", params.draft);
4321
+ }
4322
+ function validateCreateComment(params) {
4323
+ assertRepoRef(params);
4324
+ assertNativeId("number", params.number);
4325
+ assertNonEmpty("body", params.body);
4326
+ }
4327
+ function validateMergePullRequest(params) {
4328
+ validateGetPullRequest(params);
4329
+ assertOptionalOneOf("merge_method", params.merge_method, ["merge", "squash", "rebase"]);
4330
+ assertOptionalString("commit_title", params.commit_title);
4331
+ assertOptionalString("commit_message", params.commit_message);
4332
+ }
4333
+ function validateListRepositories(params) {
4334
+ if (params.org !== void 0 && params.user !== void 0) {
4335
+ throw invalidArgumentError("Invalid `org`/`user`: provide at most one of them");
4336
+ }
4337
+ assertOptionalPathSegment("org", params.org);
4338
+ assertOptionalPathSegment("user", params.user);
4339
+ assertMaxPages(params.maxPages);
4340
+ }
4341
+ function validateCreateRepository(params) {
4342
+ assertNonEmpty("name", params.name);
4343
+ assertOptionalString("description", params.description);
4344
+ assertOptionalBoolean("private", params.private);
4345
+ assertOptionalBoolean("auto_init", params.auto_init);
4346
+ assertOptionalPathSegment("org", params.org);
4347
+ }
4348
+ function validateGetFileContents(params) {
4349
+ assertRepoRef(params);
4350
+ assertFilePath("path", params.path);
4351
+ assertOptionalNonEmpty("ref", params.ref);
4352
+ }
4353
+ function validateCreateOrUpdateFile(params) {
4354
+ assertRepoRef(params);
4355
+ assertFilePath("path", params.path);
4356
+ if (typeof params.content !== "string") {
4357
+ throw invalidArgumentError("Invalid `content`: expected a string");
4358
+ }
4359
+ assertNonEmpty("message", params.message);
4360
+ assertOptionalNonEmpty("branch", params.branch);
4361
+ assertOptionalNonEmpty("sha", params.sha);
4362
+ assertOptionalOneOf("encoding", params.encoding, ["base64", "utf8"]);
4363
+ }
4364
+ function validateDeleteFile(params) {
4365
+ assertRepoRef(params);
4366
+ assertFilePath("path", params.path);
4367
+ assertNonEmpty("message", params.message);
4368
+ assertNonEmpty("sha", params.sha);
4369
+ assertOptionalNonEmpty("branch", params.branch);
4370
+ }
4371
+ function validatePushFiles(params) {
4372
+ assertRepoRef(params);
4373
+ assertPushFilesParams(params);
4374
+ }
4375
+ function validateCreateBranch(params) {
4376
+ assertRepoRef(params);
4377
+ assertNonEmpty("name", params.name);
4378
+ assertNonEmpty("from", params.from);
4379
+ }
4380
+ function validateListCommits(params) {
4381
+ assertRepoRef(params);
4382
+ assertOptionalNonEmpty("branch", params.branch);
4383
+ assertMaxPages(params.maxPages);
4384
+ }
4385
+ function validateGetCommit(params) {
4386
+ assertRepoRef(params);
4387
+ assertNonEmpty("sha", params.sha);
4388
+ }
4389
+ var GitClient = class {
4390
+ /** Whether write capabilities are refused. */
4391
+ readonly;
4392
+ providers;
4393
+ constructor(options = {}) {
4394
+ this.readonly = options.readonly === true;
4395
+ this.providers = {
4396
+ github: this.resolve("github", options),
4397
+ gitee: this.resolve("gitee", options),
4398
+ atomgit: this.resolve("atomgit", options)
4399
+ };
4400
+ }
4401
+ /** Providers that have a token configured. Names only — never values. */
4402
+ configuredProviders() {
4403
+ return ["github", "gitee", "atomgit"].filter(
4404
+ (provider) => this.providers[provider].hasToken
4405
+ );
4406
+ }
4407
+ /** Capability table of one provider, for callers that render a matrix. */
4408
+ capabilities(provider) {
4409
+ assertProvider(provider);
4410
+ return this.providers[provider].adapter.capabilities;
4411
+ }
4412
+ /** Parameter-level capability table of one provider. */
4413
+ paramCapabilities(provider) {
4414
+ assertProvider(provider);
4415
+ return this.providers[provider].adapter.paramCapabilities;
4416
+ }
4417
+ /* ---------------------------------------------------------------------- */
4418
+ /* Issue */
4419
+ /* ---------------------------------------------------------------------- */
4420
+ /** Lists issues, aggregating every page. */
4421
+ listIssues(params) {
4422
+ return this.dispatch(
4423
+ "listIssues",
4424
+ "issues.list",
4425
+ params,
4426
+ validateListIssues,
4427
+ (p, ctx) => ctx.adapter.listIssues(ctx.ctx, p)
4428
+ );
4429
+ }
4430
+ /** Reads one issue. */
4431
+ getIssue(params) {
4432
+ return this.dispatch(
4433
+ "getIssue",
4434
+ "issues.get",
4435
+ params,
4436
+ validateGetIssue,
4437
+ (p, ctx) => ctx.adapter.getIssue(ctx.ctx, p)
4438
+ );
4439
+ }
4440
+ /** Creates an issue. */
4441
+ createIssue(params) {
4442
+ return this.dispatch(
4443
+ "createIssue",
4444
+ "issues.create",
4445
+ params,
4446
+ validateCreateIssue,
4447
+ (p, ctx) => ctx.adapter.createIssue(ctx.ctx, p)
4448
+ );
4449
+ }
4450
+ /** Updates an issue, leaving omitted fields untouched. */
4451
+ updateIssue(params) {
4452
+ return this.dispatch(
4453
+ "updateIssue",
4454
+ "issues.update",
4455
+ params,
4456
+ validateUpdateIssue,
4457
+ (p, ctx) => ctx.adapter.updateIssue(ctx.ctx, p)
4458
+ );
4459
+ }
4460
+ /** Lists an issue's comments. */
4461
+ listIssueComments(params) {
4462
+ return this.dispatch(
4463
+ "listIssueComments",
4464
+ "issues.listComments",
4465
+ params,
4466
+ validateListComments,
4467
+ (p, ctx) => ctx.adapter.listIssueComments(ctx.ctx, p)
4468
+ );
4469
+ }
4470
+ /** Adds a comment to an issue. */
4471
+ createIssueComment(params) {
4472
+ return this.dispatch(
4473
+ "createIssueComment",
4474
+ "issues.createComment",
4475
+ params,
4476
+ validateCreateComment,
4477
+ (p, ctx) => ctx.adapter.createIssueComment(ctx.ctx, p)
4478
+ );
4479
+ }
4480
+ /* ---------------------------------------------------------------------- */
4481
+ /* Pull request */
4482
+ /* ---------------------------------------------------------------------- */
4483
+ /**
4484
+ * Lists pull requests.
4485
+ *
4486
+ * The `head` filter goes through the parameter capability gate: AtomGit has no
4487
+ * such filter, and returning an unfiltered list would be undetectable.
4488
+ */
4489
+ listPullRequests(params) {
4490
+ return this.dispatch(
4491
+ "listPullRequests",
4492
+ "pulls.list",
4493
+ params,
4494
+ validateListPullRequests,
4495
+ (p, ctx) => ctx.adapter.listPullRequests(ctx.ctx, p),
4496
+ (p, ctx) => {
4497
+ if (p.head !== void 0) {
4498
+ this.assertParamCapability(ctx, "pulls.list.headFilter");
4499
+ }
4500
+ if (p.milestone !== void 0) {
4501
+ this.assertParamCapability(ctx, "pulls.list.milestoneFilter");
4502
+ }
4503
+ }
4504
+ );
4505
+ }
4506
+ /** Reads one pull request. */
4507
+ getPullRequest(params) {
4508
+ return this.dispatch(
4509
+ "getPullRequest",
4510
+ "pulls.get",
4511
+ params,
4512
+ validateGetPullRequest,
4513
+ (p, ctx) => ctx.adapter.getPullRequest(ctx.ctx, p)
4514
+ );
4515
+ }
4516
+ /** Opens a pull request. */
4517
+ createPullRequest(params) {
4518
+ return this.dispatch(
4519
+ "createPullRequest",
4520
+ "pulls.create",
4521
+ params,
4522
+ validateCreatePullRequest,
4523
+ (p, ctx) => ctx.adapter.createPullRequest(ctx.ctx, p)
4524
+ );
4525
+ }
4526
+ /** Merges a pull request and returns its post-merge state. */
4527
+ mergePullRequest(params) {
4528
+ return this.dispatch(
4529
+ "mergePullRequest",
4530
+ "pulls.merge",
4531
+ params,
4532
+ validateMergePullRequest,
4533
+ (p, ctx) => ctx.adapter.mergePullRequest(ctx.ctx, p)
4534
+ );
4535
+ }
4536
+ /** Lists a pull request's comments. */
4537
+ listPullRequestComments(params) {
4538
+ return this.dispatch(
4539
+ "listPullRequestComments",
4540
+ "pulls.listComments",
4541
+ params,
4542
+ validateListComments,
4543
+ (p, ctx) => ctx.adapter.listPullRequestComments(ctx.ctx, p)
4544
+ );
4545
+ }
4546
+ /** Adds a comment to a pull request. */
4547
+ createPullRequestComment(params) {
4548
+ return this.dispatch(
4549
+ "createPullRequestComment",
4550
+ "pulls.createComment",
4551
+ params,
4552
+ validateCreateComment,
4553
+ (p, ctx) => ctx.adapter.createPullRequestComment(ctx.ctx, p)
4554
+ );
4555
+ }
4556
+ /* ---------------------------------------------------------------------- */
4557
+ /* Repository */
4558
+ /* ---------------------------------------------------------------------- */
4559
+ /** Lists repositories of an org, a user, or the authenticated account. */
4560
+ listRepositories(params) {
4561
+ return this.dispatch(
4562
+ "listRepositories",
4563
+ "repos.list",
4564
+ params,
4565
+ validateListRepositories,
4566
+ (p, ctx) => ctx.adapter.listRepositories(ctx.ctx, p)
4567
+ );
4568
+ }
4569
+ /** Reads one repository. */
4570
+ getRepository(params) {
4571
+ return this.dispatch(
4572
+ "getRepository",
4573
+ "repos.get",
4574
+ params,
4575
+ assertRepoRef,
4576
+ (p, ctx) => ctx.adapter.getRepository(ctx.ctx, p)
4577
+ );
4578
+ }
4579
+ /** Creates a repository. */
4580
+ createRepository(params) {
4581
+ return this.dispatch(
4582
+ "createRepository",
4583
+ "repos.create",
4584
+ params,
4585
+ validateCreateRepository,
4586
+ (p, ctx) => ctx.adapter.createRepository(ctx.ctx, p)
4587
+ );
4588
+ }
4589
+ /** Reads one file's content. Directory paths are rejected by the adapters. */
4590
+ getFileContents(params) {
4591
+ return this.dispatch(
4592
+ "getFileContents",
4593
+ "repos.getFileContents",
4594
+ params,
4595
+ validateGetFileContents,
4596
+ (p, ctx) => ctx.adapter.getFileContents(ctx.ctx, p)
4597
+ );
4598
+ }
4599
+ /* ---------------------------------------------------------------------- */
4600
+ /* Files */
4601
+ /* ---------------------------------------------------------------------- */
4602
+ /**
4603
+ * Creates or replaces one file.
4604
+ *
4605
+ * `sha` selects the endpoint: absent means create, present means update. The
4606
+ * capability gate follows that choice so a provider that served one but not
4607
+ * the other would still be blocked correctly.
4608
+ */
4609
+ createOrUpdateFile(params) {
4610
+ return this.dispatch(
4611
+ "createOrUpdateFile",
4612
+ (p) => p.sha === void 0 ? "files.create" : "files.update",
4613
+ params,
4614
+ validateCreateOrUpdateFile,
4615
+ (p, ctx) => p.sha === void 0 ? ctx.adapter.createFile(ctx.ctx, p) : ctx.adapter.updateFile(ctx.ctx, p)
4616
+ );
4617
+ }
4618
+ /** Deletes one file. */
4619
+ deleteFile(params) {
4620
+ return this.dispatch(
4621
+ "deleteFile",
4622
+ "files.delete",
4623
+ params,
4624
+ validateDeleteFile,
4625
+ (p, ctx) => ctx.adapter.deleteFile(ctx.ctx, p)
4626
+ );
4627
+ }
4628
+ /**
4629
+ * Commits every entry of a batch in one commit.
4630
+ *
4631
+ * AtomGit cannot do this and is refused by the capability gate; the batch is
4632
+ * never split into N single-file commits.
4633
+ */
4634
+ pushFiles(params) {
4635
+ return this.dispatch(
4636
+ "pushFiles",
4637
+ "files.pushFiles",
4638
+ params,
4639
+ validatePushFiles,
4640
+ (p, ctx) => ctx.adapter.pushFiles(ctx.ctx, p)
4641
+ );
4642
+ }
4643
+ /* ---------------------------------------------------------------------- */
4644
+ /* Branch / Commit */
4645
+ /* ---------------------------------------------------------------------- */
4646
+ /** Lists branches. */
4647
+ listBranches(params) {
4648
+ return this.dispatch(
4649
+ "listBranches",
4650
+ "branches.list",
4651
+ params,
4652
+ (p) => {
4653
+ assertRepoRef(p);
4654
+ assertMaxPages(p.maxPages);
4655
+ },
4656
+ (p, ctx) => ctx.adapter.listBranches(ctx.ctx, p)
4657
+ );
4658
+ }
4659
+ /** Creates a branch from a branch name or commit sha. */
4660
+ createBranch(params) {
4661
+ return this.dispatch(
4662
+ "createBranch",
4663
+ "branches.create",
4664
+ params,
4665
+ validateCreateBranch,
4666
+ (p, ctx) => ctx.adapter.createBranch(ctx.ctx, p)
4667
+ );
4668
+ }
4669
+ /** Lists commits. */
4670
+ listCommits(params) {
4671
+ return this.dispatch(
4672
+ "listCommits",
4673
+ "commits.list",
4674
+ params,
4675
+ validateListCommits,
4676
+ (p, ctx) => ctx.adapter.listCommits(ctx.ctx, p)
4677
+ );
4678
+ }
4679
+ /** Reads one commit. */
4680
+ getCommit(params) {
4681
+ return this.dispatch(
4682
+ "getCommit",
4683
+ "commits.get",
4684
+ params,
4685
+ validateGetCommit,
4686
+ (p, ctx) => ctx.adapter.getCommit(ctx.ctx, p)
4687
+ );
4688
+ }
4689
+ /* ---------------------------------------------------------------------- */
4690
+ /* Bulk */
4691
+ /* ---------------------------------------------------------------------- */
4692
+ /**
4693
+ * Runs a task per item with partial-failure isolation.
4694
+ *
4695
+ * Delegates to `core/bulk.ts` so the batching semantics (bounded concurrency,
4696
+ * `{ok, index}` results, never rejecting) are identical to the standalone
4697
+ * helper.
4698
+ */
4699
+ bulk(items, run, options) {
4700
+ return bulk(items, run, options);
4701
+ }
4702
+ /* ---------------------------------------------------------------------- */
4703
+ /* Internals */
4704
+ /* ---------------------------------------------------------------------- */
4705
+ /** Builds the per-provider bundle consumed by every method. */
4706
+ resolve(provider, options) {
4707
+ const credentials = options[provider] ?? {};
4708
+ const defaults = DEFAULT_ENDPOINTS[provider];
4709
+ assertEndpoint(provider, "baseUrl", credentials.baseUrl);
4710
+ assertEndpoint(provider, "webBaseUrl", credentials.webBaseUrl);
4711
+ const baseUrl = trimSlash(credentials.baseUrl ?? defaults.api);
4712
+ const webBaseUrl = trimSlash(credentials.webBaseUrl ?? defaults.web);
4713
+ const token = credentials.token !== void 0 && credentials.token.length > 0 ? credentials.token : void 0;
4714
+ const http = new HttpClient({
4715
+ baseUrl,
4716
+ provider,
4717
+ // All provider tokens travel in the Authorization header.
4718
+ auth: { style: "bearer" },
4719
+ token,
4720
+ fetch: options.fetch,
4721
+ sleep: options.sleep,
4722
+ random: options.random,
4723
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
4724
+ retry: options.retry,
4725
+ userAgent: options.userAgent ?? DEFAULT_USER_AGENT
4726
+ });
4727
+ const adapter = getAdapter(provider);
4728
+ return {
4729
+ provider,
4730
+ adapter,
4731
+ tokenEnvVar: TOKEN_ENV_VARS[provider],
4732
+ hasToken: http.hasToken,
4733
+ ctx: {
4734
+ http,
4735
+ caps: adapter.capabilities,
4736
+ paramCaps: adapter.paramCapabilities,
4737
+ webBaseUrl
4738
+ }
4739
+ };
4740
+ }
4741
+ /** Throws unless a parameter-level capability is supported. */
4742
+ assertParamCapability(ctx, capability) {
4743
+ if (ctx.ctx.paramCaps[capability] !== "supported") {
4744
+ throw unsupportedCapabilityError(ctx.provider, capability);
4745
+ }
4746
+ }
4747
+ /**
4748
+ * Runs the five gates in order, then dispatches to the adapter.
4749
+ *
4750
+ * `async` on purpose: a gate failure must reject the returned promise rather
4751
+ * than throw synchronously, so `await`/`.catch()` behave identically for a
4752
+ * refused call and for a failed request.
4753
+ *
4754
+ * @param method Method name, used in validation and read-only messages.
4755
+ * @param capabilityFor Method-level capability, or a selector evaluated after validation.
4756
+ * @param params Caller payload; `provider` is read from it.
4757
+ * @param validate Parameter validator, run before any other gate.
4758
+ * @param run Adapter call, reached only when every gate passes.
4759
+ * @param paramGate Optional parameter-level capability check.
4760
+ */
4761
+ async dispatch(method, capabilityFor, params, validate, run, paramGate) {
4762
+ assertParamsObject(params, method);
4763
+ assertProvider(params.provider);
4764
+ try {
4765
+ validate(params);
4766
+ } catch (error) {
4767
+ throw withProvider(error, params.provider);
4768
+ }
4769
+ const capability = typeof capabilityFor === "function" ? capabilityFor(params) : capabilityFor;
4770
+ const ctx = this.providers[params.provider];
4771
+ if (this.readonly && isWriteCapability(capability)) {
4772
+ throw readonlyBlockedError(params.provider, capability, method);
4773
+ }
4774
+ if (!ctx.hasToken) {
4775
+ throw authMissingError(params.provider, ctx.tokenEnvVar);
4776
+ }
4777
+ if (ctx.adapter.capabilities[capability] !== "supported") {
4778
+ throw unsupportedCapabilityError(params.provider, capability);
4779
+ }
4780
+ paramGate?.(params, ctx);
4781
+ return run(params, ctx);
4782
+ }
4783
+ };
4784
+ function withProvider(error, provider) {
4785
+ if (error instanceof GitForgeError && error.provider === void 0) {
4786
+ return new GitForgeError({
4787
+ code: error.code,
4788
+ message: error.message,
4789
+ provider,
4790
+ status: error.status,
4791
+ requestId: error.requestId,
4792
+ capability: error.capability,
4793
+ retryable: error.retryable,
4794
+ cause: error.cause
4795
+ });
4796
+ }
4797
+ return error;
4798
+ }
4799
+
4800
+ // src/index.ts
4801
+ var VERSION = "0.1.0";
4802
+
4803
+ exports.CAPABILITY_IDS = CAPABILITY_IDS;
4804
+ exports.DEFAULT_BULK_CONCURRENCY = DEFAULT_BULK_CONCURRENCY;
4805
+ exports.DEFAULT_MAX_PAGES = DEFAULT_MAX_PAGES;
4806
+ exports.DEFAULT_PER_PAGE = DEFAULT_PER_PAGE;
4807
+ exports.DEFAULT_RETRY_POLICY = DEFAULT_RETRY_POLICY;
4808
+ exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
4809
+ exports.DEFAULT_USER_AGENT = DEFAULT_USER_AGENT;
4810
+ exports.ERROR_CODES = ERROR_CODES;
4811
+ exports.GitClient = GitClient;
4812
+ exports.GitForgeError = GitForgeError;
4813
+ exports.HttpClient = HttpClient;
4814
+ exports.MAX_PAGES_LIMIT = MAX_PAGES_LIMIT;
4815
+ exports.MAX_PER_PAGE = MAX_PER_PAGE;
4816
+ exports.PARAM_CAPABILITY_IDS = PARAM_CAPABILITY_IDS;
4817
+ exports.PROVIDERS = PROVIDERS;
4818
+ exports.REDACTED = REDACTED;
4819
+ exports.VERSION = VERSION;
4820
+ exports.WRITE_CAPABILITIES = WRITE_CAPABILITIES;
4821
+ exports.allSucceeded = allSucceeded;
4822
+ exports.assertCapabilityTableKeys = assertCapabilityTableKeys;
4823
+ exports.assertFilePath = assertFilePath;
4824
+ exports.assertMaxPages = assertMaxPages;
4825
+ exports.assertNativeId = assertNativeId;
4826
+ exports.assertNonEmpty = assertNonEmpty;
4827
+ exports.assertNonEmptyStringArray = assertNonEmptyStringArray;
4828
+ exports.assertOneOf = assertOneOf;
4829
+ exports.assertOptionalFilePath = assertOptionalFilePath;
4830
+ exports.assertOptionalNonEmpty = assertOptionalNonEmpty;
4831
+ exports.assertOptionalPositiveInt = assertOptionalPositiveInt;
4832
+ exports.assertParamsObject = assertParamsObject;
4833
+ exports.assertPathSegment = assertPathSegment;
4834
+ exports.assertPositiveInt = assertPositiveInt;
4835
+ exports.assertProvider = assertProvider;
4836
+ exports.assertRepoRef = assertRepoRef;
4837
+ exports.assertStringArray = assertStringArray;
4838
+ exports.authMissingError = authMissingError;
4839
+ exports.bulk = bulk;
4840
+ exports.collectPages = collectPages;
4841
+ exports.computeDelay = computeDelay;
4842
+ exports.dedupeBy = dedupeBy;
4843
+ exports.defaultRetryable = defaultRetryable;
4844
+ exports.errorFromNetwork = errorFromNetwork;
4845
+ exports.errorFromResponse = errorFromResponse;
4846
+ exports.extractRequestId = extractRequestId;
4847
+ exports.extractUpstreamMessage = extractUpstreamMessage;
4848
+ exports.invalidArgumentError = invalidArgumentError;
4849
+ exports.isGitForgeError = isGitForgeError;
4850
+ exports.isIdempotentMethod = isIdempotentMethod;
4851
+ exports.isRateLimitResponse = isRateLimitResponse;
4852
+ exports.isRetryableStatus = isRetryableStatus;
4853
+ exports.isSensitiveKey = isSensitiveKey;
4854
+ exports.isWriteCapability = isWriteCapability;
4855
+ exports.mapStatusToCode = mapStatusToCode;
4856
+ exports.normalizeMaxPages = normalizeMaxPages;
4857
+ exports.normalizePerPage = normalizePerPage;
4858
+ exports.parseLinkHeader = parseLinkHeader;
4859
+ exports.parseRetryAfter = parseRetryAfter;
4860
+ exports.partitionBulk = partitionBulk;
4861
+ exports.readTotalCount = readTotalCount;
4862
+ exports.readTotalPage = readTotalPage;
4863
+ exports.readonlyBlockedError = readonlyBlockedError;
4864
+ exports.redactUrl = redactUrl;
4865
+ exports.resolveNextPage = resolveNextPage;
4866
+ exports.resolveRetryPolicy = resolveRetryPolicy;
4867
+ exports.retryAfterFromHeaders = retryAfterFromHeaders;
4868
+ exports.retryableForStatus = retryableForStatus;
4869
+ exports.scrubSecrets = scrubSecrets;
4870
+ exports.shouldRetry = shouldRetry;
4871
+ exports.unsupportedCapabilityError = unsupportedCapabilityError;
4872
+ //# sourceMappingURL=index.cjs.map
4873
+ //# sourceMappingURL=index.cjs.map