Personal Telegram developer console for GitHub

fix(github): restore service and add guarded PR merge

davoodmehraban89 committed Oct 5, 2026 at 04:58 UTC cf38ef03d28974bc2df45e7a252fac2c45d34a47
1 file changed +39 -261
src/github.js
+39 -261
@@ -3,259 +3,48 @@ import { DEFAULT_CONFIG } from './config.js';
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 -};
6 +const numericId = (value, label) => { const text = String(value ?? ''); if (!/^\d+$/.test(text)) throw new Error(`Invalid ${label} ID`); return text; };
7 +const fullSha = (value, label = 'Git commit') => { const text = String(value || ''); if (!/^[a-f0-9]{40}$/i.test(text)) throw new Error(`Invalid ${label} SHA`); return text; };
8 +const gitBranch = value => { const branch = String(value || ''); if (!branch || branch.includes('..') || branch.startsWith('/') || branch.endsWith('/') || branch.includes('\0')) throw new Error('Invalid Git branch'); return branch; };
9 const encodedBranch = value => gitBranch(value).split('/').map(encodeURIComponent).join('/');
10 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 -};
11 +const decodeBase64Utf8 = value => { let binary; try { binary = atob(String(value || '').replace(/\s/g, '')); } catch { throw new Error('GitHub file content is not valid base64'); } const bytes = Uint8Array.from(binary, char => char.charCodeAt(0)); try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { throw new Error('GitHub file content is not valid UTF-8 text'); } };
12
13 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 - const error = new Error(`${label} failed: ${res.status}${detail}`);
79 - error.status = res.status;
80 - throw error;
81 - }
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, { headers: this.getHeaders() });
90 - const raw = await res.text();
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) {
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 -
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 -
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 -
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 -
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() {
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);
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 -
131 - async listFiles(repoRef, path = '', ref = '') {
132 - const { apiBase } = await this.getRepositoryContext(repoRef);
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 -
140 - async getFile(repoRef, filePath, ref = '') {
141 - const { apiBase } = await this.getRepositoryContext(repoRef);
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 -
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 -
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 -
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 -
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 -
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 -
178 - async getPullRequestChecks(repoRef, prNumber) {
179 - const pr = await this.getPullRequest(repoRef, prNumber);
180 - const { apiBase } = await this.getRepositoryContext(repoRef);
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 -
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 -
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);
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 -
203 - async createGitTree(repoRef, { baseTreeSha, entries } = {}) {
204 - const base = fullSha(baseTreeSha, 'Git base tree');
205 - if (!Array.isArray(entries)) throw new Error('Git tree entries are required');
206 - const tree = entries.map(entry => {
207 - const path = String(entry?.path || '');
208 - if (!path || path.startsWith('/') || path.includes('\0')) throw new Error('Invalid Git tree path');
209 - if (entry?.mode !== '100644' || entry?.type !== 'blob') throw new Error('Unsupported Git tree entry');
210 - return { path, mode: '100644', type: 'blob', sha: fullSha(entry.sha, 'Git blob') };
211 - });
212 - const { apiBase } = await this.getRepositoryContext(repoRef);
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 -
217 - async createGitCommit(repoRef, { message, treeSha, parentSha, timestamp } = {}) {
218 - const commitMessage = String(message || '');
219 - if (!commitMessage) throw new Error('Git commit message is required');
220 - const tree = fullSha(treeSha, 'Git tree');
221 - const parent = fullSha(parentSha, 'Git parent commit');
222 - const date = new Date(String(timestamp || ''));
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);
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 } = {}) {
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');
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');
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) {
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 } = {}) {
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 -
14 + constructor(token = '', owner = DEFAULT_CONFIG.defaultOwner) { this.token = token; this.owner = owner; this.baseUrl = 'https://api.github.com'; }
15 + requireToken() { if (!this.token) throw new Error('GITHUB_TOKEN is not configured'); }
16 + getHeaders() { this.requireToken(); return { 'User-Agent': 'Nexa-Dev-Bot-v1.1', 'Accept': 'application/vnd.github+json', 'Authorization': `Bearer ${this.token}`, 'X-GitHub-Api-Version': '2022-11-28' }; }
17 + async requestJson(url, label, { method = 'GET', body, allowEmpty = false, allowNotFound = false } = {}) { const headers = this.getHeaders(); const options = { method, headers }; if (body !== undefined) { options.body = JSON.stringify(body); options.headers = { ...headers, 'Content-Type': 'application/json' }; } const res = await fetch(url, options); const raw = await res.text(); let parsed = null; if (raw) { try { parsed = JSON.parse(raw); } catch { parsed = null; } } if (!res.ok) { if (allowNotFound && res.status === 404) return null; const providerMessage = parsed?.message || raw.slice(0, 240); const detail = providerMessage ? ` ${providerMessage}` : ''; const error = new Error(`${label} failed: ${res.status}${detail}`); error.status = res.status; throw error; } if (allowEmpty) return { accepted: true, status: res.status }; if (!raw) return null; if (parsed === null) throw new Error(`${label} failed: invalid JSON response`); return parsed; }
18 + async requestText(url, label, { maxChars = 12000 } = {}) { const res = await fetch(url, { method: 'GET', headers: this.getHeaders() }); const raw = await res.text(); if (!res.ok) { const detail = raw ? ` ${raw.slice(0, 240)}` : ''; throw new Error(`${label} failed: ${res.status}${detail}`); } const limit = Math.max(1, Math.min(20000, Number(maxChars) || 12000)); return { text: raw.length > limit ? raw.slice(-limit) : raw, truncated: raw.length > limit }; }
19 + repoUrl(repo, suffix = '') { return `${this.baseUrl}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(repo)}${suffix}`; }
20 + repositoryLookupUrl(repoRef) { const value = String(repoRef || ''); return /^\d+$/.test(value) ? `${this.baseUrl}/repositories/${value}` : this.repoUrl(value); }
21 + repositoryApiBase(fullName) { const parts = String(fullName || '').split('/').filter(Boolean); if (parts.length !== 2) throw new Error('GitHub repository full_name is invalid'); return `${this.baseUrl}/repos/${parts.map(encodeURIComponent).join('/')}`; }
22 + async getRepositoryContext(repoRef) { const value = String(repoRef || ''); try { const raw = await this.requestJson(this.repositoryLookupUrl(value), 'GitHub repository'); return { raw, apiBase: this.repositoryApiBase(raw.full_name) }; } catch (error) { if (!/^\d+$/.test(value) || error?.status !== 404) throw error; const repositories = await this.listRepositories(); const match = repositories.find(repo => repo.id === value); if (!match?.fullName) throw error; const apiBase = this.repositoryApiBase(match.fullName); const raw = await this.requestJson(apiBase, 'GitHub repository'); return { raw, apiBase: this.repositoryApiBase(raw.full_name) }; } }
23 + mapRepository(r) { return { id: String(r.id ?? r.name), name: r.name, fullName: r.full_name, private: !!r.private, description: r.description || '', defaultBranch: r.default_branch || 'main', archived: !!r.archived, htmlUrl: r.html_url || '', stars: r.stargazers_count ?? 0, forks: r.forks_count ?? 0 }; }
24 + mapWorkflowRun(run = {}) { return { id: run.id, name: run.name || 'Workflow', status: run.status || '', conclusion: run.conclusion || null, event: run.event || '', branch: run.head_branch || '', sha: String(run.head_sha || '').slice(0, 7), runNumber: run.run_number ?? null, url: run.html_url || '', createdAt: run.created_at || '', updatedAt: run.updated_at || '' }; }
25 + mapWorkflowJob(job = {}) { return { id: job.id, name: job.name || 'Job', status: job.status || '', conclusion: job.conclusion || null, startedAt: job.started_at || '', completedAt: job.completed_at || '', url: job.html_url || '', steps: (job.steps || []).slice(0, 30).map(step => ({ number: step.number, name: step.name || 'Step', status: step.status || '', conclusion: step.conclusion || null })) }; }
26 + mapPullRequestFile(file = {}) { return { filename: file.filename || '', status: file.status || '', additions: file.additions ?? 0, deletions: file.deletions ?? 0, changes: file.changes ?? 0, patch: boundedPatch(file.patch) }; }
27 + mapIssue(issue = {}) { return { number: issue.number, title: issue.title || '', state: issue.state || '', author: issue.user?.login || 'unknown', comments: issue.comments ?? 0, url: issue.html_url || '' }; }
28 + async listRepositories() { const data = await this.requestJson(`${this.baseUrl}/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member`, 'GitHub repositories'); return data.map(r => { const repo = this.mapRepository(r); return { ...repo, title: `${repo.name} ${repo.private ? '🔒' : '🌐'}` }; }); }
29 + async getRepository(repoRef) { const { raw } = await this.getRepositoryContext(repoRef); return this.mapRepository(raw); }
30 + async listPullRequests(repoRef, { perPage = 10, page = 1 } = {}) { const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : ''; const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/pulls?state=all&per_page=${count}${pageQuery}`, 'GitHub pull requests'); return data.map(pr => ({ number: pr.number, title: pr.title, author: pr.user?.login || 'unknown', state: pr.state, merged: !!pr.merged_at, createdAt: pr.created_at, url: pr.html_url })); }
31 + async getPullRequest(repoRef, prNumber) { const number = numericId(prNumber, 'pull request'); const { apiBase } = await this.getRepositoryContext(repoRef); const pr = await this.requestJson(`${apiBase}/pulls/${number}`, 'GitHub pull request'); return { number: pr.number, title: pr.title || '', author: pr.user?.login || 'unknown', state: pr.state || '', merged: !!(pr.merged ?? pr.merged_at), body: pr.body || '', url: pr.html_url || '', 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 }; }
32 + async listPullRequestFiles(repoRef, prNumber, { perPage = 20, page = 1 } = {}) { const number = numericId(prNumber, 'pull request'); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/pulls/${number}/files?per_page=${count}&page=${pageNumber}`, 'GitHub pull request files'); return data.map(file => this.mapPullRequestFile(file)); }
33 + async listCommits(repoRef) { const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/commits?per_page=5`, 'GitHub commits'); return data.map(c => ({ sha: String(c.sha || '').slice(0, 7), fullSha: String(c.sha || ''), message: String(c.commit?.message || '').split('\n')[0], author: c.author?.login || c.commit?.author?.name || 'Unknown', date: c.commit?.author?.date ? c.commit.author.date.slice(0, 10) : '' })); }
34 + async getCommit(repoRef, sha) { const commitSha = fullSha(sha); const { apiBase } = await this.getRepositoryContext(repoRef); const c = await this.requestJson(`${apiBase}/commits/${commitSha}`, 'GitHub commit'); const files = (c.files || []).slice(0, 20).map(file => ({ filename: file.filename || '', status: file.status || '', additions: file.additions ?? 0, deletions: file.deletions ?? 0, changes: file.changes ?? 0 })); return { sha: commitSha, shortSha: commitSha.slice(0, 7), message: String(c.commit?.message || ''), author: c.author?.login || c.commit?.author?.name || 'Unknown', date: c.commit?.author?.date || '', additions: c.stats?.additions ?? 0, deletions: c.stats?.deletions ?? 0, changedFiles: files.length, files }; }
35 + async listCommitChecks(repoRef, sha, { perPage = 20, page = 1 } = {}) { const commitSha = fullSha(sha); const count = clampPerPage(perPage, 20); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/commits/${commitSha}/check-runs?per_page=${count}&page=${pageNumber}`, 'GitHub check runs'); return (data.check_runs || []).map(check => ({ id: check.id, name: check.name || 'Check', status: check.status || '', conclusion: check.conclusion || null, url: check.html_url || '' })); }
36 + async listFiles(repoRef, path = '', { ref } = {}) { const { apiBase } = await this.getRepositoryContext(repoRef); const suffix = path ? `/contents/${encodedPath(path)}` : '/contents'; const query = ref ? `?ref=${encodeURIComponent(String(ref))}` : ''; const data = await this.requestJson(`${apiBase}${suffix}${query}`, 'GitHub contents'); if (!Array.isArray(data)) throw new Error('GitHub contents response is not a directory listing'); return data.map(item => ({ name: item.name, path: item.path, type: item.type === 'dir' ? 'dir' : 'file', size: item.size ?? 0, sha: item.sha || '' })); }
37 + async getGitRef(repoRef, branch, { allowMissing = false } = {}) { const branchName = gitBranch(branch); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/ref/heads/${encodedBranch(branchName)}`, 'GitHub branch ref', { allowNotFound: allowMissing }); if (data === null) return null; return { branch: branchName, sha: fullSha(data?.object?.sha, 'Git branch head') }; }
38 + async getBranchSnapshot(repoRef, branch) { const branchName = gitBranch(branch); const { apiBase } = await this.getRepositoryContext(repoRef); const ref = await this.requestJson(`${apiBase}/git/ref/heads/${encodedBranch(branchName)}`, 'GitHub branch ref'); const headSha = fullSha(ref?.object?.sha, 'Git branch head'); const commit = await this.requestJson(`${apiBase}/git/commits/${headSha}`, 'GitHub branch commit'); const treeSha = fullSha(commit?.tree?.sha, 'Git tree'); return { branch: branchName, headSha, treeSha }; }
39 + async getFileAtRef(repoRef, path, ref) { const filePath = String(path || ''); if (!filePath || filePath.startsWith('/') || filePath.includes('\0')) throw new Error('Invalid GitHub file path'); const commitRef = fullSha(ref); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/contents/${encodedPath(filePath)}?ref=${commitRef}`, 'GitHub file'); if (!data || Array.isArray(data) || data.type !== 'file') throw new Error('GitHub contents response is not a file'); if (data.encoding !== 'base64') throw new Error('GitHub file encoding is not supported'); const content = decodeBase64Utf8(data.content || ''); return { path: data.path || filePath, sha: String(data.sha || ''), size: Number(data.size) || 0, encoding: 'utf-8', content }; }
40 + async createGitBlob(repoRef, text) { const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/blobs`, 'GitHub create blob', { method: 'POST', body: { content: String(text ?? ''), encoding: 'utf-8' } }); return { sha: fullSha(data?.sha, 'Git blob') }; }
41 + async createGitTree(repoRef, { baseTreeSha, entries } = {}) { const base = fullSha(baseTreeSha, 'Git base tree'); if (!Array.isArray(entries)) throw new Error('Git tree entries are required'); const tree = entries.map(entry => { const path = String(entry?.path || ''); if (!path || path.startsWith('/') || path.includes('\0')) throw new Error('Invalid Git tree path'); if (entry?.mode !== '100644' || entry?.type !== 'blob') throw new Error('Unsupported Git tree entry'); return { path, mode: '100644', type: 'blob', sha: fullSha(entry.sha, 'Git blob') }; }); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/trees`, 'GitHub create tree', { method: 'POST', body: { base_tree: base, tree } }); return { sha: fullSha(data?.sha, 'Git tree') }; }
42 + async createGitCommit(repoRef, { message, treeSha, parentSha, timestamp } = {}) { const commitMessage = String(message || ''); if (!commitMessage) throw new Error('Git commit message is required'); const tree = fullSha(treeSha, 'Git tree'); const parent = fullSha(parentSha, 'Git parent commit'); const date = new Date(String(timestamp || '')); if (Number.isNaN(date.getTime()) || date.toISOString() !== String(timestamp)) throw new Error('Invalid Git commit timestamp'); const identity = { name: 'Nexa Dev Bot', email: 'nexa-dev-bot@users.noreply.github.com', date: String(timestamp) }; const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/commits`, 'GitHub create commit', { method: 'POST', body: { message: commitMessage, tree, parents: [parent], author: identity, committer: identity } }); return { sha: fullSha(data?.sha, 'Git commit') }; }
43 + async createGitBranchRef(repoRef, { branch, sha } = {}) { const branchName = gitBranch(branch); const commitSha = fullSha(sha, 'Git commit'); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/refs`, 'GitHub create branch ref', { method: 'POST', body: { ref: `refs/heads/${branchName}`, sha: commitSha } }); return { ref: String(data?.ref || `refs/heads/${branchName}`), sha: fullSha(data?.object?.sha || commitSha, 'Git commit') }; }
44 + async listTree(repoRef, sha) { if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git tree SHA'); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/trees/${encodeURIComponent(sha)}`, 'GitHub tree'); 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 || '' })); }
45 + async getBlob(repoRef, sha) { if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) throw new Error('Invalid Git blob SHA'); const { apiBase } = await this.getRepositoryContext(repoRef); const data = await this.requestJson(`${apiBase}/git/blobs/${encodeURIComponent(sha)}`, 'GitHub blob'); return { encoding: data.encoding || '', size: data.size ?? 0, content: data.content || '' }; }
46 + async getRepoStatus(repoRef) { 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 || []; 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 || '' })) }; }
47 + async listWorkflowRuns(repoRef, { perPage = 10, page = 1 } = {}) { const count = clampPerPage(perPage, 10); const pageNumber = clampPage(page); const { apiBase } = await this.getRepositoryContext(repoRef); const pageQuery = pageNumber > 1 ? `&page=${pageNumber}` : ''; const data = await this.requestJson(`${apiBase}/actions/runs?per_page=${count}${pageQuery}`, 'GitHub workflow runs'); return (data.workflow_runs || []).map(run => this.mapWorkflowRun(run)); }
48 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')); }
49 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)); }
50 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')); }
@@ -268,18 +57,7 @@ export class GitHubService {
57 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 || '' }; }
58 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 || '' })); }
59 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);
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 -
60 + async mergePullRequest(repoRef, prNumber, { expectedHeadSha, mergeMethod = 'squash' } = {}) { const number = numericId(prNumber, 'pull request'); const method = String(mergeMethod || 'squash'); if (!['merge', 'squash', 'rebase'].includes(method)) throw new Error('Unsupported merge method'); const expected = fullSha(expectedHeadSha, 'expected pull request head'); const { apiBase } = await this.getRepositoryContext(repoRef); const result = await this.requestJson(`${apiBase}/pulls/${number}/merge`, 'GitHub pull request merge', { method: 'PUT', body: { sha: expected, merge_method: method } }); if (!result?.merged) throw new Error(`GitHub pull request merge failed: ${String(result?.message || 'not merged').slice(0, 240)}`); return { merged: true, sha: String(result.sha || ''), message: String(result.message || '') }; }
61 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 }); }
62 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 }); }
63 }