-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgithub-graphql.ts
More file actions
464 lines (398 loc) · 13.3 KB
/
github-graphql.ts
File metadata and controls
464 lines (398 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import { graphql } from '@octokit/graphql';
import type { GitHubUser, Repository, Commit, ContributionDay } from './types.js';
interface GraphQLResponse {
viewer?: {
login: string;
name: string;
avatarUrl: string;
bio: string;
company: string;
location: string;
createdAt: string;
repositories: { totalCount: number };
followers: { totalCount: number };
following: { totalCount: number };
contributionsCollection: ContributionsCollectionData;
repositories_data: RepositoriesData;
};
user?: {
login: string;
name: string;
avatarUrl: string;
bio: string;
company: string;
location: string;
createdAt: string;
repositories: { totalCount: number };
followers: { totalCount: number };
following: { totalCount: number };
contributionsCollection: ContributionsCollectionData;
repositories_data: RepositoriesData;
};
}
interface ContributionsCollectionData {
totalCommitContributions: number;
totalIssueContributions: number;
totalPullRequestContributions: number;
totalPullRequestReviewContributions: number;
contributionCalendar: {
totalContributions: number;
weeks: Array<{
contributionDays: Array<{
contributionCount: number;
date: string;
weekday: number;
color: string;
}>;
}>;
};
commitContributionsByRepository: Array<{
repository: {
name: string;
nameWithOwner: string;
stargazerCount: number;
forkCount: number;
primaryLanguage: { name: string; color: string } | null;
};
contributions: {
totalCount: number;
nodes: Array<{
occurredAt: string;
}>;
};
}>;
pullRequestContributions: {
totalCount: number;
nodes: Array<{
pullRequest: {
title: string;
createdAt: string;
additions: number;
deletions: number;
changedFiles: number;
repository: { name: string };
} | null;
}>;
};
}
interface RepositoriesData {
totalCount: number;
nodes: Array<{
name: string;
stargazerCount: number;
forkCount: number;
description: string;
url: string;
createdAt: string;
updatedAt: string;
primaryLanguage: { name: string; color: string } | null;
}>;
}
export class GitHubGraphQLClient {
private graphqlWithAuth: typeof graphql;
private username: string;
private statsCache: Map<number, GraphQLResponse> = new Map();
constructor(username: string, token?: string) {
this.username = username;
this.graphqlWithAuth = graphql.defaults({
headers: {
authorization: token ? `bearer ${token}` : undefined,
},
});
}
private async getCompleteStats(year: number = 2025): Promise<GraphQLResponse> {
// Return cached data if available
if (this.statsCache.has(year)) {
return this.statsCache.get(year)!;
}
const startDate = new Date(`${year}-01-01`);
const today = new Date();
const yearEnd = new Date(`${year}-12-31`);
const endDate = year === today.getFullYear() ? today : yearEnd;
// Check if year is in the future
if (startDate > today) {
throw new Error(`Year ${year} is in the future. Please use ${today.getFullYear()} or earlier.`);
}
// Always use user(login:) query - token just provides higher rate limits
// and access to private contributions for the queried user
const query = `
query($username: String!, $from: DateTime!, $to: DateTime!) {
user(login: $username) {
login
name
avatarUrl
bio
company
location
createdAt
repositories {
totalCount
}
followers {
totalCount
}
following {
totalCount
}
# ContributionsCollection - requires authentication
contributionsCollection(from: $from, to: $to) {
totalCommitContributions
totalIssueContributions
totalPullRequestContributions
totalPullRequestReviewContributions
contributionCalendar {
totalContributions
weeks {
contributionDays {
contributionCount
date
weekday
color
}
}
}
commitContributionsByRepository(maxRepositories: 100) {
repository {
name
nameWithOwner
stargazerCount
forkCount
primaryLanguage {
name
color
}
}
contributions(first: 100) {
totalCount
nodes {
occurredAt
}
}
}
pullRequestContributions(first: 100) {
totalCount
nodes {
pullRequest {
title
createdAt
additions
deletions
changedFiles
repository {
name
}
}
}
}
}
repositories_data: repositories(first: 10, orderBy: {field: STARGAZERS, direction: DESC}) {
totalCount
nodes {
name
stargazerCount
forkCount
description
url
createdAt
updatedAt
primaryLanguage {
name
color
}
}
}
}
}
`;
try {
const variables = {
username: this.username,
from: startDate.toISOString(),
to: endDate.toISOString()
};
const result = await this.graphqlWithAuth<GraphQLResponse>(query, variables);
// Get user data from the user query
const userData = result.user;
// Validate response structure
if (!userData) {
throw new Error(`Failed to fetch user data. Please check the username or token.`);
}
if (!userData.contributionsCollection) {
throw new Error(`⚠️ AUTHENTICATION REQUIRED
GitHub's API requires authentication to access contribution data.
What you need:
1. Create a Personal Access Token at: https://github.com/settings/tokens
2. Required scopes:
- read:user (for contribution data)
- repo (to include private repository commits)
3. Run this app again and provide the token when prompted
Why this is needed:
- Without a token: Only public repository data is visible
- With a token (read:user): Public contributions and statistics
- With a token (read:user + repo): All contributions including private repositories
Get your token now: https://github.com/settings/tokens/new?description=GitHub%20Wrapped&scopes=read:user,repo`);
}
// Normalize the response
const normalizedResult: GraphQLResponse = { user: userData as any };
// Cache the result
this.statsCache.set(year, normalizedResult);
return normalizedResult;
} catch (error: unknown) {
// Clear cache on error
this.statsCache.delete(year);
// Type-safe error handling
const errorMessage = error instanceof Error ? error.message : String(error);
const errorStatus = (error as any)?.status; // GraphQL errors may have status
// Handle specific errors
if (errorMessage.includes('AUTHENTICATION REQUIRED')) {
throw error instanceof Error ? error : new Error(errorMessage);
}
if (errorMessage.includes('NOT_FOUND') || errorMessage.includes('Could not resolve to a User')) {
throw new Error(`GitHub user "${this.username}" not found. Please check the username and try again.`);
}
if (errorStatus === 401 || errorMessage.includes('Bad credentials')) {
throw new Error(`Invalid GitHub token. Please check your token and try again.
Get a new token at: https://github.com/settings/tokens
Required scopes: read:user, repo (for private repositories)`);
}
if (errorStatus === 403 || errorMessage.includes('rate limit')) {
throw new Error('GitHub API rate limit exceeded. Please use a GitHub token for higher limits.');
}
throw new Error(`Failed to fetch data: ${errorMessage}`);
}
}
private getUserData(response: GraphQLResponse) {
return response.user!;
}
async getUser(): Promise<GitHubUser> {
const data = await this.getCompleteStats();
const user = this.getUserData(data);
return {
login: user.login,
name: user.name,
avatar_url: user.avatarUrl,
bio: user.bio,
company: user.company,
location: user.location,
public_repos: user.repositories.totalCount,
followers: user.followers.totalCount,
following: user.following.totalCount,
created_at: user.createdAt,
} as GitHubUser;
}
async getRepositories(): Promise<Repository[]> {
const data = await this.getCompleteStats();
const user = this.getUserData(data);
return user.repositories_data.nodes.map((repo) => ({
name: repo.name,
full_name: `${user.login}/${repo.name}`,
stargazers_count: repo.stargazerCount,
forks_count: repo.forkCount,
description: repo.description,
html_url: repo.url,
language: repo.primaryLanguage?.name || 'Unknown',
created_at: repo.createdAt,
updated_at: repo.updatedAt,
size: 0,
})) as Repository[];
}
async getCommitsForYear(year: number = 2025): Promise<Commit[]> {
const data = await this.getCompleteStats(year);
const user = this.getUserData(data);
const commits: Commit[] = [];
const repoContribs = user.contributionsCollection.commitContributionsByRepository || [];
for (const repoContrib of repoContribs) {
if (!repoContrib?.repository || !repoContrib?.contributions?.nodes) continue;
for (const contrib of repoContrib.contributions.nodes) {
if (!contrib?.occurredAt) continue;
commits.push({
sha: '',
commit: {
author: {
date: contrib.occurredAt,
name: user.login,
email: '',
},
message: '',
},
repository: repoContrib.repository.name,
} as Commit);
}
}
if (commits.length === 0) {
throw new Error(`No commits found for ${this.username} in ${year}. Try a different year or username.`);
}
return commits;
}
async getPullRequests(year: number = 2025): Promise<number> {
const data = await this.getCompleteStats(year);
const user = this.getUserData(data);
return user.contributionsCollection?.totalPullRequestContributions || 0;
}
async getIssues(year: number = 2025): Promise<number> {
const data = await this.getCompleteStats(year);
const user = this.getUserData(data);
return user.contributionsCollection?.totalIssueContributions || 0;
}
async getLanguages(): Promise<{ [key: string]: number }> {
const data = await this.getCompleteStats();
const user = this.getUserData(data);
const languageStats: { [key: string]: number } = {};
const repoContribs = user.contributionsCollection.commitContributionsByRepository || [];
for (const repoContrib of repoContribs) {
if (!repoContrib?.repository?.primaryLanguage) continue;
const lang = repoContrib.repository.primaryLanguage.name;
const count = repoContrib.contributions.totalCount;
languageStats[lang] = (languageStats[lang] || 0) + count;
}
return languageStats;
}
async getContributionCalendar(year: number = 2025): Promise<ContributionDay[]> {
const data = await this.getCompleteStats(year);
const user = this.getUserData(data);
const calendar = user.contributionsCollection?.contributionCalendar;
const contributions: ContributionDay[] = [];
if (!calendar?.weeks) {
return contributions;
}
for (const week of calendar.weeks) {
if (!week?.contributionDays) continue;
for (const day of week.contributionDays) {
if (!day?.date) continue;
contributions.push({
date: day.date,
count: day.contributionCount || 0,
});
}
}
return contributions;
}
async getTotalLinesChanged(year: number = 2025): Promise<{ additions: number; deletions: number; total: number }> {
const data = await this.getCompleteStats(year);
const user = this.getUserData(data);
const prs = user.contributionsCollection.pullRequestContributions?.nodes || [];
let totalAdditions = 0;
let totalDeletions = 0;
for (const pr of prs) {
if (pr?.pullRequest) {
totalAdditions += pr.pullRequest.additions || 0;
totalDeletions += pr.pullRequest.deletions || 0;
}
}
return {
additions: totalAdditions,
deletions: totalDeletions,
total: totalAdditions + totalDeletions,
};
}
async getCodeReviewCount(year: number = 2025): Promise<number> {
const data = await this.getCompleteStats(year);
const user = this.getUserData(data);
return user.contributionsCollection?.totalPullRequestReviewContributions || 0;
}
async getTotalCommitCount(year: number = 2025): Promise<number> {
const data = await this.getCompleteStats(year);
const user = this.getUserData(data);
return user.contributionsCollection?.totalCommitContributions || 0;
}
}