The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // @effect-diagnostics globalDate:off -- Usage windows are calendar days in the viewer's zone, derived from wall-clock "now" via Intl. |
| 2 | import { |
| 3 | UsageDay, |
| 4 | type UsageResolution, |
| 5 | type UsageSource, |
| 6 | type UsageSummaryInput, |
| 7 | } from "@t3tools/contracts"; |
| 8 | |
| 9 | const CURRENCY = new Intl.NumberFormat("en-US", { |
| 10 | style: "currency", |
| 11 | currency: "USD", |
| 12 | minimumFractionDigits: 2, |
| 13 | maximumFractionDigits: 2, |
| 14 | }); |
| 15 | |
| 16 | const INTEGER = new Intl.NumberFormat("en-US"); |
| 17 | |
| 18 | // Clients pass their UI locale; English (and the server, which passes none) keeps en-US. |
| 19 | function formatLocale(locale: string | undefined): string { |
| 20 | return locale === undefined || locale === "en" ? "en-US" : locale; |
| 21 | } |
| 22 | |
| 23 | const numberFormatters = new Map<string, Intl.NumberFormat>(); |
| 24 | |
| 25 | function numberFormatter(locale: string, currency: boolean): Intl.NumberFormat { |
| 26 | if (locale === "en-US") return currency ? CURRENCY : INTEGER; |
| 27 | const key = `${locale}:${currency}`; |
| 28 | let formatter = numberFormatters.get(key); |
| 29 | if (formatter === undefined) { |
| 30 | formatter = currency |
| 31 | ? new Intl.NumberFormat(locale, { |
| 32 | style: "currency", |
| 33 | currency: "USD", |
| 34 | minimumFractionDigits: 2, |
| 35 | maximumFractionDigits: 2, |
| 36 | }) |
| 37 | : new Intl.NumberFormat(locale); |
| 38 | numberFormatters.set(key, formatter); |
| 39 | } |
| 40 | return formatter; |
| 41 | } |
| 42 | |
| 43 | export function formatMalformedUsageWarning(count: number): string { |
| 44 | return `${count} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`; |
| 45 | } |
| 46 | |
| 47 | export function usageSourceMessages( |
| 48 | sources: readonly UsageSource[], |
| 49 | malformedWarning: (count: number) => string = formatMalformedUsageWarning, |
| 50 | ): readonly string[] { |
| 51 | const messages = new Set<string>(); |
| 52 | const malformedBySource = new Map<string, number>(); |
| 53 | for (const source of sources) { |
| 54 | if ( |
| 55 | source.status !== "partial" && |
| 56 | source.status !== "failed" && |
| 57 | source.fingerprint.provider !== "cursor" && |
| 58 | !(source.status === "missing" && source.malformedRecords > 0) |
| 59 | ) { |
| 60 | continue; |
| 61 | } |
| 62 | let message = source.message; |
| 63 | if (source.malformedRecords > 0) { |
| 64 | const { hostId, provider, resolvedHomePath, volumeId } = source.fingerprint; |
| 65 | const key = JSON.stringify([hostId, provider, resolvedHomePath, volumeId]); |
| 66 | malformedBySource.set( |
| 67 | key, |
| 68 | Math.max(malformedBySource.get(key) ?? 0, source.malformedRecords), |
| 69 | ); |
| 70 | // Servers also append this warning to message; retain any preceding read failure. |
| 71 | const warning = formatMalformedUsageWarning(source.malformedRecords); |
| 72 | if (message?.endsWith(warning)) message = message.slice(0, -warning.length).trim(); |
| 73 | } |
| 74 | if (message) messages.add(message); |
| 75 | } |
| 76 | const malformedRecords = [...malformedBySource.values()].reduce( |
| 77 | (total, count) => total + count, |
| 78 | 0, |
| 79 | ); |
| 80 | if (malformedRecords > 0) messages.add(malformedWarning(malformedRecords)); |
| 81 | return [...messages]; |
| 82 | } |
| 83 | |
| 84 | export function formatUsd(value: number, locale?: string): string { |
| 85 | return numberFormatter(formatLocale(locale), true).format(value); |
| 86 | } |
| 87 | |
| 88 | export function formatCount(value: number, locale?: string): string { |
| 89 | return numberFormatter(formatLocale(locale), false).format(Math.round(value)); |
| 90 | } |
| 91 | |
| 92 | const TOKEN_SUFFIXES = ["K", "M", "B", "T"] as const; |
| 93 | |
| 94 | export function formatTokens(value: number): string { |
| 95 | if (Math.abs(Math.round(value)) < 1e3) return INTEGER.format(Math.round(value)); |
| 96 | let scaled = value / 1e3; |
| 97 | let unit = 0; |
| 98 | // Choose the unit after rounding, so 999,999 reads 1M rather than 1000K. |
| 99 | while (Math.abs(Number(trim(scaled))) >= 1e3 && unit < TOKEN_SUFFIXES.length - 1) { |
| 100 | scaled /= 1e3; |
| 101 | unit += 1; |
| 102 | } |
| 103 | return `${trim(scaled)}${TOKEN_SUFFIXES[unit]}`; |
| 104 | } |
| 105 | |
| 106 | function trim(value: number): string { |
| 107 | const abs = Math.abs(value); |
| 108 | const digits = abs >= 100 ? 0 : abs >= 10 ? 1 : 2; |
| 109 | return value.toFixed(digits).replace(/\.0+$/, ""); |
| 110 | } |
| 111 | |
| 112 | export function formatPercent(share: number, digits = 1): string { |
| 113 | const percent = share * 100; |
| 114 | const smallest = 10 ** -digits; |
| 115 | if (percent > 0 && percent < smallest) return `<${smallest.toFixed(digits)}%`; |
| 116 | return `${percent.toFixed(digits)}%`; |
| 117 | } |
| 118 | |
| 119 | export function formatDayShort(day: string, locale?: string): string { |
| 120 | const [year, month, dayOfMonth] = day.split("-").map((part) => Number(part)); |
| 121 | if (year === undefined || month === undefined || dayOfMonth === undefined) return day; |
| 122 | const intlLocale = formatLocale(locale); |
| 123 | if (intlLocale !== "en-US") { |
| 124 | const date = new Date(Date.UTC(year, month - 1, dayOfMonth)); |
| 125 | return Number.isNaN(date.getTime()) |
| 126 | ? day |
| 127 | : dateTimeFormatter(intlLocale, { timeZone: "UTC", month: "short", day: "numeric" }).format( |
| 128 | date, |
| 129 | ); |
| 130 | } |
| 131 | const MONTHS = [ |
| 132 | "Jan", |
| 133 | "Feb", |
| 134 | "Mar", |
| 135 | "Apr", |
| 136 | "May", |
| 137 | "Jun", |
| 138 | "Jul", |
| 139 | "Aug", |
| 140 | "Sep", |
| 141 | "Oct", |
| 142 | "Nov", |
| 143 | "Dec", |
| 144 | ]; |
| 145 | return `${MONTHS[month - 1] ?? ""} ${dayOfMonth}`; |
| 146 | } |
| 147 | |
| 148 | export function enumerateDays(sinceDay: string, untilDay: string): readonly string[] { |
| 149 | const days: string[] = []; |
| 150 | const start = Date.parse(`${sinceDay}T00:00:00Z`); |
| 151 | const end = Date.parse(`${untilDay}T00:00:00Z`); |
| 152 | if (Number.isNaN(start) || Number.isNaN(end) || end < start) return days; |
| 153 | |
| 154 | for (let cursor = start; cursor <= end; cursor += 86_400_000) { |
| 155 | days.push(new Date(cursor).toISOString().slice(0, 10)); |
| 156 | } |
| 157 | return days; |
| 158 | } |
| 159 | |
| 160 | const HOUR_MS = 60 * 60 * 1000; |
| 161 | |
| 162 | const dateTimeFormatters = new Map<string, Intl.DateTimeFormat>(); |
| 163 | |
| 164 | function dateTimeFormatter( |
| 165 | locale: string, |
| 166 | options: Intl.DateTimeFormatOptions, |
| 167 | ): Intl.DateTimeFormat { |
| 168 | if (options.timeZone === undefined) return new Intl.DateTimeFormat(locale, options); |
| 169 | const key = JSON.stringify([locale, options]); |
| 170 | let formatter = dateTimeFormatters.get(key); |
| 171 | if (formatter === undefined) { |
| 172 | formatter = new Intl.DateTimeFormat(locale, options); |
| 173 | if (dateTimeFormatters.size >= 16) dateTimeFormatters.clear(); |
| 174 | dateTimeFormatters.set(key, formatter); |
| 175 | } |
| 176 | return formatter; |
| 177 | } |
| 178 | |
| 179 | export function enumerateHourStarts(sinceTime: string, untilTime: string): readonly string[] { |
| 180 | const starts: string[] = []; |
| 181 | const start = Date.parse(sinceTime); |
| 182 | const end = Date.parse(untilTime); |
| 183 | if (Number.isNaN(start) || Number.isNaN(end) || end <= start) return starts; |
| 184 | |
| 185 | for (let cursor = start; cursor < end; cursor += HOUR_MS) { |
| 186 | starts.push(new Date(cursor).toISOString()); |
| 187 | } |
| 188 | return starts; |
| 189 | } |
| 190 | |
| 191 | function hourOptions(hour12: boolean): Intl.DateTimeFormatOptions { |
| 192 | return hour12 ? { hour: "numeric" } : { hour: "2-digit", hourCycle: "h23" }; |
| 193 | } |
| 194 | |
| 195 | function formatHour(formatter: Intl.DateTimeFormat, date: Date, hour12: boolean): string { |
| 196 | if (hour12) return formatter.format(date); |
| 197 | // Rolling buckets can start between whole hours, but their labels always name the hour. |
| 198 | return formatter |
| 199 | .formatToParts(date) |
| 200 | .map((part) => (part.type === "hour" ? `${part.value}:00` : part.value)) |
| 201 | .join(""); |
| 202 | } |
| 203 | |
| 204 | /** |
| 205 | * Repeated wall-clock hours during a fall-back transition include their short zone name so the |
| 206 | * two distinct buckets remain distinguishable. |
| 207 | */ |
| 208 | export function formatHourShort( |
| 209 | hourStart: string, |
| 210 | timeZone?: string, |
| 211 | hour12 = true, |
| 212 | locale?: string, |
| 213 | ): string { |
| 214 | const instant = new Date(hourStart); |
| 215 | if (Number.isNaN(instant.getTime())) return hourStart; |
| 216 | const options = timeZone === undefined ? {} : { timeZone }; |
| 217 | const intlLocale = formatLocale(locale); |
| 218 | const hourFormat = dateTimeFormatter(intlLocale, { |
| 219 | ...options, |
| 220 | ...hourOptions(hour12), |
| 221 | }); |
| 222 | const wallHourFormat = dateTimeFormatter("en-CA", { |
| 223 | ...options, |
| 224 | year: "numeric", |
| 225 | month: "2-digit", |
| 226 | day: "2-digit", |
| 227 | hour: "2-digit", |
| 228 | hourCycle: "h23", |
| 229 | }); |
| 230 | const wallHour = wallHourFormat.format(instant); |
| 231 | const isRepeatedHour = [-HOUR_MS, HOUR_MS].some( |
| 232 | (offset) => wallHourFormat.format(new Date(instant.getTime() + offset)) === wallHour, |
| 233 | ); |
| 234 | |
| 235 | if (!isRepeatedHour) return formatHour(hourFormat, instant, hour12); |
| 236 | const zonedHourFormat = dateTimeFormatter(intlLocale, { |
| 237 | ...options, |
| 238 | ...hourOptions(hour12), |
| 239 | timeZoneName: "short", |
| 240 | }); |
| 241 | return formatHour(zonedHourFormat, instant, hour12); |
| 242 | } |
| 243 | |
| 244 | export function formatDateTimeShort( |
| 245 | instant: string, |
| 246 | timeZone?: string, |
| 247 | hour12 = true, |
| 248 | locale?: string, |
| 249 | ): string { |
| 250 | const date = new Date(instant); |
| 251 | if (Number.isNaN(date.getTime())) return instant; |
| 252 | const dateHourFormat = dateTimeFormatter(formatLocale(locale), { |
| 253 | ...(timeZone === undefined ? {} : { timeZone }), |
| 254 | month: "short", |
| 255 | day: "numeric", |
| 256 | ...hourOptions(hour12), |
| 257 | }); |
| 258 | return formatHour(dateHourFormat, date, hour12); |
| 259 | } |
| 260 | |
| 261 | export function formatRelativeHourShort( |
| 262 | hourStart: string, |
| 263 | relativeTo: string, |
| 264 | timeZone?: string, |
| 265 | hour12 = true, |
| 266 | relativeDay: (hour: string, daysAgo: 0 | 1) => string = (hour, daysAgo) => |
| 267 | daysAgo === 0 ? `${hour} today` : `${hour} yesterday`, |
| 268 | locale?: string, |
| 269 | ): string { |
| 270 | const instant = new Date(hourStart); |
| 271 | const reference = new Date(relativeTo); |
| 272 | if (Number.isNaN(instant.getTime()) || Number.isNaN(reference.getTime())) { |
| 273 | return formatDateTimeShort(hourStart, timeZone, hour12, locale); |
| 274 | } |
| 275 | |
| 276 | const dayFormat = dateTimeFormatter("en-CA", { |
| 277 | ...(timeZone === undefined ? {} : { timeZone }), |
| 278 | year: "numeric", |
| 279 | month: "2-digit", |
| 280 | day: "2-digit", |
| 281 | }); |
| 282 | const instantDay = Date.parse(`${dayFormat.format(instant)}T00:00:00Z`); |
| 283 | const referenceDay = Date.parse(`${dayFormat.format(reference)}T00:00:00Z`); |
| 284 | const calendarDaysAgo = Math.round((referenceDay - instantDay) / (24 * HOUR_MS)); |
| 285 | const hour = formatHourShort(hourStart, timeZone, hour12, locale); |
| 286 | |
| 287 | if (calendarDaysAgo === 0 || calendarDaysAgo === 1) return relativeDay(hour, calendarDaysAgo); |
| 288 | return formatDateTimeShort(hourStart, timeZone, hour12, locale); |
| 289 | } |
| 290 | |
| 291 | export function makeWindow( |
| 292 | days: number, |
| 293 | now = new Date(), |
| 294 | resolution: UsageResolution = "day", |
| 295 | ): UsageSummaryInput { |
| 296 | let timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; |
| 297 | let format: Intl.DateTimeFormat; |
| 298 | try { |
| 299 | format = new Intl.DateTimeFormat("en-CA", { |
| 300 | timeZone, |
| 301 | year: "numeric", |
| 302 | month: "2-digit", |
| 303 | day: "2-digit", |
| 304 | }); |
| 305 | } catch { |
| 306 | timeZone = "UTC"; |
| 307 | format = new Intl.DateTimeFormat("en-CA", { |
| 308 | timeZone: "UTC", |
| 309 | year: "numeric", |
| 310 | month: "2-digit", |
| 311 | day: "2-digit", |
| 312 | }); |
| 313 | } |
| 314 | const untilDay = format.format(now); |
| 315 | if (resolution === "hour") { |
| 316 | const untilTimeMs = Math.floor(now.getTime() / 60_000) * 60_000; |
| 317 | const sinceTimeMs = untilTimeMs - 24 * HOUR_MS; |
| 318 | const sinceTime = new Date(sinceTimeMs); |
| 319 | const untilTime = new Date(untilTimeMs); |
| 320 | return { |
| 321 | sinceDay: UsageDay.make(format.format(sinceTime)), |
| 322 | untilDay: UsageDay.make(format.format(untilTime)), |
| 323 | timeZone, |
| 324 | resolution, |
| 325 | sinceTime: sinceTime.toISOString(), |
| 326 | untilTime: untilTime.toISOString(), |
| 327 | }; |
| 328 | } |
| 329 | // Use calendar arithmetic in UTC; fixed millisecond subtraction crosses DST days incorrectly. |
| 330 | const [year = 0, month = 1, dayOfMonth = 1] = untilDay |
| 331 | .split("-") |
| 332 | .map((part) => Number.parseInt(part, 10)); |
| 333 | const start = new Date(Date.UTC(year, month - 1, dayOfMonth - (days - 1))); |
| 334 | return { |
| 335 | sinceDay: UsageDay.make(start.toISOString().slice(0, 10)), |
| 336 | untilDay: UsageDay.make(untilDay), |
| 337 | timeZone, |
| 338 | resolution, |
| 339 | }; |
| 340 | } |