diff --git a/.changeset/apidocs-package.md b/.changeset/apidocs-package.md new file mode 100644 index 0000000..1d0b45f --- /dev/null +++ b/.changeset/apidocs-package.md @@ -0,0 +1,7 @@ +--- +"@elide/apidocs": minor +--- + +Add `@elide/apidocs`: static HTML and Markdown API reference pages from the `apidocs/1` model that Elide's Javadoc +doclet and Dokka plugin write, with a JSON Schema, a classic-script renderer bundle and runner for JVM tools, client +islands, neutral and Elide theme presets, sample models and a hot-reload development loop. diff --git a/apps/apidocs-astro/.gitignore b/apps/apidocs-astro/.gitignore new file mode 100644 index 0000000..27baa03 --- /dev/null +++ b/apps/apidocs-astro/.gitignore @@ -0,0 +1,5 @@ +dist/ +.astro/ +.wrangler/ +src/generated/ +public/guides/ diff --git a/apps/apidocs-astro/astro.config.mjs b/apps/apidocs-astro/astro.config.mjs new file mode 100644 index 0000000..7fa83c9 --- /dev/null +++ b/apps/apidocs-astro/astro.config.mjs @@ -0,0 +1,27 @@ +// The sample app for @elide/apidocs/astro: the Java sample in two versions (2.0, the latest release, and main, +// a development version), the Kotlin sample, and the Markdown sample suite, on the Cloudflare adapter. Pages +// render on request, as the Komodo docs Worker renders them; the version menu and notice are server islands. +import cloudflare from "@astrojs/cloudflare"; +import { apidocs } from "@elide/apidocs/astro/integration"; +import { defineConfig } from "astro/config"; +import { guidesPlugin } from "./scripts/guides.mjs"; + +const theme = { extends: "elide" }; + +export default defineConfig({ + adapter: cloudflare(), + server: { host: "127.0.0.1", port: 5190 }, + devToolbar: { enabled: false }, + integrations: [ + apidocs({ + sites: [ + { base: "/java/2.0/", model: "./src/models/java.ts", theme, version: "2.0" }, + { base: "/java/main/", model: "./src/models/java.ts", theme, version: "main" }, + { base: "/kotlin/", model: "./src/models/kotlin.ts", theme }, + { base: "/guides/", model: "./src/generated/guides.json", theme }, + ], + versions: "./src/versions.ts", + }), + ], + vite: { plugins: [guidesPlugin()] }, +}); diff --git a/apps/apidocs-astro/package.json b/apps/apidocs-astro/package.json new file mode 100644 index 0000000..676cf23 --- /dev/null +++ b/apps/apidocs-astro/package.json @@ -0,0 +1,28 @@ +{ + "name": "@elide/apidocs-astro", + "private": true, + "version": "0.0.0", + "type": "module", + "description": "Sample Astro app for @elide/apidocs/astro: the Java and Kotlin sample models in two fake versions, with server islands and the client router.", + "scripts": { + "dev": "astro dev --host 127.0.0.1 --port 5190", + "build": "astro build", + "preview": "wrangler dev -c dist/server/wrangler.json --ip 127.0.0.1 --port 5190", + "lint": "astro sync && tsc --noEmit", + "test": "bun test --timeout 60000 test/" + }, + "dependencies": { + "@astrojs/cloudflare": "14.4.4", + "@astrojs/preact": "6.1.6", + "@elide/apidocs": "workspace:*", + "astro": "7.4.7", + "preact": "^11.2.0" + }, + "devDependencies": { + "@types/bun": "^1.3.0", + "axe-core": "4.14.0", + "playwright": "^1.65.0", + "typescript": "^7.0.2", + "wrangler": "4.157.0" + } +} diff --git a/apps/apidocs-astro/public/versions.json b/apps/apidocs-astro/public/versions.json new file mode 100644 index 0000000..4aab1ff --- /dev/null +++ b/apps/apidocs-astro/public/versions.json @@ -0,0 +1,4 @@ +[ + { "id": "2.0", "base": "/java/2.0/", "latest": true }, + { "id": "main", "base": "/java/main/", "channel": "development" } +] diff --git a/apps/apidocs-astro/scripts/guides.mjs b/apps/apidocs-astro/scripts/guides.mjs new file mode 100644 index 0000000..50e4b55 --- /dev/null +++ b/apps/apidocs-astro/scripts/guides.mjs @@ -0,0 +1,39 @@ +// Imports the Markdown sample suite (packages/apidocs/samples/guides) into a guides-only model at +// src/generated/guides.json, and copies its images to public/guides/, when Astro starts and whenever a file in +// the suite changes. Both outputs are generated and ignored by git. +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { guidesModel, importMarkdown, readSuite } from "@elide/apidocs/import"; + +const app = fileURLToPath(new URL("..", import.meta.url)); +const suite = resolve(app, "../../packages/apidocs/samples/guides"); + +export function generateGuides() { + const { files, assets } = readSuite(suite); + const result = importMarkdown(files, { + suite: "markdown", + assets, + links: [{ prefix: "../developer/", target: "https://example.com/developer/" }, { prefix: "../api/", target: "/java/2.0/" }], + }); + const model = guidesModel(result, { name: "Geo user guide", version: "2.0" }); + mkdirSync(resolve(app, "src/generated"), { recursive: true }); + writeFileSync(resolve(app, "src/generated/guides.json"), JSON.stringify(model)); + rmSync(resolve(app, "public/guides"), { recursive: true, force: true }); + for (const copy of result.files) { + const to = resolve(app, "public/guides", copy.to); + mkdirSync(dirname(to), { recursive: true }); + writeFileSync(to, copy.data); + } +} + +export function guidesPlugin() { + generateGuides(); + return { + name: "sample-guides", + configureServer(server) { + server.watcher.add(suite); + server.watcher.on("change", file => file.startsWith(suite) && generateGuides()); + }, + }; +} diff --git a/apps/apidocs-astro/src/env.d.ts b/apps/apidocs-astro/src/env.d.ts new file mode 100644 index 0000000..3e33ea8 --- /dev/null +++ b/apps/apidocs-astro/src/env.d.ts @@ -0,0 +1,4 @@ +/** The Workers runtime module that src/versions.ts reads the assets binding from, when it runs there. */ +declare module "cloudflare:workers" { + export const env: Record; +} diff --git a/apps/apidocs-astro/src/models/java.ts b/apps/apidocs-astro/src/models/java.ts new file mode 100644 index 0000000..ce8d2f4 --- /dev/null +++ b/apps/apidocs-astro/src/models/java.ts @@ -0,0 +1,4 @@ +/** The Java sample model, as the doclet would write it. */ +import { samples } from "@elide/apidocs/samples"; + +export default samples.java; diff --git a/apps/apidocs-astro/src/models/kotlin.ts b/apps/apidocs-astro/src/models/kotlin.ts new file mode 100644 index 0000000..ce6272b --- /dev/null +++ b/apps/apidocs-astro/src/models/kotlin.ts @@ -0,0 +1,4 @@ +/** The Kotlin sample model, as the Dokka plugin would write it. */ +import { samples } from "@elide/apidocs/samples"; + +export default samples.kotlin; diff --git a/apps/apidocs-astro/src/pages/index.astro b/apps/apidocs-astro/src/pages/index.astro new file mode 100644 index 0000000..b272c22 --- /dev/null +++ b/apps/apidocs-astro/src/pages/index.astro @@ -0,0 +1,30 @@ +--- +/** The sample's front page: links to each site. Not part of the integration. */ +const sites = [ + { href: "/java/2.0/", label: "Java sample 2.0", note: "the latest release" }, + { href: "/java/main/", label: "Java sample main", note: "a development version, with a version notice" }, + { href: "/kotlin/", label: "Kotlin sample", note: "unversioned" }, + { href: "/guides/", label: "Markdown sample suite", note: "a guides-only site from the importer" }, +]; +--- + + + + + + @elide/apidocs on Astro + + + + +
+

@elide/apidocs on Astro

+ +
+ + diff --git a/apps/apidocs-astro/src/versions.ts b/apps/apidocs-astro/src/versions.ts new file mode 100644 index 0000000..6689565 --- /dev/null +++ b/apps/apidocs-astro/src/versions.ts @@ -0,0 +1,22 @@ +/** + * The Java sample's versions. Pages render with `versions` (the fallback the version islands show first); the + * islands call loadVersions on each request, which reads public/versions.json through the Worker's assets + * binding, so editing that file changes the menu on pages that are already cached. A real app reads its + * versions.json from R2 the same way. + */ +import type { Version } from "@elide/apidocs/astro/helpers"; +import initial from "../public/versions.json"; + +export const versions: Version[] = initial as Version[]; + +export async function loadVersions(request: Request): Promise { + try { + const { env } = await import("cloudflare:workers"); + const assets = (env as { ASSETS?: { fetch: (input: string | URL) => Promise } }).ASSETS; + const response = await assets?.fetch(new URL("/versions.json", request.url)); + if (response?.ok) return (await response.json()) as Version[]; + } catch { + /* not on the Workers runtime */ + } + return versions; +} diff --git a/apps/apidocs-astro/test/browser.test.ts b/apps/apidocs-astro/test/browser.test.ts new file mode 100644 index 0000000..6daa03d --- /dev/null +++ b/apps/apidocs-astro/test/browser.test.ts @@ -0,0 +1,411 @@ +/** + * The sample app built for Cloudflare and served by wrangler dev, in Chromium: the client router, the persisted + * top bar and navigator, the page behaviors across navigations, server islands, JavaScript off, reduced motion, + * layout stability, axe, and head metadata against the static renderer. + * + * Builds the app and starts wrangler dev on port 5191 unless APIDOCS_ASTRO_URL names a running server. Needs a + * Playwright 1.65 Chromium (PLAYWRIGHT_BROWSERS_PATH). + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { type ChildProcess, spawn, spawnSync } from "node:child_process"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; +import { samples } from "@elide/apidocs/samples"; +import { render } from "@elide/apidocs"; +import { mapUrl } from "@elide/apidocs/astro/helpers"; +import { type Browser, type BrowserContextOptions, chromium, type Page } from "playwright"; + +const app = fileURLToPath(new URL("..", import.meta.url)); +const require = createRequire(import.meta.url); +const PORT = 5191; +let origin = process.env.APIDOCS_ASTRO_URL?.replace(/\/$/, "") ?? `http://127.0.0.1:${PORT}`; +let server: ChildProcess | undefined; +let browser: Browser; + +const TYPE = "/java/2.0/com/example/geo/Circle"; +const OTHER = "/java/2.0/com/example/geo/Shapes"; + +beforeAll(async () => { + if (!process.env.APIDOCS_ASTRO_URL) { + const build = spawnSync("bun", ["run", "build"], { cwd: app, encoding: "utf8" }); + if (build.status !== 0) throw new Error(build.stdout + build.stderr); + server = spawn("bunx", ["wrangler", "dev", "-c", "dist/server/wrangler.json", "--ip", "127.0.0.1", "--port", String(PORT)], { cwd: app, stdio: "ignore" }); + origin = `http://127.0.0.1:${PORT}`; + for (let i = 0; ; i++) { + try { + if ((await fetch(`${origin}/`)).ok) break; + } catch { + if (i > 120) throw new Error("wrangler dev did not start"); + } + await new Promise(r => setTimeout(r, 500)); + } + } + browser = await chromium.launch(); +}, 240_000); + +afterAll(async () => { + await browser?.close(); + server?.kill(); +}); + +interface Opened { + page: Page; + errors: string[]; + /** Document requests after the first: a full page load. */ + documents: string[]; +} + +async function open(path: string, options: BrowserContextOptions = {}): Promise { + const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, colorScheme: "light", ...options }); + const page = await context.newPage(); + const errors: string[] = []; + const documents: string[] = []; + page.on("pageerror", e => errors.push(e.message)); + page.on("console", m => m.type() === "error" && errors.push(m.text())); + await page.goto(origin + path, { waitUntil: "load" }); + page.on("request", r => r.resourceType() === "document" && r.frame() === page.mainFrame() && documents.push(r.url())); + return { page, errors, documents }; +} + +/** Clicks a link and waits until the router has swapped in its page. */ +async function follow(page: Page, selector: string): Promise { + const before = await page.evaluate(() => location.href); + const loaded = page.evaluate(() => new Promise(r => document.addEventListener("astro:page-load", () => r(), { once: true }))); + await page.locator(selector).first().click(); + await loaded; + expect(await page.evaluate(() => location.href)).not.toBe(before); +} + +async function afterLoad(page: Page, action: () => Promise): Promise { + const loaded = page.evaluate(() => new Promise(r => document.addEventListener("astro:page-load", () => r(), { once: true }))); + await action(); + await loaded; +} + +describe("client router", () => { + test("links, back and forward swap pages without a document load", async () => { + const { page, errors, documents } = await open(TYPE); + await page.evaluate(() => ((window as unknown as { marker: number }).marker = 1)); + await follow(page, `.sidebar a[href="${OTHER}"]`); + expect(await page.locator("h1").textContent()).toContain("Shapes"); + await afterLoad(page, () => page.goBack()); + expect(new URL(page.url()).pathname).toBe(TYPE); + expect(await page.locator("h1").textContent()).toContain("Circle"); + await afterLoad(page, () => page.goForward()); + expect(new URL(page.url()).pathname).toBe(OTHER); + expect(await page.evaluate(() => (window as unknown as { marker?: number }).marker)).toBe(1); + expect(documents).toEqual([]); + expect(errors).toEqual([]); + await page.context().close(); + }); + + test("back restores the scroll position", async () => { + const { page } = await open("/java/2.0/com/example/geo/registry/ShapeCatalog"); + await page.evaluate(() => window.scrollTo(0, 1500)); + await page.waitForTimeout(100); + await follow(page, `.sidebar a[href="/java/2.0/com/example/geo/"]`); + expect(await page.evaluate(() => scrollY)).toBe(0); + await afterLoad(page, () => page.goBack()); + expect(await page.evaluate(() => scrollY)).toBe(1500); + await page.context().close(); + }); + + test("the route change is announced, and focus leaves the old page", async () => { + const { page } = await open(TYPE); + await follow(page, `.content a[href="/java/2.0/com/example/geo/Shape"]`); + await page.waitForFunction(() => document.querySelector(".astro-route-announcer")?.textContent === document.title); + expect(await page.evaluate(() => document.activeElement === document.body || !!document.activeElement?.closest(".topbar, .sidebar"))).toBe(true); + await page.context().close(); + }); + + test("a keyboard user who follows a navigator row keeps focus on that row", async () => { + const { page } = await open(TYPE); + await page.locator(`.sidebar a[href="${OTHER}"]`).focus(); + await afterLoad(page, () => page.keyboard.press("Enter")); + expect(await page.evaluate(() => document.activeElement?.getAttribute("href"))).toBe(OTHER); + expect(await page.evaluate(() => document.activeElement?.getAttribute("aria-current"))).toBe("page"); + await page.context().close(); + }); + + test("hovering a link prefetches its page", async () => { + const { page } = await open(TYPE); + const fetched = page.waitForRequest(r => r.url() === `${origin}/java/2.0/com/example/geo/Units`, { timeout: 5000 }); + await page.locator(`.sidebar a[href="/java/2.0/com/example/geo/Units"]`).hover(); + await fetched; + await page.context().close(); + }); +}); + +describe("the persisted top bar and navigator", () => { + test("the navigator keeps its scroll position and filter text, and shows the new page as current", async () => { + const { page } = await open(TYPE, { viewport: { width: 1440, height: 500 } }); + const nav = page.locator("#apidocs-nav"); + await page.locator("#apidocs-nav-filter").fill("sha"); + // Scroll so the row to follow is in view, then follow it without Playwright scrolling anything. + await nav.evaluate((n, href) => (n.scrollTop = (n.querySelector(`a[href="${href}"]`) as HTMLElement).offsetTop - 120), OTHER); + await page.waitForTimeout(50); + const top = await nav.evaluate(n => n.scrollTop); + expect(top).toBeGreaterThan(0); + await afterLoad(page, () => page.evaluate(href => (document.querySelector(`.sidebar a[href="${href}"]`) as HTMLAnchorElement).click(), OTHER)); + expect(await nav.evaluate(n => n.scrollTop)).toBe(top); + expect(await page.locator("#apidocs-nav-filter").inputValue()).toBe("sha"); + expect(await page.locator('.sidebar [aria-current="page"]').getAttribute("href")).toBe(OTHER); + // The filter applies to the new page's rows: Units does not match "sha". + expect(await page.locator(`.sidebar a[href="/java/2.0/com/example/geo/Units"]`).isVisible()).toBe(false); + await page.context().close(); + }); + + test("the index links follow the page", async () => { + const { page } = await open(TYPE); + await follow(page, '.topbar-nav a[href="/java/2.0/packages"]'); + expect(await page.locator('.topbar-nav [aria-current="page"]').getAttribute("href")).toBe("/java/2.0/packages"); + await page.context().close(); + }); + + test("the elements are the same objects after a navigation", async () => { + const { page } = await open(TYPE); + await page.evaluate(() => ((window as unknown as { kept: Element[] }).kept = [document.querySelector(".topbar")!, document.querySelector(".sidebar")!])); + await follow(page, `.sidebar a[href="${OTHER}"]`); + expect(await page.evaluate(() => (window as unknown as { kept: Element[] }).kept.every(e => e.isConnected))).toBe(true); + await page.context().close(); + }); +}); + +describe("behaviors across navigations", () => { + const pages = [TYPE, OTHER, "/java/2.0/com/example/geo/Units", "/java/2.0/guides/concepts", "/java/2.0/com/example/geo/"]; + + test("after ten navigations, every behavior works once, with no errors", async () => { + const { page, errors } = await open(TYPE); + for (let i = 1; i <= 10; i++) { + const target = pages[i % pages.length]!; + await afterLoad(page, () => page.evaluate(href => (document.querySelector(`a[href="${href}"]`) as HTMLAnchorElement).click(), target)); + } + await afterLoad(page, () => page.evaluate(href => (document.querySelector(`a[href="${href}"]`) as HTMLAnchorElement).click(), OTHER)); + // Theme switch: one click is one step (a duplicate listener would skip a mode). + await page.locator("[data-theme-switch]").click(); + expect(await page.evaluate(() => document.documentElement.dataset.theme)).toBe("light"); + await page.locator("[data-theme-switch]").click(); + expect(await page.evaluate(() => document.documentElement.dataset.theme)).toBe("dark"); + // Expand all: one click opens every member of the group. + const toggle = page.locator("[data-expand-all]").first(); + await toggle.click(); + expect(await toggle.getAttribute("aria-expanded")).toBe("true"); + expect(await page.locator("section.members").first().locator("details.member:not([open])").count()).toBe(0); + // The rail's filter narrows the rail to the entries that match. + const visible = () => page.locator(".toc-entries a:visible").count(); + const all = await visible(); + const first = (await page.locator(".toc-entries a").first().textContent())!.split("(")[0]!; + await page.locator("#apidocs-toc-filter").fill(first); + const narrowed = await visible(); + expect(narrowed).toBeGreaterThan(0); + expect(narrowed).toBeLessThan(all); + // The navigator toggle. + await page.locator(".nav-button").click(); + expect(await page.locator("#apidocs-nav").isVisible()).toBe(false); + await page.locator(".nav-button").click(); + // The table of contents follows the page. + await page.locator("#apidocs-toc-filter").fill(""); + await page.evaluate(() => document.querySelector("details.member:last-of-type")?.scrollIntoView()); + await page.waitForSelector('.toc a[aria-current="true"]'); + // Search: type, open a result through the router. + await page.locator("#apidocs-search").fill("ShapeCat"); + await page.locator("#apidocs-results [role=option]").first().waitFor(); + await afterLoad(page, () => page.locator("#apidocs-search").press("Enter")); + expect(new URL(page.url()).pathname).toBe("/java/2.0/com/example/geo/registry/ShapeCatalog"); + expect(await page.locator("#apidocs-search").inputValue()).toBe(""); + expect(errors).toEqual([]); + await page.context().close(); + }, 60_000); + + test("twenty navigations leave listener and node counts flat", async () => { + const { page } = await open(TYPE); + const cdp = await page.context().newCDPSession(page); + await cdp.send("Performance.enable"); + const sample = async () => { + await cdp.send("HeapProfiler.collectGarbage"); + const { metrics } = await cdp.send("Performance.getMetrics"); + const get = (name: string) => metrics.find(m => m.name === name)!.value; + return { listeners: get("JSEventListeners"), nodes: get("Nodes"), documents: get("Documents") }; + }; + // A router transition keeps the outgoing page alive until it ends, and a slow runner ends it late. Sample until + // three reads in a row agree, so the counts are those of the settled page; a real leak never settles lower. + const measure = async () => { + let last = await sample(); + for (let stable = 0, tries = 0; stable < 3 && tries < 40; tries++) { + await page.waitForTimeout(250); + const next = await sample(); + stable = JSON.stringify(next) === JSON.stringify(last) ? stable + 1 : 0; + last = next; + } + return last; + }; + const loop = async (n: number) => { + for (let i = 0; i < n; i++) { + await afterLoad(page, () => page.evaluate(href => (document.querySelector(`a[href="${href}"]`) as HTMLAnchorElement).click(), i % 2 ? TYPE : OTHER)); + } + }; + await loop(4); + await page.waitForTimeout(300); + const before = await measure(); + await loop(20); + await page.waitForTimeout(300); + const after = await measure(); + console.log(" listeners and nodes, after 4 and after 24 navigations:", before, after); + expect(after.listeners).toBeLessThanOrEqual(before.listeners); + expect(after.nodes).toBeLessThanOrEqual(before.nodes * 1.02); + expect(after.documents).toBeLessThanOrEqual(before.documents); + await page.context().close(); + }, 120_000); +}); + +describe("layout stability", () => { + async function shifts(page: Page): Promise { + return page.evaluate(() => (window as unknown as { cls: number }).cls); + } + const observe = () => { + (window as unknown as { cls: number }).cls = 0; + new PerformanceObserver(list => { + for (const entry of list.getEntries() as unknown as { value: number; hadRecentInput: boolean }[]) { + if (!entry.hadRecentInput) (window as unknown as { cls: number }).cls += entry.value; + } + }).observe({ type: "layout-shift", buffered: true }); + }; + + test("first load shifts nothing, with the version islands arriving after it", async () => { + const context = await browser.newContext({ viewport: { width: 1440, height: 900 } }); + const page = await context.newPage(); + await page.addInitScript(observe); + const box = async () => page.locator(".version-menu").first().boundingBox(); + await page.goto(origin + "/java/main/com/example/geo/Circle", { waitUntil: "domcontentloaded" }); + const fallback = await box(); + await page.waitForFunction(() => !!document.querySelector("details.version-menu .version-list a[href='/java/2.0/com/example/geo/Circle']")); + await page.waitForLoadState("networkidle"); + await page.evaluate(() => document.fonts.ready); + await page.waitForTimeout(500); + expect(await box()).toEqual(fallback); + expect(await shifts(page)).toBe(0); + await context.close(); + }); + + test("a navigation shifts nothing", async () => { + const { page } = await open("/java/main/com/example/geo/Circle"); + await page.evaluate(observe); + await page.waitForTimeout(300); + await follow(page, `.sidebar a[href="/java/main/com/example/geo/Shapes"]`); + await page.waitForLoadState("networkidle"); + await page.waitForTimeout(500); + expect(await shifts(page)).toBe(0); + await page.context().close(); + }); +}); + +describe("server islands", () => { + test("the version menu lists the versions and opens the same page in another one", async () => { + const { page, documents } = await open("/java/main/com/example/geo/Circle"); + await page.waitForSelector("details.version-menu .version-list", { state: "attached" }); + expect(await page.locator(".version-notice").textContent()).toContain("latest release is 2.0"); + await follow(page, `.sidebar a[href="/java/main/com/example/geo/Shapes"]`); + await page.locator("details.version-menu summary").click(); + // The menu was rendered for Circle; its links now point at the page being read. + expect(await page.locator(".version-list a").first().getAttribute("href")).toBe("/java/2.0/com/example/geo/Shapes"); + await follow(page, '.version-list a[href="/java/2.0/com/example/geo/Shapes"]'); + expect(new URL(page.url()).pathname).toBe("/java/2.0/com/example/geo/Shapes"); + await page.waitForSelector("details.version-menu .version-list", { state: "attached" }); + expect(await page.locator("details.version-menu summary").textContent()).toContain("2.0"); + expect(await page.locator(".version-notice").count()).toBe(0); + expect(await page.locator('.sidebar a[aria-current="page"]').getAttribute("href")).toBe("/java/2.0/com/example/geo/Shapes"); + expect(documents).toEqual([]); + await page.context().close(); + }); +}); + +describe("JavaScript off", () => { + test("pages are complete, links work, and the islands' fallbacks stand in", async () => { + const { page } = await open("/java/main/com/example/geo/Circle", { javaScriptEnabled: false }); + expect(await page.locator("h1").textContent()).toContain("Circle"); + expect(await page.locator("details.member").count()).toBeGreaterThan(3); + expect(await page.locator(".toc a").count()).toBeGreaterThan(5); + for (const control of await page.locator("[data-js-only]").all()) expect(await control.isVisible()).toBe(false); + // The fallbacks: a working version menu and the notice, from the versions known when the page rendered. + expect(await page.locator(".version-notice").textContent()).toContain("2.0"); + await page.locator("details.version-menu summary").click(); + await page.locator('.version-list a[href="/java/2.0/com/example/geo/Circle"]').click(); + await page.waitForURL(`${origin}/java/2.0/com/example/geo/Circle`); + await page.locator(`.sidebar a[href="${OTHER}"]`).click(); + await page.waitForURL(origin + OTHER); + expect(await page.locator("h1").textContent()).toContain("Shapes"); + await page.context().close(); + }); +}); + +describe("reduced motion", () => { + test("no transition or load bar animates, and navigation still works", async () => { + const { page } = await open(TYPE, { reducedMotion: "reduce" }); + expect(await page.locator(".loadbar").evaluate(e => getComputedStyle(e).display)).toBe("none"); + const animated = page.evaluate(() => new Promise(resolve => { + const seen = new Set(); + const watch = () => { + for (const a of document.getAnimations()) if ((a.effect as KeyframeEffect | null)?.getComputedTiming().duration) seen.add(String((a as CSSAnimation).animationName ?? a.id)); + }; + const timer = setInterval(watch, 5); + document.addEventListener("astro:page-load", () => { + watch(); + clearInterval(timer); + resolve([...seen]); + }, { once: true }); + })); + await page.locator(`.sidebar a[href="${OTHER}"]`).click(); + expect(await animated).toEqual([]); + expect(await page.locator("h1").textContent()).toContain("Shapes"); + await page.context().close(); + }); +}); + +describe("accessibility", () => { + for (const colorScheme of ["light", "dark"] as const) { + for (const path of [TYPE, "/java/2.0/guides/concepts", "/java/2.0/index-all", "/java/main/com/example/geo/", "/guides/"]) { + test(`${path} in ${colorScheme} has no axe violations`, async () => { + const { page } = await open(path, { colorScheme }); + await page.waitForLoadState("networkidle"); + await page.addScriptTag({ path: require.resolve("axe-core/axe.min.js") }); + const violations = await page.evaluate(async () => { + const result = await (window as unknown as { axe: { run: (o: object) => Promise<{ violations: { id: string; nodes: { target: string[] }[] }[] }> } }) + .axe.run({ runOnly: { type: "tag", values: ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "best-practice"] } }); + return result.violations.map(v => `${v.id}: ${v.nodes.slice(0, 3).map(n => n.target.join(" ")).join(", ")}`); + }); + expect(violations).toEqual([]); + await page.context().close(); + }, 30_000); + } + } +}); + +describe("metadata", () => { + test("a served page's head metadata is the static renderer's, apart from the URL form", async () => { + const baseUrl = `${origin}/java/2.0/`; + const page = "com/example/geo/Circle"; + const served = await (await fetch(`${baseUrl}${page}`)).text(); + const staticHtml = render(samples.java, { extends: "elide", baseUrl })[`${page}.html`] as string; + const ctx = { page, base: "/java/2.0/", baseUrl }; + const metadata = (html: string, map: (u: string) => string | undefined) => { + const head = html.split("")[1]!.split("")[0]!; + return { + title: /(.*?)<\/title>/.exec(head)?.[1], + meta: [...head.matchAll(/<meta (?:name|property)="(description|keywords|generator|apidocs:[a-z]+|og:[a-z_]+|twitter:card)" content="([^"]*)"\/?>/g)].map(m => [m[1], m[1] === "og:url" ? map(m[2]!) : m[2]]), + links: [...head.matchAll(/<link rel="(canonical|alternate|index)"[^>]*? href="([^"]*)"/g)].map(m => [m[1], map(m[2]!)]), + jsonLd: JSON.parse(/<script type="application\/ld\+json">(.*?)<\/script>/.exec(head)![1]!, (key, value) => (["url", "item", "contentUrl"].includes(key) ? map(value) : value)), + }; + }; + expect(metadata(served, u => u)).toEqual(metadata(staticHtml, u => mapUrl(u, ctx))); + }); + + test("text files are served with their types; the static form redirects", async () => { + const at = (path: string) => fetch(`${origin}${path}`, { redirect: "manual" }); + expect((await at("/java/2.0/llms.txt")).headers.get("content-type")).toContain("text/plain"); + expect((await at("/java/2.0/com/example/geo/Circle.md")).headers.get("content-type")).toContain("text/markdown"); + const redirect = await at("/java/2.0/com/example/geo/Circle.html"); + expect(redirect.status).toBe(301); + expect(redirect.headers.get("location")).toBe("/java/2.0/com/example/geo/Circle"); + expect((await at("/java/2.0/com/example/geo/Nope")).status).toBe(404); + }); +}); diff --git a/apps/apidocs-astro/tsconfig.json b/apps/apidocs-astro/tsconfig.json new file mode 100644 index 0000000..03d805d --- /dev/null +++ b/apps/apidocs-astro/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "astro/tsconfigs/strict", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "preact", + "types": [ + "bun" + ], + "verbatimModuleSyntax": false + }, + "include": [ + ".astro/types.d.ts", + "src", + "test", + "scripts", + "*.mjs" + ], + "exclude": [ + "dist" + ] +} diff --git a/apps/apidocs-astro/wrangler.jsonc b/apps/apidocs-astro/wrangler.jsonc new file mode 100644 index 0000000..2e80a66 --- /dev/null +++ b/apps/apidocs-astro/wrangler.jsonc @@ -0,0 +1,9 @@ +// The sample app as a Worker, for `wrangler dev` (bun run apidocs:astro:preview). It is never deployed. +{ + "name": "apidocs-astro-sample", + // The newest date the pinned wrangler's workerd supports; the adapter's default is newer. + "compatibility_date": "2026-11-04", + "compatibility_flags": ["nodejs_compat"], + "workers_dev": false, + "preview_urls": false +} diff --git a/bun.lock b/bun.lock index 872db84..d2ffe5b 100644 --- a/bun.lock +++ b/bun.lock @@ -14,6 +14,24 @@ "typescript": "^7.0.2", }, }, + "apps/apidocs-astro": { + "name": "@elide/apidocs-astro", + "version": "0.0.0", + "dependencies": { + "@astrojs/cloudflare": "14.4.4", + "@astrojs/preact": "6.1.6", + "@elide/apidocs": "workspace:*", + "astro": "7.4.7", + "preact": "^11.2.0", + }, + "devDependencies": { + "@types/bun": "^1.3.0", + "axe-core": "4.14.0", + "playwright": "^1.65.0", + "typescript": "^7.0.2", + "wrangler": "4.157.0", + }, + }, "apps/benchmark": { "name": "@elide/benchmark", "version": "0.0.0", @@ -112,6 +130,48 @@ "vitest": "^5.1.0", }, }, + "packages/apidocs": { + "name": "@elide/apidocs", + "version": "0.0.0", + "bin": { + "apidocs": "./src/cli.ts", + }, + "dependencies": { + "@elide/brand": "workspace:*", + "@elide/tokens": "workspace:*", + "@fontsource-variable/instrument-sans": "^5.3.0", + "@fontsource-variable/inter": "^5.3.0", + "@fontsource-variable/jetbrains-mono": "^5.3.0", + "preact": "^11.2.0", + "preact-render-to-string": "^6.8.2", + }, + "devDependencies": { + "@astrojs/preact": "6.1.6", + "@types/bun": "^1.3.0", + "@types/mdast": "4.0.4", + "astro": "7.4.7", + "axe-core": "4.14.0", + "chrome-launcher": "1.2.3", + "lighthouse": "13.6.0", + "mdast-util-from-markdown": "2.1.0", + "mdast-util-gfm": "3.1.0", + "micromark-extension-gfm": "3.0.0", + "node-html-parser": "6.1.13", + "playwright": "^1.65.0", + "postcss": "8.5.32", + "typescript": "^7.0.2", + "vite": "^8.3.6", + "yaml": "2.9.1", + }, + "peerDependencies": { + "@astrojs/preact": "^6.1.6", + "astro": "^7.4.7", + }, + "optionalPeers": [ + "@astrojs/preact", + "astro", + ], + }, "packages/brand": { "name": "@elide/brand", "version": "0.2.0", @@ -229,6 +289,48 @@ "@adobe/css-tools": ["@adobe/css-tools@4.5.0", "", {}, "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q=="], + "@astrojs/cloudflare": ["@astrojs/cloudflare@14.4.4", "", { "dependencies": { "@astrojs/internal-helpers": "0.13.0", "@astrojs/underscore-redirects": "1.0.4", "@cloudflare/vite-plugin": "^1.63.1", "piccolore": "^0.1.3", "prismjs": "^1.30.0", "vite": "^8.3.4" }, "peerDependencies": { "astro": "^7.4.0", "wrangler": "^4.125.0" } }, "sha512-VC7BVACFSNNKevbuDftzmhwW+9yYy5cqplrBwPBeGa9Nojj6pXyIxMGIyIwhAyZWuRchqwCh7KDhb015oXaoKg=="], + + "@astrojs/compiler-binding": ["@astrojs/compiler-binding@0.5.3", "", { "optionalDependencies": { "@astrojs/compiler-binding-android-arm64": "0.5.3", "@astrojs/compiler-binding-darwin-arm64": "0.5.3", "@astrojs/compiler-binding-darwin-x64": "0.5.3", "@astrojs/compiler-binding-linux-arm64-gnu": "0.5.3", "@astrojs/compiler-binding-linux-arm64-musl": "0.5.3", "@astrojs/compiler-binding-linux-x64-gnu": "0.5.3", "@astrojs/compiler-binding-linux-x64-musl": "0.5.3", "@astrojs/compiler-binding-wasm32-wasi": "0.5.3", "@astrojs/compiler-binding-win32-arm64-msvc": "0.5.3", "@astrojs/compiler-binding-win32-x64-msvc": "0.5.3" } }, "sha512-fHG6eWKvnSlV11dUMZSi4AynOGjVbNBgZZc704Hi9DW8WeKtbsS7fJQT3omz1Nba+5mccLQQGAWOQ65cnuNLtg=="], + + "@astrojs/compiler-binding-android-arm64": ["@astrojs/compiler-binding-android-arm64@0.5.3", "", { "os": "android", "cpu": "arm64" }, "sha512-ThyoCqtrdp6UwmMvScluDll4vvj4kXwUPKHYozLbXJKPH5zrJ8sr5xQJVOk0YvgBrCvGBA/lPVVLyEp1aLuBYg=="], + + "@astrojs/compiler-binding-darwin-arm64": ["@astrojs/compiler-binding-darwin-arm64@0.5.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-zMI4ndCVCd0Wsrm8sXVcIk6uviKsgndFLnxqNd6Qx26LINSkb0lQ7SL8gKyGcTu0hJRTBwl7Y1WcpMk37aeaKQ=="], + + "@astrojs/compiler-binding-darwin-x64": ["@astrojs/compiler-binding-darwin-x64@0.5.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-Ce51oGlDgBAwoVOy5Y4FeIqFkXbS/vJkIAPN5pXIYchn/3izF4c2t//KuUZJopwzD6Kblj46kKiqmxRUt/mAJg=="], + + "@astrojs/compiler-binding-linux-arm64-gnu": ["@astrojs/compiler-binding-linux-arm64-gnu@0.5.3", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-WCBGgpmUqbuWW3KAsNOKRXDeQIAeQLftZhZ+CNyl3eg4JtkfZRXHav2qItzVg6ODyzmS2e+QkpgsQuwMSInGgA=="], + + "@astrojs/compiler-binding-linux-arm64-musl": ["@astrojs/compiler-binding-linux-arm64-musl@0.5.3", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-DRcjEOFWcMbaaTsbOEferYozr2zDUf/roDzcF6WxHSSto+rqZ1N87xxj/pjOpz0JtTBlZ3V59nZGONcNiQUSWw=="], + + "@astrojs/compiler-binding-linux-x64-gnu": ["@astrojs/compiler-binding-linux-x64-gnu@0.5.3", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-8rIMmEFtuVe5mMvwBR59uSHZL7CaJ/CPm5Hh3r3Bd5JLoSPkBbl1xk8kwUkNKJ0QSbGEFdWkUnx73JRZq46i2A=="], + + "@astrojs/compiler-binding-linux-x64-musl": ["@astrojs/compiler-binding-linux-x64-musl@0.5.3", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-+sZCsIXq/PQBiemALIr+GbERKQbQ82mHW2ibJUlCDtsjyFA/8Udm8WGZhS7AGjb2P9ekQ4j7Z8dbxb0f3E0oZw=="], + + "@astrojs/compiler-binding-wasm32-wasi": ["@astrojs/compiler-binding-wasm32-wasi@0.5.3", "", { "dependencies": { "@emnapi/core": "1.11.3", "@emnapi/runtime": "1.11.3", "@napi-rs/wasm-runtime": "^1.2.7" }, "cpu": "none" }, "sha512-cEhZ7XAoZYffJdNYb3MDWci1UKhSEjPN+DMaLEB8X1tKlhlYNw9eVWUyNZTe1gb3nr7JJBVXdXDioqE00dyVLQ=="], + + "@astrojs/compiler-binding-win32-arm64-msvc": ["@astrojs/compiler-binding-win32-arm64-msvc@0.5.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-Vcg6+NlU2SOmVGweQEmufu40MHuDuRR80dp9xNLutBWGdJG1HP0XivjGWKGkx/2EK3HN5rwB2NwPgBNDkhKsnQ=="], + + "@astrojs/compiler-binding-win32-x64-msvc": ["@astrojs/compiler-binding-win32-x64-msvc@0.5.3", "", { "os": "win32", "cpu": "x64" }, "sha512-Mt5bK4l5ZcUdNcVxJ7VVt2x5Ck46cXgxCmIhT8sVyUST04FBRYqcYTXQLvy1Py4ejglcWRxAS6z+jBVHs3LPfg=="], + + "@astrojs/compiler-rs": ["@astrojs/compiler-rs@0.5.3", "", { "dependencies": { "@astrojs/compiler-binding": "0.5.3" } }, "sha512-rNSAYm5IcRJMpNm+cSMaaPNCmzCXIdiz67kcBwC1qN8eTmO48wEJ6hZdlGq60+0HIHwUlncfaMxti1Fk2uJu7w=="], + + "@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.13.2", "", { "dependencies": { "@types/hast": "^3.0.5", "@types/mdast": "^4.0.4", "picomatch": "^4.0.7", "retext-smartypants": "^6.2.0", "shiki": "^4.6.0", "smol-toml": "^1.9.1", "unified": "^11.0.5", "yaml": "^2.9.1" } }, "sha512-SWiNS+OMrhwWYzJENTekHUyUCMKB+tdU6D4v1ZNIU1ZHh2mScQ8WIs0J6AJ8KPXkIrs9+EZU7Rm2CstfThyVnw=="], + + "@astrojs/markdown-satteri": ["@astrojs/markdown-satteri@0.4.7", "", { "dependencies": { "@astrojs/internal-helpers": "0.13.1", "@astrojs/prism": "4.1.2", "github-slugger": "^2.0.0", "satteri": "^0.11.6" } }, "sha512-MZvnec/898GGGHQZfkArVbkdZmL1imjIM8RWkmzbAmse737zr8D9inUjFQ5eLBXV3vPobOUs/ZRV/D6Po/bVDg=="], + + "@astrojs/preact": ["@astrojs/preact@6.1.6", "", { "dependencies": { "@astrojs/internal-helpers": "^0.13.2", "@astrojs/preact-renderer": "^0.1.3", "@preact/preset-vite": "^2.10.6" }, "peerDependencies": { "preact": "^10.6.5 || ^11.0.0" } }, "sha512-eFxWZTyAhT4YX2wU4pQkZFUruI2LGIVUmH0eoXFlZ+Wy5K5+dnfB8V98yYXV67flPnaI3cps9ZMiIIaJQMDkmQ=="], + + "@astrojs/preact-renderer": ["@astrojs/preact-renderer@0.1.3", "", { "dependencies": { "@astrojs/internal-helpers": "^0.13.2", "@astrojs/runtime": "^0.1.1", "@preact/signals": "^2.11.4", "preact-render-to-string": "^6.8.2" }, "peerDependencies": { "preact": "^10.6.5 || ^11.0.0" } }, "sha512-I2pNexVHD/X8U8L1V9vI2fjCdCamL7ljEcVIRHVpF3cXq2CubPQjJKafuhfaeflLN0RFHbZI/CklUDcHocqdzg=="], + + "@astrojs/prism": ["@astrojs/prism@4.1.2", "", { "dependencies": { "prismjs": "^1.30.0" } }, "sha512-jMrUEpFDarDO1KWPvVc9eSa8DSfwBlwEOHwX+8zvZQpiqXRGDxFnOXHsYqV6DP7w+0qIgTr98gS1GdQlm8ypWg=="], + + "@astrojs/runtime": ["@astrojs/runtime@0.1.2", "", { "dependencies": { "@oslojs/encoding": "^1.1.0", "clsx": "^2.1.1" } }, "sha512-qLNoKPjASZmKtkvQNYqax7DHIe5+0TC1PX8n2AkA87Bv+JxiaFZtPepdm0lwcRbL/jLoiRvHXVCliFC1CRFQxA=="], + + "@astrojs/telemetry": ["@astrojs/telemetry@3.4.2", "", { "dependencies": { "ci-info": "^4.4.0", "dset": "^3.1.4", "is-docker": "^4.0.0", "package-manager-detector": "^1.9.0" } }, "sha512-2JOMRUxJrBSfiVDfeKLv1wBmvSIx1Y6u2YEO8awZ9qSq3u/rNAiUyFdOYi8dHv91kHrmYEQX7pRDw0J4xyj3UA=="], + + "@astrojs/underscore-redirects": ["@astrojs/underscore-redirects@1.0.4", "", {}, "sha512-sD3bn7i2yC+ocxlhCTshdg3gUM471Nag3wgyHilA+kpmufokvmUu1p5Mw5GT5Xp8SPC1Nlq0BJAgV/lslnWvRw=="], + "@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], "@babel/compat-data": ["@babel/compat-data@7.29.7", "", {}, "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg=="], @@ -299,10 +401,34 @@ "@blazediff/core": ["@blazediff/core@1.10.0", "", {}, "sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ=="], + "@bruits/satteri-android-arm64": ["@bruits/satteri-android-arm64@0.11.7", "", { "os": "android", "cpu": "arm64" }, "sha512-ej+1rIKs+yb6/OtcIe1SO22OXjJV0qqUopl5VNZF8Sqc/Pj4m1DXoqBQsPxW5OUYYiDUymIy6hnnn8M78VYk2w=="], + + "@bruits/satteri-darwin-arm64": ["@bruits/satteri-darwin-arm64@0.11.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-yllQOX1kVWrwqL7tamQlp4NP0loIb4KuadjuNrAe4JEOerHpgYISPRDb8DqLipgvP7Ks4e87LydZpdakMR1rhQ=="], + + "@bruits/satteri-darwin-x64": ["@bruits/satteri-darwin-x64@0.11.7", "", { "os": "darwin", "cpu": "x64" }, "sha512-RMQrKzEZRZSiYyLFifiSuk0nBH6uAY1TVMNR/h/aE4rr2OS6l82e4MJTpC6H/tqSMoE+3CwbkUKBQGLHIweYlg=="], + + "@bruits/satteri-freebsd-x64": ["@bruits/satteri-freebsd-x64@0.11.7", "", { "os": "freebsd", "cpu": "x64" }, "sha512-EFlqw+RDRo3wYdy1ZSR/dNYhfWjuZL86PYwRcpLWWEZskjfpNnhIdxS13Xw2QJE1hSjTGVq4aZaVvlUjoj8p5A=="], + + "@bruits/satteri-linux-arm64-gnu": ["@bruits/satteri-linux-arm64-gnu@0.11.7", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-aeH365GHaqv01wRSiHaGUlpL28U8e9UnV9LxjIF6BOyTj71/M5bop4HKomcis4VxFZjd68fDqNyU22yFkF/h7A=="], + + "@bruits/satteri-linux-arm64-musl": ["@bruits/satteri-linux-arm64-musl@0.11.7", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-72WlBhuwOHm+2Nv4Qf1WzfS75PHOLz81sYkDJnmj0Rm2C4Xax5faSiTDt7vWo1IcK6rDlkuRDNnWIw8uIKWuVQ=="], + + "@bruits/satteri-linux-x64-gnu": ["@bruits/satteri-linux-x64-gnu@0.11.7", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-gDp4v1jjckeNCetLtrMUfDV4CKGYL6fayDPdoaQq09nkDCSrclxEFK7kAmRuHhoalgsao4bZMFqQr3HQtN2NEQ=="], + + "@bruits/satteri-linux-x64-musl": ["@bruits/satteri-linux-x64-musl@0.11.7", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-zqzSpQLA6V3J/TO2Vjuc1VRQPIQQdoSYmzKKFL+3GwGlbXiFQP2ZUDSLw9xlm0tTKXkCM9ANr4jMiDASZ+JGUw=="], + + "@bruits/satteri-wasm32-wasi": ["@bruits/satteri-wasm32-wasi@0.11.7", "", { "dependencies": { "@emnapi/core": "1.11.1", "@emnapi/runtime": "1.11.1", "@napi-rs/wasm-runtime": "^1.2.7" }, "cpu": "none" }, "sha512-L46f6rtlaBR4fsTWGCTFcXtbtka2GyM3l9TsmE0FgTxjXGq+sndYg5X3hzlhWDkNvJpRtCHCmgTRJ5+cIi4o3A=="], + + "@bruits/satteri-win32-arm64-msvc": ["@bruits/satteri-win32-arm64-msvc@0.11.7", "", { "os": "win32", "cpu": "arm64" }, "sha512-R2+o6EbJK4pqbd086H9BGUVYAyZ5F6FnShfoyRIu0Zu9DTE3H6EU/Z+ua7p9dmYf6JQQbE9DCwwavi4xiaGAhQ=="], + + "@bruits/satteri-win32-x64-msvc": ["@bruits/satteri-win32-x64-msvc@0.11.7", "", { "os": "win32", "cpu": "x64" }, "sha512-OIyBFJ35uMu5CH5RWnIR3bKsZwScKZ7vXmhCohZ+qonT1SkxmHCEf4H8YRWThRL2EXdVDjkjhfOsaiA4O24Vvw=="], + "@cacheable/memory": ["@cacheable/memory@2.2.0", "", { "dependencies": { "@cacheable/utils": "^2.5.0", "@keyv/bigmap": "^1.3.1", "hookified": "^1.15.1", "keyv": "^5.6.0" } }, "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ=="], "@cacheable/utils": ["@cacheable/utils@2.5.0", "", { "dependencies": { "hashery": "^1.5.1", "keyv": "^5.6.0" } }, "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA=="], + "@capsizecss/unpack": ["@capsizecss/unpack@4.0.1", "", { "dependencies": { "fontkitten": "^1.0.3" } }, "sha512-CuNiSqg7+e1cO/GjffyMOm5Tt2jUF9CWHHnvQ/UkqvtkGfHdgwEC0wpmq7fkN3gxwpRnrAN0WzO3vREKmNolMQ=="], + "@changesets/apply-release-plan": ["@changesets/apply-release-plan@8.1.1", "", { "dependencies": { "@changesets/config": "^4.0.1", "@changesets/format": "^0.1.2", "@changesets/git": "^4.0.1", "@changesets/should-skip-package": "^1.0.0", "@changesets/types": "^7.0.0", "import-meta-resolve": "^4.2.0", "jsonc-parser": "^3.3.1", "semver": "^7.8.1" } }, "sha512-nk2Hbq3M9NeHMdaIRBDvawKrQJzXB9sGyBUE5yWnIKtvdcNCPj75zBekJYr0gTT2ecJH3eFeTrc8eisPImcv0Q=="], "@changesets/assemble-release-plan": ["@changesets/assemble-release-plan@7.0.0", "", { "dependencies": { "@changesets/errors": "^1.0.0", "@changesets/get-dependents-graph": "^3.0.0", "@changesets/should-skip-package": "^1.0.0", "@changesets/types": "^7.0.0", "semver": "^7.8.1" } }, "sha512-oEW8BxdA604kGGtDSCiHr5w9Tv4UWe9I2k61IBNZzCOE1kbYaJj4v+lFQNgcEZFkUc2pV/+hASErGDvpJOZCTg=="], @@ -339,14 +465,36 @@ "@clack/prompts": ["@clack/prompts@1.8.1", "", { "dependencies": { "@clack/core": "1.5.1", "fast-string-width": "^3.0.2", "fast-wrap-ansi": "^0.2.0", "sisteransi": "^1.0.5" } }, "sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ=="], + "@cloudflare/kv-asset-handler": ["@cloudflare/kv-asset-handler@0.5.0", "", {}, "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg=="], + + "@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.16.2", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": ">1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ=="], + + "@cloudflare/vite-plugin": ["@cloudflare/vite-plugin@1.70.1", "", { "dependencies": { "@cloudflare/unenv-preset": "2.16.2", "miniflare": "5.20261117.0-beta", "unenv": "2.0.0-rc.24", "wrangler": "4.164.0", "ws": "8.22.0" }, "peerDependencies": { "vite": "^6.1.0 || ^7.0.0 || ^8.0.0" } }, "sha512-a17DWG4xPeIpdSAOrF4QwTPQhSAiRzKLU5kr7/aNWrHt4xC/SAIDGX2JYq1v4mG53XxWvoaM2c3jlZeRGuo7/Q=="], + + "@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20261103.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-6lWDetzg9mclXUVv/u6/WQWzuJ96cgBqnQ+kEhqckm5TE6FPUkXkCmjMfyIt0qff6aWhhrtYxEfcE2e1X1i4nQ=="], + + "@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20261103.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-dtsvzndPMoGK9zHCq/pCIekywDsY1RLcBWZnzK2iL7L4jVvJVsBeRe3a+3lMgIRyM4HcelnJup7tT+2s3WYxHw=="], + + "@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20261103.1", "", { "os": "linux", "cpu": "x64" }, "sha512-g++gRXeum4QXseRgX7/X8RHH+A/wzypgslqVnOzttLjpmw3l+XXRo85S+ct1yYfOsQrlh1II+y3HYbdn2Goxvg=="], + + "@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20261103.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-zvVXyJ8h68MVBYboxqZaemdmbvjjNPlZTeKDrwlaaVYaDBWTRsiPjRunEwNtlYF/Zq1IXYEEgkNo4xGAEg+qiQ=="], + + "@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20261103.1", "", { "os": "win32", "cpu": "x64" }, "sha512-g7zu5yaJyxPsVAn/WChF3vu0PheeIh/7HCJ3WTOGKshWCcwv1jUs/+Y13cR3srOQ1CGvJSDJoJXrAixQ2M4+IA=="], + "@codecov/bundler-plugin-core": ["@codecov/bundler-plugin-core@2.0.1", "", { "dependencies": { "@actions/core": "^3.0.0", "@actions/github": "^9.0.0", "chalk": "4.1.2", "semver": "^7.5.4", "unplugin": "^1.10.1", "zod": "^3.22.4" } }, "sha512-TkdKn/rEwZQ723M7DDUmHe5r0IJa23rUT4TAx5jXmg12wGZGAHGWWU7LKeQsYCsKdLMxK7bLaGk9M++4wSRD5w=="], "@codecov/vite-plugin": ["@codecov/vite-plugin@2.0.1", "", { "dependencies": { "@codecov/bundler-plugin-core": "^2.0.1", "unplugin": "^1.10.1" }, "peerDependencies": { "vite": "4.x || 5.x || 6.x" } }, "sha512-w7nGA9SSc0WECzn05yRrw3uN8293I620Kd9x97I0kyyxUjtWxCMmlgmAbS364gJZYvljd0A6iQyAigVV2dOX9A=="], + "@cspotcode/source-map-support": ["@cspotcode/source-map-support@0.8.1", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="], + "@dotenvx/dotenvx": ["@dotenvx/dotenvx@1.75.1", "", { "dependencies": { "@dotenvx/primitives": "^0.8.0", "commander": "^11.1.0", "conf": "^10.2.0", "dotenv": "^17.2.1", "enquirer": "^2.4.1", "env-paths": "^2.2.1", "execa": "^5.1.1", "fdir": "^6.2.0", "ignore": "^5.3.0", "object-treeify": "1.1.33", "open": "^8.4.2", "picomatch": "^4.0.4", "systeminformation": "^5.22.11", "undici": "^7.11.0", "which": "^4.0.0", "yocto-spinner": "^1.1.0" }, "bin": { "dotenvx": "src/cli/dotenvx.js" } }, "sha512-/BITOC9dmS/edY2zQwZNicQ059O6RKabtQfyEafV0nGtfYRNHYy1DIPiYVcov40+tob9hfmBnbR963dS+EQ1DQ=="], "@dotenvx/primitives": ["@dotenvx/primitives@0.8.0", "", {}, "sha512-VYJy0uhFm9zTJ1TxBaW/pA8bjbOM/OttaNMwZ1RHG4JKyRG7DhSdiqD1ipQoAyoD22olUtxbP78W9xY3Wd11bg=="], + "@elide/apidocs": ["@elide/apidocs@workspace:packages/apidocs"], + + "@elide/apidocs-astro": ["@elide/apidocs-astro@workspace:apps/apidocs-astro"], + "@elide/benchmark": ["@elide/benchmark@workspace:apps/benchmark"], "@elide/brand": ["@elide/brand@workspace:packages/brand"], @@ -539,7 +687,7 @@ "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], - "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.9", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ=="], "@keyv/bigmap": ["@keyv/bigmap@1.3.1", "", { "dependencies": { "hashery": "^1.4.0", "hookified": "^1.15.0" }, "peerDependencies": { "keyv": "^5.6.0" } }, "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ=="], @@ -597,6 +745,8 @@ "@opentelemetry/api": ["@opentelemetry/api@1.10.0", "", {}, "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ=="], + "@oslojs/encoding": ["@oslojs/encoding@1.1.0", "", {}, "sha512-70wQhgYmndg4GCPxPPxPGevRKqTIJ2Nh4OkiMWmDAVYsTQ+Ta7Sq+rPevXyXGdzr30/qZBnyOalCszoMxlyldQ=="], + "@oxc-parser/binding-android-arm-eabi": ["@oxc-parser/binding-android-arm-eabi@0.127.0", "", { "os": "android", "cpu": "arm" }, "sha512-0LC7ye4hvqbIKxAzThzvswgHLFu2AURKzYLeSVvLdu2TBOYWQDmHnTqPLeA597BcUCxiLqLsS4CJ5uoI5WYWCQ=="], "@oxc-parser/binding-android-arm64": ["@oxc-parser/binding-android-arm64@0.127.0", "", { "os": "android", "cpu": "arm64" }, "sha512-b5jtVTH6AU5CJXHNdj7Jj9IEiR9yVjjnwHzPJhGyHGPdcsZSzBCkS9GBbV33niRMvKthDwQRFRJfI4a+k4PvYg=="], @@ -685,8 +835,18 @@ "@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="], + "@poppinss/colors": ["@poppinss/colors@4.1.6", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg=="], + + "@poppinss/dumper": ["@poppinss/dumper@0.6.5", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@sindresorhus/is": "^7.0.2", "supports-color": "^10.0.0" } }, "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw=="], + + "@poppinss/exception": ["@poppinss/exception@1.2.3", "", {}, "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw=="], + "@preact/preset-vite": ["@preact/preset-vite@2.10.6", "", { "dependencies": { "@babel/plugin-transform-react-jsx": "^7.27.1", "@babel/plugin-transform-react-jsx-development": "^7.27.1", "@prefresh/vite": "^2.4.11", "@rollup/pluginutils": "^5.0.0", "babel-plugin-transform-hook-names": "^1.0.2", "debug": "^4.4.3", "magic-string": "^0.30.21", "picocolors": "^1.1.1", "vite-prerender-plugin": "^0.5.8", "zimmerframe": "^1.1.4" }, "peerDependencies": { "@babel/core": "7.x", "vite": "2.x || 3.x || 4.x || 5.x || 6.x || 7.x || 8.x" } }, "sha512-ZZ5RIT2ZVXg8UxRA8VZpoT8CdpDG7RFIqOT4bELqNBp85+HKvQBbgmh3gsoW1UOQXx26TLe+ZRNKI7q281Kckw=="], + "@preact/signals": ["@preact/signals@2.11.4", "", { "dependencies": { "@preact/signals-core": "^1.14.5" }, "peerDependencies": { "preact": ">= 10.25.0 || >=11.0.0-0" } }, "sha512-Rb+5RPo9gWSaHtzJeauhHxiC8KP/IF2DEPkHPEOGOnuy2wnJzRqyeLRankUCYd6ADqtxS6GnWGv6Ie343d8aYw=="], + + "@preact/signals-core": ["@preact/signals-core@1.14.5", "", {}, "sha512-vcRv7Ityz5JVmeiVqIluLFzT/PDS/AlhHUpw3/aUWqcVUs6bDGIPXE/6RSC4evBNWYvnniozg5Syfj33al3gkg=="], + "@prefresh/babel-plugin": ["@prefresh/babel-plugin@0.5.4", "", { "peerDependencies": { "@babel/core": "^7.0.0 || ^8.0.0" } }, "sha512-GSwqHGVem7AjnOKAkmLNbAExqZZFddf9S3ySOwowGEsJR8vwNKJ7Z/262fov5wra8LkDVSmFw3CjMGRdLoCmRA=="], "@prefresh/core": ["@prefresh/core@1.5.11", "", { "peerDependencies": { "preact": "^10.0.0 || ^11.0.0-0" } }, "sha512-Ml00PP8jeHaADxfQqxUs4+M5JS+T5J26UnvPVfsrmlpGw2I3e9XtM0DMeuzkmvg+Tn7VdHSMpLBrDPG0iHoDqQ=="], @@ -817,8 +977,12 @@ "@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.1.0", "", {}, "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ=="], + "@sindresorhus/is": ["@sindresorhus/is@7.2.0", "", {}, "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw=="], + "@sindresorhus/merge-streams": ["@sindresorhus/merge-streams@4.0.0", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="], + "@speed-highlight/core": ["@speed-highlight/core@1.2.24", "", {}, "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw=="], + "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], "@storybook/addon-a11y": ["@storybook/addon-a11y@10.6.6", "", { "dependencies": { "@storybook/global": "^5.0.0", "axe-core": "^4.2.0" }, "peerDependencies": { "storybook": "^10.6.6" } }, "sha512-+LdCNVDELDqYWWbWkMX8LH9CXxDXnizfzvyJUVfkdF5CPZFRZu1xpv+jvLBFEumw/sQmizPZUXlw8zbdO1jvEQ=="], @@ -909,8 +1073,12 @@ "@types/babel__traverse": ["@types/babel__traverse@7.28.0", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="], + "@types/bun": ["@types/bun@1.4.5", "", { "dependencies": { "bun-types": "1.4.5" } }, "sha512-DpgwNI9z0L1S0gtb45QLCWgwCUcMLnsHYMJHQvpNj7erGiCGBvpggltAIeARrtobNMKMuy0UP7i56tKKgwFs/Q=="], + "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], + "@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="], + "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], "@types/doctrine": ["@types/doctrine@0.0.9", "", {}, "sha512-eOIHzCUSH7SMfonMG1LsC2f8vxBFtho6NGBznK41R84YzPuvSBzrhEps33IsQiOW9+VL6NQ9DbjQJznk/S4uRA=="], @@ -919,12 +1087,18 @@ "@types/estree": ["@types/estree@1.0.10", "", {}, "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g=="], + "@types/estree-jsx": ["@types/estree-jsx@1.0.5", "", { "dependencies": { "@types/estree": "*" } }, "sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg=="], + "@types/hast": ["@types/hast@3.0.5", "", { "dependencies": { "@types/unist": "*" } }, "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g=="], "@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="], "@types/mdast": ["@types/mdast@4.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA=="], + "@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="], + + "@types/nlcst": ["@types/nlcst@2.0.3", "", { "dependencies": { "@types/unist": "*" } }, "sha512-vSYNSDe6Ix3q+6Z7ri9lyWqgGhJTmzRjZRqyq15N0Z/1/UnVsno9G/N40NBijoYx2seFDIl0+B2mgAb9mezUCA=="], + "@types/node": ["@types/node@26.6.6", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="], "@types/react": ["@types/react@19.3.0", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="], @@ -1043,6 +1217,8 @@ "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], + "am-i-vibing": ["am-i-vibing@0.5.0", "", { "dependencies": { "process-ancestry": "^0.1.0" }, "bin": { "am-i-vibing": "dist/cli.mjs" } }, "sha512-KLcsDhqf1XRrJmJr+9I/C0EX2K+sGrAGZFgkmd84c8TJO9zJBu+/kFInjazu1KfJWFhWDKdRWkpBzEs7s35DVA=="], + "ansi-colors": ["ansi-colors@4.1.3", "", {}, "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw=="], "ansi-regex": ["ansi-regex@6.6.0", "", {}, "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g=="], @@ -1051,6 +1227,8 @@ "any-promise": ["any-promise@1.3.0", "", {}, "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A=="], + "anymatch": ["anymatch@3.1.3", "", { "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" } }, "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw=="], + "aria-query": ["aria-query@5.3.2", "", {}, "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw=="], "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], @@ -1059,12 +1237,18 @@ "ast-v8-to-istanbul": ["ast-v8-to-istanbul@1.0.8", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.31", "estree-walker": "^3.0.3", "js-tokens": "^10.0.0" } }, "sha512-lPdpagk13ANXV+HClJEpCZM7kUsl5XcvgqKzZhaj6Ve1ZFICcY2sGhAN1n1vT0tML6EclT7bfVgTxqL57Gkpow=="], + "astro": ["astro@7.4.7", "", { "dependencies": { "@astrojs/compiler-rs": "^0.5.2", "@astrojs/internal-helpers": "0.13.1", "@astrojs/markdown-satteri": "0.4.7", "@astrojs/telemetry": "3.4.2", "@capsizecss/unpack": "^4.0.1", "@clack/prompts": "^1.8.1", "@oslojs/encoding": "^1.1.0", "am-i-vibing": "^0.5.0", "aria-query": "^5.3.2", "axobject-query": "^4.1.0", "ci-info": "^4.4.0", "clsx": "^2.1.1", "common-ancestor-path": "^2.0.0", "cookie": "^2.0.1", "devalue": "^6.0.3", "diff": "^9.0.0", "dset": "^3.1.4", "es-module-lexer": "^3.0.4", "flattie": "^1.1.1", "fontace": "~0.4.1", "get-tsconfig": "5.0.0-beta.6", "github-slugger": "^2.0.0", "html-escaper": "3.0.3", "http-cache-semantics": "^4.3.0", "jsonc-parser": "^3.3.1", "magic-string": "^1.4.5", "magicast": "^0.5.5", "mrmime": "^2.0.1", "neotraverse": "^1.0.1", "obug": "^3.0.0", "p-limit": "^7.3.3", "p-queue": "^10.0.0", "package-manager-detector": "^1.9.0", "piccolore": "^0.1.3", "picomatch": "^4.0.7", "rolldown": "^1.2.16", "shiki": "^4.5.0", "smol-toml": "^1.9.1", "svgo": "^4.1.0", "tinyclip": "^1.0.3", "tinyexec": "^1.3.1", "tinyglobby": "^0.2.17", "tinyps": "^0.5.1", "ultrahtml": "^1.7.0", "unifont": "^1.0.3", "unstorage": "^1.17.6", "verkit": "^0.5.0", "vite": "^8.3.5", "vitefu": "^1.1.3", "xxhash-wasm": "^1.1.0", "yargs-parser": "^22.0.0", "zod": "^4.6.7" }, "optionalDependencies": { "sharp": "^0.35.4" }, "peerDependencies": { "@astrojs/markdown-remark": "^7.3.0" }, "optionalPeers": ["@astrojs/markdown-remark"], "bin": { "astro": "./bin/astro.mjs" } }, "sha512-fH54IOaCkZY1paEjygKn8CPfuJ3w8ns7PourcPML5AouJkQuTBqBQ2RbbIbBhutZbg2qn5se6Yl9DYybzqjC0Q=="], + "atomically": ["atomically@2.1.1", "", { "dependencies": { "stubborn-fs": "^2.0.0", "when-exit": "^2.1.4" } }, "sha512-P4w9o2dqARji6P7MHprklbfiArZAWvo07yW7qs3pdljb3BWr12FIB7W+p0zJiuiVsUpRO0iZn1kFFcpPegg0tQ=="], "axe-core": ["axe-core@4.14.0", "", {}, "sha512-9WTZxEjsZ7b13TH8JPmbV2z8CHbl80/2hm3XPEG4JgNdQLK81IBRXmSxHfMAOkSqQeRxT/0dwNDz2GOm3zzpcQ=="], + "axobject-query": ["axobject-query@4.1.0", "", {}, "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="], + "babel-plugin-transform-hook-names": ["babel-plugin-transform-hook-names@1.0.2", "", { "peerDependencies": { "@babel/core": "^7.12.10" } }, "sha512-5gafyjyyBTTdX/tQQ0hRgu4AhNHG/hqWi0ZZmg2xvs2FgRkJXzDNKBZCyoYqgFkovfDrgM8OoKg8karoUvWeCw=="], + "bail": ["bail@2.0.2", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="], + "balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], "baseline-browser-mapping": ["baseline-browser-mapping@2.11.35", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-GNk8KX52CHqeNKGk8+7tZnQab/2k1t/BgrUHPKNdijzpEhF1saPQZHVKb6m5loSAxB39gyrTYw34Qf9CQ3u1qQ=="], @@ -1075,6 +1259,8 @@ "before-after-hook": ["before-after-hook@4.0.0", "", {}, "sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ=="], + "blake3-wasm": ["blake3-wasm@2.1.5", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="], + "boolbase": ["boolbase@1.0.0", "", {}, "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww=="], "brace-expansion": ["brace-expansion@5.0.12", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ=="], @@ -1083,6 +1269,8 @@ "browserslist": ["browserslist@4.29.5", "", { "dependencies": { "baseline-browser-mapping": "^2.11.33", "caniuse-lite": "^1.0.30001819", "electron-to-chromium": "^1.5.464", "node-releases": "^2.0.60", "update-browserslist-db": "^1.3.4" }, "bin": { "browserslist": "cli.js" } }, "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ=="], + "bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + "bundle-name": ["bundle-name@4.1.1", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-DdH81/zPLVS11EUgWq3tEu/xn+EzljlMYooDNdzWEnFha3R3NBMpMV1UqYIpjYHV/SgpFKMIX1Oh7o06SjM/oA=="], "bundle-require": ["bundle-require@5.1.0", "", { "dependencies": { "load-tsconfig": "^0.2.3" }, "peerDependencies": { "esbuild": ">=0.18" } }, "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA=="], @@ -1099,6 +1287,8 @@ "chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], + "character-entities": ["character-entities@2.0.2", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="], + "character-entities-html4": ["character-entities-html4@2.1.0", "", {}, "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA=="], "character-entities-legacy": ["character-entities-legacy@3.0.0", "", {}, "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ=="], @@ -1113,6 +1303,8 @@ "chromium-bidi": ["chromium-bidi@157.0.8090-0", "", { "dependencies": { "mitt": "^3.0.1", "zod": "^4.6.5" }, "peerDependencies": { "devtools-protocol": "*" } }, "sha512-KJw7IQgqXwxpJgJlEIPg5mr2ZoqA+jkTRtc5EABI7sUJ3bu3cpI7NuEBoj4Gn1AsF78CaT9So5WQWspK3/wYag=="], + "ci-info": ["ci-info@4.5.0", "", {}, "sha512-d1uM8k5UZEyPza1n/MG3ko8nKupKN0KJpFsipgPcgaCCvV+IqIfJ+NzTjetlLM+UcXZx3+cLrNr76+eAO7G1Mw=="], + "class-variance-authority": ["class-variance-authority@0.7.1", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="], "cli-cursor": ["cli-cursor@5.0.0", "", { "dependencies": { "restore-cursor": "^5.0.0" } }, "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw=="], @@ -1135,6 +1327,8 @@ "commander": ["commander@14.0.3", "", {}, "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw=="], + "common-ancestor-path": ["common-ancestor-path@2.0.0", "", {}, "sha512-dnN3ibLeoRf2HNC+OlCiNc5d2zxbLJXOtiZUudNFSXZrNSydxcCsSpRzXwfu7BBWCIfHPw+xTayeBvJCP/D8Ng=="], + "conf": ["conf@10.2.0", "", { "dependencies": { "ajv": "^8.6.3", "ajv-formats": "^2.1.1", "atomically": "^1.7.0", "debounce-fn": "^4.0.0", "dot-prop": "^6.0.1", "env-paths": "^2.2.1", "json-schema-typed": "^7.0.3", "onetime": "^5.1.2", "pkg-up": "^3.1.0", "semver": "^7.3.5" } }, "sha512-8fLl9F04EJqjSqH+QjITQfJF8BrOVaYr1jewVgSRAEWePfxT0sku4w2hrGQ60BC/TNLGQ2pgxNlTbWQmMPFvXg=="], "confbox": ["confbox@0.1.8", "", {}, "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w=="], @@ -1147,16 +1341,26 @@ "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], + "cookie": ["cookie@2.0.2", "", {}, "sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw=="], + + "cookie-es": ["cookie-es@1.2.3", "", {}, "sha512-lXVyvUvrNXblMqzIRrxHb57UUVmqsSWlxqt3XIjCkUP0wDAf6uicO6KMbEgYrMNtEvWgWHwe42CKxPu9MYAnWw=="], + "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], + "crossws": ["crossws@0.3.5", "", { "dependencies": { "uncrypto": "^0.1.3" } }, "sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA=="], + "csp_evaluator": ["csp_evaluator@1.1.8", "", {}, "sha512-EwOnfYuNbTytvbMKsLixTrRgnjOa0WZCxGy8A9nnSYAicrdwn+T/epU/yjgymmOxlgKnvH+8wXt+7p/8ak5Feg=="], "css-select": ["css-select@5.2.2", "", { "dependencies": { "boolbase": "^1.0.0", "css-what": "^6.1.0", "domhandler": "^5.0.2", "domutils": "^3.0.1", "nth-check": "^2.0.1" } }, "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw=="], - "css-what": ["css-what@6.2.2", "", {}, "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA=="], + "css-tree": ["css-tree@3.2.1", "", { "dependencies": { "mdn-data": "2.27.1", "source-map-js": "^1.2.1" } }, "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA=="], + + "css-what": ["css-what@7.0.0", "", {}, "sha512-wD5oz5xibMOPHzy13CyGmogB3phdvcDaB5t0W/Nr5Z2O/agcB8YwOz6e2Lsp10pNDzBoDO9nVa3RGs/2BttpHQ=="], "css.escape": ["css.escape@1.5.1", "", {}, "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg=="], + "csso": ["csso@5.0.5", "", { "dependencies": { "css-tree": "~2.2.0" } }, "sha512-0LrrStPOdJj+SPCCrGhzryycLjwcgUSHBtxNA8aIDxf0GLsRh1cKYhB00Gd1lDOS4yGH69+SNn13+TWbVHETFQ=="], + "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], "data-uri-to-buffer": ["data-uri-to-buffer@4.0.1", "", {}, "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A=="], @@ -1169,6 +1373,8 @@ "decimal.js": ["decimal.js@10.6.0", "", {}, "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg=="], + "decode-named-character-reference": ["decode-named-character-reference@1.3.0", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q=="], + "dedent": ["dedent@1.7.2", "", { "peerDependencies": { "babel-plugin-macros": "^3.1.0" }, "optionalPeers": ["babel-plugin-macros"] }, "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA=="], "deep-eql": ["deep-eql@5.0.2", "", {}, "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q=="], @@ -1183,15 +1389,21 @@ "define-lazy-prop": ["define-lazy-prop@3.0.0", "", {}, "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg=="], + "defu": ["defu@6.1.7", "", {}, "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ=="], + "dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="], + "destr": ["destr@2.0.5", "", {}, "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA=="], + "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], + "devalue": ["devalue@6.0.3", "", {}, "sha512-3woMEITftG1wKeO/4d/QXH1DVKctTSZg3jNGPpjp9hNr5Hos8MCFF5McTML5ZtgKDObm2R591B0spRp2IVernA=="], + "devlop": ["devlop@1.1.0", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="], "devtools-protocol": ["devtools-protocol@0.0.1727723", "", {}, "sha512-laxmpDN+zItbpy5klVbHqBsZ38O2rC6VwI9W5daM11Pc3Dj2gruc2wwnHW48CB8wYiWHALDkA6vRg92U2cfdLA=="], - "diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="], + "diff": ["diff@9.0.0", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="], "doctrine": ["doctrine@3.0.0", "", { "dependencies": { "esutils": "^2.0.2" } }, "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w=="], @@ -1209,6 +1421,8 @@ "dotenv": ["dotenv@17.4.2", "", {}, "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw=="], + "dset": ["dset@3.1.4", "", {}, "sha512-2QF/g9/zTaPDc3BjNcVTGoBbXBgYfMTTceLaYcFJ/W9kggFUkhxD/hMEeuLKbugyef9SqAx8cpgwlIP/jinUTA=="], + "electron-to-chromium": ["electron-to-chromium@1.5.478", "", {}, "sha512-pftG+ma5Lm8O6/p45bhYT6StBN5ziQymaRzmCZwFl8DwWHKPPD93FdOmP1aqftcepolQYvrcyTLa17kE8Yf+jg=="], "emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], @@ -1223,9 +1437,11 @@ "env-paths": ["env-paths@2.2.1", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="], + "error-stack-parser-es": ["error-stack-parser-es@1.0.5", "", {}, "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA=="], + "es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="], - "es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], + "es-module-lexer": ["es-module-lexer@3.0.5", "", {}, "sha512-RNq2lKJw53c7z9QRHeiKeA6Ez0oikOqiBGdmxQhKDxEiOX1g5QJR4IoFVwicn8uCZcRWNrXC3NZaJihgK7aEbg=="], "esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="], @@ -1259,6 +1475,8 @@ "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="], + "extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="], + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], "fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="], @@ -1297,6 +1515,14 @@ "flatted": ["flatted@3.4.4", "", {}, "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q=="], + "flattie": ["flattie@1.1.1", "", {}, "sha512-9UbaD6XdAL97+k/n+N7JwX46K/M6Zc6KcFYskrYL8wbBV/Uyk0CTAMY0VT+qiK5PM7AIc9aTWYtq65U7T+aCNQ=="], + + "fnv1a-64": ["fnv1a-64@0.1.2", "", {}, "sha512-mJbcILTPybAR1jdOwt/lVv8N2cffeJFFP+gVbSAwLEx1ujXH27RpPd8Rokec/KX9c76UYIB6Co+H4lQzxPnJfA=="], + + "fontace": ["fontace@0.4.1", "", { "dependencies": { "fontkitten": "^1.0.2" } }, "sha512-lDMvbAzSnHmbYMTEld5qdtvNH2/pWpICOqpean9IgC7vUbUJc3k+k5Dokp85CegamqQpFbXf0rAVkbzpyTA8aw=="], + + "fontkitten": ["fontkitten@1.0.3", "", { "dependencies": { "tiny-inflate": "^1.0.3" } }, "sha512-Wp1zXWPVUPBmfoa3Cqc9ctaKuzKAV6uLstRqlR56kSjplf5uAce+qeyYym7F+PHbGTk+tCEdkCW6RD7DX/gBZw=="], + "formdata-polyfill": ["formdata-polyfill@4.0.10", "", { "dependencies": { "fetch-blob": "^3.1.2" } }, "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g=="], "fs-extra": ["fs-extra@11.4.1", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA=="], @@ -1317,6 +1543,10 @@ "get-stream": ["get-stream@9.0.1", "", { "dependencies": { "@sec-ant/readable-stream": "^0.4.1", "is-stream": "^4.0.1" } }, "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA=="], + "get-tsconfig": ["get-tsconfig@5.0.0-beta.6", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-X6fBC0pmImC70gvX2zm56go9hx0MyoGVdG0tUCkg/D+Xnh5TJsOZ7iDbOdI3PvmtrDxnu1YdDufpK2QJX1Meqw=="], + + "github-slugger": ["github-slugger@2.0.0", "", {}, "sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw=="], + "glob": ["glob@14.0.4", "", { "dependencies": { "minimatch": "^11.0.5", "minipass": "^7.1.3", "path-scurry": "^3.0.0" } }, "sha512-mMiwNKoJZ4HAIRVJxotO6LsNRReA30gQwP9E2/p94tfLv+jygCNpKDjhhSL6OLY6LE371EZm5EAf7RpYuUqlsw=="], "glob-parent": ["glob-parent@6.0.2", "", { "dependencies": { "is-glob": "^4.0.3" } }, "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A=="], @@ -1325,6 +1555,8 @@ "graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="], + "h3": ["h3@1.15.11", "", { "dependencies": { "cookie-es": "^1.2.3", "crossws": "^0.3.5", "defu": "^6.1.6", "destr": "^2.0.5", "iron-webcrypto": "^1.2.1", "node-mock-http": "^1.0.4", "radix3": "^1.1.2", "ufo": "^1.6.3", "uncrypto": "^0.1.3" } }, "sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg=="], + "has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="], "hashery": ["hashery@1.5.1", "", { "dependencies": { "hookified": "^1.15.0" } }, "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ=="], @@ -1341,8 +1573,12 @@ "html-encoding-sniffer": ["html-encoding-sniffer@7.0.0", "", { "dependencies": { "@exodus/bytes": "^1.15.1" } }, "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w=="], + "html-escaper": ["html-escaper@3.0.3", "", {}, "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ=="], + "html-void-elements": ["html-void-elements@3.0.0", "", {}, "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg=="], + "http-cache-semantics": ["http-cache-semantics@4.3.0", "", {}, "sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA=="], + "http-link-header": ["http-link-header@1.1.4", "", {}, "sha512-xT3GPW6/ZbGuw4UvwHqErSCEjNUlwbQJuZn9/q5U4WEKfp2kENVCAlousG1zLxHeaQ/ffOHUNpWamvkbBW0eNw=="], "human-id": ["human-id@4.2.2", "", { "bin": { "human-id": "dist/cli.js" } }, "sha512-Z+8unD6em/MJwyrkWQ2M3wygRGI1+MztbutiNwk1DCuEPXOZRWGjtcMPZYP1exY9iNZMhd7ZOSMQSo9WYtiQRw=="], @@ -1363,6 +1599,8 @@ "ip-address": ["ip-address@10.7.6", "", {}, "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg=="], + "iron-webcrypto": ["iron-webcrypto@1.2.1", "", {}, "sha512-feOM6FaSr6rEABp/eDfVseKyTMDt+KGpeB35SkVn9Tyn0CqvVsY3EwI0v5i8nMHyJnzCIQf7nsy3p41TPkJZhg=="], + "is-alphabetical": ["is-alphabetical@2.0.1", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="], "is-alphanumerical": ["is-alphanumerical@2.0.1", "", { "dependencies": { "is-alphabetical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw=="], @@ -1371,7 +1609,7 @@ "is-decimal": ["is-decimal@2.0.1", "", {}, "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A=="], - "is-docker": ["is-docker@2.2.1", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="], + "is-docker": ["is-docker@4.0.0", "", { "bin": { "is-docker": "cli.js" } }, "sha512-LHE+wROyG/Y/0ZnbktRCoTix2c1RhgWaZraMZ8o1Q7zCh0VSrICJQO5oqIIISrcSBtrXv0o233w1IYwsWCjTzA=="], "is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="], @@ -1491,6 +1729,8 @@ "log-symbols": ["log-symbols@6.0.0", "", { "dependencies": { "chalk": "^5.3.0", "is-unicode-supported": "^1.3.0" } }, "sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw=="], + "longest-streak": ["longest-streak@3.1.0", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="], + "loupe": ["loupe@3.2.1", "", {}, "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ=="], "lru-cache": ["lru-cache@11.5.3", "", {}, "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg=="], @@ -1503,20 +1743,94 @@ "magicast": ["magicast@0.5.5", "", { "dependencies": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", "source-map-js": "^1.2.1" } }, "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA=="], + "markdown-table": ["markdown-table@3.1.0", "", {}, "sha512-xpeSCdM+B+6P3ncfgaB7FoDbtJ30xAe6Z18TGT7AgXJsHqCElCICZovQqdRMm7kHgpTyYv36EupqewoFFSB8vw=="], + "marky": ["marky@1.3.0", "", {}, "sha512-ocnPZQLNpvbedwTy9kNrQEsknEfgvcLMvOtz3sFeWApDq1MXH1TqkCIx58xlpESsfwQOnuBO9beyQuNGzVvuhQ=="], + "mdast-util-find-and-replace": ["mdast-util-find-and-replace@3.0.5", "", { "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.1.0" } }, "sha512-of3wZLEBWpK8mSYy8wmKnwyxfUKjhCkXxGLz45DVBqfcahTP37LscCK+0oAZh+ReZ5OunPDkB2zdGMIxrojLhw=="], + + "mdast-util-from-markdown": ["mdast-util-from-markdown@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A=="], + + "mdast-util-gfm": ["mdast-util-gfm@3.1.0", "", { "dependencies": { "mdast-util-from-markdown": "^2.0.0", "mdast-util-gfm-autolink-literal": "^2.0.0", "mdast-util-gfm-footnote": "^2.0.0", "mdast-util-gfm-strikethrough": "^2.0.0", "mdast-util-gfm-table": "^2.0.0", "mdast-util-gfm-task-list-item": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ=="], + + "mdast-util-gfm-autolink-literal": ["mdast-util-gfm-autolink-literal@2.1.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "ccount": "^2.0.0", "devlop": "^1.0.0", "mdast-util-find-and-replace": "^3.0.0", "micromark-util-character": "^2.0.0" } }, "sha512-rAlbZBGZfv2YRr6lSFGHTN305KkNawOYRRlbldFyPHnTlHJZwlGdzVwyIDvr3fxbhRbmJOSZc06c8H5Fgfu8Ng=="], + + "mdast-util-gfm-footnote": ["mdast-util-gfm-footnote@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0" } }, "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ=="], + + "mdast-util-gfm-strikethrough": ["mdast-util-gfm-strikethrough@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-OuJHqvr455pwu2OaOrir7dbzqs4jlWKOtlu9L6GjcIjjQwNyw02VntQsr/Ek6/A13vgnXfUhBekWRUP1OkNivw=="], + + "mdast-util-gfm-table": ["mdast-util-gfm-table@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "markdown-table": "^3.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "mdast-util-to-string": "^4.0.0", "unist-util-visit": "^5.0.0" } }, "sha512-fiIjPrAy4kz68/eFbPHhsiWDGHhqUSVoU1XsfLM5DsEPXw7MxgiVVyulUggFRckVWeT1KXQXkg5vm3kv4oMSOA=="], + + "mdast-util-gfm-task-list-item": ["mdast-util-gfm-task-list-item@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-jXVO1hvB2hs82g1esi7I9nIJDqiijbQLIyH2jDUb5s7jIAZMr/79h0VHSq7XHKTqpLARRm+DDNjduB7S9+6XZA=="], + + "mdast-util-phrasing": ["mdast-util-phrasing@4.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "unist-util-is": "^6.0.0" } }, "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w=="], + "mdast-util-to-hast": ["mdast-util-to-hast@13.2.1", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@ungap/structured-clone": "^1.0.0", "devlop": "^1.0.0", "micromark-util-sanitize-uri": "^2.0.0", "trim-lines": "^3.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA=="], + "mdast-util-to-markdown": ["mdast-util-to-markdown@2.2.4", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "longest-streak": "^3.0.0", "mdast-util-phrasing": "^4.0.0", "mdast-util-to-string": "^4.0.0", "micromark-util-character": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-html-tag-name": "^2.0.0", "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" } }, "sha512-aCsogoZ2Oz1EItAlC12A+/uGuzp+CWlDU0xZ3o5jbJaepLsOu2tlxpvHslnX5dRhspD1gxNVkBtYG0yMiIpXoQ=="], + + "mdast-util-to-string": ["mdast-util-to-string@4.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0" } }, "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg=="], + + "mdn-data": ["mdn-data@2.27.1", "", {}, "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ=="], + "merge-stream": ["merge-stream@2.0.0", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="], "merge2": ["merge2@1.4.1", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="], + "micromark": ["micromark@4.0.3", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-edit-map": "^1.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw=="], + + "micromark-core-commonmark": ["micromark-core-commonmark@2.0.4", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", "micromark-factory-space": "^2.1.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-edit-map": "^1.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.3" } }, "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w=="], + + "micromark-extension-gfm": ["micromark-extension-gfm@3.0.0", "", { "dependencies": { "micromark-extension-gfm-autolink-literal": "^2.0.0", "micromark-extension-gfm-footnote": "^2.0.0", "micromark-extension-gfm-strikethrough": "^2.0.0", "micromark-extension-gfm-table": "^2.0.0", "micromark-extension-gfm-tagfilter": "^2.0.0", "micromark-extension-gfm-task-list-item": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w=="], + + "micromark-extension-gfm-autolink-literal": ["micromark-extension-gfm-autolink-literal@2.1.0", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw=="], + + "micromark-extension-gfm-footnote": ["micromark-extension-gfm-footnote@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw=="], + + "micromark-extension-gfm-strikethrough": ["micromark-extension-gfm-strikethrough@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw=="], + + "micromark-extension-gfm-table": ["micromark-extension-gfm-table@2.1.2", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-pRzm4kDTu0MjlmBkxmS9yYhw60nncfcEwu9NNdPFSQEFXS95ZKyIIyTSHu/o3ReBUrLKYEq+7YaXCRn/bPB4MA=="], + + "micromark-extension-gfm-tagfilter": ["micromark-extension-gfm-tagfilter@2.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg=="], + + "micromark-extension-gfm-task-list-item": ["micromark-extension-gfm-task-list-item@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw=="], + + "micromark-factory-destination": ["micromark-factory-destination@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA=="], + + "micromark-factory-label": ["micromark-factory-label@2.0.1", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg=="], + + "micromark-factory-space": ["micromark-factory-space@2.1.0", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q=="], + + "micromark-factory-title": ["micromark-factory-title@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw=="], + + "micromark-factory-whitespace": ["micromark-factory-whitespace@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ=="], + "micromark-util-character": ["micromark-util-character@2.1.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q=="], + "micromark-util-chunked": ["micromark-util-chunked@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA=="], + + "micromark-util-classify-character": ["micromark-util-classify-character@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q=="], + + "micromark-util-combine-extensions": ["micromark-util-combine-extensions@2.0.1", "", { "dependencies": { "micromark-util-chunked": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg=="], + + "micromark-util-decode-numeric-character-reference": ["micromark-util-decode-numeric-character-reference@2.0.2", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw=="], + + "micromark-util-decode-string": ["micromark-util-decode-string@2.0.1", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-symbol": "^2.0.0" } }, "sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ=="], + + "micromark-util-edit-map": ["micromark-util-edit-map@1.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q=="], + "micromark-util-encode": ["micromark-util-encode@2.0.1", "", {}, "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw=="], + "micromark-util-html-tag-name": ["micromark-util-html-tag-name@2.0.1", "", {}, "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA=="], + + "micromark-util-normalize-identifier": ["micromark-util-normalize-identifier@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q=="], + + "micromark-util-resolve-all": ["micromark-util-resolve-all@2.0.1", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg=="], + "micromark-util-sanitize-uri": ["micromark-util-sanitize-uri@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-symbol": "^2.0.0" } }, "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ=="], + "micromark-util-subtokenize": ["micromark-util-subtokenize@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA=="], + "micromark-util-symbol": ["micromark-util-symbol@2.0.1", "", {}, "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q=="], "micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], @@ -1529,6 +1843,8 @@ "min-indent": ["min-indent@1.0.1", "", {}, "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg=="], + "miniflare": ["miniflare@5.20261103.0-beta", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.5", "undici": "7.30.1", "workerd": "1.20261103.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" } }, "sha512-wghSXG3KHzMbAYvcrHFxN6JNI1Or3LSxpBe1qHdnFXFOPIDIlXCNvsRVF2J97rXsfFSJr7EzxRSjoUCmgVDEUA=="], + "minimatch": ["minimatch@11.0.5", "", { "dependencies": { "@isaacs/nonrecursive-glob-match": "^1.1.0", "brace-expansion": "^5.0.12" } }, "sha512-snPlVppFcYWfLLFQGhDxUyBcHNtMlWmn3jtj7pEaO+DP8pqL0IvAzXhMYmn1z9ASNtgmwLBdFxSf4tMUB0OTKA=="], "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], @@ -1551,14 +1867,24 @@ "natural-compare": ["natural-compare@1.4.0", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="], + "neotraverse": ["neotraverse@1.0.2", "", {}, "sha512-DLMUFnyCrRAncRJhDC2yNbSTcpEukp+nczID/na3XdIHQFokPveK69xel642cQHgUGszctsOSeCePqPpY25W6Q=="], + + "nlcst-to-string": ["nlcst-to-string@4.0.0", "", { "dependencies": { "@types/nlcst": "^2.0.0" } }, "sha512-YKLBCcUYKAg0FNlOBT6aI91qFmSiFKiluk655WzPF+DDMA02qIyy8uiRqI8QXtcFpEvll12LpL5MXqEmAZ+dcA=="], + "node-domexception": ["node-domexception@1.0.0", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="], "node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="], + "node-fetch-native": ["node-fetch-native@1.6.7", "", {}, "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q=="], + "node-html-parser": ["node-html-parser@6.1.13", "", { "dependencies": { "css-select": "^5.1.0", "he": "1.2.0" } }, "sha512-qIsTMOY4C/dAa5Q5vsobRpOOvPfC4pB61UVW2uSwZNUp0QU/jCekTal1vMmbO0DgdHeLUJpv/ARmDqErVxA3Sg=="], + "node-mock-http": ["node-mock-http@1.0.5", "", {}, "sha512-KQyt/wLjG3TAc7DOUhpqWzgd4ERxR80JOlTK5VE5R1S12IaPVN5qkj4klBce9HPG1Njuup4Sb5bljaT34lIyjw=="], + "node-releases": ["node-releases@2.0.63", "", {}, "sha512-6li2QanLsAXpIH2R6j77MzRyvOyrvdTqlKtO4CgBdHGNvN99ZZfyxszHc5o5+IZBWD5u6Hzwg83JoGXmqZNG9Q=="], + "normalize-path": ["normalize-path@3.0.0", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="], + "npm-run-path": ["npm-run-path@6.0.0", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="], "nth-check": ["nth-check@2.1.1", "", { "dependencies": { "boolbase": "^1.0.0" } }, "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w=="], @@ -1569,6 +1895,8 @@ "obug": ["obug@3.0.0", "", {}, "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw=="], + "ofetch": ["ofetch@1.5.1", "", { "dependencies": { "destr": "^2.0.5", "node-fetch-native": "^1.6.7", "ufo": "^1.6.1" } }, "sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA=="], + "onetime": ["onetime@5.1.2", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="], "oniguruma-parser": ["oniguruma-parser@0.12.2", "", {}, "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw=="], @@ -1585,10 +1913,12 @@ "oxc-resolver": ["oxc-resolver@11.21.2", "", { "optionalDependencies": { "@oxc-resolver/binding-android-arm-eabi": "11.21.2", "@oxc-resolver/binding-android-arm64": "11.21.2", "@oxc-resolver/binding-darwin-arm64": "11.21.2", "@oxc-resolver/binding-darwin-x64": "11.21.2", "@oxc-resolver/binding-freebsd-x64": "11.21.2", "@oxc-resolver/binding-linux-arm-gnueabihf": "11.21.2", "@oxc-resolver/binding-linux-arm-musleabihf": "11.21.2", "@oxc-resolver/binding-linux-arm64-gnu": "11.21.2", "@oxc-resolver/binding-linux-arm64-musl": "11.21.2", "@oxc-resolver/binding-linux-ppc64-gnu": "11.21.2", "@oxc-resolver/binding-linux-riscv64-gnu": "11.21.2", "@oxc-resolver/binding-linux-riscv64-musl": "11.21.2", "@oxc-resolver/binding-linux-s390x-gnu": "11.21.2", "@oxc-resolver/binding-linux-x64-gnu": "11.21.2", "@oxc-resolver/binding-linux-x64-musl": "11.21.2", "@oxc-resolver/binding-openharmony-arm64": "11.21.2", "@oxc-resolver/binding-wasm32-wasi": "11.21.2", "@oxc-resolver/binding-win32-arm64-msvc": "11.21.2", "@oxc-resolver/binding-win32-x64-msvc": "11.21.2" } }, "sha512-w5tLwYN3Zo24w5EeWJjJWZOwhYqTtC8PS2B1tIt7BZUuqTIcU07sQValbDw+rq7+AuAGzOHklgK+ifsy4lpXfw=="], - "p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="], + "p-limit": ["p-limit@7.3.3", "", { "dependencies": { "yocto-queue": "^1.2.1" } }, "sha512-SKgVvDU5TNIxQ4r30U75BNLC6a+6GOEjngrk/ysM5+Zu3oJuk1SC5ApzIzY/7PjCEjoVPMWJ0zho/4QUiEB7TQ=="], "p-locate": ["p-locate@5.0.0", "", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="], + "p-queue": ["p-queue@10.0.0", "", {}, "sha512-P2wrCri3bhGLPo3kX7qYVXbo/5GvaVATU0DpO24CbeT53Y4z35t8JUWku04ERpXHUYB5rPMi3TkWE3fmJgx5rA=="], + "p-try": ["p-try@2.2.0", "", {}, "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ=="], "package-manager-detector": ["package-manager-detector@1.9.0", "", {}, "sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA=="], @@ -1609,10 +1939,14 @@ "path-scurry": ["path-scurry@3.0.0", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg=="], + "path-to-regexp": ["path-to-regexp@6.3.0", "", {}, "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ=="], + "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], "pathval": ["pathval@2.0.1", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="], + "piccolore": ["piccolore@0.1.3", "", {}, "sha512-o8bTeDWjE086iwKrROaDf31K0qC/BENdm15/uH9usSC/uZjJOKb2YGiVHfLY4GhwsERiPI1jmwI2XrA7ACOxVw=="], + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], @@ -1647,6 +1981,10 @@ "pretty-ms": ["pretty-ms@9.3.1", "", { "dependencies": { "parse-ms": "^4.0.0" } }, "sha512-HzMy3Geq23nVALD/M2LliU+F+M+gVNsvkQWWqeBZ8HDiCgzo6YPJ/Omrmtq24EFrIsk0a3EkQGEd7bDOo+IhGA=="], + "prismjs": ["prismjs@1.30.0", "", {}, "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw=="], + + "process-ancestry": ["process-ancestry@0.1.0", "", {}, "sha512-tGqJW/UnclpYASFcM6Xh8D8l/BMtaQ9+CSG0vlJSJTcdMM4lDRv4c6H0Pdcsfted+bVczdYSfk2fdukg2gQkZg=="], + "prompts": ["prompts@2.4.2", "", { "dependencies": { "kleur": "^3.0.3", "sisteransi": "^1.0.5" } }, "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q=="], "property-information": ["property-information@7.2.0", "", {}, "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg=="], @@ -1659,6 +1997,8 @@ "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="], + "radix3": ["radix3@1.1.2", "", {}, "sha512-b484I/7b8rDEdSDKckSSBA8knMpcdsXudlE/LNL639wFoHKwLbEkQFZHWEYwDC0wa0FKUcCY+GAF73Z7wxNVFA=="], + "react": ["react@19.3.1", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="], "react-docgen": ["react-docgen@8.0.4", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/traverse": "^7.28.0", "@babel/types": "^7.28.2", "@types/babel__core": "^7.20.5", "@types/babel__traverse": "^7.20.7", "@types/doctrine": "^0.0.9", "@types/resolve": "^1.20.2", "doctrine": "^3.0.0", "resolve": "^1.22.1", "strip-indent": "^4.0.0" } }, "sha512-gIYjtVTU4NCWZnb/LXVSWfClZXnjzX3+xxi69Tkfu4YsmYuqiOk8giLkKt/WwxWqh+U66CTh8Kqbha1uPv8/qQ=="], @@ -1689,8 +2029,12 @@ "resolve-from": ["resolve-from@5.0.0", "", {}, "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw=="], + "resolve-pkg-maps": ["resolve-pkg-maps@1.0.0", "", {}, "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw=="], + "restore-cursor": ["restore-cursor@5.1.0", "", { "dependencies": { "onetime": "^7.0.0", "signal-exit": "^4.1.0" } }, "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA=="], + "retext-smartypants": ["retext-smartypants@6.2.0", "", { "dependencies": { "@types/nlcst": "^2.0.0", "nlcst-to-string": "^4.0.0", "unist-util-visit": "^5.0.0" } }, "sha512-kk0jOU7+zGv//kfjXEBjdIryL1Acl4i9XNkHxtM7Tm5lFiCog576fjNC9hjoR7LTKQ0DsPWy09JummSsH1uqfQ=="], + "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], "robots-parser": ["robots-parser@3.0.1", "", {}, "sha512-s+pyvQeIKIZ0dx5iJiQk1tPLJAWln39+MI5jtM8wnyws+G5azk+dMnMX0qfbqNetKKNgcWWOdi0sfm+FbQbgdQ=="], @@ -1703,6 +2047,10 @@ "run-parallel": ["run-parallel@1.2.0", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="], + "satteri": ["satteri@0.11.7", "", { "dependencies": { "@types/estree-jsx": "^1.0.5", "@types/hast": "^3.0.5", "@types/mdast": "^4.0.4", "@types/unist": "^3.0.3" }, "optionalDependencies": { "@bruits/satteri-android-arm64": "0.11.7", "@bruits/satteri-darwin-arm64": "0.11.7", "@bruits/satteri-darwin-x64": "0.11.7", "@bruits/satteri-freebsd-x64": "0.11.7", "@bruits/satteri-linux-arm64-gnu": "0.11.7", "@bruits/satteri-linux-arm64-musl": "0.11.7", "@bruits/satteri-linux-x64-gnu": "0.11.7", "@bruits/satteri-linux-x64-musl": "0.11.7", "@bruits/satteri-wasm32-wasi": "0.11.7", "@bruits/satteri-win32-arm64-msvc": "0.11.7", "@bruits/satteri-win32-x64-msvc": "0.11.7" } }, "sha512-xDOSxkc1ew3z3IovIjmsqJaVHRXTGYJkPvx0LL/U6o90km8kSU+pmrZVvnWd5creJeE0UnvMEienlkPuYQdJaA=="], + + "sax": ["sax@1.6.1", "", {}, "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q=="], + "saxes": ["saxes@6.0.0", "", { "dependencies": { "xmlchars": "^2.2.0" } }, "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA=="], "scheduler": ["scheduler@0.28.0", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="], @@ -1733,6 +2081,8 @@ "smart-buffer": ["smart-buffer@4.2.0", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="], + "smol-toml": ["smol-toml@1.9.1", "", {}, "sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ=="], + "socks": ["socks@2.8.10", "", { "dependencies": { "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" } }, "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ=="], "source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="], @@ -1777,6 +2127,8 @@ "supports-preserve-symlinks-flag": ["supports-preserve-symlinks-flag@1.0.0", "", {}, "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w=="], + "svgo": ["svgo@4.1.0", "", { "dependencies": { "commander": "^11.1.0", "css-select": "^6.0.0", "css-tree": "^3.0.1", "css-what": "^7.0.0", "csso": "^5.0.5", "picocolors": "^1.1.1", "sax": "1.6.1" }, "bin": { "svgo": "bin/svgo.js" } }, "sha512-bkxnTg1kSU0guhIBmibA6UUhrQmPVA1XsQLN+ylCd+UWzbnLkySOcXpyk1mrl05f+pcaCx2eHb+sp6BgMZWX+Q=="], + "systeminformation": ["systeminformation@5.33.19", "", { "os": "!aix", "bin": { "systeminformation": "lib/cli.js" } }, "sha512-Zm7wGeCG7PqfvzegMJIzrxICopWqYCeLATVmvxOOci1isLcNVKgY4Fr0hhYQzvc7cgtK3377jQVChTFAnznOiA=="], "tagged-tag": ["tagged-tag@1.0.0", "", {}, "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng=="], @@ -1793,14 +2145,20 @@ "third-party-web": ["third-party-web@0.30.0", "", {}, "sha512-p+PfyL5U0ediGzvwPzMSdD9MnC8rHW6nWJJVLIQvqN7RsSqfaZ+7n4c9GILqH36EYR0eXB9CzAeCRnKFr/9uJg=="], + "tiny-inflate": ["tiny-inflate@1.0.3", "", {}, "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw=="], + "tiny-invariant": ["tiny-invariant@1.3.3", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="], "tinybench": ["tinybench@6.2.3", "", {}, "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw=="], + "tinyclip": ["tinyclip@1.0.3", "", {}, "sha512-nTv2raKFMzGG6JJp0lpNDsRPdfFE6UHlu2rVEjXo8vkx1ZS3LW2CVXqIaLu8xZlu+6tbFs9V58Qc/Jmk/Ii7wA=="], + "tinyexec": ["tinyexec@1.3.1", "", {}, "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA=="], "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], + "tinyps": ["tinyps@0.5.2", "", {}, "sha512-sYhvdbpuo2rGE7u/jPUMiZz4H2LCaOodUtRD9ot4DLNFQbr884g9zozoJnxLI+1r4hXqWkmdHUl8Yig2Rllxxw=="], + "tinyrainbow": ["tinyrainbow@3.2.0", "", {}, "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A=="], "tinyspy": ["tinyspy@4.0.6", "", {}, "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg=="], @@ -1825,6 +2183,8 @@ "trim-lines": ["trim-lines@3.0.1", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="], + "trough": ["trough@2.2.0", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="], + "ts-api-utils": ["ts-api-utils@2.5.0", "", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA=="], "ts-dedent": ["ts-dedent@2.3.0", "", {}, "sha512-JfJeIHke7y2egdGGgRAvpCwYFUsHlM2gPcrVOxFkznt/4uzQ7HFmvE63iFHVLBJNDuyDOQgijDK/tXH/f6Msjg=="], @@ -1861,12 +2221,22 @@ "ufo": ["ufo@1.6.4", "", {}, "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA=="], + "ultrahtml": ["ultrahtml@1.7.0", "", {}, "sha512-2xRd0VHoAQE4M+vF/DvFFB7pUV0ZxTW1TLi7lHQWnF/Sb5TPeEUV/l+hxcNnGO00ZXGnR0voCMmYRKQf+rvJ2g=="], + + "uncrypto": ["uncrypto@0.1.3", "", {}, "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q=="], + "undici": ["undici@8.12.4", "", {}, "sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA=="], "undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + "unenv": ["unenv@2.0.0-rc.24", "", { "dependencies": { "pathe": "^2.0.3" } }, "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw=="], + "unicorn-magic": ["unicorn-magic@0.3.0", "", {}, "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA=="], + "unified": ["unified@11.0.5", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="], + + "unifont": ["unifont@1.0.3", "", { "dependencies": { "css-tree": "^3.1.0", "fnv1a-64": "^0.1.2", "std-env": "^4.2.0", "undici": "^8.0.0" } }, "sha512-XGnEwj5sWdCbiBX01mWLSBncS0yMRjnLygau3IfdOlfjMacNIQvTGW4VH7pWBq+gGWArfSef/CensMLjMmIr/A=="], + "unist-util-is": ["unist-util-is@6.0.1", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="], "unist-util-position": ["unist-util-position@5.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="], @@ -1883,6 +2253,8 @@ "unplugin": ["unplugin@1.16.1", "", { "dependencies": { "acorn": "^8.14.0", "webpack-virtual-modules": "^0.6.2" } }, "sha512-4/u/j4FrCKdi17jaxuJA0jClGxB1AvU2hw/IuayPc4ay1XGaJs/rbb4v5WKwAjNifjmXK9PIFyuPiaK8azyR9w=="], + "unstorage": ["unstorage@1.17.6", "", { "dependencies": { "anymatch": "^3.1.3", "chokidar": "^5.0.0", "destr": "^2.0.5", "h3": "^1.15.11", "lru-cache": "^11.5.3", "node-fetch-native": "^1.6.7", "ofetch": "^1.5.1", "ufo": "^1.6.4" }, "peerDependencies": { "@azure/app-configuration": "^1.8.0", "@azure/cosmos": "^4.2.0", "@azure/data-tables": "^13.3.0", "@azure/identity": "^4.6.0", "@azure/keyvault-secrets": "^4.9.0", "@azure/storage-blob": "^12.26.0", "@capacitor/preferences": "^6 || ^7 || ^8", "@deno/kv": ">=0.9.0", "@netlify/blobs": "^6.5.0 || ^7.0.0 || ^8.1.0 || ^9.0.0 || ^10.0.0 || ^11.0.0", "@planetscale/database": "^1.19.0", "@upstash/redis": "^1.34.3", "@vercel/blob": ">=0.27.1", "@vercel/functions": "^2.2.12 || ^3.0.0", "@vercel/kv": "^1 || ^2 || ^3", "aws4fetch": "^1.0.20", "db0": ">=0.2.1", "idb-keyval": "^6.2.1", "ioredis": "^5.4.2", "uploadthing": "^7.4.4" }, "optionalPeers": ["@azure/app-configuration", "@azure/cosmos", "@azure/data-tables", "@azure/identity", "@azure/keyvault-secrets", "@azure/storage-blob", "@capacitor/preferences", "@deno/kv", "@netlify/blobs", "@planetscale/database", "@upstash/redis", "@vercel/blob", "@vercel/functions", "@vercel/kv", "aws4fetch", "db0", "idb-keyval", "ioredis", "uploadthing"] }, "sha512-gjKtcmn/KwZuJZO9o2sc0esAQnhmTw0LviDHwevTXbJMYs0dRTp8ZEEWXHU0vTpzbN3cA0yxlTeyXssMp3zDqw=="], + "update-browserslist-db": ["update-browserslist-db@1.3.4", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A=="], "uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="], @@ -1897,6 +2269,8 @@ "validate-npm-package-name": ["validate-npm-package-name@7.0.2", "", {}, "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A=="], + "verkit": ["verkit@0.5.0", "", {}, "sha512-u4J1hr6Y+C/hit34GwL3eIcUf3wngT8TlYUjK7tk0jxydKLAq3sYvifjdTDA6U3KCKRcQCQDGf/srjxfZF3l7g=="], + "vfile": ["vfile@6.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="], "vfile-message": ["vfile-message@4.0.4", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-66ycRswIkNmHH9PHku7ADtv5RVwgIrOcuv3J8Svz6h4qgGRrKVa+9/neuKyJZUXyOpYwLTvS+whZ4R2urHHgQg=="], @@ -1905,6 +2279,8 @@ "vite-prerender-plugin": ["vite-prerender-plugin@0.5.14", "", { "dependencies": { "kolorist": "^1.8.0", "magic-string": "0.x >= 0.26.0", "node-html-parser": "^6.1.12", "simple-code-frame": "^1.3.0", "source-map": "^0.7.4", "stack-trace": "^1.0.0-pre2" }, "peerDependencies": { "vite": "5.x || 6.x || 7.x || 8.x" } }, "sha512-X2w9AS1OhwEUec9HSryGAmEnEQJGhW6eFoiCVJv8BfOTVpM8SOjk75cEw/IC28APDHZudeIRbP8Sp7wfABq+Aw=="], + "vitefu": ["vitefu@1.1.4", "", { "peerDependencies": { "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["vite"] }, "sha512-qbEIDswfXH3x3IYRMScl/bf1AVW0dn7Z8qkr7g7nohkusfuC7tcFa7t5EoTOz60AunosLM9sDrDjHxsX+Up+CQ=="], + "vitest": ["vitest@5.1.0", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/mocker": "5.1.0", "chai": "^6.3.0", "es-module-lexer": "^2.3.2", "expect-type": "^1.4.0", "magic-string": "^1.4.3", "obug": "^3.0.0", "picomatch": "^4.0.7", "std-env": "^4.3.0", "tinybench": "^6.2.2", "tinyexec": "^1.3.1", "tinyglobby": "^0.2.17", "why-is-node-running": "3.2.1" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "5.1.0", "@vitest/browser-preview": "5.1.0", "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", "@vitest/coverage-istanbul": "5.1.0", "@vitest/coverage-v8": "5.1.0", "@vitest/ui": "5.1.0", "happy-dom": "*", "jsdom": "*", "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA=="], "w3c-xmlserializer": ["w3c-xmlserializer@6.0.0", "", { "dependencies": { "xml-name-validator": "^5.0.0" } }, "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q=="], @@ -1929,6 +2305,10 @@ "word-wrap": ["word-wrap@1.2.5", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="], + "workerd": ["workerd@1.20261103.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20261103.1", "@cloudflare/workerd-darwin-arm64": "1.20261103.1", "@cloudflare/workerd-linux-64": "1.20261103.1", "@cloudflare/workerd-linux-arm64": "1.20261103.1", "@cloudflare/workerd-windows-64": "1.20261103.1" }, "hasInstallScript": true, "bin": { "workerd": "bin/workerd" } }, "sha512-GgcAnUH94uY8BEDc7CUyX3qsuLVbiidV+SZqJhasxbKi+f2dtR5xrgBC18uLbnaBFarlNFCYfr8JAIL2xJpnZw=="], + + "wrangler": ["wrangler@4.157.0", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.5.0", "@cloudflare/unenv-preset": "2.16.2", "@cspotcode/source-map-support": "0.8.1", "blake3-wasm": "2.1.5", "esbuild": "0.28.2", "miniflare": "5.20261103.0-beta", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20261103.1" }, "optionalDependencies": { "fsevents": "2.3.3" }, "peerDependencies": { "@cloudflare/workers-types": "^5.20261103.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js", "cf-wrangler": "bin/cf-wrangler.js" } }, "sha512-HUft0VZiUbt/oFZXQRDmJAGzPgfDYpdVmJwCGlGBcXrE5IP0yGcTwc1u/H3+bUYhaX2NHoL1sdQqn3zptxyFkA=="], + "wrap-ansi": ["wrap-ansi@9.0.2", "", { "dependencies": { "ansi-styles": "^6.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" } }, "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww=="], "ws": ["ws@8.22.2", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA=="], @@ -1941,6 +2321,8 @@ "xmlchars": ["xmlchars@2.2.0", "", {}, "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw=="], + "xxhash-wasm": ["xxhash-wasm@1.1.0", "", {}, "sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA=="], + "y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="], "yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], @@ -1951,12 +2333,16 @@ "yargs-parser": ["yargs-parser@22.0.0", "", {}, "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw=="], - "yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], + "yocto-queue": ["yocto-queue@1.2.2", "", {}, "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ=="], "yocto-spinner": ["yocto-spinner@1.2.2", "", { "dependencies": { "yoctocolors": "^2.1.1" } }, "sha512-DODGl1wJjA/s5pnJFKau9lIYHT81lnhob1i3e1TjxZRxEhWRKl74nTbWE6H5KlkViQQTo/Z29YFdxzTZAMY3ng=="], "yoctocolors": ["yoctocolors@2.2.0", "", {}, "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg=="], + "youch": ["youch@4.1.0-beta.10", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@poppinss/dumper": "^0.6.4", "@speed-highlight/core": "^1.2.7", "cookie": "^1.0.2", "youch-core": "^0.3.3" } }, "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ=="], + + "youch-core": ["youch-core@0.3.3", "", { "dependencies": { "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } }, "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA=="], + "zimmerframe": ["zimmerframe@1.1.5", "", {}, "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA=="], "zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], @@ -1969,16 +2355,34 @@ "@actions/http-client/undici": ["undici@6.29.1", "", {}, "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA=="], + "@astrojs/cloudflare/@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.13.0", "", { "dependencies": { "@types/hast": "^3.0.5", "@types/mdast": "^4.0.4", "picomatch": "^4.0.7", "retext-smartypants": "^6.2.0", "shiki": "^4.5.0", "smol-toml": "^1.9.1", "unified": "^11.0.5", "yaml": "^2.9.1" } }, "sha512-20jxQqnSmpskcGyad7N5l6Xf1gz0UCa6lNde44bEBdaXGpncEYfAZJ142r2ZgzBaG4dUyzGmhqZWv1INU2eiHQ=="], + + "@astrojs/compiler-binding-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" } }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], + + "@astrojs/markdown-satteri/@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.13.1", "", { "dependencies": { "@types/hast": "^3.0.5", "@types/mdast": "^4.0.4", "picomatch": "^4.0.7", "retext-smartypants": "^6.2.0", "shiki": "^4.5.0", "smol-toml": "^1.9.1", "unified": "^11.0.5", "yaml": "^2.9.1" } }, "sha512-LgGLGzoC0wCT3mjDYrxz+hct/tws0enpWsLJW3bswHR3PKgusp/H9xRIT8rTdsyvLM0TcRhhvRL30J2oaZNcqA=="], + "@babel/code-frame/js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], "@babel/core/semver": ["semver@6.3.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ=="], + "@babel/generator/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + "@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], "@babel/helper-compilation-targets/semver": ["semver@6.3.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ=="], "@babel/helper-create-class-features-plugin/semver": ["semver@6.3.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ=="], + "@bruits/satteri-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.1", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ=="], + + "@bruits/satteri-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="], + + "@cloudflare/vite-plugin/miniflare": ["miniflare@5.20261117.0-beta", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.5", "undici": "7.30.1", "workerd": "1.20261117.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" }, "peerDependencies": { "kerberos": "^2.0.0" }, "optionalPeers": ["kerberos"] }, "sha512-D2ygY04wQUmbpwgBhj828piErZoj7UMlXNGr4EWQp/c1PNGHyYOh0dMIyobjwOXiD5Ifl1EaEVAoNuBHK+qtkw=="], + + "@cloudflare/vite-plugin/wrangler": ["wrangler@4.164.0", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.5.0", "@cloudflare/unenv-preset": "2.16.2", "@cspotcode/source-map-support": "0.8.1", "blake3-wasm": "2.1.5", "esbuild": "0.28.2", "miniflare": "5.20261117.0-beta", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20261117.1" }, "optionalDependencies": { "fsevents": "2.3.3" }, "peerDependencies": { "@cloudflare/workers-types": "^5.20261117.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js", "cf-wrangler": "bin/cf-wrangler.js" } }, "sha512-WwM+DL4F+zvz1id0CAPa06CAmTb6nOq1adR+Dy5AdwDsDXH5xDjSmDUUBQQN8KgSEuPCOLvzkrdMDUODIDml1A=="], + + "@cloudflare/vite-plugin/ws": ["ws@8.22.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg=="], + "@codecov/bundler-plugin-core/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], "@dotenvx/dotenvx/commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="], @@ -1993,6 +2397,10 @@ "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], + "@jridgewell/gen-mapping/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + + "@jridgewell/remapping/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + "@octokit/plugin-paginate-rest/@octokit/types": ["@octokit/types@16.0.0", "", { "dependencies": { "@octokit/openapi-types": "^27.0.0" } }, "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg=="], "@octokit/plugin-rest-endpoint-methods/@octokit/types": ["@octokit/types@16.0.0", "", { "dependencies": { "@octokit/openapi-types": "^27.0.0" } }, "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg=="], @@ -2003,6 +2411,8 @@ "@oxc-resolver/binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-55coeOFKHv1ywEcUXJtWU5f+Jr/W5tZDvZig8DLKSwUN1JpROQ4rk/SNOQiFWmaR/VKF4zuFyW1B8JduOSv6Pg=="], + "@poppinss/dumper/supports-color": ["supports-color@10.2.2", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="], + "@preact/preset-vite/magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], "@prefresh/vite/@rollup/pluginutils": ["@rollup/pluginutils@4.2.1", "", { "dependencies": { "estree-walker": "^2.0.1", "picomatch": "^2.2.2" } }, "sha512-iKnFXr7NkdZAIHiIWE+BX5ULi/ucVFYWD6TbAV+rZctiRTY2PL6tsIKhoIOaoskiWAkgu+VsbXgUVDNLHf+InQ=="], @@ -2037,10 +2447,18 @@ "@vitest/expect/tinyrainbow": ["tinyrainbow@2.0.0", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="], + "@vitest/mocker/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + "@vitest/mocker/@vitest/spy": ["@vitest/spy@5.1.0", "", {}, "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A=="], "ajv-formats/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], + "anymatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], + + "ast-v8-to-istanbul/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + + "astro/@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.13.1", "", { "dependencies": { "@types/hast": "^3.0.5", "@types/mdast": "^4.0.4", "picomatch": "^4.0.7", "retext-smartypants": "^6.2.0", "shiki": "^4.5.0", "smol-toml": "^1.9.1", "unified": "^11.0.5", "yaml": "^2.9.1" } }, "sha512-LgGLGzoC0wCT3mjDYrxz+hct/tws0enpWsLJW3bswHR3PKgusp/H9xRIT8rTdsyvLM0TcRhhvRL30J2oaZNcqA=="], + "chalk/supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], "cliui/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], @@ -2053,6 +2471,10 @@ "conf/dot-prop": ["dot-prop@6.0.1", "", { "dependencies": { "is-obj": "^2.0.0" } }, "sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA=="], + "css-select/css-what": ["css-what@6.2.2", "", {}, "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA=="], + + "csso/css-tree": ["css-tree@2.2.1", "", { "dependencies": { "mdn-data": "2.0.28", "source-map-js": "^1.0.1" } }, "sha512-OA0mILzGc1kCOCSJerOeqDxDQ4HOh+G8NbOJFOTgOCzpw7fCBubk0fEyxp8AgOL/jvLgYA/uV0cMbe43ElF1JA=="], + "dom-serializer/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="], "dot-prop/type-fest": ["type-fest@5.10.0", "", { "dependencies": { "tagged-tag": "^1.0.0" } }, "sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA=="], @@ -2065,14 +2487,22 @@ "is-inside-container/is-docker": ["is-docker@3.0.0", "", { "bin": { "is-docker": "cli.js" } }, "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ=="], + "is-wsl/is-docker": ["is-docker@2.2.1", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="], + "jsdom/parse5": ["parse5@8.1.1", "", { "dependencies": { "entities": "^9.0.0" } }, "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w=="], "log-symbols/chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], "log-symbols/is-unicode-supported": ["is-unicode-supported@1.3.0", "", {}, "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ=="], + "mdast-util-find-and-replace/escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="], + "micromatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], + "miniflare/undici": ["undici@7.30.1", "", {}, "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg=="], + + "miniflare/ws": ["ws@8.21.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="], + "npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="], "onetime/mimic-fn": ["mimic-fn@2.1.0", "", {}, "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="], @@ -2083,6 +2513,8 @@ "oxc-parser/@oxc-project/types": ["@oxc-project/types@0.127.0", "", {}, "sha512-aIYXQBo4lCbO4z0R3FHeucQHpF46l2LbMdxRvqvuRuW2OxdnSkcng5B8+K12spgLDj93rtN3+J2Vac/TIO+ciQ=="], + "p-locate/p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="], + "parse5-parser-stream/parse5": ["parse5@8.1.1", "", { "dependencies": { "entities": "^9.0.0" } }, "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w=="], "pkg-up/find-up": ["find-up@3.0.0", "", { "dependencies": { "locate-path": "^3.0.0" } }, "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg=="], @@ -2103,6 +2535,8 @@ "restore-cursor/onetime": ["onetime@7.0.0", "", { "dependencies": { "mimic-function": "^5.0.0" } }, "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ=="], + "shadcn/diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="], + "shadcn/undici": ["undici@7.30.2", "", {}, "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA=="], "storybook/@testing-library/jest-dom": ["@testing-library/jest-dom@6.9.1", "", { "dependencies": { "@adobe/css-tools": "^4.4.0", "aria-query": "^5.0.0", "css.escape": "^1.5.1", "dom-accessibility-api": "^0.6.3", "picocolors": "^1.1.1", "redent": "^3.0.0" } }, "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA=="], @@ -2111,14 +2545,34 @@ "sucrase/commander": ["commander@4.1.1", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="], + "svgo/commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="], + + "svgo/css-select": ["css-select@6.0.0", "", { "dependencies": { "boolbase": "^1.0.0", "css-what": "^7.0.0", "domhandler": "^5.0.3", "domutils": "^3.2.2", "nth-check": "^2.1.1" } }, "sha512-rZZVSLle8v0+EY8QAkDWrKhpgt6SA5OtHsgBnsj6ZaLb5dmDVOWUDtQitd9ydxxvEjhewNudS6eTVU7uOyzvXw=="], + "vite-prerender-plugin/magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], + "vitest/es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], + "wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], "wrap-ansi/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], "wsl-utils/is-wsl": ["is-wsl@3.1.1", "", { "dependencies": { "is-inside-container": "^1.0.0" } }, "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw=="], + "youch/cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], + + "@astrojs/compiler-binding-wasm32-wasi/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g=="], + + "@bruits/satteri-wasm32-wasi/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="], + + "@cloudflare/vite-plugin/miniflare/undici": ["undici@7.30.1", "", {}, "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg=="], + + "@cloudflare/vite-plugin/miniflare/workerd": ["workerd@1.20261117.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20261117.1", "@cloudflare/workerd-darwin-arm64": "1.20261117.1", "@cloudflare/workerd-linux-64": "1.20261117.1", "@cloudflare/workerd-linux-arm64": "1.20261117.1", "@cloudflare/workerd-windows-64": "1.20261117.1" }, "hasInstallScript": true, "bin": { "workerd": "bin/workerd" } }, "sha512-iakDbGVtJRiErpWSM5fYT0z3spJ2Mo1x/POsEajBNLqUbTRwm8vMqbB7g8zPN2tzs6eZYNiO5ECyEnAXO9Foxw=="], + + "@cloudflare/vite-plugin/miniflare/ws": ["ws@8.21.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="], + + "@cloudflare/vite-plugin/wrangler/workerd": ["workerd@1.20261117.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20261117.1", "@cloudflare/workerd-darwin-arm64": "1.20261117.1", "@cloudflare/workerd-linux-64": "1.20261117.1", "@cloudflare/workerd-linux-arm64": "1.20261117.1", "@cloudflare/workerd-windows-64": "1.20261117.1" }, "hasInstallScript": true, "bin": { "workerd": "bin/workerd" } }, "sha512-iakDbGVtJRiErpWSM5fYT0z3spJ2Mo1x/POsEajBNLqUbTRwm8vMqbB7g8zPN2tzs6eZYNiO5ECyEnAXO9Foxw=="], + "@dotenvx/dotenvx/execa/get-stream": ["get-stream@6.0.1", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="], "@dotenvx/dotenvx/execa/human-signals": ["human-signals@2.1.0", "", {}, "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw=="], @@ -2133,6 +2587,8 @@ "@dotenvx/dotenvx/open/define-lazy-prop": ["define-lazy-prop@2.0.0", "", {}, "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og=="], + "@dotenvx/dotenvx/open/is-docker": ["is-docker@2.2.1", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="], + "@dotenvx/dotenvx/which/isexe": ["isexe@3.1.5", "", {}, "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w=="], "@octokit/plugin-paginate-rest/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@27.0.0", "", {}, "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA=="], @@ -2201,16 +2657,40 @@ "conf/dot-prop/is-obj": ["is-obj@2.0.0", "", {}, "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w=="], + "csso/css-tree/mdn-data": ["mdn-data@2.0.28", "", {}, "sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g=="], + "enquirer/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], "jsdom/parse5/entities": ["entities@9.0.0", "", {}, "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg=="], + "p-locate/p-limit/yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], + "parse5-parser-stream/parse5/entities": ["entities@9.0.0", "", {}, "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg=="], "pkg-up/find-up/locate-path": ["locate-path@3.0.0", "", { "dependencies": { "p-locate": "^3.0.0", "path-exists": "^3.0.0" } }, "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A=="], "storybook/open/wsl-utils": ["wsl-utils@0.1.0", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="], + "@cloudflare/vite-plugin/miniflare/workerd/@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20261117.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-qfAYw6iPoey0BmPsp4z5ARWOa+XSBD3gQzmcBI2ql9pKTSA5eEC8F1oI6BIk/FVguhomfSn5gS4RzbWhTd/EpQ=="], + + "@cloudflare/vite-plugin/miniflare/workerd/@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20261117.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-cInx5Cr9O27oW+ujyI49lTRQZra/lMgWUFiKmGY3jxDncATSxzfQ6udXHkVvK4//1/PfxQTDyMjdQUIN8m6Aqg=="], + + "@cloudflare/vite-plugin/miniflare/workerd/@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20261117.1", "", { "os": "linux", "cpu": "x64" }, "sha512-gZLA8X11m/luZwn+YA3+mDu61vdxNJzpksP/QZqjydKTQ+VUCulsK5gtn9Bqst1p3KJu2kafQpJ1nDQv4B23jA=="], + + "@cloudflare/vite-plugin/miniflare/workerd/@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20261117.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-gxWngFojq41ULKNKb9rpWYvKotN5hT2I/xot+Bpy31cXzrwcTgtDLSMb2t75sW5BJxH7hihFvikgYb577kB3Zg=="], + + "@cloudflare/vite-plugin/miniflare/workerd/@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20261117.1", "", { "os": "win32", "cpu": "x64" }, "sha512-0OR2Btx5EDonOKvvuGDq8rxBSggxoF1ThQjbZN3vsu3GlaF/oXW5f9/iB78OgV0CzMPTi+hZgzc1NR95UJCURA=="], + + "@cloudflare/vite-plugin/wrangler/workerd/@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20261117.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-qfAYw6iPoey0BmPsp4z5ARWOa+XSBD3gQzmcBI2ql9pKTSA5eEC8F1oI6BIk/FVguhomfSn5gS4RzbWhTd/EpQ=="], + + "@cloudflare/vite-plugin/wrangler/workerd/@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20261117.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-cInx5Cr9O27oW+ujyI49lTRQZra/lMgWUFiKmGY3jxDncATSxzfQ6udXHkVvK4//1/PfxQTDyMjdQUIN8m6Aqg=="], + + "@cloudflare/vite-plugin/wrangler/workerd/@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20261117.1", "", { "os": "linux", "cpu": "x64" }, "sha512-gZLA8X11m/luZwn+YA3+mDu61vdxNJzpksP/QZqjydKTQ+VUCulsK5gtn9Bqst1p3KJu2kafQpJ1nDQv4B23jA=="], + + "@cloudflare/vite-plugin/wrangler/workerd/@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20261117.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-gxWngFojq41ULKNKb9rpWYvKotN5hT2I/xot+Bpy31cXzrwcTgtDLSMb2t75sW5BJxH7hihFvikgYb577kB3Zg=="], + + "@cloudflare/vite-plugin/wrangler/workerd/@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20261117.1", "", { "os": "win32", "cpu": "x64" }, "sha512-0OR2Btx5EDonOKvvuGDq8rxBSggxoF1ThQjbZN3vsu3GlaF/oXW5f9/iB78OgV0CzMPTi+hZgzc1NR95UJCURA=="], + "pkg-up/find-up/locate-path/p-locate": ["p-locate@3.0.0", "", { "dependencies": { "p-limit": "^2.0.0" } }, "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ=="], "pkg-up/find-up/locate-path/path-exists": ["path-exists@3.0.0", "", {}, "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ=="], diff --git a/package.json b/package.json index 7f10dd7..94cf5af 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,13 @@ "scripts": { "build": "turbo run build", "dev": "turbo run dev", + "apidocs:astro:dev": "bun run --cwd apps/apidocs-astro dev", + "apidocs:astro:build": "bun run --cwd apps/apidocs-astro build", + "apidocs:astro:preview": "bun run --cwd apps/apidocs-astro preview", + "apidocs:audit": "bun run --cwd packages/apidocs audit", + "apidocs:dev": "bun run --cwd packages/apidocs dev", + "apidocs:guides": "bun run --cwd packages/apidocs guides", + "apidocs:sample": "bun run --cwd packages/apidocs sample", "lint": "turbo run lint", "test": "turbo run test", "test:preact": "turbo run test --filter=@elide/preact", diff --git a/packages/apidocs/AUDITS.md b/packages/apidocs/AUDITS.md new file mode 100644 index 0000000..8a67190 --- /dev/null +++ b/packages/apidocs/AUDITS.md @@ -0,0 +1,108 @@ +# Audits + +`bun run audit` (or `bun run apidocs:audit` from the repository root) builds the samples with `dist/runner.mjs`, +exactly as the doclet does, serves each site on its own free localhost port, and runs three audits. It prints one table +row per audit target, writes full reports to a fresh temporary directory (its path is printed; `--out` picks one), and +exits 1 when a score is below its threshold. + +```sh +export PLAYWRIGHT_BROWSERS_PATH=/path/to/ms-playwright # a Playwright 1.65 browser directory (chromium-1254) +bun run audit # both samples, both presets; Lighthouse on java-elide +bun run audit --only agentic,css # no browser; about a second +bun run audit --only lighthouse --form-factor mobile +bun run audit --model path/to/api.json --preset elide # a real model; Ir.html as the largest page if present +bun run audit --host agent # serve with Markdown negotiation and Link headers +bun run audit --threshold-lighthouse 95 --threshold-agentic 90 --threshold-css 0 +``` + +To audit a site that is already served, such as the Astro sample app (`bun run apidocs:astro:preview`, or its +test server on port 5191), pass its base URL: + +```sh +bun run audit --url http://127.0.0.1:5190/java/2.0/ # Lighthouse and agent readiness; nothing is built +``` + +The audit reads the site's `llms.txt` for its pages, fetches each at its Astro URL, and saves it in the static layout +(`X.html`, its links mapped back to the static form) for the checks that read files; the checks that make requests, +and Lighthouse, go to the server. The CSS audit needs the stylesheet files, so it runs on static builds only. + +Other flags: `--sample java,kotlin`, `--preset neutral,elide`, `--page <path.html>` (the largest type page to use), +`--theme theme.json` (merged over the preset), `--lighthouse-sites first|all`, `--no-base-url`, `--no-build`, `--json`. +`test/audit.test.ts` covers the rule logic and runs the agent-readiness audit over the Java sample; it does not run +Lighthouse. + +To compare two runs, keep each run's `--out` directory and diff `summary.md` (or `summary.json`). + +## Thresholds + +Every threshold defaults to 100. A Lighthouse row passes when the lowest of performance, accessibility, best practices +and SEO meets it. The agentic-browsing category (`AG` in the table) is reported, not gated. The agent-readiness row uses +the score below; the CSS row is the share of the nine mechanical good-css rules with no violation. + +## Lighthouse + +Lighthouse 13.6.0 (pinned) runs programmatically in the Chromium that Playwright installs, through chrome-launcher, once +per page and form factor (mobile is Lighthouse's default config; desktop uses `desktop-config.js`). It audits the module +overview, the package page with the most types, the smallest type page with real content, and the largest type page +(`ShapeCatalog.html` in the Java sample; `dev/elide/kotlin/api/Ir.html` in the Komodo model). Each run's JSON and HTML +report, and a summary of the failing weighted audits with their values, are in `lighthouse/`. + +The pages are served the way a static host would serve them: brotli or gzip, `Cache-Control: public, max-age=31536000` +on `assets/` and revalidation on pages, strong ETags, a real 404. These results depend on the server, not the pages: +`uses-text-compression`, `cache-insight` (cache lifetimes), `modern-http-insight` (HTTP/2: the audit server speaks +HTTP/1.1, and Lighthouse does not flag HTTP/1.1 on localhost), `document-latency-insight`, `server-response-time`, +`redirects`, `is-on-https` (localhost counts as secure) and the security-header diagnostics (`csp-xss`, `has-hsts`, +`origin-isolation`, `clickjacking-mitigation`). The year-long asset cache is only safe on a real host if asset names +change with their content, which today they do not. Throttling is Lighthouse's simulated default, so performance on +a loaded machine still varies by a few points. + +## Agent readiness ("is-agentic") + +[Is Agentic](https://is-agentic.com) (Vercel Labs) scores a public website from 0 to 100 for AI agents. Its checks are +run by [Ora](https://ora.ai); its [methodology](https://is-agentic.com/methodology) describes the score. Its CLI, +[`is-agentic` on npm](https://www.npmjs.com/package/is-agentic), only fetches or starts a hosted scan of a public URL, +so it cannot audit localhost or a directory, and the audit never submits anything to it. + +The check catalog and the scoring formula are public in every report (for example +[a report page](https://is-agentic.com/scan/vercel.com)) and at +[Ora's rules, version 2](https://ora.ai/api/ranker/releases/2/rules). `scripts/audit/agentic.ts` implements, locally, +the checks that apply to a documentation site (Ora's `content` site type): + +- the 15 required checks: content without JavaScript, metadata completeness, JSON-LD, llms.txt exists, sitemap, + noindex, robots.txt AI-crawler and agent-user policy, crawler reachability, bot detection, content behind auth, + redirect hygiene, page token budget (100,000 characters of text), agent-friendly 404s, trust anchors; +- the gated checks that follow: llms.txt formatting and links, schema type breadth; +- the bonus checks a reference can earn: sitemap lastmod, agent instruction in llms.txt, Link headers, Markdown + negotiation, and the five accessibility-tree checks (`ax-*`); +- the emerging, unscored checks: Markdown alternate link, `.md` URL fallback, Markdown frontmatter, code fences, + Markdown agent docs, modular llms.txt. + +The score follows Ora's formula: layer weights accessibility 30, discovery 20, usability 40 (payments has no checks +here); emerging checks unscored; bonus checks count only what they earn. It is an approximation of the hosted score: +Ora's partial-credit thresholds are not all published, and the values used are in the code next to each check. Is +Agentic's own display groups checks as Essential (80 points), Recommended (20) and Bonus (5); that grouping per site +type is not published, so the audit reports Ora's score. + +Each finding names an owner: `page` (markup, CSS, client script), `output` (files the renderer writes: llms.txt, +sitemap.xml, robots.txt, 404 pages, JSON-LD content) or `host` (status codes, headers, negotiation). `--host agent` +serves each page's `.md` twin for `Accept: text/markdown` with `Vary: Accept` and adds Link headers, to show the score +with a host that does that. + +Not testable locally: trust-anchor pages (about, contact, privacy belong to the host site; reported as not applicable), +a real host's WAF and bot rules (the local server treats every user agent alike), search ranking and brand +discoverability, Wikipedia presence, registry listings, and everything about APIs, OAuth, MCP servers and payments, +which do not apply to a generated reference. + +## good-css.com + +[good-css.com](https://good-css.com) is a guideline, not a tool: 47 modern CSS techniques in eight categories, each with +its rules and sources, written for agents ([llms.txt](https://good-css.com/llms.txt)). It has no score. Its +[agent skill](https://good-css.com/skills/good-css/SKILL.md) lists nine rules for all CSS, which `scripts/audit/css.ts` +checks mechanically over the shipped `assets/apidocs.css` and `assets/theme.css`, each violation with its line and +selector: logical properties (including multi-value margin and padding shorthands), `oklch()` colors with `none` as a +gray's hue, fluid sizes in `clamp()` rather than width breakpoints, `:hover` only inside +`@media (hover: hover) and (pointer: fine)`, `:focus-visible` and never `outline: none`, an `:active` state for +everything pressable (approximated: every `:hover` selector has a matching `:active`), motion inside +`prefers-reduced-motion: no-preference`, named transition properties without `all` or `ease-in` and at most 300 ms, +`overflow: clip` over `hidden`, and the declarations the skill leaves out on purpose. The 47 entries need judgment +about where they apply, so each gets a `review` row in the report with what the stylesheet shows; a person settles it. diff --git a/packages/apidocs/README.md b/packages/apidocs/README.md new file mode 100644 index 0000000..8ed3159 --- /dev/null +++ b/packages/apidocs/README.md @@ -0,0 +1,403 @@ +# @elide/apidocs + +Static API reference pages, as HTML and Markdown, from the `apidocs/1` model that Elide's Javadoc doclet and Dokka +plugin write. Pages are prerendered with Preact. They work from `file://`, from any path prefix and inside a +`-javadoc.jar`. Branding is a theme input; the package's own components carry none. + +## What it builds + +`bun run build` writes `dist/`: + +| File | What it is | +| --- | --- | +| `render.js` | One classic script (IIFE) that defines the global `ApiDocs = { schema, render }`. Preact and the highlighter are inlined. `render(model, theme)` is a pure function: no file, network, Node, Bun or DOM API. | +| `runner.mjs` | Runs `render.js` in Bun or Node and writes the site. The JVM tools ship it with `render.js` and `assets/`. | +| `assets/` | `apidocs.css`, `apidocs.js` (the client islands, Preact inlined, loaded with `defer`) and the fonts the Elide preset uses. | +| `apidocs-1.schema.json` | The model's JSON Schema. `src/model.ts` is generated from it. | + +```sh +node dist/runner.mjs --bundle dist/render.js --assets dist/assets --model api.json --theme theme.json --out site/ +``` + +The runner prints `{"files":N,"bytes":N,"renderMs":N}` and exits 0, or prints the error and exits 1. It never reaches +the network. + +## Output + +Every page has an `.html` and an `.md` twin: `index`, `<package/path>/index` and `<package/path>/<Type>`, with nested +types as `Outer.Inner`. The root also holds `llms.txt`, `llms-full.txt`, `api.json`, `element-list` and `assets/`. +With a theme `baseUrl` it also has `sitemap.xml`, and pages carry canonical links. Every link is relative and names +its file. Scripts are classic. Search reads `assets/search-index.js`, which assigns a global, so nothing uses `fetch`. +With JavaScript off, pages keep all their content; only search, the theme switch, copy buttons and table-of-contents +tracking go away. + +## Guides + +A module can carry narrative guides in `module.guides`: `{ id, slug, title, summary?, group?, order?, body?, +source? }`. The body is the same block tree as a documentation comment, plus `admonition` blocks (`tone`: note, tip, +important, warning, caution, apiNote, implSpec, implNote; optional `title`). Each guide is `guides/<slug>.html` and +`.md`. Its headings get readable anchors (the heading's `anchor`, or its text slugified), deduplicated with `-2`, +`-3`; level-2 and level-3 headings fill "On this page". A link targets a guide with `target: { id }` and a section +with `target: { id, section }`, from guides and from doc comments; an unresolved one renders as plain text, and the +output checker reports a link to a section that does not exist. Pages list ungrouped guides first, then each group +in the order of its first guide; inside each, guides with an `order` come first, lowest first. Guides appear on the +overview, in the navigator, in search (guides and sections), in `llms.txt` before the reference pages, in +`llms-full.txt` after the overview, and in `sitemap.xml`. + +A model may name one guide as `module.overview`: that guide is the overview page (`index.html`) instead of a page +under `guides/`, and the package lists follow it when there are packages. A model with guides and no packages is a +guides-only site: no package block in the navigator, no package, type or A-Z index pages and no `element-list`; the +overview, search, `llms.txt`, `llms-full.txt`, Markdown twins and `sitemap.xml` cover the guides. A guide's +`navTitle` is its label in the navigator. A group's crumb links to the group's first guide when that guide has the +group's title, as a suite's `index.md` does. + +## Markdown suites + +`apidocs guides` builds a documentation site from a directory of Markdown files, with the same components, design and +outputs as an API reference. The importer (`src/import/markdown.ts`) reads the layout and frontmatter of Astro +Starlight's docs collection, so a suite written for Starlight imports unchanged. + +```sh +bun src/cli.ts guides --src docs/user --id user --title "Komodo user guide" --out site/user \ + --theme theme.json --version 1.2.0 --base-url https://example.com/user/ \ + --source-link 'https://github.com/o/r/blob/main/{path}#L{line}' --source-root docs/user \ + --link ../developer/=../developer/ --link ../api/=https://example.com/api/ +``` + +From the repository root, `bun run apidocs:guides -- <arguments>` runs the same command. + +| Option | What it does | +| --- | --- | +| `--src`, `--id`, `--title`, `--out` | Required. The suite's directory; its id, which namespaces guide ids (`guide:<id>/<path>`); the site's title; the output directory. | +| `--theme <file>` | A theme JSON file, as for API sites. | +| `--version` | The version the top bar and `llms.txt` show. | +| `--base-url <url/>` | The site's address: canonical links and `sitemap.xml`. | +| `--source-link <template>`, `--source-root <path>` | Source links on every page: `{path}` is `<source-root>/<file>`, `{line}` is 1. | +| `--link <prefix>=<target>` | Repeatable. A link that leaves the suite, resolved from the suite's root, that starts with `prefix` goes to `target` plus the rest of its path. `target` is an absolute URL or a path from the site's root. A rest that names a Markdown file becomes that page in a site this command built: `index.md` is `index.html`, `a/b.md` is `guides/a/b.html`. | +| `--include-drafts` | Include pages with `draft: true`. | +| `--warn-only` | Report errors as warnings and write the site anyway. | +| `--assets <dir>` | Take the stylesheet, client script and fonts from a directory instead of the sources and `dist/assets/apidocs.js` (built when missing or stale). | + +It writes the same files as an API site, plus the suite's images under `guides/`, and adds to `--out` without +deleting anything. Diagnostics go to stderr as `<src>/<file>:<line>: message` (`warning: ` before a warning's +message). The exit status is 1 when there is an error (nothing is written), 2 for bad arguments, and 0 otherwise, +with one JSON line of counts on stdout. + +For programmatic use, `@elide/apidocs/import` exports `importMarkdown(files, options)`, `readSuite(dir)`, +`suiteSite(dir, options)`, `guidesModel(result, module)` and `formatDiagnostic`. The root export, `render.js` and the +client bundle do not include the importer. + +`bun run dev --guides <dir>` serves a suite through the dev server; editing, adding or removing a file reloads the +page. The dev bar also offers the Markdown sample suite, `samples/guides`. + +### What the importer reads + +- **Files.** Every `.md` file is a page; paths become URLs, so names should be lower-case kebab-case (others are + slugified, with a warning). The root `index.md` is the overview page. Each directory is a group, titled by its + `index.md`; a nested directory is a group named `Parent › Child`. Pages read in this order: the overview, the root's + other pages, then each group (its `index.md` first, then its pages, then its subgroups). Pages and groups sort by + `sidebar.order` (a group by its index's), then by name. +- **Frontmatter.** `title` (required), `description` (the summary listings, search and `llms.txt` show; a warning when + missing), `sidebar.label` (the navigator label; an `index.md` without one is "Overview"), `sidebar.order`, and + `draft: true` (left out unless `--include-drafts`). Any other key is an error naming the file, line and key, unless + `importMarkdown`'s `extraKeys` lists it (`template`, `sidebar.badge`). +- **Markdown.** CommonMark with GitHub's tables, task lists, strikethrough and autolinks; fenced code with its + language (`text` without one); GitHub alerts (`> [!NOTE]`, `[!TIP]`, `[!IMPORTANT]`, `[!WARNING]`, `[!CAUTION]`) as + admonitions. The title is the page's heading, so the body starts at `##`: `##` is a section and `###` a subsection + in "On this page". `## Heading {#id}` sets a heading's anchor. HTML comments, the sync block among them, are + dropped. Other raw HTML becomes a raw node, which the renderer passes through its allowlist sanitizer. +- **Links.** A relative link to a `.md` file becomes a reference to that guide, and a `#fragment` a reference to its + section; both are checked at import. A fragment matches the renderer's anchor, the heading's `{#id}` or GitHub's + slug of the heading. A missing file or heading, a link outside the suite with no `--link` mapping, and an unsafe URL + are errors with file and line. A link to a draft that is left out is a warning and shows as text. Absolute URLs + pass through `safeUrl()`. +- **Images.** `![alt](path "title")` with the image in the suite is copied to `guides/<path>` and gets its width and + height from the file (PNG, GIF, JPEG, WebP, SVG). The alternative text is required. A link to an image in the suite + copies it too. + +### Copied files and hosting + +Only images are copied: `png`, `jpg`, `jpeg`, `gif`, `webp`, `avif` and `svg`, by the final extension. A name with a +second document-like extension (`shot.html.png`) or ending in a dot or a space is refused, and so is every other +type, with an error at the link. An SVG is rebuilt from an allowlist of drawing elements and presentation attributes +(`src/import/svg.ts`): scripts, styles, `foreignObject`, embedded images, links, animation and event handlers go, an +`href` survives only as a `#fragment` and `url()` only as a whole value `url(#fragment)`. A presentation value with a +backslash (a CSS escape) or a control character is dropped, and so is any `style`. An SVG with a DOCTYPE, CDATA or markup +that does not parse is refused. Symbolic links in the suite are not followed, and files are written from the bytes +read at import. + +A host should serve the copied files under `guides/` with `X-Content-Type-Options: nosniff`, and anything that is not +an image the pages embed with `Content-Security-Policy: sandbox`. + +### Not supported + +- MDX (`.mdx` pages are an error) and Starlight components and asides (`:::note`); use GitHub alerts. +- Footnotes (an error at the reference and the definition). +- Downloads other than images, raw `<img>` and other embedded media in HTML (the sanitizer drops them), and image + sizes set in Markdown. +- Starlight frontmatter beyond `title`, `description`, `sidebar.label`, `sidebar.order` and `draft`: `template`, + `hero`, `banner`, `sidebar.badge`, `sidebar.hidden` and the rest are errors unless accepted as extra keys, and then + ignored. +- Redirects, `lastUpdated`, edit links other than the source link, and ordered lists that start at a number other + than 1. + +## Themes + +A theme is JSON: + +```json +{ + "extends": "elide", + "productName": "Komodo", + "links": { "header": [{ "label": "GitHub", "url": "https://github.com/elide-dev/komodo" }] }, + "sourceLink": "https://github.com/elide-dev/komodo/blob/{ref}/{path}#L{line}", + "sourceRef": "main", + "baseUrl": "https://example.com/api/", + "tokens": { "light": { "accent": "#6d28d9" }, "dark": { "accent": "#c4b5fd" } }, + "css": ".member { scroll-margin-top: 80px; }" +} +``` + +The stylesheet reads only `--apidocs-*` custom properties; `tokens` sets them without the prefix (see the top of +`src/styles/apidocs.css` for the names). `extends` picks a preset. `neutral` is the default and is unbranded. +`elide` maps the tokens to `@elide/tokens` and takes its logo from `@elide/brand`. A theme can also set `logo` +(SVG markup for light and dark), `favicon`, `fonts` and `footer`. + +## Astro + +`@elide/apidocs/astro` serves the same pages from an Astro app (Astro 7), rendered on request or from models the app +has when it builds, with the same components and stylesheet. + +Use the static renderer for output that must work anywhere: a `-javadoc.jar`, `file://`, any static host. Use the +Astro integration for a docs site you run: pages render on demand from models in storage, navigation goes through +Astro's client router (the top bar and the navigator stay put while the content cross-fades), and parts that change +more often than the pages, such as a version menu, come from server islands so the pages stay cacheable. + +### URLs + +A site lives under a base path that starts and ends with `/` (`/api/komodo/main/`; `/` itself is allowed). Under it: + +| Page | Static file | Astro URL | +| --- | --- | --- | +| Overview | `index.html` | the base itself | +| Package | `com/example/geo/index.html` | `com/example/geo/` | +| Type, guide, index page | `com/example/geo/Circle.html` | `com/example/geo/Circle` | +| Anything else | `Circle.md`, `llms.txt`, `api.json`, ... | the same path | + +The static paths redirect (301) to the Astro URLs, and so do `com/example/geo` (a package without its slash) and +`com/example/geo/Circle/`. Keep Astro's `trailingSlash` at `"ignore"`. Every link in a page is root-absolute in this +form. + +### The contract + +From `@elide/apidocs/astro` (`.astro` files and TypeScript; plain code outside Astro's Vite pipeline imports the +same functions from `@elide/apidocs/astro/helpers`): + +- `resolvePage(model, path, theme?)`: what `path` (relative to the base, no leading slash) is. + `{ kind: "page", page }`, `{ kind: "markdown", page }`, `{ kind: "file", name }`, `{ kind: "redirect", to }` or + `{ kind: "missing" }`. `to` is relative to the base and never leaves it: no scheme, leading `/`, backslash or `..`. +- `<ApidocsPage model page theme base site? />`: the whole document for a page. Slots: `topbar` (replaces the module's + version, beside the brand), `notice` (one line above the page) and `head`. Canonical URLs use `site`, else + `Astro.site`, else the request's origin; a theme's `baseUrl` wins. +- `renderText(model, path, theme?)`: `{ body, contentType }` for a Markdown twin (`${page}.md`), `llms.txt`, + `llms-full.txt`, `api.json`, `element-list`, `sitemap.xml` (when the theme has a `baseUrl`), the search index + (`assets/search-index.js`, and `assets/search-index.json` in the Astro form), `assets/theme.css` and the theme's + artwork. `llms.txt`, `llms-full.txt` and `element-list` render the whole site once per model object and keep only + those three; everything else renders alone. +- `prefersMarkdown(accept)`, `linkHeader(base, page)` and `notFound(base, title, accept)`: serve a page's Markdown + twin at its URL to a client that asks for Markdown, point at the other forms in a `Link` header, and answer a + missing page with directions. +- `<VersionSelect versions current path />` and `<VersionNotice versions current path />`: a version menu for the top + bar and a "not the latest release" line, each a fixed box (see "Server islands"). A `Version` is + `{ id, label?, base, channel?: "release" | "prerelease" | "development", latest? }`. +- `apidocs(options)`, from `@elide/apidocs/astro/integration` in `astro.config`: routes for sites whose models the app + has at build time. +- `assertBase(base)`: throws for a base that is not an absolute path with a single leading `/` and a trailing `/`. + +The search island is Preact: the app needs `@astrojs/preact`. `apidocs()` adds it (and keeps one copy of Preact), so an +app that renders on request adds `apidocs()` with no sites. An app that also uses React gives each renderer `include` +patterns. Astro bundles the stylesheet, the client script and the Elide preset's fonts as hashed files under +`/_astro/`; a theme's tokens are inlined. Nothing under `assets/` needs copying unless a theme names its own fonts, +which resolve to `assets/fonts/...` under the base. + +Keep the parsed model object between requests (per version, say): the site structure and each page's data are +cached in `WeakMap`s keyed by it. + +### On request + +The models live in storage; the app's own catch-all route does what `apidocs()` would: + +```astro +--- +// src/pages/api/[version]/[...path].astro +import { ApidocsPage, assertBase, linkHeader, notFound, prefersMarkdown, renderText, resolvePage } from "@elide/apidocs/astro"; +import { loadModel } from "../../../models"; // the app's: api.json from R2, parsed once per version and kept + +const { version } = Astro.params; +const base = `/api/${version}/`; +assertBase(base); +const model = await loadModel(version); +if (!model) return notFound("/api/", "API reference", Astro.request.headers.get("accept")); +const theme = { extends: "elide" as const, productName: "Komodo" }; +const path = Astro.url.pathname.slice(base.length); +const resolved = resolvePage(model, path, theme); +if (resolved.kind === "redirect") return Astro.redirect(base + resolved.to + Astro.url.search, 301); +if (resolved.kind === "missing") return notFound(base, model.module.name, Astro.request.headers.get("accept")); +if (resolved.kind !== "page" || prefersMarkdown(Astro.request.headers.get("accept"))) { + const text = renderText(model, resolved.kind === "file" ? resolved.name : `${resolved.page}.md`, theme); + if (!text) return notFound(base, model.module.name, null); + return new Response(text.body, { headers: { "content-type": text.contentType, vary: "Accept" } }); +} +Astro.response.headers.set("vary", "Accept"); +Astro.response.headers.set("link", linkHeader(base, resolved.page)); +--- +<ApidocsPage model={model} page={resolved.page} theme={theme} base={base} /> +``` + +### At build time + +```js +// astro.config.mjs +import cloudflare from "@astrojs/cloudflare"; +import { apidocs } from "@elide/apidocs/astro/integration"; +import { defineConfig } from "astro/config"; + +export default defineConfig({ + adapter: cloudflare(), + integrations: [ + apidocs({ + sites: [ + { base: "/java/2.0/", model: "./models/java-2.0.json", theme: { extends: "elide" }, version: "2.0" }, + { base: "/java/main/", model: "./models/java-main.json", theme: { extends: "elide" }, version: "main" }, + ], + versions: "./src/versions.ts", // exports `versions`, and optionally `loadVersions(request)` + }), + ], +}); +``` + +`model` is a path from the project root to an `api.json`, or to a module whose default export is the model. Each site +gets a route at `${base}[...path]` that resolves, redirects, serves text (with Markdown negotiation and `Link` +headers) and renders pages, on request. With `versions`, the route puts the version menu and, on versions that are +not the latest release, the notice in server islands. `astro dev` reloads when a model, a component or a sample +changes, and updates the stylesheet in place. + +### Server islands + +A server island renders after the page, from its own request, so the page can be cached while the island shows +something newer. The pattern, as the integration uses it: + +```astro +--- +// VersionIsland.astro, the app's own: reads the newest versions.json on each request. +import { VersionSelect } from "@elide/apidocs/astro"; +const { current, path } = Astro.props; +const versions = await loadVersionsFromR2(); // the app's +Astro.response.headers.set("cache-control", "public, max-age=60, stale-while-revalidate=600"); +--- +<VersionSelect versions={versions} current={current} path={path} /> +``` + +```astro +<ApidocsPage model={model} page={page} theme={theme} base={base}> + <VersionIsland server:defer slot="topbar" current={id} path={path}> + <VersionSelect slot="fallback" versions={versionsWhenRendered} current={id} path={path} /> + </VersionIsland> +</ApidocsPage> +``` + +The fallback is the same component rendered from the versions known when the page rendered: a working menu with +JavaScript off, and the same closed box (the current version's label) as the island's, so the swap moves nothing. +`<VersionNotice>` goes in the `notice` slot the same way; render it only on versions that are not the latest release. +Island props travel encrypted in the island's URL, so set `ASTRO_KEY` (`astro create-key`) when pages outlive a +deploy, or cached pages will ask for islands with a key the new deploy cannot read. + +### Caching + +A page's HTML depends only on the model, the theme, the base and the site's origin: cache it per URL for as long as +the version's model does not change (a released version's never does), and vary it on `Accept` when Markdown +negotiation is on. What changes more often goes in server islands, which have their own `Cache-Control` (the +integration's: one minute, then stale while revalidating). The `/_astro/` files are named by their content and can be +cached for a year. + +### Behaviors + +| Behavior | How it runs on an Astro page | +| --- | --- | +| Search | A Preact island, `client:idle`, in the top bar. Loads `assets/search-index.json` on first focus or keystroke; opens results through the router. The top bar persists, so it hydrates once per site. | +| Theme switch, navigator toggle and `[`, copy buttons, copy as Markdown, member expand and collapse, open-on-hash, list filters, "On this page" tracking, menus | The static page's functions (`src/client/behaviors.tsx`), started on `astro:page-load` and stopped on `astro:before-swap` through one `AbortController` per page: no listener outlives its page. | +| Top bar and navigator | `transition:persist`, keyed by the site's base: across pages of one site they are the same elements, so the navigator keeps its scroll position and filter text without a script restoring them. Before each swap the client moves the new page's index links and navigator rows into them. | +| Theme and `data-js` | The head script sets them on first load; the client carries them to each new page's `<html>`, whose attributes the router replaces. | +| Load bar | Starts on `astro:before-preparation`, finishes on arrival, clears if the navigation is aborted. | +| Page transition | The router's view transition, with the static stylesheet's `::view-transition` rules: the content fades and rises 6px, the top bar and navigator do not move. The browser's cross-document transitions are off on Astro pages, so the two never both run. With reduced motion nothing animates. | +| Prefetch | The router's, on hover, for same-site links. The static pages' speculation rules are not on Astro pages. | +| Version menu and notice | Server islands; the client keeps their links on the page being read. | + +The router announces each new page (its title) to assistive technology and restores scroll on back and forward; +focus starts from the top of the new page, except that a keyboard user who followed a navigator row stays on it. + +The sample app, `apps/apidocs-astro`, serves the Java sample at `/java/2.0/` and `/java/main/`, the Kotlin sample at +`/kotlin/` and the Markdown sample suite at `/guides/`, on the Cloudflare adapter: + +```sh +bun run apidocs:astro:dev # astro dev on http://127.0.0.1:5190/ +bun run apidocs:astro:build +bun run apidocs:astro:preview # wrangler dev on http://127.0.0.1:5190/ +bun run --cwd apps/apidocs-astro test # builds, serves on 5191, and drives it in Chromium +``` + +Astro 7 runs `astro dev` in the background when it detects an AI agent; set `ASTRO_DEV_BACKGROUND=1` to keep it in the +foreground. + +## Development + +From this directory (or from the repository root with `bun run apidocs:dev` and `bun run apidocs:sample`): + +```sh +bun run dev # http://127.0.0.1:5180/, opens the browser +bun run dev --port 5190 --no-open +bun run dev --model ../../../../../bazel-bin/tools/release/komodo-api-api.json # a real model +``` + +The dev server renders pages with the production `render()` and the same components, under +`/site/<model>/<preset>/`. Editing a component, the stylesheet, a theme preset, a sample or the `--model` file +reloads the page. In dev, the islands run as a module; the built pages load the `defer` bundle instead. The bar at the +top is for development only and is not part of any output. It switches the model (Java sample, Kotlin sample, the +`--model` file), the theme preset, light or dark, the viewport width, and JavaScript off for the current page. + +To check the portable output in the same loop, build it exactly as the doclet will: + +```sh +bun run sample # the Java sample, neutral theme, into dist/sample/java-neutral/ +bun run sample --sample kotlin --preset elide --open # opens it from file:// +bun run sample --model path/to/api.json --serve # serves it on http://127.0.0.1:5181/ +bun run sample --runtime node # run the runner with Node instead of Bun +``` + +It runs `bun run build` first (`--no-build` skips that), then `dist/runner.mjs`, and prints the `file://` URL. + +### The samples + +`samples/java.ts` and `samples/kotlin.ts` are hand-written models in the doclet's and the Dokka plugin's flavors. +One generated type has hundreds of members. [`samples/FEATURES.md`](samples/FEATURES.md) lists each feature and the +page that shows it, and says how to add one. + +## Tests + +`bun test` (turbo runs `build` first): + +- the samples and the Komodo doclet's fixture model (`test/fixtures/fixture-java.api.json`) validate against the + schema; `src/model.ts` and the Elide artwork module are current; +- HTML and Markdown snapshots of the fixture's pages; +- the output checker (`test/check.ts`) over every model and preset: no absolute URLs other than the model's externals + and theme links, no module scripts, no `fetch`, and no link to a missing file or anchor; +- the Markdown importer (`test/import.test.ts`): each construct, the diagnostics fixture + (`test/fixtures/guides-errors`), hostile Markdown and SVG, copied-file rules, the sample suite as a guides-only site + through the output checker, the CLI, and Komodo's two suites when this package sits inside Komodo; +- in Chromium, a site built with `dist/runner.mjs` opened from `file://` with JavaScript on and off, and axe on the + page shell in light and dark; the same for the Markdown sample suite built with `apidocs guides` + (`test/guides-browser.test.ts`). Locally, point `PLAYWRIGHT_BROWSERS_PATH` at a Playwright 1.65 browser directory, or + install one with `bunx playwright install chromium`. +- the Astro helpers (`test/astro.test.ts`): every page and text file of every sample resolves in both URL forms and + renders as the static renderer does, head metadata equals the static page's apart from the URL form, and hostile + links and paths never leave the site's base. The sample app's own suite drives the Astro pages in Chromium. diff --git a/packages/apidocs/package.json b/packages/apidocs/package.json new file mode 100644 index 0000000..6325499 --- /dev/null +++ b/packages/apidocs/package.json @@ -0,0 +1,87 @@ +{ + "name": "@elide/apidocs", + "version": "0.0.0", + "private": true, + "description": "Static API reference pages (HTML and Markdown) from the apidocs/1 model that Elide's Javadoc doclet and Dokka plugin write. Prerendered with Preact; works from file:// and inside a -javadoc.jar.", + "license": "UNLICENSED", + "type": "module", + "sideEffects": [ + "*.css", + "./src/astro/client.ts", + "./src/client/islands.tsx" + ], + "exports": { + ".": "./src/index.ts", + "./import": "./src/import/index.ts", + "./astro": "./src/astro/index.ts", + "./astro/helpers": "./src/astro/helpers.ts", + "./astro/integration": "./src/astro/integration.ts", + "./samples": "./samples/index.ts", + "./schema": "./schema/apidocs-1.schema.json", + "./render.js": "./dist/render.js", + "./assets/*": "./dist/assets/*" + }, + "bin": { + "apidocs": "./src/cli.ts" + }, + "files": [ + "dist", + "schema", + "src", + "README.md" + ], + "scripts": { + "audit": "bun scripts/audit.ts", + "build": "bun scripts/gen-types.ts --check && bun scripts/gen-artwork.ts --check && vite build --config vite.render.config.ts && vite build --config vite.client.config.ts && bun scripts/assets.ts", + "dev": "bun scripts/dev.ts", + "sample": "bun scripts/sample.ts", + "generate": "bun scripts/gen-types.ts && bun scripts/gen-artwork.ts", + "guides": "bun src/cli.ts guides", + "lint": "tsc -p tsconfig.json --noEmit", + "test": "bun test" + }, + "dependencies": { + "@elide/brand": "workspace:*", + "@elide/tokens": "workspace:*", + "@fontsource-variable/instrument-sans": "^5.3.0", + "@fontsource-variable/inter": "^5.3.0", + "@fontsource-variable/jetbrains-mono": "^5.3.0", + "preact": "^11.2.0", + "preact-render-to-string": "^6.8.2" + }, + "devDependencies": { + "@astrojs/preact": "6.1.6", + "@types/bun": "^1.3.0", + "@types/mdast": "4.0.4", + "astro": "7.4.7", + "axe-core": "4.14.0", + "chrome-launcher": "1.2.3", + "lighthouse": "13.6.0", + "mdast-util-from-markdown": "2.1.0", + "mdast-util-gfm": "3.1.0", + "micromark-extension-gfm": "3.0.0", + "node-html-parser": "6.1.13", + "playwright": "^1.65.0", + "postcss": "8.5.32", + "typescript": "^7.0.2", + "vite": "^8.3.6", + "yaml": "2.9.1" + }, + "peerDependencies": { + "@astrojs/preact": "^6.1.6", + "astro": "^7.4.7" + }, + "peerDependenciesMeta": { + "@astrojs/preact": { + "optional": true + }, + "astro": { + "optional": true + } + }, + "repository": { + "type": "git", + "url": "git+https://github.com/elide-dev/components.git", + "directory": "packages/apidocs" + } +} diff --git a/packages/apidocs/samples/FEATURES.md b/packages/apidocs/samples/FEATURES.md new file mode 100644 index 0000000..acdcb15 --- /dev/null +++ b/packages/apidocs/samples/FEATURES.md @@ -0,0 +1,99 @@ +# Sample features + +Each feature the renderer supports, and the sample page that shows it. Paths are relative to the site root. Open +them with `bun run dev` (pick the sample in the dev bar) or `bun run sample`. `java` is `samples/java.ts`, the +doclet's flavor. `kotlin` is `samples/kotlin.ts`, the Dokka plugin's flavor. `render.test.ts` validates both against +`schema/apidocs-1.schema.json` and runs the output checker over both. + +| Feature | Sample | Page | +| --- | --- | --- | +| Module overview, packages table, all-types table | java, kotlin | `index.html` | +| Package description with a heading and a see-also link | java | `com/example/geo/index.html` | +| Several packages with descriptions | java, kotlin | `index.html` | +| Empty package | java, kotlin | `com/example/geo/spi/index.html`, `org/example/kgeo/internal/index.html` | +| Class, abstract class, final class | java | `com/example/geo/Polygon.html`, `AbstractShape.html`, `Shapes.html` | +| Interface; sealed interface with permitted subtypes | java | `com/example/geo/Shape.html` | +| Record with documented components (`#param-radius`) | java | `com/example/geo/Circle.html` | +| Enum with a deprecated constant | java, kotlin | `com/example/geo/Units.html`, `org/example/kgeo/LengthUnit.html` | +| Annotation interface with element defaults | java, kotlin | `com/example/geo/Measured.html`, `org/example/kgeo/experimental/ExperimentalGeometry.html` | +| Exception (grouped under Exceptions) | java | `com/example/geo/GeometryException.html` | +| Nested types, two levels deep, in breadcrumbs and navigation | java | `com/example/geo/Shapes.Builder.Option.html` | +| Generics with bounds and wildcards | java | `com/example/geo/Shapes.html#largest(java.util.Collection)` | +| Constructors | java, kotlin | `com/example/geo/Circle.html`, `org/example/kgeo/Point.html` | +| Overloads | java, kotlin | `Shapes.html` `area(Circle)` and `area(Polygon)`; `org/example/kgeo/Geometry.html` `distance` | +| Fields and constants | java, kotlin | `Shapes.html#PRECISION`; `org/example/kgeo/index.html#VERSION` | +| Varargs | java | `Shapes.html#total(com.example.geo.Shape...)`, `Polygon.html` constructor | +| Parameters, returns and throws (declared and unchecked) | java | `Shapes.html#parse(java.lang.String)` | +| API note, implementation requirements and implementation note callouts | java | `Shapes.html#parse(java.lang.String)`, `Shape.html` | +| Deprecated with a replacement link, and deprecated for removal | java, kotlin | `Shapes.html#sum(java.util.List)`, `com/example/geo/LegacyShape.html`, `org/example/kgeo/index.html#totalArea(List<Shape>)` | +| Since badges | java, kotlin | most pages | +| Nullability badges (JSpecify and Kotlin `?`) | java, kotlin | `Shapes.html#find(java.util.Map,java.lang.String)`, `org/example/kgeo/index.html#parseShape(String)` | +| Null-marked badge | java | `com/example/geo/index.html` | +| Inherited members | java | `com/example/geo/Polygon.html#inherited-members` | +| Inherited description ("copied from") | java | `com/example/geo/Polygon.html#area()` | +| See-also: declaration link, labeled link, plain text, URL | java | `com/example/geo/Shapes.html` (type description) | +| Internal and external links (JDK, Kotlin stdlib) | java, kotlin | signatures on every page | +| Unresolved link rendered as plain code | java, kotlin | `Shapes.html#describe(com.example.geo.Shape)`, `org/example/kgeo/coroutines/index.html` `watchShapes` | +| Code samples in Java and Kotlin | java, kotlin | `Shapes.html` description; `org/example/kgeo/coroutines/index.html` | +| Tables, ordered and unordered lists, block quote | java | `Shapes.html` description | +| Raw HTML node (block and inline) | java | `Shapes.html` description (`<dl>`) and `describe` (`<sup>`) | +| Very long signature, one parameter per line | java | `Shapes.html` `transform` | +| Signatures as the source formatter lays them out (google-java-format, ktfmt), with one-line summaries and titles | java, kotlin | `Shapes.html` `transform`, `com/example/geo/io/ShapeReader.html` `readAll`; `org/example/kgeo/Geometry.html` `transformShapes`, `nearest` | +| A type with hundreds of members (generated) | java | `com/example/geo/registry/ShapeCatalog.html` | +| Top-level functions and properties | kotlin | `org/example/kgeo/index.html` | +| Extension function and property with a receiver | kotlin | `org/example/kgeo/index.html` `scaled` and `isDegenerate` | +| Object and companion object | kotlin | `org/example/kgeo/Geometry.html`, `org/example/kgeo/Circle.Companion.html` | +| Data, sealed, value and enum classes | kotlin | `Circle.html`, `Shape.html`, `Meters.html`, `LengthUnit.html` under `org/example/kgeo/` | +| Suspend function | kotlin | `org/example/kgeo/coroutines/index.html` `loadShapes` | +| Inline function with a reified type parameter | kotlin | `org/example/kgeo/Geometry.html` `filterShapes` | +| Operator function | kotlin | `org/example/kgeo/Meters.html` `plus` | +| Type aliases | kotlin | `org/example/kgeo/index.html#type-aliases` | +| Default arguments | kotlin | `org/example/kgeo/Point.html`, `scaled` | +| Markdown twin, `llms.txt`, `llms-full.txt`, `api.json`, `element-list` | java, kotlin | site root; `<page>.md` beside every page | +| Guides listed on the overview, ungrouped first, then by group | java, kotlin | `index.html#guides`, `index.md` | +| Guide ordering: `order` first, guides without one after; a group's second guide listed first in the model | java | `guides/migrating-from-1x.html` (no order, comes third); Advanced: `custom-shapes` (order 1) before `text-format` (order 2) | +| Guide with an install snippet (Gradle, Maven, module path) and a first example | java, kotlin | `guides/getting-started.html` | +| Guide sections: h2 sections and h3 subsections in the rail, self-links on headings | java, kotlin | `guides/concepts.html` | +| Duplicate heading text, deduplicated anchors | java | `guides/concepts.html#example` and `#example-2` | +| Admonitions: note, tip, important, warning, caution, API note, implementation requirements, implementation note; with and without a title | java, kotlin | `guides/concepts.html` | +| Table, nested lists and an ordered list in a guide | java, kotlin | `guides/concepts.html#shapes`, `#units` (java), `#lengths` (kotlin) | +| Guide links to types, members, an overload, a nested type and a package | java, kotlin | `guides/concepts.html#measuring` (java), `#distance` and `#shapes` (kotlin) | +| Guide links to deprecated declarations | java, kotlin | `guides/migrating-from-1x.html` | +| Guide link to a section of another guide | java, kotlin | `guides/concepts.html#further-reading` | +| External link and unresolved links (a declaration and a guide) in a guide | java, kotlin | `guides/concepts.html#further-reading` | +| Guide in a group, with a nested slug and a source link | java, kotlin | `guides/advanced/text-format.html`, `guides/coroutines/loading.html` | +| Previous and next guide links | java, kotlin | the foot of every guide page | +| Doc comment links into guides: module overview, package description, deprecation, `@see` to a section | java, kotlin | `index.html`, `com/example/geo/index.html`, `LegacyShape.html`, `Shapes.html#parse(java.lang.String)`; `org/example/kgeo/index.html` | +| Guides in `llms.txt` (before the reference pages), `llms-full.txt`, search and Markdown | java, kotlin | site root; `guides/*.md` | + +## The Markdown sample suite + +`samples/guides` is a Markdown suite for `apidocs guides` (see the README's Markdown suites section). Build it with +`bun src/cli.ts guides --src samples/guides --id geo --title "Geo user guide" --out <dir> --link +../developer/=https://example.com/developer/ --link ../api/=https://example.com/api/`, or pick "Markdown sample +suite" in `bun run dev`. The diagnostics the importer reports live in a separate fixture, +`test/fixtures/guides-errors`, one per line. + +| Feature | Source | Page | +| --- | --- | --- | +| Overview page from the root `index.md`, with a table and the sync comment dropped | `index.md` | `index.html` | +| Guides-only site: guides in the navigator, no package block, no API index pages | every page | `index.html` | +| Ungrouped page ordered by `sidebar.order` | `getting-started.md` | `guides/getting-started.html` | +| Fenced code with and without a language, task list, strikethrough, autolinks, `mailto:` | `getting-started.md` | `guides/getting-started.html` | +| Group titled by its `index.md`, the index first as "Overview" | `concepts/index.md` | `guides/concepts/index.html` | +| Nested group `Concepts › Advanced topics` | `concepts/advanced/` | `guides/concepts/advanced/custom-shapes.html` | +| The five GitHub alerts, a plain quote, `{#id}`, raw HTML (`kbd`, `sub`, `sup`, `dl`), a rule | `concepts/alerts.md` | `guides/concepts/alerts.html` | +| `sidebar.label` as the navigator label | `concepts/alerts.md` | the navigator ("Alerts") | +| PNG and SVG images with their size, a title, a link to a suite file | `concepts/images.md` | `guides/concepts/images.html` | +| Links: same page, other page, section by GitHub slug and by `{#id}`, up a directory, mapped to a sibling suite and an API reference, absolute | `index.md`, `getting-started.md`, `concepts/` | throughout | +| Drafts left out (a whole group) | `reference/` | absent; `--include-drafts` adds it | +| Breadcrumbs through the group, previous and next across groups | every guide | foot of each guide | + +## Adding a feature + +1. Add the declaration to `samples/java.ts` or `samples/kotlin.ts` (or both), with the builders in `samples/build.ts`. + Write what the doclet or the Dokka plugin would emit; when the model needs a new field, change + `schema/apidocs-1.schema.json` first and run `bun run generate`. A guide goes in `module.guides` through the + `guide()` builder; `[[guide:slug|label]]` and `[[guide:slug#section|label]]` link to a guide or a section. +2. Add a row above naming the page that shows it. +3. Run `bun test`: the samples must validate against the schema and pass the output checker. diff --git a/packages/apidocs/samples/build.ts b/packages/apidocs/samples/build.ts new file mode 100644 index 0000000..5cebedc --- /dev/null +++ b/packages/apidocs/samples/build.ts @@ -0,0 +1,301 @@ +/** + * Builders for the hand-written sample models. They produce exactly what the + * doclet (Java) and the Dokka plugin (Kotlin) write: signatures as tokens, + * documentation as trees. `md` turns a short marked-up string into inlines: + * `code`, *emphasis*, **strong**, [[id]] or [[id|label]] for a declaration + * link, [[guide:slug|label]] or [[guide:slug#section|label]] for a link to a + * guide or one of its sections, [label](url) for a URL link. + */ +import type { AdmonitionTone, Block, Deprecation, Doc, Guide, Inline, Member, Note, Param, Ref, Token, Type, TypeParam } from "../src/model"; + +// ---- Tokens. + +export const kw = (text: string): Token => ({ kind: "keyword", text }); +export const nm = (text: string): Token => ({ kind: "name", text }); +export const pu = (text: string): Token => ({ kind: "punct", text }); +export const tp = (text: string): Token => ({ kind: "typeParam", text }); +export const lit = (text: string): Token => ({ kind: "literal", text }); +export const prm = (text: string): Token => ({ kind: "param", text }); +export function ty(text: string, ref?: string, url?: string): Token { + return { kind: "type", text, ...(ref ? { ref } : {}), ...(url ? { url } : {}) }; +} +export function an(text: string, ref?: string, url?: string): Token { + return { kind: "annotation", text, ...(ref ? { ref } : {}), ...(url ? { url } : {}) }; +} + +/** Tokens from parts; strings are punctuation, and adjacent punctuation merges. */ +export function tk(...parts: (Token | Token[] | string)[]): Token[] { + const out: Token[] = []; + for (const part of parts.flat()) { + const token = typeof part === "string" ? pu(part) : part; + const last = out[out.length - 1]; + if (token.kind === "punct" && last?.kind === "punct") out[out.length - 1] = pu(last.text + token.text); + else if (token.text) out.push(token); + } + return out; +} + +export const JDK = "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/"; +export const KOTLIN = "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/"; +export const jdk = (pkg: string, name: string) => ty(name, `${pkg}.${name}`, `${JDK}${pkg.replace(/\./g, "/")}/${name}.html`); +export const kt = (name: string) => ty(name, `kotlin/${name}///PointingToDeclaration/`, `${KOTLIN}-${name.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`).slice(1)}/`); + +// ---- Documentation. + +export function md(text: string): Inline[] { + const out: Inline[] = []; + const re = /`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*|\[\[([^\]|]+)(?:\|([^\]]+))?\]\]|\[([^\]]+)\]\(([^)]+)\)/g; + let at = 0; + for (const m of text.matchAll(re)) { + if (m.index! > at) out.push({ kind: "text", text: text.slice(at, m.index) }); + if (m[1]) out.push({ kind: "code", text: m[1] }); + else if (m[2]) out.push({ kind: "strong", children: md(m[2]) }); + else if (m[3]) out.push({ kind: "emphasis", children: md(m[3]) }); + else if (m[4]?.startsWith("guide:")) { + // A guide link: prose, not code. The section, if any, follows a #. + const [id, section] = m[4].split("#"); + out.push({ kind: "link", target: { id: id!, ...(section ? { section } : {}) }, children: md(m[5] ?? id!) }); + } else if (m[4]) { + const label = m[5] ?? linkLabel(m[4]); + out.push({ kind: "link", target: { id: m[4] }, code: true, children: [{ kind: "text", text: label }] }); + } else out.push({ kind: "link", url: m[7]!, children: md(m[6]!) }); + at = m.index! + m[0].length; + } + if (at < text.length) out.push({ kind: "text", text: text.slice(at) }); + return out; +} + +/** The label {@link} would show: Type, Type.member(Simple, Types), or a Kotlin DRI's last name. */ +function linkLabel(id: string): string { + if (id.includes("/")) return id.split("/").filter(Boolean).filter(p => p !== "PointingToDeclaration" && !p.startsWith("#"))[1] ?? id; + const [owner, member] = id.split("#"); + const type = owner!.slice(owner!.lastIndexOf(".") + 1).replace(/\$/g, "."); + if (!member) return /^[a-z]/.test(type) ? owner! : type; + const simple = member.replace(/\(([^)]*)\)/, (_, ps: string) => `(${ps.split(",").filter(Boolean).map(p => p.slice(p.lastIndexOf(".") + 1)).join(", ")})`); + return `${type}.${simple}`; +} + +export const P = (text: string): Block => ({ kind: "paragraph", children: md(text) }); +export const UL = (...items: (string | Block[])[]): Block => ({ kind: "list", items: items.map(i => (typeof i === "string" ? [P(i)] : i)) }); +export const OL = (...items: string[]): Block => ({ kind: "list", ordered: true, items: items.map(i => [P(i)]) }); +export const CODE = (language: string | undefined, text: string): Block => ({ kind: "code", ...(language ? { language } : {}), text }); +export const H = (level: number, text: string): Block => ({ kind: "heading", level, children: md(text) }); +export const QUOTE = (text: string): Block => ({ kind: "quote", children: [P(text)] }); +export const RAW = (html: string, text: string): Block => ({ kind: "raw", html, text }); +export function TABLE(caption: string, head: string[], rows: string[][]): Block { + return { kind: "table", caption: md(caption), head: [head.map(h => [P(h)])], rows: rows.map(r => r.map(c => [P(c)])) }; +} + +/** An admonition: a tone, the text as paragraphs (or blocks), and an optional title. */ +export function ADMON(tone: AdmonitionTone, body: string | Block[], title?: string): Block { + return { kind: "admonition", tone, ...(title ? { title: md(title) } : {}), children: typeof body === "string" ? blocks(body) : body }; +} + +/** A guide, as an extractor writes it: the id is guide: and the slug. */ +export function guide(spec: { slug: string; title: string; summary: string; body: Block[]; group?: string; order?: number; source?: Guide["source"] }): Guide { + return { + id: `guide:${spec.slug}`, slug: spec.slug, title: spec.title, summary: md(spec.summary), + ...(spec.group ? { group: spec.group } : {}), + ...(spec.order !== undefined ? { order: spec.order } : {}), + body: spec.body, + ...(spec.source ? { source: spec.source } : {}), + }; +} + +export interface DocSpec { + body?: string | Block[]; + notes?: [Note["kind"], string | Block[]][]; + see?: (string | Inline[])[]; + inheritedFrom?: Ref; +} + +/** A doc tree; the summary is the body's first sentence. */ +export function doc(spec: DocSpec | string): Doc { + const s = typeof spec === "string" ? { body: spec } : spec; + const body = typeof s.body === "string" ? s.body.split("\n\n").map(P) : (s.body ?? []); + const first = body[0]; + let summary: Inline[] = []; + if (first?.kind === "paragraph") { + for (const node of first.children ?? []) { + if (node.kind === "text" && /\.(\s|$)/.test(node.text)) { + summary.push({ kind: "text", text: node.text.slice(0, node.text.search(/\.(\s|$)/) + 1) }); + break; + } + summary.push(node); + } + } + return { + ...(summary.length ? { summary } : {}), + ...(body.length ? { body } : {}), + ...(s.notes?.length ? { notes: s.notes.map(([kind, b]) => ({ kind, body: typeof b === "string" ? [P(b)] : b })) } : {}), + ...(s.see?.length ? { see: s.see.map(e => (typeof e === "string" ? md(e) : e)) } : {}), + ...(s.inheritedFrom ? { inheritedFrom: s.inheritedFrom } : {}), + }; +} + +export const blocks = (text: string): Block[] => text.split("\n\n").map(P); +export const deprecated = (text: string, since?: string, forRemoval?: boolean): Deprecation => ({ + doc: blocks(text), ...(since ? { since } : {}), ...(forRemoval ? { forRemoval } : {}), +}); + +// ---- Members. + +export interface ParamSpec { + name: string; + type: Token[]; + doc?: string; + varargs?: boolean; + nullness?: Param["nullness"]; + defaultValue?: string; + annotations?: Token[][]; +} + +export interface MemberSpec { + name: string; + kind?: Member["kind"]; + mods?: string[]; + annotations?: Token[][]; + typeParams?: { name: string; bounds?: Token[][]; doc?: string }[]; + receiver?: ParamSpec; + params?: ParamSpec[]; + returns?: { type: Token[]; doc?: string; nullness?: Param["nullness"] }; + type?: Token[]; + nullness?: Param["nullness"]; + throws?: { type: Token[]; doc?: string; declared?: boolean }[]; + constant?: string; + defaultValue?: string; + overrides?: Ref; + implicit?: boolean; + doc?: DocSpec | string; + deprecated?: Deprecation; + since?: string; + line?: number; + file?: string; + /** + * Lay the signature out as the source formatter does when it is too long for one line: google-java-format + * (one parameter per line at +8, throws on its own continuation line) or ktfmt (one parameter per line at + * +4, the closing parenthesis and return type on their own line). The newlines and indentation go in the + * punctuation tokens, as the doclet and the Dokka plugin write them after running the formatter. + */ + wrap?: boolean; +} + +function params(list: ParamSpec[] | undefined): Param[] { + return (list ?? []).map(p => ({ + name: p.name, type: p.type, + ...(p.varargs ? { varargs: true } : {}), + ...(p.defaultValue ? { defaultValue: p.defaultValue } : {}), + ...(p.nullness ? { nullness: p.nullness } : {}), + ...(p.annotations ? { annotations: p.annotations } : {}), + ...(p.doc ? { doc: blocks(p.doc) } : {}), + })); +} + +function typeParams(list: MemberSpec["typeParams"]): TypeParam[] { + return (list ?? []).map(t => ({ name: t.name, ...(t.bounds ? { bounds: t.bounds } : {}), ...(t.doc ? { doc: blocks(t.doc) } : {}) })); +} + +function typeParamTokens(list: MemberSpec["typeParams"], keyword: string): Token[] { + if (!list?.length) return []; + return tk("<", ...list.flatMap((t, i) => [ + ...(i ? [pu(", ")] : []), tp(t.name), + ...(t.bounds?.length ? [pu(` ${keyword} `), ...t.bounds.flatMap((b, j) => [...(j ? [pu(" & ")] : []), ...b])] : []), + ]), ">"); +} + +/** The JDK doclet's anchor: the name and erased parameter types. */ +function javaAnchor(spec: MemberSpec): string { + if (spec.kind === "field" || spec.kind === "enumConstant") return spec.name; + const name = spec.kind === "constructor" ? "<init>" : spec.name; + const types = (spec.params ?? []).map(p => { + const head = p.type.find(t => t.kind === "type" || t.kind === "typeParam" || t.kind === "keyword")!; + const base = head.kind === "type" && head.ref ? head.ref.replace(/\$/g, ".") : head.text; + const array = p.type.some(t => t.kind === "punct" && t.text.includes("[]")); + return base + (p.varargs ? "..." : array ? "[]" : ""); + }); + return `${name}(${types.join(",")})`; +} + +function base(owner: string, spec: MemberSpec, anchor: string, id: string, signature: Token[], kind: Member["kind"]): Member { + return { + id, anchor, kind, name: spec.name, + ...(spec.mods?.length ? { modifiers: spec.mods } : {}), + ...(spec.annotations?.length ? { annotations: spec.annotations } : {}), + ...(spec.typeParams?.length ? { typeParams: typeParams(spec.typeParams) } : {}), + ...(spec.receiver ? { receiver: params([spec.receiver])[0] } : {}), + signature, + ...(spec.params?.length ? { params: params(spec.params) } : {}), + ...(spec.returns ? { returns: { type: spec.returns.type, ...(spec.returns.nullness ? { nullness: spec.returns.nullness } : {}), ...(spec.returns.doc ? { doc: blocks(spec.returns.doc) } : {}) } } : {}), + ...(spec.type ? { type: spec.type } : {}), + ...(spec.nullness ? { nullness: spec.nullness } : {}), + ...(spec.throws?.length ? { throws: spec.throws.map(t => ({ type: t.type, ...(t.declared ? { declared: true } : {}), ...(t.doc ? { doc: blocks(t.doc) } : {}) })) } : {}), + ...(spec.constant ? { constant: spec.constant } : {}), + ...(spec.defaultValue ? { defaultValue: spec.defaultValue } : {}), + ...(spec.overrides ? { overrides: spec.overrides } : {}), + ...(spec.implicit ? { implicit: true } : {}), + ...(spec.doc ? { doc: doc(spec.doc) } : {}), + ...(spec.deprecated ? { deprecated: spec.deprecated } : {}), + ...(spec.since ? { since: spec.since } : {}), + ...(spec.line ? { source: { path: spec.file ?? owner.replace(/\$.*/, "").replace(/\./g, "/") + ".java", line: spec.line } } : {}), + }; +} + +/** A Java member, as the doclet writes it. */ +export function javaMember(owner: string, ownerName: string, spec: MemberSpec): Member { + const kind = spec.kind ?? "method"; + const sig: (Token | Token[] | string)[] = []; + for (const mod of spec.mods ?? []) sig.push(kw(mod), " "); + if (kind === "enumConstant") sig.push(nm(spec.name)); + else if (kind === "field") sig.push(spec.type!, " ", nm(spec.name)); + else { + const tps = typeParamTokens(spec.typeParams, "extends"); + if (tps.length) sig.push(tps, " "); + if (kind !== "constructor") sig.push(spec.returns?.type ?? [kw("void")], " "); + const indent = "\n" + " ".repeat(8); + sig.push(nm(kind === "constructor" ? ownerName.split(".").pop()! : spec.name), "(", spec.wrap ? indent : ""); + (spec.params ?? []).forEach((p, i) => { + if (i) sig.push(spec.wrap ? `,${indent}` : ", "); + for (const a of p.annotations ?? []) sig.push(a, " "); + sig.push(p.type, " ", prm(p.name)); + }); + sig.push(")"); + if (spec.defaultValue) sig.push(" ", kw("default"), " ", lit(spec.defaultValue)); + const declared = (spec.throws ?? []).filter(t => t.declared); + if (declared.length) sig.push(spec.wrap ? indent : " ", kw("throws"), " ", ...declared.flatMap((t, i) => [...(i ? [", "] : []), t.type])); + } + const anchor = javaAnchor({ ...spec, kind }); + return base(owner, { ...spec, file: spec.file }, anchor, `${owner}#${anchor}`, tk(...sig), kind); +} + +/** A Kotlin member, as the Dokka plugin writes it: ids are DRIs, anchors are readable names. */ +export function kotlinMember(owner: string, spec: MemberSpec): Member { + const kind = spec.kind ?? "function"; + const sig: (Token | Token[] | string)[] = []; + for (const mod of spec.mods ?? []) sig.push(kw(mod), " "); + sig.push(kw(kind === "property" ? (spec.mods?.includes("var") ? "" : "val") : kind === "constructor" ? "constructor" : "fun")); + if (kind !== "constructor") sig.push(" "); + const tps = typeParamTokens(spec.typeParams, ":"); + if (tps.length) sig.push(tps, " "); + if (spec.receiver) sig.push(spec.receiver.type, "."); + if (kind !== "constructor") sig.push(nm(spec.name)); + if (kind === "property") sig.push(": ", spec.type!); + else { + sig.push("(", spec.wrap ? "\n " : ""); + (spec.params ?? []).forEach((p, i) => { + if (i) sig.push(spec.wrap ? ",\n " : ", "); + if (p.varargs) sig.push(kw("vararg"), " "); + sig.push(prm(p.name), ": ", p.type); + if (p.defaultValue) sig.push(" = ", lit(p.defaultValue)); + }); + sig.push(spec.wrap ? ",\n)" : ")"); + if (spec.returns) sig.push(": ", spec.returns.type); + } + const anchor = kind === "property" ? spec.name : `${spec.name}(${(spec.params ?? []).map(p => p.type.map(t => t.text).join("")).join(",")})`; + const id = `${owner}/${spec.name}/${spec.receiver ? spec.receiver.type.map(t => t.text).join("") : ""}#${(spec.params ?? []).map(p => p.type.map(t => t.text).join("")).join("#")}/PointingToDeclaration/`; + return base(owner, { ...spec, file: spec.file ?? `${owner.split("/")[0]!.replace(/\./g, "/")}/${(owner.split("/")[1] || "Top")}.kt` }, anchor, id, tk(...sig.filter(s => s !== "")), kind); +} + +/** A type: fills the defaults every type needs. */ +export function type(t: Partial<Type> & Pick<Type, "id" | "name" | "kind" | "signature">, language = "java"): Type { + return { language, ...t } as Type; +} diff --git a/packages/apidocs/samples/guides/concepts/advanced/custom-shapes.md b/packages/apidocs/samples/guides/concepts/advanced/custom-shapes.md new file mode 100644 index 0000000..c4b6634 --- /dev/null +++ b/packages/apidocs/samples/guides/concepts/advanced/custom-shapes.md @@ -0,0 +1,20 @@ +--- +title: Custom shapes +description: Write a shape of your own and measure it like the built-in ones. +--- + +## The contract + +A custom shape implements `area()` and `perimeter()`. Both must be finite and not negative. + +```java +record Square(double side) implements Shape { + public double area() { return side * side; } + public double perimeter() { return 4 * side; } +} +``` + +## Checking a shape + +`Shapes.check` measures a shape twice and compares the results. See [Units](../index.md#units) for the unit the +results are in, and [Getting started](../../getting-started.md) for the setup. diff --git a/packages/apidocs/samples/guides/concepts/advanced/index.md b/packages/apidocs/samples/guides/concepts/advanced/index.md new file mode 100644 index 0000000..d5de75c --- /dev/null +++ b/packages/apidocs/samples/guides/concepts/advanced/index.md @@ -0,0 +1,8 @@ +--- +title: Advanced topics +description: What a custom shape must do, and how Geo checks it. +sidebar: + order: 3 +--- + +These pages assume the [concepts](../index.md). diff --git a/packages/apidocs/samples/guides/concepts/alerts.md b/packages/apidocs/samples/guides/concepts/alerts.md new file mode 100644 index 0000000..80919bc --- /dev/null +++ b/packages/apidocs/samples/guides/concepts/alerts.md @@ -0,0 +1,44 @@ +--- +title: Callouts +description: The five GitHub alerts, an explicit heading id and raw HTML. +sidebar: + label: Alerts + order: 1 +--- + +## Before you start {#before-you-start} + +> [!NOTE] +> Measurements are exact for circles and polygons. + +> [!TIP] +> Reuse a `Shapes.Builder` to build many shapes. + +> [!IMPORTANT] +> Shapes are immutable: every transform returns a new shape. + +> [!WARNING] +> A polygon whose edges cross has no defined area. + +> [!CAUTION] +> `Shapes.parse` reads untrusted text: limit its input size. +> +> It allocates one object per vertex. + +## A plain quote + +> Geometry is the art of correct reasoning from incorrectly drawn figures. + +## Raw HTML + +Press <kbd>Ctrl</kbd>+<kbd>C</kbd> to copy. Water is H<sub>2</sub>O, and E = mc<sup>2</sup>. +<!-- An inline comment, which does not render. --> + +<dl> + <dt>Area</dt> + <dd>The size of the inside.</dd> +</dl> + +--- + +Back to the [concepts](index.md#shapes). diff --git a/packages/apidocs/samples/guides/concepts/diagram.svg b/packages/apidocs/samples/guides/concepts/diagram.svg new file mode 100644 index 0000000..7daaee3 --- /dev/null +++ b/packages/apidocs/samples/guides/concepts/diagram.svg @@ -0,0 +1,6 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 240" width="240" height="240" role="img" aria-label="A circle inside a square"> + <rect x="20" y="20" width="200" height="200" fill="none" stroke="#6d28d9" stroke-width="4"/> + <circle cx="120" cy="120" r="100" fill="#ede9fe" stroke="#6d28d9" stroke-width="4"/> + <line x1="120" y1="120" x2="220" y2="120" stroke="#1b1f27" stroke-width="3"/> + <text x="160" y="112" font-family="sans-serif" font-size="18" fill="#1b1f27">r</text> +</svg> diff --git a/packages/apidocs/samples/guides/concepts/images.md b/packages/apidocs/samples/guides/concepts/images.md new file mode 100644 index 0000000..4770158 --- /dev/null +++ b/packages/apidocs/samples/guides/concepts/images.md @@ -0,0 +1,16 @@ +--- +title: Pictures +description: Diagrams and screenshots, with their sizes known before they load. +sidebar: + order: 2 +--- + +## A diagram + +![A circle of radius r inside a square of side 2r](diagram.svg "Circle and square") + +## A screenshot + +![The Geo color swatch, a purple bar](swatch.png) + +You can also [download the diagram](diagram.svg). diff --git a/packages/apidocs/samples/guides/concepts/index.md b/packages/apidocs/samples/guides/concepts/index.md new file mode 100644 index 0000000..c490ee5 --- /dev/null +++ b/packages/apidocs/samples/guides/concepts/index.md @@ -0,0 +1,26 @@ +--- +title: Concepts +description: Shapes, units, callouts and pictures, the ideas the rest of the guide assumes. +sidebar: + order: 2 +--- + +Every shape has an area and a perimeter, measured in one unit. + +## Shapes + +A shape is closed and flat. Geo has circles, polygons and the shapes you write yourself +([custom shapes](advanced/custom-shapes.md)). + +## Units + +Lengths are in meters unless you pass a `Units` value. Areas are in the square of that unit. + +1. Pick a unit. +2. Measure. +3. Convert, if you need to. + +## In this section + +- [Callouts](alerts.md) +- [Pictures](images.md) diff --git a/packages/apidocs/samples/guides/concepts/swatch.png b/packages/apidocs/samples/guides/concepts/swatch.png new file mode 100644 index 0000000..e47a59c Binary files /dev/null and b/packages/apidocs/samples/guides/concepts/swatch.png differ diff --git a/packages/apidocs/samples/guides/getting-started.md b/packages/apidocs/samples/guides/getting-started.md new file mode 100644 index 0000000..d0b3bab --- /dev/null +++ b/packages/apidocs/samples/guides/getting-started.md @@ -0,0 +1,53 @@ +--- +title: Getting started +description: Install Geo, then measure your first shape. +sidebar: + order: 1 +--- + +<!-- sync +samples/java.ts +--> + +Geo needs Java 21 or later. ~~Java 17 is supported.~~ Java 17 support ended with 2.0. + +## Install + +Add the dependency with Gradle: + +```kotlin +dependencies { + implementation("com.example:geo:2.1.0") +} +``` + +Or with Maven: + +```xml +<dependency> + <groupId>com.example</groupId> + <artifactId>geo</artifactId> + <version>2.1.0</version> +</dependency> +``` + +## Measure a shape + +```java +Shape circle = new Circle(2.0); +System.out.println(Shapes.area(circle)); +``` + +``` +12.566370614359172 +``` + +The result is in the square of the unit you measured in; [Units](concepts/index.md#units) explains which. + +## Checklist + +- [x] Add the dependency +- [x] Measure a circle +- [ ] Read [the callouts page](concepts/alerts.md#before-you-start) + +Questions go to <mailto:geo@example.com> or https://example.com/geo/issues. Back to [the top](#install). diff --git a/packages/apidocs/samples/guides/index.md b/packages/apidocs/samples/guides/index.md new file mode 100644 index 0000000..675944b --- /dev/null +++ b/packages/apidocs/samples/guides/index.md @@ -0,0 +1,33 @@ +--- +title: Geo user guide +description: Measure and draw shapes with the Geo library, from installation to custom shapes. +sidebar: + label: Overview + order: 0 +--- + +<!-- sync +samples/java.ts +--> + +Geo measures and draws two-dimensional shapes. This guide is the sample suite for the Markdown importer: each page +exercises some of the Markdown the importer reads. For the classes themselves, read the +[API reference](../api/index.html). + +## Sections + +- [Getting started](getting-started.md): install Geo and measure a first shape. +- [Concepts](concepts/index.md): shapes, units, callouts and pictures. +- [Advanced topics](concepts/advanced/index.md): what a custom shape must do. + +## What each page shows + +| Page | Markdown it uses | +| --- | --- | +| [Getting started](getting-started.md) | fenced code, task lists, strikethrough, autolinks, a link to a section | +| [Callouts](concepts/alerts.md) | the five GitHub alerts, an explicit heading id, raw HTML | +| [Pictures](concepts/images.md) | a PNG and an SVG image, a download link | +| [Custom shapes](concepts/advanced/custom-shapes.md) | a nested group, links up and across | + +The [developer guide](../developer/index.md) covers embedding Geo; its +[shapes section](../developer/concepts/shapes.md#the-shape-interface) starts with the interface. diff --git a/packages/apidocs/samples/guides/reference/format.md b/packages/apidocs/samples/guides/reference/format.md new file mode 100644 index 0000000..ebe8c75 --- /dev/null +++ b/packages/apidocs/samples/guides/reference/format.md @@ -0,0 +1,7 @@ +--- +title: The text format +description: The grammar Shapes.parse reads. +draft: true +--- + +This page is not written yet. diff --git a/packages/apidocs/samples/guides/reference/index.md b/packages/apidocs/samples/guides/reference/index.md new file mode 100644 index 0000000..4b85714 --- /dev/null +++ b/packages/apidocs/samples/guides/reference/index.md @@ -0,0 +1,7 @@ +--- +title: Reference +description: The text format and the command-line tool. +draft: true +--- + +This page is not written yet. It will cover the text format. diff --git a/packages/apidocs/samples/index.ts b/packages/apidocs/samples/index.ts new file mode 100644 index 0000000..497539f --- /dev/null +++ b/packages/apidocs/samples/index.ts @@ -0,0 +1,8 @@ +/** The sample models, as plain JSON values (exactly what a doclet or plugin would write). */ +import type { Model } from "../src/model"; +import { javaSample } from "./java"; +import { kotlinSample } from "./kotlin"; + +const plain = (model: Model): Model => JSON.parse(JSON.stringify(model)); + +export const samples: Record<"java" | "kotlin", Model> = { java: plain(javaSample), kotlin: plain(kotlinSample) }; diff --git a/packages/apidocs/samples/java.ts b/packages/apidocs/samples/java.ts new file mode 100644 index 0000000..d5d7d83 --- /dev/null +++ b/packages/apidocs/samples/java.ts @@ -0,0 +1,494 @@ +/** + * The Java-flavored sample: what the Javadoc doclet writes for a small + * geometry library. Hand-written, except the generated Registry type with + * hundreds of members. samples/FEATURES.md lists what each page shows. + */ +import type { Guide, Member, Model, Package, Type } from "../src/model"; +import { + ADMON, an, blocks, CODE, deprecated, doc, guide, H, jdk, javaMember, kw, lit, nm, OL, P, QUOTE, RAW, TABLE, tk, tp, ty, type, UL, +} from "./build"; + +const G = "com.example.geo"; +const IO = "com.example.geo.io"; +const BIG = "com.example.geo.registry"; +const EMPTY = "com.example.geo.spi"; + +const t = (name: string, pkg = G) => ty(name.replace(/\$/g, "."), `${pkg}.${name}`); +const STRING = jdk("java.lang", "String"); +const OBJECT = jdk("java.lang", "Object"); +const DOUBLE = kw("double"); +const INT = kw("int"); +const NULLABLE = an("@Nullable", "org.jspecify.annotations.Nullable", "https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"); +const objectRef = { id: "java.lang.Object", url: `https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html` }; +const objectMembers = ["equals(java.lang.Object)", "getClass()", "hashCode()", "notify()", "notifyAll()", "toString()", "wait()", "wait(long)", "wait(long,int)"] + .map(a => ({ id: `java.lang.Object#${a}`, text: a.replace(/\(.*/, ""), url: `${objectRef.url}#${a}` })); +const fromObject = { from: { ...objectRef, text: "Object" }, kind: "class", members: objectMembers }; + +const m = (owner: string, spec: Parameters<typeof javaMember>[2]) => javaMember(owner, owner.slice(owner.lastIndexOf(".") + 1).replace(/\$/g, "."), spec); + +// ---- com.example.geo + +const shape: Type = type({ + id: `${G}.Shape`, name: "Shape", kind: "interface", modifiers: ["public", "sealed"], + signature: tk(kw("public"), " ", kw("sealed"), " ", kw("interface"), " ", nm("Shape"), " ", kw("extends"), " ", jdk("java.lang", "Comparable"), "<", t("Shape"), "> ", kw("permits"), " ", t("Circle"), ", ", t("Polygon")), + interfaces: [tk(jdk("java.lang", "Comparable"), "<", t("Shape"), ">")], + permits: [{ id: `${G}.Circle` }, { id: `${G}.Polygon` }], + members: [ + m(`${G}.Shape`, { name: "area", returns: { type: [DOUBLE], doc: "the area in square meters, never negative" }, doc: "The shape's area.", line: 24 }), + m(`${G}.Shape`, { + name: "compareTo", mods: ["default"], params: [{ name: "other", type: [t("Shape")], nullness: "nonNull", doc: "the shape to compare with" }], + returns: { type: [INT], doc: "a negative number, zero or a positive number as this shape is smaller, equal or larger" }, + doc: { body: "Compares shapes by area.", notes: [["implSpec", "The default compares `area()` with `Double.compare`."]] }, line: 31, + }), + m(`${G}.Shape`, { name: "name", mods: ["default"], returns: { type: tk(NULLABLE, " ", STRING), nullness: "nullable", doc: "the name, or `null` for an anonymous shape" }, doc: "Returns the shape's name, or `null` for an anonymous shape.", since: "1.1", line: 40 }), + ], + doc: doc({ + body: [P("A closed plane figure."), P("Every shape reports its area in square [[com.example.geo.Units#METERS|meters]]. Shapes order by area, so a `List<Shape>` sorts from smallest to largest.")], + notes: [["apiNote", "The hierarchy is **sealed**: only [[com.example.geo.Circle]] and [[com.example.geo.Polygon]] implement it, so a `switch` over a shape is exhaustive."]], + }), + since: "1.0", nullMarked: true, source: { path: "com/example/geo/Shape.java", line: 18 }, +}); + +const circle: Type = type({ + id: `${G}.Circle`, name: "Circle", kind: "record", modifiers: ["public"], + signature: tk(kw("public"), " ", kw("record"), " ", nm("Circle"), "(", DOUBLE, " ", { kind: "param", text: "radius" }, ", ", NULLABLE, " ", STRING, " ", { kind: "param", text: "label" }, ") ", kw("implements"), " ", t("Shape")), + superclass: [jdk("java.lang", "Record")], ancestors: [{ id: "java.lang.Record", url: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html" }, objectRef], + interfaces: [[t("Shape")]], + components: [ + { name: "radius", type: [DOUBLE], doc: blocks("the radius in meters; not negative") }, + { name: "label", type: tk(NULLABLE, " ", STRING), nullness: "nullable", doc: blocks("an optional label shown by [[com.example.geo.Shape#name()]]") }, + ], + members: [ + m(`${G}.Circle`, { name: "Circle", kind: "constructor", mods: ["public"], params: [{ name: "radius", type: [DOUBLE], doc: "the radius in meters; not negative" }, { name: "label", type: tk(NULLABLE, " ", STRING), nullness: "nullable", doc: "an optional label" }], throws: [{ type: [jdk("java.lang", "IllegalArgumentException")], doc: "if `radius` is negative" }], doc: "Checks the radius.", line: 22 }), + m(`${G}.Circle`, { name: "of", mods: ["public", "static"], params: [{ name: "radius", type: [DOUBLE], doc: "the radius in meters" }], returns: { type: [t("Circle")], nullness: "nonNull", doc: "an unlabeled circle" }, doc: "Creates an unlabeled circle.", line: 34 }), + m(`${G}.Circle`, { name: "area", mods: ["public"], returns: { type: [DOUBLE], doc: "the area in square meters, never negative" }, overrides: { id: `${G}.Shape#area()` }, doc: { body: "The shape's area. For a circle this is `π r²`.", inheritedFrom: undefined }, line: 40 }), + m(`${G}.Circle`, { name: "radius", mods: ["public"], returns: { type: [DOUBLE], doc: "the radius in meters; not negative" }, implicit: true }), + m(`${G}.Circle`, { name: "label", mods: ["public"], returns: { type: tk(NULLABLE, " ", STRING), nullness: "nullable", doc: "an optional label" }, implicit: true }), + m(`${G}.Circle`, { name: "toString", mods: ["public", "final"], returns: { type: [STRING], nullness: "nonNull" }, implicit: true }), + ], + inherited: [{ from: { id: `${G}.Shape`, text: "Shape" }, kind: "interface", members: [{ id: `${G}.Shape#compareTo(com.example.geo.Shape)`, text: "compareTo" }, { id: `${G}.Shape#name()`, text: "name" }] }], + doc: doc("A circle, the simplest shape.\n\nCircles compare by radius as well as by area: their order is the same."), + since: "1.0", nullMarked: true, source: { path: "com/example/geo/Circle.java", line: 16 }, +}); + +const abstractShape: Type = type({ + id: `${G}.AbstractShape`, name: "AbstractShape", kind: "class", modifiers: ["public", "abstract"], + signature: tk(kw("public"), " ", kw("abstract"), " ", kw("class"), " ", nm("AbstractShape")), + superclass: [OBJECT], ancestors: [objectRef], + members: [ + m(`${G}.AbstractShape`, { name: "perimeter", mods: ["public", "abstract"], returns: { type: [DOUBLE], doc: "the perimeter in meters" }, doc: "The length of the shape's boundary.", line: 20 }), + m(`${G}.AbstractShape`, { name: "describe", mods: ["public"], returns: { type: [STRING], nullness: "nonNull", doc: "a description such as `polygon, 4 sides`" }, doc: "Describes the shape for logs.", line: 28 }), + ], + inherited: [fromObject], + doc: doc("Shared behavior for shapes with a boundary."), since: "1.0", nullMarked: true, +}); + +const polygon: Type = type({ + id: `${G}.Polygon`, name: "Polygon", kind: "class", modifiers: ["public", "non-sealed"], + signature: tk(kw("public"), " ", kw("non-sealed"), " ", kw("class"), " ", nm("Polygon"), " ", kw("extends"), " ", t("AbstractShape"), " ", kw("implements"), " ", t("Shape")), + superclass: [t("AbstractShape")], ancestors: [{ id: `${G}.AbstractShape` }, objectRef], interfaces: [[t("Shape")]], + members: [ + m(`${G}.Polygon`, { name: "Polygon", kind: "constructor", mods: ["public"], params: [{ name: "sides", type: tk(DOUBLE, "..."), varargs: true, doc: "each side's length in meters; at least three" }], throws: [{ type: [jdk("java.lang", "IllegalArgumentException")], doc: "if there are fewer than three sides" }], doc: "Creates a regular polygon from its sides.", line: 25 }), + m(`${G}.Polygon`, { name: "area", mods: ["public"], returns: { type: [DOUBLE], doc: "the area in square meters, never negative" }, overrides: { id: `${G}.Shape#area()` }, doc: { body: "The shape's area.", inheritedFrom: { id: `${G}.Shape#area()` } }, line: 36 }), + m(`${G}.Polygon`, { name: "perimeter", mods: ["public"], returns: { type: [DOUBLE], doc: "the perimeter in meters" }, overrides: { id: `${G}.AbstractShape#perimeter()` }, doc: "The sum of the sides.", line: 44 }), + ], + inherited: [ + { from: { id: `${G}.AbstractShape`, text: "AbstractShape" }, kind: "class", members: [{ id: `${G}.AbstractShape#describe()`, text: "describe" }] }, + fromObject, + { from: { id: `${G}.Shape`, text: "Shape" }, kind: "interface", members: [{ id: `${G}.Shape#compareTo(com.example.geo.Shape)`, text: "compareTo" }, { id: `${G}.Shape#name()`, text: "name" }] }, + ], + doc: doc("A regular polygon. Not sealed: applications may extend it."), since: "1.0", nullMarked: true, +}); + +const units: Type = type({ + id: `${G}.Units`, name: "Units", kind: "enum", modifiers: ["public"], + signature: tk(kw("public"), " ", kw("enum"), " ", nm("Units")), + superclass: tk(jdk("java.lang", "Enum"), "<", t("Units"), ">"), ancestors: [{ id: "java.lang.Enum", url: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html" }, objectRef], + members: [ + m(`${G}.Units`, { name: "values", mods: ["public", "static"], returns: { type: tk(t("Units"), "[]"), nullness: "nonNull" }, implicit: true }), + m(`${G}.Units`, { name: "valueOf", mods: ["public", "static"], params: [{ name: "name", type: [STRING], nullness: "nonNull" }], returns: { type: [t("Units")], nullness: "nonNull" }, implicit: true }), + m(`${G}.Units`, { name: "METERS", kind: "enumConstant", type: [t("Units")], doc: "Meters: the base unit." }), + m(`${G}.Units`, { name: "FEET", kind: "enumConstant", type: [t("Units")], doc: "International feet.", deprecated: deprecated("Use [[com.example.geo.Units#METERS]]; mixing units causes rounding errors.", "1.2"), annotations: [tk(an("@Deprecated", "java.lang.Deprecated", "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Deprecated.html"), "(", { kind: "param", text: "since" }, " = ", lit('"1.2"'), ")")] }), + m(`${G}.Units`, { name: "toMeters", mods: ["public"], params: [{ name: "value", type: [DOUBLE], doc: "a length in this unit" }], returns: { type: [DOUBLE], doc: "the length in meters" }, doc: "Converts a length in this unit to meters." }), + ], + doc: doc("Units of length."), since: "1.0", nullMarked: true, +}); + +const measured: Type = type({ + id: `${G}.Measured`, name: "Measured", kind: "annotation", modifiers: ["public"], + annotations: [[an("@Documented", "java.lang.annotation.Documented", "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/annotation/Documented.html")]], + signature: tk(kw("public"), " ", kw("@interface"), " ", nm("Measured")), + members: [ + m(`${G}.Measured`, { name: "unit", kind: "annotationElement", returns: { type: [t("Units")], doc: "the unit" }, defaultValue: "METERS", doc: "The unit of the values." }), + m(`${G}.Measured`, { name: "precision", kind: "annotationElement", returns: { type: [INT], doc: "the number of digits" }, defaultValue: "3", doc: "Significant digits." }), + ], + doc: doc("Marks a declaration whose values are lengths, and in which unit."), since: "1.1", nullMarked: true, +}); + +const geoException: Type = type({ + id: `${G}.GeometryException`, name: "GeometryException", kind: "class", modifiers: ["public"], + signature: tk(kw("public"), " ", kw("class"), " ", nm("GeometryException"), " ", kw("extends"), " ", jdk("java.lang", "Exception")), + superclass: [jdk("java.lang", "Exception")], + ancestors: ["Exception", "Throwable"].map(n => ({ id: `java.lang.${n}`, url: `https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/${n}.html` })).concat([objectRef]), + members: [m(`${G}.GeometryException`, { name: "GeometryException", kind: "constructor", mods: ["public"], params: [{ name: "message", type: [STRING], doc: "what was wrong" }], doc: "Creates an exception." })], + doc: doc("A shape that cannot exist, such as a triangle whose sides violate the triangle inequality."), since: "1.0", nullMarked: true, +}); + +const legacyShape: Type = type({ + id: `${G}.LegacyShape`, name: "LegacyShape", kind: "class", modifiers: ["public", "final"], + signature: tk(kw("public"), " ", kw("final"), " ", kw("class"), " ", nm("LegacyShape")), + superclass: [OBJECT], ancestors: [objectRef], + deprecated: deprecated("Use [[com.example.geo.Polygon]]; this class predates sealed shapes and will be removed in 3.0. See [[guide:migrating-from-1x#classes-to-replace|Classes to replace]] in the migration guide.", "2.0", true), + doc: doc("A shape from the 1.x API."), since: "1.0", +}); + +const shapesId = `${G}.Shapes`; +const shapes: Type = type({ + id: shapesId, name: "Shapes", kind: "class", modifiers: ["public", "final"], + signature: tk(kw("public"), " ", kw("final"), " ", kw("class"), " ", nm("Shapes")), + superclass: [OBJECT], ancestors: [objectRef], + members: [ + m(shapesId, { name: "PRECISION", kind: "field", mods: ["public", "static", "final"], type: [INT], constant: "6", doc: "The default number of significant digits: `6`.", line: 60 }), + m(shapesId, { name: "NAME", kind: "field", mods: ["public", "static", "final"], type: [STRING], nullness: "nonNull", constant: '"geo"', doc: "The library's name as tools report it." }), + m(shapesId, { name: "area", mods: ["public", "static"], params: [{ name: "circle", type: [t("Circle")], nullness: "nonNull", doc: "the circle" }], returns: { type: [DOUBLE], doc: "its area" }, doc: "The area of a circle. One of two overloads." }), + m(shapesId, { name: "area", mods: ["public", "static"], params: [{ name: "polygon", type: [t("Polygon")], nullness: "nonNull", doc: "the polygon" }], returns: { type: [DOUBLE], doc: "its area" }, doc: "The area of a polygon. One of two overloads." }), + m(shapesId, { + name: "largest", mods: ["public", "static"], + typeParams: [{ name: "T", bounds: [[t("Shape")], tk(jdk("java.lang", "Comparable"), "<? ", kw("super"), " ", tp("T"), ">")], doc: "the shape type" }], + params: [{ name: "shapes", type: tk(jdk("java.util", "Collection"), "<? ", kw("extends"), " ", tp("T"), ">"), nullness: "nonNull", doc: "the shapes; not empty" }], + returns: { type: [tp("T")], doc: "the largest of `shapes`" }, + throws: [{ type: [jdk("java.util", "NoSuchElementException")], doc: "if `shapes` is empty" }], + doc: { body: "Returns the largest shape.", notes: [["implSpec", "Compares with [[java.lang.Comparable#compareTo(T)|Comparable.compareTo]], keeping the first of equal shapes."]] }, + }), + m(shapesId, { + name: "total", mods: ["public", "static"], annotations: [tk(an("@Measured", `${G}.Measured`), "(", { kind: "param", text: "precision" }, " = ", lit("6"), ")")], + params: [{ name: "shapes", type: tk(t("Shape"), "..."), varargs: true, nullness: "nonNull", doc: "the shapes" }], + returns: { type: [DOUBLE], doc: "the total area in square meters; `0` for no shapes" }, doc: "Sums the shapes' areas.", + }), + m(shapesId, { + name: "parse", mods: ["public", "static"], params: [{ name: "text", type: [STRING], nullness: "nonNull", doc: "the text form, such as `circle 2.5`" }], + returns: { type: [t("Shape")], nullness: "nonNull", doc: "the shape" }, + throws: [ + { type: [jdk("java.io", "IOException")], declared: true, doc: "if the text names a file that cannot be read" }, + { type: [t("GeometryException")], declared: true, doc: "if the text describes an impossible shape" }, + { type: [jdk("java.lang", "IllegalStateException")], doc: "if the parser was closed" }, + ], + doc: { + body: [P("Parses a shape from its text form."), CODE("java", 'Shape s = Shapes.parse("circle 2.5");\nassert s instanceof Circle c && c.radius() == 2.5;')], + notes: [ + ["apiNote", "The text form is **not stable** across releases: store shapes some other way. Parsing `circle -1` throws rather than returning an empty shape."], + ["implNote", "Parses with a hand-written scanner; no regular expressions."], + ], + see: ["[[com.example.geo.io.ShapeReader]]", "[[guide:advanced/text-format#grammar|The text format: grammar]]", "[Shape text format](https://example.com/geo/format)"], + }, + }), + m(shapesId, { + name: "sum", mods: ["public", "static"], params: [{ name: "shapes", type: tk(jdk("java.util", "List"), "<", t("Shape"), ">"), nullness: "nonNull", doc: "the shapes" }], + returns: { type: [DOUBLE], doc: "the total area" }, + deprecated: deprecated("Use [[com.example.geo.Shapes#total(com.example.geo.Shape...)|total(Shape...)]], which takes any number of shapes.", "1.1", true), + annotations: [tk(an("@Deprecated", "java.lang.Deprecated", "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Deprecated.html"), "(", { kind: "param", text: "since" }, " = ", lit('"1.1"'), ", ", { kind: "param", text: "forRemoval" }, " = ", lit("true"), ")")], + doc: "Sums the areas of a list of shapes.", + }), + m(shapesId, { + name: "find", mods: ["public", "static"], since: "1.1", + params: [ + { name: "shapes", type: tk(jdk("java.util", "Map"), "<", STRING, ", ? ", kw("extends"), " ", t("Shape"), ">"), nullness: "nonNull", doc: "shapes by name" }, + { name: "name", type: [STRING], nullness: "nonNull", doc: "the name to look up" }, + ], + returns: { type: tk(NULLABLE, " ", t("Shape")), nullness: "nullable", doc: "the shape, or `null` when there is none" }, + doc: { body: [P("Finds a shape by name. Unlike [[com.example.geo.Shapes$Registry|the registry]], this never throws for a missing name.")] }, + }), + m(shapesId, { + name: "transform", mods: ["public", "static"], + typeParams: [{ name: "S", bounds: [[t("Shape")]] }, { name: "R", bounds: [tk(jdk("java.lang", "Comparable"), "<? ", kw("super"), " ", tp("R"), ">")] }], + params: [ + { name: "shapes", type: tk(jdk("java.util", "Collection"), "<? ", kw("extends"), " ", tp("S"), ">"), doc: "the input shapes" }, + { name: "mapper", type: tk(jdk("java.util.function", "Function"), "<? ", kw("super"), " ", tp("S"), ", ? ", kw("extends"), " ", tp("R"), ">"), doc: "maps each shape" }, + { name: "filter", type: tk(jdk("java.util.function", "Predicate"), "<? ", kw("super"), " ", tp("R"), ">"), doc: "keeps a result when it returns `true`" }, + { name: "comparator", type: tk(jdk("java.util", "Comparator"), "<? ", kw("super"), " ", tp("R"), ">"), doc: "orders the results" }, + { name: "limit", type: [INT], doc: "the most results to return" }, + { name: "units", type: [t("Units")], doc: "the unit for measured results" }, + { name: "label", type: tk(NULLABLE, " ", STRING), nullness: "nullable", doc: "a label for diagnostics, or `null`" }, + ], + returns: { type: tk(jdk("java.util", "List"), "<", tp("R"), ">"), nullness: "nonNull", doc: "the sorted, filtered results" }, + throws: [{ type: [t("GeometryException")], declared: true, doc: "if a shape cannot be measured in `units`" }], + doc: "Maps, filters and sorts shapes in one pass. A long signature, laid out by google-java-format: one parameter per line, `throws` on its own line.", + wrap: true, + }), + m(shapesId, { + name: "describe", mods: ["public", "static"], params: [{ name: "shape", type: [t("Shape")], doc: "the shape" }], + returns: { type: [STRING], doc: "the description" }, + doc: { body: [P("Describes a shape. This links to [[com.example.geo.Ellipse|an ellipse type]] that this model does not contain, so the link renders as plain code."), { kind: "paragraph", children: [{ kind: "text", text: "Also an inline raw node: E = mc" }, { kind: "raw", html: "<sup>2</sup>", text: "2" }, { kind: "text", text: "." }] }] }, + }), + ], + inherited: [fromObject], + doc: doc({ + body: [ + P("Operations on [[com.example.geo.Shape|shapes]]."), + P("Every method is *pure*: it never modifies its arguments. **Thread safety:** every method is safe to call concurrently."), + UL("[[com.example.geo.Shapes#largest(java.util.Collection)]] picks the largest shape.", "[[com.example.geo.Shapes#total(com.example.geo.Shape...)]] sums areas."), + OL("Measure each shape.", "Compare the results with `compareTo`."), + TABLE("Unit factors", ["Unit", "Factor"], [["[[com.example.geo.Units#METERS]]", "1.0"], ["[[com.example.geo.Units#FEET]]", "0.3048"]]), + H(2, "Java and Kotlin"), + CODE("java", "Shape big = Shapes.largest(List.of(Circle.of(1), new Polygon(1, 1, 1)));\ndouble total = Shapes.total(big, Circle.of(3)); // 0x1F, 3.5e2"), + CODE("kotlin", "val big = Shapes.largest(listOf(Circle.of(1.0), Polygon(1.0, 1.0, 1.0)))\nval total: Double = Shapes.total(big, Circle.of(3.0))"), + QUOTE("Measure twice, cut once."), + RAW('<dl class="legacy"><dt>Precision</dt><dd>Six digits</dd></dl>', "Precision: Six digits"), + ], + notes: [["implNote", "Areas are computed in double precision."]], + see: ["[[com.example.geo.Shape]]", "[[com.example.geo.Shape#area()|the area of a shape]]", '"Euclid, Elements, Book I"', "[Area on Wikipedia](https://en.wikipedia.org/wiki/Area)"], + }), + since: "1.0", nullMarked: true, source: { path: "com/example/geo/Shapes.java", line: 50 }, +}); + +const builder: Type = type({ + id: `${G}.Shapes$Builder`, name: "Shapes.Builder", kind: "class", modifiers: ["public", "static", "final"], enclosing: shapesId, + signature: tk(kw("public"), " ", kw("static"), " ", kw("final"), " ", kw("class"), " ", nm("Shapes.Builder")), + superclass: [OBJECT], ancestors: [objectRef], + members: [ + m(`${G}.Shapes$Builder`, { name: "Builder", kind: "constructor", mods: ["public"], doc: "Creates an empty builder." }), + m(`${G}.Shapes$Builder`, { name: "with", mods: ["public"], params: [{ name: "option", type: [t("Shapes$Builder$Option")], doc: "the option to set" }], returns: { type: [t("Shapes$Builder")], doc: "this builder" }, doc: "Sets an option." }), + ], + inherited: [fromObject], doc: doc("Builds a list of shapes one at a time."), since: "1.2", nullMarked: true, +}); + +const option: Type = type({ + id: `${G}.Shapes$Builder$Option`, name: "Shapes.Builder.Option", kind: "enum", modifiers: ["public"], enclosing: `${G}.Shapes$Builder`, + signature: tk(kw("public"), " ", kw("enum"), " ", nm("Shapes.Builder.Option")), + members: [ + m(`${G}.Shapes$Builder$Option`, { name: "SORTED", kind: "enumConstant", type: [t("Shapes$Builder$Option")], doc: "Keep shapes sorted by area." }), + m(`${G}.Shapes$Builder$Option`, { name: "DISTINCT", kind: "enumConstant", type: [t("Shapes$Builder$Option")], doc: "Drop shapes equal to one already added." }), + ], + doc: doc("Options for a builder: a type nested two levels deep."), nullMarked: true, +}); + +const registry: Type = type({ + id: `${G}.Shapes$Registry`, name: "Shapes.Registry", kind: "interface", modifiers: ["public", "static"], enclosing: shapesId, + signature: tk(kw("public"), " ", kw("interface"), " ", nm("Shapes.Registry")), + members: [m(`${G}.Shapes$Registry`, { name: "lookup", params: [{ name: "name", type: [STRING], doc: "the shape's name" }], returns: { type: [t("Shape")], doc: "the shape" }, throws: [{ type: [jdk("java.util", "NoSuchElementException")], doc: "if no shape has that name" }], doc: "Looks up a shape by name." })], + doc: doc("Shapes by name."), nullMarked: true, +}); + +// ---- com.example.geo.io + +const reader: Type = type({ + id: `${IO}.ShapeReader`, name: "ShapeReader", kind: "class", modifiers: ["public", "final"], + signature: tk(kw("public"), " ", kw("final"), " ", kw("class"), " ", nm("ShapeReader"), " ", kw("implements"), " ", jdk("java.lang", "AutoCloseable")), + superclass: [OBJECT], ancestors: [objectRef], interfaces: [[jdk("java.lang", "AutoCloseable")]], + members: [ + m(`${IO}.ShapeReader`, { name: "read", mods: ["public", "static"], params: [{ name: "in", type: [jdk("java.io", "InputStream")], doc: "the stream; not closed" }], returns: { type: tk(jdk("java.util", "List"), "<", t("Shape"), ">"), doc: "the shapes, in order" }, throws: [{ type: [jdk("java.io", "IOException")], declared: true, doc: "if reading fails" }], doc: "Reads every shape from a stream of UTF-8 text." }), + m(`${IO}.ShapeReader`, { name: "read", mods: ["public", "static"], params: [{ name: "reader", type: [jdk("java.io", "Reader")], doc: "the reader; not closed" }, { name: "charset", type: [jdk("java.nio.charset", "Charset")], doc: "the charset the text was decoded from" }], returns: { type: tk(jdk("java.util", "List"), "<", t("Shape"), ">"), doc: "the shapes, in order" }, throws: [{ type: [jdk("java.io", "IOException")], declared: true, doc: "if reading fails" }], doc: "Reads every shape from a reader." }), + m(`${IO}.ShapeReader`, { + name: "readAll", mods: ["public", "static"], wrap: true, since: "2.1", + params: [ + { name: "directory", type: [jdk("java.nio.file", "Path")], doc: "the directory to read" }, + { name: "glob", type: [STRING], doc: "the file names to read, such as `*.shapes`" }, + { name: "charset", type: [jdk("java.nio.charset", "Charset")], doc: "the files' charset" }, + { name: "maxShapes", type: [INT], doc: "the most shapes to read before failing" }, + ], + returns: { type: tk(jdk("java.util", "List"), "<", t("Shape", G), ">"), nullness: "nonNull", doc: "the shapes, by file name and then line" }, + throws: [ + { type: [jdk("java.io", "IOException")], declared: true, doc: "if a file cannot be read" }, + { type: [t("GeometryException", G)], declared: true, doc: "if a line describes an impossible shape, or there are more than `maxShapes`" }, + ], + doc: "Reads every shape from the matching files in a directory. Its signature is laid out as google-java-format lays it out.", + }), + m(`${IO}.ShapeReader`, { name: "close", mods: ["public"], throws: [{ type: [jdk("java.io", "IOException")], declared: true, doc: "if closing the reader fails" }], doc: "Closes the underlying reader.", overrides: { id: "java.lang.AutoCloseable#close()", url: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html#close()" } }), + ], + inherited: [fromObject], + doc: doc({ body: "Reads shapes in their text form, one per line.", see: ["[[com.example.geo.Shapes#parse(java.lang.String)]]"] }), since: "1.0", +}); + +// ---- com.example.geo.registry: one type with hundreds of members. + +function generated(): Type { + const id = `${BIG}.ShapeCatalog`; + const members: Member[] = []; + const families = ["circle", "square", "triangle", "hexagon", "octagon", "ellipse", "star", "arc", "ring", "sector"]; + const verbs = ["area", "perimeter", "scale", "rotate", "translate", "mirror", "contains", "intersects", "union", "bounds"]; + for (let i = 0; i < 40; i++) { + members.push(m(id, { name: `${families[i % 10]!.toUpperCase()}_${Math.floor(i / 10) + 1}`, kind: "field", mods: ["public", "static", "final"], type: [STRING], constant: `"${families[i % 10]}-${i}"`, doc: `The catalog key of ${families[i % 10]} variant ${Math.floor(i / 10) + 1}.` })); + } + for (const family of families) { + for (const verb of verbs) { + for (const arity of [1, 2, 3]) { + const cap = family[0]!.toUpperCase() + family.slice(1); + members.push(m(id, { + name: `${verb}${cap}`, mods: ["public"], + params: Array.from({ length: arity }, (_, k) => ({ name: ["shape", "factor", "origin"][k]!, type: [k === 0 ? t("Shape", G) : DOUBLE], doc: ["the shape", "the factor", "the origin offset"][k] })), + returns: { type: [verb === "contains" || verb === "intersects" ? kw("boolean") : DOUBLE], doc: `the ${verb} result` }, + doc: `Computes ${verb} for a ${family}${arity > 1 ? ` with ${arity} arguments` : ""}.`, + })); + } + } + } + return type({ + id, name: "ShapeCatalog", kind: "class", modifiers: ["public", "final"], + signature: tk(kw("public"), " ", kw("final"), " ", kw("class"), " ", nm("ShapeCatalog")), + superclass: [OBJECT], ancestors: [objectRef], members, inherited: [fromObject], + doc: doc("A catalog with hundreds of members, generated to exercise long pages, the member summary and the table of contents."), + since: "2.0", + }); +} + +// ---- Guides. Listed out of reading order on purpose: the migration guide has no order, and the Advanced group +// lists its second guide first, so the pages show how the renderer orders them. + +function guides(): Guide[] { + const gettingStarted = guide({ + slug: "getting-started", title: "Getting started", order: 1, + summary: "Add geo to a build and measure a first shape.", + source: { path: "docs/guides/getting-started.md", line: 1 }, + body: [ + P("geo measures plane shapes: circles, polygons and shapes you build from them. This guide adds it to a build and runs a first program."), + H(2, "Install"), + P("geo needs Java 21 or later. With Gradle, add the dependency to `build.gradle.kts`:"), + CODE("kotlin", 'dependencies {\n implementation("com.example:geo:2.1.0")\n}'), + P("With Maven, add it to `pom.xml`:"), + CODE("xml", "<dependency>\n <groupId>com.example</groupId>\n <artifactId>geo</artifactId>\n <version>2.1.0</version>\n</dependency>"), + P("On the module path, require the module:"), + CODE("java", "module my.app {\n requires com.example.geo;\n}"), + H(2, "Your first shape"), + P("Create shapes with [[com.example.geo.Circle#of(double)|Circle.of]] and the [[com.example.geo.Polygon#<init>(double...)|Polygon]] constructor, then measure them with [[com.example.geo.Shapes]]:"), + CODE("java", 'import com.example.geo.*;\n\nclass First {\n public static void main(String[] args) {\n Shape circle = Circle.of(2);\n Shape triangle = new Polygon(3, 3, 3);\n System.out.printf("total area: %.2f m²%n", Shapes.total(circle, triangle));\n }\n}'), + ADMON("tip", "Every length is in meters. To work in other units, see [[guide:concepts#units|Units]] in the concepts guide."), + H(2, "Next steps"), + UL( + "[[guide:concepts|Concepts]] explains shapes, measuring and units.", + "[[guide:migrating-from-1x|Migrating from 1.x]] lists what changed in 2.0.", + "The [[com.example.geo]] package is the reference for everything above.", + ), + ], + }); + + const concepts = guide({ + slug: "concepts", title: "Concepts", order: 2, + summary: "Shapes, measuring and units: the ideas the reference pages assume.", + body: [ + P("Three ideas carry the whole library: a closed set of shapes, pure functions that measure them, and one unit of length. Each section below links to the declarations it describes."), + H(2, "Shapes"), + P("Every shape implements the sealed interface [[com.example.geo.Shape]]. Two classes implement it:"), + UL( + [P("[[com.example.geo.Circle]], a record of a radius and an optional label."), UL("Create one with [[com.example.geo.Circle#of(double)|Circle.of(double)]].", "Its [[com.example.geo.Circle#area()|area()]] is `π r²`.")], + [P("[[com.example.geo.Polygon]], a regular polygon built from its sides."), UL("It extends [[com.example.geo.AbstractShape]], which adds [[com.example.geo.AbstractShape#perimeter()|perimeter()]].", "It is not sealed: [[guide:advanced/custom-shapes|Custom shapes]] shows how to extend it.")], + ), + ADMON("note", "Because the hierarchy is sealed, a `switch` over a shape needs no `default` branch, and the compiler tells you when a new shape appears."), + H(3, "Example"), + CODE("java", 'String describe(Shape shape) {\n return switch (shape) {\n case Circle c -> "circle of radius " + c.radius();\n case Polygon p -> "polygon with perimeter " + p.perimeter();\n };\n}'), + H(2, "Measuring"), + P("[[com.example.geo.Shapes]] holds the operations. They are pure: none modifies its arguments. `area` is overloaded, so the compiler picks [[com.example.geo.Shapes#area(com.example.geo.Circle)|area(Circle)]] or [[com.example.geo.Shapes#area(com.example.geo.Polygon)|area(Polygon)]] from the argument's static type."), + OL("Build the shapes.", "Measure each one, or sum them with [[com.example.geo.Shapes#total(com.example.geo.Shape...)|total(Shape...)]].", "Compare the results: shapes order by area."), + ADMON("tip", "To collect shapes as you go, use [[com.example.geo.Shapes$Builder|Shapes.Builder]] with the options of its nested enum [[com.example.geo.Shapes$Builder$Option|Shapes.Builder.Option]], such as [[com.example.geo.Shapes$Builder$Option#SORTED|SORTED]].", "Collecting shapes"), + H(3, "Example"), + CODE("java", "double small = Shapes.area(Circle.of(1));\ndouble large = Shapes.area(new Polygon(4, 4, 4, 4));\nassert small < large;"), + H(2, "Units"), + P("Every length is in meters, and every area in square meters. [[com.example.geo.Units]] converts other units at the edges of a program:"), + TABLE("Units of length", ["Unit", "Meters per unit", "Status"], [ + ["[[com.example.geo.Units#METERS]]", "`1.0`", "The base unit"], + ["[[com.example.geo.Units#FEET]]", "`0.3048`", "Deprecated since 1.2"], + ]), + ADMON("important", "Methods take and return meters. Convert once, when a value enters the program, with [[com.example.geo.Units#toMeters(double)|toMeters(double)]]."), + ADMON("warning", "Converting back and forth between units loses precision. Keep lengths in meters until you show them.", "Round trips lose precision"), + H(2, "Parsing"), + P("[[com.example.geo.Shapes#parse(java.lang.String)|Shapes.parse]] reads the text form of one shape. The [[guide:advanced/text-format#grammar|text format guide]] has the grammar."), + ADMON("caution", "The text form is not stable across releases. Store shapes some other way, and never parse text you do not trust without a size limit."), + H(2, "Threads"), + ADMON("apiNote", "Every method of [[com.example.geo.Shapes]] is safe to call from several threads at once."), + ADMON("implSpec", "A subclass of [[com.example.geo.Polygon]] must keep `area()` free of side effects, so that callers may cache it."), + ADMON("implNote", "The library keeps no caches and allocates only the results it returns."), + H(2, "Further reading"), + UL( + "[Polygon](https://en.wikipedia.org/wiki/Polygon) on Wikipedia.", + "[[guide:migrating-from-1x#classes-to-replace|Classes to replace]], in the migration guide.", + "[[com.example.geo.Ellipse|Ellipse]] is planned for a later release. This model does not contain it, so the link renders as plain text.", + "[[guide:recipes|Recipes]] is a guide that does not exist yet, so this link renders as plain text too.", + ), + ], + }); + + const migration = guide({ + slug: "migrating-from-1x", title: "Migrating from 1.x", + summary: "What changed in 2.0, and how to update code written for 1.x.", + body: [ + P("Version 2.0 keeps every 1.x class, but deprecates a few for removal in 3.0. This guide lists each one with its replacement."), + ADMON("important", "Compile with `-Xlint:deprecation` to list every use of a deprecated declaration in your code."), + H(2, "Classes to replace"), + P("[[com.example.geo.LegacyShape]] predates sealed shapes. Replace it with [[com.example.geo.Polygon]] or [[com.example.geo.Circle]]:"), + TABLE("Replacements", ["1.x", "2.0"], [ + ["[[com.example.geo.LegacyShape]]", "[[com.example.geo.Polygon]]"], + ["[[com.example.geo.Shapes#sum(java.util.List)|Shapes.sum(List)]]", "[[com.example.geo.Shapes#total(com.example.geo.Shape...)|Shapes.total(Shape...)]]"], + ["[[com.example.geo.Units#FEET]]", "[[com.example.geo.Units#METERS]], converting with `toMeters`"], + ]), + H(2, "Changed methods"), + P("[[com.example.geo.Shapes#sum(java.util.List)|sum(List)]] becomes [[com.example.geo.Shapes#total(com.example.geo.Shape...)|total(Shape...)]], which takes any number of shapes:"), + CODE("java", "// 1.x\ndouble before = Shapes.sum(List.of(a, b));\n\n// 2.0\ndouble after = Shapes.total(a, b);"), + H(2, "Units"), + P("[[com.example.geo.Units#FEET]] is deprecated: mixing units caused rounding errors. Convert to meters at the edge, as [[guide:concepts#units|Units]] describes."), + ADMON("caution", "When `FEET` goes in 3.0, the ordinals of later constants change. Do not store `ordinal()` values."), + H(2, "Checklist"), + OL("Update the dependency to 2.1.0.", "Fix each deprecation warning with the table above.", "Run your tests."), + ], + }); + + const textFormat = guide({ + slug: "advanced/text-format", title: "The text format", group: "Advanced", order: 2, + summary: "The grammar `Shapes.parse` reads, and how to read files of shapes.", + source: { path: "docs/guides/advanced/text-format.md", line: 1 }, + body: [ + P("Shapes have a one-line text form, for logs and test fixtures. [[com.example.geo.Shapes#parse(java.lang.String)|Shapes.parse]] reads one; [[com.example.geo.io.ShapeReader]] reads a stream of them."), + H(2, "Grammar"), + CODE("text", "shape = circle | polygon\ncircle = \"circle\" number\npolygon = \"polygon\" number number number { number }\nnumber = digit { digit } [ \".\" digit { digit } ]"), + P("Numbers are lengths in meters. Blank lines and lines starting with `#` are skipped."), + H(2, "Reading files"), + P("[[com.example.geo.io.ShapeReader#read(java.io.InputStream)|read(InputStream)]] reads UTF-8 text; the [[com.example.geo.io.ShapeReader#read(java.io.Reader,java.nio.charset.Charset)|read(Reader, Charset)]] overload reads text you have already decoded."), + CODE("java", 'try (var in = Files.newInputStream(Path.of("shapes.txt"))) {\n List<Shape> shapes = ShapeReader.read(in);\n}'), + ADMON("warning", "A malformed line throws [[com.example.geo.GeometryException]] and stops the read. Validate files from users before you read them."), + ], + }); + + const customShapes = guide({ + slug: "advanced/custom-shapes", title: "Custom shapes", group: "Advanced", order: 1, + summary: "Extend `Polygon` to add a shape of your own.", + body: [ + P("[[com.example.geo.Shape]] is sealed, but [[com.example.geo.Polygon]] is not: extend it to add a shape the library does not have."), + CODE("java", "public final class Square extends Polygon {\n public Square(double side) {\n super(side, side, side, side);\n }\n}"), + P("Override [[com.example.geo.AbstractShape#perimeter()|perimeter()]] only when you can compute it faster than summing the sides."), + ADMON("tip", "Keep custom shapes immutable, like the built-in ones; [[guide:concepts#threads|Threads]] explains why."), + ], + }); + + return [migration, gettingStarted, concepts, textFormat, customShapes]; +} + +const packages: Package[] = [ + { + id: G, name: G, nullMarked: true, since: "1.0", + doc: doc({ + body: [P("Shapes, units and measurements."), H(2, "Where to start"), P("Start with [[com.example.geo.Shape]] and the operations in [[com.example.geo.Shapes]]. Readers live in [[com.example.geo.io]]. The [[guide:concepts#shapes|Shapes]] section of the concepts guide explains how they fit together.")], + see: ["[[com.example.geo.io]]", "[[guide:concepts|Concepts]]"], + }), + types: [abstractShape, circle, geoException, legacyShape, measured, polygon, shape, shapes, builder, option, registry, units].sort((a, b) => a.name.localeCompare(b.name)), + }, + { id: IO, name: IO, since: "1.0", doc: doc("Reading shapes from streams. Not null-marked: nullness here is unspecified unless annotated."), types: [reader] }, + { id: BIG, name: BIG, since: "2.0", doc: doc("A generated catalog, for performance."), types: [generated()] }, + { id: EMPTY, name: EMPTY, since: "2.1", doc: doc("Service-provider interfaces. Reserved: this package declares nothing public yet.") }, +]; + +export const javaSample: Model = { + schema: "apidocs/1", + module: { + name: "geo", version: "2.1.0", languages: ["java"], + doc: doc({ body: [ + P("A small geometry library: the Java-flavored sample for `@elide/apidocs`."), + P("New here? Start with [[guide:getting-started|Getting started]], then read [[guide:concepts|Concepts]]."), + P("It shows every construct the doclet writes. See `samples/FEATURES.md` for the list."), + ] }), + guides: guides(), + }, + externals: [ + { prefix: "java.", url: "https://docs.oracle.com/en/java/javase/25/docs/api/{module}/" }, + { prefix: "org.jspecify.", url: "https://jspecify.dev/docs/api/" }, + ], + packages, +}; + diff --git a/packages/apidocs/samples/kotlin.ts b/packages/apidocs/samples/kotlin.ts new file mode 100644 index 0000000..e637c9e --- /dev/null +++ b/packages/apidocs/samples/kotlin.ts @@ -0,0 +1,306 @@ +/** + * The Kotlin-flavored sample: what the Dokka plugin will write. Ids are Dokka + * DRIs; anchors are readable names. It covers top-level functions and + * properties, extensions with receivers, objects and companions, data, sealed, + * value and enum classes, suspend and inline functions, type aliases, nullable + * types and default arguments. + */ +import type { Guide, Model, Package, Token, Type } from "../src/model"; +import { ADMON, an, blocks, CODE, deprecated, doc, guide, H, kotlinMember, kw, lit, nm, OL, P, prm, TABLE, tk, tp, ty, type, UL } from "./build"; + +const K = "org.example.kgeo"; +const KC = "org.example.kgeo.coroutines"; +const KE = "org.example.kgeo.experimental"; + +const dri = (pkg: string, cls: string) => `${pkg}/${cls}///PointingToDeclaration/`; +const t = (name: string, pkg = K) => ty(name, dri(pkg, name)); +const std = (name: string, pkg = "kotlin") => + ty(name, dri(pkg, name), `https://kotlinlang.org/api/core/kotlin-stdlib/${pkg}/-${name.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()}/`); +const DOUBLE = std("Double"); +const STRING = std("String"); +const BOOLEAN = std("Boolean"); +const list = (...item: Token[]) => tk(std("List", "kotlin.collections"), "<", ...item, ">"); +const nullable = (...type: Token[]) => tk(...type, "?"); +const f = (owner: string, spec: Parameters<typeof kotlinMember>[1]) => kotlinMember(owner, spec); + +const shape: Type = type({ + id: dri(K, "Shape"), name: "Shape", kind: "class", modifiers: ["public", "sealed"], + signature: tk(kw("sealed"), " ", kw("class"), " ", nm("Shape")), + members: [ + f(`${K}/Shape`, { name: "area", kind: "property", mods: ["abstract"], type: [DOUBLE], nullness: "nonNull", doc: "The area in square meters; never negative." }), + f(`${K}/Shape`, { name: "describe", mods: ["open"], returns: { type: [STRING], doc: "a description such as `circle r=2.0`" }, doc: "Describes the shape for logs." }), + ], + doc: doc({ body: "A closed plane figure.\n\nThe hierarchy is sealed, so a `when` over a shape needs no `else` branch.", notes: [["apiNote", "Subclasses live in this module only; a `when` over [[org.example.kgeo/Shape///PointingToDeclaration/|Shape]] is exhaustive."]] }), + since: "1.0", source: { path: "org/example/kgeo/Shape.kt", line: 12 }, +}, "kotlin"); + +const circle: Type = type({ + id: dri(K, "Circle"), name: "Circle", kind: "class", modifiers: ["public", "data"], + signature: tk(kw("data"), " ", kw("class"), " ", nm("Circle"), "(", kw("val"), " ", prm("radius"), ": ", DOUBLE, ", ", kw("val"), " ", prm("label"), ": ", STRING, "? = ", lit("null"), ") : ", t("Shape"), "()"), + superclass: [t("Shape")], ancestors: [{ id: dri(K, "Shape") }, { id: dri("kotlin", "Any"), url: "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-any/" }], + members: [ + f(`${K}/Circle`, { name: "Circle", kind: "constructor", params: [{ name: "radius", type: [DOUBLE], doc: "the radius in meters" }, { name: "label", type: nullable(STRING), nullness: "nullable", defaultValue: "null", doc: "an optional label" }], doc: "Creates a circle." }), + f(`${K}/Circle`, { name: "radius", kind: "property", type: [DOUBLE], doc: "The radius in meters." }), + f(`${K}/Circle`, { name: "label", kind: "property", type: nullable(STRING), nullness: "nullable", doc: "An optional label, or `null`." }), + f(`${K}/Circle`, { name: "area", kind: "property", mods: ["override"], type: [DOUBLE], overrides: { id: `${K}/Shape/area/#/PointingToDeclaration/` }, doc: "The area: `π r²`." }), + f(`${K}/Circle`, { name: "copy", params: [{ name: "radius", type: [DOUBLE], defaultValue: "this.radius" }, { name: "label", type: nullable(STRING), nullness: "nullable", defaultValue: "this.label" }], returns: { type: [t("Circle")] }, implicit: true }), + ], + doc: doc("A circle: a data class with a default argument and a companion object."), since: "1.0", +}, "kotlin"); + +const companion: Type = type({ + id: `${K}/Circle.Companion///PointingToDeclaration/`, name: "Circle.Companion", kind: "object", modifiers: ["public", "companion"], enclosing: dri(K, "Circle"), + signature: tk(kw("companion"), " ", kw("object"), " ", nm("Companion")), + members: [ + f(`${K}/Circle.Companion`, { name: "UNIT", kind: "property", mods: ["const"], type: [DOUBLE], constant: "1.0", doc: "The unit radius." }), + f(`${K}/Circle.Companion`, { name: "unit", returns: { type: [t("Circle")], doc: "a circle of radius [[org.example.kgeo/Circle.Companion/UNIT/#/PointingToDeclaration/|UNIT]]" }, doc: "The unit circle." }), + ], + doc: doc("Factories for circles."), since: "1.0", +}, "kotlin"); + +const rect: Type = type({ + id: dri(K, "Rectangle"), name: "Rectangle", kind: "class", modifiers: ["public", "data"], + signature: tk(kw("data"), " ", kw("class"), " ", nm("Rectangle"), "(", kw("val"), " ", prm("width"), ": ", t("Meters"), ", ", kw("val"), " ", prm("height"), ": ", t("Meters"), " = ", prm("width"), ") : ", t("Shape"), "()"), + superclass: [t("Shape")], ancestors: [{ id: dri(K, "Shape") }], + members: [ + f(`${K}/Rectangle`, { name: "Rectangle", kind: "constructor", params: [{ name: "width", type: [t("Meters")], doc: "the width" }, { name: "height", type: [t("Meters")], defaultValue: "width", doc: "the height; a square when left out" }], doc: "Creates a rectangle, or a square when `height` is left out." }), + f(`${K}/Rectangle`, { name: "area", kind: "property", mods: ["override"], type: [DOUBLE], doc: "Width times height." }), + ], + doc: doc("An axis-aligned rectangle."), since: "1.0", +}, "kotlin"); + +const meters: Type = type({ + id: dri(K, "Meters"), name: "Meters", kind: "class", modifiers: ["public", "value"], + annotations: [[an("@JvmInline", dri("kotlin.jvm", "JvmInline"), "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.jvm/-jvm-inline/")]], + signature: tk(kw("value"), " ", kw("class"), " ", nm("Meters"), "(", kw("val"), " ", prm("value"), ": ", DOUBLE, ") : ", std("Comparable"), "<", t("Meters"), ">"), + interfaces: [tk(std("Comparable"), "<", t("Meters"), ">")], + members: [ + f(`${K}/Meters`, { name: "value", kind: "property", type: [DOUBLE], doc: "The length in meters." }), + f(`${K}/Meters`, { name: "plus", mods: ["operator"], params: [{ name: "other", type: [t("Meters")], doc: "the length to add" }], returns: { type: [t("Meters")], doc: "the sum" }, doc: "Adds two lengths: `a + b`." }), + f(`${K}/Meters`, { name: "compareTo", mods: ["override"], params: [{ name: "other", type: [t("Meters")] }], returns: { type: [std("Int")] }, doc: "Compares lengths." }), + ], + doc: doc({ body: "A length in meters, as a value class: no allocation on the JVM.", notes: [["implNote", "Compiles to a `double` wherever the type is not boxed."]] }), since: "1.1", +}, "kotlin"); + +const lengthUnit: Type = type({ + id: dri(K, "LengthUnit"), name: "LengthUnit", kind: "enum", modifiers: ["public"], + signature: tk(kw("enum"), " ", kw("class"), " ", nm("LengthUnit"), "(", kw("val"), " ", prm("factor"), ": ", DOUBLE, ")"), + members: [ + f(`${K}/LengthUnit`, { name: "METER", kind: "enumConstant", type: [t("LengthUnit")], doc: "The base unit." }), + f(`${K}/LengthUnit`, { name: "FOOT", kind: "enumConstant", type: [t("LengthUnit")], doc: "International feet.", deprecated: deprecated("Use [[org.example.kgeo/LengthUnit/METER/#/PointingToDeclaration/|METER]].", "1.2") }), + f(`${K}/LengthUnit`, { name: "factor", kind: "property", type: [DOUBLE], doc: "Meters per unit." }), + ], + doc: doc("Units of length."), since: "1.0", +}, "kotlin"); + +const geometry: Type = type({ + id: dri(K, "Geometry"), name: "Geometry", kind: "object", modifiers: ["public"], + signature: tk(kw("object"), " ", nm("Geometry")), + members: [ + f(`${K}/Geometry`, { name: "distance", params: [{ name: "a", type: [t("Point")] }, { name: "b", type: [t("Point")] }], returns: { type: [DOUBLE], doc: "the Euclidean distance" }, doc: "The distance between two points. One of two overloads." }), + f(`${K}/Geometry`, { name: "distance", params: [{ name: "a", type: [t("Point")], doc: "the first point" }, { name: "b", type: [t("Point")], doc: "the second point" }, { name: "metric", type: [t("Metric")], defaultValue: "Metric.EUCLID", doc: "how to measure" }], returns: { type: [DOUBLE], doc: "the distance under `metric`" }, doc: "The distance between two points under a metric." }), + f(`${K}/Geometry`, { + name: "transformShapes", wrap: true, since: "2.1", + params: [ + { name: "shapes", type: list(t("Shape")), doc: "the shapes" }, + { name: "transform", type: tk(ty("Transform", `${K}/Transform///PointingToDeclaration/`), "<", t("Shape"), ">"), doc: "applied to each shape" }, + { name: "filter", type: tk("(", t("Shape"), ") -> ", BOOLEAN), defaultValue: "{ true }", doc: "keeps a result when it returns `true`" }, + { name: "limit", type: [std("Int")], defaultValue: "Int.MAX_VALUE", doc: "the most results" }, + ], + returns: { type: list(t("Shape")), doc: "the transformed shapes that pass `filter`" }, + doc: "Transforms and filters shapes in one pass. Its signature is laid out as ktfmt lays it out.", + }), + f(`${K}/Geometry`, { + name: "nearest", wrap: true, since: "2.1", + params: [ + { name: "point", type: [t("Point")], doc: "the point to measure from" }, + { name: "candidates", type: tk(std("Collection", "kotlin.collections"), "<", t("Point"), ">"), doc: "the points to choose from" }, + { name: "metric", type: [t("Metric")], defaultValue: "Metric.EUCLID", doc: "how to measure" }, + { name: "maxDistance", type: [DOUBLE], defaultValue: "Double.POSITIVE_INFINITY", doc: "ignore candidates farther than this" }, + ], + returns: { type: nullable(t("Point")), nullness: "nullable", doc: "the nearest candidate, or `null` when none is within `maxDistance`" }, + doc: "The candidate nearest to a point.", + }), + f(`${K}/Geometry`, { + name: "filterShapes", mods: ["inline"], typeParams: [{ name: "reified T", bounds: [[t("Shape")]], doc: "the shape type to keep" }], + params: [{ name: "shapes", type: list(t("Shape")), doc: "the shapes" }], returns: { type: list(tp("T")), doc: "the shapes of type `T`" }, + doc: { body: [P("Keeps the shapes of one type."), CODE("kotlin", "val circles: List<Circle> = Geometry.filterShapes<Circle>(shapes)")] }, + }), + ], + doc: doc("Geometry functions, as a singleton object."), since: "1.0", +}, "kotlin"); + +const point: Type = type({ + id: dri(K, "Point"), name: "Point", kind: "class", modifiers: ["public", "data"], + signature: tk(kw("data"), " ", kw("class"), " ", nm("Point"), "(", kw("val"), " ", prm("x"), ": ", DOUBLE, " = ", lit("0.0"), ", ", kw("val"), " ", prm("y"), ": ", DOUBLE, " = ", lit("0.0"), ")"), + members: [ + f(`${K}/Point`, { name: "Point", kind: "constructor", params: [{ name: "x", type: [DOUBLE], defaultValue: "0.0", doc: "the x coordinate" }, { name: "y", type: [DOUBLE], defaultValue: "0.0", doc: "the y coordinate" }], doc: "Creates a point; both coordinates default to zero." }), + f(`${K}/Point`, { name: "x", kind: "property", type: [DOUBLE], doc: "The x coordinate." }), + f(`${K}/Point`, { name: "y", kind: "property", type: [DOUBLE], doc: "The y coordinate." }), + ], + doc: doc("A point in the plane."), since: "1.0", +}, "kotlin"); + +const metric: Type = type({ + id: dri(K, "Metric"), name: "Metric", kind: "interface", modifiers: ["public", "fun"], + signature: tk(kw("fun"), " ", kw("interface"), " ", nm("Metric")), + members: [f(`${K}/Metric`, { name: "measure", mods: ["abstract"], params: [{ name: "a", type: [t("Point")] }, { name: "b", type: [t("Point")] }], returns: { type: [DOUBLE] }, doc: "Measures the distance from `a` to `b`." })], + doc: doc("How to measure distance: a functional interface."), since: "1.1", +}, "kotlin"); + +const experimental: Type = type({ + id: dri(KE, "ExperimentalGeometry"), name: "ExperimentalGeometry", kind: "annotation", modifiers: ["public"], + annotations: [tk(an("@RequiresOptIn", dri("kotlin", "RequiresOptIn"), "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-requires-opt-in/"))], + signature: tk(kw("annotation"), " ", kw("class"), " ", nm("ExperimentalGeometry")), + doc: doc("Marks API that may change without notice. Opt in with `@OptIn(ExperimentalGeometry::class)`."), since: "2.0", +}, "kotlin"); + +// ---- Guides. + +const fn = (owner: string, name: string, params: string[], receiver = "") => `${owner}/${name}/${receiver}#${params.join("#")}/PointingToDeclaration/`; + +function guides(): Guide[] { + const gettingStarted = guide({ + slug: "getting-started", title: "Getting started", order: 1, + summary: "Add kgeo to a Gradle build and measure a first shape.", + body: [ + P("kgeo is a small geometry library for Kotlin. This guide adds it to a build and measures two shapes."), + H(2, "Install"), + P("Add the dependency to `build.gradle.kts`:"), + CODE("kotlin", 'dependencies {\n implementation("org.example:kgeo:2.1.0")\n}'), + H(2, "First steps"), + P("Shapes are data classes such as [[org.example.kgeo/Circle///PointingToDeclaration/|Circle]] and [[org.example.kgeo/Rectangle///PointingToDeclaration/|Rectangle]]. Top-level functions such as [[" + fn("org.example.kgeo/", "area", ["Shape"]) + "|area]] measure them:"), + CODE("kotlin", "fun main() {\n val shapes = listOf(Circle(2.0), Rectangle(Meters(3.0)))\n println(shapes.sumOf { area(it) })\n}"), + ADMON("tip", "Lengths are [[org.example.kgeo/Meters///PointingToDeclaration/|Meters]], a value class: type safety at no cost at run time. [[guide:concepts#lengths|Lengths]] explains more."), + H(2, "Next steps"), + UL("[[guide:concepts|Concepts]]: shapes, lengths, distance and extensions.", "[[guide:coroutines/loading|Loading shapes]]: suspending APIs."), + ], + }); + + const concepts = guide({ + slug: "concepts", title: "Concepts", order: 2, + summary: "Shapes, lengths, distance and extensions in kgeo.", + source: { path: "docs/guides/concepts.md", line: 1 }, + body: [ + P("kgeo leans on Kotlin's type system: sealed classes for shapes, a value class for lengths and extensions for convenience."), + H(2, "Shapes"), + P("[[org.example.kgeo/Shape///PointingToDeclaration/|Shape]] is a sealed class with these subclasses:"), + UL( + [P("[[org.example.kgeo/Circle///PointingToDeclaration/|Circle]], a data class."), UL("Its companion object [[org.example.kgeo/Circle.Companion///PointingToDeclaration/|Circle.Companion]] holds factories such as `unit()`.", "A `label` defaults to `null`.")], + [P("[[org.example.kgeo/Rectangle///PointingToDeclaration/|Rectangle]], also a data class."), UL("Leave out `height` for a square.")], + ), + ADMON("note", "A `when` over a shape needs no `else` branch, because the hierarchy is sealed."), + H(2, "Lengths"), + P("[[org.example.kgeo/Meters///PointingToDeclaration/|Meters]] wraps a `Double`. Its [[" + fn("org.example.kgeo/Meters", "plus", ["Meters"]) + "|plus]] operator adds lengths with `+`."), + TABLE("Length units", ["Unit", "Factor", "Status"], [ + ["[[org.example.kgeo/LengthUnit/METER/#/PointingToDeclaration/|METER]]", "`1.0`", "The base unit"], + ["[[org.example.kgeo/LengthUnit/FOOT/#/PointingToDeclaration/|FOOT]]", "`0.3048`", "Deprecated since 1.2"], + ]), + ADMON("important", "Store lengths as `Meters`, never as a bare `Double`: the compiler then catches unit mix-ups."), + ADMON("warning", "Boxing a value class (in a generic collection, for example) allocates. Prefer `DoubleArray` in hot loops.", "Boxing"), + H(2, "Distance"), + P("[[org.example.kgeo/Geometry///PointingToDeclaration/|Geometry]] has two `distance` overloads: [[" + fn("org.example.kgeo/Geometry", "distance", ["Point", "Point"]) + "|distance(Point, Point)]] and [[" + fn("org.example.kgeo/Geometry", "distance", ["Point", "Point", "Metric"]) + "|distance(Point, Point, Metric)]], which takes a [[org.example.kgeo/Metric///PointingToDeclaration/|Metric]]."), + CODE("kotlin", "val manhattan = Metric { a, b -> abs(a.x - b.x) + abs(a.y - b.y) }\nGeometry.distance(Point(), Point(3.0, 4.0), manhattan) // 7.0"), + ADMON("tip", "`Metric` is a `fun interface`, so a lambda converts to it."), + H(2, "Extensions"), + P("[[" + fn("org.example.kgeo/", "scaled", ["Double"], "Shape") + "|scaled]] and [[" + fn("org.example.kgeo/", "isDegenerate", [], "Shape") + "|isDegenerate]] extend `Shape`. Import them from `org.example.kgeo`."), + ADMON("caution", "Extensions resolve statically: a `scaled` you declare on a subclass does not override this one."), + H(2, "API notes"), + ADMON("apiNote", "Every function in `Geometry` is pure."), + ADMON("implSpec", "A `Metric` must be symmetric: `measure(a, b) == measure(b, a)`."), + ADMON("implNote", "`Meters` compiles to a `double` wherever it is not boxed."), + H(2, "Further reading"), + UL( + "[Sealed classes](https://kotlinlang.org/docs/sealed-classes.html) in the Kotlin documentation.", + "[[guide:migrating-from-1x#deprecated-functions|Deprecated functions]], in the migration guide.", + "[[org.example.kgeo/Triangle///PointingToDeclaration/|Triangle]] is not in this model, so the link renders as plain text.", + "[[guide:faq|FAQ]] does not exist, so this link renders as plain text too.", + ), + ], + }); + + const migration = guide({ + slug: "migrating-from-1x", title: "Migrating from 1.x", order: 3, + summary: "Replace the declarations 2.0 deprecates.", + body: [ + P("2.0 deprecates a few 1.x declarations. Each has a replacement."), + H(2, "Deprecated functions"), + P("[[" + fn("org.example.kgeo/", "totalArea", ["List<Shape>"]) + "|totalArea]] is deprecated. Use `sumOf`:"), + CODE("kotlin", "// 1.x\nval total = totalArea(shapes)\n\n// 2.0\nval total = shapes.sumOf { it.area }"), + H(2, "Deprecated units"), + P("[[org.example.kgeo/LengthUnit/FOOT/#/PointingToDeclaration/|LengthUnit.FOOT]] is deprecated; convert to [[org.example.kgeo/LengthUnit/METER/#/PointingToDeclaration/|METER]] once, at the edge."), + H(2, "Nullable parsing"), + P("[[" + fn("org.example.kgeo/", "parseShape", ["String"]) + "|parseShape]] now returns `null` for blank text instead of throwing."), + ADMON("warning", "Code that caught the exception for blank text must now check for `null`."), + OL("Update the dependency.", "Fix each deprecation warning.", "Check callers of `parseShape` for `null`."), + ], + }); + + const loading = guide({ + slug: "coroutines/loading", title: "Loading shapes", group: "Coroutines", order: 1, + summary: "Load and watch shape files without blocking a thread.", + body: [ + P("[[" + fn("org.example.kgeo.coroutines/", "loadShapes", ["String"]) + "|loadShapes]] suspends while it reads a file; [[" + fn("org.example.kgeo.coroutines/", "watchShapes", ["String"]) + "|watchShapes]] returns a `Flow` that emits as the file changes."), + CODE("kotlin", 'suspend fun report() {\n val shapes = loadShapes("shapes.txt")\n println("${shapes.size} shapes")\n}'), + ADMON("note", "Call these from a coroutine, for example inside `runBlocking` or a `viewModelScope`."), + ], + }); + + return [gettingStarted, concepts, migration, loading]; +} + +const top = `${K}/`; +const packages: Package[] = [ + { + id: K, name: K, since: "1.0", + doc: doc({ body: [P("Shapes and measurements in Kotlin."), UL("Shapes: [[org.example.kgeo/Shape///PointingToDeclaration/|Shape]] and its subclasses.", "Extensions on shapes, such as `scaled`; see [[guide:concepts#extensions|Extensions]]."), P("The [[guide:concepts|Concepts]] guide explains how these fit together.")] }), + types: [circle, companion, geometry, lengthUnit, meters, metric, point, rect, shape], + typeAliases: [ + { id: `${K}/ShapeList///PointingToDeclaration/`, name: "ShapeList", signature: tk(kw("typealias"), " ", nm("ShapeList"), " = ", list(t("Shape"))), target: list(t("Shape")), doc: doc("A list of shapes."), since: "1.0" }, + { id: `${K}/Transform///PointingToDeclaration/`, name: "Transform", typeParams: [{ name: "T", doc: blocks("the value type") }], signature: tk(kw("typealias"), " ", nm("Transform"), "<", tp("T"), "> = (", tp("T"), ") -> ", tp("T")), target: tk("(", tp("T"), ") -> ", tp("T")), doc: doc("A function from a value to a value of the same type."), since: "1.1" }, + ], + functions: [ + f(top, { name: "area", params: [{ name: "shape", type: [t("Shape")], doc: "the shape" }], returns: { type: [DOUBLE], doc: "its area" }, doc: "The area of a shape: a top-level function.", since: "1.0" }), + f(top, { name: "scaled", receiver: { name: "this", type: [t("Shape")], doc: "the shape to scale" }, params: [{ name: "by", type: [DOUBLE], defaultValue: "1.0", doc: "the scale factor" }], returns: { type: [t("Shape")], doc: "a scaled copy" }, doc: "Scales a shape: an extension function with a default argument." }), + f(top, { + name: "parseShape", annotations: [tk(an("@Throws", dri("kotlin", "Throws"), "https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-throws/"), "(", ty("IOException", "java.io.IOException", "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html"), "::", kw("class"), ")")], + params: [{ name: "text", type: [STRING], doc: "the text form" }], returns: { type: nullable(t("Shape")), nullness: "nullable", doc: "the shape, or `null` when `text` is blank" }, + throws: [{ type: [ty("IOException", "java.io.IOException", "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html")], declared: true, doc: "if the text names a file that cannot be read" }], + doc: { body: "Parses a shape; blank text gives `null`.", notes: [["apiNote", "Returns `null` for blank input instead of throwing, unlike the Java API."]], see: ["[[guide:migrating-from-1x#nullable-parsing|Nullable parsing]], in the migration guide"] }, + }), + f(top, { name: "totalArea", params: [{ name: "shapes", type: list(t("Shape")) }], returns: { type: [DOUBLE] }, deprecated: deprecated("Use `shapes.sumOf { it.area }`.", "1.2"), doc: "Sums areas." }), + ], + properties: [ + f(top, { name: "VERSION", kind: "property", mods: ["const"], type: [STRING], constant: '"2.1.0"', doc: "The library version." }), + f(top, { name: "defaultUnit", kind: "property", mods: ["var"], type: [t("LengthUnit")], doc: "The unit lengths use when none is given. Mutable." }), + f(top, { name: "isDegenerate", kind: "property", receiver: { name: "this", type: [t("Shape")] }, type: [BOOLEAN], doc: "Whether the shape has zero area: an extension property." }), + ], + }, + { + id: KC, name: KC, since: "1.2", doc: doc("Suspending APIs for loading shapes."), + functions: [ + f(`${KC}/`, { name: "loadShapes", mods: ["suspend"], params: [{ name: "path", type: [STRING], doc: "a file path" }], returns: { type: list(t("Shape")), doc: "the shapes in the file" }, doc: { body: [P("Loads shapes without blocking."), CODE("kotlin", 'runBlocking {\n val shapes = loadShapes("shapes.txt")\n println(shapes.size)\n}')] } }), + f(`${KC}/`, { name: "watchShapes", params: [{ name: "path", type: [STRING] }], returns: { type: tk(ty("Flow", dri("kotlinx.coroutines.flow", "Flow")), "<", t("Shape"), ">") }, doc: "Emits shapes as the file changes. Links to a kotlinx type outside this model, so `Flow` renders as plain code." }), + ], + }, + { id: KE, name: KE, since: "2.0", doc: doc("Experimental API."), types: [experimental] }, + { id: `${K}.internal`, name: `${K}.internal`, doc: doc("Internal helpers. This package declares nothing public.") }, +]; + +export const kotlinSample: Model = { + schema: "apidocs/1", + module: { + name: "kgeo", version: "2.1.0", languages: ["kotlin"], + doc: doc({ body: [ + P("A small Kotlin geometry library: the Kotlin-flavored sample for `@elide/apidocs`."), + P("Start with [[guide:getting-started|Getting started]]."), + P("It shows what the Dokka plugin writes. See `samples/FEATURES.md` for the list."), + ] }), + guides: guides(), + }, + externals: [ + { prefix: "kotlin", url: "https://kotlinlang.org/api/core/kotlin-stdlib/" }, + { prefix: "java.", url: "https://docs.oracle.com/en/java/javase/25/docs/api/{module}/" }, + ], + packages, +}; diff --git a/packages/apidocs/schema/apidocs-1.schema.json b/packages/apidocs/schema/apidocs-1.schema.json new file mode 100644 index 0000000..66847a4 --- /dev/null +++ b/packages/apidocs/schema/apidocs-1.schema.json @@ -0,0 +1,482 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://elide.dev/schemas/apidocs-1.schema.json", + "title": "Model", + "description": "The apidocs/1 model of one module's public API, as the Javadoc doclet and the Dokka plugin write it. A null value, false and an empty list are left out, so each is the default when a property is absent. Lists keep the extractor's order.", + "$ref": "#/$defs/Model", + "$defs": { + "Model": { + "description": "One module's model.", + "type": "object", + "additionalProperties": false, + "required": ["schema", "module"], + "properties": { + "schema": { "const": "apidocs/1", "description": "The schema name." }, + "module": { "$ref": "#/$defs/Module" }, + "externals": { "type": "array", "items": { "$ref": "#/$defs/External" }, "description": "Where references outside this model point, by name prefix; the first match wins." }, + "packages": { "type": "array", "items": { "$ref": "#/$defs/Package" }, "description": "The documented packages, sorted by name." } + } + }, + "Module": { + "description": "The documented module.", + "type": "object", + "additionalProperties": false, + "required": ["name"], + "properties": { + "name": { "type": "string", "description": "The module's name, as pages show it." }, + "version": { "type": "string", "description": "The module's version." }, + "javaModule": { "type": "string", "description": "The named JPMS module the packages belong to; absent for the unnamed module." }, + "languages": { "type": "array", "items": { "type": "string" }, "description": "The source languages, sorted: java, kotlin." }, + "doc": { "$ref": "#/$defs/Doc" }, + "guides": { "type": "array", "items": { "$ref": "#/$defs/Guide" }, "description": "Narrative guides beside the API reference, in the author's order. Pages list ungrouped guides first, then each group in the order of its first guide; inside each, guides with an order come first, lowest first, and the rest keep this list's order." }, + "overview": { "type": "string", "description": "The id of the guide that is the module's overview page (index.html) instead of a page of its own, such as a documentation suite's introduction. A model with guides and no packages is a guides-only site." } + } + }, + "Guide": { + "description": "A narrative page, such as Getting started or Migrating from 1.x. Its page is guides/<slug>.html. Headings in its body are its sections: each gets an anchor, its own or one derived from its text, and links can target it.", + "type": "object", + "additionalProperties": false, + "required": ["id", "slug", "title"], + "properties": { + "id": { "type": "string", "description": "The stable id links use as a Ref's id. Distinct from every declaration id; the extractors write guide: and the slug." }, + "slug": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]*(/[a-z0-9][a-z0-9-]*)*$", "description": "The page path below guides/, without an extension: lowercase letters, digits and hyphens, with / between segments for nesting." }, + "title": { "type": "string", "description": "The title, as the page and listings show it." }, + "navTitle": { "type": "string", "description": "A shorter label for the navigator, when the title is too long for it; absent to show the title." }, + "summary": { "$ref": "#/$defs/Inlines", "description": "One sentence for listings, search and llms.txt." }, + "group": { "type": "string", "description": "The group the guide is listed under, such as Advanced; absent for an ungrouped guide." }, + "order": { "type": "integer", "description": "The guide's place in its group: lower first. Guides without one follow those with one." }, + "body": { "$ref": "#/$defs/Blocks", "description": "The guide's text. A heading of level 2 starts a section, level 3 a subsection; level 1 counts as 2." }, + "source": { "$ref": "#/$defs/Source", "description": "Where the guide's text comes from, for a source link." } + } + }, + "External": { + "description": "Documentation outside this model: a reference whose id starts with prefix links below url.", + "type": "object", + "additionalProperties": false, + "required": ["prefix", "url"], + "properties": { + "prefix": { "type": "string", "description": "A package or name prefix, such as java." }, + "url": { "type": "string", "description": "The base URL (absolute) or path (relative to the model's root); {module} stands for a target's module." } + } + }, + "Package": { + "description": "A package (Java) or a package's top-level declarations (Kotlin).", + "type": "object", + "additionalProperties": false, + "required": ["id", "name"], + "properties": { + "id": { "type": "string", "description": "The package's id: its qualified name." }, + "name": { "type": "string", "description": "The qualified name; empty for the unnamed package." }, + "doc": { "$ref": "#/$defs/Doc" }, + "since": { "type": "string" }, + "deprecated": { "$ref": "#/$defs/Deprecation" }, + "nullMarked": { "type": "boolean", "description": "Whether the package is JSpecify @NullMarked." }, + "types": { "type": "array", "items": { "$ref": "#/$defs/Type" }, "description": "The package's types, nested types included, sorted by name." }, + "functions": { "type": "array", "items": { "$ref": "#/$defs/Member" }, "description": "Top-level functions (Kotlin)." }, + "properties": { "type": "array", "items": { "$ref": "#/$defs/Member" }, "description": "Top-level properties (Kotlin)." }, + "typeAliases": { "type": "array", "items": { "$ref": "#/$defs/TypeAlias" }, "description": "Type aliases (Kotlin)." } + } + }, + "TypeKind": { + "description": "What a type declaration is.", + "enum": ["class", "interface", "record", "enum", "annotation", "object"] + }, + "Type": { + "description": "A type declaration. Its page is <package path>/<name>.html.", + "type": "object", + "additionalProperties": false, + "required": ["id", "name", "kind", "language", "signature"], + "properties": { + "id": { "type": "string", "description": "The stable id: the binary name (p.Outer$Inner) for Java, Dokka's DRI for Kotlin." }, + "name": { "type": "string", "description": "The name inside its package, nesting joined with dots (Outer.Inner)." }, + "kind": { "$ref": "#/$defs/TypeKind" }, + "language": { "type": "string", "description": "java or kotlin." }, + "modifiers": { "type": "array", "items": { "type": "string" }, "description": "Modifiers in canonical order, without implied ones." }, + "annotations": { "type": "array", "items": { "$ref": "#/$defs/Tokens" }, "description": "Documented annotations, each as tokens." }, + "typeParams": { "type": "array", "items": { "$ref": "#/$defs/TypeParam" } }, + "signature": { "$ref": "#/$defs/Tokens", "description": "The declaration line as tokens." }, + "superclass": { "$ref": "#/$defs/Tokens", "description": "The direct superclass as tokens; absent for interfaces." }, + "interfaces": { "type": "array", "items": { "$ref": "#/$defs/Tokens" }, "description": "Implemented or extended interfaces." }, + "ancestors": { "type": "array", "items": { "$ref": "#/$defs/Ref" }, "description": "The superclass chain, nearest first." }, + "permits": { "type": "array", "items": { "$ref": "#/$defs/Ref" }, "description": "Permitted subtypes of a sealed type." }, + "enclosing": { "type": "string", "description": "The enclosing type's id." }, + "components": { "type": "array", "items": { "$ref": "#/$defs/Param" }, "description": "Record components with their @param documentation." }, + "members": { "type": "array", "items": { "$ref": "#/$defs/Member" }, "description": "Declared members, in declaration order." }, + "inherited": { "type": "array", "items": { "$ref": "#/$defs/Inherited" }, "description": "Members inherited from supertypes, grouped by declaring type." }, + "doc": { "$ref": "#/$defs/Doc" }, + "deprecated": { "$ref": "#/$defs/Deprecation" }, + "since": { "type": "string" }, + "nullMarked": { "type": "boolean", "description": "Whether the declaration is in a JSpecify @NullMarked scope." }, + "source": { "$ref": "#/$defs/Source" } + } + }, + "MemberKind": { + "description": "What a member is.", + "enum": ["constructor", "method", "field", "enumConstant", "annotationElement", "function", "property"] + }, + "Member": { + "description": "A member of a type, or a Kotlin top-level function or property.", + "type": "object", + "additionalProperties": false, + "required": ["id", "anchor", "kind", "name", "signature"], + "properties": { + "id": { "type": "string", "description": "<type id>#<anchor> for Java, Dokka's DRI for Kotlin." }, + "anchor": { "type": "string", "description": "The fragment on its page; for Java the JDK doclet's, such as read(java.io.InputStream)." }, + "kind": { "$ref": "#/$defs/MemberKind" }, + "name": { "type": "string", "description": "The simple name; a constructor is named after its type." }, + "modifiers": { "type": "array", "items": { "type": "string" } }, + "annotations": { "type": "array", "items": { "$ref": "#/$defs/Tokens" } }, + "typeParams": { "type": "array", "items": { "$ref": "#/$defs/TypeParam" } }, + "receiver": { "$ref": "#/$defs/Param", "description": "The receiver of a Kotlin extension function or property." }, + "signature": { "$ref": "#/$defs/Tokens", "description": "The declaration as tokens, on one line." }, + "params": { "type": "array", "items": { "$ref": "#/$defs/Param" } }, + "returns": { "$ref": "#/$defs/Returns" }, + "type": { "$ref": "#/$defs/Tokens", "description": "The type of a field, property or enum constant." }, + "nullness": { "$ref": "#/$defs/Nullness" }, + "throws": { "type": "array", "items": { "$ref": "#/$defs/Thrown" }, "description": "Declared and documented exceptions, merged." }, + "constant": { "type": "string", "description": "A compile-time constant's value as a source literal." }, + "defaultValue": { "type": "string", "description": "An annotation element's default as source text." }, + "overrides": { "$ref": "#/$defs/Ref", "description": "The member this one overrides or implements." }, + "implicit": { "type": "boolean", "description": "Whether the compiler declares it (a record's accessors, an enum's values())." }, + "doc": { "$ref": "#/$defs/Doc" }, + "deprecated": { "$ref": "#/$defs/Deprecation" }, + "since": { "type": "string" }, + "source": { "$ref": "#/$defs/Source" } + } + }, + "TypeAlias": { + "description": "A Kotlin type alias.", + "type": "object", + "additionalProperties": false, + "required": ["id", "name", "signature", "target"], + "properties": { + "id": { "type": "string" }, + "name": { "type": "string" }, + "typeParams": { "type": "array", "items": { "$ref": "#/$defs/TypeParam" } }, + "signature": { "$ref": "#/$defs/Tokens" }, + "target": { "$ref": "#/$defs/Tokens" }, + "doc": { "$ref": "#/$defs/Doc" }, + "deprecated": { "$ref": "#/$defs/Deprecation" }, + "since": { "type": "string" }, + "source": { "$ref": "#/$defs/Source" } + } + }, + "Nullness": { + "description": "Whether a reference type admits null; absent when unknown or not applicable.", + "enum": ["nullable", "nonNull"] + }, + "Param": { + "description": "A value parameter or record component.", + "type": "object", + "additionalProperties": false, + "required": ["name", "type"], + "properties": { + "name": { "type": "string" }, + "type": { "$ref": "#/$defs/Tokens" }, + "varargs": { "type": "boolean" }, + "defaultValue": { "type": "string", "description": "A Kotlin default argument as source text." }, + "nullness": { "$ref": "#/$defs/Nullness" }, + "annotations": { "type": "array", "items": { "$ref": "#/$defs/Tokens" } }, + "doc": { "$ref": "#/$defs/Blocks" } + } + }, + "TypeParam": { + "description": "A type parameter.", + "type": "object", + "additionalProperties": false, + "required": ["name"], + "properties": { + "name": { "type": "string" }, + "bounds": { "type": "array", "items": { "$ref": "#/$defs/Tokens" } }, + "doc": { "$ref": "#/$defs/Blocks" } + } + }, + "Returns": { + "description": "A return value.", + "type": "object", + "additionalProperties": false, + "required": ["type"], + "properties": { + "type": { "$ref": "#/$defs/Tokens" }, + "nullness": { "$ref": "#/$defs/Nullness" }, + "doc": { "$ref": "#/$defs/Blocks" } + } + }, + "Thrown": { + "description": "An exception a member throws.", + "type": "object", + "additionalProperties": false, + "required": ["type"], + "properties": { + "type": { "$ref": "#/$defs/Tokens" }, + "declared": { "type": "boolean", "description": "Whether the throws clause names it." }, + "doc": { "$ref": "#/$defs/Blocks" } + } + }, + "Deprecation": { + "description": "A deprecation.", + "type": "object", + "additionalProperties": false, + "properties": { + "doc": { "$ref": "#/$defs/Blocks" }, + "since": { "type": "string" }, + "forRemoval": { "type": "boolean" } + } + }, + "Inherited": { + "description": "Members a type inherits from one supertype.", + "type": "object", + "additionalProperties": false, + "required": ["from", "kind"], + "properties": { + "from": { "$ref": "#/$defs/Ref" }, + "kind": { "type": "string", "description": "class or interface." }, + "members": { "type": "array", "items": { "$ref": "#/$defs/Ref" } } + } + }, + "Source": { + "description": "A declaration's place in its source.", + "type": "object", + "additionalProperties": false, + "required": ["path", "line"], + "properties": { + "path": { "type": "string", "description": "The file's path below its source root." }, + "line": { "type": "integer", "minimum": 1 } + } + }, + "Ref": { + "description": "A reference to a declaration. It links locally when the model has the id, else through url, else not at all.", + "type": "object", + "additionalProperties": false, + "required": ["id"], + "properties": { + "id": { "type": "string" }, + "text": { "type": "string", "description": "The text to show, when not the target's own name." }, + "url": { "type": "string", "description": "The target's URL, when outside this model and an external covers it." }, + "section": { "type": "string", "description": "An anchor on the target's page to link to instead of the target itself: a guide section's anchor." } + } + }, + "TokenKind": { + "description": "What a signature token is.", + "enum": ["keyword", "name", "type", "typeParam", "annotation", "literal", "punct", "param"] + }, + "Token": { + "description": "One token of a signature.", + "type": "object", + "additionalProperties": false, + "required": ["kind", "text"], + "properties": { + "kind": { "$ref": "#/$defs/TokenKind" }, + "text": { "type": "string" }, + "ref": { "type": "string", "description": "The target's model id, for a type or annotation." }, + "url": { "type": "string", "description": "The target's URL when outside the model." } + } + }, + "Tokens": { "type": "array", "items": { "$ref": "#/$defs/Token" } }, + "Doc": { + "description": "Documentation as a tree. Parameter, return and exception documentation live on those parts.", + "type": "object", + "additionalProperties": false, + "properties": { + "summary": { "$ref": "#/$defs/Inlines", "description": "The first sentence." }, + "body": { "$ref": "#/$defs/Blocks", "description": "The full description, first sentence included." }, + "notes": { "type": "array", "items": { "$ref": "#/$defs/Note" } }, + "see": { "type": "array", "items": { "$ref": "#/$defs/Inlines" } }, + "inheritedFrom": { "$ref": "#/$defs/Ref", "description": "The member whose documentation this is, when inherited." } + } + }, + "NoteKind": { "enum": ["apiNote", "implSpec", "implNote"] }, + "Note": { + "description": "An @apiNote, @implSpec or @implNote section.", + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { + "kind": { "$ref": "#/$defs/NoteKind" }, + "body": { "$ref": "#/$defs/Blocks" } + } + }, + "Blocks": { "type": "array", "items": { "$ref": "#/$defs/Block" } }, + "Inlines": { "type": "array", "items": { "$ref": "#/$defs/Inline" } }, + "Block": { + "oneOf": [ + { "$ref": "#/$defs/Paragraph" }, + { "$ref": "#/$defs/ListBlock" }, + { "$ref": "#/$defs/CodeBlock" }, + { "$ref": "#/$defs/Table" }, + { "$ref": "#/$defs/Heading" }, + { "$ref": "#/$defs/Quote" }, + { "$ref": "#/$defs/Admonition" }, + { "$ref": "#/$defs/RawBlock" } + ] + }, + "Paragraph": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { "kind": { "const": "paragraph" }, "children": { "$ref": "#/$defs/Inlines" } } + }, + "ListBlock": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { + "kind": { "const": "list" }, + "ordered": { "type": "boolean" }, + "items": { "type": "array", "items": { "$ref": "#/$defs/Blocks" } } + } + }, + "CodeBlock": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "text"], + "properties": { + "kind": { "const": "code" }, + "language": { "type": "string", "description": "Absent for the declaration's own language." }, + "text": { "type": "string" } + } + }, + "Table": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { + "kind": { "const": "table" }, + "caption": { "$ref": "#/$defs/Inlines" }, + "head": { "type": "array", "items": { "$ref": "#/$defs/Row" } }, + "rows": { "type": "array", "items": { "$ref": "#/$defs/Row" } } + } + }, + "Row": { "type": "array", "items": { "$ref": "#/$defs/Blocks" } }, + "Heading": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "level"], + "properties": { + "kind": { "const": "heading" }, + "level": { "type": "integer", "minimum": 1 }, + "children": { "$ref": "#/$defs/Inlines" }, + "anchor": { "type": "string", "description": "The heading's anchor in a guide, when the author set one; otherwise the renderer derives it from the text." } + } + }, + "Quote": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { "kind": { "const": "quote" }, "children": { "$ref": "#/$defs/Blocks" } } + }, + "AdmonitionTone": { + "description": "What an admonition is: the five general tones, or one of the API note kinds.", + "enum": ["note", "tip", "important", "warning", "caution", "apiNote", "implSpec", "implNote"] + }, + "Admonition": { + "description": "A callout set apart from the text: a note, tip, warning and so on.", + "type": "object", + "additionalProperties": false, + "required": ["kind", "tone"], + "properties": { + "kind": { "const": "admonition" }, + "tone": { "$ref": "#/$defs/AdmonitionTone" }, + "title": { "$ref": "#/$defs/Inlines", "description": "A title; absent for the tone's own label." }, + "children": { "$ref": "#/$defs/Blocks" } + } + }, + "RawBlock": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "html", "text"], + "properties": { "kind": { "const": "raw" }, "html": { "type": "string" }, "text": { "type": "string" } } + }, + "Inline": { + "oneOf": [ + { "$ref": "#/$defs/Text" }, + { "$ref": "#/$defs/Code" }, + { "$ref": "#/$defs/Emphasis" }, + { "$ref": "#/$defs/Strong" }, + { "$ref": "#/$defs/Link" }, + { "$ref": "#/$defs/Break" }, + { "$ref": "#/$defs/RawInline" }, + { "$ref": "#/$defs/Strikethrough" }, + { "$ref": "#/$defs/Image" }, + { "$ref": "#/$defs/TaskCheck" } + ] + }, + "Text": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "text"], + "properties": { "kind": { "const": "text" }, "text": { "type": "string" } } + }, + "Code": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "text"], + "properties": { "kind": { "const": "code" }, "text": { "type": "string" } } + }, + "Emphasis": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { "kind": { "const": "emphasis" }, "children": { "$ref": "#/$defs/Inlines" } } + }, + "Strong": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { "kind": { "const": "strong" }, "children": { "$ref": "#/$defs/Inlines" } } + }, + "Link": { + "description": "A link to a declaration (target) or a URL. An unresolved declaration link renders as its label.", + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { + "kind": { "const": "link" }, + "target": { "$ref": "#/$defs/Ref" }, + "url": { "type": "string" }, + "code": { "type": "boolean", "description": "Whether the label is code ({@link}) rather than prose ({@linkplain})." }, + "children": { "$ref": "#/$defs/Inlines" } + } + }, + "Break": { + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { "kind": { "const": "break" } } + }, + "RawInline": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "html", "text"], + "properties": { "kind": { "const": "raw" }, "html": { "type": "string" }, "text": { "type": "string" } } + }, + "Strikethrough": { + "description": "Text struck through, as Markdown's ~~text~~.", + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { "kind": { "const": "strikethrough" }, "children": { "$ref": "#/$defs/Inlines" } } + }, + "Image": { + "description": "An image, such as a diagram or a screenshot in a guide. A relative src is a path from the site's root; the tool that writes the model also copies the file there.", + "type": "object", + "additionalProperties": false, + "required": ["kind", "src", "alt"], + "properties": { + "kind": { "const": "image" }, + "src": { "type": "string", "description": "An absolute URL, or a path relative to the site's root." }, + "alt": { "type": "string", "description": "The text that replaces the image for a reader who cannot see it." }, + "title": { "type": "string", "description": "A tooltip, when the author gave one." }, + "width": { "type": "integer", "minimum": 1, "description": "The intrinsic width in pixels, when known, so the page reserves the image's box before it loads." }, + "height": { "type": "integer", "minimum": 1, "description": "The intrinsic height in pixels, when known." } + } + }, + "TaskCheck": { + "description": "The check box that starts a task-list item: done or not.", + "type": "object", + "additionalProperties": false, + "required": ["kind"], + "properties": { "kind": { "const": "check" }, "checked": { "type": "boolean", "description": "Whether the task is done." } } + } + } +} diff --git a/packages/apidocs/scripts/assets.ts b/packages/apidocs/scripts/assets.ts new file mode 100644 index 0000000..ced65ea --- /dev/null +++ b/packages/apidocs/scripts/assets.ts @@ -0,0 +1,20 @@ +/** + * Completes dist/: the stylesheet, the fonts the Elide preset names, the + * runner, and the JSON Schema, beside the two bundles Vite wrote. + */ +import { copyFileSync, mkdirSync } from "node:fs"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; +import { elide } from "../src/presets/elide"; + +const require = createRequire(import.meta.url); +const pkg = (path: string) => fileURLToPath(new URL(`../${path}`, import.meta.url)); +mkdirSync(pkg("dist/assets/fonts"), { recursive: true }); +copyFileSync(pkg("src/styles/apidocs.css"), pkg("dist/assets/apidocs.css")); +copyFileSync(pkg("src/runner.mjs"), pkg("dist/runner.mjs")); +copyFileSync(pkg("schema/apidocs-1.schema.json"), pkg("dist/apidocs-1.schema.json")); +for (const font of elide.fonts ?? []) { + const file = font.asset.slice("fonts/".length); + const family = file.replace(/-latin-.*$/, ""); + copyFileSync(require.resolve(`@fontsource-variable/${family}/files/${file}`), pkg(`dist/assets/${font.asset}`)); +} diff --git a/packages/apidocs/scripts/audit.ts b/packages/apidocs/scripts/audit.ts new file mode 100644 index 0000000..3ec9a39 --- /dev/null +++ b/packages/apidocs/scripts/audit.ts @@ -0,0 +1,209 @@ +/** + * Audits the static output: Lighthouse (performance, accessibility, best + * practices, SEO, and the experimental agentic-browsing category, on mobile + * and desktop), agent readiness (the checks Is Agentic scores, run locally), + * and the good-css.com rules. AUDITS.md says where each rule comes from. + * + * bun run audit [--only lighthouse,agentic,css] [--sample java,kotlin] [--preset neutral,elide] + * [--model api.json] [--page path.html] [--theme theme.json] + * [--lighthouse-sites first|all] [--form-factor mobile,desktop] + * [--threshold N] [--threshold-lighthouse N] [--threshold-agentic N] [--threshold-css N] + * [--host static|agent] [--no-base-url] [--no-build] [--out dir] [--json] + * [--url http://host/base/] + * + * Each site is built with dist/runner.mjs exactly as the doclet builds it, and + * served on its own free localhost port for the run, with compression and + * cache headers. Full reports go to a fresh temporary directory (or --out), + * whose path is printed. Exits 1 when any score is below its threshold. + * + * --url audits a site that is already served, such as the Astro sample app (`bun run apidocs:astro:preview`), + * instead of building one: Lighthouse and agent readiness, read through the site's llms.txt (audit/remote.ts). + */ +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { samples } from "../samples"; +import { agenticAudit } from "./audit/agentic"; +import { mirrorSite } from "./audit/remote"; +import { buildDist, renderSite, representativePages } from "./audit/build"; +import { cssAudit, type Stylesheet } from "./audit/css"; +import { type FormFactor, type LighthouseRun, reportPath, startLighthouse } from "./audit/lighthouse"; +import { type AuditServer, type HostProfile, serve } from "./audit/server"; +import type { AuditResult, Site } from "./audit/types"; + +const args = process.argv.slice(2); +if (args.includes("--help") || args.includes("-h")) { + console.log(readFileSync(new URL(import.meta.url), "utf8").split("*/")[0]!.replace(/^\/\*\*?|^ \* ?/gm, "")); + process.exit(0); +} +const flag = (name: string) => { + const at = args.indexOf(`--${name}`); + return at < 0 ? undefined : args[at + 1]; +}; +const list = (name: string, fallback: string[]) => flag(name)?.split(",").map(s => s.trim()).filter(Boolean) ?? fallback; +const cwd = process.env.INIT_CWD ?? process.cwd(); +const AUDITS = ["lighthouse", "agentic", "css"] as const; +const remote = flag("url") ? (flag("url")!.endsWith("/") ? flag("url")! : `${flag("url")}/`) : undefined; +// A served site has no stylesheet files to read; the CSS audit runs on the static build. +const only = new Set(list("only", remote ? ["lighthouse", "agentic"] : [...AUDITS])); +for (const a of only) if (!AUDITS.includes(a as (typeof AUDITS)[number])) throw new Error(`--only takes ${AUDITS.join(", ")}; got ${a}`); +const presets = list("preset", ["neutral", "elide"]); +const sampleNames = list("sample", ["java", "kotlin"]); +const modelPath = flag("model") ? resolve(cwd, flag("model")!) : undefined; +const formFactors = list("form-factor", ["mobile", "desktop"]) as FormFactor[]; +const host = (flag("host") ?? "static") as HostProfile; +const base = Number(flag("threshold") ?? 100); +const threshold = { lighthouse: Number(flag("threshold-lighthouse") ?? base), agentic: Number(flag("threshold-agentic") ?? base), css: Number(flag("threshold-css") ?? base) }; +const extraTheme = flag("theme") ? JSON.parse(readFileSync(resolve(cwd, flag("theme")!), "utf8")) : {}; +const reportDir = flag("out") ? resolve(cwd, flag("out")!) : mkdtempSync(join(tmpdir(), "apidocs-audit-")); +mkdirSync(join(reportDir, "lighthouse"), { recursive: true }); +const started = Date.now(); + +if (!args.includes("--no-build") && !remote) { + console.log(" building dist/ ..."); + buildDist(); +} + +// Build each site under its own server, so each sits at a host root (llms.txt, robots.txt and sitemap.xml are root files). +const servers: AuditServer[] = []; +const sites: Site[] = []; +if (remote) { + sites.push(await mirrorSite("served", remote, join(reportDir, "sites", "served"))); + console.log(` served: ${sites[0]!.pages.all.length} pages from ${remote}`); +} +const inputs = remote + ? [] + : modelPath + ? presets.map(preset => ({ name: `model-${preset}`, preset, model: { path: modelPath } })) + : sampleNames.flatMap(sample => { + if (!samples[sample as keyof typeof samples]) throw new Error(`No sample named ${sample}; use ${Object.keys(samples).join(" or ")}`); + return presets.map(preset => ({ name: `${sample}-${preset}`, preset, model: { json: JSON.stringify(samples[sample as keyof typeof samples]) } })); + }); +for (const input of inputs) { + const dir = join(reportDir, "sites", input.name); + const server = serve(dir, host); + servers.push(server); + const theme = { ...extraTheme, extends: extraTheme.extends ?? input.preset, ...(args.includes("--no-base-url") ? {} : { baseUrl: server.url }) }; + const stats = renderSite({ model: input.model, theme, out: dir, work: join(reportDir, "work", input.name) }); + const prefer = flag("page") ?? (modelPath ? "dev/elide/kotlin/api/Ir.html" : undefined); + sites.push({ name: input.name, dir, url: server.url, pages: representativePages(dir, prefer) }); + console.log(` ${input.name}: ${stats.files} files, ${(stats.bytes / 1e6).toFixed(1)} MB, at ${server.url}`); +} + +const results: AuditResult[] = []; +let exitCode = 0; +try { + for (const site of sites) { + if (only.has("css")) { + const sheets: Stylesheet[] = [ + { path: "assets/apidocs.css", css: readFileSync(join(site.dir, "assets/apidocs.css"), "utf8"), source: "src/styles/apidocs.css" }, + { path: "assets/theme.css", css: readFileSync(join(site.dir, "assets/theme.css"), "utf8"), source: "src/theme.ts (themeCss) and src/presets/*" }, + ]; + const css = cssAudit(sheets); + const report = `css--${site.name}.json`; + writeFileSync(join(reportDir, report), JSON.stringify(css, null, 2)); + results.push({ audit: "css", target: `${site.name} stylesheets`, score: css.score, threshold: threshold.css, failures: css.rules.filter(r => r.status !== "pass").map(r => `${r.rule} (${r.evidence.split(" ")[0]})`), findings: [...css.rules, ...css.checklist], report }); + } + if (only.has("agentic")) { + const agentic = await agenticAudit(site); + const report = `agentic--${site.name}.json`; + writeFileSync(join(reportDir, report), JSON.stringify(agentic, null, 2)); + const scored = agentic.findings.filter(f => f.status === "fail" || f.status === "partial"); + results.push({ audit: "agentic", target: `${site.name} (${agentic.pages.length} pages, host ${host})`, score: agentic.score, threshold: threshold.agentic, failures: scored.map(f => `${f.rule}${f.evidence.startsWith("[") ? "*" : ""} ${fmt(f.score)}/${f.max}`), findings: agentic.findings, report }); + } + } + + if (only.has("lighthouse")) { + const which = flag("lighthouse-sites") ?? "first"; + const lhSites = which === "all" ? sites : [sites.find(s => s.name.endsWith("-elide")) ?? sites[0]!]; + const at = (site: Site, page: string) => (site.urlOf ? site.urlOf(page) : site.url + page); + console.log(` lighthouse: ${lhSites.length} site(s) x 4 pages x ${formFactors.length} form factors ...`); + const lh = await startLighthouse(); + try { + for (const site of lhSites) { + const { overview, package: pkg, smallType, largestType } = site.pages; + for (const page of [...new Set([overview, pkg, smallType, largestType])]) { + for (const formFactor of formFactors) { + const base = reportPath(reportDir, site.name, page, formFactor); + const t = Date.now(); + let run: LighthouseRun; + try { + run = await lh.run(at(site, page), formFactor, base); + } catch (e) { + results.push({ audit: "lighthouse", target: `${site.name} ${page} ${formFactor}`, score: 0, threshold: threshold.lighthouse, failures: [`did not run: ${(e as Error).message.slice(0, 120)}`], findings: [] }); + continue; + } + const cats = ["performance", "accessibility", "best-practices", "seo", "agentic-browsing"]; + const scores = cats.map(c => run.categories[c]); + const gated = scores.slice(0, 4).filter((s): s is number => s !== null && s !== undefined); + writeFileSync(`${base}.summary.json`, JSON.stringify(run, null, 2)); + results.push({ + audit: "lighthouse", target: `${site.name} ${page} ${formFactor}`, + score: Math.min(...gated), threshold: threshold.lighthouse, + failures: [`P${scores[0]} A${scores[1]} BP${scores[2]} S${scores[3]} AG${scores[4] ?? "-"}`, ...run.failing.map(f => `${f.rule} ${f.score}`)], + findings: [...run.failing, ...run.advisories], + report: `${base.slice(reportDir.length + 1)}.html`, + }); + console.log(` ${site.name} ${page} ${formFactor}: P${scores[0]} A${scores[1]} BP${scores[2]} S${scores[3]} AG${scores[4] ?? "-"} (${((Date.now() - t) / 1000).toFixed(1)} s)`); + } + } + } + } finally { + await lh.close(); + } + } +} finally { + for (const server of servers) server.stop(); +} + +// Report. +for (const r of results) if (r.score === undefined || r.score < r.threshold) exitCode = 1; +writeFileSync(join(reportDir, "summary.json"), JSON.stringify({ started: new Date(started).toISOString(), seconds: (Date.now() - started) / 1000, host, threshold, results }, null, 2)); +writeFileSync(join(reportDir, "summary.md"), markdown(results)); +if (args.includes("--json")) console.log(JSON.stringify(results.map(({ findings, ...r }) => r), null, 2)); +else printTable(results); +console.log(`\n reports: ${reportDir} (summary.md, summary.json, lighthouse/*.html)`); +console.log(` ${((Date.now() - started) / 1000).toFixed(0)} s; ${exitCode ? "below threshold" : "all scores at or above threshold"}\n`); +process.exit(exitCode); + +function printTable(rows: AuditResult[]): void { + const cells = rows.map(r => [r.audit, r.target, r.score === undefined ? "-" : `${r.score}`, `${r.score !== undefined && r.score >= r.threshold ? "ok" : "LOW"} (${r.threshold})`, r.failures.join(", ")]); + const head = ["audit", "target", "score", "threshold", "failures"]; + const width = (i: number) => Math.min(i === 1 ? 60 : 20, Math.max(head[i]!.length, ...cells.map(c => c[i]!.length))); + const line = (c: string[]) => " " + c.map((v, i) => (i === 4 ? v : v.slice(0, width(i)).padEnd(width(i)))).join(" "); + console.log("\n" + line(head)); + for (const c of cells) console.log(line([...c.slice(0, 4), wrap(c[4]!, 100, 2 + [0, 1, 2, 3].reduce((a, i) => a + width(i) + 2, 0))])); +} + +function wrap(text: string, width: number, indent: number): string { + const out: string[] = []; + let current = ""; + for (const word of text.split(", ")) { + if (current && current.length + word.length + 2 > width) { + out.push(current + ","); + current = word; + } else current = current ? `${current}, ${word}` : word; + } + out.push(current); + return out.join("\n" + " ".repeat(indent)); +} + +function markdown(rows: AuditResult[]): string { + const lines = ["# apidocs audit", "", `Host profile: ${host}. Thresholds: ${JSON.stringify(threshold)}.`, "", "| Audit | Target | Score | Threshold | Failures |", "| --- | --- | ---: | ---: | --- |"]; + for (const r of rows) lines.push(`| ${r.audit} | ${r.target} | ${r.score ?? "-"} | ${r.threshold} | ${r.failures.join(", ").replace(/\|/g, "\\|")} |`); + for (const r of rows) { + const shown = r.findings.filter(f => f.status !== "pass" && f.status !== "na"); + if (!shown.length) continue; + lines.push("", `## ${r.audit}: ${r.target}${r.report ? ` ([report](${r.report}))` : ""}`, ""); + for (const f of shown) { + lines.push(`- **${f.rule}** (${f.status}, ${f.owner}${f.score !== undefined ? `, ${fmt(f.score)}/${f.max}` : ""}): ${f.evidence}${f.file ? ` File: \`${f.file}\`.` : ""}${f.fix ? ` Fix: ${f.fix}` : ""}`); + for (const w of f.where ?? []) lines.push(` - ${w.replace(/\n/g, " ")}`); + } + } + return lines.join("\n") + "\n"; +} + +function fmt(n: number | undefined): string { + return n === undefined ? "-" : Number.isInteger(n) ? `${n}` : n.toFixed(2); +} + diff --git a/packages/apidocs/scripts/audit/agentic.ts b/packages/apidocs/scripts/audit/agentic.ts new file mode 100644 index 0000000..465b9df --- /dev/null +++ b/packages/apidocs/scripts/audit/agentic.ts @@ -0,0 +1,518 @@ +/** + * Agent readiness, measured locally with the checks Is Agentic + * (https://is-agentic.com) scores. Is Agentic's scans are run by Ora, whose + * scoring rules are public (https://ora.ai/api/ranker/releases/2/rules, + * version 2, revision 17). Is Agentic only scans public URLs, so this file + * re-implements, against the built files and the local audit server, every + * check that applies to a documentation site (Ora's "content" site type): + * the 15 checks it requires, the gated checks that follow from them, and the + * bonus and emerging checks a static reference can earn. Checks about the + * owner's business (pricing, OAuth, MCP servers, payments, search ranking, + * Wikipedia) are out of scope for the generator and listed in AUDITS.md. + * + * The score follows Ora's published formula (weighted-active-layer-ratios: + * accessibility 30, discovery 20, usability 40, payments 10 and empty here; + * emerging checks unscored; bonus checks count only what they earn). It is a + * local approximation of the hosted score, not the hosted score: Ora's + * partial-credit thresholds are not all published, and the values used here + * are written next to each check. + */ +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { readPage, type PageFacts } from "./html"; +import type { Finding, Owner, Site, Status } from "./types"; + +type State = "req" | "gated" | "bonus" | "emerging" | "na"; +type Layer = "accessibility" | "discovery" | "usability"; + +interface Rule { + id: string; + name: string; + layer?: Layer; + max: number; + state: State; + owner: Owner; + file?: string; +} + +/** Layer weights from Ora's rules, version 2. Payments has no checks here, and its weight is redistributed. */ +const LAYER_WEIGHTS: Record<Layer, number> = { accessibility: 30, discovery: 20, usability: 40 }; +const SOURCE = "https://is-agentic.com/methodology; rules: https://ora.ai/api/ranker/releases/2/rules"; + +const RULES: Rule[] = [ + { id: "content-no-js", name: "Content without JavaScript", layer: "accessibility", max: 3, state: "req", owner: "page", file: "src/components/chrome.tsx" }, + { id: "metadata-completeness", name: "Metadata completeness", layer: "accessibility", max: 2, state: "req", owner: "page", file: "src/components/chrome.tsx" }, + { id: "json-ld", name: "JSON-LD structured data", layer: "accessibility", max: 4, state: "req", owner: "output", file: "src/pages.tsx" }, + { id: "schema-type-breadth", name: "Schema type breadth", layer: "accessibility", max: 2, state: "gated", owner: "output", file: "src/pages.tsx" }, + { id: "llms-txt-exists", name: "llms.txt exists", layer: "accessibility", max: 1, state: "req", owner: "output", file: "src/render.tsx" }, + { id: "llms-txt-formatting", name: "llms.txt formatting", layer: "accessibility", max: 2, state: "gated", owner: "output", file: "src/render.tsx" }, + { id: "llms-txt-links-resolve", name: "llms.txt links resolve", layer: "accessibility", max: 2, state: "gated", owner: "output", file: "src/render.tsx" }, + { id: "sitemap", name: "Sitemap exists", layer: "accessibility", max: 2, state: "req", owner: "output", file: "src/render.tsx" }, + { id: "noindex-directives", name: "Homepage not hidden from search", layer: "discovery", max: 1, state: "req", owner: "page", file: "src/components/chrome.tsx" }, + { id: "robots-ai-policy-quality", name: "robots.txt AI crawler policy", layer: "discovery", max: 2, state: "req", owner: "output", file: "src/render.tsx" }, + { id: "robots-agent-user-policy", name: "robots.txt agent-user policy", layer: "accessibility", max: 2, state: "req", owner: "output", file: "src/render.tsx" }, + { id: "agent-crawler-reachability", name: "Agent crawler reachability", layer: "accessibility", max: 2, state: "req", owner: "host" }, + { id: "bot-detection", name: "Not blocked by bot detection", layer: "accessibility", max: 2, state: "req", owner: "host" }, + { id: "docs-auth-gate", name: "Content behind auth", layer: "accessibility", max: 2, state: "req", owner: "host" }, + { id: "redirect-hygiene", name: "Redirect hygiene", layer: "accessibility", max: 1, state: "req", owner: "page", file: "src/components/chrome.tsx" }, + { id: "page-token-budget", name: "Page token budget", layer: "accessibility", max: 1, state: "req", owner: "page", file: "src/pages.tsx" }, + { id: "agent-friendly-404", name: "Agent-friendly 404s", layer: "usability", max: 2, state: "req", owner: "host", file: "src/render.tsx" }, + { id: "trust-anchors", name: "Trust anchor pages", layer: "accessibility", max: 2, state: "na", owner: "host" }, + { id: "sitemap-lastmod", name: "Sitemap freshness (lastmod)", layer: "accessibility", max: 1, state: "bonus", owner: "output", file: "src/render.tsx" }, + { id: "agent-instruction", name: "Agent instruction / when-to-use", layer: "accessibility", max: 3, state: "bonus", owner: "output", file: "src/render.tsx" }, + { id: "link-headers-discovery", name: "HTTP Link headers (RFC 8288)", layer: "accessibility", max: 1, state: "bonus", owner: "host" }, + { id: "markdown-negotiation-vary", name: "Markdown content negotiation", layer: "accessibility", max: 1, state: "bonus", owner: "host" }, + { id: "ax-document-structure", name: "Accessible document structure", layer: "usability", max: 3, state: "bonus", owner: "page", file: "src/components/chrome.tsx" }, + { id: "ax-native-controls", name: "Native interactive controls", layer: "usability", max: 3, state: "bonus", owner: "page", file: "src/components/chrome.tsx" }, + { id: "ax-accessible-names", name: "Accessible names on controls", layer: "usability", max: 2, state: "bonus", owner: "page", file: "src/components/chrome.tsx" }, + { id: "ax-form-labeling", name: "Form control labeling", layer: "usability", max: 2, state: "bonus", owner: "page", file: "src/components/chrome.tsx" }, + { id: "ax-tree-injection-safe", name: "Accessibility-tree injection safety", layer: "usability", max: 2, state: "bonus", owner: "page", file: "src/components/chrome.tsx" }, + { id: "markdown-link-alternate", name: "Markdown alternate link", max: 1, state: "emerging", owner: "page", file: "src/components/chrome.tsx" }, + { id: "markdown-url-fallback", name: "Markdown URL fallback", max: 2, state: "emerging", owner: "output", file: "src/render.tsx" }, + { id: "markdown-frontmatter", name: "Markdown frontmatter metadata", max: 1, state: "emerging", owner: "output", file: "src/markdown.ts" }, + { id: "code-fence-validity", name: "Code fence validity", max: 1, state: "emerging", owner: "output", file: "src/markdown.ts" }, + { id: "markdown-negotiation", name: "Markdown agent docs", max: 1, state: "emerging", owner: "host" }, + { id: "modular-llms-txt", name: "Modular llms.txt per section", max: 1, state: "emerging", owner: "output", file: "src/render.tsx" }, +]; + +export interface AgenticOptions { + /** Read every page when the site has at most this many; otherwise the representative pages and an even sample. */ + pageLimit?: number; +} + +export interface AgenticReport { + score: number; + findings: Finding[]; + pages: string[]; + layers: Record<string, { earned: number; available: number }>; +} + +const AGENTS_SEARCH = ["OAI-SearchBot", "Claude-SearchBot", "PerplexityBot"]; +const AGENTS_USER = ["ChatGPT-User", "Claude-User", "Perplexity-User"]; +const TOKEN_BUDGET_CHARS = 100_000; + +/** Where a page of the site is served. */ +function pageAt(site: Site, page: string): string { + return site.urlOf ? site.urlOf(page) : site.url + page; +} + +export async function agenticAudit(site: Site, options: AgenticOptions = {}): Promise<AgenticReport> { + const limit = options.pageLimit ?? 150; + const pages = samplePages(site, limit); + const facts = new Map<string, PageFacts>(); + for (const page of pages) facts.set(page, readPage(readFileSync(join(site.dir, page), "utf8"))); + const overview = facts.get(site.pages.overview)!; + const file = (path: string) => (existsSync(join(site.dir, path)) ? readFileSync(join(site.dir, path), "utf8") : undefined); + const results = new Map<string, Omit<Finding, "rule" | "name" | "owner"> & { owner?: Owner }>(); + const set = (id: string, r: Omit<Finding, "rule" | "name" | "owner"> & { owner?: Owner }) => results.set(id, r); + const worst = <T>(list: T[], key: (t: T) => number, n = 5) => [...list].sort((a, b) => key(b) - key(a)).slice(0, n); + + // content-no-js. Ora: homepage 500+ characters with an H1, sequential headings, and a text-to-HTML ratio of 5%; + // inner pages need their main text in the raw HTML. + { + const rows = pages.map(p => ({ page: p, f: facts.get(p)! })).map(({ page, f }) => ({ page, chars: f.mainText.length, ratio: f.bodyText.length / f.bytes, h1: f.h1, skip: f.maxHeadingSkip })); + const home = rows.find(r => r.page === site.pages.overview)!; + const homeChecks = [home.chars >= 500, home.h1 === 1, home.ratio >= 0.05, home.skip <= 1]; + const inner = rows.filter(r => r.page !== site.pages.overview); + const innerOk = inner.filter(r => r.chars >= 200 && r.h1 === 1); + const lowRatio = rows.filter(r => r.ratio < 0.05); + const skips = rows.filter(r => r.skip > 1); + const score = 2 * (homeChecks.filter(Boolean).length / 4) + (inner.length ? innerOk.length / inner.length : 1); + set("content-no-js", { + score, max: 3, status: statusOf(score, 3), + evidence: `Overview: ${home.chars} chars of main text, ${home.h1} h1, text/HTML ratio ${(home.ratio * 100).toFixed(1)}% (target 5%), largest heading skip ${home.skip}. ` + + `${innerOk.length}/${inner.length} inner pages have main text and one h1 without JavaScript. Ratio below 5% on ${lowRatio.length}/${rows.length} pages (lowest ${pct(Math.min(...rows.map(r => r.ratio)))}). Heading skips >1 on ${skips.length} pages.`, + where: [...worst(lowRatio, r => -r.ratio).map(r => `${r.page} ratio ${pct(r.ratio)}`), ...skips.slice(0, 3).map(r => `${r.page} heading skip ${r.skip}`)], + fix: lowRatio.length ? "Cut repeated markup per page: the navigator and member rows repeat wrapper elements, classes and inline SVG on every page. Ora measures text over HTML bytes." : undefined, + }); + } + + // metadata-completeness: canonical (own site), html lang, og:image, og:type, on the homepage; also counted over all pages. + { + const signals = (f: PageFacts) => ({ + canonical: f.links.some(l => l.rel.split(/\s+/).includes("canonical") && /^https?:\/\//.test(l.href)), + lang: !!f.lang, + "og:image": !!f.meta.get("og:image"), + "og:type": !!f.meta.get("og:type"), + }); + const home = signals(overview); + const missing = Object.entries(home).filter(([, v]) => !v).map(([k]) => k); + const pagesMissing = Object.keys(home).map(k => [k, pages.filter(p => !signals(facts.get(p)!)[k as keyof typeof home]).length] as const); + const score = 2 * (4 - missing.length) / 4; + set("metadata-completeness", { + score, max: 2, status: statusOf(score, 2), + evidence: missing.length ? `Overview lacks ${missing.join(", ")}. Pages missing each: ${pagesMissing.map(([k, n]) => `${k} ${n}/${pages.length}`).join(", ")}.` : "Canonical URL, lang, og:image and og:type on the overview.", + fix: missing.length ? `Add ${missing.map(m => m === "canonical" ? '<link rel="canonical"> (needs the theme baseUrl)' : m === "lang" ? "<html lang>" : `<meta property="${m}">`).join(", ")} in the page head. og:image needs an image in the output (a theme or preset asset), og:type can be "website" or "article".` : undefined, + }); + } + + // json-ld: identity JSON-LD on the homepage, with name, description, url and a type. Every page's JSON-LD must parse. + { + const blocks = overview.jsonLd.map(b => b.value).filter(Boolean) as Record<string, unknown>[]; + const items = blocks.flatMap(b => (Array.isArray(b["@graph"]) ? (b["@graph"] as Record<string, unknown>[]) : [b])); + const primary = items[0]; + const checks = { + parses: overview.jsonLd.length > 0 && overview.jsonLd.every(b => !b.error), + type: !!primary?.["@type"], + name: !!primary?.name, + description: !!primary?.description, + url: !!primary?.url, + }; + const broken = pages.filter(p => facts.get(p)!.jsonLd.some(b => b.error)); + const noLd = pages.filter(p => facts.get(p)!.jsonLd.length === 0); + const typeOk = /^(SoftwareSourceCode|SoftwareApplication|WebSite|APIReference|TechArticle|Organization|Product|CreativeWork|Article)$/.test(String(primary?.["@type"] ?? "")); + const passed = Object.values(checks).filter(Boolean).length; + const score = broken.length ? Math.min(2, 4 * passed / 5) : 4 * passed / 5; + set("json-ld", { + score, max: 4, status: statusOf(score, 4), + evidence: `Overview: ${overview.jsonLd.length} block(s), @type ${JSON.stringify(primary?.["@type"])}${typeOk ? "" : " (not an identity type Ora recognizes)"}; ` + + Object.entries(checks).map(([k, v]) => `${k} ${v ? "yes" : "no"}`).join(", ") + `. Pages without JSON-LD: ${noLd.length}/${pages.length}; unparseable: ${broken.length}.`, + where: [...broken, ...noLd].slice(0, 5), + fix: !checks.url ? 'Add "url" (the page\'s absolute URL from the theme baseUrl, or its relative path) to each JSON-LD block; on the overview, describe the library as SoftwareSourceCode (name, description, url, programmingLanguage, version, codeRepository).' : undefined, + }); + const list = items.find(i => i["@type"] === "ItemList" || Array.isArray(i.hasPart) || (i.mainEntity as Record<string, unknown> | undefined)?.["@type"] === "ItemList"); + const s2 = list ? 2 : 0; + set("schema-type-breadth", { + score: s2, max: 2, status: statusOf(s2, 2), + evidence: list ? "The overview marks up its list of packages." : "The overview lists packages and types, but its JSON-LD has no ItemList (or hasPart) pointing at them.", + fix: list ? undefined : "On the overview (and package pages), add an ItemList (or hasPart) whose items are the package (type) pages, each with name and url.", + }); + } + + // llms.txt + const llms = await get(`${site.url}llms.txt`); + { + const ok = llms.status === 200 && llms.text.trim().length >= 100 && !/^\s*<(!doctype|html)/i.test(llms.text); + set("llms-txt-exists", { score: ok ? 1 : 0, max: 1, status: ok ? "pass" : "fail", evidence: `GET /llms.txt: ${llms.status}, ${llms.type ?? "no type"}, ${llms.text.length} chars.` }); + const links = [...llms.text.matchAll(/\[[^\]]*\]\(([^)\s]+)\)/g)].map(m => m[1]!); + const heading = /^# \S/.test(llms.text.trimStart()); + const len = llms.text.length; + const fmtScore = !ok ? 0 : (heading ? 0.5 : 0) + (links.length ? 0.5 : 0) + (len <= 30_000 ? 1 : len <= 100_000 ? 0.5 : 0); + set("llms-txt-formatting", { + score: fmtScore, max: 2, status: ok ? statusOf(fmtScore, 2) : "na", + evidence: `Starts with a heading: ${heading ? "yes" : "no"}; ${links.length} Markdown links; ${len.toLocaleString("en")} chars (Ora's target: under 30,000; agents truncate past 100,000).`, + fix: len > 30_000 ? "Keep llms.txt an index under 30,000 characters: link the package pages (and llms-full.txt) instead of listing every type, or list types per package in per-package llms.txt files." : undefined, + }); + const targets = [...new Set(links.map(l => new URL(l, `${site.url}llms.txt`).href))]; + const bad: string[] = []; + await pool(targets, 16, async href => { + const r = await get(href); + if (r.status !== 200 || (href.endsWith(".md") && /^\s*<!doctype/i.test(r.text))) bad.push(`${href.slice(site.url.length)} (${r.status})`); + }); + const lr = !ok ? 0 : targets.length === 0 ? 0 : 2 * (targets.length - bad.length) / targets.length; + set("llms-txt-links-resolve", { + score: lr, max: 2, status: ok ? statusOf(lr, 2) : "na", + evidence: `${targets.length - bad.length}/${targets.length} links in llms.txt resolve to their content.`, where: bad.slice(0, 5), + }); + const when = /^#{1,3} .*(when to use|use (this|it) (for|when)|for (ai )?agents)/im.test(llms.text); + set("agent-instruction", { + score: when ? 3 : 0, max: 3, status: when ? "pass" : "fail", + evidence: when ? "llms.txt has a when-to-use section." : "llms.txt has no section that tells an agent when to use this reference and how to read it.", + fix: when ? undefined : 'Add a "## When to use this" section to llms.txt: what the library is for, that each page has a .md twin, that api.json holds the whole model, and how to find a type (element-list, search-index).', + }); + const modular = targets.some(t => /\/llms\.txt$/.test(t) && t !== `${site.url}llms.txt`); + set("modular-llms-txt", { score: modular ? 1 : 0, max: 1, status: modular ? "pass" : "fail", evidence: modular ? "Per-section llms.txt files are linked." : "Only a root llms.txt; no per-package llms.txt.", fix: modular ? undefined : "For a large module, write <package>/llms.txt per package and link each from the root llms.txt." }); + } + + // sitemap + { + const sm = await get(`${site.url}sitemap.xml`); + const locs = [...sm.text.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map(m => m[1]!); + const lastmod = (sm.text.match(/<lastmod>/g) ?? []).length; + const htmlPages = site.pages.all.length; + const valid = sm.status === 200 && /<urlset[\s>]/.test(sm.text) && locs.length > 0; + const sample = locs.filter((_, i) => i % Math.max(1, Math.floor(locs.length / 20)) === 0); + const dead: string[] = []; + await pool(sample, 8, async loc => { + const r = await get(loc); + if (r.status !== 200) dead.push(`${loc} (${r.status})`); + }); + const s = !valid ? 0 : dead.length ? 1 : 2; + set("sitemap", { + score: s, max: 2, status: statusOf(s, 2), + evidence: valid ? `sitemap.xml lists ${locs.length} URLs for ${htmlPages} HTML pages; ${sample.length - dead.length}/${sample.length} sampled URLs resolve.` : `GET /sitemap.xml: ${sm.status}. The renderer writes it only when the theme sets baseUrl.`, + where: dead.slice(0, 5), + fix: valid ? undefined : "Write sitemap.xml whenever the site's URL is known (theme baseUrl), and have the JVM tools pass the published URL. Without a base URL, say so in the run output.", + }); + const lm = valid && locs.length ? lastmod / locs.length : 0; + set("sitemap-lastmod", { score: lm >= 0.5 ? 1 : 0, max: 1, status: lm >= 0.5 ? "pass" : "fail", evidence: valid ? `${lastmod}/${locs.length} sitemap entries carry <lastmod>.` : "No sitemap.", fix: lm >= 0.5 ? undefined : "Add <lastmod> to sitemap entries from the model's build date (or the module version's release date)." }); + } + + // noindex-directives + { + const r = await get(pageAt(site, site.pages.overview)); + const robotsMeta = ["robots", "googlebot", "bingbot"].map(k => overview.meta.get(k) ?? "").join(" "); + const header = r.headers.get("x-robots-tag") ?? ""; + const hidden = /noindex/i.test(robotsMeta) || /noindex/i.test(header); + set("noindex-directives", { score: hidden ? 0 : 1, max: 1, status: hidden ? "fail" : "pass", evidence: hidden ? `noindex in ${robotsMeta ? "meta robots" : "X-Robots-Tag"}` : "No noindex meta tag or X-Robots-Tag header on the overview." }); + } + + // robots.txt + { + const robots = await get(`${site.url}robots.txt`); + const paths = pages.slice(0, 6).map(p => "/" + p); + const evaluate = (agents: string[]) => { + if (robots.status === 404) return { blocked: [] as string[], note: "no robots.txt (404): nothing is restricted" }; + if (robots.status !== 200 || /html/.test(robots.type ?? "")) return { blocked: ["*"], note: `robots.txt answered ${robots.status} ${robots.type}; crawlers treat errors and HTML as no usable rules` }; + const blocked = agents.flatMap(a => paths.filter(p => !robotsAllows(robots.text, a, p)).map(p => `${a} ${p}`)); + return { blocked, note: `robots.txt present (${robots.text.length} chars)` }; + }; + const search = evaluate(AGENTS_SEARCH); + const user = evaluate(AGENTS_USER); + set("robots-ai-policy-quality", { + score: search.blocked.length ? 0 : 2, max: 2, status: search.blocked.length ? "fail" : "pass", + evidence: `${search.note}. AI search crawlers (${AGENTS_SEARCH.join(", ")}) on ${paths.length} pages: ${search.blocked.length ? `blocked ${search.blocked.length}` : "allowed"}.`, where: search.blocked.slice(0, 5), + fix: robots.status === 404 ? "Optional: write a robots.txt (Allow: / for all, and Sitemap: <baseUrl>sitemap.xml) when the reference is served at a host root. It passes without one." : undefined, + }); + set("robots-agent-user-policy", { + score: user.blocked.length ? 0 : 2, max: 2, status: user.blocked.length ? "fail" : "pass", + evidence: `${user.note}. User-triggered agents (${AGENTS_USER.join(", ")}): ${user.blocked.length ? `blocked ${user.blocked.length}` : "allowed"}.`, where: user.blocked.slice(0, 5), + }); + } + + // agent-crawler-reachability and bot-detection: the audit server serves every user agent alike; this proves the pages need no cookies or JS challenge. + { + const base = await get(pageAt(site, site.pages.overview)); + const uas = ["ChatGPT-User/1.0", "OAI-SearchBot/1.0", "Claude-User/1.0", "PerplexityBot/1.0"]; + const results = await Promise.all(uas.map(async ua => ({ ua, r: await get(pageAt(site, site.pages.overview), { "user-agent": `Mozilla/5.0 (compatible; ${ua})` }) }))); + // The same content: a page with server islands differs in every response (each render encrypts the islands' + // props anew), so compare the text a reader gets, not the bytes. + const text = (html: string) => readPage(html).mainText; + const ok = results.filter(x => x.r.status === 200 && text(x.r.text) === text(base.text)); + const s = 2 * ok.length / uas.length; + const evidence = `${ok.length}/${uas.length} agent user agents got the same 200 page from the audit server. A real host's WAF or bot rules are not tested here.`; + set("agent-crawler-reachability", { score: s, max: 2, status: statusOf(s, 2), evidence }); + set("bot-detection", { score: s, max: 2, status: statusOf(s, 2), evidence }); + } + + // docs-auth-gate + { + const gated = pages.filter(p => /<input[^>]+type="password"/i.test(readFileSync(join(site.dir, p), "utf8"))); + const s = gated.length ? 0 : 2; + set("docs-auth-gate", { score: s, max: 2, status: statusOf(s, 2), evidence: `${pages.length - gated.length}/${pages.length} pages are readable with no sign-in form.`, where: gated.slice(0, 5) }); + } + + // redirect-hygiene + { + const stubs = pages.filter(p => { + const f = facts.get(p)!; + return f.metaRefresh || f.inlineScripts.some(s => /\b(window\.)?location(\.href)?\s*=(?!=)|location\.(replace|assign)\s*\(/.test(s)); + }); + set("redirect-hygiene", { score: stubs.length ? 0 : 1, max: 1, status: stubs.length ? "fail" : "pass", evidence: `${stubs.length} of ${pages.length} pages carry a meta refresh or a script redirect.`, where: stubs.slice(0, 5) }); + } + + // page-token-budget: extracted text under ~100K characters (~25K tokens). + { + const rows = pages.map(p => ({ page: p, chars: facts.get(p)!.bodyText.length, md: (file(p.replace(/\.html$/, ".md")) ?? "").length })); + const over = rows.filter(r => r.chars > TOKEN_BUDGET_CHARS); + const largest = worst(rows, r => r.chars, 1)[0]!; + set("page-token-budget", { + score: over.length ? 0 : 1, max: 1, status: over.length ? "fail" : "pass", + evidence: `${pages.length - over.length}/${pages.length} pages fit ${TOKEN_BUDGET_CHARS.toLocaleString("en")} chars of text (~25K tokens). Largest: ${largest.page}, ${largest.chars.toLocaleString("en")} chars of text (~${Math.round(largest.chars / 4000)}K tokens); its .md twin is ${largest.md.toLocaleString("en")} chars.`, + where: worst(over, r => r.chars).map(r => `${r.page}: ${r.chars.toLocaleString("en")} chars`), + fix: over.length ? "Split very large type pages: keep the summary tables and the most-used members on the type page and move member details for big groups (or inherited members) to per-group pages, or drop text repeated per member (each member's full signature appears in the summary and again in its detail). The .md twin needs the same split." : undefined, + }); + } + + // agent-friendly-404: real 404/410 status (partial), plus a Markdown body for Accept: text/markdown (full). + { + const missing = `${site.url}no-such-page-${Date.now()}.html`; + const html = await get(missing); + const md = await get(missing, { accept: "text/markdown" }); + const realStatus = html.status === 404 || html.status === 410; + const mdBody = (md.status === 404 || md.status === 410) && /markdown/.test(md.type ?? "") && md.text.trim().length >= 20; + const s = (realStatus ? 1 : 0) + (mdBody ? 1 : 0); + set("agent-friendly-404", { + score: s, max: 2, status: statusOf(s, 2), + evidence: `GET a missing page: ${html.status} ${html.type ?? ""}; with Accept: text/markdown: ${md.status} ${md.type ?? ""}, ${md.text.length} chars. Output has 404.html: ${existsSync(join(site.dir, "404.html")) ? "yes" : "no"}, 404.md: ${existsSync(join(site.dir, "404.md")) ? "yes" : "no"}.`, + fix: mdBody ? undefined : "Have the renderer write 404.html and 404.md (a short page that points at index, llms.txt and the search), so hosts that serve a 404 page (GitHub Pages, Netlify, Cloudflare Pages) return them; the host must serve 404.md for Accept: text/markdown.", + }); + } + + set("trust-anchors", { status: "na", evidence: "About, contact and privacy pages belong to the site that hosts the reference, not to the generated reference. Not scored here; the hosted scan checks the host's root." }); + + // Host-dependent bonus checks. + { + const r = await get(pageAt(site, site.pages.overview)); + const link = r.headers.get("link") ?? ""; + set("link-headers-discovery", { score: link ? 1 : 0, max: 1, status: link ? "pass" : "fail", evidence: link ? `Link: ${link}` : "No Link response header on the overview (the host adds it; the agent host profile does)." }); + const md = await get(site.url, { accept: "text/markdown" }); + const vary = (md.headers.get("vary") ?? "").toLowerCase().includes("accept"); + const okMd = /markdown/.test(md.type ?? "") && md.text.trim().length > 0 && vary; + set("markdown-negotiation-vary", { score: okMd ? 1 : 0, max: 1, status: okMd ? "pass" : "fail", evidence: `GET / with Accept: text/markdown: ${md.status} ${md.type ?? ""}, Vary: ${md.headers.get("vary") ?? "none"}.`, fix: okMd ? undefined : "Host: serve each page's .md twin for Accept: text/markdown with Vary: Accept (run with --host agent to see the score with it)." }); + const staticMd = await Promise.all(["llms.md", "agents.md", "auth.md"].map(f => get(site.url + f))); + const neg = okMd || staticMd.some(x => x.status === 200 && /markdown/.test(x.type ?? "")); + set("markdown-negotiation", { score: neg ? 1 : 0, max: 1, status: neg ? "pass" : "fail", evidence: neg ? "Markdown served for the homepage, by negotiation or a root .md file." : "No Accept: text/markdown negotiation on / and no /llms.md or /agents.md.", fix: neg ? undefined : "Either the host negotiates (see markdown-negotiation-vary), or the renderer also writes llms.txt as /llms.md." }); + } + + // Accessibility-tree checks, from raw HTML. + { + const rows = pages.map(p => ({ page: p, f: facts.get(p)! })); + const structureOk = rows.filter(({ f }) => f.landmarks.main === 1 && f.h1 === 1 && f.maxHeadingSkip <= 1); + const landmarkAvg = rows.reduce((a, { f }) => a + ["header", "nav", "main", "footer"].filter(k => f.landmarks[k as keyof typeof f.landmarks] > 0).length, 0) / rows.length; + const s1 = 3 * structureOk.length / rows.length; + set("ax-document-structure", { + score: s1, max: 3, status: statusOf(s1, 3), + evidence: `${structureOk.length}/${rows.length} pages have one main, one h1 and no heading skip over 1. Landmarks (header, nav, main, footer) present on average: ${landmarkAvg.toFixed(1)}/4.`, + where: rows.filter(r => !structureOk.includes(r)).slice(0, 5).map(({ page, f }) => `${page}: main ${f.landmarks.main}, h1 ${f.h1}, skip ${f.maxHeadingSkip}`), + }); + const controls = rows.flatMap(({ page, f }) => f.controls.map(c => ({ page, c }))); + const nonNative = controls.filter(x => !x.c.native); + const nativeShare = controls.length ? (controls.length - nonNative.length) / controls.length : 1; + const s2 = nativeShare >= 0.95 ? 3 : 3 * nativeShare; + set("ax-native-controls", { score: s2, max: 3, status: statusOf(s2, 3), evidence: `${controls.length - nonNative.length}/${controls.length} interactive elements are native (${pct(nativeShare)}).`, where: unique(nonNative.map(x => `${x.c.label} (${x.page})`)).slice(0, 5) }); + const unnamed = controls.filter(x => !x.c.name); + const named = controls.length ? (controls.length - unnamed.length) / controls.length : 1; + const s3 = named === 1 ? 2 : 2 * named; + set("ax-accessible-names", { score: s3, max: 2, status: statusOf(s3, 2), evidence: `${controls.length - unnamed.length}/${controls.length} interactive elements have a name in the raw HTML (${pct(named)}).`, where: unique(unnamed.map(x => `${x.c.label} (${x.page})`)).slice(0, 5) }); + const fields = rows.flatMap(({ page, f }) => f.fields.map(x => ({ page, ...x }))); + const unlabelled = fields.filter(x => !x.labelled); + const s4 = fields.length ? 2 * (fields.length - unlabelled.length) / fields.length : 2; + set("ax-form-labeling", { score: s4, max: 2, status: statusOf(s4, 2), evidence: `${fields.length - unlabelled.length}/${fields.length} form fields have a label.`, where: unique(unlabelled.map(x => `${x.label} (${x.page})`)).slice(0, 5) }); + const inj = rows.flatMap(({ page, f }) => f.injection.map(i => `${page}: ${i}`)); + set("ax-tree-injection-safe", { score: inj.length ? 0 : 2, max: 2, status: inj.length ? "fail" : "pass", evidence: inj.length ? `${inj.length} hidden strings read like instructions to an agent.` : "No hidden text that reads like an instruction to an agent.", where: inj.slice(0, 5) }); + } + + // Emerging Markdown checks. + { + const rows = pages.map(p => ({ page: p, f: facts.get(p)! })); + const bad: string[] = []; + let advertised = 0; + for (const { page, f } of rows) { + const alt = f.links.find(l => l.rel.split(/\s+/).includes("alternate") && l.type === "text/markdown"); + if (!alt) { + bad.push(`${page}: no alternate`); + continue; + } + advertised++; + const target = join(site.dir, page, "..", alt.href.split("#")[0]!); + const body = existsSync(target) ? readFileSync(target, "utf8") : undefined; + if (!body || /^\s*</.test(body)) bad.push(`${page}: ${alt.href} ${body ? "is HTML" : "missing"}`); + } + const s = rows.length ? (rows.length - bad.length) / rows.length : 0; + set("markdown-link-alternate", { score: s, max: 1, status: statusOf(s, 1), evidence: `${advertised}/${rows.length} pages advertise a Markdown twin; ${rows.length - bad.length} of them resolve to Markdown.`, where: bad.slice(0, 5) }); + const index = await get(`${site.url}index.md`); + const twins = pages.filter(p => existsSync(join(site.dir, p.replace(/\.html$/, ".md")))); + const okIndex = index.status === 200 && /markdown/.test(index.type ?? "") && /^#/.test(index.text.trimStart()); + const sf = okIndex ? (twins.length === pages.length ? 2 : 1) : 0; + set("markdown-url-fallback", { score: sf, max: 2, status: statusOf(sf, 2), evidence: `/index.md: ${index.status} ${index.type ?? ""}; ${twins.length}/${pages.length} pages have a .md twin at the same path.` }); + const mdFiles = pages.map(p => p.replace(/\.html$/, ".md")).filter(p => existsSync(join(site.dir, p))); + const withFront = mdFiles.filter(p => /^---\n[\s\S]*?\btitle:[\s\S]*?\n---\n/.test(readFileSync(join(site.dir, p), "utf8"))); + const sfm = mdFiles.length ? withFront.length / mdFiles.length : 0; + set("markdown-frontmatter", { score: sfm, max: 1, status: statusOf(sfm, 1), evidence: `${withFront.length}/${mdFiles.length} Markdown pages open with a --- frontmatter block carrying a title.`, fix: sfm < 1 ? "Open each .md twin with frontmatter: title, description (the summary), canonical (the HTML page's absolute URL when baseUrl is set), and the module version. Keep llms-full.txt readable (strip or keep per page)." : undefined }); + const unbalanced = mdFiles.filter(p => !fencesBalanced(readFileSync(join(site.dir, p), "utf8"))); + set("code-fence-validity", { score: unbalanced.length ? 0 : 1, max: 1, status: unbalanced.length ? "fail" : "pass", evidence: `${mdFiles.length - unbalanced.length}/${mdFiles.length} Markdown pages close every code fence.`, where: unbalanced.slice(0, 5) }); + } + + // Assemble, in rule order, and score with Ora's formula. + const findings: Finding[] = RULES.map(rule => { + const r = results.get(rule.id); + if (!r) return { rule: rule.id, name: rule.name, owner: rule.owner, status: "info" as Status, evidence: "not measured", source: SOURCE }; + return { rule: rule.id, name: rule.name, owner: r.owner ?? rule.owner, file: rule.file, source: SOURCE, ...r, ...(rule.state === "emerging" ? { evidence: `[emerging, unscored] ${r.evidence}` } : rule.state === "bonus" ? { evidence: `[bonus] ${r.evidence}` } : {}) }; + }); + const layers: Record<string, { earned: number; available: number }> = {}; + for (const rule of RULES) { + if (!rule.layer || rule.state === "emerging" || rule.state === "na") continue; + const r = results.get(rule.id); + if (!r || r.status === "na" || r.score === undefined) continue; + const layer = (layers[rule.layer] ??= { earned: 0, available: 0 }); + layer.earned += r.score; + layer.available += rule.state === "bonus" ? r.score : rule.max; + } + let weighted = 0; + let weights = 0; + for (const [id, l] of Object.entries(layers)) { + if (l.available === 0) continue; + weighted += LAYER_WEIGHTS[id as Layer] * (l.earned / l.available); + weights += LAYER_WEIGHTS[id as Layer]; + } + return { score: weights ? Math.round((100 * weighted) / weights) : 0, findings, pages, layers }; +} + +/** The representative pages, and when the site is large, an even sample of the rest. */ +function samplePages(site: Site, limit: number): string[] { + const { overview, package: pkg, smallType, largestType, all } = site.pages; + if (all.length <= limit) return all; + const picked = new Set([overview, pkg, smallType, largestType]); + const step = all.length / (limit - picked.size); + for (let i = 0; i < all.length && picked.size < limit; i += step) picked.add(all[Math.floor(i)]!); + return [...picked]; +} + +/** Whether a robots.txt lets a user agent fetch a path: the most specific matching group, then the longest matching rule. */ +export function robotsAllows(robots: string, agent: string, path: string): boolean { + const groups: { agents: string[]; rules: { allow: boolean; path: string }[] }[] = []; + let current: (typeof groups)[number] | undefined; + let lastWasAgent = false; + for (const raw of robots.split(/\r?\n/)) { + const line = raw.replace(/#.*/, "").trim(); + const m = /^([a-z-]+)\s*:\s*(.*)$/i.exec(line); + if (!m) continue; + const key = m[1]!.toLowerCase(); + const value = m[2]!.trim(); + if (key === "user-agent") { + if (!lastWasAgent || !current) groups.push((current = { agents: [], rules: [] })); + current.agents.push(value.toLowerCase()); + lastWasAgent = true; + } else { + lastWasAgent = false; + if (current && (key === "allow" || key === "disallow") && value) current.rules.push({ allow: key === "allow", path: value }); + } + } + const name = agent.toLowerCase(); + const group = groups.find(g => g.agents.some(a => a !== "*" && name.startsWith(a))) ?? groups.find(g => g.agents.includes("*")); + if (!group) return true; + const matches = group.rules.filter(r => pathMatches(r.path, path)).sort((a, b) => b.path.length - a.path.length || Number(b.allow) - Number(a.allow)); + return matches[0]?.allow ?? true; +} + +function pathMatches(pattern: string, path: string): boolean { + const anchored = pattern.endsWith("$"); + const body = (anchored ? pattern.slice(0, -1) : pattern).split("*").map(s => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*"); + return new RegExp(`^${body}${anchored ? "$" : ""}`).test(path); +} + +/** Whether every ``` or ~~~ fence in a Markdown document is closed (CommonMark: a closing fence uses the same character, at least as long). */ +export function fencesBalanced(md: string): boolean { + let open: { char: string; len: number } | undefined; + for (const line of md.split("\n")) { + const m = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line); + if (!m) continue; + const fence = m[1]!; + if (!open) { + if (fence[0] === "`" && m[2]!.includes("`")) continue; + open = { char: fence[0]!, len: fence.length }; + } else if (fence[0] === open.char && fence.length >= open.len && m[2]!.trim() === "") open = undefined; + } + return !open; +} + +interface Got { + status: number; + type?: string; + text: string; + headers: Headers; +} + +async function get(url: string, headers: Record<string, string> = {}): Promise<Got> { + try { + const r = await fetch(url, { headers, redirect: "manual" }); + return { status: r.status, type: r.headers.get("content-type") ?? undefined, text: await r.text(), headers: r.headers }; + } catch (e) { + return { status: 0, text: String(e), headers: new Headers() }; + } +} + +async function pool<T>(items: T[], size: number, work: (item: T) => Promise<void>): Promise<void> { + let next = 0; + await Promise.all(Array.from({ length: Math.min(size, items.length) }, async () => { + while (next < items.length) await work(items[next++]!); + })); +} + +function statusOf(score: number, max: number): Status { + return score >= max - 1e-9 ? "pass" : score <= 0 ? "fail" : "partial"; +} + +const pct = (x: number) => `${(x * 100).toFixed(1)}%`; +const unique = (list: string[]) => [...new Set(list)]; diff --git a/packages/apidocs/scripts/audit/build.ts b/packages/apidocs/scripts/audit/build.ts new file mode 100644 index 0000000..73fef83 --- /dev/null +++ b/packages/apidocs/scripts/audit/build.ts @@ -0,0 +1,83 @@ +/** + * Builds a site exactly as the doclet does (dist/runner.mjs running + * dist/render.js), and picks the pages the audits read closely. + */ +import { spawnSync } from "node:child_process"; +import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { join, relative } from "node:path"; +import { fileURLToPath } from "node:url"; +import type { RepresentativePages } from "./types"; + +export const packageRoot = fileURLToPath(new URL("../..", import.meta.url)); + +/** Runs `bun run build` in the package. Retries once, since another editor may be mid-change. */ +export function buildDist(): void { + for (let attempt = 1; ; attempt++) { + const run = spawnSync("bun", ["run", "build"], { cwd: packageRoot, encoding: "utf8" }); + if (run.status === 0) return; + if (attempt >= 3) throw new Error(`bun run build failed:\n${(run.stdout + run.stderr).slice(-4000)}`); + console.error(` build failed (attempt ${attempt}); retrying in 10 s, in case a file is mid-edit`); + Bun.sleepSync(10_000); + } +} + +export interface BuildInput { + /** A model as JSON text, or the path of one. */ + model: { json: string } | { path: string }; + theme: Record<string, unknown>; + out: string; + work: string; +} + +/** Renders a model into out/ with the runner. Returns the runner's stats. */ +export function renderSite(input: BuildInput): { files: number; bytes: number; renderMs: number } { + mkdirSync(input.work, { recursive: true }); + const model = "path" in input.model ? input.model.path : join(input.work, "model.json"); + if ("json" in input.model) writeFileSync(model, input.model.json); + const theme = join(input.work, "theme.json"); + writeFileSync(theme, JSON.stringify(input.theme)); + rmSync(input.out, { recursive: true, force: true }); + const run = spawnSync(process.execPath, [ + join(packageRoot, "dist/runner.mjs"), "--bundle", join(packageRoot, "dist/render.js"), "--assets", join(packageRoot, "dist/assets"), + "--model", model, "--theme", theme, "--out", input.out, + ], { encoding: "utf8", maxBuffer: 64 << 20 }); + if (run.status !== 0) throw new Error(`runner failed:\n${run.stderr}`); + return JSON.parse(run.stdout); +} + +/** Every file under dir, as paths relative to it. */ +export function listFiles(dir: string): string[] { + const out: string[] = []; + const walk = (d: string) => { + for (const entry of readdirSync(d, { withFileTypes: true })) { + const path = join(d, entry.name); + if (entry.isDirectory()) walk(path); + else out.push(relative(dir, path)); + } + }; + walk(dir); + return out.sort(); +} + +/** + * The module overview, the package page with the most types, the smallest and + * the largest type page by HTML size, and every page. `prefer` names a page + * to use as the largest type page when it exists (dev/elide/kotlin/api/Ir.html + * for the Komodo model). + */ +export function representativePages(dir: string, prefer?: string): RepresentativePages { + const html = listFiles(dir).filter(f => f.endsWith(".html") && !f.startsWith("assets/") && f !== "404.html"); + const packages = html.filter(f => f.endsWith("/index.html")); + const types = html.filter(f => !f.endsWith("index.html")); + const size = (f: string) => statSync(join(dir, f)).size; + const typeCount = (pkgPage: string) => { + const prefix = pkgPage.slice(0, -"index.html".length); + return types.filter(t => t.startsWith(prefix) && !t.slice(prefix.length).includes("/")).length; + }; + const bySize = [...types].sort((a, b) => size(a) - size(b)); + const pkg = [...packages].sort((a, b) => typeCount(b) - typeCount(a))[0] ?? "index.html"; + const largest = prefer && types.includes(prefer) ? prefer : bySize.at(-1) ?? "index.html"; + // The smallest type page that still documents something: skip pages under 2 KB of text (empty annotation types). + const small = bySize.find(f => readFileSync(join(dir, f), "utf8").length > 4000) ?? bySize[0] ?? "index.html"; + return { overview: "index.html", package: pkg, smallType: small, largestType: largest, all: html }; +} diff --git a/packages/apidocs/scripts/audit/css.ts b/packages/apidocs/scripts/audit/css.ts new file mode 100644 index 0000000..45ee138 --- /dev/null +++ b/packages/apidocs/scripts/audit/css.ts @@ -0,0 +1,255 @@ +/** + * The good-css.com rules, checked against the stylesheets a site ships. + * + * good-css.com is a list of 47 modern CSS techniques with rules, written for + * agents ("Strong opinions about modern CSS technique, borrowed from + * experts"). It is a guideline, not a tool, and has no score. Its agent skill + * (https://good-css.com/skills/good-css/SKILL.md) states nine rules "in all + * CSS"; this file checks those mechanically, with each violation's selector. + * The 47 entries (https://good-css.com/llms.txt) need judgment about where a + * technique applies, so each gets a checklist row with what the stylesheet + * shows (a signal) and a "review" status for a person to settle. + * + * The score is the share of the mechanical rules with no violation. + */ +import postcss, { type AtRule, type Declaration, type Rule } from "postcss"; +import type { Finding, Status } from "./types"; + +export interface Stylesheet { + /** The published path, such as "assets/apidocs.css". */ + path: string; + css: string; + /** The source file it comes from, for the report. */ + source: string; +} + +interface Decl { + sheet: string; + line: number; + selector: string; + /** Ancestor at-rules, outermost first, such as "@media (hover: hover) and (pointer: fine)". */ + context: string[]; + prop: string; + value: string; +} + +export interface CssReport { + score: number; + rules: Finding[]; + checklist: Finding[]; +} + +const SKILL = "https://good-css.com/skills/good-css/SKILL.md"; +const entry = (slug: string) => `https://good-css.com/${slug}`; + +const PHYSICAL = /^(margin|padding|scroll-margin|scroll-padding)-(left|right|top|bottom)$|^border-(left|right|top|bottom)(-(width|style|color))?$|^(left|right|top|bottom)$|^border-(top|bottom)-(left|right)-radius$|^overscroll-behavior-[xy]$/; +const NAMED_COLOR = /\b(white|black|red|green|blue|gray|grey|silver|orange|yellow|purple|pink|navy|teal|maroon|olive|lime|aqua|fuchsia)\b/i; +const MOVES = /\b(transform|translate|scale|rotate|inset|top|left|right|bottom|margin[\w-]*|width|height|inline-size|block-size|grid-template[\w-]*|all)\b/; + +export function readDeclarations(sheets: Stylesheet[]): Decl[] { + const out: Decl[] = []; + for (const sheet of sheets) { + const root = postcss.parse(sheet.css, { from: sheet.path }); + root.walkDecls((decl: Declaration) => { + const context: string[] = []; + let selector = ""; + for (let p = decl.parent; p && p.type !== "root"; p = p.parent as typeof p) { + if (p.type === "rule" && !selector) selector = (p as Rule).selector.replace(/\s+/g, " "); + else if (p.type === "rule") selector = `${(p as Rule).selector.replace(/\s+/g, " ")} ${selector}`; + if (p.type === "atrule") context.unshift(`@${(p as AtRule).name} ${(p as AtRule).params}`.trim()); + } + out.push({ sheet: sheet.path, line: decl.source?.start?.line ?? 0, selector: selector || "(at-rule)", context, prop: decl.prop.toLowerCase(), value: decl.value }); + }); + } + return out; +} + +export function cssAudit(sheets: Stylesheet[]): CssReport { + const decls = readDeclarations(sheets); + const sourceOf = (sheet: string) => sheets.find(s => s.path === sheet)?.source ?? sheet; + const at = (d: Decl) => `${d.sheet}:${d.line} ${d.selector.slice(0, 70)} { ${d.prop}: ${d.value.slice(0, 60)} }`; + const files = (list: Decl[]) => [...new Set(list.map(d => sourceOf(d.sheet)))].join(", ") || undefined; + const rules: Finding[] = []; + const rule = (id: string, name: string, violations: Decl[], evidence: string, fix: string, source = SKILL, extra: string[] = []) => { + rules.push({ + rule: id, name, owner: "page", status: violations.length || extra.length ? "fail" : "pass", + evidence: violations.length || extra.length ? `${violations.length + extra.length} ${evidence}` : "No violations.", + where: [...extra, ...violations.map(at)].slice(0, 8), file: files(violations) ?? (extra.length ? sheets[0]?.source : undefined), fix: violations.length || extra.length ? fix : undefined, source, + }); + }; + const inMedia = (d: Decl, re: RegExp) => d.context.some(c => c.startsWith("@media") && re.test(c)); + const selectors = [...new Set(decls.map(d => d.selector))]; + + // 1. Logical properties. + const physical = decls.filter(d => PHYSICAL.test(d.prop) + || (d.prop === "text-align" && /\b(left|right)\b/.test(d.value)) + || (d.prop === "float" && /\b(left|right)\b/.test(d.value)) + || (/^(margin|padding|inset|scroll-margin|scroll-padding)$/.test(d.prop) && splitValues(d.value).length > 1 && !allSame(splitValues(d.value)))); + rule("logical-properties", "Logical properties in place of left, right, top and bottom", physical, + "declarations name a physical side (or use a multi-value margin, padding or inset shorthand)", + "Use margin-inline/-block(-start/-end), padding-inline/-block, inset-inline/-block, border-inline-start, text-align: start/end; the -inline and -block shorthands in place of multi-value margin and padding.", entry("logical-properties")); + + // 2. OKLCH colors, and grays with a hue of none. + const colorDecls = decls.filter(d => !/^(font|src|content|grid|transition|animation|counter|quotes|unicode)/.test(d.prop) && !/url\(/.test(d.value)); + const legacy = colorDecls.filter(d => /#[0-9a-f]{3,8}\b|\b(rgba?|hsla?|hwb|lab|lch)\(/i.test(d.value) || (NAMED_COLOR.test(d.value) && /color|background|border|outline|fill|stroke|shadow|^--/.test(d.prop) && !/color-mix\(in oklch,[^)]*\b(white|black)\b/.test(d.value))); + const grayHue = colorDecls.filter(d => [...d.value.matchAll(/oklch\(\s*[\d.]+%?\s+0(?:\.0+)?\s+([\d.]+)/g)].length > 0); + rule("oklch-color", "Colors in oklch(), grays with hue none", [...legacy, ...grayHue], + "declarations use hex, rgb(), hsl() or a named color, or write a gray's hue as a number", + "Write colors as oklch(); derive hover, tint and transparent versions with color-mix(in oklch, ...); write grays as oklch(L 0 none).", entry("oklch-color")); + + // 3. Fluid sizes with clamp(): no bare vw, and no font-size or spacing ladders in width media queries. + const bareVw = decls.filter(d => /\d(vw|vi)\b/.test(d.value) && !/clamp\(|min\(|max\(/.test(d.value)); + const ladder = decls.filter(d => /^(font-size|padding|margin|gap|row-gap|column-gap)(-|$)/.test(d.prop) && inMedia(d, /(min|max)-width|width\s*[<>]/)); + const vwOnly = decls.filter(d => /clamp\([^,]+,\s*[\d.]+vw\s*,/.test(d.value)); + rule("fluid-clamp", "Sizes that grow with the screen in one clamp() token", [...bareVw, ...vwOnly, ...ladder], + "declarations use a bare vw value, a vw-only clamp middle, or step a font size or spacing through width media queries", + "Put each fluid size in one custom property: clamp(min-rem, rem + vw, max-rem), and use it in place of the breakpoint steps.", entry("fluid-sizes-with-clamp")); + + // 4. :hover only inside @media (hover: hover) and (pointer: fine). + const hover = decls.filter(d => /:hover\b/.test(d.selector) && !inMedia(d, /hover:\s*hover/) ); + const hoverHalf = decls.filter(d => /:hover\b/.test(d.selector) && inMedia(d, /hover:\s*hover/) && !inMedia(d, /pointer:\s*fine/)); + rule("hover-media", ":hover only where hover exists", [...hover, ...hoverHalf], + "declarations under :hover are not inside @media (hover: hover) and (pointer: fine)", + "Wrap every :hover rule in @media (hover: hover) and (pointer: fine); give touch feedback with :active.", entry("hover-styles-only-where-hover-exists")); + + // 5. Focus with :focus-visible and outline; never outline: none. + const outlineNone = decls.filter(d => /^outline$/.test(d.prop) && /^(none|0|0px)\b/.test(d.value.trim()) || d.prop === "outline-style" && d.value.trim() === "none"); + const plainFocus = decls.filter(d => /:focus(?![-\w])/.test(d.selector)); + rule("focus-visible", "Focus styled with :focus-visible and outline, never outline: none", [...outlineNone, ...plainFocus], + "declarations remove the outline or style :focus in place of :focus-visible", + "Style focus with :focus-visible { outline: ... }; where a component draws its ring with box-shadow, set outline-color: transparent, never outline: none.", entry("one-focus-ring-with-focus-visible")); + + // 6. Everything pressable has an :active state. Approximated as: every selector with :hover has a matching :active. + const base = (s: string) => s.replace(/:(hover|active|focus-visible|focus-within)\b/g, "").replace(/\s+/g, " ").trim(); + const activeBases = new Set(selectors.filter(s => /:active\b/.test(s)).flatMap(s => s.split(",").map(base))); + const hoverOnly = [...new Set(selectors.filter(s => /:hover\b/.test(s)).flatMap(s => s.split(",").filter(p => /:hover\b/.test(p)).map(base)))].filter(b => !activeBases.has(b)); + rule("press-feedback", "Everything pressable has an :active state", [], + "hover targets have no :active state", + "Add an :active rule for each pressable element (a scale of 0.95 to 0.98 inside the reduced-motion query, or a color change).", entry("press-feedback"), hoverOnly.map(s => `no :active for ${s}`)); + + // 7. Motion inside prefers-reduced-motion: no-preference; name properties; never all; never ease-in. + const transitions = decls.filter(d => /^(transition|transition-property|animation|animation-name)$/.test(d.prop)); + const moving = transitions.filter(d => (d.prop.startsWith("transition") ? MOVES.test(d.value) || /^\s*[\d.]+m?s\b/.test(d.value) : !/^none$/.test(d.value.trim())) && !inMedia(d, /prefers-reduced-motion:\s*no-preference/)); + const all = transitions.filter(d => d.prop.startsWith("transition") && (/\ball\b/.test(d.value) || /^\s*[\d.]+m?s\b/.test(d.value))); + const easeIn = decls.filter(d => /(transition|animation)(-timing-function)?$/.test(d.prop) && /\bease-in\b(?!-out)/.test(d.value) || /^--ease/.test(d.prop) && /\bease-in\b(?!-out)/.test(d.value)); + const slow = transitions.filter(d => [...d.value.matchAll(/([\d.]+)(m?s)\b/g)].some(m => Number(m[1]) * (m[2] === "s" ? 1000 : 1) > 300)); + rule("opt-in-motion", "Motion that moves or scales only inside prefers-reduced-motion: no-preference", moving, + "transitions or animations that move, resize or animate 'all' run outside @media (prefers-reduced-motion: no-preference)", + "Build the state change first, then add the transition inside @media (prefers-reduced-motion: no-preference). Fades of opacity and color may stay outside.", entry("opt-in-motion")); + rule("motion-properties", "Transitions name their properties, never all, never ease-in, 300 ms or less", [...all, ...easeIn, ...slow], + "transitions animate all (or name no property), use ease-in, or run longer than 300 ms", + "Name each property (transition: opacity 180ms var(--ease-out)); use ease-out or a custom curve; keep UI transitions at or under 300 ms (dialogs and drawers excepted).", entry("motion-tokens")); + + // 8. overflow: clip over hidden. + const hidden = decls.filter(d => /^overflow(-x|-y|-inline|-block)?$/.test(d.prop) && /\bhidden\b/.test(d.value)); + rule("overflow-clip", "overflow: clip over hidden", hidden, + "declarations use overflow: hidden", + "Use overflow: clip where nothing scrolls the element by script and it has no resize handle; keep hidden only for those.", entry("overflow-clip-over-hidden")); + + // 9. Left out on purpose. + const leftOut = decls.filter(d => (d.prop === "text-rendering" && /optimizelegibility/i.test(d.value)) + || (/^text-box(-trim)?$/.test(d.prop) && /(^|,)\s*\*\s*($|,)/.test(d.selector)) + || (d.prop === "display" && d.value === "contents" && /(^|,)\s*\*\s*($|,)/.test(d.selector))); + rule("left-out", "No text-box trim on *, no optimizeLegibility, no display: contents on *", leftOut, + "declarations the skill leaves out on purpose", + "Remove them; good-css.com/the-reset says why.", SKILL); + + const passing = rules.filter(r => r.status === "pass").length; + return { score: Math.round((100 * passing) / rules.length), rules, checklist: checklist(decls, sheets) }; +} + +interface Entry { + slug: string; + title: string; + /** What in the stylesheet shows the technique is used. */ + signal: (d: Decl[]) => string | undefined; + /** When the pages plainly need the technique. */ + applies?: string; +} + +const has = (decls: Decl[], prop: RegExp, value: RegExp = /./) => decls.filter(d => prop.test(d.prop) && value.test(d.value)); +const said = (list: Decl[], what: string) => (list.length ? `${what} (${list.length}x, first ${list[0]!.selector.slice(0, 40)})` : undefined); + +const ENTRIES: Entry[] = [ + { slug: "the-reset", title: "The reset", applies: "every page", signal: d => { + const parts = [["box-sizing", /border-box/], ["min-width", /^0/], ["text-wrap", /pretty/], ["font-synthesis", /none/], ["scrollbar-gutter", /stable/], ["overflow-wrap", /break-word/], ["-webkit-text-size-adjust", /100%/], ["touch-action", /manipulation/]] as const; + const found = parts.filter(([p, v]) => has(d, new RegExp(`^${p}$`), v).length).map(([p]) => p); + return `${found.length}/${parts.length} reset declarations present (${found.join(", ") || "none"}); missing: ${parts.filter(([p]) => !found.includes(p)).map(([p]) => p).join(", ") || "none"}`; + } }, + { slug: "logical-properties", title: "Logical properties", applies: "every page", signal: d => said(has(d, /-(inline|block)(-start|-end)?$|^inset-/), "logical properties used") }, + { slug: "oklch-color", title: "OKLCH color", applies: "every page", signal: d => said(d.filter(x => /oklch\(|color-mix\(in oklch/.test(x.value)), "oklch()/color-mix used") }, + { slug: "one-set-of-color-tokens-for-light-and-dark", title: "One set of color tokens for light and dark", applies: "the pages have a dark theme", signal: d => [said(has(d, /^color-scheme$/), "color-scheme set"), said(d.filter(x => /light-dark\(/.test(x.value)), "light-dark() used"), d.some(x => x.context.some(c => /prefers-color-scheme/.test(c)) && /^--/.test(x.prop)) ? "tokens are redefined under prefers-color-scheme (the entry says switch color-scheme, never redefine tokens)" : undefined].filter(Boolean).join("; ") || undefined }, + { slug: "fluid-sizes-with-clamp", title: "Fluid sizes with clamp()", signal: d => said(d.filter(x => /clamp\(/.test(x.value)), "clamp() used") }, + { slug: "one-fluid-scale-for-type-and-space", title: "One fluid scale for type and space", signal: d => said(has(d, /^--(step|space|text|font-size)/, /clamp\(/), "fluid scale tokens") }, + { slug: "content-grid-with-breakouts", title: "Content grid with breakouts", signal: d => said(has(d, /^grid-template-columns$/, /\[[\w-]*(content|full|breakout)/), "named content-grid lines") }, + { slug: "intrinsic-grid", title: "Intrinsic grid", signal: d => said(has(d, /^grid-template-columns$/, /auto-(fit|fill)/), "auto-fit/auto-fill grid") }, + { slug: "subgrid-rows-shared-across-cards", title: "Subgrid rows shared across cards", signal: d => said(has(d, /^grid-template-rows$|^grid-template-columns$/, /subgrid/), "subgrid") }, + { slug: "sidebar-that-wraps-on-its-own", title: "Sidebar that wraps on its own", applies: "the navigator beside the content", signal: d => said(has(d, /^flex-basis$|^flex$/, /\d/), "flex-basis sizing") }, + { slug: "container-queries-with-container-units", title: "Container queries with container units", signal: d => said(d.filter(x => x.context.some(c => c.startsWith("@container")) || x.prop === "container-type"), "container queries") }, + { slug: "stack-layers-with-grid", title: "Stack layers with grid", signal: d => said(has(d, /^grid-area$/, /1\s*\/\s*1/), "grid-area: 1 / 1 stacking") }, + { slug: "safe-alignment", title: "Safe alignment", signal: d => said(has(d, /^(justify|align)-(content|items|self)$/, /\bsafe\b/), "safe alignment") }, + { slug: "overflow-clip-over-hidden", title: "overflow: clip over hidden", applies: "anything cut off", signal: d => said(has(d, /^overflow/, /clip/), "overflow: clip") }, + { slug: "section-spacing-that-depends-on-its-neighbors", title: "Section spacing that depends on its neighbors", signal: d => said(d.filter(x => /\+|:has\(\s*\+/.test(x.selector) && /margin|padding/.test(x.prop)), "sibling-dependent spacing") }, + { slug: "space-between-siblings-set-by-the-parent", title: "Space between siblings set by the parent", applies: "stacked blocks of documentation", signal: d => said(has(d, /^(gap|row-gap)$/), "gap on parents") }, + { slug: "push-one-item-away-with-an-auto-margin", title: "Push one item away with an auto margin", signal: d => said(has(d, /^margin-(inline|block)-start$|^margin-(left|top)$/, /^auto$/), "auto margin") }, + { slug: "concentric-nested-radius", title: "Concentric nested radius", signal: d => said(d.filter(x => /radius/.test(x.prop) && /calc\(.*-/.test(x.value)), "nested radius computed") }, + { slug: "long-text-that-wraps-truncates-or-clamps", title: "Long text that wraps, truncates or clamps", applies: "long type and member names", signal: d => said(has(d, /^text-overflow$/, /ellipsis/), "ellipsis truncation") }, + { slug: "image-box-that-holds-any-upload", title: "Image box that holds any upload", signal: d => said(has(d, /^aspect-ratio$|^object-fit$/), "aspect-ratio/object-fit") }, + { slug: "tabular-numbers", title: "Tabular numbers", applies: "counts in the navigator and table of contents", signal: d => said(has(d, /^font-variant-numeric$/, /tabular-nums/), "tabular-nums") }, + { slug: "label-centered-on-its-letters-with-text-box", title: "Label centered on its letters with text-box", signal: d => said(has(d, /^text-box/), "text-box") }, + { slug: "icon-sized-by-the-text-beside-it", title: "Icon sized by the text beside it", applies: "icons beside labels", signal: d => said(d.filter(x => /^(width|height|inline-size|block-size)$/.test(x.prop) && /\d(em|cap|lh)\b/.test(x.value)), "icons sized in em/cap/lh") }, + { slug: "one-focus-ring-with-focus-visible", title: "One focus ring with :focus-visible", applies: "every control", signal: d => said(d.filter(x => /:focus-visible/.test(x.selector)), ":focus-visible rules") }, + { slug: "hover-styles-only-where-hover-exists", title: "Hover styles only where hover exists", applies: "every :hover rule", signal: d => said(d.filter(x => /:hover/.test(x.selector) && x.context.some(c => /hover:\s*hover/.test(c))), ":hover guarded by (hover: hover)") }, + { slug: "press-feedback", title: "Press feedback", applies: "every button", signal: d => said(d.filter(x => /:active/.test(x.selector)), ":active rules") }, + { slug: "hit-area-larger-than-the-visual", title: "Hit area larger than the visual", applies: "icon buttons (theme switch, navigator toggle, copy)", signal: d => said(d.filter(x => /::?(after|before)/.test(x.selector) && x.prop === "inset"), "pseudo-element hit areas") }, + { slug: "whole-card-clickable-from-one-link", title: "Whole card clickable from one link", signal: d => said(d.filter(x => /a::?after|::?after/.test(x.selector) && x.prop === "inset" && /^0/.test(x.value)), "stretched link") }, + { slug: "has-for-parent-and-page-state", title: ":has() for parent and page state", signal: d => said(d.filter(x => /:has\(/.test(x.selector)), ":has() selectors") }, + { slug: "form-feedback-with-user-invalid", title: "Form feedback with :user-invalid", signal: d => said(d.filter(x => /:user-invalid/.test(x.selector)), ":user-invalid") }, + { slug: "textarea-that-grows-with-its-content", title: "Textarea that grows with its content", signal: d => said(has(d, /^field-sizing$/), "field-sizing") }, + { slug: "opt-in-motion", title: "Opt-in motion", applies: "every transition that moves", signal: d => said(d.filter(x => x.context.some(c => /prefers-reduced-motion:\s*no-preference/.test(c))), "rules inside prefers-reduced-motion: no-preference") }, + { slug: "motion-tokens", title: "Motion tokens", applies: "every transition", signal: d => said(has(d, /^--(ease|duration)/), "easing/duration tokens") }, + { slug: "transition-a-custom-property-with-property", title: "Transition a custom property with @property", signal: () => undefined }, + { slug: "shadow-change-that-fades-and-does-not-repaint", title: "Shadow change that fades and does not repaint", signal: d => said(d.filter(x => /::?(after|before)/.test(x.selector) && x.prop === "box-shadow"), "shadow on a pseudo-element") }, + { slug: "cross-document-view-transitions", title: "Cross-document view transitions", applies: "a multi-page site (page transitions are planned)", signal: d => said(d.filter(x => x.context.some(c => c.startsWith("@view-transition")) || /::view-transition/.test(x.selector)), "@view-transition rules") }, + { slug: "indicator-that-slides-to-the-active-item", title: "Indicator that slides to the active item", applies: "the table-of-contents marker", signal: d => said(d.filter(x => /anchor-name|position-anchor/.test(x.prop)), "anchor positioning") }, + { slug: "enter-and-exit-transitions-from-display-none", title: "Enter and exit transitions from display: none", applies: "search results and the mobile navigator", signal: d => said(d.filter(x => x.context.some(c => c.startsWith("@starting-style")) || /allow-discrete/.test(x.value)), "@starting-style / allow-discrete") }, + { slug: "popover-anchored-to-its-trigger", title: "Popover anchored to its trigger", signal: d => said(d.filter(x => /:popover-open/.test(x.selector) || /position-anchor|anchor\(/.test(x.prop + x.value)), "popover/anchor") }, + { slug: "accordion-that-animates-its-height", title: "Accordion that animates its height", applies: "<details> folds in the table of contents", signal: d => said(d.filter(x => /::details-content/.test(x.selector) || x.prop === "interpolate-size"), "::details-content / interpolate-size") }, + { slug: "reveal-with-clip-path", title: "Reveal with clip-path", signal: d => said(has(d, /^clip-path$/), "clip-path") }, + { slug: "carousel-on-native-scroll", title: "Carousel on native scroll", signal: d => said(has(d, /^scroll-snap-type$/), "scroll-snap") }, + { slug: "scroll-area-between-a-fixed-header-and-footer", title: "Scroll area between a fixed header and footer", applies: "the navigator and table-of-contents rails", signal: d => said(has(d, /^overscroll-behavior/), "overscroll-behavior") }, + { slug: "styles-that-apply-only-when-a-scroller-overflows", title: "Styles that apply only when a scroller overflows", applies: "wide signatures and tables", signal: d => said(d.filter(x => /scroll-state|animation-timeline/.test(x.prop + x.value) || x.context.some(c => /scroll-state/.test(c))), "scroll-state / scroll-driven") }, + { slug: "anchor-targets-that-clear-a-sticky-header", title: "Anchor targets that clear a sticky header", applies: "member anchors under the sticky top bar", signal: d => said(has(d, /^scroll-(padding|margin)(-block-start|-top)?$/), "scroll-padding/margin") }, + { slug: "no-rubber-band-bounce-on-desktop", title: "No rubber-band bounce on desktop", signal: d => said(has(d, /^overscroll-behavior(-y|-block)?$/, /none/), "overscroll-behavior: none") }, + { slug: "content-clear-of-the-notch", title: "Content clear of the notch", signal: d => said(d.filter(x => /safe-area-inset/.test(x.value)), "env(safe-area-inset-*)") }, +]; + +function checklist(decls: Decl[], sheets: Stylesheet[]): Finding[] { + return ENTRIES.map(e => { + const signal = e.signal(decls); + const status: Status = "review"; + return { + rule: e.slug, name: e.title, owner: "page", status, + evidence: `${signal ?? "no sign of the technique in the stylesheet"}${e.applies ? `. Applies to: ${e.applies}.` : "."}`, + file: sheets[0]?.source, source: entry(e.slug), + }; + }); +} + +function splitValues(value: string): string[] { + const out: string[] = []; + let depth = 0; + let current = ""; + for (const ch of value.trim()) { + if (ch === "(") depth++; + if (ch === ")") depth--; + if (/\s/.test(ch) && depth === 0) { + if (current) out.push(current); + current = ""; + } else current += ch; + } + if (current) out.push(current); + return out; +} + +const allSame = (list: string[]) => list.every(v => v === list[0]); diff --git a/packages/apidocs/scripts/audit/html.ts b/packages/apidocs/scripts/audit/html.ts new file mode 100644 index 0000000..3ef525d --- /dev/null +++ b/packages/apidocs/scripts/audit/html.ts @@ -0,0 +1,187 @@ +/** + * What the agent-readiness checks read from a page's raw HTML, with no + * JavaScript run: its text, headings, head metadata, JSON-LD, landmarks and + * controls. Uses node-html-parser, which is fast enough for multi-megabyte + * type pages. + */ +import { type HTMLElement, type Node, NodeType, parse } from "node-html-parser"; + +export interface Control { + tag: string; + /** The accessible name as far as raw HTML gives one, or "" when it has none. */ + name: string; + native: boolean; + /** A short description for the report: tag, id and class. */ + label: string; +} + +export interface PageFacts { + bytes: number; + lang?: string; + title?: string; + meta: Map<string, string>; + links: { rel: string; type?: string; href: string }[]; + /** Text of the body with scripts, styles and templates removed, whitespace collapsed. */ + bodyText: string; + /** Text of <main>, or of the body when there is no main. */ + mainText: string; + headings: { level: number; text: string }[]; + h1: number; + /** The largest jump between consecutive heading levels (h2 to h4 is 2). */ + maxHeadingSkip: number; + landmarks: { header: number; nav: number; main: number; footer: number }; + jsonLd: { raw: string; value?: unknown; error?: string }[]; + inlineScripts: string[]; + metaRefresh: boolean; + controls: Control[]; + /** Form fields (input, select, textarea) that are not hidden, and whether each has a label. */ + fields: { label: string; labelled: boolean }[]; + /** Text a reader cannot see (aria-label, title, visually hidden, hidden) that reads like an instruction to an agent. */ + injection: string[]; + ids: Set<string>; +} + +const SKIP = new Set(["script", "style", "template", "svg"]); +const INSTRUCTION = /\b(ignore (all |any )?(previous|prior|above) instructions|you are (an? )?(ai|assistant|language model)|as an ai|system prompt|disregard (the|all|previous)|do not tell the user)\b/i; + +export function readPage(html: string): PageFacts { + const root = parse(html, { comment: false, blockTextElements: { script: true, style: true, pre: true, textarea: true } }); + const doc = root.querySelector("html") ?? root; + const head = root.querySelector("head"); + const body = root.querySelector("body") ?? root; + const meta = new Map<string, string>(); + for (const m of head?.querySelectorAll("meta") ?? []) { + const key = m.getAttribute("name") ?? m.getAttribute("property") ?? m.getAttribute("http-equiv"); + if (key) meta.set(key.toLowerCase(), m.getAttribute("content") ?? ""); + } + const links = (head?.querySelectorAll("link") ?? []).map(l => ({ rel: (l.getAttribute("rel") ?? "").toLowerCase(), type: l.getAttribute("type"), href: l.getAttribute("href") ?? "" })); + const jsonLd = root.querySelectorAll('script[type="application/ld+json"]').map(s => { + const raw = s.rawText; + try { + return { raw, value: JSON.parse(raw) as unknown }; + } catch (e) { + return { raw, error: (e as Error).message }; + } + }); + const inlineScripts = root.querySelectorAll("script") + .filter(s => !s.getAttribute("src") && /^(|text\/javascript|module)$/.test(s.getAttribute("type") ?? "")) + .map(s => s.rawText); + const headings = body.querySelectorAll("h1, h2, h3, h4, h5, h6").map(h => ({ level: Number(h.tagName[1]), text: collapse(textOf(h)) })); + let maxHeadingSkip = 0; + for (let i = 1; i < headings.length; i++) maxHeadingSkip = Math.max(maxHeadingSkip, headings[i]!.level - headings[i - 1]!.level); + if (headings[0] && headings[0].level > 1) maxHeadingSkip = Math.max(maxHeadingSkip, headings[0].level - 1); + const main = body.querySelector("main"); + const ids = new Set(root.querySelectorAll("[id]").map(e => e.id)); + const labelFor = new Set(root.querySelectorAll("label[for]").map(l => l.getAttribute("for")!)); + const labelText = new Map(root.querySelectorAll("label[for]").map(l => [l.getAttribute("for")!, collapse(textOf(l))])); + + const nameOf = (el: HTMLElement): string => { + const aria = el.getAttribute("aria-label"); + if (aria?.trim()) return aria.trim(); + const by = el.getAttribute("aria-labelledby"); + if (by) { + const text = by.split(/\s+/).map(id => root.querySelector(`#${cssEscape(id)}`)).map(e => (e ? collapse(textOf(e)) : "")).join(" ").trim(); + if (text) return text; + } + if (el.id && labelText.get(el.id)) return labelText.get(el.id)!; + const text = collapse(textOf(el)); + if (text) return text; + const img = el.querySelector("img[alt]"); + if (img?.getAttribute("alt")?.trim()) return img.getAttribute("alt")!.trim(); + if (el.tagName === "INPUT" && /^(submit|button|reset)$/i.test(el.getAttribute("type") ?? "")) return el.getAttribute("value") ?? ""; + return el.getAttribute("title")?.trim() ?? el.getAttribute("placeholder")?.trim() ?? ""; + }; + + const controls: Control[] = []; + const fields: { label: string; labelled: boolean }[] = []; + const injection: string[] = []; + for (const el of body.querySelectorAll("*")) { + const tag = el.tagName.toLowerCase(); + const role = el.getAttribute("role"); + const hidden = el.hasAttribute("hidden") || el.getAttribute("aria-hidden") === "true"; + const label = describe(el); + for (const attr of ["aria-label", "title", "alt", "aria-description"]) { + const value = el.getAttribute(attr); + if (value && INSTRUCTION.test(value)) injection.push(`${label} [${attr}]: ${value.slice(0, 100)}`); + } + if ((hidden || /\b(visually-hidden|sr-only)\b/.test(el.classNames)) && INSTRUCTION.test(textOf(el))) injection.push(`${label}: ${collapse(textOf(el)).slice(0, 100)}`); + if (hidden) continue; + const nativeControl = (tag === "a" && el.hasAttribute("href")) || tag === "button" || tag === "select" || tag === "textarea" || tag === "summary" || (tag === "input" && el.getAttribute("type") !== "hidden"); + // A focusable <pre> or region (tabindex="0" so keyboards can scroll it) is not a control. + const focusableBox = el.hasAttribute("tabindex") && Number(el.getAttribute("tabindex")) >= 0 && /^(div|span|li|td|p|img)$/.test(tag) && !role; + const ariaControl = !nativeControl && (/^(button|link|tab|menuitem|checkbox|switch|option|radio|combobox|slider)$/.test(role ?? "") || focusableBox || el.hasAttribute("onclick")); + if (nativeControl || ariaControl) controls.push({ tag, name: nameOf(el), native: nativeControl, label }); + if ((tag === "input" && el.getAttribute("type") !== "hidden") || tag === "select" || tag === "textarea") { + const labelled = !!(el.getAttribute("aria-label")?.trim() || el.getAttribute("aria-labelledby") || (el.id && labelFor.has(el.id)) || closest(el, "label")); + fields.push({ label, labelled }); + } + } + + return { + bytes: Buffer.byteLength(html), + lang: doc.getAttribute?.("lang") ?? undefined, + title: root.querySelector("title")?.text, + meta, + links, + bodyText: collapse(textOf(body)), + mainText: collapse(textOf(main ?? body)), + headings, + h1: headings.filter(h => h.level === 1).length, + maxHeadingSkip, + landmarks: { + header: body.querySelectorAll('header, [role="banner"]').filter(e => !closest(e, "main, article, section, aside, nav")).length, + nav: body.querySelectorAll('nav, [role="navigation"]').length, + main: body.querySelectorAll('main, [role="main"]').length, + footer: body.querySelectorAll('footer, [role="contentinfo"]').filter(e => !closest(e, "main, article, section, aside, nav")).length, + }, + jsonLd, + inlineScripts, + metaRefresh: (head?.querySelectorAll("meta") ?? []).some(m => (m.getAttribute("http-equiv") ?? "").toLowerCase() === "refresh"), + controls, + fields, + injection, + ids, + }; +} + +/** Text of a node, skipping scripts, styles, templates and SVG. Block elements end with a space. */ +export function textOf(node: Node): string { + if (node.nodeType === NodeType.TEXT_NODE) return decode(node.rawText); + if (node.nodeType !== NodeType.ELEMENT_NODE) return ""; + const el = node as HTMLElement; + if (SKIP.has(el.rawTagName?.toLowerCase())) return ""; + let out = ""; + for (const child of el.childNodes) out += textOf(child); + return /^(p|div|li|tr|td|th|dd|dt|h[1-6]|pre|section|article|br|table|ul|ol|dl)$/i.test(el.rawTagName ?? "") ? out + " " : out; +} + +function closest(el: HTMLElement, selector: string): HTMLElement | null { + const tags = selector.split(",").map(s => s.trim().toUpperCase()); + for (let p = el.parentNode as HTMLElement | null; p && p.tagName; p = p.parentNode as HTMLElement | null) if (tags.includes(p.tagName)) return p; + return null; +} + +function describe(el: HTMLElement): string { + const cls = el.classNames ? "." + el.classNames.trim().split(/\s+/).join(".") : ""; + return `${el.tagName.toLowerCase()}${el.id ? "#" + el.id : ""}${cls}`; +} + +const collapse = (s: string) => s.replace(/\s+/g, " ").trim(); + +function decode(s: string): string { + return s.replace(/&(#x?[0-9a-f]+|amp|lt|gt|quot|apos|nbsp);/gi, (m, e: string) => { + const k = e.toLowerCase(); + if (k === "amp") return "&"; + if (k === "lt") return "<"; + if (k === "gt") return ">"; + if (k === "quot") return '"'; + if (k === "apos") return "'"; + if (k === "nbsp") return " "; + const code = k.startsWith("#x") ? parseInt(k.slice(2), 16) : parseInt(k.slice(1), 10); + return Number.isFinite(code) ? String.fromCodePoint(code) : m; + }); +} + +function cssEscape(id: string): string { + return id.replace(/([^a-zA-Z0-9_-])/g, "\\$1"); +} diff --git a/packages/apidocs/scripts/audit/lighthouse.ts b/packages/apidocs/scripts/audit/lighthouse.ts new file mode 100644 index 0000000..f089b68 --- /dev/null +++ b/packages/apidocs/scripts/audit/lighthouse.ts @@ -0,0 +1,152 @@ +/** + * Lighthouse, run programmatically against the audit server with the + * Chromium that Playwright installs (the same one test/browser.test.ts uses; + * point PLAYWRIGHT_BROWSERS_PATH at a Playwright browser directory). One + * Chrome serves every run, one page at a time, so performance numbers do not + * compete for the CPU. + */ +import { existsSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import * as chromeLauncher from "chrome-launcher"; +import lighthouse, { type Flags } from "lighthouse"; +import desktopConfig from "lighthouse/core/config/desktop-config.js"; +import { chromium } from "playwright"; +import type { Finding } from "./types"; + +export type FormFactor = "mobile" | "desktop"; + +export interface LighthouseRun { + url: string; + formFactor: FormFactor; + lighthouseVersion: string; + /** Category id to score, 0 to 100. agentic-browsing is Lighthouse's experimental category, scored as a fraction. */ + categories: Record<string, number | null>; + /** Audits that count toward a category score and did not pass, with their category, weight and measured value. */ + failing: Finding[]; + /** Insights and diagnostics that did not pass but carry no weight. */ + advisories: Finding[]; + /** Core metrics, as Lighthouse displays them. */ + metrics: Record<string, string>; +} + +export interface Lighthouse { + run(url: string, formFactor: FormFactor, reportBase: string): Promise<LighthouseRun>; + close(): Promise<void>; +} + +export function chromiumPath(): string { + const path = process.env.CHROME_PATH ?? chromium.executablePath(); + if (!existsSync(path)) { + throw new Error(`No Chromium at ${path}. Set PLAYWRIGHT_BROWSERS_PATH to a Playwright ${chromiumVersionHint()} browser directory, run \`bunx playwright install chromium\`, or set CHROME_PATH.`); + } + return path; +} + +function chromiumVersionHint(): string { + try { + return `1.${require("playwright/package.json").version.split(".")[1]}`; + } catch { + return ""; + } +} + +export async function startLighthouse(): Promise<Lighthouse> { + const probe = Bun.listen({ hostname: "127.0.0.1", port: 0, socket: { data() {} } }); + const port = probe.port; + probe.stop(true); + const chrome = await chromeLauncher.launch({ + port, + chromePath: chromiumPath(), + chromeFlags: ["--headless=new", "--no-sandbox", "--disable-gpu-sandbox"], + logLevel: "silent", + }); + return { + async run(url, formFactor, reportBase) { + const flags: Flags = { port: chrome.port, output: ["json", "html"], logLevel: "error" }; + const result = await lighthouse(url, flags, formFactor === "desktop" ? desktopConfig : undefined); + if (!result) throw new Error(`Lighthouse returned nothing for ${url}`); + const [json, html] = result.report as string[]; + writeFileSync(`${reportBase}.json`, json!); + writeFileSync(`${reportBase}.html`, html!); + return summarize(result.lhr, formFactor); + }, + async close() { + chrome.kill(); + }, + }; +} + +// The LHR type is large; this reads only what the summary needs. +interface Lhr { + finalDisplayedUrl: string; + lighthouseVersion: string; + runtimeError?: { code: string; message: string }; + runWarnings: string[]; + categories: Record<string, { id: string; score: number | null; auditRefs: { id: string; weight: number }[] }>; + audits: Record<string, { id: string; title: string; score: number | null; scoreDisplayMode: string; displayValue?: string; numericValue?: number; numericUnit?: string; details?: { type: string; items?: unknown[] }; metricSavings?: Record<string, number> }>; +} + +function summarize(lhrInput: unknown, formFactor: FormFactor): LighthouseRun { + const lhr = lhrInput as Lhr; + if (lhr.runtimeError) throw new Error(`Lighthouse runtime error ${lhr.runtimeError.code}: ${lhr.runtimeError.message}`); + const categories: Record<string, number | null> = {}; + const failing: Finding[] = []; + const weighted = new Set<string>(); + for (const category of Object.values(lhr.categories)) { + categories[category.id] = category.score === null ? null : Math.round(category.score * 100); + for (const ref of category.auditRefs) { + const audit = lhr.audits[ref.id]; + if (!audit || ref.weight === 0) continue; + weighted.add(ref.id); + if (audit.score === null || audit.score >= 1 || /notApplicable|informative|manual/.test(audit.scoreDisplayMode)) continue; + failing.push({ + rule: audit.id, name: audit.title, owner: ownerOf(audit.id), status: audit.score === 0 ? "fail" : "partial", + score: Math.round(audit.score * 100), max: 100, + evidence: `${category.id} (weight ${ref.weight}): score ${Math.round(audit.score * 100)}${audit.displayValue ? `, ${audit.displayValue}` : ""}${audit.numericValue !== undefined ? ` (${round(audit.numericValue)} ${audit.numericUnit ?? ""})` : ""}`, + where: items(audit.details), + source: `https://developer.chrome.com/docs/lighthouse/`, + }); + } + } + const advisories: Finding[] = []; + for (const audit of Object.values(lhr.audits)) { + if (weighted.has(audit.id) || audit.score === null || audit.score >= 1 || /notApplicable|informative|manual|error/.test(audit.scoreDisplayMode)) continue; + const savings = audit.metricSavings ? Object.entries(audit.metricSavings).filter(([, v]) => v > 0).map(([k, v]) => `${k} -${round(v)}`).join(", ") : ""; + advisories.push({ + rule: audit.id, name: audit.title, owner: ownerOf(audit.id), status: "info", + evidence: `unweighted: score ${Math.round(audit.score * 100)}${audit.displayValue ? `, ${audit.displayValue}` : ""}${savings ? `; metric savings ${savings}` : ""}`, + where: items(audit.details), + }); + } + const metrics: Record<string, string> = {}; + for (const id of ["first-contentful-paint", "largest-contentful-paint", "total-blocking-time", "cumulative-layout-shift", "speed-index", "interactive"]) { + if (lhr.audits[id]?.displayValue) metrics[id] = lhr.audits[id]!.displayValue!; + } + return { url: lhr.finalDisplayedUrl, formFactor, lighthouseVersion: lhr.lighthouseVersion, categories, failing, advisories, metrics }; +} + +/** Audits whose result depends on the server rather than the pages. */ +const HOST_AUDITS = new Set(["uses-text-compression", "uses-long-cache-ttl", "cache-insight", "uses-http2", "modern-http-insight", "redirects", "server-response-time", "document-latency-insight", "is-on-https", "redirects-http", "has-hsts", "csp-xss", "origin-isolation", "clickjacking-mitigation", "http-status-code"]); +const OUTPUT_AUDITS = new Set(["robots-txt", "llms-txt", "ard-schema", "canonical", "hreflang", "structured-data"]); + +function ownerOf(id: string): Finding["owner"] { + return HOST_AUDITS.has(id) ? "host" : OUTPUT_AUDITS.has(id) ? "output" : "page"; +} + +function items(details: { type: string; items?: unknown[] } | undefined): string[] | undefined { + if (!details?.items?.length) return undefined; + return details.items.slice(0, 5).map(item => { + const i = item as Record<string, unknown>; + const node = i.node as { snippet?: string; selector?: string; nodeLabel?: string } | undefined; + if (node) return `${node.selector ?? ""} ${node.snippet ?? node.nodeLabel ?? ""}`.trim().slice(0, 160); + const parts = [i.url, i.source, i.label, i.wastedBytes !== undefined ? `wasted ${round(Number(i.wastedBytes))} B` : undefined, i.cacheLifetimeMs !== undefined ? `ttl ${i.cacheLifetimeMs} ms` : undefined] + .filter(x => x !== undefined && x !== "" && typeof x !== "object"); + return parts.length ? parts.join(" ").slice(0, 160) : JSON.stringify(i).slice(0, 160); + }); +} + +const round = (n: number) => (Math.abs(n) >= 100 ? Math.round(n) : Math.round(n * 100) / 100); + +export function reportPath(dir: string, site: string, page: string, formFactor: FormFactor): string { + return join(dir, "lighthouse", `${site}--${page.replace(/\//g, "_").replace(/\.html$/, "")}--${formFactor}`); +} diff --git a/packages/apidocs/scripts/audit/remote.ts b/packages/apidocs/scripts/audit/remote.ts new file mode 100644 index 0000000..d5ec0c4 --- /dev/null +++ b/packages/apidocs/scripts/audit/remote.ts @@ -0,0 +1,77 @@ +/** + * `bun run audit --url <site>`: audits a site someone else serves, such as the Astro sample app. The site is read + * through its llms.txt (every page's Markdown twin, so every page) and saved into a directory in the static + * renderer's layout, so the checks that read files see what the server sends: each page is fetched at its Astro + * URL (urls.ts) and written as X.html, with its links mapped back to the static form (relative, naming .html + * files), and the Markdown twins and text files are written as they are. Checks that make requests, and + * Lighthouse, go to the server itself at the Astro URLs (Site.urlOf). + */ +import { mkdirSync, statSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { pageUrl } from "../../src/astro/urls"; +import { relative } from "../../src/site"; +import type { Site } from "./types"; + +/** The static file a site-relative Astro path names: "" -> index.html, "x/" -> x/index.html, "x/Y" -> x/Y.html. */ +function staticFile(path: string, pages: Set<string>): string { + if (path === "" || path.endsWith("/")) return `${path}index.html`; + return pages.has(path) ? `${path}.html` : path; +} + +async function text(url: string): Promise<string | undefined> { + const r = await fetch(url, { redirect: "manual" }); + return r.status === 200 ? r.text() : undefined; +} + +/** Fetches the site at `url` (ending with "/") into `dir`, and describes it for the audits. */ +export async function mirrorSite(name: string, url: string, dir: string): Promise<Site> { + const base = new URL(url).pathname; + const llms = await text(`${url}llms.txt`); + if (!llms) throw new Error(`${url}llms.txt did not load: --url takes the base URL of an apidocs site`); + const pages = new Set([...llms.matchAll(/\]\(([^)#]+)\.md\)/g)].map(m => m[1]!).filter(p => !/^[a-z]+:/i.test(p))); + pages.add("index"); + const write = (path: string, body: string) => { + mkdirSync(dirname(join(dir, path)), { recursive: true }); + writeFileSync(join(dir, path), body); + }; + const toStatic = (page: string, href: string) => { + // Absolute URLs (the canonical link, og:url) stay as the server wrote them, as the static build's do. + const full = href; + if (!full.startsWith(base) || full.startsWith("//")) return href; + const cut = full.search(/[?#]/); + const path = decodeURI(cut < 0 ? full.slice(base.length) : full.slice(base.length, cut)); + const file = staticFile(path, pages); + const link = file.endsWith(".html") ? relative(page, file.slice(0, -".html".length), ".html") : relative(page, file, ""); + return link + (cut < 0 ? "" : full.slice(cut)); + }; + for (const page of pages) { + const html = await text(url + pageUrl(page)); + if (!html) throw new Error(`${url}${pageUrl(page)} did not load`); + write(`${page}.html`, html.replace(/(\s(?:href|src)=")([^"]*)(")/g, (_, a: string, href: string, b: string) => a + toStatic(page, href.replace(/&/g, "&")).replace(/&/g, "&") + b)); + const md = await text(`${url}${page}.md`); + if (md !== undefined) write(`${page}.md`, md); + } + for (const file of ["llms.txt", "llms-full.txt", "api.json", "element-list", "sitemap.xml", "robots.txt"]) { + const body = await text(url + file); + if (body !== undefined) write(file, body); + } + const all = [...pages].map(p => `${p}.html`); + const size = (f: string) => statSync(join(dir, f)).size; + const types = all.filter(f => !f.endsWith("index.html") && !f.startsWith("guides/") && !["packages.html", "types.html", "index-all.html", "deprecated.html"].includes(f)); + const packages = all.filter(f => f.endsWith("/index.html")).sort((a, b) => size(b) - size(a)); + const bySize = [...types].sort((a, b) => size(a) - size(b)); + return { + name, + dir, + url, + urlOf: page => url + pageUrl(page.replace(/\.html$/, "")), + pages: { + overview: "index.html", + package: packages[0] ?? "index.html", + // The smallest type page with real content, and the largest, as representativePages chooses them. + smallType: bySize.find(f => size(f) > 4000) ?? bySize[0] ?? "index.html", + largestType: bySize.at(-1) ?? "index.html", + all, + }, + }; +} diff --git a/packages/apidocs/scripts/audit/server.ts b/packages/apidocs/scripts/audit/server.ts new file mode 100644 index 0000000..d81251b --- /dev/null +++ b/packages/apidocs/scripts/audit/server.ts @@ -0,0 +1,150 @@ +/** + * A static server for the audits, configured as a good static host would be, + * so that Lighthouse scores the pages rather than a bare development server: + * + * - brotli or gzip for text responses, chosen from Accept-Encoding; + * - Cache-Control: a year for assets/, revalidate for everything else; strong ETags and 304s; + * - a real 404 status, with the site's 404.html (or 404.md for Accept: text/markdown) when it has one; + * - correct Content-Type for .md, .txt, .xml, .json, .woff2 and the rest. + * + * The "agent" profile adds what a host can do for agents on top of static + * files: Accept: text/markdown negotiation onto each page's .md twin with + * Vary: Accept, and RFC 8288 Link headers for the Markdown alternate, + * llms.txt and sitemap.xml. It needs nothing the renderer does not already + * write. It does not serve HTTP/2 (Bun.serve speaks HTTP/1.1 without TLS). + */ +import { createHash } from "node:crypto"; +import { existsSync, readFileSync, statSync } from "node:fs"; +import { extname, join, resolve } from "node:path"; +import { brotliCompressSync, constants, gzipSync } from "node:zlib"; + +export type HostProfile = "static" | "agent"; + +export const CONTENT_TYPES: Record<string, string> = { + ".html": "text/html; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".mjs": "text/javascript; charset=utf-8", + ".json": "application/json; charset=utf-8", + ".md": "text/markdown; charset=utf-8", + ".txt": "text/plain; charset=utf-8", + ".xml": "application/xml; charset=utf-8", + ".svg": "image/svg+xml", + ".woff2": "font/woff2", + ".png": "image/png", + ".ico": "image/x-icon", +}; + +/** element-list and other extensionless files are plain text. */ +const typeOf = (file: string) => CONTENT_TYPES[extname(file)] ?? "text/plain; charset=utf-8"; +const compressible = (type: string) => /^(text\/|application\/(json|xml|javascript)|image\/svg)/.test(type); + +export interface AuditServer { + url: string; + port: number; + stop(): void; +} + +interface Body { + bytes: Uint8Array; + etag: string; + br?: Uint8Array; + gzip?: Uint8Array; +} + +/** Starts a server on a free port. The directory may be empty or missing at start: files are read per request. */ +export function serve(dir: string, profile: HostProfile = "static"): AuditServer { + const root = resolve(dir); + const cache = new Map<string, { mtime: number; body: Body }>(); + const load = (file: string): Body => { + const mtime = statSync(file).mtimeMs; + const hit = cache.get(file); + if (hit && hit.mtime === mtime) return hit.body; + const bytes = new Uint8Array(readFileSync(file)); + const body: Body = { bytes, etag: `"${createHash("sha1").update(bytes).digest("base64url")}"` }; + cache.set(file, { mtime, body }); + return body; + }; + const encode = (body: Body, encoding: "br" | "gzip") => { + if (encoding === "br") return (body.br ??= new Uint8Array(brotliCompressSync(body.bytes, { params: { [constants.BROTLI_PARAM_QUALITY]: 9 } }))); + return (body.gzip ??= new Uint8Array(gzipSync(body.bytes, { level: 9 }))); + }; + const find = (pathname: string): string | undefined => { + let path: string; + try { + path = decodeURIComponent(pathname); + } catch { + return undefined; + } + const file = resolve(root, "." + path); + if (file !== root && !file.startsWith(root + "/")) return undefined; + if (existsSync(file) && statSync(file).isDirectory()) return existsSync(join(file, "index.html")) ? join(file, "index.html") : undefined; + return existsSync(file) ? file : undefined; + }; + + const server = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + fetch(request) { + const url = new URL(request.url); + const accept = request.headers.get("accept") ?? ""; + const wantsMarkdown = profile === "agent" && prefersMarkdown(accept); + const headers = new Headers(); + let status = 200; + let file = find(url.pathname); + if (request.method !== "GET" && request.method !== "HEAD") return new Response("Method not allowed", { status: 405, headers: { allow: "GET, HEAD" } }); + if (!file) { + status = 404; + const notFound = wantsMarkdown && existsSync(join(root, "404.md")) ? join(root, "404.md") : existsSync(join(root, "404.html")) ? join(root, "404.html") : undefined; + if (!notFound) return new Response("Not found\n", { status: 404, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } }); + file = notFound; + } + if (profile === "agent" && file.endsWith(".html") && status === 200) { + const twin = file.replace(/\.html$/, ".md"); + const twinUrl = url.pathname.endsWith("/") ? "index.md" : url.pathname.split("/").pop()!.replace(/\.html$/, ".md"); + headers.set("vary", "Accept, Accept-Encoding"); + if (existsSync(twin)) { + const links = [`<${twinUrl}>; rel="alternate"; type="text/markdown"`, `</llms.txt>; rel="describedby"; type="text/plain"`]; + if (existsSync(join(root, "sitemap.xml"))) links.push(`</sitemap.xml>; rel="sitemap"; type="application/xml"`); + headers.set("link", links.join(", ")); + if (wantsMarkdown) file = twin; + } + } + const type = typeOf(file); + const body = load(file); + headers.set("content-type", type); + headers.set("etag", body.etag); + headers.set("x-content-type-options", "nosniff"); + if (!headers.has("vary")) headers.set("vary", "Accept-Encoding"); + const relativePath = file.slice(root.length + 1); + headers.set("cache-control", status !== 200 ? "no-store" : relativePath.startsWith("assets/") ? "public, max-age=31536000" : "public, max-age=0, must-revalidate"); + if (status === 200 && request.headers.get("if-none-match") === body.etag) return new Response(null, { status: 304, headers }); + let bytes = body.bytes; + if (compressible(type) && bytes.length > 512) { + const accepted = request.headers.get("accept-encoding") ?? ""; + const encoding = /\bbr\b/.test(accepted) ? "br" : /\bgzip\b/.test(accepted) ? "gzip" : undefined; + if (encoding) { + bytes = encode(body, encoding); + headers.set("content-encoding", encoding); + } + } + return new Response(request.method === "HEAD" ? null : (bytes as unknown as BodyInit), { status, headers }); + }, + }); + return { url: `http://127.0.0.1:${server.port}/`, port: server.port!, stop: () => server.stop(true) }; +} + +/** Whether an Accept header ranks text/markdown at or above text/html. */ +export function prefersMarkdown(accept: string): boolean { + const q = (type: string) => { + for (const part of accept.split(",")) { + const [media, ...params] = part.trim().split(";").map(s => s.trim()); + if (media?.toLowerCase() !== type) continue; + const qp = params.find(p => p.startsWith("q=")); + return qp ? Number(qp.slice(2)) : 1; + } + return -1; + }; + const md = q("text/markdown"); + return md > 0 && md >= q("text/html"); +} diff --git a/packages/apidocs/scripts/audit/types.ts b/packages/apidocs/scripts/audit/types.ts new file mode 100644 index 0000000..a67d3a7 --- /dev/null +++ b/packages/apidocs/scripts/audit/types.ts @@ -0,0 +1,76 @@ +/** + * Shared shapes for the audits: what a check found, who owns the fix, and how + * a run reports a score against its threshold. + */ + +/** + * Who has to change for a finding to go away. + * - page: the markup, CSS or client script of the pages (src/components, src/pages.tsx, src/styles, src/client). + * - output: the set of files the renderer writes (src/render.tsx: llms.txt, sitemap.xml, robots.txt, JSON-LD content). + * - host: the web server or CDN that serves the files (status codes, headers, compression, content negotiation). + */ +export type Owner = "page" | "output" | "host"; + +export type Status = "pass" | "partial" | "fail" | "na" | "review" | "info"; + +export interface Finding { + /** The rule's stable id, such as "content-no-js" or "logical-properties". */ + rule: string; + /** The rule's name for people. */ + name: string; + status: Status; + owner: Owner; + /** Points earned and available, where the audit scores the rule. */ + score?: number; + max?: number; + /** What was measured, with numbers. */ + evidence: string; + /** Pages or selectors the evidence came from, capped for the table. */ + where?: string[]; + /** The source file most likely to need the change. */ + file?: string; + /** What to change. */ + fix?: string; + /** Where the rule comes from. */ + source?: string; +} + +export interface AuditResult { + audit: "lighthouse" | "agentic" | "css"; + /** The site and page (or "site") audited, such as "java-elide index.html (mobile)". */ + target: string; + /** 0 to 100, or undefined for a report with no score. */ + score?: number; + threshold: number; + /** Short failure labels for the table. */ + failures: string[]; + findings: Finding[]; + /** The path of the full report, relative to the report directory. */ + report?: string; +} + +/** A built site under the audit server. */ +export interface Site { + /** "java-elide", "kotlin-neutral", "model-elide", ... */ + name: string; + /** Absolute directory of the files. */ + dir: string; + /** The site's URL under the audit server, with a trailing slash. */ + url: string; + /** Pages to audit closely, as paths relative to the site root. */ + pages: RepresentativePages; + /** + * The URL a page (a path in dir, such as "index.html") is served at. Defaults to url + page; a site mirrored from + * a server whose URLs differ from its file names (the Astro form, `--url`) maps them back. + */ + urlOf?: (page: string) => string; +} + +export interface RepresentativePages { + overview: string; + package: string; + smallType: string; + largestType: string; + /** Every HTML page, for the checks that read all of them. */ + all: string[]; +} diff --git a/packages/apidocs/scripts/dev.ts b/packages/apidocs/scripts/dev.ts new file mode 100644 index 0000000..3dd0a84 --- /dev/null +++ b/packages/apidocs/scripts/dev.ts @@ -0,0 +1,239 @@ +/** + * The development loop: a Vite server that renders the sample models (or a + * real api.json) with the production render() and reloads the page when a + * component, the stylesheet, a theme, a sample or the model file changes. + * + * bun run dev [--port 5180] [--model path/to/api.json] [--guides path/to/suite] [--no-open] + * + * --guides serves a Markdown suite through the importer (src/import/markdown.ts) as a guides-only site; editing a + * .md file or an image in it reloads the page. The Markdown sample suite (samples/guides) is always available. + * + * Pages are served under /site/<model>/<preset>/; / is a dev-only shell with + * controls for the theme preset, light or dark, the model and the viewport + * width. The shell and the module script that runs the islands in dev are not + * part of any output: `bun run sample` builds what the doclet writes. + */ +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createServer, type ViteDevServer } from "vite"; + +const args = process.argv.slice(2); +const flag = (name: string) => { + const at = args.indexOf(`--${name}`); + return at < 0 ? undefined : args[at + 1]; +}; +const port = Number(flag("port") ?? 5180); +const host = flag("host") ?? "127.0.0.1"; +const modelPath = flag("model") ? resolve(process.env.INIT_CWD ?? process.cwd(), flag("model")!) : undefined; +const guidesPath = flag("guides") ? resolve(process.env.INIT_CWD ?? process.cwd(), flag("guides")!) : undefined; +const open = !args.includes("--no-open"); + +const root = fileURLToPath(new URL("..", import.meta.url)); +const sampleSuite = resolve(root, "samples/guides"); +/** The Markdown suites the dev bar offers: the sample, and the --guides directory. */ +const suites: Record<string, string> = { markdown: sampleSuite, ...(guidesPath ? { guides: guidesPath } : {}) }; +/** Files a suite's pages show (images), by model and path in the site: copied from the suite, not rendered. */ +const suiteFiles = new Map<string, Map<string, Uint8Array>>(); +const require = createRequire(import.meta.url); +type Output = Record<string, string | { asset: string }>; +const cache = new Map<string, Output>(); + +async function site(server: ViteDevServer, model: string, preset: string): Promise<Output> { + const key = `${model}/${preset}`; + const cached = cache.get(key); + if (cached) return cached; + const { render } = await server.ssrLoadModule("/src/render.tsx"); + const theme = { extends: preset === "elide" ? "elide" : "neutral" }; + if (suites[model]) { + const { suiteSite } = await server.ssrLoadModule("/src/import/suite.ts"); + const { formatDiagnostic } = await server.ssrLoadModule("/src/import/markdown.ts"); + const started = performance.now(); + const built = suiteSite(suites[model], { + id: model, + title: model === "markdown" ? "Geo user guide" : (guidesPath!.split("/").filter(Boolean).pop() ?? "Guides"), + theme, + includeDrafts: args.includes("--include-drafts"), + // The sample suite links to a sibling suite and an API reference; both live on example.com. + links: [{ prefix: "../developer/", target: "https://example.com/developer/" }, { prefix: "../api/", target: "https://example.com/api/" }], + }); + for (const d of built.diagnostics) console.log(` ${formatDiagnostic(d, `${suites[model]}/`)}`); + suiteFiles.set(key, new Map(built.copies.map((c: { to: string; data: Uint8Array }) => [c.to, c.data]))); + console.log(` rendered ${model} with ${preset}: ${Object.keys(built.output).length} files in ${Math.round(performance.now() - started)} ms`); + cache.set(key, built.output); + return built.output; + } + let input: unknown; + if (model === "model") { + if (!modelPath) throw new Error("Start the server with --model <api.json> to browse a real model"); + input = readFileSync(modelPath, "utf8"); + } else { + const { samples } = await server.ssrLoadModule("/samples/index.ts"); + input = samples[model]; + if (!input) throw new Error(`No sample named ${model}`); + } + const started = performance.now(); + const out = render(input, theme) as Output; + console.log(` rendered ${model} with ${preset}: ${Object.keys(out).length} files in ${Math.round(performance.now() - started)} ms`); + cache.set(key, out); + return out; +} + +/** The dev-only replacement for the deferred client bundle: the islands as a module, plus Vite's reload client. */ +const DEV_SCRIPTS = '<script type="module" src="/@vite/client"></script><script type="module" src="/src/client/islands.tsx"></script>'; + +function asset(name: string): { body: Buffer | string; type: string } { + if (name === "apidocs.css") return { body: readFileSync(resolve(root, "src/styles/apidocs.css"), "utf8"), type: "text/css" }; + if (name.startsWith("fonts/")) { + const file = name.slice("fonts/".length); + return { body: readFileSync(require.resolve(`@fontsource-variable/${file.replace(/-latin-.*$/, "")}/files/${file}`)), type: "font/woff2" }; + } + throw new Error(`No asset ${name}`); +} + +const TYPES: Record<string, string> = { + html: "text/html; charset=utf-8", md: "text/markdown; charset=utf-8", txt: "text/plain; charset=utf-8", + js: "text/javascript; charset=utf-8", css: "text/css; charset=utf-8", json: "application/json", + svg: "image/svg+xml", xml: "application/xml", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", + webp: "image/webp", +}; + +function shell(): string { + const models = ["java", "kotlin", "markdown", ...(guidesPath ? ["guides"] : []), ...(modelPath ? ["model"] : [])]; + const label = (m: string) => (m === "model" ? modelPath : m === "guides" ? `${guidesPath} (Markdown)` : m === "markdown" ? "Markdown sample suite" : `${m} sample`); + return `<!doctype html> +<html lang="en"><head><meta charset="utf-8"><title>apidocs dev + +
+ @elide/apidocs dev + + + + + + open page +
+
+ +`; +} + +const server = await createServer({ + root, + configFile: false, + appType: "custom", + oxc: { jsx: { runtime: "automatic", importSource: "preact" } }, + resolve: { dedupe: ["preact"] }, + server: { port, host, strictPort: true, open: open ? "/" : false }, + plugins: [{ + name: "apidocs-dev", + configureServer(dev) { + if (modelPath) dev.watcher.add(modelPath); + if (guidesPath) dev.watcher.add(guidesPath); + const reload = (file: string) => { + if (file === modelPath || /\/(src|samples)\//.test(file) || (guidesPath && file.startsWith(`${guidesPath}/`))) { + cache.clear(); + dev.moduleGraph.invalidateAll(); + dev.ws.send({ type: "full-reload" }); + } + }; + // A new or removed page changes the navigator of every page, so they reload too. + for (const event of ["change", "add", "unlink"] as const) dev.watcher.on(event, reload); + dev.middlewares.use(async (req, res, next) => { + const url = new URL(req.url ?? "/", "http://localhost"); + if (url.pathname === "/") { + res.setHeader("content-type", TYPES.html!); + res.end(shell()); + return; + } + const match = /^\/site\/([^/]+)\/([^/]+)\/(.*)$/.exec(url.pathname); + if (!match) return next(); + const [, model, preset, rawPath] = match; + const path = decodeURIComponent(rawPath || "index.html"); + try { + const out = await site(dev, model!, preset!); + const file = out[path]; + const copied = suiteFiles.get(`${model}/${preset}`)?.get(path); + if (file === undefined && copied) { + res.setHeader("content-type", TYPES[path.slice(path.lastIndexOf(".") + 1).toLowerCase()] ?? "application/octet-stream"); + res.setHeader("x-content-type-options", "nosniff"); + res.end(copied); + return; + } + if (file === undefined) { + res.statusCode = 404; + res.end(`Not in the rendered site: ${path}`); + return; + } + const ext = path.slice(path.lastIndexOf(".") + 1); + if (typeof file === "string") { + let body = file; + if (ext === "html") { + body = url.searchParams.has("nojs") + ? body.replace(/]*>[\s\S]*?<\/script>/g, m => (m.includes("ld+json") ? m : "")) + : body.replace(/ + + diff --git a/packages/apidocs/src/astro/Route.astro b/packages/apidocs/src/astro/Route.astro new file mode 100644 index 0000000..90b4406 --- /dev/null +++ b/packages/apidocs/src/astro/Route.astro @@ -0,0 +1,55 @@ +--- +/** + * The route apidocs() injects for each site: `${base}[...path]`. It resolves the path, redirects the static + * form to the canonical one, serves text files, and renders pages with , adding the version menu + * and notice as server islands when the site has a version. + */ +import { sites, versions } from "virtual:@elide/apidocs/sites"; +import ApidocsPage from "./ApidocsPage.astro"; +import { resolvePage } from "./resolve"; +import { linkHeader, notFound, prefersMarkdown } from "./http"; +import { renderText } from "./text"; +import VersionIsland from "./VersionIsland.astro"; +import VersionNotice from "./VersionNotice.astro"; +import VersionSelect from "./VersionSelect.astro"; +import { latestRelease } from "./versions"; + +const pathname = Astro.url.pathname; +const site = sites.filter(s => pathname.startsWith(s.base) || `${pathname}/` === s.base).sort((a, b) => b.base.length - a.base.length)[0]; +if (!site) return new Response("Not found", { status: 404 }); +if (`${pathname}/` === site.base) return Astro.redirect(site.base + Astro.url.search, 301); +const path = pathname.slice(site.base.length); +// The site's address is known from the request, so sitemap.xml can list absolute URLs. +const theme = { ...site.theme, baseUrl: site.theme.baseUrl ?? new URL(site.base, Astro.site ?? Astro.url.origin).href }; +const resolved = resolvePage(site.model, path, theme); +if (resolved.kind === "redirect") return Astro.redirect(site.base + resolved.to + Astro.url.search, 301); +if (resolved.kind === "markdown" || resolved.kind === "file") { + const text = renderText(site.model, resolved.kind === "markdown" ? `${resolved.page}.md` : resolved.name, theme); + if (!text) return new Response("Not found", { status: 404 }); + return new Response(text.body, { headers: { "content-type": text.contentType } }); +} +const accept = Astro.request.headers.get("accept"); +if (resolved.kind === "missing") return notFound(site.base, site.model.module.name, accept); +const page = resolved.page; +// One URL, two forms: a request that prefers Markdown gets the page's twin. +if (prefersMarkdown(accept)) { + const text = renderText(site.model, `${page}.md`, theme)!; + return new Response(text.body, { headers: { "content-type": text.contentType, vary: "Accept", link: linkHeader(site.base, page) } }); +} +Astro.response.headers.set("vary", "Accept"); +Astro.response.headers.set("link", linkHeader(site.base, page)); +const here = site.version ? versions.find(v => v.id === site.version) : undefined; +const latest = latestRelease(versions); +--- + + {here && ( + + + + )} + {here && latest && latest.id !== here.id && ( + + + + )} + diff --git a/packages/apidocs/src/astro/Search.tsx b/packages/apidocs/src/astro/Search.tsx new file mode 100644 index 0000000..a2e6aee --- /dev/null +++ b/packages/apidocs/src/astro/Search.tsx @@ -0,0 +1,105 @@ +/** + * Search, as an Astro client island (client:idle) in the top bar. The server renders the same markup as the + * static page's search field; once hydrated, it loads the site's index (assets/search-index.json, paths already + * in the Astro form) on first focus or keystroke, and opens results through the client router. The top bar is + * kept across navigations within a site, so the island hydrates once per site, not once per page. + */ +import { navigate } from "astro:transitions/client"; +import { useEffect, useRef, useState } from "preact/hooks"; +import { isShortcut, Results, siteRoot } from "../client/behaviors"; +import { type Entry, search } from "../client/search"; + +/** Each site's index, by URL: the client router can move between sites (versions) without a page load. */ +const indexes = new Map>(); + +function loadIndex(root: string): Promise { + const url = `${root}assets/search-index.json`; + let index = indexes.get(url); + if (!index) { + index = fetch(url).then(r => (r.ok ? (r.json() as Promise) : [])).catch(() => []); + indexes.set(url, index); + } + return index; +} + +export default function Search({ api }: { api: boolean }) { + const [query, setQuery] = useState(""); + const [items, setItems] = useState([]); + const [active, setActive] = useState(0); + const [open, setOpen] = useState(false); + const box = useRef(null); + const input = useRef(null); + const root = typeof document === "undefined" ? "" : siteRoot(); + + const run = async (value: string) => { + setQuery(value); + const entries = await loadIndex(siteRoot()); + setItems(search(entries, value)); + setActive(0); + setOpen(value.trim().length > 0); + }; + + useEffect(() => { + // Text typed before hydration searches at once. + if (input.current?.value) void run(input.current.value); + const controller = new AbortController(); + const { signal } = controller; + document.addEventListener("click", event => { + if (!box.current?.contains(event.target as Node)) setOpen(false); + }, { signal }); + document.addEventListener("keydown", event => { + if (isShortcut(event, "/")) { + event.preventDefault(); + input.current?.focus(); + } + }, { signal }); + // A new page starts with an empty search, as a full page load would. + document.addEventListener("astro:after-swap", () => { + setQuery(""); + setItems([]); + setOpen(false); + }, { signal }); + return () => controller.abort(); + }, []); + + useEffect(() => { + if (open) document.getElementById(`apidocs-result-${active}`)?.scrollIntoView({ block: "nearest" }); + }, [open, active]); + + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + if (!items.length) return; + event.preventDefault(); + setActive((active + (event.key === "ArrowDown" ? 1 : items.length - 1)) % items.length); + } else if (event.key === "Enter") { + const item = items[active]; + if (item) { + event.preventDefault(); + setOpen(false); + void navigate(siteRoot() + item[2]); + } + } else if (event.key === "Escape") { + setQuery(""); + setItems([]); + setOpen(false); + input.current?.blur(); + } + }; + + return ( + + + void loadIndex(siteRoot())} + onInput={event => void run((event.target as HTMLInputElement).value)} + onKeyDown={onKeyDown} /> + + + + ); +} diff --git a/packages/apidocs/src/astro/VersionIsland.astro b/packages/apidocs/src/astro/VersionIsland.astro new file mode 100644 index 0000000..717b651 --- /dev/null +++ b/packages/apidocs/src/astro/VersionIsland.astro @@ -0,0 +1,24 @@ +--- +/** + * The version menu or notice as a server island (render it with server:defer). It reads the newest versions + * with the app's loadVersions on each request, so a cached page shows a current list; the response may be + * cached briefly. Its fallback should be the same part rendered from the versions the page was rendered with. + * + * This one reads versions through apidocs(); an app without the integration writes its own island the same + * way, loading versions.json from wherever it keeps it (README, "Server islands"). + */ +import { loadVersions } from "virtual:@elide/apidocs/sites"; +import VersionNotice from "./VersionNotice.astro"; +import VersionSelect from "./VersionSelect.astro"; + +interface Props { + part: "select" | "notice"; + current: string; + path?: string; +} + +const { part, current, path } = Astro.props; +const versions = await loadVersions(Astro.request); +Astro.response.headers.set("cache-control", "public, max-age=60, stale-while-revalidate=600"); +--- +{part === "select" ? : } diff --git a/packages/apidocs/src/astro/VersionNotice.astro b/packages/apidocs/src/astro/VersionNotice.astro new file mode 100644 index 0000000..98b3588 --- /dev/null +++ b/packages/apidocs/src/astro/VersionNotice.astro @@ -0,0 +1,28 @@ +--- +/** + * One line above the page for a version that is not the latest release: which version this is, and a link to + * the same page in the latest release. Always one line of the same height, whatever it says, so a server + * island can render it over a fallback of itself without moving the page. + */ +import { latestRelease, type Version, versionLabel } from "./versions"; + +interface Props { + versions: Version[]; + current: string; + /** The page's path under its site's base. */ + path?: string; +} + +const { versions, current, path = "" } = Astro.props; +const here = versions.find(v => v.id === current); +const latest = latestRelease(versions); +const label = here ? versionLabel(here) : current; +const kind = here?.channel === "development" ? "the development version" : here?.channel === "prerelease" ? "a prerelease" : "an older release"; +--- +

+ {latest && latest.id !== current ? ( + You are reading {label}, {kind}. The latest release is {versionLabel(latest)}. + ) : ( + You are reading {label}, the latest release. + )} +

diff --git a/packages/apidocs/src/astro/VersionSelect.astro b/packages/apidocs/src/astro/VersionSelect.astro new file mode 100644 index 0000000..4a99b6d --- /dev/null +++ b/packages/apidocs/src/astro/VersionSelect.astro @@ -0,0 +1,41 @@ +--- +/** + * A compact version menu for the top bar: the current version, and the same page in each other version. A + * disclosure of plain links, so it works without JavaScript and the client router follows its links. The + * Astro client keeps each link pointing at the page being read (versionMenus in client.ts). + * + * Render it inside a server island so a cached page shows the newest versions.json, with a fallback that is + * this same component rendered from the versions known when the page was rendered: both draw the same closed + * box (the current version's label), so the island replaces it without moving anything. + */ +import { type Version, versionLabel } from "./versions"; + +interface Props { + versions: Version[]; + /** The id of the version this page belongs to. */ + current: string; + /** The page's path under its site's base, so each link opens the same page in that version. */ + path?: string; +} + +const { versions, current, path = "" } = Astro.props; +const here = versions.find(v => v.id === current); +const label = here ? versionLabel(here) : current; +const note = (v: Version) => (v.latest ? "latest" : v.channel === "development" ? "development" : v.channel === "prerelease" ? "prerelease" : undefined); +--- +
+ + {label} + + + +
diff --git a/packages/apidocs/src/astro/apidocs-astro.css b/packages/apidocs/src/astro/apidocs-astro.css new file mode 100644 index 0000000..9ab41b8 --- /dev/null +++ b/packages/apidocs/src/astro/apidocs-astro.css @@ -0,0 +1,60 @@ +/* + * What Astro pages add to apidocs.css: they navigate with Astro's client router, and they can carry a version + * menu and a version notice. Loaded after apidocs.css. + */ + +/* The client router runs page transitions itself (with the same ::view-transition rules apidocs.css gives the + static pages), so the browser's cross-document transitions stay off here: the last @view-transition rule wins. + A full page load between two Astro pages (a reload, data-astro-reload) is then a plain load, never a second + transition on top of the router's. */ +@view-transition { navigation: none; } + +@media (prefers-reduced-motion: reduce) { + ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; } +} + +/* ---- The version menu, in the top bar where the module's version is ---- */ + +.version-menu { + position: relative; flex: none; display: inline-block; + color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); line-height: 1; + user-select: none; -webkit-user-select: none; +} +.version-current { + display: inline-flex; align-items: center; gap: 4px; block-size: 26px; padding-inline: 8px 6px; + border: 1px solid var(--apidocs-rule-strong); border-radius: var(--apidocs-radius); + white-space: nowrap; list-style: none; cursor: pointer; +} +.version-current::-webkit-details-marker { display: none; } +.version-current .icon { vertical-align: 0; } +.version-fallback .version-current { cursor: default; } +.version-menu[open] > .version-current { color: var(--apidocs-fg); background: var(--apidocs-subtle); } +@media (hover: hover) and (pointer: fine) { + details.version-menu > .version-current:hover { color: var(--apidocs-fg); background: var(--apidocs-subtle); } + .version-list a:hover { background: var(--apidocs-subtle); text-decoration: none; } +} +details.version-menu > .version-current:active, .version-list a:active { background: var(--apidocs-subtle); } +.version-list { + position: absolute; inset-inline-start: -1px; inset-block-start: calc(100% + 6px); z-index: 12; + min-inline-size: 12rem; margin: 0; padding: 4px; list-style: none; + background: var(--apidocs-surface); border: 1px solid var(--apidocs-rule-strong); + border-radius: calc(var(--apidocs-radius) + 2px); box-shadow: 0 12px 32px -12px rgb(0 0 0 / 0.28); + line-height: 1.5; +} +.version-list a { + display: flex; align-items: baseline; justify-content: space-between; gap: 20px; + padding: 5px 10px; border-radius: 4px; color: var(--apidocs-fg); +} +.version-list a[aria-current="page"] { color: var(--apidocs-accent); font-weight: 600; } +.version-list small { color: var(--apidocs-faint); font-size: var(--apidocs-size-xs); font-weight: 400; } + +/* ---- The version notice: one line above the page, the same height whatever it says ---- */ + +.version-notice { + display: flex; align-items: center; block-size: 34px; margin-block: 0 14px; padding-inline: 12px; + border-radius: var(--apidocs-radius); background: var(--apidocs-accent-soft); + color: var(--apidocs-muted); font-size: var(--apidocs-size-sm); white-space: nowrap; overflow: clip; +} +.version-notice > span { min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; } +.version-notice .version { color: var(--apidocs-fg); } +.version-notice a .version { color: inherit; } diff --git a/packages/apidocs/src/astro/client.ts b/packages/apidocs/src/astro/client.ts new file mode 100644 index 0000000..6cd9c82 --- /dev/null +++ b/packages/apidocs/src/astro/client.ts @@ -0,0 +1,120 @@ +/** + * The Astro pages' client script: a module Astro bundles once and runs once. The client router swaps pages + * without a document load, so each behavior starts on astro:page-load (which also fires for the first page) + * and stops on astro:before-swap: one AbortController per page owns every listener and observer. + * + * Around the swap it also does what a full page load would have done: + * - carries the theme choice and the boot script's marks (data-js, data-emoji) to the new page's , whose + * attributes the router replaces; + * - updates the top bar and the navigator, which the router keeps (transition:persist) so the navigator keeps + * its scroll position and filter text: the index links' current page, and the navigator's rows for the new + * page, leaving the filter field in place; + * - runs the load bar from astro:before-preparation and finishes it on arrival. + */ +import { pageBehaviors, saveNavigatorScroll, siteRoot } from "../client/behaviors"; +import { pathUnder } from "./versions"; + +/** The attributes the page's own scripts set, which the router's swap would drop. */ +const CARRIED = ["data-js", "data-emoji", "data-theme", "data-file"]; +const PERSIST = "data-astro-transition-persist"; + +let page: AbortController | undefined; + +function start() { + page?.abort(); + page = new AbortController(); + pageBehaviors(page.signal); + versionMenus(page.signal); +} + +/** Keeps each version menu's links on the page being read: the top bar, and the menu in it, outlive the page. */ +function versionMenus(signal: AbortSignal) { + const update = (menu: Element) => { + const path = pathUnder(location.pathname, siteRoot()); + for (const link of menu.querySelectorAll("a[data-version-base]")) link.href = link.dataset.versionBase! + path; + }; + for (const menu of document.querySelectorAll("[data-version-menu], .version-notice")) update(menu); + // toggle does not bubble; a capturing listener on the document sees it for menus that server islands add later. + document.addEventListener("toggle", event => { + const menu = event.target as HTMLDetailsElement; + if (menu.matches?.("details[data-version-menu]") && menu.open) update(menu); + }, { capture: true, signal }); +} + +/** Moves a persisted element's page-specific content from the new page into the kept element. */ +function refreshPersisted(newDocument: Document) { + for (const kept of document.querySelectorAll(`[${PERSIST}]`)) { + const next = newDocument.querySelector(`[${PERSIST}="${CSS.escape(kept.getAttribute(PERSIST)!)}"]`); + if (!next) continue; + if (kept.matches(".topbar")) { + const nav = kept.querySelector(".topbar-nav"); + const fresh = next.querySelector(".topbar-nav"); + if (nav && fresh) nav.replaceWith(document.importNode(fresh, true)); + } else if (kept.matches(".sidebar")) { + refreshNavigator(kept, next); + } + } +} + +function refreshNavigator(kept: HTMLElement, next: HTMLElement) { + const focused = kept.contains(document.activeElement) ? (document.activeElement as HTMLAnchorElement).getAttribute?.("href") : null; + const top = kept.scrollTop; + for (const child of [...kept.children]) if (!child.matches(".nav-filter")) child.remove(); + for (const child of [...next.children]) if (!child.matches(".nav-filter")) kept.append(document.importNode(child, true)); + kept.scrollTop = top; + // Keyboard users who chose a row stay on it. + if (focused) kept.querySelector(`a[href="${CSS.escape(focused)}"]`)?.focus({ preventScroll: true }); + // The current page's row comes into view if it is out of it, as on a first load. + const current = kept.querySelector('[aria-current="page"]'); + if (current && (current.offsetTop < kept.scrollTop || current.offsetTop > kept.scrollTop + kept.clientHeight - 40)) { + kept.scrollTop = Math.max(0, current.offsetTop - kept.clientHeight / 3); + } + kept.dataset.scrollTop = String(kept.scrollTop); +} + +// The router fires the first page's astro:page-load on window load, after images and fonts. Start at once +// instead (a module script runs when the document is parsed), and let that first event pass. +let firstLoadPending = true; +start(); +document.addEventListener("astro:page-load", () => { + if (firstLoadPending) { + firstLoadPending = false; + if (page) return; + } + start(); +}); + +document.addEventListener("astro:before-preparation", event => { + const root = document.documentElement; + root.removeAttribute("data-arriving"); + root.setAttribute("data-leaving", ""); + // A navigation that is aborted (another click, an error) leaves the bar where it was. + event.signal.addEventListener("abort", () => root.removeAttribute("data-leaving"), { once: true }); +}); + +document.addEventListener("astro:before-swap", event => { + firstLoadPending = false; + page?.abort(); + page = undefined; + const next = event.newDocument.documentElement; + for (const name of CARRIED) { + const value = document.documentElement.getAttribute(name); + if (value !== null) next.setAttribute(name, value); + } + next.setAttribute("data-arriving", ""); + refreshPersisted(event.newDocument); +}); + +document.addEventListener("astro:after-swap", () => { + // Where the router cannot move an element without detaching it (no Element.moveBefore), the navigator loses + // its scroll position in the move: put it back before the new page paints. + const nav = document.querySelector(`.sidebar[${PERSIST}]`); + if (nav?.dataset.scrollTop !== undefined) { + const top = Number(nav.dataset.scrollTop); + if (nav.scrollTop !== top) nav.scrollTop = top; + delete nav.dataset.scrollTop; + } +}); + +// A full load or a reload restores the navigator's position from what the last page saved (NAV_BOOT). +saveNavigatorScroll(); diff --git a/packages/apidocs/src/astro/env.d.ts b/packages/apidocs/src/astro/env.d.ts new file mode 100644 index 0000000..1852dff --- /dev/null +++ b/packages/apidocs/src/astro/env.d.ts @@ -0,0 +1,17 @@ +/// + +/** The sites, models, themes and versions apidocs() was given (integration.ts writes this module). */ +declare module "virtual:@elide/apidocs/sites" { + import type { Model } from "../model"; + import type { Theme } from "../theme"; + import type { Version } from "./versions"; + export const sites: { base: string; model: Model; theme: Theme; version: string | null }[]; + export const versions: Version[]; + export function loadVersions(request: Request): Promise; +} + +/** For tsc outside Astro's tooling, which types .astro files itself. */ +declare module "*.astro" { + const Component: (props: Record) => unknown; + export default Component; +} diff --git a/packages/apidocs/src/astro/fonts.ts b/packages/apidocs/src/astro/fonts.ts new file mode 100644 index 0000000..434713a --- /dev/null +++ b/packages/apidocs/src/astro/fonts.ts @@ -0,0 +1,11 @@ +/** + * The Elide preset's font files, bundled by Vite: each URL names the file's content hash, so a host can cache it + * for a year. A theme font that is not here is served from the site's assets/ (see assetFile). + */ +import jetbrainsItalic from "@fontsource-variable/jetbrains-mono/files/jetbrains-mono-latin-wght-italic.woff2?url"; +import jetbrainsNormal from "@fontsource-variable/jetbrains-mono/files/jetbrains-mono-latin-wght-normal.woff2?url"; + +export const bundledFonts: Record = { + "fonts/jetbrains-mono-latin-wght-normal.woff2": jetbrainsNormal, + "fonts/jetbrains-mono-latin-wght-italic.woff2": jetbrainsItalic, +}; diff --git a/packages/apidocs/src/astro/helpers.ts b/packages/apidocs/src/astro/helpers.ts new file mode 100644 index 0000000..6752027 --- /dev/null +++ b/packages/apidocs/src/astro/helpers.ts @@ -0,0 +1,10 @@ +/** + * @elide/apidocs/astro/helpers: everything in @elide/apidocs/astro except the Astro components and the + * integration, for code that runs outside Astro's Vite pipeline (tests, scripts, a Worker's own router). + */ +export { renderPage, type PageParts, type RenderOptions } from "./render"; +export { type Resolved, resolvePage, sitePaths, textFiles } from "./resolve"; +export { linkHeader, notFound, prefersMarkdown } from "./http"; +export { prepareTheme, renderText, searchEntries, type TextFile } from "./text"; +export { assertBase, fileUrl, isBaseRelative, mapUrl, pageUrl, rewriteHtml } from "./urls"; +export { latestRelease, pathUnder, type Version, versionLabel } from "./versions"; diff --git a/packages/apidocs/src/astro/http.ts b/packages/apidocs/src/astro/http.ts new file mode 100644 index 0000000..48bbe13 --- /dev/null +++ b/packages/apidocs/src/astro/http.ts @@ -0,0 +1,47 @@ +/** + * What a server adds around a page for programs and AI agents: the page's Markdown twin for a request that asks + * for Markdown, Link headers that point at the other forms, and a 404 that says where to start. + */ + +/** Whether an Accept header prefers Markdown to HTML: text/markdown with a higher q, or no HTML at all. */ +export function prefersMarkdown(accept: string | null | undefined): boolean { + const q = (type: string) => { + for (const part of (accept ?? "").split(",")) { + const [name, ...params] = part.trim().split(";"); + if (name?.trim().toLowerCase() !== type) continue; + const value = params.map(p => p.trim()).find(p => p.startsWith("q=")); + return value ? Number(value.slice(2)) || 0 : 1; + } + return -1; + }; + const markdown = q("text/markdown"); + return markdown > 0 && markdown > q("text/html"); +} + +/** + * The Link header for a page: its Markdown twin, llms.txt and the model. `base` is the site's base path. No + * canonical link: the page declares its own, and a second one that differs in form reads as a conflict. + */ +export function linkHeader(base: string, page: string): string { + return [ + `<${base}${page}.md>; rel="alternate"; type="text/markdown"`, + `<${base}llms.txt>; rel="alternate"; type="text/markdown"; title="llms.txt"`, + `<${base}api.json>; rel="alternate"; type="application/json"; title="api.json"`, + ].join(", "); +} + +function escapeHtml(s: string): string { + return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} + +/** A 404 response that points at the site's overview and llms.txt, as Markdown or HTML by the Accept header. */ +export function notFound(base: string, title: string, accept: string | null | undefined): Response { + const headers = { vary: "Accept", "cache-control": "public, max-age=60" }; + if (prefersMarkdown(accept)) { + const body = `# Not found\n\nThere is no such page in ${title}. Start at the [overview](${base}index.md), or read [llms.txt](${base}llms.txt), which lists every page.\n`; + return new Response(body, { status: 404, headers: { ...headers, "content-type": "text/markdown; charset=utf-8" } }); + } + const name = escapeHtml(title); + const body = `\nNot found (${name})

Not found

There is no such page in ${name}. Start at the overview, or read llms.txt, which lists every page as Markdown.

\n`; + return new Response(body, { status: 404, headers: { ...headers, "content-type": "text/html; charset=utf-8" } }); +} diff --git a/packages/apidocs/src/astro/index.ts b/packages/apidocs/src/astro/index.ts new file mode 100644 index 0000000..6fe3a47 --- /dev/null +++ b/packages/apidocs/src/astro/index.ts @@ -0,0 +1,14 @@ +/** + * @elide/apidocs/astro: apidocs pages in an Astro app, rendered on request or at build time with the same + * components as the static renderer. See the README's "Astro" section. + */ +export { default as ApidocsPage } from "./ApidocsPage.astro"; +export { default as VersionNotice } from "./VersionNotice.astro"; +export { default as VersionSelect } from "./VersionSelect.astro"; +export { type ApidocsOptions, type ApidocsSite, apidocs } from "./integration"; +export { renderPage, type PageParts, type RenderOptions } from "./render"; +export { type Resolved, resolvePage, sitePaths, textFiles } from "./resolve"; +export { linkHeader, notFound, prefersMarkdown } from "./http"; +export { prepareTheme, renderText, searchEntries, type TextFile } from "./text"; +export { assertBase, fileUrl, isBaseRelative, mapUrl, pageUrl, rewriteHtml } from "./urls"; +export { latestRelease, pathUnder, type Version, versionLabel } from "./versions"; diff --git a/packages/apidocs/src/astro/integration.ts b/packages/apidocs/src/astro/integration.ts new file mode 100644 index 0000000..dad23b5 --- /dev/null +++ b/packages/apidocs/src/astro/integration.ts @@ -0,0 +1,91 @@ +/** + * apidocs(options): the Astro integration for apps that have their models when they build (a local api.json, a + * sample, an imported Markdown suite). It serves each site under its base with an injected route, adds the + * Preact renderer the search island needs, and makes the models, themes and versions a virtual module, so + * `astro dev` reloads when a model, a component or the stylesheet changes. + * + * Apps whose models arrive at request time (from R2, say) do not need it: they use resolvePage, renderText + * and in their own route. They still need the Preact renderer (`preact()` from + * @astrojs/preact) for the search island; `apidocs()` with no sites adds just that. + */ +import { isAbsolute, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import preact from "@astrojs/preact"; +import type { AstroIntegration } from "astro"; +import type { Theme } from "../theme"; +import { assertBase } from "./urls"; + +export interface ApidocsSite { + /** The site's base path, ending with a slash: "/java/2.0/". */ + base: string; + /** The model: a path (from the project root) to an api.json, or to a module whose default export is the model. */ + model: string; + theme?: Theme; + /** The id of the version this site is, in `versions`; enables the version menu and notice. */ + version?: string; +} + +export interface ApidocsOptions { + sites?: ApidocsSite[]; + /** + * The versions of the sites: a path to a JSON file (an array of Version), or to a module that exports + * `versions` (what pages are rendered with) and optionally `loadVersions(request)`, which the version server + * islands call on each request, so they can read the newest list while pages stay cached. + */ + versions?: string; +} + +const VIRTUAL = "virtual:@elide/apidocs/sites"; +const PREACT = ["preact", "preact/hooks", "preact/jsx-runtime", "preact/jsx-dev-runtime", "preact/devtools"]; + +export function apidocs(options: ApidocsOptions = {}): AstroIntegration { + const sites = options.sites ?? []; + for (const site of sites) assertBase(site.base); + return { + name: "@elide/apidocs", + hooks: { + "astro:config:setup": ({ config, updateConfig, injectRoute, logger }) => { + const root = fileURLToPath(config.root); + const at = (path: string) => (isAbsolute(path) ? path : resolve(root, path)); + if (!config.integrations.some(i => i.name === "@astrojs/preact")) { + updateConfig({ integrations: [preact()] }); + } + if (config.trailingSlash !== "ignore") { + logger.warn(`trailingSlash is "${config.trailingSlash}"; apidocs URLs need "ignore": packages end with a slash and types do not.`); + } + updateConfig({ + vite: { + // One Preact: the pages render with this package's copy, and the search island with the renderer's. Listing + // its entry points up front keeps the dev server from finding them at the first request and optimizing + // again, which serves that request with two copies (a "reading '__H'" error from Preact's hooks). + resolve: { dedupe: ["preact", "preact-render-to-string"] }, + optimizeDeps: { include: PREACT }, + ssr: { optimizeDeps: { include: PREACT } }, + plugins: [{ + name: "apidocs-sites", + resolveId: id => (id === VIRTUAL ? `\0${VIRTUAL}` : undefined), + load: id => { + if (id !== `\0${VIRTUAL}`) return undefined; + const lines = sites.map((site, i) => `import * as model${i} from ${JSON.stringify(at(site.model))};`); + if (options.versions) lines.push(`import * as versionsModule from ${JSON.stringify(at(options.versions))};`); + lines.push( + `const pick = m => m.default ?? m.model;`, + `export const sites = [${sites.map((site, i) => `{ base: ${JSON.stringify(site.base)}, model: pick(model${i}), theme: ${JSON.stringify(site.theme ?? {})}, version: ${JSON.stringify(site.version ?? null)} }`).join(", ")}];`, + options.versions + ? `const module = m => m;\nexport const versions = module(versionsModule).versions ?? module(versionsModule).default ?? [];\nexport const loadVersions = module(versionsModule).loadVersions ?? (async () => versions);` + : `export const versions = [];\nexport const loadVersions = async () => [];`, + ); + return lines.join("\n"); + }, + }], + }, + }); + for (const site of sites) { + injectRoute({ pattern: `${site.base}[...path]`, entrypoint: new URL("./Route.astro", import.meta.url), prerender: false }); + } + }, + }, + }; +} + +export default apidocs; diff --git a/packages/apidocs/src/astro/pages.tsx b/packages/apidocs/src/astro/pages.tsx new file mode 100644 index 0000000..c3ab9b4 --- /dev/null +++ b/packages/apidocs/src/astro/pages.tsx @@ -0,0 +1,66 @@ +/** + * One page at a time: which pages a model has, and how each renders as HTML and Markdown. render() writes the + * whole site in one pass; an on-demand server renders only the page it was asked for, so this mirrors render()'s + * dispatch page by page. test/astro.test.ts checks that both give the same pages and the same Markdown. + */ +import type { VNode } from "preact"; +import { DeprecatedPage, IndexAllPage, PackagesIndexPage, TypesIndexPage } from "../indexes"; +import { deprecatedIndexMarkdown, guideMarkdown, indexAllMarkdown, indexMarkdown, packageMarkdown, packagesIndexMarkdown, typeMarkdown, typesIndexMarkdown } from "../markdown"; +import type { Model } from "../model"; +import { GuidePage } from "../narrative"; +import { IndexPage, PackagePage, TypePage } from "../pages"; +import { SCHEMA } from "../render"; +import { buildSite, DEPRECATED_PAGE, INDEX, INDEX_ALL_PAGE, indexPages, PACKAGES_PAGE, packagePage, type Site, TYPES_PAGE, typePage } from "../site"; +import type { SymbolMode } from "../symbols"; + +/** A page of a site: its path without an extension, its code language, and how to render it. */ +export interface SitePage { + page: string; + language: string; + html: () => VNode; + markdown: (symbols: SymbolMode) => string; +} + +interface Built { + site: Site; + pages: Map; +} + +const built = new WeakMap(); + +/** The model's site structure and its pages, computed once per model object. Keep the model object to reuse them. */ +export function siteOf(model: Model): Built { + let entry = built.get(model); + if (!entry) { + if (model.schema !== SCHEMA) throw new Error(`Expected an ${SCHEMA} model, got ${JSON.stringify(model.schema)}`); + const site = buildSite(model); + entry = { site, pages: new Map(sitePages(site).map(p => [p.page, p])) }; + built.set(model, entry); + } + return entry; +} + +/** Every page, in render()'s order: the overview, the guides, each package and its types, the index pages. */ +function sitePages(site: Site): SitePage[] { + const pages: SitePage[] = []; + pages.push({ page: INDEX, language: site.language, html: () => , markdown: s => indexMarkdown(site, s) }); + for (const entry of site.guides) { + // The overview guide is the index page. + if (entry.page === INDEX) continue; + pages.push({ page: entry.page, language: site.language, html: () => , markdown: s => guideMarkdown(site, entry, s) }); + } + for (const pkg of site.packages) { + pages.push({ page: packagePage(pkg), language: site.language, html: () => , markdown: s => packageMarkdown(site, pkg, s) }); + for (const type of pkg.types ?? []) { + pages.push({ page: typePage(pkg, type), language: type.language, html: () => , markdown: s => typeMarkdown(site, type, s) }); + } + } + for (const { page } of indexPages(site)) { + const lang = site.language; + if (page === PACKAGES_PAGE) pages.push({ page, language: lang, html: () => , markdown: s => packagesIndexMarkdown(site, s) }); + if (page === TYPES_PAGE) pages.push({ page, language: lang, html: () => , markdown: s => typesIndexMarkdown(site, s) }); + if (page === INDEX_ALL_PAGE) pages.push({ page, language: lang, html: () => , markdown: s => indexAllMarkdown(site, s) }); + if (page === DEPRECATED_PAGE) pages.push({ page, language: lang, html: () => , markdown: s => deprecatedIndexMarkdown(site, s) }); + } + return pages; +} diff --git a/packages/apidocs/src/astro/render.tsx b/packages/apidocs/src/astro/render.tsx new file mode 100644 index 0000000..4abee76 --- /dev/null +++ b/packages/apidocs/src/astro/render.tsx @@ -0,0 +1,85 @@ +/** + * One page as the pieces ApidocsPage.astro assembles: the head's metadata, and the body split at the places + * where Astro adds its own content. The page is rendered by the static renderer's components (Shell in its + * "astro" variant), then its URLs are mapped to the Astro form (urls.ts). + */ +import { renderToString } from "preact-render-to-string"; +import { HOLES, type Hole, ModuleVersion, ShellVariantContext } from "../components/chrome"; +import { Ctx, type PageContext } from "../context"; +import type { Model } from "../model"; +import { type Theme, themeCss } from "../theme"; +import { siteOf } from "./pages"; +import { prepareTheme } from "./text"; +import { assertBase, rewriteHtml } from "./urls"; + +export interface RenderOptions { + /** The site's base path, ending with a slash: "/api/komodo/main/". */ + base: string; + /** The site's absolute URL, ending with a slash; canonical links and the JSON-LD use it. theme.baseUrl wins. */ + baseUrl?: string; + /** Where a theme font file is served, from its asset path ("fonts/inter.woff2"). Defaults to the site's assets/. */ + fontUrl?: (asset: string) => string; +} + +export interface PageParts { + /** The head's elements: metadata, favicon, the boot script, JSON-LD. */ + head: string; + /** The body, split at the holes: before the top-bar slot, before search, before the notice, the rest. */ + body: [string, string, string, string]; + /** What the top-bar slot shows when the app fills it with nothing: the module's name and version. */ + moduleVersion: string; + /** The theme's tokens (on :root:root, so they win over the stylesheet's defaults in any order) and font faces. */ + themeCss: string; + /** Font files to preload: the upright faces. */ + preload: string[]; + /** Whether the site has an API reference (packages), which decides the search field's wording. */ + api: boolean; + /** The page's title. */ + title: string; +} + +function between(html: string, open: string, close: string): string { + const start = html.indexOf(open); + const end = html.lastIndexOf(close); + if (start < 0 || end < start) throw new Error(`apidocs: rendered page has no ${open}`); + return html.slice(start + open.length, end); +} + +/** Renders one page of a model (a page path from resolvePage) into the pieces of an Astro document. */ +export function renderPage(model: Model, page: string, themeInput: Theme | string | undefined, options: RenderOptions): PageParts { + const { site, pages } = siteOf(model); + const entry = pages.get(page); + if (!entry) throw new Error(`apidocs: no page ${JSON.stringify(page)} in ${model.module.name}`); + const base = options.base.endsWith("/") ? options.base : `${options.base}/`; + assertBase(base); + const input = typeof themeInput === "string" ? (JSON.parse(themeInput) as Theme) : (themeInput ?? {}); + const theme = prepareTheme({ ...input, baseUrl: input.baseUrl ?? options.baseUrl }); + const ctx: PageContext = { site, theme, page, language: entry.language }; + const render = (node: preact.VNode) => + rewriteHtml( + renderToString( + + {node} + , + ), + { page, base, baseUrl: theme.baseUrl }, + ); + const html = render(entry.html()); + const head = between(html, "", ""); + const parts = between(html, "", "").split(/<\/apidocs-hole>/); + // split() with a capture group interleaves the hole names: [chunk, name, chunk, name, ...]. + const names = parts.filter((_, i) => i % 2 === 1) as Hole[]; + if (names.join() !== HOLES.join()) throw new Error(`apidocs: expected the holes ${HOLES.join(", ")}, got ${names.join(", ")}`); + const chunks = parts.filter((_, i) => i % 2 === 0); + const fontUrl = options.fontUrl ?? ((asset: string) => `${base}assets/${asset}`); + const fonts = (theme.fonts ?? []).map(face => ({ ...face, asset: fontUrl(face.asset) })); + return { + head, + body: chunks as PageParts["body"], + moduleVersion: render(), + themeCss: themeCss({ ...theme, fonts }, ":root:root"), + preload: fonts.filter(face => face.preload ?? (face.style ?? "normal") === "normal").map(face => face.asset), + api: site.packages.length > 0, + title: /([\s\S]*?)<\/title>/.exec(head)?.[1] ?? "", + }; +} diff --git a/packages/apidocs/src/astro/resolve.ts b/packages/apidocs/src/astro/resolve.ts new file mode 100644 index 0000000..7fbf4a8 --- /dev/null +++ b/packages/apidocs/src/astro/resolve.ts @@ -0,0 +1,95 @@ +/** + * What a path under a site means. Paths are relative to the site's base, without a leading slash, decoded: + * "" (the overview), "com/example/geo/", "com/example/geo/Circle", "guides/concepts", "packages", and every + * file the static renderer writes ("llms.txt", "com/example/geo/Circle.md", "assets/search-index.js", ...). + * The static renderer's page paths ("index.html", "com/example/geo/Circle.html") redirect to the Astro form. + */ +import type { Model } from "../model"; +import type { Theme } from "../theme"; +import { prepareTheme } from "./text"; +import { isBaseRelative, pageUrl } from "./urls"; +import { siteOf } from "./pages"; + +export type Resolved = + /** An HTML page: render it with <ApidocsPage page={page} />. */ + | { kind: "page"; page: string } + /** A page's Markdown twin: serve renderText(model, `${page}.md`). */ + | { kind: "markdown"; page: string } + /** Another file: renderText(model, name) for text, or a theme font (see assetFile). */ + | { kind: "file"; name: string } + /** A permanent redirect to the canonical path, relative to the base: never with a scheme, a leading "/" or "\\", a backslash, or a "..". */ + | { kind: "redirect"; to: string } + | { kind: "missing" }; + +/** The text files of a site other than Markdown twins, as renderText serves them. */ +export function textFiles(model: Model, themeInput?: Theme): string[] { + const { site } = siteOf(model); + const theme = themeInput && prepareTheme(themeInput); + return [ + "llms.txt", + "llms-full.txt", + "api.json", + // A guides-only site has no packages for javadoc -link to find, so it has no element-list. + ...(site.packages.length > 0 || !site.guides.length ? ["element-list"] : []), + "assets/search-index.js", + "assets/search-index.json", + "assets/theme.css", + ...(!theme || theme.logo?.light ? ["assets/logo-light.svg"] : []), + ...(!theme || theme.logo?.dark ? ["assets/logo-dark.svg"] : []), + ...(!theme || theme.favicon ? ["assets/favicon.svg"] : []), + ...(!theme || theme.baseUrl ? ["sitemap.xml"] : []), + ]; +} + +function decode(path: string): string { + if (!path.includes("%")) return path; + try { + return decodeURIComponent(path); + } catch { + return path; + } +} + +/** + * What `path` (relative to the site's base) is. Without a theme, theme-dependent files (logos, the favicon, + * sitemap.xml, fonts) resolve by name, and renderText returns undefined for one the theme does not have. + */ +export function resolvePage(model: Model, rawPath: string, theme?: Theme): Resolved { + const { pages } = siteOf(model); + const path = decode(rawPath).replace(/^\/+/, ""); + // Names in the model are untrusted, and an app writes base + to into a Location header: a target that could + // leave the base (a leading slash, a backslash, a ".." segment, a scheme) is not a page. + const canonical = (page: string): Resolved => (isBaseRelative(pageUrl(page)) ? { kind: "redirect", to: pageUrl(page) } : { kind: "missing" }); + if (path === "") return { kind: "page", page: "index" }; + if (textFiles(model, theme).includes(path)) return { kind: "file", name: path }; + if (path.startsWith("assets/fonts/") && /\.woff2$/.test(path)) { + const fonts = theme ? (prepareTheme(theme).fonts ?? []).map(f => `assets/${f.asset}`) : undefined; + return !fonts || fonts.includes(path) ? { kind: "file", name: path } : { kind: "missing" }; + } + if (path.endsWith(".html")) { + const page = path.slice(0, -".html".length); + return pages.has(page) ? canonical(page) : { kind: "missing" }; + } + if (path.endsWith(".md")) { + const page = path.slice(0, -".md".length); + return pages.has(page) ? { kind: "markdown", page } : { kind: "missing" }; + } + if (path.endsWith("/")) { + const dir = path.slice(0, -1); + if (pages.has(`${dir}/index`)) return { kind: "page", page: `${dir}/index` }; + return pages.has(dir) ? canonical(dir) : { kind: "missing" }; + } + if (pages.has(path)) return path === "index" || path.endsWith("/index") ? canonical(path) : { kind: "page", page: path }; + if (pages.has(`${path}/index`)) return canonical(`${path}/index`); + return { kind: "missing" }; +} + +/** Every path a site serves in the Astro form, pages first: what a prerendering route lists in getStaticPaths. */ +export function sitePaths(model: Model, theme?: Theme): string[] { + const { pages } = siteOf(model); + return [ + ...[...pages.keys()].map(pageUrl), + ...[...pages.keys()].map(page => `${page}.md`), + ...textFiles(model, theme), + ]; +} diff --git a/packages/apidocs/src/astro/text.ts b/packages/apidocs/src/astro/text.ts new file mode 100644 index 0000000..075edd3 --- /dev/null +++ b/packages/apidocs/src/astro/text.ts @@ -0,0 +1,111 @@ +/** + * The text a site serves besides its HTML pages: Markdown twins, llms.txt, llms-full.txt, api.json, + * element-list, the search index, the theme stylesheet, the theme's artwork and sitemap.xml. Each is the same + * text the static renderer writes, except sitemap.xml and assets/search-index.json, which list URLs in the + * Astro form. + */ +import type { Model } from "../model"; +import { render, safeTheme, searchIndex } from "../render"; +import { resolveTheme, type Theme, themeCss } from "../theme"; +import type { Entry } from "../client/search"; +import { siteOf } from "./pages"; +import { fileUrl, pageUrl } from "./urls"; + +/** A theme with its preset applied and its URLs checked, as render() uses it. Accepts the theme as JSON text. */ +export function prepareTheme(input: Theme | string | undefined): Theme { + return safeTheme(resolveTheme(typeof input === "string" ? JSON.parse(input) : input)); +} + +export interface TextFile { + body: string; + /** The Content-Type to serve it with. */ + contentType: string; +} + +const TYPES: Record<string, string> = { + md: "text/markdown; charset=utf-8", + txt: "text/plain; charset=utf-8", + json: "application/json; charset=utf-8", + js: "text/javascript; charset=utf-8", + css: "text/css; charset=utf-8", + svg: "image/svg+xml", + xml: "application/xml; charset=utf-8", +}; + +function contentType(path: string): string { + const ext = /\.([a-z0-9]+)$/.exec(path)?.[1]; + return (ext && TYPES[ext]) || "text/plain; charset=utf-8"; +} + +/** The site-wide files that need every page: rendered once per model and symbol set, then kept. */ +const whole = new WeakMap<Model, Map<string, Record<string, string>>>(); + +function wholeSite(model: Model, theme: Theme): Record<string, string> { + let perModel = whole.get(model); + if (!perModel) whole.set(model, (perModel = new Map())); + const key = theme.symbols ?? "utf"; + let files = perModel.get(key); + if (!files) { + // render() writes every page too; only the files built from all of them are kept. + const out = render(model, { ...theme, baseUrl: undefined, extends: undefined }); + files = {}; + for (const name of ["llms.txt", "llms-full.txt", "element-list"]) if (typeof out[name] === "string") files[name] = out[name]; + perModel.set(key, files); + } + return files; +} + +/** The search index's entries with their paths in the Astro form: what assets/search-index.json holds. */ +export function searchEntries(model: Model): Entry[] { + const script = searchIndex(siteOf(model).site); + const json = script.slice(script.indexOf("=") + 1, script.lastIndexOf(";")); + return (JSON.parse(json) as Entry[]).map(entry => { + const at = entry[2].indexOf("#"); + const file = at < 0 ? entry[2] : entry[2].slice(0, at); + return [entry[0], entry[1], fileUrl(file) + (at < 0 ? "" : entry[2].slice(at)), entry[3], entry[4]] as Entry; + }); +} + +/** + * The text at `path` (relative to the site's base; a page's Markdown twin is `${page}.md`), or undefined when + * the site has no such text file. llms.txt, llms-full.txt and element-list render the whole site once per model + * object, and keep only those files; everything else renders on its own. + */ +export function renderText(model: Model, path: string, themeInput?: Theme | string): TextFile | undefined { + const { site, pages } = siteOf(model); + const theme = prepareTheme(themeInput); + const body = ((): string | undefined => { + if (path.endsWith(".md")) return pages.get(path.slice(0, -".md".length))?.markdown(theme.symbols ?? "utf"); + switch (path) { + case "llms.txt": + case "llms-full.txt": + case "element-list": + return wholeSite(model, theme)[path]; + case "api.json": + return JSON.stringify(model); + case "assets/search-index.js": + return searchIndex(site); + case "assets/search-index.json": + return JSON.stringify(searchEntries(model)); + case "assets/theme.css": + return themeCss(theme); + case "assets/logo-light.svg": + return theme.logo?.light; + case "assets/logo-dark.svg": + return theme.logo?.dark; + case "assets/favicon.svg": + return theme.favicon; + case "sitemap.xml": + return theme.baseUrl ? sitemap(theme.baseUrl, [...pages.keys()]) : undefined; + default: + return undefined; + } + })(); + return body === undefined ? undefined : { body, contentType: contentType(path) }; +} + +function sitemap(base: string, pages: string[]): string { + const escape = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); + const urls = pages.map(p => ` <url><loc>${escape(base + pageUrl(p))}</loc></url>`).join("\n"); + return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls}\n</urlset>\n`; +} diff --git a/packages/apidocs/src/astro/urls.ts b/packages/apidocs/src/astro/urls.ts new file mode 100644 index 0000000..b91fb86 --- /dev/null +++ b/packages/apidocs/src/astro/urls.ts @@ -0,0 +1,170 @@ +/** + * The Astro integration's URL form, and the mapping from the static renderer's links to it. + * + * A site lives under a base path that ends with a slash (`/api/komodo/main/`). Under it: + * + * static file Astro URL (relative to the base) + * index.html (the base itself) + * com/example/geo/index.html com/example/geo/ a package: a directory URL + * com/example/geo/Circle.html com/example/geo/Circle a type, a guide or an index page: no extension + * anything else the same path .md twins, llms.txt, api.json, assets/... + * + * Pages are rendered with the static renderer's components, whose links are relative and name .html files. + * rewriteHtml maps every such link to a root-absolute URL in this form, so the top bar and the navigator, which + * the client router keeps across pages, link correctly from any page of the site. + */ +import { safeUrl } from "../url"; + +/** A page's URL under the base, from its page path without an extension ("com/example/geo/index" -> "com/example/geo/"). */ +export function pageUrl(page: string): string { + if (page === "index") return ""; + if (page.endsWith("/index")) return page.slice(0, -"index".length); + return page; +} + +/** A static file path's URL under the base: pages lose ".html" (and "index.html"); other files keep their path. */ +export function fileUrl(path: string): string { + return path.endsWith(".html") ? pageUrl(path.slice(0, -".html".length)) : path; +} + +/** The directory part of a page path, with a trailing slash ("com/example/geo/Circle" -> "com/example/geo/"). */ +function dirOf(page: string): string { + return page.slice(0, page.lastIndexOf("/") + 1); +} + +/** Resolves a relative path against a directory, or undefined when it climbs above the site root. */ +function join(dir: string, relative: string): string | undefined { + const parts = dir.split("/").filter(Boolean); + for (const segment of relative.split("/")) { + if (segment === "..") { + if (!parts.length) return undefined; + parts.pop(); + } else if (segment !== "." && segment !== "") parts.push(segment); + } + return parts.join("/") + (relative.endsWith("/") ? "/" : ""); +} + +export interface UrlContext { + /** The page whose links these are, as a page path without an extension. */ + page: string; + /** The site's base path, ending with a slash: "/api/komodo/main/". */ + base: string; + /** The site's absolute URL (theme.baseUrl when the page was rendered), ending with a slash. */ + baseUrl?: string; +} + +/** A backslash, or a control character (which browsers strip from URLs, joining what was around it). */ +// eslint-disable-next-line no-control-regex +const UNSAFE = /[\\\u0000-\u001f\u007f]/; + +/** + * Throws unless `base` is an absolute path that starts with a single "/" and ends with "/", whose segments are + * plain names: "/" and "/api/komodo/main/" are bases; "//x/", "/x", "x/", "/a/../" and "/a\\b/" are not. A base + * that passes can never join with a mapped path into a URL that starts with "//" or "/\\". + */ +export function assertBase(base: string): void { + const segments = base.slice(1, -1).split("/"); + const ok = base.startsWith("/") && base.endsWith("/") && !UNSAFE.test(base) && !/[\s?#]/.test(base) + && (base === "/" || segments.every(segment => segment !== "" && segment !== "." && segment !== "..")); + if (!ok) throw new Error(`apidocs: a site's base is an absolute path that starts and ends with "/", such as "/api/" or "/"; got ${JSON.stringify(base)}`); +} + +/** + * Whether a path relative to a site's base stays inside it when appended to the base: no scheme, no leading "/" + * or "\\", no backslash or control character, and no empty, "." or ".." segment (a trailing "/" is allowed). + */ +export function isBaseRelative(path: string): boolean { + if (UNSAFE.test(path) || /^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("/")) return false; + const segments = (path.endsWith("/") ? path.slice(0, -1) : path).split("/"); + return path === "" || segments.every(segment => segment !== "" && segment !== "." && segment !== ".."); +} + +/** + * One URL from a page rendered by the static renderer, in the Astro form: relative links become root-absolute, + * links under baseUrl stay absolute, and fragments, other sites and other schemes are left alone. Undefined when + * safeUrl rejects the URL: the caller drops the attribute, so a link renders as text. + * + * Links can come from documentation comments, which are untrusted, so a rewritten URL always starts with the + * base (or baseUrl) it was mapped under and passes safeUrl again. Anything that could leave it (a backslash, a + * control character, a target that resolves to a path starting with "/") is not rewritten: it keeps the static + * page's form, relative to the page, with backslashes percent-encoded so no browser reads one as a slash. + */ +export function mapUrl(url: string, ctx: UrlContext): string | undefined { + assertBase(ctx.base); + const safe = safeUrl(url); + if (safe === undefined) return undefined; + const keep = () => { + const kept = safe.replace(/\\/g, "%5C"); + // safeUrl drops tabs and newlines, as browsers do: "/<tab>/host" would come out as "//host", another origin. + return kept.startsWith("//") && UNSAFE.test(url) ? undefined : kept; + }; + if (UNSAFE.test(url) || UNSAFE.test(safe)) return keep(); + if (ctx.baseUrl && safe.startsWith(ctx.baseUrl)) { + const rest = safe.slice(ctx.baseUrl.length); + return rest.startsWith("/") ? keep() : (under(ctx.baseUrl + mapPath(rest), ctx.baseUrl) ?? keep()); + } + if (safe === "" || safe.startsWith("#") || safe.startsWith("/") || /^[a-z][a-z0-9+.-]*:/i.test(safe)) return keep(); + const cut = safe.search(/[?#]/); + const path = cut < 0 ? safe : safe.slice(0, cut); + const target = join(dirOf(ctx.page), path); + if (target === undefined || target.startsWith("/")) return keep(); + return under(ctx.base + mapPath(target + (cut < 0 ? "" : safe.slice(cut))), ctx.base) ?? keep(); +} + +/** The mapped URL when it starts with its prefix, cannot be read as another origin, and passes safeUrl unchanged. */ +function under(mapped: string, prefix: string): string | undefined { + if (!mapped.startsWith(prefix) || /^\/[/\\]/.test(mapped) || UNSAFE.test(mapped)) return undefined; + return safeUrl(mapped) === mapped ? mapped : undefined; +} + +/** A site-relative path with an optional query and fragment, with its file part in the Astro form. */ +function mapPath(pathWithRest: string): string { + const cut = pathWithRest.search(/[?#]/); + const path = cut < 0 ? pathWithRest : pathWithRest.slice(0, cut); + return fileUrl(path) + (cut < 0 ? "" : pathWithRest.slice(cut)); +} + +const ATTR = /(\s(?:href|src|data-copy-markdown)=")([^"]*)(")/g; +const META_CONTENT = /(<meta property="og:url" content=")([^"]*)(")/g; +const JSON_LD = /(<script type="application\/ld\+json">)([\s\S]*?)(<\/script>)/g; +/** The JSON-LD keys whose values are URLs. */ +const URL_KEYS = new Set(["url", "item", "contentUrl"]); + +function unescapeAttr(s: string): string { + return s.replace(/"/g, '"').replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&"); +} + +function escapeAttr(s: string): string { + return s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">"); +} + +/** + * Maps the URLs in a page that Preact rendered: href, src and data-copy-markdown attributes, og:url, and the + * URL fields of the JSON-LD graph. Preact escapes every quote in text and in attribute values, so `href="` can + * occur only as an attribute; raw HTML from documentation comments has passed the sanitizer, which writes its + * attributes the same way. + */ +export function rewriteHtml(html: string, ctx: UrlContext): string { + const map = (value: string) => { + const url = mapUrl(unescapeAttr(value), ctx); + return url === undefined ? undefined : escapeAttr(url); + }; + return html + // An attribute whose URL safeUrl rejects is dropped: a link without href renders as its text. + .replace(ATTR, (_, start: string, value: string, end: string) => { + const url = map(value); + return url === undefined ? "" : start + url + end; + }) + .replace(META_CONTENT, (_, start: string, value: string, end: string) => start + (map(value) ?? "") + end) + .replace(JSON_LD, (_, start: string, json: string, end: string) => { + const graph = JSON.parse(json) as unknown; + const walk = (node: unknown): unknown => { + if (Array.isArray(node)) return node.map(walk); + if (node && typeof node === "object") { + return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, URL_KEYS.has(k) && typeof v === "string" ? (mapUrl(v, ctx) ?? "") : walk(v)])); + } + return node; + }; + return start + JSON.stringify(walk(graph)).replace(/</g, "\\u003c") + end; + }); +} diff --git a/packages/apidocs/src/astro/versions.ts b/packages/apidocs/src/astro/versions.ts new file mode 100644 index 0000000..d961b75 --- /dev/null +++ b/packages/apidocs/src/astro/versions.ts @@ -0,0 +1,28 @@ +/** Versions of one documentation set, for the version selector and the version notice. */ + +export interface Version { + /** A stable id: "main", "2.0". */ + id: string; + /** What the selector shows; defaults to the id. */ + label?: string; + /** The version's site base path, ending with a slash: "/api/komodo/2.0/". */ + base: string; + /** "release" (the default), "prerelease", or "development" for a branch such as main. */ + channel?: "release" | "prerelease" | "development"; + /** Whether this is the release readers should use. Defaults to the first release in the list. */ + latest?: boolean; +} + +export function versionLabel(version: Version): string { + return version.label ?? version.id; +} + +/** The release readers should use: the one marked latest, else the first release. */ +export function latestRelease(versions: Version[]): Version | undefined { + return versions.find(v => v.latest) ?? versions.find(v => (v.channel ?? "release") === "release"); +} + +/** A page's path under its site's base ("com/example/geo/Circle"), from a URL path and the base. */ +export function pathUnder(pathname: string, base: string): string { + return pathname.startsWith(base) ? pathname.slice(base.length) : ""; +} diff --git a/packages/apidocs/src/cli.ts b/packages/apidocs/src/cli.ts new file mode 100644 index 0000000..d022787 --- /dev/null +++ b/packages/apidocs/src/cli.ts @@ -0,0 +1,186 @@ +#!/usr/bin/env bun +/** + * The apidocs command line. One command so far: + * + * apidocs guides --src <suite dir> --id <suite id> --title <site title> --out <output dir> + * [--theme <theme.json>] [--version <string>] [--base-url <url with trailing slash>] + * [--source-link <template with {path} and {line}>] [--source-root <repo-relative suite path>] + * [--link <prefix>=<target> ...] [--include-drafts] [--warn-only] [--assets <dir>] + * + * It imports a Markdown suite (src/import/markdown.ts), renders it as a guides-only site and writes the site into + * --out: HTML pages and their Markdown twins, llms.txt, llms-full.txt, api.json (the guides-only model), the search + * index, the assets and the suite's images. Diagnostics go to stderr as file:line: message, with paths as given to + * --src. It exits 1 when there is an error (unless --warn-only), 2 on bad arguments, and prints one JSON line of + * counts on success. It writes into --out without deleting what is already there. + * + * The stylesheet and fonts come from the sources; the client script from dist/assets/apidocs.js, which is built + * first when it is missing or older than src/client. --assets takes every asset from a directory instead. + */ +import { spawnSync } from "node:child_process"; +import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, isAbsolute, join, normalize, resolve, sep } from "node:path"; +import { fileURLToPath } from "node:url"; +import { formatDiagnostic, type LinkMapping } from "./import/markdown"; +import { suiteSite } from "./import/suite"; +import type { Theme } from "./theme"; + +const USAGE = `usage: apidocs guides --src <suite dir> --id <suite id> --title <site title> --out <output dir> + [--theme <theme.json>] [--version <string>] [--base-url <url/>] [--source-link <template>] + [--source-root <path>] [--link <prefix>=<target> ...] [--include-drafts] [--warn-only] [--assets <dir>]`; + +const pkg = fileURLToPath(new URL("..", import.meta.url)); +const require = createRequire(import.meta.url); + +class UsageError extends Error {} + +interface Args { + values: Map<string, string>; + links: LinkMapping[]; + flags: Set<string>; +} + +const VALUED = new Set(["src", "id", "title", "out", "theme", "version", "base-url", "source-link", "source-root", "assets"]); +const FLAGS = new Set(["include-drafts", "warn-only"]); + +function parseArgs(argv: string[]): Args { + const args: Args = { values: new Map(), links: [], flags: new Set() }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]!; + const [key, inline] = arg.startsWith("--") ? (arg.includes("=") && !arg.startsWith("--link") ? [arg.slice(2, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)] : [arg.slice(2), undefined]) : [arg, undefined]; + if (FLAGS.has(key)) { + args.flags.add(key); + continue; + } + if (key !== "link" && !VALUED.has(key)) throw new UsageError(`unknown argument ${arg}`); + const value = inline ?? argv[++i]; + if (value === undefined) throw new UsageError(`${arg} needs a value`); + if (key === "link") { + const at = value.indexOf("="); + if (at <= 0) throw new UsageError(`--link takes <prefix>=<target>, got ${value}`); + args.links.push({ prefix: value.slice(0, at), target: value.slice(at + 1) }); + } else args.values.set(key, value); + } + for (const required of ["src", "id", "title", "out"]) if (!args.values.get(required)) throw new UsageError(`missing --${required}`); + return args; +} + +/** A path inside the output directory; refuses absolute paths and ".." segments. */ +function inside(root: string, path: string): string { + const target = normalize(join(root, path)); + if (isAbsolute(path) || path.split("/").includes("..") || !(target + sep).startsWith(resolve(root) + sep)) { + throw new Error(`refusing to write outside the output directory: ${path}`); + } + return target; +} + +/** The client bundle, built when it is missing or older than its sources. */ +function clientBundle(): string { + const bundle = join(pkg, "dist/assets/apidocs.js"); + const newest = Math.max(...readdirSync(join(pkg, "src/client")).map(f => statSync(join(pkg, "src/client", f)).mtimeMs)); + if (!existsSync(bundle) || statSync(bundle).mtimeMs < newest) { + process.stderr.write("apidocs: building the client script (dist/assets/apidocs.js)\n"); + const run = spawnSync("bunx", ["vite", "build", "--config", "vite.client.config.ts"], { cwd: pkg, stdio: ["ignore", "ignore", "inherit"] }); + if (run.status !== 0) throw new Error("could not build the client script; run `bun run build` in packages/apidocs"); + } + return bundle; +} + +/** Where a renderer asset comes from: --assets, or the package's sources and its client bundle. */ +function assetSource(name: string, assets: string | undefined): string { + if (assets) return inside(assets, name); + if (name === "apidocs.css") return join(pkg, "src/styles/apidocs.css"); + if (name === "apidocs.js") return clientBundle(); + if (name.startsWith("fonts/")) { + const file = name.slice("fonts/".length); + return require.resolve(`@fontsource-variable/${file.replace(/-latin-.*$/, "")}/files/${file}`); + } + throw new Error(`no source for the asset ${name}`); +} + +function guides(argv: string[]): number { + const args = parseArgs(argv); + // Relative paths are the caller's: the directory a package script started in, else this process's. + const cwd = process.env.npm_lifecycle_event && process.env.INIT_CWD ? process.env.INIT_CWD : process.cwd(); + const src = resolve(cwd, args.values.get("src")!); + const out = resolve(cwd, args.values.get("out")!); + if (!existsSync(src) || !statSync(src).isDirectory()) throw new UsageError(`--src ${args.values.get("src")} is not a directory`); + const themePath = args.values.get("theme"); + const theme: Theme = themePath ? JSON.parse(readFileSync(resolve(cwd, themePath), "utf8")) : {}; + const assetsDir = args.values.get("assets") ? resolve(cwd, args.values.get("assets")!) : undefined; + const warnOnly = args.flags.has("warn-only"); + const opt = (key: string) => args.values.get(key); + + const site = suiteSite(src, { + id: opt("id")!, + title: opt("title")!, + ...(opt("version") ? { version: opt("version")! } : {}), + theme, + ...(opt("base-url") ? { baseUrl: opt("base-url")! } : {}), + ...(opt("source-link") ? { sourceLink: opt("source-link")! } : {}), + ...(opt("source-root") ? { sourceRoot: opt("source-root")! } : {}), + ...(args.links.length ? { links: args.links } : {}), + ...(args.flags.has("include-drafts") ? { includeDrafts: true } : {}), + }); + + const prefix = args.values.get("src")!.replace(/\/*$/, "/"); + let errors = 0; + let warnings = 0; + for (const d of site.diagnostics) { + const shown = warnOnly ? { ...d, severity: "warning" as const } : d; + if (shown.severity === "error") errors++; + else warnings++; + process.stderr.write(formatDiagnostic(shown, prefix) + "\n"); + } + if (errors) { + process.stderr.write(`apidocs: ${errors} error${errors === 1 ? "" : "s"}; nothing written (--warn-only writes anyway)\n`); + return 1; + } + + let count = 0; + let bytes = 0; + for (const [path, content] of Object.entries(site.output)) { + const target = inside(out, path); + mkdirSync(dirname(target), { recursive: true }); + if (typeof content === "string") { + writeFileSync(target, content); + bytes += Buffer.byteLength(content); + } else { + copyFileSync(assetSource(content.asset, assetsDir), target); + bytes += statSync(target).size; + } + count++; + } + for (const file of site.copies) { + const target = inside(out, file.to); + mkdirSync(dirname(target), { recursive: true }); + // The bytes read with the suite (an SVG's sanitized form), never a fresh read through the file system. + writeFileSync(target, file.data); + bytes += file.data.byteLength; + count++; + } + const pages = Object.keys(site.output).filter(p => p.endsWith(".html")).length; + process.stdout.write(JSON.stringify({ files: count, bytes, pages, guides: site.model.module.guides?.length ?? 0, drafts: site.result.drafts.length, errors: 0, warnings }) + "\n"); + return 0; +} + +function main(argv: string[]): number { + const [command, ...rest] = argv; + try { + if (command === "guides") return guides(rest); + if (command === "--help" || command === "-h" || command === "help") { + process.stdout.write(USAGE + "\n"); + return 0; + } + throw new UsageError(command ? `unknown command ${command}` : "no command"); + } catch (error) { + if (error instanceof UsageError) { + process.stderr.write(`apidocs: ${error.message}\n${USAGE}\n`); + return 2; + } + process.stderr.write(`apidocs: ${(error as Error).message ?? error}\n`); + return 1; + } +} + +process.exit(main(process.argv.slice(2))); diff --git a/packages/apidocs/src/client/behaviors.tsx b/packages/apidocs/src/client/behaviors.tsx new file mode 100644 index 0000000..36d051e --- /dev/null +++ b/packages/apidocs/src/client/behaviors.tsx @@ -0,0 +1,469 @@ +/** + * The page behaviors, as functions with no side effects at import. Each one finds its static markup and adds + * behavior; with JavaScript off the pages lose these and nothing else. + * + * Every listener and observer is tied to an AbortSignal, so a caller can start the behaviors for a page and + * stop them all at once. The static bundle (islands.tsx) starts them once per page load and never stops them. + * The Astro client (src/astro/client.ts) starts them on every astro:page-load and stops them on + * astro:before-swap, so the client router's page swaps never stack listeners. + */ +import { render } from "preact"; + +import { type Entry, search } from "./search"; + +declare global { + interface Window { + apidocsSearch?: Entry[]; + } +} + + +/** The site root, from the page: "../../" on a static page, the site's base path on an Astro page. */ +export function siteRoot(): string { + return document.documentElement.getAttribute("data-root") ?? "./"; +} + +function storage(): Storage | undefined { + try { + return window.localStorage; + } catch { + return undefined; + } +} + +// ---- Theme switch: system, light, dark; the choice persists where storage works. + +export function themeSwitch(signal?: AbortSignal) { + const button = document.querySelector<HTMLButtonElement>("[data-theme-switch]"); + if (!button) return; + const modes = ["system", "light", "dark"] as const; + type Mode = (typeof modes)[number]; + let mode: Mode = "system"; + try { + const stored = storage()?.getItem("apidocs-theme"); + if (stored === "light" || stored === "dark") mode = stored; + } catch { + /* storage blocked: follow the system */ + } + const apply = () => { + if (mode === "system") document.documentElement.removeAttribute("data-theme"); + else document.documentElement.setAttribute("data-theme", mode); + button.dataset.mode = mode; + button.setAttribute("aria-label", `Color theme: ${mode}. Change`); + button.title = `Theme: ${mode}`; + }; + button.hidden = false; + apply(); + button.addEventListener("click", () => { + mode = modes[(modes.indexOf(mode) + 1) % modes.length]!; + try { + if (mode === "system") storage()?.removeItem("apidocs-theme"); + else storage()?.setItem("apidocs-theme", mode); + } catch { + /* not persisted */ + } + apply(); + }, { signal }); +} + +// ---- Copy buttons on signatures and code blocks. + +export function copyButtons(signal?: AbortSignal) { + for (const button of document.querySelectorAll<HTMLButtonElement>("[data-copy]")) { + button.hidden = false; + button.addEventListener("click", async () => { + const text = button.parentElement?.querySelector("pre")?.textContent ?? ""; + let ok = false; + try { + await navigator.clipboard.writeText(text); + ok = true; + } catch { + const area = document.createElement("textarea"); + area.value = text; + area.setAttribute("readonly", ""); + area.style.position = "fixed"; + area.style.opacity = "0"; + document.body.appendChild(area); + area.select(); + try { + ok = document.execCommand("copy"); + } catch { + ok = false; + } + area.remove(); + } + button.textContent = ok ? "Copied" : "Copy failed"; + button.dataset.copied = ""; + setTimeout(() => { + button.textContent = "Copy"; + delete button.dataset.copied; + }, 1500); + }, { signal }); + } +} + +// ---- Search over the lazily loaded index. + +function loadIndex(): Promise<Entry[]> { + if (window.apidocsSearch) return Promise.resolve(window.apidocsSearch); + return new Promise((resolve, reject) => { + const script = document.createElement("script"); + script.src = `${siteRoot()}assets/search-index.js`; + script.onload = () => (window.apidocsSearch ? resolve(window.apidocsSearch) : reject(new Error("empty index"))); + script.onerror = () => reject(new Error("search index did not load")); + document.head.appendChild(script); + }); +} + +/** The result rows, linked from the site root. Shared by the static search box and the Astro search island. */ +export function Results({ items, active, query, root }: { items: Entry[]; active: number; query: string; root: string }) { + if (!items.length) return <li class="search-empty" role="presentation">No declarations match “{query}”.</li>; + return ( + <> + {items.map((item, i) => ( + <li key={item[2]} id={`apidocs-result-${i}`} role="option" aria-selected={i === active ? "true" : "false"}> + <a href={root + item[2]} tabIndex={-1}> + <span class="result-label"><Highlight text={item[0]} query={query} /></span> + <span class="result-kind">{item[1]}</span> + {(item[3] || item[4]) && <span class="result-context">{[item[3], item[4]].filter(Boolean).join(": ")}</span>} + </a> + </li> + ))} + </> + ); +} + +function Highlight({ text, query }: { text: string; query: string }) { + const at = text.toLowerCase().indexOf(query.trim().toLowerCase()); + if (at < 0 || !query.trim()) return <>{text}</>; + const end = at + query.trim().length; + return <>{text.slice(0, at)}<mark>{text.slice(at, end)}</mark>{text.slice(end)}</>; +} + +/** Whether a key press is the given shortcut, typed outside a text field. */ +export function isShortcut(event: KeyboardEvent, key: string): boolean { + const target = event.target as HTMLElement; + return event.key === key && !event.metaKey && !event.ctrlKey && !event.altKey && !/^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName) && !target.isContentEditable; +} + +export function searchBox(signal?: AbortSignal) { + const box = document.querySelector<HTMLElement>("[data-search]"); + const input = box?.querySelector("input"); + const list = box?.querySelector<HTMLUListElement>("ul"); + if (!box || !input || !list) return; + box.hidden = false; + document.querySelector<HTMLElement>(".search-fallback")?.setAttribute("hidden", ""); + let items: Entry[] = []; + let active = 0; + let entries: Entry[] | undefined; + + const show = () => { + const open = input.value.trim().length > 0; + list.hidden = !open; + input.setAttribute("aria-expanded", String(open)); + if (open) { + render(<Results items={items} active={active} query={input.value} root={siteRoot()} />, list); + input.setAttribute("aria-activedescendant", items.length ? `apidocs-result-${active}` : ""); + document.getElementById(`apidocs-result-${active}`)?.scrollIntoView({ block: "nearest" }); + } + }; + const update = async () => { + try { + entries ??= await loadIndex(); + } catch { + entries = []; + } + items = search(entries, input.value); + active = 0; + show(); + }; + input.addEventListener("focus", () => void loadIndex().then(e => (entries = e)).catch(() => undefined), { signal }); + input.addEventListener("input", () => void update(), { signal }); + input.addEventListener("keydown", event => { + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + if (!items.length) return; + event.preventDefault(); + active = (active + (event.key === "ArrowDown" ? 1 : items.length - 1)) % items.length; + show(); + } else if (event.key === "Enter") { + const item = items[active]; + if (item) { + event.preventDefault(); + window.location.href = siteRoot() + item[2]; + } + } else if (event.key === "Escape") { + input.value = ""; + items = []; + show(); + input.blur(); + } + }, { signal }); + document.addEventListener("click", event => { + if (!box.contains(event.target as Node)) { + list.hidden = true; + input.setAttribute("aria-expanded", "false"); + } + }, { signal }); + document.addEventListener("keydown", event => { + if (isShortcut(event, "/")) { + event.preventDefault(); + input.focus(); + } + }, { signal }); +} + +// ---- Table of contents: mark the section in view. + +export function tableOfContents(signal?: AbortSignal) { + const toc = document.querySelector<HTMLElement>(".toc"); + const links = new Map<string, HTMLAnchorElement>(); + for (const link of document.querySelectorAll<HTMLAnchorElement>("[data-toc-target]")) links.set(link.dataset.tocTarget!, link); + if (!toc || !links.size || !("IntersectionObserver" in window)) return; + const visible = new Set<string>(); + let current: HTMLAnchorElement | undefined; + const observer = new IntersectionObserver(entries => { + for (const entry of entries) { + if (entry.isIntersecting) visible.add(entry.target.id); + else visible.delete(entry.target.id); + } + // The most specific entry in view: a member over the section that contains it. + let first: HTMLAnchorElement | undefined; + for (const [id, link] of links) { + if (!visible.has(id)) continue; + if (!first || (link.closest(".toc-entries") && !first.closest(".toc-entries"))) first = link; + if (first.closest(".toc-entries")) break; + } + if (first && first !== current) { + current?.removeAttribute("aria-current"); + first.setAttribute("aria-current", "true"); + current = first; + const fold = first.closest("details"); + if (fold) fold.open = true; + const top = first.offsetTop - toc.clientHeight / 3; + if (first.offsetTop < toc.scrollTop || first.offsetTop > toc.scrollTop + toc.clientHeight - 40) toc.scrollTop = Math.max(0, top); + } + }, { rootMargin: "-56px 0px -55% 0px" }); + for (const id of links.keys()) { + const target = document.getElementById(id); + if (target) observer.observe(target); + } + signal?.addEventListener("abort", () => observer.disconnect(), { once: true }); +} + +// ---- The navigator's scroll position across full page loads: saved when the page goes, restored on load. + +/** The key the navigator's scroll position is stored under: one per site. */ +export function navScrollKey(): string { + return `apidocs-nav:${new URL(siteRoot(), window.location.href).pathname}`; +} + +export function navigatorScroll(signal?: AbortSignal) { + const nav = document.querySelector<HTMLElement>(".sidebar"); + if (!nav) return; + const key = navScrollKey(); + let restored = false; + try { + const saved = window.sessionStorage.getItem(key); + if (saved) { + nav.scrollTop = Number(saved); + restored = true; + } + } catch { + /* storage blocked */ + } + const currentLink = nav.querySelector<HTMLElement>('[aria-current="page"]'); + if (currentLink && (!restored || currentLink.offsetTop < nav.scrollTop || currentLink.offsetTop > nav.scrollTop + nav.clientHeight)) { + nav.scrollTop = Math.max(0, currentLink.offsetTop - nav.clientHeight / 3); + } + saveNavigatorScroll(signal); +} + +/** Saves the navigator's scroll position when the page is left, for the next page of the site to restore. */ +export function saveNavigatorScroll(signal?: AbortSignal) { + window.addEventListener("pagehide", () => { + const nav = document.querySelector<HTMLElement>(".sidebar"); + if (!nav) return; + try { + window.sessionStorage.setItem(navScrollKey(), String(nav.scrollTop)); + } catch { + /* storage blocked */ + } + }, { signal }); +} + +// ---- List filters: narrow the navigator, or the page rail and the member summary, to rows that match. + +export function listFilter(boxSelector: string, rowSelector: string, also: string | undefined, signal?: AbortSignal) { + const box = document.querySelector<HTMLElement>(boxSelector); + const input = box?.querySelector<HTMLInputElement>("input"); + if (!box || !input) return; + box.hidden = false; + const apply = () => { + const query = input.value.trim().toLowerCase(); + const scope = box.parentElement!; + for (const fold of scope.querySelectorAll<HTMLDetailsElement>("details")) if (query) fold.open = true; + for (const row of scope.querySelectorAll<HTMLElement>(rowSelector)) { + const hit = !query || (row.textContent ?? "").toLowerCase().includes(query); + row.toggleAttribute("data-filtered-out", !hit); + } + if (also) { + for (const row of document.querySelectorAll<HTMLElement>(also)) { + const hit = !query || (row.querySelector("summary, th")?.textContent ?? "").toLowerCase().includes(query); + row.toggleAttribute("data-filtered-out", !hit); + } + } + }; + input.addEventListener("input", apply, { signal }); + input.addEventListener("keydown", event => { + if (event.key === "Escape") { + input.value = ""; + input.dispatchEvent(new Event("input")); + } + }, { signal }); + // A filter that kept its text across a client-side navigation applies to the new page's rows at once. + if (input.value.trim()) apply(); +} + +// ---- Copy the page as Markdown: read the Markdown file beside the page and put it on the clipboard. + +export function copyMarkdown(signal?: AbortSignal) { + const button = document.querySelector<HTMLButtonElement>("[data-copy-markdown]"); + if (!button) return; + const url = button.dataset.copyMarkdown!; + button.addEventListener("click", () => { + // XMLHttpRequest, not the newer API: the control exists only on a served page (data-served-only), and the + // output check forbids the newer call everywhere so that no page can come to depend on it from file://. + const request = new XMLHttpRequest(); + request.open("GET", url); + request.responseType = "text"; + const fail = () => { + window.location.href = url; + }; + request.onerror = fail; + request.onload = async () => { + if (request.status < 200 || request.status >= 300) return fail(); + try { + await navigator.clipboard.writeText(request.responseText); + } catch { + return fail(); + } + button.dataset.copied = ""; + button.setAttribute("aria-label", "Copied"); + setTimeout(() => { + delete button.dataset.copied; + button.setAttribute("aria-label", "Copy this page as Markdown"); + }, 1600); + }; + request.send(); + }, { signal }); +} + +// ---- Menus built on <details>: close on Escape and on a click elsewhere. + +/** The menus this closes: the page's formats menu, and a site's version menu. */ +const MENUS = "details.formats-menu[open], details.version-menu[open]"; + +export function menus(signal?: AbortSignal) { + const open = () => document.querySelectorAll<HTMLDetailsElement>(MENUS); + document.addEventListener("click", event => { + for (const menu of open()) if (!menu.contains(event.target as Node)) menu.open = false; + }, { signal }); + document.addEventListener("keydown", event => { + if (event.key !== "Escape") return; + for (const menu of open()) { + menu.open = false; + menu.querySelector<HTMLElement>("summary")?.focus(); + } + }, { signal }); +} + +// ---- Leaving for another page of this site: start the load bar; the next page finishes it. + +export function leaving(signal?: AbortSignal) { + const here = () => window.location.href.replace(/#.*$/, ""); + document.addEventListener("click", event => { + if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + const link = (event.target as Element).closest?.("a[href]") as HTMLAnchorElement | null; + if (!link || link.target || link.hasAttribute("download")) return; + if (link.origin !== window.location.origin || link.href.replace(/#.*$/, "") === here()) return; + if (!/\.html$/.test(link.pathname)) return; + document.documentElement.setAttribute("data-leaving", ""); + try { + window.sessionStorage.setItem("apidocs-load", "1"); + } catch { + /* storage blocked: the next page simply does not finish the bar */ + } + }, { signal }); + // Back from the page cache: this page never unloaded, so clear what the click left. + window.addEventListener("pageshow", () => document.documentElement.removeAttribute("data-leaving"), { signal }); +} + +// ---- Folded members: open or fold a whole group; open the member a link points at. + +export function members(signal?: AbortSignal) { + for (const button of document.querySelectorAll<HTMLButtonElement>("[data-expand-all]")) { + button.addEventListener("click", () => { + const open = button.getAttribute("aria-expanded") !== "true"; + for (const member of button.closest("section")!.querySelectorAll<HTMLDetailsElement>("details.member")) member.open = open; + button.setAttribute("aria-expanded", String(open)); + button.textContent = open ? "Collapse all" : "Expand all"; + }, { signal }); + } + // Browsers open a closed disclosure when a link lands inside it; this covers the ones that do not. + const reveal = () => { + const id = decodeURIComponent(window.location.hash.slice(1)); + const fold = id ? document.getElementById(id)?.closest("details") : null; + if (fold && !fold.open) { + fold.open = true; + document.getElementById(id)?.scrollIntoView(); + } + }; + window.addEventListener("hashchange", reveal, { signal }); + reveal(); +} + +// ---- The navigator toggle: remember "hidden" on wide screens; "[" toggles it. + +export function navigatorToggle(signal?: AbortSignal) { + const toggle = document.querySelector<HTMLInputElement>("#apidocs-nav-toggle"); + if (!toggle) return; + const wide = window.matchMedia("(min-width: 861px)"); + toggle.addEventListener("change", () => { + if (!wide.matches) return; + try { + window.localStorage.setItem("apidocs-nav", toggle.checked ? "closed" : "open"); + } catch { + /* storage blocked */ + } + }, { signal }); + // A narrow screen's open panel must not become a hidden navigator when the window grows, or the reverse. + wide.addEventListener("change", () => { + let closed = false; + try { + closed = window.localStorage.getItem("apidocs-nav") === "closed"; + } catch { + /* storage blocked */ + } + toggle.checked = wide.matches && closed; + }, { signal }); + document.addEventListener("keydown", event => { + if (isShortcut(event, "[")) { + toggle.checked = !toggle.checked; + toggle.dispatchEvent(new Event("change")); + } + }, { signal }); +} + +/** The behaviors every page has, whichever renderer wrote it. Search and the load bar differ, so callers add those. */ +export function pageBehaviors(signal?: AbortSignal) { + themeSwitch(signal); + copyButtons(signal); + tableOfContents(signal); + navigatorToggle(signal); + copyMarkdown(signal); + members(signal); + menus(signal); + // Types only: packages stay, so the way to another package is never filtered away. + listFilter("[data-nav-filter]", ".nav-section:not(:first-of-type) .nav-list > li", undefined, signal); + listFilter("[data-toc-filter]", ".toc-entries > li", ".members > details.member", signal); +} diff --git a/packages/apidocs/src/client/islands.tsx b/packages/apidocs/src/client/islands.tsx new file mode 100644 index 0000000..7094e83 --- /dev/null +++ b/packages/apidocs/src/client/islands.tsx @@ -0,0 +1,17 @@ +/** + * The static site's client bundle (assets/apidocs.js): the behaviors in behaviors.tsx over prerendered pages, + * started once per page load. Classic script, no modules, no fetch: the search index is a script that assigns + * window.apidocsSearch, loaded on first use. Astro pages use src/astro/client.ts instead. + */ +import { leaving, navigatorScroll, pageBehaviors, searchBox } from "./behaviors"; + +function start() { + document.documentElement.dataset.js = ""; + pageBehaviors(); + searchBox(); + navigatorScroll(); + leaving(); +} + +if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", start); +else start(); diff --git a/packages/apidocs/src/client/search.ts b/packages/apidocs/src/client/search.ts new file mode 100644 index 0000000..4bb9ff1 --- /dev/null +++ b/packages/apidocs/src/client/search.ts @@ -0,0 +1,37 @@ +/** Search ranking, shared by the client bundle and its tests. */ + +/** A search index entry: [label, kind, path from the site root, context, summary]. */ +export type Entry = [label: string, kind: string, path: string, context: string, summary: string]; + +// Guides lead: someone who types a topic wants the page that explains it. Sections rank with members. +const KIND_RANK: Record<string, number> = { guide: 0, section: 3, package: 0, method: 3, function: 3, field: 4, property: 4, constructor: 5, enumConstant: 4, annotationElement: 4 }; + +/** Ranks entries: exact name, prefix, word start, substring; types before members; shorter first. */ +export function search(entries: Entry[], query: string, limit = 40): Entry[] { + const q = query.trim().toLowerCase(); + if (!q) return []; + const scored: [number, Entry][] = []; + for (const entry of entries) { + const label = entry[0]; + const name = label.split("(")[0]!.toLowerCase(); + const simple = name.slice(name.lastIndexOf(".") + 1); + let score: number; + if (simple === q || name === q) score = 0; + else if (simple.startsWith(q)) score = 1; + else if (name.startsWith(q)) score = 2; + else if (wordStart(label, q)) score = 3; + else if (name.includes(q)) score = 4; + else if (`${entry[3]}.${label}`.toLowerCase().includes(q)) score = 5; + else continue; + scored.push([score * 10 + (KIND_RANK[entry[1]] ?? 1) + Math.min(label.length, 80) / 100, entry]); + } + scored.sort((a, b) => a[0] - b[0]); + return scored.slice(0, limit).map(s => s[1]); +} + +function wordStart(label: string, q: string): boolean { + // Camel-case and dotted word starts: "rt" matches "ResolvedType". + const starts = label.replace(/[^A-Za-z0-9]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(" ").map(w => w[0]?.toLowerCase()).join(""); + return starts.includes(q) || label.toLowerCase().split(/[.(\s]/).some(part => part.startsWith(q)); +} + diff --git a/packages/apidocs/src/components/callout.tsx b/packages/apidocs/src/components/callout.tsx new file mode 100644 index 0000000..8fb634e --- /dev/null +++ b/packages/apidocs/src/components/callout.tsx @@ -0,0 +1,37 @@ +/** Callouts: notes, deprecations and the admonitions of prose, in one design. */ +import type preact from "preact"; + +/** Icons for callouts: 16px line drawings in the callout's tone. */ +const CALLOUT_ICON: Record<string, preact.ComponentChildren> = { + // A caller's heads-up. + apiNote: <><circle cx="8" cy="8" r="6.25" /><path d="M8 4.6v3.9" /><path d="M8 11.1v.01" /></>, + // A requirement an override must meet. + implSpec: <><rect x="2.75" y="2.75" width="10.5" height="10.5" rx="2.5" /><path d="M5.4 8.2l1.8 1.8 3.4-3.9" /></>, + // A fact about the code. + implNote: <path d="M6 4.5 2.75 8 6 11.5M10 4.5 13.25 8 10 11.5" />, + deprecated: <><circle cx="8" cy="8" r="6.25" /><path d="M3.7 12.3l8.6-8.6" /></>, + // Tones for prose. + note: <><circle cx="8" cy="8" r="6.25" /><path d="M8 7.4v3.9" /><path d="M8 4.8v.01" /></>, + tip: <><path d="M5.6 10.4a4 4 0 1 1 4.8 0c-.4.3-.6.7-.6 1.2H6.2c0-.5-.2-.9-.6-1.2z" /><path d="M6.5 13.6h3" /></>, + important: <><path d="M3 3.25h10v7.5H8.4L5.5 13.3v-2.55H3z" /><path d="M8 5.4v2.4" /><path d="M8 9.3v.01" /></>, + warning: <><path d="M8 2.6 14.1 13H1.9z" /><path d="M8 6.5v3" /><path d="M8 11.3v.01" /></>, + caution: <><path d="M5.5 2.5h5l3 3v5l-3 3h-5l-3-3v-5z" /><path d="M8 5.3v3.2" /><path d="M8 10.6v.01" /></>, +}; + +/** + * A callout: an icon tile, a label and the text, in a soft panel. Tone and weight come from the kind: an API note + * and a deprecation are filled, an implementation note is an outline only. + */ +export function Callout({ kind, label, children }: { kind: string; label: preact.ComponentChildren; children: preact.ComponentChildren }) { + return ( + <div class={`callout callout-${kind}`} role="note"> + <span class="callout-icon" aria-hidden="true"> + <svg viewBox="0 0 16 16" width="16" height="16">{CALLOUT_ICON[kind]}</svg> + </span> + <div class="callout-body"> + <p class="callout-label">{label}</p> + {children} + </div> + </div> + ); +} diff --git a/packages/apidocs/src/components/chrome.tsx b/packages/apidocs/src/components/chrome.tsx new file mode 100644 index 0000000..2008363 --- /dev/null +++ b/packages/apidocs/src/components/chrome.tsx @@ -0,0 +1,720 @@ +/** + * The page shell: head, header, navigation, breadcrumbs, table of contents and footer. + * + * Two renderers compose these parts. The static renderer (src/render.tsx) renders Shell into a whole document + * that works from file:// and inside a jar. The Astro integration (src/astro/) renders the same Shell in its + * "astro" variant: the same markup, minus what only a static site needs (its stylesheet links, the deferred + * client bundle, speculation rules), plus the attributes the client router persists elements by and named holes + * where Astro puts its own content (a slot in the top bar, the search island, a notice above the page). + */ +import { createContext, type ComponentChildren } from "preact"; +import { useContext } from "preact/hooks"; +import { type PageContext, usePage } from "../context"; +import type { Package, Type } from "../model"; +import { INDEX, guideNav, indexPages, isAbsolute, isThrowable, packagePage, relative, rootOf, typePage } from "../site"; +import { typeGroups } from "../structure"; +import type { Theme } from "../theme"; +import { SYMBOLS, sym } from "../symbols"; + +export interface Crumb { + label: string; + page?: string; +} + +export interface TocItem { + id: string; + label: string; + depth: number; + code?: boolean; +} + +/** + * Which document Shell renders. "static" (the default) is the static renderer's page. "astro" is the Astro + * integration's: `persist` names the elements the client router keeps across navigations within one site. + */ +export type ShellVariant = { kind: "static" } | { kind: "astro"; persist: string }; + +export const ShellVariantContext = createContext<ShellVariant>({ kind: "static" }); + +function useVariant(): ShellVariant { + return useContext(ShellVariantContext); +} + +/** A named place in the astro variant's markup where the Astro component puts its own content. */ +export const HOLES = ["topbar", "search", "notice"] as const; +export type Hole = (typeof HOLES)[number]; + +function HoleMark({ name }: { name: Hole }) { + const Tag = "apidocs-hole" as "span"; + return <Tag {...({ name } as object)} />; +} + +/** The attribute Astro's client router keeps an element by (what `transition:persist="id"` compiles to). */ +function persistAttr(variant: ShellVariant, id: string): Record<string, string> { + return variant.kind === "astro" ? { "data-astro-transition-persist": `${id}:${variant.persist}` } : {}; +} + +/** + * Runs before first paint: applies a stored theme choice, and marks the page as scripted so the controls that + * need the script take their space at once instead of appearing (and moving the page) when the bundle loads. + */ +export const THEME_BOOT = + 'var d=document.documentElement;d.setAttribute("data-js","");' + + // A page opened from disk cannot read its neighbors, so the controls that need to are left out there. + 'if(location.protocol==="file:")d.setAttribute("data-file","");' + + // Color emoji are used only where the platform draws them well; elsewhere the drawn icons stay. + 'try{if(!/Win/.test((navigator.userAgentData&&navigator.userAgentData.platform)||navigator.platform||""))d.setAttribute("data-emoji","")}catch(e){}' + + // Coming from another page of this site: finish the load bar that page started. + 'try{if(sessionStorage.getItem("apidocs-load")){sessionStorage.removeItem("apidocs-load");d.setAttribute("data-arriving","")}}catch(e){}' + + 'try{var t=localStorage.getItem("apidocs-theme");if(t==="light"||t==="dark")document.documentElement.setAttribute("data-theme",t)}catch(e){}'; + +/** The width that keeps an SVG's aspect ratio at a height, from its viewBox, so the image reserves its box before it loads. */ +function logoWidth(svg: string, height: number): number | undefined { + const box = /viewBox="\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)/.exec(svg); + if (!box) return undefined; + const w = Number(box[1]); + const h = Number(box[2]); + return w > 0 && h > 0 ? Math.round((height * w) / h) : undefined; +} + +/** Restores the navigator's scroll position as soon as it is parsed, so it never jumps after paint. */ +const NAV_BOOT = + '(function(){var n=document.getElementById("apidocs-nav");if(!n)return;try{var k="apidocs-nav:"+new URL(document.documentElement.getAttribute("data-root")||"./",location.href).pathname;var s=sessionStorage.getItem(k);if(s)n.scrollTop=+s}catch(e){}var c=n.querySelector(\'[aria-current="page"]\');if(c&&(c.offsetTop<n.scrollTop||c.offsetTop>n.scrollTop+n.clientHeight-40))n.scrollTop=Math.max(0,c.offsetTop-n.clientHeight/3)})()'; + +/** + * Preloads the upright font files, so they are ready at first paint. Done from the head script, not with link + * elements in the markup, because a font preload is a cross-origin request and a page opened from file:// has + * no origin to make one with: there the links would fail and log errors, and the faces load from CSS as usual. + */ +function fontPreload(fonts: Theme["fonts"], root: string): string { + const urls = (fonts ?? []) + .filter(face => face.preload ?? (face.style ?? "normal") === "normal") + .map(face => `${root}assets/${face.asset}`); + if (urls.length === 0) return ""; + const list = JSON.stringify(urls).replace(/</g, "\\u003c"); + return `;if(location.protocol!=="file:")${list}.forEach(function(h){var l=document.createElement("link");l.rel="preload";l.as="font";l.type="font/woff2";l.crossOrigin="anonymous";l.href=h;document.head.appendChild(l)})`; +} + +/** Pages of this site only: relative links to .html files. Other sites are never preloaded. */ +const SPECULATION = JSON.stringify({ + prerender: [{ where: { selector_matches: "a[href$='.html']:not([href*='://']), a[href*='.html#']:not([href*='://'])" }, eagerness: "moderate" }], +}); + +/** Applies a stored "navigator hidden" choice on a wide screen, before the navigator is painted. */ +const NAV_STATE_BOOT = + 'try{if(matchMedia("(min-width:861px)").matches&&localStorage.getItem("apidocs-nav")==="closed")document.getElementById("apidocs-nav-toggle").checked=true}catch(e){}'; + +export interface ShellProps { + title: string; + description: string; + crumbs: Crumb[]; + toc: TocItem[]; + jsonLd: object; + /** What the page documents, for machine-readable metadata. */ + meta?: PageMeta; + children: ComponentChildren; +} + +export interface PageMeta { + kind: "module" | "package" | "type" | "guide"; + /** The declaration's stable id. */ + id?: string; + package?: string; + language?: string; + /** Terms a search should find this page by, most specific first. */ + keywords?: string[]; +} + +/** Where a page's machine-readable versions are: absolute when the site's address is known, else relative to the page. */ +export interface Formats { + markdown: string; + llms: string; + full: string; + model: string; +} + +/** + * A page's head metadata as data: what HeadMeta renders, and what a program can compare or reuse. URLs are in + * the static renderer's form (relative, or under theme.baseUrl, naming .html files); the Astro integration maps + * them to its own form after rendering. + */ +export interface HeadData { + title: string; + description: string; + keywords: string[]; + /** The product the pages belong to: the theme's productName, else the module's name. */ + product: string; + canonical?: string; + /** name or property, and content, in document order. */ + meta: { name?: string; property?: string; content: string }[]; + /** The alternate and index links, in document order. */ + links: { rel: string; type?: string; href: string; title: string }[]; + formats: Formats; + /** The JSON-LD graph. */ + jsonLd: object; +} + +/** The head metadata of the page being rendered, from Shell's props. */ +export function headData(ctx: PageContext, props: Pick<ShellProps, "title" | "description" | "crumbs" | "jsonLd" | "meta">): HeadData { + const { site, theme, page } = ctx; + const { title, description, crumbs, jsonLd, meta } = props; + const root = rootOf(page); + const name = page.split("/").pop()!; + const product = theme.productName ?? site.model.module.name; + const canonical = theme.baseUrl ? `${theme.baseUrl}${page}.html` : undefined; + const m = site.model.module; + const at = (path: string, fromRoot: boolean) => (theme.baseUrl ? `${theme.baseUrl}${fromRoot ? path : `${page.slice(0, page.lastIndexOf("/") + 1)}${path}`}` : `${fromRoot ? root : ""}${path}`); + const formats: Formats = { + markdown: at(`${name}.md`, false), + llms: at("llms.txt", true), + full: at("llms-full.txt", true), + model: at("api.json", true), + }; + const keywords = [...new Set([...(meta?.keywords ?? []), m.name, ...(m.languages ?? []).map(languageName), ...(site.packages.length ? ["API reference"] : [])])].filter(Boolean); + const graph = { + "@context": "https://schema.org", + "@graph": [ + { + ...jsonLd, + "@context": undefined, + headline: title, + inLanguage: "en", + keywords: keywords.join(", "), + encoding: [{ "@type": "MediaObject", encodingFormat: "text/markdown", contentUrl: formats.markdown, name: "This page as Markdown" }], + ...(m.version ? { version: m.version } : {}), + }, + ...(crumbs.length > 1 + ? [{ + "@type": "BreadcrumbList", + itemListElement: crumbs.map((crumb, i) => ({ + "@type": "ListItem", + position: i + 1, + name: crumb.label, + item: theme.baseUrl ? `${theme.baseUrl}${crumb.page ?? page}.html` : relative(page, crumb.page ?? page, ".html"), + })), + }] + : []), + { + "@type": "DataCatalog", + name: `${product} machine-readable reference`, + description: "The same reference as Markdown and JSON, for programs and AI agents.", + dataset: [ + { "@type": "Dataset", name: "llms.txt", description: "Index of every page as Markdown links.", encodingFormat: "text/markdown", url: formats.llms }, + { "@type": "Dataset", name: "llms-full.txt", description: "The whole reference in one Markdown file.", encodingFormat: "text/markdown", url: formats.full }, + { "@type": "Dataset", name: "api.json", description: "The apidocs/1 model of the module.", encodingFormat: "application/json", url: formats.model }, + ], + }, + ], + }; + const tags: HeadData["meta"] = [ + { name: "description", content: description }, + { name: "keywords", content: keywords.join(", ") }, + { name: "generator", content: "apidocs" }, + { name: "color-scheme", content: "light dark" }, + // What this page documents, for programs that read pages. + { name: "apidocs:kind", content: meta?.kind ?? "module" }, + { name: "apidocs:module", content: m.name }, + ...(m.version ? [{ name: "apidocs:version", content: m.version }] : []), + ...(meta?.id ? [{ name: "apidocs:id", content: meta.id }] : []), + ...(meta?.package ? [{ name: "apidocs:package", content: meta.package }] : []), + ...(meta?.language ? [{ name: "apidocs:language", content: meta.language }] : []), + { property: "og:type", content: meta?.kind === "module" || !meta ? "website" : "article" }, + { property: "og:title", content: title }, + { property: "og:description", content: description }, + { property: "og:site_name", content: product }, + ...(canonical ? [{ property: "og:url", content: canonical }] : []), + { name: "twitter:card", content: "summary" }, + ]; + // The same content for programs and AI agents: this page as Markdown, the index, the whole reference, the model. + const links: HeadData["links"] = [ + { rel: "alternate", type: "text/markdown", href: `${name}.md`, title: "This page as Markdown" }, + { rel: "alternate", type: "text/markdown", href: `${root}llms.txt`, title: "llms.txt: index of every page, as Markdown links" }, + { rel: "alternate", type: "text/markdown", href: `${root}llms-full.txt`, title: "llms-full.txt: the whole reference in one Markdown file" }, + { rel: "alternate", type: "application/json", href: `${root}api.json`, title: "api.json: the apidocs/1 model of this module" }, + { rel: "index", href: `${root}index.html`, title: `${product} API reference` }, + ]; + return { title, description, keywords, product, canonical, meta: tags, links, formats, jsonLd: graph }; +} + +/** The head's metadata elements: charset and viewport, title, meta tags, canonical, alternates and index. */ +export function HeadMeta({ head }: { head: HeadData }) { + return ( + <> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>{head.title} + {head.meta.map(tag => )} + {head.canonical && } + {head.links.map(link => )} + + ); +} + +/** The JSON-LD graph as a script element; the head's last element. */ +export function JsonLd({ head }: { head: HeadData }) { + return
Geo user guide2.1.0

Concepts

Callouts

The five GitHub alerts, an explicit heading id and raw HTML.

Before you start

Note

Measurements are exact for circles and polygons.

Tip

Reuse a Shapes.Builder to build many shapes.

Important

Shapes are immutable: every transform returns a new shape.

Warning

A polygon whose edges cross has no defined area.

Caution

Shapes.parse reads untrusted text: limit its input size.

It allocates one object per vertex.

A plain quote

Geometry is the art of correct reasoning from incorrectly drawn figures.

Raw HTML

Press Ctrl+C to copy. Water is H2O, and E = mc2.

+
Area
+
The size of the inside.
+

Back to the concepts.

+" +`; diff --git a/packages/apidocs/test/__snapshots__/indexes.test.ts.snap b/packages/apidocs/test/__snapshots__/indexes.test.ts.snap new file mode 100644 index 0000000..4c61d64 --- /dev/null +++ b/packages/apidocs/test/__snapshots__/indexes.test.ts.snap @@ -0,0 +1,207 @@ +// Bun Snapshot v1, https://bun.sh/docs/test/snapshots + +exports[`index pages Markdown snapshots of the fixture's index pages: packages.md 1`] = ` +"# Packages + +Every package of fixture. + +- [\`fixture.java\`](fixture/java/index.md) (1 abstract class, 1 annotation interface, 7 class, 2 enum class, 1 exception, 3 interface, 1 record, 1 sealed interface): Shapes, units and measurements: a fixture that exercises every declaration kind and documentation construct the API model represents. +- [\`fixture.java.io\`](fixture/java/io/index.md) (1 class): Reading shapes from streams. +" +`; + +exports[`index pages Markdown snapshots of the fixture's index pages: types.md 1`] = ` +"# All types + +Every type of fixture, nested ones too, by name. + +- [\`AbstractCanvas\`](fixture/java/AbstractCanvas.md), abstract class in fixture.java: A canvas that counts what it draws. +- [\`Box\`](fixture/java/Box.md), class in fixture.java: A mutable holder for one comparable value. +- [\`Builder\`](fixture/java/Polygon.Builder.md), class in fixture.java: Builds a polygon one side at a time. +- [\`Canvas\`](fixture/java/Canvas.md), interface in fixture.java: Somewhere to draw shapes. +- [\`Circle\`](fixture/java/Circle.md), record in fixture.java: A circle. +- [\`Edge\`](fixture/java/Polygon.Edge.md), class in fixture.java: One edge of this polygon: an inner class, bound to its polygon. +- [\`Geometry\`](fixture/java/Geometry.md), class in fixture.java: Operations on [\`shapes\`](fixture/java/Shape.md). +- [\`GeometryException\`](fixture/java/GeometryException.md), exception in fixture.java: A shape that cannot exist, such as a triangle whose sides violate the triangle inequality. +- [\`Kind\`](fixture/java/Canvas.Layer.Kind.md), enum class in fixture.java: What a layer holds. +- [\`Layer\`](fixture/java/Canvas.Layer.md), interface in fixture.java: One layer of a canvas. +- [\`Legacy\`](fixture/java/Geometry.Legacy.md), class in fixture.java: Methods from before null markings; their nullness is unspecified. +- [\`Measured\`](fixture/java/Measured.md), annotation interface in fixture.java: Marks a declaration whose values are lengths, and in which unit. +- [\`Polygon\`](fixture/java/Polygon.md), class in fixture.java: A regular polygon. +- [\`Rect\`](fixture/java/Rect.md), class in fixture.java: An axis-aligned rectangle. +- [\`Shape\`](fixture/java/Shape.md), sealed interface in fixture.java: A closed plane figure. +- [\`ShapeReader\`](fixture/java/io/ShapeReader.md), class in fixture.java.io: Reads shapes in their [text form](fixture/java/Geometry.md#parse%28java.lang.String%29), one per line. +- [\`Units\`](fixture/java/Units.md), enum class in fixture.java: Units of length. +- [\`Visitor\`](fixture/java/Shape.Visitor.md), interface in fixture.java: Operations over each kind of shape. +" +`; + +exports[`index pages Markdown snapshots of the fixture's index pages: index-all.md 1`] = ` +"# Index + +Every declaration of fixture, from A to Z. + +## A + +- [\`AbstractCanvas\`](fixture/java/AbstractCanvas.md), abstract class in fixture.java: A canvas that counts what it draws. +- [\`accept(Shape.Visitor)\`](fixture/java/Circle.md#accept%28fixture.java.Shape.Visitor%29), method in Circle: Calls the visitor's method for this shape's kind. +- [\`accept(Shape.Visitor)\`](fixture/java/Polygon.md#accept%28fixture.java.Shape.Visitor%29), method in Polygon: Calls the visitor's method for this shape's kind. +- [\`accept(Shape.Visitor)\`](fixture/java/Rect.md#accept%28fixture.java.Shape.Visitor%29), method in Rect: Calls the visitor's method for this shape's kind. +- [\`accept(Shape.Visitor)\`](fixture/java/Shape.md#accept%28fixture.java.Shape.Visitor%29), method in Shape: Calls the visitor's method for this shape's kind. +- [\`area()\`](fixture/java/Circle.md#area%28%29), method in Circle: The shape's area. +- [\`area()\`](fixture/java/Polygon.md#area%28%29), method in Polygon: The area of a regular polygon with these sides' mean length. +- [\`area()\`](fixture/java/Rect.md#area%28%29), method in Rect: The shape's area. +- [\`area()\`](fixture/java/Shape.md#area%28%29), method in Shape: The shape's area. + +## B + +- [\`BACKGROUND\`](fixture/java/Canvas.Layer.Kind.md#BACKGROUND), enum constant in Canvas.Layer.Kind: Background fills. +- [\`Box\`](fixture/java/Box.md), class in fixture.java: A mutable holder for one comparable value. +- [\`Box(T)\`](fixture/java/Box.md#%3Cinit%3E%28T%29), constructor in Box: Creates a box. +- [\`build()\`](fixture/java/Polygon.Builder.md#build%28%29), method in Polygon.Builder: Builds the polygon. +- [\`Builder\`](fixture/java/Polygon.Builder.md), class in fixture.java: Builds a polygon one side at a time. +- [\`Builder()\`](fixture/java/Polygon.Builder.md#%3Cinit%3E%28%29), constructor in Polygon.Builder: Creates an empty builder. + +## C + +- [\`Canvas\`](fixture/java/Canvas.md), interface in fixture.java: Somewhere to draw shapes. +- [\`Circle\`](fixture/java/Circle.md), record in fixture.java: A circle. +- [\`Circle(double, String)\`](fixture/java/Circle.md#%3Cinit%3E%28double,java.lang.String%29), constructor in Circle: Checks the radius. +- [\`clear()\`](fixture/java/Canvas.md#clear%28%29), method in Canvas: Clears every layer. +- [\`close()\`](fixture/java/io/ShapeReader.md#close%28%29), method in ShapeReader: Closes the underlying reader. +- [\`compareTo(Box)\`](fixture/java/Box.md#compareTo%28fixture.java.Box%29), method in Box: Compares the value with another box's. +- [\`compareTo(Shape)\`](fixture/java/Shape.md#compareTo%28fixture.java.Shape%29), method in Shape: Compares shapes by area. + +## D + +- [\`draw(Shape, Canvas.Layer)\`](fixture/java/AbstractCanvas.md#draw%28fixture.java.Shape,fixture.java.Canvas.Layer%29), method in AbstractCanvas: Draws a shape on a layer. +- [\`draw(Shape, Canvas.Layer)\`](fixture/java/Canvas.md#draw%28fixture.java.Shape,fixture.java.Canvas.Layer%29), method in Canvas: Draws a shape on a layer. +- [\`drawn()\`](fixture/java/AbstractCanvas.md#drawn%28%29), method in AbstractCanvas: The number of shapes drawn so far. + +## E + +- [\`Edge\`](fixture/java/Polygon.Edge.md), class in fixture.java: One edge of this polygon: an inner class, bound to its polygon. +- [\`Edge(int)\`](fixture/java/Polygon.Edge.md#%3Cinit%3E%28int%29), constructor in Polygon.Edge: Selects an edge. +- [\`empty()\`](fixture/java/Canvas.md#empty%28%29), method in Canvas: A canvas that ignores everything drawn on it. +- [\`equals(Object)\`](fixture/java/Circle.md#equals%28java.lang.Object%29), method in Circle + +## F + +- [\`FEET\`](fixture/java/Units.md#FEET), enum constant in Units (deprecated): International feet. +- [\`find(Map, String)\`](fixture/java/Geometry.md#find%28java.util.Map,java.lang.String%29), method in Geometry: Finds a shape by name. + +## G + +- [\`Geometry\`](fixture/java/Geometry.md), class in fixture.java: Operations on [\`shapes\`](fixture/java/Shape.md). +- [\`GeometryException\`](fixture/java/GeometryException.md), exception in fixture.java: A shape that cannot exist, such as a triangle whose sides violate the triangle inequality. +- [\`GeometryException(String)\`](fixture/java/GeometryException.md#%3Cinit%3E%28java.lang.String%29), constructor in GeometryException: Creates an exception. +- [\`GeometryException(String, Throwable)\`](fixture/java/GeometryException.md#%3Cinit%3E%28java.lang.String,java.lang.Throwable%29), constructor in GeometryException: Creates an exception with a cause. + +## H + +- [\`hashCode()\`](fixture/java/Circle.md#hashCode%28%29), method in Circle +- [\`height\`](fixture/java/Rect.md#height), field in Rect: The height in meters. + +## I + +- [\`index()\`](fixture/java/Canvas.Layer.md#index%28%29), method in Canvas.Layer: The layer's index. + +## K + +- [\`Kind\`](fixture/java/Canvas.Layer.Kind.md), enum class in fixture.java: What a layer holds. +- [\`kind()\`](fixture/java/Canvas.Layer.md#kind%28%29), method in Canvas.Layer: What a layer holds. + +## L + +- [\`label()\`](fixture/java/Circle.md#label%28%29), method in Circle +- [\`largest(Collection)\`](fixture/java/Geometry.md#largest%28java.util.Collection%29), method in Geometry: Returns the largest shape. +- [\`Layer\`](fixture/java/Canvas.Layer.md), interface in fixture.java: One layer of a canvas. +- [\`Legacy\`](fixture/java/Geometry.Legacy.md), class in fixture.java: Methods from before null markings; their nullness is unspecified. +- [\`length()\`](fixture/java/Polygon.Edge.md#length%28%29), method in Polygon.Edge: The edge's length. + +## M + +- [\`map(Function)\`](fixture/java/Box.md#map%28java.util.function.Function%29), method in Box: Applies a function to the value. +- [\`MAX_LAYERS\`](fixture/java/Canvas.md#MAX_LAYERS), field in Canvas: The largest layer index a canvas supports. +- [\`Measured\`](fixture/java/Measured.md), annotation interface in fixture.java: Marks a declaration whose values are lengths, and in which unit. +- [\`METERS\`](fixture/java/Units.md#METERS), enum constant in Units: Meters: the base unit. + +## N + +- [\`NAME\`](fixture/java/Geometry.md#NAME), field in Geometry: The library's name, [\`"fixture"\`](fixture/java/Geometry.md#NAME), as tools report it. +- [\`name()\`](fixture/java/Circle.md#name%28%29), method in Circle: Returns the shape's name, or \`null\` for an anonymous shape. +- [\`name()\`](fixture/java/Shape.md#name%28%29), method in Shape: Returns the shape's name, or \`null\` for an anonymous shape. +- [\`nameOf(Shape)\`](fixture/java/Geometry.Legacy.md#nameOf%28fixture.java.Shape%29), method in Geometry.Legacy: Returns the name, possibly \`null\`. + +## O + +- [\`of(double)\`](fixture/java/Circle.md#of%28double%29), method in Circle: Creates an unlabeled circle. +- [\`open(Reader)\`](fixture/java/io/ShapeReader.md#open%28java.io.Reader%29), method in ShapeReader: Opens a reader. + +## P + +- [\`parse(String)\`](fixture/java/Geometry.md#parse%28java.lang.String%29), method in Geometry: Parses a shape from its text form, such as \`circle 2.5\`. +- [\`Polygon\`](fixture/java/Polygon.md), class in fixture.java: A regular polygon. +- [\`Polygon(double...)\`](fixture/java/Polygon.md#%3Cinit%3E%28double...%29), constructor in Polygon: Creates a polygon from its sides. +- [\`PRECISION\`](fixture/java/Geometry.md#PRECISION), field in Geometry: The default number of significant digits: \`6\`. +- [\`precision()\`](fixture/java/Measured.md#precision%28%29), element in Measured: Significant digits. +- [\`present()\`](fixture/java/Box.md#present%28%29), method in Box: Returns whether the box holds a value. + +## R + +- [\`radius()\`](fixture/java/Circle.md#radius%28%29), method in Circle +- [\`read(InputStream)\`](fixture/java/io/ShapeReader.md#read%28java.io.InputStream%29), method in ShapeReader: Reads every shape from a stream of UTF-8 text. +- [\`read(Reader, Charset)\`](fixture/java/io/ShapeReader.md#read%28java.io.Reader,java.nio.charset.Charset%29), method in ShapeReader: Reads every shape from a reader. +- [\`Rect\`](fixture/java/Rect.md), class in fixture.java: An axis-aligned rectangle. +- [\`Rect(double, double)\`](fixture/java/Rect.md#%3Cinit%3E%28double,double%29), constructor in Rect: Creates a rectangle. + +## S + +- [\`Shape\`](fixture/java/Shape.md), sealed interface in fixture.java: A closed plane figure. +- [\`ShapeReader\`](fixture/java/io/ShapeReader.md), class in fixture.java.io: Reads shapes in their [text form](fixture/java/Geometry.md#parse%28java.lang.String%29), one per line. +- [\`SHAPES\`](fixture/java/Canvas.Layer.Kind.md#SHAPES), enum constant in Canvas.Layer.Kind: Shapes. +- [\`side(double)\`](fixture/java/Polygon.Builder.md#side%28double%29), method in Polygon.Builder: Adds a side. +- [\`square(double)\`](fixture/java/Rect.md#square%28double%29), method in Rect: Creates a square. +- [\`sum(List)\`](fixture/java/Geometry.md#sum%28java.util.List%29), method in Geometry (deprecated for removal): Sums the areas of a list of shapes. + +## T + +- [\`tags()\`](fixture/java/Measured.md#tags%28%29), element in Measured: Free-form tags. +- [\`toMeters(double)\`](fixture/java/Units.md#toMeters%28double%29), method in Units: Converts a length in this unit to meters. +- [\`toString()\`](fixture/java/Circle.md#toString%28%29), method in Circle +- [\`totalArea(Shape...)\`](fixture/java/Geometry.md#totalArea%28fixture.java.Shape...%29), method in Geometry: Sums the shapes' areas. + +## U + +- [\`unit()\`](fixture/java/Measured.md#unit%28%29), element in Measured: The unit of the values. +- [\`Units\`](fixture/java/Units.md), enum class in fixture.java: Units of length. + +## V + +- [\`value\`](fixture/java/Box.md#value), field in Box: The value, or \`null\` when the box is empty. +- [\`valueOf(String)\`](fixture/java/Canvas.Layer.Kind.md#valueOf%28java.lang.String%29), method in Canvas.Layer.Kind +- [\`valueOf(String)\`](fixture/java/Units.md#valueOf%28java.lang.String%29), method in Units +- [\`values()\`](fixture/java/Canvas.Layer.Kind.md#values%28%29), method in Canvas.Layer.Kind +- [\`values()\`](fixture/java/Units.md#values%28%29), method in Units +- [\`visitCircle(Circle)\`](fixture/java/Shape.Visitor.md#visitCircle%28fixture.java.Circle%29), method in Shape.Visitor: Visits a circle. +- [\`Visitor\`](fixture/java/Shape.Visitor.md), interface in fixture.java: Operations over each kind of shape. +- [\`visitPolygon(Polygon)\`](fixture/java/Shape.Visitor.md#visitPolygon%28fixture.java.Polygon%29), method in Shape.Visitor: Visits a polygon. +- [\`visitRect(Rect)\`](fixture/java/Shape.Visitor.md#visitRect%28fixture.java.Rect%29), method in Shape.Visitor: Visits a rectangle. + +## W + +- [\`width\`](fixture/java/Rect.md#width), field in Rect: The width in meters. +" +`; + +exports[`index pages Markdown snapshots of the fixture's index pages: deprecated.md 1`] = ` +"# Deprecated + +Everything deprecated in fixture; what will be removed comes first. + +## Members + +- [\`sum(List)\`](fixture/java/Geometry.md#sum%28java.util.List%29), method in Geometry (deprecated for removal) Since 1.1. Use [\`totalArea(Shape...)\`](fixture/java/Geometry.md#totalArea%28fixture.java.Shape...%29), which takes any number of shapes. +- [\`FEET\`](fixture/java/Units.md#FEET), enum constant in Units (deprecated) Since 1.2. Use [\`METERS\`](fixture/java/Units.md#METERS); mixing units causes rounding errors. +" +`; diff --git a/packages/apidocs/test/__snapshots__/markdown.test.ts.snap b/packages/apidocs/test/__snapshots__/markdown.test.ts.snap new file mode 100644 index 0000000..7db7955 --- /dev/null +++ b/packages/apidocs/test/__snapshots__/markdown.test.ts.snap @@ -0,0 +1,530 @@ +// Bun Snapshot v1, https://bun.sh/docs/test/snapshots + +exports[`Markdown snapshots of the fixture: fixture/java/Geometry.md 1`] = ` +"# Geometry + +[fixture](../../index.md) › [fixture.java](index.md) · Every page: [llms.txt](../../llms.txt) + +Class in [\`fixture.java\`](index.md). Since 1.0. Null-marked: types are non-null unless annotated. + +\`\`\`java +public final class Geometry +\`\`\` + +Inheritance: [\`Object\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > \`Geometry\` + +Operations on [\`shapes\`](Shape.md). + +Every method is *pure*: it never modifies its arguments. **Thread safety:** every method is safe to call concurrently. + +- [\`largest(Collection)\`](Geometry.md#largest%28java.util.Collection%29) picks the largest shape. +- [\`totalArea(Shape...)\`](Geometry.md#totalArea%28fixture.java.Shape...%29) sums areas. + +1. First, measure. +2. Then compare, with \`compareTo\`. + +Unit factors + +| Unit | Factor | +| --- | --- | +| [\`Units.METERS\`](Units.md#METERS) | 1.0 | +| [\`Units.FEET\`](Units.md#FEET) | 0.3048 | + +\`\`\`java +Shape big = Geometry.largest(List.of(Circle.of(1), Rect.square(2))); +double total = Geometry.totalArea(big, Circle.of(3)); +\`\`\` + +> Measure twice, cut once. + +## Edge cases + +Text with an entity — a superscript kept as raw markup, a line + break, a [hyperlink](https://example.com/spec), and \\ as literal text. + +> **Implementation note** +> +> Areas are computed in double precision. + +**See also** + +- [\`Shape\`](Shape.md) +- [\`the area of a shape\`](Shape.md#area%28%29) +- "Euclid, Elements, Book I" +- [Area](https://en.wikipedia.org/wiki/Area) + +## Nested types + +- [\`Geometry.Legacy\`](Geometry.Legacy.md) (class): Methods from before null markings; their nullness is unspecified. + +## Fields + +### PRECISION + +\`\`\`java +public static final int PRECISION +\`\`\` + +The default number of significant digits: \`6\`. + +Constant value: \`6\` + +### NAME + +\`\`\`java +public static final String NAME +\`\`\` + +The library's name, [\`"fixture"\`](Geometry.md#NAME), as tools report it. + +Constant value: \`"fixture"\` + +## Methods + +### largest(Collection) + +\`\`\`java +public static > T largest(Collection shapes) +\`\`\` + +Returns the largest shape. + +**Type parameters** + +- \`\`: the shape type + +**Parameters** + +- \`shapes\` [\`Collection\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Collection.html)\`\` (non-null): the shapes; not empty + +**Returns** \`T\`: the largest of \`shapes\` + +**Throws** + +- [\`NoSuchElementException\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/NoSuchElementException.html) (unchecked): if \`shapes\` is empty + +> **Implementation requirements** +> +> Compares with [\`Comparable.compareTo(Object)\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Comparable.html#compareTo%28T%29), keeping the first of equal shapes. + +### totalArea(Shape...) + +\`\`\`java +@Measured(precision = 6) +public static double totalArea(Shape... shapes) +\`\`\` + +Sums the shapes' areas. + +**Parameters** + +- \`shapes\` [\`Shape\`](Shape.md)\`...\` (non-null): the shapes + +**Returns** \`double\`: the total area in square meters; \`0\` for no shapes + +### parse(String) + +\`\`\`java +public static Shape parse(String text) throws IOException, ParseException +\`\`\` + +Parses a shape from its text form, such as \`circle 2.5\`. + +**Parameters** + +- \`text\` [\`String\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) (non-null): the text form + +**Returns** [\`Shape\`](Shape.md) (non-null): the shape + +**Throws** + +- [\`IOException\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html): if the text names a file that cannot be read +- [\`IllegalStateException\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html) (unchecked): if the parser was closed +- [\`ParseException\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/text/ParseException.html): No description. + +> **API note** +> +> The text form is not stable across releases; store shapes some other way. + +### sum(List) + +\`\`\`java +@Deprecated(since = "1.1", forRemoval = true) +public static double sum(List shapes) +\`\`\` + +> **Deprecated for removal since 1.1.** +> +> Use [\`totalArea(Shape...)\`](Geometry.md#totalArea%28fixture.java.Shape...%29), which takes any number of shapes. + +Sums the areas of a list of shapes. + +**Parameters** + +- \`shapes\` [\`List\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html)\`<\`[\`Shape\`](Shape.md)\`>\` (non-null): the shapes + +**Returns** \`double\`: the total area + +### find(Map, String) + +\`\`\`java +public static @Nullable Shape find(Map shapes, String name) +\`\`\` + +Since 1.1. + +Finds a shape by name. + +**Parameters** + +- \`shapes\` [\`Map\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html)\`<\`[\`String\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html)\`, ? extends \`[\`Shape\`](Shape.md)\`>\` (non-null): shapes by name +- \`name\` [\`String\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) (non-null): the name to look up + +**Returns** [\`@Nullable\`](https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html)\` \`[\`Shape\`](Shape.md) (nullable): the shape, or \`null\` when there is none + +## Inherited members + +- From class [\`Object\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [\`equals\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [\`getClass\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [\`hashCode\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [\`notify\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [\`notifyAll\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [\`toString\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString%28%29), [\`wait\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [\`wait\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [\`wait\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29) +" +`; + +exports[`Markdown snapshots of the fixture: fixture/java/Circle.md 1`] = ` +"# Circle + +[fixture](../../index.md) › [fixture.java](index.md) · Every page: [llms.txt](../../llms.txt) + +Record in [\`fixture.java\`](index.md). Since 1.0. Null-marked: types are non-null unless annotated. + +\`\`\`java +public record Circle(double radius, @Nullable String label) implements Shape +\`\`\` + +Inheritance: [\`Object\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > [\`Record\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html) > \`Circle\` + +Implements: [\`Shape\`](Shape.md) + +A circle. + +**Record components** + +- \`radius\` \`double\`: the radius in meters; not negative +- \`label\` [\`@Nullable\`](https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html)\` \`[\`String\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) (nullable): an optional label + +## Constructors + +### Circle(double, String) + +\`\`\`java +public Circle(double radius, @Nullable String label) +\`\`\` + +Checks the radius. + +**Parameters** + +- \`radius\` \`double\`: the radius in meters; not negative +- \`label\` [\`@Nullable\`](https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html)\` \`[\`String\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) (nullable): an optional label + +**Throws** + +- [\`IllegalArgumentException\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) (unchecked): if \`radius\` is negative + +## Methods + +### of(double) + +\`\`\`java +public static Circle of(double radius) +\`\`\` + +Creates an unlabeled circle. + +**Parameters** + +- \`radius\` \`double\`: the radius in meters + +**Returns** [\`Circle\`](Circle.md) (non-null): the circle + +### area() + +\`\`\`java +public double area() +\`\`\` + +The shape's area. For a circle this is \`π r²\`. + +**Returns** \`double\`: the area in square meters, never negative + +Overrides [\`area()\`](Shape.md#area%28%29). + +### name() + +\`\`\`java +public @Nullable String name() +\`\`\` + +Returns the shape's name, or \`null\` for an anonymous shape. + +Description copied from [\`name()\`](Shape.md#name%28%29). + +**Returns** [\`@Nullable\`](https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html)\` \`[\`String\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) (nullable): the shape's name, or \`null\` for an anonymous shape + +Overrides [\`name()\`](Shape.md#name%28%29). + +### accept(Shape.Visitor) + +\`\`\`java +public R accept(Shape.Visitor visitor) +\`\`\` + +Calls the visitor's method for this shape's kind. + +Description copied from [\`accept()\`](Shape.md#accept%28fixture.java.Shape.Visitor%29). + +**Type parameters** + +- \`\`: the visitor's result type + +**Parameters** + +- \`visitor\` [\`Shape.Visitor\`](Shape.Visitor.md)\`\` (non-null): the visitor + +**Returns** \`R\`: what the visitor returned + +Overrides [\`accept()\`](Shape.md#accept%28fixture.java.Shape.Visitor%29). + +### toString() + +\`\`\`java +public final String toString() +\`\`\` + +**Returns** [\`String\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) (non-null): No description. + +Overrides [\`toString()\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html#toString%28%29). + +### hashCode() + +\`\`\`java +public final int hashCode() +\`\`\` + +**Returns** \`int\`: No description. + +Overrides [\`hashCode()\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html#hashCode%28%29). + +### equals(Object) + +\`\`\`java +public final boolean equals(Object o) +\`\`\` + +**Parameters** + +- \`o\` [\`Object\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) (non-null): No description. + +**Returns** \`boolean\`: No description. + +Overrides [\`equals(java.lang.Object)\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html#equals%28java.lang.Object%29). + +### radius() + +\`\`\`java +public double radius() +\`\`\` + +**Returns** \`double\`: No description. + +### label() + +\`\`\`java +public @Nullable String label() +\`\`\` + +**Returns** [\`@Nullable\`](https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html)\` \`[\`String\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) (nullable): No description. + +## Inherited members + +- From class [\`Object\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [\`getClass\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [\`notify\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [\`notifyAll\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [\`wait\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [\`wait\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [\`wait\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29) +- From interface [\`Shape\`](Shape.md): [\`compareTo\`](Shape.md#compareTo%28fixture.java.Shape%29) +" +`; + +exports[`Markdown snapshots of the fixture: fixture/java/io/ShapeReader.md 1`] = ` +"# ShapeReader + +[fixture](../../../index.md) › [fixture.java.io](index.md) · Every page: [llms.txt](../../../llms.txt) + +Class in [\`fixture.java.io\`](index.md). Since 1.0. + +\`\`\`java +public final class ShapeReader implements AutoCloseable +\`\`\` + +Inheritance: [\`Object\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > \`ShapeReader\` + +Implements: [\`AutoCloseable\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html) + +Reads shapes in their [text form](../Geometry.md#parse%28java.lang.String%29), one per line. + +**See also** + +- [\`Geometry.parse(String)\`](../Geometry.md#parse%28java.lang.String%29) + +## Methods + +### read(InputStream) + +\`\`\`java +public static List read(InputStream in) throws IOException, GeometryException +\`\`\` + +Reads every shape from a stream of UTF-8 text. + +**Parameters** + +- \`in\` [\`InputStream\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/InputStream.html): the stream; not closed + +**Returns** [\`List\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html)\`<\`[\`Shape\`](../Shape.md)\`>\`: the shapes, in order + +**Throws** + +- [\`IOException\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html): if reading fails +- [\`GeometryException\`](../GeometryException.md): if a line describes an impossible shape + +### read(Reader, Charset) + +\`\`\`java +public static List read(Reader reader, Charset charset) throws IOException, GeometryException +\`\`\` + +Reads every shape from a reader. + +**Parameters** + +- \`reader\` [\`Reader\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/Reader.html): the reader; not closed +- \`charset\` [\`Charset\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/charset/Charset.html): the charset the text was decoded from, for error messages + +**Returns** [\`List\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html)\`<\`[\`Shape\`](../Shape.md)\`>\`: the shapes, in order + +**Throws** + +- [\`IOException\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html): if reading fails +- [\`GeometryException\`](../GeometryException.md): if a line describes an impossible shape + +### open(Reader) + +\`\`\`java +public static ShapeReader open(Reader reader) +\`\`\` + +Opens a reader. + +**Parameters** + +- \`reader\` [\`Reader\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/Reader.html): the reader to read from + +**Returns** [\`ShapeReader\`](ShapeReader.md): the shape reader; close it to close \`reader\` + +### close() + +\`\`\`java +public void close() throws IOException +\`\`\` + +Closes the underlying reader. + +**Throws** + +- [\`IOException\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html): if closing the reader fails + +Overrides [\`close()\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html#close%28%29). + +## Inherited members + +- From class [\`Object\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [\`equals\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [\`getClass\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [\`hashCode\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [\`notify\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [\`notifyAll\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [\`toString\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString%28%29), [\`wait\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [\`wait\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [\`wait\`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29) +" +`; + +exports[`Markdown snapshots of the fixture: index.md 1`] = ` +"# fixture 1.0 + +Every page: [llms.txt](llms.txt), or all in one file: [llms-full.txt](llms-full.txt) + +API reference for fixture. + +## Packages + +- [\`fixture.java\`](fixture/java/index.md): Shapes, units and measurements: a fixture that exercises every declaration kind and documentation construct the API model represents. +- [\`fixture.java.io\`](fixture/java/io/index.md): Reading shapes from streams. + +## Types in \`fixture.java\` + +- [\`AbstractCanvas\`](fixture/java/AbstractCanvas.md) (abstract class): A canvas that counts what it draws. +- [\`Box\`](fixture/java/Box.md) (class): A mutable holder for one comparable value. +- [\`Canvas\`](fixture/java/Canvas.md) (interface): Somewhere to draw shapes. +- [\`Canvas.Layer\`](fixture/java/Canvas.Layer.md) (interface): One layer of a canvas. +- [\`Canvas.Layer.Kind\`](fixture/java/Canvas.Layer.Kind.md) (enum class): What a layer holds. +- [\`Circle\`](fixture/java/Circle.md) (record): A circle. +- [\`Geometry\`](fixture/java/Geometry.md) (class): Operations on shapes. +- [\`Geometry.Legacy\`](fixture/java/Geometry.Legacy.md) (class): Methods from before null markings; their nullness is unspecified. +- [\`GeometryException\`](fixture/java/GeometryException.md) (exception): A shape that cannot exist, such as a triangle whose sides violate the triangle inequality. +- [\`Measured\`](fixture/java/Measured.md) (annotation interface): Marks a declaration whose values are lengths, and in which unit. +- [\`Polygon\`](fixture/java/Polygon.md) (class): A regular polygon. +- [\`Polygon.Builder\`](fixture/java/Polygon.Builder.md) (class): Builds a polygon one side at a time. +- [\`Polygon.Edge\`](fixture/java/Polygon.Edge.md) (class): One edge of this polygon: an inner class, bound to its polygon. +- [\`Rect\`](fixture/java/Rect.md) (class): An axis-aligned rectangle. +- [\`Shape\`](fixture/java/Shape.md) (sealed interface): A closed plane figure. +- [\`Shape.Visitor\`](fixture/java/Shape.Visitor.md) (interface): Operations over each kind of shape. +- [\`Units\`](fixture/java/Units.md) (enum class): Units of length. + +## Types in \`fixture.java.io\` + +- [\`ShapeReader\`](fixture/java/io/ShapeReader.md) (class): Reads shapes in their text form, one per line. +" +`; + +exports[`Markdown snapshots of the fixture: llms.txt 1`] = ` +"# fixture 1.0 + +> API reference for fixture. + +Each page below is Markdown; the HTML page of the same name has the same content. llms-full.txt has every page in one file, and api.json is the apidocs/1 model. + +## Overview + +- [fixture](index.md): packages and types +- [llms-full.txt](llms-full.txt): every page in one file +- [api.json](api.json): the apidocs/1 model + +## Pages + +- [Package fixture.java](fixture/java/index.md): Shapes, units and measurements: a fixture that exercises every declaration kind and documentation construct the API model represents. +- [AbstractCanvas (abstract class in fixture.java)](fixture/java/AbstractCanvas.md): A canvas that counts what it draws. +- [Box (class in fixture.java)](fixture/java/Box.md): A mutable holder for one comparable value. +- [Canvas (interface in fixture.java)](fixture/java/Canvas.md): Somewhere to draw shapes. +- [Canvas.Layer (interface in fixture.java)](fixture/java/Canvas.Layer.md): One layer of a canvas. +- [Canvas.Layer.Kind (enum class in fixture.java)](fixture/java/Canvas.Layer.Kind.md): What a layer holds. +- [Circle (record in fixture.java)](fixture/java/Circle.md): A circle. +- [Geometry (class in fixture.java)](fixture/java/Geometry.md): Operations on shapes. +- [Geometry.Legacy (class in fixture.java)](fixture/java/Geometry.Legacy.md): Methods from before null markings; their nullness is unspecified. +- [GeometryException (exception in fixture.java)](fixture/java/GeometryException.md): A shape that cannot exist, such as a triangle whose sides violate the triangle inequality. +- [Measured (annotation interface in fixture.java)](fixture/java/Measured.md): Marks a declaration whose values are lengths, and in which unit. +- [Polygon (class in fixture.java)](fixture/java/Polygon.md): A regular polygon. +- [Polygon.Builder (class in fixture.java)](fixture/java/Polygon.Builder.md): Builds a polygon one side at a time. +- [Polygon.Edge (class in fixture.java)](fixture/java/Polygon.Edge.md): One edge of this polygon: an inner class, bound to its polygon. +- [Rect (class in fixture.java)](fixture/java/Rect.md): An axis-aligned rectangle. +- [Shape (sealed interface in fixture.java)](fixture/java/Shape.md): A closed plane figure. +- [Shape.Visitor (interface in fixture.java)](fixture/java/Shape.Visitor.md): Operations over each kind of shape. +- [Units (enum class in fixture.java)](fixture/java/Units.md): Units of length. +- [Package fixture.java.io](fixture/java/io/index.md): Reading shapes from streams. +- [ShapeReader (class in fixture.java.io)](fixture/java/io/ShapeReader.md): Reads shapes in their text form, one per line. + +## Indexes + +- [Packages](packages.md): every package with its summary and type counts +- [All types](types.md): every type, nested ones too, by name +- [Index](index-all.md): every declaration from A to Z +- [Deprecated](deprecated.md): everything deprecated, for removal first +" +`; diff --git a/packages/apidocs/test/__snapshots__/narrative.test.ts.snap b/packages/apidocs/test/__snapshots__/narrative.test.ts.snap new file mode 100644 index 0000000..5d4176c --- /dev/null +++ b/packages/apidocs/test/__snapshots__/narrative.test.ts.snap @@ -0,0 +1,173 @@ +// Bun Snapshot v1, https://bun.sh/docs/test/snapshots + +exports[`outputs guide page snapshots, HTML and Markdown: guides/concepts.md 1`] = ` +"# ¶ Concepts + +[geo](../index.md) › Guides · Every page: [llms.txt](../llms.txt) + +*Shapes, measuring and units: the ideas the reference pages assume.* + +Three ideas carry the whole library: a closed set of shapes, pure functions that measure them, and one unit of length. Each section below links to the declarations it describes. + +## Shapes + +Every shape implements the sealed interface [\`Shape\`](../com/example/geo/Shape.md). Two classes implement it: + +- [\`Circle\`](../com/example/geo/Circle.md), a record of a radius and an optional label. + + - Create one with [\`Circle.of(double)\`](../com/example/geo/Circle.md#of%28double%29). + - Its [\`area()\`](../com/example/geo/Circle.md#area%28%29) is \`π r²\`. +- [\`Polygon\`](../com/example/geo/Polygon.md), a regular polygon built from its sides. + + - It extends [\`AbstractShape\`](../com/example/geo/AbstractShape.md), which adds [\`perimeter()\`](../com/example/geo/AbstractShape.md#perimeter%28%29). + - It is not sealed: [Custom shapes](advanced/custom-shapes.md) shows how to extend it. + +> [!NOTE] +> Because the hierarchy is sealed, a \`switch\` over a shape needs no \`default\` branch, and the compiler tells you when a new shape appears. + +### Example + +\`\`\`java +String describe(Shape shape) { + return switch (shape) { + case Circle c -> "circle of radius " + c.radius(); + case Polygon p -> "polygon with perimeter " + p.perimeter(); + }; +} +\`\`\` + +## Measuring + +[\`Shapes\`](../com/example/geo/Shapes.md) holds the operations. They are pure: none modifies its arguments. \`area\` is overloaded, so the compiler picks [\`area(Circle)\`](../com/example/geo/Shapes.md#area%28com.example.geo.Circle%29) or [\`area(Polygon)\`](../com/example/geo/Shapes.md#area%28com.example.geo.Polygon%29) from the argument's static type. + +1. Build the shapes. +2. Measure each one, or sum them with [\`total(Shape...)\`](../com/example/geo/Shapes.md#total%28com.example.geo.Shape...%29). +3. Compare the results: shapes order by area. + +> [!TIP] +> **Collecting shapes** +> +> To collect shapes as you go, use [\`Shapes.Builder\`](../com/example/geo/Shapes.Builder.md) with the options of its nested enum [\`Shapes.Builder.Option\`](../com/example/geo/Shapes.Builder.Option.md), such as [\`SORTED\`](../com/example/geo/Shapes.Builder.Option.md#SORTED). + +### Example + +\`\`\`java +double small = Shapes.area(Circle.of(1)); +double large = Shapes.area(new Polygon(4, 4, 4, 4)); +assert small < large; +\`\`\` + +## Units + +Every length is in meters, and every area in square meters. [\`Units\`](../com/example/geo/Units.md) converts other units at the edges of a program: + +Units of length + +| Unit | Meters per unit | Status | +| --- | --- | --- | +| [\`Units.METERS\`](../com/example/geo/Units.md#METERS) | \`1.0\` | The base unit | +| [\`Units.FEET\`](../com/example/geo/Units.md#FEET) | \`0.3048\` | Deprecated since 1.2 | + +> [!IMPORTANT] +> Methods take and return meters. Convert once, when a value enters the program, with [\`toMeters(double)\`](../com/example/geo/Units.md#toMeters%28double%29). + +> [!WARNING] +> **Round trips lose precision** +> +> Converting back and forth between units loses precision. Keep lengths in meters until you show them. + +## Parsing + +[\`Shapes.parse\`](../com/example/geo/Shapes.md#parse%28java.lang.String%29) reads the text form of one shape. The [text format guide](advanced/text-format.md#grammar) has the grammar. + +> [!CAUTION] +> The text form is not stable across releases. Store shapes some other way, and never parse text you do not trust without a size limit. + +## Threads + +> **⚠︎ API note** +> +> Every method of [\`Shapes\`](../com/example/geo/Shapes.md) is safe to call from several threads at once. + +> **☑︎ Implementation requirements** +> +> A subclass of [\`Polygon\`](../com/example/geo/Polygon.md) must keep \`area()\` free of side effects, so that callers may cache it. + +> **✎ Implementation note** +> +> The library keeps no caches and allocates only the results it returns. + +## Further reading + +- [Polygon](https://en.wikipedia.org/wiki/Polygon) on Wikipedia. +- [Classes to replace](migrating-from-1x.md#classes-to-replace), in the migration guide. +- \`Ellipse\` is planned for a later release. This model does not contain it, so the link renders as plain text. +- Recipes is a guide that does not exist yet, so this link renders as plain text too. + +--- + +Previous: [Getting started](getting-started.md) +Next: [Migrating from 1.x](migrating-from-1x.md) +" +`; + +exports[`outputs guide page snapshots, HTML and Markdown: guides/advanced/text-format.md 1`] = ` +"# ¶ The text format + +[geo](../../index.md) › Advanced · Every page: [llms.txt](../../llms.txt) + +*The grammar \`Shapes.parse\` reads, and how to read files of shapes.* + +Shapes have a one-line text form, for logs and test fixtures. [\`Shapes.parse\`](../../com/example/geo/Shapes.md#parse%28java.lang.String%29) reads one; [\`ShapeReader\`](../../com/example/geo/io/ShapeReader.md) reads a stream of them. + +## Grammar + +\`\`\`text +shape = circle | polygon +circle = "circle" number +polygon = "polygon" number number number { number } +number = digit { digit } [ "." digit { digit } ] +\`\`\` + +Numbers are lengths in meters. Blank lines and lines starting with \`#\` are skipped. + +## Reading files + +[\`read(InputStream)\`](../../com/example/geo/io/ShapeReader.md#read%28java.io.InputStream%29) reads UTF-8 text; the [\`read(Reader, Charset)\`](../../com/example/geo/io/ShapeReader.md#read%28java.io.Reader,java.nio.charset.Charset%29) overload reads text you have already decoded. + +\`\`\`java +try (var in = Files.newInputStream(Path.of("shapes.txt"))) { + List shapes = ShapeReader.read(in); +} +\`\`\` + +> [!WARNING] +> A malformed line throws [\`GeometryException\`](../../com/example/geo/GeometryException.md) and stops the read. Validate files from users before you read them. + +--- + +Previous: [Custom shapes](custom-shapes.md) +" +`; + +exports[`outputs guide page snapshots, HTML and Markdown: guides/getting-started.html 1`] = ` +" +Getting started (geo 2.1.0)
geo2.1.0
All types

Guide

Getting started

Add geo to a build and measure a first shape.

geo measures plane shapes: circles, polygons and shapes you build from them. This guide adds it to a build and runs a first program.

Install

geo needs Java 21 or later. With Gradle, add the dependency to build.gradle.kts:

dependencies {
+    implementation("com.example:geo:2.1.0")
+}

With Maven, add it to pom.xml:

<dependency>
+  <groupId>com.example</groupId>
+  <artifactId>geo</artifactId>
+  <version>2.1.0</version>
+</dependency>

On the module path, require the module:

module my.app {
+    requires com.example.geo;
+}

Your first shape

Create shapes with Circle.of and the Polygon constructor, then measure them with Shapes:

import com.example.geo.*;
+
+class First {
+    public static void main(String[] args) {
+        Shape circle = Circle.of(2);
+        Shape triangle = new Polygon(3, 3, 3);
+        System.out.printf("total area: %.2f m²%n", Shapes.total(circle, triangle));
+    }
+}

Tip

Every length is in meters. To work in other units, see Units in the concepts guide.

Next steps

+" +`; diff --git a/packages/apidocs/test/__snapshots__/render.test.ts.snap b/packages/apidocs/test/__snapshots__/render.test.ts.snap new file mode 100644 index 0000000..02fa105 --- /dev/null +++ b/packages/apidocs/test/__snapshots__/render.test.ts.snap @@ -0,0 +1,33 @@ +// Bun Snapshot v1, https://bun.sh/docs/test/snapshots + +exports[`render HTML snapshots: fixture/java/Geometry.html 1`] = ` +" +Geometry (fixture 1.0)
fixture1.0
All types

Geometry

Javaclassin fixture.javasince 1.0null-marked

public final class Geometry
Inheritance
  1. Object
  2. Geometry

Operations on shapes.

Every method is pure: it never modifies its arguments. Thread safety: every method is safe to call concurrently.

  1. First, measure.

  2. Then compare, with compareTo.

Unit factors
UnitFactor
Units.METERS1.0
Units.FEET0.3048
Shape big = Geometry.largest(List.of(Circle.of(1), Rect.square(2)));
+double total = Geometry.totalArea(big, Circle.of(3));

Measure twice, cut once.

Edge cases

Text with an entity — a superscript kept as raw markup, a line
break, a hyperlink, and <angle brackets> as literal text.

Implementation note

Areas are computed in double precision.

See also

Nested types

NameKindDescription
LegacyclassMethods from before null markings; their nullness is unspecified.

Fields2

static int PRECISIONThe default number of significant digits: 6.

PRECISION

static
public static final int PRECISION

The default number of significant digits: 6.

Value

int
Constant: 6
static String NAMEThe library's name, "fixture", as tools report it.

NAME

static
public static final String NAME

The library's name, "fixture", as tools report it.

Value

Stringnon-null
Constant: "fixture"

Methods5

static T largest(Collection)Returns the largest shape.

largest

static
public static <T extends Shape & Comparable<? super T>> T largest(
+    Collection<? extends T> shapes
+)

Returns the largest shape.

Type parameters

<T>
the shape type

Parameters

shapesCollection<? extends T>non-null
the shapes; not empty

Returns

T
the largest of shapes

Throws

NoSuchElementExceptionunchecked
if shapes is empty

Implementation requirements

Compares with Comparable.compareTo(Object), keeping the first of equal shapes.

static double totalArea(Shape...)Sums the shapes' areas.

totalArea

static
@Measured(precision = 6)
+public static double totalArea(Shape... shapes)

Sums the shapes' areas.

Parameters

shapesShape...non-null
the shapes

Returns

double
the total area in square meters; 0 for no shapes
static Shape parse(String)Parses a shape from its text form, such as circle 2.5.Has an API note

parse

static
public static Shape parse(String text) throws IOException, ParseException

Parses a shape from its text form, such as circle 2.5.

Parameters

textStringnon-null
the text form

Returns

Shapenon-null
the shape

Throws

IOException
if the text names a file that cannot be read
IllegalStateExceptionunchecked
if the parser was closed
ParseException
No description.

API note

The text form is not stable across releases; store shapes some other way.

static double sum(List)Sums the areas of a list of shapes.for removal

sum

static
@Deprecated(since = "1.1", forRemoval = true)
+public static double sum(List<Shape> shapes)

Deprecated for removal since 1.1

Use totalArea(Shape...), which takes any number of shapes.

Sums the areas of a list of shapes.

Parameters

shapesList<Shape>non-null
the shapes

Returns

double
the total area
static Shape find(Map, String)Finds a shape by name.

find

staticsince 1.1
public static @Nullable Shape find(
+    Map<String, ? extends Shape> shapes,
+    String name
+)

Finds a shape by name.

Parameters

shapesMap<String, ? extends Shape>non-null
shapes by name
nameStringnon-null
the name to look up

Returns

@Nullable Shapenullable
the shape, or null when there is none

Inherited members

+" +`; + +exports[`render HTML snapshots: fixture/java/Circle.html 1`] = ` +" +Circle (fixture 1.0)
fixture1.0
All types

Circle

Javarecordin fixture.javasince 1.0null-marked

public record Circle(double radius, @Nullable String label) implements Shape
Inheritance
  1. Object
  2. Record
  3. Circle
Implements

A circle.

Record components

radiusdouble
the radius in meters; not negative
label@Nullable Stringnullable
an optional label

Constructors1

Circle(double, String)Checks the radius.

Circle

public Circle(double radius, @Nullable String label)

Checks the radius.

Parameters

radiusdouble
the radius in meters; not negative
label@Nullable Stringnullable
an optional label

Throws

IllegalArgumentExceptionunchecked
if radius is negative

Methods9

static Circle of(double)Creates an unlabeled circle.

of

static
public static Circle of(double radius)

Creates an unlabeled circle.

Parameters

radiusdouble
the radius in meters

Returns

Circlenon-null
the circle
double area()The shape's area.

area

public double area()

The shape's area. For a circle this is π r².

Returns

double
the area in square meters, never negative

Overrides area().

String name()Returns the shape's name, or null for an anonymous shape.

name

public @Nullable String name()

Returns the shape's name, or null for an anonymous shape.

Description copied from name().

Returns

@Nullable Stringnullable
the shape's name, or null for an anonymous shape

Overrides name().

R accept(Shape.Visitor)Calls the visitor's method for this shape's kind.

accept

public <R> R accept(Shape.Visitor<R> visitor)

Calls the visitor's method for this shape's kind.

Description copied from accept().

Type parameters

<R>
the visitor's result type

Parameters

visitorShape.Visitor<R>non-null
the visitor

Returns

R
what the visitor returned

Overrides accept().

String toString()No description.

toString

public final String toString()

No description.

Returns

Stringnon-null
No description.

Overrides toString().

int hashCode()No description.

hashCode

public final int hashCode()

No description.

Returns

int
No description.

Overrides hashCode().

boolean equals(Object)No description.

equals

public final boolean equals(Object o)

No description.

Parameters

oObjectnon-null
No description.

Returns

boolean
No description.

Overrides equals(java.lang.Object).

double radius()No description.

radius

public double radius()

No description.

Returns

double
No description.
String label()No description.

label

public @Nullable String label()

No description.

Returns

@Nullable Stringnullable
No description.

Inherited members

From interface Shape

compareTo

+" +`; + +exports[`render HTML snapshots: fixture/java/index.html 1`] = ` +" +fixture.java (fixture 1.0)
fixture1.0
All types

fixture.java

Javapackagesince 1.0null-marked

Shapes, units and measurements: a fixture that exercises every declaration kind and documentation construct the API model represents.

Where to start

Start with fixture.java.Shape and the operations in fixture.java.Geometry. Readers live in fixture.java.io.

Interfaces

NameDescription
CanvasSomewhere to draw shapes.
ShapeA closed plane figure.

Classes

NameDescription
AbstractCanvasA canvas that counts what it draws.
BoxA mutable holder for one comparable value.
GeometryOperations on shapes.
PolygonA regular polygon.
RectAn axis-aligned rectangle.

Records

NameDescription
CircleA circle.

Enums

NameDescription
UnitsUnits of length.

Exceptions

NameDescription
GeometryExceptionA shape that cannot exist, such as a triangle whose sides violate the triangle inequality.

Annotations

NameDescription
MeasuredMarks a declaration whose values are lengths, and in which unit.
+" +`; + +exports[`render HTML snapshots: index.html 1`] = ` +" +fixture 1.0 API
fixture1.0
All types

fixture

version 1.0Java

API reference for fixture.

Packages

NameDescription
fixture.javaShapes, units and measurements: a fixture that exercises every declaration kind and documentation construct the API model represents.
fixture.java.ioReading shapes from streams.

All types

fixture.java

NameKindDescription
AbstractCanvasabstract classA canvas that counts what it draws.
BoxclassA mutable holder for one comparable value.
CanvasinterfaceSomewhere to draw shapes.
Canvas.LayerinterfaceOne layer of a canvas.
Canvas.Layer.Kindenum classWhat a layer holds.
CirclerecordA circle.
GeometryclassOperations on shapes.
Geometry.LegacyclassMethods from before null markings; their nullness is unspecified.
GeometryExceptionexceptionA shape that cannot exist, such as a triangle whose sides violate the triangle inequality.
Measuredannotation interfaceMarks a declaration whose values are lengths, and in which unit.
PolygonclassA regular polygon.
Polygon.BuilderclassBuilds a polygon one side at a time.
Polygon.EdgeclassOne edge of this polygon: an inner class, bound to its polygon.
RectclassAn axis-aligned rectangle.
Shapesealed interfaceA closed plane figure.
Shape.VisitorinterfaceOperations over each kind of shape.
Unitsenum classUnits of length.

fixture.java.io

NameKindDescription
ShapeReaderclassReads shapes in their text form, one per line.
+" +`; diff --git a/packages/apidocs/test/astro.test.ts b/packages/apidocs/test/astro.test.ts new file mode 100644 index 0000000..406dcc9 --- /dev/null +++ b/packages/apidocs/test/astro.test.ts @@ -0,0 +1,255 @@ +/** + * The Astro integration's helpers, without Astro: resolvePage and renderText over every page of every sample, + * in both URL forms, and renderPage's markup against the static renderer's. + */ +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { samples } from "../samples"; +import { guidesModel, importMarkdown, readSuite } from "../src/import"; +import type { Model } from "../src/model"; +import { render } from "../src/render"; +import { assertBase, isBaseRelative, linkHeader, mapUrl, notFound, pageUrl, prefersMarkdown, renderPage, renderText, resolvePage, searchEntries, sitePaths, textFiles } from "../src/astro/helpers"; + +const fixture: Model = JSON.parse(readFileSync(new URL("fixtures/fixture-java.api.json", import.meta.url), "utf8")); +const suite = readSuite(fileURLToPath(new URL("../samples/guides", import.meta.url))); +const guides = guidesModel(importMarkdown(suite.files, { suite: "markdown", assets: suite.assets }), { name: "Geo user guide", version: "2.0" }); +const models: Record = { java: samples.java, kotlin: samples.kotlin, fixture, guides }; +const theme = { extends: "elide" as const, baseUrl: "https://example.com/docs/" }; + +for (const [name, model] of Object.entries(models)) { + describe(`${name}: every page and file`, () => { + const out = render(model, theme); + const pages = Object.keys(out).filter(f => f.endsWith(".html")).map(f => f.slice(0, -".html".length)); + + test("the pages are the static renderer's pages", () => { + const astroPages = sitePaths(model, theme).filter(p => p.endsWith(".md")).map(p => p.slice(0, -".md".length)); + expect(astroPages.sort()).toEqual([...pages].sort()); + }); + + test("each page resolves in the Astro form, and its static form redirects there", () => { + for (const page of pages) { + expect(resolvePage(model, pageUrl(page), theme)).toEqual({ kind: "page", page }); + const url = pageUrl(page); + // A leading slash is accepted, and so is the encoded form a request URL has. + expect(resolvePage(model, `/${encodeURI(url)}`, theme)).toEqual({ kind: "page", page }); + expect(resolvePage(model, `${page}.html`, theme)).toEqual({ kind: "redirect", to: url }); + if (url.endsWith("/")) expect(resolvePage(model, url.slice(0, -1), theme)).toEqual({ kind: "redirect", to: url }); + else if (url) expect(resolvePage(model, `${url}/`, theme)).toEqual({ kind: "redirect", to: url }); + } + }); + + test("each Markdown twin is the static renderer's", () => { + for (const page of pages) { + expect(resolvePage(model, `${page}.md`, theme)).toEqual({ kind: "markdown", page }); + const text = renderText(model, `${page}.md`, theme)!; + expect(text.body).toBe(out[`${page}.md`] as string); + expect(text.contentType).toBe("text/markdown; charset=utf-8"); + } + }); + + test("each text file is the static renderer's, except the Astro-form sitemap and search index", () => { + for (const file of textFiles(model, theme)) { + expect(resolvePage(model, file, theme)).toEqual({ kind: "file", name: file }); + const text = renderText(model, file, theme); + if (file === "assets/search-index.json" || file === "sitemap.xml") continue; + expect(text?.body).toBe(out[file] as string); + } + for (const file of Object.keys(out).filter(f => typeof out[f] === "string" && !f.endsWith(".html") && !f.endsWith(".md"))) { + expect(textFiles(model, theme)).toContain(file); + } + }); + + test("sitemap.xml and the JSON search index name pages in the Astro form", () => { + const sitemap = renderText(model, "sitemap.xml", theme)!.body; + expect(sitemap).not.toContain(".html<"); + for (const page of pages) expect(sitemap).toContain(`${theme.baseUrl}${pageUrl(page)}`); + for (const entry of searchEntries(model)) { + const path = entry[2].split("#")[0]!; + expect(path.endsWith(".html")).toBe(false); + expect(resolvePage(model, path, theme).kind).toBe("page"); + } + }); + + test("paths that are not in the site are missing", () => { + for (const path of ["nope", "nope/", "nope.html", "nope.md", "assets/apidocs.css", "assets/apidocs.js", "assets/fonts/other.woff2", "../index.html"]) { + expect(resolvePage(model, path, theme)).toEqual({ kind: "missing" }); + } + expect(renderText(model, "nope.md", theme)).toBeUndefined(); + }); + }); +} + +describe("theme-dependent files", () => { + test("without a theme, resolvePage names them; renderText has them only when the theme does", () => { + expect(resolvePage(samples.java, "assets/logo-light.svg")).toEqual({ kind: "file", name: "assets/logo-light.svg" }); + expect(renderText(samples.java, "assets/logo-light.svg")).toBeUndefined(); + expect(renderText(samples.java, "assets/logo-light.svg", { extends: "elide" })?.contentType).toBe("image/svg+xml"); + expect(resolvePage(samples.java, "sitemap.xml", { extends: "neutral" })).toEqual({ kind: "missing" }); + expect(resolvePage(samples.java, "assets/fonts/jetbrains-mono-latin-wght-normal.woff2", { extends: "elide" }).kind).toBe("file"); + }); +}); + +describe("mapUrl", () => { + const ctx = { page: "com/example/geo/Circle", base: "/docs/", baseUrl: "https://example.com/docs/" }; + test("maps the static renderer's links to the Astro form", () => { + expect(mapUrl("Shape.html", ctx)).toBe("/docs/com/example/geo/Shape"); + expect(mapUrl("index.html", ctx)).toBe("/docs/com/example/geo/"); + expect(mapUrl("../../../index.html#all-types", ctx)).toBe("/docs/#all-types"); + expect(mapUrl("io/index.html", ctx)).toBe("/docs/com/example/geo/io/"); + expect(mapUrl("Circle.html#area()", ctx)).toBe("/docs/com/example/geo/Circle#area()"); + expect(mapUrl("Circle.md", ctx)).toBe("/docs/com/example/geo/Circle.md"); + expect(mapUrl("../../../llms.txt", ctx)).toBe("/docs/llms.txt"); + expect(mapUrl("https://example.com/docs/com/example/geo/Circle.html", ctx)).toBe("https://example.com/docs/com/example/geo/Circle"); + expect(mapUrl("https://example.com/docs/index.html", ctx)).toBe("https://example.com/docs/"); + }); + test("leaves fragments, other sites and other schemes alone", () => { + for (const url of ["#area()", "https://docs.oracle.com/x.html", "mailto:a@example.com", "/other/x.html", "../../../../../escape.html"]) expect(mapUrl(url, ctx)).toBe(url); + }); +}); + +describe("renderPage", () => { + const base = "/docs/"; + const pageOf = (model: Model, page: string) => renderPage(model, page, theme, { base, baseUrl: theme.baseUrl }); + + test("every site link is root-absolute in the Astro form; nothing names an .html page of the site", () => { + for (const [name, model] of Object.entries(models)) { + const out = render(model, theme); + for (const file of Object.keys(out).filter(f => f.endsWith(".html")).slice(0, 40)) { + const parts = pageOf(model, file.slice(0, -".html".length)); + const html = parts.head + parts.body.join(""); + for (const m of html.matchAll(/\s(?:href|src)="([^"]*)"/g)) { + const url = m[1]!.replace(/&/g, "&"); + if (/^[a-z]+:/i.test(url)) { + if (url.startsWith(theme.baseUrl)) expect(`${name} ${file} ${url}`).not.toMatch(/\.html(#|$)/); + continue; + } + expect(`${name} ${file} ${url}`).toMatch(new RegExp(`^${name} ${file.replace(/[.()$]/g, "\\$&")} (/docs/|#)`)); + expect(url).not.toMatch(/\.html(#|$)/); + } + } + } + }); + + test("the head's metadata is the static renderer's, apart from the URL form", () => { + for (const [name, model] of Object.entries(models)) { + const out = render(model, theme); + for (const file of Object.keys(out).filter(f => f.endsWith(".html")).slice(0, 25)) { + const page = file.slice(0, -".html".length); + const ctx = { page, base, baseUrl: theme.baseUrl }; + const staticHead = (out[file] as string).split("")[1]!.split("")[0]!; + const astroHead = pageOf(model, page).head; + const metadata = (head: string, map: (u: string) => string | undefined) => ({ + title: /(.*?)<\/title>/.exec(head)?.[1], + meta: [...head.matchAll(/<meta (?:name|property)="([^"]*)" content="([^"]*)"\/>/g)].map(m => [m[1], m[1] === "og:url" ? map(m[2]!) : m[2]]), + links: [...head.matchAll(/<link rel="(canonical|alternate|index)"[^>]*? href="([^"]*)"/g)].map(m => [m[1], map(m[2]!)]), + jsonLd: JSON.parse(/<script type="application\/ld\+json">(.*?)<\/script>/.exec(head)![1]!, (key, value) => (["url", "item", "contentUrl"].includes(key) ? map(value) : value)), + }); + expect(`${name} ${page}`).toBeTruthy(); + expect(metadata(astroHead, u => u)).toEqual(metadata(staticHead, u => mapUrl(u, ctx))); + } + } + }); + + test("static-only head and body parts stay out; the router's persisted elements carry the site's base", () => { + const parts = pageOf(samples.java, "com/example/geo/Circle"); + const html = parts.head + parts.body.join(""); + expect(html).not.toContain("speculationrules"); + expect(html).not.toContain("assets/apidocs.js"); + expect(html).not.toContain('rel="stylesheet"'); + expect(html).toContain('data-astro-transition-persist="apidocs-topbar:/docs/"'); + expect(html).toContain('data-astro-transition-persist="apidocs-nav:/docs/"'); + expect(parts.body).toHaveLength(4); + expect(parts.themeCss).toContain(":root:root{"); + expect(parts.preload).toEqual(["/docs/assets/fonts/jetbrains-mono-latin-wght-normal.woff2"]); + expect(parts.moduleVersion).toBe('<span class="module-version"><span class="version">2.1.0</span></span>'); + }); + + test("an unknown page is an error, not an empty page", () => { + expect(() => pageOf(samples.java, "com/example/geo/Nope")).toThrow("no page"); + }); +}); + +describe("untrusted links and paths", () => { + // The forms a link in a documentation comment, or a path in a request, can take to try to leave the site. + const hostile = ["//host", "/\\host", "\\\\host", "\\/host", "%5C%5Chost", "%2F%2Fhost", "..//host", "....//", "a\tb/../../../\t/host", "\n/host", "/\t/host", "a\\..\\..\\host"]; + /** Whether a browser on this site would leave it to follow the URL. */ + const offSite = (url: string) => new URL(url.replace(/[\t\n\r]/g, ""), "https://site.example/docs/com/example/geo/Circle").origin !== "https://site.example"; + + for (const base of ["/", "/docs/"]) { + test(`with base ${base}, no mapped link leaves the site unless it named another site itself`, () => { + const ctx = { page: "com/example/geo/Circle", base, baseUrl: `https://site.example${base}` }; + for (const url of hostile) { + const mapped = mapUrl(url, ctx); + if (mapped === undefined) continue; + // "//host" names another site in so many words, as https://host would; it is kept as written. Nothing else + // may leave the site, start with "//" or "/\\", or keep a backslash. + if (url === "//host") continue; + expect(mapped).not.toMatch(/^\/[/\\]|\\/); + expect(`${JSON.stringify(url)} -> ${offSite(mapped)}`).toBe(`${JSON.stringify(url)} -> false`); + } + expect(mapUrl("//host", ctx)).toBe("//host"); + expect(mapUrl("/\\host", ctx)).toBe("/%5Chost"); + expect(mapUrl("\\\\host", ctx)).toBeUndefined(); + expect(mapUrl("/\t/host", ctx)).toBeUndefined(); + expect(mapUrl("%2F%2Fhost", ctx)).toBe(`${base}com/example/geo/%2F%2Fhost`); + expect(mapUrl("..//host", ctx)).toBe(`${base}com/example/host`); + // A normal relative link still maps. + expect(mapUrl("../geo/Shape.html#area()", ctx)).toBe(`${base}com/example/geo/Shape#area()`); + expect(mapUrl("../../../index.html", ctx)).toBe(base); + }); + + test(`with base ${base}, a rewritten page drops a link that safeUrl rejects and keeps every link on the site`, () => { + const html = renderPage(samples.java, "com/example/geo/Circle", theme, { base, baseUrl: `https://example.com${base}` }); + for (const m of (html.head + html.body.join("")).matchAll(/\s(?:href|src)="([^"]*)"/g)) expect(m[1]).not.toMatch(/^\/[/\\]/); + }); + } + + test("a base must be an absolute path with a single leading slash and a trailing one", () => { + for (const base of ["/", "/docs/", "/api/komodo/2.0/"]) expect(() => assertBase(base)).not.toThrow(); + for (const base of ["", "docs/", "/docs", "//", "//host/", "/\\host/", "/a/../", "/a/./", "/a//b/", "/a b/", "/a\n/", "/a?x/"]) { + expect(() => assertBase(base)).toThrow("base"); + // renderPage adds a missing trailing slash, so "" and "/docs" are bases there; nothing else that fails here is. + if (base !== "" && base !== "/docs") expect(() => renderPage(samples.java, "index", theme, { base })).toThrow("base"); + } + }); + + test("request paths in every hostile form are missing or stay inside the base", () => { + for (const path of [...hostile, "%2F%2Fhost.html", "%5C%5Chost.html", "..%2F..%2Findex.html", "/%2e%2e/index.html", "https://host/index.html", "//host/index.html"]) { + const resolved = resolvePage(samples.java, path, theme); + if (resolved.kind === "redirect") expect(isBaseRelative(resolved.to)).toBe(true); + } + }); + + test("a redirect never leaves the base, even from names in the model", () => { + const model: Model = structuredClone(samples.java); + model.packages = [{ id: "evil", name: ".host.x", types: [{ ...model.packages![0]!.types![0]!, id: "evil.T", name: "T" }] }]; + for (const path of ["/host/x/index.html", "host/x/index.html", "/host/x", "/host/x/T.html"]) { + const resolved = resolvePage(model, path, theme); + if (resolved.kind === "redirect") expect(isBaseRelative(resolved.to)).toBe(true); + } + for (const to of ["", "a", "a/", "a/b", "packages"]) expect(isBaseRelative(to)).toBe(true); + for (const to of ["/a", "//a", "\\a", "a\\b", "a/../b", "../a", "./a", "a//b", "https:x", "a\tb", "a\nb"]) expect(isBaseRelative(to)).toBe(false); + }); +}); + +describe("serving helpers", () => { + test("prefersMarkdown reads the Accept header's preference", () => { + expect(prefersMarkdown("text/markdown")).toBe(true); + expect(prefersMarkdown("text/markdown, text/html;q=0.9")).toBe(true); + expect(prefersMarkdown("text/html, text/markdown;q=0.9")).toBe(false); + expect(prefersMarkdown("text/html,application/xhtml+xml,*/*;q=0.8")).toBe(false); + expect(prefersMarkdown(null)).toBe(false); + }); + test("linkHeader names the twin, llms.txt and the model", () => { + expect(linkHeader("/docs/", "com/example/geo/index")).toBe('</docs/com/example/geo/index.md>; rel="alternate"; type="text/markdown", </docs/llms.txt>; rel="alternate"; type="text/markdown"; title="llms.txt", </docs/api.json>; rel="alternate"; type="application/json"; title="api.json"'); + }); + test("notFound answers 404 in the form asked for, pointing at the overview and llms.txt", async () => { + const html = notFound("/docs/", "geo <1>", "text/html"); + expect(html.status).toBe(404); + expect(await html.text()).toContain('There is no such page in geo <1>. Start at the <a href="/docs/">overview</a>'); + const md = notFound("/docs/", "geo", "text/markdown"); + expect(md.headers.get("content-type")).toContain("text/markdown"); + expect(await md.text()).toContain("[llms.txt](/docs/llms.txt)"); + }); +}); diff --git a/packages/apidocs/test/audit.test.ts b/packages/apidocs/test/audit.test.ts new file mode 100644 index 0000000..c7ab050 --- /dev/null +++ b/packages/apidocs/test/audit.test.ts @@ -0,0 +1,88 @@ +/** + * The pure parts of the audits (scripts/audit/): the good-css.com rules on + * hand-written CSS, the robots.txt and code-fence helpers, and one + * agent-readiness run over the Java sample built with the runner and served + * by the audit server. Lighthouse is not run here; `bun run audit` runs it. + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { samples } from "../samples"; +import { agenticAudit, fencesBalanced, robotsAllows } from "../scripts/audit/agentic"; +import { packageRoot, renderSite, representativePages } from "../scripts/audit/build"; +import { cssAudit } from "../scripts/audit/css"; +import { type AuditServer, prefersMarkdown, serve } from "../scripts/audit/server"; + +describe("good-css rules", () => { + const status = (css: string, rule: string) => cssAudit([{ path: "a.css", css, source: "a.css" }]).rules.find(r => r.rule === rule)!.status; + test("logical properties", () => { + expect(status(".a { margin-left: 1px }", "logical-properties")).toBe("fail"); + expect(status(".a { padding: 0 4px }", "logical-properties")).toBe("fail"); + expect(status(".a { margin-inline-start: 1px; padding: 4px }", "logical-properties")).toBe("pass"); + }); + test("oklch colors and gray hues", () => { + expect(status(".a { color: #fff }", "oklch-color")).toBe("fail"); + expect(status(".a { color: oklch(98% 0 0) }", "oklch-color")).toBe("fail"); + expect(status(".a { color: oklch(98% 0 none) }", "oklch-color")).toBe("pass"); + }); + test(":hover inside the hover media query, with :active", () => { + expect(status("a:hover { color: red }", "hover-media")).toBe("fail"); + expect(status("@media (hover: hover) and (pointer: fine) { a:hover { color: red } }", "hover-media")).toBe("pass"); + expect(status("@media (hover: hover) and (pointer: fine) { a:hover { color: red } } a:active { color: blue }", "press-feedback")).toBe("pass"); + }); + test("focus and motion", () => { + expect(status(".a:focus { outline: none }", "focus-visible")).toBe("fail"); + expect(status(".a:focus-visible { outline: 2px solid }", "focus-visible")).toBe("pass"); + expect(status(".a { transition: transform 200ms ease-out }", "opt-in-motion")).toBe("fail"); + expect(status("@media (prefers-reduced-motion: no-preference) { .a { transition: transform 200ms ease-out } }", "opt-in-motion")).toBe("pass"); + expect(status(".a { transition: all 200ms }", "motion-properties")).toBe("fail"); + expect(status(".a { transition: opacity 150ms ease-in }", "motion-properties")).toBe("fail"); + }); +}); + +describe("helpers", () => { + test("robots.txt matching", () => { + const robots = "User-agent: *\nDisallow: /private/\n\nUser-agent: GPTBot\nDisallow: /\n"; + expect(robotsAllows(robots, "Claude-User", "/index.html")).toBe(true); + expect(robotsAllows(robots, "Claude-User", "/private/x.html")).toBe(false); + expect(robotsAllows(robots, "GPTBot", "/index.html")).toBe(false); + }); + test("code fences", () => { + expect(fencesBalanced("```java\nx\n```\n")).toBe(true); + expect(fencesBalanced("````md\n```\n````\n")).toBe(true); + expect(fencesBalanced("```\nx\n")).toBe(false); + }); + test("markdown negotiation", () => { + expect(prefersMarkdown("text/markdown")).toBe(true); + expect(prefersMarkdown("text/html, text/markdown;q=0.5")).toBe(false); + expect(prefersMarkdown("text/html")).toBe(false); + }); +}); + +describe("agent readiness over the Java sample", () => { + let dir: string; + let server: AuditServer; + beforeAll(() => { + if (!existsSync(join(packageRoot, "dist/render.js"))) throw new Error("dist/ is missing: run `bun run build` first"); + dir = mkdtempSync(join(tmpdir(), "apidocs-audit-test-")); + server = serve(join(dir, "out")); + renderSite({ model: { json: JSON.stringify(samples.java) }, theme: { extends: "elide", baseUrl: server.url }, out: join(dir, "out"), work: join(dir, "work") }); + }); + afterAll(() => { + server?.stop(); + if (dir) rmSync(dir, { recursive: true, force: true }); + }); + + test("every rule reports, and the output basics pass", async () => { + const out = join(dir, "out"); + const report = await agenticAudit({ name: "java", dir: out, url: server.url, pages: representativePages(out) }); + expect(report.score).toBeGreaterThan(0); + expect(report.score).toBeLessThanOrEqual(100); + const by = new Map(report.findings.map(f => [f.rule, f])); + for (const id of ["llms-txt-exists", "llms-txt-links-resolve", "sitemap", "noindex-directives", "redirect-hygiene", "code-fence-validity", "markdown-link-alternate", "ax-tree-injection-safe"]) { + expect(`${id}: ${by.get(id)?.status}`).toBe(`${id}: pass`); + } + for (const f of report.findings) expect(f.evidence).not.toBe("not measured"); + }, 30_000); +}); diff --git a/packages/apidocs/test/browser.test.ts b/packages/apidocs/test/browser.test.ts new file mode 100644 index 0000000..50c767c --- /dev/null +++ b/packages/apidocs/test/browser.test.ts @@ -0,0 +1,221 @@ +/** + * Opens a site built exactly as the doclet builds it (dist/runner.mjs running + * dist/render.js) in Chromium: from file:// with JavaScript on and off, and + * over HTTP where a test needs it. Runs axe on the page shell in light and + * dark. Needs `bun run build` first (turbo runs it) and a Playwright Chromium. + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { type Browser, type BrowserContextOptions, chromium, type Page } from "playwright"; +import { samples } from "../samples"; + +const root = fileURLToPath(new URL("..", import.meta.url)); +const require = createRequire(import.meta.url); +let browser: Browser; +let site: string; +let out: string; +let server: ReturnType<typeof Bun.serve>; + +beforeAll(async () => { + if (!existsSync(join(root, "dist/render.js"))) throw new Error("dist/ is missing: run `bun run build` first"); + site = mkdtempSync(join(tmpdir(), "apidocs-browser-")); + out = join(site, "out"); + const model = join(site, "model.json"); + const theme = join(site, "theme.json"); + writeFileSync(model, JSON.stringify(samples.java)); + writeFileSync(theme, JSON.stringify({ extends: "elide" })); + const run = spawnSync(process.execPath, [join(root, "dist/runner.mjs"), "--bundle", join(root, "dist/render.js"), "--assets", join(root, "dist/assets"), "--model", model, "--theme", theme, "--out", out], { encoding: "utf8" }); + if (run.status !== 0) throw new Error(run.stderr); + server = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + fetch(request) { + const path = decodeURIComponent(new URL(request.url).pathname).replace(/^\/+/, ""); + const file = resolve(out, path); + if (!file.startsWith(out) || !existsSync(file)) return new Response("Not found", { status: 404 }); + const type = file.endsWith(".html") ? "text/html" : file.endsWith(".css") ? "text/css" : file.endsWith(".js") ? "text/javascript" : file.endsWith(".woff2") ? "font/woff2" : "application/octet-stream"; + return new Response(readFileSync(file), { headers: { "content-type": type } }); + }, + }); + browser = await chromium.launch(); +}); + +afterAll(async () => { + await browser?.close(); + server?.stop(true); + if (site) rmSync(site, { recursive: true, force: true }); +}); + +const fileUrl = (path: string) => { + const [file, fragment] = path.split("#"); + return pathToFileURL(join(out, file!)).href + (fragment === undefined ? "" : `#${fragment}`); +}; +const httpUrl = (path: string) => `http://127.0.0.1:${server.port}/${path}`; + +async function open(path: string, options: BrowserContextOptions & { http?: boolean } = {}): Promise<{ page: Page; requests: string[]; errors: string[] }> { + const { http, ...contextOptions } = options; + const context = await browser.newContext({ colorScheme: "light", ...contextOptions }); + const page = await context.newPage(); + const requests: string[] = []; + const errors: string[] = []; + page.on("request", request => requests.push(request.url())); + page.on("pageerror", error => errors.push(error.message)); + page.on("console", message => message.type() === "error" && errors.push(message.text())); + await page.goto(http ? httpUrl(path) : fileUrl(path)); + return { page, requests, errors }; +} + +describe("from file:// with JavaScript off", () => { + test("pages are complete, and script-only controls stay out", async () => { + const { page, requests } = await open("com/example/geo/Shapes.html", { javaScriptEnabled: false }); + expect(await page.getByRole("heading", { level: 1 }).textContent()).toContain("Shapes"); + expect(await page.getByRole("heading", { level: 1, name: "Shapes" }).count()).toBe(1); + // Members are disclosures: every entry is in the page, and one opens with a click and no script. + expect(await page.locator("details.member").count()).toBeGreaterThan(8); + const parse = page.locator("details.member", { has: page.locator("#parse\\(java\\.lang\\.String\\)") }); + expect(await parse.locator(".callout-apiNote").count()).toBe(1); + expect(await parse.locator(".callout-apiNote").isVisible()).toBe(false); + await parse.locator("summary").click(); + expect(await parse.locator(".callout-apiNote").isVisible()).toBe(true); + for (const control of await page.locator("[data-js-only]").all()) expect(await control.isVisible()).toBe(false); + expect(await page.locator(".search-fallback").isVisible()).toBe(true); + expect(await page.locator("[data-copy]").first().isVisible()).toBe(false); + expect(requests.every(r => r.startsWith("file://"))).toBe(true); + await page.context().close(); + }); +}); + +describe("from file:// with JavaScript on", () => { + test("script-only controls show at first paint, before the deferred bundle runs", async () => { + const bundle = join(out, "assets/apidocs.js"); + renameSync(bundle, `${bundle}.held`); + try { + const { page } = await open("com/example/geo/Shapes.html"); + expect(await page.evaluate(() => document.documentElement.hasAttribute("data-js"))).toBe(true); + expect(await page.locator("[data-search]").isVisible()).toBe(true); + expect(await page.locator("[data-theme-switch]").isVisible()).toBe(true); + expect(await page.locator(".search-fallback").isVisible()).toBe(false); + await page.context().close(); + } finally { + renameSync(`${bundle}.held`, bundle); + } + }); + + test("search finds a member and opens it, with no errors and no network", async () => { + const { page, requests, errors } = await open("index.html"); + const input = page.getByRole("combobox", { name: "Search the API" }); + await input.fill("parse"); + const first = page.locator("#apidocs-results [role=option]").first(); + await first.waitFor(); + expect(await first.textContent()).toContain("parse(String)"); + await input.press("Enter"); + await page.waitForURL(/Shapes\.html#parse/); + expect(requests.every(r => r.startsWith("file://"))).toBe(true); + expect(errors).toEqual([]); + await page.context().close(); + }); + + test("the theme switch cycles and persists", async () => { + const { page } = await open("com/example/geo/Shape.html"); + const button = page.locator("[data-theme-switch]"); + await button.click(); + expect(await page.evaluate(() => document.documentElement.dataset.theme)).toBe("light"); + await button.click(); + expect(await page.evaluate(() => document.documentElement.dataset.theme)).toBe("dark"); + await page.reload(); + expect(await page.evaluate(() => document.documentElement.dataset.theme)).toBe("dark"); + await page.context().close(); + }); + + test("copy buttons show, and the table of contents follows the page", async () => { + const { page } = await open("com/example/geo/registry/ShapeCatalog.html#scaleStar(com.example.geo.Shape,double)"); + expect(await page.locator("[data-copy]").first().isVisible()).toBe(true); + await page.waitForSelector('.toc a[aria-current="true"]', { state: "attached" }); + expect(await page.locator('.toc a[aria-current="true"]').first().textContent()).toContain("scaleStar"); + await page.context().close(); + }); + + test("the navigator toggle hides it on a wide screen, remembers that, and [ toggles it", async () => { + const { page } = await open("com/example/geo/Shapes.html", { viewport: { width: 1440, height: 900 } }); + const nav = page.locator("#apidocs-nav"); + expect(await nav.isVisible()).toBe(true); + await page.locator(".nav-button").click(); + expect(await nav.isVisible()).toBe(false); + await page.reload(); + expect(await nav.isVisible()).toBe(false); + await page.locator("main").click({ position: { x: 5, y: 5 } }); + await page.keyboard.press("["); + expect(await nav.isVisible()).toBe(true); + await page.reload(); + expect(await nav.isVisible()).toBe(true); + await page.context().close(); + }); + + test("the navigator toggle shows it on a narrow screen", async () => { + const { page } = await open("com/example/geo/Shapes.html", { viewport: { width: 390, height: 844 } }); + const nav = page.locator("#apidocs-nav"); + expect(await nav.isVisible()).toBe(false); + await page.locator(".nav-button").click(); + expect(await nav.isVisible()).toBe(true); + await page.context().close(); + }); + + test("font preloads appear over HTTP and not on file://", async () => { + const preloads = (page: Page) => page.locator('head link[rel="preload"][as="font"]').count(); + const local = await open("com/example/geo/Shapes.html"); + expect(await preloads(local.page)).toBe(0); + expect(local.errors).toEqual([]); + await local.page.context().close(); + const served = await open("com/example/geo/Shapes.html", { http: true }); + expect(await preloads(served.page)).toBe(1); + expect(served.errors).toEqual([]); + await served.page.context().close(); + }); +}); + +describe("layout stability", () => { + async function shift(blockFonts: boolean): Promise<number> { + const context = await browser.newContext({ viewport: { width: 1440, height: 900 } }); + const page = await context.newPage(); + if (blockFonts) await page.route("**/*.woff2", route => route.abort()); + await page.addInitScript(() => { + (window as unknown as { cls: number }).cls = 0; + new PerformanceObserver(list => { + for (const entry of list.getEntries() as unknown as { value: number; hadRecentInput: boolean }[]) { + if (!entry.hadRecentInput) (window as unknown as { cls: number }).cls += entry.value; + } + }).observe({ type: "layout-shift", buffered: true }); + }); + await page.goto(httpUrl("com/example/geo/Shapes.html"), { waitUntil: "load" }); + await page.evaluate(() => document.fonts.ready); + await page.waitForTimeout(800); + const cls = await page.evaluate(() => (window as unknown as { cls: number }).cls); + await context.close(); + return cls; + } + test("a type page does not shift as it loads, with fonts", async () => expect(await shift(false)).toBe(0)); + test("a type page does not shift as it loads, with font requests blocked", async () => expect(await shift(true)).toBe(0)); +}); + +describe("accessibility", () => { + for (const colorScheme of ["light", "dark"] as const) { + for (const path of ["index.html", "com/example/geo/index.html", "com/example/geo/Shapes.html", "com/example/geo/Circle.html"]) { + test(`${path} in ${colorScheme} has no axe violations`, async () => { + const { page } = await open(path, { colorScheme }); + await page.addScriptTag({ path: require.resolve("axe-core/axe.min.js") }); + const violations = await page.evaluate(async () => { + const result = await (window as unknown as { axe: { run: (o: object) => Promise<{ violations: { id: string; nodes: { target: string[] }[] }[] }> } }) + .axe.run({ runOnly: { type: "tag", values: ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "best-practice"] } }); + return result.violations.map(v => `${v.id}: ${v.nodes.slice(0, 3).map(n => n.target.join(" ")).join(", ")}`); + }); + expect(violations).toEqual([]); + await page.context().close(); + }, 30_000); + } + } +}); diff --git a/packages/apidocs/test/check.ts b/packages/apidocs/test/check.ts new file mode 100644 index 0000000..835826b --- /dev/null +++ b/packages/apidocs/test/check.ts @@ -0,0 +1,99 @@ +/** + * Checks a rendered site against the portability rules: every link is + * relative and names its file, and its target file and anchor exist; no + * absolute URL except the model's externals and the theme's own links; no + * module scripts, no fetch, no event-handler attributes and no URL that + * safeUrl rejects (javascript:, data:, ...). Returns every problem found. + */ +import type { Output } from "../src/render"; +import { safeUrl } from "../src/url"; + +export interface CheckOptions { + /** URL prefixes allowed as absolute links: the model's externals, theme links, the base URL. */ + allowed: string[]; +} + +const ATTRS = /\s(href|src)="([^"]*)"/g; + +export function checkSite(out: Output, options: CheckOptions): string[] { + const errors: string[] = []; + const ids = new Map<string, Set<string>>(); + const idsOf = (file: string) => { + let set = ids.get(file); + if (!set) { + set = new Set(); + const html = out[file]; + if (typeof html === "string") for (const m of html.matchAll(/\sid="([^"]*)"/g)) set.add(unescape(m[1]!)); + ids.set(file, set); + } + return set; + }; + for (const [file, content] of Object.entries(out)) { + if (typeof content !== "string") continue; + if (file.endsWith(".html") || file.endsWith(".js")) { + if (/<script\b[^>]*\btype="module"/.test(content)) errors.push(`${file}: module script`); + // Only code counts: inline scripts (not JSON-LD) and script files, with string literals removed, so prose + // ("programs import (the stdlib)") and index data never match. + const code = file.endsWith(".js") + ? content + : [...content.matchAll(/<script\b(?![^>]*application\/ld\+json)[^>]*>([\s\S]*?)<\/script>/g)].map(m => m[1]).join("\n"); + const bare = code.replace(/"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`/g, '""'); + if (/\bfetch\s*\(/.test(bare)) errors.push(`${file}: uses fetch`); + if (/\bimport\s*\(/.test(bare)) errors.push(`${file}: dynamic import`); + } + if (!file.endsWith(".html")) continue; + // A tag runs to the first > outside a quoted value; attribute names are read with the values blanked, so text + // such as onerror= inside an escaped value is not mistaken for an attribute. + for (const tag of content.matchAll(/<[a-zA-Z](?:[^>"']|"[^"]*"|'[^']*')*>/g)) { + if (/\son[a-z]+\s*=/i.test(tag[0].replace(/"[^"]*"|'[^']*'/g, '""'))) errors.push(`${file}: event handler attribute in ${tag[0].slice(0, 80)}`); + } + for (const m of content.matchAll(ATTRS)) { + const url = unescape(m[2]!); + if (safeUrl(url) === undefined) { + errors.push(`${file}: unsafe URL ${url}`); + continue; + } + if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith("//")) { + if (!options.allowed.some(prefix => url.startsWith(prefix))) errors.push(`${file}: absolute URL ${url}`); + continue; + } + if (url === "" || url.startsWith("#")) { + errors.push(`${file}: link does not name its file: "${url}"`); + continue; + } + const [path, anchor] = splitAnchor(url); + if (path.endsWith("/")) { + errors.push(`${file}: link names a directory: ${url}`); + continue; + } + const target = join(file, decodeURIComponent(path)); + if (!(target in out)) { + errors.push(`${file}: link to a missing file ${url}`); + continue; + } + if (anchor !== undefined && target.endsWith(".html") && !idsOf(target).has(decodeURIComponent(anchor))) { + errors.push(`${file}: link to a missing anchor ${url}`); + } + } + } + return errors; +} + +function splitAnchor(url: string): [string, string | undefined] { + const at = url.indexOf("#"); + return at < 0 ? [url, undefined] : [url.slice(0, at), url.slice(at + 1)]; +} + +function unescape(s: string): string { + return s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&"); +} + +/** Resolves a relative URL against the file that contains it. */ +function join(from: string, relative: string): string { + const parts = from.split("/").slice(0, -1); + for (const segment of relative.split("/")) { + if (segment === "..") parts.pop(); + else if (segment !== "." && segment !== "") parts.push(segment); + } + return parts.join("/"); +} diff --git a/packages/apidocs/test/fixtures/fixture-java.api.json b/packages/apidocs/test/fixtures/fixture-java.api.json new file mode 100644 index 0000000..85613db --- /dev/null +++ b/packages/apidocs/test/fixtures/fixture-java.api.json @@ -0,0 +1,6551 @@ +{ + "schema": "apidocs/1", + "module": { + "name": "fixture", + "version": "1.0", + "languages": ["java"] + }, + "externals": [ + { + "prefix": "java.", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/{module}/" + }, + { + "prefix": "org.jspecify.", + "url": "https://jspecify.dev/docs/api/" + } + ], + "packages": [ + { + "id": "fixture.java", + "name": "fixture.java", + "doc": { + "summary": [ + { + "kind": "text", + "text": "Shapes, units and measurements: a fixture that exercises every declaration kind and documentation construct the API model represents." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Shapes, units and measurements: a fixture that exercises every declaration kind and documentation construct the API model represents." + } + ] + }, + { + "kind": "heading", + "level": 2, + "children": [ + { + "kind": "text", + "text": "Where to start" + } + ] + }, + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Start with " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Shape" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "fixture.java.Shape" + } + ] + }, + { + "kind": "text", + "text": " and the operations in " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Geometry" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "fixture.java.Geometry" + } + ] + }, + { + "kind": "text", + "text": ". Readers live in " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.io" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "fixture.java.io" + } + ] + }, + { + "kind": "text", + "text": "." + } + ] + } + ], + "see": [ + [ + { + "kind": "link", + "target": { + "id": "fixture.java.io" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "fixture.java.io" + } + ] + } + ] + ] + }, + "since": "1.0", + "nullMarked": true, + "types": [ + { + "id": "fixture.java.AbstractCanvas", + "name": "AbstractCanvas", + "kind": "class", + "language": "java", + "modifiers": ["public", "abstract"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"abstract"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"class"}, {"kind":"punct","text":" "}, {"kind":"name","text":"AbstractCanvas"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"implements"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Canvas","ref":"fixture.java.Canvas"}], + "superclass": [{"kind":"type","text":"Object","ref":"java.lang.Object","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html"}], + "interfaces": [ + [{"kind":"type","text":"Canvas","ref":"fixture.java.Canvas"}] + ], + "ancestors": [ + { + "id": "java.lang.Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + } + ], + "members": [ + { + "id": "fixture.java.AbstractCanvas#draw(fixture.java.Shape,fixture.java.Canvas.Layer)", + "anchor": "draw(fixture.java.Shape,fixture.java.Canvas.Layer)", + "kind": "method", + "name": "draw", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"void"}, {"kind":"punct","text":" "}, {"kind":"name","text":"draw"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":" "}, {"kind":"param","text":"shape"}, {"kind":"punct","text":", "}, {"kind":"type","text":"Canvas.Layer","ref":"fixture.java.Canvas$Layer"}, {"kind":"punct","text":" "}, {"kind":"param","text":"layer"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "shape", + "type": [{"kind":"type","text":"Shape","ref":"fixture.java.Shape"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shape" + } + ] + } + ] + }, + { + "name": "layer", + "type": [{"kind":"type","text":"Canvas.Layer","ref":"fixture.java.Canvas$Layer"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the layer to draw on" + } + ] + } + ] + } + ], + "overrides": { + "id": "fixture.java.Canvas#draw(fixture.java.Shape,fixture.java.Canvas.Layer)" + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Draws a shape on a layer." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Draws a shape on a layer." + } + ] + }, + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "This canvas also counts the shape." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/AbstractCanvas.java", + "line": 24 + } + }, + { + "id": "fixture.java.AbstractCanvas#drawn()", + "anchor": "drawn()", + "kind": "method", + "name": "drawn", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"int"}, {"kind":"punct","text":" "}, {"kind":"name","text":"drawn"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"keyword","text":"int"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the count" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "The number of shapes drawn so far." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The number of shapes drawn so far." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/AbstractCanvas.java", + "line": 43 + } + } + ], + "inherited": [ + { + "from": { + "id": "java.lang.Object", + "text": "Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Object#equals(java.lang.Object)", + "text": "equals", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)" + }, + { + "id": "java.lang.Object#getClass()", + "text": "getClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass()" + }, + { + "id": "java.lang.Object#hashCode()", + "text": "hashCode", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode()" + }, + { + "id": "java.lang.Object#notify()", + "text": "notify", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify()" + }, + { + "id": "java.lang.Object#notifyAll()", + "text": "notifyAll", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll()" + }, + { + "id": "java.lang.Object#toString()", + "text": "toString", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString()" + }, + { + "id": "java.lang.Object#wait()", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait()" + }, + { + "id": "java.lang.Object#wait(long)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long)" + }, + { + "id": "java.lang.Object#wait(long,int)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long,int)" + } + ] + }, + { + "from": { + "id": "fixture.java.Canvas", + "text": "Canvas" + }, + "kind": "interface", + "members": [ + { + "id": "fixture.java.Canvas#MAX_LAYERS", + "text": "MAX_LAYERS" + }, + { + "id": "fixture.java.Canvas#clear()", + "text": "clear" + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "A canvas that counts what it draws." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "A canvas that counts what it draws." + } + ] + } + ] + }, + "since": "1.0", + "nullMarked": true, + "source": { + "path": "fixture/java/AbstractCanvas.java", + "line": 13 + } + }, + { + "id": "fixture.java.Box", + "name": "Box", + "kind": "class", + "language": "java", + "modifiers": ["public"], + "typeParams": [ + { + "name": "T", + "bounds": [ + [{"kind":"type","text":"Comparable","ref":"java.lang.Comparable","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Comparable.html"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":">"}] + ], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the value's type" + } + ] + } + ] + } + ], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"class"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Box"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"extends"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Comparable","ref":"java.lang.Comparable","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Comparable.html"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":">>"}], + "superclass": [{"kind":"type","text":"Object","ref":"java.lang.Object","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html"}], + "ancestors": [ + { + "id": "java.lang.Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + } + ], + "members": [ + { + "id": "fixture.java.Box#value", + "anchor": "value", + "kind": "field", + "name": "value", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":" "}, {"kind":"name","text":"value"}], + "type": [{"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"typeParam","text":"T"}], + "nullness": "nullable", + "doc": { + "summary": [ + { + "kind": "text", + "text": "The value, or " + }, + { + "kind": "code", + "text": "null" + }, + { + "kind": "text", + "text": " when the box is empty." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The value, or " + }, + { + "kind": "code", + "text": "null" + }, + { + "kind": "text", + "text": " when the box is empty." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Box.java", + "line": 29 + } + }, + { + "id": "fixture.java.Box#<init>(T)", + "anchor": "<init>(T)", + "kind": "constructor", + "name": "Box", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Box"}, {"kind":"punct","text":"("}, {"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":" "}, {"kind":"param","text":"value"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "value", + "type": [{"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"typeParam","text":"T"}], + "nullness": "nullable", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the initial value, or " + }, + { + "kind": "code", + "text": "null" + } + ] + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Creates a box." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Creates a box." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Box.java", + "line": 36 + } + }, + { + "id": "fixture.java.Box#map(java.util.function.Function)", + "anchor": "map(java.util.function.Function)", + "kind": "method", + "name": "map", + "modifiers": ["public"], + "typeParams": [ + { + "name": "U", + "bounds": [ + [{"kind":"type","text":"Comparable","ref":"java.lang.Comparable","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Comparable.html"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"U"}, {"kind":"punct","text":">"}] + ], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the result type" + } + ] + } + ] + } + ], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" <"}, {"kind":"typeParam","text":"U"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"extends"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Comparable","ref":"java.lang.Comparable","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Comparable.html"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"U"}, {"kind":"punct","text":">> "}, {"kind":"type","text":"Box","ref":"fixture.java.Box"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"U"}, {"kind":"punct","text":"> "}, {"kind":"name","text":"map"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Function","ref":"java.util.function.Function","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Function.html"}, {"kind":"punct","text":"<? "}, {"kind":"keyword","text":"super"}, {"kind":"punct","text":" "}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":", ? "}, {"kind":"keyword","text":"extends"}, {"kind":"punct","text":" "}, {"kind":"typeParam","text":"U"}, {"kind":"punct","text":"> "}, {"kind":"param","text":"function"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "function", + "type": [{"kind":"type","text":"Function","ref":"java.util.function.Function","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Function.html"}, {"kind":"punct","text":"<? "}, {"kind":"keyword","text":"super"}, {"kind":"punct","text":" "}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":", ? "}, {"kind":"keyword","text":"extends"}, {"kind":"punct","text":" "}, {"kind":"typeParam","text":"U"}, {"kind":"punct","text":">"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the function" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"type","text":"Box","ref":"fixture.java.Box"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"U"}, {"kind":"punct","text":">"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "a box holding the function's result" + } + ] + } + ] + }, + "throws": [ + { + "type": [{"kind":"type","text":"NullPointerException","ref":"java.lang.NullPointerException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/NullPointerException.html"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "if the box is empty" + } + ] + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Applies a function to the value." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Applies a function to the value." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Box.java", + "line": 48 + } + }, + { + "id": "fixture.java.Box#present()", + "anchor": "present()", + "kind": "method", + "name": "present", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"boolean"}, {"kind":"punct","text":" "}, {"kind":"name","text":"present"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"keyword","text":"boolean"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "whether the box holds a value" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Returns whether the box holds a value." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Returns whether the box holds a value." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Box.java", + "line": 58 + } + }, + { + "id": "fixture.java.Box#compareTo(fixture.java.Box)", + "anchor": "compareTo(fixture.java.Box)", + "kind": "method", + "name": "compareTo", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"int"}, {"kind":"punct","text":" "}, {"kind":"name","text":"compareTo"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Box","ref":"fixture.java.Box"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":"> "}, {"kind":"param","text":"other"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "other", + "type": [{"kind":"type","text":"Box","ref":"fixture.java.Box"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":">"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the other box" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"keyword","text":"int"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the comparison, as " + }, + { + "kind": "link", + "target": { + "id": "java.lang.Comparable#compareTo(T)", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Comparable.html#compareTo(T)" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "Comparable.compareTo(Object)" + } + ] + }, + { + "kind": "text", + "text": " defines it" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Compares the value with another box's." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Compares the value with another box's." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Box.java", + "line": 68 + } + } + ], + "inherited": [ + { + "from": { + "id": "java.lang.Object", + "text": "Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Object#equals(java.lang.Object)", + "text": "equals", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)" + }, + { + "id": "java.lang.Object#getClass()", + "text": "getClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass()" + }, + { + "id": "java.lang.Object#hashCode()", + "text": "hashCode", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode()" + }, + { + "id": "java.lang.Object#notify()", + "text": "notify", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify()" + }, + { + "id": "java.lang.Object#notifyAll()", + "text": "notifyAll", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll()" + }, + { + "id": "java.lang.Object#toString()", + "text": "toString", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString()" + }, + { + "id": "java.lang.Object#wait()", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait()" + }, + { + "id": "java.lang.Object#wait(long)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long)" + }, + { + "id": "java.lang.Object#wait(long,int)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long,int)" + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "A mutable holder for one comparable value." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "A mutable holder for one comparable value. Boxes are not thread-safe." + } + ] + }, + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Read the value with " + }, + { + "kind": "code", + "text": "fixture.box.mode" + }, + { + "kind": "text", + "text": " unset; see the box semantics below." + } + ] + }, + { + "kind": "code", + "language": "java", + "text": "Box<String> box = new Box<>(\"a\");\nbox.value = \"b\";" + } + ] + }, + "since": "1.0", + "nullMarked": true, + "source": { + "path": "fixture/java/Box.java", + "line": 27 + } + }, + { + "id": "fixture.java.Canvas", + "name": "Canvas", + "kind": "interface", + "language": "java", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"interface"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Canvas"}], + "members": [ + { + "id": "fixture.java.Canvas#MAX_LAYERS", + "anchor": "MAX_LAYERS", + "kind": "field", + "name": "MAX_LAYERS", + "signature": [{"kind":"keyword","text":"int"}, {"kind":"punct","text":" "}, {"kind":"name","text":"MAX_LAYERS"}], + "type": [{"kind":"keyword","text":"int"}], + "constant": "16", + "doc": { + "summary": [ + { + "kind": "text", + "text": "The largest layer index a canvas supports." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The largest layer index a canvas supports." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Canvas.java", + "line": 15 + } + }, + { + "id": "fixture.java.Canvas#draw(fixture.java.Shape,fixture.java.Canvas.Layer)", + "anchor": "draw(fixture.java.Shape,fixture.java.Canvas.Layer)", + "kind": "method", + "name": "draw", + "signature": [{"kind":"keyword","text":"void"}, {"kind":"punct","text":" "}, {"kind":"name","text":"draw"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":" "}, {"kind":"param","text":"shape"}, {"kind":"punct","text":", "}, {"kind":"type","text":"Canvas.Layer","ref":"fixture.java.Canvas$Layer"}, {"kind":"punct","text":" "}, {"kind":"param","text":"layer"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "shape", + "type": [{"kind":"type","text":"Shape","ref":"fixture.java.Shape"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shape" + } + ] + } + ] + }, + { + "name": "layer", + "type": [{"kind":"type","text":"Canvas.Layer","ref":"fixture.java.Canvas$Layer"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the layer to draw on" + } + ] + } + ] + } + ], + "throws": [ + { + "type": [{"kind":"type","text":"IllegalArgumentException","ref":"java.lang.IllegalArgumentException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "if " + }, + { + "kind": "code", + "text": "layer" + }, + { + "kind": "text", + "text": " is out of range" + } + ] + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Draws a shape on a layer." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Draws a shape on a layer." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Canvas.java", + "line": 24 + } + }, + { + "id": "fixture.java.Canvas#clear()", + "anchor": "clear()", + "kind": "method", + "name": "clear", + "modifiers": ["default"], + "signature": [{"kind":"keyword","text":"default"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"void"}, {"kind":"punct","text":" "}, {"kind":"name","text":"clear"}, {"kind":"punct","text":"()"}], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Clears every layer." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Clears every layer." + } + ] + } + ], + "notes": [ + { + "kind": "implSpec", + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The default draws nothing and returns." + } + ] + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Canvas.java", + "line": 31 + } + }, + { + "id": "fixture.java.Canvas#empty()", + "anchor": "empty()", + "kind": "method", + "name": "empty", + "modifiers": ["static"], + "signature": [{"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Canvas","ref":"fixture.java.Canvas"}, {"kind":"punct","text":" "}, {"kind":"name","text":"empty"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"type","text":"Canvas","ref":"fixture.java.Canvas"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the canvas" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "A canvas that ignores everything drawn on it." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "A canvas that ignores everything drawn on it." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Canvas.java", + "line": 38 + } + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Somewhere to draw shapes." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Somewhere to draw shapes." + } + ] + } + ] + }, + "since": "1.0", + "nullMarked": true, + "source": { + "path": "fixture/java/Canvas.java", + "line": 13 + } + }, + { + "id": "fixture.java.Canvas$Layer", + "name": "Canvas.Layer", + "kind": "interface", + "language": "java", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"interface"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Canvas.Layer"}], + "enclosing": "fixture.java.Canvas", + "members": [ + { + "id": "fixture.java.Canvas$Layer#index()", + "anchor": "index()", + "kind": "method", + "name": "index", + "signature": [{"kind":"keyword","text":"int"}, {"kind":"punct","text":" "}, {"kind":"name","text":"index"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"keyword","text":"int"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the index, from zero to " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Canvas#MAX_LAYERS" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "Canvas.MAX_LAYERS" + } + ] + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "The layer's index." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The layer's index." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Canvas.java", + "line": 49 + } + }, + { + "id": "fixture.java.Canvas$Layer#kind()", + "anchor": "kind()", + "kind": "method", + "name": "kind", + "signature": [{"kind":"type","text":"Canvas.Layer.Kind","ref":"fixture.java.Canvas$Layer$Kind"}, {"kind":"punct","text":" "}, {"kind":"name","text":"kind"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"type","text":"Canvas.Layer.Kind","ref":"fixture.java.Canvas$Layer$Kind"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the kind" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "What a layer holds." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "What a layer holds." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Canvas.java", + "line": 56 + } + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "One layer of a canvas." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "One layer of a canvas." + } + ] + } + ] + }, + "nullMarked": true, + "source": { + "path": "fixture/java/Canvas.java", + "line": 43 + } + }, + { + "id": "fixture.java.Canvas$Layer$Kind", + "name": "Canvas.Layer.Kind", + "kind": "enum", + "language": "java", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"enum"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Canvas.Layer.Kind"}], + "superclass": [{"kind":"type","text":"Enum","ref":"java.lang.Enum","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html"}, {"kind":"punct","text":"<"}, {"kind":"type","text":"Canvas.Layer.Kind","ref":"fixture.java.Canvas$Layer$Kind"}, {"kind":"punct","text":">"}], + "ancestors": [ + { + "id": "java.lang.Enum", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html" + }, + { + "id": "java.lang.Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + } + ], + "enclosing": "fixture.java.Canvas$Layer", + "members": [ + { + "id": "fixture.java.Canvas$Layer$Kind#values()", + "anchor": "values()", + "kind": "method", + "name": "values", + "modifiers": ["public", "static"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Canvas.Layer.Kind","ref":"fixture.java.Canvas$Layer$Kind"}, {"kind":"punct","text":"[] "}, {"kind":"name","text":"values"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"type","text":"Canvas.Layer.Kind","ref":"fixture.java.Canvas$Layer$Kind"}, {"kind":"punct","text":"[]"}], + "nullness": "nonNull" + } + }, + { + "id": "fixture.java.Canvas$Layer$Kind#valueOf(java.lang.String)", + "anchor": "valueOf(java.lang.String)", + "kind": "method", + "name": "valueOf", + "modifiers": ["public", "static"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Canvas.Layer.Kind","ref":"fixture.java.Canvas$Layer$Kind"}, {"kind":"punct","text":" "}, {"kind":"name","text":"valueOf"}, {"kind":"punct","text":"("}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"name"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "name", + "type": [{"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "nullness": "nonNull" + } + ], + "returns": { + "type": [{"kind":"type","text":"Canvas.Layer.Kind","ref":"fixture.java.Canvas$Layer$Kind"}], + "nullness": "nonNull" + } + }, + { + "id": "fixture.java.Canvas$Layer$Kind#BACKGROUND", + "anchor": "BACKGROUND", + "kind": "enumConstant", + "name": "BACKGROUND", + "signature": [{"kind":"name","text":"BACKGROUND"}], + "type": [{"kind":"type","text":"Canvas.Layer.Kind","ref":"fixture.java.Canvas$Layer$Kind"}], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Background fills." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Background fills." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Canvas.java", + "line": 61 + } + }, + { + "id": "fixture.java.Canvas$Layer$Kind#SHAPES", + "anchor": "SHAPES", + "kind": "enumConstant", + "name": "SHAPES", + "signature": [{"kind":"name","text":"SHAPES"}], + "type": [{"kind":"type","text":"Canvas.Layer.Kind","ref":"fixture.java.Canvas$Layer$Kind"}], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Shapes." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Shapes." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Canvas.java", + "line": 63 + } + } + ], + "inherited": [ + { + "from": { + "id": "java.lang.Enum", + "text": "Enum", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Enum#compareTo(E)", + "text": "compareTo", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#compareTo(E)" + }, + { + "id": "java.lang.Enum#describeConstable()", + "text": "describeConstable", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#describeConstable()" + }, + { + "id": "java.lang.Enum#equals(java.lang.Object)", + "text": "equals", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#equals(java.lang.Object)" + }, + { + "id": "java.lang.Enum#getDeclaringClass()", + "text": "getDeclaringClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#getDeclaringClass()" + }, + { + "id": "java.lang.Enum#hashCode()", + "text": "hashCode", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#hashCode()" + }, + { + "id": "java.lang.Enum#name()", + "text": "name", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#name()" + }, + { + "id": "java.lang.Enum#ordinal()", + "text": "ordinal", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#ordinal()" + }, + { + "id": "java.lang.Enum#toString()", + "text": "toString", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#toString()" + }, + { + "id": "java.lang.Enum#valueOf(java.lang.Class,java.lang.String)", + "text": "valueOf", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#valueOf(java.lang.Class,java.lang.String)" + } + ] + }, + { + "from": { + "id": "java.lang.Object", + "text": "Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Object#getClass()", + "text": "getClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass()" + }, + { + "id": "java.lang.Object#notify()", + "text": "notify", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify()" + }, + { + "id": "java.lang.Object#notifyAll()", + "text": "notifyAll", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll()" + }, + { + "id": "java.lang.Object#wait()", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait()" + }, + { + "id": "java.lang.Object#wait(long)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long)" + }, + { + "id": "java.lang.Object#wait(long,int)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long,int)" + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "What a layer holds." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "What a layer holds." + } + ] + } + ] + }, + "nullMarked": true, + "source": { + "path": "fixture/java/Canvas.java", + "line": 59 + } + }, + { + "id": "fixture.java.Circle", + "name": "Circle", + "kind": "record", + "language": "java", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"record"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Circle"}, {"kind":"punct","text":"("}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"param","text":"radius"}, {"kind":"punct","text":", "}, {"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"label"}, {"kind":"punct","text":") "}, {"kind":"keyword","text":"implements"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}], + "superclass": [{"kind":"type","text":"Record","ref":"java.lang.Record","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html"}], + "interfaces": [ + [{"kind":"type","text":"Shape","ref":"fixture.java.Shape"}] + ], + "ancestors": [ + { + "id": "java.lang.Record", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html" + }, + { + "id": "java.lang.Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + } + ], + "components": [ + { + "name": "radius", + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the radius in meters; not negative" + } + ] + } + ] + }, + { + "name": "label", + "type": [{"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "nullness": "nullable", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "an optional label" + } + ] + } + ] + } + ], + "members": [ + { + "id": "fixture.java.Circle#<init>(double,java.lang.String)", + "anchor": "<init>(double,java.lang.String)", + "kind": "constructor", + "name": "Circle", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Circle"}, {"kind":"punct","text":"("}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"param","text":"radius"}, {"kind":"punct","text":", "}, {"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"label"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "radius", + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the radius in meters; not negative" + } + ] + } + ] + }, + { + "name": "label", + "type": [{"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "nullness": "nullable", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "an optional label" + } + ] + } + ] + } + ], + "throws": [ + { + "type": [{"kind":"type","text":"IllegalArgumentException","ref":"java.lang.IllegalArgumentException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "if " + }, + { + "kind": "code", + "text": "radius" + }, + { + "kind": "text", + "text": " is negative" + } + ] + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Checks the radius." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Checks the radius." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Circle.java", + "line": 23 + } + }, + { + "id": "fixture.java.Circle#of(double)", + "anchor": "of(double)", + "kind": "method", + "name": "of", + "modifiers": ["public", "static"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Circle","ref":"fixture.java.Circle"}, {"kind":"punct","text":" "}, {"kind":"name","text":"of"}, {"kind":"punct","text":"("}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"param","text":"radius"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "radius", + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the radius in meters" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"type","text":"Circle","ref":"fixture.java.Circle"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the circle" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Creates an unlabeled circle." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Creates an unlabeled circle." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Circle.java", + "line": 35 + } + }, + { + "id": "fixture.java.Circle#area()", + "anchor": "area()", + "kind": "method", + "name": "area", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"name","text":"area"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the area in square meters, never negative" + } + ] + } + ] + }, + "overrides": { + "id": "fixture.java.Shape#area()" + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "The shape's area." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The shape's area. For a circle this is " + }, + { + "kind": "code", + "text": "π r²" + }, + { + "kind": "text", + "text": "." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Circle.java", + "line": 40 + } + }, + { + "id": "fixture.java.Circle#name()", + "anchor": "name()", + "kind": "method", + "name": "name", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"name","text":"name"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "nullness": "nullable", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shape's name, or " + }, + { + "kind": "code", + "text": "null" + }, + { + "kind": "text", + "text": " for an anonymous shape" + } + ] + } + ] + }, + "overrides": { + "id": "fixture.java.Shape#name()" + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Returns the shape's name, or " + }, + { + "kind": "code", + "text": "null" + }, + { + "kind": "text", + "text": " for an anonymous shape." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Returns the shape's name, or " + }, + { + "kind": "code", + "text": "null" + }, + { + "kind": "text", + "text": " for an anonymous shape." + } + ] + } + ], + "inheritedFrom": { + "id": "fixture.java.Shape#name()" + } + }, + "source": { + "path": "fixture/java/Circle.java", + "line": 45 + } + }, + { + "id": "fixture.java.Circle#accept(fixture.java.Shape.Visitor)", + "anchor": "accept(fixture.java.Shape.Visitor)", + "kind": "method", + "name": "accept", + "modifiers": ["public"], + "typeParams": [ + { + "name": "R", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the visitor's result type" + } + ] + } + ] + } + ], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" <"}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":"> "}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":" "}, {"kind":"name","text":"accept"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Shape.Visitor","ref":"fixture.java.Shape$Visitor"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":"> "}, {"kind":"param","text":"visitor"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "visitor", + "type": [{"kind":"type","text":"Shape.Visitor","ref":"fixture.java.Shape$Visitor"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":">"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the visitor" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"typeParam","text":"R"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "what the visitor returned" + } + ] + } + ] + }, + "overrides": { + "id": "fixture.java.Shape#accept(fixture.java.Shape.Visitor)" + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Calls the visitor's method for this shape's kind." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Calls the visitor's method for this shape's kind." + } + ] + } + ], + "inheritedFrom": { + "id": "fixture.java.Shape#accept(fixture.java.Shape.Visitor)" + } + }, + "source": { + "path": "fixture/java/Circle.java", + "line": 50 + } + }, + { + "id": "fixture.java.Circle#toString()", + "anchor": "toString()", + "kind": "method", + "name": "toString", + "modifiers": ["public", "final"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"final"}, {"kind":"punct","text":" "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"name","text":"toString"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "nullness": "nonNull" + }, + "overrides": { + "id": "java.lang.Record#toString()", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html#toString()" + } + }, + { + "id": "fixture.java.Circle#hashCode()", + "anchor": "hashCode()", + "kind": "method", + "name": "hashCode", + "modifiers": ["public", "final"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"final"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"int"}, {"kind":"punct","text":" "}, {"kind":"name","text":"hashCode"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"keyword","text":"int"}] + }, + "overrides": { + "id": "java.lang.Record#hashCode()", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html#hashCode()" + } + }, + { + "id": "fixture.java.Circle#equals(java.lang.Object)", + "anchor": "equals(java.lang.Object)", + "kind": "method", + "name": "equals", + "modifiers": ["public", "final"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"final"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"boolean"}, {"kind":"punct","text":" "}, {"kind":"name","text":"equals"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Object","ref":"java.lang.Object","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"o"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "o", + "type": [{"kind":"type","text":"Object","ref":"java.lang.Object","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html"}], + "nullness": "nonNull" + } + ], + "returns": { + "type": [{"kind":"keyword","text":"boolean"}] + }, + "overrides": { + "id": "java.lang.Record#equals(java.lang.Object)", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Record.html#equals(java.lang.Object)" + } + }, + { + "id": "fixture.java.Circle#radius()", + "anchor": "radius()", + "kind": "method", + "name": "radius", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"name","text":"radius"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"keyword","text":"double"}] + } + }, + { + "id": "fixture.java.Circle#label()", + "anchor": "label()", + "kind": "method", + "name": "label", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"name","text":"label"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "nullness": "nullable" + } + } + ], + "inherited": [ + { + "from": { + "id": "java.lang.Object", + "text": "Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Object#getClass()", + "text": "getClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass()" + }, + { + "id": "java.lang.Object#notify()", + "text": "notify", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify()" + }, + { + "id": "java.lang.Object#notifyAll()", + "text": "notifyAll", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll()" + }, + { + "id": "java.lang.Object#wait()", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait()" + }, + { + "id": "java.lang.Object#wait(long)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long)" + }, + { + "id": "java.lang.Object#wait(long,int)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long,int)" + } + ] + }, + { + "from": { + "id": "fixture.java.Shape", + "text": "Shape" + }, + "kind": "interface", + "members": [ + { + "id": "fixture.java.Shape#compareTo(fixture.java.Shape)", + "text": "compareTo" + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "A circle." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "A circle." + } + ] + } + ] + }, + "since": "1.0", + "nullMarked": true, + "source": { + "path": "fixture/java/Circle.java", + "line": 17 + } + }, + { + "id": "fixture.java.Geometry", + "name": "Geometry", + "kind": "class", + "language": "java", + "modifiers": ["public", "final"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"final"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"class"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Geometry"}], + "superclass": [{"kind":"type","text":"Object","ref":"java.lang.Object","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html"}], + "ancestors": [ + { + "id": "java.lang.Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + } + ], + "members": [ + { + "id": "fixture.java.Geometry#PRECISION", + "anchor": "PRECISION", + "kind": "field", + "name": "PRECISION", + "modifiers": ["public", "static", "final"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"final"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"int"}, {"kind":"punct","text":" "}, {"kind":"name","text":"PRECISION"}], + "type": [{"kind":"keyword","text":"int"}], + "constant": "6", + "doc": { + "summary": [ + { + "kind": "text", + "text": "The default number of significant digits: " + }, + { + "kind": "code", + "text": "6" + }, + { + "kind": "text", + "text": "." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The default number of significant digits: " + }, + { + "kind": "code", + "text": "6" + }, + { + "kind": "text", + "text": "." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Geometry.java", + "line": 70 + } + }, + { + "id": "fixture.java.Geometry#NAME", + "anchor": "NAME", + "kind": "field", + "name": "NAME", + "modifiers": ["public", "static", "final"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"final"}, {"kind":"punct","text":" "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"name","text":"NAME"}], + "type": [{"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "nullness": "nonNull", + "constant": "\"fixture\"", + "doc": { + "summary": [ + { + "kind": "text", + "text": "The library's name, " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Geometry#NAME" + }, + "code": true, + "children": [ + { + "kind": "code", + "text": "\"fixture\"" + } + ] + }, + { + "kind": "text", + "text": ", as tools report it." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The library's name, " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Geometry#NAME" + }, + "code": true, + "children": [ + { + "kind": "code", + "text": "\"fixture\"" + } + ] + }, + { + "kind": "text", + "text": ", as tools report it." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Geometry.java", + "line": 73 + } + }, + { + "id": "fixture.java.Geometry#largest(java.util.Collection)", + "anchor": "largest(java.util.Collection)", + "kind": "method", + "name": "largest", + "modifiers": ["public", "static"], + "typeParams": [ + { + "name": "T", + "bounds": [ + [{"kind":"type","text":"Shape","ref":"fixture.java.Shape"}], + [{"kind":"type","text":"Comparable","ref":"java.lang.Comparable","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Comparable.html"}, {"kind":"punct","text":"<? "}, {"kind":"keyword","text":"super"}, {"kind":"punct","text":" "}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":">"}] + ], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shape type" + } + ] + } + ] + } + ], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" <"}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"extends"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":" & "}, {"kind":"type","text":"Comparable","ref":"java.lang.Comparable","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Comparable.html"}, {"kind":"punct","text":"<? "}, {"kind":"keyword","text":"super"}, {"kind":"punct","text":" "}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":">> "}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":" "}, {"kind":"name","text":"largest"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Collection","ref":"java.util.Collection","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Collection.html"}, {"kind":"punct","text":"<? "}, {"kind":"keyword","text":"extends"}, {"kind":"punct","text":" "}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":"> "}, {"kind":"param","text":"shapes"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "shapes", + "type": [{"kind":"type","text":"Collection","ref":"java.util.Collection","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Collection.html"}, {"kind":"punct","text":"<? "}, {"kind":"keyword","text":"extends"}, {"kind":"punct","text":" "}, {"kind":"typeParam","text":"T"}, {"kind":"punct","text":">"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shapes; not empty" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"typeParam","text":"T"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the largest of " + }, + { + "kind": "code", + "text": "shapes" + } + ] + } + ] + }, + "throws": [ + { + "type": [{"kind":"type","text":"NoSuchElementException","ref":"java.util.NoSuchElementException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/NoSuchElementException.html"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "if " + }, + { + "kind": "code", + "text": "shapes" + }, + { + "kind": "text", + "text": " is empty" + } + ] + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Returns the largest shape." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Returns the largest shape." + } + ] + } + ], + "notes": [ + { + "kind": "implSpec", + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Compares with " + }, + { + "kind": "link", + "target": { + "id": "java.lang.Comparable#compareTo(T)", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Comparable.html#compareTo(T)" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "Comparable.compareTo(Object)" + } + ] + }, + { + "kind": "text", + "text": ", keeping the first of equal shapes." + } + ] + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Geometry.java", + "line": 87 + } + }, + { + "id": "fixture.java.Geometry#totalArea(fixture.java.Shape...)", + "anchor": "totalArea(fixture.java.Shape...)", + "kind": "method", + "name": "totalArea", + "modifiers": ["public", "static"], + "annotations": [ + [{"kind":"annotation","text":"@Measured","ref":"fixture.java.Measured"}, {"kind":"punct","text":"("}, {"kind":"param","text":"precision"}, {"kind":"punct","text":" = "}, {"kind":"literal","text":"6"}, {"kind":"punct","text":")"}] + ], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"name","text":"totalArea"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":"... "}, {"kind":"param","text":"shapes"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "shapes", + "type": [{"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":"..."}], + "varargs": true, + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shapes" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the total area in square meters; " + }, + { + "kind": "code", + "text": "0" + }, + { + "kind": "text", + "text": " for no shapes" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Sums the shapes' areas." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Sums the shapes' areas." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Geometry.java", + "line": 106 + } + }, + { + "id": "fixture.java.Geometry#parse(java.lang.String)", + "anchor": "parse(java.lang.String)", + "kind": "method", + "name": "parse", + "modifiers": ["public", "static"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":" "}, {"kind":"name","text":"parse"}, {"kind":"punct","text":"("}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"text"}, {"kind":"punct","text":") "}, {"kind":"keyword","text":"throws"}, {"kind":"punct","text":" "}, {"kind":"type","text":"IOException","ref":"java.io.IOException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html"}, {"kind":"punct","text":", "}, {"kind":"type","text":"ParseException","ref":"java.text.ParseException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/text/ParseException.html"}], + "params": [ + { + "name": "text", + "type": [{"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the text form" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"type","text":"Shape","ref":"fixture.java.Shape"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shape" + } + ] + } + ] + }, + "throws": [ + { + "type": [{"kind":"type","text":"IOException","ref":"java.io.IOException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html"}], + "declared": true, + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "if the text names a file that cannot be read" + } + ] + } + ] + }, + { + "type": [{"kind":"type","text":"IllegalStateException","ref":"java.lang.IllegalStateException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "if the parser was closed" + } + ] + } + ] + }, + { + "type": [{"kind":"type","text":"ParseException","ref":"java.text.ParseException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/text/ParseException.html"}], + "declared": true + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Parses a shape from its text form, such as " + }, + { + "kind": "code", + "text": "circle 2.5" + }, + { + "kind": "text", + "text": "." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Parses a shape from its text form, such as " + }, + { + "kind": "code", + "text": "circle 2.5" + }, + { + "kind": "text", + "text": "." + } + ] + } + ], + "notes": [ + { + "kind": "apiNote", + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The text form is not stable across releases; store shapes some other way." + } + ] + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Geometry.java", + "line": 125 + } + }, + { + "id": "fixture.java.Geometry#sum(java.util.List)", + "anchor": "sum(java.util.List)", + "kind": "method", + "name": "sum", + "modifiers": ["public", "static"], + "annotations": [ + [{"kind":"annotation","text":"@Deprecated","ref":"java.lang.Deprecated","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Deprecated.html"}, {"kind":"punct","text":"("}, {"kind":"param","text":"since"}, {"kind":"punct","text":" = "}, {"kind":"literal","text":"\"1.1\""}, {"kind":"punct","text":", "}, {"kind":"param","text":"forRemoval"}, {"kind":"punct","text":" = "}, {"kind":"literal","text":"true"}, {"kind":"punct","text":")"}] + ], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"name","text":"sum"}, {"kind":"punct","text":"("}, {"kind":"type","text":"List","ref":"java.util.List","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html"}, {"kind":"punct","text":"<"}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":"> "}, {"kind":"param","text":"shapes"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "shapes", + "type": [{"kind":"type","text":"List","ref":"java.util.List","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html"}, {"kind":"punct","text":"<"}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":">"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shapes" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the total area" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Sums the areas of a list of shapes." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Sums the areas of a list of shapes." + } + ] + } + ] + }, + "deprecated": { + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Use " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Geometry#totalArea(fixture.java.Shape...)" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "totalArea(Shape...)" + } + ] + }, + { + "kind": "text", + "text": ", which takes any number of shapes." + } + ] + } + ], + "since": "1.1", + "forRemoval": true + }, + "source": { + "path": "fixture/java/Geometry.java", + "line": 136 + } + }, + { + "id": "fixture.java.Geometry#find(java.util.Map,java.lang.String)", + "anchor": "find(java.util.Map,java.lang.String)", + "kind": "method", + "name": "find", + "modifiers": ["public", "static"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":" "}, {"kind":"name","text":"find"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Map","ref":"java.util.Map","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html"}, {"kind":"punct","text":"<"}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":", ? "}, {"kind":"keyword","text":"extends"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":"> "}, {"kind":"param","text":"shapes"}, {"kind":"punct","text":", "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"name"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "shapes", + "type": [{"kind":"type","text":"Map","ref":"java.util.Map","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html"}, {"kind":"punct","text":"<"}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":", ? "}, {"kind":"keyword","text":"extends"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":">"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "shapes by name" + } + ] + } + ] + }, + { + "name": "name", + "type": [{"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the name to look up" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}], + "nullness": "nullable", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shape, or " + }, + { + "kind": "code", + "text": "null" + }, + { + "kind": "text", + "text": " when there is none" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Finds a shape by name." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Finds a shape by name." + } + ] + } + ] + }, + "since": "1.1", + "source": { + "path": "fixture/java/Geometry.java", + "line": 149 + } + } + ], + "inherited": [ + { + "from": { + "id": "java.lang.Object", + "text": "Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Object#equals(java.lang.Object)", + "text": "equals", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)" + }, + { + "id": "java.lang.Object#getClass()", + "text": "getClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass()" + }, + { + "id": "java.lang.Object#hashCode()", + "text": "hashCode", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode()" + }, + { + "id": "java.lang.Object#notify()", + "text": "notify", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify()" + }, + { + "id": "java.lang.Object#notifyAll()", + "text": "notifyAll", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll()" + }, + { + "id": "java.lang.Object#toString()", + "text": "toString", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString()" + }, + { + "id": "java.lang.Object#wait()", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait()" + }, + { + "id": "java.lang.Object#wait(long)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long)" + }, + { + "id": "java.lang.Object#wait(long,int)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long,int)" + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Operations on " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Shape" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "shapes" + } + ] + }, + { + "kind": "text", + "text": "." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Operations on " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Shape" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "shapes" + } + ] + }, + { + "kind": "text", + "text": "." + } + ] + }, + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Every method is " + }, + { + "kind": "emphasis", + "children": [ + { + "kind": "text", + "text": "pure" + } + ] + }, + { + "kind": "text", + "text": ": it never modifies its arguments. " + }, + { + "kind": "strong", + "children": [ + { + "kind": "text", + "text": "Thread safety:" + } + ] + }, + { + "kind": "text", + "text": " every method is safe to call concurrently." + } + ] + }, + { + "kind": "list", + "items": [ + [ + { + "kind": "paragraph", + "children": [ + { + "kind": "link", + "target": { + "id": "fixture.java.Geometry#largest(java.util.Collection)" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "largest(Collection)" + } + ] + }, + { + "kind": "text", + "text": " picks the largest shape." + } + ] + } + ], + [ + { + "kind": "paragraph", + "children": [ + { + "kind": "link", + "target": { + "id": "fixture.java.Geometry#totalArea(fixture.java.Shape...)" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "totalArea(Shape...)" + } + ] + }, + { + "kind": "text", + "text": " sums areas." + } + ] + } + ] + ] + }, + { + "kind": "list", + "ordered": true, + "items": [ + [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "First, measure." + } + ] + } + ], + [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Then compare, with " + }, + { + "kind": "code", + "text": "compareTo" + }, + { + "kind": "text", + "text": "." + } + ] + } + ] + ] + }, + { + "kind": "table", + "caption": [ + { + "kind": "text", + "text": "Unit factors" + } + ], + "head": [ + [ + [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Unit" + } + ] + } + ], + [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Factor" + } + ] + } + ] + ] + ], + "rows": [ + [ + [ + { + "kind": "paragraph", + "children": [ + { + "kind": "link", + "target": { + "id": "fixture.java.Units#METERS" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "Units.METERS" + } + ] + } + ] + } + ], + [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "1.0" + } + ] + } + ] + ], + [ + [ + { + "kind": "paragraph", + "children": [ + { + "kind": "link", + "target": { + "id": "fixture.java.Units#FEET" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "Units.FEET" + } + ] + } + ] + } + ], + [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "0.3048" + } + ] + } + ] + ] + ] + }, + { + "kind": "code", + "text": "Shape big = Geometry.largest(List.of(Circle.of(1), Rect.square(2)));\ndouble total = Geometry.totalArea(big, Circle.of(3));" + }, + { + "kind": "quote", + "children": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Measure twice, cut once." + } + ] + } + ] + }, + { + "kind": "heading", + "level": 2, + "children": [ + { + "kind": "text", + "text": "Edge cases" + } + ] + }, + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Text with an entity — a " + }, + { + "kind": "raw", + "html": "<sup>superscript</sup>", + "text": "superscript" + }, + { + "kind": "text", + "text": " kept as raw markup, a line" + }, + { + "kind": "break" + }, + { + "kind": "text", + "text": " break, a " + }, + { + "kind": "link", + "url": "https://example.com/spec", + "children": [ + { + "kind": "text", + "text": "hyperlink" + } + ] + }, + { + "kind": "text", + "text": ", and <angle brackets> as literal text." + } + ] + } + ], + "notes": [ + { + "kind": "implNote", + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Areas are computed in double precision." + } + ] + } + ] + } + ], + "see": [ + [ + { + "kind": "link", + "target": { + "id": "fixture.java.Shape" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "Shape" + } + ] + } + ], + [ + { + "kind": "link", + "target": { + "id": "fixture.java.Shape#area()" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "the area of a shape" + } + ] + } + ], + [ + { + "kind": "text", + "text": "\"Euclid, Elements, Book I\"" + } + ], + [ + { + "kind": "link", + "url": "https://en.wikipedia.org/wiki/Area", + "children": [ + { + "kind": "text", + "text": "Area" + } + ] + } + ] + ] + }, + "since": "1.0", + "nullMarked": true, + "source": { + "path": "fixture/java/Geometry.java", + "line": 68 + } + }, + { + "id": "fixture.java.Geometry$Legacy", + "name": "Geometry.Legacy", + "kind": "class", + "language": "java", + "modifiers": ["public", "static", "final"], + "annotations": [ + [{"kind":"annotation","text":"@NullUnmarked","ref":"org.jspecify.annotations.NullUnmarked","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/NullUnmarked.html"}] + ], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"final"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"class"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Geometry.Legacy"}], + "superclass": [{"kind":"type","text":"Object","ref":"java.lang.Object","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html"}], + "ancestors": [ + { + "id": "java.lang.Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + } + ], + "enclosing": "fixture.java.Geometry", + "members": [ + { + "id": "fixture.java.Geometry$Legacy#nameOf(fixture.java.Shape)", + "anchor": "nameOf(fixture.java.Shape)", + "kind": "method", + "name": "nameOf", + "modifiers": ["public", "static"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"name","text":"nameOf"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":" "}, {"kind":"param","text":"shape"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "shape", + "type": [{"kind":"type","text":"Shape","ref":"fixture.java.Shape"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "a shape, or " + }, + { + "kind": "code", + "text": "null" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "its name" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Returns the name, possibly " + }, + { + "kind": "code", + "text": "null" + }, + { + "kind": "text", + "text": "." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Returns the name, possibly " + }, + { + "kind": "code", + "text": "null" + }, + { + "kind": "text", + "text": "." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Geometry.java", + "line": 171 + } + } + ], + "inherited": [ + { + "from": { + "id": "java.lang.Object", + "text": "Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Object#equals(java.lang.Object)", + "text": "equals", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)" + }, + { + "id": "java.lang.Object#getClass()", + "text": "getClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass()" + }, + { + "id": "java.lang.Object#hashCode()", + "text": "hashCode", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode()" + }, + { + "id": "java.lang.Object#notify()", + "text": "notify", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify()" + }, + { + "id": "java.lang.Object#notifyAll()", + "text": "notifyAll", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll()" + }, + { + "id": "java.lang.Object#toString()", + "text": "toString", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString()" + }, + { + "id": "java.lang.Object#wait()", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait()" + }, + { + "id": "java.lang.Object#wait(long)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long)" + }, + { + "id": "java.lang.Object#wait(long,int)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long,int)" + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Methods from before null markings; their nullness is unspecified." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Methods from before null markings; their nullness is unspecified." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Geometry.java", + "line": 161 + } + }, + { + "id": "fixture.java.GeometryException", + "name": "GeometryException", + "kind": "class", + "language": "java", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"class"}, {"kind":"punct","text":" "}, {"kind":"name","text":"GeometryException"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"extends"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Exception","ref":"java.lang.Exception","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Exception.html"}], + "superclass": [{"kind":"type","text":"Exception","ref":"java.lang.Exception","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Exception.html"}], + "ancestors": [ + { + "id": "java.lang.Exception", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Exception.html" + }, + { + "id": "java.lang.Throwable", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html" + }, + { + "id": "java.lang.Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + } + ], + "members": [ + { + "id": "fixture.java.GeometryException#<init>(java.lang.String)", + "anchor": "<init>(java.lang.String)", + "kind": "constructor", + "name": "GeometryException", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"name","text":"GeometryException"}, {"kind":"punct","text":"("}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"message"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "message", + "type": [{"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "what was wrong" + } + ] + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Creates an exception." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Creates an exception." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/GeometryException.java", + "line": 25 + } + }, + { + "id": "fixture.java.GeometryException#<init>(java.lang.String,java.lang.Throwable)", + "anchor": "<init>(java.lang.String,java.lang.Throwable)", + "kind": "constructor", + "name": "GeometryException", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"name","text":"GeometryException"}, {"kind":"punct","text":"("}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"message"}, {"kind":"punct","text":", "}, {"kind":"type","text":"Throwable","ref":"java.lang.Throwable","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"cause"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "message", + "type": [{"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "what was wrong" + } + ] + } + ] + }, + { + "name": "cause", + "type": [{"kind":"type","text":"Throwable","ref":"java.lang.Throwable","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "what caused it" + } + ] + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Creates an exception with a cause." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Creates an exception with a cause." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/GeometryException.java", + "line": 35 + } + } + ], + "inherited": [ + { + "from": { + "id": "java.lang.Throwable", + "text": "Throwable", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Throwable#addSuppressed(java.lang.Throwable)", + "text": "addSuppressed", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#addSuppressed(java.lang.Throwable)" + }, + { + "id": "java.lang.Throwable#fillInStackTrace()", + "text": "fillInStackTrace", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#fillInStackTrace()" + }, + { + "id": "java.lang.Throwable#getCause()", + "text": "getCause", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#getCause()" + }, + { + "id": "java.lang.Throwable#getLocalizedMessage()", + "text": "getLocalizedMessage", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#getLocalizedMessage()" + }, + { + "id": "java.lang.Throwable#getMessage()", + "text": "getMessage", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#getMessage()" + }, + { + "id": "java.lang.Throwable#getStackTrace()", + "text": "getStackTrace", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#getStackTrace()" + }, + { + "id": "java.lang.Throwable#getSuppressed()", + "text": "getSuppressed", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#getSuppressed()" + }, + { + "id": "java.lang.Throwable#initCause(java.lang.Throwable)", + "text": "initCause", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#initCause(java.lang.Throwable)" + }, + { + "id": "java.lang.Throwable#printStackTrace()", + "text": "printStackTrace", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#printStackTrace()" + }, + { + "id": "java.lang.Throwable#printStackTrace(java.io.PrintStream)", + "text": "printStackTrace", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)" + }, + { + "id": "java.lang.Throwable#printStackTrace(java.io.PrintWriter)", + "text": "printStackTrace", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#printStackTrace(java.io.PrintWriter)" + }, + { + "id": "java.lang.Throwable#setStackTrace(java.lang.StackTraceElement[])", + "text": "setStackTrace", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#setStackTrace(java.lang.StackTraceElement[])" + }, + { + "id": "java.lang.Throwable#toString()", + "text": "toString", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#toString()" + } + ] + }, + { + "from": { + "id": "java.lang.Object", + "text": "Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Object#equals(java.lang.Object)", + "text": "equals", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)" + }, + { + "id": "java.lang.Object#getClass()", + "text": "getClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass()" + }, + { + "id": "java.lang.Object#hashCode()", + "text": "hashCode", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode()" + }, + { + "id": "java.lang.Object#notify()", + "text": "notify", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify()" + }, + { + "id": "java.lang.Object#notifyAll()", + "text": "notifyAll", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll()" + }, + { + "id": "java.lang.Object#wait()", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait()" + }, + { + "id": "java.lang.Object#wait(long)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long)" + }, + { + "id": "java.lang.Object#wait(long,int)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long,int)" + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "A shape that cannot exist, such as a triangle whose sides violate the triangle inequality." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "A shape that cannot exist, such as a triangle whose sides violate the triangle inequality." + } + ] + } + ] + }, + "since": "1.0", + "nullMarked": true, + "source": { + "path": "fixture/java/GeometryException.java", + "line": 16 + } + }, + { + "id": "fixture.java.Measured", + "name": "Measured", + "kind": "annotation", + "language": "java", + "modifiers": ["public"], + "annotations": [ + [{"kind":"annotation","text":"@Documented","ref":"java.lang.annotation.Documented","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/annotation/Documented.html"}], + [{"kind":"annotation","text":"@Retention","ref":"java.lang.annotation.Retention","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/annotation/Retention.html"}, {"kind":"punct","text":"("}, {"kind":"literal","text":"RUNTIME"}, {"kind":"punct","text":")"}], + [{"kind":"annotation","text":"@Target","ref":"java.lang.annotation.Target","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/annotation/Target.html"}, {"kind":"punct","text":"("}, {"kind":"literal","text":"{TYPE, METHOD}"}, {"kind":"punct","text":")"}] + ], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"@interface"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Measured"}], + "members": [ + { + "id": "fixture.java.Measured#unit()", + "anchor": "unit()", + "kind": "annotationElement", + "name": "unit", + "signature": [{"kind":"type","text":"Units","ref":"fixture.java.Units"}, {"kind":"punct","text":" "}, {"kind":"name","text":"unit"}, {"kind":"punct","text":"() "}, {"kind":"keyword","text":"default"}, {"kind":"punct","text":" "}, {"kind":"literal","text":"METERS"}], + "returns": { + "type": [{"kind":"type","text":"Units","ref":"fixture.java.Units"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the unit" + } + ] + } + ] + }, + "defaultValue": "METERS", + "doc": { + "summary": [ + { + "kind": "text", + "text": "The unit of the values." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The unit of the values." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Measured.java", + "line": 28 + } + }, + { + "id": "fixture.java.Measured#precision()", + "anchor": "precision()", + "kind": "annotationElement", + "name": "precision", + "signature": [{"kind":"keyword","text":"int"}, {"kind":"punct","text":" "}, {"kind":"name","text":"precision"}, {"kind":"punct","text":"() "}, {"kind":"keyword","text":"default"}, {"kind":"punct","text":" "}, {"kind":"literal","text":"3"}], + "returns": { + "type": [{"kind":"keyword","text":"int"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the number of digits" + } + ] + } + ] + }, + "defaultValue": "3", + "doc": { + "summary": [ + { + "kind": "text", + "text": "Significant digits." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Significant digits." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Measured.java", + "line": 35 + } + }, + { + "id": "fixture.java.Measured#tags()", + "anchor": "tags()", + "kind": "annotationElement", + "name": "tags", + "signature": [{"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":"[] "}, {"kind":"name","text":"tags"}, {"kind":"punct","text":"() "}, {"kind":"keyword","text":"default"}, {"kind":"punct","text":" "}, {"kind":"literal","text":"{}"}], + "returns": { + "type": [{"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":"[]"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the tags" + } + ] + } + ] + }, + "defaultValue": "{}", + "doc": { + "summary": [ + { + "kind": "text", + "text": "Free-form tags." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Free-form tags." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Measured.java", + "line": 42 + } + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Marks a declaration whose values are lengths, and in which unit." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Marks a declaration whose values are lengths, and in which unit." + } + ] + } + ] + }, + "since": "1.1", + "nullMarked": true, + "source": { + "path": "fixture/java/Measured.java", + "line": 19 + } + }, + { + "id": "fixture.java.Polygon", + "name": "Polygon", + "kind": "class", + "language": "java", + "modifiers": ["public", "non-sealed"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"non-sealed"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"class"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Polygon"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"implements"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}], + "superclass": [{"kind":"type","text":"Object","ref":"java.lang.Object","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html"}], + "interfaces": [ + [{"kind":"type","text":"Shape","ref":"fixture.java.Shape"}] + ], + "ancestors": [ + { + "id": "java.lang.Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + } + ], + "members": [ + { + "id": "fixture.java.Polygon#<init>(double...)", + "anchor": "<init>(double...)", + "kind": "constructor", + "name": "Polygon", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Polygon"}, {"kind":"punct","text":"("}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":"... "}, {"kind":"param","text":"sides"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "sides", + "type": [{"kind":"keyword","text":"double"}, {"kind":"punct","text":"..."}], + "varargs": true, + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "each side's length in meters; at least three" + } + ] + } + ] + } + ], + "throws": [ + { + "type": [{"kind":"type","text":"IllegalArgumentException","ref":"java.lang.IllegalArgumentException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "if there are fewer than three sides" + } + ] + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Creates a polygon from its sides." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Creates a polygon from its sides." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Polygon.java", + "line": 25 + } + }, + { + "id": "fixture.java.Polygon#area()", + "anchor": "area()", + "kind": "method", + "name": "area", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"name","text":"area"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the area in square meters" + } + ] + } + ] + }, + "overrides": { + "id": "fixture.java.Shape#area()" + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "The area of a regular polygon with these sides' mean length." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The area of a regular polygon with these sides' mean length." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Polygon.java", + "line": 46 + } + }, + { + "id": "fixture.java.Polygon#accept(fixture.java.Shape.Visitor)", + "anchor": "accept(fixture.java.Shape.Visitor)", + "kind": "method", + "name": "accept", + "modifiers": ["public"], + "typeParams": [ + { + "name": "R", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the visitor's result type" + } + ] + } + ] + } + ], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" <"}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":"> "}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":" "}, {"kind":"name","text":"accept"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Shape.Visitor","ref":"fixture.java.Shape$Visitor"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":"> "}, {"kind":"param","text":"visitor"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "visitor", + "type": [{"kind":"type","text":"Shape.Visitor","ref":"fixture.java.Shape$Visitor"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":">"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the visitor" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"typeParam","text":"R"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "what the visitor returned" + } + ] + } + ] + }, + "overrides": { + "id": "fixture.java.Shape#accept(fixture.java.Shape.Visitor)" + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Calls the visitor's method for this shape's kind." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Calls the visitor's method for this shape's kind." + } + ] + } + ], + "inheritedFrom": { + "id": "fixture.java.Shape#accept(fixture.java.Shape.Visitor)" + } + }, + "source": { + "path": "fixture/java/Polygon.java", + "line": 55 + } + } + ], + "inherited": [ + { + "from": { + "id": "java.lang.Object", + "text": "Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Object#equals(java.lang.Object)", + "text": "equals", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)" + }, + { + "id": "java.lang.Object#getClass()", + "text": "getClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass()" + }, + { + "id": "java.lang.Object#hashCode()", + "text": "hashCode", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode()" + }, + { + "id": "java.lang.Object#notify()", + "text": "notify", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify()" + }, + { + "id": "java.lang.Object#notifyAll()", + "text": "notifyAll", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll()" + }, + { + "id": "java.lang.Object#toString()", + "text": "toString", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString()" + }, + { + "id": "java.lang.Object#wait()", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait()" + }, + { + "id": "java.lang.Object#wait(long)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long)" + }, + { + "id": "java.lang.Object#wait(long,int)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long,int)" + } + ] + }, + { + "from": { + "id": "fixture.java.Shape", + "text": "Shape" + }, + "kind": "interface", + "members": [ + { + "id": "fixture.java.Shape#compareTo(fixture.java.Shape)", + "text": "compareTo" + }, + { + "id": "fixture.java.Shape#name()", + "text": "name" + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "A regular polygon." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "A regular polygon. Not sealed: applications may extend it." + } + ] + } + ] + }, + "since": "1.0", + "nullMarked": true, + "source": { + "path": "fixture/java/Polygon.java", + "line": 16 + } + }, + { + "id": "fixture.java.Polygon$Builder", + "name": "Polygon.Builder", + "kind": "class", + "language": "java", + "modifiers": ["public", "static", "final"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"final"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"class"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Polygon.Builder"}], + "superclass": [{"kind":"type","text":"Object","ref":"java.lang.Object","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html"}], + "ancestors": [ + { + "id": "java.lang.Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + } + ], + "enclosing": "fixture.java.Polygon", + "members": [ + { + "id": "fixture.java.Polygon$Builder#<init>()", + "anchor": "<init>()", + "kind": "constructor", + "name": "Builder", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Builder"}, {"kind":"punct","text":"()"}], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Creates an empty builder." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Creates an empty builder." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Polygon.java", + "line": 65 + } + }, + { + "id": "fixture.java.Polygon$Builder#side(double)", + "anchor": "side(double)", + "kind": "method", + "name": "side", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Polygon.Builder","ref":"fixture.java.Polygon$Builder"}, {"kind":"punct","text":" "}, {"kind":"name","text":"side"}, {"kind":"punct","text":"("}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"param","text":"length"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "length", + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the side's length in meters" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"type","text":"Polygon.Builder","ref":"fixture.java.Polygon$Builder"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "this builder" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Adds a side." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Adds a side." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Polygon.java", + "line": 73 + } + }, + { + "id": "fixture.java.Polygon$Builder#build()", + "anchor": "build()", + "kind": "method", + "name": "build", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Polygon","ref":"fixture.java.Polygon"}, {"kind":"punct","text":" "}, {"kind":"name","text":"build"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"type","text":"Polygon","ref":"fixture.java.Polygon"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the polygon" + } + ] + } + ] + }, + "throws": [ + { + "type": [{"kind":"type","text":"IllegalArgumentException","ref":"java.lang.IllegalArgumentException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "if fewer than three sides were added" + } + ] + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Builds the polygon." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Builds the polygon." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Polygon.java", + "line": 84 + } + } + ], + "inherited": [ + { + "from": { + "id": "java.lang.Object", + "text": "Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Object#equals(java.lang.Object)", + "text": "equals", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)" + }, + { + "id": "java.lang.Object#getClass()", + "text": "getClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass()" + }, + { + "id": "java.lang.Object#hashCode()", + "text": "hashCode", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode()" + }, + { + "id": "java.lang.Object#notify()", + "text": "notify", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify()" + }, + { + "id": "java.lang.Object#notifyAll()", + "text": "notifyAll", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll()" + }, + { + "id": "java.lang.Object#toString()", + "text": "toString", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString()" + }, + { + "id": "java.lang.Object#wait()", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait()" + }, + { + "id": "java.lang.Object#wait(long)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long)" + }, + { + "id": "java.lang.Object#wait(long,int)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long,int)" + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Builds a polygon one side at a time." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Builds a polygon one side at a time." + } + ] + } + ] + }, + "nullMarked": true, + "source": { + "path": "fixture/java/Polygon.java", + "line": 61 + } + }, + { + "id": "fixture.java.Polygon$Edge", + "name": "Polygon.Edge", + "kind": "class", + "language": "java", + "modifiers": ["public", "final"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"final"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"class"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Polygon.Edge"}], + "superclass": [{"kind":"type","text":"Object","ref":"java.lang.Object","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html"}], + "ancestors": [ + { + "id": "java.lang.Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + } + ], + "enclosing": "fixture.java.Polygon", + "members": [ + { + "id": "fixture.java.Polygon$Edge#<init>(int)", + "anchor": "<init>(int)", + "kind": "constructor", + "name": "Edge", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Edge"}, {"kind":"punct","text":"("}, {"kind":"keyword","text":"int"}, {"kind":"punct","text":" "}, {"kind":"param","text":"index"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "index", + "type": [{"kind":"keyword","text":"int"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the edge's index, from zero" + } + ] + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Selects an edge." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Selects an edge." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Polygon.java", + "line": 100 + } + }, + { + "id": "fixture.java.Polygon$Edge#length()", + "anchor": "length()", + "kind": "method", + "name": "length", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"name","text":"length"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the length in meters" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "The edge's length." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The edge's length." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Polygon.java", + "line": 109 + } + } + ], + "inherited": [ + { + "from": { + "id": "java.lang.Object", + "text": "Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Object#equals(java.lang.Object)", + "text": "equals", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)" + }, + { + "id": "java.lang.Object#getClass()", + "text": "getClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass()" + }, + { + "id": "java.lang.Object#hashCode()", + "text": "hashCode", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode()" + }, + { + "id": "java.lang.Object#notify()", + "text": "notify", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify()" + }, + { + "id": "java.lang.Object#notifyAll()", + "text": "notifyAll", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll()" + }, + { + "id": "java.lang.Object#toString()", + "text": "toString", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString()" + }, + { + "id": "java.lang.Object#wait()", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait()" + }, + { + "id": "java.lang.Object#wait(long)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long)" + }, + { + "id": "java.lang.Object#wait(long,int)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long,int)" + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "One edge of this polygon: an inner class, bound to its polygon." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "One edge of this polygon: an inner class, bound to its polygon." + } + ] + } + ] + }, + "nullMarked": true, + "source": { + "path": "fixture/java/Polygon.java", + "line": 92 + } + }, + { + "id": "fixture.java.Rect", + "name": "Rect", + "kind": "class", + "language": "java", + "modifiers": ["public", "final"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"final"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"class"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Rect"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"implements"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}], + "superclass": [{"kind":"type","text":"Object","ref":"java.lang.Object","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html"}], + "interfaces": [ + [{"kind":"type","text":"Shape","ref":"fixture.java.Shape"}] + ], + "ancestors": [ + { + "id": "java.lang.Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + } + ], + "members": [ + { + "id": "fixture.java.Rect#width", + "anchor": "width", + "kind": "field", + "name": "width", + "modifiers": ["public", "final"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"final"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"name","text":"width"}], + "type": [{"kind":"keyword","text":"double"}], + "doc": { + "summary": [ + { + "kind": "text", + "text": "The width in meters." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The width in meters." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Rect.java", + "line": 15 + } + }, + { + "id": "fixture.java.Rect#height", + "anchor": "height", + "kind": "field", + "name": "height", + "modifiers": ["public", "final"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"final"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"name","text":"height"}], + "type": [{"kind":"keyword","text":"double"}], + "doc": { + "summary": [ + { + "kind": "text", + "text": "The height in meters." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The height in meters." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Rect.java", + "line": 18 + } + }, + { + "id": "fixture.java.Rect#<init>(double,double)", + "anchor": "<init>(double,double)", + "kind": "constructor", + "name": "Rect", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Rect"}, {"kind":"punct","text":"("}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"param","text":"width"}, {"kind":"punct","text":", "}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"param","text":"height"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "width", + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the width in meters" + } + ] + } + ] + }, + { + "name": "height", + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the height in meters" + } + ] + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Creates a rectangle." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Creates a rectangle." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Rect.java", + "line": 26 + } + }, + { + "id": "fixture.java.Rect#square(double)", + "anchor": "square(double)", + "kind": "method", + "name": "square", + "modifiers": ["public", "static"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Rect","ref":"fixture.java.Rect"}, {"kind":"punct","text":" "}, {"kind":"name","text":"square"}, {"kind":"punct","text":"("}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"param","text":"side"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "side", + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the side's length in meters" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"type","text":"Rect","ref":"fixture.java.Rect"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "a rectangle whose sides are all " + }, + { + "kind": "code", + "text": "side" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Creates a square." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Creates a square." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Rect.java", + "line": 37 + } + }, + { + "id": "fixture.java.Rect#area()", + "anchor": "area()", + "kind": "method", + "name": "area", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"name","text":"area"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the area in square meters, never negative" + } + ] + } + ] + }, + "overrides": { + "id": "fixture.java.Shape#area()" + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "The shape's area." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The shape's area." + } + ] + } + ], + "inheritedFrom": { + "id": "fixture.java.Shape#area()" + } + }, + "source": { + "path": "fixture/java/Rect.java", + "line": 41 + } + }, + { + "id": "fixture.java.Rect#accept(fixture.java.Shape.Visitor)", + "anchor": "accept(fixture.java.Shape.Visitor)", + "kind": "method", + "name": "accept", + "modifiers": ["public"], + "typeParams": [ + { + "name": "R" + } + ], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" <"}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":"> "}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":" "}, {"kind":"name","text":"accept"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Shape.Visitor","ref":"fixture.java.Shape$Visitor"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":"> "}, {"kind":"param","text":"visitor"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "visitor", + "type": [{"kind":"type","text":"Shape.Visitor","ref":"fixture.java.Shape$Visitor"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":">"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the visitor" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"typeParam","text":"R"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "what the visitor returned; for a rectangle, what " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Shape$Visitor#visitRect(fixture.java.Rect)" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "Visitor.visitRect(Rect)" + } + ] + }, + { + "kind": "text", + "text": " returned" + } + ] + } + ] + }, + "overrides": { + "id": "fixture.java.Shape#accept(fixture.java.Shape.Visitor)" + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Calls the visitor's method for this shape's kind." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Calls the visitor's method for this shape's kind." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Rect.java", + "line": 53 + } + } + ], + "inherited": [ + { + "from": { + "id": "java.lang.Object", + "text": "Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Object#equals(java.lang.Object)", + "text": "equals", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)" + }, + { + "id": "java.lang.Object#getClass()", + "text": "getClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass()" + }, + { + "id": "java.lang.Object#hashCode()", + "text": "hashCode", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode()" + }, + { + "id": "java.lang.Object#notify()", + "text": "notify", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify()" + }, + { + "id": "java.lang.Object#notifyAll()", + "text": "notifyAll", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll()" + }, + { + "id": "java.lang.Object#toString()", + "text": "toString", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString()" + }, + { + "id": "java.lang.Object#wait()", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait()" + }, + { + "id": "java.lang.Object#wait(long)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long)" + }, + { + "id": "java.lang.Object#wait(long,int)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long,int)" + } + ] + }, + { + "from": { + "id": "fixture.java.Shape", + "text": "Shape" + }, + "kind": "interface", + "members": [ + { + "id": "fixture.java.Shape#compareTo(fixture.java.Shape)", + "text": "compareTo" + }, + { + "id": "fixture.java.Shape#name()", + "text": "name" + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "An axis-aligned rectangle." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "An axis-aligned rectangle." + } + ] + } + ] + }, + "since": "1.0", + "nullMarked": true, + "source": { + "path": "fixture/java/Rect.java", + "line": 13 + } + }, + { + "id": "fixture.java.Shape", + "name": "Shape", + "kind": "interface", + "language": "java", + "modifiers": ["public", "sealed"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"sealed"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"interface"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Shape"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"extends"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Comparable","ref":"java.lang.Comparable","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Comparable.html"}, {"kind":"punct","text":"<"}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":"> "}, {"kind":"keyword","text":"permits"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Circle","ref":"fixture.java.Circle"}, {"kind":"punct","text":", "}, {"kind":"type","text":"Rect","ref":"fixture.java.Rect"}, {"kind":"punct","text":", "}, {"kind":"type","text":"Polygon","ref":"fixture.java.Polygon"}], + "interfaces": [ + [{"kind":"type","text":"Comparable","ref":"java.lang.Comparable","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Comparable.html"}, {"kind":"punct","text":"<"}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":">"}] + ], + "permits": [ + { + "id": "fixture.java.Circle" + }, + { + "id": "fixture.java.Rect" + }, + { + "id": "fixture.java.Polygon" + } + ], + "members": [ + { + "id": "fixture.java.Shape#area()", + "anchor": "area()", + "kind": "method", + "name": "area", + "signature": [{"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"name","text":"area"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the area in square meters, never negative" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "The shape's area." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The shape's area." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Shape.java", + "line": 26 + } + }, + { + "id": "fixture.java.Shape#compareTo(fixture.java.Shape)", + "anchor": "compareTo(fixture.java.Shape)", + "kind": "method", + "name": "compareTo", + "modifiers": ["default"], + "signature": [{"kind":"keyword","text":"default"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"int"}, {"kind":"punct","text":" "}, {"kind":"name","text":"compareTo"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":" "}, {"kind":"param","text":"other"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "other", + "type": [{"kind":"type","text":"Shape","ref":"fixture.java.Shape"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shape to compare with" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"keyword","text":"int"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "a negative number, zero or a positive number as this shape's area is smaller than, equal to or larger than " + }, + { + "kind": "code", + "text": "other" + }, + { + "kind": "text", + "text": "'s" + } + ] + } + ] + }, + "overrides": { + "id": "java.lang.Comparable#compareTo(T)", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Comparable.html#compareTo(T)" + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Compares shapes by area." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Compares shapes by area." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Shape.java", + "line": 35 + } + }, + { + "id": "fixture.java.Shape#name()", + "anchor": "name()", + "kind": "method", + "name": "name", + "modifiers": ["default"], + "signature": [{"kind":"keyword","text":"default"}, {"kind":"punct","text":" "}, {"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"name","text":"name"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"annotation","text":"@Nullable","ref":"org.jspecify.annotations.Nullable","url":"https://jspecify.dev/docs/api/org/jspecify/annotations/Nullable.html"}, {"kind":"punct","text":" "}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "nullness": "nullable", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shape's name, or " + }, + { + "kind": "code", + "text": "null" + }, + { + "kind": "text", + "text": " for an anonymous shape" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Returns the shape's name, or " + }, + { + "kind": "code", + "text": "null" + }, + { + "kind": "text", + "text": " for an anonymous shape." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Returns the shape's name, or " + }, + { + "kind": "code", + "text": "null" + }, + { + "kind": "text", + "text": " for an anonymous shape." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Shape.java", + "line": 41 + } + }, + { + "id": "fixture.java.Shape#accept(fixture.java.Shape.Visitor)", + "anchor": "accept(fixture.java.Shape.Visitor)", + "kind": "method", + "name": "accept", + "typeParams": [ + { + "name": "R", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the visitor's result type" + } + ] + } + ] + } + ], + "signature": [{"kind":"punct","text":"<"}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":"> "}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":" "}, {"kind":"name","text":"accept"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Shape.Visitor","ref":"fixture.java.Shape$Visitor"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":"> "}, {"kind":"param","text":"visitor"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "visitor", + "type": [{"kind":"type","text":"Shape.Visitor","ref":"fixture.java.Shape$Visitor"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":">"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the visitor" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"typeParam","text":"R"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "what the visitor returned" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Calls the visitor's method for this shape's kind." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Calls the visitor's method for this shape's kind." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Shape.java", + "line": 52 + } + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "A closed plane figure." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "A closed plane figure." + } + ] + }, + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Every shape reports its " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Shape#area()" + }, + "children": [ + { + "kind": "text", + "text": "area" + } + ] + }, + { + "kind": "text", + "text": " in square " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Units#METERS" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "meters" + } + ] + }, + { + "kind": "text", + "text": "." + } + ] + } + ], + "notes": [ + { + "kind": "apiNote", + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "The hierarchy is sealed: only " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Circle" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "Circle" + } + ] + }, + { + "kind": "text", + "text": ", " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Rect" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "Rect" + } + ] + }, + { + "kind": "text", + "text": " and " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Polygon" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "Polygon" + } + ] + }, + { + "kind": "text", + "text": " implement it." + } + ] + } + ] + } + ] + }, + "since": "1.0", + "nullMarked": true, + "source": { + "path": "fixture/java/Shape.java", + "line": 20 + } + }, + { + "id": "fixture.java.Shape$Visitor", + "name": "Shape.Visitor", + "kind": "interface", + "language": "java", + "modifiers": ["public"], + "typeParams": [ + { + "name": "R", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the result type" + } + ] + } + ] + } + ], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"interface"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Shape.Visitor"}, {"kind":"punct","text":"<"}, {"kind":"typeParam","text":"R"}, {"kind":"punct","text":">"}], + "enclosing": "fixture.java.Shape", + "members": [ + { + "id": "fixture.java.Shape$Visitor#visitCircle(fixture.java.Circle)", + "anchor": "visitCircle(fixture.java.Circle)", + "kind": "method", + "name": "visitCircle", + "signature": [{"kind":"typeParam","text":"R"}, {"kind":"punct","text":" "}, {"kind":"name","text":"visitCircle"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Circle","ref":"fixture.java.Circle"}, {"kind":"punct","text":" "}, {"kind":"param","text":"circle"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "circle", + "type": [{"kind":"type","text":"Circle","ref":"fixture.java.Circle"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the circle" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"typeParam","text":"R"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the result" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Visits a circle." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Visits a circle." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Shape.java", + "line": 66 + } + }, + { + "id": "fixture.java.Shape$Visitor#visitRect(fixture.java.Rect)", + "anchor": "visitRect(fixture.java.Rect)", + "kind": "method", + "name": "visitRect", + "signature": [{"kind":"typeParam","text":"R"}, {"kind":"punct","text":" "}, {"kind":"name","text":"visitRect"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Rect","ref":"fixture.java.Rect"}, {"kind":"punct","text":" "}, {"kind":"param","text":"rect"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "rect", + "type": [{"kind":"type","text":"Rect","ref":"fixture.java.Rect"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the rectangle" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"typeParam","text":"R"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the result" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Visits a rectangle." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Visits a rectangle." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Shape.java", + "line": 74 + } + }, + { + "id": "fixture.java.Shape$Visitor#visitPolygon(fixture.java.Polygon)", + "anchor": "visitPolygon(fixture.java.Polygon)", + "kind": "method", + "name": "visitPolygon", + "signature": [{"kind":"typeParam","text":"R"}, {"kind":"punct","text":" "}, {"kind":"name","text":"visitPolygon"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Polygon","ref":"fixture.java.Polygon"}, {"kind":"punct","text":" "}, {"kind":"param","text":"polygon"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "polygon", + "type": [{"kind":"type","text":"Polygon","ref":"fixture.java.Polygon"}], + "nullness": "nonNull", + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the polygon" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"typeParam","text":"R"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the result" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Visits a polygon." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Visits a polygon." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Shape.java", + "line": 82 + } + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Operations over each kind of shape." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Operations over each kind of shape." + } + ] + } + ] + }, + "nullMarked": true, + "source": { + "path": "fixture/java/Shape.java", + "line": 59 + } + }, + { + "id": "fixture.java.Units", + "name": "Units", + "kind": "enum", + "language": "java", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"enum"}, {"kind":"punct","text":" "}, {"kind":"name","text":"Units"}], + "superclass": [{"kind":"type","text":"Enum","ref":"java.lang.Enum","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html"}, {"kind":"punct","text":"<"}, {"kind":"type","text":"Units","ref":"fixture.java.Units"}, {"kind":"punct","text":">"}], + "ancestors": [ + { + "id": "java.lang.Enum", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html" + }, + { + "id": "java.lang.Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + } + ], + "members": [ + { + "id": "fixture.java.Units#values()", + "anchor": "values()", + "kind": "method", + "name": "values", + "modifiers": ["public", "static"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Units","ref":"fixture.java.Units"}, {"kind":"punct","text":"[] "}, {"kind":"name","text":"values"}, {"kind":"punct","text":"()"}], + "returns": { + "type": [{"kind":"type","text":"Units","ref":"fixture.java.Units"}, {"kind":"punct","text":"[]"}], + "nullness": "nonNull" + } + }, + { + "id": "fixture.java.Units#valueOf(java.lang.String)", + "anchor": "valueOf(java.lang.String)", + "kind": "method", + "name": "valueOf", + "modifiers": ["public", "static"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"type","text":"Units","ref":"fixture.java.Units"}, {"kind":"punct","text":" "}, {"kind":"name","text":"valueOf"}, {"kind":"punct","text":"("}, {"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"name"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "name", + "type": [{"kind":"type","text":"String","ref":"java.lang.String","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html"}], + "nullness": "nonNull" + } + ], + "returns": { + "type": [{"kind":"type","text":"Units","ref":"fixture.java.Units"}], + "nullness": "nonNull" + } + }, + { + "id": "fixture.java.Units#METERS", + "anchor": "METERS", + "kind": "enumConstant", + "name": "METERS", + "signature": [{"kind":"name","text":"METERS"}], + "type": [{"kind":"type","text":"Units","ref":"fixture.java.Units"}], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Meters: the base unit." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Meters: the base unit." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Units.java", + "line": 15 + } + }, + { + "id": "fixture.java.Units#FEET", + "anchor": "FEET", + "kind": "enumConstant", + "name": "FEET", + "annotations": [ + [{"kind":"annotation","text":"@Deprecated","ref":"java.lang.Deprecated","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Deprecated.html"}, {"kind":"punct","text":"("}, {"kind":"param","text":"since"}, {"kind":"punct","text":" = "}, {"kind":"literal","text":"\"1.2\""}, {"kind":"punct","text":")"}] + ], + "signature": [{"kind":"name","text":"FEET"}], + "type": [{"kind":"type","text":"Units","ref":"fixture.java.Units"}], + "doc": { + "summary": [ + { + "kind": "text", + "text": "International feet." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "International feet." + } + ] + } + ] + }, + "deprecated": { + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Use " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Units#METERS" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "METERS" + } + ] + }, + { + "kind": "text", + "text": "; mixing units causes rounding errors." + } + ] + } + ], + "since": "1.2" + }, + "source": { + "path": "fixture/java/Units.java", + "line": 21 + } + }, + { + "id": "fixture.java.Units#toMeters(double)", + "anchor": "toMeters(double)", + "kind": "method", + "name": "toMeters", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"name","text":"toMeters"}, {"kind":"punct","text":"("}, {"kind":"keyword","text":"double"}, {"kind":"punct","text":" "}, {"kind":"param","text":"value"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "value", + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "a length in this unit" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"keyword","text":"double"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the length in meters" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Converts a length in this unit to meters." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Converts a length in this unit to meters." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/Units.java", + "line": 36 + } + } + ], + "inherited": [ + { + "from": { + "id": "java.lang.Enum", + "text": "Enum", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Enum#compareTo(E)", + "text": "compareTo", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#compareTo(E)" + }, + { + "id": "java.lang.Enum#describeConstable()", + "text": "describeConstable", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#describeConstable()" + }, + { + "id": "java.lang.Enum#equals(java.lang.Object)", + "text": "equals", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#equals(java.lang.Object)" + }, + { + "id": "java.lang.Enum#getDeclaringClass()", + "text": "getDeclaringClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#getDeclaringClass()" + }, + { + "id": "java.lang.Enum#hashCode()", + "text": "hashCode", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#hashCode()" + }, + { + "id": "java.lang.Enum#name()", + "text": "name", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#name()" + }, + { + "id": "java.lang.Enum#ordinal()", + "text": "ordinal", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#ordinal()" + }, + { + "id": "java.lang.Enum#toString()", + "text": "toString", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#toString()" + }, + { + "id": "java.lang.Enum#valueOf(java.lang.Class,java.lang.String)", + "text": "valueOf", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#valueOf(java.lang.Class,java.lang.String)" + } + ] + }, + { + "from": { + "id": "java.lang.Object", + "text": "Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Object#getClass()", + "text": "getClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass()" + }, + { + "id": "java.lang.Object#notify()", + "text": "notify", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify()" + }, + { + "id": "java.lang.Object#notifyAll()", + "text": "notifyAll", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll()" + }, + { + "id": "java.lang.Object#wait()", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait()" + }, + { + "id": "java.lang.Object#wait(long)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long)" + }, + { + "id": "java.lang.Object#wait(long,int)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long,int)" + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Units of length." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Units of length." + } + ] + } + ] + }, + "since": "1.0", + "nullMarked": true, + "source": { + "path": "fixture/java/Units.java", + "line": 13 + } + } + ] + }, + { + "id": "fixture.java.io", + "name": "fixture.java.io", + "doc": { + "summary": [ + { + "kind": "text", + "text": "Reading shapes from streams." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Reading shapes from streams. Not null-marked: nullness here is unspecified unless annotated." + } + ] + } + ] + }, + "since": "1.0", + "types": [ + { + "id": "fixture.java.io.ShapeReader", + "name": "ShapeReader", + "kind": "class", + "language": "java", + "modifiers": ["public", "final"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"final"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"class"}, {"kind":"punct","text":" "}, {"kind":"name","text":"ShapeReader"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"implements"}, {"kind":"punct","text":" "}, {"kind":"type","text":"AutoCloseable","ref":"java.lang.AutoCloseable","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html"}], + "superclass": [{"kind":"type","text":"Object","ref":"java.lang.Object","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html"}], + "interfaces": [ + [{"kind":"type","text":"AutoCloseable","ref":"java.lang.AutoCloseable","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html"}] + ], + "ancestors": [ + { + "id": "java.lang.Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + } + ], + "members": [ + { + "id": "fixture.java.io.ShapeReader#read(java.io.InputStream)", + "anchor": "read(java.io.InputStream)", + "kind": "method", + "name": "read", + "modifiers": ["public", "static"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"type","text":"List","ref":"java.util.List","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html"}, {"kind":"punct","text":"<"}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":"> "}, {"kind":"name","text":"read"}, {"kind":"punct","text":"("}, {"kind":"type","text":"InputStream","ref":"java.io.InputStream","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/InputStream.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"in"}, {"kind":"punct","text":") "}, {"kind":"keyword","text":"throws"}, {"kind":"punct","text":" "}, {"kind":"type","text":"IOException","ref":"java.io.IOException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html"}, {"kind":"punct","text":", "}, {"kind":"type","text":"GeometryException","ref":"fixture.java.GeometryException"}], + "params": [ + { + "name": "in", + "type": [{"kind":"type","text":"InputStream","ref":"java.io.InputStream","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/InputStream.html"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the stream; not closed" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"type","text":"List","ref":"java.util.List","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html"}, {"kind":"punct","text":"<"}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":">"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shapes, in order" + } + ] + } + ] + }, + "throws": [ + { + "type": [{"kind":"type","text":"IOException","ref":"java.io.IOException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html"}], + "declared": true, + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "if reading fails" + } + ] + } + ] + }, + { + "type": [{"kind":"type","text":"GeometryException","ref":"fixture.java.GeometryException"}], + "declared": true, + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "if a line describes an impossible shape" + } + ] + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Reads every shape from a stream of UTF-8 text." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Reads every shape from a stream of UTF-8 text." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/io/ShapeReader.java", + "line": 40 + } + }, + { + "id": "fixture.java.io.ShapeReader#read(java.io.Reader,java.nio.charset.Charset)", + "anchor": "read(java.io.Reader,java.nio.charset.Charset)", + "kind": "method", + "name": "read", + "modifiers": ["public", "static"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"type","text":"List","ref":"java.util.List","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html"}, {"kind":"punct","text":"<"}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":"> "}, {"kind":"name","text":"read"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Reader","ref":"java.io.Reader","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/Reader.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"reader"}, {"kind":"punct","text":", "}, {"kind":"type","text":"Charset","ref":"java.nio.charset.Charset","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/charset/Charset.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"charset"}, {"kind":"punct","text":") "}, {"kind":"keyword","text":"throws"}, {"kind":"punct","text":" "}, {"kind":"type","text":"IOException","ref":"java.io.IOException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html"}, {"kind":"punct","text":", "}, {"kind":"type","text":"GeometryException","ref":"fixture.java.GeometryException"}], + "params": [ + { + "name": "reader", + "type": [{"kind":"type","text":"Reader","ref":"java.io.Reader","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/Reader.html"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the reader; not closed" + } + ] + } + ] + }, + { + "name": "charset", + "type": [{"kind":"type","text":"Charset","ref":"java.nio.charset.Charset","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/charset/Charset.html"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the charset the text was decoded from, for error messages" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"type","text":"List","ref":"java.util.List","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html"}, {"kind":"punct","text":"<"}, {"kind":"type","text":"Shape","ref":"fixture.java.Shape"}, {"kind":"punct","text":">"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shapes, in order" + } + ] + } + ] + }, + "throws": [ + { + "type": [{"kind":"type","text":"IOException","ref":"java.io.IOException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html"}], + "declared": true, + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "if reading fails" + } + ] + } + ] + }, + { + "type": [{"kind":"type","text":"GeometryException","ref":"fixture.java.GeometryException"}], + "declared": true, + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "if a line describes an impossible shape" + } + ] + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Reads every shape from a reader." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Reads every shape from a reader." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/io/ShapeReader.java", + "line": 53 + } + }, + { + "id": "fixture.java.io.ShapeReader#open(java.io.Reader)", + "anchor": "open(java.io.Reader)", + "kind": "method", + "name": "open", + "modifiers": ["public", "static"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"static"}, {"kind":"punct","text":" "}, {"kind":"type","text":"ShapeReader","ref":"fixture.java.io.ShapeReader"}, {"kind":"punct","text":" "}, {"kind":"name","text":"open"}, {"kind":"punct","text":"("}, {"kind":"type","text":"Reader","ref":"java.io.Reader","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/Reader.html"}, {"kind":"punct","text":" "}, {"kind":"param","text":"reader"}, {"kind":"punct","text":")"}], + "params": [ + { + "name": "reader", + "type": [{"kind":"type","text":"Reader","ref":"java.io.Reader","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/Reader.html"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the reader to read from" + } + ] + } + ] + } + ], + "returns": { + "type": [{"kind":"type","text":"ShapeReader","ref":"fixture.java.io.ShapeReader"}], + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "the shape reader; close it to close " + }, + { + "kind": "code", + "text": "reader" + } + ] + } + ] + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Opens a reader." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Opens a reader." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/io/ShapeReader.java", + "line": 63 + } + }, + { + "id": "fixture.java.io.ShapeReader#close()", + "anchor": "close()", + "kind": "method", + "name": "close", + "modifiers": ["public"], + "signature": [{"kind":"keyword","text":"public"}, {"kind":"punct","text":" "}, {"kind":"keyword","text":"void"}, {"kind":"punct","text":" "}, {"kind":"name","text":"close"}, {"kind":"punct","text":"() "}, {"kind":"keyword","text":"throws"}, {"kind":"punct","text":" "}, {"kind":"type","text":"IOException","ref":"java.io.IOException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html"}], + "throws": [ + { + "type": [{"kind":"type","text":"IOException","ref":"java.io.IOException","url":"https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html"}], + "declared": true, + "doc": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "if closing the reader fails" + } + ] + } + ] + } + ], + "overrides": { + "id": "java.lang.AutoCloseable#close()", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html#close()" + }, + "doc": { + "summary": [ + { + "kind": "text", + "text": "Closes the underlying reader." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Closes the underlying reader." + } + ] + } + ] + }, + "source": { + "path": "fixture/java/io/ShapeReader.java", + "line": 72 + } + } + ], + "inherited": [ + { + "from": { + "id": "java.lang.Object", + "text": "Object", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html" + }, + "kind": "class", + "members": [ + { + "id": "java.lang.Object#equals(java.lang.Object)", + "text": "equals", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)" + }, + { + "id": "java.lang.Object#getClass()", + "text": "getClass", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass()" + }, + { + "id": "java.lang.Object#hashCode()", + "text": "hashCode", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode()" + }, + { + "id": "java.lang.Object#notify()", + "text": "notify", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify()" + }, + { + "id": "java.lang.Object#notifyAll()", + "text": "notifyAll", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll()" + }, + { + "id": "java.lang.Object#toString()", + "text": "toString", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString()" + }, + { + "id": "java.lang.Object#wait()", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait()" + }, + { + "id": "java.lang.Object#wait(long)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long)" + }, + { + "id": "java.lang.Object#wait(long,int)", + "text": "wait", + "url": "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait(long,int)" + } + ] + } + ], + "doc": { + "summary": [ + { + "kind": "text", + "text": "Reads shapes in their " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Geometry#parse(java.lang.String)" + }, + "children": [ + { + "kind": "text", + "text": "text form" + } + ] + }, + { + "kind": "text", + "text": ", one per line." + } + ], + "body": [ + { + "kind": "paragraph", + "children": [ + { + "kind": "text", + "text": "Reads shapes in their " + }, + { + "kind": "link", + "target": { + "id": "fixture.java.Geometry#parse(java.lang.String)" + }, + "children": [ + { + "kind": "text", + "text": "text form" + } + ] + }, + { + "kind": "text", + "text": ", one per line." + } + ] + } + ], + "see": [ + [ + { + "kind": "link", + "target": { + "id": "fixture.java.Geometry#parse(java.lang.String)" + }, + "code": true, + "children": [ + { + "kind": "text", + "text": "Geometry.parse(String)" + } + ] + } + ] + ] + }, + "since": "1.0", + "source": { + "path": "fixture/java/io/ShapeReader.java", + "line": 25 + } + } + ] + } + ] +} diff --git a/packages/apidocs/test/fixtures/guides-errors/bad-yaml.md b/packages/apidocs/test/fixtures/guides-errors/bad-yaml.md new file mode 100644 index 0000000..ecc68a6 --- /dev/null +++ b/packages/apidocs/test/fixtures/guides-errors/bad-yaml.md @@ -0,0 +1,6 @@ +--- +title: [unclosed +description: x +--- + +Text. diff --git a/packages/apidocs/test/fixtures/guides-errors/diagram.png b/packages/apidocs/test/fixtures/guides-errors/diagram.png new file mode 100644 index 0000000..b205525 Binary files /dev/null and b/packages/apidocs/test/fixtures/guides-errors/diagram.png differ diff --git a/packages/apidocs/test/fixtures/guides-errors/draft.md b/packages/apidocs/test/fixtures/guides-errors/draft.md new file mode 100644 index 0000000..a8e4dfb --- /dev/null +++ b/packages/apidocs/test/fixtures/guides-errors/draft.md @@ -0,0 +1,7 @@ +--- +title: Not written yet +description: A draft. +draft: true +--- + +This page is not written yet. diff --git a/packages/apidocs/test/fixtures/guides-errors/getting-started.md b/packages/apidocs/test/fixtures/guides-errors/getting-started.md new file mode 100644 index 0000000..d54816a --- /dev/null +++ b/packages/apidocs/test/fixtures/guides-errors/getting-started.md @@ -0,0 +1,8 @@ +--- +title: Getting started +description: A page with a heading. +--- + +## Install + +Install it. diff --git a/packages/apidocs/test/fixtures/guides-errors/index.md b/packages/apidocs/test/fixtures/guides-errors/index.md new file mode 100644 index 0000000..09e94bb --- /dev/null +++ b/packages/apidocs/test/fixtures/guides-errors/index.md @@ -0,0 +1,24 @@ +--- +title: Broken suite +description: Every diagnostic the importer reports, one per line. +template: splash +sidebar: + order: 0 + badge: New +--- + +A link to [a missing page](missing.md). + +A link to [a missing heading](getting-started.md#nope). + +A link [outside the suite](../../outside.md). + +A link to [a draft](draft.md). + +A link to [an MDX page](page.mdx). + +An image without alternative text: ![](diagram.png) + +A note.[^1] + +[^1]: The footnote. diff --git a/packages/apidocs/test/fixtures/guides-errors/no-frontmatter.md b/packages/apidocs/test/fixtures/guides-errors/no-frontmatter.md new file mode 100644 index 0000000..d1997dd --- /dev/null +++ b/packages/apidocs/test/fixtures/guides-errors/no-frontmatter.md @@ -0,0 +1,3 @@ +## A page with no frontmatter + +Text. diff --git a/packages/apidocs/test/fixtures/guides-errors/page.mdx b/packages/apidocs/test/fixtures/guides-errors/page.mdx new file mode 100644 index 0000000..07f7856 --- /dev/null +++ b/packages/apidocs/test/fixtures/guides-errors/page.mdx @@ -0,0 +1,8 @@ +--- +title: An MDX page +description: MDX is not supported. +--- + +import Thing from "./thing.astro"; + +<Thing /> diff --git a/packages/apidocs/test/guides-browser.test.ts b/packages/apidocs/test/guides-browser.test.ts new file mode 100644 index 0000000..d22d941 --- /dev/null +++ b/packages/apidocs/test/guides-browser.test.ts @@ -0,0 +1,118 @@ +/** + * A guides-only site in Chromium: the Markdown sample suite built with the CLI (`apidocs guides`), opened from + * file:// with JavaScript on and off, and axe on its pages in light and dark. Needs `bun run build` first and a + * Playwright Chromium (PLAYWRIGHT_BROWSERS_PATH). + */ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { type Browser, type BrowserContextOptions, chromium, type Page } from "playwright"; + +const root = fileURLToPath(new URL("..", import.meta.url)); +const require = createRequire(import.meta.url); +let browser: Browser; +let site: string; +let out: string; + +beforeAll(async () => { + if (!existsSync(join(root, "dist/assets/apidocs.js"))) throw new Error("dist/ is missing: run `bun run build` first"); + site = mkdtempSync(join(tmpdir(), "apidocs-guides-browser-")); + out = join(site, "out"); + // The Elide preset, as Komodo uses it. + writeFileSync(join(site, "theme.json"), JSON.stringify({ extends: "elide" })); + const run = spawnSync(process.execPath, [ + join(root, "src/cli.ts"), "guides", "--src", join(root, "samples/guides"), "--id", "geo", "--title", "Geo user guide", "--out", out, + "--version", "2.1.0", "--theme", join(site, "theme.json"), "--assets", join(root, "dist/assets"), "--link", "../developer/=https://example.com/developer/", "--link", "../api/=https://example.com/api/", + ], { encoding: "utf8" }); + if (run.status !== 0) throw new Error(run.stderr); + browser = await chromium.launch(); +}); + +afterAll(async () => { + await browser?.close(); + if (site) rmSync(site, { recursive: true, force: true }); +}); + +async function open(path: string, options: BrowserContextOptions = {}): Promise<{ page: Page; requests: string[]; errors: string[] }> { + const context = await browser.newContext({ colorScheme: "light", ...options }); + const page = await context.newPage(); + const requests: string[] = []; + const errors: string[] = []; + page.on("request", request => requests.push(request.url())); + page.on("pageerror", error => errors.push(error.message)); + page.on("console", message => message.type() === "error" && errors.push(message.text())); + const [file, fragment] = path.split("#"); + await page.goto(pathToFileURL(join(out, file!)).href + (fragment === undefined ? "" : `#${fragment}`)); + return { page, requests, errors }; +} + +describe("a guides-only site from file://", () => { + test("with JavaScript off, pages are complete and script-only controls stay out", async () => { + const { page, requests } = await open("guides/concepts/alerts.html", { javaScriptEnabled: false }); + expect(await page.getByRole("heading", { level: 1 }).textContent()).toBe("Callouts"); + expect(await page.locator(".callout").count()).toBe(5); + expect(await page.getByRole("navigation", { name: "Guides" }).locator(".nav-row").count()).toBe(7); + expect(await page.locator(".nav-packages").count()).toBe(0); + for (const control of await page.locator("[data-js-only]").all()) expect(await control.isVisible()).toBe(false); + expect(requests.every(r => r.startsWith("file://"))).toBe(true); + await page.context().close(); + }); + + test("images load with their size reserved", async () => { + const { page, errors } = await open("guides/concepts/images.html"); + const images = page.locator(".prose img"); + expect(await images.count()).toBe(2); + for (const image of await images.all()) { + await image.scrollIntoViewIfNeeded(); + await page.waitForFunction(i => (i as HTMLImageElement).complete, await image.elementHandle()); + expect(await image.evaluate(i => (i as HTMLImageElement).naturalWidth)).toBeGreaterThan(0); + expect(await image.getAttribute("width")).not.toBeNull(); + } + expect(errors).toEqual([]); + await page.context().close(); + }); + + test("with JavaScript on, search finds a section and opens it, with no errors and no network", async () => { + const { page, requests, errors } = await open("index.html"); + const input = page.getByRole("combobox", { name: "Search the guides" }); + await input.fill("before you"); + const first = page.locator("#apidocs-results [role=option]").first(); + await first.waitFor(); + expect(await first.textContent()).toContain("Before you start"); + await input.press("Enter"); + await page.waitForURL(/alerts\.html#before-you-start/); + expect(requests.every(r => r.startsWith("file://"))).toBe(true); + expect(errors).toEqual([]); + await page.context().close(); + }); + + test("previous and next follow reading order across groups", async () => { + const { page } = await open("guides/concepts/images.html", { javaScriptEnabled: false }); + await page.locator("a.guide-next").click(); + await page.waitForURL(/concepts\/advanced\/index\.html$/); + expect(await page.getByRole("heading", { level: 1 }).textContent()).toBe("Advanced topics"); + await page.context().close(); + }); +}); + +describe("accessibility of a guides-only site", () => { + for (const colorScheme of ["light", "dark"] as const) { + for (const path of ["index.html", "guides/getting-started.html", "guides/concepts/alerts.html", "guides/concepts/images.html"]) { + test(`${path} in ${colorScheme} has no axe violations`, async () => { + const { page } = await open(path, { colorScheme }); + await page.addScriptTag({ path: require.resolve("axe-core/axe.min.js") }); + const violations = await page.evaluate(async () => { + const result = await (window as unknown as { axe: { run: (o: object) => Promise<{ violations: { id: string; nodes: { target: string[] }[] }[] }> } }) + .axe.run({ runOnly: { type: "tag", values: ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "best-practice"] } }); + return result.violations.map(v => `${v.id}: ${v.nodes.slice(0, 3).map(n => n.target.join(" ")).join(", ")}`); + }); + expect(violations).toEqual([]); + await page.context().close(); + }, 30_000); + } + } +}); diff --git a/packages/apidocs/test/import.test.ts b/packages/apidocs/test/import.test.ts new file mode 100644 index 0000000..ff0419d --- /dev/null +++ b/packages/apidocs/test/import.test.ts @@ -0,0 +1,523 @@ +/** The Markdown importer: each construct, the diagnostics, hostile input, guides-only sites, the CLI and Komodo's suites. */ +import { describe, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { readSuite } from "../src/import/files"; +import { imageSize } from "../src/import/images"; +import { sanitizeSvg } from "../src/import/svg"; +import { formatDiagnostic, guidesModel, importMarkdown, type ImportOptions, mapLink } from "../src/import/markdown"; +import { suiteSite } from "../src/import/suite"; +import type { Block, Guide, Inline, Model } from "../src/model"; +import { type Output, render } from "../src/render"; +import { checkSite } from "./check"; +import { validate } from "./validate"; + +const root = fileURLToPath(new URL("..", import.meta.url)); +const SAMPLE = join(root, "samples/guides"); +const ERRORS = join(root, "test/fixtures/guides-errors"); +const SAMPLE_LINKS = [{ prefix: "../developer/", target: "https://example.com/developer/" }, { prefix: "../api/", target: "https://example.com/api/" }]; + +/** A page with frontmatter. */ +const page = (title: string, body: string, extra = "") => `---\ntitle: ${title}\ndescription: About ${title}.\n${extra}---\n\n${body}\n`; +const imp = (files: Record<string, string>, options: ImportOptions = {}) => + importMarkdown(Object.entries(files).map(([path, text]) => ({ path, text })), options); +/** The body of the one non-overview guide, or of the guide at a path. */ +const bodyOf = (markdown: string, options: ImportOptions = {}): Block[] => { + const result = imp({ "index.md": page("Home", "Home."), "a.md": page("A", markdown) }, options); + return result.guides.find(g => g.slug === "a")!.body ?? []; +}; +const first = (blocks: Block[]) => blocks[0]!; +const inl = (markdown: string): Inline[] => (first(bodyOf(markdown)) as { children: Inline[] }).children; + +describe("frontmatter", () => { + test("title, description, sidebar.label and sidebar.order", () => { + const result = imp({ + "index.md": page("Home", "x", "sidebar:\n label: Start\n order: 0\n"), + "b.md": page("B page", "x", "sidebar:\n order: 1\n"), + "a.md": page("A page", "x", "sidebar:\n order: 2\n label: A\n"), + }); + expect(result.diagnostics).toEqual([]); + expect(result.guides.map(g => [g.slug, g.title, g.navTitle, g.summary])).toEqual([ + ["index", "Home", "Start", [{ kind: "text", text: "About Home." }]], + ["b", "B page", undefined, [{ kind: "text", text: "About B page." }]], + ["a", "A page", "A", [{ kind: "text", text: "About A page." }]], + ]); + }); + test("drafts are left out unless included", () => { + const files = { "index.md": page("Home", "x"), "d.md": page("D", "x", "draft: true\n") }; + expect(imp(files).guides.map(g => g.slug)).toEqual(["index"]); + expect(imp(files).drafts).toEqual(["d.md"]); + expect(imp(files, { includeDrafts: true }).guides.map(g => g.slug)).toEqual(["index", "d"]); + }); + test("an unknown key is an error naming the file and the key, unless accepted", () => { + const files = { "index.md": page("Home", "x", "template: splash\nsidebar:\n badge: New\n") }; + expect(imp(files).diagnostics.map(d => formatDiagnostic(d))).toEqual([ + 'index.md:4: unknown frontmatter key "template"; the importer reads title, description, sidebar.label, sidebar.order and draft', + 'index.md:6: unknown frontmatter key "sidebar.badge"; the importer reads sidebar.label and sidebar.order', + ]); + expect(imp(files, { extraKeys: ["template", "sidebar.badge"] }).diagnostics).toEqual([]); + }); + test("bad values and a missing title are errors; a missing description is a warning", () => { + const result = imp({ "index.md": "---\nsidebar:\n order: first\ndraft: maybe\n---\n\nx\n" }); + expect(result.diagnostics.map(d => `${d.severity} ${d.line} ${d.message}`)).toEqual([ + "error 3 sidebar.order must be a number", + "error 4 draft must be true or false", + "error 1 the frontmatter has no title", + "warning 1 the frontmatter has no description, which listings, search and llms.txt show", + ]); + }); +}); + +describe("structure", () => { + const files = { + "index.md": page("Suite", "x", "sidebar:\n label: Overview\n"), + "zeta.md": page("Zeta", "x"), + "alpha.md": page("Alpha", "x"), + "usage/index.md": page("Using it", "x", "sidebar:\n order: 2\n"), + "usage/running.md": page("Running", "x", "sidebar:\n order: 1\n"), + "usage/advanced/index.md": page("Advanced", "x"), + "usage/advanced/tuning.md": page("Tuning", "x"), + "start/index.md": page("Start here", "x", "sidebar:\n order: 1\n"), + "start/install.md": page("Install", "x"), + }; + const result = imp(files, { suite: "user", sourceRoot: "docs/user/" }); + test("the root index is the overview; directories are groups in their index's order, nested ones named Parent › Child", () => { + expect(result.overview).toBe("guide:user/index"); + expect(result.guides.map(g => [g.slug, g.group ?? ""])).toEqual([ + ["index", ""], ["alpha", ""], ["zeta", ""], + ["start/index", "Start here"], ["start/install", "Start here"], + ["usage/index", "Using it"], ["usage/running", "Using it"], + ["usage/advanced/index", "Using it › Advanced"], ["usage/advanced/tuning", "Using it › Advanced"], + ]); + }); + test("stable ids from paths, Overview as an index's navigator label, source paths", () => { + const usage = result.guides.find(g => g.slug === "usage/index")!; + expect(usage.id).toBe("guide:user/usage/index"); + expect(usage.navTitle).toBe("Overview"); + expect(usage.source).toEqual({ path: "docs/user/usage/index.md", line: 1 }); + }); + test("the model validates and renders nested pages", () => { + const model = guidesModel(result, { name: "Suite", version: "1.0" }); + expect(validate(model)).toEqual([]); + const out = render(model); + expect(Object.keys(out)).toContain("guides/usage/advanced/tuning.html"); + expect(out["guides/usage/index.html"]).toBeDefined(); + expect(checkSite(out, { allowed: [] })).toEqual([]); + }); + test("a directory without an index is a group named after it, with a warning", () => { + const r = imp({ "index.md": page("Home", "x"), "how-to/x.md": page("X", "x") }); + expect(r.guides[1]!.group).toBe("How to"); + expect(r.diagnostics.map(d => formatDiagnostic(d))).toEqual(['how-to/:1: warning: the directory has no index.md to introduce it and name its group; the group is named "How to"']); + }); +}); + +describe("Markdown", () => { + test("headings: levels, explicit {#id}, and anchors the renderer generates", () => { + const body = bodyOf("## Install it {#setup}\n\n### Then *this*\n\n#### Deep"); + expect(body).toEqual([ + { kind: "heading", level: 2, children: [{ kind: "text", text: "Install it" }], anchor: "setup" }, + { kind: "heading", level: 3, children: [{ kind: "text", text: "Then " }, { kind: "emphasis", children: [{ kind: "text", text: "this" }] }] }, + { kind: "heading", level: 4, children: [{ kind: "text", text: "Deep" }] }, + ]); + }); + test("HTML comments, the sync block among them, do not render", () => { + expect(bodyOf("<!-- sync\ndocs/handbook/usage.md\n-->\n\nText <!-- hidden --> here.")).toEqual([ + { kind: "paragraph", children: [{ kind: "text", text: "Text " }, { kind: "text", text: " here." }] }, + ]); + }); + test("inline: emphasis, strong, strikethrough, code, hard break, autolinks", () => { + expect(inl("*a* **b** ~~c~~ `d` \ne https://example.com <mailto:x@example.com>")).toEqual([ + { kind: "emphasis", children: [{ kind: "text", text: "a" }] }, { kind: "text", text: " " }, + { kind: "strong", children: [{ kind: "text", text: "b" }] }, { kind: "text", text: " " }, + { kind: "strikethrough", children: [{ kind: "text", text: "c" }] }, { kind: "text", text: " " }, + { kind: "code", text: "d" }, { kind: "break" }, { kind: "text", text: "e " }, + { kind: "link", children: [{ kind: "text", text: "https://example.com" }], url: "https://example.com" }, { kind: "text", text: " " }, + { kind: "link", children: [{ kind: "text", text: "mailto:x@example.com" }], url: "mailto:x@example.com" }, + ]); + }); + test("lists, ordered lists and task lists", () => { + expect(bodyOf("- a\n- b\n\n1. one\n2. two\n\n- [x] done\n- [ ] open")).toEqual([ + { kind: "list", items: [[{ kind: "paragraph", children: [{ kind: "text", text: "a" }] }], [{ kind: "paragraph", children: [{ kind: "text", text: "b" }] }]] }, + { kind: "list", ordered: true, items: [[{ kind: "paragraph", children: [{ kind: "text", text: "one" }] }], [{ kind: "paragraph", children: [{ kind: "text", text: "two" }] }]] }, + { kind: "list", items: [ + [{ kind: "paragraph", children: [{ kind: "check", checked: true }, { kind: "text", text: "done" }] }], + [{ kind: "paragraph", children: [{ kind: "check" }, { kind: "text", text: "open" }] }], + ] }, + ]); + }); + test("fenced code keeps its language; a fence without one is text", () => { + expect(bodyOf("```Kotlin\nfun main() {}\n```\n\n```\nplain\n```")).toEqual([ + { kind: "code", language: "kotlin", text: "fun main() {}" }, + { kind: "code", language: "text", text: "plain" }, + ]); + }); + test("tables: the first row is the head", () => { + expect(bodyOf("| A | B |\n| --- | :-: |\n| `x` | |")).toEqual([{ + kind: "table", + head: [[[{ kind: "paragraph", children: [{ kind: "text", text: "A" }] }], [{ kind: "paragraph", children: [{ kind: "text", text: "B" }] }]]], + rows: [[[{ kind: "paragraph", children: [{ kind: "code", text: "x" }] }], []]], + }]); + }); + test("each GitHub alert is an admonition; another quote stays a quote", () => { + const body = bodyOf(["NOTE", "TIP", "IMPORTANT", "WARNING", "CAUTION"].map(t => `> [!${t}]\n> About ${t}.`).join("\n\n") + "\n\n> [!note]\n>\n> Lower case, own paragraph.\n\n> Just a quote."); + expect(body.map(b => (b.kind === "admonition" ? b.tone : b.kind))).toEqual(["note", "tip", "important", "warning", "caution", "note", "quote"]); + expect(body[1]).toEqual({ kind: "admonition", tone: "tip", children: [{ kind: "paragraph", children: [{ kind: "text", text: "About TIP." }] }] }); + expect(body[5]).toEqual({ kind: "admonition", tone: "note", children: [{ kind: "paragraph", children: [{ kind: "text", text: "Lower case, own paragraph." }] }] }); + }); + test("raw HTML: a block is a raw node; an inline element is one raw node with its content; a rule is <hr>", () => { + expect(bodyOf("<dl><dt>A</dt><dd>B</dd></dl>\n\nPress <kbd>Ctrl</kbd>+C and <br> go.\n\n---")).toEqual([ + { kind: "raw", html: "<dl><dt>A</dt><dd>B</dd></dl>", text: "AB" }, + { kind: "paragraph", children: [ + { kind: "text", text: "Press " }, { kind: "raw", html: "<kbd>Ctrl</kbd>", text: "Ctrl" }, { kind: "text", text: "+C and " }, + { kind: "raw", html: "<br>", text: "" }, { kind: "text", text: " go." }, + ] }, + { kind: "raw", html: "<hr>", text: "---" }, + ]); + }); + test("footnotes are reported, not rendered", () => { + const result = imp({ "index.md": page("Home", "A note.[^1]\n\n[^1]: The note.") }); + expect(result.diagnostics.map(d => formatDiagnostic(d))).toEqual([ + "index.md:6: footnotes are not supported; put the note in the text or in a callout", + "index.md:8: footnotes are not supported; put the note in the text or in a callout", + ]); + }); +}); + +describe("links", () => { + const files = { + "index.md": page("Home", "## Intro\n\n[same](#intro) [up](usage/index.md) [dir](usage/) [section](usage/run.md#Running-a-file) [by id](usage/run.md#flags) [file](usage/chart.png)"), + "usage/index.md": page("Usage", "[home](../index.md#intro) [sibling suite](../../developer/embedding/index.md#setup) [api](../../api/latest/index.html) [web](https://example.com/x?y#z)"), + "usage/run.md": page("Run", "## Running a file\n\n## Options {#flags}"), + }; + const result = imp(files, { suite: "s", assets: [{ path: "usage/chart.png", data: new TextEncoder().encode("png") }], links: [{ prefix: "../developer/", target: "../developer/" }, { prefix: "../api/", target: "https://example.com/api/" }] }); + const links = (slug: string) => (result.guides.find(g => g.slug === slug)!.body!.find(b => b.kind === "paragraph") as { children: Inline[] }).children.filter(n => n.kind === "link"); + test("Markdown files become guide references, fragments become sections, checked at import", () => { + expect(result.diagnostics).toEqual([]); + expect(links("index").map(l => (l.kind === "link" ? l.target ?? l.url : undefined))).toEqual([ + { id: "guide:s/index", section: "intro" }, + { id: "guide:s/usage/index" }, + { id: "guide:s/usage/index" }, + { id: "guide:s/usage/run", section: "running-a-file" }, + { id: "guide:s/usage/run", section: "flags" }, + "guides/usage/chart.png", + ]); + expect(result.files.map(f => [f.from, f.to])).toEqual([["usage/chart.png", "guides/usage/chart.png"]]); + }); + test("links that leave the suite go through the mapping, relative to their page", () => { + expect(links("usage/index").map(l => (l.kind === "link" ? l.target ?? l.url : undefined))).toEqual([ + { id: "guide:s/index", section: "intro" }, + "../../../developer/guides/embedding/index.html#setup", + "https://example.com/api/latest/index.html", + "https://example.com/x?y#z", + ]); + expect(mapLink("../developer/index.md", undefined, [{ prefix: "../developer/", target: "../developer/" }])).toBe("../developer/index.html"); + expect(mapLink("../developer/", undefined, [{ prefix: "../developer/", target: "https://e.com/dev" }])).toBe("https://e.com/dev/index.html"); + }); + test("the rendered links resolve", () => { + const out = render(guidesModel(result, { name: "S" })); + expect(out["index.html"] as string).toContain('href="guides/usage/run.html#running-a-file"'); + expect(out["index.html"] as string).toContain('href="index.html#intro"'); + expect(out["guides/usage/index.html"] as string).toContain('href="../../../developer/guides/embedding/index.html#setup"'); + expect(out["guides/usage/index.md"] as string).toContain("(../../index.md#intro)"); + }); +}); + +describe("images", () => { + const png = Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, 0, 0, 1, 0x2c, 0, 0, 0, 0x96, 8, 2, 0, 0, 0]); + test("a suite image is copied, sized and linked from the site root", () => { + const result = imp({ "index.md": page("Home", "x"), "a/index.md": page("A", "x"), "a/b.md": page("B", '![A chart of sales](img/chart.png "Sales")') }, { assets: [{ path: "a/img/chart.png", data: png }] }); + expect(result.diagnostics).toEqual([]); + expect(inlOf(result.guides[2]!)).toEqual([{ kind: "image", src: "guides/a/img/chart.png", alt: "A chart of sales", title: "Sales", width: 300, height: 150 }]); + expect(result.files).toEqual([{ from: "a/img/chart.png", to: "guides/a/img/chart.png", data: png }]); + const out = render(guidesModel(result, { name: "S" })); + expect(out["guides/a/b.html"] as string).toContain('<img src="../../guides/a/img/chart.png" alt="A chart of sales" title="Sales" width="300" height="150" loading="lazy" decoding="async"/>'); + expect(out["guides/a/b.md"] as string).toContain("![A chart of sales](../../guides/a/img/chart.png)"); + expect(checkSite({ ...out, "guides/a/img/chart.png": "" }, { allowed: [] })).toEqual([]); + }); + test("an image needs alternative text and an existing file", () => { + const result = imp({ "index.md": page("Home", "![](a.png) ![Shown](missing.png)") }, { assets: [{ path: "a.png", data: png }] }); + expect(result.diagnostics.map(d => formatDiagnostic(d))).toEqual([ + "index.md:6: the image a.png has no alternative text; describe it in the brackets: ![what it shows](a.png)", + "index.md:6: the image missing.png is not in the suite", + ]); + }); + test("sizes from PNG, GIF, JPEG, WebP and SVG headers", () => { + expect(imageSize(png)).toEqual({ width: 300, height: 150 }); + expect(imageSize(Uint8Array.from([0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 10, 0, 20, 0]))).toEqual({ width: 10, height: 20 }); + expect(imageSize(Uint8Array.from([0xff, 0xd8, 0xff, 0xe0, 0, 4, 0, 0, 0xff, 0xc0, 0, 17, 8, 0, 40, 0, 30, 3, 0, 0, 0]))).toEqual({ width: 30, height: 40 }); + const webp = new Uint8Array(30); + webp.set(new TextEncoder().encode("RIFF"), 0); + webp.set(new TextEncoder().encode("WEBPVP8X"), 8); + webp.set([99, 0, 0, 49, 0, 0], 24); + expect(imageSize(webp)).toEqual({ width: 100, height: 50 }); + expect(imageSize(new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 80">'))).toEqual({ width: 120, height: 80 }); + expect(imageSize(new TextEncoder().encode('<svg width="100%" height="2em">'))).toBeUndefined(); + expect(imageSize(new TextEncoder().encode("not an image"))).toBeUndefined(); + }); +}); + +function inlOf(guide: Guide): Inline[] { + return (guide.body![0] as { children: Inline[] }).children; +} + +describe("copied files", () => { + const bytes = (text: string) => new TextEncoder().encode(text); + const png = Uint8Array.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, 0, 0, 0, 8, 0, 0, 0, 8]); + test("only images are copied; every other type is an error and stays out of the output", () => { + const rejected = ["page.html", "page.HTM", "page.xhtml", "page.shtml", "feed.xml", "archive.mht", "notes.txt", "data.json", "report.pdf", "app.js", + "shot.html.png", "shot.png.", "shot.png ", "README"]; + const body = rejected.map((name, i) => `[f${i}](${encodeURI(name)})`).join("\n\n") + "\n\n![A photo](photo.PNG) ![A sketch](sketch.svg)"; + const result = imp({ "index.md": page("Home", body) }, { + assets: [...rejected.map(path => ({ path, data: bytes("<script>alert(1)</script>") })), { path: "photo.PNG", data: png }, + { path: "sketch.svg", data: bytes('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><circle cx="5" cy="5" r="4"/></svg>') }], + }); + const messages = result.diagnostics.map(d => formatDiagnostic(d)); + expect(messages.length).toBe(rejected.length); + for (const [i, name] of rejected.entries()) expect(messages[i]).toStartWith(`index.md:${6 + 2 * i}: ${name} is not copied into the site: `); + expect(messages.filter(m => m.endsWith("second, document-like extension"))).toEqual(["index.md:26: shot.html.png is not copied into the site: its name has a second, document-like extension"]); + expect(messages.filter(m => m.endsWith("a dot or a space")).length).toBe(2); + expect(result.files.map(f => f.to)).toEqual(["guides/photo.PNG", "guides/sketch.svg"]); + const out = render(guidesModel(result, { name: "S" })); + for (const name of rejected) expect(Object.keys(out).some(k => k.includes(name.trim()))).toBe(false); + expect(out["index.html"] as string).toContain('<img src="guides/photo.PNG" alt="A photo" width="8" height="8"'); + expect(out["index.html"] as string).toContain('<img src="guides/sketch.svg" alt="A sketch" width="10" height="10"'); + }); + test("a hostile SVG comes out inert; one that cannot be made safe is refused", () => { + const hostile = [ + '<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 10 10" onload="alert(1)">', + "<script>alert(2)</script><script xlink:href=\"https://evil.example/x.js\"/>", + '<foreignObject><div xmlns="http://www.w3.org/1999/xhtml"><img src="x" onerror="alert(3)"/><iframe src="javascript:alert(4)"></iframe></div></foreignObject>', + '<use href="https://evil.example/s.svg#a"/><use xlink:href="data:image/svg+xml,<svg onload=alert(5)>"/><use href="#ok"/>', + '<a href="javascript:alert(6)"><text>click</text></a><image href="https://evil.example/t.png"/>', + '<style>@import url(https://evil.example/x.css); rect { fill: url(https://evil.example/p) }</style>', + '<rect width="10" height="10" fill="url(https://evil.example/p)" stroke="url(#g)" style="background:url(//evil.example)" onclick="alert(7)"/>', + '<set attributeName="onmouseover" to="alert(8)"/><animate attributeName="href" to="javascript:alert(9)"/>', + "</svg>", + ].join(""); + const result = imp({ "index.md": page("Home", "![Hostile](h.svg) ![Entities](e.svg)") }, { + assets: [{ path: "h.svg", data: bytes(hostile) }, { path: "e.svg", data: bytes('<!DOCTYPE svg [<!ENTITY a "<script>">]><svg xmlns="http://www.w3.org/2000/svg">&a;</svg>') }], + }); + expect(result.diagnostics.map(d => formatDiagnostic(d))).toEqual([ + "index.md:6: e.svg is not copied into the site: the SVG cannot be made safe, because it has a DOCTYPE or CDATA section, which can declare entities or hide markup", + ]); + const svg = new TextDecoder().decode(result.files.find(f => f.from === "h.svg")!.data); + expect(svg).toBe('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 10 10"><use/><use/><use href="#ok"/><rect width="10" height="10" stroke="url(#g)"/></svg>\n'); + expect(svg).not.toMatch(/script|foreignObject|onload|onclick|onerror|javascript:|data:|evil|<a\b|<image|<style|<set|<animate/i); + expect(result.files.some(f => f.from === "e.svg")).toBe(false); + }); + test("a symbolic link is never followed, so a file outside the suite cannot be copied", () => { + const dir = mkdtempSync(join(tmpdir(), "apidocs-symlink-")); + try { + mkdirSync(join(dir, "suite")); + writeFileSync(join(dir, "secret.png"), png); + symlinkSync(join(dir, "secret.png"), join(dir, "suite/leak.png")); + symlinkSync(dir, join(dir, "suite/up")); + writeFileSync(join(dir, "suite/index.md"), page("Home", "![Leak](leak.png) ![Up](up/secret.png)")); + const { files, assets } = readSuite(join(dir, "suite")); + expect(assets).toEqual([]); + const result = importMarkdown(files, { assets }); + expect(result.files).toEqual([]); + expect(result.diagnostics.map(d => d.message)).toEqual(["the image leak.png is not in the suite", "the image up/secret.png is not in the suite"]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + test("CSS escapes, control characters and anything but url(#id) refuse a presentation value", () => { + const value = (attr: string, v: string) => { + const result = sanitizeSvg(`<svg xmlns="http://www.w3.org/2000/svg"><rect ${attr}="${v}"/></svg>`); + if (!result.ok) throw new Error(result.reason); + return /<rect( [^>]*)?\/>/.exec(result.svg)![1] ?? ""; + }; + const refused: [string, string][] = [ + ["fill", "\\75 rl(https://evil.example/p)"], ["fill", "\\75rl(https://evil.example/p)"], ["fill", "\\u rl(https://evil.example/p)"], + ["fill", "u\\rl(https://evil.example/p)"], ["fill", "\\6a avascript:alert(1)"], ["fill", "\\j avascript:alert(1)"], + ["fill", "\\65 xpression(alert(1))"], ["fill", "e\\xpression(alert(1))"], ["stroke", "\\75 \\72 \\6c (#g)"], + ["fill", "url(https://evil.example/p)"], ["fill", "url(#g) url(#h)"], ["fill", "url(#g), red"], ["fill", "URL( data:x )"], + ["fill", "expression(alert(1))"], ["fill", "red;@import x"], ["fill", "javascript:alert(1)"], ["fill", "vbscript:x"], + ["fill", "data:image/svg+xml,x"], ["fill", "red\u0000"], ["fill", "url(#g\u0000)"], ["fill", "red"], ["fill", "re d"], ["mask", "url(#m)x"], + ]; + for (const [attr, v] of refused) expect([attr, v, value(attr, v)]).toEqual([attr, v, ""]); + expect(value("fill", "url(#gradient)")).toBe(' fill="url(#gradient)"'); + expect(value("fill", " url( '#paint-1' ) ")).toBe(' fill=" url( \'#paint-1\' ) "'); + expect(value("d", "M 0 0\n L 10 10")).toBe(' d="M 0 0 L 10 10"'); + expect(value("id", "has\\backslash")).toBe(' id="has\\backslash"'); + expect(value("style", "fill:red")).toBe(""); + // A null character written as a reference is not XML at all: the file is refused. + expect(sanitizeSvg('<svg xmlns="http://www.w3.org/2000/svg"><rect fill="red�"/></svg>').ok).toBe(false); + }); + test("an ordinary diagram keeps its drawing", () => { + const { files, assets } = readSuite(SAMPLE); + const result = importMarkdown(files, { assets, links: SAMPLE_LINKS }); + const svg = new TextDecoder().decode(result.files.find(f => f.from === "concepts/diagram.svg")!.data); + for (const part of ['viewBox="0 0 240 240"', "<rect ", "<circle ", "<line ", '<text x="160" y="112"', ">r</text>", 'aria-label="A circle inside a square"']) expect(svg).toContain(part); + expect(result.files.find(f => f.from === "concepts/swatch.png")!.data).toEqual(assets.find(a => a.path === "concepts/swatch.png")!.data); + }); +}); + +describe("diagnostics", () => { + test("the broken fixture reports each problem with its file and line", () => { + const { files, assets } = readSuite(ERRORS); + const result = importMarkdown(files, { assets }); + expect(result.diagnostics.map(d => formatDiagnostic(d))).toEqual([ + "bad-yaml.md:3: the frontmatter is not valid YAML: Flow sequence in block collection must be sufficiently indented and end with a ]", + 'index.md:4: unknown frontmatter key "template"; the importer reads title, description, sidebar.label, sidebar.order and draft', + 'index.md:7: unknown frontmatter key "sidebar.badge"; the importer reads sidebar.label and sidebar.order', + "no-frontmatter.md:1: the page has no frontmatter: start it with ---, a title and a description, then ---", + "page.mdx:1: MDX is not supported: write the page as Markdown (.md)", + "index.md:20: the image diagram.png has no alternative text; describe it in the brackets: ![what it shows](diagram.png)", + "index.md:22: footnotes are not supported; put the note in the text or in a callout", + "index.md:24: footnotes are not supported; put the note in the text or in a callout", + "index.md:10: links to missing.md, which is not in the suite", + "index.md:12: links to #nope in getting-started.md, which has no such heading", + "index.md:14: links outside the suite to ../../outside.md; add a link mapping for it, or use an absolute URL", + "index.md:16: warning: links to draft.md, a draft this build leaves out; the link shows as text", + "index.md:18: links to page.mdx, an MDX page, which is not supported", + ]); + }); + test("the CLI prints them, exits 1 and writes nothing; --warn-only writes the site", () => { + const out = mkdtempSync(join(tmpdir(), "apidocs-guides-")); + try { + const failed = spawnSync(process.execPath, [join(root, "src/cli.ts"), "guides", "--src", ERRORS, "--id", "e", "--title", "E", "--out", join(out, "a")], { encoding: "utf8" }); + expect(failed.status).toBe(1); + expect(failed.stderr).toContain(`${ERRORS}/index.md:10: links to missing.md, which is not in the suite`); + expect(existsSync(join(out, "a"))).toBe(false); + const warned = spawnSync(process.execPath, [join(root, "src/cli.ts"), "guides", "--src", ERRORS, "--id", "e", "--title", "E", "--out", join(out, "b"), "--warn-only"], { encoding: "utf8" }); + expect(warned.status).toBe(0); + expect(warned.stderr).toContain(`${ERRORS}/index.md:10: warning: links to missing.md`); + expect(existsSync(join(out, "b/index.html"))).toBe(true); + const usage = spawnSync(process.execPath, [join(root, "src/cli.ts"), "guides", "--src", ERRORS], { encoding: "utf8" }); + expect(usage.status).toBe(2); + expect(usage.stderr).toContain("missing --id"); + } finally { + rmSync(out, { recursive: true, force: true }); + } + }, 60_000); +}); + +describe("hostile Markdown", () => { + const evil = imp({ + "index.md": [ + "---", + `title: '<img src=x onerror="alert(1)">'`, + `description: '<script>alert(2)</script> "quoted"'`, + "---", + "", + '<div onclick="alert(3)"><script>alert(4)</script><a href="javascript:alert(5)">a</a></div>', + "", + '[a](javascript:alert(6)) [b](JaVaScRiPt:alert(7)) [c](javascript:alert(8)) [d](javascript:alert(9)) [e](<java\tscript:alert(10)>) [f](data:text/html,<script>alert(11)</script>) [g](vbscript:x)', + "", + "![img](javascript:alert(12)) <b onmouseover=alert(13)>bold</b> <svg onload=alert(14)>", + "", + "## <img src=y onerror=alert(15)> {#\"onclick=alert(16)}", + ].join("\n"), + }); + const out = render(guidesModel(evil, { name: '<script>alert("name")</script>' })); + test("unsafe link URLs are reported and dropped", () => { + expect(evil.diagnostics.filter(d => d.message.startsWith("unsafe link")).length).toBe(7); + expect(evil.diagnostics.filter(d => d.message.startsWith("unsafe image")).length).toBe(1); + }); + test("no executable markup or unsafe URL reaches the output", () => { + for (const [file, content] of Object.entries(out)) { + if (typeof content !== "string" || file === "api.json" || file.endsWith(".js")) continue; + // Hostile text stays as text: HTML escapes its angle brackets as entities, Markdown with a backslash. + expect(content).not.toMatch(/javascript:|vbscript:|data:text|(?<!\\)<script>alert|(?<!\\)<img src=|(?<!\\)<svg onload|(?<!\\)<div onclick|<b onmouseover/i); + } + expect(checkSite(out, { allowed: [] })).toEqual([]); + expect(out["index.html"] as string).toContain("<b>bold</b>"); + }); +}); + +describe("guides-only site", () => { + const site = suiteSite(SAMPLE, { id: "geo", title: "Geo user guide", version: "2.1.0", baseUrl: "https://docs.example.com/geo/", links: SAMPLE_LINKS, theme: { extends: "elide" } }); + const out: Output = { ...site.output, ...Object.fromEntries(site.copies.map(c => [c.to, ""])) }; + const html = (path: string) => out[path] as string; + test("the sample suite imports cleanly; its model validates", () => { + expect(site.diagnostics).toEqual([]); + expect(site.result.drafts).toEqual(["reference/format.md", "reference/index.md"]); + expect(validate(site.model)).toEqual([]); + expect(validate(JSON.parse(html("api.json")))).toEqual([]); + }); + test("passes the output checker", () => { + // With a base URL, pages offer to open themselves in Claude and ChatGPT. + expect(checkSite(out, { allowed: ["https://example.com/", "https://docs.example.com/", "mailto:", "https://claude.ai/", "https://chatgpt.com/"] })).toEqual([]); + }); + test("the overview is the suite's index, with no API lists, index pages or element-list", () => { + expect(html("index.html")).toContain("<h1>Geo user guide</h1>"); + expect(html("index.html")).not.toContain('id="packages"'); + expect(html("index.html")).not.toContain("nav-packages"); + expect(html("index.html")).not.toContain("search-fallback"); + for (const file of ["packages.html", "types.html", "index-all.html", "deprecated.html", "element-list", "guides/index.html"]) expect(out[file]).toBeUndefined(); + expect(html("index.html")).toContain('placeholder="Search the guides"'); + }); + test("navigator, breadcrumbs and reading order across groups", () => { + const alerts = html("guides/concepts/alerts.html"); + expect(alerts).toContain('<nav class="crumbs" aria-label="Breadcrumbs"><ol><li><a href="../../index.html">Geo user guide</a></li><li><a href="index.html">Concepts</a></li><li><span aria-current="page">Callouts</span></li></ol></nav>'); + expect(alerts).toMatch(/<span class="nav-label">Alerts<\/span>/); + expect(alerts).toContain('<p class="nav-subheading">Concepts › Advanced topics</p>'); + const order = site.model.module.guides!.map(g => g.slug); + expect(order).toEqual(["index", "getting-started", "concepts/index", "concepts/alerts", "concepts/images", "concepts/advanced/index", "concepts/advanced/custom-shapes"]); + expect(html("index.html")).toContain('rel="next" href="guides/getting-started.html"'); + expect(html("guides/concepts/images.html")).toContain('rel="next" href="advanced/index.html"'); + expect(html("guides/concepts/index.html")).toContain('rel="prev" href="../getting-started.html"'); + expect(html("guides/getting-started.html")).toContain('rel="prev" href="../index.html"'); + }); + test("search, llms.txt, llms-full.txt, Markdown twins and the sitemap", () => { + const index = JSON.parse(html("assets/search-index.js").replace(/^window\.apidocsSearch=/, "").replace(/;\n$/, "")) as string[][]; + expect(index).toContainEqual(["Before you start", "section", "guides/concepts/alerts.html#before-you-start", "Callouts", ""]); + expect(index).toContainEqual(["Getting started", "guide", "guides/getting-started.html", "Guides", "Install Geo, then measure your first shape."]); + expect(html("llms.txt")).not.toContain("## Pages"); + expect(html("llms.txt")).toContain("> Measure and draw shapes with the Geo library, from installation to custom shapes."); + for (const slug of ["getting-started", "concepts/alerts", "concepts/advanced/custom-shapes"]) { + expect(html("llms.txt")).toContain(`(guides/${slug}.md)`); + expect(html("llms-full.txt")).toContain(`<!-- guides/${slug}.md -->`); + expect(out[`guides/${slug}.md`]).toBeDefined(); + } + expect(html("sitemap.xml")).toContain("<loc>https://docs.example.com/geo/guides/concepts/images.html</loc>"); + }); + test("snapshots", () => { + for (const path of ["index.md", "guides/getting-started.md", "guides/concepts/alerts.md", "guides/concepts/images.md", "guides/concepts/alerts.html"]) expect(out[path]).toMatchSnapshot(path); + }); + test("a guides-only model without an overview lists its guides, with no empty package lists", () => { + const model: Model = { schema: "apidocs/1", module: { name: "m", guides: [{ id: "guide:a", slug: "a", title: "A" }] } }; + const plain = render(model); + expect(plain["index.html"] as string).toContain('id="guides"'); + expect(plain["index.html"] as string).not.toContain('id="packages"'); + expect(plain["index.md"] as string).not.toContain("## Packages"); + expect(checkSite(plain, { allowed: [] })).toEqual([]); + }); + test("the CLI writes the same site, with the suite's files", () => { + const dir = mkdtempSync(join(tmpdir(), "apidocs-guides-")); + try { + const run = spawnSync(process.execPath, [join(root, "src/cli.ts"), "guides", "--src", SAMPLE, "--id", "geo", "--title", "Geo user guide", "--out", dir, "--version", "2.1.0", + "--source-link", "https://example.com/src/{path}#L{line}", "--source-root", "docs/user", ...SAMPLE_LINKS.flatMap(l => ["--link", `${l.prefix}=${l.target}`])], { encoding: "utf8" }); + expect(run.status).toBe(0); + expect(JSON.parse(run.stdout)).toMatchObject({ pages: 7, guides: 7, drafts: 2, errors: 0, warnings: 0 }); + for (const file of ["index.html", "index.md", "llms.txt", "llms-full.txt", "api.json", "assets/search-index.js", "assets/apidocs.css", "assets/apidocs.js", "guides/concepts/swatch.png", "guides/concepts/diagram.svg"]) { + expect(existsSync(join(dir, file))).toBe(true); + } + expect(readFileSync(join(dir, "guides/getting-started.html"), "utf8")).toContain('href="https://example.com/src/docs/user/getting-started.md#L1"'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, 60_000); +}); + +// Komodo's documentation suites, when this package is checked out inside Komodo (web/vendor/components). Not a +// snapshot: those pages change on their own schedule. +const komodo = join(root, "../../../../../docs"); +describe.skipIf(!existsSync(join(komodo, "user/index.md")) || !existsSync(join(komodo, "developer/index.md")))("Komodo's suites", () => { + for (const [suite, other] of [["user", "developer"], ["developer", "user"]] as const) { + for (const includeDrafts of [false, true]) { + test(`${suite}${includeDrafts ? " with drafts" : ""} imports without errors and passes the output checker`, () => { + const site = suiteSite(join(komodo, suite), { id: suite, title: `Komodo ${suite} guide`, includeDrafts, links: [{ prefix: `../${other}/`, target: `https://example.com/${other}/` }] }); + expect(site.diagnostics.filter(d => d.severity === "error").map(d => formatDiagnostic(d))).toEqual([]); + expect(site.model.module.overview).toBe(`guide:${suite}/index`); + const out = { ...site.output, ...Object.fromEntries(site.copies.map(c => [c.to, ""])) }; + expect(checkSite(out, { allowed: ["https://"] })).toEqual([]); + }); + } + } +}); diff --git a/packages/apidocs/test/indexes.test.ts b/packages/apidocs/test/indexes.test.ts new file mode 100644 index 0000000..5fb6746 --- /dev/null +++ b/packages/apidocs/test/indexes.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { samples } from "../samples"; +import { compareNames } from "../src/index-data"; +import type { Model } from "../src/model"; +import { render } from "../src/render"; +import { buildSite, DEPRECATED_PAGE, INDEX_ALL_PAGE, indexPages, PACKAGES_PAGE, TYPES_PAGE } from "../src/site"; +import { checkSite } from "./check"; + +const fixture: Model = JSON.parse(readFileSync(new URL("fixtures/fixture-java.api.json", import.meta.url), "utf8")); +const PAGES = [PACKAGES_PAGE, TYPES_PAGE, INDEX_ALL_PAGE, DEPRECATED_PAGE]; +const allowed = (model: Model) => [...(model.externals ?? []).map(e => e.url.split("{")[0]!), "https://example.com/", "https://en.wikipedia.org/", "https://kotlinlang.org/", "https://schema.org"]; + +describe("index pages", () => { + for (const [name, model] of Object.entries(samples)) { + const site = render(model, { extends: "elide" }); + test(`${name}: every index page and its Markdown twin`, () => { + for (const page of PAGES) { + expect(site[`${page}.html`]).toBeString(); + expect(site[`${page}.md`]).toBeString(); + } + expect(indexPages(buildSite(model)).map(p => p.page)).toEqual(PAGES); + expect(site["llms.txt"] as string).toContain("## Indexes"); + }); + test(`${name}: links resolve and the output stays portable`, () => { + // Scoped to the index pages' own links: the page shell's skip link is checked with the shell's tests. + const errors = checkSite(site, { allowed: allowed(model) }).filter(e => PAGES.some(p => e.startsWith(`${p}.html:`)) && !e.endsWith('"#content"')); + expect(errors).toEqual([]); + }); + test(`${name}: letters are sorted, each group links from the letter bar`, () => { + const html = site[`${INDEX_ALL_PAGE}.html`] as string; + const letters = [...html.matchAll(/<section id="index-([A-Z]|other)" class="section index-letter"/g)].map(m => m[1]!); + const sorted = [...letters].sort((a, b) => (a === "other" ? 1 : b === "other" ? -1 : compareNames(a, b))); + expect(letters).toEqual(sorted); + for (const letter of letters) expect(html).toContain(`index-all.html#index-${letter}"`); + }); + } + test("overloads are listed separately by their parameter types", () => { + const md = render(samples.java)[`${INDEX_ALL_PAGE}.md`] as string; + expect(md).toContain("`area(Circle)`"); + expect(md).toContain("`area(Polygon)`"); + }); + test("deprecated: for removal first, with the deprecation text", () => { + const md = render(samples.java)[`${DEPRECATED_PAGE}.md`] as string; + const members = md.slice(md.indexOf("## Members")); + expect(members.indexOf("for removal")).toBeLessThan(members.indexOf("(deprecated)")); + expect(md).toContain("total(Shape...)"); + }); + test("guides come first on the A-Z page when the model has any", () => { + const html = render(samples.java)[`${INDEX_ALL_PAGE}.html`] as string; + if (samples.java.module.guides?.length) expect(html.indexOf('id="index-guides"')).toBeLessThan(html.indexOf('class="section index-letter"', html.indexOf('id="index-guides"') + 1)); + }); + test("a page without content is not written", () => { + const clean = structuredClone(fixture); + for (const pkg of clean.packages ?? []) { + delete pkg.deprecated; + for (const type of pkg.types ?? []) { + delete type.deprecated; + for (const member of type.members ?? []) delete member.deprecated; + } + } + const site = render(clean); + expect(site[`${DEPRECATED_PAGE}.html`]).toBeUndefined(); + expect(site[`${DEPRECATED_PAGE}.md`]).toBeUndefined(); + expect(site[`${PACKAGES_PAGE}.html`]).toBeString(); + const empty = render({ schema: "apidocs/1", module: { name: "empty" } }); + for (const page of PAGES) expect(empty[`${page}.html`]).toBeUndefined(); + }); + test("Markdown snapshots of the fixture's index pages", () => { + const site = render(fixture); + for (const page of PAGES) expect(site[`${page}.md`]).toMatchSnapshot(`${page}.md`); + }); +}); diff --git a/packages/apidocs/test/markdown.test.ts b/packages/apidocs/test/markdown.test.ts new file mode 100644 index 0000000..762ccf4 --- /dev/null +++ b/packages/apidocs/test/markdown.test.ts @@ -0,0 +1,32 @@ +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { samples } from "../samples"; +import type { Model } from "../src/model"; +import { render } from "../src/render"; + +const fixture: Model = JSON.parse(readFileSync(new URL("fixtures/fixture-java.api.json", import.meta.url), "utf8")); + +test("Markdown snapshots of the fixture", () => { + const out = render(fixture, { symbols: "none" }); + for (const page of ["fixture/java/Geometry.md", "fixture/java/Circle.md", "fixture/java/io/ShapeReader.md", "index.md", "llms.txt"]) { + expect(out[page]).toMatchSnapshot(page); + } +}); + +test("Markdown sections come in a fixed order", () => { + const md = render(samples.java, { symbols: "none" })["com/example/geo/Shapes.md"] as string; + const parse = md.slice(md.indexOf("### parse(String)"), md.indexOf("### sum(")); + const order = ["```java", "Parses a shape", "**Parameters**", "**Returns**", "**Throws**", "> **API note**", "> **Implementation note**", "**See also**"]; + const at = order.map(marker => parse.indexOf(marker)); + expect(at.every(i => i >= 0)).toBe(true); + expect([...at].sort((a, b) => a - b)).toEqual(at); +}); + +test("Kotlin features in Markdown: receivers, default arguments, type aliases", () => { + const md = render(samples.kotlin)["org/example/kgeo/index.md"] as string; + expect(md).toContain("### Shape.scaled(Double)"); + expect(md).toContain("**Receiver** "); + expect(md).toContain("`by` [`Double`]"); + expect(md).toContain("= `1.0`"); + expect(md).toContain("## Type aliases"); +}); diff --git a/packages/apidocs/test/narrative.test.ts b/packages/apidocs/test/narrative.test.ts new file mode 100644 index 0000000..32c4d44 --- /dev/null +++ b/packages/apidocs/test/narrative.test.ts @@ -0,0 +1,143 @@ +/** Guides: schema, ordering, anchors, links, outputs, backward compatibility and hostile input. */ +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { samples } from "../samples"; +import type { Guide, Model } from "../src/model"; +import { render } from "../src/render"; +import { buildSite, orderGuides } from "../src/site"; +import { compactTokens, guideAnchors } from "../src/structure"; +import { checkSite } from "./check"; +import { validate } from "./validate"; + +const fixture: Model = JSON.parse(readFileSync(new URL("fixtures/fixture-java.api.json", import.meta.url), "utf8")); +const allowed = (model: Model) => [...(model.externals ?? []).map(e => e.url.split("{")[0]!), "https://example.com/", "https://en.wikipedia.org/", "https://kotlinlang.org/", "https://jspecify.dev/"]; +const p = (text: string) => ({ kind: "paragraph" as const, children: [{ kind: "text" as const, text }] }); +const h = (level: number, text: string, anchor?: string) => ({ kind: "heading" as const, level, children: [{ kind: "text" as const, text }], ...(anchor ? { anchor } : {}) }); +const g = (slug: string, extra: Partial<Guide> = {}): Guide => ({ id: `guide:${slug}`, slug, title: slug, ...extra }); +const withGuides = (guides: Guide[], doc?: Model["module"]["doc"]): Model => ({ schema: "apidocs/1", module: { name: "m", guides, ...(doc ? { doc } : {}) } }); + +describe("schema", () => { + for (const [name, model] of Object.entries(samples)) test(`${name} sample with guides is valid`, () => expect(validate(model)).toEqual([])); + test("rejects an admonition without a tone and an unknown tone", () => { + expect(validate(withGuides([g("a", { body: [{ kind: "admonition" } as never] })])).length).toBeGreaterThan(0); + expect(validate(withGuides([g("a", { body: [{ kind: "admonition", tone: "danger" } as never] })])).length).toBeGreaterThan(0); + }); +}); + +describe("backward compatibility", () => { + test("a model without guides gets no guide files and no guide links; an empty list renders the same", () => { + const out = render(fixture); + const empty = render({ ...fixture, module: { ...fixture.module, guides: [] } }); + expect({ ...empty, "api.json": "" }).toEqual({ ...out, "api.json": "" }); + for (const [file, content] of Object.entries(out)) { + expect(file.startsWith("guides/")).toBe(false); + if (typeof content === "string" && file !== "api.json") expect(content).not.toContain("guides/"); + } + expect(out["llms.txt"] as string).not.toContain("## Guides"); + }); +}); + +describe("ordering and pages", () => { + test("ungrouped first, groups by first appearance, order before unordered, model order on ties", () => { + const list = [g("c"), g("x/b", { group: "X", order: 2 }), g("a", { order: 1 }), g("x/a", { group: "X", order: 1 }), g("y/a", { group: "Y" }), g("d")]; + expect(orderGuides(list).map(x => x.slug)).toEqual(["a", "c", "d", "x/a", "x/b", "y/a"]); + }); + test("slugs become safe paths; a taken page gets a suffix", () => { + const site = buildSite(withGuides([g("../../etc/Passwd"), g("a b/C"), g(""), g("a-b/c")])); + expect(site.guides.map(e => e.page)).toEqual(["guides/etc/passwd", "guides/a-b/c", "guides/guide", "guides/a-b/c-2"]); + }); +}); + +describe("anchors", () => { + test("readable, deduplicated, never a shell id, explicit anchors win", () => { + const body = [h(2, "Café & Crème"), h(2, "Example"), h(3, "Example"), h(2, "Content"), h(2, "Any", "custom-id"), { kind: "admonition" as const, tone: "note" as const, children: [h(2, "Example")] }, h(4, "Deep")]; + const { anchors, sections } = guideAnchors(body, ["content"]); + expect([...anchors.values()]).toEqual(["cafe-creme", "example", "example-2", "content-2", "custom-id", "example-3", "deep"]); + expect(sections.map(s => [s.anchor, s.level])).toEqual([["cafe-creme", 2], ["example", 2], ["example-2", 3], ["content-2", 2], ["custom-id", 2]]); + }); + test("links to a guide and a section resolve in HTML and Markdown; a missing guide is plain text", () => { + const link = (id: string, section?: string) => ({ kind: "link" as const, target: { id, ...(section ? { section } : {}) }, children: [{ kind: "text" as const, text: `to ${id}${section ?? ""}` }] }); + const model = withGuides([g("a/b", { body: [h(2, "Intro"), { kind: "paragraph", children: [link("guide:c", "usage"), link("guide:missing")] }] }), g("c", { body: [h(2, "Usage")] })], + { body: [{ kind: "paragraph", children: [link("guide:a/b", "intro")] }] }); + const out = render(model); + expect(out["index.html"] as string).toContain('href="guides/a/b.html#intro"'); + expect(out["index.md"] as string).toContain("(guides/a/b.md#intro)"); + expect(out["guides/a/b.html"] as string).toContain('href="../c.html#usage"'); + expect(out["guides/a/b.html"] as string).toContain("to guide:missing"); + expect(out["guides/a/b.html"] as string).not.toContain("missing.html"); + expect(checkSite(out, { allowed: [] })).toEqual([]); + }); + test("the checker reports a link to a missing section", () => { + const model = withGuides([g("a", { body: [{ kind: "paragraph", children: [{ kind: "link", target: { id: "guide:b", section: "nope" }, children: [{ kind: "text", text: "x" }] }] }] }), g("b")]); + expect(checkSite(render(model), { allowed: [] })).toEqual(["guides/a.html: link to a missing anchor ../guides/b.html#nope".replace("../guides/", "")]); + }); +}); + +describe("outputs", () => { + const out = render(samples.java, { baseUrl: "https://docs.example.com/" }); + test("both samples pass the output checker", () => { + for (const [name, model] of Object.entries(samples)) expect(checkSite(render(model, { extends: "elide" }), { allowed: allowed(model) })).toEqual([]); + }); + test("llms.txt lists guides before the reference pages; llms-full.txt puts them after the overview", () => { + const llms = out["llms.txt"] as string; + expect(llms.indexOf("## Guides")).toBeGreaterThan(0); + expect(llms.indexOf("## Guides")).toBeLessThan(llms.indexOf("## Pages")); + expect(llms.indexOf("guides/getting-started.md")).toBeLessThan(llms.indexOf("guides/concepts.md")); + expect(llms.indexOf("guides/concepts.md")).toBeLessThan(llms.indexOf("guides/migrating-from-1x.md")); + expect(llms.indexOf("guides/advanced/custom-shapes.md")).toBeLessThan(llms.indexOf("guides/advanced/text-format.md")); + const full = out["llms-full.txt"] as string; + expect(full.indexOf("<!-- guides/getting-started.md -->")).toBeLessThan(full.indexOf("<!-- com/example/geo/index.md -->")); + expect(full.indexOf("<!-- index.md -->")).toBe(0); + }); + test("search has an entry per guide and per section; the sitemap lists guides", () => { + const index = JSON.parse((out["assets/search-index.js"] as string).replace(/^window\.apidocsSearch=/, "").replace(/;\n$/, "")) as string[][]; + expect(index).toContainEqual(["Concepts", "guide", "guides/concepts.html", "Guides", "Shapes, measuring and units: the ideas the reference pages assume."]); + expect(index).toContainEqual(["Example", "section", "guides/concepts.html#example-2", "Concepts", ""]); + expect(index).toContainEqual(["The text format", "guide", "guides/advanced/text-format.html", "Advanced", "The grammar Shapes.parse reads, and how to read files of shapes."]); + expect(out["sitemap.xml"] as string).toContain("<loc>https://docs.example.com/guides/concepts.html</loc>"); + }); + test("every admonition tone renders as a callout, in HTML and Markdown", () => { + const html = out["guides/concepts.html"] as string; + for (const tone of ["note", "tip", "important", "warning", "caution", "apiNote", "implSpec", "implNote"]) expect(html).toContain(`callout callout-${tone}`); + const md = out["guides/concepts.md"] as string; + for (const alert of ["[!NOTE]", "[!TIP]", "[!IMPORTANT]", "[!WARNING]", "[!CAUTION]"]) expect(md).toContain(`> ${alert}`); + expect(md).toContain("> **⚠︎ API note**"); + }); + test("guide page snapshots, HTML and Markdown", () => { + for (const page of ["guides/concepts.md", "guides/advanced/text-format.md", "guides/getting-started.html"]) expect(out[page]).toMatchSnapshot(page); + }); + test("compact tokens put a formatter-wrapped signature on one line", () => { + const tokens = [{ kind: "name" as const, text: "f" }, { kind: "punct" as const, text: "(\n " }, { kind: "param" as const, text: "a" }, { kind: "punct" as const, text: ",\n " }, { kind: "param" as const, text: "b" }, { kind: "punct" as const, text: ",\n)" }]; + expect(compactTokens(tokens).map(t => t.text).join("")).toBe("f(a, b)"); + }); +}); + +describe("hostile guides", () => { + const evil = withGuides([{ + id: "guide:x", slug: "x", title: '<img src=x onerror="alert(1)">', + summary: [{ kind: "link", url: "javascript:alert(2)", children: [{ kind: "text", text: "s" }] }], + body: [ + h(2, '"><script>alert(3)</script>', '" onclick="alert(4)'), + { kind: "paragraph", children: [ + { kind: "link", url: "javascript:alert(5)", children: [{ kind: "text", text: "encoded" }] }, + { kind: "link", target: { id: "guide:x", section: '" onmouseover="alert(6)' }, children: [{ kind: "text", text: "section" }] }, + { kind: "raw", html: "<svg onload=alert(7)></svg>", text: "" }, + ] }, + { kind: "admonition", tone: "warning", title: [{ kind: "raw", html: "<b onclick=x>t</b>", text: "t" }], children: [{ kind: "raw", html: "<script>alert(8)</script>", text: "" }] }, + ], + }]); + const out = render(evil); + test("no executable markup or unsafe URL reaches the output", () => { + for (const [file, content] of Object.entries(out)) { + if (typeof content !== "string" || file === "api.json" || file.endsWith(".js")) continue; + // Markdown escapes the angle brackets of hostile text; HTML escapes them as entities. + expect(content).not.toMatch(/javascript:|(?<!\\)<script>alert|(?<!\\)<img|(?<!\\)<svg onload/i); + } + // The hostile section names no heading, so the only finding is that missing anchor. + expect(checkSite(out, { allowed: [] })).toEqual(["guides/x.html: link to a missing anchor x.html#%22%20onmouseover%3D%22alert(6)"]); + expect(out["guides/x.html"] as string).toContain("encoded"); + }); + test("the hostile section becomes an encoded fragment", () => { + expect(out["guides/x.html"] as string).toContain('href="x.html#%22%20onmouseover%3D%22alert(6)"'); + }); +}); diff --git a/packages/apidocs/test/render.test.ts b/packages/apidocs/test/render.test.ts new file mode 100644 index 0000000..45664cf --- /dev/null +++ b/packages/apidocs/test/render.test.ts @@ -0,0 +1,238 @@ +import { describe, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { spawnSync } from "node:child_process"; +import { samples } from "../samples"; +import { generate } from "../scripts/gen-types"; +import { search } from "../src/client/search"; +import { highlight } from "../src/highlight"; +import type { Model, Token } from "../src/model"; +import { render } from "../src/render"; +import { sanitize } from "../src/sanitize"; +import { layoutSignature } from "../src/signature"; +import { sharedPrefix } from "../src/components/chrome"; +import { checkSite } from "./check"; +import { validate } from "./validate"; + +const fixture: Model = JSON.parse(readFileSync(new URL("fixtures/fixture-java.api.json", import.meta.url), "utf8")); +const models: Record<string, Model> = { fixture, java: samples.java, kotlin: samples.kotlin }; + +function allowed(model: Model): string[] { + return [...(model.externals ?? []).map(e => e.url.split("{")[0]!), "https://example.com/", "https://en.wikipedia.org/", "https://kotlinlang.org/"]; +} + +describe("schema", () => { + for (const [name, model] of Object.entries(models)) { + test(`${name} model is valid apidocs/1`, () => expect(validate(model)).toEqual([])); + } + test("src/model.ts is generated from the schema", () => { + const schema = JSON.parse(readFileSync(new URL("../schema/apidocs-1.schema.json", import.meta.url), "utf8")); + expect(readFileSync(new URL("../src/model.ts", import.meta.url), "utf8")).toBe(generate(schema)); + }); + test("the Elide artwork module is current", () => { + const check = spawnSync("bun", ["scripts/gen-artwork.ts", "--check"], { cwd: new URL("..", import.meta.url).pathname }); + expect(check.status).toBe(0); + }); + test("the validator rejects what the schema forbids", () => { + expect(validate({ schema: "apidocs/1", module: { name: "m" }, extra: 1 })).toContain("$: unexpected property extra"); + expect(validate({ schema: "apidocs/2", module: { name: "m" } })).toHaveLength(1); + const bad = structuredClone(fixture); + (bad.packages![0]!.types![0]! as { kind: string }).kind = "struct"; + expect(validate(bad).join()).toContain("is not one of"); + }); +}); + +describe("render", () => { + const out = render(fixture); + test("is deterministic", () => expect(render(fixture)).toEqual(out)); + test("accepts the model and theme as JSON text", () => expect(render(JSON.stringify(fixture), "{}")).toEqual(out)); + test("rejects another schema", () => expect(() => render({ ...fixture, schema: "apidocs/0" as "apidocs/1" })).toThrow("apidocs/1")); + test("writes every page as HTML and Markdown, and the indexes", () => { + for (const page of ["index", "fixture/java/index", "fixture/java/Geometry", "fixture/java/Canvas.Layer.Kind", "fixture/java/io/ShapeReader"]) { + expect(out[`${page}.html`]).toBeString(); + expect(out[`${page}.md`]).toBeString(); + } + for (const file of ["llms.txt", "llms-full.txt", "api.json", "element-list", "assets/search-index.js", "assets/theme.css"]) expect(out[file]).toBeDefined(); + expect(out["assets/apidocs.css"]).toEqual({ asset: "apidocs.css" }); + expect(out["sitemap.xml"]).toBeUndefined(); + expect(out["element-list"]).toBe("fixture.java\nfixture.java.io\n"); + const named = render({ ...fixture, module: { ...fixture.module, javaModule: "dev.example.fixture" } }); + expect(named["element-list"]).toBe("module:dev.example.fixture\nfixture.java\nfixture.java.io\n"); + }); + test("uses the JDK doclet's anchors", () => { + const html = out["fixture/java/io/ShapeReader.html"] as string; + expect(html).toContain('id="read(java.io.InputStream)"'); + expect(out["fixture/java/Polygon.html"] as string).toContain('id="<init>(double...)"'); + }); + test("HTML snapshots", () => { + for (const page of ["fixture/java/Geometry.html", "fixture/java/Circle.html", "fixture/java/index.html", "index.html"]) { + expect(out[page]).toMatchSnapshot(page); + } + }); + test("a base URL adds canonical links and a sitemap", () => { + const site = render(fixture, { baseUrl: "https://docs.example.com/api/" }); + expect(site["sitemap.xml"]).toContain("<loc>https://docs.example.com/api/fixture/java/Geometry.html</loc>"); + expect(site["index.html"]).toContain('rel="canonical" href="https://docs.example.com/api/index.html"'); + }); + test("the neutral default carries no Elide branding (fixture text has none)", () => { + for (const model of [fixture]) { + for (const [file, content] of Object.entries(render(model))) { + if (typeof content === "string" && file !== "api.json" && file !== "llms-full.txt") expect(`${file}: ${content}`).not.toMatch(/elide/i); + } + } + }); + test("the Elide preset adds its artwork and fonts", () => { + const site = render(fixture, { extends: "elide" }); + expect(site["assets/logo-light.svg"]).toContain("<svg"); + expect(site["assets/fonts/jetbrains-mono-latin-wght-normal.woff2"]).toEqual({ asset: "fonts/jetbrains-mono-latin-wght-normal.woff2" }); + // Prose and headings use the reader's system fonts: no other font file ships. + expect(Object.keys(site).filter(f => f.startsWith("assets/fonts/")).sort()).toEqual(["assets/fonts/jetbrains-mono-latin-wght-italic.woff2", "assets/fonts/jetbrains-mono-latin-wght-normal.woff2"]); + expect(site["assets/theme.css"]).toContain("--apidocs-accent:#6d28d9"); + }); + test("notes render as distinct callouts, the API note first", () => { + const html = out["fixture/java/Geometry.html"] as string; + expect(html).toContain('class="callout callout-implSpec"'); + const shapes = render(samples.java)["com/example/geo/Shapes.html"] as string; + const parse = shapes.slice(shapes.indexOf('id="parse(java.lang.String)"')); + expect(parse.indexOf("callout-apiNote")).toBeGreaterThan(0); + expect(parse.indexOf("callout-apiNote")).toBeLessThan(parse.indexOf("callout-implNote")); + expect(render(samples.java, { symbols: "none" })["com/example/geo/Shapes.md"]).toContain("> **API note**"); + }); +}); + +describe("layout", () => { + const java = render(samples.java, { extends: "elide" }); + const between = (html: string, start: string, end: string) => html.slice(html.indexOf(start), html.indexOf(end, html.indexOf(start))); + + test("sharedPrefix: one package, several, one equal to the prefix, the default package", () => { + expect(sharedPrefix(["com.example.geo"])).toBe("com.example"); + expect(sharedPrefix(["com.example.geo.io", "com.example.geo.spi"])).toBe("com.example.geo"); + expect(sharedPrefix(["com.example.geo", "com.example.geo.io"])).toBe("com.example"); + expect(sharedPrefix(["", "org.example.kgeo"])).toBe("org.example"); + expect(sharedPrefix([""])).toBe(""); + expect(sharedPrefix(["alpha", "beta"])).toBe(""); + }); + test("the navigator has no disclosure widgets", () => { + for (const page of ["index.html", "com/example/geo/index.html", "com/example/geo/Shapes.Builder.Option.html"]) { + const nav = between(java[page] as string, '<nav class="sidebar"', "</nav>"); + expect(nav.length).toBeGreaterThan(100); + expect(nav).not.toContain("<details"); + } + }); + test("a rail section with more than 12 entries is folded; a short one is not", () => { + const rail = (page: string) => between(java[page] as string, '<nav class="toc"', "</nav>"); + expect(rail("com/example/geo/registry/ShapeCatalog.html")).toContain('<details class="toc-more">'); + expect(rail("com/example/geo/Circle.html")).not.toContain('<details class="toc-more">'); + }); + test("script-only controls are marked, and the head marks script support before paint", () => { + const html = java["com/example/geo/Shapes.html"] as string; + for (const control of ["data-search", "data-theme-switch", "data-nav-filter"]) { + expect(html).toMatch(new RegExp(`${control}="true"[^>]*data-js-only|data-js-only[^>]*${control}`)); + } + const head = between(html, "<head>", "</head>"); + expect(head).toContain('setAttribute("data-js","")'); + expect(head.indexOf('setAttribute("data-js","")')).toBeLessThan(head.indexOf("apidocs.css") < 0 ? Infinity : head.length); + }); + test("the navigator toggle is a checkbox that works without script", () => { + const html = java["index.html"] as string; + expect(html).toContain('<input type="checkbox" id="apidocs-nav-toggle"'); + expect(html).toContain('for="apidocs-nav-toggle"'); + }); + test("font preloads are added at run time off file://, upright faces only", () => { + const head = between(java["com/example/geo/Shapes.html"] as string, "<head>", "</head>"); + expect(head).not.toContain('<link rel="preload"'); + expect(head).toContain('if(location.protocol!=="file:")'); + const urls = JSON.parse(/\(location\.protocol!=="file:"\)(\[[^\]]*\])/.exec(head)![1]!) as string[]; + expect(urls.map(u => u.split("/").pop())).toEqual(["jetbrains-mono-latin-wght-normal.woff2"]); + // A theme without font files preloads nothing. + expect(render(fixture)["index.html"]).not.toContain(".forEach(function(h)"); + }); +}); + +describe("output checker", () => { + for (const [name, model] of Object.entries(models)) { + for (const preset of ["neutral", "elide"] as const) { + test(`${name} with ${preset} passes`, () => expect(checkSite(render(model, { extends: preset }), { allowed: allowed(model) })).toEqual([])); + } + } + test("reads only script code for fetch and import(), not prose or string data", () => { + expect(checkSite({ + "a.html": "<p>Modules that programs import (the stdlib) and fetch (later).</p><script>var s = \"fetch(x)\";</script>", + "b.js": 'window.index = ["programs import (the stdlib)"];', + }, { allowed: [] })).toEqual([]); + expect(checkSite({ "a.html": "<script>fetch('x')</script>", "b.js": "import('x')" }, { allowed: [] })) + .toEqual(["a.html: uses fetch", "b.js: dynamic import"]); + }); + test("allows inline classic scripts and JSON-LD; rejects module scripts", () => { + expect(checkSite({ "a.html": '<script>document.documentElement.setAttribute("data-js","")</script><script type="application/ld+json">{}</script>' }, { allowed: [] })).toEqual([]); + expect(checkSite({ "a.html": '<script type="module">x()</script>' }, { allowed: [] })).toEqual(["a.html: module script"]); + }); + test("finds what breaks portability", () => { + const errors = checkSite({ + "a.html": '<a href="https://evil.example/x">x</a><a href="b.html#nope">b</a><a href="missing.html">m</a><a href="#top">t</a><a href="dir/">d</a><script type="module" src="c.js"></script>', + "b.html": '<p id="yes"></p>', + "c.js": "fetch('x')", + }, { allowed: [] }); + expect(errors).toEqual([ + "a.html: module script", + "a.html: absolute URL https://evil.example/x", + "a.html: link to a missing anchor b.html#nope", + "a.html: link to a missing file missing.html", + 'a.html: link does not name its file: "#top"', + "a.html: link names a directory: dir/", + "c.js: uses fetch", + ]); + }); +}); + +describe("runner", () => { + test("renders through dist/runner.mjs, with --source-ref filling the theme's {ref}", () => { + const work = mkdtempSync(join(tmpdir(), "apidocs-runner-")); + try { + writeFileSync(join(work, "model.json"), JSON.stringify(fixture)); + writeFileSync(join(work, "theme.json"), JSON.stringify({ sourceLink: "https://example.com/blob/{ref}/{path}#L{line}" })); + const dist = new URL("../dist/", import.meta.url).pathname; + const run = spawnSync(process.execPath, [`${dist}runner.mjs`, "--bundle", `${dist}render.js`, "--assets", `${dist}assets`, + "--model", join(work, "model.json"), "--theme", join(work, "theme.json"), "--source-ref", "v1.2.3", "--out", join(work, "out")], { encoding: "utf8" }); + expect(run.stderr).toBe(""); + expect(JSON.parse(run.stdout).files).toBeGreaterThan(40); + expect(readFileSync(join(work, "out/fixture/java/Geometry.html"), "utf8")).toContain("https://example.com/blob/v1.2.3/fixture/java/Geometry.java#L"); + } finally { + rmSync(work, { recursive: true, force: true }); + } + }); +}); + +describe("parts", () => { + test("highlights Java and Kotlin", () => { + expect(highlight('String s = "a"; // c', "java")).toEqual([ + { cls: "t", text: "String" }, { text: " s = " }, { cls: "s", text: '"a"' }, { text: "; " }, { cls: "c", text: "// c" }, + ]); + expect(highlight("suspend fun f() = 1", "kotlin").filter(r => r.cls === "k").map(r => r.text)).toEqual(["suspend", "fun"]); + expect(highlight("x", "cobol")).toEqual([{ text: "x" }]); + }); + test("lays out long signatures one parameter per line", () => { + const tokens: Token[] = [ + { kind: "keyword", text: "public" }, { kind: "punct", text: " " }, { kind: "name", text: "transform" }, + { kind: "punct", text: "(" }, { kind: "type", text: "Map" }, { kind: "punct", text: "<" }, { kind: "type", text: "String" }, + { kind: "punct", text: ", " }, { kind: "type", text: "Object" }, { kind: "punct", text: "> " }, { kind: "param", text: "aVeryLongParameterName" }, + { kind: "punct", text: ", " }, { kind: "keyword", text: "int" }, { kind: "punct", text: " " }, { kind: "param", text: "anotherQuiteLongParameterName" }, + { kind: "punct", text: ")" }, + ]; + expect(layoutSignature(tokens).map(t => t.text).join("")).toBe( + "public transform(\n Map<String, Object> aVeryLongParameterName,\n int anotherQuiteLongParameterName\n)"); + expect(layoutSignature(tokens.slice(0, 4))).toEqual(tokens.slice(0, 4)); + }); + test("ranks search results", () => { + const entries: [string, string, string, string, string][] = [ + ["readAll()", "method", "a", "Reader", ""], ["Reader", "class", "b", "p", ""], ["ShapeReader", "class", "c", "p", ""], ["thread()", "method", "d", "X", ""], + ]; + expect(search(entries, "reader").map(e => e[0])).toEqual(["Reader", "ShapeReader", "readAll()"]); + expect(search(entries, "read").map(e => e[0])).toEqual(["Reader", "readAll()", "ShapeReader", "thread()"]); + expect(search(entries, "")).toEqual([]); + }); + test("drops executable markup from raw nodes", () => { + expect(sanitize('<sup onclick="x()">2</sup><script>alert(1)</script><a href="javascript:x">y</a>')).toBe("<sup>2</sup><a>y</a>"); + }); +}); diff --git a/packages/apidocs/test/security.test.ts b/packages/apidocs/test/security.test.ts new file mode 100644 index 0000000..93462f5 --- /dev/null +++ b/packages/apidocs/test/security.test.ts @@ -0,0 +1,141 @@ +/** + * Documentation comments and themes are untrusted: hostile URLs and markup + * must never reach an attribute or execute. These inputs mirror known bypasses + * of blocklist sanitizers. + */ +import { describe, expect, test } from "bun:test"; +import type { Model } from "../src/model"; +import { render } from "../src/render"; +import { sanitize } from "../src/sanitize"; +import { safeUrl } from "../src/url"; +import { checkSite } from "./check"; + +describe("safeUrl", () => { + const hostile = [ + "javascript:alert(1)", "JaVaScRiPt:alert(1)", " javascript:alert(1)", "\u0001javascript:alert(1)", + "java\tscript:alert(1)", "java\nscript:alert(1)", "java\rscript:alert(1)", "javascript:alert(1)", + "javascript:alert(1)", "javascript:alert(1)", "javascript:alert(1)", "javascript:alert(1)", + "data:text/html,<script>alert(1)</script>", "DATA:text/html;base64,PHNjcmlwdD4=", "vbscript:msgbox(1)", + "file:///etc/passwd", "blob:https://x/y", "\\\\evil/share", "java\u0000script:alert(1)", + "jav&#x61;script:alert(1)", "jav&amp;#x61;script:alert(1)", "&#106;avascript:alert(1)", + "javascript&colon;alert(1)", "javascript&amp;colon;alert(1)", "java script:alert(1)", + "java script:alert(1)", "&amp;amp;amp;amp;amp;#106;avascript:alert(1)", + ]; + for (const url of hostile) test(`rejects ${JSON.stringify(url)}`, () => expect(safeUrl(url)).toBeUndefined()); + const fine = ["https://example.com/a?b#c", "HTTP://example.com", "mailto:a@example.com", "../x.html#y", "x.html", "a/b.html#read(java.io.InputStream)"]; + for (const url of fine) test(`keeps ${url}`, () => expect(safeUrl(url)).toBe(url)); +}); + +describe("sanitize", () => { + const cases: [string, string][] = [ + ['<b onclick="alert(1)">x</b>', "<b>x</b>"], + ["<b onclick='alert(1)'>x</b>", "<b>x</b>"], + ["<b onclick=alert(1)>x</b>", "<b>x</b>"], + ['<b ONCLICK = "alert(1)">x</b>', "<b>x</b>"], + ["<b/onclick=alert(1)>x</b>", "<b>x</b>"], + ['<b onmouseover="a" title="t">x</b>', '<b title="t">x</b>'], + ["<script>alert(1)</script>after", "after"], + ["<SCRIPT src=//evil.js></SCRIPT>after", "after"], + ["<img src=x onerror=alert(1)>", ""], + ["<svg onload=alert(1)><circle/><script>alert(2)</script></svg>after", "after"], + ['<iframe srcdoc="<script>alert(1)</script>"></iframe>after', "after"], + ['<a href="javascript:alert(1)">x</a>', "<a>x</a>"], + ['<a href="javascript:alert(1)">x</a>', "<a>x</a>"], + ['<a href=" javascript:alert(1)">x</a>', "<a>x</a>"], + ['<a href="data:text/html,x">x</a>', "<a>x</a>"], + ['<a href="vbscript:x">x</a>', "<a>x</a>"], + ['<a href="https://example.com/" target="_blank" rel="opener">ok</a>', '<a href="https://example.com/">ok</a>'], + ['<sup class="x" style="color:red" id="y">2</sup>', "<sup>2</sup>"], + ["<style>body{display:none}</style>shown", "shown"], + ["<math><mi>x</mi></math>shown", "shown"], + ["<object data=x></object><embed src=x>", ""], + ["<b>unclosed", "<b>unclosed</b>"], + ['<a href="x>broken', ""], + ["<b", ""], + ["1 < 2 && 3 > 2", "1 < 2 && 3 > 2"], + ["<!-- <script>alert(1)</script> -->kept", "kept"], + ["<p><script>alert(1)</script>ok</p>", "<p>ok</p>"], + ["<unknown onclick=x>text</unknown>", "text"], + ['<td colspan="2" rowspan="x" onclick="y">c</td>', '<td colspan="2">c</td>'], + ['<th scope="col" scope="evil">h</th>', '<th scope="col">h</th>'], + ['<span title=""><script>alert(1)</script>">t</span>', '<span title=""><script>alert(1)</script>">t</span>'], + ["</b>stray", "stray"], + ]; + for (const [input, output] of cases) test(`sanitizes ${JSON.stringify(input)}`, () => expect(sanitize(input)).toBe(output)); +}); + +describe("Markdown link destinations", () => { + const model: Model = { + schema: "apidocs/1", + module: { name: "m", doc: { body: [{ kind: "paragraph", children: [ + { kind: "link", url: "https://example.com/a?b=1&c=(x) y\"z'<w>`v\\", children: [{ kind: "text", text: "odd" }] }, + { kind: "link", url: "jav&#x61;script:alert(1)", children: [{ kind: "text", text: "double" }] }, + ] }] } }, + }; + const md = render(model)["index.md"] as string; + test("are percent-encoded so a Markdown renderer cannot reinterpret them", () => { + const destination = /\[odd\]\(([^\s]*)\)/.exec(md)?.[1]; + expect(destination).toBe("https://example.com/a?b=1%26c=%28x%29%20y%22z%27%3Cw%3E%60v%5C"); + expect(destination).not.toMatch(/[&()<>"'`\\ ]/); + }); + test("drop a doubly encoded script URL, keeping the label", () => { + expect(md).toContain("double"); + expect(md).not.toMatch(/script:/i); + }); +}); + +describe("hostile models and themes", () => { + const hostile: Model = { + schema: "apidocs/1", + module: { name: "evil", doc: { body: [{ kind: "paragraph", children: [ + { kind: "link", url: "javascript:alert(1)", children: [{ kind: "text", text: "click me" }] }, + { kind: "link", url: "javascript:alert(2)", children: [{ kind: "text", text: "encoded" }] }, + { kind: "raw", html: '<img src=x onerror="alert(3)"><sup onclick=alert(4)>2</sup>', text: "2" }, + ] }, { kind: "raw", html: "<svg onload=alert(5)></svg><script>alert(6)</script>", text: "" }] } }, + externals: [{ prefix: "x.", url: "javascript:alert(7)//" }], + packages: [{ id: "p", name: "p", types: [{ + id: "p.T", name: "T", kind: "class", language: "java", + signature: [{ kind: "type", text: "Evil", ref: "x.Evil", url: "javascript:alert(8)" }], + source: { path: "p/T.java", line: 1 }, + doc: { see: [[{ kind: "link", url: "data:text/html,<script>alert(9)</script>", children: [{ kind: "text", text: "see" }] }]] }, + }] }], + }; + const theme = { + links: { header: [{ label: "bad", url: "javascript:alert(10)" }, { label: "good", url: "https://example.com/" }], footer: [{ label: "bad", url: " vbscript:x" }] }, + sourceLink: "javascript:alert('{path}')", + baseUrl: "javascript:alert(11)//", + }; + const site = render(hostile, theme); + + test("the output has no event handlers and no unsafe URLs", () => { + expect(checkSite(site, { allowed: ["https://example.com/"] })).toEqual([]); + for (const [file, content] of Object.entries(site)) { + if (typeof content !== "string" || !file.endsWith(".html")) continue; + expect(content).not.toMatch(/javascript:|vbscript:|data:text|onerror|onload|onclick/i); + expect(content).not.toMatch(/<script>alert/); + } + }); + test("unsafe links keep their labels as text", () => { + expect(site["index.html"]).toContain("click me"); + expect(site["index.html"]).toContain("<sup>2</sup>"); + expect(site["p/T.html"]).toContain(">see<"); + }); + test("the theme's unsafe links, base URL and source template are dropped", () => { + expect(site["index.html"]).toContain('href="https://example.com/"'); + expect(site["sitemap.xml"]).toBeUndefined(); + expect(site["p/T.html"]).not.toContain("source-link"); + }); + test("Markdown keeps labels and drops unsafe URLs", () => { + for (const [file, content] of Object.entries(site)) { + if (typeof content === "string" && file.endsWith(".md")) expect(content).not.toMatch(/javascript:|data:text|vbscript:/i); + } + expect(site["index.md"]).toContain("click me"); + }); + test("the checker catches what slips through", () => { + expect(checkSite({ "a.html": '<b onclick="x">y</b><a href="javascript:x">z</a><a href="javascript:x">w</a>' }, { allowed: [] })).toEqual([ + 'a.html: event handler attribute in <b onclick="x">', + "a.html: unsafe URL javascript:x", + "a.html: unsafe URL javascript:x", + ]); + }); +}); diff --git a/packages/apidocs/test/validate.ts b/packages/apidocs/test/validate.ts new file mode 100644 index 0000000..12eb16b --- /dev/null +++ b/packages/apidocs/test/validate.ts @@ -0,0 +1,68 @@ +/** + * A strict validator for the JSON Schema subset apidocs-1.schema.json uses: + * type, properties, required, additionalProperties: false, items, $ref, + * const, enum, oneOf and minimum. Returns every error with its JSON path. + */ +import schema from "../schema/apidocs-1.schema.json"; + +interface S { + $ref?: string; + type?: string; + const?: unknown; + enum?: unknown[]; + oneOf?: S[]; + items?: S; + properties?: Record<string, S>; + required?: string[]; + additionalProperties?: boolean; + minimum?: number; +} + +const defs = (schema as { $defs: Record<string, S> }).$defs; + +export function validate(value: unknown): string[] { + const errors: string[] = []; + check(value, schema as S, "$", errors); + return errors; +} + +function check(value: unknown, s: S, path: string, errors: string[]) { + if (s.$ref) return check(value, defs[s.$ref.replace("#/$defs/", "")]!, path, errors); + if (s.const !== undefined && value !== s.const) errors.push(`${path}: expected ${JSON.stringify(s.const)}`); + if (s.enum && !s.enum.includes(value)) errors.push(`${path}: ${JSON.stringify(value)} is not one of ${s.enum.join(", ")}`); + if (s.oneOf) { + const matches = s.oneOf.filter(option => { + const sub: string[] = []; + check(value, option, path, sub); + return sub.length === 0; + }); + if (matches.length !== 1) errors.push(`${path}: matches ${matches.length} of the oneOf options (kind ${JSON.stringify((value as { kind?: unknown })?.kind)})`); + return; + } + switch (s.type) { + case "string": if (typeof value !== "string") errors.push(`${path}: expected a string`); break; + case "boolean": if (typeof value !== "boolean") errors.push(`${path}: expected a boolean`); break; + case "integer": + if (!Number.isInteger(value)) errors.push(`${path}: expected an integer`); + else if (s.minimum !== undefined && (value as number) < s.minimum) errors.push(`${path}: below ${s.minimum}`); + break; + case "array": + if (!Array.isArray(value)) errors.push(`${path}: expected an array`); + else value.forEach((item, i) => check(item, s.items!, `${path}[${i}]`, errors)); + break; + case "object": { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + errors.push(`${path}: expected an object`); + break; + } + const record = value as Record<string, unknown>; + for (const key of s.required ?? []) if (!(key in record)) errors.push(`${path}: missing ${key}`); + for (const [key, item] of Object.entries(record)) { + const prop = s.properties?.[key]; + if (!prop) { + if (s.additionalProperties === false) errors.push(`${path}: unexpected property ${key}`); + } else check(item, prop, `${path}.${key}`, errors); + } + } + } +} diff --git a/packages/apidocs/tsconfig.json b/packages/apidocs/tsconfig.json new file mode 100644 index 0000000..5216944 --- /dev/null +++ b/packages/apidocs/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "react-jsx", + "jsxImportSource": "preact", + "strict": true, + "noUncheckedIndexedAccess": true, + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "types": ["bun"] + }, + "include": ["src", "scripts", "test", "samples", "*.ts"] +} diff --git a/packages/apidocs/vite.client.config.ts b/packages/apidocs/vite.client.config.ts new file mode 100644 index 0000000..698ae6a --- /dev/null +++ b/packages/apidocs/vite.client.config.ts @@ -0,0 +1,5 @@ +import { defineConfig } from "vite"; +import { bundle } from "./vite.shared.ts"; + +// assets/apidocs.js: the client islands, Preact inlined, loaded with defer. +export default defineConfig(bundle("src/client/islands.tsx", "ApiDocsClient", "apidocs.js", "dist/assets")); diff --git a/packages/apidocs/vite.render.config.ts b/packages/apidocs/vite.render.config.ts new file mode 100644 index 0000000..3587f1d --- /dev/null +++ b/packages/apidocs/vite.render.config.ts @@ -0,0 +1,6 @@ +import { defineConfig } from "vite"; +import { bundle } from "./vite.shared.ts"; + +// render.js: the pure render(model, theme) function, Preact and the highlighter inlined, one classic script that +// defines the global ApiDocs. +export default defineConfig(bundle("src/entry-render.ts", "ApiDocs", "render.js", "dist")); diff --git a/packages/apidocs/vite.shared.ts b/packages/apidocs/vite.shared.ts new file mode 100644 index 0000000..06d4401 --- /dev/null +++ b/packages/apidocs/vite.shared.ts @@ -0,0 +1,19 @@ +import type { UserConfig } from "vite"; + +/** Settings both bundles share: Preact JSX, ES2020 output (GraalJS, Bun, Node and browsers), no CDN, no splitting. */ +export function bundle(entry: string, name: string, fileName: string, outDir: string): UserConfig { + return { + oxc: { jsx: { runtime: "automatic", importSource: "preact" } }, + resolve: { dedupe: ["preact"] }, + build: { + target: "es2020", + outDir, + emptyOutDir: false, + minify: true, + sourcemap: false, + copyPublicDir: false, + lib: { entry, name, formats: ["iife"], fileName: () => fileName }, + }, + logLevel: "warn", + }; +} diff --git a/turbo.json b/turbo.json index 35e33b8..94a87cb 100644 --- a/turbo.json +++ b/turbo.json @@ -40,6 +40,18 @@ "^build" ] }, + "@elide/apidocs#build": { + "dependsOn": ["^build"], + "outputs": ["dist/**"] + }, + "@elide/apidocs#lint": { + "dependsOn": ["^build"] + }, + "@elide/apidocs#test": { + "dependsOn": ["build"], + "cache": false, + "passThroughEnv": ["PLAYWRIGHT_BROWSERS_PATH"] + }, "@elide/elements#test": { "dependsOn": ["build"], "cache": false