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

usageFormat.ts

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