import type { ParameterLocation } from "@docspack/lapis"; import { CONSOLE_ATTRIBUTES, SAMPLE_ATTRIBUTES, SAMPLE_LANGUAGE_CHOICE, SAMPLE_LANGUAGE_KEY, } from "./contract.js"; import { buildRequest, type RequestTarget, type RequestValues } from "./request.js"; /** * The try-it console's behaviour — progressive enhancement, not a component. * * A console that sends a request needs state, and the React shell that renders the reference is * required to hold none: a stateful component there forces an Astro island, and cascivo's * per-component CSS does not arrive under `client:load` (see `packages/sheaf-react/CLAUDE.md`). * The resolution is the one the rest of this repository already uses for copy buttons and the * reading-position marker: the markup renders statically and says what the request looks like, and * a small DOM module makes it send. * * That also means the console degrades into something true. With no JavaScript the reader gets a * labelled, filled-in form showing exactly which inputs the endpoint takes and the code samples * beside it — which is what a reference page is for. The Send button is the only thing that needs * the script, and it is disabled until the script has claimed it. * * **The credential is never stored.** It is read from the field at send time and kept in no * variable that outlives the request: not `localStorage`, not `sessionStorage`, not a cookie, not a * closure. A reader who closes the tab has revoked nothing, because nothing was kept. */ /** * Wires every console in `scope`, and returns how many it found. * * The count is returned rather than logged so a caller can assert on it. A page that renders a * console the script never claimed shows a disabled button, which is visible but easy to miss. */ export function mountApiConsoles(scope: ParentNode = document): number { const roots = scope.querySelectorAll(`[${CONSOLE_ATTRIBUTES.root}]`); let mounted = 0; for (const root of roots) { if (mountApiConsole(root)) mounted += 1; } return mounted; } /** Wires one console. Returns false when the markup is not a console this module understands. */ export function mountApiConsole(root: HTMLElement): boolean { const target = readTarget(root); const form = root.querySelector(`[${CONSOLE_ATTRIBUTES.form}]`); if (target === undefined || form === null) return false; const send = root.querySelector(`[${CONSOLE_ATTRIBUTES.send}]`); if (send !== null) send.disabled = false; let inFlight = false; form.addEventListener("submit", (event) => { event.preventDefault(); // A second submit while the first is open would race two responses into one panel, and the // one that renders last is not necessarily the one the reader asked for. if (inFlight) return; inFlight = true; if (send !== null) send.disabled = true; void perform(root, target, readValues(root)).finally(() => { inFlight = false; if (send !== null) send.disabled = false; }); }); return true; } function readTarget(root: HTMLElement): RequestTarget | undefined { const script = root.querySelector(`[${CONSOLE_ATTRIBUTES.target}]`); if (script === null) return undefined; try { const parsed: unknown = JSON.parse(script.textContent ?? ""); // The blob is produced by the renderer next to this module, so the check is a guard against a // stale build rather than against hostile input — but an undefined `path` here would send a // request to the page's own origin, which is worth one `if`. if (typeof parsed !== "object" || parsed === null) return undefined; const candidate = parsed as Partial; if (typeof candidate.method !== "string" || typeof candidate.path !== "string") return undefined; return parsed as RequestTarget; } catch { return undefined; } } function readValues(root: HTMLElement): RequestValues { const path: Record = {}; const query: Record = {}; const header: Record = {}; for (const field of root.querySelectorAll( `[${CONSOLE_ATTRIBUTES.input}]`, )) { const bucket = locationOf(field.getAttribute(CONSOLE_ATTRIBUTES.location)); if (bucket === undefined || field.name.length === 0) continue; const value = field.value.trim(); if (value.length === 0) continue; if (bucket === "path") path[field.name] = value; else if (bucket === "query") query[field.name] = value; else if (bucket === "header") header[field.name] = value; } const body = root.querySelector(`[${CONSOLE_ATTRIBUTES.body}]`); const server = root.querySelector( `[${CONSOLE_ATTRIBUTES.server}]`, ); const credential = root.querySelector(`[${CONSOLE_ATTRIBUTES.credential}]`); return { path, query, header, ...(body === null || body.value.trim().length === 0 ? {} : { body: body.value }), ...(server === null || server.value.length === 0 ? {} : { server: server.value }), ...(credential === null || credential.value.length === 0 ? {} : { credential: credential.value }), }; } function locationOf(raw: string | null): ParameterLocation | undefined { return raw === "path" || raw === "query" || raw === "header" || raw === "cookie" ? raw : undefined; } async function perform( root: HTMLElement, target: RequestTarget, values: RequestValues, ): Promise { const request = buildRequest(target, values); if (request.missing.length > 0) { show(root, `Fill in ${request.missing.join(", ")} first.`, "", "warning"); return; } show(root, "Sending…", "", "neutral"); const started = performance.now(); try { const response = await fetch(request.url, { method: request.method, headers: Object.fromEntries(request.headers), ...(request.body === undefined ? {} : { body: request.body }), }); const elapsed = Math.round(performance.now() - started); const text = await response.text(); show( root, `${response.status} ${response.statusText} · ${elapsed}ms`, prettyJson(text, response.headers.get("content-type")), response.ok ? "success" : "danger", ); } catch (error) { // A failed `fetch` from a documentation page is a CORS rejection far more often than it is a // dead API, and the browser deliberately tells JavaScript nothing about which. Saying so beats // printing "Failed to fetch" and letting the reader conclude their token is wrong. show( root, "Request failed", [ error instanceof Error ? error.message : String(error), "", "The browser blocks a cross-origin request unless the API sends CORS headers for this", "page's origin. The cURL sample beside this console has no such restriction.", ].join("\n"), "danger", ); } } /** JSON is re-indented; anything else is shown as it arrived. */ function prettyJson(text: string, contentType: string | null): string { if (contentType === null || !/\bjson\b/.test(contentType)) return text; try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return text; } } function show(root: HTMLElement, status: string, body: string, tone: string): void { const result = root.querySelector(`[${CONSOLE_ATTRIBUTES.result}]`); const line = root.querySelector(`[${CONSOLE_ATTRIBUTES.status}]`); const panel = root.querySelector(`[${CONSOLE_ATTRIBUTES.response}]`); if (result !== null) { result.hidden = false; result.dataset.tone = tone; } if (line !== null) line.textContent = status; if (panel !== null) panel.textContent = body; } /** * Gives the rendered tab strips their behaviour. * * It does not build them. The markup carries the tabs and the panels, and an inline script sets the * chosen language on the document element before the first paint, so what a reader sees is settled * by the stylesheet and never reflows. What is left for a script is the part markup cannot do: * changing the choice, remembering it, and keeping `aria-selected` honest. * * One click retargets every sample set on the page, because the choice is one attribute in one * place rather than state held per set. * * Returns how many sets are on the page. */ export function mountApiSamples(scope: ParentNode = document): number { const tabs = [...scope.querySelectorAll(`[${SAMPLE_ATTRIBUTES.tab}]`)]; if (tabs.length === 0) return 0; const root = document.documentElement; const languageOf = (tab: Element): string => tab.getAttribute(SAMPLE_ATTRIBUTES.language) ?? ""; /** * One choice, applied everywhere at once. * * Setting the attribute is the whole of the visual switch — the host's stylesheet shows the * matching panel in every sample set on the page from that one change, so a reference with * fourteen operations costs one attribute write rather than fifty-six. */ const choose = (language: string): void => { root.setAttribute(SAMPLE_LANGUAGE_CHOICE, language); try { localStorage.setItem(SAMPLE_LANGUAGE_KEY, language); } catch { // A browser refusing storage still switches; it just forgets by the next page. } for (const tab of tabs) { const selected = languageOf(tab) === language; // `aria-selected`, not a class: the state has to reach a screen reader, and the stylesheet // can read the same attribute. tab.setAttribute("aria-selected", String(selected)); // Roving tabindex, so the strip is one stop and the arrow keys move within it. tab.tabIndex = selected ? 0 : -1; } }; for (const tab of tabs) { tab.addEventListener("click", () => { choose(languageOf(tab)); }); tab.addEventListener("keydown", (event) => { const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0; if (step === 0) return; event.preventDefault(); // Within this strip, not across the page: the strips are copies of one another, so the // neighbour a reader means is the one beside the tab they are on. const strip = tab.closest(`[${SAMPLE_ATTRIBUTES.tablist}]`); const siblings = [ ...(strip?.querySelectorAll(`[${SAMPLE_ATTRIBUTES.tab}]`) ?? []), ]; const next = siblings[(siblings.indexOf(tab) + step + siblings.length) % siblings.length]; if (next === undefined) return; choose(languageOf(next)); next.focus(); }); } /* * The attribute is normally already set — an inline script puts it there before the first paint, * which is the point of it — so this agrees with what is on screen rather than overriding it. * The fallbacks are for a host that renders the samples without that script. */ const stored = ((): string | null => { try { return localStorage.getItem(SAMPLE_LANGUAGE_KEY); } catch { return null; } })(); const known = new Set(tabs.map(languageOf)); const first = tabs[0]; const candidates = [root.getAttribute(SAMPLE_LANGUAGE_CHOICE), stored]; if (first !== undefined) candidates.push(languageOf(first)); const current = candidates.find( (candidate): candidate is string => candidate !== null && known.has(candidate), ); if (current !== undefined) choose(current); return scope.querySelectorAll(`[${SAMPLE_ATTRIBUTES.root}]`).length; }