import githubRequest from 'kody:@kody/github/request' import { issueRefsInText } from './pr-refs.ts' import { commentFetchConcurrency, frictionLabel, type FrictionIssue, type IssueComment } from './shared.ts' type GithubRequestResult = { ok?: boolean status?: number data?: unknown text?: string } type GithubIssue = { number?: number title?: string | null body?: string | null html_url?: string | null user?: { login?: string | null } | null created_at?: string | null updated_at?: string | null pull_request?: unknown labels?: Array<{ name?: string } | string> } type GithubComment = { id?: number body?: string | null created_at?: string | null user?: { login?: string | null } | null } function requireOk(result: GithubRequestResult, path: string) { if (result?.ok === false || (result.status && result.status >= 400)) { throw new Error( `GitHub ${path} failed (${result.status}): ${String(result.text || '').slice(0, 200)}`, ) } return result.data } function asArray(data: unknown): Array { return Array.isArray(data) ? (data as Array) : [] } function issueLabels(issue: GithubIssue) { return (issue.labels || []) .map((label) => (typeof label === 'string' ? label : String(label?.name || ''))) .filter(Boolean) } function toComment(comment: GithubComment): IssueComment { return { id: Number(comment.id || 0), userLogin: String(comment.user?.login || ''), createdAt: String(comment.created_at || ''), body: String(comment.body || ''), } } /** * List open issues (no pull requests), oldest first, WITHOUT comments. Pass * `label` to list only issues with that label. One request per 100 issues, so * this stays fast as the backlog grows. Fetch comments only for the issues a * run selects (`loadIssueComments`). */ export async function listOpenIssues(repoSlug: string, input: { label?: string } = {}): Promise> { const issues: Array = [] const labelQuery = input.label ? `labels=${encodeURIComponent(input.label)}&` : '' for (let page = 1; page <= 10; page += 1) { const path = `/repos/${repoSlug}/issues?${labelQuery}state=open&per_page=100&page=${page}` const data = asArray(requireOk(await githubRequest({ path }), path)) for (const issue of data) { const number = Number(issue.number || 0) if (!number || issue.pull_request) continue issues.push({ number, title: String(issue.title || ''), body: String(issue.body || ''), htmlUrl: String(issue.html_url || ''), userLogin: String(issue.user?.login || ''), createdAt: String(issue.created_at || ''), updatedAt: String(issue.updated_at || ''), labels: issueLabels(issue), comments: [], }) } if (data.length < 100) break } issues.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt)) return issues } /** Open `friction` issues, oldest first, without comments. */ export async function listFrictionIssues(repoSlug: string): Promise> { return await listOpenIssues(repoSlug, { label: frictionLabel }) } /** * Make sure a repo label exists (bot account). Reads it first and creates it * only on 404; a 422 on create means another caller just made it. */ export async function ensureRepoLabel( repoSlug: string, label: { name: string; color: string; description: string }, ): Promise<{ created: boolean }> { const readPath = `/repos/${repoSlug}/labels/${encodeURIComponent(label.name)}` const existing = (await githubRequest({ path: readPath })) as GithubRequestResult if (existing?.status !== 404) { requireOk(existing, `GET ${readPath}`) return { created: false } } const createPath = `/repos/${repoSlug}/labels` const created = (await githubRequest({ method: 'POST', path: createPath, body: label, confirm: true, })) as GithubRequestResult if (created?.status === 422) return { created: false } requireOk(created, `POST ${createPath}`) return { created: true } } /** Add labels to one issue (bot account). */ export async function addIssueLabels(repoSlug: string, issueNumber: number, labels: Array) { const path = `/repos/${repoSlug}/issues/${issueNumber}/labels` requireOk(await githubRequest({ method: 'POST', path, body: { labels }, confirm: true }), `POST ${path}`) } /** Post one comment on an issue (bot account, no @-mentions allowed). */ export async function postIssueComment(repoSlug: string, issueNumber: number, body: string) { const path = `/repos/${repoSlug}/issues/${issueNumber}/comments` requireOk(await githubRequest({ method: 'POST', path, body: { body }, confirm: true }), `POST ${path}`) } /** * Issue numbers referenced by open pull requests (title or body), mapped to * one PR URL each. Read-only; at most 5 pages of 100 open PRs. */ export async function listOpenPrIssueRefs(repoSlug: string): Promise> { const refs = new Map() for (let page = 1; page <= 5; page += 1) { const path = `/repos/${repoSlug}/pulls?state=open&per_page=100&page=${page}` const data = asArray(requireOk(await githubRequest({ path }), path)) for (const pr of data) { const url = String(pr.html_url || '') for (const number of issueRefsInText(`${pr.title || ''}\n${pr.body || ''}`, repoSlug)) { if (number !== Number(pr.number) && !refs.has(number)) refs.set(number, url) } } if (data.length < 100) break } return refs } async function listIssueComments(repoSlug: string, issueNumber: number) { const comments: Array = [] for (let page = 1; page <= 10; page += 1) { const path = `/repos/${repoSlug}/issues/${issueNumber}/comments?per_page=100&page=${page}` const pageComments = asArray( requireOk(await githubRequest({ path }), path), ) comments.push(...pageComments) if (pageComments.length < 100) break } return comments.map(toComment) } /** Run `task` over `items` with at most `limit` in flight; keeps input order. */ export async function mapWithConcurrency( items: ReadonlyArray, limit: number, task: (item: T, index: number) => Promise, ): Promise> { const results = new Array(items.length) let next = 0 const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => { while (next < items.length) { const index = next next += 1 results[index] = await task(items[index], index) } }) await Promise.all(workers) return results } /** Fill `comments` for the given (already selected) issues only. */ export async function loadIssueComments( repoSlug: string, issues: ReadonlyArray, concurrency = commentFetchConcurrency, ): Promise> { return await mapWithConcurrency(issues, concurrency, async (issue) => ({ ...issue, comments: await listIssueComments(repoSlug, issue.number), })) }