Personal Telegram developer console for GitHub

feat/studio-g0-foundation
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 1,026 lines 34.7 KB
Raw
1 import { githubPluginManifest } from './manifest.js';
2 import { createWorkspaceController } from './workspace.js';
3
4 const CALLBACK_ACTIONS = Object.freeze([
5 ['files:', 'github.files.list'],
6 ['tree:', 'github.tree.read'],
7 ['blob:', 'github.blob.read'],
8 ['pr:', 'github.pr.list'],
9 ['commits:', 'github.commits.list'],
10 ['status:', 'github.status.read']
11 ]);
12
13 const escapeHtml = (value) =>
14 String(value ?? '')
15 .replaceAll('&', '&')
16 .replaceAll('<', '&lt;')
17 .replaceAll('>', '&gt;')
18 .replaceAll('"', '&quot;');
19
20 const short = (value, max = 80) => {
21 const text = String(value ?? '');
22 return text.length > max ? `${text.slice(0, max - 1)}…` : text;
23 };
24
25 const numericPair = (value, prefix) => {
26 const match = String(value || '').match(
27 new RegExp(`^${prefix}:(\\d+):(\\d+)$`)
28 );
29 if (!match) return null;
30 return { repoId: Number(match[1]), runId: Number(match[2]) };
31 };
32
33 const numericTriple = (value, prefix) => {
34 const match = String(value || '').match(
35 new RegExp(`^${prefix}:(\\d+):(\\d+):(\\d+)$`)
36 );
37 if (!match) return null;
38 return {
39 repoId: Number(match[1]),
40 itemId: Number(match[2]),
41 page: Math.max(1, Math.min(100, Number(match[3]) || 1))
42 };
43 };
44
45 const pagedPair = (value, prefix) => {
46 const match = String(value || '').match(
47 new RegExp(`^${prefix}:(\\d+):(\\d+)(?::(\\d+))?$`)
48 );
49 if (!match) return null;
50 return {
51 repoId: Number(match[1]),
52 itemId: Number(match[2]),
53 page: Math.max(1, Math.min(100, Number(match[3]) || 1))
54 };
55 };
56
57 const numericSingle = (value, prefix) => {
58 const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+)$`));
59 return match ? Number(match[1]) : null;
60 };
61
62 const pagedSingle = (value, prefix) => {
63 const match = String(value || '').match(
64 new RegExp(`^${prefix}:(\\d+)(?::(\\d+))?$`)
65 );
66 if (!match) return null;
67 return {
68 repoId: Number(match[1]),
69 page: Math.max(1, Math.min(100, Number(match[2]) || 1))
70 };
71 };
72
73 const compareRef = (value) => {
74 const match = String(value || '').match(/^compare:(\d+):([a-f0-9]{40})$/i);
75 if (!match) return null;
76 return { repoId: Number(match[1]), sha: match[2] };
77 };
78
79 const commitDetailRef = (value) => {
80 const match = String(value || '').match(
81 /^commitdetail:(\d+):([a-f0-9]{40})$/i
82 );
83 if (!match) return null;
84 return { repoId: Number(match[1]), sha: match[2] };
85 };
86
87 const workflowRunsPage = (value) => pagedSingle(value, 'runs');
88
89 const runIcon = (run) => {
90 if (run.conclusion === 'success') return '✅';
91 if (run.conclusion === 'failure') return '❌';
92 if (run.conclusion === 'cancelled') return '⏹';
93 return run.status === 'in_progress' ? '🟡' : '⏳';
94 };
95
96 const stateIcon = (value) => {
97 if (value === 'success' || value === 'completed') return '✅';
98 if (value === 'failure') return '❌';
99 if (value === 'cancelled') return '⏹';
100 if (value === 'open') return '🟢';
101 if (value === 'closed') return '⚫';
102 return '•';
103 };
104
105 const addRepoAdvancedButtons = (view, repoId) => {
106 const rows = [...(view?.reply_markup?.inline_keyboard || [])];
107 const insertAt = Math.max(0, rows.length - 1);
108 rows.splice(
109 insertAt,
110 0,
111 [{ text: '🌿 Branches', callback_data: `branches:${repoId}` }],
112 [
113 { text: '🐛 Issues', callback_data: `issues:${repoId}` },
114 { text: '🏷 Releases', callback_data: `releases:${repoId}` }
115 ]
116 );
117 return {
118 ...view,
119 reply_markup: { ...(view?.reply_markup || {}), inline_keyboard: rows }
120 };
121 };
122
123 function listPagination(prefix, repoId, page, count, pageSize) {
124 const row = [];
125 if (page > 1)
126 row.push({
127 text: '⬅️ جدیدتر',
128 callback_data: `${prefix}:${repoId}:${page - 1}`
129 });
130 if (count === pageSize && page < 100)
131 row.push({
132 text: 'قدیمی‌تر ➡️',
133 callback_data: `${prefix}:${repoId}:${page + 1}`
134 });
135 return row.length ? [row] : [];
136 }
137
138 function explicitPagination(prefix, repoId, page, hasMore) {
139 const row = [];
140 if (page > 1)
141 row.push({
142 text: '⬅️ جدیدتر',
143 callback_data: `${prefix}:${repoId}:${page - 1}`
144 });
145 if (hasMore && page < 100)
146 row.push({
147 text: 'قدیمی‌تر ➡️',
148 callback_data: `${prefix}:${repoId}:${page + 1}`
149 });
150 return row.length ? [row] : [];
151 }
152
153 function pairPagination(prefix, repoId, itemId, page, count, pageSize) {
154 const row = [];
155 if (page > 1)
156 row.push({
157 text: '⬅️ جدیدتر',
158 callback_data: `${prefix}:${repoId}:${itemId}:${page - 1}`
159 });
160 if (count === pageSize && page < 100)
161 row.push({
162 text: 'قدیمی‌تر ➡️',
163 callback_data: `${prefix}:${repoId}:${itemId}:${page + 1}`
164 });
165 return row.length ? [row] : [];
166 }
167
168 async function commitsView(github, repoId) {
169 const [repo, commits] = await Promise.all([
170 github.getRepository(repoId),
171 github.listCommits(repoId)
172 ]);
173 const body = commits.length
174 ? commits
175 .slice(0, 10)
176 .map(
177 (commit) =>
178 `• <code>${escapeHtml(commit.shortSha || commit.sha)}</code> — ${escapeHtml(short(commit.message, 110))}\n ${escapeHtml(commit.author || 'Unknown')}${commit.date ? ` · ${escapeHtml(commit.date)}` : ''}`
179 )
180 .join('\n\n')
181 : '<i>کامیتی در پاسخ GitHub یافت نشد.</i>';
182 const detailRows = commits
183 .slice(0, 10)
184 .map((commit) => {
185 const sha = String(commit.fullSha || commit.sha || '');
186 return /^[a-f0-9]{40}$/i.test(sha)
187 ? [
188 {
189 text: `📝 ${short(commit.message || sha.slice(0, 7), 42)}`,
190 callback_data: `commitdetail:${repoId}:${sha}`
191 }
192 ]
193 : null;
194 })
195 .filter(Boolean);
196 return {
197 text: `📝 <b>آخرین Commitهای ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
198 reply_markup: {
199 inline_keyboard: [
200 ...detailRows,
201 [
202 { text: '🔄 بروزرسانی', callback_data: `commits:${repoId}` },
203 { text: '🔙 پروژه', callback_data: `repo:${repoId}` }
204 ]
205 ]
206 }
207 };
208 }
209
210 async function commitDetailView(github, repoId, sha) {
211 const [repo, commit] = await Promise.all([
212 github.getRepository(repoId),
213 github.getCommit(repoId, sha)
214 ]);
215 const files = (commit.files || [])
216 .slice(0, 12)
217 .map(
218 (file) =>
219 `• <code>${escapeHtml(short(file.filename, 90))}</code> · ${escapeHtml(file.status || 'changed')} · +${file.additions ?? 0}/-${file.deletions ?? 0}`
220 )
221 .join('\n');
222 return {
223 text: `📝 <b>Commit — ${escapeHtml(repo.name)}</b>\n<code>${escapeHtml(commit.shortSha || String(commit.sha).slice(0, 7))}</code> · ${escapeHtml(commit.author || 'Unknown')}\n${escapeHtml(commit.date || '-')}\n+${commit.additions ?? 0}/-${commit.deletions ?? 0} · ${commit.changedFiles ?? (commit.files || []).length} files\n➖➖➖➖➖➖➖➖➖➖\n${escapeHtml(short(commit.message || '', 1200)) || '<i>بدون پیام.</i>'}\n\n<b>فایل‌های تغییرکرده</b>\n${files || '<i>فایلی گزارش نشده است.</i>'}`,
224 reply_markup: {
225 inline_keyboard: [
226 [
227 {
228 text: '🔄 بروزرسانی',
229 callback_data: `commitdetail:${repoId}:${sha}`
230 },
231 { text: '🔙 Commitها', callback_data: `commits:${repoId}` }
232 ],
233 [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
234 ]
235 }
236 };
237 }
238
239 async function workflowRunsView(github, repoId, page = 1) {
240 const [repo, runs] = await Promise.all([
241 github.getRepository(repoId),
242 github.listWorkflowRuns(repoId, { perPage: 10, page })
243 ]);
244 const body = runs.length
245 ? runs
246 .slice(0, 10)
247 .map(
248 (run) =>
249 `${runIcon(run)} <b>${escapeHtml(run.name)}</b> #${run.runNumber ?? '-'}\n └ ${escapeHtml(run.branch || '-')} · <code>${escapeHtml(run.sha || '-')}</code> · ${escapeHtml(run.conclusion || run.status || 'unknown')}`
250 )
251 .join('\n\n')
252 : '<i>Workflow runی یافت نشد.</i>';
253 const refreshCallback =
254 page === 1 ? `runs:${repoId}` : `runs:${repoId}:${page}`;
255 return {
256 text: `🧪 <b>CI / Actions — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
257 reply_markup: {
258 inline_keyboard: [
259 ...runs.slice(0, 10).map((run) => [
260 {
261 text: `${runIcon(run)} ${short(run.name, 32)} #${run.runNumber ?? run.id}`,
262 callback_data: `run:${repoId}:${run.id}`
263 }
264 ]),
265 ...listPagination('runs', repoId, page, runs.length, 10),
266 [
267 { text: '🔄 بروزرسانی', callback_data: refreshCallback },
268 { text: '🔙 پروژه', callback_data: `repo:${repoId}` }
269 ]
270 ]
271 }
272 };
273 }
274
275 async function workflowRunView(github, repoId, runId) {
276 const [repo, run] = await Promise.all([
277 github.getRepository(repoId),
278 github.getWorkflowRun(repoId, runId)
279 ]);
280 const rows = [
281 [
282 { text: '👷 Jobها', callback_data: `jobs:${repoId}:${runId}` },
283 { text: '📦 Artifacts', callback_data: `artifacts:${repoId}:${runId}` }
284 ]
285 ];
286 if (run.conclusion === 'failure')
287 rows.push([
288 {
289 text: '🔁 اجرای مجدد jobهای ناموفق',
290 callback_data: `rerun:${repoId}:${runId}`
291 }
292 ]);
293 if (run.status === 'in_progress' || run.status === 'queued')
294 rows.push([
295 { text: '⏹ لغو Workflow', callback_data: `cancelrun:${repoId}:${runId}` }
296 ]);
297 rows.push([
298 { text: '🔄 بروزرسانی', callback_data: `run:${repoId}:${runId}` },
299 { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
300 ]);
301 return {
302 text: `🧪 <b>${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\nوضعیت: ${runIcon(run)} <b>${escapeHtml(run.conclusion || run.status || 'unknown')}</b>\nRun: <code>#${escapeHtml(run.runNumber ?? run.id)}</code>\nBranch: <code>${escapeHtml(run.branch || '-')}</code>\nSHA: <code>${escapeHtml(run.sha || '-')}</code>\nTrigger: <code>${escapeHtml(run.event || '-')}</code>`,
303 reply_markup: { inline_keyboard: rows }
304 };
305 }
306
307 async function workflowJobsView(github, repoId, runId) {
308 const [repo, run, jobs] = await Promise.all([
309 github.getRepository(repoId),
310 github.getWorkflowRun(repoId, runId),
311 github.listWorkflowJobs(repoId, runId)
312 ]);
313 const body = jobs.length
314 ? jobs
315 .slice(0, 20)
316 .map((job) => {
317 const jobState = job.conclusion || job.status || 'unknown';
318 const steps = (job.steps || [])
319 .slice(0, 30)
320 .map(
321 (step) =>
322 ` ${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`
323 )
324 .join('\n');
325 return `<b>${escapeHtml(job.name)}</b> — ${escapeHtml(jobState)}${steps ? `\n${steps}` : ''}`;
326 })
327 .join('\n\n')
328 : '<i>Jobی در این Run یافت نشد.</i>';
329 return {
330 text: `👷 <b>Jobهای ${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
331 reply_markup: {
332 inline_keyboard: [
333 ...jobs.slice(0, 20).map((job) => [
334 {
335 text: `${stateIcon(job.conclusion || job.status)} ${short(job.name, 40)}`,
336 callback_data: `job:${repoId}:${job.id}`
337 }
338 ]),
339 [
340 { text: '🔄 بروزرسانی', callback_data: `jobs:${repoId}:${runId}` },
341 { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }
342 ]
343 ]
344 }
345 };
346 }
347
348 async function workflowJobView(github, repoId, jobId) {
349 const [repo, job] = await Promise.all([
350 github.getRepository(repoId),
351 github.getWorkflowJob(repoId, jobId)
352 ]);
353 const status = job.conclusion || job.status || 'unknown';
354 const steps = (job.steps || [])
355 .slice(0, 30)
356 .map(
357 (step) =>
358 `${stateIcon(step.conclusion || step.status)} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`
359 )
360 .join('\n');
361 const rows = [];
362 if (job.conclusion === 'failure')
363 rows.push([
364 {
365 text: '📜 مشاهده log ناموفق',
366 callback_data: `joblog:${repoId}:${jobId}`
367 }
368 ]);
369 rows.push([
370 { text: '🔄 بروزرسانی', callback_data: `job:${repoId}:${jobId}` },
371 { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
372 ]);
373 return {
374 text: `👷 <b>${escapeHtml(job.name)} — ${escapeHtml(repo.name)}</b>\nوضعیت: ${stateIcon(status)} <b>${escapeHtml(status)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${steps || '<i>Stepی ثبت نشده.</i>'}`,
375 reply_markup: { inline_keyboard: rows }
376 };
377 }
378
379 async function workflowJobLogView(github, repoId, jobId) {
380 const [job, repo] = await Promise.all([
381 github.getWorkflowJob(repoId, jobId),
382 github.getRepository(repoId)
383 ]);
384 const fullName = String(repo.fullName || '')
385 .split('/')
386 .map(encodeURIComponent)
387 .join('/');
388 return {
389 text: `📜 <b>Log — ${escapeHtml(job.name)}</b>\nبرای جلوگیری از ارسال کد یا راز، متن خام Log وارد پیام تلگرام نمی‌شود. لاگ را در GitHub مشاهده کنید.`,
390 reply_markup: {
391 inline_keyboard: [
392 ...(fullName.includes('/')
393 ? [
394 [
395 {
396 text: '📜 مشاهده در GitHub',
397 url: 'https://github.com/' + fullName + '/actions'
398 }
399 ]
400 ]
401 : []),
402 [{ text: '🔙 Job', callback_data: `job:${repoId}:${jobId}` }]
403 ]
404 }
405 };
406 }
407
408 async function workflowArtifactsView(github, repoId, runId, page = 1) {
409 const [repo, artifacts] = await Promise.all([
410 github.getRepository(repoId),
411 github.listWorkflowArtifacts(repoId, runId, { perPage: 10, page })
412 ]);
413 const body = artifacts.length
414 ? artifacts
415 .slice(0, 10)
416 .map(
417 (item) =>
418 `📦 <b>${escapeHtml(item.name)}</b>\n ${item.expired ? 'منقضی شده' : 'فعال'} · ${Number(item.size || 0).toLocaleString()} bytes\n expires: ${escapeHtml(item.expiresAt || '-')}`
419 )
420 .join('\n\n')
421 : '<i>Artifactی برای این Run یافت نشد.</i>';
422 const refreshCallback =
423 page === 1
424 ? `artifacts:${repoId}:${runId}`
425 : `artifacts:${repoId}:${runId}:${page}`;
426 return {
427 text: `📦 <b>Artifacts — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
428 reply_markup: {
429 inline_keyboard: [
430 ...pairPagination(
431 'artifacts',
432 repoId,
433 runId,
434 page,
435 artifacts.length,
436 10
437 ),
438 [
439 { text: '🔄 بروزرسانی', callback_data: refreshCallback },
440 { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }
441 ]
442 ]
443 }
444 };
445 }
446
447 async function branchesView(github, repoId, page = 1) {
448 const [repo, branches] = await Promise.all([
449 github.getRepository(repoId),
450 github.listBranches(repoId, { perPage: 20, page })
451 ]);
452 const body = branches.length
453 ? branches
454 .slice(0, 20)
455 .map(
456 (branch) =>
457 `🌿 <b>${escapeHtml(short(branch.name, 70))}</b>\n <code>${escapeHtml(String(branch.sha).slice(0, 10))}</code>${branch.protected ? ' · 🛡 protected' : ''}`
458 )
459 .join('\n\n')
460 : '<i>Branchی یافت نشد.</i>';
461 return {
462 text: `🌿 <b>Branches — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
463 reply_markup: {
464 inline_keyboard: [
465 ...branches
466 .slice(0, 20)
467 .filter((branch) => /^[a-f0-9]{40}$/i.test(String(branch.sha)))
468 .map((branch) => [
469 {
470 text: `↔️ ${short(branch.name, 42)}`,
471 callback_data: `compare:${repoId}:${branch.sha}`
472 }
473 ]),
474 ...listPagination('branches', repoId, page, branches.length, 20),
475 [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
476 ]
477 }
478 };
479 }
480
481 async function compareView(github, repoId, sha) {
482 const [repo, compare] = await Promise.all([
483 github.getRepository(repoId),
484 github.compareWithDefault(repoId, sha)
485 ]);
486 const files = (compare.files || [])
487 .slice(0, 12)
488 .map(
489 (file) =>
490 `${stateIcon(file.status)} <code>${escapeHtml(short(file.filename, 90))}</code> · +${file.additions}/-${file.deletions}`
491 )
492 .join('\n');
493 return {
494 text: `↔️ <b>Compare — ${escapeHtml(repo.name)}</b>\n<code>${escapeHtml(compare.base)}</code> ← <code>${escapeHtml(String(compare.head).slice(0, 10))}</code>\nوضعیت: <b>${escapeHtml(compare.status || '-')}</b>\nAhead: <b>${compare.aheadBy ?? 0}</b> · Behind: <b>${compare.behindBy ?? 0}</b> · Commits: <b>${compare.totalCommits ?? 0}</b>\n➖➖➖➖➖➖➖➖➖➖\n${files || '<i>فایل تغییریافته‌ای نیست.</i>'}`,
495 reply_markup: {
496 inline_keyboard: [
497 [{ text: '🔙 Branches', callback_data: `branches:${repoId}` }]
498 ]
499 }
500 };
501 }
502
503 async function pullRequestsView(github, repoId, page = 1) {
504 const [repo, prs] = await Promise.all([
505 github.getRepository(repoId),
506 github.listPullRequests(repoId, { perPage: 10, page })
507 ]);
508 const body = prs.length
509 ? prs
510 .slice(0, 10)
511 .map(
512 (pr) =>
513 `${pr.merged ? '🟣' : stateIcon(pr.state)} <b>#${pr.number} ${escapeHtml(short(pr.title, 100))}</b>\n ${escapeHtml(pr.author)} · ${escapeHtml(pr.merged ? 'merged' : pr.state)}`
514 )
515 .join('\n\n')
516 : '<i>Pull Requestی یافت نشد.</i>';
517 return {
518 text: `🔎 <b>Pull Requests — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
519 reply_markup: {
520 inline_keyboard: [
521 ...prs.slice(0, 10).map((pr) => [
522 {
523 text: `#${pr.number} ${short(pr.title, 42)}`,
524 callback_data: `prdetail:${repoId}:${pr.number}`
525 }
526 ]),
527 ...listPagination('prs', repoId, page, prs.length, 10),
528 [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
529 ]
530 }
531 };
532 }
533
534 async function pullRequestDetailView(github, repoId, prNumber) {
535 const [repo, pr] = await Promise.all([
536 github.getRepository(repoId),
537 github.getPullRequest(repoId, prNumber)
538 ]);
539 const body = escapeHtml(short(pr.body || '', 600));
540 return {
541 text: `🔎 <b>PR #${pr.number} — ${escapeHtml(repo.name)}</b>\n<b>${escapeHtml(pr.title)}</b>\n${pr.merged ? '🟣 merged' : `${stateIcon(pr.state)} ${escapeHtml(pr.state)}`} · ${escapeHtml(pr.author)}\n<code>${escapeHtml(pr.head || '-')}</code> → <code>${escapeHtml(pr.base || '-')}</code>\n+${pr.additions}/-${pr.deletions} · ${pr.changedFiles} files\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون توضیح.</i>'}`,
542 reply_markup: {
543 inline_keyboard: [
544 [
545 {
546 text: '🧩 فایل‌ها / Diff',
547 callback_data: `prfiles:${repoId}:${prNumber}:1`
548 },
549 {
550 text: '✅ Checks',
551 callback_data: `prchecks:${repoId}:${prNumber}:1`
552 }
553 ],
554 [{ text: '🔙 PRها', callback_data: `prs:${repoId}` }]
555 ]
556 }
557 };
558 }
559
560 async function pullRequestFilesView(github, repoId, prNumber, page = 1) {
561 const files = await github.listPullRequestFiles(repoId, prNumber, {
562 perPage: 8,
563 page
564 });
565 const body = files.length
566 ? files
567 .slice(0, 8)
568 .map((file) => {
569 return `🧩 <code>${escapeHtml(short(file.filename, 100))}</code> · ${escapeHtml(file.status)} · +${file.additions}/-${file.deletions}`;
570 })
571 .join('\n\n')
572 : '<i>فایل تغییریافته‌ای یافت نشد.</i>';
573 return {
574 text: `🧩 <b>PR #${prNumber} Files / Diff</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
575 reply_markup: {
576 inline_keyboard: [
577 ...pairPagination('prfiles', repoId, prNumber, page, files.length, 8),
578 [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]
579 ]
580 }
581 };
582 }
583
584 async function pullRequestChecksView(github, repoId, prNumber, page = 1) {
585 const pr = await github.getPullRequest(repoId, prNumber);
586 const checks = await github.listCommitChecks(repoId, pr.headSha, {
587 perPage: 20,
588 page
589 });
590 const body = checks.length
591 ? checks
592 .slice(0, 20)
593 .map(
594 (check) =>
595 `${stateIcon(check.conclusion || check.status)} <b>${escapeHtml(check.name)}</b> — ${escapeHtml(check.conclusion || check.status || 'unknown')}`
596 )
597 .join('\n')
598 : '<i>Checkی یافت نشد.</i>';
599 return {
600 text: `✅ <b>PR #${prNumber} Checks</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
601 reply_markup: {
602 inline_keyboard: [
603 ...pairPagination(
604 'prchecks',
605 repoId,
606 prNumber,
607 page,
608 checks.length,
609 20
610 ),
611 [{ text: '🔙 PR', callback_data: `prdetail:${repoId}:${prNumber}` }]
612 ]
613 }
614 };
615 }
616
617 async function issuesView(github, repoId, page = 1) {
618 const [repo, issuePage] = await Promise.all([
619 github.getRepository(repoId),
620 github.listIssuesPage(repoId, { page })
621 ]);
622 const issues = issuePage.items || [];
623 const body = issues.length
624 ? issues
625 .slice(0, 20)
626 .map(
627 (issue) =>
628 `${stateIcon(issue.state)} <b>#${issue.number} ${escapeHtml(short(issue.title, 110))}</b>\n ${escapeHtml(issue.author)} · ${issue.comments} comments`
629 )
630 .join('\n\n')
631 : '<i>Issueی یافت نشد.</i>';
632 return {
633 text: `🐛 <b>Issues — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
634 reply_markup: {
635 inline_keyboard: [
636 ...issues.slice(0, 20).map((issue) => [
637 {
638 text: `#${issue.number} ${short(issue.title, 42)}`,
639 callback_data: `issuedetail:${repoId}:${issue.number}`
640 }
641 ]),
642 ...explicitPagination('issues', repoId, page, !!issuePage.hasMore),
643 [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
644 ]
645 }
646 };
647 }
648
649 async function issueDetailView(github, repoId, issueNumber) {
650 const [repo, issue] = await Promise.all([
651 github.getRepository(repoId),
652 github.getIssue(repoId, issueNumber)
653 ]);
654 const labels = (issue.labels || [])
655 .map((label) => `#${escapeHtml(label)}`)
656 .join(' ');
657 const assignees = (issue.assignees || [])
658 .map((name) => `@${escapeHtml(name)}`)
659 .join(' ');
660 const body = escapeHtml(short(issue.body || '', 1800));
661 return {
662 text: `🐛 <b>Issue #${issue.number} — ${escapeHtml(repo.name)}</b>\n<b>${escapeHtml(issue.title)}</b>\n${stateIcon(issue.state)} ${escapeHtml(issue.state || 'unknown')} · ${escapeHtml(issue.author)} · ${issue.comments ?? 0} comments\nLabels: ${labels || '-'}\nAssignees: ${assignees || '-'}\nUpdated: ${escapeHtml(issue.updatedAt || issue.createdAt || '-')}\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون توضیح.</i>'}`,
663 reply_markup: {
664 inline_keyboard: [
665 [
666 {
667 text: '🔄 بروزرسانی',
668 callback_data: `issuedetail:${repoId}:${issueNumber}`
669 },
670 { text: '🔙 Issues', callback_data: `issues:${repoId}` }
671 ]
672 ]
673 }
674 };
675 }
676
677 async function releasesView(github, repoId, page = 1) {
678 const [repo, releases] = await Promise.all([
679 github.getRepository(repoId),
680 github.listReleases(repoId, { perPage: 10, page })
681 ]);
682 const body = releases.length
683 ? releases
684 .slice(0, 10)
685 .map(
686 (release) =>
687 `🏷 <b>${escapeHtml(release.tag || release.name)}</b>${release.prerelease ? ' · pre-release' : ''}${release.draft ? ' · draft' : ''}\n ${escapeHtml(short(release.name, 110))}\n ${escapeHtml(release.publishedAt || '-')}`
688 )
689 .join('\n\n')
690 : '<i>هیچ Release منتشرشده‌ای برای این مخزن در GitHub وجود ندارد.</i>';
691 return {
692 text: `🏷 <b>Releases — ${escapeHtml(repo.name)}</b>\nصفحه: <b>${page}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
693 reply_markup: {
694 inline_keyboard: [
695 ...releases.slice(0, 10).map((release) => [
696 {
697 text: `🏷 ${short(release.tag || release.name, 42)}`,
698 callback_data: `releasedetail:${repoId}:${release.id}`
699 }
700 ]),
701 ...listPagination('releases', repoId, page, releases.length, 10),
702 [{ text: '🔙 پروژه', callback_data: `repo:${repoId}` }]
703 ]
704 }
705 };
706 }
707
708 async function releaseDetailView(github, repoId, releaseId) {
709 const [repo, release] = await Promise.all([
710 github.getRepository(repoId),
711 github.getRelease(repoId, releaseId)
712 ]);
713 const body = escapeHtml(short(release.body || '', 1800));
714 const flags = [
715 release.draft ? 'draft' : '',
716 release.prerelease ? 'pre-release' : ''
717 ]
718 .filter(Boolean)
719 .join(' · ');
720 return {
721 text: `🏷 <b>${escapeHtml(release.name)} — ${escapeHtml(repo.name)}</b>\nTag: <code>${escapeHtml(release.tag || '-')}</code>\nTarget: <code>${escapeHtml(release.target || '-')}</code>\nAuthor: ${escapeHtml(release.author || 'unknown')}\nPublished: ${escapeHtml(release.publishedAt || '-')}${flags ? `\nState: ${escapeHtml(flags)}` : ''}\n➖➖➖➖➖➖➖➖➖➖\n${body || '<i>بدون Release notes.</i>'}`,
722 reply_markup: {
723 inline_keyboard: [
724 [
725 {
726 text: '🔄 بروزرسانی',
727 callback_data: `releasedetail:${repoId}:${releaseId}`
728 },
729 { text: '🔙 Releases', callback_data: `releases:${repoId}` }
730 ]
731 ]
732 }
733 };
734 }
735
736 function workflowActionResultView(repoId, runId, action) {
737 const rerun = action === 'rerun_failed';
738 return {
739 text: rerun
740 ? '✅ درخواست اجرای مجدد jobهای ناموفق برای GitHub ارسال شد.'
741 : '✅ درخواست لغو Workflow برای GitHub ارسال شد.',
742 reply_markup: {
743 inline_keyboard: [
744 [
745 { text: '🧪 مشاهده Run', callback_data: `run:${repoId}:${runId}` },
746 { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
747 ]
748 ]
749 }
750 };
751 }
752
753 function resolveReadCallback(data) {
754 const value = String(data || '');
755 if (value === 'menu:repos')
756 return { actionId: 'github.repos.list', kind: 'legacy' };
757 const repoId = numericSingle(value, 'repo');
758 if (repoId !== null)
759 return { actionId: 'github.repo.detail', kind: 'repo', repoId };
760 const commits = numericSingle(value, 'commits');
761 if (commits !== null)
762 return {
763 actionId: 'github.commits.list',
764 kind: 'commits',
765 repoId: commits
766 };
767 const commitdetail = commitDetailRef(value);
768 if (commitdetail)
769 return {
770 actionId: 'github.commit.detail',
771 kind: 'commitdetail',
772 ...commitdetail
773 };
774 const legacyStatus = numericSingle(value, 'status');
775 if (legacyStatus !== null)
776 return {
777 actionId: 'github.workflow.runs.list',
778 kind: 'runs',
779 repoId: legacyStatus,
780 page: 1
781 };
782 const runs = workflowRunsPage(value);
783 if (runs)
784 return { actionId: 'github.workflow.runs.list', kind: 'runs', ...runs };
785 const run = numericPair(value, 'run');
786 if (run)
787 return { actionId: 'github.workflow.run.detail', kind: 'run', ...run };
788 const jobs = numericPair(value, 'jobs');
789 if (jobs)
790 return { actionId: 'github.workflow.jobs.list', kind: 'jobs', ...jobs };
791 const job = numericPair(value, 'job');
792 if (job)
793 return {
794 actionId: 'github.workflow.job.detail',
795 kind: 'job',
796 repoId: job.repoId,
797 jobId: job.runId
798 };
799 const joblog = numericPair(value, 'joblog');
800 if (joblog)
801 return {
802 actionId: 'github.workflow.job.log',
803 kind: 'joblog',
804 repoId: joblog.repoId,
805 jobId: joblog.runId
806 };
807 const artifacts = pagedPair(value, 'artifacts');
808 if (artifacts)
809 return {
810 actionId: 'github.workflow.artifacts.list',
811 kind: 'artifacts',
812 repoId: artifacts.repoId,
813 runId: artifacts.itemId,
814 page: artifacts.page
815 };
816 const branches = pagedSingle(value, 'branches');
817 if (branches)
818 return { actionId: 'github.branches.list', kind: 'branches', ...branches };
819 const compare = compareRef(value);
820 if (compare)
821 return { actionId: 'github.compare.read', kind: 'compare', ...compare };
822 const legacyPr = numericSingle(value, 'pr');
823 if (legacyPr !== null)
824 return {
825 actionId: 'github.pr.advanced.list',
826 kind: 'prs',
827 repoId: legacyPr,
828 page: 1
829 };
830 const prs = pagedSingle(value, 'prs');
831 if (prs) return { actionId: 'github.pr.advanced.list', kind: 'prs', ...prs };
832 const prdetail = numericPair(value, 'prdetail');
833 if (prdetail)
834 return {
835 actionId: 'github.pr.detail',
836 kind: 'prdetail',
837 repoId: prdetail.repoId,
838 prNumber: prdetail.runId
839 };
840 const prfiles = numericTriple(value, 'prfiles');
841 if (prfiles)
842 return {
843 actionId: 'github.pr.files.list',
844 kind: 'prfiles',
845 repoId: prfiles.repoId,
846 prNumber: prfiles.itemId,
847 page: prfiles.page
848 };
849 const prchecks = numericTriple(value, 'prchecks');
850 if (prchecks)
851 return {
852 actionId: 'github.pr.checks.list',
853 kind: 'prchecks',
854 repoId: prchecks.repoId,
855 prNumber: prchecks.itemId,
856 page: prchecks.page
857 };
858 const issues = pagedSingle(value, 'issues');
859 if (issues)
860 return { actionId: 'github.issues.list', kind: 'issues', ...issues };
861 const issuedetail = numericPair(value, 'issuedetail');
862 if (issuedetail)
863 return {
864 actionId: 'github.issue.detail',
865 kind: 'issuedetail',
866 repoId: issuedetail.repoId,
867 issueNumber: issuedetail.runId
868 };
869 const releases = pagedSingle(value, 'releases');
870 if (releases)
871 return { actionId: 'github.releases.list', kind: 'releases', ...releases };
872 const releasedetail = numericPair(value, 'releasedetail');
873 if (releasedetail)
874 return {
875 actionId: 'github.release.detail',
876 kind: 'releasedetail',
877 repoId: releasedetail.repoId,
878 releaseId: releasedetail.runId
879 };
880 for (const [prefix, actionId] of CALLBACK_ACTIONS) {
881 if (value.startsWith(prefix)) return { actionId, kind: 'legacy' };
882 }
883 return null;
884 }
885
886 function resolveWriteCallback(data) {
887 const rerun = numericPair(data, 'rerun');
888 if (rerun) {
889 return {
890 actionId: 'github.workflow.run.rerun_failed',
891 approval: { input: rerun, label: 'اجرای مجدد jobهای ناموفق' },
892 execute: async (github) => {
893 await github.rerunFailedWorkflowRun(rerun.repoId, rerun.runId);
894 return workflowActionResultView(
895 rerun.repoId,
896 rerun.runId,
897 'rerun_failed'
898 );
899 }
900 };
901 }
902 const cancel = numericPair(data, 'cancelrun');
903 if (cancel) {
904 return {
905 actionId: 'github.workflow.run.cancel',
906 approval: { input: cancel, label: 'لغو Workflow در حال اجرا' },
907 execute: async (github) => {
908 await github.cancelWorkflowRun(cancel.repoId, cancel.runId);
909 return workflowActionResultView(cancel.repoId, cancel.runId, 'cancel');
910 }
911 };
912 }
913 return null;
914 }
915
916 export function createGitHubPlugin({
917 github,
918 menu,
919 workspaces,
920 editorUrl
921 } = {}) {
922 if (!github) throw new Error('GitHub plugin requires github service');
923 if (!menu) throw new Error('GitHub plugin requires menu manager');
924 const workspaceController = workspaces
925 ? createWorkspaceController({ github, workspaces, editorUrl })
926 : null;
927
928 return {
929 manifest: githubPluginManifest,
930
931 resolveCommand(command) {
932 if (command !== '/repos') return null;
933 return {
934 actionId: 'github.repos.list',
935 execute: () => menu.getReposListView()
936 };
937 },
938
939 resolveMessage(payload, context = {}) {
940 return workspaceController?.resolveMessage(payload, context) || null;
941 },
942
943 resolveCallback(data, context = {}) {
944 const write = resolveWriteCallback(data);
945 if (write)
946 return {
947 actionId: write.actionId,
948 approval: write.approval,
949 execute: () => write.execute(github)
950 };
951
952 const workspaceRoute = workspaceController?.resolveCallback(
953 data,
954 context
955 );
956 if (workspaceRoute) return workspaceRoute;
957
958 const read = resolveReadCallback(data);
959 if (!read) return null;
960 return {
961 actionId: read.actionId,
962 execute: async () => {
963 if (read.kind === 'repo')
964 return addRepoAdvancedButtons(
965 await menu.renderByCallback(data),
966 read.repoId
967 );
968 if (read.kind === 'commits')
969 return typeof github.listCommits === 'function'
970 ? commitsView(github, read.repoId)
971 : menu.renderByCallback(data);
972 if (read.kind === 'commitdetail')
973 return commitDetailView(github, read.repoId, read.sha);
974 if (read.kind === 'runs')
975 return workflowRunsView(github, read.repoId, read.page);
976 if (read.kind === 'run')
977 return workflowRunView(github, read.repoId, read.runId);
978 if (read.kind === 'jobs')
979 return workflowJobsView(github, read.repoId, read.runId);
980 if (read.kind === 'job')
981 return workflowJobView(github, read.repoId, read.jobId);
982 if (read.kind === 'joblog')
983 return workflowJobLogView(github, read.repoId, read.jobId);
984 if (read.kind === 'artifacts')
985 return workflowArtifactsView(
986 github,
987 read.repoId,
988 read.runId,
989 read.page
990 );
991 if (read.kind === 'branches')
992 return branchesView(github, read.repoId, read.page);
993 if (read.kind === 'compare')
994 return compareView(github, read.repoId, read.sha);
995 if (read.kind === 'prs')
996 return pullRequestsView(github, read.repoId, read.page);
997 if (read.kind === 'prdetail')
998 return pullRequestDetailView(github, read.repoId, read.prNumber);
999 if (read.kind === 'prfiles')
1000 return pullRequestFilesView(
1001 github,
1002 read.repoId,
1003 read.prNumber,
1004 read.page
1005 );
1006 if (read.kind === 'prchecks')
1007 return pullRequestChecksView(
1008 github,
1009 read.repoId,
1010 read.prNumber,
1011 read.page
1012 );
1013 if (read.kind === 'issues')
1014 return issuesView(github, read.repoId, read.page);
1015 if (read.kind === 'issuedetail')
1016 return issueDetailView(github, read.repoId, read.issueNumber);
1017 if (read.kind === 'releases')
1018 return releasesView(github, read.repoId, read.page);
1019 if (read.kind === 'releasedetail')
1020 return releaseDetailView(github, read.repoId, read.releaseId);
1021 return menu.renderByCallback(data);
1022 }
1023 };
1024 }
1025 };
1026 }