dsh-devdock 0.0.0-stage → 2.0.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/CHANGELOG.md +166 -0
- package/CONTRACT.md +519 -0
- package/LICENSE +21 -0
- package/PUBLISHING.md +175 -0
- package/README.md +244 -2
- package/assets/devdock-256.png +0 -0
- package/assets/devdock-32.png +0 -0
- package/assets/devdock-512.png +0 -0
- package/assets/devdock-64.png +0 -0
- package/client.js +11242 -0
- package/cordis.patch.yml +7 -0
- package/icon.svg +6 -0
- package/index.js +95 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +180 -4
- package/src/host/git.js +1664 -0
- package/src/host/github.js +1922 -0
- package/src/host/index.js +3969 -0
- package/src/host/npm.js +424 -0
- package/src/host/npmcli.js +283 -0
- package/src/host/review.js +627 -0
- package/src/host/store.js +874 -0
|
@@ -0,0 +1,1922 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-push — GitHub REST client.
|
|
3
|
+
*
|
|
4
|
+
* WHY `node:https` AND NOT `fetch`/undici: this Host runs inside the DSH
|
|
5
|
+
* profile process, where `fetch` is undici's implementation. On the machine
|
|
6
|
+
* this plugin was written on, undici's TLS stack refuses GitHub with a
|
|
7
|
+
* certificate error while nothing else about the network is broken — a
|
|
8
|
+
* difference that is invisible to the user and impossible to work around from
|
|
9
|
+
* inside the plugin. Plain `node:https` gives control of the socket, a real
|
|
10
|
+
* timeout (AbortSignal on the request) and the exact error code, which is what
|
|
11
|
+
* makes the NETWORK error message actionable instead of a generic failure.
|
|
12
|
+
*
|
|
13
|
+
* EVERY request carries a hard timeout. A background HTTP server must never
|
|
14
|
+
* hold a browser request open on a dead socket, so the default is 15 s and the
|
|
15
|
+
* abort surfaces as `NETWORK` with a Chinese message naming the TLS/proxy
|
|
16
|
+
* cause and pointing at the `gitPath` setting when that is the likely culprit.
|
|
17
|
+
*
|
|
18
|
+
* @module src/host/github.js
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { request as httpsRequest } from 'node:https';
|
|
22
|
+
import { request as httpRequest } from 'node:http';
|
|
23
|
+
|
|
24
|
+
/** Default ceiling for one GitHub API call (CONTRACT-independent; the browser
|
|
25
|
+
* gives up long before a dead socket would). */
|
|
26
|
+
export const DEFAULT_TIMEOUT_MS = 15_000;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The REST base URL.
|
|
30
|
+
*
|
|
31
|
+
* Read from the environment so a test can point the whole client at a local
|
|
32
|
+
* server and exercise the real request path (status codes, headers, body
|
|
33
|
+
* decoding) instead of stubbing the transport. Unset in production, where it
|
|
34
|
+
* is exactly the public API.
|
|
35
|
+
*/
|
|
36
|
+
const API_BASE = process.env.DSH_PUSH_API_BASE || 'https://api.github.com';
|
|
37
|
+
/** GraphQL has its own endpoint; the REST helpers below never reach it. */
|
|
38
|
+
const GRAPHQL_URL = `${API_BASE}/graphql`;
|
|
39
|
+
const WEB_ORIGIN = 'https://github.com';
|
|
40
|
+
const ACCEPT_JSON = 'application/vnd.github+json';
|
|
41
|
+
const API_VERSION = '2022-11-28';
|
|
42
|
+
/** GitHub rejects requests without a User-Agent; this one also tells GitHub's
|
|
43
|
+
* abuse detection which software is calling. */
|
|
44
|
+
const USER_AGENT = 'dsh-push (+https://github.com/)';
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* One GitHub failure, already translated into the CONTRACT §0 vocabulary.
|
|
48
|
+
*
|
|
49
|
+
* `status` is GitHub's own HTTP status when one exists — the client shows it
|
|
50
|
+
* to help the user distinguish "wrong token" from "repository gone".
|
|
51
|
+
*/
|
|
52
|
+
export class GithubError extends Error {
|
|
53
|
+
/**
|
|
54
|
+
* @param {string} code FORBIDDEN|BAD_REQUEST|NOT_FOUND|NO_ACCOUNT|
|
|
55
|
+
* UNAUTHORIZED|RATE_LIMITED|NETWORK|INTERNAL.
|
|
56
|
+
* @param {string} message human-readable Chinese message.
|
|
57
|
+
* @param {{status?: number, cause?: unknown}} [details]
|
|
58
|
+
*/
|
|
59
|
+
constructor(code, message, details = {}) {
|
|
60
|
+
super(message, details.cause === undefined ? undefined : { cause: details.cause });
|
|
61
|
+
this.name = 'GithubError';
|
|
62
|
+
this.code = code;
|
|
63
|
+
if (typeof details.status === 'number') this.status = details.status;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Translate a low-level socket error into the NETWORK code with a message a
|
|
69
|
+
* Chinese-speaking user can act on.
|
|
70
|
+
*
|
|
71
|
+
* The message must name the actual cause because there is no way for the panel
|
|
72
|
+
* to distinguish "offline" from "corporate TLS interception" from "the
|
|
73
|
+
* connection timed out" — the user fixes all three differently.
|
|
74
|
+
*
|
|
75
|
+
* @param {NodeJS.ErrnoException|Error} error
|
|
76
|
+
* @param {string} target the URL or host that failed.
|
|
77
|
+
* @param {number} timeoutMs
|
|
78
|
+
* @returns {GithubError}
|
|
79
|
+
*/
|
|
80
|
+
function networkError(error, target, timeoutMs) {
|
|
81
|
+
const code = String(error?.code ?? '');
|
|
82
|
+
const name = String(error?.name ?? '');
|
|
83
|
+
const timedOut = name === 'AbortError' || code === 'ABORT_ERR' || name === 'TimeoutError';
|
|
84
|
+
if (timedOut) {
|
|
85
|
+
return new GithubError(
|
|
86
|
+
'NETWORK',
|
|
87
|
+
`连接 GitHub 超时(${Math.round(timeoutMs / 1000)} 秒):${target}。`
|
|
88
|
+
+ '请检查网络或代理设置;如果只是本机 TLS 证书被拦截,可在插件设置里改用可用代理,或改用可用的 git(设置项「git 路径」)。',
|
|
89
|
+
{ cause: error },
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
const tls = /CERT|TLS|SSL|SELF_SIGNED|UNABLE_TO_VERIFY|EPROTO|ERR_TLS/i.test(`${code} ${error?.message ?? ''}`);
|
|
93
|
+
const dns = code === 'ENOTFOUND' || code === 'EAI_AGAIN' || code === 'EAI_FAIL';
|
|
94
|
+
const refused = code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'EHOSTUNREACH' || code === 'ETIMEDOUT';
|
|
95
|
+
let hint;
|
|
96
|
+
if (tls) {
|
|
97
|
+
hint = '本机 TLS/证书校验未能通过 GitHub 的证书(常见于系统时间错误、企业代理或杀毒软件拦截)。'
|
|
98
|
+
+ '请修复证书/代理,或改用可用的 git(设置项「git 路径」)。';
|
|
99
|
+
} else if (dns) {
|
|
100
|
+
hint = 'DNS 解析失败,请检查网络连接或代理配置。';
|
|
101
|
+
} else if (refused) {
|
|
102
|
+
hint = '网络连接被拒绝或中断,请检查网络、代理或防火墙。';
|
|
103
|
+
} else {
|
|
104
|
+
hint = '请检查网络连接、代理设置和系统时间。';
|
|
105
|
+
}
|
|
106
|
+
return new GithubError(
|
|
107
|
+
'NETWORK',
|
|
108
|
+
`无法连接 GitHub:${target}(${code || '网络错误'})。${hint}`,
|
|
109
|
+
{ cause: error },
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Send one HTTPS request and resolve with the status, headers and a decoded
|
|
115
|
+
* body.
|
|
116
|
+
*
|
|
117
|
+
* The body is decoded as JSON when the content type says so and as text
|
|
118
|
+
* otherwise; GitHub's device-flow endpoints answer `application/json` when
|
|
119
|
+
* asked, but a text fallback keeps a proxy's HTML error page readable.
|
|
120
|
+
*
|
|
121
|
+
* @param {object} options
|
|
122
|
+
* @param {'GET'|'POST'|'DELETE'|'PATCH'} options.method
|
|
123
|
+
* @param {string} options.url absolute https URL.
|
|
124
|
+
* @param {string} [options.token] bearer token.
|
|
125
|
+
* @param {object} [options.body] JSON body.
|
|
126
|
+
* @param {Record<string,string>} [options.headers]
|
|
127
|
+
* @param {number} [options.timeoutMs]
|
|
128
|
+
* @returns {Promise<{status: number, headers: object, json: any, text: string}>}
|
|
129
|
+
*/
|
|
130
|
+
function request(options) {
|
|
131
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) ? Number(options.timeoutMs) : DEFAULT_TIMEOUT_MS;
|
|
132
|
+
const headers = {
|
|
133
|
+
'user-agent': USER_AGENT,
|
|
134
|
+
accept: ACCEPT_JSON,
|
|
135
|
+
'x-github-api-version': API_VERSION,
|
|
136
|
+
...(options.headers ?? {}),
|
|
137
|
+
};
|
|
138
|
+
if (typeof options.token === 'string' && options.token !== '') {
|
|
139
|
+
headers.authorization = `Bearer ${options.token}`;
|
|
140
|
+
}
|
|
141
|
+
let payload;
|
|
142
|
+
if (options.rawBody !== undefined) {
|
|
143
|
+
// Release-asset uploads send the file bytes verbatim with their own content
|
|
144
|
+
// type (set by the caller). Wrapping them in JSON would corrupt the upload,
|
|
145
|
+
// which is why this branch exists separately from `body`.
|
|
146
|
+
payload = Buffer.isBuffer(options.rawBody) ? options.rawBody : Buffer.from(options.rawBody);
|
|
147
|
+
headers['content-length'] = String(payload.length);
|
|
148
|
+
} else if (options.body !== undefined) {
|
|
149
|
+
payload = Buffer.from(JSON.stringify(options.body), 'utf8');
|
|
150
|
+
headers['content-type'] = 'application/json; charset=utf-8';
|
|
151
|
+
headers['content-length'] = String(payload.length);
|
|
152
|
+
}
|
|
153
|
+
return new Promise((resolvePromise, reject) => {
|
|
154
|
+
const controller = new AbortController();
|
|
155
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
156
|
+
let settled = false;
|
|
157
|
+
const done = (fn, value) => {
|
|
158
|
+
if (settled) return;
|
|
159
|
+
settled = true;
|
|
160
|
+
clearTimeout(timer);
|
|
161
|
+
fn(value);
|
|
162
|
+
};
|
|
163
|
+
let req;
|
|
164
|
+
try {
|
|
165
|
+
// Pick the transport from the URL scheme. In production every URL is
|
|
166
|
+
// https, so this is always `httpsRequest`; the http branch exists so a
|
|
167
|
+
// test can run the REAL request path against a local plain-HTTP server
|
|
168
|
+
// instead of stubbing the transport (see tests/verify-delete-semantics).
|
|
169
|
+
const transport = String(options.url).startsWith('http://') ? httpRequest : httpsRequest;
|
|
170
|
+
req = transport(options.url, { method: options.method, headers, signal: controller.signal }, (res) => {
|
|
171
|
+
const chunks = [];
|
|
172
|
+
res.on('data', (chunk) => chunks.push(chunk));
|
|
173
|
+
res.on('end', () => {
|
|
174
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
175
|
+
const contentType = String(res.headers['content-type'] ?? '');
|
|
176
|
+
let json;
|
|
177
|
+
if (text !== '' && /json/i.test(contentType)) {
|
|
178
|
+
try {
|
|
179
|
+
json = JSON.parse(text);
|
|
180
|
+
} catch {
|
|
181
|
+
json = undefined;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
done(resolvePromise, {
|
|
185
|
+
status: typeof res.statusCode === 'number' ? res.statusCode : 0,
|
|
186
|
+
headers: res.headers,
|
|
187
|
+
json,
|
|
188
|
+
text,
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
res.on('error', (error) => done(reject, networkError(error, options.url, timeoutMs)));
|
|
192
|
+
});
|
|
193
|
+
} catch (error) {
|
|
194
|
+
clearTimeout(timer);
|
|
195
|
+
reject(networkError(error, options.url, timeoutMs));
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
req.on('error', (error) => done(reject, networkError(error, options.url, timeoutMs)));
|
|
199
|
+
if (payload !== undefined) req.write(payload);
|
|
200
|
+
req.end();
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Raise the contract-shaped error for one failed GitHub response.
|
|
206
|
+
*
|
|
207
|
+
* @param {{status: number, headers: object, json: any, text: string}} response
|
|
208
|
+
* @param {string} action Chinese description of what was being attempted.
|
|
209
|
+
* @returns {GithubError}
|
|
210
|
+
*/
|
|
211
|
+
function responseError(response, action) {
|
|
212
|
+
const detail = typeof response.json?.message === 'string'
|
|
213
|
+
? response.json.message
|
|
214
|
+
: response.text.slice(0, 300);
|
|
215
|
+
const status = response.status;
|
|
216
|
+
// GitHub signals throttling as 403 + `x-ratelimit-remaining: 0`, or 429.
|
|
217
|
+
const remaining = response.headers['x-ratelimit-remaining'];
|
|
218
|
+
if (status === 429 || (status === 403 && String(remaining) === '0')) {
|
|
219
|
+
const reset = Number(response.headers['x-ratelimit-reset']);
|
|
220
|
+
const when = Number.isFinite(reset) && reset > 0
|
|
221
|
+
? new Date(reset * 1000).toLocaleString('zh-CN')
|
|
222
|
+
: '稍后';
|
|
223
|
+
return new GithubError('RATE_LIMITED', `GitHub API 触发速率限制,请在 ${when} 之后重试。`, { status });
|
|
224
|
+
}
|
|
225
|
+
if (status === 401) {
|
|
226
|
+
return new GithubError(
|
|
227
|
+
'UNAUTHORIZED',
|
|
228
|
+
`GitHub 令牌已失效或无权限(${action}):${detail || '请重新登录该账号'}。`,
|
|
229
|
+
{ status },
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
if (status === 404) {
|
|
233
|
+
return new GithubError('NOT_FOUND', `GitHub 上找不到对应资源(${action}):${detail || '仓库或分支可能已被删除'}。`, { status });
|
|
234
|
+
}
|
|
235
|
+
if (status === 403) {
|
|
236
|
+
return new GithubError(
|
|
237
|
+
'UNAUTHORIZED',
|
|
238
|
+
`GitHub 拒绝了该操作(${action}):${detail || '当前账号缺少所需权限范围(scope)'}。`,
|
|
239
|
+
{ status },
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
if (status === 422) {
|
|
243
|
+
return new GithubError('BAD_REQUEST', `GitHub 拒绝了该请求(${action}):${detail || '参数不合法'}。`, { status });
|
|
244
|
+
}
|
|
245
|
+
if (status >= 400 && status < 500) {
|
|
246
|
+
return new GithubError('BAD_REQUEST', `GitHub 请求失败(${action},HTTP ${status}):${detail}`, { status });
|
|
247
|
+
}
|
|
248
|
+
return new GithubError(
|
|
249
|
+
'NETWORK',
|
|
250
|
+
`GitHub 服务异常(HTTP ${status},${action}):${detail || '请稍后重试'}。`,
|
|
251
|
+
{ status },
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* One authenticated GitHub API call, with 401/403/429/5xx translated.
|
|
257
|
+
*
|
|
258
|
+
* @param {object} options see {@link request}; `action` names the operation in
|
|
259
|
+
* the Chinese error message.
|
|
260
|
+
* @returns {Promise<{json: any, headers: object, status: number}>}
|
|
261
|
+
*/
|
|
262
|
+
async function api(options) {
|
|
263
|
+
const response = await request(options);
|
|
264
|
+
if (response.status < 200 || response.status >= 300) {
|
|
265
|
+
throw responseError(response, options.action ?? '调用 GitHub API');
|
|
266
|
+
}
|
|
267
|
+
return { json: response.json, headers: response.headers, status: response.status };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Read the scopes GitHub reports for the token in use.
|
|
272
|
+
*
|
|
273
|
+
* `x-oauth-scopes` is a comma-separated list; fine-grained tokens send no
|
|
274
|
+
* header at all, which is why the contract allows an empty array.
|
|
275
|
+
*
|
|
276
|
+
* @param {object} headers
|
|
277
|
+
* @returns {string[]}
|
|
278
|
+
*/
|
|
279
|
+
export function parseScopes(headers) {
|
|
280
|
+
const raw = headers?.['x-oauth-scopes'];
|
|
281
|
+
if (typeof raw !== 'string' || raw.trim() === '') return [];
|
|
282
|
+
return raw.split(',').map((scope) => scope.trim()).filter(Boolean);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Validate a personal access token and return the account it belongs to.
|
|
287
|
+
*
|
|
288
|
+
* This is the ONLY place a token is proven good before it is stored, so the
|
|
289
|
+
* `addedAt`/identity fields are read here rather than trusting client input.
|
|
290
|
+
*
|
|
291
|
+
* @param {string} token
|
|
292
|
+
* @param {{timeoutMs?: number}} [options]
|
|
293
|
+
* @returns {Promise<{login: string, name: string|null, avatarUrl: string|null,
|
|
294
|
+
* htmlUrl: string|null, scopes: string[], id: number|null}>}
|
|
295
|
+
* @throws {GithubError} UNAUTHORIZED for a bad token, NETWORK for no network.
|
|
296
|
+
*/
|
|
297
|
+
export async function verifyToken(token, options = {}) {
|
|
298
|
+
const value = typeof token === 'string' ? token.trim() : '';
|
|
299
|
+
if (value === '') throw new GithubError('BAD_REQUEST', '请输入 GitHub 令牌');
|
|
300
|
+
const { json, headers } = await api({
|
|
301
|
+
method: 'GET',
|
|
302
|
+
url: `${API_BASE}/user`,
|
|
303
|
+
token: value,
|
|
304
|
+
timeoutMs: options.timeoutMs,
|
|
305
|
+
action: '校验令牌',
|
|
306
|
+
});
|
|
307
|
+
if (!json || typeof json.login !== 'string') {
|
|
308
|
+
throw new GithubError('UNAUTHORIZED', 'GitHub 未返回有效的用户信息,请确认令牌是否正确。');
|
|
309
|
+
}
|
|
310
|
+
return {
|
|
311
|
+
login: json.login,
|
|
312
|
+
name: typeof json.name === 'string' ? json.name : null,
|
|
313
|
+
avatarUrl: typeof json.avatar_url === 'string' ? json.avatar_url : null,
|
|
314
|
+
htmlUrl: typeof json.html_url === 'string' ? json.html_url : null,
|
|
315
|
+
scopes: parseScopes(headers),
|
|
316
|
+
id: typeof json.id === 'number' ? json.id : null,
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Map one GitHub repository payload onto the contract's `RemoteRepo`.
|
|
322
|
+
* @param {any} raw
|
|
323
|
+
* @returns {object}
|
|
324
|
+
*/
|
|
325
|
+
export function mapRepo(raw) {
|
|
326
|
+
const repo = raw ?? {};
|
|
327
|
+
const owner = repo.owner ?? {};
|
|
328
|
+
return {
|
|
329
|
+
id: String(repo.id ?? ''),
|
|
330
|
+
owner: String(owner.login ?? ''),
|
|
331
|
+
name: String(repo.name ?? ''),
|
|
332
|
+
fullName: String(repo.full_name ?? ''),
|
|
333
|
+
private: repo.private === true,
|
|
334
|
+
fork: repo.fork === true,
|
|
335
|
+
archived: repo.archived === true,
|
|
336
|
+
defaultBranch: String(repo.default_branch ?? ''),
|
|
337
|
+
description: typeof repo.description === 'string' ? repo.description : null,
|
|
338
|
+
updatedAt: String(repo.updated_at ?? ''),
|
|
339
|
+
pushedAt: typeof repo.pushed_at === 'string' ? repo.pushed_at : null,
|
|
340
|
+
htmlUrl: String(repo.html_url ?? ''),
|
|
341
|
+
cloneUrl: String(repo.clone_url ?? ''),
|
|
342
|
+
sshUrl: String(repo.ssh_url ?? ''),
|
|
343
|
+
permissions: repo.permissions
|
|
344
|
+
? {
|
|
345
|
+
admin: repo.permissions.admin === true,
|
|
346
|
+
push: repo.permissions.push === true,
|
|
347
|
+
pull: repo.permissions.pull === true,
|
|
348
|
+
}
|
|
349
|
+
: null,
|
|
350
|
+
language: typeof repo.language === 'string' ? repo.language : null,
|
|
351
|
+
stars: Number(repo.stargazers_count ?? 0),
|
|
352
|
+
// Forks are shown beside stars on the cards and in the list; omitting the
|
|
353
|
+
// field made every repository read as "0 forks".
|
|
354
|
+
forks: Number(repo.forks_count ?? 0),
|
|
355
|
+
openIssues: Number(repo.open_issues_count ?? 0),
|
|
356
|
+
ownerAvatar: typeof owner.avatar_url === 'string' ? owner.avatar_url : null,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** The `per_page` the plugin asks for; the client pages by 30 to match. */
|
|
361
|
+
const PER_PAGE = 50;
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* List the authenticated user's repositories (CONTRACT §2 `GET /repos`).
|
|
365
|
+
*
|
|
366
|
+
* `hasMore` is derived from GitHub's `Link` header when present and otherwise
|
|
367
|
+
* from a full page — GitHub stops sending Link on the last page, so a short
|
|
368
|
+
* page is the reliable "no more" signal.
|
|
369
|
+
*
|
|
370
|
+
* @param {object} options
|
|
371
|
+
* @param {string} options.token
|
|
372
|
+
* @param {number} [options.page]
|
|
373
|
+
* @param {string} [options.affiliation]
|
|
374
|
+
* @param {string} [options.sort]
|
|
375
|
+
* @param {number} [options.timeoutMs]
|
|
376
|
+
* @returns {Promise<{items: object[], page: number, hasMore: boolean, total?: number}>}
|
|
377
|
+
*/
|
|
378
|
+
export async function listRepos(options) {
|
|
379
|
+
const page = Number.isFinite(options.page) && options.page >= 1 ? Math.trunc(options.page) : 1;
|
|
380
|
+
const affiliation = typeof options.affiliation === 'string' && options.affiliation !== ''
|
|
381
|
+
? options.affiliation
|
|
382
|
+
: 'owner,collaborator,organization_member';
|
|
383
|
+
const sort = typeof options.sort === 'string' && options.sort !== '' ? options.sort : 'updated';
|
|
384
|
+
const { json, headers } = await api({
|
|
385
|
+
method: 'GET',
|
|
386
|
+
url: `${API_BASE}/user/repos?per_page=${PER_PAGE}&page=${page}`
|
|
387
|
+
+ `&affiliation=${encodeURIComponent(affiliation)}&sort=${encodeURIComponent(sort)}`,
|
|
388
|
+
token: options.token,
|
|
389
|
+
timeoutMs: options.timeoutMs,
|
|
390
|
+
action: '读取仓库列表',
|
|
391
|
+
});
|
|
392
|
+
const items = Array.isArray(json) ? json.map(mapRepo) : [];
|
|
393
|
+
const link = String(headers?.link ?? '');
|
|
394
|
+
const hasMore = link !== '' ? /rel="next"/.test(link) : items.length >= PER_PAGE;
|
|
395
|
+
return { items, page, hasMore };
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Search the authenticated user's repositories (CONTRACT §2: `q` non-empty).
|
|
400
|
+
*
|
|
401
|
+
* The query is narrowed with `user:<login>` and (for a multi-word query) the
|
|
402
|
+
* words are ANDed, which is GitHub's own `in:name,description` behaviour once
|
|
403
|
+
* the user qualifier is present.
|
|
404
|
+
*
|
|
405
|
+
* @param {object} options
|
|
406
|
+
* @param {string} options.token
|
|
407
|
+
* @param {string} options.login the authenticated login (search qualifier).
|
|
408
|
+
* @param {string} options.q
|
|
409
|
+
* @param {number} [options.page]
|
|
410
|
+
* @param {number} [options.timeoutMs]
|
|
411
|
+
* @returns {Promise<{items: object[], page: number, hasMore: boolean, total?: number}>}
|
|
412
|
+
*/
|
|
413
|
+
export async function searchRepos(options) {
|
|
414
|
+
const q = String(options.q ?? '').trim();
|
|
415
|
+
if (q === '') return { items: [], page: 1, hasMore: false, total: 0 };
|
|
416
|
+
const page = Number.isFinite(options.page) && options.page >= 1 ? Math.trunc(options.page) : 1;
|
|
417
|
+
const query = `user:${options.login} ${q}`;
|
|
418
|
+
const { json } = await api({
|
|
419
|
+
method: 'GET',
|
|
420
|
+
url: `${API_BASE}/search/repositories?q=${encodeURIComponent(query)}&per_page=${PER_PAGE}&page=${page}`,
|
|
421
|
+
token: options.token,
|
|
422
|
+
timeoutMs: options.timeoutMs,
|
|
423
|
+
action: '搜索仓库',
|
|
424
|
+
});
|
|
425
|
+
const items = Array.isArray(json?.items) ? json.items.map(mapRepo) : [];
|
|
426
|
+
return {
|
|
427
|
+
items,
|
|
428
|
+
page,
|
|
429
|
+
// Search caps at 1000 results; `total_count` is the honest number.
|
|
430
|
+
hasMore: items.length >= PER_PAGE,
|
|
431
|
+
total: Number(json?.total_count ?? items.length),
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* One repository plus its branches (CONTRACT §2 `GET /repos/detail`).
|
|
437
|
+
*
|
|
438
|
+
* @param {object} options
|
|
439
|
+
* @param {string} options.token
|
|
440
|
+
* @param {string} options.owner
|
|
441
|
+
* @param {string} options.name
|
|
442
|
+
* @param {number} [options.timeoutMs]
|
|
443
|
+
* @returns {Promise<{repo: object, branches: object[]}>}
|
|
444
|
+
*/
|
|
445
|
+
export async function repoDetail(options) {
|
|
446
|
+
const owner = String(options.owner ?? '').trim();
|
|
447
|
+
const name = String(options.name ?? '').trim();
|
|
448
|
+
if (owner === '' || name === '') throw new GithubError('BAD_REQUEST', '缺少仓库的 owner 或名称');
|
|
449
|
+
const [repo, branches] = await Promise.all([
|
|
450
|
+
api({
|
|
451
|
+
method: 'GET',
|
|
452
|
+
url: `${API_BASE}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`,
|
|
453
|
+
token: options.token,
|
|
454
|
+
timeoutMs: options.timeoutMs,
|
|
455
|
+
action: '读取仓库详情',
|
|
456
|
+
}),
|
|
457
|
+
api({
|
|
458
|
+
method: 'GET',
|
|
459
|
+
url: `${API_BASE}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/branches?per_page=100`,
|
|
460
|
+
token: options.token,
|
|
461
|
+
timeoutMs: options.timeoutMs,
|
|
462
|
+
action: '读取分支列表',
|
|
463
|
+
}),
|
|
464
|
+
]);
|
|
465
|
+
const rows = Array.isArray(branches.json) ? branches.json : [];
|
|
466
|
+
return {
|
|
467
|
+
repo: mapRepo(repo.json),
|
|
468
|
+
branches: rows.map((branch) => ({
|
|
469
|
+
name: String(branch?.name ?? ''),
|
|
470
|
+
sha: String(branch?.commit?.sha ?? ''),
|
|
471
|
+
protected: branch?.protected === true,
|
|
472
|
+
})),
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Create a repository.
|
|
478
|
+
*
|
|
479
|
+
* `owner` selects the namespace: omitted (or the authenticated login) creates
|
|
480
|
+
* under the user, anything else goes through the organization endpoint, which
|
|
481
|
+
* is where the contract's optional `owner` field leads. A permission failure on
|
|
482
|
+
* the org path is reported as-is — GitHub's message names the missing role.
|
|
483
|
+
*
|
|
484
|
+
* @param {object} options
|
|
485
|
+
* @param {string} options.token
|
|
486
|
+
* @param {string} options.name
|
|
487
|
+
* @param {string} [options.owner] organization login (or the user's own).
|
|
488
|
+
* @param {string} [options.login] the authenticated login (for the comparison).
|
|
489
|
+
* @param {boolean} [options.private]
|
|
490
|
+
* @param {string} [options.description]
|
|
491
|
+
* @param {boolean} [options.autoInit]
|
|
492
|
+
* @param {number} [options.timeoutMs]
|
|
493
|
+
* @returns {Promise<{repo: object}>}
|
|
494
|
+
*/
|
|
495
|
+
export async function createRepo(options) {
|
|
496
|
+
const name = String(options.name ?? '').trim();
|
|
497
|
+
if (name === '') throw new GithubError('BAD_REQUEST', '仓库名称不能为空');
|
|
498
|
+
const owner = String(options.owner ?? '').trim();
|
|
499
|
+
const login = String(options.login ?? '').trim();
|
|
500
|
+
const underOrg = owner !== '' && (login === '' || owner.toLowerCase() !== login.toLowerCase());
|
|
501
|
+
const { json } = await api({
|
|
502
|
+
method: 'POST',
|
|
503
|
+
url: underOrg ? `${API_BASE}/orgs/${encodeURIComponent(owner)}/repos` : `${API_BASE}/user/repos`,
|
|
504
|
+
token: options.token,
|
|
505
|
+
timeoutMs: options.timeoutMs,
|
|
506
|
+
action: '新建仓库',
|
|
507
|
+
body: {
|
|
508
|
+
name,
|
|
509
|
+
private: options.private !== false,
|
|
510
|
+
description: typeof options.description === 'string' ? options.description : '',
|
|
511
|
+
auto_init: options.autoInit === true,
|
|
512
|
+
},
|
|
513
|
+
});
|
|
514
|
+
return { repo: mapRepo(json) };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* Delete a repository.
|
|
519
|
+
*
|
|
520
|
+
* GitHub requires the `delete_repo` scope, which PATs almost never carry — so
|
|
521
|
+
* a 403 here is translated into the specific instruction instead of a bare
|
|
522
|
+
* permission error.
|
|
523
|
+
*
|
|
524
|
+
* @param {object} options
|
|
525
|
+
* @param {string} options.token
|
|
526
|
+
* @param {string} options.owner
|
|
527
|
+
* @param {string} options.name
|
|
528
|
+
* @param {number} [options.timeoutMs]
|
|
529
|
+
* @returns {Promise<{deleted: true}>}
|
|
530
|
+
*/
|
|
531
|
+
export async function deleteRepo(options) {
|
|
532
|
+
const owner = String(options.owner ?? '').trim();
|
|
533
|
+
const name = String(options.name ?? '').trim();
|
|
534
|
+
if (owner === '' || name === '') throw new GithubError('BAD_REQUEST', '缺少仓库的 owner 或名称');
|
|
535
|
+
const response = await request({
|
|
536
|
+
method: 'DELETE',
|
|
537
|
+
url: `${API_BASE}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`,
|
|
538
|
+
token: options.token,
|
|
539
|
+
timeoutMs: options.timeoutMs,
|
|
540
|
+
});
|
|
541
|
+
// 204 No Content is the only real success shape.
|
|
542
|
+
if (response.status === 204 || response.status === 200) return { deleted: true };
|
|
543
|
+
// A 404 is AMBIGUOUS and must not be reported as success on its own. GitHub
|
|
544
|
+
// answers 404 both for "already gone" and for "you cannot see this repo at
|
|
545
|
+
// all" (wrong owner, a token without `repo`, a typo, or a repo that never
|
|
546
|
+
// existed). The old code returned `{deleted:true}` here, so deleting a
|
|
547
|
+
// repository that did not exist — or one the token cannot reach — reported a
|
|
548
|
+
// clean success and told the user their repository was gone. Ask instead
|
|
549
|
+
// whether the repo is readable now: readable + 404 from DELETE means the
|
|
550
|
+
// delete genuinely had nothing left to do; unreadable means it never
|
|
551
|
+
// resolved, and the caller must see a real failure.
|
|
552
|
+
if (response.status === 404) {
|
|
553
|
+
const readable = await repoExists({
|
|
554
|
+
token: options.token, owner, name, timeoutMs: options.timeoutMs,
|
|
555
|
+
});
|
|
556
|
+
if (readable) return { deleted: true };
|
|
557
|
+
throw new GithubError(
|
|
558
|
+
'NOT_FOUND',
|
|
559
|
+
`找不到仓库 ${owner}/${name}:它可能从未存在、已被改名或转移,或当前令牌无权访问。`
|
|
560
|
+
+ '(读取需要 repo 权限范围,删除还需要 delete_repo。)',
|
|
561
|
+
{ status: 404 },
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
if (response.status === 403 || response.status === 401) {
|
|
565
|
+
throw new GithubError(
|
|
566
|
+
'UNAUTHORIZED',
|
|
567
|
+
'删除仓库需要令牌具备 delete_repo 权限范围(scope)。请重新生成带 delete_repo 的经典令牌,或直接在 GitHub 网页上删除。',
|
|
568
|
+
{ status: response.status },
|
|
569
|
+
);
|
|
570
|
+
}
|
|
571
|
+
throw responseError(response, '删除仓库');
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Whether the authenticated token can currently see one repository.
|
|
576
|
+
*
|
|
577
|
+
* Used to disambiguate a 404 from a DELETE: GitHub hides inaccessible repos
|
|
578
|
+
* behind the same status as absent ones. A network failure propagates (it is
|
|
579
|
+
* evidence neither way); only a definite 200/404 decides. 403/401 means the
|
|
580
|
+
* token cannot reach it, which is the same end state as "not visible".
|
|
581
|
+
*
|
|
582
|
+
* @param {{token: string, owner: string, name: string, timeoutMs?: number}} options
|
|
583
|
+
* @returns {Promise<boolean>}
|
|
584
|
+
*/
|
|
585
|
+
async function repoExists(options) {
|
|
586
|
+
const owner = String(options.owner ?? '').trim();
|
|
587
|
+
const name = String(options.name ?? '').trim();
|
|
588
|
+
const response = await request({
|
|
589
|
+
method: 'GET',
|
|
590
|
+
url: `${API_BASE}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`,
|
|
591
|
+
token: options.token,
|
|
592
|
+
timeoutMs: options.timeoutMs,
|
|
593
|
+
});
|
|
594
|
+
if (response.status === 200) return true;
|
|
595
|
+
if (response.status === 404) return false;
|
|
596
|
+
if (response.status === 403 || response.status === 401) return false;
|
|
597
|
+
throw responseError(response, '检查仓库是否存在');
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* List releases for one repository (newest first, as GitHub returns them).
|
|
602
|
+
* @param {object} options
|
|
603
|
+
* @param {string} options.token
|
|
604
|
+
* @param {string} options.owner
|
|
605
|
+
* @param {string} options.repo
|
|
606
|
+
* @param {number} [options.timeoutMs]
|
|
607
|
+
* @returns {Promise<{items: object[]}>}
|
|
608
|
+
*/
|
|
609
|
+
export async function listReleases(options) {
|
|
610
|
+
const owner = String(options.owner ?? '').trim();
|
|
611
|
+
const repo = String(options.repo ?? '').trim();
|
|
612
|
+
if (owner === '' || repo === '') throw new GithubError('BAD_REQUEST', '缺少仓库的 owner 或名称');
|
|
613
|
+
const { json } = await api({
|
|
614
|
+
method: 'GET',
|
|
615
|
+
url: `${API_BASE}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/releases?per_page=50`,
|
|
616
|
+
token: options.token,
|
|
617
|
+
timeoutMs: options.timeoutMs,
|
|
618
|
+
action: '读取 release 列表',
|
|
619
|
+
});
|
|
620
|
+
const rows = Array.isArray(json) ? json : [];
|
|
621
|
+
return { items: rows.map(mapRelease) };
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* Map one GitHub release payload onto the contract's `Release`.
|
|
626
|
+
* @param {any} raw
|
|
627
|
+
* @returns {object}
|
|
628
|
+
*/
|
|
629
|
+
export function mapRelease(raw) {
|
|
630
|
+
const release = raw ?? {};
|
|
631
|
+
return {
|
|
632
|
+
id: String(release.id ?? ''),
|
|
633
|
+
tagName: String(release.tag_name ?? ''),
|
|
634
|
+
name: typeof release.name === 'string' ? release.name : null,
|
|
635
|
+
draft: release.draft === true,
|
|
636
|
+
prerelease: release.prerelease === true,
|
|
637
|
+
createdAt: String(release.created_at ?? ''),
|
|
638
|
+
htmlUrl: String(release.html_url ?? ''),
|
|
639
|
+
// Assets ride along in the release payload. They are mapped here so the
|
|
640
|
+
// panel can LIST what it uploaded and offer to remove it — without this
|
|
641
|
+
// an upload was a one-way door.
|
|
642
|
+
assets: Array.isArray(release.assets)
|
|
643
|
+
? release.assets.map((asset) => ({
|
|
644
|
+
id: String(asset.id ?? ''),
|
|
645
|
+
name: String(asset.name ?? ''),
|
|
646
|
+
size: Number(asset.size ?? 0),
|
|
647
|
+
downloadUrl: typeof asset.browser_download_url === 'string' ? asset.browser_download_url : '',
|
|
648
|
+
}))
|
|
649
|
+
: [],
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* Create a release.
|
|
655
|
+
* @param {object} options
|
|
656
|
+
* @param {string} options.token
|
|
657
|
+
* @param {string} options.owner
|
|
658
|
+
* @param {string} options.repo
|
|
659
|
+
* @param {string} options.tagName
|
|
660
|
+
* @param {string} [options.name]
|
|
661
|
+
* @param {string} [options.body]
|
|
662
|
+
* @param {string} [options.target] commitish for a not-yet-existing tag.
|
|
663
|
+
* @param {boolean} [options.draft]
|
|
664
|
+
* @param {boolean} [options.prerelease]
|
|
665
|
+
* @param {number} [options.timeoutMs]
|
|
666
|
+
* @returns {Promise<{release: object}>}
|
|
667
|
+
*/
|
|
668
|
+
export async function createRelease(options) {
|
|
669
|
+
const owner = String(options.owner ?? '').trim();
|
|
670
|
+
const repo = String(options.repo ?? '').trim();
|
|
671
|
+
const tagName = String(options.tagName ?? '').trim();
|
|
672
|
+
if (owner === '' || repo === '') throw new GithubError('BAD_REQUEST', '缺少仓库的 owner 或名称');
|
|
673
|
+
if (tagName === '') throw new GithubError('BAD_REQUEST', '缺少标签名');
|
|
674
|
+
const body = {
|
|
675
|
+
tag_name: tagName,
|
|
676
|
+
draft: options.draft === true,
|
|
677
|
+
prerelease: options.prerelease === true,
|
|
678
|
+
};
|
|
679
|
+
if (typeof options.name === 'string' && options.name !== '') body.name = options.name;
|
|
680
|
+
if (typeof options.body === 'string' && options.body !== '') body.body = options.body;
|
|
681
|
+
if (typeof options.target === 'string' && options.target !== '') body.target_commitish = options.target;
|
|
682
|
+
const { json } = await api({
|
|
683
|
+
method: 'POST',
|
|
684
|
+
url: `${API_BASE}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/releases`,
|
|
685
|
+
token: options.token,
|
|
686
|
+
timeoutMs: options.timeoutMs,
|
|
687
|
+
action: '创建 release',
|
|
688
|
+
body,
|
|
689
|
+
});
|
|
690
|
+
return { release: mapRelease(json) };
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/* ------------------------------------------------------------------ */
|
|
694
|
+
/* Contribution calendar (GraphQL) + notifications (REST) */
|
|
695
|
+
/* ------------------------------------------------------------------ */
|
|
696
|
+
|
|
697
|
+
/** The one GraphQL document this plugin needs (CONTRACT §2 `GET /contributions`). */
|
|
698
|
+
const CONTRIBUTIONS_QUERY = `query($login: String!, $from: DateTime!, $to: DateTime!) {
|
|
699
|
+
user(login: $login) {
|
|
700
|
+
contributionsCollection(from: $from, to: $to) {
|
|
701
|
+
contributionCalendar {
|
|
702
|
+
totalContributions
|
|
703
|
+
weeks { contributionDays { date contributionCount weekday } }
|
|
704
|
+
}
|
|
705
|
+
restrictedContributionsCount
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}`;
|
|
709
|
+
|
|
710
|
+
/** Shown inline by the panel when the token simply cannot read contributions. */
|
|
711
|
+
const CONTRIBUTIONS_SCOPE_MESSAGE = '贡献图需要令牌具备 read:user 权限;当前令牌没有该权限。';
|
|
712
|
+
|
|
713
|
+
/** The `data` document for a token that is missing `read:user`. */
|
|
714
|
+
function scopeUnavailable() {
|
|
715
|
+
return { unavailable: true, reason: 'SCOPE', message: CONTRIBUTIONS_SCOPE_MESSAGE };
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* Flatten the calendar's `weeks[].contributionDays[]` into one array sorted by
|
|
720
|
+
* date ascending (CONTRACT §2 `GET /contributions`).
|
|
721
|
+
*
|
|
722
|
+
* The client renders a seven-column grid from this array, so the ORDER is the
|
|
723
|
+
* API: weeks arrive newest-last but a day grid needs plain chronological days,
|
|
724
|
+
* and a malformed week must not poison the rest of the calendar.
|
|
725
|
+
*
|
|
726
|
+
* @param {any} weeks
|
|
727
|
+
* @returns {{date: string, count: number, weekday: number}[]}
|
|
728
|
+
*/
|
|
729
|
+
export function flattenContributionDays(weeks) {
|
|
730
|
+
const rows = Array.isArray(weeks) ? weeks : [];
|
|
731
|
+
const days = [];
|
|
732
|
+
for (const week of rows) {
|
|
733
|
+
const list = Array.isArray(week?.contributionDays) ? week.contributionDays : [];
|
|
734
|
+
for (const day of list) {
|
|
735
|
+
const date = String(day?.date ?? '');
|
|
736
|
+
if (date === '') continue;
|
|
737
|
+
days.push({
|
|
738
|
+
date,
|
|
739
|
+
count: Number(day?.contributionCount ?? 0),
|
|
740
|
+
weekday: Number(day?.weekday ?? 0),
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
days.sort((left, right) => (left.date < right.date ? -1 : left.date > right.date ? 1 : 0));
|
|
745
|
+
return days;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/** GraphQL `errors[]` → one readable Chinese-message fragment. */
|
|
749
|
+
function graphqlErrorText(errors) {
|
|
750
|
+
const text = (Array.isArray(errors) ? errors : [])
|
|
751
|
+
.map((error) => String(error?.message ?? '').trim())
|
|
752
|
+
.filter(Boolean)
|
|
753
|
+
.join(';');
|
|
754
|
+
return text === '' ? '未知错误' : text;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* Does this failure mean "the token lacks the scope", rather than anything else?
|
|
759
|
+
*
|
|
760
|
+
* GraphQL answers a missing `read:user` either as HTTP 200 with `errors[]` or as
|
|
761
|
+
* a bare 401/403. Both are recoverable from the panel's point of view (it shows
|
|
762
|
+
* an inline notice), which is why they must be distinguishable from a genuine
|
|
763
|
+
* network/rate-limit failure.
|
|
764
|
+
*
|
|
765
|
+
* @param {number} status
|
|
766
|
+
* @param {any} errors
|
|
767
|
+
* @param {string} message
|
|
768
|
+
* @returns {boolean}
|
|
769
|
+
*/
|
|
770
|
+
function isScopeFailure(status, errors, message) {
|
|
771
|
+
const types = (Array.isArray(errors) ? errors : []).map((error) => String(error?.type ?? ''));
|
|
772
|
+
if (types.includes('INSUFFICIENT_SCOPES')) return true;
|
|
773
|
+
const text = String(message ?? '');
|
|
774
|
+
if (/resource not accessible by/i.test(text)) return true;
|
|
775
|
+
if (/required scopes?/i.test(text)) return true;
|
|
776
|
+
if (/not been granted/i.test(text)) return true;
|
|
777
|
+
if (/insufficient (?:scope|permission)/i.test(text)) return true;
|
|
778
|
+
// A 401/403 without a rate-limit header is GitHub refusing this token, and for
|
|
779
|
+
// the GraphQL endpoint that is nearly always the missing-scope case.
|
|
780
|
+
return status === 401 || status === 403;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
/**
|
|
784
|
+
* One authenticated GraphQL call, reusing {@link request}'s timeout/abort and
|
|
785
|
+
* error machinery. Scope failures are TAGGED (`error.scope = true`) instead of
|
|
786
|
+
* being turned into a different error class, so the caller decides whether they
|
|
787
|
+
* become a hard failure or the panel's inline notice.
|
|
788
|
+
*
|
|
789
|
+
* @param {object} options
|
|
790
|
+
* @param {string} options.token
|
|
791
|
+
* @param {string} options.query GraphQL document.
|
|
792
|
+
* @param {Record<string, any>} [options.variables]
|
|
793
|
+
* @param {string} [options.action] Chinese description for error messages.
|
|
794
|
+
* @param {number} [options.timeoutMs]
|
|
795
|
+
* @returns {Promise<{json: any, status: number, headers: object}>}
|
|
796
|
+
*/
|
|
797
|
+
async function githubGraphql(options) {
|
|
798
|
+
const action = options.action ?? '调用 GitHub GraphQL API';
|
|
799
|
+
const response = await request({
|
|
800
|
+
method: 'POST',
|
|
801
|
+
url: GRAPHQL_URL,
|
|
802
|
+
token: options.token,
|
|
803
|
+
timeoutMs: options.timeoutMs,
|
|
804
|
+
body: { query: options.query, variables: options.variables ?? {} },
|
|
805
|
+
});
|
|
806
|
+
if (response.status < 200 || response.status >= 300) {
|
|
807
|
+
const mapped = responseError(response, action);
|
|
808
|
+
const detail = typeof response.json?.message === 'string'
|
|
809
|
+
? response.json.message
|
|
810
|
+
: response.text.slice(0, 300);
|
|
811
|
+
// A rate-limited 403 is not a scope problem: it must stay RATE_LIMITED so the
|
|
812
|
+
// panel can say "wait until …" instead of "your token lacks read:user".
|
|
813
|
+
if (mapped.code !== 'RATE_LIMITED' && isScopeFailure(response.status, response.json?.errors, detail)) {
|
|
814
|
+
mapped.scope = true;
|
|
815
|
+
}
|
|
816
|
+
throw mapped;
|
|
817
|
+
}
|
|
818
|
+
const json = response.json;
|
|
819
|
+
if (json === undefined || json === null || typeof json !== 'object') {
|
|
820
|
+
throw new GithubError(
|
|
821
|
+
'NETWORK',
|
|
822
|
+
`GitHub GraphQL 返回了无法识别的响应(${action}):${response.text.slice(0, 200) || '空响应'}。`,
|
|
823
|
+
{ status: response.status },
|
|
824
|
+
);
|
|
825
|
+
}
|
|
826
|
+
const errors = Array.isArray(json.errors) ? json.errors : [];
|
|
827
|
+
if (errors.length > 0) {
|
|
828
|
+
const detail = graphqlErrorText(errors);
|
|
829
|
+
if (isScopeFailure(response.status, errors, detail)) {
|
|
830
|
+
const error = new GithubError(
|
|
831
|
+
'UNAUTHORIZED',
|
|
832
|
+
`GitHub 拒绝了 GraphQL 查询(${action}):${detail}。`,
|
|
833
|
+
{ status: response.status },
|
|
834
|
+
);
|
|
835
|
+
error.scope = true;
|
|
836
|
+
throw error;
|
|
837
|
+
}
|
|
838
|
+
const types = errors.map((error) => String(error?.type ?? ''));
|
|
839
|
+
if (types.includes('NOT_FOUND')) {
|
|
840
|
+
throw new GithubError('NOT_FOUND', `GitHub 上找不到对应资源(${action}):${detail}。`, { status: response.status });
|
|
841
|
+
}
|
|
842
|
+
throw new GithubError('BAD_REQUEST', `GitHub GraphQL 查询失败(${action}):${detail}。`, { status: response.status });
|
|
843
|
+
}
|
|
844
|
+
if (json.data === undefined || json.data === null) {
|
|
845
|
+
throw new GithubError('NETWORK', `GitHub GraphQL 没有返回数据(${action}),请稍后重试。`, { status: response.status });
|
|
846
|
+
}
|
|
847
|
+
return { json: json.data, status: response.status, headers: response.headers };
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* Read one user's contribution calendar (CONTRACT §2 `GET /contributions`).
|
|
852
|
+
*
|
|
853
|
+
* A token without `read:user` is NOT an error here: the panel is expected to
|
|
854
|
+
* render an inline notice while the rest of the page keeps working, so the
|
|
855
|
+
* resolved value says `unavailable: true` instead of throwing.
|
|
856
|
+
*
|
|
857
|
+
* @param {object} options
|
|
858
|
+
* @param {string} options.token
|
|
859
|
+
* @param {string} options.login GitHub login (defaults handled by the caller).
|
|
860
|
+
* @param {number} [options.days] window length in days, 1–365.
|
|
861
|
+
* @param {number} [options.timeoutMs]
|
|
862
|
+
* @returns {Promise<object>}
|
|
863
|
+
*/
|
|
864
|
+
export async function contributions(options) {
|
|
865
|
+
const login = String(options.login ?? '').trim();
|
|
866
|
+
if (login === '') throw new GithubError('BAD_REQUEST', '缺少 GitHub 用户名');
|
|
867
|
+
const windowDays = Number.isFinite(options.days) && options.days >= 1
|
|
868
|
+
? Math.min(365, Math.trunc(options.days))
|
|
869
|
+
: 365;
|
|
870
|
+
const toDate = new Date();
|
|
871
|
+
// Both bounds are full timestamps, as the `DateTime!` variables require; the
|
|
872
|
+
// calendar itself snaps to whole days.
|
|
873
|
+
const from = new Date(toDate.getTime() - windowDays * 86_400_000).toISOString();
|
|
874
|
+
const to = toDate.toISOString();
|
|
875
|
+
|
|
876
|
+
let payload;
|
|
877
|
+
try {
|
|
878
|
+
const result = await githubGraphql({
|
|
879
|
+
token: options.token,
|
|
880
|
+
query: CONTRIBUTIONS_QUERY,
|
|
881
|
+
variables: { login, from, to },
|
|
882
|
+
timeoutMs: options.timeoutMs,
|
|
883
|
+
action: '读取贡献图',
|
|
884
|
+
});
|
|
885
|
+
payload = result.json;
|
|
886
|
+
} catch (error) {
|
|
887
|
+
if (error?.scope === true) return scopeUnavailable();
|
|
888
|
+
throw error;
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
const collection = payload?.user?.contributionsCollection;
|
|
892
|
+
const calendar = collection?.contributionCalendar;
|
|
893
|
+
if (!calendar) {
|
|
894
|
+
throw new GithubError(
|
|
895
|
+
'NOT_FOUND',
|
|
896
|
+
`找不到 GitHub 用户 ${login} 的贡献数据,请确认用户名是否正确。`,
|
|
897
|
+
{ status: 200 },
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
const weeks = Array.isArray(calendar.weeks) ? calendar.weeks : [];
|
|
901
|
+
return {
|
|
902
|
+
total: Number(calendar.totalContributions ?? 0),
|
|
903
|
+
days: flattenContributionDays(weeks),
|
|
904
|
+
weeks: weeks.length,
|
|
905
|
+
restricted: Number(collection.restrictedContributionsCount ?? 0),
|
|
906
|
+
login: String(payload?.user?.login ?? login),
|
|
907
|
+
from,
|
|
908
|
+
to,
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/** API resource segment → the web path that renders it. */
|
|
913
|
+
const NOTIFICATION_WEB_PATH = Object.freeze({
|
|
914
|
+
pulls: '/pull',
|
|
915
|
+
issues: '/issues',
|
|
916
|
+
commits: '/commit',
|
|
917
|
+
discussions: '/discussions',
|
|
918
|
+
});
|
|
919
|
+
|
|
920
|
+
/**
|
|
921
|
+
* Convert a notification's API `subject.url` to the web URL the panel opens.
|
|
922
|
+
*
|
|
923
|
+
* The REST notification payload only carries the API URL
|
|
924
|
+
* (`https://api.github.com/repos/{owner}/{repo}/{kind}/{id}`), and the mapping is
|
|
925
|
+
* NOT a plain suffix swap: `pulls/{n}` becomes `/pull/{n}`, `commits/{sha}`
|
|
926
|
+
* becomes `/commit/{sha}`, and a release has no per-id page at all.
|
|
927
|
+
*
|
|
928
|
+
* @param {string} subjectUrl
|
|
929
|
+
* @param {string} [fallbackRepo] `owner/name`, used when the URL is unusable.
|
|
930
|
+
* @returns {string}
|
|
931
|
+
*/
|
|
932
|
+
export function notificationHtmlUrl(subjectUrl, fallbackRepo = '') {
|
|
933
|
+
let segments = [];
|
|
934
|
+
try {
|
|
935
|
+
segments = new URL(String(subjectUrl ?? '')).pathname.split('/').filter(Boolean);
|
|
936
|
+
} catch {
|
|
937
|
+
segments = [];
|
|
938
|
+
}
|
|
939
|
+
// /repos/{owner}/{repo}/{kind}/{id}
|
|
940
|
+
if (segments.length >= 4 && segments[0] === 'repos') {
|
|
941
|
+
const owner = segments[1];
|
|
942
|
+
const repo = segments[2];
|
|
943
|
+
const kind = segments[3];
|
|
944
|
+
const id = segments[4];
|
|
945
|
+
const base = `${WEB_ORIGIN}/${owner}/${repo}`;
|
|
946
|
+
if (kind === 'releases') return `${base}/releases`;
|
|
947
|
+
const suffix = NOTIFICATION_WEB_PATH[kind];
|
|
948
|
+
if (suffix !== undefined && typeof id === 'string' && id !== '') return `${base}${suffix}/${id}`;
|
|
949
|
+
return base;
|
|
950
|
+
}
|
|
951
|
+
const fallback = String(fallbackRepo ?? '').trim();
|
|
952
|
+
return fallback === '' ? WEB_ORIGIN : `${WEB_ORIGIN}/${fallback}`;
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
/**
|
|
956
|
+
* Map one GitHub notification payload onto the contract's notification object.
|
|
957
|
+
*
|
|
958
|
+
* GitHub puts the repository on the notification root; the CONTRACT §2 wording
|
|
959
|
+
* names `subject.repository`, so both positions are accepted and the web URL
|
|
960
|
+
* falls back to the repository when `subject.url` is unusable.
|
|
961
|
+
*
|
|
962
|
+
* @param {any} raw
|
|
963
|
+
* @returns {object}
|
|
964
|
+
*/
|
|
965
|
+
export function mapNotification(raw) {
|
|
966
|
+
const row = raw ?? {};
|
|
967
|
+
const subject = row.subject ?? {};
|
|
968
|
+
const repo = typeof subject.repository?.full_name === 'string'
|
|
969
|
+
? subject.repository.full_name
|
|
970
|
+
: (typeof row.repository?.full_name === 'string' ? row.repository.full_name : '');
|
|
971
|
+
return {
|
|
972
|
+
id: String(row.id ?? ''),
|
|
973
|
+
title: String(subject.title ?? ''),
|
|
974
|
+
type: String(subject.type ?? ''),
|
|
975
|
+
repo,
|
|
976
|
+
reason: String(row.reason ?? ''),
|
|
977
|
+
unread: row.unread === true,
|
|
978
|
+
updatedAt: String(row.updated_at ?? ''),
|
|
979
|
+
url: notificationHtmlUrl(subject.url, repo),
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
/**
|
|
984
|
+
* List notifications (CONTRACT §2 `GET /notifications`).
|
|
985
|
+
*
|
|
986
|
+
* GitHub caps `per_page` at 50; `unreadCount` is scoped to THIS page on purpose
|
|
987
|
+
* (the panel shows "N unread in the list you are looking at", not a global
|
|
988
|
+
* counter that a paged view could never reconcile).
|
|
989
|
+
*
|
|
990
|
+
* @param {object} options
|
|
991
|
+
* @param {string} options.token
|
|
992
|
+
* @param {boolean} [options.all] `true` includes already-read threads.
|
|
993
|
+
* @param {number} [options.limit] 1–50, default 30.
|
|
994
|
+
* @param {number} [options.timeoutMs]
|
|
995
|
+
* @returns {Promise<{items: object[], unreadCount: number}>}
|
|
996
|
+
*/
|
|
997
|
+
export async function listNotifications(options) {
|
|
998
|
+
const limit = Number.isFinite(options.limit)
|
|
999
|
+
? Math.min(50, Math.max(1, Math.trunc(options.limit)))
|
|
1000
|
+
: 30;
|
|
1001
|
+
const all = options.all === true;
|
|
1002
|
+
const { json } = await api({
|
|
1003
|
+
method: 'GET',
|
|
1004
|
+
url: `${API_BASE}/notifications?per_page=${limit}&all=${all ? 'true' : 'false'}`,
|
|
1005
|
+
token: options.token,
|
|
1006
|
+
timeoutMs: options.timeoutMs,
|
|
1007
|
+
action: '读取通知列表',
|
|
1008
|
+
});
|
|
1009
|
+
const items = Array.isArray(json) ? json.map(mapNotification) : [];
|
|
1010
|
+
return { items, unreadCount: items.filter((item) => item.unread === true).length };
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/**
|
|
1014
|
+
* Mark ONE notification thread read (CONTRACT §2 `POST /notifications/read`).
|
|
1015
|
+
*
|
|
1016
|
+
* GitHub answers PATCH with `205 Reset Content` and no body, so success is the
|
|
1017
|
+
* status range — there is nothing to parse and no envelope to unwrap.
|
|
1018
|
+
*
|
|
1019
|
+
* @param {object} options
|
|
1020
|
+
* @param {string} options.token
|
|
1021
|
+
* @param {string} options.id notification thread id.
|
|
1022
|
+
* @param {number} [options.timeoutMs]
|
|
1023
|
+
* @returns {Promise<{read: true}>}
|
|
1024
|
+
*/
|
|
1025
|
+
export async function markNotificationRead(options) {
|
|
1026
|
+
const id = String(options.id ?? '').trim();
|
|
1027
|
+
if (id === '') throw new GithubError('BAD_REQUEST', '缺少通知 id');
|
|
1028
|
+
const response = await request({
|
|
1029
|
+
method: 'PATCH',
|
|
1030
|
+
url: `${API_BASE}/notifications/threads/${encodeURIComponent(id)}`,
|
|
1031
|
+
token: options.token,
|
|
1032
|
+
timeoutMs: options.timeoutMs,
|
|
1033
|
+
});
|
|
1034
|
+
if (response.status >= 200 && response.status < 300) return { read: true };
|
|
1035
|
+
if (response.status === 404) {
|
|
1036
|
+
throw new GithubError('NOT_FOUND', `找不到这条通知(${id}),它可能已被删除。`, { status: 404 });
|
|
1037
|
+
}
|
|
1038
|
+
throw responseError(response, '标记通知已读');
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
/* ------------------------------------------------------------------ */
|
|
1042
|
+
/* Device flow (OAuth app sign-in) */
|
|
1043
|
+
/* ------------------------------------------------------------------ */
|
|
1044
|
+
|
|
1045
|
+
/**
|
|
1046
|
+
* Start the OAuth device flow.
|
|
1047
|
+
*
|
|
1048
|
+
* Device flow is the only sign-in that works without a redirect URL, which is
|
|
1049
|
+
* what a desktop plugin needs: the user types a short code on github.com and
|
|
1050
|
+
* the Host polls for the token.
|
|
1051
|
+
*
|
|
1052
|
+
* @param {object} options
|
|
1053
|
+
* @param {string} options.clientId the OAuth app's client id (settings).
|
|
1054
|
+
* @param {number} [options.timeoutMs]
|
|
1055
|
+
* @returns {Promise<{verificationUri: string, userCode: string,
|
|
1056
|
+
* deviceCode: string, expiresIn: number, interval: number}>}
|
|
1057
|
+
*/
|
|
1058
|
+
export async function startDeviceFlow(options) {
|
|
1059
|
+
const clientId = String(options.clientId ?? '').trim();
|
|
1060
|
+
if (clientId === '') {
|
|
1061
|
+
throw new GithubError('BAD_REQUEST', '未配置 oauthClientId:请先在设置里填入 GitHub OAuth 应用的 Client ID,或改用个人访问令牌登录。');
|
|
1062
|
+
}
|
|
1063
|
+
const response = await request({
|
|
1064
|
+
method: 'POST',
|
|
1065
|
+
url: `${WEB_ORIGIN}/login/device/code`,
|
|
1066
|
+
timeoutMs: options.timeoutMs,
|
|
1067
|
+
// These two endpoints want plain JSON, not the API's versioned media type.
|
|
1068
|
+
headers: { accept: 'application/json' },
|
|
1069
|
+
body: { client_id: clientId, scope: 'repo read:user' },
|
|
1070
|
+
});
|
|
1071
|
+
if (response.status >= 400 || !response.json) {
|
|
1072
|
+
throw responseError(response, '发起设备码登录');
|
|
1073
|
+
}
|
|
1074
|
+
const json = response.json;
|
|
1075
|
+
if (typeof json.device_code !== 'string' || typeof json.user_code !== 'string') {
|
|
1076
|
+
throw new GithubError('INTERNAL', `GitHub 设备码接口返回了无法识别的响应:${response.text.slice(0, 200)}`);
|
|
1077
|
+
}
|
|
1078
|
+
return {
|
|
1079
|
+
verificationUri: String(json.verification_uri ?? json.verification_url ?? 'https://github.com/login/device'),
|
|
1080
|
+
userCode: json.user_code,
|
|
1081
|
+
deviceCode: json.device_code,
|
|
1082
|
+
expiresIn: Number(json.expires_in ?? 900),
|
|
1083
|
+
interval: Number(json.interval ?? 5),
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/**
|
|
1088
|
+
* Poll the device flow once.
|
|
1089
|
+
*
|
|
1090
|
+
* Polling is the CLIENT's job (it owns the countdown and the interval), so this
|
|
1091
|
+
* function performs exactly one poll and reports the state honestly:
|
|
1092
|
+
* `pending` and `slow_down` are normal outcomes, not errors.
|
|
1093
|
+
*
|
|
1094
|
+
* @param {object} options
|
|
1095
|
+
* @param {string} options.clientId
|
|
1096
|
+
* @param {string} options.deviceCode
|
|
1097
|
+
* @param {number} [options.timeoutMs]
|
|
1098
|
+
* @returns {Promise<{status: 'pending'|'slow_down'|'done', token?: string}>}
|
|
1099
|
+
*/
|
|
1100
|
+
export async function pollDeviceFlow(options) {
|
|
1101
|
+
const clientId = String(options.clientId ?? '').trim();
|
|
1102
|
+
const deviceCode = String(options.deviceCode ?? '').trim();
|
|
1103
|
+
if (clientId === '') throw new GithubError('BAD_REQUEST', '未配置 oauthClientId');
|
|
1104
|
+
if (deviceCode === '') throw new GithubError('BAD_REQUEST', '缺少 deviceCode');
|
|
1105
|
+
const response = await request({
|
|
1106
|
+
method: 'POST',
|
|
1107
|
+
url: `${WEB_ORIGIN}/login/oauth/access_token`,
|
|
1108
|
+
timeoutMs: options.timeoutMs,
|
|
1109
|
+
headers: { accept: 'application/json' },
|
|
1110
|
+
body: {
|
|
1111
|
+
client_id: clientId,
|
|
1112
|
+
device_code: deviceCode,
|
|
1113
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
|
|
1114
|
+
},
|
|
1115
|
+
});
|
|
1116
|
+
const json = response.json;
|
|
1117
|
+
if (!json) {
|
|
1118
|
+
throw new GithubError('INTERNAL', `GitHub 设备码接口返回了无法识别的响应:${response.text.slice(0, 200)}`);
|
|
1119
|
+
}
|
|
1120
|
+
if (typeof json.access_token === 'string' && json.access_token !== '') {
|
|
1121
|
+
return { status: 'done', token: json.access_token };
|
|
1122
|
+
}
|
|
1123
|
+
const error = String(json.error ?? '');
|
|
1124
|
+
if (error === 'authorization_pending') return { status: 'pending' };
|
|
1125
|
+
if (error === 'slow_down') return { status: 'slow_down' };
|
|
1126
|
+
if (error === 'expired_token') {
|
|
1127
|
+
throw new GithubError('BAD_REQUEST', '设备码已过期,请重新发起登录。');
|
|
1128
|
+
}
|
|
1129
|
+
if (error === 'access_denied') {
|
|
1130
|
+
throw new GithubError('UNAUTHORIZED', '你已取消 GitHub 授权。');
|
|
1131
|
+
}
|
|
1132
|
+
if (error === 'incorrect_client_credentials') {
|
|
1133
|
+
throw new GithubError('BAD_REQUEST', 'oauthClientId 不正确:请核对 GitHub OAuth 应用的 Client ID。');
|
|
1134
|
+
}
|
|
1135
|
+
throw new GithubError('INTERNAL', `设备码轮询失败:${json.error_description ?? error ?? '未知错误'}`);
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
/**
|
|
1139
|
+
* The HTML URL of a repository, for "open in browser" actions.
|
|
1140
|
+
* @param {string} owner
|
|
1141
|
+
* @param {string} name
|
|
1142
|
+
* @returns {string}
|
|
1143
|
+
*/
|
|
1144
|
+
/**
|
|
1145
|
+
* Byte counts per language for one repository (CONTRACT 2, GET /repos/languages).
|
|
1146
|
+
*
|
|
1147
|
+
* GitHub returns a map of language to raw bytes, unordered. The panel draws a
|
|
1148
|
+
* proportion bar, so this normalizes to a sorted array with the percentage
|
|
1149
|
+
* already computed. Computing it here rather than in the client keeps two
|
|
1150
|
+
* surfaces from disagreeing.
|
|
1151
|
+
*
|
|
1152
|
+
* @param {object} options
|
|
1153
|
+
* @param {string} options.token
|
|
1154
|
+
* @param {string} options.owner
|
|
1155
|
+
* @param {string} options.name
|
|
1156
|
+
* @returns {Promise<{items: {name: string, bytes: number, percent: number}[]}>}
|
|
1157
|
+
*/
|
|
1158
|
+
export async function repoLanguages(options) {
|
|
1159
|
+
const owner = String(options.owner ?? '').trim();
|
|
1160
|
+
const name = String(options.name ?? '').trim();
|
|
1161
|
+
if (owner === '' || name === '') throw new GithubError('BAD_REQUEST', '缺少仓库的 owner 或名称');
|
|
1162
|
+
const response = await request({
|
|
1163
|
+
method: 'GET',
|
|
1164
|
+
url: API_BASE + '/repos/' + encodeURIComponent(owner) + '/' + encodeURIComponent(name) + '/languages',
|
|
1165
|
+
token: options.token,
|
|
1166
|
+
timeoutMs: options.timeoutMs,
|
|
1167
|
+
});
|
|
1168
|
+
if (response.status !== 200) {
|
|
1169
|
+
if (response.status === 404) return { items: [] };
|
|
1170
|
+
throw responseError(response, '读取语言构成');
|
|
1171
|
+
}
|
|
1172
|
+
const raw = response.json && typeof response.json === 'object' ? response.json : {};
|
|
1173
|
+
const entries = Object.entries(raw)
|
|
1174
|
+
.map(([language, bytes]) => ({ name: language, bytes: Number(bytes) || 0 }))
|
|
1175
|
+
.filter((entry) => entry.bytes > 0)
|
|
1176
|
+
.sort((a, b) => b.bytes - a.bytes);
|
|
1177
|
+
const total = entries.reduce((sum, entry) => sum + entry.bytes, 0);
|
|
1178
|
+
return {
|
|
1179
|
+
items: entries.map((entry) => ({
|
|
1180
|
+
name: entry.name,
|
|
1181
|
+
bytes: entry.bytes,
|
|
1182
|
+
// One decimal is enough for a bar; the client renders the same number it
|
|
1183
|
+
// was given, so rounding here is the single source of truth.
|
|
1184
|
+
percent: total > 0 ? Math.round((entry.bytes / total) * 1000) / 10 : 0,
|
|
1185
|
+
})),
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
/**
|
|
1190
|
+
* Upload one asset to an existing release (CONTRACT 2, POST /releases/asset).
|
|
1191
|
+
*
|
|
1192
|
+
* GitHub's upload endpoint is NOT on api.github.com: it is
|
|
1193
|
+
* uploads.github.com/repos/{owner}/{repo}/releases/{id}/assets?name=... with the
|
|
1194
|
+
* bytes as the raw request body and an explicit content type. Sending it to the
|
|
1195
|
+
* API host silently 404s, which is the classic mistake here, so the URL is
|
|
1196
|
+
* derived from API_BASE rather than written out twice.
|
|
1197
|
+
*
|
|
1198
|
+
* @param {object} options
|
|
1199
|
+
* @param {string} options.token
|
|
1200
|
+
* @param {string} options.owner
|
|
1201
|
+
* @param {string} options.name repository name.
|
|
1202
|
+
* @param {string|number} options.releaseId
|
|
1203
|
+
* @param {string} options.fileName
|
|
1204
|
+
* @param {Buffer} options.bytes
|
|
1205
|
+
* @param {string} [options.contentType]
|
|
1206
|
+
* @returns {Promise<{asset: object}>}
|
|
1207
|
+
*/
|
|
1208
|
+
export async function uploadReleaseAsset(options) {
|
|
1209
|
+
const owner = String(options.owner ?? '').trim();
|
|
1210
|
+
const name = String(options.name ?? '').trim();
|
|
1211
|
+
const releaseId = String(options.releaseId ?? '').trim();
|
|
1212
|
+
const fileName = String(options.fileName ?? '').trim();
|
|
1213
|
+
if (owner === '' || name === '' || releaseId === '') {
|
|
1214
|
+
throw new GithubError('BAD_REQUEST', '缺少仓库或发布 id');
|
|
1215
|
+
}
|
|
1216
|
+
if (fileName === '') throw new GithubError('BAD_REQUEST', '缺少文件名');
|
|
1217
|
+
const bytes = options.bytes;
|
|
1218
|
+
if (!bytes || typeof bytes.length !== 'number' || bytes.length === 0) {
|
|
1219
|
+
throw new GithubError('BAD_REQUEST', '文件内容为空');
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
// Derive the uploads host structurally. A literal string replace on
|
|
1223
|
+
// API_BASE only works for the production spelling; if the base is overridden
|
|
1224
|
+
// (tests, enterprise) the upload would silently go to the API host and 404.
|
|
1225
|
+
const uploadBase = (() => {
|
|
1226
|
+
try {
|
|
1227
|
+
const url = new URL(API_BASE);
|
|
1228
|
+
// api.github.com -> uploads.github.com; anything else keeps its host but
|
|
1229
|
+
// is still reported clearly if GitHub ever rejects it.
|
|
1230
|
+
url.hostname = url.hostname.replace(/^api\./, 'uploads.');
|
|
1231
|
+
return url.origin;
|
|
1232
|
+
} catch {
|
|
1233
|
+
return API_BASE;
|
|
1234
|
+
}
|
|
1235
|
+
})();
|
|
1236
|
+
const url = uploadBase + '/repos/' + encodeURIComponent(owner) + '/' + encodeURIComponent(name)
|
|
1237
|
+
+ '/releases/' + encodeURIComponent(releaseId) + '/assets?name=' + encodeURIComponent(fileName);
|
|
1238
|
+
|
|
1239
|
+
const response = await request({
|
|
1240
|
+
method: 'POST',
|
|
1241
|
+
url,
|
|
1242
|
+
token: options.token,
|
|
1243
|
+
timeoutMs: options.timeoutMs ?? 120000,
|
|
1244
|
+
headers: {
|
|
1245
|
+
// The generic JSON accept is wrong for an upload; ask for JSON back but
|
|
1246
|
+
// send raw bytes with their own type.
|
|
1247
|
+
'content-type': options.contentType || 'application/octet-stream',
|
|
1248
|
+
},
|
|
1249
|
+
rawBody: bytes,
|
|
1250
|
+
});
|
|
1251
|
+
if (response.status !== 201 && response.status !== 200) {
|
|
1252
|
+
throw responseError(response, '上传发布附件');
|
|
1253
|
+
}
|
|
1254
|
+
const asset = response.json ?? {};
|
|
1255
|
+
return {
|
|
1256
|
+
asset: {
|
|
1257
|
+
id: String(asset.id ?? ''),
|
|
1258
|
+
name: String(asset.name ?? fileName),
|
|
1259
|
+
size: Number(asset.size ?? bytes.length),
|
|
1260
|
+
downloadUrl: typeof asset.browser_download_url === 'string' ? asset.browser_download_url : '',
|
|
1261
|
+
},
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
|
|
1266
|
+
export function repoHtmlUrl(owner, name) {
|
|
1267
|
+
return `${WEB_ORIGIN}/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`;
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
/* ------------------------------------------------------------------ */
|
|
1271
|
+
/* Repository management (CONTRACT §3c) */
|
|
1272
|
+
/* ------------------------------------------------------------------ */
|
|
1273
|
+
|
|
1274
|
+
/** `{owner}/{name}` URL segment, encoded once. */
|
|
1275
|
+
function repoPath(owner, name) {
|
|
1276
|
+
const safeOwner = String(owner ?? '').trim();
|
|
1277
|
+
const safeName = String(name ?? '').trim();
|
|
1278
|
+
if (safeOwner === '' || safeName === '') throw new GithubError('BAD_REQUEST', '缺少仓库的 owner 或名称');
|
|
1279
|
+
return `${API_BASE}/repos/${encodeURIComponent(safeOwner)}/${encodeURIComponent(safeName)}`;
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
/**
|
|
1283
|
+
* Does this error mean "the token is missing a permission/scope"?
|
|
1284
|
+
*
|
|
1285
|
+
* TWO CASES MUST BE DISTINGUISHED for {@link managementFetch}: a 403/404 that
|
|
1286
|
+
* GitHub sends because the token cannot SEE a feature (webhooks without
|
|
1287
|
+
* `admin:repo_hook`, collaborators without push access) is expected and becomes
|
|
1288
|
+
* a warning; anything else (network, rate limit) is also a warning but needs a
|
|
1289
|
+
* different sentence. Fine-grained tokens report nothing in `x-oauth-scopes`,
|
|
1290
|
+
* so the HTTP status is the signal.
|
|
1291
|
+
*
|
|
1292
|
+
* @param {unknown} error
|
|
1293
|
+
* @returns {boolean}
|
|
1294
|
+
*/
|
|
1295
|
+
export function isScopeError(error) {
|
|
1296
|
+
if (error?.code !== 'UNAUTHORIZED' && error?.code !== 'FORBIDDEN' && error?.code !== 'NOT_FOUND') return false;
|
|
1297
|
+
return !/速率限制/.test(String(error?.message ?? ''));
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
/**
|
|
1301
|
+
* Map one `/branches` payload row onto CONTRACT §2/§3c `Branch`.
|
|
1302
|
+
* @param {any} raw
|
|
1303
|
+
* @returns {{name: string, sha: string, protected: boolean}}
|
|
1304
|
+
*/
|
|
1305
|
+
function mapBranch(raw) {
|
|
1306
|
+
const branch = raw ?? {};
|
|
1307
|
+
return {
|
|
1308
|
+
name: String(branch.name ?? ''),
|
|
1309
|
+
sha: String(branch.commit?.sha ?? ''),
|
|
1310
|
+
protected: branch.protected === true,
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
/** Map one `/collaborators` row onto CONTRACT §3c's shape. */
|
|
1315
|
+
function mapCollaborator(raw) {
|
|
1316
|
+
const user = raw ?? {};
|
|
1317
|
+
// Fine-grained permissions arrive as `{ pull, push, admin, … }`; classic ones
|
|
1318
|
+
// as a single `role_name`/`permission` string. The UI only needs a label.
|
|
1319
|
+
const permissions = user.permissions ?? {};
|
|
1320
|
+
let role = typeof user.role_name === 'string' && user.role_name !== '' ? user.role_name : '';
|
|
1321
|
+
if (role === '') {
|
|
1322
|
+
if (permissions.admin === true) role = 'admin';
|
|
1323
|
+
else if (permissions.maintain === true) role = 'maintain';
|
|
1324
|
+
else if (permissions.push === true) role = 'write';
|
|
1325
|
+
else if (permissions.triage === true) role = 'triage';
|
|
1326
|
+
else if (permissions.pull === true) role = 'read';
|
|
1327
|
+
else role = String(user.permission ?? 'read');
|
|
1328
|
+
}
|
|
1329
|
+
return {
|
|
1330
|
+
login: String(user.login ?? ''),
|
|
1331
|
+
avatarUrl: typeof user.avatar_url === 'string' ? user.avatar_url : null,
|
|
1332
|
+
role,
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
/** Map one `/hooks` row onto CONTRACT §3c's shape. */
|
|
1337
|
+
function mapWebhook(raw) {
|
|
1338
|
+
const hook = raw ?? {};
|
|
1339
|
+
const config = hook.config ?? {};
|
|
1340
|
+
return {
|
|
1341
|
+
id: String(hook.id ?? ''),
|
|
1342
|
+
url: String(config.url ?? ''),
|
|
1343
|
+
events: Array.isArray(hook.events) ? hook.events.filter((event) => typeof event === 'string') : [],
|
|
1344
|
+
active: hook.active === true,
|
|
1345
|
+
};
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
/**
|
|
1349
|
+
* Call one GitHub endpoint for the management aggregate.
|
|
1350
|
+
*
|
|
1351
|
+
* @param {{token: string, owner: string, name: string, path: string,
|
|
1352
|
+
* action: string, timeoutMs?: number}} options
|
|
1353
|
+
* @returns {Promise<{json: any, headers: object}>}
|
|
1354
|
+
*/
|
|
1355
|
+
function manageRequest(options) {
|
|
1356
|
+
return api({
|
|
1357
|
+
method: 'GET',
|
|
1358
|
+
url: `${repoPath(options.owner, options.name)}${options.path}`,
|
|
1359
|
+
token: options.token,
|
|
1360
|
+
timeoutMs: options.timeoutMs,
|
|
1361
|
+
action: options.action,
|
|
1362
|
+
});
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
/**
|
|
1366
|
+
* Turn the six settled sub-requests into the CONTRACT §3c document.
|
|
1367
|
+
*
|
|
1368
|
+
* EXTRACTED AS A PURE FUNCTION so the interesting rule — "a rejected
|
|
1369
|
+
* sub-request becomes `null` plus a Chinese warning, never a failed call" — can
|
|
1370
|
+
* be verified without a live GitHub and without patching the network. `settled`
|
|
1371
|
+
* is exactly what {@link repoManage}'s `Promise.allSettled` produced.
|
|
1372
|
+
*
|
|
1373
|
+
* @param {PromiseSettledResult<{json: any}>[]} settled
|
|
1374
|
+
* [repo, branches, releases, collaborators, webhooks, openPRs]
|
|
1375
|
+
* @returns {object} the contract document (throws only for a rejected repo).
|
|
1376
|
+
*/
|
|
1377
|
+
export function assembleRepoManage(settled) {
|
|
1378
|
+
const [repoResult] = settled;
|
|
1379
|
+
if (repoResult.status === 'rejected') {
|
|
1380
|
+
// A repository the token cannot read means there is nothing to manage; the
|
|
1381
|
+
// contract's "partial failure" rule is about SUB-resources, not this one.
|
|
1382
|
+
const error = repoResult.reason;
|
|
1383
|
+
if (isScopeError(error)) {
|
|
1384
|
+
throw new GithubError(
|
|
1385
|
+
'UNAUTHORIZED',
|
|
1386
|
+
'无法读取该仓库:当前账号没有访问权限(或令牌缺少 repo 权限范围)。',
|
|
1387
|
+
{ status: error?.status },
|
|
1388
|
+
);
|
|
1389
|
+
}
|
|
1390
|
+
throw error;
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
const rawRepo = repoResult.value?.json ?? {};
|
|
1394
|
+
const repo = mapRepo(rawRepo);
|
|
1395
|
+
const warnings = [];
|
|
1396
|
+
/** The parsed payload of one fulfilled sub-result, else null. */
|
|
1397
|
+
const valueAt = (at) => (settled[at].status === 'fulfilled' ? settled[at].value?.json : null);
|
|
1398
|
+
/**
|
|
1399
|
+
* Turn one rejection into a warning.
|
|
1400
|
+
*
|
|
1401
|
+
* A missing scope is named AS a missing scope (`缺少 admin:repo_hook 权限…`)
|
|
1402
|
+
* because "forbidden" alone does not tell the user which token to mint.
|
|
1403
|
+
* Anything else reports GitHub's own (already Chinese-framed) message.
|
|
1404
|
+
*/
|
|
1405
|
+
const warn = (at, scopeMessage, action) => {
|
|
1406
|
+
if (settled[at].status !== 'rejected') return;
|
|
1407
|
+
const reason = settled[at].reason;
|
|
1408
|
+
warnings.push(isScopeError(reason)
|
|
1409
|
+
? scopeMessage
|
|
1410
|
+
: `${action}失败:${reason?.message ?? '未知原因'}`);
|
|
1411
|
+
};
|
|
1412
|
+
|
|
1413
|
+
let branches = null;
|
|
1414
|
+
if (Array.isArray(valueAt(1))) branches = valueAt(1).map(mapBranch);
|
|
1415
|
+
else warn(1, '缺少读取分支的权限,无法显示分支列表(需要 repo 权限范围)', '读取分支列表');
|
|
1416
|
+
|
|
1417
|
+
let releases = null;
|
|
1418
|
+
if (Array.isArray(valueAt(2))) releases = valueAt(2).map(mapRelease);
|
|
1419
|
+
else warn(2, '缺少读取发布的权限,无法显示发布列表(需要 repo 权限范围)', '读取发布列表');
|
|
1420
|
+
|
|
1421
|
+
let collaborators = null;
|
|
1422
|
+
if (Array.isArray(valueAt(3))) collaborators = valueAt(3).map(mapCollaborator);
|
|
1423
|
+
else warn(3, '缺少读取协作者的权限,无法显示协作者列表(需要对仓库的管理权限)', '读取协作者列表');
|
|
1424
|
+
|
|
1425
|
+
let webhooks = null;
|
|
1426
|
+
if (Array.isArray(valueAt(4))) webhooks = valueAt(4).map(mapWebhook);
|
|
1427
|
+
else warn(4, '缺少 admin:repo_hook 权限,无法读取 Webhook', '读取 Webhook 列表');
|
|
1428
|
+
|
|
1429
|
+
let openPRs = 0;
|
|
1430
|
+
const searchJson = valueAt(5);
|
|
1431
|
+
if (settled[5].status === 'fulfilled' && Number.isFinite(Number(searchJson?.total_count))) {
|
|
1432
|
+
openPRs = Number(searchJson.total_count);
|
|
1433
|
+
} else if (settled[5].status === 'rejected') {
|
|
1434
|
+
// The count is a nicety, so a failure leaves a number the UI can render
|
|
1435
|
+
// instead of `null` in a numeric field.
|
|
1436
|
+
warn(5, '缺少搜索权限,无法统计开放的 Pull Request', '统计开放 PR');
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
// `topics` come from the repo payload; GitHub only includes them when the
|
|
1440
|
+
// Accept header is the versioned JSON one, which every request in this module
|
|
1441
|
+
// sends (`ACCEPT_JSON`). A repository created before topics existed simply
|
|
1442
|
+
// omits the array.
|
|
1443
|
+
const topics = Array.isArray(rawRepo.topics)
|
|
1444
|
+
? rawRepo.topics.filter((topic) => typeof topic === 'string')
|
|
1445
|
+
: [];
|
|
1446
|
+
const license = rawRepo.license && typeof rawRepo.license === 'object'
|
|
1447
|
+
? String(rawRepo.license.spdx_id ?? rawRepo.license.name ?? '') || null
|
|
1448
|
+
: null;
|
|
1449
|
+
const admin = rawRepo.permissions?.admin === true;
|
|
1450
|
+
const push = rawRepo.permissions?.push === true;
|
|
1451
|
+
|
|
1452
|
+
return {
|
|
1453
|
+
repo,
|
|
1454
|
+
branches,
|
|
1455
|
+
topics,
|
|
1456
|
+
stats: {
|
|
1457
|
+
stars: Number(rawRepo.stargazers_count ?? 0),
|
|
1458
|
+
forks: Number(rawRepo.forks_count ?? 0),
|
|
1459
|
+
// `subscribers_count` is watchers; `watchers_count` is a legacy alias of
|
|
1460
|
+
// stars, so using it here would print the star count twice.
|
|
1461
|
+
watchers: Number(rawRepo.subscribers_count ?? rawRepo.watchers_count ?? 0),
|
|
1462
|
+
openIssues: Number(rawRepo.open_issues_count ?? 0),
|
|
1463
|
+
openPRs,
|
|
1464
|
+
sizeKb: Number(rawRepo.size ?? 0),
|
|
1465
|
+
language: typeof rawRepo.language === 'string' ? rawRepo.language : null,
|
|
1466
|
+
license,
|
|
1467
|
+
createdAt: String(rawRepo.created_at ?? ''),
|
|
1468
|
+
updatedAt: String(rawRepo.updated_at ?? ''),
|
|
1469
|
+
pushedAt: typeof rawRepo.pushed_at === 'string' ? rawRepo.pushed_at : null,
|
|
1470
|
+
},
|
|
1471
|
+
releases,
|
|
1472
|
+
collaborators,
|
|
1473
|
+
webhooks,
|
|
1474
|
+
warnings,
|
|
1475
|
+
can: {
|
|
1476
|
+
admin,
|
|
1477
|
+
push,
|
|
1478
|
+
// Deleting needs BOTH repository admin rights and a token that may delete
|
|
1479
|
+
// repos. For a classic PAT that is the `delete_repo` scope; for a
|
|
1480
|
+
// fine-grained token the scopes are invisible to us, so this is based on
|
|
1481
|
+
// `permissions.admin` and the UI text mentions the scope separately.
|
|
1482
|
+
delete: admin,
|
|
1483
|
+
},
|
|
1484
|
+
};
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
/**
|
|
1488
|
+
* Read the FULL management aggregate of CONTRACT §3c.
|
|
1489
|
+
*
|
|
1490
|
+
* EVERY sub-request is independent: the panel must still render stars,
|
|
1491
|
+
* branches and releases when the token cannot read webhooks, so a rejected
|
|
1492
|
+
* sub-request becomes `null` plus one Chinese warning instead of failing the
|
|
1493
|
+
* whole call. `Promise.allSettled` is what makes "all six in parallel, none
|
|
1494
|
+
* able to cancel another" true.
|
|
1495
|
+
*
|
|
1496
|
+
* OPEN PRs: counted through the SEARCH API (`/search/issues?q=repo:O/N+is:pr+
|
|
1497
|
+
* is:open`) rather than by parsing the `Link` header of a `per_page=1` pulls
|
|
1498
|
+
* page. Reason: `Link` only tells you "there is a next page", which cannot be
|
|
1499
|
+
* turned into a count on the last page, and GitHub's search response carries
|
|
1500
|
+
* `total_count` directly. A `per_page=100&state=open` pulls call would need
|
|
1501
|
+
* pagination of its own for a large repository.
|
|
1502
|
+
*
|
|
1503
|
+
* @param {{token: string, owner: string, name: string, timeoutMs?: number}} options
|
|
1504
|
+
* @returns {Promise<object>} the CONTRACT §3c document. Never rejects for a
|
|
1505
|
+
* sub-request failure; DOES reject when the repository itself is unreadable.
|
|
1506
|
+
*/
|
|
1507
|
+
export async function repoManage(options) {
|
|
1508
|
+
const token = options.token;
|
|
1509
|
+
const owner = String(options.owner ?? '').trim();
|
|
1510
|
+
const name = String(options.name ?? '').trim();
|
|
1511
|
+
if (owner === '' || name === '') throw new GithubError('BAD_REQUEST', '缺少仓库的 owner 或名称');
|
|
1512
|
+
|
|
1513
|
+
const settled = await Promise.allSettled([
|
|
1514
|
+
manageRequest({ token, owner, name, path: '', action: '读取仓库详情', timeoutMs: options.timeoutMs }),
|
|
1515
|
+
manageRequest({ token, owner, name, path: '/branches?per_page=100', action: '读取分支列表', timeoutMs: options.timeoutMs }),
|
|
1516
|
+
manageRequest({ token, owner, name, path: '/releases?per_page=50', action: '读取 release 列表', timeoutMs: options.timeoutMs }),
|
|
1517
|
+
manageRequest({ token, owner, name, path: '/collaborators?per_page=100', action: '读取协作者列表', timeoutMs: options.timeoutMs }),
|
|
1518
|
+
manageRequest({ token, owner, name, path: '/hooks?per_page=100', action: '读取 Webhook 列表', timeoutMs: options.timeoutMs }),
|
|
1519
|
+
// Open PR count via search (`total_count`), see the doc comment above.
|
|
1520
|
+
api({
|
|
1521
|
+
method: 'GET',
|
|
1522
|
+
url: `${API_BASE}/search/issues?q=${encodeURIComponent(`repo:${owner}/${name} is:pr is:open`)}&per_page=1`,
|
|
1523
|
+
token,
|
|
1524
|
+
timeoutMs: options.timeoutMs,
|
|
1525
|
+
action: '统计开放的 Pull Request',
|
|
1526
|
+
}),
|
|
1527
|
+
]);
|
|
1528
|
+
const document = assembleRepoManage(settled);
|
|
1529
|
+
// The repo name is only available inside the settled payload; the caller's
|
|
1530
|
+
// copy is already correct, so the permission message above stays generic.
|
|
1531
|
+
return document;
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
/**
|
|
1535
|
+
* `PATCH /repos/{owner}/{repo}` — update metadata (CONTRACT §3c `/repos/update`).
|
|
1536
|
+
*
|
|
1537
|
+
* Only the fields PRESENT in `patch` are sent: GitHub treats an omitted field
|
|
1538
|
+
* as "leave alone", and sending `description: null` for a field the user did
|
|
1539
|
+
* not edit would wipe it.
|
|
1540
|
+
*
|
|
1541
|
+
* @param {{token: string, owner: string, name: string, timeoutMs?: number,
|
|
1542
|
+
* patch: {description?: string, homepage?: string, private?: boolean,
|
|
1543
|
+
* archived?: boolean, topics?: string[], defaultBranch?: string}}} options
|
|
1544
|
+
* @returns {Promise<{repo: object, topics: string[]}>} `topics` is the raw
|
|
1545
|
+
* payload's topic list, which the panel re-renders after an edit.
|
|
1546
|
+
*/
|
|
1547
|
+
export async function updateRepo(options) {
|
|
1548
|
+
const body = {};
|
|
1549
|
+
const patch = options.patch ?? {};
|
|
1550
|
+
if (typeof patch.description === 'string') body.description = patch.description;
|
|
1551
|
+
if (typeof patch.homepage === 'string') body.homepage = patch.homepage;
|
|
1552
|
+
if (typeof patch.private === 'boolean') body.private = patch.private;
|
|
1553
|
+
if (typeof patch.archived === 'boolean') body.archived = patch.archived;
|
|
1554
|
+
if (typeof patch.defaultBranch === 'string' && patch.defaultBranch !== '') {
|
|
1555
|
+
body.default_branch = patch.defaultBranch;
|
|
1556
|
+
}
|
|
1557
|
+
// Deliberately NOT added to `body`: a PATCH ignores topics entirely.
|
|
1558
|
+
// They are written through the dedicated endpoint below.
|
|
1559
|
+
const wantsTopics = Array.isArray(patch.topics);
|
|
1560
|
+
if (Object.keys(body).length === 0 && !wantsTopics) {
|
|
1561
|
+
throw new GithubError('BAD_REQUEST', '没有需要修改的字段');
|
|
1562
|
+
}
|
|
1563
|
+
// A topics-only update has an empty PATCH body; skip the request entirely
|
|
1564
|
+
// rather than send {} (which GitHub would reject as no-op).
|
|
1565
|
+
let json = null;
|
|
1566
|
+
if (Object.keys(body).length > 0) {
|
|
1567
|
+
const response = await api({
|
|
1568
|
+
method: 'PATCH',
|
|
1569
|
+
url: repoPath(options.owner, options.name),
|
|
1570
|
+
token: options.token,
|
|
1571
|
+
timeoutMs: options.timeoutMs,
|
|
1572
|
+
action: '修改仓库信息',
|
|
1573
|
+
body,
|
|
1574
|
+
});
|
|
1575
|
+
json = response.json;
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
// Topics are a separate resource; the PATCH above cannot carry them.
|
|
1579
|
+
let topics = Array.isArray(json?.topics)
|
|
1580
|
+
? json.topics.filter((topic) => typeof topic === 'string')
|
|
1581
|
+
: [];
|
|
1582
|
+
if (wantsTopics) {
|
|
1583
|
+
const written = await setTopics({
|
|
1584
|
+
token: options.token,
|
|
1585
|
+
owner: options.owner,
|
|
1586
|
+
name: options.name,
|
|
1587
|
+
topics: patch.topics,
|
|
1588
|
+
timeoutMs: options.timeoutMs,
|
|
1589
|
+
});
|
|
1590
|
+
topics = written.topics;
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
// With no PATCH issued there is no repository payload; read the topics we
|
|
1594
|
+
// just wrote back and let the caller refetch the rest.
|
|
1595
|
+
return { repo: json ? mapRepo(json) : null, topics };
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
/**
|
|
1599
|
+
* Rename a branch (CONTRACT §3c `/repos/branch/rename`).
|
|
1600
|
+
* @param {{token: string, owner: string, name: string, from: string, to: string, timeoutMs?: number}} options
|
|
1601
|
+
* @returns {Promise<{renamed: true}>}
|
|
1602
|
+
*/
|
|
1603
|
+
export async function renameBranch(options) {
|
|
1604
|
+
const from = String(options.from ?? '').trim();
|
|
1605
|
+
const to = String(options.to ?? '').trim();
|
|
1606
|
+
if (from === '') throw new GithubError('BAD_REQUEST', '缺少原分支名');
|
|
1607
|
+
if (to === '') throw new GithubError('BAD_REQUEST', '缺少新分支名');
|
|
1608
|
+
await api({
|
|
1609
|
+
method: 'POST',
|
|
1610
|
+
url: `${repoPath(options.owner, options.name)}/branches/${encodeURIComponent(from)}/rename`,
|
|
1611
|
+
token: options.token,
|
|
1612
|
+
timeoutMs: options.timeoutMs,
|
|
1613
|
+
action: `重命名分支 ${from}`,
|
|
1614
|
+
body: { new_name: to },
|
|
1615
|
+
});
|
|
1616
|
+
return { renamed: true };
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
/**
|
|
1620
|
+
* Delete a remote branch (CONTRACT §3c `/repos/branch/delete`).
|
|
1621
|
+
*
|
|
1622
|
+
* The REST API has no DELETE for branches; deleting the underlying git ref is
|
|
1623
|
+
* the documented way (`DELETE /git/refs/heads/{branch}`).
|
|
1624
|
+
*
|
|
1625
|
+
* @param {{token: string, owner: string, name: string, branch: string, timeoutMs?: number}} options
|
|
1626
|
+
* @returns {Promise<{deleted: true}>}
|
|
1627
|
+
*/
|
|
1628
|
+
export async function deleteBranchRemote(options) {
|
|
1629
|
+
const branch = String(options.branch ?? '').trim();
|
|
1630
|
+
if (branch === '') throw new GithubError('BAD_REQUEST', '缺少分支名');
|
|
1631
|
+
const response = await request({
|
|
1632
|
+
method: 'DELETE',
|
|
1633
|
+
url: `${repoPath(options.owner, options.name)}/git/refs/heads/${encodeURIComponent(branch)}`,
|
|
1634
|
+
token: options.token,
|
|
1635
|
+
timeoutMs: options.timeoutMs,
|
|
1636
|
+
});
|
|
1637
|
+
if (response.status === 204 || response.status === 200) return { deleted: true };
|
|
1638
|
+
if (response.status === 404) {
|
|
1639
|
+
throw new GithubError('NOT_FOUND', `GitHub 上找不到分支 ${branch}(可能已被删除)。`, { status: 404 });
|
|
1640
|
+
}
|
|
1641
|
+
if (response.status === 403 || response.status === 422) {
|
|
1642
|
+
throw new GithubError(
|
|
1643
|
+
'UNAUTHORIZED',
|
|
1644
|
+
`删除分支 ${branch} 需要仓库的写入权限(且不能是默认分支或受保护分支)。`,
|
|
1645
|
+
{ status: response.status },
|
|
1646
|
+
);
|
|
1647
|
+
}
|
|
1648
|
+
throw responseError(response, `删除分支 ${branch}`);
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
/**
|
|
1652
|
+
* Protect / unprotect a branch (CONTRACT §3c `/repos/branch/protect`).
|
|
1653
|
+
*
|
|
1654
|
+
* The PUT body is deliberately MINIMAL: requiring an exhaustive protection
|
|
1655
|
+
* object would let the panel's "protect" switch fail on every repository with
|
|
1656
|
+
* an unusual setting. GitHub fills the unspecified rules with its defaults.
|
|
1657
|
+
*
|
|
1658
|
+
* @param {{token: string, owner: string, name: string, branch: string,
|
|
1659
|
+
* protected: boolean, timeoutMs?: number}} options
|
|
1660
|
+
* @returns {Promise<{protected: boolean}>}
|
|
1661
|
+
*/
|
|
1662
|
+
export async function protectBranch(options) {
|
|
1663
|
+
const branch = String(options.branch ?? '').trim();
|
|
1664
|
+
if (branch === '') throw new GithubError('BAD_REQUEST', '缺少分支名');
|
|
1665
|
+
const url = `${repoPath(options.owner, options.name)}/branches/${encodeURIComponent(branch)}/protection`;
|
|
1666
|
+
if (options.protected !== true) {
|
|
1667
|
+
const response = await request({ method: 'DELETE', url, token: options.token, timeoutMs: options.timeoutMs });
|
|
1668
|
+
if (response.status === 204 || response.status === 200) return { protected: false };
|
|
1669
|
+
if (response.status === 404) return { protected: false };
|
|
1670
|
+
if (response.status === 403) {
|
|
1671
|
+
throw new GithubError('UNAUTHORIZED', `取消保护分支 ${branch} 需要仓库管理员权限。`, { status: 403 });
|
|
1672
|
+
}
|
|
1673
|
+
throw responseError(response, `取消保护分支 ${branch}`);
|
|
1674
|
+
}
|
|
1675
|
+
await api({
|
|
1676
|
+
method: 'PUT',
|
|
1677
|
+
url,
|
|
1678
|
+
token: options.token,
|
|
1679
|
+
timeoutMs: options.timeoutMs,
|
|
1680
|
+
action: `保护分支 ${branch}`,
|
|
1681
|
+
body: {
|
|
1682
|
+
required_status_checks: null,
|
|
1683
|
+
enforce_admins: false,
|
|
1684
|
+
required_pull_request_reviews: null,
|
|
1685
|
+
restrictions: null,
|
|
1686
|
+
},
|
|
1687
|
+
});
|
|
1688
|
+
return { protected: true };
|
|
1689
|
+
}
|
|
1690
|
+
|
|
1691
|
+
/**
|
|
1692
|
+
* Delete a release (CONTRACT §3c `/repos/release/delete`).
|
|
1693
|
+
* @param {{token: string, owner: string, name: string, id: string, timeoutMs?: number}} options
|
|
1694
|
+
* @returns {Promise<{deleted: true}>}
|
|
1695
|
+
*/
|
|
1696
|
+
/**
|
|
1697
|
+
* Remove one asset from a release (CONTRACT 2, POST /releases/asset/delete).
|
|
1698
|
+
*
|
|
1699
|
+
* Deleting the release itself would take its assets with it, but removing a
|
|
1700
|
+
* single mis-uploaded file is the common case and needs its own call.
|
|
1701
|
+
*
|
|
1702
|
+
* @param {object} options
|
|
1703
|
+
* @param {string} options.token
|
|
1704
|
+
* @param {string} options.owner
|
|
1705
|
+
* @param {string} options.name
|
|
1706
|
+
* @param {string} options.assetId
|
|
1707
|
+
* @returns {Promise<{deleted: true}>}
|
|
1708
|
+
*/
|
|
1709
|
+
export async function deleteReleaseAsset(options) {
|
|
1710
|
+
const owner = String(options.owner ?? '').trim();
|
|
1711
|
+
const name = String(options.name ?? '').trim();
|
|
1712
|
+
const assetId = String(options.assetId ?? '').trim();
|
|
1713
|
+
if (owner === '' || name === '' || assetId === '') {
|
|
1714
|
+
throw new GithubError('BAD_REQUEST', '缺少仓库或附件 id');
|
|
1715
|
+
}
|
|
1716
|
+
const response = await request({
|
|
1717
|
+
method: 'DELETE',
|
|
1718
|
+
url: API_BASE + '/repos/' + encodeURIComponent(owner) + '/' + encodeURIComponent(name)
|
|
1719
|
+
+ '/releases/assets/' + encodeURIComponent(assetId),
|
|
1720
|
+
token: options.token,
|
|
1721
|
+
timeoutMs: options.timeoutMs,
|
|
1722
|
+
});
|
|
1723
|
+
if (response.status === 204 || response.status === 200) return { deleted: true };
|
|
1724
|
+
if (response.status === 404) return { deleted: true };
|
|
1725
|
+
throw responseError(response, '删除发布附件');
|
|
1726
|
+
}
|
|
1727
|
+
export async function deleteRelease(options) {
|
|
1728
|
+
const id = String(options.id ?? '').trim();
|
|
1729
|
+
if (id === '') throw new GithubError('BAD_REQUEST', '缺少 release id');
|
|
1730
|
+
const response = await request({
|
|
1731
|
+
method: 'DELETE',
|
|
1732
|
+
url: `${repoPath(options.owner, options.name)}/releases/${encodeURIComponent(id)}`,
|
|
1733
|
+
token: options.token,
|
|
1734
|
+
timeoutMs: options.timeoutMs,
|
|
1735
|
+
});
|
|
1736
|
+
if (response.status === 204 || response.status === 200) return { deleted: true };
|
|
1737
|
+
if (response.status === 404) return { deleted: true };
|
|
1738
|
+
throw responseError(response, '删除 release');
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
/**
|
|
1742
|
+
* Edit a release (CONTRACT §3c `/repos/release/update`).
|
|
1743
|
+
* @param {{token: string, owner: string, name: string, id: string,
|
|
1744
|
+
* name?: string, body?: string, draft?: boolean, prerelease?: boolean,
|
|
1745
|
+
* timeoutMs?: number}} options
|
|
1746
|
+
* @returns {Promise<{release: object}>}
|
|
1747
|
+
*/
|
|
1748
|
+
export async function updateRelease(options) {
|
|
1749
|
+
const id = String(options.id ?? '').trim();
|
|
1750
|
+
if (id === '') throw new GithubError('BAD_REQUEST', '缺少 release id');
|
|
1751
|
+
const patch = {};
|
|
1752
|
+
// `title` is the RELEASE title; `repo` is the repository. They were once both
|
|
1753
|
+
// `name`, and the service's spread silently put the title into the repo path.
|
|
1754
|
+
// `title` and `body` are nullable ON THE WIRE: an empty string here is the
|
|
1755
|
+
// user clearing the field, so it is sent rather than skipped.
|
|
1756
|
+
if (typeof options.title === 'string') patch.name = options.title;
|
|
1757
|
+
if (typeof options.body === 'string') patch.body = options.body;
|
|
1758
|
+
if (typeof options.draft === 'boolean') patch.draft = options.draft;
|
|
1759
|
+
if (typeof options.prerelease === 'boolean') patch.prerelease = options.prerelease;
|
|
1760
|
+
if (Object.keys(patch).length === 0) throw new GithubError('BAD_REQUEST', '没有需要修改的字段');
|
|
1761
|
+
const { json } = await api({
|
|
1762
|
+
method: 'PATCH',
|
|
1763
|
+
url: `${repoPath(options.owner, options.repo)}/releases/${encodeURIComponent(id)}`,
|
|
1764
|
+
token: options.token,
|
|
1765
|
+
timeoutMs: options.timeoutMs,
|
|
1766
|
+
action: '修改 release',
|
|
1767
|
+
body: patch,
|
|
1768
|
+
});
|
|
1769
|
+
return { release: mapRelease(json) };
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1772
|
+
/**
|
|
1773
|
+
* Add or update one collaborator (CONTRACT §3c `/repos/collaborator/add`).
|
|
1774
|
+
*
|
|
1775
|
+
* `permission` maps to GitHub's `permission` field; the classic `push`/`pull`
|
|
1776
|
+
* spellings are still accepted by the API and are passed through untouched so
|
|
1777
|
+
* the panel can offer either vocabulary.
|
|
1778
|
+
*
|
|
1779
|
+
* @param {{token: string, owner: string, name: string, user: string,
|
|
1780
|
+
* permission?: string, timeoutMs?: number}} options
|
|
1781
|
+
* @returns {Promise<{added: true, invitation: boolean}>}
|
|
1782
|
+
*/
|
|
1783
|
+
export async function addCollaborator(options) {
|
|
1784
|
+
const user = String(options.user ?? '').trim();
|
|
1785
|
+
if (user === '') throw new GithubError('BAD_REQUEST', '缺少协作的 GitHub 用户名');
|
|
1786
|
+
const permission = typeof options.permission === 'string' && options.permission.trim() !== ''
|
|
1787
|
+
? options.permission.trim()
|
|
1788
|
+
: 'push';
|
|
1789
|
+
const response = await request({
|
|
1790
|
+
method: 'PUT',
|
|
1791
|
+
url: `${repoPath(options.owner, options.name)}/collaborators/${encodeURIComponent(user)}`,
|
|
1792
|
+
token: options.token,
|
|
1793
|
+
timeoutMs: options.timeoutMs,
|
|
1794
|
+
body: { permission },
|
|
1795
|
+
});
|
|
1796
|
+
// 201 = added outright, 204 = permission changed, 202 = invitation sent.
|
|
1797
|
+
if (response.status === 201 || response.status === 204) {
|
|
1798
|
+
return { added: true, invitation: false };
|
|
1799
|
+
}
|
|
1800
|
+
if (response.status === 202) return { added: true, invitation: true };
|
|
1801
|
+
throw responseError(response, `添加协作者 ${user}`);
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
/**
|
|
1805
|
+
* Remove one collaborator (CONTRACT §3c `/repos/collaborator/remove`).
|
|
1806
|
+
* @param {{token: string, owner: string, name: string, user: string, timeoutMs?: number}} options
|
|
1807
|
+
* @returns {Promise<{removed: true}>}
|
|
1808
|
+
*/
|
|
1809
|
+
export async function removeCollaborator(options) {
|
|
1810
|
+
const user = String(options.user ?? '').trim();
|
|
1811
|
+
if (user === '') throw new GithubError('BAD_REQUEST', '缺少要移除的 GitHub 用户名');
|
|
1812
|
+
const response = await request({
|
|
1813
|
+
method: 'DELETE',
|
|
1814
|
+
url: `${repoPath(options.owner, options.name)}/collaborators/${encodeURIComponent(user)}`,
|
|
1815
|
+
token: options.token,
|
|
1816
|
+
timeoutMs: options.timeoutMs,
|
|
1817
|
+
});
|
|
1818
|
+
if (response.status === 204 || response.status === 200) return { removed: true };
|
|
1819
|
+
if (response.status === 404) return { removed: true };
|
|
1820
|
+
if (response.status === 403) {
|
|
1821
|
+
throw new GithubError(
|
|
1822
|
+
'UNAUTHORIZED',
|
|
1823
|
+
`移除协作者 ${user} 需要仓库管理员权限。`,
|
|
1824
|
+
{ status: 403 },
|
|
1825
|
+
);
|
|
1826
|
+
}
|
|
1827
|
+
throw responseError(response, `移除协作者 ${user}`);
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1830
|
+
/**
|
|
1831
|
+
* Replace the topic list of a repository.
|
|
1832
|
+
*
|
|
1833
|
+
* Topics are NOT part of the repository PATCH: GitHub exposes them on
|
|
1834
|
+
* `PUT /repos/{owner}/{repo}/topics` with a `{ names: [...] }` body, and
|
|
1835
|
+
* silently ignores `topics` in a PATCH. Sending them with the PATCH looked
|
|
1836
|
+
* like it worked (200 OK) and changed nothing.
|
|
1837
|
+
*
|
|
1838
|
+
* @param {object} options
|
|
1839
|
+
* @param {string} options.token
|
|
1840
|
+
* @param {string} options.owner
|
|
1841
|
+
* @param {string} options.name
|
|
1842
|
+
* @param {string[]} options.topics
|
|
1843
|
+
* @returns {Promise<{topics: string[]}>}
|
|
1844
|
+
*/
|
|
1845
|
+
export async function setTopics(options) {
|
|
1846
|
+
const owner = String(options.owner ?? '').trim();
|
|
1847
|
+
const name = String(options.name ?? '').trim();
|
|
1848
|
+
if (owner === '' || name === '') throw new GithubError('BAD_REQUEST', '缺少仓库的 owner 或名称');
|
|
1849
|
+
const names = Array.isArray(options.topics)
|
|
1850
|
+
? options.topics
|
|
1851
|
+
.map((topic) => String(topic).trim().toLowerCase())
|
|
1852
|
+
.filter((topic) => topic !== '')
|
|
1853
|
+
: [];
|
|
1854
|
+
const { json } = await api({
|
|
1855
|
+
method: 'PUT',
|
|
1856
|
+
url: repoPath(owner, name) + '/topics',
|
|
1857
|
+
token: options.token,
|
|
1858
|
+
timeoutMs: options.timeoutMs,
|
|
1859
|
+
action: '设置 topics',
|
|
1860
|
+
body: { names },
|
|
1861
|
+
});
|
|
1862
|
+
return {
|
|
1863
|
+
topics: Array.isArray(json?.names)
|
|
1864
|
+
? json.names.filter((topic) => typeof topic === 'string')
|
|
1865
|
+
: names,
|
|
1866
|
+
};
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
/**
|
|
1870
|
+
* Rename a repository (CONTRACT §3c `/repos/rename`, requires `confirm`).
|
|
1871
|
+
*
|
|
1872
|
+
* GitHub answers 202 while it rewrites redirects in the background; that is a
|
|
1873
|
+
* success for the panel, so the response body (which may be empty) is only
|
|
1874
|
+
* used when it parses.
|
|
1875
|
+
*
|
|
1876
|
+
* @param {{token: string, owner: string, name: string, newName: string, timeoutMs?: number}} options
|
|
1877
|
+
* @returns {Promise<{repo: object|null, name: string}>}
|
|
1878
|
+
*/
|
|
1879
|
+
export async function renameRepo(options) {
|
|
1880
|
+
const newName = String(options.newName ?? '').trim();
|
|
1881
|
+
if (newName === '') throw new GithubError('BAD_REQUEST', '缺少新的仓库名称');
|
|
1882
|
+
const response = await request({
|
|
1883
|
+
method: 'PATCH',
|
|
1884
|
+
url: repoPath(options.owner, options.name),
|
|
1885
|
+
token: options.token,
|
|
1886
|
+
timeoutMs: options.timeoutMs,
|
|
1887
|
+
body: { name: newName },
|
|
1888
|
+
});
|
|
1889
|
+
if (response.status < 200 || response.status >= 300) {
|
|
1890
|
+
throw responseError(response, '重命名仓库');
|
|
1891
|
+
}
|
|
1892
|
+
return {
|
|
1893
|
+
repo: response.json && typeof response.json === 'object' ? mapRepo(response.json) : null,
|
|
1894
|
+
name: newName,
|
|
1895
|
+
};
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
/**
|
|
1899
|
+
* Transfer a repository to another owner (CONTRACT §3c `/repos/transfer`,
|
|
1900
|
+
* requires `confirm`).
|
|
1901
|
+
*
|
|
1902
|
+
* @param {{token: string, owner: string, name: string, newOwner: string, timeoutMs?: number}} options
|
|
1903
|
+
* @returns {Promise<{transferred: true, newOwner: string}>}
|
|
1904
|
+
*/
|
|
1905
|
+
export async function transferRepo(options) {
|
|
1906
|
+
const newOwner = String(options.newOwner ?? '').trim();
|
|
1907
|
+
if (newOwner === '') throw new GithubError('BAD_REQUEST', '缺少新的仓库所有者');
|
|
1908
|
+
const { json } = await api({
|
|
1909
|
+
method: 'POST',
|
|
1910
|
+
url: `${repoPath(options.owner, options.name)}/transfer`,
|
|
1911
|
+
token: options.token,
|
|
1912
|
+
timeoutMs: options.timeoutMs,
|
|
1913
|
+
action: '转移仓库',
|
|
1914
|
+
body: { new_owner: newOwner },
|
|
1915
|
+
});
|
|
1916
|
+
// The transfer endpoint returns 202 with a `message` document (not the repo).
|
|
1917
|
+
return {
|
|
1918
|
+
transferred: true,
|
|
1919
|
+
newOwner,
|
|
1920
|
+
message: typeof json?.message === 'string' ? json.message : undefined,
|
|
1921
|
+
};
|
|
1922
|
+
}
|