import { expect, test } from "bun:test"
import { readFileSync, readdirSync } from "node:fs"
import { join } from "node:path"
const dir = import.meta.dir
const page = join(dir, "page")
const read = (f) => readFileSync(join(page, f), "utf8")
const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"))
// view.js is a classic script, as the page loads it
const scope = {}
new Function("globalThis", read("view.js"))(scope)
const V = scope.UsageView
// usage:summary as magpie answers it (pluginpage.go, pageRead)
const summary = {
period: "7d", since: "2026-10-09T00:00:00+08:00", calls: 1234, errors: 12,
input: 3456789, output: 210000, cacheRead: 2000000, cost: 41.5,
models: [
{ model: "claude-sonnet-4-5", calls: 200, input: 3000000, output: 150000, cost: 30 },
{ model: "gpt-5-codex", calls: 1000, input: 450000, output: 50000, cost: 11 },
{ model: "deepseek-chat", calls: 34, input: 6789, output: 10000, cost: 0.5 },
],
}
test("asks for one read, usage:summary, and nothing else", () => {
expect(pkg.magpie.permissions).toEqual(["usage:summary"])
const reads = new Set()
for (const f of readdirSync(page).filter((f) => f.endsWith(".js"))) {
for (const m of read(f).matchAll(/magpie\.read\(\s*"([^"]+)"/g)) reads.add(m[1])
// no way out of the frame: magpie's policy refuses these anyway
expect(read(f)).not.toMatch(/\bfetch\(|XMLHttpRequest|WebSocket|sendBeacon|EventSource|importScripts/)
}
expect([...reads]).toEqual(["usage:summary"])
})
test("is a page magpie serves: its files in page/, scripts as files", () => {
expect(pkg.main).toBeUndefined()
expect(pkg.exports).toBeUndefined()
expect(pkg.magpie.page).toEqual({
title: "Usage glance",
titles: { zh: "用量速览", "zh-TW": "用量速覽", ja: "使用量の概要", de: "Nutzung im Überblick" },
file: "page/index.html",
icon: "page/icon.svg",
})
const html = read("index.html")
expect(html).toContain('')
// the policy runs no inline script
for (const m of html.matchAll(/