<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Usage - blyte</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<style>
@font-face {
font-family: "Archivo";
src: url("/fonts/archivo.woff2") format("woff2");
font-weight: 400 900;
font-stretch: 62% 125%;
font-display: swap;
}
@font-face {
font-family: "IBM Plex Mono";
src: url("/fonts/plex-mono-400.woff2") format("woff2");
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "IBM Plex Mono";
src: url("/fonts/plex-mono-500.woff2") format("woff2");
font-weight: 500;
font-style: normal;
font-display: swap;
}
:root {
--color-page: #ECEFF0;
--color-card: #F4F6F7;
--color-line: #C9D0D4;
--color-line-dark: #B3BCC1;
--color-text: #2A3238;
--color-strong: #141A1E;
--color-muted: #56616A;
--status-running: #A6441A;
--status-amber: #8A6A12;
--status-red: #A93A36;
--focus-ring: #A6441A;
--brand-rust: #A6441A;
--brand-rust-soft: #E8C8B7;
--font-sans: "Archivo", "Helvetica Neue", Helvetica, Arial, sans-serif;
--font-mono: "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace;
--pass: #2E7A4D;
--pass-soft: #CFE3D6;
--fail: #A93A36;
--fail-soft: #F0D3D1;
--amber: #8A6A12;
--amber-soft: #EFE3BF;
--merged: #3E6D64;
--merged-soft: #C3D6D1;
--research: #3B6EA5;
--research-soft: #D6E4F0;
--lane: #E6EAEC;
}
@media (prefers-color-scheme: dark) {
:root {
--color-page: #0F1315;
--color-card: #171D20;
--color-line: #283136;
--color-line-dark: #36414A;
--color-text: #C9D1D5;
--color-strong: #E2E7E9;
--color-muted: #93A0A7;
--status-running: #E27A44;
--status-amber: #D9B45A;
--status-red: #E27B76;
--focus-ring: #E27A44;
--brand-rust: #E27A44;
--brand-rust-soft: #4A2B1D;
--pass: #6CC08E;
--pass-soft: #1E3428;
--fail: #E27B76;
--fail-soft: #3A2120;
--amber: #D9B45A;
--amber-soft: #3A3218;
--merged: #7FB2A6;
--merged-soft: #1F3431;
--research: #6FA3D8;
--research-soft: #1E2E3E;
--lane: #131A1D;
}
}
*, *::before, *::after {
box-sizing: border-box;
}
html, body {
min-height: 100%;
margin: 0;
padding: 0;
background-color: var(--color-page);
color: var(--color-text);
font-family: var(--font-sans);
font-size: 14px;
line-height: 1.45;
-webkit-font-smoothing: antialiased;
}
[hidden] {
display: none !important;
}
button, a {
font-family: inherit;
font-size: inherit;
color: inherit;
}
button:focus-visible, a:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: 2px;
}
.mono {
font-family: var(--font-mono);
}
.nums {
font-variant-numeric: tabular-nums;
}
#bar {
background: var(--color-card);
border-bottom: 1px solid var(--color-line);
padding: 10px 16px;
position: sticky;
top: 0;
z-index: 10;
}
.bar-inner {
max-width: 1120px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.bar-group {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.brand {
display: inline-flex;
align-items: center;
gap: 8px;
}
.m-i { fill: var(--color-strong); }
.m-s { fill: var(--brand-rust-soft); }
.m-r { fill: var(--brand-rust); }
#usage-back {
padding: 5px 10px;
border-radius: 4px;
border: 1px solid var(--color-line-dark);
background: var(--color-page);
color: var(--color-strong);
font-size: 12px;
font-weight: 500;
text-decoration: none;
display: inline-flex;
align-items: center;
line-height: 1.3;
}
#usage-back:hover {
border-color: var(--brand-rust);
}
.usage-heading {
margin: 0;
font-size: 17px;
font-weight: 700;
color: var(--color-strong);
letter-spacing: -0.01em;
line-height: 1.2;
}
#usage-range {
display: inline-flex;
align-items: center;
gap: 4px;
}
.range-btn {
font-family: var(--font-mono);
font-size: 12px;
padding: 5px 10px;
border: 1px solid var(--color-line-dark);
border-radius: 4px;
color: var(--color-muted);
background: transparent;
cursor: pointer;
}
.range-btn:hover {
border-color: var(--brand-rust);
color: var(--color-strong);
}
.range-btn[aria-pressed="true"] {
background: var(--brand-rust-soft);
border-color: var(--brand-rust);
color: var(--color-strong);
font-weight: 500;
}
.usage-main {
max-width: 1120px;
margin: 0 auto;
padding: 20px 16px 40px;
display: flex;
flex-direction: column;
gap: 18px;
}
#usage-status {
padding: 10px 14px;
border-radius: 6px;
background: var(--fail-soft);
border: 1px solid var(--status-red);
color: var(--status-red);
font-family: var(--font-mono);
font-size: 12.5px;
word-break: break-word;
}
#usage-totals {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
}
@media (max-width: 760px) {
#usage-totals {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 440px) {
#usage-totals {
grid-template-columns: minmax(0, 1fr);
}
}
.total-card {
background: var(--color-card);
border: 1px solid var(--color-line);
border-radius: 6px;
padding: 14px 16px;
display: flex;
flex-direction: column;
gap: 6px;
}
.total-label {
font-family: var(--font-mono);
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--color-muted);
}
.total-value-row {
display: flex;
align-items: baseline;
gap: 8px;
flex-wrap: wrap;
}
.total-value {
font-family: var(--font-mono);
font-size: 20px;
font-weight: 600;
color: var(--color-strong);
line-height: 1.2;
}
.total-sub {
font-family: var(--font-mono);
font-size: 12px;
color: var(--color-muted);
}
#usage-notes {
margin: 0;
padding: 10px 14px;
list-style: none;
border-radius: 6px;
background: var(--amber-soft);
border: 1px solid var(--amber);
color: var(--color-strong);
font-family: var(--font-mono);
font-size: 12px;
display: flex;
flex-direction: column;
gap: 4px;
}
.section-card {
background: var(--color-card);
border: 1px solid var(--color-line);
border-radius: 6px;
padding: 14px 16px;
display: flex;
flex-direction: column;
gap: 12px;
}
.section-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
flex-wrap: wrap;
}
.section-title {
margin: 0;
font-size: 13px;
font-weight: 600;
color: var(--color-strong);
}
.section-caption {
font-family: var(--font-mono);
font-size: 11px;
color: var(--color-muted);
}
.days-chart {
height: 136px;
display: flex;
align-items: flex-end;
gap: 4px;
padding: 8px 4px 0;
border-bottom: 1px solid var(--color-line);
overflow-x: auto;
}
.days-bar-slot {
flex: 1 1 12px;
min-width: 8px;
max-width: 44px;
height: 120px;
display: flex;
align-items: flex-end;
}
.days-bar {
width: 100%;
background: var(--brand-rust);
border-radius: 2px 2px 0 0;
transition: filter 0.12s ease;
}
.days-bar:hover {
filter: brightness(1.12);
}
.days-axis {
display: flex;
justify-content: space-between;
font-family: var(--font-mono);
font-size: 11px;
color: var(--color-muted);
min-height: 16px;
}
.days-empty {
font-family: var(--font-mono);
font-size: 12px;
color: var(--color-muted);
padding: 8px 0;
}
.tables-stack {
display: flex;
flex-direction: column;
gap: 16px;
}
.table-wrap {
overflow-x: auto;
}
table.usage-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
table.usage-table th {
text-align: left;
font-family: var(--font-mono);
font-size: 11px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--color-muted);
padding: 6px 8px;
border-bottom: 1px solid var(--color-line-dark);
white-space: nowrap;
}
table.usage-table td {
padding: 7px 8px;
border-bottom: 1px solid var(--color-line);
color: var(--color-text);
vertical-align: top;
}
table.usage-table tbody tr:last-child td {
border-bottom: none;
}
table.usage-table th.num,
table.usage-table td.num {
text-align: right;
font-family: var(--font-mono);
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
table.usage-table td.name-cell {
font-family: var(--font-mono);
color: var(--color-strong);
word-break: break-word;
}
table.usage-table td.muted-cell {
font-family: var(--font-mono);
font-size: 12px;
color: var(--color-muted);
white-space: nowrap;
}
table.usage-table td.empty-cell {
font-family: var(--font-mono);
font-size: 12px;
color: var(--color-muted);
padding: 12px 8px;
}
</style>
</head>
<body>
<header id="bar">
<div class="bar-inner">
<div class="bar-group">
<span class="brand" aria-hidden="true">
<svg viewBox="0 0 100 100" width="20" height="20">
<rect class="m-i" x="10" y="10" width="24" height="24" rx="3"/>
<rect class="m-i" x="38" y="10" width="24" height="24" rx="3"/>
<rect class="m-i" x="66" y="10" width="24" height="24" rx="3"/>
<rect class="m-i" x="10" y="38" width="24" height="24" rx="3"/>
<rect class="m-s" x="38" y="38" width="24" height="24" rx="3"/>
<rect class="m-r" x="66" y="38" width="24" height="24" rx="3"/>
<rect class="m-i" x="10" y="66" width="24" height="24" rx="3"/>
<rect class="m-r" x="38" y="66" width="24" height="24" rx="3"/>
<rect class="m-r" x="66" y="66" width="24" height="24" rx="3"/>
</svg>
</span>
<a id="usage-back" href="/">Back to the surface</a>
<h1 class="usage-heading">Usage</h1>
</div>
<div id="usage-range" role="group" aria-label="Time range">
<button type="button" class="range-btn" data-range="7d" aria-pressed="false">7 days</button>
<button type="button" class="range-btn" data-range="30d" aria-pressed="true">30 days</button>
<button type="button" class="range-btn" data-range="all" aria-pressed="false">All time</button>
</div>
</div>
</header>
<main class="usage-main">
<div id="usage-status" role="alert" hidden></div>
<section id="usage-totals" aria-label="Totals"></section>
<ul id="usage-notes" hidden></ul>
<section id="usage-days" class="section-card" aria-label="Daily usage">
<div class="section-head">
<h2 class="section-title">Daily cost</h2>
<span class="section-caption">Days are UTC days</span>
</div>
<div id="usage-days-bars" class="days-chart"></div>
<div id="usage-days-axis" class="days-axis"></div>
</section>
<div class="tables-stack">
<section class="section-card" aria-label="Usage by surface">
<div class="section-head">
<h2 class="section-title">By surface</h2>
</div>
<div class="table-wrap">
<table id="usage-by-surface" class="usage-table">
<thead>
<tr>
<th>Surface</th>
<th class="num">Cost</th>
<th class="num">Runs</th>
<th class="num">Lines</th>
<th class="num">Last used</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</section>
<section class="section-card" aria-label="Usage by kind">
<div class="section-head">
<h2 class="section-title">By kind</h2>
</div>
<div class="table-wrap">
<table id="usage-by-kind" class="usage-table">
<thead>
<tr>
<th>Name</th>
<th class="num">Cost</th>
<th class="num">Runs</th>
<th class="num">Lines</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</section>
<section class="section-card" aria-label="Usage by repository">
<div class="section-head">
<h2 class="section-title">By repository</h2>
</div>
<div class="table-wrap">
<table id="usage-by-repo" class="usage-table">
<thead>
<tr>
<th>Name</th>
<th class="num">Cost</th>
<th class="num">Runs</th>
<th class="num">Lines</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</section>
<section class="section-card" aria-label="Usage by model">
<div class="section-head">
<h2 class="section-title">By model</h2>
</div>
<div class="table-wrap">
<table id="usage-by-model" class="usage-table">
<thead>
<tr>
<th>Name</th>
<th class="num">Cost</th>
<th class="num">Runs</th>
<th class="num">Lines</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</section>
</div>
</main>
<script>
const TOKEN_HEADER = "X-Blyte-Token";
const TOKEN_STORAGE_KEY = "blyte.surface.token";
const MISSING_TOKEN_MSG = "Open this page from a surface: its token is missing";
const MAX_BAR_PX = 120;
let selectedRange = "30d";
let requestSeq = 0;
function formatUsd(n) {
if (typeof n !== "number" || !Number.isFinite(n)) {
throw new Error("not a cost: " + n);
}
const negative = n < 0;
const fixed = Math.abs(n).toFixed(2);
const parts = fixed.split(".");
const intPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const sign = negative && fixed !== "0.00" ? "-" : "";
return "USD " + sign + intPart + "." + parts[1];
}
function formatCount(n) {
if (typeof n !== "number" || !Number.isFinite(n)) {
throw new Error("not a count: " + n);
}
const rounded = Math.round(n);
const negative = rounded < 0;
const digits = String(Math.abs(rounded)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return (negative ? "-" : "") + digits;
}
function rangeSince(range, nowSecs) {
if (range === "7d") {
return nowSecs - 7 * 86400;
}
if (range === "30d") {
return nowSecs - 30 * 86400;
}
if (range === "all") {
return null;
}
throw new Error("unknown range: " + range);
}
function usageUrl(since) {
if (since === null) {
return "/api/usage";
}
return "/api/usage?since=" + since;
}
function surfaceLabel(row) {
if (row && typeof row.name === "string" && row.name.trim().length > 0) {
return row.name;
}
if (row && typeof row.surface === "string" && row.surface.trim().length > 0) {
return row.surface;
}
return "Not from a surface";
}
function usageNotes(report) {
const notes = [];
if (report && report.totals && report.totals.unpriced > 0) {
notes.push(formatCount(report.totals.unpriced) + " lines have no price and are not in the cost");
}
if (report && report.unreadable_lines > 0) {
notes.push(formatCount(report.unreadable_lines) + " lines in the log could not be read");
}
if (report && report.log_exists === false) {
notes.push("No usage recorded yet at " + report.log);
}
return notes;
}
function barHeights(days, maxPx) {
if (!Array.isArray(days) || days.length === 0) {
return [];
}
let greatest = 0;
for (const day of days) {
if (day.cost_usd > greatest) {
greatest = day.cost_usd;
}
}
if (greatest === 0) {
return days.map(() => 0);
}
return days.map((day) => Math.round((maxPx * day.cost_usd) / greatest));
}
function isPlainObject(v) {
return v !== null && typeof v === "object" && !Array.isArray(v);
}
function validateGroup(group, label) {
if (!isPlainObject(group)) {
return label + " must be an object";
}
const fields = ["cost_usd", "unpriced", "lines", "runs", "input", "cached", "output", "thinking"];
for (const field of fields) {
if (typeof group[field] !== "number" || !Number.isFinite(group[field])) {
return label + " missing or invalid field " + field;
}
}
return null;
}
function validateUsageReport(data) {
if (!isPlainObject(data)) {
return "response must be a JSON object";
}
if (typeof data.log !== "string") {
return "missing or invalid field log";
}
if (typeof data.log_exists !== "boolean") {
return "missing or invalid field log_exists";
}
if (typeof data.unreadable_lines !== "number" || !Number.isFinite(data.unreadable_lines)) {
return "missing or invalid field unreadable_lines";
}
const totalsErr = validateGroup(data.totals, "totals");
if (totalsErr) {
return totalsErr;
}
const arrayGroups = [
["by_day", "day", false],
["by_kind", "kind", false],
["by_repo", "repo", false],
["by_model", "model", false],
];
for (const [listKey, keyField] of arrayGroups) {
if (!Array.isArray(data[listKey])) {
return "missing or invalid field " + listKey;
}
for (let i = 0; i < data[listKey].length; i++) {
const item = data[listKey][i];
const err = validateGroup(item, listKey + "[" + i + "]");
if (err) {
return err;
}
if (typeof item[keyField] !== "string") {
return listKey + "[" + i + "] missing or invalid field " + keyField;
}
}
}
if (!Array.isArray(data.by_surface)) {
return "missing or invalid field by_surface";
}
for (let i = 0; i < data.by_surface.length; i++) {
const item = data.by_surface[i];
const err = validateGroup(item, "by_surface[" + i + "]");
if (err) {
return err;
}
if (item.surface !== null && typeof item.surface !== "string") {
return "by_surface[" + i + "] invalid field surface";
}
if (item.name !== null && typeof item.name !== "string") {
return "by_surface[" + i + "] invalid field name";
}
if (typeof item.last_ts !== "number" || !Number.isFinite(item.last_ts)) {
return "by_surface[" + i + "] missing or invalid field last_ts";
}
}
return null;
}
function readToken() {
if (typeof window === "undefined" || !window.sessionStorage) {
return null;
}
try {
const token = window.sessionStorage.getItem(TOKEN_STORAGE_KEY);
return token || null;
} catch (_) {
return null;
}
}
function setStatus(message) {
const el = document.getElementById("usage-status");
if (!el) return;
el.textContent = message;
el.hidden = !message;
}
function clearElement(el) {
if (!el) return;
while (el.firstChild) {
el.removeChild(el.firstChild);
}
}
function clearFigures() {
clearElement(document.getElementById("usage-totals"));
const notesEl = document.getElementById("usage-notes");
if (notesEl) {
clearElement(notesEl);
notesEl.hidden = true;
}
clearElement(document.getElementById("usage-days-bars"));
clearElement(document.getElementById("usage-days-axis"));
for (const id of ["usage-by-surface", "usage-by-kind", "usage-by-repo", "usage-by-model"]) {
const table = document.getElementById(id);
const tbody = table ? table.querySelector("tbody") : null;
clearElement(tbody);
}
}
function formatLastUsed(ts) {
return new Date(ts * 1000).toLocaleString();
}
function appendTotalCard(container, label, value, sub) {
const card = document.createElement("div");
card.className = "total-card";
const labelEl = document.createElement("div");
labelEl.className = "total-label";
labelEl.textContent = label;
const row = document.createElement("div");
row.className = "total-value-row";
const valEl = document.createElement("span");
valEl.className = "total-value nums";
valEl.textContent = value;
row.appendChild(valEl);
if (sub) {
const subEl = document.createElement("span");
subEl.className = "total-sub nums";
subEl.textContent = sub;
row.appendChild(subEl);
}
card.appendChild(labelEl);
card.appendChild(row);
container.appendChild(card);
}
function renderTotals(totals) {
const container = document.getElementById("usage-totals");
if (!container) return;
clearElement(container);
const activeTokens = totals.input + totals.output + totals.thinking;
appendTotalCard(container, "Cost", formatUsd(totals.cost_usd), "");
appendTotalCard(container, "Runs", formatCount(totals.runs), "");
appendTotalCard(container, "Lines", formatCount(totals.lines), "");
appendTotalCard(
container,
"Tokens",
formatCount(activeTokens),
formatCount(totals.cached) + " cached"
);
}
function renderNotes(report) {
const notesEl = document.getElementById("usage-notes");
if (!notesEl) return;
clearElement(notesEl);
const notes = usageNotes(report);
if (notes.length === 0) {
notesEl.hidden = true;
return;
}
for (const note of notes) {
const li = document.createElement("li");
li.textContent = note;
notesEl.appendChild(li);
}
notesEl.hidden = false;
}
function renderDays(days) {
const barsEl = document.getElementById("usage-days-bars");
const axisEl = document.getElementById("usage-days-axis");
if (!barsEl) return;
clearElement(barsEl);
clearElement(axisEl);
if (days.length === 0) {
const empty = document.createElement("div");
empty.className = "days-empty";
empty.textContent = "No usage in this range.";
barsEl.appendChild(empty);
return;
}
const heights = barHeights(days, MAX_BAR_PX);
for (let i = 0; i < days.length; i++) {
const day = days[i];
const slot = document.createElement("div");
slot.className = "days-bar-slot";
const bar = document.createElement("div");
bar.className = "days-bar";
bar.style.height = heights[i] + "px";
bar.title = day.day + ": " + formatUsd(day.cost_usd);
slot.appendChild(bar);
barsEl.appendChild(slot);
}
if (axisEl) {
const first = document.createElement("span");
first.textContent = days[0].day;
axisEl.appendChild(first);
if (days.length > 1) {
const last = document.createElement("span");
last.textContent = days[days.length - 1].day;
axisEl.appendChild(last);
}
}
}
function renderSimpleTable(tableId, rows, keyField) {
const table = document.getElementById(tableId);
const tbody = table ? table.querySelector("tbody") : null;
if (!tbody) return;
clearElement(tbody);
if (rows.length === 0) {
const tr = document.createElement("tr");
const td = document.createElement("td");
td.colSpan = 4;
td.className = "empty-cell";
td.textContent = "None";
tr.appendChild(td);
tbody.appendChild(tr);
return;
}
for (const row of rows) {
const tr = document.createElement("tr");
const nameTd = document.createElement("td");
nameTd.className = "name-cell";
nameTd.textContent = row[keyField];
const costTd = document.createElement("td");
costTd.className = "num";
costTd.textContent = formatUsd(row.cost_usd);
const runsTd = document.createElement("td");
runsTd.className = "num";
runsTd.textContent = formatCount(row.runs);
const linesTd = document.createElement("td");
linesTd.className = "num";
linesTd.textContent = formatCount(row.lines);
tr.appendChild(nameTd);
tr.appendChild(costTd);
tr.appendChild(runsTd);
tr.appendChild(linesTd);
tbody.appendChild(tr);
}
}
function renderSurfaceTable(rows) {
const table = document.getElementById("usage-by-surface");
const tbody = table ? table.querySelector("tbody") : null;
if (!tbody) return;
clearElement(tbody);
if (rows.length === 0) {
const tr = document.createElement("tr");
const td = document.createElement("td");
td.colSpan = 5;
td.className = "empty-cell";
td.textContent = "None";
tr.appendChild(td);
tbody.appendChild(tr);
return;
}
for (const row of rows) {
const tr = document.createElement("tr");
const nameTd = document.createElement("td");
nameTd.className = "name-cell";
nameTd.textContent = surfaceLabel(row);
const costTd = document.createElement("td");
costTd.className = "num";
costTd.textContent = formatUsd(row.cost_usd);
const runsTd = document.createElement("td");
runsTd.className = "num";
runsTd.textContent = formatCount(row.runs);
const linesTd = document.createElement("td");
linesTd.className = "num";
linesTd.textContent = formatCount(row.lines);
const lastTd = document.createElement("td");
lastTd.className = "num muted-cell";
lastTd.textContent = formatLastUsed(row.last_ts);
tr.appendChild(nameTd);
tr.appendChild(costTd);
tr.appendChild(runsTd);
tr.appendChild(linesTd);
tr.appendChild(lastTd);
tbody.appendChild(tr);
}
}
function renderReport(report) {
setStatus("");
renderTotals(report.totals);
renderNotes(report);
renderDays(report.by_day);
renderSurfaceTable(report.by_surface);
renderSimpleTable("usage-by-kind", report.by_kind, "kind");
renderSimpleTable("usage-by-repo", report.by_repo, "repo");
renderSimpleTable("usage-by-model", report.by_model, "model");
}
async function extractErrorText(res) {
let raw = "";
try {
if (typeof res.text === "function") {
raw = await res.text();
} else if (typeof res.json === "function") {
const data = await res.json();
if (isPlainObject(data) && typeof data.error === "string") {
return data.error;
}
return "";
}
} catch (_) {
return "";
}
try {
const parsed = JSON.parse(raw);
if (isPlainObject(parsed) && typeof parsed.error === "string") {
return parsed.error;
}
} catch (_) {}
return raw.trim();
}
function updateRangeButtons() {
const rangeEl = document.getElementById("usage-range");
if (!rangeEl) return;
const buttons = rangeEl.querySelectorAll("[data-range]");
for (const btn of buttons) {
const active = btn.getAttribute("data-range") === selectedRange;
btn.setAttribute("aria-pressed", active ? "true" : "false");
}
}
async function loadUsage() {
const token = readToken();
if (!token) {
clearFigures();
setStatus(MISSING_TOKEN_MSG);
return;
}
const seq = ++requestSeq;
const nowSecs = Math.floor(Date.now() / 1000);
const since = rangeSince(selectedRange, nowSecs);
const url = usageUrl(since);
const headers = {};
headers[TOKEN_HEADER] = token;
let res;
try {
res = await fetch(url, { headers });
} catch (err) {
if (seq !== requestSeq) return;
clearFigures();
setStatus("Could not load usage: " + (err && err.message ? err.message : String(err)));
return;
}
if (seq !== requestSeq) return;
if (res.status !== 200) {
const errText = await extractErrorText(res);
if (seq !== requestSeq) return;
clearFigures();
const detail = errText ? " " + errText : "";
setStatus("Could not load usage: " + res.status + detail);
return;
}
let data;
try {
data = await res.json();
} catch (err) {
if (seq !== requestSeq) return;
clearFigures();
setStatus("Could not load usage: invalid JSON: " + (err && err.message ? err.message : String(err)));
return;
}
if (seq !== requestSeq) return;
const validationErr = validateUsageReport(data);
if (validationErr) {
clearFigures();
setStatus("Could not load usage: " + validationErr);
return;
}
renderReport(data);
}
function bindEvents() {
const rangeEl = document.getElementById("usage-range");
if (!rangeEl) return;
rangeEl.addEventListener("click", (e) => {
const btn = e.target && typeof e.target.closest === "function"
? e.target.closest("[data-range]")
: null;
if (!btn) return;
const nextRange = btn.getAttribute("data-range");
if (!nextRange) return;
selectedRange = nextRange;
updateRangeButtons();
loadUsage();
});
}
function init() {
updateRangeButtons();
bindEvents();
loadUsage();
}
if (typeof document !== "undefined") {
init();
}
</script>
</body>
</html>