Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usageFormat.ts

232 lines7.5 KB

1// @effect-diagnostics globalDate:off -- Usage windows are calendar days in the viewer's zone, derived from wall-clock "now" via Intl.
2/**
3 * Display formatting for the usage page.
4 *
5 * @module usageFormat
6 */
7import { UsageDay, type UsageResolution, type UsageSummaryInput } from "@t3tools/contracts";
8​
9const CURRENCY = new Intl.NumberFormat("en-US", {
10 style: "currency",
11 currency: "USD",
12 minimumFractionDigits: 2,
13 maximumFractionDigits: 2,
14});
15​
16const INTEGER = new Intl.NumberFormat("en-US");
17​
18export function formatUsd(value: number): string {
19 return CURRENCY.format(value);
21​
22export function formatCount(value: number): string {
23 return INTEGER.format(Math.round(value));
25​
26/**
27 * Compacts a token count to three significant figures with a unit suffix, so
28 * columns of numbers line up at a glance (`19.9B`, `76.7M`, `804K`).
29 */
30export function formatTokens(value: number): string {
31 const abs = Math.abs(value);
32 if (abs >= 1e12) return `${trim(value / 1e12)}T`;
33 if (abs >= 1e9) return `${trim(value / 1e9)}B`;
34 if (abs >= 1e6) return `${trim(value / 1e6)}M`;
35 if (abs >= 1e3) return `${trim(value / 1e3)}K`;
36 return INTEGER.format(Math.round(value));
38​
39function trim(value: number): string {
40 const abs = Math.abs(value);
41 const digits = abs >= 100 ? 0 : abs >= 10 ? 1 : 2;
42 return value.toFixed(digits).replace(/\.0+$/, "");
44​
45export function formatPercent(share: number, digits = 1): string {
46 return `${(share * 100).toFixed(digits)}%`;
48​
49/** `2026-08-07` to `Aug 7`. */
50export function formatDayShort(day: string): string {
51 const [year, month, dayOfMonth] = day.split("-").map((part) => Number(part));
52 if (year === undefined || month === undefined || dayOfMonth === undefined) return day;
53 const MONTHS = [
54 "Jan",
55 "Feb",
56 "Mar",
57 "Apr",
58 "May",
59 "Jun",
60 "Jul",
61 "Aug",
62 "Sep",
63 "Oct",
64 "Nov",
65 "Dec",
66 ];
67 return `${MONTHS[month - 1] ?? ""} ${dayOfMonth}`;
69​
70/** Inclusive day list between two `YYYY-MM-DD` bounds. */
71export function enumerateDays(sinceDay: string, untilDay: string): readonly string[] {
72 const days: string[] = [];
73 const start = Date.parse(`${sinceDay}T00:00:00Z`);
74 const end = Date.parse(`${untilDay}T00:00:00Z`);
75 if (Number.isNaN(start) || Number.isNaN(end) || end < start) return days;
76​
77 for (let cursor = start; cursor <= end; cursor += 86_400_000) {
78 days.push(new Date(cursor).toISOString().slice(0, 10));
79 }
80 return days;
82​
83const HOUR_MS = 60 * 60 * 1000;
84​
85/** Every fixed-duration bucket start in an hourly rolling window. */
86export function enumerateHourStarts(sinceTime: string, untilTime: string): readonly string[] {
87 const starts: string[] = [];
88 const start = Date.parse(sinceTime);
89 const end = Date.parse(untilTime);
90 if (Number.isNaN(start) || Number.isNaN(end) || end <= start) return starts;
91​
92 for (let cursor = start; cursor < end; cursor += HOUR_MS) {
93 starts.push(new Date(cursor).toISOString());
94 }
95 return starts;
97​
98/**
99 * A rolling bucket start rendered in the viewer's requested time zone.
100 *
101 * Repeated wall-clock hours during a fall-back transition include their short
102 * zone name so the two distinct buckets remain distinguishable.
103 */
104export function formatHourShort(hourStart: string, timeZone?: string): string {
105 const instant = new Date(hourStart);
106 if (Number.isNaN(instant.getTime())) return hourStart;
107 const options = timeZone === undefined ? {} : { timeZone };
108 const hourFormat = new Intl.DateTimeFormat("en-US", {
109 ...options,
110 hour: "numeric",
111 });
112 const wallHourFormat = new Intl.DateTimeFormat("en-CA", {
113 ...options,
114 year: "numeric",
115 month: "2-digit",
116 day: "2-digit",
117 hour: "2-digit",
118 hourCycle: "h23",
119 });
120 const wallHour = wallHourFormat.format(instant);
121 const isRepeatedHour = [-HOUR_MS, HOUR_MS].some(
122 (offset) => wallHourFormat.format(new Date(instant.getTime() + offset)) === wallHour,
123 );
124​
125 if (!isRepeatedHour) return hourFormat.format(instant);
126 return new Intl.DateTimeFormat("en-US", {
127 ...(timeZone === undefined ? {} : { timeZone }),
128 hour: "numeric",
129 timeZoneName: "short",
130 }).format(instant);
132​
133/** `2026-08-11T14:37:00Z` to `Aug 11, 2 PM` in the requested zone. */
134export function formatDateTimeShort(instant: string, timeZone?: string): string {
135 const date = new Date(instant);
136 if (Number.isNaN(date.getTime())) return instant;
137 return new Intl.DateTimeFormat("en-US", {
138 ...(timeZone === undefined ? {} : { timeZone }),
139 month: "short",
140 day: "numeric",
141 hour: "numeric",
142 }).format(date);
144​
145/** An hourly tooltip label relative to the rolling window's end date. */
146export function formatRelativeHourShort(
147 hourStart: string,
148 relativeTo: string,
149 timeZone?: string,
150): string {
151 const instant = new Date(hourStart);
152 const reference = new Date(relativeTo);
153 if (Number.isNaN(instant.getTime()) || Number.isNaN(reference.getTime())) {
154 return formatDateTimeShort(hourStart, timeZone);
155 }
156​
157 const dayFormat = new Intl.DateTimeFormat("en-CA", {
158 ...(timeZone === undefined ? {} : { timeZone }),
159 year: "numeric",
160 month: "2-digit",
161 day: "2-digit",
162 });
163 const instantDay = Date.parse(`${dayFormat.format(instant)}T00:00:00Z`);
164 const referenceDay = Date.parse(`${dayFormat.format(reference)}T00:00:00Z`);
165 const calendarDaysAgo = Math.round((referenceDay - instantDay) / (24 * HOUR_MS));
166 const hour = formatHourShort(hourStart, timeZone);
167​
168 if (calendarDaysAgo === 0) return `${hour} today`;
169 if (calendarDaysAgo === 1) return `${hour} yesterday`;
170 return formatDateTimeShort(hourStart, timeZone);
172​
173/**
174 * The window the page requests, expressed in the viewer's own time zone so days
175 * line up with what they actually experienced.
176 */
177export function makeWindow(
178 days: number,
179 now = new Date(),
180 resolution: UsageResolution = "day",
181): UsageSummaryInput {
182 let timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
183 let format: Intl.DateTimeFormat;
184 try {
185 format = new Intl.DateTimeFormat("en-CA", {
186 timeZone,
187 year: "numeric",
188 month: "2-digit",
189 day: "2-digit",
190 });
191 } catch {
192 // An unknown zone should degrade to UTC rather than crash the page.
193 timeZone = "UTC";
194 format = new Intl.DateTimeFormat("en-CA", {
195 timeZone: "UTC",
196 year: "numeric",
197 month: "2-digit",
198 day: "2-digit",
199 });
200 }
201 const untilDay = format.format(now);
202 if (resolution === "hour") {
203 // Minute-aligned bounds keep labels readable while still representing an
204 // exact rolling 24-hour duration. Fixed-duration buckets remain correct
205 // across offset changes and daylight-saving transitions.
206 const untilTimeMs = Math.floor(now.getTime() / 60_000) * 60_000;
207 const sinceTimeMs = untilTimeMs - 24 * HOUR_MS;
208 const sinceTime = new Date(sinceTimeMs);
209 const untilTime = new Date(untilTimeMs);
210 return {
211 sinceDay: UsageDay.make(format.format(sinceTime)),
212 untilDay: UsageDay.make(format.format(untilTime)),
213 timeZone,
214 resolution,
215 sinceTime: sinceTime.toISOString(),
216 untilTime: untilTime.toISOString(),
217 };
218 }
219 // Subtracting fixed milliseconds from `now` lands on the wrong calendar day
220 // around a DST transition. The window start is pure calendar arithmetic on
221 // the local end day, done in UTC where days are uniform.
222 const [year = 0, month = 1, dayOfMonth = 1] = untilDay
223 .split("-")
224 .map((part) => Number.parseInt(part, 10));
225 const start = new Date(Date.UTC(year, month - 1, dayOfMonth - (days - 1)));
226 return {
227 sinceDay: UsageDay.make(start.toISOString().slice(0, 10)),
228 untilDay: UsageDay.make(untilDay),
229 timeZone,
230 resolution,
231 };