返回 CodeWhale
github.ts
根目录 / web / lib / github.ts
1 import { OUTBOUND_TIMEOUT_MS } from "./bounded-body";
2 import snapshot from "../data/repo-stats-snapshot.json";
3 import type { RepoStats } from "./types";
4
5 const SNAPSHOT: unknown = snapshot;
6
7 const REPO = process.env.GITHUB_REPO ?? "codewhale-hq/CodeWhale";
8 const GH = "https://api.github.com";
9
10 function isProductionBuild(): boolean {
11 return process.env.NEXT_PHASE === "phase-production-build";
12 }
13
14 function headers(token?: string): HeadersInit {
15 const h: Record<string, string> = {
16 Accept: "application/vnd.github+json",
17 "X-GitHub-Api-Version": "2022-11-28",
18 "User-Agent": "codewhale-web",
19 };
20 if (token) h.Authorization = `Bearer ${token}`;
21 return h;
22 }
23
24 const UNKNOWN_STATS: RepoStats = {
25 stars: null,
26 forks: null,
27 openIssues: null,
28 openPulls: null,
29 contributors: null,
30 fetchedAt: null,
31 source: "unknown",
32 };
33
34 function count(value: unknown): number | null {
35 return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
36 }
37
38 export function readRepoStatsSnapshot(raw: unknown = SNAPSHOT): RepoStats {
39 if (!raw || typeof raw !== "object") return UNKNOWN_STATS;
40 const row = raw as Record<string, unknown>;
41 if (typeof row.readAt !== "string" || !Number.isFinite(Date.parse(row.readAt))) return UNKNOWN_STATS;
42 const stars = count(row.stars);
43 if (stars === null || stars === 0) return UNKNOWN_STATS;
44 return {
45 stars,
46 forks: count(row.forks),
47 openIssues: count(row.openIssues),
48 openPulls: count(row.openPulls),
49 contributors: null,
50 fetchedAt: row.readAt,
51 source: "snapshot",
52 };
53 }
54
55 export async function fetchRepoStats(token?: string): Promise<RepoStats> {
56 if (isProductionBuild()) return readRepoStatsSnapshot();
57
58 try {
59 const [repoRes, contribRes, releaseRes] = await Promise.all([
60 fetch(`${GH}/repos/${REPO}`, { headers: headers(token), signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS), next: { revalidate: 1800 } }),
61 fetch(`${GH}/repos/${REPO}/contributors?per_page=1&anon=true`, {
62 headers: headers(token), signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS),
63 next: { revalidate: 3600 },
64 }),
65 fetch(`${GH}/repos/${REPO}/releases/latest`, { headers: headers(token), signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS), next: { revalidate: 3600 } }),
66 ]);
67
68 const repo = repoRes.ok ? await repoRes.json().catch(() => null) : null;
69 const stars = numberField(repo, "stargazers_count");
70 const forks = numberField(repo, "forks_count");
71 const repoOpenCount = numberField(repo, "open_issues_count");
72 const contributors = contribRes.ok ? (lastPageFromLink(contribRes.headers.get("link")) ?? null) : null;
73
74 const prRes = await fetch(
75 `${GH}/search/issues?q=${encodeURIComponent(`repo:${REPO} is:pr is:open`)}&per_page=1`,
76 { headers: headers(token), signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS), next: { revalidate: 1800 } }
77 );
78 const prJson = prRes.ok ? ((await prRes.json().catch(() => null)) as { total_count?: unknown } | null) : null;
79 const openPulls = count(prJson?.total_count);
80 const openIssues = repoOpenCount !== null && openPulls !== null ? Math.max(0, repoOpenCount - openPulls) : null;
81
82 let latestRelease: RepoStats["latestRelease"];
83 if (releaseRes.ok) {
84 const r = (await releaseRes.json().catch(() => null)) as { tag_name?: string; published_at?: string; html_url?: string } | null;
85 if (r && typeof r.tag_name === "string" && typeof r.published_at === "string" && typeof r.html_url === "string") {
86 latestRelease = { tag: r.tag_name, publishedAt: r.published_at, url: r.html_url };
87 }
88 }
89
90 if (stars === null) return UNKNOWN_STATS;
91 return {
92 stars: stars === 0 ? null : stars,
93 forks,
94 openIssues,
95 openPulls,
96 contributors,
97 latestRelease,
98 fetchedAt: new Date().toISOString(),
99 source: "live",
100 };
101 } catch {
102 return UNKNOWN_STATS;
103 }
104 }
105
106 function numberField(body: unknown, key: string): number | null {
107 if (!body || typeof body !== "object") return null;
108 return count((body as Record<string, unknown>)[key]);
109 }
110
111 export function lastPageFromLink(link: string | null): number | undefined {
112 if (!link) return undefined;
113
114 for (const part of link.split(",")) {
115 const [rawUrl, rawRel] = part.split(";").map((segment) => segment.trim());
116 if (rawRel !== 'rel="last"') continue;
117
118 const match = rawUrl.match(/^<(.+)>$/);
119 if (!match) continue;
120
121 const page = new URL(match[1]).searchParams.get("page");
122 const parsed = page ? Number.parseInt(page, 10) : NaN;
123 if (Number.isFinite(parsed) && parsed > 0) return parsed;
124 }
125
126 return undefined;
127 }
128
129 interface RawIssue {
130 number: number;
131 title: string;
132 html_url: string;
133 comments: number;
134 labels: { name: string }[];
135 pull_request?: unknown;
136 }
137
138 export interface Face {
139 login: string;
140 avatar: string;
141 }
142
143 export interface OpenIssue {
144 number: number;
145 title: string;
146 url: string;
147 comments: number;
148 labels: string[];
149 }
150
151 export async function fetchLabelled(label: string, token?: string, limit = 6): Promise<OpenIssue[]> {
152 if (isProductionBuild()) return [];
153 const res = await fetch(
154 `${GH}/repos/${REPO}/issues?state=open&labels=${encodeURIComponent(label)}&per_page=${limit}&sort=updated&direction=desc`,
155 { headers: headers(token), signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS), next: { revalidate: 1800 } },
156 );
157 const rows = await responseArray<RawIssue>(res);
158 return rows
159 .filter((i) => !i.pull_request)
160 .map((i) => ({
161 number: i.number,
162 title: i.title,
163 url: i.html_url,
164 comments: i.comments,
165 labels: (i.labels ?? []).map((l) => l.name).filter((name) => name !== label),
166 }));
167 }
168
169 async function responseArray<T>(res: Response): Promise<T[]> {
170 if (!res.ok) return [];
171 const body = await res.json().catch(() => null);
172 return Array.isArray(body) ? (body as T[]) : [];
173 }
174
175 /** Compact star-count label, e.g. 39312 → "39.3k". */
176 export function formatStars(n: number): string {
177 if (n >= 1000) {
178 return `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k`;
179 }
180 return String(n);
181 }
182
183 /**
184 * An age expressed the way `Intl.RelativeTimeFormat` wants it: a negative
185 * count and a unit. Past ages are negative; anything under a minute (and any
186 * unparseable or future date) is `0 seconds`, which `numeric: "auto"` renders
187 * as the locale's own "now".
188 *
189 * This exists so a surface can print an age in the reader's language without
190 * a hand-translated abbreviation table per locale — CLDR already has one, and
191 * the masthead already formats its date the same way off `chrome.dateLocale`.
192 */
193 export interface RelativeAge {
194 value: number;
195 unit: "second" | "minute" | "hour" | "day" | "month" | "year";
196 }
197
198 export function relativeAge(iso: string): RelativeAge {
199 const then = +new Date(iso);
200 if (!Number.isFinite(then)) return { value: 0, unit: "second" };
201
202 const mins = Math.round((Date.now() - then) / 60000);
203 if (mins < 1) return { value: 0, unit: "second" };
204 if (mins < 60) return { value: -mins, unit: "minute" };
205 const hrs = Math.round(mins / 60);
206 if (hrs < 24) return { value: -hrs, unit: "hour" };
207 const days = Math.round(hrs / 24);
208 if (days < 30) return { value: -days, unit: "day" };
209 const months = Math.round(days / 30);
210 if (months < 12) return { value: -months, unit: "month" };
211 return { value: -Math.round(months / 12), unit: "year" };
212 }
213
214 const AGE_SUFFIX: Record<RelativeAge["unit"], string> = {
215 second: "",
216 minute: "m",
217 hour: "h",
218 day: "d",
219 month: "mo",
220 year: "y",
221 };
222
223 /** Compact English age, e.g. "5m", "3h", "2y". Same thresholds as `relativeAge`. */
224 export function relativeTime(iso: string): string {
225 const age = relativeAge(iso);
226 if (age.unit === "second") return "just now";
227 return `${Math.abs(age.value)}${AGE_SUFFIX[age.unit]}`;
228 }
229
229 lines TYPESCRIPT