Commit 0c6cf335b1
Unsigned
Layout: unified · split
web/.env.sample +9 −1
| @@ -14,8 +14,16 @@ OUTPUT='' | |||
| 14 | # Used to generate sitemap.xml and for canonical URLs | 14 | # Used to generate sitemap.xml and for canonical URLs |
| 15 | SITE_URL='' | 15 | SITE_URL='' |
| 16 | 16 | ||
| 17 | # Base URL of the Awesome Privacy API (powers search and enrichment data). | ||
| 18 | # Defaults to the hosted instance; override to point at a self-hosted API. | ||
| 19 | PUBLIC_API_URL='https://api.awesome-privacy.xyz' | ||
| 20 | |||
| 21 | # Bearer token for the API's enrichment routes (/v1/enrich/*). | ||
| 22 | # Only needed at build-time, and only if the target API has auth enabled. | ||
| 23 | API_TOKEN='' | ||
| 24 | |||
| 17 | # GitHub API key (with pub repo read perms). | 25 | # GitHub API key (with pub repo read perms). |
| 18 | # This is used to fetch reposity stats for open source apps which are listed | 26 | # Used for repo metrics and contributor lists fetched directly from GitHub. |
| 19 | GITHUB_API_KEY='' | 27 | GITHUB_API_KEY='' |
| 20 | 28 | ||
| 21 | # A Font Awesome Pro package token | 29 | # A Font Awesome Pro package token |
web/src/components/things/GitHubDetailedInfo.astro +1 −1
| @@ -166,7 +166,7 @@ const languageChart = `https://quickchart.io/chart?c=${generateChartData(gitHubD | |||
| 166 | <h4>Size</h4> | 166 | <h4>Size</h4> |
| 167 | <p>{formatBigNumber(gitHubData.info.size)} KB</p> | 167 | <p>{formatBigNumber(gitHubData.info.size)} KB</p> |
| 168 | <h4>Stars</h4> | 168 | <h4>Stars</h4> |
| 169 | <p>{formatBigNumber(gitHubData.info.scarCount)}</p> | 169 | <p>{formatBigNumber(gitHubData.info.starCount)}</p> |
| 170 | <h4>Forks</h4> | 170 | <h4>Forks</h4> |
| 171 | <p>{formatBigNumber(gitHubData.info.forksCount)}</p> | 171 | <p>{formatBigNumber(gitHubData.info.forksCount)}</p> |
| 172 | <h4>Watchers</h4> | 172 | <h4>Watchers</h4> |
web/src/components/things/ItemGitHubMetrics.astro +69 −87
| @@ -1,120 +1,102 @@ | |||
| 1 | --- | 1 | --- |
| 2 | import FontAwesome from "@components/form/FontAwesome.svelte"; | 2 | import FontAwesome from '@components/form/FontAwesome.svelte'; |
| 3 | import { error } from "@utils/logger"; | 3 | import { error } from '@utils/logger'; |
| 4 | import { safeFetch } from '@utils/safe-fetch'; | ||
| 5 | import { fetchGitHubStats } from '@utils/fetch-repo-info'; | ||
| 6 | |||
| 4 | const { github } = Astro.props; | 7 | const { github } = Astro.props; |
| 5 | 8 | ||
| 6 | interface GitHubRepoData { | 9 | interface RepoMetrics { |
| 7 | stargazers_count?: number; | 10 | stars: number; |
| 8 | forks_count?: number; | 11 | forks: number; |
| 9 | open_issues_count?: number; | 12 | openIssues: number; |
| 10 | language?: string; | 13 | language: string; |
| 11 | license?: { spdx_id?: string; name?: string }; | 14 | licenseSpdx: string; |
| 15 | licenseName: string; | ||
| 12 | } | 16 | } |
| 13 | 17 | ||
| 14 | /** | 18 | const normalizeRepo = (repo: string) => |
| 15 | * For a given `user/repo` fetch repository stats from the GitHub API data | 19 | repo.replace(/^https?:\/\/github\.com\//, '').replace(/\/+$/, ''); |
| 16 | * If API key is available through env var, use it to increase rate limit | ||
| 17 | * Returns the response data and status code (200 == success) | ||
| 18 | * @param repo | ||
| 19 | */ | ||
| 20 | const fetchGitHubData = async (repo: string) => { | ||
| 21 | const apiKey = import.meta.env.GITHUB_API_KEY; | ||
| 22 | const headers = new Headers(); | ||
| 23 | if (apiKey) { | ||
| 24 | headers.append("Authorization", `token ${apiKey}`); | ||
| 25 | } | ||
| 26 | 20 | ||
| 27 | let data: GitHubRepoData = {}; | 21 | // Fallback straight to the GitHub API when our API is unavailable. |
| 28 | let statusCode; | 22 | const fromGitHub = async (repo: string): Promise<RepoMetrics | null> => { |
| 29 | 23 | const headers: Record<string, string> = { 'User-Agent': 'awesome-privacy' }; | |
| 30 | const response = await fetch(`https://api.github.com/repos/${repo}`, { | 24 | const apiKey = import.meta.env.GITHUB_API_KEY; |
| 31 | headers: headers, | 25 | if (apiKey) headers['Authorization'] = `token ${apiKey}`; |
| 32 | }).catch((e) => { | 26 | try { |
| 33 | error('GitHub API', `Network error for ${repo}: ${e.message}`); | 27 | const res = await safeFetch(`https://api.github.com/repos/${repo}`, { headers }); |
| 34 | // Return a placeholder response to handle this gracefully | 28 | if (!res.ok) { |
| 29 | error('GitHub API', `HTTP ${res.status} for ${repo}`); | ||
| 30 | return null; | ||
| 31 | } | ||
| 32 | const data = await res.json(); | ||
| 33 | return { | ||
| 34 | stars: data.stargazers_count ?? 0, | ||
| 35 | forks: data.forks_count ?? 0, | ||
| 36 | openIssues: data.open_issues_count ?? 0, | ||
| 37 | language: data.language ?? '', | ||
| 38 | licenseSpdx: data.license?.spdx_id ?? '', | ||
| 39 | licenseName: data.license?.name ?? '', | ||
| 40 | }; | ||
| 41 | } catch (e) { | ||
| 42 | error('GitHub API', `Network error for ${repo}: ${e}`); | ||
| 35 | return null; | 43 | return null; |
| 36 | }); | ||
| 37 | |||
| 38 | // Check if fetch was successful but caught by the catch block | ||
| 39 | if (!response) { | ||
| 40 | return { data, statusCode: 503 }; // Use an appropriate error status code | ||
| 41 | } | 44 | } |
| 45 | }; | ||
| 42 | 46 | ||
| 43 | statusCode = response.status; | 47 | // Prefer our unified API, then fall back to the GitHub API directly. |
| 44 | 48 | const getMetrics = async (repo: string): Promise<RepoMetrics | null> => { | |
| 45 | // Only attempt to parse JSON if the response was OK | 49 | const stats = await fetchGitHubStats(repo); |
| 46 | if (response.ok) { | 50 | if (stats) { |
| 47 | data = await response.json(); | 51 | const { info } = stats; |
| 48 | } else { | 52 | return { |
| 49 | error('GitHub API', `HTTP ${response.status} for ${repo}`); | 53 | stars: info.starCount, |
| 54 | forks: info.forksCount, | ||
| 55 | openIssues: info.openIssues, | ||
| 56 | language: info.language, | ||
| 57 | licenseSpdx: info.license, | ||
| 58 | licenseName: info.licenseName, | ||
| 59 | }; | ||
| 50 | } | 60 | } |
| 51 | 61 | return fromGitHub(normalizeRepo(repo)); | |
| 52 | return { data, statusCode }; | ||
| 53 | }; | 62 | }; |
| 54 | 63 | ||
| 64 | const formatLicense = (spdx: string) => { | ||
| 65 | if (!spdx) return 'Unknown'; | ||
| 66 | if (spdx === 'NOASSERTION') return 'No License'; | ||
| 67 | return spdx; | ||
| 68 | }; | ||
| 55 | 69 | ||
| 56 | /** | ||
| 57 | * Given a license object, return SPDX ID, or a formatted name | ||
| 58 | * @param license | ||
| 59 | */ | ||
| 60 | const formatLicense = (license?: { spdx_id?: string, name?: string }) => { | ||
| 61 | if (!license) { | ||
| 62 | return "Unknown"; | ||
| 63 | } | ||
| 64 | if (license.spdx_id === "NOASSERTION") { | ||
| 65 | return "No License"; | ||
| 66 | } | ||
| 67 | return license.spdx_id; | ||
| 68 | } | ||
| 69 | |||
| 70 | /** | ||
| 71 | * Given a (possibly large) number, return a formatted string | ||
| 72 | * E.g. If greater than thousand, then return in k format | ||
| 73 | * @param num | ||
| 74 | */ | ||
| 75 | const formatBigNumber = (num: number | undefined) => { | 70 | const formatBigNumber = (num: number | undefined) => { |
| 76 | if (num == null) return 0; | 71 | if (num == null) return 0; |
| 77 | if (num > 1000) { | 72 | if (num > 1000) { |
| 78 | return `${(num / 1000).toFixed(1)}k`; | 73 | return `${(num / 1000).toFixed(1)}k`; |
| 79 | } | 74 | } |
| 80 | return num; | 75 | return num; |
| 81 | } | 76 | }; |
| 82 | |||
| 83 | // Initiate GitHub fetch, and make available to the component | ||
| 84 | const stats = await fetchGitHubData(github); | ||
| 85 | |||
| 86 | const { | ||
| 87 | stargazers_count, forks_count, open_issues_count, language, license, | ||
| 88 | } = stats.data; | ||
| 89 | |||
| 90 | 77 | ||
| 78 | const metrics = await getMetrics(github); | ||
| 91 | --- | 79 | --- |
| 92 | 80 | ||
| 93 | <div class="github-metrics"> | 81 | <div class="github-metrics"> |
| 94 | <!-- <span title={`Built / owned by @${user}`}> | ||
| 95 | <img src={`https://github.com/${user}.png`} alt={user || owner?.login} width="20" height="20" /> | ||
| 96 | </span> --> | ||
| 97 | <!-- <span title={`${repo} is open source, with code published on GitHub`}> | ||
| 98 | <FontAwesome iconName="openSource" /> Open Source | ||
| 99 | </span> --> | ||
| 100 | <span title={`GitHub repository: ${github}`}> | 82 | <span title={`GitHub repository: ${github}`}> |
| 101 | <a href={`https://github.com/${github}`} target="_blank"><FontAwesome iconName="github" /> {github}</a> | 83 | <a href={`https://github.com/${github}`} target="_blank"><FontAwesome iconName="github" /> {github}</a> |
| 102 | </span> | 84 | </span> |
| 103 | { stats.statusCode === 200 && stats.data && ( | 85 | { metrics && ( |
| 104 | <span title={`GitHub Star Count: ${stargazers_count}`}> | 86 | <span title={`GitHub Star Count: ${metrics.stars}`}> |
| 105 | <FontAwesome iconName="stars" /> {formatBigNumber(stargazers_count)} | 87 | <FontAwesome iconName="stars" /> {formatBigNumber(metrics.stars)} |
| 106 | </span> | 88 | </span> |
| 107 | <span title={`GitHub Fork Count: ${forks_count}`}> | 89 | <span title={`GitHub Fork Count: ${metrics.forks}`}> |
| 108 | <FontAwesome iconName="forks" /> {formatBigNumber(forks_count)} | 90 | <FontAwesome iconName="forks" /> {formatBigNumber(metrics.forks)} |
| 109 | </span> | 91 | </span> |
| 110 | <span title={`Open Issues / Bugs: ${open_issues_count}`}> | 92 | <span title={`Open Issues / Bugs: ${metrics.openIssues}`}> |
| 111 | <FontAwesome iconName="issues" /> {formatBigNumber(open_issues_count)} | 93 | <FontAwesome iconName="issues" /> {formatBigNumber(metrics.openIssues)} |
| 112 | </span> | 94 | </span> |
| 113 | <span title={`Code licensed under ${license?.name}`}> | 95 | <span title={`Code licensed under ${metrics.licenseName}`}> |
| 114 | <FontAwesome iconName="license" /> {formatLicense(license)} | 96 | <FontAwesome iconName="license" /> {formatLicense(metrics.licenseSpdx)} |
| 115 | </span> | 97 | </span> |
| 116 | <span title={`Primary programming language ${language}`}> | 98 | <span title={`Primary programming language ${metrics.language}`}> |
| 117 | <FontAwesome iconName="language" /> {language} | 99 | <FontAwesome iconName="language" /> {metrics.language} |
| 118 | </span> | 100 | </span> |
| 119 | )} | 101 | )} |
| 120 | </div> | 102 | </div> |
web/src/components/things/SmartSuggestions.svelte +4 −3
| @@ -3,6 +3,7 @@ | |||
| 3 | import type { Category, Service } from '../../types/Service'; | 3 | import type { Category, Service } from '../../types/Service'; |
| 4 | import { formatLink } from '@utils/parse-markdown'; | 4 | import { formatLink } from '@utils/parse-markdown'; |
| 5 | import { slugify } from '@utils/fetch-data'; | 5 | import { slugify } from '@utils/fetch-data'; |
| 6 | import { apiBase } from '@utils/api-config'; | ||
| 6 | 7 | ||
| 7 | interface ServiceResult extends Service { | 8 | interface ServiceResult extends Service { |
| 8 | path: string; | 9 | path: string; |
| @@ -20,11 +21,11 @@ | |||
| 20 | str.toLowerCase().replace(/[^a-z0-9]/g, ''); | 21 | str.toLowerCase().replace(/[^a-z0-9]/g, ''); |
| 21 | 22 | ||
| 22 | onMount(async () => { | 23 | onMount(async () => { |
| 23 | const apiEndpoint = `https://awesome-privacy.as93.workers.dev/${searchTerm}`; | 24 | const apiEndpoint = `${apiBase}/v1/search?q=${encodeURIComponent(searchTerm)}`; |
| 24 | const fetchedServices = await fetch(apiEndpoint) | 25 | const fetchedServices = await fetch(apiEndpoint) |
| 25 | .then((response) => response.json()) | 26 | .then((response) => response.json()) |
| 26 | .then((data) => | 27 | .then((res) => |
| 27 | (JSON.parse(data) || []).map((servName: string) => normalize(servName)), | 28 | (res.data || []).map((hit: { name: string }) => normalize(hit.name)), |
| 28 | ); | 29 | ); |
| 29 | 30 | ||
| 30 | const tmpResults: ServiceResult[] = []; | 31 | const tmpResults: ServiceResult[] = []; |
web/src/utils/api-config.ts added +12
| @@ -0,0 +1,12 @@ | |||
| 1 | // Base URL and auth for the unified Awesome Privacy API. | ||
| 2 | const strip = (value: string): string => value.replace(/['";]+/g, '').trim(); | ||
| 3 | |||
| 4 | export const apiBase = | ||
| 5 | strip(import.meta.env.PUBLIC_API_URL || '').replace(/\/+$/, '') || | ||
| 6 | 'https://api.awesome-privacy.xyz'; | ||
| 7 | |||
| 8 | // Bearer header for enrichment routes; omitted when no token is set. | ||
| 9 | export const enrichHeaders = (): Record<string, string> => { | ||
| 10 | const token = strip(import.meta.env.API_TOKEN || ''); | ||
| 11 | return token ? { Authorization: `Bearer ${token}` } : {}; | ||
| 12 | }; | ||
web/src/utils/fetch-android-info.ts +4 −2
| @@ -1,5 +1,6 @@ | |||
| 1 | import { error } from './logger'; | 1 | import { error } from './logger'; |
| 2 | import { safeFetch } from './safe-fetch'; | 2 | import { safeFetch } from './safe-fetch'; |
| 3 | import { apiBase, enrichHeaders } from './api-config'; | ||
| 3 | 4 | ||
| 4 | const extractPackage = (str: string): string => | 5 | const extractPackage = (str: string): string => |
| 5 | str.includes('id=') ? str.split('id=')[1] : str; | 6 | str.includes('id=') ? str.split('id=')[1] : str; |
| @@ -7,9 +8,10 @@ const extractPackage = (str: string): string => | |||
| 7 | export const fetchAndroidInfo = async ( | 8 | export const fetchAndroidInfo = async ( |
| 8 | androidPackage: string, | 9 | androidPackage: string, |
| 9 | ): Promise<AndroidInfo | null> => { | 10 | ): Promise<AndroidInfo | null> => { |
| 10 | const endpoint = `https://android-app-privacy.as93.net/${extractPackage(androidPackage)}`; | 11 | const pkg = extractPackage(androidPackage); |
| 12 | const endpoint = `${apiBase}/v1/enrich/android/${pkg}`; | ||
| 11 | try { | 13 | try { |
| 12 | const res = await safeFetch(endpoint); | 14 | const res = await safeFetch(endpoint, { headers: enrichHeaders() }); |
| 13 | if (!res.ok) { | 15 | if (!res.ok) { |
| 14 | error( | 16 | error( |
| 15 | 'Android', | 17 | 'Android', |
web/src/utils/fetch-discord-info.ts +3 −2
| @@ -1,12 +1,13 @@ | |||
| 1 | import { error } from './logger'; | 1 | import { error } from './logger'; |
| 2 | import { safeFetch } from './safe-fetch'; | 2 | import { safeFetch } from './safe-fetch'; |
| 3 | import { apiBase, enrichHeaders } from './api-config'; | ||
| 3 | 4 | ||
| 4 | export const fetchDiscordInfo = async ( | 5 | export const fetchDiscordInfo = async ( |
| 5 | discordInvite: string, | 6 | discordInvite: string, |
| 6 | ): Promise<DiscordInfo | null> => { | 7 | ): Promise<DiscordInfo | null> => { |
| 7 | const endpoint = `https://discord-invite-info.as93.net/${discordInvite}`; | 8 | const endpoint = `${apiBase}/v1/enrich/discord/${discordInvite}`; |
| 8 | try { | 9 | try { |
| 9 | const res = await safeFetch(endpoint); | 10 | const res = await safeFetch(endpoint, { headers: enrichHeaders() }); |
| 10 | if (!res.ok) { | 11 | if (!res.ok) { |
| 11 | error('Discord', `HTTP ${res.status} for ${discordInvite} (${endpoint})`); | 12 | error('Discord', `HTTP ${res.status} for ${discordInvite} (${endpoint})`); |
| 12 | return null; | 13 | return null; |
web/src/utils/fetch-ios-info.ts +9 −2
| @@ -1,12 +1,19 @@ | |||
| 1 | import { error } from './logger'; | 1 | import { error } from './logger'; |
| 2 | import { safeFetch } from './safe-fetch'; | 2 | import { safeFetch } from './safe-fetch'; |
| 3 | import { apiBase, enrichHeaders } from './api-config'; | ||
| 4 | |||
| 5 | // Pull the id from an App Store URL's `/id123` segment, else pass it through. | ||
| 6 | const extractId = (iosUrl: string): string => { | ||
| 7 | const match = iosUrl.match(/\/id(\d+)/); | ||
| 8 | return match ? match[1] : iosUrl; | ||
| 9 | }; | ||
| 3 | 10 | ||
| 4 | export const fetchIosInfo = async ( | 11 | export const fetchIosInfo = async ( |
| 5 | iosUrl: string, | 12 | iosUrl: string, |
| 6 | ): Promise<IoSApiResponse | null> => { | 13 | ): Promise<IoSApiResponse | null> => { |
| 7 | const endpoint = `https://ios-app-info.as93.net?appStoreUrl=${iosUrl}`; | 14 | const endpoint = `${apiBase}/v1/enrich/ios/${extractId(iosUrl)}`; |
| 8 | try { | 15 | try { |
| 9 | const res = await safeFetch(endpoint); | 16 | const res = await safeFetch(endpoint, { headers: enrichHeaders() }); |
| 10 | if (!res.ok) { | 17 | if (!res.ok) { |
| 11 | error('iOS', `HTTP ${res.status} for ${iosUrl} (${endpoint})`); | 18 | error('iOS', `HTTP ${res.status} for ${iosUrl} (${endpoint})`); |
| 12 | return null; | 19 | return null; |
web/src/utils/fetch-privacy-policy.ts +5 −3
| @@ -1,12 +1,14 @@ | |||
| 1 | import { error } from './logger'; | 1 | import { error } from './logger'; |
| 2 | import { safeFetch } from './safe-fetch'; | 2 | import { safeFetch } from './safe-fetch'; |
| 3 | import { apiBase, enrichHeaders } from './api-config'; | ||
| 3 | 4 | ||
| 5 | // Wrap the flat ToS;DR v3 record in the shape the app already consumes. | ||
| 4 | export const fetchTosdrPrivacy = async ( | 6 | export const fetchTosdrPrivacy = async ( |
| 5 | serviceId: string, | 7 | serviceId: string, |
| 6 | ): Promise<PrivacyPolicyResponse | null> => { | 8 | ): Promise<PrivacyPolicyResponse | null> => { |
| 7 | const endpoint = `https://privacy-policies.as93.workers.dev/${serviceId}`; | 9 | const endpoint = `${apiBase}/v1/enrich/privacy/${serviceId}`; |
| 8 | try { | 10 | try { |
| 9 | const res = await safeFetch(endpoint); | 11 | const res = await safeFetch(endpoint, { headers: enrichHeaders() }); |
| 10 | if (!res.ok) { | 12 | if (!res.ok) { |
| 11 | error( | 13 | error( |
| 12 | 'ToS;DR', | 14 | 'ToS;DR', |
| @@ -14,7 +16,7 @@ export const fetchTosdrPrivacy = async ( | |||
| 14 | ); | 16 | ); |
| 15 | return null; | 17 | return null; |
| 16 | } | 18 | } |
| 17 | return await res.json(); | 19 | return { error: 0, message: '', parameters: await res.json() }; |
| 18 | } catch (err) { | 20 | } catch (err) { |
| 19 | error('ToS;DR', `Network error for service ${serviceId}: ${err}`); | 21 | error('ToS;DR', `Network error for service ${serviceId}: ${err}`); |
| 20 | return null; | 22 | return null; |
web/src/utils/fetch-reddit-info.ts +3 −2
| @@ -1,12 +1,13 @@ | |||
| 1 | import { error } from './logger'; | 1 | import { error } from './logger'; |
| 2 | import { safeFetch } from './safe-fetch'; | 2 | import { safeFetch } from './safe-fetch'; |
| 3 | import { apiBase, enrichHeaders } from './api-config'; | ||
| 3 | 4 | ||
| 4 | export const fetchRedditInfo = async ( | 5 | export const fetchRedditInfo = async ( |
| 5 | subreddit: string, | 6 | subreddit: string, |
| 6 | ): Promise<RedditData | null> => { | 7 | ): Promise<RedditData | null> => { |
| 7 | const endpoint = `https://subreddit-info.as93.net/${subreddit}`; | 8 | const endpoint = `${apiBase}/v1/enrich/reddit/${subreddit}`; |
| 8 | try { | 9 | try { |
| 9 | const res = await safeFetch(endpoint); | 10 | const res = await safeFetch(endpoint, { headers: enrichHeaders() }); |
| 10 | if (!res.ok) { | 11 | if (!res.ok) { |
| 11 | error('Reddit', `HTTP ${res.status} for r/${subreddit} (${endpoint})`); | 12 | error('Reddit', `HTTP ${res.status} for r/${subreddit} (${endpoint})`); |
| 12 | return null; | 13 | return null; |
web/src/utils/fetch-repo-info.ts +17 −122
| @@ -1,135 +1,25 @@ | |||
| 1 | import { error } from './logger'; | 1 | import { error } from './logger'; |
| 2 | import { safeFetch } from './safe-fetch'; | 2 | import { safeFetch } from './safe-fetch'; |
| 3 | 3 | import { apiBase, enrichHeaders } from './api-config'; | |
| 4 | const githubHeaders = (): Record<string, string> => { | ||
| 5 | const headers: Record<string, string> = { | ||
| 6 | 'User-Agent': 'awesome-privacy', | ||
| 7 | Accept: 'application/vnd.github.v3+json', | ||
| 8 | }; | ||
| 9 | const token = import.meta.env.GITHUB_API_KEY; | ||
| 10 | if (token) headers['Authorization'] = `token ${token}`; | ||
| 11 | return headers; | ||
| 12 | }; | ||
| 13 | |||
| 14 | const fetchFromGitHub = async ( | ||
| 15 | github: string, | ||
| 16 | ): Promise<GitHubStatsResponse | null> => { | ||
| 17 | const base = `https://api.github.com/repos/${github}`; | ||
| 18 | const headers = githubHeaders(); | ||
| 19 | |||
| 20 | const [infoRes, langsRes, tagsRes, contribRes, commitsRes] = | ||
| 21 | await Promise.all([ | ||
| 22 | safeFetch(base, { headers }), | ||
| 23 | safeFetch(`${base}/languages`, { headers }), | ||
| 24 | safeFetch(`${base}/tags`, { headers }), | ||
| 25 | safeFetch(`${base}/contributors`, { headers }), | ||
| 26 | safeFetch(`${base}/commits`, { headers }), | ||
| 27 | ]); | ||
| 28 | |||
| 29 | if (!infoRes.ok) { | ||
| 30 | error( | ||
| 31 | 'GitHub Stats', | ||
| 32 | `GitHub API returned ${infoRes.status} for ${github}`, | ||
| 33 | ); | ||
| 34 | return null; | ||
| 35 | } | ||
| 36 | |||
| 37 | const parseJson = (r: Response) => | ||
| 38 | r.ok && r.status !== 204 ? r.json() : null; | ||
| 39 | |||
| 40 | const [info, languages, tags, contributors, commits] = await Promise.all( | ||
| 41 | [infoRes, langsRes, tagsRes, contribRes, commitsRes].map(parseJson), | ||
| 42 | ); | ||
| 43 | |||
| 44 | return { | ||
| 45 | info: { | ||
| 46 | ownerUsername: info.owner?.login ?? '', | ||
| 47 | ownerAvatar: info.owner?.avatar_url ?? '', | ||
| 48 | description: info.description ?? '', | ||
| 49 | url: info.html_url ?? '', | ||
| 50 | homepage: info.homepage ?? '', | ||
| 51 | language: info.language ?? '', | ||
| 52 | topics: info.topics ?? [], | ||
| 53 | license: info.license?.spdx_id ?? '', | ||
| 54 | isFork: info.fork ?? false, | ||
| 55 | isArchived: info.archived ?? false, | ||
| 56 | createdAt: info.created_at ?? '', | ||
| 57 | updatedAt: info.updated_at ?? '', | ||
| 58 | size: info.size ?? 0, | ||
| 59 | scarCount: info.stargazers_count ?? 0, | ||
| 60 | forksCount: info.forks_count ?? 0, | ||
| 61 | watchersCount: info.watchers_count ?? 0, | ||
| 62 | }, | ||
| 63 | languages: languages ?? {}, | ||
| 64 | versions: (tags ?? []).map( | ||
| 65 | (tag: { | ||
| 66 | name: string; | ||
| 67 | commit?: { sha?: string }; | ||
| 68 | zipball_url?: string; | ||
| 69 | tarball_url?: string; | ||
| 70 | }) => ({ | ||
| 71 | name: tag.name, | ||
| 72 | commit: tag.commit?.sha ?? '', | ||
| 73 | zipball: tag.zipball_url ?? '', | ||
| 74 | tarball: tag.tarball_url ?? '', | ||
| 75 | }), | ||
| 76 | ), | ||
| 77 | contributors: (contributors ?? []).map( | ||
| 78 | (c: { login?: string; avatar_url?: string; contributions?: number }) => ({ | ||
| 79 | username: c.login ?? '', | ||
| 80 | avatar: c.avatar_url ?? '', | ||
| 81 | contributions: c.contributions ?? 0, | ||
| 82 | }), | ||
| 83 | ), | ||
| 84 | commits: (commits ?? []).map( | ||
| 85 | (c: { | ||
| 86 | sha?: string; | ||
| 87 | commit?: { | ||
| 88 | author?: { name?: string; date?: string }; | ||
| 89 | message?: string; | ||
| 90 | }; | ||
| 91 | author?: { login?: string; avatar_url?: string }; | ||
| 92 | }) => ({ | ||
| 93 | sha: c.sha ?? '', | ||
| 94 | authorName: c.commit?.author?.name ?? '', | ||
| 95 | authorDate: c.commit?.author?.date ?? '', | ||
| 96 | message: c.commit?.message ?? '', | ||
| 97 | authorUsername: c.author?.login ?? '', | ||
| 98 | authorAvatar: c.author?.avatar_url ?? '', | ||
| 99 | }), | ||
| 100 | ), | ||
| 101 | }; | ||
| 102 | }; | ||
| 103 | |||
| 104 | const fetchFromWorker = async ( | ||
| 105 | github: string, | ||
| 106 | ): Promise<GitHubStatsResponse | null> => { | ||
| 107 | const res = await safeFetch(`https://repo-info.as93.workers.dev/${github}`); | ||
| 108 | if (!res.ok) return null; | ||
| 109 | return res.json(); | ||
| 110 | }; | ||
| 111 | 4 | ||
| 112 | const normalizeRepo = (github: string): string => | 5 | const normalizeRepo = (github: string): string => |
| 113 | github.replace(/^https?:\/\/github\.com\//, ''); | 6 | github.replace(/^https?:\/\/github\.com\//, '').replace(/\/+$/, ''); |
| 114 | 7 | ||
| 115 | export const fetchGitHubStats = async ( | 8 | export const fetchGitHubStats = async ( |
| 116 | github: string, | 9 | github: string, |
| 117 | ): Promise<GitHubStatsResponse | null> => { | 10 | ): Promise<GitHubStatsResponse | null> => { |
| 118 | github = normalizeRepo(github); | 11 | const repo = normalizeRepo(github); |
| 12 | const endpoint = `${apiBase}/v1/enrich/github/${repo}`; | ||
| 119 | try { | 13 | try { |
| 120 | const result = await fetchFromGitHub(github); | 14 | const res = await safeFetch(endpoint, { headers: enrichHeaders() }); |
| 121 | if (result) return result; | 15 | if (!res.ok) { |
| 122 | const fallback = await fetchFromWorker(github); | 16 | error('GitHub Stats', `HTTP ${res.status} for ${repo} (${endpoint})`); |
| 123 | if (fallback) return fallback; | ||
| 124 | error('GitHub Stats', `Both direct API and worker failed for ${github}`); | ||
| 125 | return null; | ||
| 126 | } catch (err) { | ||
| 127 | try { | ||
| 128 | return await fetchFromWorker(github); | ||
| 129 | } catch { | ||
| 130 | error('GitHub Stats', `All fetches failed for ${github}: ${err}`); | ||
| 131 | return null; | 17 | return null; |
| 132 | } | 18 | } |
| 19 | return await res.json(); | ||
| 20 | } catch (err) { | ||
| 21 | error('GitHub Stats', `Network error for ${repo}: ${err}`); | ||
| 22 | return null; | ||
| 133 | } | 23 | } |
| 134 | }; | 24 | }; |
| 135 | 25 | ||
| @@ -143,14 +33,18 @@ export interface GitHubStatsResponse { | |||
| 143 | language: string; | 33 | language: string; |
| 144 | topics: string[]; | 34 | topics: string[]; |
| 145 | license: string; | 35 | license: string; |
| 36 | licenseName: string; | ||
| 146 | isFork: boolean; | 37 | isFork: boolean; |
| 147 | isArchived: boolean; | 38 | isArchived: boolean; |
| 39 | forkParent: string; | ||
| 148 | createdAt: string; | 40 | createdAt: string; |
| 149 | updatedAt: string; | 41 | updatedAt: string; |
| 42 | pushedAt: string; | ||
| 150 | size: number; | 43 | size: number; |
| 151 | scarCount: number; | 44 | starCount: number; |
| 152 | forksCount: number; | 45 | forksCount: number; |
| 153 | watchersCount: number; | 46 | watchersCount: number; |
| 47 | openIssues: number; | ||
| 154 | }; | 48 | }; |
| 155 | languages: { | 49 | languages: { |
| 156 | [key: string]: number; | 50 | [key: string]: number; |
| @@ -164,6 +58,7 @@ export interface GitHubStatsResponse { | |||
| 164 | contributors: Array<{ | 58 | contributors: Array<{ |
| 165 | username: string; | 59 | username: string; |
| 166 | avatar: string; | 60 | avatar: string; |
| 61 | url: string; | ||
| 167 | contributions: number; | 62 | contributions: number; |
| 168 | }>; | 63 | }>; |
| 169 | commits: Array<{ | 64 | commits: Array<{ |
web/src/utils/fetch-website-info.ts +3 −2
| @@ -1,12 +1,13 @@ | |||
| 1 | import { error } from './logger'; | 1 | import { error } from './logger'; |
| 2 | import { safeFetch } from './safe-fetch'; | 2 | import { safeFetch } from './safe-fetch'; |
| 3 | import { apiBase, enrichHeaders } from './api-config'; | ||
| 3 | 4 | ||
| 4 | export const fetchWebsiteInfo = async ( | 5 | export const fetchWebsiteInfo = async ( |
| 5 | url: string, | 6 | url: string, |
| 6 | ): Promise<WebsiteData | null> => { | 7 | ): Promise<WebsiteData | null> => { |
| 7 | const endpoint = `https://site-info-fetch.as93.workers.dev/?url=${url}`; | 8 | const endpoint = `${apiBase}/v1/enrich/website?url=${encodeURIComponent(url)}`; |
| 8 | try { | 9 | try { |
| 9 | const res = await safeFetch(endpoint); | 10 | const res = await safeFetch(endpoint, { headers: enrichHeaders() }); |
| 10 | if (!res.ok) { | 11 | if (!res.ok) { |
| 11 | error('Website', `HTTP ${res.status} for ${url} (${endpoint})`); | 12 | error('Website', `HTTP ${res.status} for ${url} (${endpoint})`); |
| 12 | return null; | 13 | return null; |