diff --git a/src/app/[locale]/leaderboard/[country]/page.tsx b/src/app/[locale]/leaderboard/[country]/page.tsx index f67c4f3..2b4abc0 100644 --- a/src/app/[locale]/leaderboard/[country]/page.tsx +++ b/src/app/[locale]/leaderboard/[country]/page.tsx @@ -1,40 +1,13 @@ import type { Metadata } from "next"; -import countriesData from "@/data/countries.json"; import { JsonLd } from "@/components/seo/json-ld"; import { CountryLeaderboardClient } from "@/features/leaderboard"; -import { getLeaderboardResult } from "@/features/leaderboard/services"; +import { getLeaderboardResult, getCountryInfo } from "@/features/leaderboard/services"; import { toAbsoluteUrl } from "@/lib/seo"; -type CountryInfo = { - slug: string; - title: string; - keywords?: string[]; -}; - type Props = { params: Promise<{ locale?: string; country: string }>; }; -const countries = countriesData as CountryInfo[]; - -function formatCountryTitle(country: string): string { - return country - .split("_") - .filter(Boolean) - .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)) - .join(" "); -} - -function getCountryInfo(country: string): CountryInfo { - return ( - countries.find((entry) => entry.slug === country) ?? { - slug: country, - title: formatCountryTitle(country), - keywords: [], - } - ); -} - export async function generateMetadata({ params }: Props): Promise { const { country } = await params; const countryInfo = getCountryInfo(country); diff --git a/src/app/[locale]/page.tsx b/src/app/[locale]/page.tsx index cc141c2..bd24e45 100644 --- a/src/app/[locale]/page.tsx +++ b/src/app/[locale]/page.tsx @@ -1,7 +1,6 @@ import type { Metadata } from "next"; import { Suspense } from "react"; -import { HomePageClient } from "@/features/comparison"; -import { Skeleton } from "@/components/ui/skeleton"; +import { HomePageClient, HomePageFallback } from "@/features/comparison"; import { JsonLd } from "@/components/seo/json-ld"; import { toAbsoluteUrl } from "@/lib/seo"; @@ -62,54 +61,6 @@ const softwareSchema = { }, }; -function HomePageFallback() { - return ( -
-
-
- - - -
- -
-
-
- - -
-
- - -
-
- -
- -
- {Array.from({ length: 8 }).map((_, index) => ( - - ))} -
-
- -
- - - -
-
-
- -
- - - -
-
- ); -} - export default function HomePage() { return ( <> diff --git a/src/app/[locale]/user/[username]/page.tsx b/src/app/[locale]/user/[username]/page.tsx index a18b386..f951773 100644 --- a/src/app/[locale]/user/[username]/page.tsx +++ b/src/app/[locale]/user/[username]/page.tsx @@ -2,23 +2,17 @@ import { cache } from "react"; import type { Metadata } from "next"; import { JsonLd } from "@/components/seo/json-ld"; import { UserProfileClient, UserNotFoundCard } from "@/features/developer"; -import { getUserProfile } from "@/features/developer/services"; +import { + getUserProfile, + buildUserProfileSchema, + buildUserBreadcrumbSchema, +} from "@/features/developer/services"; import { toAbsoluteUrl } from "@/lib/seo"; -import countriesData from "@/data/countries.json"; -import { detectCountry } from "@/lib/geo"; - const getCachedUserProfile = cache(async (username: string) => { return getUserProfile(username); }); -type CountryInfo = { - slug: string; - title: string; -}; - -const countries = countriesData as CountryInfo[]; - export const revalidate = 1800; // Cache user profile on Edge CDN for 30 minutes via ISR export const dynamicParams = true; @@ -116,83 +110,8 @@ export default async function UserProfilePage({ params, searchParams }: Props) { } const { user, location } = profileData; - const displayName = user.name?.trim() || user.username; - - const profilePageSchema = { - "@context": "https://schema.org", - "@type": "ProfilePage", - name: `${displayName} Developer Profile`, - description: `Open-source impact statistics and scoring for ${displayName} (@${user.username}).`, - url: profileUrl, - mainEntity: { - "@type": "Person", - name: displayName, - alternateName: user.username, - image: user.avatarUrl, - url: `https://github.com/${user.username}`, - ...(location ? { homeLocation: location } : {}), - interactionStatistic: [ - { - "@type": "InteractionCounter", - interactionType: "https://schema.org/LikeAction", - userInteractionCount: user.finalScore, - }, - ], - }, - isPartOf: { - "@type": "WebSite", - name: "DevImpact", - url: toAbsoluteUrl("/"), - }, - }; - - const detectedSlug = (countryParam || detectCountry(location))?.trim().toLowerCase(); - const countryInfo = detectedSlug - ? countries.find((c) => c.slug.toLowerCase() === detectedSlug) - : null; - - const breadcrumbElements = [ - { - "@type": "ListItem", - position: 1, - name: "Home", - item: toAbsoluteUrl("/"), - }, - { - "@type": "ListItem", - position: 2, - name: "Leaderboards", - item: toAbsoluteUrl("/leaderboard"), - }, - ]; - - if (countryInfo) { - breadcrumbElements.push({ - "@type": "ListItem", - position: 3, - name: countryInfo.title, - item: toAbsoluteUrl(`/leaderboard/${countryInfo.slug}`), - }); - breadcrumbElements.push({ - "@type": "ListItem", - position: 4, - name: displayName, - item: profileUrl, - }); - } else { - breadcrumbElements.push({ - "@type": "ListItem", - position: 3, - name: displayName, - item: profileUrl, - }); - } - - const breadcrumbSchema = { - "@context": "https://schema.org", - "@type": "BreadcrumbList", - itemListElement: breadcrumbElements, - }; + const profilePageSchema = buildUserProfileSchema(user, location); + const breadcrumbSchema = buildUserBreadcrumbSchema(user, location, countryParam); return (
diff --git a/src/app/api/compare/route.ts b/src/app/api/compare/route.ts index 28aff35..f7774e8 100644 --- a/src/app/api/compare/route.ts +++ b/src/app/api/compare/route.ts @@ -6,7 +6,7 @@ import { resolveLocale, } from "@/features/comparison/services"; import { formatApiErrorResponse, parseSelectedLanguagesFromSearchParams } from "@/lib/api"; -import { cleanGitHubUsername } from "@/utils/github"; +import { cleanGitHubUsername } from "@/utils"; export const runtime = "nodejs"; diff --git a/src/app/api/user/[username]/route.ts b/src/app/api/user/[username]/route.ts index 5a39372..ede761b 100644 --- a/src/app/api/user/[username]/route.ts +++ b/src/app/api/user/[username]/route.ts @@ -1,7 +1,7 @@ import { NextResponse } from "next/server"; import { getUserProfile } from "@/features/developer/services"; import { formatApiErrorResponse, parseSelectedLanguagesFromSearchParams } from "@/lib/api"; -import { cleanGitHubUsername } from "@/utils/github"; +import { cleanGitHubUsername } from "@/utils"; export const runtime = "nodejs"; diff --git a/src/components/cards/community-card-item.tsx b/src/components/cards/community-card-item.tsx index a41b403..33c4609 100644 --- a/src/components/cards/community-card-item.tsx +++ b/src/components/cards/community-card-item.tsx @@ -1,8 +1,8 @@ "use client"; import { MessageSquare, Star } from "lucide-react"; -import { useTranslation } from "@/components/providers/language-provider"; -import type { UserResult } from "@/features/developer/types"; +import { useTranslation } from "@/components/providers"; +import type { UserResult } from "@/features/developer"; import { StatChip } from "./work-card-helpers"; export type CommunityCardItemProps = { diff --git a/src/components/cards/pr-card-item.tsx b/src/components/cards/pr-card-item.tsx index ae70a03..3753d2d 100644 --- a/src/components/cards/pr-card-item.tsx +++ b/src/components/cards/pr-card-item.tsx @@ -1,8 +1,8 @@ "use client"; import { ArrowDown, ArrowUp, Star } from "lucide-react"; -import { useTranslation } from "@/components/providers/language-provider"; -import type { UserResult } from "@/features/developer/types"; +import { useTranslation } from "@/components/providers"; +import type { UserResult } from "@/features/developer"; import { formatLanguageMatch, LanguageBreakdown, diff --git a/src/components/cards/repo-card-item.tsx b/src/components/cards/repo-card-item.tsx index 0a5029a..4c98598 100644 --- a/src/components/cards/repo-card-item.tsx +++ b/src/components/cards/repo-card-item.tsx @@ -1,8 +1,8 @@ "use client"; import { Eye, GitFork, Star } from "lucide-react"; -import { useTranslation } from "@/components/providers/language-provider"; -import type { UserResult } from "@/features/developer/types"; +import { useTranslation } from "@/components/providers"; +import type { UserResult } from "@/features/developer"; import { formatLanguageMatch, LanguageBreakdown, diff --git a/src/components/cards/score-card.tsx b/src/components/cards/score-card.tsx index 2bf8927..c3602bb 100644 --- a/src/components/cards/score-card.tsx +++ b/src/components/cards/score-card.tsx @@ -1,8 +1,8 @@ "use client"; -import { cn } from "@/utils/cn"; -import { useTranslation } from "@/components/providers/language-provider"; -import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { cn } from "@/utils"; +import { useTranslation } from "@/components/providers"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui"; export type ScoreCardProps = { title: string; diff --git a/src/components/cards/work-card-helpers.tsx b/src/components/cards/work-card-helpers.tsx index e4edd8b..0ce6171 100644 --- a/src/components/cards/work-card-helpers.tsx +++ b/src/components/cards/work-card-helpers.tsx @@ -1,7 +1,7 @@ "use client"; import type { ReactNode } from "react"; -import type { UserResult } from "@/features/developer/types"; +import type { UserResult } from "@/features/developer"; export type LanguageEntry = { name: string; diff --git a/src/components/layout/index.ts b/src/components/layout/index.ts index 05ad583..b97aba7 100644 --- a/src/components/layout/index.ts +++ b/src/components/layout/index.ts @@ -1,6 +1,5 @@ export * from "./app-header"; export * from "./app-footer"; export * from "./brand-logo"; -export * from "./avatar"; export * from "./github-link"; -export * from "./skeletons"; +export { Avatar, type AvatarProps } from "@/components/ui/avatar"; diff --git a/src/components/layout/avatar.test.tsx b/src/components/ui/avatar.test.tsx similarity index 100% rename from src/components/layout/avatar.test.tsx rename to src/components/ui/avatar.test.tsx diff --git a/src/components/layout/avatar.tsx b/src/components/ui/avatar.tsx similarity index 92% rename from src/components/layout/avatar.tsx rename to src/components/ui/avatar.tsx index baf3147..4a90447 100644 --- a/src/components/layout/avatar.tsx +++ b/src/components/ui/avatar.tsx @@ -1,7 +1,7 @@ import Image from "next/image"; import { cn } from "@/utils/cn"; -type AvatarProps = { +export type AvatarProps = { src?: string | null; alt: string; size?: number; @@ -11,8 +11,7 @@ type AvatarProps = { }; /** - * Reusable avatar image component. - * + * Reusable avatar image component with initial fallback. */ export function Avatar({ src, diff --git a/src/components/ui/index.ts b/src/components/ui/index.ts index 10b2f61..76345fa 100644 --- a/src/components/ui/index.ts +++ b/src/components/ui/index.ts @@ -6,3 +6,4 @@ export * from "./progress"; export * from "./skeleton"; export * from "./tooltip"; export * from "./kbd"; +export * from "./avatar"; diff --git a/src/features/comparison/components/breakdown-bars.tsx b/src/features/comparison/components/breakdown-bars.tsx deleted file mode 100644 index 9562ae3..0000000 --- a/src/features/comparison/components/breakdown-bars.tsx +++ /dev/null @@ -1,60 +0,0 @@ -"use client"; - -import type { UserResult } from "@/features/developer"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Progress } from "@/components/ui/progress"; -import { useTranslation } from "@/components/providers/language-provider"; - -type Props = { - user1: UserResult; - user2: UserResult; -}; - -export function BreakdownBars({ user1, user2 }: Props) { - const getMaxScore = (score1: number, score2: number) => Math.max(score1, score2, 1); - const { t } = useTranslation(); - - return ( - - - {t("breakdown.title")} - {t("breakdown.description")} - - - {["repoScore", "prScore", "contributionScore"].map((metric) => { - const user1Value = user1[metric as keyof UserResult] as number; - const user2Value = user2[metric as keyof UserResult] as number; - const maxVal = getMaxScore(user1Value, user2Value); - const metricLabel = - metric === "repoScore" - ? "breakdown.repo" - : metric === "prScore" - ? "breakdown.pr" - : "breakdown.contribution"; - return ( -
-
- {t(metricLabel)} - - {user1.name}: {user1Value} | {user2.name}: {user2Value} - -
-
-
- {user1.name} - - {user1Value} -
-
- {user2.name} - - {user2Value} -
-
-
- ); - })} -
-
- ); -} diff --git a/src/features/comparison/components/compare-form.tsx b/src/features/comparison/components/compare-form.tsx index 4467b98..5c2b684 100644 --- a/src/features/comparison/components/compare-form.tsx +++ b/src/features/comparison/components/compare-form.tsx @@ -2,14 +2,19 @@ import { useEffect, useRef } from "react"; import { ArrowLeftRight, RefreshCw, X } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; -import { Kbd } from "@/components/ui/kbd"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { useTranslation } from "@/components/providers/language-provider"; +import { + Button, + Input, + Kbd, + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui"; +import { useTranslation } from "@/components/providers"; import { handleEscapeToClear, matchesHotkey, useHotkeys, useIsApplePlatform } from "@/hooks"; -import { cn } from "@/utils/cn"; -import { cleanGitHubUsername } from "@/utils/github"; +import { cn, cleanGitHubUsername } from "@/utils"; const LANGUAGE_OPTIONS = [ "TypeScript", diff --git a/src/features/comparison/components/comparison-table.tsx b/src/features/comparison/components/comparison-table.tsx deleted file mode 100644 index 60daea2..0000000 --- a/src/features/comparison/components/comparison-table.tsx +++ /dev/null @@ -1,79 +0,0 @@ -"use client"; - -import { Avatar } from "@/components/layout/avatar"; -import type { UserResult } from "@/features/developer"; -import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; -import { useTranslation } from "@/components/providers/language-provider"; - -type ComparisonTableProps = { - user1: UserResult; - user2: UserResult; -}; - -export function ComparisonTable({ user1, user2 }: ComparisonTableProps) { - const { t } = useTranslation(); - - return ( -
- {[user1, user2].map((user, idx) => ( - - - -
- - {user.name || user.username} -
- {user.isWinner && ( - - {t("banner.winner")} - - )} -
-
- -
- {t("comparison.final.score")} - {user.finalScore} -
-
- {t("comparison.repo.score")} - (idx === 0 ? user2.repoScore : user1.repoScore) ? "text-primary" : ""}`} - > - {user.repoScore} - -
-
- {t("comparison.pr.score")} - (idx === 0 ? user2.prScore : user1.prScore) ? "text-primary" : ""}`} - > - {user.prScore} - -
-
- {t("comparison.contribution.score")} - (idx === 0 ? user2.contributionScore : user1.contributionScore) ? "text-primary" : ""}`} - > - {user.contributionScore} - -
-
-
- ))} -
- ); -} diff --git a/src/components/layout/skeletons.tsx b/src/features/comparison/components/dashboard-skeleton.tsx similarity index 100% rename from src/components/layout/skeletons.tsx rename to src/features/comparison/components/dashboard-skeleton.tsx diff --git a/src/features/comparison/components/home-page-client.tsx b/src/features/comparison/components/home-page-client.tsx index 47faad5..f428e8b 100644 --- a/src/features/comparison/components/home-page-client.tsx +++ b/src/features/comparison/components/home-page-client.tsx @@ -4,14 +4,14 @@ import { useMemo } from "react"; import Image from "next/image"; import { CompareForm } from "./compare-form"; import { ResultDashboard } from "./result-dashboard"; -import { DashboardSkeleton } from "@/components/layout/skeletons"; +import { DashboardSkeleton } from "./dashboard-skeleton"; import { BrandLogo } from "@/components/layout/brand-logo"; -import { useTranslation } from "@/components/providers/language-provider"; -import { cn } from "@/utils/cn"; +import { useTranslation } from "@/components/providers"; +import { cn } from "@/utils"; import { useComparisonController } from "../hooks"; import { type ComparisonPreset } from "../config/comparison-presets"; import { PresetPills } from "./preset-pills"; -import { Button } from "@/components/ui/button"; +import { Button } from "@/components/ui"; export function HomePageClient() { const { t } = useTranslation(); diff --git a/src/features/comparison/components/home-page-fallback.tsx b/src/features/comparison/components/home-page-fallback.tsx new file mode 100644 index 0000000..1ee7e79 --- /dev/null +++ b/src/features/comparison/components/home-page-fallback.tsx @@ -0,0 +1,49 @@ +import { Skeleton } from "@/components/ui"; + +export function HomePageFallback() { + return ( +
+
+
+ + + +
+ +
+
+
+ + +
+
+ + +
+
+ +
+ +
+ {Array.from({ length: 8 }).map((_, index) => ( + + ))} +
+
+ +
+ + + +
+
+
+ +
+ + + +
+
+ ); +} diff --git a/src/features/comparison/components/index.ts b/src/features/comparison/components/index.ts index 77dd066..2dbda89 100644 --- a/src/features/comparison/components/index.ts +++ b/src/features/comparison/components/index.ts @@ -1,8 +1,8 @@ export * from "./compare-form"; export * from "./comparison-chart"; -export * from "./comparison-table"; export * from "./result-dashboard"; -export * from "./breakdown-bars"; export * from "./insights-list"; export * from "./top-list"; export * from "./home-page-client"; +export * from "./home-page-fallback"; +export * from "./dashboard-skeleton"; diff --git a/src/features/comparison/components/insights-list.tsx b/src/features/comparison/components/insights-list.tsx index 20701a5..2be1e3b 100644 --- a/src/features/comparison/components/insights-list.tsx +++ b/src/features/comparison/components/insights-list.tsx @@ -1,8 +1,8 @@ "use client"; import { TrendingUp } from "lucide-react"; -import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; -import { useTranslation } from "@/components/providers/language-provider"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui"; +import { useTranslation } from "@/components/providers"; import type { CompareInsights } from "../types"; import type { UserResult } from "@/features/developer"; diff --git a/src/features/comparison/components/preset-pills.tsx b/src/features/comparison/components/preset-pills.tsx index c51857e..721a92b 100644 --- a/src/features/comparison/components/preset-pills.tsx +++ b/src/features/comparison/components/preset-pills.tsx @@ -1,8 +1,8 @@ "use client"; import { useId } from "react"; -import { useTranslation } from "@/components/providers/language-provider"; -import { cn } from "@/utils/cn"; +import { useTranslation } from "@/components/providers"; +import { cn } from "@/utils"; import { COMPARISON_PRESETS } from "../config/comparison-presets"; type Preset = (typeof COMPARISON_PRESETS)[number]; diff --git a/src/features/comparison/components/result-dashboard.tsx b/src/features/comparison/components/result-dashboard.tsx index 366a862..461ddfe 100644 --- a/src/features/comparison/components/result-dashboard.tsx +++ b/src/features/comparison/components/result-dashboard.tsx @@ -7,7 +7,7 @@ import { Check, Copy, ExternalLink, Trophy, Share2, XCircle } from "lucide-react import { useSearchParams } from "next/navigation"; import { useClipboardCopy } from "@/hooks"; import dynamic from "next/dynamic"; -import { Avatar } from "@/components/layout/avatar"; +import { Avatar } from "@/components/ui"; const ComparisonChart = dynamic( () => import("./comparison-chart").then((mod) => mod.ComparisonChart), @@ -21,11 +21,10 @@ const ComparisonChart = dynamic( import { TopList } from "./top-list"; import { InsightsList } from "./insights-list"; import { ScoreCard } from "@/components/cards"; -import { Button } from "@/components/ui/button"; -import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Button, Card, CardContent, CardHeader, CardTitle } from "@/components/ui"; import { getSignalMetricEntries, type UserResult } from "@/features/developer"; -import { useTranslation } from "@/components/providers/language-provider"; -import { formatComparisonToMarkdown } from "../format-comparison-to-markdown"; +import { useTranslation } from "@/components/providers"; +import { formatComparisonToMarkdown } from "../services/format-comparison-to-markdown"; import type { CompareInsights, CompareWinner } from "../types"; type Props = { diff --git a/src/features/comparison/components/top-list.tsx b/src/features/comparison/components/top-list.tsx index 56b8a19..7811330 100644 --- a/src/features/comparison/components/top-list.tsx +++ b/src/features/comparison/components/top-list.tsx @@ -3,7 +3,7 @@ import Link from "next/link"; import type { Route } from "next"; import { ExternalLink, GitPullRequest, MessageSquare, Star } from "lucide-react"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui"; import type { UserResult } from "@/features/developer"; import { RepoCardItem, @@ -12,7 +12,7 @@ import { findRepoLanguageMeta, findPrLanguageMeta, } from "@/components/cards"; -import { useTranslation } from "@/components/providers/language-provider"; +import { useTranslation } from "@/components/providers"; type Props = { userResults: UserResult[]; diff --git a/src/features/comparison/index.ts b/src/features/comparison/index.ts index 0949c22..4246d38 100644 --- a/src/features/comparison/index.ts +++ b/src/features/comparison/index.ts @@ -1,5 +1,5 @@ export * from "./types"; export * from "./components"; export * from "./services/compare-request"; -export * from "./format-comparison-to-markdown"; +export * from "./services/format-comparison-to-markdown"; export * from "./hooks"; diff --git a/src/features/comparison/services/compare-service.ts b/src/features/comparison/services/compare-service.ts index 4d19c93..6dd47a5 100644 --- a/src/features/comparison/services/compare-service.ts +++ b/src/features/comparison/services/compare-service.ts @@ -1,36 +1,8 @@ -import { normalizeSelectedLanguages } from "@/features/scoring"; import { getUserProfile, UserFetchError } from "@/features/developer/services"; -import { - DEFAULT_LOCALE, - LOCALE_COOKIE, - isSupportedLocale, - parseAcceptLanguage, - type Locale, -} from "@/lib/i18n/core"; +import { resolveRequestLocale, type Locale } from "@/lib/i18n/core"; import type { ComparedUserResult, CompareInsights, CompareWinner, LanguageWinner } from "../types"; -export class CompareUserFetchError extends Error { - readonly username: string; - readonly causeError: unknown; - - constructor(username: string, causeError: unknown) { - super(`Failed to fetch GitHub data for ${username}`); - this.name = "CompareUserFetchError"; - this.username = username; - this.causeError = causeError; - } -} - -export function parseSelectedLanguagesFromSearchParams(searchParams: URLSearchParams): string[] { - const fromRepeated = searchParams.getAll("selectedLanguage"); - const fromCsv = searchParams - .get("selectedLanguages") - ?.split(",") - .map((language) => language.trim()) - .filter(Boolean); - - return normalizeSelectedLanguages([...(fromRepeated ?? []), ...(fromCsv ?? [])]); -} +export { resolveRequestLocale as resolveLocale, UserFetchError }; function calculatePercentageDifference(difference: number, baseline: number): number | null { if (baseline <= 0) { @@ -236,55 +208,33 @@ export function createComparisonInsights( }; } -export function resolveLocale(request: Request): Locale { - const cookieHeader = request.headers.get("cookie"); - const localeFromCookie = cookieHeader - ?.split(";") - .map((value) => value.trim()) - .find((value) => value.startsWith(`${LOCALE_COOKIE}=`)) - ?.split("=")[1]; - - if (isSupportedLocale(localeFromCookie)) { - return localeFromCookie; - } - - return parseAcceptLanguage(request.headers.get("accept-language"), ["en", "ar"], DEFAULT_LOCALE); -} - export async function compareUsers( usernames: string[], selectedLanguages: string[], ): Promise { const settled = await Promise.allSettled( usernames.map(async (username) => { - try { - const { user } = await getUserProfile(username, selectedLanguages); - return { - username: user.username, - name: user.name, - avatarUrl: user.avatarUrl, - repoScore: user.repoScore, - prScore: user.prScore, - contributionScore: user.contributionScore, - finalScore: user.finalScore, - normalizedRepoScore: user.normalizedRepoScore ?? user.repoScore, - normalizedPRScore: user.normalizedPRScore ?? user.prScore, - normalizedContributionScore: user.normalizedContributionScore ?? user.contributionScore, - normalizedFinalScore: user.normalizedFinalScore ?? user.finalScore, - topRepos: user.topRepos as ComparedUserResult["topRepos"], - topPullRequests: user.topPullRequests as ComparedUserResult["topPullRequests"], - topCommunityContributions: (user.topCommunityContributions ?? - []) as ComparedUserResult["topCommunityContributions"], - languageScores: user.languageScores as ComparedUserResult["languageScores"], - signals: user.signals, - explanations: user.explanations, - } as unknown as ComparedUserResult; - } catch (error: unknown) { - throw new CompareUserFetchError( - username, - error instanceof UserFetchError ? error.causeError : error, - ); - } + const { user } = await getUserProfile(username, selectedLanguages); + return { + username: user.username, + name: user.name, + avatarUrl: user.avatarUrl, + repoScore: user.repoScore, + prScore: user.prScore, + contributionScore: user.contributionScore, + finalScore: user.finalScore, + normalizedRepoScore: user.normalizedRepoScore ?? user.repoScore, + normalizedPRScore: user.normalizedPRScore ?? user.prScore, + normalizedContributionScore: user.normalizedContributionScore ?? user.contributionScore, + normalizedFinalScore: user.normalizedFinalScore ?? user.finalScore, + topRepos: user.topRepos as ComparedUserResult["topRepos"], + topPullRequests: user.topPullRequests as ComparedUserResult["topPullRequests"], + topCommunityContributions: (user.topCommunityContributions ?? + []) as ComparedUserResult["topCommunityContributions"], + languageScores: user.languageScores as ComparedUserResult["languageScores"], + signals: user.signals, + explanations: user.explanations, + } as unknown as ComparedUserResult; }), ); diff --git a/src/features/comparison/format-comparison-to-markdown.ts b/src/features/comparison/services/format-comparison-to-markdown.ts similarity index 98% rename from src/features/comparison/format-comparison-to-markdown.ts rename to src/features/comparison/services/format-comparison-to-markdown.ts index b787b7e..3a31500 100644 --- a/src/features/comparison/format-comparison-to-markdown.ts +++ b/src/features/comparison/services/format-comparison-to-markdown.ts @@ -1,5 +1,5 @@ import type { UserResult } from "@/features/developer"; -import type { CompareWinner } from "./types"; +import type { CompareWinner } from "../types"; type ComparisonMarkdownUser = Pick< UserResult, diff --git a/src/features/comparison/services/index.ts b/src/features/comparison/services/index.ts index 64c13c7..dc8cb10 100644 --- a/src/features/comparison/services/index.ts +++ b/src/features/comparison/services/index.ts @@ -1,2 +1,3 @@ export * from "./compare-request"; export * from "./compare-service"; +export * from "./format-comparison-to-markdown"; diff --git a/src/features/comparison/tests/format-comparison-to-markdown.test.ts b/src/features/comparison/tests/format-comparison-to-markdown.test.ts index 4440be7..fb557d8 100644 --- a/src/features/comparison/tests/format-comparison-to-markdown.test.ts +++ b/src/features/comparison/tests/format-comparison-to-markdown.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "vitest"; -import { formatComparisonToMarkdown } from "@/features/comparison/format-comparison-to-markdown"; +import { formatComparisonToMarkdown } from "@/features/comparison"; import type { UserResult } from "@/features/developer"; import type { CompareWinner } from "@/features/comparison/types"; diff --git a/src/features/developer/components/user-not-found.tsx b/src/features/developer/components/user-not-found.tsx index 634f548..8cca499 100644 --- a/src/features/developer/components/user-not-found.tsx +++ b/src/features/developer/components/user-not-found.tsx @@ -2,9 +2,8 @@ import Link from "next/link"; import { ArrowLeft, Search, Trophy } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { useTranslation } from "@/components/providers/language-provider"; +import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui"; +import { useTranslation } from "@/components/providers"; type Props = { username: string; diff --git a/src/features/developer/components/user-profile-client.tsx b/src/features/developer/components/user-profile-client.tsx index 679e5b6..7174c53 100644 --- a/src/features/developer/components/user-profile-client.tsx +++ b/src/features/developer/components/user-profile-client.tsx @@ -18,21 +18,27 @@ import { Star, Trophy, } from "lucide-react"; -import { Avatar } from "@/components/layout/avatar"; -import { Button } from "@/components/ui/button"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Progress } from "@/components/ui/progress"; +import { + Avatar, + Button, + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, + Progress, +} from "@/components/ui"; import { ScoreCard, RepoCardItem, PullRequestCardItem, CommunityCardItem, } from "@/components/cards"; -import { useTranslation } from "@/components/providers/language-provider"; +import { useTranslation } from "@/components/providers"; import { getCountryCode, detectCountry } from "@/lib/geo"; import countriesData from "@/data/countries.json"; import type { UserResult } from "../types"; -import { getSignalMetricEntries } from "../signal-metrics"; +import { getSignalMetricEntries } from "../services/signal-metrics"; type CountryInfo = { slug: string; diff --git a/src/features/developer/index.ts b/src/features/developer/index.ts index 781c06c..ba94413 100644 --- a/src/features/developer/index.ts +++ b/src/features/developer/index.ts @@ -1,3 +1,3 @@ export * from "./types"; export * from "./components"; -export { getSignalMetricEntries } from "./signal-metrics"; +export { getSignalMetricEntries } from "./services/signal-metrics"; diff --git a/src/features/developer/services/developer-seo.ts b/src/features/developer/services/developer-seo.ts new file mode 100644 index 0000000..f3b4230 --- /dev/null +++ b/src/features/developer/services/developer-seo.ts @@ -0,0 +1,100 @@ +import { toAbsoluteUrl } from "@/lib/seo"; +import { detectCountry } from "@/lib/geo"; +import countriesData from "@/data/countries.json"; +import type { UserResult } from "../types"; + +type CountryInfo = { + slug: string; + title: string; +}; + +const countries = countriesData as CountryInfo[]; + +export function buildUserProfileSchema(user: UserResult, location?: string | null) { + const displayName = user.name?.trim() || user.username; + const profileUrl = toAbsoluteUrl(`/user/${user.username}`); + + return { + "@context": "https://schema.org", + "@type": "ProfilePage", + name: `${displayName} Developer Profile`, + description: `Open-source impact statistics and scoring for ${displayName} (@${user.username}).`, + url: profileUrl, + mainEntity: { + "@type": "Person", + name: displayName, + alternateName: user.username, + image: user.avatarUrl, + url: `https://github.com/${user.username}`, + ...(location ? { homeLocation: location } : {}), + interactionStatistic: [ + { + "@type": "InteractionCounter", + interactionType: "https://schema.org/LikeAction", + userInteractionCount: user.finalScore, + }, + ], + }, + isPartOf: { + "@type": "WebSite", + name: "DevImpact", + url: toAbsoluteUrl("/"), + }, + }; +} + +export function buildUserBreadcrumbSchema( + user: UserResult, + location?: string | null, + countryParam?: string, +) { + const displayName = user.name?.trim() || user.username; + const profileUrl = toAbsoluteUrl(`/user/${user.username}`); + const detectedSlug = (countryParam || detectCountry(location ?? null))?.trim().toLowerCase(); + const countryInfo = detectedSlug + ? countries.find((c) => c.slug.toLowerCase() === detectedSlug) + : null; + + const breadcrumbElements = [ + { + "@type": "ListItem", + position: 1, + name: "Home", + item: toAbsoluteUrl("/"), + }, + { + "@type": "ListItem", + position: 2, + name: "Leaderboards", + item: toAbsoluteUrl("/leaderboard"), + }, + ]; + + if (countryInfo) { + breadcrumbElements.push({ + "@type": "ListItem", + position: 3, + name: countryInfo.title, + item: toAbsoluteUrl(`/leaderboard/${countryInfo.slug}`), + }); + breadcrumbElements.push({ + "@type": "ListItem", + position: 4, + name: displayName, + item: profileUrl, + }); + } else { + breadcrumbElements.push({ + "@type": "ListItem", + position: 3, + name: displayName, + item: profileUrl, + }); + } + + return { + "@context": "https://schema.org", + "@type": "BreadcrumbList", + itemListElement: breadcrumbElements, + }; +} diff --git a/src/features/developer/services/index.ts b/src/features/developer/services/index.ts index fec844e..be7958d 100644 --- a/src/features/developer/services/index.ts +++ b/src/features/developer/services/index.ts @@ -1,3 +1,5 @@ export * from "./user-service"; export * from "./user-persistence"; export * from "./profile-cache"; +export * from "./signal-metrics"; +export * from "./developer-seo"; diff --git a/src/features/developer/signal-metrics.ts b/src/features/developer/services/signal-metrics.ts similarity index 100% rename from src/features/developer/signal-metrics.ts rename to src/features/developer/services/signal-metrics.ts diff --git a/src/features/developer/services/user-persistence.ts b/src/features/developer/services/user-persistence.ts index 780ade9..2f5f227 100644 --- a/src/features/developer/services/user-persistence.ts +++ b/src/features/developer/services/user-persistence.ts @@ -1,8 +1,7 @@ -import { calculateUserScore } from "@/features/scoring"; +import { calculateUserScore, type CalculateUserScoreResult } from "@/features/scoring"; import { getDatabaseStore } from "@/lib/db"; import { detectCountry } from "@/lib/geo"; import type { GitHubUserData } from "@/lib/github"; -import type { CalculateUserScoreResult } from "@/features/scoring/services"; export type PersistUserOptions = { data: GitHubUserData; diff --git a/src/features/developer/services/user-service.ts b/src/features/developer/services/user-service.ts index 3befd2f..0282f9c 100644 --- a/src/features/developer/services/user-service.ts +++ b/src/features/developer/services/user-service.ts @@ -1,6 +1,5 @@ import { getUserData } from "@/lib/github"; -import { calculateUserScore } from "@/features/scoring"; -import type { CalculateUserScoreResult } from "@/features/scoring/services"; +import { calculateUserScore, type CalculateUserScoreResult } from "@/features/scoring"; import { scheduleBackground } from "@/lib/background"; import { persistUserScores } from "./user-persistence"; import { getCachedProfile, setCachedProfile } from "./profile-cache"; diff --git a/src/features/developer/tests/signal-metrics.test.ts b/src/features/developer/tests/signal-metrics.test.ts index 99caa96..937d9e4 100644 --- a/src/features/developer/tests/signal-metrics.test.ts +++ b/src/features/developer/tests/signal-metrics.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import type { ScoringSignals } from "@/features/scoring"; import en from "@/locales/en.json"; import ar from "@/locales/ar.json"; -import { getSignalMetricEntries } from "../signal-metrics"; +import { getSignalMetricEntries } from "../services/signal-metrics"; const signals: ScoringSignals = { reposAnalyzed: 0, diff --git a/src/features/leaderboard/components/leaderboard-table.tsx b/src/features/leaderboard/components/leaderboard-table.tsx index f996897..b0b1282 100644 --- a/src/features/leaderboard/components/leaderboard-table.tsx +++ b/src/features/leaderboard/components/leaderboard-table.tsx @@ -12,12 +12,20 @@ import { ChevronLeft, ChevronRight, } from "lucide-react"; -import { Avatar } from "@/components/layout/avatar"; -import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; -import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"; -import { Button } from "@/components/ui/button"; +import { + Avatar, + Button, + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui"; import { useTranslation } from "@/components/providers/language-provider"; -import { cn } from "@/utils/cn"; +import { cn } from "@/utils"; import type { ScoredLeaderboardEntry as LeaderboardEntry } from "../types"; import { SearchField } from "./search-field"; diff --git a/src/features/leaderboard/services/calculate-leaderboard.ts b/src/features/leaderboard/services/calculate-leaderboard.ts index 6b39f00..b3cdde2 100644 --- a/src/features/leaderboard/services/calculate-leaderboard.ts +++ b/src/features/leaderboard/services/calculate-leaderboard.ts @@ -5,6 +5,7 @@ import { persistUserScores } from "@/features/developer/services"; import { createCacheStore, getCacheConfigFromEnv } from "@/lib/cache"; import { getDatabaseStore, type DatabaseStore } from "@/lib/db"; import { getDisplayLimit } from "./display-limit"; +import { buildLeaderboardCacheKey, mapRowsToScoredLeaderboardEntries } from "./leaderboard-helpers"; import type { CalculateLeaderboardResponse, LeaderboardMeta, @@ -32,10 +33,6 @@ export type { CalculateLeaderboardResponse, LeaderboardMeta, LeaderboardResult, // ─── Helpers ──────────────────────────────────────────────────────────── -function buildLeaderboardCacheKey(country: string, namespace: string): string { - return `${namespace}:leaderboard:${country.trim().toLowerCase()}`; -} - function getEnvInt(key: string, fallback: number): number { const raw = process.env[key]?.trim(); if (!raw) return fallback; @@ -215,20 +212,7 @@ export async function buildLeaderboardResult( ): Promise<{ result: LeaderboardResult; meta: LeaderboardMeta }> { const allUsers = await db.getLeaderboard(country, getDisplayLimit(country)); const totalCount = await db.getLeaderboardCount(country); - - const scored: ScoredEntry[] = allUsers.map((row) => ({ - username: row.username, - name: row.name, - avatarUrl: row.avatar_url, - repoScore: row.repo_score, - prScore: row.pr_score, - contributionScore: row.contribution_score, - finalScore: row.final_score, - impactRank: 0, - })); - - scored.sort((a, b) => b.finalScore - a.finalScore); - scored.forEach((u, idx) => (u.impactRank = idx + 1)); + const scored = mapRowsToScoredLeaderboardEntries(allUsers); const result: LeaderboardResult = { title: sourceData.title, diff --git a/src/features/leaderboard/services/index.ts b/src/features/leaderboard/services/index.ts index 186f77c..7e31a5a 100644 --- a/src/features/leaderboard/services/index.ts +++ b/src/features/leaderboard/services/index.ts @@ -1,3 +1,4 @@ export * from "./leaderboard-service"; export * from "./calculate-leaderboard"; export * from "./display-limit"; +export * from "./leaderboard-helpers"; diff --git a/src/features/leaderboard/services/leaderboard-helpers.ts b/src/features/leaderboard/services/leaderboard-helpers.ts new file mode 100644 index 0000000..ebe0b6a --- /dev/null +++ b/src/features/leaderboard/services/leaderboard-helpers.ts @@ -0,0 +1,55 @@ +import type { LeaderboardUserRow } from "@/lib/db"; +import countriesData from "@/data/countries.json"; +import type { ScoredLeaderboardEntry } from "../types"; + +export type CountryInfo = { + slug: string; + title: string; + keywords?: string[]; +}; + +const countries = countriesData as CountryInfo[]; + +export function formatCountryTitle(country: string): string { + return country + .split("_") + .filter(Boolean) + .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)) + .join(" "); +} + +export function getCountryInfo(country: string): CountryInfo { + return ( + countries.find((entry) => entry.slug === country) ?? { + slug: country, + title: formatCountryTitle(country), + keywords: [], + } + ); +} + +export function buildLeaderboardCacheKey(country: string, namespace: string): string { + return `${namespace}:leaderboard:${country.trim().toLowerCase()}`; +} + +export function mapRowsToScoredLeaderboardEntries( + rows: LeaderboardUserRow[], +): ScoredLeaderboardEntry[] { + const scored: ScoredLeaderboardEntry[] = rows.map((row) => ({ + username: row.username, + name: row.name, + avatarUrl: row.avatar_url, + repoScore: row.repo_score, + prScore: row.pr_score, + contributionScore: row.contribution_score, + finalScore: row.final_score, + impactRank: 0, + })); + + scored.sort((a, b) => b.finalScore - a.finalScore); + scored.forEach((user, index) => { + user.impactRank = index + 1; + }); + + return scored; +} diff --git a/src/features/leaderboard/services/leaderboard-service.ts b/src/features/leaderboard/services/leaderboard-service.ts index c3e3e62..786fc06 100644 --- a/src/features/leaderboard/services/leaderboard-service.ts +++ b/src/features/leaderboard/services/leaderboard-service.ts @@ -2,13 +2,10 @@ import { createCacheStore, getCacheConfigFromEnv } from "@/lib/cache"; import { getDatabaseStore } from "@/lib/db"; import type { LeaderboardResult, ScoredLeaderboardEntry } from "../types"; import { getDisplayLimit, isWorldwideSlug } from "./display-limit"; +import { buildLeaderboardCacheKey, mapRowsToScoredLeaderboardEntries } from "./leaderboard-helpers"; export type { LeaderboardResult, ScoredLeaderboardEntry }; -function buildLeaderboardCacheKey(country: string, namespace: string): string { - return `${namespace}:leaderboard:${country.trim().toLowerCase()}`; -} - function getLeaderboardTitle(country: string): string { return isWorldwideSlug(country) ? "Worldwide" : country; } @@ -65,21 +62,7 @@ export async function getLeaderboardResult(country: string): Promise ({ - username: row.username, - name: row.name, - avatarUrl: row.avatar_url, - repoScore: row.repo_score, - prScore: row.pr_score, - contributionScore: row.contribution_score, - finalScore: row.final_score, - impactRank: 0, - })); - - scored.sort((a, b) => b.finalScore - a.finalScore); - scored.forEach((user, index) => { - user.impactRank = index + 1; - }); + const scored = mapRowsToScoredLeaderboardEntries(rows); const result: LeaderboardResult = { title, diff --git a/src/features/leaderboard/tests/leaderboard-table.test.tsx b/src/features/leaderboard/tests/leaderboard-table.test.tsx index 22c4465..921f08c 100644 --- a/src/features/leaderboard/tests/leaderboard-table.test.tsx +++ b/src/features/leaderboard/tests/leaderboard-table.test.tsx @@ -48,9 +48,13 @@ vi.mock("@/components/providers/language-provider", () => ({ })); // Mock Avatar -vi.mock("@/components/layout/avatar", () => ({ - Avatar: ({ src, alt }: { src: string; alt: string }) => {alt}, -})); +vi.mock("@/components/ui", async (importOriginal) => { + const actual = await importOriginal>(); + return { + ...actual, + Avatar: ({ src, alt }: { src: string; alt: string }) => {alt}, + }; +}); // Mock Tooltip components vi.mock("@/components/ui/tooltip", () => ({ diff --git a/src/features/scoring/services/language-scoring.ts b/src/features/scoring/services/language-scoring.ts index 13f0fc0..07a9859 100644 --- a/src/features/scoring/services/language-scoring.ts +++ b/src/features/scoring/services/language-scoring.ts @@ -1,10 +1,9 @@ import type { RepoLanguages } from "@/lib/github"; +import { normalizeLanguageName } from "@/lib/languages"; -const MAX_SELECTED_LANGUAGES = 5; +export { normalizeLanguageName }; -export function normalizeLanguageName(language: string): string { - return language.trim().toLowerCase(); -} +const MAX_SELECTED_LANGUAGES = 5; export function normalizeSelectedLanguages(languages?: string[]): string[] { if (!languages || languages.length === 0) { diff --git a/src/features/scoring/services/score-engine.ts b/src/features/scoring/services/score-engine.ts index 7742347..71d918b 100644 --- a/src/features/scoring/services/score-engine.ts +++ b/src/features/scoring/services/score-engine.ts @@ -1,5 +1,10 @@ import type { DiscussionNode, IssueNode, PullRequestNode, RepoNode } from "@/lib/github"; -import type { ScoringExplanations, ScoringSignals } from "../types"; +import type { + CalculateUserScoreResult, + LanguageScores, + ScoringExplanations, + ScoringSignals, +} from "../types"; import { getTopLanguages, normalizeSelectedLanguages } from "./language-scoring"; import { BASE_SCORING_EXPLANATIONS, @@ -24,100 +29,15 @@ export * from "./repo-scoring"; export * from "./pr-scoring"; export * from "./community-scoring"; -export type TopRepo = { - name: string; - url?: string; - stars: number; - forks: number; - watchers: number; - score: number; - topLanguages?: { - name: string; - percentage: number; - }[]; -}; - -export type TopPullRequest = { - repo: string; - title: string; - url?: string; - stars: number; - score: number; - additions: number; - deletions: number; - topLanguages?: { - name: string; - percentage: number; - }[]; -}; - -export type TopCommunityContribution = { - type: "issue" | "discussion"; - title: string; - url?: string; - repo: string; - stars: number; - comments: number; - score: number; -}; - -export type TopLanguageRepo = TopRepo & { - languageMatch: number; - topLanguages: { - name: string; - percentage: number; - }[]; -}; - -export type TopLanguagePullRequest = TopPullRequest & { - languageMatch: number; - topLanguages: { - name: string; - percentage: number; - }[]; -}; - -export type LanguageScores = { - selectedLanguages: string[]; - repoScore: number; - prScore: number; - contributionScore: number; - finalScore: number; - normalizedRepoScore: number; - normalizedPRScore: number; - normalizedContributionScore: number; - normalizedFinalScore: number; - topRepos: TopLanguageRepo[]; - topPullRequests: TopLanguagePullRequest[]; -}; - -export type CalculateUserScoreResult = { - username: string; - repoScore: number; - prScore: number; - contributionScore: number; - finalScore: number; - normalizedRepoScore: number; - normalizedPRScore: number; - normalizedContributionScore: number; - normalizedFinalScore: number; - scores: { - repoScore: number; - prScore: number; - contributionScore: number; - finalScore: number; - normalizedRepoScore: number; - normalizedPRScore: number; - normalizedContributionScore: number; - normalizedFinalScore: number; - }; - topRepos: TopRepo[]; - topPullRequests: TopPullRequest[]; - topCommunityContributions: TopCommunityContribution[]; - languageScores?: LanguageScores; - signals: ScoringSignals; - explanations: ScoringExplanations; -}; +export type { + TopRepo, + TopPullRequest, + TopCommunityContribution, + TopLanguageRepo, + TopLanguagePullRequest, + LanguageScores, + CalculateUserScoreResult, +} from "../types"; export function calculateUserScore( data: { diff --git a/src/features/scoring/types.ts b/src/features/scoring/types.ts index a5d4c69..f4900a8 100644 --- a/src/features/scoring/types.ts +++ b/src/features/scoring/types.ts @@ -42,15 +42,75 @@ export type ScoringExplanations = { language?: string[]; }; -export type LanguageScore = { - language: string; +export type TopRepo = { + name: string; + url?: string; + stars: number; + forks: number; + watchers: number; + score: number; + topLanguages?: { + name: string; + percentage: number; + }[]; +}; + +export type TopPullRequest = { + repo: string; + title: string; + url?: string; + stars: number; + score: number; + additions: number; + deletions: number; + topLanguages?: { + name: string; + percentage: number; + }[]; +}; + +export type TopCommunityContribution = { + type: "issue" | "discussion"; + title: string; + url?: string; + repo: string; + stars: number; + comments: number; + score: number; +}; + +export type TopLanguageRepo = TopRepo & { + languageMatch: number; + topLanguages: { + name: string; + percentage: number; + }[]; +}; + +export type TopLanguagePullRequest = TopPullRequest & { + languageMatch: number; + topLanguages: { + name: string; + percentage: number; + }[]; +}; + +export type LanguageScores = { + selectedLanguages: string[]; repoScore: number; prScore: number; contributionScore: number; finalScore: number; + normalizedRepoScore: number; + normalizedPRScore: number; + normalizedContributionScore: number; + normalizedFinalScore: number; + topRepos: TopLanguageRepo[]; + topPullRequests: TopLanguagePullRequest[]; }; -export type ScoreBreakdown = { +export type CalculateUserScoreResult = { + username: string; repoScore: number; prScore: number; contributionScore: number; @@ -59,10 +119,20 @@ export type ScoreBreakdown = { normalizedPRScore: number; normalizedContributionScore: number; normalizedFinalScore: number; - topRepos: RepoScoreDetail[]; - topPullRequests: PullRequestScoreDetail[]; - topCommunityContributions: CommunityContributionDetail[]; - languageScores: LanguageScore[]; + scores: { + repoScore: number; + prScore: number; + contributionScore: number; + finalScore: number; + normalizedRepoScore: number; + normalizedPRScore: number; + normalizedContributionScore: number; + normalizedFinalScore: number; + }; + topRepos: TopRepo[]; + topPullRequests: TopPullRequest[]; + topCommunityContributions: TopCommunityContribution[]; + languageScores?: LanguageScores; signals: ScoringSignals; explanations: ScoringExplanations; }; diff --git a/src/lib/api/api-helpers.ts b/src/lib/api/api-helpers.ts index bb34a53..26ffa8c 100644 --- a/src/lib/api/api-helpers.ts +++ b/src/lib/api/api-helpers.ts @@ -43,7 +43,7 @@ export function parseSelectedLanguagesFromSearchParams(searchParams: URLSearchPa /** * Standardized API error response handler for route handlers. - * Translates UserFetchError, CompareUserFetchError, and generic exceptions + * Translates UserFetchError and generic exceptions * into structured ClientSafeError responses with proper HTTP status codes. */ export function formatApiErrorResponse(error: unknown): NextResponse { diff --git a/src/lib/db/db-store.ts b/src/lib/db/db-store.ts index b4d8563..7e5a6c3 100644 --- a/src/lib/db/db-store.ts +++ b/src/lib/db/db-store.ts @@ -1,7 +1,7 @@ import { Pool, PoolConfig } from "pg"; import countries from "@/data/countries.json"; import type { GitHubUserData } from "@/lib/github"; -import type { CalculateUserScoreResult } from "@/features/scoring/services"; +import type { CalculateUserScoreResult } from "@/features/scoring"; // ─── Types ───────────────────────────────────────────────────────────── diff --git a/src/lib/github/github-client.ts b/src/lib/github/github-client.ts index a3afbed..6c280ab 100644 --- a/src/lib/github/github-client.ts +++ b/src/lib/github/github-client.ts @@ -513,101 +513,6 @@ async function fetchUserDataFromGitHub( return { data: userData, metrics }; } -// Wrapper to maintain the old function signature for existing callers -async function fetchUserDataFromGitHubWrapper( - executor: GitHubQueryExecutor, - username: string, -): Promise { - const { data } = await fetchUserDataFromGitHub(executor, username); - return data; -} - -// --------------------------------------------------------------------------- -// Fetcher factory (caching + single-flight) -// --------------------------------------------------------------------------- - -export function createGitHubUserDataFetcherWithMetrics( - dependencies: GitHubFetcherDependencies, -): (username: string) => Promise<{ data: GitHubUserData; metrics: UserFetchMetrics }> { - const inFlightByCacheKey = new Map< - string, - Promise<{ data: GitHubUserData; metrics: UserFetchMetrics }> - >(); - const logger = dependencies.logger ?? console; - - return async (username: string): Promise<{ data: GitHubUserData; metrics: UserFetchMetrics }> => { - const normalizedUsername = normalizeGitHubUsername(username); - if (!normalizedUsername) { - throw new Error("Username is required"); - } - - const cacheKey = buildGitHubUserCacheKey( - normalizedUsername, - dependencies.cacheConfig.namespace, - ); - - // Caching logic remains the same, but we now cache the { data, metrics } object - if (dependencies.cacheStore.enabled) { - try { - const cached = await dependencies.cacheStore.get(cacheKey); - if (cached !== undefined) { - // A simple check to see if it's our object. - if ( - isObject(cached) && - "data" in cached && - "metrics" in cached && - isGitHubUserData(cached.data) - ) { - logger.info("cache-hit", { key: cacheKey }); - return cached as { data: GitHubUserData; metrics: UserFetchMetrics }; - } - logger.warn("cache-corrupt", { key: cacheKey }); - await dependencies.cacheStore.del?.(cacheKey); - } else { - logger.info("cache-miss", { key: cacheKey }); - } - } catch (error: unknown) { - logger.warn("cache-read-fail", { - key: cacheKey, - message: error instanceof Error ? error.message : String(error), - }); - } - } - - const inFlight = inFlightByCacheKey.get(cacheKey); - if (inFlight) { - logger.info("single-flight-join", { key: cacheKey }); - return inFlight; - } - - const request = (async () => { - const freshResult = await fetchUserDataFromGitHub(dependencies.executor, normalizedUsername); - - if (dependencies.cacheStore.enabled) { - try { - await dependencies.cacheStore.set( - cacheKey, - freshResult, - dependencies.cacheConfig.ttlSeconds, - ); - } catch (error: unknown) { - logger.warn("cache-set-fail", { - key: cacheKey, - message: error instanceof Error ? error.message : String(error), - }); - } - } - - return freshResult; - })().finally(() => { - inFlightByCacheKey.delete(cacheKey); - }); - - inFlightByCacheKey.set(cacheKey, request); - return request; - }; -} - // --------------------------------------------------------------------------- // Fetcher factory (caching + single-flight) // --------------------------------------------------------------------------- @@ -657,11 +562,11 @@ export function createGitHubUserDataFetcher( } const request = (async () => { - const fresh = await fetchUserDataFromGitHubWrapper(dependencies.executor, normalizedUsername); + const { data } = await fetchUserDataFromGitHub(dependencies.executor, normalizedUsername); if (dependencies.cacheStore.enabled) { try { - await dependencies.cacheStore.set(cacheKey, fresh, dependencies.cacheConfig.ttlSeconds); + await dependencies.cacheStore.set(cacheKey, data, dependencies.cacheConfig.ttlSeconds); } catch (error: unknown) { logger.warn("cache-set-fail", { key: cacheKey, @@ -670,7 +575,7 @@ export function createGitHubUserDataFetcher( } } - return fresh; + return data; })().finally(() => { inFlightByCacheKey.delete(cacheKey); }); diff --git a/src/lib/i18n/core.ts b/src/lib/i18n/core.ts index 35a9c76..9ffa2b5 100644 --- a/src/lib/i18n/core.ts +++ b/src/lib/i18n/core.ts @@ -54,3 +54,22 @@ export function parseAcceptLanguage( export function getLocaleDir(locale: Locale) { return localeMeta[locale].dir; } + +export function resolveRequestLocale(request: Request): Locale { + const cookieHeader = request.headers.get("cookie"); + const localeFromCookie = cookieHeader + ?.split(";") + .map((value) => value.trim()) + .find((value) => value.startsWith(`${LOCALE_COOKIE}=`)) + ?.split("=")[1]; + + if (isSupportedLocale(localeFromCookie)) { + return localeFromCookie; + } + + return parseAcceptLanguage( + request.headers.get("accept-language"), + supportedLocales, + DEFAULT_LOCALE, + ); +} diff --git a/src/types/index.ts b/src/types/index.ts new file mode 100644 index 0000000..0475d35 --- /dev/null +++ b/src/types/index.ts @@ -0,0 +1,2 @@ +export * from "./api"; +export * from "./models"; diff --git a/src/types/models.ts b/src/types/models.ts index 9276507..b1ee0d7 100644 --- a/src/types/models.ts +++ b/src/types/models.ts @@ -4,12 +4,3 @@ export interface BaseDeveloper { avatarUrl: string; location?: string | null; } - -export interface BaseRepository { - name: string; - owner: string; - url: string; - stargazerCount?: number; - forkCount?: number; - primaryLanguage?: string | null; -} diff --git a/src/types/next.ts b/src/types/next.ts deleted file mode 100644 index d7ba558..0000000 --- a/src/types/next.ts +++ /dev/null @@ -1,12 +0,0 @@ -export type PageProps< - TParams = Record, - TSearchParams = Record, -> = { - params: Promise; - searchParams?: Promise; -}; - -export type LayoutProps> = { - children: React.ReactNode; - params?: Promise; -};