Open History to see the last commit
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);
20}
21
22export function formatCount(value: number): string {
23 return INTEGER.format(Math.round(value));
24}
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));
37}
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+$/, "");
43}
44
45export function formatPercent(share: number, digits = 1): string {
46 const percent = share * 100;
47 const smallest = 10 ** -digits;
48 if (percent > 0 && percent < smallest) return `<${smallest.toFixed(digits)}%`;
49 return `${percent.toFixed(digits)}%`;
50}
51
52/** `2026-08-07` to `Aug 7`. */
53export function formatDayShort(day: string): string {
54 const [year, month, dayOfMonth] = day.split("-").map((part) => Number(part));
55 if (year === undefined || month === undefined || dayOfMonth === undefined) return day;
56 const MONTHS = [
57 "Jan",
58 "Feb",
59 "Mar",
60 "Apr",
61 "May",
62 "Jun",
63 "Jul",
64 "Aug",
65 "Sep",
66 "Oct",
67 "Nov",
68 "Dec",
69 ];
70 return `${MONTHS[month - 1] ?? ""} ${dayOfMonth}`;
71}
72
73/** Inclusive day list between two `YYYY-MM-DD` bounds. */
74export function enumerateDays(sinceDay: string, untilDay: string): readonly string[] {
75 const days: string[] = [];
76 const start = Date.parse(`${sinceDay}T00:00:00Z`);
77 const end = Date.parse(`${untilDay}T00:00:00Z`);
78 if (Number.isNaN(start) || Number.isNaN(end) || end < start) return days;
79
80 for (let cursor = start; cursor <= end; cursor += 86_400_000) {
81 days.push(new Date(cursor).toISOString().slice(0, 10));
82 }
83 return days;
84}
85
86const HOUR_MS = 60 * 60 * 1000;
87
88const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>();
89
90function dateTimeFormatter(
91 locale: string,
92 options: Intl.DateTimeFormatOptions,
93): Intl.DateTimeFormat {
94 if (options.timeZone === undefined) return new Intl.DateTimeFormat(locale, options);
95 const key = JSON.stringify([locale, options]);
96 let formatter = dateTimeFormatters.get(key);
97 if (formatter === undefined) {
98 formatter = new Intl.DateTimeFormat(locale, options);
99 if (dateTimeFormatters.size >= 16) dateTimeFormatters.clear();
100 dateTimeFormatters.set(key, formatter);
101 }
102 return formatter;
103}
104
105/** Every fixed-duration bucket start in an hourly rolling window. */
106export function enumerateHourStarts(sinceTime: string, untilTime: string): readonly string[] {
107 const starts: string[] = [];
108 const start = Date.parse(sinceTime);
109 const end = Date.parse(untilTime);
110 if (Number.isNaN(start) || Number.isNaN(end) || end <= start) return starts;
111
112 for (let cursor = start; cursor < end; cursor += HOUR_MS) {
113 starts.push(new Date(cursor).toISOString());
114 }
115 return starts;
116}
117
118/**
119 * A rolling bucket start rendered in the viewer's requested time zone.
120 *
121 * Repeated wall-clock hours during a fall-back transition include their short
122 * zone name so the two distinct buckets remain distinguishable.
123 */
124export function formatHourShort(hourStart: string, timeZone?: string): string {
125 const instant = new Date(hourStart);
126 if (Number.isNaN(instant.getTime())) return hourStart;
127 const options = timeZone === undefined ? {} : { timeZone };
128 const hourFormat = dateTimeFormatter("en-US", {
129 ...options,
130 hour: "numeric",
131 });
132 const wallHourFormat = dateTimeFormatter("en-CA", {
133 ...options,
134 year: "numeric",
135 month: "2-digit",
136 day: "2-digit",
137 hour: "2-digit",
138 hourCycle: "h23",
139 });
140 const wallHour = wallHourFormat.format(instant);
141 const isRepeatedHour = [-HOUR_MS, HOUR_MS].some(
142 (offset) => wallHourFormat.format(new Date(instant.getTime() + offset)) === wallHour,
143 );
144
145 if (!isRepeatedHour) return hourFormat.format(instant);
146 return dateTimeFormatter("en-US", {
147 ...(timeZone === undefined ? {} : { timeZone }),
148 hour: "numeric",
149 timeZoneName: "short",
150 }).format(instant);
151}
152
153/** `2026-08-11T14:37:00Z` to `Aug 11, 2 PM` in the requested zone. */
154export function formatDateTimeShort(instant: string, timeZone?: string): string {
155 const date = new Date(instant);
156 if (Number.isNaN(date.getTime())) return instant;
157 return dateTimeFormatter("en-US", {
158 ...(timeZone === undefined ? {} : { timeZone }),
159 month: "short",
160 day: "numeric",
161 hour: "numeric",
162 }).format(date);
163}
164
165/** An hourly tooltip label relative to the rolling window's end date. */
166export function formatRelativeHourShort(
167 hourStart: string,
168 relativeTo: string,
169 timeZone?: string,
170): string {
171 const instant = new Date(hourStart);
172 const reference = new Date(relativeTo);
173 if (Number.isNaN(instant.getTime()) || Number.isNaN(reference.getTime())) {
174 return formatDateTimeShort(hourStart, timeZone);
175 }
176
177 const dayFormat = dateTimeFormatter("en-CA", {
178 ...(timeZone === undefined ? {} : { timeZone }),
179 year: "numeric",
180 month: "2-digit",
181 day: "2-digit",
182 });
183 const instantDay = Date.parse(`${dayFormat.format(instant)}T00:00:00Z`);
184 const referenceDay = Date.parse(`${dayFormat.format(reference)}T00:00:00Z`);
185 const calendarDaysAgo = Math.round((referenceDay - instantDay) / (24 * HOUR_MS));
186 const hour = formatHourShort(hourStart, timeZone);
187
188 if (calendarDaysAgo === 0) return `${hour} today`;
189 if (calendarDaysAgo === 1) return `${hour} yesterday`;
190 return formatDateTimeShort(hourStart, timeZone);
191}
192
193/**
194 * The window the page requests, expressed in the viewer's own time zone so days
195 * line up with what they actually experienced.
196 */
197export function makeWindow(
198 days: number,
199 now = new Date(),
200 resolution: UsageResolution = "day",
201): UsageSummaryInput {
202 let timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
203 let format: Intl.DateTimeFormat;
204 try {
205 format = new Intl.DateTimeFormat("en-CA", {
206 timeZone,
207 year: "numeric",
208 month: "2-digit",
209 day: "2-digit",
210 });
211 } catch {
212 // An unknown zone should degrade to UTC rather than crash the page.
213 timeZone = "UTC";
214 format = new Intl.DateTimeFormat("en-CA", {
215 timeZone: "UTC",
216 year: "numeric",
217 month: "2-digit",
218 day: "2-digit",
219 });
220 }
221 const untilDay = format.format(now);
222 if (resolution === "hour") {
223 // Minute-aligned bounds keep labels readable while still representing an
224 // exact rolling 24-hour duration. Fixed-duration buckets remain correct
225 // across offset changes and daylight-saving transitions.
226 const untilTimeMs = Math.floor(now.getTime() / 60_000) * 60_000;
227 const sinceTimeMs = untilTimeMs - 24 * HOUR_MS;
228 const sinceTime = new Date(sinceTimeMs);
229 const untilTime = new Date(untilTimeMs);
230 return {
231 sinceDay: UsageDay.make(format.format(sinceTime)),
232 untilDay: UsageDay.make(format.format(untilTime)),
233 timeZone,
234 resolution,
235 sinceTime: sinceTime.toISOString(),
236 untilTime: untilTime.toISOString(),
237 };
238 }
239 // Subtracting fixed milliseconds from `now` lands on the wrong calendar day
240 // around a DST transition. The window start is pure calendar arithmetic on
241 // the local end day, done in UTC where days are uniform.
242 const [year = 0, month = 1, dayOfMonth = 1] = untilDay
243 .split("-")
244 .map((part) => Number.parseInt(part, 10));
245 const start = new Date(Date.UTC(year, month - 1, dayOfMonth - (days - 1)));
246 return {
247 sinceDay: UsageDay.make(start.toISOString().slice(0, 10)),
248 untilDay: UsageDay.make(untilDay),
249 timeZone,
250 resolution,
251 };
252}