import "./index.css" import { Link, Meta, Title } from "@solidjs/meta" import { ProviderIcon } from "@opencode-ai/ui/provider-icon" import { geoEquirectangular, geoPath } from "d3-geo" import { scaleSqrt } from "d3-scale" import countryCodesSource from "i18n-iso-countries/codes.json?raw" import { feature, mesh } from "topojson-client" import countriesTopologySource from "world-atlas/countries-50m.json?raw" import ibmPlexMonoRegularLatin1 from "@ibm/plex/IBM-Plex-Mono/fonts/split/woff2/IBMPlexMono-Regular-Latin1.woff2?url" import ibmPlexMonoMediumLatin1 from "@ibm/plex/IBM-Plex-Mono/fonts/split/woff2/IBMPlexMono-Medium-Latin1.woff2?url" import ibmPlexMonoSemiBoldLatin1 from "@ibm/plex/IBM-Plex-Mono/fonts/split/woff2/IBMPlexMono-SemiBold-Latin1.woff2?url" import ibmPlexMonoBoldLatin1 from "@ibm/plex/IBM-Plex-Mono/fonts/split/woff2/IBMPlexMono-Bold-Latin1.woff2?url" import { getStatsHomeData, type CacheRatioEntry, type CountryEntry, type LeaderboardEntry, type MarketDay, type StatsHomeData, type SessionCostEntry, type TokenCostEntry, type UsagePoint, } from "@opencode-ai/stats-core/domain/home" import { createAsync, query } from "@solidjs/router" import { createEffect, createMemo, createSignal, For, onCleanup, onMount, Show, type JSX } from "solid-js" import { getRequestEvent } from "solid-js/web" import type { FeatureCollection, GeometryObject, GeoJsonProperties } from "geojson" import type { GeometryCollection, Topology } from "topojson-specification" import { runStatsEffect } from "../stats-runtime" import { LocaleLinks } from "../component/locale-links" import { useI18n } from "../context/i18n" import { useLanguage } from "../context/language" import { localizedUrl } from "../lib/language" import { findModelCatalogEntry, getModelCatalog, type ModelCatalog } from "./model-catalog" import { applyThemePreference, Footer, getGitHubStars, githubLink, Header, isThemePreference, themeStorageKey, type ThemePreference, } from "./stats-shell" const products = ["All Users", "Zen", "Go"] as const const tokenProducts = ["Zen", "Go"] as const const ranges = ["1D", "1W", "2W", "1M", "2M"] as const const statsUnfurlPath = "banner.jpg" const usageColors = [ "#ed6aff", "#a684ff", "#7c86ff", "#51a2ff", "#00d3f2", "#00d5be", "#00bc7d", "#9ae600", "#ffb900", "#ff8904", "#ff6467", ] const marketColors = ["#ed6aff", "#a684ff", "#7c86ff", "#51a2ff", "#00d3f2", "#00d5be", "#00bc7d", "#9ae600", "#ffb900"] const geoMapWidth = 960 const geoMapHeight = 430 type UsageProduct = (typeof products)[number] type TokenProduct = (typeof tokenProducts)[number] type UsageRange = (typeof ranges)[number] type IsoCountryCode = readonly [string, string, string] type WorldCountryProperties = GeoJsonProperties & { name?: string } type WorldTopology = Topology<{ countries: GeometryCollection }> function productLabel(product: UsageProduct | TokenProduct, i18n: ReturnType) { if (product === "All Users") return i18n.t("product.allUsers") if (product === "Zen") return i18n.t("product.zen") return i18n.t("product.go") } function rangeLabel(range: UsageRange, i18n: ReturnType) { if (range === "1D") return i18n.t("range.1D") if (range === "1W") return i18n.t("range.1W") if (range === "2W") return i18n.t("range.2W") if (range === "1M") return i18n.t("range.1M") return i18n.t("range.2M") } const countryNumericIds = new Map( (JSON.parse(countryCodesSource) as IsoCountryCode[]).map((country) => [country[0], country[2]] as const), ) const worldTopology = JSON.parse(countriesTopologySource) as WorldTopology const worldCountryGeometries: GeometryCollection = { ...worldTopology.objects.countries, geometries: worldTopology.objects.countries.geometries.filter((country) => String(country.id ?? "") !== "010"), } const worldCountries = feature(worldTopology, worldCountryGeometries) as FeatureCollection< GeometryObject, WorldCountryProperties > const worldProjection = geoEquirectangular().fitExtent( [ [10, 12], [geoMapWidth - 10, geoMapHeight - 12], ], worldCountries, ) const worldPath = geoPath(worldProjection) const worldCountryPaths = worldCountries.features.map((country) => ({ id: String(country.id ?? "").padStart(3, "0"), path: worldPath(country) ?? "", marker: geoCountryMarker(country), })) const worldBorderPath = worldPath(mesh(worldTopology, worldCountryGeometries, (a, b) => a !== b)) ?? "" const getData = query(async () => { "use server" return runStatsEffect(getStatsHomeData()) }, "getStatsHomeData") export default function StatsHome() { const i18n = useI18n() const language = useLanguage() const event = getRequestEvent() event?.response.headers.set("Cache-Control", "public, max-age=60, s-maxage=300, stale-while-revalidate=86400") const statsHomeUrl = localizedUrl(language.locale(), "/data/") const statsUnfurlUrl = new URL(statsUnfurlPath, localizedUrl("en", "/data/")).toString() const data = createAsync(() => getData()) const catalog = createAsync(() => getModelCatalog()) const githubStars = createAsync(() => getGitHubStars()) const [themePreference, setThemePreference] = createSignal("system") const updateThemePreference = (preference: ThemePreference) => { applyThemePreference(preference) setThemePreference(preference) if (typeof window === "undefined") return window.localStorage.setItem(themeStorageKey, preference) } onMount(() => { if (typeof window === "undefined") return const preference = window.localStorage.getItem(themeStorageKey) const nextPreference = isThemePreference(preference) ? preference : "system" applyThemePreference(nextPreference) setThemePreference(nextPreference) }) return (
{i18n.t("app.title")}
}> {(stats) => ( <> )}
) } function Hero(props: { updatedAt: string | null }) { const i18n = useI18n() const language = useLanguage() const [timeZone, setTimeZone] = createSignal("UTC") const [previousTimeZone, setPreviousTimeZone] = createSignal("UTC") const [isTicking, setIsTicking] = createSignal(false) const updatedAtParts = (timeZone: string) => props.updatedAt ? formatUpdatedAtParts(props.updatedAt, timeZone, language.tag(language.locale()), i18n.t("home.justNow")) : { date: i18n.t("home.noRows"), time: "" } const previousUpdatedAt = createMemo(() => updatedAtParts(previousTimeZone())) const currentUpdatedAt = createMemo(() => updatedAtParts(timeZone())) const currentUpdatedLabel = createMemo(() => props.updatedAt ? `${i18n.t("home.updated")} ${formatUpdatedAtLabel(currentUpdatedAt())}` : i18n.t("home.noRows"), ) const isDateTicking = createMemo(() => isTicking() && previousUpdatedAt().date !== currentUpdatedAt().date) const isTimeTicking = createMemo(() => isTicking() && previousUpdatedAt().time !== currentUpdatedAt().time) onMount(() => { if (!props.updatedAt) return const nextTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC" if (nextTimeZone === "UTC") return if ( formatUpdatedAtLabel( formatUpdatedAtParts(props.updatedAt, nextTimeZone, language.tag(language.locale()), i18n.t("home.justNow")), ) === formatUpdatedAtLabel(updatedAtParts("UTC")) ) return const timeouts: number[] = [] timeouts.push( window.setTimeout(() => { setPreviousTimeZone(timeZone()) setTimeZone(nextTimeZone) setIsTicking(true) timeouts.push( window.setTimeout(() => { setPreviousTimeZone(nextTimeZone) setIsTicking(false) }, 720), ) }, 480), ) onCleanup(() => timeouts.forEach((timeout) => window.clearTimeout(timeout))) }) return (

{props.updatedAt ? ( <> ) : ( {i18n.t("home.noRows")} )}

) } function HeroMetaTickerPart(props: { previous: string; current: string; ticking: boolean }) { return ( {props.previous} {props.current} ) } function StatsLoading() { const i18n = useI18n() return ( <> ) } function ChartSection(props: { id?: string title: string description?: string controls?: JSX.Element children: JSX.Element }) { return (

{props.title}

{props.description &&

{props.description}

}
{props.controls}
{props.children}
) } function SectionTitle(props: { title: string; description: string }) { return (

{props.title}. {props.description}

) } function SectionBridge(props: { label: string; href: string }) { const i18n = useI18n() return ( {i18n.t("bridge.learnMore")} {props.label} ) } function EmptyState(props: { title: string; description: string }) { return (
{props.title}

{props.description}

) } function formatUpdatedAtParts(value: string, timeZone: string, locale: string, fallback: string) { const date = new Date(value) if (Number.isNaN(date.getTime())) return { date: fallback, time: "" } return { date: new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", timeZone, }).format(date), time: new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit", timeZone, timeZoneName: "short", }).format(date), } } function formatUpdatedAtLabel(value: { date: string; time: string }) { if (!value.time) return value.date return `${value.date}, ${value.time}` } function TopModelsSection(props: { data: StatsHomeData["usage"]; leaderboard: StatsHomeData["leaderboard"] }) { const i18n = useI18n() const [product, setProduct] = createSignal("Go") const [range, setRange] = createSignal("2M") const [sheet, setSheet] = createSignal<"product" | "range">() const [activeModel, setActiveModel] = createSignal() const data = createMemo(() => props.data[product()][range()]) const leaderboard = createMemo(() => props.leaderboard[product()][range()]) createEffect(() => { if (!sheet()) return if (typeof document === "undefined") return const htmlOverflow = document.documentElement.style.overflow const bodyOverflow = document.body.style.overflow document.documentElement.style.overflow = "hidden" document.body.style.overflow = "hidden" const onKeyDown = (event: KeyboardEvent) => { if (event.key === "Escape") setSheet(undefined) } document.addEventListener("keydown", onKeyDown) onCleanup(() => { document.documentElement.style.overflow = htmlOverflow document.body.style.overflow = bodyOverflow document.removeEventListener("keydown", onKeyDown) }) }) return (

{i18n.t("nav.topModels")}. {i18n.t("home.topModelsDescription")}

usageTotal(item) > 0)} fallback={} > 0} fallback={ } > {(kind) => ( { setProduct(value) setSheet(undefined) }} onRangeSelect={(value) => { setRange(value) setSheet(undefined) }} onClose={() => setSheet(undefined)} /> )}
) } function MobileFilterButton(props: { label: string; value: string; expanded: boolean; onClick: () => void }) { return ( ) } function MobileFilterSheet(props: { kind: "product" | "range" product: UsageProduct range: UsageRange onProductSelect: (product: UsageProduct) => void onRangeSelect: (range: UsageRange) => void onClose: () => void }) { const i18n = useI18n() return (
{(item) => ( )} } > {(item) => ( )}
) } function ChevronDown() { return ( ) } function StatsFilters(props: { product: UsageProduct range: UsageRange onProductSelect: (product: UsageProduct) => void onRangeSelect: (range: UsageRange) => void }) { const i18n = useI18n() return ( <> productLabel(item, i18n)} onSelect={props.onProductSelect} /> rangeLabel(item, i18n)} onSelect={props.onRangeSelect} /> ) } function FilterPills(props: { items: readonly T[] selected: T label: string variant: "product" | "range" formatLabel?: (item: T) => string onSelect: (item: T) => void }) { return (
{(item) => ( )}
) } function TopModelsChart(props: { data: UsagePoint[] range: UsageRange metric?: "tokens" | "users" ariaLabel?: string activeModel: string | undefined onActiveModelChange: (model: string | undefined) => void }) { const i18n = useI18n() let chartRef: HTMLDivElement | undefined const [activeIndex, setActiveIndex] = createSignal() const maxTotal = createMemo(() => getTopModelsMaxTotal(props.data)) const segmentOrder = createMemo(() => getTopModelsSegmentOrder(props.data)) const activePoint = createMemo(() => props.data[activeIndex() ?? -1]) const metric = createMemo(() => props.metric ?? "tokens") createEffect(() => scrollDenseChartToEnd(chartRef, props.range, props.data.length)) return (
{ if (event.pointerType === "touch") return setActiveIndex(undefined) props.onActiveModelChange(undefined) }} >
{ if (event.pointerType === "touch") return setActiveIndex(undefined) props.onActiveModelChange(undefined) }} > {(day, dayIndex) => (
{ if (event.pointerType !== "touch") return setActiveIndex(dayIndex()) props.onActiveModelChange(undefined) }} onPointerEnter={(event) => { setActiveIndex(dayIndex()) if (isTopModelsBlankHover(event.currentTarget, event.clientY)) props.onActiveModelChange(undefined) }} onPointerMove={(event) => { if (event.pointerType === "touch") return setActiveIndex(dayIndex()) if (isTopModelsBlankHover(event.currentTarget, event.clientY)) props.onActiveModelChange(undefined) }} onClick={() => { setActiveIndex(dayIndex()) props.onActiveModelChange(undefined) }} onFocus={() => { setActiveIndex(dayIndex()) props.onActiveModelChange(undefined) }} onBlur={() => { setActiveIndex(undefined) props.onActiveModelChange(undefined) }} onKeyDown={(event) => { if (event.key !== "Enter" && event.key !== " ") return event.preventDefault() setActiveIndex(dayIndex()) props.onActiveModelChange(undefined) }} >
{(item) => ( { event.stopPropagation() setActiveIndex(dayIndex()) props.onActiveModelChange(item.segment.model) }} onPointerDown={(event) => { event.stopPropagation() setActiveIndex(dayIndex()) props.onActiveModelChange(item.segment.model) }} onClick={(event) => { event.stopPropagation() setActiveIndex(dayIndex()) props.onActiveModelChange(item.segment.model) }} /> )}
{(point) => (
props.data.length * 0.62 ? "left" : "right"} > {point().date} {formatUsageChartValue(usageTotal(point()), metric())} {usageChartTotalLabel(metric(), i18n)}
{(item) => (

{" "} {item.segment.model} {formatUsageChartValue(item.segment.value, metric())}

)}
)}
)}
) } function UniqueUsersSection(props: { data: StatsHomeData["users"] }) { const i18n = useI18n() const [activeModel, setActiveModel] = createSignal() const data = createMemo(() => props.data.Go["2M"]) return (
usageTotal(item) > 0)} fallback={ } >
) } function isTopModelsBlankHover(bar: HTMLElement, clientY: number) { const stack = bar.querySelector('[data-slot="top-models-stack"]') if (!stack) return true return clientY < stack.getBoundingClientRect().top - 6 } function getTopModelsBarHeight(total: number, max: number) { if (total <= 0) return 0 return Math.max(2, Math.min(100, (total / max) * 100)) } function getTopModelsMaxTotal(data: UsagePoint[]) { const max = Math.max(0, ...data.map((item) => usageTotal(item))) if (max === 0) return 1 if (data.length === 1) return max * 1.75 return max } function getTopModelsSegmentRows(point: UsagePoint, order: Map) { const total = usageTotal(point) if (total <= 0) return "" return stackedTopModelsSegments(point, order) .map((item) => `${(item.segment.value / total) * 100}%`) .join(" ") } function visibleTopModelsSegments(point: UsagePoint) { return point.segments.map((segment, index) => ({ segment, index })).filter((item) => item.segment.value > 0) } function stackedTopModelsSegments(point: UsagePoint, order: Map) { return visibleTopModelsSegments(point) .slice() .sort((a, b) => (order.get(b.segment.model) ?? b.index) - (order.get(a.segment.model) ?? a.index)) } function getTopModelsSegmentOrder(data: UsagePoint[]) { return new Map( data.find((point) => point.segments.length > 0)?.segments.map((segment, index) => [segment.model, index]) ?? [], ) } function getTopModelsSegmentColor( model: string, index: number, order: Map, muted: boolean, activeModel: string | undefined, ) { if (activeModel !== undefined) return activeModel === model ? getRankColor(model, index, order, usageColors) : "var(--stats-layer-2)" if (muted) return "var(--stats-layer-2)" return getRankColor(model, index, order, usageColors) } function isTopModelsMobileAxisHidden(index: number, count: number) { return count > 7 && index % 2 === 1 } function isColumnLabelHidden(index: number, count: number) { if (count <= 20) return false const interval = Math.ceil(count / 8) return index !== count - 1 && index % interval !== 0 } function isDenseColumnRange(range: UsageRange) { return range === "1M" || range === "2M" } function scrollDenseChartToEnd(element: HTMLDivElement | undefined, range: UsageRange, count: number) { if (!element || count <= 0 || !isDenseColumnRange(range) || typeof window === "undefined") return window.requestAnimationFrame(() => { element.scrollLeft = element.scrollWidth - element.clientWidth }) } function formatTopModelsMobileDate(label: string, range: UsageRange) { if (range === "1M" || range === "2M") return label.split(" - ")[0] ?? label return label } function usageTotal(point: UsagePoint) { return point.segments.reduce((sum, item) => sum + item.value, 0) } function formatTokens(value: number) { if (value >= 1) return `${value.toFixed(value >= 10 ? 0 : 1)}T` return `${Math.round(value * 1000)}B` } function formatUsageChartValue(value: number, metric: "tokens" | "users") { if (metric === "users") return formatUsers(value) return formatTokens(value) } function usageChartTotalLabel(metric: "tokens" | "users", i18n: ReturnType) { if (metric === "users") return i18n.t("home.modelUsers") return i18n.t("home.total") } function formatUsers(value: number) { if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(value >= 10_000_000 ? 0 : 1)}M` if (value >= 1_000) return `${(value / 1_000).toFixed(value >= 10_000 ? 0 : 1)}K` return new Intl.NumberFormat("en").format(Math.round(value)) } function Leaderboard(props: { data: LeaderboardEntry[] activeModel: string | undefined onActiveModelChange: (model: string | undefined) => void }) { const i18n = useI18n() const featured = createMemo(() => props.data.slice(0, 3)) const compact = createMemo(() => props.data.slice(3)) return (
{(entry) => ( )}
) } function LeaderboardCard(props: { entry: LeaderboardEntry size: "featured" | "compact" active: boolean onActiveModelChange: (model: string | undefined) => void }) { const i18n = useI18n() const language = useLanguage() return ( props.onActiveModelChange(props.entry.model)} onPointerLeave={(event) => { if (event.pointerType === "touch") return props.onActiveModelChange(undefined) }} onFocus={() => props.onActiveModelChange(props.entry.model)} onBlur={() => props.onActiveModelChange(undefined)} onClick={() => props.onActiveModelChange(props.entry.model)} > {String(props.entry.rank).padStart(2, "0")} ) } function getProviderIconId(author: string) { if (author === "MiniMax") return "minimax" if (author === "Moonshot") return "moonshotai" if (author === "Zhipu") return "zhipuai" return author.toLowerCase() } function formatBillions(value: number) { if (value >= 1000) return `${(value / 1000).toFixed(value >= 10000 ? 0 : 1)}T` return `${value}B` } function formatChange(value: number | null, i18n: ReturnType) { if (value === null) return i18n.t("home.new") if (value > 0) return `+${value}%` return `${value}%` } function MarketShareSection(props: { data: StatsHomeData["market"] }) { const i18n = useI18n() const [range, setRange] = createSignal("2M") const [activeIndex, setActiveIndex] = createSignal(2) const [activeAuthor, setActiveAuthor] = createSignal() const [inspecting, setInspecting] = createSignal(false) const data = createMemo(() => props.data[range()]) const authorOrder = createMemo(() => getMarketAuthorOrder(data())) const selectedIndex = createMemo(() => Math.min(activeIndex(), Math.max(data().length - 1, 0))) const activeDay = createMemo(() => data()[selectedIndex()]) return (
{ if (event.pointerType === "touch") return setActiveAuthor(undefined) setInspecting(false) }} > } > {(day) => ( <> { setActiveIndex(index) setInspecting(true) }} onActiveAuthorChange={(author) => { setActiveAuthor(author) setInspecting(true) }} /> { setActiveAuthor(author) setInspecting(true) }} /> )}

[*] {inspecting() ? formatMarketDate(activeDay(), i18n.t("home.noData")) : formatMarketRange(data(), i18n.t("home.noData"))}

) } function MarketShare(props: { data: MarketDay[] range: UsageRange authorOrder: Map activeIndex: number activeAuthor: string | undefined inspecting: boolean onActiveIndexChange: (index: number) => void onActiveAuthorChange: (author: string) => void }) { const i18n = useI18n() let chartRef: HTMLDivElement | undefined createEffect(() => scrollDenseChartToEnd(chartRef, props.range, props.data.length)) return (
{(day, index) => ( )}
{(day, index) => ( )}
) } function MarketShareList(props: { data: MarketDay["authors"] authorOrder: Map activeAuthor: string | undefined onActiveAuthorChange: (author: string) => void }) { const i18n = useI18n() return (
    {(item, index) => (
  1. props.onActiveAuthorChange(item.author)} onFocus={() => props.onActiveAuthorChange(item.author)} onKeyDown={(event) => { if (event.key !== "Enter" && event.key !== " ") return event.preventDefault() props.onActiveAuthorChange(item.author) }} > {String(index() + 1).padStart(2, "0")} {item.author} {formatTrillions(item.tokens)} {item.share.toFixed(1)}%
  2. )}
) } function GeoBreakdownSection(props: { data: StatsHomeData["country"] }) { const i18n = useI18n() const language = useLanguage() const [activeCountry, setActiveCountry] = createSignal() const data = createMemo(() => props.data["2M"]) const countryById = createMemo( () => new Map( data().flatMap((country) => { const id = countryNumericId(country.country) return id ? [[id, country] as const] : [] }), ), ) const maxTokens = createMemo(() => Math.max(0, ...data().map((country) => country.tokens)) || 1) const topCountries = createMemo(() => data().slice(0, 15)) const active = createMemo(() => data().find((country) => country.country === activeCountry()) ?? data()[0]) return (
{ if (event.pointerType === "touch") return setActiveCountry(undefined) }} > 0} fallback={} >
{(country) => (
#{String(country().rank).padStart(2, "0")} {formatCountryName(country().country, language.tag(language.locale()), i18n.t("home.unknown"))}

{formatGeoTokens(country().tokens)} {formatGeoShare(country().share)}

)}
) } function GeoWorldMap(props: { countryById: Map activeCountry: string | undefined maxTokens: number onActiveCountryChange: (country: string | undefined) => void }) { const i18n = useI18n() const opacityScale = createMemo(() => scaleSqrt().domain([0, props.maxTokens]).range([0.26, 0.96]).clamp(true)) const countryOpacity = (country: CountryEntry | undefined) => { if (!country) return 0 const opacity = opacityScale()(country.tokens) if (!props.activeCountry || props.activeCountry === country.country) return opacity return Math.max(0.18, opacity * 0.36) } return ( {i18n.t("home.geoMapTitle")} {(country) => { const entry = () => props.countryById.get(country.id) return ( {(country) => { const entry = () => props.countryById.get(country.id) return ( {(marker) => ( ) }} ) } function GeoCountryList(props: { data: CountryEntry[] activeCountry: string | undefined maxTokens: number onActiveCountryChange: (country: string | undefined) => void }) { const i18n = useI18n() const language = useLanguage() const opacityScale = createMemo(() => scaleSqrt().domain([0, props.maxTokens]).range([0.26, 0.96]).clamp(true)) return (
    {(country) => (
  1. )}
) } function countryNumericId(country: string) { return countryNumericIds.get(country.toUpperCase())?.padStart(3, "0") } function geoCountryMarker(country: (typeof worldCountries.features)[number]) { const bounds = worldPath.bounds(country) const [x, y] = worldPath.centroid(country) if (!Number.isFinite(x) || !Number.isFinite(y)) return undefined if (bounds[1][0] - bounds[0][0] >= 3 && bounds[1][1] - bounds[0][1] >= 3) return undefined return { x, y } } function formatCountryName(country: string, locale: string, unknown: string) { const code = country.toUpperCase() if (code === "ZZ") return unknown if (!countryNumericId(code)) return code return new Intl.DisplayNames([locale], { type: "region" }).of(code) ?? code } function formatGeoTokens(value: number) { return formatTrillions(value) } function formatGeoShare(value: number) { return `${value.toFixed(value > 0 && value < 1 ? 1 : 0)}%` } function getMarketSegmentColor(author: string, color: string, activeAuthor: string | undefined) { if (!activeAuthor) return color if (activeAuthor === author) return color return "var(--stats-bar-idle)" } function stackedMarketAuthors(day: MarketDay, order: Map) { return day.authors .map((author, index) => ({ author, index })) .slice() .sort((a, b) => (order.get(b.author.author) ?? b.index) - (order.get(a.author.author) ?? a.index)) } function getMarketAuthorOrder(data: MarketDay[]) { return getRankOrder( data.flatMap((day) => day.authors.map((author, index) => ({ key: author.author, value: author.tokens, index }))), ) } function getRankOrder(items: { key: string; value: number; index: number }[]) { return new Map( Object.values( items.reduce>((result, item) => { result[item.key] = { key: item.key, value: (result[item.key]?.value ?? 0) + item.value, index: Math.min(result[item.key]?.index ?? item.index, item.index), } return result }, {}), ) .toSorted((a, b) => b.value - a.value || a.index - b.index || a.key.localeCompare(b.key)) .map((item, index) => [item.key, index] as const), ) } function getRankColor(key: string, fallbackIndex: number, order: Map, colors: readonly string[]) { return colors[order.get(key) ?? fallbackIndex] ?? "var(--stats-text)" } function isMarketMobileLabelHidden(index: number, count: number) { return count > 7 && index % 2 === 1 } function formatMarketMobileDate(label: string) { return marketDateParts(label).start } function formatTrillions(value: number) { if (value === 0) return "0" if (value < 0.001) return `${Number((value * 1_000_000).toFixed(value >= 0.00001 ? 0 : 1))}M` if (value < 1) return `${Number((value * 1_000).toFixed(value >= 0.01 ? 0 : 1))}B` return `${value.toFixed(value >= 10 ? 0 : 1)}T` } function formatMarketDate(day: MarketDay | undefined, fallback: string) { if (!day) return fallback return formatMarketDateLabel(day.date) } function formatMarketRange(data: MarketDay[], fallback: string) { const first = data[0]?.date const last = data[data.length - 1]?.date if (!first || !last) return fallback const start = marketDateParts(first).start const end = marketDateParts(last).end if (start === end) return formatMarketDateLabel(start) return `${start} ${new Date().getFullYear()} → ${end} ${new Date().getFullYear()}` } function formatMarketDateLabel(label: string) { const parts = marketDateParts(label) const year = new Date().getFullYear() if (parts.start === parts.end) return `${parts.start} ${year}` return `${parts.start} ${year} → ${parts.end} ${year}` } function marketDateParts(label: string) { const [start, end] = label.split(" - ") return { start: start ?? label, end: end ?? start ?? label } } function TokenCostSection(props: { data: StatsHomeData["tokenCost"]; catalog: ModelCatalog | null }) { const i18n = useI18n() const [product, setProduct] = createSignal("Go") const [activeIndex, setActiveIndex] = createSignal(2) const data = createMemo(() => priceTokenCostFromCatalog(props.data[product()], props.catalog)) const visible = createMemo(() => data().slice(0, 13)) const selectedIndex = createMemo(() => Math.min(activeIndex(), Math.max(visible().length - 1, 0))) return (
0} fallback={ } >
) } function TokenCostChart(props: { data: TokenCostEntry[] activeIndex: number onActiveIndexChange: (index: number) => void }) { const i18n = useI18n() const max = createMemo(() => Math.max(0, ...props.data.map((item) => item.total)) || 1) const active = createMemo(() => props.data[props.activeIndex] ?? props.data[0]) return (
{(item, index) => ( )} {(item) => (

{i18n.t("chart.input")} {formatDollars(item().input)}

{i18n.t("chart.output")} {formatDollars(item().output)}

{i18n.t("chart.cached")} {formatDollars(item().cached)}

)}
) } function CacheRatioSection(props: { data: StatsHomeData["cacheRatio"] }) { const i18n = useI18n() const [product, setProduct] = createSignal("Go") const [activeIndex, setActiveIndex] = createSignal(2) const data = createMemo(() => props.data[product()]) const visible = createMemo(() => data().slice(0, 16)) const selectedIndex = createMemo(() => Math.min(activeIndex(), Math.max(visible().length - 1, 0))) return (
0} fallback={} >
) } function CacheRatioChart(props: { data: CacheRatioEntry[] activeIndex: number onActiveIndexChange: (index: number) => void }) { const i18n = useI18n() const active = createMemo(() => props.data[props.activeIndex] ?? props.data[0]) return (
{(item, index) => ( )}
{(item) => (

{i18n.t("chart.cacheRatio")} {formatRatio(item().ratio)}

{i18n.t("chart.cached")} {formatBillions(item().cached)}

{i18n.t("chart.uncached")} {formatBillions(item().uncached)}

)}
) } function CacheRatioMarker(props: { ratio: number; active: boolean }) { const fill = createMemo(() => Math.min(100, Math.max(0, props.ratio))) return ( ) } function formatRatio(value: number) { return `${value.toFixed(value > 0 && value < 10 ? 1 : 0)}%` } function formatDollars(value: number) { return `$${value.toFixed(value > 0 && value < 0.01 ? 4 : 2)}` } function MetricBar(props: { value: number; max: number; active: boolean }) { const fill = createMemo(() => Math.min(1, Math.max(props.value / props.max, props.value > 0 ? 0.03 : 0))) return ( ) } function SessionCostSection(props: { data: StatsHomeData["sessionCost"] }) { const i18n = useI18n() const [product, setProduct] = createSignal("Go") const [activeIndex, setActiveIndex] = createSignal(2) const data = createMemo(() => props.data[product()]) const visible = createMemo(() => data().slice(0, 16)) const selectedIndex = createMemo(() => Math.min(activeIndex(), Math.max(visible().length - 1, 0))) return (
0} fallback={ } >
) } function SessionCostChart(props: { data: SessionCostEntry[] activeIndex: number onActiveIndexChange: (index: number) => void }) { const i18n = useI18n() const maxCost = createMemo(() => Math.max(0, ...props.data.map((item) => item.cost)) || 1) const maxTokens = createMemo(() => Math.max(0, ...props.data.map((item) => item.tokens)) || 1) const active = createMemo(() => props.data[props.activeIndex] ?? props.data[0]) return (