Personal Telegram developer console for GitHub

feat/safe-github-ops
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 319 lines 9.06 KB
Raw
1 import { DEFAULT_CONFIG } from './config.js';
2
3 export class GitHubService {
4 constructor(token = '', owner = DEFAULT_CONFIG.defaultOwner) {
5 this.token = token;
6 this.owner = owner;
7 this.baseUrl = 'https://api.github.com';
8 }
9
10 requireToken() {
11 if (!this.token) {
12 throw new Error('GITHUB_TOKEN is not configured');
13 }
14 }
15
16 getHeaders() {
17 this.requireToken();
18 return {
19 'User-Agent': 'Nexa-Dev-Bot-v1.1',
20 'Accept': 'application/vnd.github+json',
21 'Authorization': `Bearer ${this.token}`,
22 'X-GitHub-Api-Version': '2022-11-28'
23 };
24 }
25
26 async requestJson(url, label, { method = 'GET', body, allowEmpty = false } = {}) {
27 const headers = this.getHeaders();
28 const options = { method, headers };
29 if (body !== undefined) {
30 options.body = JSON.stringify(body);
31 options.headers = { ...headers, 'Content-Type': 'application/json' };
32 }
33
34 const res = await fetch(url, options);
35 const raw = await res.text();
36 let parsed = null;
37 if (raw) {
38 try {
39 parsed = JSON.parse(raw);
40 } catch {
41 parsed = null;
42 }
43 }
44
45 if (!res.ok) {
46 const providerMessage = parsed?.message || raw.slice(0, 240);
47 const detail = providerMessage ? ` ${providerMessage}` : '';
48 throw new Error(`${label} failed: ${res.status}${detail}`);
49 }
50
51 if (allowEmpty) {
52 return { accepted: true, status: res.status };
53 }
54
55 if (!raw) return null;
56 if (parsed === null) {
57 throw new Error(`${label} failed: invalid JSON response`);
58 }
59 return parsed;
60 }
61
62 repoUrl(repo, suffix = '') {
63 return `${this.baseUrl}/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(repo)}${suffix}`;
64 }
65
66 repositoryLookupUrl(repoRef) {
67 const value = String(repoRef || '');
68 if (/^\d+$/.test(value)) {
69 return `${this.baseUrl}/repositories/${value}`;
70 }
71 return this.repoUrl(value);
72 }
73
74 repositoryApiBase(fullName) {
75 const parts = String(fullName || '').split('/').filter(Boolean);
76 if (parts.length !== 2) {
77 throw new Error('GitHub repository full_name is invalid');
78 }
79 return `${this.baseUrl}/repos/${parts.map(encodeURIComponent).join('/')}`;
80 }
81
82 async getRepositoryContext(repoRef) {
83 const raw = await this.requestJson(this.repositoryLookupUrl(repoRef), 'GitHub repository');
84 return {
85 raw,
86 apiBase: this.repositoryApiBase(raw.full_name)
87 };
88 }
89
90 mapRepository(r) {
91 return {
92 id: String(r.id ?? r.name),
93 name: r.name,
94 fullName: r.full_name,
95 private: !!r.private,
96 description: r.description || '',
97 defaultBranch: r.default_branch || 'main',
98 archived: !!r.archived,
99 htmlUrl: r.html_url || '',
100 stars: r.stargazers_count ?? 0,
101 forks: r.forks_count ?? 0
102 };
103 }
104
105 mapWorkflowRun(run = {}) {
106 return {
107 id: run.id,
108 name: run.name || 'Workflow',
109 status: run.status || '',
110 conclusion: run.conclusion || null,
111 event: run.event || '',
112 branch: run.head_branch || '',
113 sha: String(run.head_sha || '').slice(0, 7),
114 runNumber: run.run_number ?? null,
115 url: run.html_url || '',
116 createdAt: run.created_at || '',
117 updatedAt: run.updated_at || ''
118 };
119 }
120
121 mapWorkflowJob(job = {}) {
122 return {
123 id: job.id,
124 name: job.name || 'Job',
125 status: job.status || '',
126 conclusion: job.conclusion || null,
127 startedAt: job.started_at || '',
128 completedAt: job.completed_at || '',
129 url: job.html_url || '',
130 steps: (job.steps || []).slice(0, 30).map(step => ({
131 number: step.number,
132 name: step.name || 'Step',
133 status: step.status || '',
134 conclusion: step.conclusion || null
135 }))
136 };
137 }
138
139 async listRepositories() {
140 const data = await this.requestJson(
141 `${this.baseUrl}/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member`,
142 'GitHub repositories'
143 );
144
145 return data.map(r => {
146 const repo = this.mapRepository(r);
147 return {
148 ...repo,
149 title: `${repo.name} ${repo.private ? '🔒' : '🌐'}`
150 };
151 });
152 }
153
154 async getRepository(repoRef) {
155 const { raw } = await this.getRepositoryContext(repoRef);
156 return this.mapRepository(raw);
157 }
158
159 async listPullRequests(repoRef) {
160 const { apiBase } = await this.getRepositoryContext(repoRef);
161 const data = await this.requestJson(
162 `${apiBase}/pulls?state=all&per_page=10`,
163 'GitHub pull requests'
164 );
165
166 return data.map(pr => ({
167 number: pr.number,
168 title: pr.title,
169 author: pr.user?.login || 'unknown',
170 state: pr.state,
171 merged: !!pr.merged_at,
172 createdAt: pr.created_at,
173 url: pr.html_url
174 }));
175 }
176
177 async listCommits(repoRef) {
178 const { apiBase } = await this.getRepositoryContext(repoRef);
179 const data = await this.requestJson(
180 `${apiBase}/commits?per_page=5`,
181 'GitHub commits'
182 );
183
184 return data.map(c => ({
185 sha: c.sha.slice(0, 7),
186 message: String(c.commit?.message || '').split('\n')[0],
187 author: c.author?.login || c.commit?.author?.name || 'Unknown',
188 date: c.commit?.author?.date ? c.commit.author.date.slice(0, 10) : ''
189 }));
190 }
191
192 async listFiles(repoRef, path = '') {
193 const { apiBase } = await this.getRepositoryContext(repoRef);
194 const suffix = path
195 ? `/contents/${path.split('/').map(encodeURIComponent).join('/')}`
196 : '/contents';
197 const data = await this.requestJson(`${apiBase}${suffix}`, 'GitHub contents');
198
199 if (!Array.isArray(data)) {
200 throw new Error('GitHub contents response is not a directory listing');
201 }
202
203 return data.map(item => ({
204 name: item.name,
205 path: item.path,
206 type: item.type === 'dir' ? 'dir' : 'file',
207 size: item.size ?? 0,
208 sha: item.sha || ''
209 }));
210 }
211
212 async listTree(repoRef, sha) {
213 if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) {
214 throw new Error('Invalid Git tree SHA');
215 }
216
217 const { apiBase } = await this.getRepositoryContext(repoRef);
218 const data = await this.requestJson(
219 `${apiBase}/git/trees/${encodeURIComponent(sha)}`,
220 'GitHub tree'
221 );
222
223 return (data.tree || [])
224 .filter(item => item.type === 'tree' || item.type === 'blob')
225 .map(item => ({
226 name: item.path,
227 path: item.path,
228 type: item.type === 'tree' ? 'dir' : 'file',
229 size: item.size ?? 0,
230 sha: item.sha || ''
231 }));
232 }
233
234 async getBlob(repoRef, sha) {
235 if (!/^[a-f0-9]{40}$/i.test(String(sha || ''))) {
236 throw new Error('Invalid Git blob SHA');
237 }
238
239 const { apiBase } = await this.getRepositoryContext(repoRef);
240 const data = await this.requestJson(
241 `${apiBase}/git/blobs/${encodeURIComponent(sha)}`,
242 'GitHub blob'
243 );
244
245 return {
246 encoding: data.encoding || '',
247 size: data.size ?? 0,
248 content: data.content || ''
249 };
250 }
251
252 async getRepoStatus(repoRef) {
253 const { raw, apiBase } = await this.getRepositoryContext(repoRef);
254 const runsData = await this.requestJson(
255 `${apiBase}/actions/runs?per_page=3`,
256 'GitHub Actions runs'
257 );
258
259 const runs = runsData.workflow_runs || [];
260 return {
261 repo: String(repoRef),
262 repoName: raw.name,
263 defaultBranch: raw.default_branch || 'main',
264 lastRuns: runs.map(r => ({
265 name: r.name,
266 status: r.status,
267 conclusion: r.conclusion,
268 commit: r.head_commit?.message?.slice(0, 80) || '',
269 url: r.html_url || ''
270 }))
271 };
272 }
273
274 async listWorkflowRuns(repoRef, { perPage = 10 } = {}) {
275 const count = Math.max(1, Math.min(20, Number(perPage) || 10));
276 const { apiBase } = await this.getRepositoryContext(repoRef);
277 const data = await this.requestJson(
278 `${apiBase}/actions/runs?per_page=${count}`,
279 'GitHub workflow runs'
280 );
281 return (data.workflow_runs || []).map(run => this.mapWorkflowRun(run));
282 }
283
284 async getWorkflowRun(repoRef, runId) {
285 const { apiBase } = await this.getRepositoryContext(repoRef);
286 const data = await this.requestJson(
287 `${apiBase}/actions/runs/${encodeURIComponent(String(runId))}`,
288 'GitHub workflow run'
289 );
290 return this.mapWorkflowRun(data);
291 }
292
293 async listWorkflowJobs(repoRef, runId) {
294 const { apiBase } = await this.getRepositoryContext(repoRef);
295 const data = await this.requestJson(
296 `${apiBase}/actions/runs/${encodeURIComponent(String(runId))}/jobs?per_page=20`,
297 'GitHub workflow jobs'
298 );
299 return (data.jobs || []).map(job => this.mapWorkflowJob(job));
300 }
301
302 async rerunFailedWorkflowRun(repoRef, runId) {
303 const { apiBase } = await this.getRepositoryContext(repoRef);
304 return this.requestJson(
305 `${apiBase}/actions/runs/${encodeURIComponent(String(runId))}/rerun-failed-jobs`,
306 'GitHub rerun failed jobs',
307 { method: 'POST', allowEmpty: true }
308 );
309 }
310
311 async cancelWorkflowRun(repoRef, runId) {
312 const { apiBase } = await this.getRepositoryContext(repoRef);
313 return this.requestJson(
314 `${apiBase}/actions/runs/${encodeURIComponent(String(runId))}/cancel`,
315 'GitHub cancel workflow run',
316 { method: 'POST', allowEmpty: true }
317 );
318 }
319 }