web/src/utils/fetch-repo-info.ts
150 lines · 4337 bytes
1import { error } from './logger';
2
3const githubHeaders = (): Record<string, string> => {
4 const headers: Record<string, string> = {
5 'User-Agent': 'awesome-privacy',
6 'Accept': 'application/vnd.github.v3+json',
7 };
8 const token = import.meta.env.GITHUB_API_KEY;
9 if (token) headers['Authorization'] = `token ${token}`;
10 return headers;
11};
12
13const fetchFromGitHub = async (github: string): Promise<GitHubStatsResponse | null> => {
14 const base = `https://api.github.com/repos/${github}`;
15 const headers = githubHeaders();
16
17 const [infoRes, langsRes, tagsRes, contribRes, commitsRes] = await Promise.all([
18 fetch(base, { headers }),
19 fetch(`${base}/languages`, { headers }),
20 fetch(`${base}/tags`, { headers }),
21 fetch(`${base}/contributors`, { headers }),
22 fetch(`${base}/commits`, { headers }),
23 ]);
24
25 if (!infoRes.ok) {
26 error('GitHub Stats', `GitHub API returned ${infoRes.status} for ${github}`);
27 return null;
28 }
29
30 const parseJson = (r: Response) =>
31 r.ok && r.status !== 204 ? r.json() : null;
32
33 const [info, languages, tags, contributors, commits] = await Promise.all(
34 [infoRes, langsRes, tagsRes, contribRes, commitsRes].map(parseJson),
35 );
36
37 return {
38 info: {
39 ownerUsername: info.owner?.login ?? '',
40 ownerAvatar: info.owner?.avatar_url ?? '',
41 description: info.description ?? '',
42 url: info.html_url ?? '',
43 homepage: info.homepage ?? '',
44 language: info.language ?? '',
45 topics: info.topics ?? [],
46 license: info.license?.spdx_id ?? '',
47 isFork: info.fork ?? false,
48 isArchived: info.archived ?? false,
49 createdAt: info.created_at ?? '',
50 updatedAt: info.updated_at ?? '',
51 size: info.size ?? 0,
52 scarCount: info.stargazers_count ?? 0,
53 forksCount: info.forks_count ?? 0,
54 watchersCount: info.watchers_count ?? 0,
55 },
56 languages: languages ?? {},
57 versions: (tags ?? []).map((tag: any) => ({
58 name: tag.name,
59 commit: tag.commit?.sha ?? '',
60 zipball: tag.zipball_url ?? '',
61 tarball: tag.tarball_url ?? '',
62 })),
63 contributors: (contributors ?? []).map((c: any) => ({
64 username: c.login ?? '',
65 avatar: c.avatar_url ?? '',
66 contributions: c.contributions ?? 0,
67 })),
68 commits: (commits ?? []).map((c: any) => ({
69 sha: c.sha ?? '',
70 authorName: c.commit?.author?.name ?? '',
71 authorDate: c.commit?.author?.date ?? '',
72 message: c.commit?.message ?? '',
73 authorUsername: c.author?.login ?? '',
74 authorAvatar: c.author?.avatar_url ?? '',
75 })),
76 };
77};
78
79const fetchFromWorker = async (github: string): Promise<GitHubStatsResponse | null> => {
80 const res = await fetch(`https://repo-info.as93.workers.dev/${github}`);
81 if (!res.ok) return null;
82 return res.json();
83};
84
85const normalizeRepo = (github: string): string =>
86 github.replace(/^https?:\/\/github\.com\//, '');
87
88export const fetchGitHubStats = async (
89 github: string,
90): Promise<GitHubStatsResponse | null> => {
91 github = normalizeRepo(github);
92 try {
93 const result = await fetchFromGitHub(github);
94 if (result) return result;
95 const fallback = await fetchFromWorker(github);
96 if (fallback) return fallback;
97 error('GitHub Stats', `Both direct API and worker failed for ${github}`);
98 return null;
99 } catch (err) {
100 try {
101 return await fetchFromWorker(github);
102 } catch {
103 error('GitHub Stats', `All fetches failed for ${github}: ${err}`);
104 return null;
105 }
106 }
107};
108
109export interface GitHubStatsResponse {
110 info: {
111 ownerUsername: string;
112 ownerAvatar: string;
113 description: string;
114 url: string;
115 homepage: string;
116 language: string;
117 topics: string[];
118 license: string;
119 isFork: boolean;
120 isArchived: boolean;
121 createdAt: string;
122 updatedAt: string;
123 size: number;
124 scarCount: number;
125 forksCount: number;
126 watchersCount: number;
127 };
128 languages: {
129 [key: string]: number;
130 };
131 versions: Array<{
132 name: string;
133 commit: string;
134 zipball: string;
135 tarball: string;
136 }>;
137 contributors: Array<{
138 username: string;
139 avatar: string;
140 contributions: number;
141 }>;
142 commits: Array<{
143 sha: string;
144 authorName: string;
145 authorDate: string;
146 message: string;
147 authorUsername: string;
148 authorAvatar: string;
149 }>;
150}