Personal Telegram developer console for GitHub
feat(github): add exact-head pull request merge
davoodmehraban89 committed
Oct 5, 2026 at 04:52 UTC
6f6383cfec8e9f9895b8736e4d0e20f9c3ea0ade
1 file changed
+101
-311
src/github.js
+101
-311
@@ -79,240 +79,124 @@ export class GitHubService {
79
error.status = res.status;
80
throw error;
81
}
82
- if (allowEmpty) return { accepted: true, status: res.status };
83
- if (!raw) return null;
82
+ if (!raw && allowEmpty) return null;
83
+ if (!raw) throw new Error(`${label} failed: empty response`);
84
if (parsed === null) throw new Error(`${label} failed: invalid JSON response`);
85
return parsed;
86
}
87
88
async requestText(url, label, { maxChars = 12000 } = {}) {
89
- const res = await fetch(url, { method: 'GET', headers: this.getHeaders() });
89
+ const res = await fetch(url, { headers: this.getHeaders() });
90
const raw = await res.text();
91
- if (!res.ok) {
92
- const detail = raw ? ` ${raw.slice(0, 240)}` : '';
93
- throw new Error(`${label} failed: ${res.status}${detail}`);
94
- }
95
- const limit = Math.max(1, Math.min(20000, Number(maxChars) || 12000));
96
- return { text: raw.length > limit ? raw.slice(-limit) : raw, truncated: raw.length > limit };
97
- }
98
-
99
- repoUrl(repo, suffix = '') {
100
- return `${this.baseUrl}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(repo)}${suffix}`;
101
- }
102
-
103
- repositoryLookupUrl(repoRef) {
104
- const value = String(repoRef || '');
105
- return /^\d+$/.test(value) ? `${this.baseUrl}/repositories/${value}` : this.repoUrl(value);
106
- }
107
-
108
- repositoryApiBase(fullName) {
109
- const parts = String(fullName || '').split('/').filter(Boolean);
110
- if (parts.length !== 2) throw new Error('GitHub repository full_name is invalid');
111
- return `${this.baseUrl}/repos/${parts.map(encodeURIComponent).join('/')}`;
91
+ if (!res.ok) throw new Error(`${label} failed: ${res.status} ${raw.slice(0, 240)}`);
92
+ return raw.slice(0, maxChars);
93
}
94
95
async getRepositoryContext(repoRef) {
115
- const value = String(repoRef || '');
116
- try {
117
- const raw = await this.requestJson(this.repositoryLookupUrl(value), 'GitHub repository');
118
- return { raw, apiBase: this.repositoryApiBase(raw.full_name) };
119
- } catch (error) {
120
- if (!/^\d+$/.test(value) || error?.status !== 404) throw error;
121
-
122
- const repositories = await this.listRepositories();
123
- const match = repositories.find(repo => repo.id === value);
124
- if (!match?.fullName) throw error;
125
-
126
- const apiBase = this.repositoryApiBase(match.fullName);
127
- const raw = await this.requestJson(apiBase, 'GitHub repository');
128
- return { raw, apiBase: this.repositoryApiBase(raw.full_name) };
129
- }
96
+ const value = String(repoRef || '').trim();
97
+ if (!value) throw new Error('GitHub repository is required');
98
+ const [owner, repo] = value.includes('/') ? value.split('/') : [this.owner, value];
99
+ if (!owner || !repo) throw new Error('Invalid GitHub repository');
100
+ const apiBase = `${this.baseUrl}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
101
+ const raw = await this.requestJson(apiBase, 'GitHub repository');
102
+ return { raw, apiBase, owner, repo };
103
}
104
132
- mapRepository(r) {
133
- return {
134
- id: String(r.id ?? r.name), name: r.name, fullName: r.full_name, private: !!r.private,
135
- description: r.description || '', defaultBranch: r.default_branch || 'main', archived: !!r.archived,
136
- htmlUrl: r.html_url || '', stars: r.stargazers_count ?? 0, forks: r.forks_count ?? 0
137
- };
105
+ mapPullRequestFile(file) {
106
+ return { filename: file.filename || '', status: file.status || '', additions: file.additions ?? 0, deletions: file.deletions ?? 0, changes: file.changes ?? 0, patch: boundedPatch(file.patch) };
107
}
108
140
- mapWorkflowRun(run = {}) {
141
- return {
142
- id: run.id, name: run.name || 'Workflow', status: run.status || '', conclusion: run.conclusion || null,
143
- event: run.event || '', branch: run.head_branch || '', sha: String(run.head_sha || '').slice(0, 7),
144
- runNumber: run.run_number ?? null, url: run.html_url || '', createdAt: run.created_at || '', updatedAt: run.updated_at || ''
145
- };
109
+ mapWorkflowRun(run) {
110
+ return { id: run.id, name: run.name || '', status: run.status || '', conclusion: run.conclusion || '', branch: run.head_branch || '', sha: run.head_sha || '', event: run.event || '', url: run.html_url || '', createdAt: run.created_at || '', updatedAt: run.updated_at || '' };
111
}
112
148
- mapWorkflowJob(job = {}) {
149
- return {
150
- id: job.id, name: job.name || 'Job', status: job.status || '', conclusion: job.conclusion || null,
151
- startedAt: job.started_at || '', completedAt: job.completed_at || '', url: job.html_url || '',
152
- steps: (job.steps || []).slice(0, 30).map(step => ({
153
- number: step.number, name: step.name || 'Step', status: step.status || '', conclusion: step.conclusion || null
154
- }))
155
- };
156
- }
157
-
158
- mapPullRequestFile(file = {}) {
159
- return {
160
- filename: file.filename || '', status: file.status || '', additions: file.additions ?? 0,
161
- deletions: file.deletions ?? 0, changes: file.changes ?? 0, patch: boundedPatch(file.patch)
162
- };
113
+ mapWorkflowJob(job) {
114
+ return { id: job.id, name: job.name || '', status: job.status || '', conclusion: job.conclusion || '', url: job.html_url || '', startedAt: job.started_at || '', completedAt: job.completed_at || '', steps: (job.steps || []).map(step => ({ name: step.name || '', status: step.status || '', conclusion: step.conclusion || '', number: step.number })) };
115
}
116
165
- mapIssue(issue = {}) {
166
- return {
167
- number: issue.number,
168
- title: issue.title || '',
169
- state: issue.state || '',
170
- author: issue.user?.login || 'unknown',
171
- comments: issue.comments ?? 0,
172
- url: issue.html_url || ''
173
- };
117
+ mapIssue(issue) {
118
+ return { number: issue.number, title: issue.title || '', state: issue.state || '', author: issue.user?.login || 'unknown', comments: issue.comments ?? 0, url: issue.html_url || '' };
119
}
120
121
async listRepositories() {
177
- const data = await this.requestJson(`${this.baseUrl}/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member`, 'GitHub repositories');
178
- return data.map(r => { const repo = this.mapRepository(r); return { ...repo, title: `${repo.name} ${repo.private ? '🔒' : '🌐'}` }; });
122
+ const data = await this.requestJson(`${this.baseUrl}/user/repos?sort=updated&per_page=100&affiliation=owner,collaborator,organization_member`, 'GitHub repositories');
123
+ return data.map(repo => ({ name: repo.name, fullName: repo.full_name, private: !!repo.private, defaultBranch: repo.default_branch || 'main', updatedAt: repo.updated_at || '', language: repo.language || '', url: repo.html_url || '' }));
124
}
125
126
async getRepository(repoRef) {
127
const { raw } = await this.getRepositoryContext(repoRef);
183
- return this.mapRepository(raw);
128
+ return { name: raw.name, fullName: raw.full_name, private: !!raw.private, defaultBranch: raw.default_branch || 'main', description: raw.description || '', updatedAt: raw.updated_at || '', language: raw.language || '', stars: raw.stargazers_count || 0, forks: raw.forks_count || 0, openIssues: raw.open_issues_count || 0, url: raw.html_url || '' };
129
}
130
186
- async listPullRequests(repoRef, { perPage = 10, page = 1 } = {}) {
187
- const count = clampPerPage(perPage, 10);
188
- const pageNumber = clampPage(page);
189
- const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
131
+ async listFiles(repoRef, path = '', ref = '') {
132
const { apiBase } = await this.getRepositoryContext(repoRef);
191
- const data = await this.requestJson(`${apiBase}/pulls?state=all&per_page=${count}${pageQuery}`, 'GitHub pull requests');
192
- return data.map(pr => ({
193
- number: pr.number, title: pr.title, author: pr.user?.login || 'unknown', state: pr.state,
194
- merged: !!pr.merged_at, createdAt: pr.created_at, url: pr.html_url
195
- }));
133
+ const suffix = path ? `/${encodedPath(path)}` : '';
134
+ const query = ref ? `?ref=${encodeURIComponent(ref)}` : '';
135
+ const data = await this.requestJson(`${apiBase}/contents${suffix}${query}`, 'GitHub files');
136
+ const items = Array.isArray(data) ? data : [data];
137
+ return items.map(item => ({ name: item.name, path: item.path, type: item.type, size: item.size ?? 0, sha: item.sha || '', url: item.html_url || '' }));
138
}
139
198
- async getPullRequest(repoRef, prNumber) {
199
- const number = numericId(prNumber, 'pull request');
140
+ async getFile(repoRef, filePath, ref = '') {
141
const { apiBase } = await this.getRepositoryContext(repoRef);
201
- const pr = await this.requestJson(`${apiBase}/pulls/${number}`, 'GitHub pull request');
202
- return {
203
- number: pr.number, title: pr.title || '', author: pr.user?.login || 'unknown', state: pr.state || '',
204
- merged: !!(pr.merged ?? pr.merged_at), body: pr.body || '', url: pr.html_url || '', head: pr.head?.ref || '',
205
- headSha: pr.head?.sha || '', base: pr.base?.ref || '', additions: pr.additions ?? 0,
206
- deletions: pr.deletions ?? 0, changedFiles: pr.changed_files ?? 0
207
- };
142
+ const query = ref ? `?ref=${encodeURIComponent(ref)}` : '';
143
+ const data = await this.requestJson(`${apiBase}/contents/${encodedPath(filePath)}${query}`, 'GitHub file');
144
+ if (data.type !== 'file') throw new Error('GitHub path is not a file');
145
+ return { name: data.name, path: data.path, size: data.size ?? 0, sha: data.sha || '', encoding: data.encoding || '', content: data.content || '', url: data.html_url || '' };
146
}
147
210
- async listPullRequestFiles(repoRef, prNumber, { perPage = 20, page = 1 } = {}) {
211
- const number = numericId(prNumber, 'pull request');
212
- const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
213
- const { apiBase } = await this.getRepositoryContext(repoRef);
214
- const data = await this.requestJson(`${apiBase}/pulls/${number}/files?per_page=${count}&page=${pageNumber}`, 'GitHub pull request files');
215
- return data.map(file => this.mapPullRequestFile(file));
148
+ async listCommits(repoRef, { perPage = 10, page = 1 } = {}) {
149
+ const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
150
+ const data = await this.requestJson(`${apiBase}/commits?per_page=${count}&page=${pageNumber}`, 'GitHub commits');
151
+ return data.map(commit => ({ sha: commit.sha || '', message: commit.commit?.message || '', author: commit.author?.login || commit.commit?.author?.name || 'unknown', date: commit.commit?.author?.date || '', url: commit.html_url || '' }));
152
}
153
218
- async listCommits(repoRef) {
219
- const { apiBase } = await this.getRepositoryContext(repoRef);
220
- const data = await this.requestJson(`${apiBase}/commits?per_page=5`, 'GitHub commits');
221
- return data.map(c => ({
222
- sha: String(c.sha || '').slice(0, 7),
223
- fullSha: String(c.sha || ''),
224
- message: String(c.commit?.message || '').split('\n')[0],
225
- author: c.author?.login || c.commit?.author?.name || 'Unknown',
226
- date: c.commit?.author?.date ? c.commit.author.date.slice(0, 10) : ''
227
- }));
154
+ async getCommit(repoRef, sha) {
155
+ const commitSha = fullSha(sha); const { apiBase } = await this.getRepositoryContext(repoRef);
156
+ const data = await this.requestJson(`${apiBase}/commits/${commitSha}`, 'GitHub commit');
157
+ return { sha: data.sha || '', message: data.commit?.message || '', author: data.author?.login || data.commit?.author?.name || 'unknown', date: data.commit?.author?.date || '', url: data.html_url || '', files: (data.files || []).slice(0, 20).map(file => this.mapPullRequestFile(file)) };
158
}
159
230
- async getCommit(repoRef, sha) {
231
- const commitSha = fullSha(sha);
232
- const { apiBase } = await this.getRepositoryContext(repoRef);
233
- const c = await this.requestJson(`${apiBase}/commits/${commitSha}`, 'GitHub commit');
234
- const files = (c.files || []).slice(0, 20).map(file => ({
235
- filename: file.filename || '',
236
- status: file.status || '',
237
- additions: file.additions ?? 0,
238
- deletions: file.deletions ?? 0,
239
- changes: file.changes ?? 0
240
- }));
241
- return {
242
- sha: commitSha,
243
- shortSha: commitSha.slice(0, 7),
244
- message: String(c.commit?.message || ''),
245
- author: c.author?.login || c.commit?.author?.name || 'Unknown',
246
- date: c.commit?.author?.date || '',
247
- additions: c.stats?.additions ?? 0,
248
- deletions: c.stats?.deletions ?? 0,
249
- changedFiles: files.length,
250
- files
251
- };
160
+ async listPullRequests(repoRef, { perPage = 10, page = 1, state = 'all' } = {}) {
161
+ const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const safeState = ['open', 'closed', 'all'].includes(state) ? state : 'all'; const { apiBase } = await this.getRepositoryContext(repoRef);
162
+ const data = await this.requestJson(`${apiBase}/pulls?state=${safeState}&per_page=${count}&page=${pageNumber}`, 'GitHub pull requests');
163
+ return data.map(pr => ({ number: pr.number, title: pr.title || '', state: pr.state || '', draft: !!pr.draft, author: pr.user?.login || 'unknown', head: pr.head?.ref || '', headSha: pr.head?.sha || '', base: pr.base?.ref || '', mergedAt: pr.merged_at || '', url: pr.html_url || '' }));
164
}
165
254
- async listCommitChecks(repoRef, sha, { perPage = 20, page = 1 } = {}) {
255
- const commitSha = fullSha(sha); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
256
- const { apiBase } = await this.getRepositoryContext(repoRef);
257
- const data = await this.requestJson(`${apiBase}/commits/${commitSha}/check-runs?per_page=${count}&page=${pageNumber}`, 'GitHub check runs');
258
- return (data.check_runs || []).map(check => ({ id: check.id, name: check.name || 'Check', status: check.status || '', conclusion: check.conclusion || null, url: check.html_url || '' }));
166
+ async getPullRequest(repoRef, prNumber) {
167
+ const number = numericId(prNumber, 'pull request'); const { apiBase } = await this.getRepositoryContext(repoRef);
168
+ const pr = await this.requestJson(`${apiBase}/pulls/${number}`, 'GitHub pull request');
169
+ return { number: pr.number, title: pr.title || '', state: pr.state || '', draft: !!pr.draft, merged: !!pr.merged, mergeable: pr.mergeable, mergeableState: pr.mergeable_state || '', author: pr.user?.login || 'unknown', head: pr.head?.ref || '', headSha: pr.head?.sha || '', base: pr.base?.ref || '', additions: pr.additions ?? 0, deletions: pr.deletions ?? 0, changedFiles: pr.changed_files ?? 0, commits: pr.commits ?? 0, url: pr.html_url || '' };
170
}
171
261
- async listFiles(repoRef, path = '', { ref } = {}) {
262
- const { apiBase } = await this.getRepositoryContext(repoRef);
263
- const suffix = path ? `/contents/${encodedPath(path)}` : '/contents';
264
- const query = ref ? `?ref=${encodeURIComponent(String(ref))}` : '';
265
- const data = await this.requestJson(`${apiBase}${suffix}${query}`, 'GitHub contents');
266
- if (!Array.isArray(data)) throw new Error('GitHub contents response is not a directory listing');
267
- return data.map(item => ({ name: item.name, path: item.path, type: item.type === 'dir' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || '' }));
172
+ async listPullRequestFiles(repoRef, prNumber, { perPage = 20, page = 1 } = {}) {
173
+ const number = numericId(prNumber, 'pull request'); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
174
+ const data = await this.requestJson(`${apiBase}/pulls/${number}/files?per_page=${count}&page=${pageNumber}`, 'GitHub pull request files');
175
+ return data.map(file => this.mapPullRequestFile(file));
176
}
177
270
- async getGitRef(repoRef, branch, { allowMissing = false } = {}) {
271
- const branchName = gitBranch(branch);
178
+ async getPullRequestChecks(repoRef, prNumber) {
179
+ const pr = await this.getPullRequest(repoRef, prNumber);
180
const { apiBase } = await this.getRepositoryContext(repoRef);
273
- const data = await this.requestJson(
274
- `${apiBase}/git/ref/heads/${encodedBranch(branchName)}`,
275
- 'GitHub branch ref',
276
- { allowNotFound: allowMissing }
277
- );
278
- if (data === null) return null;
279
- return { branch: branchName, sha: fullSha(data?.object?.sha, 'Git branch head') };
181
+ const data = await this.requestJson(`${apiBase}/commits/${fullSha(pr.headSha)}/check-runs?per_page=50`, 'GitHub pull request checks');
182
+ return (data.check_runs || []).map(check => ({ name: check.name || '', status: check.status || '', conclusion: check.conclusion || '', url: check.html_url || '' }));
183
}
184
282
- async getBranchSnapshot(repoRef, branch) {
283
- const branchName = gitBranch(branch);
284
- const { apiBase } = await this.getRepositoryContext(repoRef);
285
- const ref = await this.requestJson(`${apiBase}/git/ref/heads/${encodedBranch(branchName)}`, 'GitHub branch ref');
286
- const headSha = fullSha(ref?.object?.sha, 'Git branch head');
287
- const commit = await this.requestJson(`${apiBase}/git/commits/${headSha}`, 'GitHub branch commit');
288
- const treeSha = fullSha(commit?.tree?.sha, 'Git tree');
289
- return { branch: branchName, headSha, treeSha };
185
+ async getBranchHead(repoRef, branch) {
186
+ const branchName = gitBranch(branch); const { apiBase } = await this.getRepositoryContext(repoRef);
187
+ const data = await this.requestJson(`${apiBase}/git/ref/heads/${encodedBranch(branchName)}`, 'GitHub branch head');
188
+ return { branch: branchName, sha: fullSha(data?.object?.sha, 'Git branch head') };
189
}
190
292
- async getFileAtRef(repoRef, path, ref) {
293
- const filePath = String(path || '');
294
- if (!filePath || filePath.startsWith('/') || filePath.includes('\0')) throw new Error('Invalid GitHub file path');
295
- const commitRef = fullSha(ref);
296
- const { apiBase } = await this.getRepositoryContext(repoRef);
297
- const data = await this.requestJson(`${apiBase}/contents/${encodedPath(filePath)}?ref=${commitRef}`, 'GitHub file');
298
- if (!data || Array.isArray(data) || data.type !== 'file') throw new Error('GitHub contents response is not a file');
299
- if (data.encoding !== 'base64') throw new Error('GitHub file encoding is not supported');
300
- const content = decodeBase64Utf8(data.content || '');
301
- return {
302
- path: data.path || filePath,
303
- sha: String(data.sha || ''),
304
- size: Number(data.size) || 0,
305
- encoding: 'utf-8',
306
- content
307
- };
191
+ async getGitCommit(repoRef, sha) {
192
+ const commitSha = fullSha(sha); const { apiBase } = await this.getRepositoryContext(repoRef);
193
+ const data = await this.requestJson(`${apiBase}/git/commits/${commitSha}`, 'GitHub git commit');
194
+ return { sha: fullSha(data?.sha, 'Git commit'), treeSha: fullSha(data?.tree?.sha, 'Git tree'), message: data?.message || '' };
195
}
196
197
async createGitBlob(repoRef, text) {
198
const { apiBase } = await this.getRepositoryContext(repoRef);
312
- const data = await this.requestJson(`${apiBase}/git/blobs`, 'GitHub create blob', {
313
- method: 'POST',
314
- body: { content: String(text ?? ''), encoding: 'utf-8' }
315
- });
199
+ const data = await this.requestJson(`${apiBase}/git/blobs`, 'GitHub create blob', { method: 'POST', body: { content: String(text ?? ''), encoding: 'utf-8' } });
200
return { sha: fullSha(data?.sha, 'Git blob') };
201
}
202
@@ -326,10 +210,7 @@ export class GitHubService {
210
return { path, mode: '100644', type: 'blob', sha: fullSha(entry.sha, 'Git blob') };
211
});
212
const { apiBase } = await this.getRepositoryContext(repoRef);
329
- const data = await this.requestJson(`${apiBase}/git/trees`, 'GitHub create tree', {
330
- method: 'POST',
331
- body: { base_tree: base, tree }
332
- });
213
+ const data = await this.requestJson(`${apiBase}/git/trees`, 'GitHub create tree', { method: 'POST', body: { base_tree: base, tree } });
214
return { sha: fullSha(data?.sha, 'Git tree') };
215
}
216
@@ -342,154 +223,63 @@ export class GitHubService {
223
if (Number.isNaN(date.getTime()) || date.toISOString() !== String(timestamp)) throw new Error('Invalid Git commit timestamp');
224
const identity = { name: 'Nexa Dev Bot', email: 'nexa-dev-bot@users.noreply.github.com', date: String(timestamp) };
225
const { apiBase } = await this.getRepositoryContext(repoRef);
345
- const data = await this.requestJson(`${apiBase}/git/commits`, 'GitHub create commit', {
346
- method: 'POST',
347
- body: { message: commitMessage, tree, parents: [parent], author: identity, committer: identity }
348
- });
226
+ const data = await this.requestJson(`${apiBase}/git/commits`, 'GitHub create commit', { method: 'POST', body: { message: commitMessage, tree, parents: [parent], author: identity, committer: identity } });
227
return { sha: fullSha(data?.sha, 'Git commit') };
228
}
229
230
async createGitBranchRef(repoRef, { branch, sha } = {}) {
353
- const branchName = gitBranch(branch);
354
- const commitSha = fullSha(sha, 'Git commit');
355
- const { apiBase } = await this.getRepositoryContext(repoRef);
356
- const data = await this.requestJson(`${apiBase}/git/refs`, 'GitHub create branch ref', {
357
- method: 'POST',
358
- body: { ref: `refs/heads/${branchName}`, sha: commitSha }
359
- });
360
- return {
361
- ref: String(data?.ref || `refs/heads/${branchName}`),
362
- sha: fullSha(data?.object?.sha || commitSha, 'Git commit')
363
- };
231
+ const branchName = gitBranch(branch); const commitSha = fullSha(sha, 'Git commit'); const { apiBase } = await this.getRepositoryContext(repoRef);
232
+ const data = await this.requestJson(`${apiBase}/git/refs`, 'GitHub create branch ref', { method: 'POST', body: { ref: `refs/heads/${branchName}`, sha: commitSha } });
233
+ return { ref: String(data?.ref || `refs/heads/${branchName}`), sha: fullSha(data?.object?.sha || commitSha, 'Git commit') };
234
}
235
236
async listTree(repoRef, sha) {
237
if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git tree SHA');
368
- const { apiBase } = await this.getRepositoryContext(repoRef);
369
- const data = await this.requestJson(`${apiBase}/git/trees/${encodeURIComponent(sha)}`, 'GitHub tree');
370
- return (data.tree || []).filter(item => item.type === 'tree' || item.type === 'blob').map(item => ({
371
- name: item.path, path: item.path, type: item.type === 'tree' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || ''
372
- }));
238
+ const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/trees/${encodeURIComponent(sha)}`, 'GitHub tree');
239
+ return (data.tree || []).filter(item => item.type === 'tree' || item.type === 'blob').map(item => ({ name: item.path, path: item.path, type: item.type === 'tree' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || '' }));
240
}
241
242
async getBlob(repoRef, sha) {
243
if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git blob SHA');
377
- const { apiBase } = await this.getRepositoryContext(repoRef);
378
- const data = await this.requestJson(`${apiBase}/git/blobs/${encodeURIComponent(sha)}`, 'GitHub blob');
244
+ const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/blobs/${encodeURIComponent(sha)}`, 'GitHub blob');
245
return { encoding: data.encoding || '', size: data.size ?? 0, content: data.content || '' };
246
}
247
248
async getRepoStatus(repoRef) {
383
- const { raw, apiBase } = await this.getRepositoryContext(repoRef);
384
- const runsData = await this.requestJson(`${apiBase}/actions/runs?per_page=3`, 'GitHub Actions runs');
385
- const runs = runsData.workflow_runs || [];
386
- return {
387
- repo: String(repoRef), repoName: raw.name, defaultBranch: raw.default_branch || 'main',
388
- lastRuns: runs.map(r => ({ name: r.name, status: r.status, conclusion: r.conclusion, commit: r.head_commit?.message?.slice(0, 80) || '', url: r.html_url || '' }))
389
- };
249
+ const { raw, apiBase } = await this.getRepositoryContext(repoRef); const runsData = await this.requestJson(`${apiBase}/actions/runs?per_page=3`, 'GitHub Actions runs'); const runs = runsData.workflow_runs || [];
250
+ return { repo: String(repoRef), repoName: raw.name, defaultBranch: raw.default_branch || 'main', lastRuns: runs.map(r => ({ name: r.name, status: r.status, conclusion: r.conclusion, commit: r.head_commit?.message?.slice(0, 80) || '', url: r.html_url || '' })) };
251
}
252
253
async listWorkflowRuns(repoRef, { perPage = 10, page = 1 } = {}) {
393
- const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page);
394
- const { apiBase } = await this.getRepositoryContext(repoRef);
395
- const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
254
+ const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
255
const data = await this.requestJson(`${apiBase}/actions/runs?per_page=${count}${pageQuery}`, 'GitHub workflow runs');
256
return (data.workflow_runs || []).map(run => this.mapWorkflowRun(run));
257
}
258
400
- async getWorkflowRun(repoRef, runId) {
401
- const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
402
- return this.mapWorkflowRun(await this.requestJson(`${apiBase}/actions/runs/${id}`, 'GitHub workflow run'));
403
- }
404
-
405
- async listWorkflowJobs(repoRef, runId) {
406
- const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
407
- const data = await this.requestJson(`${apiBase}/actions/runs/${id}/jobs?per_page=20`, 'GitHub workflow jobs');
408
- return (data.jobs || []).map(job => this.mapWorkflowJob(job));
409
- }
410
-
411
- async getWorkflowJob(repoRef, jobId) {
412
- const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef);
413
- return this.mapWorkflowJob(await this.requestJson(`${apiBase}/actions/jobs/${id}`, 'GitHub workflow job'));
414
- }
415
-
416
- async getWorkflowJobLog(repoRef, jobId, { maxChars = 12000 } = {}) {
417
- const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef);
418
- return this.requestText(`${apiBase}/actions/jobs/${id}/logs`, 'GitHub workflow job log', { maxChars });
419
- }
420
-
421
- async listWorkflowArtifacts(repoRef, runId, { perPage = 20, page = 1 } = {}) {
422
- const id = numericId(runId, 'workflow run'); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
423
- const { apiBase } = await this.getRepositoryContext(repoRef);
424
- const data = await this.requestJson(`${apiBase}/actions/runs/${id}/artifacts?per_page=${count}&page=${pageNumber}`, 'GitHub workflow artifacts');
425
- return (data.artifacts || []).map(artifact => ({
426
- id: artifact.id, name: artifact.name || 'Artifact', size: artifact.size_in_bytes ?? 0, expired: !!artifact.expired,
427
- createdAt: artifact.created_at || '', expiresAt: artifact.expires_at || '', downloadUrl: artifact.archive_download_url || ''
428
- }));
429
- }
430
-
431
- async listBranches(repoRef, { perPage = 20, page = 1 } = {}) {
432
- const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
433
- const data = await this.requestJson(`${apiBase}/branches?per_page=${count}&page=${pageNumber}`, 'GitHub branches');
434
- return data.map(branch => ({ name: branch.name || '', sha: branch.commit?.sha || '', protected: !!branch.protected }));
435
- }
436
-
437
- async compareWithDefault(repoRef, headSha) {
438
- const head = fullSha(headSha); const { raw, apiBase } = await this.getRepositoryContext(repoRef); const base = raw.default_branch || 'main';
439
- const data = await this.requestJson(`${apiBase}/compare/${encodeURIComponent(base)}...${head}`, 'GitHub compare');
440
- return {
441
- base, head, status: data.status || '', aheadBy: data.ahead_by ?? 0, behindBy: data.behind_by ?? 0,
442
- totalCommits: data.total_commits ?? 0, baseSha: data.base_commit?.sha || '', mergeBaseSha: data.merge_base_commit?.sha || '',
443
- files: (data.files || []).slice(0, 20).map(file => this.mapPullRequestFile(file))
444
- };
445
- }
446
-
447
- async listIssues(repoRef, { perPage = 10, page = 1 } = {}) {
448
- const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
449
- const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=${count}&page=${pageNumber}`, 'GitHub issues');
450
- return data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue));
451
- }
452
-
453
- async listIssuesPage(repoRef, { page = 1 } = {}) {
454
- const pageNumber = clampPage(page);
455
- const { apiBase } = await this.getRepositoryContext(repoRef);
456
- const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=20&page=${pageNumber}`, 'GitHub issues');
457
- return {
458
- items: data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue)),
459
- hasMore: data.length === 20
460
- };
461
- }
462
-
463
- async getIssue(repoRef, issueNumber) {
464
- const number = numericId(issueNumber, 'issue');
465
- const { apiBase } = await this.getRepositoryContext(repoRef);
466
- const issue = await this.requestJson(apiBase + '/issues/' + number, 'GitHub issue');
467
- return { ...this.mapIssue(issue), body: issue.body || '', labels: (issue.labels || []).map(label => typeof label === 'string' ? label : label.name).filter(Boolean), assignees: (issue.assignees || []).map(user => user.login).filter(Boolean), createdAt: issue.created_at || '', updatedAt: issue.updated_at || '' };
468
- }
469
-
470
- async listReleases(repoRef, { perPage = 10, page = 1 } = {}) {
471
- const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
472
- const data = await this.requestJson(`${apiBase}/releases?per_page=${count}&page=${pageNumber}`, 'GitHub releases');
473
- return data.map(release => ({
474
- id: release.id, tag: release.tag_name || '', name: release.name || release.tag_name || 'Release', draft: !!release.draft,
475
- prerelease: !!release.prerelease, publishedAt: release.published_at || release.created_at || '', url: release.html_url || ''
476
- }));
477
- }
478
-
479
- async getRelease(repoRef, releaseId) {
480
- const id = numericId(releaseId, 'release');
259
+ async getWorkflowRun(repoRef, runId) { const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.mapWorkflowRun(await this.requestJson(`${apiBase}/actions/runs/${id}`, 'GitHub workflow run')); }
260
+ async listWorkflowJobs(repoRef, runId) { const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/actions/runs/${id}/jobs?per_page=20`, 'GitHub workflow jobs'); return (data.jobs || []).map(job => this.mapWorkflowJob(job)); }
261
+ async getWorkflowJob(repoRef, jobId) { const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.mapWorkflowJob(await this.requestJson(`${apiBase}/actions/jobs/${id}`, 'GitHub workflow job')); }
262
+ async getWorkflowJobLog(repoRef, jobId, { maxChars = 12000 } = {}) { const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.requestText(`${apiBase}/actions/jobs/${id}/logs`, 'GitHub workflow job log', { maxChars }); }
263
+ async listWorkflowArtifacts(repoRef, runId, { perPage = 20, page = 1 } = {}) { const id = numericId(runId, 'workflow run'); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/actions/runs/${id}/artifacts?per_page=${count}&page=${pageNumber}`, 'GitHub workflow artifacts'); return (data.artifacts || []).map(artifact => ({ id: artifact.id, name: artifact.name || 'Artifact', size: artifact.size_in_bytes ?? 0, expired: !!artifact.expired, createdAt: artifact.created_at || '', expiresAt: artifact.expires_at || '', downloadUrl: artifact.archive_download_url || '' })); }
264
+ async listBranches(repoRef, { perPage = 20, page = 1 } = {}) { const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/branches?per_page=${count}&page=${pageNumber}`, 'GitHub branches'); return data.map(branch => ({ name: branch.name || '', sha: branch.commit?.sha || '', protected: !!branch.protected })); }
265
+ async compareWithDefault(repoRef, headSha) { const head = fullSha(headSha); const { raw, apiBase } = await this.getRepositoryContext(repoRef); const base = raw.default_branch || 'main'; const data = await this.requestJson(`${apiBase}/compare/${encodeURIComponent(base)}...${head}`, 'GitHub compare'); return { base, head, status: data.status || '', aheadBy: data.ahead_by ?? 0, behindBy: data.behind_by ?? 0, totalCommits: data.total_commits ?? 0, baseSha: data.base_commit?.sha || '', mergeBaseSha: data.merge_base_commit?.sha || '', files: (data.files || []).slice(0, 20).map(file => this.mapPullRequestFile(file)) }; }
266
+ async listIssues(repoRef, { perPage = 10, page = 1 } = {}) { const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=${count}&page=${pageNumber}`, 'GitHub issues'); return data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue)); }
267
+ async listIssuesPage(repoRef, { page = 1 } = {}) { const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=20&page=${pageNumber}`, 'GitHub issues'); return { items: data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue)), hasMore: data.length === 20 }; }
268
+ async getIssue(repoRef, issueNumber) { const number = numericId(issueNumber, 'issue'); const { apiBase } = await this.getRepositoryContext(repoRef); const issue = await this.requestJson(apiBase + '/issues/' + number, 'GitHub issue'); return { ...this.mapIssue(issue), body: issue.body || '', labels: (issue.labels || []).map(label => typeof label === 'string' ? label : label.name).filter(Boolean), assignees: (issue.assignees || []).map(user => user.login).filter(Boolean), createdAt: issue.created_at || '', updatedAt: issue.updated_at || '' }; }
269
+ async listReleases(repoRef, { perPage = 10, page = 1 } = {}) { const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/releases?per_page=${count}&page=${pageNumber}`, 'GitHub releases'); return data.map(release => ({ id: release.id, tag: release.tag_name || '', name: release.name || release.tag_name || 'Release', draft: !!release.draft, prerelease: !!release.prerelease, publishedAt: release.published_at || release.created_at || '', url: release.html_url || '' })); }
270
+ async getRelease(repoRef, releaseId) { const id = numericId(releaseId, 'release'); const { apiBase } = await this.getRepositoryContext(repoRef); const release = await this.requestJson(apiBase + '/releases/' + id, 'GitHub release'); return { id: release.id, tag: release.tag_name || '', name: release.name || release.tag_name || 'Release', body: release.body || '', draft: !!release.draft, prerelease: !!release.prerelease, publishedAt: release.published_at || release.created_at || '', author: release.author?.login || 'unknown', target: release.target_commitish || '', url: release.html_url || '' }; }
271
+
272
+ async mergePullRequest(repoRef, prNumber, { expectedHeadSha, mergeMethod = 'squash' } = {}) {
273
+ const number = numericId(prNumber, 'pull request');
274
+ const expected = fullSha(expectedHeadSha, 'expected pull request head');
275
+ const method = String(mergeMethod || 'squash');
276
+ if (!['merge', 'squash', 'rebase'].includes(method)) throw new Error('Unsupported merge method');
277
const { apiBase } = await this.getRepositoryContext(repoRef);
482
- const release = await this.requestJson(apiBase + '/releases/' + id, 'GitHub release');
483
- return { id: release.id, tag: release.tag_name || '', name: release.name || release.tag_name || 'Release', body: release.body || '', draft: !!release.draft, prerelease: !!release.prerelease, publishedAt: release.published_at || release.created_at || '', author: release.author?.login || 'unknown', target: release.target_commitish || '', url: release.html_url || '' };
278
+ const data = await this.requestJson(`${apiBase}/pulls/${number}/merge`, 'GitHub pull request merge', { method: 'PUT', body: { sha: expected, merge_method: method } });
279
+ if (!data?.merged) throw new Error(`GitHub pull request merge failed: ${String(data?.message || 'not merged').slice(0, 240)}`);
280
+ return { merged: true, sha: String(data.sha || ''), message: String(data.message || '') };
281
}
282
486
- async rerunFailedWorkflowRun(repoRef, runId) {
487
- const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
488
- return this.requestJson(`${apiBase}/actions/runs/${id}/rerun-failed-jobs`, 'GitHub rerun failed jobs', { method: 'POST', allowEmpty: true });
489
- }
490
-
491
- async cancelWorkflowRun(repoRef, runId) {
492
- const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
493
- return this.requestJson(`${apiBase}/actions/runs/${id}/cancel`, 'GitHub cancel workflow run', { method: 'POST', allowEmpty: true });
494
- }
283
+ async rerunFailedWorkflowRun(repoRef, runId) { const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.requestJson(`${apiBase}/actions/runs/${id}/rerun-failed-jobs`, 'GitHub rerun failed jobs', { method: 'POST', allowEmpty: true }); }
284
+ async cancelWorkflowRun(repoRef, runId) { const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef); return this.requestJson(`${apiBase}/actions/runs/${id}/cancel`, 'GitHub cancel workflow run', { method: 'POST', allowEmpty: true }); }
285
}