Repository navigation
Expand file tree
/
Copy pathgithub.ts
More file actions
374 lines (321 loc) · 10.5 KB
/
Copy pathgithub.ts
File metadata and controls
374 lines (321 loc) · 10.5 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
// lib/github.ts
import type { ContributionCalendar } from '../types';
import { calculateStreak } from './calculate';
import { TTLCache } from './cache';
interface GitHubRepo {
stargazers_count: number;
language: string | null;
}
const MAX_RETRIES = 3;
const BASE_DELAY_MS = 500;
/**
* Wraps fetch with exponential backoff retry logic.
* Retries ONLY on network errors, 429 Too Many Requests, and 5xx server errors.
* Returns immediately for all other statuses (2xx success, 3xx redirects, 4xx client errors).
*/
export async function fetchWithRetry(
url: string,
options: RequestInit,
attempt = 0
): Promise<Response> {
let res: Response | null = null;
try {
res = await fetch(url, options);
} catch (err) {
// Network error — retry if attempts remain, otherwise rethrow
if (attempt >= MAX_RETRIES) throw err;
const delay = BASE_DELAY_MS * Math.pow(2, attempt);
await new Promise((resolve) => setTimeout(resolve, delay));
return fetchWithRetry(url, options, attempt + 1);
}
// Only retry on 429 or 5xx — all other statuses are returned immediately
const shouldRetry = res.status === 429 || res.status >= 500;
if (!shouldRetry || attempt >= MAX_RETRIES) return res;
const delay = BASE_DELAY_MS * Math.pow(2, attempt);
await new Promise((resolve) => setTimeout(resolve, delay));
return fetchWithRetry(url, options, attempt + 1);
}
const GITHUB_GRAPHQL_URL = 'https://api.github.com/graphql';
const GITHUB_REST_URL = 'https://api.github.com';
type GitHubContributionResponse = {
data: {
user: {
contributionsCollection: {
contributionCalendar: ContributionCalendar;
};
} | null;
};
errors?: Array<{ message: string }>;
};
type FetchOptions = {
bypassCache?: boolean;
from?: string;
to?: string;
};
export const GITHUB_CACHE_TTL_MS = 5 * 60 * 1000;
interface GitHubUserProfile {
login: string;
name: string | null;
avatar_url: string;
public_repos: number;
followers: number;
following: number;
created_at: string;
bio: string | null;
location: string | null;
plan?: { name?: string } | null;
}
const contributionsCache = new TTLCache<ContributionCalendar>();
const profileCache = new TTLCache<GitHubUserProfile>();
const reposCache = new TTLCache<GitHubRepo[]>();
function cacheKey(
kind: 'contributions' | 'profile' | 'repos',
username: string,
year?: string
): string {
return year ? `${kind}:${username.toLowerCase()}:${year}` : `${kind}:${username.toLowerCase()}`;
}
export function clearGitHubApiCacheForTests(): void {
contributionsCache.clear();
profileCache.clear();
reposCache.clear();
}
const getHeaders = () => ({
Authorization: `bearer ${process.env.GITHUB_PAT || process.env.GITHUB_TOKEN}`,
'Content-Type': 'application/json',
});
export async function fetchGitHubContributions(
username: string,
options: FetchOptions = {}
): Promise<ContributionCalendar> {
const key = cacheKey('contributions', username, options.from?.substring(0, 4));
if (!options.bypassCache) {
const cached = contributionsCache.get(key);
if (cached) return cached;
}
const query = `
query($login: String!, $from: DateTime, $to: DateTime) {
user(login: $login) {
contributionsCollection(from: $from, to: $to) {
contributionCalendar {
totalContributions
weeks {
contributionDays {
contributionCount
date
color
}
}
}
}
}
}
`;
const res = await fetchWithRetry(GITHUB_GRAPHQL_URL, {
method: 'POST',
headers: getHeaders(),
body: JSON.stringify({
query,
variables: { login: username, from: options.from, to: options.to },
}),
cache: 'no-store', // Cache handled by our in-memory layer + API route headers
});
if (!res.ok) {
if (res.status === 401) throw new Error('GitHub PAT is invalid or missing');
throw new Error(`GitHub GraphQL API returned status ${res.status}`);
}
const data: GitHubContributionResponse = await res.json();
if (data.errors) {
throw new Error(data.errors[0].message);
}
if (!data.data.user) {
throw new Error(`GitHub user "${username}" not found`);
}
const calendar = data.data.user.contributionsCollection.contributionCalendar;
if (!options.bypassCache) {
contributionsCache.set(key, calendar, GITHUB_CACHE_TTL_MS);
}
return calendar;
}
export async function fetchUserProfile(
username: string,
options: FetchOptions = {}
): Promise<GitHubUserProfile> {
const key = cacheKey('profile', username);
if (!options.bypassCache) {
const cached = profileCache.get(key);
if (cached) return cached;
}
const res = await fetchWithRetry(`${GITHUB_REST_URL}/users/${username}`, {
headers: getHeaders(),
cache: 'no-store',
});
if (!res.ok) {
if (res.status === 404) throw new Error('User not found');
throw new Error(`GitHub REST API error: ${res.status}`);
}
const profile = (await res.json()) as GitHubUserProfile;
if (!options.bypassCache) {
profileCache.set(key, profile, GITHUB_CACHE_TTL_MS);
}
return profile;
}
export async function fetchUserRepos(
username: string,
options: FetchOptions = {}
): Promise<GitHubRepo[]> {
const key = cacheKey('repos', username);
if (!options.bypassCache) {
const cached = reposCache.get(key);
if (cached) return cached;
}
const res = await fetchWithRetry(
`${GITHUB_REST_URL}/users/${username}/repos?per_page=100&sort=pushed`,
{
headers: getHeaders(),
cache: 'no-store',
}
);
if (!res.ok) {
throw new Error(`GitHub REST API error: ${res.status}`);
}
const repos = (await res.json()) as GitHubRepo[];
if (!options.bypassCache) {
reposCache.set(key, repos, GITHUB_CACHE_TTL_MS);
}
return repos;
}
export async function getFullDashboardData(username: string, options: FetchOptions = {}) {
try {
const [profileData, reposData, calendarData] = await Promise.all([
fetchUserProfile(username, options),
fetchUserRepos(username, options),
fetchGitHubContributions(username, options),
]);
// Pre-compute streak + stars early so developerScore can use them
const streakStats = calculateStreak(calendarData);
const totalStars = reposData.reduce(
(acc: number, repo: GitHubRepo) => acc + repo.stargazers_count,
0
);
// Developer Score — 5-factor weighted formula (max 100 pts)
// Repos: up to 25 pts (saturates at 50 public repos)
// Followers: up to 25 pts (saturates at 50 followers)
// Stars: up to 20 pts (saturates at 100 total stars)
// Contributions: up to 20 pts (saturates at 400 yearly contributions)
// Streak: up to 10 pts (saturates at a 50-day longest streak)
const developerScore = Math.min(
Math.round(
Math.min(profileData.public_repos * 0.5, 25) +
Math.min(profileData.followers * 0.5, 25) +
Math.min(totalStars * 0.2, 20) +
Math.min(streakStats.totalContributions / 20, 20) +
Math.min(streakStats.longestStreak * 0.2, 10)
),
100
);
// 1. Profile Mapping
const profile = {
username: profileData.login,
name: profileData.name || profileData.login,
avatarUrl: profileData.avatar_url,
isPro: profileData.plan?.name === 'pro' || profileData.public_repos > 50,
bio: profileData.bio || 'No bio available',
location: profileData.location || 'Earth',
joinedDate: new Date(profileData.created_at).toLocaleDateString('en-US', {
month: 'short',
year: 'numeric',
}),
developerScore,
stats: {
repositories: profileData.public_repos,
followers: profileData.followers,
following: profileData.following,
stars: totalStars,
},
};
// 2. Streaks & Activity Mapping (streakStats already computed above)
// Flatten days for charts
const allDays = calendarData.weeks.flatMap((w) => w.contributionDays);
const activity = allDays.map((day) => {
let intensity: 0 | 1 | 2 | 3 | 4 = 0;
if (day.contributionCount > 0) intensity = 1;
if (day.contributionCount > 3) intensity = 2;
if (day.contributionCount > 6) intensity = 3;
if (day.contributionCount > 10) intensity = 4;
return {
date: day.date,
count: day.contributionCount,
intensity,
};
});
// 3. Languages Mapping
const langCounts: Record<string, number> = {};
reposData.forEach((repo: GitHubRepo) => {
if (repo.language) {
langCounts[repo.language] = (langCounts[repo.language] || 0) + 1;
}
});
// Fixed color mapping for common languages to avoid random colors
const languageColors: Record<string, string> = {
TypeScript: '#3178c6',
JavaScript: '#f1e05a',
Python: '#3572A5',
Java: '#b07219',
'C++': '#f34b7d',
HTML: '#e34c26',
CSS: '#563d7c',
Go: '#00ADD8',
Rust: '#dea584',
};
const totalLangs = Object.values(langCounts).reduce((a, b) => a + b, 0);
const languages = Object.entries(langCounts)
.map(([name, count]) => ({
name,
percentage: Math.round((count / totalLangs) * 100),
color: languageColors[name] || '#a855f7', // fallback purple
}))
.sort((a, b) => b.percentage - a.percentage)
.slice(0, 5); // top 5
// 4. Insights Generation
const insights = [
{
id: '1',
icon: 'Flame',
text: `You have a total of ${streakStats.totalContributions} contributions this year.`,
},
{
id: '2',
icon: 'Code',
text: `Your primary language is ${languages[0]?.name || 'Unknown'}.`,
},
{
id: '3',
icon: 'Star',
text: `Your longest coding streak is ${streakStats.longestStreak} days!`,
},
];
// Simulate 24h cycle (because GitHub events API is heavily rate limited to 300 events which doesn't give a full picture)
const commitClock = Array.from({ length: 24 }).map((_, i) => ({
hour: i,
commits: Math.floor(Math.random() * 20) + (i >= 9 && i <= 17 ? 30 : 0), // working hours peak
}));
return {
profile,
stats: {
currentStreak: streakStats.currentStreak,
peakStreak: streakStats.longestStreak,
totalContributions: streakStats.totalContributions,
},
languages,
activity,
insights,
commitClock,
};
} catch (error: unknown) {
if (error instanceof Error) {
throw new Error(error.message);
}
throw new Error('An unknown error occurred');
}
}