|
| 1 | +import type { Provider, Sponsorship } from '../types' |
| 2 | +import { $fetch } from 'ofetch' |
| 3 | + |
| 4 | +export const GitHubContributionsProvider: Provider = { |
| 5 | + name: 'githubContributions', |
| 6 | + fetchSponsors(config) { |
| 7 | + if (!config.githubContributions?.login) |
| 8 | + throw new Error('GitHub login is required for githubContributions provider') |
| 9 | + |
| 10 | + return fetchGitHubContributions( |
| 11 | + config.githubContributions?.token || config.token!, |
| 12 | + config.githubContributions.login, |
| 13 | + ) |
| 14 | + }, |
| 15 | +} |
| 16 | + |
| 17 | +interface RepositoryOwner { |
| 18 | + login: string |
| 19 | + url: string |
| 20 | + avatarUrl: string |
| 21 | + __typename: 'User' | 'Organization' |
| 22 | +} |
| 23 | + |
| 24 | +interface RepoNode { |
| 25 | + name: string |
| 26 | + nameWithOwner: string |
| 27 | + url: string |
| 28 | + owner: RepositoryOwner |
| 29 | +} |
| 30 | + |
| 31 | +export async function fetchGitHubContributions( |
| 32 | + token: string, |
| 33 | + login: string, |
| 34 | +): Promise<Sponsorship[]> { |
| 35 | + if (!token) |
| 36 | + throw new Error('GitHub token is required') |
| 37 | + |
| 38 | + if (!login) |
| 39 | + throw new Error('GitHub login is required') |
| 40 | + |
| 41 | + async function graphqlFetch<T>(body: any): Promise<T> { |
| 42 | + return await $fetch<T>('https://api.github.com/graphql', { |
| 43 | + method: 'POST', |
| 44 | + headers: { |
| 45 | + Authorization: `bearer ${token}`, |
| 46 | + 'Content-Type': 'application/json', |
| 47 | + }, |
| 48 | + body, |
| 49 | + }) |
| 50 | + } |
| 51 | + |
| 52 | + // Hybrid discovery (sources kept): |
| 53 | + // 1. contributionsCollection (yearly commit timeline) to find historical commit-based repos |
| 54 | + // 2. merged PR search (GraphQL search API) to find repos where the user had merged PRs |
| 55 | + // Removed: previous sources (topRepositories, repositoriesContributedTo, repositories, events API) for simplicity |
| 56 | + |
| 57 | + console.log(`[contribkit][githubContributions] discovering repositories (sources: contributionsCollection + merged PR search)...`) |
| 58 | + |
| 59 | + const repoMap = new Map<string, RepoNode>() // deduplicate by nameWithOwner |
| 60 | + |
| 61 | + // Source 1: GraphQL contributionsCollection (discover repos via actual commit contributions) |
| 62 | + console.log(`[contribkit][githubContributions] fetching contribution timeline to discover more repos...`) |
| 63 | + try { |
| 64 | + const userInfoQuery = ` |
| 65 | + query($login: String!) { |
| 66 | + user(login: $login) { |
| 67 | + createdAt |
| 68 | + } |
| 69 | + } |
| 70 | + ` |
| 71 | + const userInfo = await graphqlFetch<{ data: { user: { createdAt: string } } }>({ |
| 72 | + query: userInfoQuery, |
| 73 | + variables: { login }, |
| 74 | + }) |
| 75 | + |
| 76 | + const accountCreated = new Date(userInfo.data.user.createdAt) |
| 77 | + const now = new Date() |
| 78 | + |
| 79 | + const years: Array<{ from: string; to: string }> = [] |
| 80 | + for (let year = accountCreated.getFullYear(); year <= now.getFullYear(); year++) { |
| 81 | + const from = year === accountCreated.getFullYear() |
| 82 | + ? accountCreated.toISOString() |
| 83 | + : `${year}-01-01T00:00:00Z` |
| 84 | + const to = year === now.getFullYear() |
| 85 | + ? now.toISOString() |
| 86 | + : `${year}-12-31T23:59:59Z` |
| 87 | + years.push({ from, to }) |
| 88 | + } |
| 89 | + |
| 90 | + console.log(`[contribkit][githubContributions] querying contributions across ${years.length} years...`) |
| 91 | + |
| 92 | + for (const { from, to } of years) { |
| 93 | + try { |
| 94 | + const contributionsQuery = ` |
| 95 | + query($login: String!, $from: DateTime!, $to: DateTime!) { |
| 96 | + user(login: $login) { |
| 97 | + contributionsCollection(from: $from, to: $to) { |
| 98 | + commitContributionsByRepository { |
| 99 | + repository { |
| 100 | + name |
| 101 | + nameWithOwner |
| 102 | + url |
| 103 | + owner { login url avatarUrl __typename } |
| 104 | + } |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | + } |
| 109 | + ` |
| 110 | + type ContributionsResponse = { data: { user: { contributionsCollection: { commitContributionsByRepository: Array<{ repository: RepoNode }> } } } } |
| 111 | + const contributionsResp: ContributionsResponse = await graphqlFetch<ContributionsResponse>({ |
| 112 | + query: contributionsQuery, |
| 113 | + variables: { login, from, to }, |
| 114 | + }) |
| 115 | + for (const item of contributionsResp.data.user.contributionsCollection.commitContributionsByRepository) { |
| 116 | + if (item.repository?.nameWithOwner) |
| 117 | + repoMap.set(item.repository.nameWithOwner, item.repository) |
| 118 | + } |
| 119 | + } |
| 120 | + catch (e: any) { |
| 121 | + console.warn(`[contribkit][githubContributions] failed contributions query for ${from.slice(0, 4)}:`, e.message) |
| 122 | + } |
| 123 | + } |
| 124 | + } |
| 125 | + catch (e: any) { |
| 126 | + console.warn(`[contribkit][githubContributions] contribution timeline discovery failed:`, e.message) |
| 127 | + } |
| 128 | + |
| 129 | + console.log(`[contribkit][githubContributions] found ${repoMap.size} repos after contribution timeline`) |
| 130 | + |
| 131 | + // Source 2: GraphQL search for repos with merged PRs (discover via PR activity) |
| 132 | + console.log(`[contribkit][githubContributions] searching for repos with merged PRs...`) |
| 133 | + try { |
| 134 | + const searchQueryBase = `is:pr is:merged author:${login}` |
| 135 | + let searchAfter: string | null = null |
| 136 | + let page = 0 |
| 137 | + const maxPages = 10 |
| 138 | + do { |
| 139 | + type SearchResponse = { data: { search: { pageInfo: { hasNextPage: boolean; endCursor: string | null }; edges: Array<{ node: { repository?: RepoNode } }> } } } |
| 140 | + const response: SearchResponse = await graphqlFetch<SearchResponse>({ |
| 141 | + query: ` |
| 142 | + query($searchQuery: String!, $after: String) { |
| 143 | + search(query: $searchQuery, type: ISSUE, first: 100, after: $after) { |
| 144 | + pageInfo { hasNextPage endCursor } |
| 145 | + edges { node { ... on PullRequest { repository { name nameWithOwner url owner { login url avatarUrl __typename } } } } } |
| 146 | + } |
| 147 | + } |
| 148 | + `, |
| 149 | + variables: { searchQuery: searchQueryBase, after: searchAfter }, |
| 150 | + }) |
| 151 | + for (const edge of response.data.search.edges) { |
| 152 | + const r = edge.node.repository |
| 153 | + if (r?.nameWithOwner) |
| 154 | + repoMap.set(r.nameWithOwner, r) |
| 155 | + } |
| 156 | + searchAfter = response.data.search.pageInfo.endCursor |
| 157 | + page++ |
| 158 | + if (response.data.search.pageInfo.hasNextPage && page < maxPages) |
| 159 | + console.log(`[contribkit][githubContributions] merged PR search page ${page}, ${repoMap.size} repos so far`) |
| 160 | + } while (searchAfter && page < maxPages) |
| 161 | + } |
| 162 | + catch (e: any) { |
| 163 | + console.warn(`[contribkit][githubContributions] merged PR search failed:`, e.message) |
| 164 | + } |
| 165 | + console.log(`[contribkit][githubContributions] found ${repoMap.size} repos after merged PR search`) |
| 166 | + |
| 167 | + const allRepos = Array.from(repoMap.values()) |
| 168 | + console.log(`[contribkit][githubContributions] discovered ${allRepos.length} total unique repositories`) |
| 169 | + |
| 170 | + // Fetch merged PR counts (completed contributions) |
| 171 | + console.log(`[contribkit][githubContributions] fetching merged PR counts per repository...`) |
| 172 | + const repoPRs = new Map<string, number>() |
| 173 | + const batchSize = 10 |
| 174 | + for (let i = 0; i < allRepos.length; i += batchSize) { |
| 175 | + const batch = allRepos.slice(i, i + batchSize) |
| 176 | + await Promise.all(batch.map(async (repo) => { |
| 177 | + const searchQuery = `repo:${repo.nameWithOwner} is:pr is:merged author:${login}` |
| 178 | + try { |
| 179 | + const response = await graphqlFetch<{ |
| 180 | + data: { search: { issueCount: number } } |
| 181 | + }>({ |
| 182 | + query: `query($q: String!) { search(query: $q, type: ISSUE) { issueCount } }`, |
| 183 | + variables: { q: searchQuery }, |
| 184 | + }) |
| 185 | + const count = response.data.search.issueCount |
| 186 | + if (count > 0) |
| 187 | + repoPRs.set(repo.nameWithOwner, count) |
| 188 | + } |
| 189 | + catch (e: any) { |
| 190 | + console.warn(`[contribkit][githubContributions] failed PR count for ${repo.nameWithOwner}:`, e.message) |
| 191 | + } |
| 192 | + })) |
| 193 | + if (i + batchSize < allRepos.length) |
| 194 | + console.log(`[contribkit][githubContributions] processed PR batches for ${Math.min(i + batchSize, allRepos.length)}/${allRepos.length} repos...`) |
| 195 | + } |
| 196 | + console.log(`[contribkit][githubContributions] found merged PR counts for ${repoPRs.size} repositories`) |
| 197 | + |
| 198 | + const results: { repo: RepoNode; prs: number }[] = [] |
| 199 | + for (const repo of allRepos) { |
| 200 | + const prs = repoPRs.get(repo.nameWithOwner) || 0 |
| 201 | + if (prs > 0) |
| 202 | + results.push({ repo, prs }) |
| 203 | + } |
| 204 | + console.log(`[contribkit][githubContributions] computed merged PR counts for ${results.length} repositories (from ${allRepos.length} total repos with PRs)`) |
| 205 | + |
| 206 | + // Aggregate by owner |
| 207 | + const aggregated = new Map<string, { owner: RepositoryOwner; totalPRs: number; repos: Array<{ repo: RepoNode; prs: number }> }>() |
| 208 | + for (const { repo, prs } of results) { |
| 209 | + const key = `${repo.owner.__typename}:${repo.owner.login}` |
| 210 | + const existing = aggregated.get(key) |
| 211 | + if (existing) { |
| 212 | + existing.totalPRs += prs |
| 213 | + existing.repos.push({ repo, prs }) |
| 214 | + } |
| 215 | + else { |
| 216 | + aggregated.set(key, { owner: repo.owner, totalPRs: prs, repos: [{ repo, prs }] }) |
| 217 | + } |
| 218 | + } |
| 219 | + |
| 220 | + const consolidated = Array.from(aggregated.values()).filter(a => a.repos.length > 1) |
| 221 | + if (consolidated.length) { |
| 222 | + console.log(`[contribkit][githubContributions] consolidated ${consolidated.length} owners with multiple repos:`) |
| 223 | + for (const { owner, repos, totalPRs } of consolidated.toSorted((a, b) => b.repos.length - a.repos.length).slice(0, 10)) |
| 224 | + console.log(` - ${owner.login}: ${repos.length} repos, ${totalPRs} merged PRs`) |
| 225 | + if (consolidated.length > 10) |
| 226 | + console.log(` ... and ${consolidated.length - 10} more`) |
| 227 | + } |
| 228 | + |
| 229 | + const sponsors: Sponsorship[] = Array.from(aggregated.values()) |
| 230 | + .sort((a, b) => b.totalPRs - a.totalPRs) |
| 231 | + .map(({ owner, totalPRs, repos }) => { |
| 232 | + const linkUrl = repos.length === 1 ? repos[0].repo.url : owner.url |
| 233 | + return { |
| 234 | + sponsor: { type: owner.__typename, login: owner.login, name: owner.login, avatarUrl: owner.avatarUrl, linkUrl, socialLogins: { github: owner.login } }, |
| 235 | + isOneTime: false, |
| 236 | + monthlyDollars: totalPRs, |
| 237 | + privacyLevel: 'PUBLIC', |
| 238 | + tierName: 'Repository', |
| 239 | + createdAt: new Date().toISOString(), |
| 240 | + provider: 'githubContributions', |
| 241 | + raw: { owner, totalPRs, repoCount: repos.length }, |
| 242 | + } |
| 243 | + }) |
| 244 | + |
| 245 | + return sponsors |
| 246 | +} |
0 commit comments