Personal Telegram developer console for GitHub

spec/repository-workspace-editor
audit/commit-drilldown audit/finalize-workspace-menu-security audit/ops-actionability audit/pr-menu-consolidation audit/status-menu-consolidation audit/telegram-menu-e2e audit/telegram-menu-e2e-wave2 chore/actions-node24-runtime cleanup/remove-diag design/cloudflare-ops-read docs/control-plane-2-7-design docs/guide-v2-1-sync docs/menu-audit-final-sync docs/phase2-acceptance-closeout docs/phase2-multifile-design feat/bootstrap-worker feat/cloudflare-ops-read feat/cp2-multifile-final feat/cp2-multifile-workspace feat/cp3-github-write-final feat/cp4-cloudflare-ops-final feat/cp5-cicd-control-plane feat/cp6-incident-manager feat/cp7-automation-engine feat/deep-file-browser feat/final-delivery-16-20 feat/github-advanced-read feat/in-app-guide-v2 feat/navigation-recovery-ux-v2 feat/ops-console-v2-1 feat/persistent-menu-code-input feat/phase2-multifile-workspace feat/phase2-multifile-workspace-v2 feat/plugin-foundation-v1 feat/safe-github-ops feat/self-register-webhook feat/studio-g0-foundation feat/telegram-main-inline-menu feat/telegram-pr-merge feat/ux-platform-8-12 feat/v3a-readonly-copilot feat/workspace-file-upload feature/mobile-repo-browser feature/multi-file-change-set fix/approval-expiry-feedback fix/callback-resilience-and-docs fix/ci-actions-pagination fix/cloudflare-fetch-binding fix/editor-request-body-cap fix/editor-safe-file-options fix/issues-permission-release-empty-ux fix/main-menu-callback-fallback fix/phase2-file-editor-selection fix/phase2-final-ux fix/phase2-workspace-ref-persistence fix/production-auto-deploy fix/provider-write-error-feedback fix/repository-id-navigation-fallback fix/repository-pr-navigation fix/telegram-callback-updates fix/telegram-runtime-diagnostics fix/workspace-editor-flow-v2 fix/workspace-recovery-validation hardening/ci-zero-test-telegram-token hardening/pr1-destructive-totp hardening/pr2-kill-switch main multifile-workspace nexa/edit-BwJEIIY3PW nexa/edit-IPHT8irO7b nexa/edit-b4Od3BIMYd p2-multifile phase2-20261005 phase2-20261005-a phase2-20261005-b phase2-20261005-c phase2-20261005-d phase2-20261005-e phase2-20261005-f phase2-20261005-g phase2-20261005-h phase2-20261005-i phase2-20261005-j phase2-20261005-k phase2-20261005-l phase2-20261005-m phase2-20261005-n phase2-20261005-o phase2-20261005-p phase2-20261005-q phase2-20261005-r phase2-20261005-s phase2-20261005-t phase2-20261005-u phase2-20261005-v phase2-20261005-w phase2-20261005-x phase2-20261005-y phase2-20261005-z phase2-acceptance-closeout phase2-add-file-hotfix phase2-change-set phase2-design-20261005 phase2-design-final phase2-implementation phase2-multifile-implementation phase2-multifile-spec phase2-spec-final phase2-workspace phase2/multifile-workspace plan/nexa-studio-v2-reviewed security/remove-telegram-setup spec/repository-workspace-editor v3a/multifile work/multifile
js 439 lines 21.3 KB
Raw
1 import { DEFAULT_CONFIG } from './config.js';
2
3 const clampPage = value => Math.max(1, Math.min(100, Number(value) || 1));
4 const clampPerPage = (value, fallback = 10) => Math.max(1, Math.min(20, Number(value) || fallback));
5 const boundedPatch = value => String(value || '').slice(0, 1200);
6 const numericId = (value, label) => {
7 const text = String(value ?? '');
8 if (!/^\d+$/.test(text)) throw new Error(`Invalid ${label} ID`);
9 return text;
10 };
11 const fullSha = (value, label = 'Git commit') => {
12 const text = String(value || '');
13 if (!/^[a-f0-9]{40}$/i.test(text)) throw new Error(`Invalid ${label} SHA`);
14 return text;
15 };
16 const gitBranch = value => {
17 const branch = String(value || '');
18 if (!branch || branch.includes('..') || branch.startsWith('/') || branch.endsWith('/') || branch.includes('\0')) {
19 throw new Error('Invalid Git branch');
20 }
21 return branch;
22 };
23 const encodedBranch = value => gitBranch(value).split('/').map(encodeURIComponent).join('/');
24 const encodedPath = value => String(value || '').split('/').filter(Boolean).map(encodeURIComponent).join('/');
25 const decodeBase64Utf8 = value => {
26 let binary;
27 try {
28 binary = atob(String(value || '').replace(/\s/g, ''));
29 } catch {
30 throw new Error('GitHub file content is not valid base64');
31 }
32 const bytes = Uint8Array.from(binary, char => char.charCodeAt(0));
33 try {
34 return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
35 } catch {
36 throw new Error('GitHub file content is not valid UTF-8 text');
37 }
38 };
39
40 export class GitHubService {
41 constructor(token = '', owner = DEFAULT_CONFIG.defaultOwner) {
42 this.token = token;
43 this.owner = owner;
44 this.baseUrl = 'https://api.github.com';
45 }
46
47 requireToken() {
48 if (!this.token) throw new Error('GITHUB_TOKEN is not configured');
49 }
50
51 getHeaders() {
52 this.requireToken();
53 return {
54 'User-Agent': 'Nexa-Dev-Bot-v1.1',
55 'Accept': 'application/vnd.github+json',
56 'Authorization': `Bearer ${this.token}`,
57 'X-GitHub-Api-Version': '2022-11-28'
58 };
59 }
60
61 async requestJson(url, label, { method = 'GET', body, allowEmpty = false, allowNotFound = false } = {}) {
62 const headers = this.getHeaders();
63 const options = { method, headers };
64 if (body !== undefined) {
65 options.body = JSON.stringify(body);
66 options.headers = { ...headers, 'Content-Type': 'application/json' };
67 }
68 const res = await fetch(url, options);
69 const raw = await res.text();
70 let parsed = null;
71 if (raw) {
72 try { parsed = JSON.parse(raw); } catch { parsed = null; }
73 }
74 if (!res.ok) {
75 if (allowNotFound && res.status === 404) return null;
76 const providerMessage = parsed?.message || raw.slice(0, 240);
77 const detail = providerMessage ? ` ${providerMessage}` : '';
78 throw new Error(`${label} failed: ${res.status}${detail}`);
79 }
80 if (allowEmpty) return { accepted: true, status: res.status };
81 if (!raw) return null;
82 if (parsed === null) throw new Error(`${label} failed: invalid JSON response`);
83 return parsed;
84 }
85
86 async requestText(url, label, { maxChars = 12000 } = {}) {
87 const res = await fetch(url, { method: 'GET', headers: this.getHeaders() });
88 const raw = await res.text();
89 if (!res.ok) {
90 const detail = raw ? ` ${raw.slice(0, 240)}` : '';
91 throw new Error(`${label} failed: ${res.status}${detail}`);
92 }
93 const limit = Math.max(1, Math.min(20000, Number(maxChars) || 12000));
94 return { text: raw.length > limit ? raw.slice(-limit) : raw, truncated: raw.length > limit };
95 }
96
97 repoUrl(repo, suffix = '') {
98 return `${this.baseUrl}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(repo)}${suffix}`;
99 }
100
101 repositoryLookupUrl(repoRef) {
102 const value = String(repoRef || '');
103 return /^\d+$/.test(value) ? `${this.baseUrl}/repositories/${value}` : this.repoUrl(value);
104 }
105
106 repositoryApiBase(fullName) {
107 const parts = String(fullName || '').split('/').filter(Boolean);
108 if (parts.length !== 2) throw new Error('GitHub repository full_name is invalid');
109 return `${this.baseUrl}/repos/${parts.map(encodeURIComponent).join('/')}`;
110 }
111
112 async getRepositoryContext(repoRef) {
113 const raw = await this.requestJson(this.repositoryLookupUrl(repoRef), 'GitHub repository');
114 return { raw, apiBase: this.repositoryApiBase(raw.full_name) };
115 }
116
117 mapRepository(r) {
118 return {
119 id: String(r.id ?? r.name), name: r.name, fullName: r.full_name, private: !!r.private,
120 description: r.description || '', defaultBranch: r.default_branch || 'main', archived: !!r.archived,
121 htmlUrl: r.html_url || '', stars: r.stargazers_count ?? 0, forks: r.forks_count ?? 0
122 };
123 }
124
125 mapWorkflowRun(run = {}) {
126 return {
127 id: run.id, name: run.name || 'Workflow', status: run.status || '', conclusion: run.conclusion || null,
128 event: run.event || '', branch: run.head_branch || '', sha: String(run.head_sha || '').slice(0, 7),
129 runNumber: run.run_number ?? null, url: run.html_url || '', createdAt: run.created_at || '', updatedAt: run.updated_at || ''
130 };
131 }
132
133 mapWorkflowJob(job = {}) {
134 return {
135 id: job.id, name: job.name || 'Job', status: job.status || '', conclusion: job.conclusion || null,
136 startedAt: job.started_at || '', completedAt: job.completed_at || '', url: job.html_url || '',
137 steps: (job.steps || []).slice(0, 30).map(step => ({
138 number: step.number, name: step.name || 'Step', status: step.status || '', conclusion: step.conclusion || null
139 }))
140 };
141 }
142
143 mapPullRequestFile(file = {}) {
144 return {
145 filename: file.filename || '', status: file.status || '', additions: file.additions ?? 0,
146 deletions: file.deletions ?? 0, changes: file.changes ?? 0, patch: boundedPatch(file.patch)
147 };
148 }
149
150 mapIssue(issue = {}) {
151 return {
152 number: issue.number,
153 title: issue.title || '',
154 state: issue.state || '',
155 author: issue.user?.login || 'unknown',
156 comments: issue.comments ?? 0,
157 url: issue.html_url || ''
158 };
159 }
160
161 async listRepositories() {
162 const data = await this.requestJson(`${this.baseUrl}/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member`, 'GitHub repositories');
163 return data.map(r => { const repo = this.mapRepository(r); return { ...repo, title: `${repo.name} ${repo.private ? '🔒' : '🌐'}` }; });
164 }
165
166 async getRepository(repoRef) {
167 const { raw } = await this.getRepositoryContext(repoRef);
168 return this.mapRepository(raw);
169 }
170
171 async listPullRequests(repoRef, { perPage = 10, page = 1 } = {}) {
172 const count = clampPerPage(perPage, 10);
173 const pageNumber = clampPage(page);
174 const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
175 const { apiBase } = await this.getRepositoryContext(repoRef);
176 const data = await this.requestJson(`${apiBase}/pulls?state=all&per_page=${count}${pageQuery}`, 'GitHub pull requests');
177 return data.map(pr => ({
178 number: pr.number, title: pr.title, author: pr.user?.login || 'unknown', state: pr.state,
179 merged: !!pr.merged_at, createdAt: pr.created_at, url: pr.html_url
180 }));
181 }
182
183 async getPullRequest(repoRef, prNumber) {
184 const number = numericId(prNumber, 'pull request');
185 const { apiBase } = await this.getRepositoryContext(repoRef);
186 const pr = await this.requestJson(`${apiBase}/pulls/${number}`, 'GitHub pull request');
187 return {
188 number: pr.number, title: pr.title || '', author: pr.user?.login || 'unknown', state: pr.state || '',
189 merged: !!(pr.merged ?? pr.merged_at), body: pr.body || '', url: pr.html_url || '', head: pr.head?.ref || '',
190 headSha: pr.head?.sha || '', base: pr.base?.ref || '', additions: pr.additions ?? 0,
191 deletions: pr.deletions ?? 0, changedFiles: pr.changed_files ?? 0
192 };
193 }
194
195 async listPullRequestFiles(repoRef, prNumber, { perPage = 20, page = 1 } = {}) {
196 const number = numericId(prNumber, 'pull request');
197 const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
198 const { apiBase } = await this.getRepositoryContext(repoRef);
199 const data = await this.requestJson(`${apiBase}/pulls/${number}/files?per_page=${count}&page=${pageNumber}`, 'GitHub pull request files');
200 return data.map(file => this.mapPullRequestFile(file));
201 }
202
203 async listCommits(repoRef) {
204 const { apiBase } = await this.getRepositoryContext(repoRef);
205 const data = await this.requestJson(`${apiBase}/commits?per_page=5`, 'GitHub commits');
206 return data.map(c => ({
207 sha: c.sha.slice(0, 7), message: String(c.commit?.message || '').split('\n')[0],
208 author: c.author?.login || c.commit?.author?.name || 'Unknown', date: c.commit?.author?.date ? c.commit.author.date.slice(0, 10) : ''
209 }));
210 }
211
212 async listCommitChecks(repoRef, sha, { perPage = 20, page = 1 } = {}) {
213 const commitSha = fullSha(sha); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
214 const { apiBase } = await this.getRepositoryContext(repoRef);
215 const data = await this.requestJson(`${apiBase}/commits/${commitSha}/check-runs?per_page=${count}&page=${pageNumber}`, 'GitHub check runs');
216 return (data.check_runs || []).map(check => ({ id: check.id, name: check.name || 'Check', status: check.status || '', conclusion: check.conclusion || null, url: check.html_url || '' }));
217 }
218
219 async listFiles(repoRef, path = '', { ref } = {}) {
220 const { apiBase } = await this.getRepositoryContext(repoRef);
221 const suffix = path ? `/contents/${encodedPath(path)}` : '/contents';
222 const query = ref ? `?ref=${encodeURIComponent(String(ref))}` : '';
223 const data = await this.requestJson(`${apiBase}${suffix}${query}`, 'GitHub contents');
224 if (!Array.isArray(data)) throw new Error('GitHub contents response is not a directory listing');
225 return data.map(item => ({ name: item.name, path: item.path, type: item.type === 'dir' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || '' }));
226 }
227
228 async getGitRef(repoRef, branch, { allowMissing = false } = {}) {
229 const branchName = gitBranch(branch);
230 const { apiBase } = await this.getRepositoryContext(repoRef);
231 const data = await this.requestJson(
232 `${apiBase}/git/ref/heads/${encodedBranch(branchName)}`,
233 'GitHub branch ref',
234 { allowNotFound: allowMissing }
235 );
236 if (data === null) return null;
237 return { branch: branchName, sha: fullSha(data?.object?.sha, 'Git branch head') };
238 }
239
240 async getBranchSnapshot(repoRef, branch) {
241 const branchName = gitBranch(branch);
242 const { apiBase } = await this.getRepositoryContext(repoRef);
243 const ref = await this.requestJson(`${apiBase}/git/ref/heads/${encodedBranch(branchName)}`, 'GitHub branch ref');
244 const headSha = fullSha(ref?.object?.sha, 'Git branch head');
245 const commit = await this.requestJson(`${apiBase}/git/commits/${headSha}`, 'GitHub branch commit');
246 const treeSha = fullSha(commit?.tree?.sha, 'Git tree');
247 return { branch: branchName, headSha, treeSha };
248 }
249
250 async getFileAtRef(repoRef, path, ref) {
251 const filePath = String(path || '');
252 if (!filePath || filePath.startsWith('/') || filePath.includes('\0')) throw new Error('Invalid GitHub file path');
253 const commitRef = fullSha(ref);
254 const { apiBase } = await this.getRepositoryContext(repoRef);
255 const data = await this.requestJson(`${apiBase}/contents/${encodedPath(filePath)}?ref=${commitRef}`, 'GitHub file');
256 if (!data || Array.isArray(data) || data.type !== 'file') throw new Error('GitHub contents response is not a file');
257 if (data.encoding !== 'base64') throw new Error('GitHub file encoding is not supported');
258 const content = decodeBase64Utf8(data.content || '');
259 return {
260 path: data.path || filePath,
261 sha: String(data.sha || ''),
262 size: Number(data.size) || 0,
263 encoding: 'utf-8',
264 content
265 };
266 }
267
268 async createGitBlob(repoRef, text) {
269 const { apiBase } = await this.getRepositoryContext(repoRef);
270 const data = await this.requestJson(`${apiBase}/git/blobs`, 'GitHub create blob', {
271 method: 'POST',
272 body: { content: String(text ?? ''), encoding: 'utf-8' }
273 });
274 return { sha: fullSha(data?.sha, 'Git blob') };
275 }
276
277 async createGitTree(repoRef, { baseTreeSha, entries } = {}) {
278 const base = fullSha(baseTreeSha, 'Git base tree');
279 if (!Array.isArray(entries)) throw new Error('Git tree entries are required');
280 const tree = entries.map(entry => {
281 const path = String(entry?.path || '');
282 if (!path || path.startsWith('/') || path.includes('\0')) throw new Error('Invalid Git tree path');
283 if (entry?.mode !== '100644' || entry?.type !== 'blob') throw new Error('Unsupported Git tree entry');
284 return { path, mode: '100644', type: 'blob', sha: fullSha(entry.sha, 'Git blob') };
285 });
286 const { apiBase } = await this.getRepositoryContext(repoRef);
287 const data = await this.requestJson(`${apiBase}/git/trees`, 'GitHub create tree', {
288 method: 'POST',
289 body: { base_tree: base, tree }
290 });
291 return { sha: fullSha(data?.sha, 'Git tree') };
292 }
293
294 async createGitCommit(repoRef, { message, treeSha, parentSha, timestamp } = {}) {
295 const commitMessage = String(message || '');
296 if (!commitMessage) throw new Error('Git commit message is required');
297 const tree = fullSha(treeSha, 'Git tree');
298 const parent = fullSha(parentSha, 'Git parent commit');
299 const date = new Date(String(timestamp || ''));
300 if (Number.isNaN(date.getTime()) || date.toISOString() !== String(timestamp)) throw new Error('Invalid Git commit timestamp');
301 const identity = { name: 'Nexa Dev Bot', email: 'nexa-dev-bot@users.noreply.github.com', date: String(timestamp) };
302 const { apiBase } = await this.getRepositoryContext(repoRef);
303 const data = await this.requestJson(`${apiBase}/git/commits`, 'GitHub create commit', {
304 method: 'POST',
305 body: { message: commitMessage, tree, parents: [parent], author: identity, committer: identity }
306 });
307 return { sha: fullSha(data?.sha, 'Git commit') };
308 }
309
310 async createGitBranchRef(repoRef, { branch, sha } = {}) {
311 const branchName = gitBranch(branch);
312 const commitSha = fullSha(sha, 'Git commit');
313 const { apiBase } = await this.getRepositoryContext(repoRef);
314 const data = await this.requestJson(`${apiBase}/git/refs`, 'GitHub create branch ref', {
315 method: 'POST',
316 body: { ref: `refs/heads/${branchName}`, sha: commitSha }
317 });
318 return {
319 ref: String(data?.ref || `refs/heads/${branchName}`),
320 sha: fullSha(data?.object?.sha || commitSha, 'Git commit')
321 };
322 }
323
324 async listTree(repoRef, sha) {
325 if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git tree SHA');
326 const { apiBase } = await this.getRepositoryContext(repoRef);
327 const data = await this.requestJson(`${apiBase}/git/trees/${encodeURIComponent(sha)}`, 'GitHub tree');
328 return (data.tree || []).filter(item => item.type === 'tree' || item.type === 'blob').map(item => ({
329 name: item.path, path: item.path, type: item.type === 'tree' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || ''
330 }));
331 }
332
333 async getBlob(repoRef, sha) {
334 if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git blob SHA');
335 const { apiBase } = await this.getRepositoryContext(repoRef);
336 const data = await this.requestJson(`${apiBase}/git/blobs/${encodeURIComponent(sha)}`, 'GitHub blob');
337 return { encoding: data.encoding || '', size: data.size ?? 0, content: data.content || '' };
338 }
339
340 async getRepoStatus(repoRef) {
341 const { raw, apiBase } = await this.getRepositoryContext(repoRef);
342 const runsData = await this.requestJson(`${apiBase}/actions/runs?per_page=3`, 'GitHub Actions runs');
343 const runs = runsData.workflow_runs || [];
344 return {
345 repo: String(repoRef), repoName: raw.name, defaultBranch: raw.default_branch || 'main',
346 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 || '' }))
347 };
348 }
349
350 async listWorkflowRuns(repoRef, { perPage = 10, page = 1 } = {}) {
351 const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page);
352 const { apiBase } = await this.getRepositoryContext(repoRef);
353 const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : '';
354 const data = await this.requestJson(`${apiBase}/actions/runs?per_page=${count}${pageQuery}`, 'GitHub workflow runs');
355 return (data.workflow_runs || []).map(run => this.mapWorkflowRun(run));
356 }
357
358 async getWorkflowRun(repoRef, runId) {
359 const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
360 return this.mapWorkflowRun(await this.requestJson(`${apiBase}/actions/runs/${id}`, 'GitHub workflow run'));
361 }
362
363 async listWorkflowJobs(repoRef, runId) {
364 const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
365 const data = await this.requestJson(`${apiBase}/actions/runs/${id}/jobs?per_page=20`, 'GitHub workflow jobs');
366 return (data.jobs || []).map(job => this.mapWorkflowJob(job));
367 }
368
369 async getWorkflowJob(repoRef, jobId) {
370 const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef);
371 return this.mapWorkflowJob(await this.requestJson(`${apiBase}/actions/jobs/${id}`, 'GitHub workflow job'));
372 }
373
374 async getWorkflowJobLog(repoRef, jobId, { maxChars = 12000 } = {}) {
375 const id = numericId(jobId, 'workflow job'); const { apiBase } = await this.getRepositoryContext(repoRef);
376 return this.requestText(`${apiBase}/actions/jobs/${id}/logs`, 'GitHub workflow job log', { maxChars });
377 }
378
379 async listWorkflowArtifacts(repoRef, runId, { perPage = 20, page = 1 } = {}) {
380 const id = numericId(runId, 'workflow run'); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page);
381 const { apiBase } = await this.getRepositoryContext(repoRef);
382 const data = await this.requestJson(`${apiBase}/actions/runs/${id}/artifacts?per_page=${count}&page=${pageNumber}`, 'GitHub workflow artifacts');
383 return (data.artifacts || []).map(artifact => ({
384 id: artifact.id, name: artifact.name || 'Artifact', size: artifact.size_in_bytes ?? 0, expired: !!artifact.expired,
385 createdAt: artifact.created_at || '', expiresAt: artifact.expires_at || '', downloadUrl: artifact.archive_download_url || ''
386 }));
387 }
388
389 async listBranches(repoRef, { perPage = 20, page = 1 } = {}) {
390 const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
391 const data = await this.requestJson(`${apiBase}/branches?per_page=${count}&page=${pageNumber}`, 'GitHub branches');
392 return data.map(branch => ({ name: branch.name || '', sha: branch.commit?.sha || '', protected: !!branch.protected }));
393 }
394
395 async compareWithDefault(repoRef, headSha) {
396 const head = fullSha(headSha); const { raw, apiBase } = await this.getRepositoryContext(repoRef); const base = raw.default_branch || 'main';
397 const data = await this.requestJson(`${apiBase}/compare/${encodeURIComponent(base)}...${head}`, 'GitHub compare');
398 return {
399 base, head, status: data.status || '', aheadBy: data.ahead_by ?? 0, behindBy: data.behind_by ?? 0,
400 totalCommits: data.total_commits ?? 0, baseSha: data.base_commit?.sha || '', mergeBaseSha: data.merge_base_commit?.sha || '',
401 files: (data.files || []).slice(0, 20).map(file => this.mapPullRequestFile(file))
402 };
403 }
404
405 async listIssues(repoRef, { perPage = 10, page = 1 } = {}) {
406 const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
407 const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=${count}&page=${pageNumber}`, 'GitHub issues');
408 return data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue));
409 }
410
411 async listIssuesPage(repoRef, { page = 1 } = {}) {
412 const pageNumber = clampPage(page);
413 const { apiBase } = await this.getRepositoryContext(repoRef);
414 const data = await this.requestJson(`${apiBase}/issues?state=all&per_page=20&page=${pageNumber}`, 'GitHub issues');
415 return {
416 items: data.filter(issue => !issue.pull_request).map(issue => this.mapIssue(issue)),
417 hasMore: data.length === 20
418 };
419 }
420
421 async listReleases(repoRef, { perPage = 10, page = 1 } = {}) {
422 const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef);
423 const data = await this.requestJson(`${apiBase}/releases?per_page=${count}&page=${pageNumber}`, 'GitHub releases');
424 return data.map(release => ({
425 id: release.id, tag: release.tag_name || '', name: release.name || release.tag_name || 'Release', draft: !!release.draft,
426 prerelease: !!release.prerelease, publishedAt: release.published_at || release.created_at || '', url: release.html_url || ''
427 }));
428 }
429
430 async rerunFailedWorkflowRun(repoRef, runId) {
431 const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
432 return this.requestJson(`${apiBase}/actions/runs/${id}/rerun-failed-jobs`, 'GitHub rerun failed jobs', { method: 'POST', allowEmpty: true });
433 }
434
435 async cancelWorkflowRun(repoRef, runId) {
436 const id = numericId(runId, 'workflow run'); const { apiBase } = await this.getRepositoryContext(repoRef);
437 return this.requestJson(`${apiBase}/actions/runs/${id}/cancel`, 'GitHub cancel workflow run', { method: 'POST', allowEmpty: true });
438 }
439 }