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.
2import { UsageDay, type UsageResolution, type UsageSummaryInput } from "@t3tools/contracts";
3
4import type { UsageContractMismatch } from "./usageMerge.ts";
5
6const CURRENCY = new Intl.NumberFormat("en-US", {
7 style: "currency",
8 currency: "USD",
9 minimumFractionDigits: 2,
10 maximumFractionDigits: 2,
11});
12
13const INTEGER = new Intl.NumberFormat("en-US");
14
15export function formatUsd(value: number): string {
16 return CURRENCY.format(value);
17}
18
19export function formatCount(value: number): string {
20 return INTEGER.format(Math.round(value));
21}
22
23export function formatTokens(value: number): string {
24 const abs = Math.abs(value);
25 if (abs >= 1e12) return `${trim(value / 1e12)}T`;
26 if (abs >= 1e9) return `${trim(value / 1e9)}B`;
27 if (abs >= 1e6) return `${trim(value / 1e6)}M`;
28 if (abs >= 1e3) return `${trim(value / 1e3)}K`;
29 return INTEGER.format(Math.round(value));
30}
31
32function trim(value: number): string {
33 const abs = Math.abs(value);
34 const digits = abs >= 100 ? 0 : abs >= 10 ? 1 : 2;
35 return value.toFixed(digits).replace(/\.0+$/, "");
36}
37
38export function formatPercent(share: number, digits = 1): string {
39 const percent = share * 100;
40 const smallest = 10 ** -digits;
41 if (percent > 0 && percent < smallest) return `<${smallest.toFixed(digits)}%`;
42 return `${percent.toFixed(digits)}%`;
43}
44
45export function formatUsageContractMismatch(
46 environmentLabel: string,
47 mismatch: Pick<UsageContractMismatch, "direction">,
48): string {
49 return mismatch.direction === "serverBehind"
50 ? `${environmentLabel} runs an older server version and is excluded from totals.`
51 : `This client is older than the server on ${environmentLabel}; its usage is excluded from totals.`;
52}
53
54export function formatDayShort(day: string): string {
55 const [year, month, dayOfMonth] = day.split("-").map((part) => Number(part));
56 if (year === undefined || month === undefined || dayOfMonth === undefined) return day;
57 const MONTHS = [
58 "Jan",
59 "Feb",
60 "Mar",
61 "Apr",
62 "May",
63 "Jun",
64 "Jul",
65 "Aug",
66 "Sep",
67 "Oct",
68 "Nov",
69 "Dec",
70 ];
71 return `${MONTHS[month - 1] ?? ""} ${dayOfMonth}`;
72}
73
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
105export function enumerateHourStarts(sinceTime: string, untilTime: string): readonly string[] {
106 const starts: string[] = [];
107 const start = Date.parse(sinceTime);
108 const end = Date.parse(untilTime);
109 if (Number.isNaN(start) || Number.isNaN(end) || end <= start) return starts;
110
111 for (let cursor = start; cursor < end; cursor += HOUR_MS) {
112 starts.push(new Date(cursor).toISOString());
113 }
114 return starts;
115}
116
117/**
118 * Repeated wall-clock hours during a fall-back transition include their short zone name so the
119 * 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);
148}
149
150export function formatDateTimeShort(instant: string, timeZone?: string): string {
151 const date = new Date(instant);
152 if (Number.isNaN(date.getTime())) return instant;
153 return dateTimeFormatter("en-US", {
154 ...(timeZone === undefined ? {} : { timeZone }),
155 month: "short",
156 day: "numeric",
157 hour: "numeric",
158 }).format(date);
159}
160
161export function formatRelativeHourShort(
162 hourStart: string,
163 relativeTo: string,
164 timeZone?: string,
165): string {
166 const instant = new Date(hourStart);
167 const reference = new Date(relativeTo);
168 if (Number.isNaN(instant.getTime()) || Number.isNaN(reference.getTime())) {
169 return formatDateTimeShort(hourStart, timeZone);
170 }
171
172 const dayFormat = dateTimeFormatter("en-CA", {
173 ...(timeZone === undefined ? {} : { timeZone }),
174 year: "numeric",
175 month: "2-digit",
176 day: "2-digit",
177 });
178 const instantDay = Date.parse(`${dayFormat.format(instant)}T00:00:00Z`);
179 const referenceDay = Date.parse(`${dayFormat.format(reference)}T00:00:00Z`);
180 const calendarDaysAgo = Math.round((referenceDay - instantDay) / (24 * HOUR_MS));
181 const hour = formatHourShort(hourStart, timeZone);
182
183 if (calendarDaysAgo === 0) return `${hour} today`;
184 if (calendarDaysAgo === 1) return `${hour} yesterday`;
185 return formatDateTimeShort(hourStart, timeZone);
186}
187
188export function makeWindow(
189 days: number,
190 now = new Date(),
191 resolution: UsageResolution = "day",
192): UsageSummaryInput {
193 let timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
194 let format: Intl.DateTimeFormat;
195 try {
196 format = new Intl.DateTimeFormat("en-CA", {
197 timeZone,
198 year: "numeric",
199 month: "2-digit",
200 day: "2-digit",
201 });
202 } catch {
203 timeZone = "UTC";
204 format = new Intl.DateTimeFormat("en-CA", {
205 timeZone: "UTC",
206 year: "numeric",
207 month: "2-digit",
208 day: "2-digit",
209 });
210 }
211 const untilDay = format.format(now);
212 if (resolution === "hour") {
213 const untilTimeMs = Math.floor(now.getTime() / 60_000) * 60_000;
214 const sinceTimeMs = untilTimeMs - 24 * HOUR_MS;
215 const sinceTime = new Date(sinceTimeMs);
216 const untilTime = new Date(untilTimeMs);
217 return {
218 sinceDay: UsageDay.make(format.format(sinceTime)),
219 untilDay: UsageDay.make(format.format(untilTime)),
220 timeZone,
221 resolution,
222 sinceTime: sinceTime.toISOString(),
223 untilTime: untilTime.toISOString(),
224 };
225 }
226 // Subtracting fixed milliseconds from `now` lands on the wrong calendar day
227 // around a DST transition. The window start is pure calendar arithmetic on
228 // the local end day, done in UTC where days are uniform.
229 const [year = 0, month = 1, dayOfMonth = 1] = untilDay
230 .split("-")
231 .map((part) => Number.parseInt(part, 10));
232 const start = new Date(Date.UTC(year, month - 1, dayOfMonth - (days - 1)));
233 return {
234 sinceDay: UsageDay.make(start.toISOString().slice(0, 10)),
235 untilDay: UsageDay.make(untilDay),
236 timeZone,
237 resolution,
238 };
239}