diff --git a/AGENTS.md b/AGENTS.md index 87baa45..f64666d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,7 +55,8 @@ a laptop. `docs/design/v3/day/` (the prototype and its README); `built/` holds the built page's shots. - `public/usage/`: the private usage page's files (setkernel-live#71), served by the Worker only with a `USAGE_AUD` token (`run_worker_first` in `wrangler.jsonc`, pinned by `test/usage-page.test.mjs`). - `table.js` (a month's rows, cells and the box's text) is pure and tested. Never move them out of `/usage`. + `table.js` (a month's rows, cells and the box's text) is pure and tested; `page.js` draws it, tested + against a stand-in document. Never move them out of `/usage`. - `public/lib/`: ES modules for the page. `state.js` is the public state, the Halifax day (`homeDay`, `homeMidnight`) and the 24-hour replay buffer; the Durable Object and `?demo` both run it. `line.js` derives each engineer's stage (state.js keeps the lanes). `words.js` (wording, diff --git a/README.md b/README.md index c508d25..6ea26c9 100644 --- a/README.md +++ b/README.md @@ -243,7 +243,9 @@ Everything under `/usage` (the page Raghav reads it on, setkernel-live#71, and i before the Worker sees the request). `/usage/data` names the newest hour stored, in any month, in a `Usage-Newest-Hour` header (absent while nothing is stored); the body keeps its shape. `public/usage/table.js` turns a month into the page's rows: fresh tokens are input + output + cache -writes, and a day or seat with no data is a dash, not zero. +writes, and a day or seat with no data is a dash, not zero. `public/usage/index.html`, `usage.css` +and `page.js` draw it (setkernel-live#78): `?month=YYYY-MM` picks the month, the newest hour is +the header's, and a 403, 503 or expired login shows a message. Its shots are in `docs/design/usage/`. ## When updates stop diff --git a/docs/design/usage/usage-1440x900-dark.png b/docs/design/usage/usage-1440x900-dark.png new file mode 100644 index 0000000..40b369b Binary files /dev/null and b/docs/design/usage/usage-1440x900-dark.png differ diff --git a/docs/design/usage/usage-1440x900.png b/docs/design/usage/usage-1440x900.png new file mode 100644 index 0000000..75cbded Binary files /dev/null and b/docs/design/usage/usage-1440x900.png differ diff --git a/docs/design/usage/usage-375x812.png b/docs/design/usage/usage-375x812.png new file mode 100644 index 0000000..1a79cd4 Binary files /dev/null and b/docs/design/usage/usage-375x812.png differ diff --git a/public/usage/index.html b/public/usage/index.html new file mode 100644 index 0000000..0947fc0 --- /dev/null +++ b/public/usage/index.html @@ -0,0 +1,32 @@ + + + + + + + Usage per seat · setkernel live + + + + + + +
+
+

setkernel live · usage

+

Loading · Only Raghav can open this page

+
+
+

Tokens per seat

+

Fresh tokens are input, output and cache writes. Days run midnight to midnight, Halifax time.

+
+ +

Loading this month's usage…

+ + + +

Dollars are what the same tokens would cost at API prices. The seats are on subscriptions, so this is a size guide, not a bill. Polaris covers Raghav's own sessions. A dash means no data, not zero.

+
+ + + diff --git a/public/usage/page.js b/public/usage/page.js new file mode 100644 index 0000000..268b9fa --- /dev/null +++ b/public/usage/page.js @@ -0,0 +1,154 @@ +// live.setkernel.com/usage (setkernel-live#78): option B from setkernel-live#71, drawn from GET +// /usage/data through buildMonth (table.js). Everything is built with textContent. Hovering, +// focusing or tapping a number shows its box; Esc or a tap elsewhere closes it. +// Tested with a stand-in document in test/usage-page.test.mjs. +import { homeDay } from "../lib/state.js"; +import { asOf, buildMonth, monthName, shiftMonth, tip } from "./table.js"; + +const $ = (id) => document.getElementById(id); +function el(tag, cls, text) { + const e = document.createElement(tag); + if (cls) e.className = cls; + if (text != null) e.textContent = text; + return e; +} + +// What the page says when GET /usage/data doesn't answer with a month. 0 is no answer at all: an +// expired login is a redirect to Access's login page, which the CSP stops. +export function failure(status) { + if (status === 403) return "This login can't read usage. Reload the page to sign in again."; + if (status === 503) return "Usage isn't set up on this site, so there is nothing to show."; + return `Usage didn't load (${status ? `HTTP ${status}` : "no answer"}). Reload the page to try again; if your login expired, that signs you in.`; +} + +function nav(month, current) { + const link = (m, text) => (m > current ? el("span", "off", text) : Object.assign(el("a", null, text), { href: `?month=${m}` })); + $("months").replaceChildren(link(shiftMonth(month, -1), `← ${monthName(shiftMonth(month, -1))}`), el("b", null, `${monthName(month)} ${month.slice(0, 4)}`), link(shiftMonth(month, 1), `${monthName(shiftMonth(month, 1))} →`)); +} + +// A number: its data-* attributes are the exact values its box shows. +function num(x, cls) { + const td = el("td", `h ${cls}`); + td.tabIndex = 0; + Object.assign(td.dataset, { who: x.who, when: x.when, f: x.f, c: x.c, u: x.u }); + td.setAttribute("aria-label", x.label); + return td; +} +const dash = (cls = "") => el("td", `none ${cls}`, "–"); + +function bar(px) { + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"), rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); + for (const [k, v] of Object.entries({ class: "bar", width: px, height: 4, "aria-hidden": "true" })) svg.setAttribute(k, v); + for (const [k, v] of Object.entries({ width: px, height: 4, rx: 2 })) rect.setAttribute(k, v); + svg.append(rect); + return svg; +} + +function draw(v, newest) { + $("title").textContent = `Tokens per seat, ${v.name}`; + $("asof").textContent = newest ? `Newest hour ends ${asOf(newest)}` : "Nothing stored yet"; + const t = v.total.all; + $("sum").replaceChildren(...[["Fresh tokens this month", t?.text], ["Cache reads", t?.cached], ["At API prices, about", t?.usd], ["Busiest seat", v.busiest]] + .map(([k, val]) => { const li = el("li"); li.append(el("span", "k", k), el("span", "v", val ?? "–")); return li; })); + if (v.empty) $("status").textContent = `Nothing is stored for ${v.name} yet.`; + else $("status").hidden = true; + + const head = el("tr"); + head.append(...["Day", ...v.seats].map((s) => el("th", null, s)), el("th", "tot", "All seats")); + for (const th of head.children) th.setAttribute("scope", "col"); + const body = el("tbody"); + for (const r of v.rows) { + const tr = el("tr", [r.weekend && "we", r.today && "today"].filter(Boolean).join(" ")); + const day = el("td", null, `${r.d} `); + day.append(el("span", "wd", r.wd)); + if (r.today) day.append(el("span", "tag", "so far")); + tr.append(day, ...r.cells.map((c) => { + if (!c) return dash(); + const td = num(c, `t${c.heat}`); + td.append(el("span", "m", c.text)); + return td; + })); + if (r.all) { + const td = num(r.all, "tot"), m = el("span", "m", `${r.all.text} `); + m.append(el("span", "usd", r.all.usd)); + td.append(m); + if (r.all.bar) td.append(bar(r.all.bar)); + tr.append(td); + } else tr.append(dash("tot")); + body.append(tr); + } + const foot = el("tr"); + foot.append(el("td", null, v.name.split(" ")[0]), ...v.total.cells.map((c) => { + if (!c) return dash(); + const td = num(c, ""); + td.append(el("span", "m", c.text), el("span", "s", c.usd)); + return td; + })); + if (t) { + const td = num(t, "tot"); + td.append(el("span", "m", t.text), el("span", "s", `${t.cached} cached`), el("span", "s", t.usd)); + foot.append(td); + } else foot.append(dash("tot")); + const thead = el("thead"), tfoot = el("tfoot"); + thead.append(head); + tfoot.append(foot); + $("usage").replaceChildren(thead, body, tfoot); + for (const id of ["sum", "scroll", ...(v.empty ? [] : ["hint"])]) $(id).hidden = false; +} + +// The box, from the reference in setkernel-live#71: placed with the CSSOM, which the CSP allows. +let pinned = null, focused = null; +function show(td) { + const box = $("tip"), t = tip(td.dataset), dl = el("dl"); + for (const [k, val] of t.rows) dl.append(el("dt", null, k), el("dd", null, val)); + box.replaceChildren(el("div", "t-h", t.head), dl); + box.hidden = false; + const r = td.getBoundingClientRect(), w = box.offsetWidth, h = box.offsetHeight; + const x = Math.min(Math.max(8, r.left + r.width / 2 - w / 2), document.documentElement.clientWidth - w - 8); + const y = r.top - h - 8 < 8 ? r.bottom + 8 : r.top - h - 8; + box.style.left = `${x}px`; + box.style.top = `${y}px`; +} +function hide() { + pinned?.classList.remove("on"); + pinned = focused = null; + $("tip").hidden = true; +} +function listen() { + const table = $("usage"); + const cell = (n) => { const td = n?.closest?.("td.h"); return td && table.contains(td) ? td : null; }; + table.addEventListener("mouseover", (e) => { const td = cell(e.target); if (td && !pinned) show(td); }); + table.addEventListener("mouseout", (e) => { if (!pinned && cell(e.target) && !cell(e.relatedTarget)) hide(); }); + table.addEventListener("focusin", (e) => { const td = cell(e.target); if (td) show(focused = td); }); + table.addEventListener("focusout", () => { if (!pinned) hide(); }); + document.addEventListener("click", (e) => { + const td = cell(e.target), again = td && td === pinned; + hide(); + if (td && !again) { pinned = td; td.classList.add("on"); show(td); } + }); + document.addEventListener("keydown", (e) => { if (e.key === "Escape") hide(); }); + // the window's scroll and the table's own: move a pinned or focused box with its number (Tab + // scrolls a number into view after focusin), drop a hovered one + document.addEventListener("scroll", () => { const td = pinned ?? focused; td ? show(td) : hide(); }, { capture: true, passive: true }); +} + +async function load() { + const today = homeDay(Date.now()), current = today.slice(0, 7); + const asked = new URLSearchParams(location.search).get("month") ?? ""; + const month = /^\d{4}-(0[1-9]|1[0-2])$/.test(asked) && asked <= current ? asked : current; + nav(month, current); + let res, data; + try { + res = await fetch(`/usage/data?month=${month}`, { cache: "no-store", redirect: "manual" }); + if (res.ok) data = await res.json(); + } catch {} + if (!data) { + $("status").textContent = failure(res?.status ?? 0); + $("asof").textContent = "Not loaded"; + return; + } + draw(buildMonth(data, today), res.headers.get("Usage-Newest-Hour")); + listen(); +} + +export const ready = load(); diff --git a/public/usage/usage.css b/public/usage/usage.css new file mode 100644 index 0000000..571a119 --- /dev/null +++ b/public/usage/usage.css @@ -0,0 +1,74 @@ +/* live.setkernel.com/usage (setkernel-live#78): option B from setkernel-live#71. The fonts, tokens, + masthead and lead come from /style.css; this adds the dark theme (the wall's colours, so the + contrast test in test/page.test.mjs covers them), the table, the shading and the box. */ +:root { --heat: 24, 24, 26; } +@media (prefers-color-scheme: dark) { + :root { + --bg: #111214; --surface: #1b1c20; --ink: #eeede9; --ink-2: #bdbbb5; --ink-3: #9a9892; + --rule: #232427; --rule-2: #3d3e42; --band: #25262a; --bar: #77756f; + --signal: #f2735f; --focus: #8fb0ff; + --heat: 238, 237, 233; color-scheme: dark; + } +} +.lead { padding-bottom: var(--s3); } +.months { display: flex; gap: var(--s4); align-items: baseline; font-size: var(--f2); line-height: var(--l2); color: var(--ink-2); padding-bottom: var(--s3); } +.months .off { color: var(--ink-3); } +a:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } +.status { margin: 0 0 var(--s4); color: var(--ink-2); } +.sum { display: flex; flex-wrap: wrap; gap: var(--s3) var(--s5); margin: 0 0 var(--s4); padding: 0; list-style: none; } +.sum li { display: flex; flex-direction: column; } +.sum .k { font-size: var(--f1); line-height: var(--l1); color: var(--ink-3); } +.sum .v { font-size: var(--f4); line-height: var(--l3); font-weight: 600; } +.hint { margin: 0 0 var(--s2); font-size: var(--f1); line-height: var(--l1); color: var(--ink-3); } +.note { margin: var(--s3) 0 0; font-size: var(--f1); line-height: var(--l1); color: var(--ink-3); max-width: 760px; } + +/* the table: one row per Halifax day, newest first; only it scrolls sideways on a phone */ +.scroll { overflow-x: auto; border-top: 1px solid var(--rule-2); } +table { border-collapse: collapse; width: 100%; font-size: var(--f2); line-height: var(--l2); } +th, td { text-align: right; padding: var(--s2) var(--s3) var(--s2) 0; border-bottom: 1px solid var(--rule); vertical-align: top; white-space: nowrap; } +thead th { font-weight: 600; color: var(--ink-2); position: sticky; top: 0; background: var(--bg); } +th:first-child, td:first-child { text-align: left; position: sticky; left: 0; background: var(--bg); padding-left: 0; z-index: 1; } +td:first-child { font: var(--f1)/var(--l2) var(--mono); color: var(--ink-2); } +td:first-child .wd { color: var(--ink-3); } +td .m, td .s { display: block; } +td .m { color: var(--ink); } +td .s { font-size: var(--f1); line-height: var(--l1); color: var(--ink-3); } +td.none { color: var(--ink-3); padding-left: var(--s3); } +th.tot, td.tot { border-left: 1px solid var(--rule-2); padding-left: var(--s3); } +tr.we td:first-child { color: var(--ink-3); } +tr.today td, tr.today td:first-child { background-color: var(--surface); } +.tag { display: inline-block; margin-left: var(--s2); font: 600 var(--f1)/var(--l1) var(--sans); color: var(--signal); } +tfoot td { border-top: 1px solid var(--rule-2); border-bottom: 0; padding-top: var(--s3); } +tfoot td:first-child { font: 600 var(--f2)/var(--l2) var(--sans); color: var(--ink); } +tfoot td .m, td.tot .m { font-weight: 600; } +.usd { font-size: var(--f1); color: var(--ink-3); } +.bar { display: block; margin: var(--s1) 0 0 auto; } +.bar rect { fill: var(--bar); } + +/* a seat's day, shaded on 8 steps by its size against the month's biggest (table.js, HEAT): a + class each, since the CSP allows no style attribute; laid over today's ground, not in place of it */ +td.h { padding-left: var(--s3); cursor: default; background-image: linear-gradient(var(--tint, transparent), var(--tint, transparent)); } +td.t1 { --tint: rgba(var(--heat), .04); } +td.t2 { --tint: rgba(var(--heat), .06); } +td.t3 { --tint: rgba(var(--heat), .08); } +td.t4 { --tint: rgba(var(--heat), .10); } +td.t5 { --tint: rgba(var(--heat), .12); } +td.t6 { --tint: rgba(var(--heat), .14); } +td.t7 { --tint: rgba(var(--heat), .16); } +td.t8 { --tint: rgba(var(--heat), .18); } +td.h:focus { outline: none; } +td.h:hover, td.h.on { outline: 2px solid var(--ink); outline-offset: -2px; } +td.h:focus-visible { outline: 2px solid var(--focus); outline-offset: -2px; } + +/* the box: a number's exact fresh tokens, cache reads and dollars */ +.tip { position: fixed; z-index: 5; min-width: 220px; padding: var(--s2) var(--s3); background: var(--ink); color: var(--bg); border-radius: 6px; font-size: var(--f2); line-height: var(--l2); pointer-events: none; box-shadow: 0 4px 16px rgba(0, 0, 0, .18); } +.tip .t-h { font-weight: 600; margin-bottom: var(--s1); } +.tip dl { display: grid; grid-template-columns: auto auto; gap: 0 var(--s3); margin: 0; } +.tip dt { opacity: .72; } +.tip dd { margin: 0; text-align: right; font-weight: 600; } + +@media (max-width: 719px) { + .sum .v { font-size: var(--f3); } + .wide { display: none; } + table { width: auto; } +} diff --git a/test/usage-page.test.mjs b/test/usage-page.test.mjs index ac8ec99..6d7b3ed 100644 --- a/test/usage-page.test.mjs +++ b/test/usage-page.test.mjs @@ -70,3 +70,117 @@ test("wrangler.jsonc runs the Worker first for /usage and everything under it", const assets = readFileSync(new URL("../wrangler.jsonc", import.meta.url), "utf8").match(/"assets":\s*(\{[^}]*\})/)[1]; assert.deepEqual(JSON.parse(assets).run_worker_first, ["/usage", "/usage/*"]); }); + +// ---- the page script (setkernel-live#78), run in node against a stand-in document built from +// index.html's ids: just enough DOM for page.js, with fetch answering from the fixture month +class Node { + constructor(tag) { Object.assign(this, { tag, kids: [], attrs: {}, dataset: {}, style: {}, on: {}, hidden: false, className: "", text: "" }); } + get classList() { const cls = () => this.className.split(" ").filter(Boolean); return { add: (c) => { this.className = [...cls(), c].join(" "); }, remove: (c) => { this.className = cls().filter((x) => x !== c).join(" "); } }; } + get children() { return this.kids; } + get textContent() { return this.text + this.kids.map((k) => k.textContent).join(""); } + set textContent(t) { this.kids = []; this.text = String(t); } + append(...kids) { for (const k of kids) { k.parentNode = this; this.kids.push(k); } } + replaceChildren(...kids) { this.kids = []; this.text = ""; this.append(...kids); } + setAttribute(k, v) { this.attrs[k] = String(v); } + addEventListener(type, f) { (this.on[type] ??= []).push(f); } + closest(sel) { const [tag, cls] = sel.split("."); for (let n = this; n; n = n.parentNode) if (n.tag === tag && n.className.split(" ").includes(cls)) return n; return null; } + contains(n) { for (; n; n = n.parentNode) if (n === this) return true; return false; } + getBoundingClientRect() { return { left: 300, top: 200, width: 60, height: 40, bottom: 240 }; } + get offsetWidth() { return 220; } + get offsetHeight() { return 90; } + *all() { yield this; for (const k of this.kids) yield* k.all(); } +} +const html = readFileSync(new URL("../public/usage/index.html", import.meta.url), "utf8"); +async function runPage(answer) { + const doc = new Node("document"), ids = {}; + for (const [, tag, id, rest] of html.matchAll(/<(\w+) [^>]*?id="([^"]+)"([^>]*)>/g)) doc.append(Object.assign(ids[id] = new Node(tag), { hidden: /\shidden\b/.test(rest) })); + Object.assign(doc, { documentElement: { clientWidth: 375 }, getElementById: (id) => ids[id], createElement: (t) => new Node(t), createElementNS: (_, t) => new Node(t) }); + const fire = (type, target, more = {}) => { for (let n = target; n; n = n.parentNode) for (const f of n.on[type] ?? []) f({ type, target, ...more }); }; + const asked = []; + Object.assign(globalThis, { document: doc, location: { search: "?month=2026-11" }, fetch: async (url) => { asked.push(url); return answer(); } }); + test.mock.timers.enable({ apis: ["Date"], now: Date.UTC(2026, 10, 2, 16) }); // noon in Halifax + try { + await (await import(`../public/usage/page.js?${Math.random()}`)).ready; + } finally { + test.mock.timers.reset(); + } + return { ids, fire, asked, cells: [...ids.usage.all()].filter((n) => n.tag === "td") }; +} +const month = () => new Response(JSON.stringify(data), { headers: { "Usage-Newest-Hour": "2026-11-02T15" } }); + +test("the page draws the fixture month: rows, a dash for no data, today so far, the months, the as-of time", async () => { + const { ids, cells, asked } = await runPage(month); + assert.deepEqual(asked, ["/usage/data?month=2026-11"]); + assert.equal(ids.title.textContent, "Tokens per seat, November 2026"); + assert.equal(ids.asof.textContent, "Newest hour ends 2 Nov, 12:00 AST"); + assert.deepEqual([ids.status.hidden, ids.scroll.hidden, ids.sum.hidden], [true, false, false]); + assert.equal(ids.sum.textContent, "Fresh tokens this month49MCache reads148MAt API prices, about$4,925Busiest seatVega"); + assert.deepEqual(ids.months.kids.map((k) => [k.tag, k.textContent, k.href]), [["a", "← October", "?month=2026-10"], ["b", "November 2026", undefined], ["span", "December →", undefined]]); + const [head, body, foot] = ids.usage.kids; + assert.equal(head.textContent, "DayVegaRigelLyraOrionPolarisCodexAll seats"); + assert.deepEqual(body.kids.map((r) => [r.className, r.kids[0].textContent]), [["today", "2 Monso far"], ["we", "1 Sun"]]); + assert.deepEqual(body.kids[1].kids.map((td) => [td.className, td.textContent]), [["", "1 Sun"], ["h t8", "25M"], ["h t1", "1.3M"], ["none ", "–"], ["none ", "–"], ["none ", "–"], ["none ", "–"], ["h tot", "26M $2,625"]]); + assert.deepEqual(body.kids[1].kids[7].kids[1].attrs, { class: "bar", width: "96", height: "4", "aria-hidden": "true" }); + assert.equal(foot.textContent, "November48M$4,8001.3M$125–––420$049M148M cached$4,925"); + assert.ok(cells.filter((td) => td.className.startsWith("h")).every((td) => td.tabIndex === 0 && td.attrs["aria-label"])); +}); + +test("a number's box: hover, focus or tap shows its exact values; Esc or a tap elsewhere closes it", async () => { + const { ids, fire, cells } = await runPage(month); + const vega = cells.find((td) => td.dataset.who === "Vega" && td.dataset.when === "Sun 1 Nov"), box = ids.tip; + assert.equal(box.hidden, true); + fire("focusin", vega.kids[0]); + assert.equal(box.hidden, false); + assert.equal(box.textContent, "Vega · Sun 1 NovFresh tokens25,000,000Cache reads75,000,000At API pricesabout $2,500"); + assert.deepEqual(box.style, { left: "147px", top: "102px" }, "centred above the number, inside a 375 px screen"); + fire("scroll", ids.scroll); // the browser scrolls a focused number into view: its box stays + assert.equal(box.hidden, false); + fire("keydown", ids.usage, { key: "Escape" }); + assert.equal(box.hidden, true); + fire("scroll", ids.scroll); // and stays closed after Esc, though the number keeps focus + assert.equal(box.hidden, true); + fire("click", vega); // a tap pins it: moving the mouse off doesn't close it + fire("mouseout", vega, { relatedTarget: ids.hint }); + assert.deepEqual([box.hidden, vega.className], [false, "h t8 on"]); + fire("click", ids.hint); + assert.deepEqual([box.hidden, vega.className], [true, "h t8"]); + fire("mouseover", cells.find((td) => td.dataset.who === "All seats" && td.dataset.when === "November")); + assert.equal(box.kids[0].textContent, "All seats · November"); + fire("scroll", ids.scroll); // a hovered box drops when the page moves under it + assert.equal(box.hidden, true); +}); + +test("a refused, failed or empty month shows a plain message, not a blank page", async () => { + for (const [answer, words] of [ + [() => new Response("Forbidden", { status: 403 }), /can't read usage/], + [() => new Response("Usage is not configured", { status: 503 }), /isn't set up/], + [() => Promise.reject(new TypeError("Failed to fetch")), /no answer/], + [() => new Response(null, { status: 500 }), /HTTP 500/], + ]) { + const { ids } = await runPage(answer); + assert.match(ids.status.textContent, words); + assert.deepEqual([ids.status.hidden, ids.scroll.hidden, ids.sum.hidden], [false, true, true]); + } + const { ids, cells } = await runPage(() => Response.json({ month: "2026-11", days: {}, totals: {} })); + assert.equal(ids.status.textContent, "Nothing is stored for November 2026 yet."); + assert.deepEqual([ids.asof.textContent, ids.hint.hidden], ["Nothing stored yet", true]); + assert.ok(cells.length > 2 && cells.filter((td) => td.className.startsWith("none")).length === cells.length - 3, "every number is a dash"); +}); + +test("the page follows the CSP and the site's rules: no inline style or script, no markup from data, site fonts only", () => { + assert.doesNotMatch(html, /]*>([\s\S]*?)<\/script>/gi)) assert.deepEqual([/\bsrc="\/usage\/page\.js"/.test(m[0]), m[1]], [true, ""]); + assert.deepEqual([...html.matchAll(//g)].map((m) => m[1]), ["/style.css", "/usage/usage.css"]); + for (const f of ["page.js", "table.js"]) { + const js = readFileSync(new URL(`../public/usage/${f}`, import.meta.url), "utf8"); + assert.doesNotMatch(js, /innerHTML|outerHTML|insertAdjacentHTML|document\.write|localStorage|sessionStorage|setAttribute\(\s*["']style|\.style\s*=|var\(--/, f); + } + const css = readFileSync(new URL("../public/usage/usage.css", import.meta.url), "utf8"); + assert.doesNotMatch(css, /@font-face|@import|font-family|url\(|\b\d+(\.\d+)?px\s*\/|font-size:\s*\d/, "fonts and sizes are style.css's"); + // the dark theme is the wall's colours, which test/page.test.mjs checks for contrast + const site = readFileSync(new URL("../public/style.css", import.meta.url), "utf8"); + const hexes = (t) => Object.fromEntries([...t.matchAll(/--([\w-]+):\s*(#[0-9a-f]{6})/gi)].map((m) => [m[1], m[2]])); + assert.deepEqual(hexes(css.slice(css.indexOf("prefers-color-scheme: dark"))), hexes(site.slice(site.indexOf("html.wall {"), site.indexOf("}", site.indexOf("html.wall {"))))); + for (const n of css.matchAll(/td\.t(\d) \{/g)) assert.ok(Number(n[1]) >= 1 && Number(n[1]) <= 8); + assert.equal(css.match(/td\.t\d \{/g).length, 8, "one class per shading step"); +}); diff --git a/test/worker/usage-page.test.js b/test/worker/usage-page.test.js index cbf22ee..459dde7 100644 --- a/test/worker/usage-page.test.js +++ b/test/worker/usage-page.test.js @@ -39,7 +39,7 @@ async function get(path, token, init = {}) { describe("usage page", () => { it("serves /usage and its files only with a live usage token", async () => { - for (const path of ["/usage/", "/usage", "/usage/table.js", "/usage/nothing-here"]) { + for (const path of ["/usage/", "/usage", "/usage/index.html", "/usage/page.js", "/usage/usage.css", "/usage/table.js", "/usage/nothing-here"]) { for (const token of [undefined, "not.a.jwt", await sign(env.INGEST_AUD)]) expect((await get(path, token)).status, path).toBe(403); } const file = await get("/usage/table.js", await sign(env.USAGE_AUD)); @@ -47,6 +47,19 @@ describe("usage page", () => { expect(file.text).toContain("export function buildMonth"); }); + it("serves the page at /usage/ and /usage, and its script and styles, to a valid token", async () => { + const token = await sign(env.USAGE_AUD); + for (const path of ["/usage/", "/usage", "/usage/index.html"]) { + const res = await exports.default.fetch(`${BASE}${path}`, { headers: { "Cf-Access-Jwt-Assertion": token } }); + const text = await res.text(); + expect(res.status, path).toBe(200); + expect(text, path).toContain(''); + expect(res.headers.get("Content-Security-Policy"), path).toContain("script-src 'self'; style-src 'self'"); + } + expect((await get("/usage/page.js", token)).text).toContain('from "./table.js"'); + expect((await get("/usage/usage.css", token)).text).toContain("td.t8"); + }); + it("answers /usage/ files 503 if USAGE_AUD is ever empty", async () => { const res = await worker.fetch(new Request(`${BASE}/usage/table.js`, { headers: { "Cf-Access-Jwt-Assertion": await sign(env.USAGE_AUD) } }), { ...env, USAGE_AUD: "" }); await res.text();