|
| 1 | +const REPO = "vixcpp/vix"; |
| 2 | +const API = `https://api.github.com/repos/${REPO}`; |
| 3 | + |
| 4 | +const LS_KEY = `vix_github_stats_${REPO}`; |
| 5 | +const TTL_MS = 6 * 60 * 60 * 1000; |
| 6 | + |
| 7 | +function isFresh(ts) { |
| 8 | + if (!ts) return false; |
| 9 | + const t = new Date(ts).getTime(); |
| 10 | + return Number.isFinite(t) && Date.now() - t < TTL_MS; |
| 11 | +} |
| 12 | + |
| 13 | +function readCache() { |
| 14 | + try { |
| 15 | + const raw = localStorage.getItem(LS_KEY); |
| 16 | + if (!raw) return null; |
| 17 | + const data = JSON.parse(raw); |
| 18 | + if (!isFresh(data?.fetched_at)) return null; |
| 19 | + return data; |
| 20 | + } catch { |
| 21 | + return null; |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +function writeCache(data) { |
| 26 | + try { |
| 27 | + localStorage.setItem(LS_KEY, JSON.stringify(data)); |
| 28 | + } catch {} |
| 29 | +} |
| 30 | + |
| 31 | +// ✅ no Vite import resolution, no crash |
| 32 | +async function loadBuildStats() { |
| 33 | + try { |
| 34 | + const url = new URL("../data/github_stats.json", import.meta.url); |
| 35 | + const res = await fetch(url); |
| 36 | + if (!res.ok) throw new Error("stats json missing"); |
| 37 | + return await res.json(); |
| 38 | + } catch { |
| 39 | + return { |
| 40 | + repo: REPO, |
| 41 | + fetched_at: null, |
| 42 | + stars: 0, |
| 43 | + forks: 0, |
| 44 | + open_issues: 0, |
| 45 | + watchers: 0, |
| 46 | + fallback: true, |
| 47 | + }; |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +export async function getInitialGithubStats() { |
| 52 | + return readCache() || (await loadBuildStats()); |
| 53 | +} |
| 54 | + |
| 55 | +export async function refreshGithubStats({ timeoutMs = 1200 } = {}) { |
| 56 | + const controller = new AbortController(); |
| 57 | + const t = setTimeout(() => controller.abort(), timeoutMs); |
| 58 | + |
| 59 | + try { |
| 60 | + const res = await fetch(API, { |
| 61 | + signal: controller.signal, |
| 62 | + headers: { Accept: "application/vnd.github+json" }, |
| 63 | + }); |
| 64 | + |
| 65 | + if (!res.ok) return null; |
| 66 | + |
| 67 | + const repo = await res.json(); |
| 68 | + |
| 69 | + const data = { |
| 70 | + repo: REPO, |
| 71 | + fetched_at: new Date().toISOString(), |
| 72 | + stars: repo.stargazers_count ?? 0, |
| 73 | + forks: repo.forks_count ?? 0, |
| 74 | + open_issues: repo.open_issues_count ?? 0, |
| 75 | + watchers: repo.subscribers_count ?? 0, |
| 76 | + }; |
| 77 | + |
| 78 | + writeCache(data); |
| 79 | + return data; |
| 80 | + } catch { |
| 81 | + return null; |
| 82 | + } finally { |
| 83 | + clearTimeout(t); |
| 84 | + } |
| 85 | +} |
0 commit comments