From 1d593a05cdf6777fdf339749eda4e607387124b8 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 00:27:52 -0400 Subject: [PATCH 01/69] feat(api-reference): render the REST API reference with fumadocs-openapi Throwaway spike, not for merge. The sync converts coder/coder's Swagger 2.0 document to OpenAPI 3 with swagger2openapi, replaces the mainline version's per-tag Markdown pages with one page per operation grouped by tag, and keeps the tag and schemas pages as short lists so existing links still land. The page renders each operation through fumadocs-openapi from a document pruned to that operation, loads its client code only on operation pages, and redirects the old anchors client-side. Assisted-by: AI --- .github/workflows/docs-pr-preview.yml | 5 +- apps/docs/app/[[...slug]]/page.tsx | 2 + apps/docs/app/global.css | 2 + apps/docs/fixtures/docs/manifest.json | 9 + .../docs/fixtures/docs/reference/api/index.md | 16 + .../fixtures/docs/reference/api/schemas.md | 16 + .../docs/fixtures/docs/reference/api/users.md | 23 + .../fixtures/docs/reference/api/workspaces.md | 15 + apps/docs/fixtures/openapi/swagger.json | 125 ++++ apps/docs/lib/openapi.ts | 25 + apps/docs/lib/versioned-shell.tsx | 10 +- apps/docs/package.json | 1 + apps/docs/scripts/openapi-source.mjs | 76 +++ apps/docs/scripts/sync-docs.mjs | 21 +- apps/offlinedocs/app/[[...slug]]/page.tsx | 2 + apps/offlinedocs/app/global.css | 2 + apps/offlinedocs/lib/openapi.ts | 19 + apps/offlinedocs/package.json | 1 + apps/offlinedocs/scripts/sync-docs.mjs | 15 +- packages/docs-build/package.json | 5 +- packages/docs-build/src/index.ts | 6 + packages/docs-build/src/openapi-reference.ts | 294 ++++++++ packages/docs-build/src/vendor.d.ts | 13 + packages/docs-next/package.json | 10 +- packages/docs-next/src/index.ts | 2 +- .../docs-next/src/openapi/anchor-redirect.tsx | 13 + .../docs-next/src/openapi/api-page-lazy.tsx | 6 + packages/docs-next/src/openapi/api-page.tsx | 39 ++ packages/docs-next/src/openapi/index.tsx | 123 ++++ packages/docs-next/src/openapi/tree.ts | 25 + packages/docs-next/src/page.tsx | 33 +- packages/docs-next/src/render-body.tsx | 33 + packages/docs-next/src/shell.tsx | 6 +- packages/docs-next/src/types.ts | 20 + packages/docs-next/src/versioned.tsx | 28 +- pnpm-lock.yaml | 634 +++++++++++++++++- 36 files changed, 1625 insertions(+), 50 deletions(-) create mode 100644 apps/docs/fixtures/docs/reference/api/index.md create mode 100644 apps/docs/fixtures/docs/reference/api/schemas.md create mode 100644 apps/docs/fixtures/docs/reference/api/users.md create mode 100644 apps/docs/fixtures/docs/reference/api/workspaces.md create mode 100644 apps/docs/fixtures/openapi/swagger.json create mode 100644 apps/docs/lib/openapi.ts create mode 100644 apps/docs/scripts/openapi-source.mjs create mode 100644 apps/offlinedocs/lib/openapi.ts create mode 100644 packages/docs-build/src/openapi-reference.ts create mode 100644 packages/docs-build/src/vendor.d.ts create mode 100644 packages/docs-next/src/openapi/anchor-redirect.tsx create mode 100644 packages/docs-next/src/openapi/api-page-lazy.tsx create mode 100644 packages/docs-next/src/openapi/api-page.tsx create mode 100644 packages/docs-next/src/openapi/index.tsx create mode 100644 packages/docs-next/src/openapi/tree.ts create mode 100644 packages/docs-next/src/render-body.tsx diff --git a/.github/workflows/docs-pr-preview.yml b/.github/workflows/docs-pr-preview.yml index fddef9eb..5e9adc16 100644 --- a/.github/workflows/docs-pr-preview.yml +++ b/.github/workflows/docs-pr-preview.yml @@ -178,7 +178,10 @@ jobs: repository: ${{ inputs.content_repository }} ref: ${{ inputs.content_ref }} path: content - sparse-checkout: docs + # coderd/apidoc holds the Swagger document the API reference is built from. + sparse-checkout: | + docs + coderd/apidoc sparse-checkout-cone-mode: true persist-credentials: false diff --git a/apps/docs/app/[[...slug]]/page.tsx b/apps/docs/app/[[...slug]]/page.tsx index 3c40adc1..5a01c269 100644 --- a/apps/docs/app/[[...slug]]/page.tsx +++ b/apps/docs/app/[[...slug]]/page.tsx @@ -1,5 +1,6 @@ import { createVersionedDocs, resolveSlug, seoMetadata, withSeoMetadata } from "@coder/docs-next"; import type { Metadata } from "next"; +import { renderApiReference } from "@/lib/openapi"; import { sourceFor } from "@/lib/sources"; import { versions } from "@/lib/versions"; import { normalizeBasePath } from "../../scripts/single-version.mjs"; @@ -32,6 +33,7 @@ const { // Root-relative image URLs get the same base path Next applies to routes. assetBasePath: basePath, openGraph, + renderBody: renderApiReference, }); // Every version serves the same page at the same slug, so the canonical is the diff --git a/apps/docs/app/global.css b/apps/docs/app/global.css index 9bd5644a..1b0bf8a6 100644 --- a/apps/docs/app/global.css +++ b/apps/docs/app/global.css @@ -1,6 +1,7 @@ @import "tailwindcss"; @import "fumadocs-ui/css/neutral.css"; @import "fumadocs-ui/css/preset.css"; +@import "fumadocs-openapi/css/preset.css"; @import "@coder/docs-theme"; @import "@fontsource-variable/geist"; @@ -13,6 +14,7 @@ * pre-generated CSS only for its own layouts). */ @source "../node_modules/@coder/docs-ui/dist/*.js"; @source "../node_modules/@coder/docs-next/dist/*.js"; +@source "../node_modules/@coder/docs-next/dist/openapi/*.js"; @source "../node_modules/fumadocs-ui/dist/components/ui/popover.js"; /* coder.com's consent manager, present only when DOCS_ANALYTICS is on. The diff --git a/apps/docs/fixtures/docs/manifest.json b/apps/docs/fixtures/docs/manifest.json index 31d05b83..a23fffbd 100644 --- a/apps/docs/fixtures/docs/manifest.json +++ b/apps/docs/fixtures/docs/manifest.json @@ -32,6 +32,15 @@ "state": ["early access", "beta"] } ] + }, + { + "title": "REST API", + "path": "./reference/api/index.md", + "children": [ + { "title": "Users", "path": "./reference/api/users.md" }, + { "title": "Workspaces", "path": "./reference/api/workspaces.md" }, + { "title": "Schemas", "path": "./reference/api/schemas.md" } + ] } ] } diff --git a/apps/docs/fixtures/docs/reference/api/index.md b/apps/docs/fixtures/docs/reference/api/index.md new file mode 100644 index 00000000..fe13f0a8 --- /dev/null +++ b/apps/docs/fixtures/docs/reference/api/index.md @@ -0,0 +1,16 @@ +--- +title: REST API +description: "Reference for the Coder REST API, including endpoints, authentication, and schemas." +--- + +Get started with the Coder API. + +## Quickstart + +List your workspaces: + +```sh +coder tokens create +``` + +Send the token in the `Coder-Session-Token` header of each request. diff --git a/apps/docs/fixtures/docs/reference/api/schemas.md b/apps/docs/fixtures/docs/reference/api/schemas.md new file mode 100644 index 00000000..49eff907 --- /dev/null +++ b/apps/docs/fixtures/docs/reference/api/schemas.md @@ -0,0 +1,16 @@ +--- +title: Schemas +--- + +## codersdk.User + +| Name | Type | Required | Restrictions | Description | +|------------|--------|----------|--------------|-------------| +| `id` | string | false | | | +| `username` | string | false | | | + +## codersdk.WorkspacesResponse + +| Name | Type | Required | Restrictions | Description | +|---------|---------|----------|--------------|-------------| +| `count` | integer | false | | | diff --git a/apps/docs/fixtures/docs/reference/api/users.md b/apps/docs/fixtures/docs/reference/api/users.md new file mode 100644 index 00000000..483a26b4 --- /dev/null +++ b/apps/docs/fixtures/docs/reference/api/users.md @@ -0,0 +1,23 @@ +--- +title: Users +--- + +## Create new user + +`POST /api/v2/users` + +### Responses + +| Status | Meaning | Description | Schema | +|--------|--------------------------------------------------------------|-------------|------------------------------------------| +| 201 | [Created](https://tools.ietf.org/html/rfc7231#section-6.3.2) | Created | [codersdk.User](schemas.md#codersdkuser) | + +## Get user by name + +`GET /api/v2/users/{user}` + +### Responses + +| Status | Meaning | Description | Schema | +|--------|---------------------------------------------------------|-------------|------------------------------------------| +| 200 | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1) | OK | [codersdk.User](schemas.md#codersdkuser) | diff --git a/apps/docs/fixtures/docs/reference/api/workspaces.md b/apps/docs/fixtures/docs/reference/api/workspaces.md new file mode 100644 index 00000000..934d6c81 --- /dev/null +++ b/apps/docs/fixtures/docs/reference/api/workspaces.md @@ -0,0 +1,15 @@ +--- +title: Workspaces +--- + +## List workspaces + +`GET /api/v2/workspaces` + +Returns the workspaces the caller can read, filtered by the search query. + +### Responses + +| Status | Meaning | Description | Schema | +|--------|---------------------------------------------------------|-------------|----------------------------------------------------------------------| +| 200 | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1) | OK | [codersdk.WorkspacesResponse](schemas.md#codersdkworkspacesresponse) | diff --git a/apps/docs/fixtures/openapi/swagger.json b/apps/docs/fixtures/openapi/swagger.json new file mode 100644 index 00000000..d7e63ada --- /dev/null +++ b/apps/docs/fixtures/openapi/swagger.json @@ -0,0 +1,125 @@ +{ + "swagger": "2.0", + "info": { "title": "Coder API", "version": "2.0" }, + "basePath": "/", + "tags": [{ "name": "Workspaces", "description": "Create, list, and manage workspaces." }], + "paths": { + "/api/v2/workspaces": { + "get": { + "security": [{ "CoderSessionToken": [] }], + "produces": ["application/json"], + "tags": ["Workspaces"], + "summary": "List workspaces", + "operationId": "list-workspaces", + "description": "Returns the workspaces the caller can read, filtered by the search query.", + "parameters": [ + { + "type": "string", + "description": "Search query, such as `owner:me`", + "name": "q", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { "$ref": "#/definitions/codersdk.WorkspacesResponse" } + } + } + } + }, + "/api/v2/users": { + "post": { + "security": [{ "CoderSessionToken": [] }], + "consumes": ["application/json"], + "produces": ["application/json"], + "tags": ["Users"], + "summary": "Create new user", + "operationId": "create-new-user", + "parameters": [ + { + "description": "Create user request", + "name": "request", + "in": "body", + "required": true, + "schema": { "$ref": "#/definitions/codersdk.CreateUserRequest" } + } + ], + "responses": { + "201": { "description": "Created", "schema": { "$ref": "#/definitions/codersdk.User" } } + } + } + }, + "/api/v2/users/{user}": { + "get": { + "security": [{ "CoderSessionToken": [] }], + "produces": ["application/json"], + "tags": ["Users"], + "summary": "Get user by name", + "operationId": "get-user-by-name", + "parameters": [ + { + "type": "string", + "description": "User ID, username, or me", + "name": "user", + "in": "path", + "required": true + } + ], + "responses": { + "200": { "description": "OK", "schema": { "$ref": "#/definitions/codersdk.User" } } + } + } + }, + "/api/v2/debug/pprof": { + "get": { + "security": [{ "CoderSessionToken": [] }], + "tags": ["Debug"], + "summary": "Debug pprof index", + "operationId": "debug-pprof-index", + "responses": { "200": { "description": "OK" } }, + "x-apidocgen": { "skip": true } + } + } + }, + "definitions": { + "codersdk.CreateUserRequest": { + "type": "object", + "required": ["email", "username"], + "properties": { + "email": { "type": "string", "format": "email" }, + "username": { "type": "string" } + } + }, + "codersdk.User": { + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "username": { "type": "string" }, + "status": { + "enum": ["active", "suspended"], + "allOf": [{ "$ref": "#/definitions/codersdk.UserStatus" }] + } + } + }, + "codersdk.UserStatus": { "type": "string", "enum": ["active", "suspended"] }, + "codersdk.Workspace": { + "type": "object", + "properties": { + "id": { "type": "string", "format": "uuid" }, + "name": { "type": "string" }, + "owner_name": { "type": "string" } + } + }, + "codersdk.WorkspacesResponse": { + "type": "object", + "properties": { + "count": { "type": "integer" }, + "workspaces": { "type": "array", "items": { "$ref": "#/definitions/codersdk.Workspace" } } + } + } + }, + "securityDefinitions": { + "CoderSessionToken": { "type": "apiKey", "name": "Coder-Session-Token", "in": "header" } + } +} diff --git a/apps/docs/lib/openapi.ts b/apps/docs/lib/openapi.ts new file mode 100644 index 00000000..585bf4a9 --- /dev/null +++ b/apps/docs/lib/openapi.ts @@ -0,0 +1,25 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { type OpenApiPagesData, createOpenApiRenderBody } from "@coder/docs-next/openapi"; + +const cache = new Map>(); + +// Read at render time rather than imported, so the document stays out of the server bundle. +function load(versionId: string | undefined): Promise { + const id = versionId ?? ""; + let cached = cache.get(id); + if (!cached) { + const file = path.join(process.cwd(), ".generated", "openapi", `${id}.json`); + cached = readFile(file, "utf8").then( + (text) => JSON.parse(text) as OpenApiPagesData, + (error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return undefined; + throw error; + }, + ); + cache.set(id, cached); + } + return cached; +} + +export const renderApiReference = createOpenApiRenderBody(load); diff --git a/apps/docs/lib/versioned-shell.tsx b/apps/docs/lib/versioned-shell.tsx index e4a22ccf..ad61d40c 100644 --- a/apps/docs/lib/versioned-shell.tsx +++ b/apps/docs/lib/versioned-shell.tsx @@ -1,7 +1,8 @@ import { latestSource, sourceFor, versionHasSlug } from "@/lib/sources"; import { versions } from "@/lib/versions"; import { analyticsEnabled, stripCodeTitle } from "@coder/docs-config"; -import { DocsShell, resolveSlug, versionSwitcherOptions } from "@coder/docs-next"; +import { DocsShell, resolveSlug, versionBaseUrl, versionSwitcherOptions } from "@coder/docs-next"; +import { collapseFoldersUnder } from "@coder/docs-next/openapi"; import { BetaBanner, CookiePreferencesButton, RuntimeVersionSwitcher } from "@coder/docs-ui"; import type { ReactNode } from "react"; import { @@ -72,9 +73,16 @@ export function VersionedShell({ slug, children }: { slug?: string[]; children: // two share one fetch). Where there is no router, a preview or a raw // deployment URL, the fetch fails and the build-time options stand. const versionsUrl = `${basePath}/versions.json`; + // Operation pages are listed in the sidebar only while reading the API reference. + const inApiReference = resolved?.slug[0] === "reference" && resolved.slug[1] === "api"; + const versionBase = resolved ? versionBaseUrl(resolved.version).replace(/\/$/, "") : ""; + const tree = inApiReference + ? undefined + : collapseFoldersUnder(source.pageTree, `${versionBase}/reference/api/`); return ( path.join(appDir, ".generated", "openapi"); + +/** The Swagger document beside a `docs/` tree on disk, or undefined when there is none. */ +export async function swaggerFromTree(docsRoot) { + const file = process.env.DOCS_OPENAPI_FILE ?? path.join(docsRoot, "..", SWAGGER_PATH); + try { + return JSON.parse(await readFile(file, "utf8")); + } catch (error) { + if (error?.code === "ENOENT") return undefined; + throw error; + } +} + +/** The Swagger document at a ref of the sync's cached clone, or undefined when the ref has none. */ +export async function swaggerFromClone(cacheDir, ref) { + for (const rev of [`refs/remotes/origin/${ref}`, `refs/tags/${ref}`, ref]) { + try { + const { stdout } = await execFileAsync("git", ["-C", cacheDir, "show", `${rev}:${SWAGGER_PATH}`], { + maxBuffer: 64 * 1024 * 1024, + }); + return JSON.parse(stdout); + } catch { + // try the next form of the ref + } + } + return undefined; +} + +/** Which versions render the generated reference: the mainline only, unless DOCS_OPENAPI_VERSIONS=all. */ +export function rendersOpenApi(version, env = process.env) { + if (env.DOCS_OPENAPI === "0") return false; + return env.DOCS_OPENAPI_VERSIONS === "all" || version.latest === true; +} + +export async function clearOpenApi(appDir) { + await rm(openApiDir(appDir), { recursive: true, force: true }); +} + +/** + * Swap the version's Markdown API reference for one page per operation and + * write the data the renderer needs. Returns the source unchanged when there + * is no Swagger document. + */ +export async function withOpenApiReference(appDir, version, source, swagger) { + if (!swagger) { + console.warn(`[sync] ${version.id}: no ${SWAGGER_PATH}; keeping the Markdown API reference`); + return source; + } + const started = Date.now(); + const { source: next, reference } = await applyOpenApiReference(source, swagger); + await mkdir(openApiDir(appDir), { recursive: true }); + await writeFile( + path.join(openApiDir(appDir), `${version.id}.json`), + JSON.stringify({ + document: reference.document, + operations: reference.operations, + anchors: reference.anchors, + }), + ); + console.log( + `[sync] ${version.id}: API reference from ${SWAGGER_PATH}, ${Object.keys(reference.operations).length} operation pages in ${Date.now() - started} ms`, + ); + for (const warning of reference.warnings) console.warn(`[sync] ${version.id}: openapi: ${warning}`); + return next; +} diff --git a/apps/docs/scripts/sync-docs.mjs b/apps/docs/scripts/sync-docs.mjs index d2ae9858..804a0c99 100644 --- a/apps/docs/scripts/sync-docs.mjs +++ b/apps/docs/scripts/sync-docs.mjs @@ -31,6 +31,13 @@ import { releaseSchedulePath, slugManifestPath, } from "./sync-helpers.mjs"; +import { + clearOpenApi, + rendersOpenApi, + swaggerFromClone, + swaggerFromTree, + withOpenApiReference, +} from "./openapi-source.mjs"; import { readVersionRedirects } from "./version-redirects.mjs"; const execFileAsync = promisify(execFile); @@ -62,6 +69,11 @@ async function ensureFixtureRepo() { path.join(repo, "docs", "README.md"), `# About\n\nFixture corpus at **${marker}**.\n\nRefer to [administration](./admin/index.md), and see the ![logo](./images/logo.svg).\n`, ); + await mkdir(path.join(repo, "coderd", "apidoc"), { recursive: true }); + await cp( + path.join(appDir, "fixtures", "openapi", "swagger.json"), + path.join(repo, "coderd", "apidoc", "swagger.json"), + ); await git(repo, ["add", "-A"]); await git(repo, ["commit", "-m", `docs at ${marker}`, "--allow-empty"], { GIT_AUTHOR_DATE: date, @@ -108,6 +120,7 @@ await rm(slugManifestPath(appDir), { force: true }); await rm(imageSizesPath(appDir), { force: true }); await rm(lastModifiedPath(appDir), { force: true }); await rm(releaseSchedulePath(appDir), { force: true }); +await clearOpenApi(appDir); // Latest syncs last: images share one unversioned public/, so the version // synced last wins path collisions, and that must be the pinned release. @@ -120,7 +133,13 @@ for (const version of latestLastSyncOrder(versions)) { const { strict } = resolveVersionPipeline(version); let result; try { - const source = await provider.loadVersion(version); + let source = await provider.loadVersion(version); + if (rendersOpenApi(version)) { + const swagger = single + ? await swaggerFromTree(process.env.DOCS_ROOT) + : await swaggerFromClone(cacheDir, version.ref); + source = await withOpenApiReference(appDir, version, source, swagger); + } result = await syncDocSource(source, { contentDir: path.join(appDir, "content", version.id), publicDir: path.join(appDir, "public"), diff --git a/apps/offlinedocs/app/[[...slug]]/page.tsx b/apps/offlinedocs/app/[[...slug]]/page.tsx index 1bce0aeb..43dac20c 100644 --- a/apps/offlinedocs/app/[[...slug]]/page.tsx +++ b/apps/offlinedocs/app/[[...slug]]/page.tsx @@ -1,4 +1,5 @@ import { createDocsPage } from "@coder/docs-next"; +import { renderApiReference } from "@/lib/openapi"; import { source } from "@/lib/source"; const { Page, generateStaticParams, generateMetadata } = createDocsPage(source, { @@ -7,6 +8,7 @@ const { Page, generateStaticParams, generateMetadata } = createDocsPage(source, // link, whose every link is to a service on the public internet. pageActions: { viewOptions: false }, editLink: false, + renderBody: renderApiReference, }); export default Page; diff --git a/apps/offlinedocs/app/global.css b/apps/offlinedocs/app/global.css index a14036a7..2f9d040a 100644 --- a/apps/offlinedocs/app/global.css +++ b/apps/offlinedocs/app/global.css @@ -1,6 +1,7 @@ @import "tailwindcss"; @import "fumadocs-ui/css/neutral.css"; @import "fumadocs-ui/css/preset.css"; +@import "fumadocs-openapi/css/preset.css"; @import "@coder/docs-theme"; @import "@fontsource-variable/geist"; @@ -13,4 +14,5 @@ * pre-generated CSS only for its own layouts). */ @source "../node_modules/@coder/docs-ui/dist/*.js"; @source "../node_modules/@coder/docs-next/dist/*.js"; +@source "../node_modules/@coder/docs-next/dist/openapi/*.js"; @source "../node_modules/fumadocs-ui/dist/components/ui/popover.js"; diff --git a/apps/offlinedocs/lib/openapi.ts b/apps/offlinedocs/lib/openapi.ts new file mode 100644 index 00000000..d3a09684 --- /dev/null +++ b/apps/offlinedocs/lib/openapi.ts @@ -0,0 +1,19 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { type OpenApiPagesData, createOpenApiRenderBody } from "@coder/docs-next/openapi"; + +let cached: Promise | undefined; + +// Read at render time rather than imported, so the document stays out of the server bundle. +function load(): Promise { + cached ??= readFile(path.join(process.cwd(), ".generated", "openapi", "main.json"), "utf8").then( + (text) => JSON.parse(text) as OpenApiPagesData, + (error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return undefined; + throw error; + }, + ); + return cached; +} + +export const renderApiReference = createOpenApiRenderBody(load); diff --git a/apps/offlinedocs/package.json b/apps/offlinedocs/package.json index 57bc96df..ed986d00 100644 --- a/apps/offlinedocs/package.json +++ b/apps/offlinedocs/package.json @@ -32,6 +32,7 @@ "@fontsource-variable/geist-mono": "5.3.0", "fumadocs-core": "catalog:", "fumadocs-mdx": "catalog:", + "fumadocs-openapi": "12.5.4", "fumadocs-ui": "catalog:", "next": "catalog:", "react": "catalog:", diff --git a/apps/offlinedocs/scripts/sync-docs.mjs b/apps/offlinedocs/scripts/sync-docs.mjs index 6d066605..14dbafea 100644 --- a/apps/offlinedocs/scripts/sync-docs.mjs +++ b/apps/offlinedocs/scripts/sync-docs.mjs @@ -17,6 +17,12 @@ import { fileURLToPath } from "node:url"; import { syncDocSource, writeReleaseSchedule } from "@coder/docs-build"; import { parseReleaseSchedule } from "@coder/docs-config"; import { createGitRefsProvider, createLocalTreeProvider } from "@coder/docs-sources"; +import { + clearOpenApi, + swaggerFromClone, + swaggerFromTree, + withOpenApiReference, +} from "../../docs/scripts/openapi-source.mjs"; import { assertDeployHasCorpus, githubBlobSourceLink, redactRepoUrl } from "./sync-helpers.mjs"; const appDir = path.dirname(path.dirname(fileURLToPath(import.meta.url))); @@ -52,7 +58,14 @@ if (process.env.DOCS_ROOT) { console.log("[sync] corpus: committed fixture (set DOCS_ROOT or DOCS_REPO for the real corpus)"); } -const source = await provider.loadVersion(version); +await clearOpenApi(appDir); +let source = await provider.loadVersion(version); +if (process.env.DOCS_ROOT || process.env.DOCS_REPO) { + const swagger = process.env.DOCS_ROOT + ? await swaggerFromTree(process.env.DOCS_ROOT) + : await swaggerFromClone(path.join(appDir, ".cache", "docs-clone"), version.ref); + source = await withOpenApiReference(appDir, version, source, swagger); +} const result = await syncDocSource(source, { contentDir: path.join(appDir, "content", "docs"), publicDir: path.join(appDir, "public"), diff --git a/packages/docs-build/package.json b/packages/docs-build/package.json index 462abb2a..ea02b6cb 100644 --- a/packages/docs-build/package.json +++ b/packages/docs-build/package.json @@ -25,7 +25,10 @@ "dependencies": { "@coder/docs-config": "workspace:*", "@coder/docs-transforms": "workspace:*", - "@fumari/image-size": "0.1.1" + "@fumari/image-size": "0.1.1", + "github-slugger": "2.0.0", + "oas-validator": "5.0.8", + "swagger2openapi": "7.0.8" }, "devDependencies": { "@mdx-js/mdx": "3.1.1", diff --git a/packages/docs-build/src/index.ts b/packages/docs-build/src/index.ts index 98517ef5..d67e4b60 100644 --- a/packages/docs-build/src/index.ts +++ b/packages/docs-build/src/index.ts @@ -9,3 +9,9 @@ export { reservedAssetReason, reservedRouteReason, } from "./reserved-routes.js"; +export { applyOpenApiReference, convertSwagger, tagSlug } from "./openapi-reference.js"; +export type { + ApplyOpenApiReferenceOptions, + OpenApiOperationRef, + OpenApiReference, +} from "./openapi-reference.js"; diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts new file mode 100644 index 00000000..81060672 --- /dev/null +++ b/packages/docs-build/src/openapi-reference.ts @@ -0,0 +1,294 @@ +import type { DocFile, DocSource, ManifestNode } from "@coder/docs-config"; +import { buildDirRoutes, mapMdPath } from "@coder/docs-transforms"; +import GithubSlugger from "github-slugger"; +import { validate } from "oas-validator"; +import { convertObj } from "swagger2openapi"; + +type Json = Record; + +export interface OpenApiOperationRef { + method: string; + path: string; +} + +/** + * The REST API reference built from coder/coder's Swagger 2.0 document: the + * OpenAPI 3 document the pages render from, the page route of every + * operation, and the old single-page anchors each tag page and the schemas + * page redirect to. + */ +export interface OpenApiReference { + document: Json; + operations: Record; + anchors: Record>; + warnings: string[]; +} + +export interface ApplyOpenApiReferenceOptions { + /** The docs-relative directory of the generated reference; defaults to `reference/api`. */ + dir?: string; + /** The server URL template the try-it panel sends to; the reader fills in `{deployment}`. */ + server?: { url: string; variables?: Record }; +} + +const METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"] as const; + +const isObject = (value: unknown): value is Json => + typeof value === "object" && value !== null && !Array.isArray(value); + +export const tagSlug = (tag: string): string => tag.toLowerCase().replace(/[^a-z0-9]/g, ""); + +const cell = (text: string): string => text.replace(/\|/g, "\\|").replace(/\s+/g, " ").trim(); + +const frontmatter = (title: string): string => `---\ntitle: ${JSON.stringify(title)}\n---\n\n`; + +function collectRefs(value: unknown, into: Set): void { + if (Array.isArray(value)) { + for (const item of value) collectRefs(item, into); + } else if (isObject(value)) { + for (const [key, child] of Object.entries(value)) { + if (key === "$ref" && typeof child === "string") into.add(child); + else collectRefs(child, into); + } + } +} + +const SCHEMA_REF = "#/components/schemas/"; + +/** Each schema an operation reaches, with how many `$ref` hops away it is. */ +function schemaDepths(roots: unknown, schemas: Json): Map { + const depths = new Map(); + let frontier = new Set(); + collectRefs(roots, frontier); + for (let depth = 0; frontier.size > 0; depth++) { + const next = new Set(); + for (const ref of frontier) { + if (!ref.startsWith(SCHEMA_REF)) continue; + const name = ref.slice(SCHEMA_REF.length); + if (depths.has(name)) continue; + depths.set(name, depth); + collectRefs(schemas[name], next); + } + frontier = next; + } + return depths; +} + +/** Converts Swagger 2.0 to OpenAPI 3, repairs the defects that make it invalid, and validates it. */ +export async function convertSwagger(swagger: unknown): Promise<{ document: Json; warnings: string[] }> { + const warnings: string[] = []; + const converted = await convertObj(swagger, { patch: true, warnOnly: true }); + const document = converted.openapi; + if (converted.patches) warnings.push(`swagger2openapi patched ${converted.patches} defect(s)`); + for (const warning of converted.warnings ?? []) warnings.push(`swagger2openapi: ${JSON.stringify(warning)}`); + + const components = isObject(document.components) ? document.components : {}; + const schemes = isObject(components.securitySchemes) ? components.securitySchemes : {}; + for (const [route, item] of Object.entries(isObject(document.paths) ? document.paths : {})) { + if (!isObject(item)) continue; + for (const method of METHODS) { + const operation = item[method]; + if (!isObject(operation)) continue; + if (Array.isArray(operation.security)) { + operation.security = operation.security.filter((requirement) => { + const unknown = Object.keys(isObject(requirement) ? requirement : {}).filter( + (name) => !(name in schemes), + ); + for (const name of unknown) { + warnings.push(`${method.toUpperCase()} ${route}: security scheme ${name} is not defined; dropped`); + } + return unknown.length === 0; + }); + } + if (Array.isArray(operation.parameters)) { + operation.parameters = operation.parameters.filter((parameter) => { + if (!isObject(parameter) || parameter.in !== "path") return true; + if (route.includes(`{${String(parameter.name)}}`)) return true; + warnings.push( + `${method.toUpperCase()} ${route}: path parameter ${String(parameter.name)} is not in the path; dropped`, + ); + return false; + }); + } + } + } + + const result = await validate(document, { lint: false, prettify: false, warnOnly: true }); + if (!result.valid) throw new Error("the converted OpenAPI document is not valid"); + return { document, warnings }; +} + +/** + * Replaces the generated single-page-per-tag API reference in a version's + * `DocSource` with one page per operation, grouped by tag, rendered from the + * version's Swagger document. `reference/api/index.md` is kept. Each tag page + * becomes a list of its endpoints and the schemas page a list of schemas with + * the endpoint that uses each, so links to either still land; the old anchors + * are returned for a client-side redirect. + */ +export async function applyOpenApiReference( + source: DocSource, + swagger: unknown, + options: ApplyOpenApiReferenceOptions = {}, +): Promise<{ source: DocSource; reference: OpenApiReference }> { + const dir = options.dir ?? "reference/api"; + const { document, warnings } = await convertSwagger(swagger); + document.servers = [ + options.server ?? { + url: "{deployment}", + variables: { + deployment: { + default: "https://coder.example.com", + description: "The URL of your Coder deployment", + }, + }, + }, + ]; + + const paths = isObject(document.paths) ? document.paths : {}; + const components = isObject(document.components) ? document.components : {}; + const schemas = isObject(components.schemas) ? components.schemas : {}; + const tagInfo = new Map(); + for (const tag of Array.isArray(document.tags) ? document.tags : []) { + if (isObject(tag) && typeof tag.name === "string") { + tagInfo.set(tag.name, typeof tag.description === "string" ? tag.description : undefined); + } + } + + interface Op { + method: string; + path: string; + summary: string; + description?: string; + deprecated: boolean; + file: string; + depths: Map; + } + const byTag = new Map(); + for (const [route, item] of Object.entries(paths)) { + if (!isObject(item)) continue; + for (const method of METHODS) { + const operation = item[method]; + if (!isObject(operation)) continue; + const apidocgen = operation["x-apidocgen"]; + if (isObject(apidocgen) && apidocgen.skip === true) continue; + const tag = + Array.isArray(operation.tags) && typeof operation.tags[0] === "string" + ? operation.tags[0] + : "General"; + let group = byTag.get(tag); + if (!group) byTag.set(tag, (group = { slugger: new GithubSlugger(), ops: [] })); + const summary = + typeof operation.summary === "string" ? operation.summary : `${method.toUpperCase()} ${route}`; + group.ops.push({ + method, + path: route, + summary, + description: typeof operation.description === "string" ? operation.description : undefined, + deprecated: operation.deprecated === true, + file: `${dir}/${tagSlug(tag)}/${group.slugger.slug(summary)}.md`, + depths: schemaDepths([operation, item.parameters], schemas), + }); + } + } + + const generated = new Map(); + const tagFile = (tag: string) => `${dir}/${tagSlug(tag)}.md`; + for (const [tag, { ops }] of byTag) { + const rows = ops.map( + (op) => + `| [${cell(op.summary)}](./${op.file.slice(dir.length + 1)}) | \`${op.method.toUpperCase()} ${op.path}\` |`, + ); + const description = tagInfo.get(tag); + generated.set( + tagFile(tag), + `${frontmatter(tag)}${description ? `${description}\n\n` : ""}| Endpoint | Request |\n| --- | --- |\n${rows.join("\n")}\n`, + ); + for (const op of ops) { + const lines = [`\`${op.method.toUpperCase()} ${op.path}\``]; + if (op.deprecated) lines.push("This endpoint is deprecated."); + if (op.description) lines.push(op.description); + generated.set(op.file, `${frontmatter(op.summary)}${lines.join("\n\n")}\n`); + } + } + + const allOps = [...byTag.values()].flatMap((group) => group.ops); + const schemaRows: string[] = []; + const schemaTargets = new Map(); + const schemaSlugger = new GithubSlugger(); + const schemaAnchors: Record = {}; + for (const name of Object.keys(schemas)) { + let best: Op | undefined; + let bestDepth = Number.POSITIVE_INFINITY; + for (const op of allOps) { + const depth = op.depths.get(name); + if (depth !== undefined && depth < bestDepth) { + best = op; + bestDepth = depth; + } + } + const anchor = schemaSlugger.slug(name); + if (best) { + schemaTargets.set(anchor, best); + schemaRows.push(`| \`${name}\` | [${cell(best.summary)}](./${best.file.slice(dir.length + 1)}) |`); + } else { + schemaRows.push(`| \`${name}\` | Not used by a documented endpoint |`); + } + } + const schemasFile = `${dir}/schemas.md`; + generated.set( + schemasFile, + `${frontmatter("Schemas")}Each endpoint's page documents the request and response schemas it uses. This table names, for each schema, the endpoint page that shows it most directly.\n\n| Schema | Shown on |\n| --- | --- |\n${schemaRows.join("\n")}\n`, + ); + + const files: DocFile[] = [ + ...source.files.filter((file) => !generated.has(file.path)), + ...[...generated].map(([path, content]) => ({ path, content })), + ]; + + const manifestPath = (file: string) => `./${file}`; + const routes = structuredClone(source.manifest.routes); + const findNode = (nodes: ManifestNode[]): ManifestNode | undefined => { + for (const node of nodes) { + if (node.path === manifestPath(`${dir}/index.md`)) return node; + const found = node.children && findNode(node.children); + if (found) return found; + } + return undefined; + }; + const apiNode = findNode(routes); + if (!apiNode) throw new Error(`the manifest has no ${dir}/index.md node`); + const children = apiNode.children ?? []; + for (const [tag, { ops }] of byTag) { + const opChildren = ops.map((op) => ({ title: op.summary, path: manifestPath(op.file) })); + const existing = children.find((child) => child.path === manifestPath(tagFile(tag))); + if (existing) existing.children = opChildren; + else { + warnings.push(`tag ${tag} has no manifest entry; appended`); + children.push({ title: tag, path: manifestPath(tagFile(tag)), children: opChildren }); + } + } + apiNode.children = children; + + const mdPaths = files.map((file) => file.path).filter((path) => path.endsWith(".md")); + const dirRoutes = buildDirRoutes(mdPaths); + const routeOf = (file: string) => mapMdPath(file, dirRoutes).route; + const operations: Record = {}; + const anchors: Record> = {}; + for (const [tag, { ops }] of byTag) { + const tagAnchors: Record = {}; + for (const op of ops) { + const route = routeOf(op.file); + operations[route] = { method: op.method, path: op.path }; + tagAnchors[route.slice(route.lastIndexOf("/") + 1)] = route; + } + anchors[routeOf(tagFile(tag))] = tagAnchors; + } + for (const [anchor, op] of schemaTargets) schemaAnchors[anchor] = routeOf(op.file); + anchors[routeOf(schemasFile)] = schemaAnchors; + + return { + source: { ...source, files, manifest: { ...source.manifest, routes } }, + reference: { document, operations, anchors, warnings }, + }; +} diff --git a/packages/docs-build/src/vendor.d.ts b/packages/docs-build/src/vendor.d.ts new file mode 100644 index 00000000..f2ffc6ae --- /dev/null +++ b/packages/docs-build/src/vendor.d.ts @@ -0,0 +1,13 @@ +declare module "swagger2openapi" { + export function convertObj( + swagger: unknown, + options: Record, + ): Promise<{ openapi: Record; patches?: number; warnings?: unknown[] }>; +} + +declare module "oas-validator" { + export function validate( + openapi: unknown, + options: Record, + ): Promise<{ valid: boolean; warnings?: unknown[] }>; +} diff --git a/packages/docs-next/package.json b/packages/docs-next/package.json index f1eed4b0..0e9d2ab2 100644 --- a/packages/docs-next/package.json +++ b/packages/docs-next/package.json @@ -19,6 +19,10 @@ "./semantic-search": { "types": "./dist/semantic-search.d.ts", "default": "./dist/semantic-search.js" + }, + "./openapi": { + "types": "./dist/openapi/index.d.ts", + "default": "./dist/openapi/index.js" } }, "files": [ @@ -35,8 +39,10 @@ "@coder/docs-manifest": "workspace:*", "@coder/docs-ui": "workspace:*", "fumadocs-core": "catalog:", + "fumadocs-openapi": "12.5.4", "fumadocs-ui": "catalog:", - "lucide-react": "1.46.0" + "lucide-react": "1.46.0", + "shiki": "4.4.3" }, "peerDependencies": { "next": ">=16", @@ -47,10 +53,10 @@ "@coder/docs-transforms": "workspace:*", "@mdx-js/mdx": "3.1.1", "@types/mdx": "2.0.14", - "fumadocs-mdx": "catalog:", "@types/node": "^22", "@types/react": "catalog:", "@types/react-dom": "catalog:", + "fumadocs-mdx": "catalog:", "jsdom": "25.0.1", "next": "catalog:", "react": "catalog:", diff --git a/packages/docs-next/src/index.ts b/packages/docs-next/src/index.ts index 16427878..51f4e8e1 100644 --- a/packages/docs-next/src/index.ts +++ b/packages/docs-next/src/index.ts @@ -92,7 +92,7 @@ export type { PageTocOptions } from "./toc.js"; export { coderFaviconIcons, coderFaviconIconsFor } from "./favicons.js"; export { screenshotBackdropStyle } from "./screenshot-backdrop.js"; export type { ScreenshotBackdropStyle } from "./screenshot-backdrop.js"; -export type { DocsSource } from "./types.js"; +export type { DocsSource, RenderBody, RenderBodyContext } from "./types.js"; export { createVersionedDocs } from "./versioned.js"; export type { DocsRenderMode, VersionedDocsOptions } from "./versioned.js"; export { diff --git a/packages/docs-next/src/openapi/anchor-redirect.tsx b/packages/docs-next/src/openapi/anchor-redirect.tsx new file mode 100644 index 00000000..48c981ce --- /dev/null +++ b/packages/docs-next/src/openapi/anchor-redirect.tsx @@ -0,0 +1,13 @@ +"use client"; + +import { useEffect } from "react"; + +/** Sends a link to an anchor of the old single-page reference on to the page that replaced it. */ +export function AnchorRedirect({ targets }: { targets: Record }) { + useEffect(() => { + const anchor = decodeURIComponent(window.location.hash.slice(1)); + const target = anchor ? targets[anchor] : undefined; + if (target) window.location.replace(target); + }, [targets]); + return null; +} diff --git a/packages/docs-next/src/openapi/api-page-lazy.tsx b/packages/docs-next/src/openapi/api-page-lazy.tsx new file mode 100644 index 00000000..02d3b29b --- /dev/null +++ b/packages/docs-next/src/openapi/api-page-lazy.tsx @@ -0,0 +1,6 @@ +"use client"; + +import dynamic from "next/dynamic"; + +// Its own chunk, so only the pages that render an operation load fumadocs-openapi. +export const ApiPage = dynamic(() => import("./api-page.js").then((module) => module.ApiPage)); diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx new file mode 100644 index 00000000..9d84a7f1 --- /dev/null +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -0,0 +1,39 @@ +"use client"; + +import { createShikiFactory } from "fumadocs-core/highlight/shiki"; +import { createCodeUsageGeneratorRegistry } from "fumadocs-openapi/requests/generators"; +import { curl } from "fumadocs-openapi/requests/generators/curl"; +import { createOpenAPIPageBase } from "fumadocs-openapi/ui/base"; + +// Only the grammars and themes an API page uses (JSON, the cURL sample, TypeScript definitions), on the JavaScript regex engine (no WASM, no eval). +const shiki = createShikiFactory({ + async init() { + const [{ createHighlighterCore }, { createJavaScriptRegexEngine }] = await Promise.all([ + import("shiki/core"), + import("shiki/engine/javascript"), + ]); + return createHighlighterCore({ + engine: createJavaScriptRegexEngine(), + langs: [ + import("shiki/langs/json.mjs"), + import("shiki/langs/shellscript.mjs"), + import("shiki/langs/typescript.mjs"), + ], + themes: [ + import("shiki/themes/github-light-high-contrast.mjs"), + import("shiki/themes/github-dark-default.mjs"), + ], + }); + }, +}); + +const codeUsages = createCodeUsageGeneratorRegistry(); +codeUsages.add("curl", curl); + +/** One REST API operation, rendered by fumadocs-openapi from the document its page was given. */ +export const ApiPage = createOpenAPIPageBase({ + shiki, + shikiOptions: { themes: { light: "github-light-high-contrast", dark: "github-dark-default" } }, + codeUsages, + storageKeyPrefix: "coder-api-", +}); diff --git a/packages/docs-next/src/openapi/index.tsx b/packages/docs-next/src/openapi/index.tsx new file mode 100644 index 00000000..e4856348 --- /dev/null +++ b/packages/docs-next/src/openapi/index.tsx @@ -0,0 +1,123 @@ +import type { Document } from "fumadocs-openapi"; +import { createOpenAPI } from "fumadocs-openapi/server"; +import type { RenderBody } from "../types.js"; +import { AnchorRedirect } from "./anchor-redirect.js"; +import { ApiPage } from "./api-page-lazy.js"; + +type Json = Record; + +/** What the sync's `applyOpenApiReference` writes for one version. */ +export interface OpenApiPagesData { + document: Json; + operations: Record; + anchors: Record>; +} + +const isObject = (value: unknown): value is Json => + typeof value === "object" && value !== null && !Array.isArray(value); + +function collectRefs(value: unknown, into: Set): void { + if (Array.isArray(value)) for (const item of value) collectRefs(item, into); + else if (isObject(value)) { + for (const [key, child] of Object.entries(value)) { + if (key === "$ref" && typeof child === "string") into.add(child); + else collectRefs(child, into); + } + } +} + +/** + * The document cut down to one operation and the components it reaches, so a + * page's props carry only what that page renders, not the whole API. + */ +export function pruneDocument(document: Json, path: string, method: string): Json { + const paths = document.paths as Record; + const item = paths[path]; + if (!item || !isObject(item[method])) throw new Error(`no ${method} ${path} in the API document`); + const components = (document.components ?? {}) as Record; + const kept: Record = { securitySchemes: components.securitySchemes ?? {} }; + const pathItem: Json = { [method]: item[method] }; + if (item.parameters) pathItem.parameters = item.parameters; + const seen = new Set(); + let frontier = new Set(); + collectRefs(pathItem, frontier); + while (frontier.size > 0) { + const next = new Set(); + for (const ref of frontier) { + if (seen.has(ref) || !ref.startsWith("#/components/")) continue; + seen.add(ref); + const [kind, name] = ref.slice("#/components/".length).split("/") as [string, string]; + const value = components[kind]?.[name]; + if (value === undefined) continue; + (kept[kind] ??= {})[name] = value; + collectRefs(value, next); + } + frontier = next; + } + const info = (document.info ?? {}) as Json; + return { + openapi: document.openapi, + info: { title: info.title, version: info.version }, + servers: document.servers, + ...(document.security ? { security: document.security } : {}), + paths: { [path]: pathItem }, + components: kept, + }; +} + +/** + * The page-body hook that renders a version's REST API reference: each + * operation page through fumadocs-openapi, and the old anchor redirect on the + * tag and schemas pages. `load` returns a version's data, or `undefined` for + * a version that keeps its Markdown reference. + */ +export function createOpenApiRenderBody( + load: (versionId: string | undefined) => Promise, +): RenderBody { + const bundled = new Map>(); + const bundle = (versionId: string | undefined, document: Json): Promise => { + let cached = bundled.get(versionId); + if (!cached) { + const server = createOpenAPI({ input: { coder: () => document as Document } }); + cached = server.getSchema("coder").then((schema) => schema.bundled as Json); + bundled.set(versionId, cached); + } + return cached; + }; + + return async ({ versionId, slugs, hrefFor }) => { + const data = await load(versionId); + if (!data) return undefined; + const route = slugs.join("/"); + const operation = data.operations[route]; + if (operation) { + const document = pruneDocument( + await bundle(versionId, data.document), + operation.path, + operation.method, + ); + return { + full: true, + replace: ( + + ), + }; + } + const anchors = data.anchors[route]; + if (!anchors) return undefined; + const targets: Record = {}; + for (const [anchor, target] of Object.entries(anchors)) { + const href = hrefFor(target); + if (href) targets[anchor] = href; + } + return { after: }; + }; +} + +export { collapseFoldersUnder } from "./tree.js"; diff --git a/packages/docs-next/src/openapi/tree.ts b/packages/docs-next/src/openapi/tree.ts new file mode 100644 index 00000000..02d3d8db --- /dev/null +++ b/packages/docs-next/src/openapi/tree.ts @@ -0,0 +1,25 @@ +import type * as PageTree from "fumadocs-core/page-tree"; + +// The same tree object for every render, so the flight payload dedupes it like the uncollapsed one. +const collapsed = new WeakMap>(); + +/** + * The page tree with each folder under `urlPrefix` reduced to its index page, + * so pages outside the API reference don't carry hundreds of operation links + * in their sidebar payload. Folders without an index page are left as they are. + */ +export function collapseFoldersUnder(tree: PageTree.Root, urlPrefix: string): PageTree.Root { + let byPrefix = collapsed.get(tree); + if (!byPrefix) collapsed.set(tree, (byPrefix = new Map())); + const cached = byPrefix.get(urlPrefix); + if (cached) return cached; + const visit = (nodes: PageTree.Node[]): PageTree.Node[] => + nodes.map((node) => { + if (node.type !== "folder") return node; + if (node.index && node.index.url.startsWith(urlPrefix)) return node.index; + return { ...node, children: visit(node.children) }; + }); + const result = { ...tree, children: visit(tree.children) }; + byPrefix.set(urlPrefix, result); + return result; +} diff --git a/packages/docs-next/src/page.tsx b/packages/docs-next/src/page.tsx index dc55f1af..34aa6e08 100644 --- a/packages/docs-next/src/page.tsx +++ b/packages/docs-next/src/page.tsx @@ -8,7 +8,8 @@ import { markdownTwinUrl } from "./llms.js"; import { type OpenGraphOptions, openGraphMetadata, sectionBadge } from "./open-graph.js"; import type { PageActionsOption } from "./page-actions.js"; import { pageNeighbours } from "./slim-tree.js"; -import type { DocsSource } from "./types.js"; +import { resolveBody } from "./render-body.js"; +import type { DocsSource, RenderBody } from "./types.js"; // The route renders an optional catch-all (`[[...slug]]`), so `slug` is // `undefined` at the index and a path-segment array elsewhere. A Next app reads @@ -46,6 +47,8 @@ export interface DocsPageOptions { * what an export whose readers cannot reach the image generator wants. */ openGraph?: OpenGraphOptions; + /** Replaces or extends a page's rendered body; refer to `RenderBody`. */ + renderBody?: RenderBody; } export function createDocsPage(source: DocsSource, options: DocsPageOptions = {}) { @@ -55,10 +58,26 @@ export function createDocsPage(source: DocsSource, options: DocsPageOptions = {} if (!page) notFound(); const MDX = page.data.body; + const { body, full } = await resolveBody( + options.renderBody, + source, + undefined, + page.slugs, + options.assetBasePath, + , + ); return ( - + {body} ); } diff --git a/packages/docs-next/src/render-body.tsx b/packages/docs-next/src/render-body.tsx new file mode 100644 index 00000000..562e55cc --- /dev/null +++ b/packages/docs-next/src/render-body.tsx @@ -0,0 +1,33 @@ +import type { ReactNode } from "react"; +import type { DocsSource, RenderBody } from "./types.js"; +import { normalizeBasePath } from "./version-routing.js"; + +/** The page body after an optional `renderBody` hook has had its say, and whether the page goes full width. */ +export async function resolveBody( + renderBody: RenderBody | undefined, + source: DocsSource, + versionId: string | undefined, + slugs: string[], + assetBasePath: string | undefined, + markdown: ReactNode, +): Promise<{ body: ReactNode; full?: boolean }> { + const custom = await renderBody?.({ + versionId, + slugs, + hrefFor: (route) => { + const url = source.getPage(route.split("/"))?.url; + if (url === undefined) return undefined; + return `${normalizeBasePath(assetBasePath)}${url.endsWith("/") ? url : `${url}/`}`; + }, + }); + if (!custom) return { body: markdown }; + return { + body: ( + <> + {custom.replace ?? markdown} + {custom.after} + + ), + full: custom.full, + }; +} diff --git a/packages/docs-next/src/shell.tsx b/packages/docs-next/src/shell.tsx index 53565269..d842d41f 100644 --- a/packages/docs-next/src/shell.tsx +++ b/packages/docs-next/src/shell.tsx @@ -1,3 +1,4 @@ +import type * as PageTree from "fumadocs-core/page-tree"; import { Copyright, type DocsContextSource } from "@coder/docs-ui"; import { DocsLayout } from "fumadocs-ui/layouts/docs"; import type { BaseLayoutProps } from "fumadocs-ui/layouts/shared"; @@ -50,8 +51,11 @@ export function DocsShell({ sidebarFooter, context, providerOptions, + tree, }: { source: DocsSource; + /** The sidebar tree, when it differs from the source's own page tree. */ + tree?: PageTree.Root; children: ReactNode; options?: Partial; /** @@ -128,7 +132,7 @@ export function DocsShell({
{topBanner}
string; }; + +/** What a page-body hook is told about the page it may render. */ +export interface RenderBodyContext { + /** The version being rendered; `undefined` under the single-version factory. */ + versionId: string | undefined; + /** The page's slugs within its version. */ + slugs: string[]; + /** The href of another page of the same version, base path included. */ + hrefFor: (route: string) => string | undefined; +} + +/** + * Replaces a page's rendered Markdown body (`replace`) or adds after it + * (`after`); `full` widens the page and drops its table of contents. + * `undefined` leaves the page as it is. + */ +export type RenderBody = ( + context: RenderBodyContext, +) => Promise<{ replace?: ReactNode; after?: ReactNode; full?: boolean } | undefined>; diff --git a/packages/docs-next/src/versioned.tsx b/packages/docs-next/src/versioned.tsx index e497d424..f800d352 100644 --- a/packages/docs-next/src/versioned.tsx +++ b/packages/docs-next/src/versioned.tsx @@ -9,7 +9,8 @@ import { markdownTwinUrl } from "./llms.js"; import { type OpenGraphOptions, openGraphMetadata, sectionBadge } from "./open-graph.js"; import type { PageActionsOption } from "./page-actions.js"; import { pageNeighbours } from "./slim-tree.js"; -import type { DocsSource } from "./types.js"; +import { resolveBody } from "./render-body.js"; +import type { DocsSource, RenderBody } from "./types.js"; import { resolveSlug, versionBaseUrl, @@ -62,6 +63,8 @@ export interface VersionedDocsOptions { source: (versionId: string) => DocsSource | undefined; /** Render mode; defaults to `static`. */ mode?: DocsRenderMode; + /** Replaces or extends a page's rendered body; refer to `RenderBody`. */ + renderBody?: RenderBody; } /** @@ -80,6 +83,7 @@ export function createVersionedDocs(options: VersionedDocsOptions) { pageActions, editLink, openGraph, + renderBody, } = options; function pick(slug: string[] | undefined) { @@ -97,9 +101,22 @@ export function createVersionedDocs(options: VersionedDocsOptions) { if (!found) notFound(); const MDX = found.page.data.body; + const { body, full } = await resolveBody( + renderBody, + found.source, + found.version.id, + found.page.slugs, + assetBasePath, + , + ); return ( - + {body} ); } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9252f6f8..f2000143 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -106,13 +106,16 @@ importers: version: 2.8.0 fumadocs-core: specifier: 'catalog:' - version: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) + version: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) fumadocs-mdx: specifier: 'catalog:' - version: 15.4.4(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) + version: 15.4.4(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) + fumadocs-openapi: + specifier: 12.5.4 + version: 12.5.4(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(fumadocs-ui@16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3))(react-dom@19.2.7(react@19.2.7))(react@19.2.7) fumadocs-ui: specifier: 'catalog:' - version: 16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) + version: 16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) next: specifier: 'catalog:' version: 16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) @@ -209,13 +212,16 @@ importers: version: 5.3.0 fumadocs-core: specifier: 'catalog:' - version: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) + version: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) fumadocs-mdx: specifier: 'catalog:' - version: 15.4.4(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) + version: 15.4.4(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) + fumadocs-openapi: + specifier: 12.5.4 + version: 12.5.4(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(fumadocs-ui@16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3))(react-dom@19.2.7(react@19.2.7))(react@19.2.7) fumadocs-ui: specifier: 'catalog:' - version: 16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) + version: 16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) next: specifier: 'catalog:' version: 16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) @@ -311,6 +317,15 @@ importers: '@fumari/image-size': specifier: 0.1.1 version: 0.1.1 + github-slugger: + specifier: 2.0.0 + version: 2.0.0 + oas-validator: + specifier: 5.0.8 + version: 5.0.8 + swagger2openapi: + specifier: 7.0.8 + version: 7.0.8 devDependencies: '@mdx-js/mdx': specifier: 3.1.1 @@ -320,10 +335,10 @@ importers: version: 22.20.1 fumadocs-core: specifier: 'catalog:' - version: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) + version: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) fumadocs-mdx: specifier: 'catalog:' - version: 15.4.4(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) + version: 15.4.4(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) tsx: specifier: ^4 version: 4.23.12 @@ -380,12 +395,18 @@ importers: fumadocs-core: specifier: 'catalog:' version: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) + fumadocs-openapi: + specifier: 12.5.4 + version: 12.5.4(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(fumadocs-ui@16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3))(react-dom@19.2.7(react@19.2.7))(react@19.2.7) fumadocs-ui: specifier: 'catalog:' version: 16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) lucide-react: specifier: 1.46.0 version: 1.46.0(react@19.2.7) + shiki: + specifier: 4.4.3 + version: 4.4.3 devDependencies: '@coder/docs-transforms': specifier: workspace:* @@ -462,7 +483,7 @@ importers: version: link:../docs-config fumadocs-core: specifier: 'catalog:' - version: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) + version: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) github-slugger: specifier: 2.0.0 version: 2.0.0 @@ -514,7 +535,7 @@ importers: version: 19.2.3(@types/react@19.2.17) fumadocs-mdx: specifier: 'catalog:' - version: 15.4.4(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) + version: 15.4.4(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) hast-util-to-html: specifier: 9.0.5 version: 9.0.5 @@ -544,10 +565,10 @@ importers: version: 2.1.10(react-dom@19.2.7(react@19.2.7))(react@19.2.7) fumadocs-core: specifier: 'catalog:' - version: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) + version: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) fumadocs-ui: specifier: 'catalog:' - version: 16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) + version: 16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) devDependencies: '@types/mdx': specifier: 2.0.14 @@ -594,6 +615,36 @@ packages: resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} engines: {node: '>=6.9.0'} + '@babel/runtime@8.0.8': + resolution: {integrity: sha512-dEu8nGlRqjsJsvviUUoSMfcRHpwomCiRlXsc2mPfJ79+ffTpDm+JtfUtTMzUrqCApHQnCsVPD3gT1ZT8RgBRCQ==} + + '@base-ui/react@1.9.0': + resolution: {integrity: sha512-S8CSYosASBKtpL8SWUfS78rFElfLijiCgA7oHOK22jCJ95FULsYyKwBNFOgudt0RA+/7yNc7F81bOvQnRgbBiQ==} + engines: {node: '>=14.0.0'} + peerDependencies: + '@date-fns/tz': ^1.2.0 + '@types/react': ^17 || ^18 || ^19 + date-fns: ^4.0.0 + react: ^17 || ^18 || ^19 + react-dom: ^17 || ^18 || ^19 + peerDependenciesMeta: + '@date-fns/tz': + optional: true + '@types/react': + optional: true + date-fns: + optional: true + + '@base-ui/utils@0.5.0': + resolution: {integrity: sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A==} + peerDependencies: + '@types/react': ^17 || ^18 || ^19 + react: ^17 || ^18 || ^19 + react-dom: ^17 || ^18 || ^19 + peerDependenciesMeta: + '@types/react': + optional: true + '@bytecodealliance/preview2-shim@0.17.6': resolution: {integrity: sha512-n3cM88gTen5980UOBAD6xDcNNL3ocTK8keab21bpx1ONdA+ARj7uD1qoFxOWCyKlkpSi195FH+GeAut7Oc6zZw==} @@ -1016,6 +1067,9 @@ packages: cpu: [x64] os: [win32] + '@exodus/schemasafe@1.3.0': + resolution: {integrity: sha512-5Aap/GaRupgNx/feGBwLLTVv8OQFfv3pq2lPRzPg9R+IOBnDgghTGW7l7EuVXOvg5cc/xSAlRW8rBrjIC3Nvqw==} + '@fastify/busboy@2.1.1': resolution: {integrity: sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==} engines: {node: '>=14'} @@ -1051,6 +1105,17 @@ packages: '@types/react': optional: true + '@fumadocs/json-schema@0.3.5': + resolution: {integrity: sha512-BhFhYtVufkLY0cZfWuMFJm0Rq7oBaIDMzONrsHovhY6on7GiPiuTSuJv4ZlOgmyBaPL3HW+s1wkevjhvRUUlFg==} + peerDependencies: + json-schema-typed: '*' + react: ^19.2.0 + peerDependenciesMeta: + json-schema-typed: + optional: true + react: + optional: true + '@fumadocs/tailwind@0.1.2': resolution: {integrity: sha512-VppeXgIRXjZMgpf2qijj1hcfxyeYl1s0ok8k6N3jyjiX64M7sDwnt2zGPd6dbfDybgbBvDw6C6J1e42gB5NzsA==} peerDependencies: @@ -1062,6 +1127,24 @@ packages: '@fumari/image-size@0.1.1': resolution: {integrity: sha512-iaiV2wyzJ4mW358NX4CX3yGit+WjKYzpaQ+rldK9BjL/5jFpeV6ruWnZVq7MEyMn3Gd0DLi8g/79NZAAQaGscw==} + '@fumari/json-schema-ts@1.0.2': + resolution: {integrity: sha512-1NHGl8Oqg50mhpWMvbhqnwFRLBugkGCRubLSH/TrAzTAS99x4z0xFgOVcbJne+yfaZv94ZNdmRWobDvUiZswPg==} + peerDependencies: + json-schema-typed: '*' + peerDependenciesMeta: + json-schema-typed: + optional: true + + '@fumari/stf@1.1.2': + resolution: {integrity: sha512-8PuvETmnMRJjof6BJLFNJBKq9at6Ar1oJWRkedSJ0K/GJ73QPHVSZqTkgXh3hb6uXkQhbbWkv+5WD0Fh50YUGA==} + peerDependencies: + '@types/react': '*' + react: ^19.2.0 + react-dom: ^19.2.0 + peerDependenciesMeta: + '@types/react': + optional: true + '@img/colour@1.1.0': resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} engines: {node: '>=18'} @@ -2258,34 +2341,78 @@ packages: rollup: optional: true + '@scalar/helpers@0.16.4': + resolution: {integrity: sha512-9eILWzUcAkHEuYMMvijpSIy69t+Vkq+NudLB/7lgARFTWqXfQpIxW1L3VH7ogKyRie5+E4CNZ3PSvlw6IIfLGw==} + engines: {node: '>=22'} + + '@scalar/json-magic@0.16.1': + resolution: {integrity: sha512-yWQJUrkufUsShizF+rGKO4BoZ/ijMpnrgwRjtCA2cYqjxkQOYaQCd+WVF+b3ihmXE7amr768pLItFCx5UV/ObQ==} + engines: {node: '>=22'} + + '@scalar/openapi-types@0.9.8': + resolution: {integrity: sha512-pGcpkZObsGBC7nRKYte+6gstoe0C4hp7B2UWQYjg5To1wE68s3OHVvin+muL3tn3ZAoahXeJAkn1+aEcMi802w==} + engines: {node: '>=22'} + + '@scalar/openapi-upgrader@0.4.6': + resolution: {integrity: sha512-wkTbowGZAlDA5AhCAnBVft6y3veoE17P+okH/zrwM/BZWBSzPghGpa4BPTCg3+IzRmRP/8ZeaYO7LfxCDAEmcA==} + engines: {node: '>=22'} + '@shikijs/core@4.4.3': resolution: {integrity: sha512-QCR4q2ZO/ILJEuwiBMel4wdcTDb1JGwfjKTxPDF6x8ixOaluPrVqIn06C99AcRPhmYlBR56d/Fb+GN58GzExpg==} engines: {node: '>=20'} + '@shikijs/core@4.5.0': + resolution: {integrity: sha512-6CIgwq+bt2JZ3OSjb/nBkkwEf/CfpHcbam+Mg5Pllco7HAGRQ2/EFhZrrJtbyNTgKwknfVS+llsXGygiDGwJWw==} + engines: {node: '>=20'} + '@shikijs/engine-javascript@4.4.3': resolution: {integrity: sha512-FbOjFJp9VLdo1Wevs10BBtVxiTWwNLqZh5Gkhjgda/ioL15YOgeSl9n+6XMa3qRlPQzfhFNe641SrynFHYG0nQ==} engines: {node: '>=20'} + '@shikijs/engine-javascript@4.5.0': + resolution: {integrity: sha512-Ed6UdEj84LyYkwnxM5CvSMWAD+id9ExTYri0/+x41U9zrgNifPSS9lZm0JqBP0VfYI8yr8tY5nbNq9+p9R0kFA==} + engines: {node: '>=20'} + '@shikijs/engine-oniguruma@4.4.3': resolution: {integrity: sha512-EcOQkxdxGQrc1Row/cC2c96/v1dbZqGnEVu1qTuT/MJmp6+cXCvQussowVmCv5Tqr3KuY3c7IbM6HTW3LJ1k9w==} engines: {node: '>=20'} + '@shikijs/engine-oniguruma@4.5.0': + resolution: {integrity: sha512-dKVmbJecVdB9recl8a/CU4jdpNXyjJQrIcesIkpS70s5HS02ohpnCSpMUbotPnEUzbAcLQ+S4hwZYbkBBiTcJw==} + engines: {node: '>=20'} + '@shikijs/langs@4.4.3': resolution: {integrity: sha512-ePic0yfAJGOF83D5wBHK/00EjK65oahBYxFk5epgq33WRv7X9UuxLEV8PtR0szC0z8dl7INIpIodB99JRFlR+A==} engines: {node: '>=20'} + '@shikijs/langs@4.5.0': + resolution: {integrity: sha512-wwBTqwduXSz0X4v9Qa2EWeFaYJEw1clCncWjoRNQRbVDu3SPRTRWucnouYapKj3b8Q+sk/41Vbc4B5c8nuYzLA==} + engines: {node: '>=20'} + '@shikijs/primitive@4.4.3': resolution: {integrity: sha512-m0wBeLDQDeIxRdUmrCPdQqfuUamDwRL5isCfYbguKD6NiaKpVbsv+3J81DyIKgNW5h4WAIIr8T4EkgQrBBxvaQ==} engines: {node: '>=20'} + '@shikijs/primitive@4.5.0': + resolution: {integrity: sha512-UM7ShlA8oz0OWxLLO8BmO9Ip6fVqdkt8yF0EH7nOCqHfrx1eEAzF0ZUVK7L+I8NEgeu1PEWSRlxaiPPeCb4iDg==} + engines: {node: '>=20'} + '@shikijs/themes@4.4.3': resolution: {integrity: sha512-w8UHjeUnIR965KMWJHUPXOc2mNJUnK3vpVLYLvw5IYU2mnTTJ89E24OrJDBNiJDQ0qzb0tc4l7mrIXx5cFeIyw==} engines: {node: '>=20'} + '@shikijs/themes@4.5.0': + resolution: {integrity: sha512-zGb87H3UBbpuI4yoh5UguB1XbU+2BDU3kflM7UfZ+Cy2hWo9lBtqjSVK20gmLY6ukYl040hAypGXMgud9vul8Q==} + engines: {node: '>=20'} + '@shikijs/types@4.4.3': resolution: {integrity: sha512-UEJxmRR++MAGR6hugn0vgVS2W/6lWAts84FFSrnlH9sP0LNol7E5+NQ792pH8liWUhyMyjhTgSUH3k7iD7tc5g==} engines: {node: '>=20'} + '@shikijs/types@4.5.0': + resolution: {integrity: sha512-drtPrtD8N0DENyD2cyt6Ajy+IWsiCLgMxODwLTpvH1UsN6a9jf90tNTPjqwHvA+0Lzu9e0txk8DjfqH1p9UJRw==} + engines: {node: '>=20'} + '@shikijs/vscode-textmate@10.0.2': resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==} @@ -2871,6 +2998,9 @@ packages: resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} engines: {node: '>= 0.4'} + call-me-maybe@1.0.2: + resolution: {integrity: sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==} + callsites@3.1.0: resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} engines: {node: '>=6'} @@ -2914,6 +3044,10 @@ packages: client-only@0.0.1: resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==} + cliui@8.0.1: + resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} + engines: {node: '>=12'} + clsx@2.1.1: resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} engines: {node: '>=6'} @@ -2923,6 +3057,11 @@ packages: engines: {node: '>=20'} hasBin: true + cn@0.5.0: + resolution: {integrity: sha512-JGEixZEpfFXm1P5uXwvEobOFLlHwIWi5v4tjd1ZwfiYmcEilkuD2l+054rvJcYCR1B+uVThHeUbgmNz1FwuxuA==} + engines: {node: '>=22'} + hasBin: true + code-block-writer@10.1.1: resolution: {integrity: sha512-67ueh2IRGst/51p0n6FvPrnRjAGHY5F8xdjkgrYE7DDzpJe6qA07RYQ9VcoUeo5ATOjSOiWpSL3SWBRRbempMw==} @@ -3106,6 +3245,9 @@ packages: resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} engines: {node: '>= 0.4'} + es6-promise@3.3.1: + resolution: {integrity: sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==} + esast-util-from-estree@2.0.0: resolution: {integrity: sha512-4CyanoAudUSBAn5K13H4JhsMH6L9ZP7XbLVe/dKybkxMO7eDyLsT8UHl9TRNrU2Gr9nz+FovfSIjuXWJ81uVwQ==} @@ -3122,6 +3264,10 @@ packages: engines: {node: '>=18'} hasBin: true + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + escape-string-regexp@5.0.0: resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==} engines: {node: '>=12'} @@ -3187,6 +3333,9 @@ packages: fast-json-stable-stringify@2.1.0: resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + fast-safe-stringify@2.1.1: + resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==} + fast-uri@3.1.8: resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==} @@ -3352,6 +3501,24 @@ packages: vite: optional: true + fumadocs-openapi@12.5.4: + resolution: {integrity: sha512-HU+x8N/oeunn5nGWFJuXtHW6ZUdZpfZ/ekq1GW20/juD5p5ociRZbXQJlT7kCZs945WjdcadLL/IPVTWF1/kQA==} + peerDependencies: + '@scalar/api-client-react': ^2.0.20 + '@types/react': '*' + fumadocs-core: ^16.15.0 + fumadocs-ui: ^16.15.0 + json-schema-typed: '*' + react: ^19.2.0 + react-dom: ^19.2.0 + peerDependenciesMeta: + '@scalar/api-client-react': + optional: true + '@types/react': + optional: true + json-schema-typed: + optional: true + fumadocs-ui@16.15.14: resolution: {integrity: sha512-yYnun6im7eBK3gMrErl69QRt+C7/KV5exZFFnoOnRx3HRi9WwAgPtAhwNhFIx1gAYLioSaSjP12+ZrpH9x2b7w==} peerDependencies: @@ -3379,6 +3546,10 @@ packages: resolution: {integrity: sha512-H7cUpwCQSiJmAHM4c/aFu6fUfrhWXW1ncyh8ftxEPMu6AiYkHw9K8br720TGPZJbk5eOH2bynjZD1yPvdDAmag==} engines: {node: '>= 4'} + get-caller-file@2.0.5: + resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} + engines: {node: 6.* || 8.* || >= 10.*} + get-east-asian-width@1.7.0: resolution: {integrity: sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==} engines: {node: '>=18'} @@ -3524,6 +3695,9 @@ packages: resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} engines: {node: '>= 14'} + http2-client@1.3.5: + resolution: {integrity: sha512-EC2utToWl4RKfs5zd36Mxq7nzHHBuomZboI0yYL6Y0RmBgT7Sgkq4rQ0ezFTYoIsSs7Tm9SJe+o2FcAg6GBhGA==} + https-proxy-agent@7.0.6: resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} engines: {node: '>= 14'} @@ -3794,6 +3968,15 @@ packages: peerDependencies: react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 + lucide-react@1.62.0: + resolution: {integrity: sha512-2i8QZZhkgYMA3oJvKYpCltHh54VnT/3rIPkDLHbzr3IJQBaCz8+7j7V2k2rczYd2aCqcBaMmNlWQ2KKeDfcxmw==} + peerDependencies: + '@types/react': '*' + react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + luxon@3.7.2: resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==} engines: {node: '>=12'} @@ -4092,6 +4275,10 @@ packages: sass: optional: true + node-fetch-h2@2.3.0: + resolution: {integrity: sha512-ofRW94Ab0T4AOh5Fk8t0h8OBWrmjb0SSB20xh1H8YnPV9EJ+f5AMoYSUQ2zgJ4Iq2HAK0I2l5/Nequ8YzFS3Hg==} + engines: {node: 4.x || >=6.0.0} + node-fetch@2.6.7: resolution: {integrity: sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==} engines: {node: 4.x || >=6.0.0} @@ -4123,6 +4310,9 @@ packages: resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==} hasBin: true + node-readfiles@0.2.0: + resolution: {integrity: sha512-SU00ZarexNlE4Rjdm83vglt5Y9yiQ+XI1XpflWlb7q7UTN1JUItm69xMeiQCTxtTfnzt+83T8Cx+vI2ED++VDA==} + nopt@8.1.0: resolution: {integrity: sha512-ieGu42u/Qsa4TFktmaKEwM6MQH0pOWnaB3htzh0JRtx84+Mebc0cbZYN5bC+6WTZ4+77xrL9Pn5m7CV6VIkV7A==} engines: {node: ^18.17.0 || >=20.5.0} @@ -4143,6 +4333,22 @@ packages: nwsapi@2.2.24: resolution: {integrity: sha512-7YRhZ3jS45LwmSCT4b2sVFHt/WuovaktDU07QrtOBY2PXskss5a9jfmR9jptyumwXST+rFjrmppMY1KT/yn35A==} + oas-kit-common@1.0.8: + resolution: {integrity: sha512-pJTS2+T0oGIwgjGpw7sIRU8RQMcUoKCDWFLdBqKB2BNmGpbBMH2sdqAaOXUg8OzonZHU0L7vfJu1mJFEiYDWOQ==} + + oas-linter@3.2.2: + resolution: {integrity: sha512-KEGjPDVoU5K6swgo9hJVA/qYGlwfbFx+Kg2QB/kd7rzV5N8N5Mg6PlsoCMohVnQmo+pzJap/F610qTodKzecGQ==} + + oas-resolver@2.5.6: + resolution: {integrity: sha512-Yx5PWQNZomfEhPPOphFbZKi9W93CocQj18NlD2Pa4GWZzdZpSJvYwoiuurRI7m3SpcChrnO08hkuQDL3FGsVFQ==} + hasBin: true + + oas-schema-walker@1.1.5: + resolution: {integrity: sha512-2yucenq1a9YPmeNExoUa9Qwrt9RFkjqaMAA1X+U7sbb0AqBeTIdMHky9SQQ6iN94bO5NW0W4TRYXerG+BdAvAQ==} + + oas-validator@5.0.8: + resolution: {integrity: sha512-cu20/HE5N5HKqVygs3dt94eYJfBi0TsZvPVXDhbXQHiEityDN+RROTleefoKRKKJ9dFAF2JBkDHgvWj0sjKGmw==} + once@1.3.3: resolution: {integrity: sha512-6vaNInhu+CHxtONf3zw3vq4SP2DOQhjBvIa3rNcG0+P7eKWlYH6Peu7rHizSloRU2EwMz6GraLieis9Ac9+p1w==} @@ -4243,6 +4449,9 @@ packages: path-to-regexp@8.3.0: resolution: {integrity: sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==} + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + pend@1.2.0: resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==} @@ -4380,6 +4589,9 @@ packages: recma-stringify@1.0.0: resolution: {integrity: sha512-cjwII1MdIIVloKvC9ErQ+OgAtwHBmcZ0Bg4ciz78FtbT8In39aAYbaA7zvxQ61xVMSPE8WxhLwLbhif4Js2C+g==} + reftools@1.1.9: + resolution: {integrity: sha512-OVede/NQE13xBQ+ob5CKd5KyeJYU2YInb1bmV4nRoOfquZPkAkxuOXicSe1PvqIuZZ4kD13sPKBbR7UFDmli6w==} + regex-recursion@6.0.2: resolution: {integrity: sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==} @@ -4416,10 +4628,17 @@ packages: remark@15.0.1: resolution: {integrity: sha512-Eht5w30ruCXgFmxVUSlNWQ9iiimq07URKeFS3hNc8cUWy1llX4KDWfyEDZRycMc+znsN9Ux5/tJ/BFdgdOwA3A==} + require-directory@2.1.1: + resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} + engines: {node: '>=0.10.0'} + require-from-string@2.0.2: resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} engines: {node: '>=0.10.0'} + reselect@5.3.0: + resolution: {integrity: sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg==} + resolve-from@4.0.0: resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} engines: {node: '>=4'} @@ -4512,6 +4731,28 @@ packages: resolution: {integrity: sha512-Mb/GvXPHBAXdgGIcnfU5L3ldpn1XcxrGkPHwqgRx17/I2XRfqlFKk2vGkHWINn1kdXvzJZeuO3is6I9KLPFm0g==} engines: {node: '>=20'} + shiki@4.5.0: + resolution: {integrity: sha512-OcRW72ngQvc+MSVWBRIovC/BTW589iUE/Vxav7VeM4RcY9MUjqB+IR6ILG1k9nuW6LiG/nct9uma4/MBtnZbmQ==} + engines: {node: '>=20'} + + should-equal@2.0.0: + resolution: {integrity: sha512-ZP36TMrK9euEuWQYBig9W55WPC7uo37qzAEmbjHz4gfyuXrEUgF8cUvQVO+w+d3OMfPvSRQJ22lSm8MQJ43LTA==} + + should-format@3.0.3: + resolution: {integrity: sha512-hZ58adtulAk0gKtua7QxevgUaXTTXxIi8t41L3zo9AHvjXO1/7sdLECuHeIN2SRtYXpNkmhoUP2pdeWgricQ+Q==} + + should-type-adaptors@1.1.0: + resolution: {integrity: sha512-JA4hdoLnN+kebEp2Vs8eBe9g7uy0zbRo+RMcU0EsNy+R+k049Ki+N5tT5Jagst2g7EAja+euFuoXFCa8vIklfA==} + + should-type@1.4.0: + resolution: {integrity: sha512-MdAsTu3n25yDbIe1NeN69G4n6mUnJGtSJHygX3+oN0ZbO3DTiATnf7XnYJdGT42JCXurTb1JI0qOBR65shvhPQ==} + + should-util@1.0.1: + resolution: {integrity: sha512-oXF8tfxx5cDk8r2kYqlkUJzZpDBqVY/II2WhvU0n9Y3XYvAYRmeaf1PvvIvTgPnv4KJ+ES5M0PyDq5Jp+Ygy2g==} + + should@13.2.3: + resolution: {integrity: sha512-ggLesLtu2xp+ZxI+ysJTmNjh2U0TsC+rQ/pfED9bUZZ4DKefP27D+7YJVVTvKsmjLpIi9jAa7itwDGkDDmt1GQ==} + signal-exit@3.0.7: resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} @@ -4632,6 +4873,10 @@ packages: svg-tags@1.0.0: resolution: {integrity: sha512-ovssysQTa+luh7A5Weu3Rta6FJlFBBbInjOh722LIt6klpU2/HtdUbszju/G4devcvk8PGt7FCLv5wftu3THUA==} + swagger2openapi@7.0.8: + resolution: {integrity: sha512-upi/0ZGkYgEcLeGieoz8gT74oWHA0E7JivX7aN9mAf+Tc7BQoRBvnIGHoPDw+f9TXTW4s6kGYCZJtauP6OYp7g==} + hasBin: true + symbol-tree@3.2.4: resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} @@ -4773,6 +5018,10 @@ packages: resolution: {integrity: sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==} engines: {node: '>=20.18.1'} + undici@8.12.3: + resolution: {integrity: sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==} + engines: {node: '>=22.19.0'} + unicorn-magic@0.4.1: resolution: {integrity: sha512-lzlXPoVB0Uy/FvTaUgX39RbixYiSKoc3JSoSf01+0c2B6FR3qdYIPN7Qjo/AV7n6sqLCk0509cT3LRj1oSZ1+A==} engines: {node: '>=20'} @@ -4832,6 +5081,11 @@ packages: '@types/react': optional: true + use-sync-external-store@1.7.0: + resolution: {integrity: sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} @@ -4895,6 +5149,10 @@ packages: engines: {node: '>= 8'} hasBin: true + wrap-ansi@7.0.0: + resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} + engines: {node: '>=10'} + wrappy@1.0.2: resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} @@ -4933,6 +5191,10 @@ packages: xmlchars@2.2.0: resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + y18n@5.0.8: + resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} + engines: {node: '>=10'} + yallist@4.0.0: resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} @@ -4940,11 +5202,23 @@ packages: resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} engines: {node: '>=18'} + yaml@1.10.3: + resolution: {integrity: sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==} + engines: {node: '>= 6'} + yaml@2.9.1: resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} engines: {node: '>= 14.6'} hasBin: true + yargs-parser@21.1.1: + resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} + engines: {node: '>=12'} + + yargs@17.7.3: + resolution: {integrity: sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==} + engines: {node: '>=12'} + yauzl-clone@1.0.4: resolution: {integrity: sha512-igM2RRCf3k8TvZoxR2oguuw4z1xasOnA31joCqHIyLkeWrvAc2Jgay5ISQ2ZplinkoGaJ6orCz56Ey456c5ESA==} engines: {node: '>=6'} @@ -5001,6 +5275,31 @@ snapshots: '@babel/helper-validator-identifier@7.29.7': {} + '@babel/runtime@8.0.8': {} + + '@base-ui/react@1.9.0(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)': + dependencies: + '@babel/runtime': 8.0.8 + '@base-ui/utils': 0.5.0(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@floating-ui/react-dom': 2.1.9(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@floating-ui/utils': 0.2.12 + react: 19.2.7 + react-dom: 19.2.7(react@19.2.7) + use-sync-external-store: 1.7.0(react@19.2.7) + optionalDependencies: + '@types/react': 19.2.17 + + '@base-ui/utils@0.5.0(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)': + dependencies: + '@babel/runtime': 8.0.8 + '@floating-ui/utils': 0.2.12 + react: 19.2.7 + react-dom: 19.2.7(react@19.2.7) + reselect: 5.3.0 + use-sync-external-store: 1.7.0(react@19.2.7) + optionalDependencies: + '@types/react': 19.2.17 + '@bytecodealliance/preview2-shim@0.17.6': {} '@cacheable/memory@2.2.0': @@ -5247,6 +5546,8 @@ snapshots: '@esbuild/win32-x64@0.28.2': optional: true + '@exodus/schemasafe@1.3.0': {} + '@fastify/busboy@2.1.1': {} '@floating-ui/core@1.8.0': @@ -5277,12 +5578,31 @@ snapshots: optionalDependencies: '@types/react': 19.2.17 + '@fumadocs/json-schema@0.3.5(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)': + dependencies: + '@fuma-translate/react': 1.0.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@scalar/json-magic': 0.16.1 + optionalDependencies: + react: 19.2.7 + transitivePeerDependencies: + - '@types/react' + - react-dom + '@fumadocs/tailwind@0.1.2(tailwindcss@4.3.3)': optionalDependencies: tailwindcss: 4.3.3 '@fumari/image-size@0.1.1': {} + '@fumari/json-schema-ts@1.0.2': {} + + '@fumari/stf@1.1.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)': + dependencies: + react: 19.2.7 + react-dom: 19.2.7(react@19.2.7) + optionalDependencies: + '@types/react': 19.2.17 + '@img/colour@1.1.0': optional: true @@ -6157,6 +6477,22 @@ snapshots: estree-walker: 2.0.2 picomatch: 4.0.7 + '@scalar/helpers@0.16.4': {} + + '@scalar/json-magic@0.16.1': + dependencies: + '@scalar/helpers': 0.16.4 + pathe: 2.0.3 + undici: 7.30.1 + yaml: 2.9.1 + + '@scalar/openapi-types@0.9.8': {} + + '@scalar/openapi-upgrader@0.4.6': + dependencies: + '@scalar/helpers': 0.16.4 + '@scalar/openapi-types': 0.9.8 + '@shikijs/core@4.4.3': dependencies: '@shikijs/primitive': 4.4.3 @@ -6165,36 +6501,74 @@ snapshots: '@types/hast': 3.0.5 hast-util-to-html: 9.0.5 + '@shikijs/core@4.5.0': + dependencies: + '@shikijs/primitive': 4.5.0 + '@shikijs/types': 4.5.0 + '@shikijs/vscode-textmate': 10.0.2 + '@types/hast': 3.0.5 + hast-util-to-html: 9.0.5 + '@shikijs/engine-javascript@4.4.3': dependencies: '@shikijs/types': 4.4.3 '@shikijs/vscode-textmate': 10.0.2 oniguruma-to-es: 4.3.6 + '@shikijs/engine-javascript@4.5.0': + dependencies: + '@shikijs/types': 4.5.0 + '@shikijs/vscode-textmate': 10.0.2 + oniguruma-to-es: 4.3.6 + '@shikijs/engine-oniguruma@4.4.3': dependencies: '@shikijs/types': 4.4.3 '@shikijs/vscode-textmate': 10.0.2 + '@shikijs/engine-oniguruma@4.5.0': + dependencies: + '@shikijs/types': 4.5.0 + '@shikijs/vscode-textmate': 10.0.2 + '@shikijs/langs@4.4.3': dependencies: '@shikijs/types': 4.4.3 + '@shikijs/langs@4.5.0': + dependencies: + '@shikijs/types': 4.5.0 + '@shikijs/primitive@4.4.3': dependencies: '@shikijs/types': 4.4.3 '@shikijs/vscode-textmate': 10.0.2 '@types/hast': 3.0.5 + '@shikijs/primitive@4.5.0': + dependencies: + '@shikijs/types': 4.5.0 + '@shikijs/vscode-textmate': 10.0.2 + '@types/hast': 3.0.5 + '@shikijs/themes@4.4.3': dependencies: '@shikijs/types': 4.4.3 + '@shikijs/themes@4.5.0': + dependencies: + '@shikijs/types': 4.5.0 + '@shikijs/types@4.4.3': dependencies: '@shikijs/vscode-textmate': 10.0.2 '@types/hast': 3.0.5 + '@shikijs/types@4.5.0': + dependencies: + '@shikijs/vscode-textmate': 10.0.2 + '@types/hast': 3.0.5 + '@shikijs/vscode-textmate@10.0.2': {} '@sinclair/typebox@0.25.24': {} @@ -6872,6 +7246,8 @@ snapshots: es-errors: 1.3.0 function-bind: 1.1.2 + call-me-maybe@1.0.2: {} + callsites@3.1.0: {} caniuse-lite@1.0.30001810: {} @@ -6904,10 +7280,18 @@ snapshots: client-only@0.0.1: {} + cliui@8.0.1: + dependencies: + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrap-ansi: 7.0.0 + clsx@2.1.1: {} cn@0.3.3: {} + cn@0.5.0: {} + code-block-writer@10.1.1: {} collapse-white-space@2.1.0: {} @@ -7062,6 +7446,8 @@ snapshots: has-tostringtag: 1.0.2 hasown: 2.0.4 + es6-promise@3.3.1: {} + esast-util-from-estree@2.0.0: dependencies: '@types/estree-jsx': 1.0.5 @@ -7134,6 +7520,8 @@ snapshots: '@esbuild/win32-ia32': 0.28.2 '@esbuild/win32-x64': 0.28.2 + escalade@3.2.0: {} + escape-string-regexp@5.0.0: {} estree-util-attach-comments@3.0.0: @@ -7227,6 +7615,8 @@ snapshots: fast-json-stable-stringify@2.1.0: optional: true + fast-safe-stringify@2.1.1: {} + fast-uri@3.1.8: {} fastest-levenshtein@1.0.16: {} @@ -7307,7 +7697,7 @@ snapshots: remark-gfm: 4.0.1 remark-rehype: 11.1.2 scroll-into-view-if-needed: 3.1.0 - shiki: 4.4.3 + shiki: 4.5.0 tinyglobby: 0.2.17 unified: 11.0.5 unist-util-visit: 5.1.0 @@ -7328,7 +7718,7 @@ snapshots: transitivePeerDependencies: - supports-color - fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6): + fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6): dependencies: '@fumari/image-size': 0.1.1 estree-util-value-to-estree: 3.5.0 @@ -7342,7 +7732,7 @@ snapshots: remark-gfm: 4.0.1 remark-rehype: 11.1.2 scroll-into-view-if-needed: 3.1.0 - shiki: 4.4.3 + shiki: 4.5.0 tinyglobby: 0.2.17 unified: 11.0.5 unist-util-visit: 5.1.0 @@ -7355,7 +7745,7 @@ snapshots: '@types/hast': 3.0.5 '@types/mdast': 4.0.4 '@types/react': 19.2.17 - lucide-react: 1.48.0(react@19.2.7) + lucide-react: 1.62.0(@types/react@19.2.17)(react@19.2.7) next: 16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) react: 19.2.7 react-dom: 19.2.7(react@19.2.7) @@ -7394,14 +7784,14 @@ snapshots: transitivePeerDependencies: - supports-color - fumadocs-mdx@15.4.4(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7): + fumadocs-mdx@15.4.4(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7): dependencies: '@mdx-js/mdx': 3.1.1 '@standard-schema/spec': 1.1.0 chokidar: 5.0.0 esbuild: 0.28.2 estree-util-value-to-estree: 3.5.0 - fumadocs-core: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) + fumadocs-core: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) github-slugger: 2.0.0 magic-string: 1.4.1 mdast-util-mdx: 3.0.0 @@ -7425,6 +7815,68 @@ snapshots: transitivePeerDependencies: - supports-color + fumadocs-openapi@12.5.4(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(fumadocs-ui@16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3))(react-dom@19.2.7(react@19.2.7))(react@19.2.7): + dependencies: + '@base-ui/react': 1.9.0(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@fuma-translate/react': 1.0.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@fumadocs/json-schema': 0.3.5(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@fumari/json-schema-ts': 1.0.2 + '@fumari/stf': 1.1.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@scalar/json-magic': 0.16.1 + '@scalar/openapi-upgrader': 0.4.6 + chokidar: 5.0.0 + class-variance-authority: 0.7.1 + cn: 0.5.0 + fumadocs-core: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) + fumadocs-ui: 16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) + github-slugger: 2.0.0 + hast-util-to-jsx-runtime: 2.3.6 + lucide-react: 1.62.0(@types/react@19.2.17)(react@19.2.7) + react: 19.2.7 + react-dom: 19.2.7(react@19.2.7) + remark: 15.0.1 + remark-rehype: 11.1.2 + shiki: 4.5.0 + undici: 8.12.3 + yaml: 2.9.1 + optionalDependencies: + '@types/react': 19.2.17 + transitivePeerDependencies: + - '@date-fns/tz' + - date-fns + - supports-color + + fumadocs-openapi@12.5.4(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(fumadocs-ui@16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3))(react-dom@19.2.7(react@19.2.7))(react@19.2.7): + dependencies: + '@base-ui/react': 1.9.0(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@fuma-translate/react': 1.0.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@fumadocs/json-schema': 0.3.5(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@fumari/json-schema-ts': 1.0.2 + '@fumari/stf': 1.1.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@scalar/json-magic': 0.16.1 + '@scalar/openapi-upgrader': 0.4.6 + chokidar: 5.0.0 + class-variance-authority: 0.7.1 + cn: 0.5.0 + fumadocs-core: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) + fumadocs-ui: 16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) + github-slugger: 2.0.0 + hast-util-to-jsx-runtime: 2.3.6 + lucide-react: 1.62.0(@types/react@19.2.17)(react@19.2.7) + react: 19.2.7 + react-dom: 19.2.7(react@19.2.7) + remark: 15.0.1 + remark-rehype: 11.1.2 + shiki: 4.5.0 + undici: 8.12.3 + yaml: 2.9.1 + optionalDependencies: + '@types/react': 19.2.17 + transitivePeerDependencies: + - '@date-fns/tz' + - date-fns + - supports-color + fumadocs-ui@16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3): dependencies: '@fuma-translate/react': 1.0.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) @@ -7450,7 +7902,7 @@ snapshots: react-remove-scroll: 2.7.2(@types/react@19.2.17)(react@19.2.7) rehype-raw: 7.0.0 scroll-into-view-if-needed: 3.1.0 - shiki: 4.4.3 + shiki: 4.5.0 unist-util-visit: 5.1.0 optionalDependencies: '@types/mdx': 2.0.14 @@ -7460,7 +7912,7 @@ snapshots: - '@types/react-dom' - tailwindcss - fumadocs-ui@16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3): + fumadocs-ui@16.15.14(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3): dependencies: '@fuma-translate/react': 1.0.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) '@fumadocs/tailwind': 0.1.2(tailwindcss@4.3.3) @@ -7476,7 +7928,7 @@ snapshots: '@radix-ui/react-tabs': 1.1.21(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) class-variance-authority: 0.7.1 cn: 0.3.3 - fumadocs-core: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.48.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) + fumadocs-core: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) lucide-react: 1.48.0(react@19.2.7) motion: 13.4.4(react-dom@19.2.7(react@19.2.7))(react@19.2.7) next-themes: 0.4.6(react-dom@19.2.7(react@19.2.7))(react@19.2.7) @@ -7485,7 +7937,7 @@ snapshots: react-remove-scroll: 2.7.2(@types/react@19.2.17)(react@19.2.7) rehype-raw: 7.0.0 scroll-into-view-if-needed: 3.1.0 - shiki: 4.4.3 + shiki: 4.5.0 unist-util-visit: 5.1.0 optionalDependencies: '@types/mdx': 2.0.14 @@ -7499,6 +7951,8 @@ snapshots: generic-pool@3.4.2: {} + get-caller-file@2.0.5: {} + get-east-asian-width@1.7.0: {} get-intrinsic@1.3.0: @@ -7736,6 +8190,8 @@ snapshots: transitivePeerDependencies: - supports-color + http2-client@1.3.5: {} + https-proxy-agent@7.0.6: dependencies: agent-base: 7.1.4 @@ -7958,6 +8414,12 @@ snapshots: dependencies: react: 19.2.7 + lucide-react@1.62.0(@types/react@19.2.17)(react@19.2.7): + dependencies: + react: 19.2.7 + optionalDependencies: + '@types/react': 19.2.17 + luxon@3.7.2: {} magic-string@0.30.21: @@ -8504,6 +8966,10 @@ snapshots: - '@types/node' - babel-plugin-macros + node-fetch-h2@2.3.0: + dependencies: + http2-client: 1.3.5 + node-fetch@2.6.7: dependencies: whatwg-url: 5.0.0 @@ -8518,6 +8984,10 @@ snapshots: node-gyp-build@4.8.4: {} + node-readfiles@0.2.0: + dependencies: + es6-promise: 3.3.1 + nopt@8.1.0: dependencies: abbrev: 3.0.1 @@ -8532,6 +9002,37 @@ snapshots: nwsapi@2.2.24: {} + oas-kit-common@1.0.8: + dependencies: + fast-safe-stringify: 2.1.1 + + oas-linter@3.2.2: + dependencies: + '@exodus/schemasafe': 1.3.0 + should: 13.2.3 + yaml: 1.10.3 + + oas-resolver@2.5.6: + dependencies: + node-fetch-h2: 2.3.0 + oas-kit-common: 1.0.8 + reftools: 1.1.9 + yaml: 1.10.3 + yargs: 17.7.3 + + oas-schema-walker@1.1.5: {} + + oas-validator@5.0.8: + dependencies: + call-me-maybe: 1.0.2 + oas-kit-common: 1.0.8 + oas-linter: 3.2.2 + oas-resolver: 2.5.6 + oas-schema-walker: 1.1.5 + reftools: 1.1.9 + should: 13.2.3 + yaml: 1.10.3 + once@1.3.3: dependencies: wrappy: 1.0.2 @@ -8678,6 +9179,8 @@ snapshots: path-to-regexp@8.3.0: {} + pathe@2.0.3: {} + pend@1.2.0: {} picocolors@1.0.0: {} @@ -8812,6 +9315,8 @@ snapshots: unified: 11.0.5 vfile: 6.0.3 + reftools@1.1.9: {} + regex-recursion@6.0.2: dependencies: regex-utilities: 2.3.0 @@ -8894,8 +9399,12 @@ snapshots: transitivePeerDependencies: - supports-color + require-directory@2.1.1: {} + require-from-string@2.0.2: {} + reselect@5.3.0: {} + resolve-from@4.0.0: {} resolve-from@5.0.0: {} @@ -9025,6 +9534,43 @@ snapshots: '@shikijs/vscode-textmate': 10.0.2 '@types/hast': 3.0.5 + shiki@4.5.0: + dependencies: + '@shikijs/core': 4.5.0 + '@shikijs/engine-javascript': 4.5.0 + '@shikijs/engine-oniguruma': 4.5.0 + '@shikijs/langs': 4.5.0 + '@shikijs/themes': 4.5.0 + '@shikijs/types': 4.5.0 + '@shikijs/vscode-textmate': 10.0.2 + '@types/hast': 3.0.5 + + should-equal@2.0.0: + dependencies: + should-type: 1.4.0 + + should-format@3.0.3: + dependencies: + should-type: 1.4.0 + should-type-adaptors: 1.1.0 + + should-type-adaptors@1.1.0: + dependencies: + should-type: 1.4.0 + should-util: 1.0.1 + + should-type@1.4.0: {} + + should-util@1.0.1: {} + + should@13.2.3: + dependencies: + should-equal: 2.0.0 + should-format: 3.0.3 + should-type: 1.4.0 + should-type-adaptors: 1.1.0 + should-util: 1.0.1 + signal-exit@3.0.7: {} signal-exit@4.0.2: {} @@ -9165,6 +9711,22 @@ snapshots: svg-tags@1.0.0: {} + swagger2openapi@7.0.8: + dependencies: + call-me-maybe: 1.0.2 + node-fetch: 2.7.0 + node-fetch-h2: 2.3.0 + node-readfiles: 0.2.0 + oas-kit-common: 1.0.8 + oas-resolver: 2.5.6 + oas-schema-walker: 1.1.5 + oas-validator: 5.0.8 + reftools: 1.1.9 + yaml: 1.10.3 + yargs: 17.7.3 + transitivePeerDependencies: + - encoding + symbol-tree@3.2.4: {} table@6.9.0: @@ -9306,6 +9868,8 @@ snapshots: undici@7.30.1: {} + undici@8.12.3: {} + unicorn-magic@0.4.1: {} unified@11.0.5: @@ -9373,6 +9937,10 @@ snapshots: optionalDependencies: '@types/react': 19.2.17 + use-sync-external-store@1.7.0(react@19.2.7): + dependencies: + react: 19.2.7 + util-deprecate@1.0.2: {} uuid@14.0.1: {} @@ -9483,6 +10051,12 @@ snapshots: dependencies: isexe: 2.0.0 + wrap-ansi@7.0.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrappy@1.0.2: {} write-file-atomic@7.0.1: @@ -9508,12 +10082,28 @@ snapshots: xmlchars@2.2.0: {} + y18n@5.0.8: {} + yallist@4.0.0: {} yallist@5.0.0: {} + yaml@1.10.3: {} + yaml@2.9.1: {} + yargs-parser@21.1.1: {} + + yargs@17.7.3: + dependencies: + cliui: 8.0.1 + escalade: 3.2.0 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + string-width: 4.2.3 + y18n: 5.0.8 + yargs-parser: 21.1.1 + yauzl-clone@1.0.4: dependencies: events-intercept: 2.0.0 From c4bfa81fd5ede0f4ebde1e05a362e3ae1ddcf47e Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 00:32:47 -0400 Subject: [PATCH 02/69] fix(api-reference): reject external $refs and read swagger.json like the docs tree The OpenAPI bundler fetches or reads any $ref that is not in-document, so the converter now fails closed, naming the JSON pointer, on any $ref that does not start with #/ before conversion and again after it, and the page renderer checks the same before bundling. Nothing reaches .generated/openapi when it fails. swagger.json is now read through a new readContainedFile in docs-sources, with the tree walk's guarantees: no symbolic link anywhere from the checkout root down, a regular file under the per-file cap, and still inside the checkout once resolved. The git path caps the blob the same way, parse errors never carry file content, and the DOCS_OPENAPI_FILE override is gone. The tag pages list their endpoints instead of a two-column table, which crushed the endpoint names next to long paths. Assisted-by: AI --- apps/docs/scripts/openapi-source.mjs | 47 +++++++--- apps/docs/scripts/openapi-source.test.mjs | 44 +++++++++ .../docs-build/src/openapi-reference.test.ts | 91 +++++++++++++++++++ packages/docs-build/src/openapi-reference.ts | 24 +++-- packages/docs-config/src/index.ts | 1 + packages/docs-config/src/openapi-refs.test.ts | 16 ++++ packages/docs-config/src/openapi-refs.ts | 32 +++++++ packages/docs-next/src/openapi/index.tsx | 3 + .../docs-sources/src/contained-file.test.ts | 50 ++++++++++ packages/docs-sources/src/contained-file.ts | 54 +++++++++++ packages/docs-sources/src/index.ts | 1 + 11 files changed, 342 insertions(+), 21 deletions(-) create mode 100644 apps/docs/scripts/openapi-source.test.mjs create mode 100644 packages/docs-build/src/openapi-reference.test.ts create mode 100644 packages/docs-config/src/openapi-refs.test.ts create mode 100644 packages/docs-config/src/openapi-refs.ts create mode 100644 packages/docs-sources/src/contained-file.test.ts create mode 100644 packages/docs-sources/src/contained-file.ts diff --git a/apps/docs/scripts/openapi-source.mjs b/apps/docs/scripts/openapi-source.mjs index f1904ffa..8a91ee16 100644 --- a/apps/docs/scripts/openapi-source.mjs +++ b/apps/docs/scripts/openapi-source.mjs @@ -1,38 +1,54 @@ // Where a version's Swagger document comes from, and where the sync leaves the // generated API reference data for the page renderer. import { execFile } from "node:child_process"; -import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdir, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { applyOpenApiReference } from "@coder/docs-build"; +import { DEFAULT_MAX_FILE_BYTES, readContainedFile } from "@coder/docs-sources"; const execFileAsync = promisify(execFile); export const SWAGGER_PATH = "coderd/apidoc/swagger.json"; export const openApiDir = (appDir) => path.join(appDir, ".generated", "openapi"); -/** The Swagger document beside a `docs/` tree on disk, or undefined when there is none. */ -export async function swaggerFromTree(docsRoot) { - const file = process.env.DOCS_OPENAPI_FILE ?? path.join(docsRoot, "..", SWAGGER_PATH); +function parseSwagger(text, where) { try { - return JSON.parse(await readFile(file, "utf8")); - } catch (error) { - if (error?.code === "ENOENT") return undefined; - throw error; + return JSON.parse(text); + } catch { + throw new Error(`${SWAGGER_PATH} at ${where} is not valid JSON`); } } +/** + * The Swagger document of the checkout a `docs/` tree sits in, or undefined + * when there is none. Read with the docs tree's own guarantees: no symbolic + * links, a regular file under the per-file cap, inside the checkout. + */ +export async function swaggerFromTree(docsRoot) { + const checkout = path.dirname(path.resolve(docsRoot)); + const text = await readContainedFile(checkout, SWAGGER_PATH, DEFAULT_MAX_FILE_BYTES); + return text === undefined ? undefined : parseSwagger(text, checkout); +} + /** The Swagger document at a ref of the sync's cached clone, or undefined when the ref has none. */ export async function swaggerFromClone(cacheDir, ref) { for (const rev of [`refs/remotes/origin/${ref}`, `refs/tags/${ref}`, ref]) { + let stdout; try { - const { stdout } = await execFileAsync("git", ["-C", cacheDir, "show", `${rev}:${SWAGGER_PATH}`], { - maxBuffer: 64 * 1024 * 1024, - }); - return JSON.parse(stdout); - } catch { - // try the next form of the ref + // A blob over the cap fails the read rather than being buffered. + ({ stdout } = await execFileAsync("git", ["-C", cacheDir, "show", `${rev}:${SWAGGER_PATH}`], { + maxBuffer: DEFAULT_MAX_FILE_BYTES, + })); + } catch (error) { + if (error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") { + throw new Error( + `${SWAGGER_PATH} at ${ref} is over the ${DEFAULT_MAX_FILE_BYTES}-byte limit`, + ); + } + continue; } + return parseSwagger(stdout, ref); } return undefined; } @@ -71,6 +87,7 @@ export async function withOpenApiReference(appDir, version, source, swagger) { console.log( `[sync] ${version.id}: API reference from ${SWAGGER_PATH}, ${Object.keys(reference.operations).length} operation pages in ${Date.now() - started} ms`, ); - for (const warning of reference.warnings) console.warn(`[sync] ${version.id}: openapi: ${warning}`); + for (const warning of reference.warnings) + console.warn(`[sync] ${version.id}: openapi: ${warning}`); return next; } diff --git a/apps/docs/scripts/openapi-source.test.mjs b/apps/docs/scripts/openapi-source.test.mjs new file mode 100644 index 00000000..37f7c877 --- /dev/null +++ b/apps/docs/scripts/openapi-source.test.mjs @@ -0,0 +1,44 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import { swaggerFromTree } from "./openapi-source.mjs"; + +async function checkout() { + const root = await mkdtemp(path.join(tmpdir(), "openapi-source-")); + await mkdir(path.join(root, "docs")); + await mkdir(path.join(root, "coderd", "apidoc"), { recursive: true }); + return root; +} + +test("reads the Swagger document beside the docs tree", async () => { + const root = await checkout(); + await writeFile(path.join(root, "coderd", "apidoc", "swagger.json"), '{"swagger":"2.0"}'); + assert.deepEqual(await swaggerFromTree(path.join(root, "docs")), { swagger: "2.0" }); +}); + +test("a symlinked swagger.json is rejected and its target never surfaces", async () => { + const root = await checkout(); + const outside = await mkdtemp(path.join(tmpdir(), "openapi-source-secret-")); + await writeFile(path.join(outside, "secret.json"), '{"secret":"do-not-leak"}'); + await symlink( + path.join(outside, "secret.json"), + path.join(root, "coderd", "apidoc", "swagger.json"), + ); + await assert.rejects(swaggerFromTree(path.join(root, "docs")), (error) => { + assert.match(error.message, /symbolic link/); + assert.doesNotMatch(error.message, /do-not-leak/); + return true; + }); +}); + +test("invalid JSON is reported without the file's content", async () => { + const root = await checkout(); + await writeFile(path.join(root, "coderd", "apidoc", "swagger.json"), "not json do-not-leak"); + await assert.rejects(swaggerFromTree(path.join(root, "docs")), (error) => { + assert.match(error.message, /is not valid JSON/); + assert.doesNotMatch(error.message, /do-not-leak/); + return true; + }); +}); diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts new file mode 100644 index 00000000..0db2725d --- /dev/null +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -0,0 +1,91 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { test } from "node:test"; +import type { DocSource } from "@coder/docs-config"; +import { applyOpenApiReference } from "./openapi-reference.js"; + +const swagger = JSON.parse( + await readFile( + new URL("../../../apps/docs/fixtures/openapi/swagger.json", import.meta.url), + "utf8", + ), +); + +const source: DocSource = { + files: [ + { path: "reference/api/index.md", content: "# REST API\n" }, + { path: "reference/api/users.md", content: "# Users\n\n## Create new user\n" }, + { path: "reference/api/workspaces.md", content: "# Workspaces\n\n## List workspaces\n" }, + { path: "reference/api/schemas.md", content: "# Schemas\n\n## codersdk.User\n" }, + ], + images: [], + manifest: { + versions: ["main"], + routes: [ + { + title: "REST API", + path: "./reference/api/index.md", + children: [ + { title: "Users", path: "./reference/api/users.md" }, + { title: "Workspaces", path: "./reference/api/workspaces.md" }, + { title: "Schemas", path: "./reference/api/schemas.md" }, + ], + }, + ], + }, +}; + +test("each documented operation gets a page under its tag, named by the old anchor", async () => { + const { source: out, reference } = await applyOpenApiReference(source, swagger); + assert.deepEqual(reference.operations, { + "reference/api/workspaces/list-workspaces": { method: "get", path: "/api/v2/workspaces" }, + "reference/api/users/create-new-user": { method: "post", path: "/api/v2/users" }, + "reference/api/users/get-user-by-name": { method: "get", path: "/api/v2/users/{user}" }, + }); + const paths = out.files.map((file) => file.path).sort(); + assert.ok(paths.includes("reference/api/users/create-new-user.md")); + assert.ok(!paths.some((p) => p.includes("pprof")), "x-apidocgen skip is honoured"); + const users = out.manifest.routes[0]?.children?.find((c) => c.title === "Users"); + assert.deepEqual( + users?.children?.map((c) => c.path), + ["./reference/api/users/create-new-user.md", "./reference/api/users/get-user-by-name.md"], + ); +}); + +test("old tag and schema anchors redirect to the operation pages", async () => { + const { reference } = await applyOpenApiReference(source, swagger); + assert.equal( + reference.anchors["reference/api/users"]?.["get-user-by-name"], + "reference/api/users/get-user-by-name", + ); + assert.equal( + reference.anchors["reference/api/schemas"]?.["codersdkworkspace"], + "reference/api/workspaces/list-workspaces", + ); +}); + +test("the try-it server is the reader's deployment, not the docs site", async () => { + const { reference } = await applyOpenApiReference(source, swagger); + assert.deepEqual(reference.document.servers, [ + { + url: "{deployment}", + variables: { + deployment: { + default: "https://coder.example.com", + description: "The URL of your Coder deployment", + }, + }, + }, + ]); +}); + +test("a Swagger document with an external $ref is rejected before conversion", async () => { + for (const ref of ["https://example.com/schema.json", "../x.json"]) { + const hostile = structuredClone(swagger); + hostile.definitions["codersdk.User"].properties.id = { $ref: ref }; + await assert.rejects( + applyOpenApiReference(source, hostile), + /\$ref at \/definitions\/codersdk\.User\/properties\/id\/\$ref is not an in-document reference/, + ); + } +}); diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 81060672..362c40cf 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -1,4 +1,4 @@ -import type { DocFile, DocSource, ManifestNode } from "@coder/docs-config"; +import { assertInDocumentRefs, type DocFile, type DocSource, type ManifestNode } from "@coder/docs-config"; import { buildDirRoutes, mapMdPath } from "@coder/docs-transforms"; import GithubSlugger from "github-slugger"; import { validate } from "oas-validator"; @@ -77,7 +77,13 @@ function schemaDepths(roots: unknown, schemas: Json): Map { /** Converts Swagger 2.0 to OpenAPI 3, repairs the defects that make it invalid, and validates it. */ export async function convertSwagger(swagger: unknown): Promise<{ document: Json; warnings: string[] }> { const warnings: string[] = []; - const converted = await convertObj(swagger, { patch: true, warnOnly: true }); + assertInDocumentRefs(swagger, "swagger.json"); + const converted = await convertObj(swagger, { + patch: true, + warnOnly: true, + resolve: false, + resolveInternal: false, + }); const document = converted.openapi; if (converted.patches) warnings.push(`swagger2openapi patched ${converted.patches} defect(s)`); for (const warning of converted.warnings ?? []) warnings.push(`swagger2openapi: ${JSON.stringify(warning)}`); @@ -113,7 +119,13 @@ export async function convertSwagger(swagger: unknown): Promise<{ document: Json } } - const result = await validate(document, { lint: false, prettify: false, warnOnly: true }); + assertInDocumentRefs(document, "the converted OpenAPI document"); + const result = await validate(document, { + lint: false, + prettify: false, + warnOnly: true, + resolve: false, + }); if (!result.valid) throw new Error("the converted OpenAPI document is not valid"); return { document, warnings }; } @@ -195,14 +207,14 @@ export async function applyOpenApiReference( const generated = new Map(); const tagFile = (tag: string) => `${dir}/${tagSlug(tag)}.md`; for (const [tag, { ops }] of byTag) { - const rows = ops.map( + const items = ops.map( (op) => - `| [${cell(op.summary)}](./${op.file.slice(dir.length + 1)}) | \`${op.method.toUpperCase()} ${op.path}\` |`, + `- [${op.summary}](./${op.file.slice(dir.length + 1)}): \`${op.method.toUpperCase()} ${op.path}\``, ); const description = tagInfo.get(tag); generated.set( tagFile(tag), - `${frontmatter(tag)}${description ? `${description}\n\n` : ""}| Endpoint | Request |\n| --- | --- |\n${rows.join("\n")}\n`, + `${frontmatter(tag)}${description ? `${description}\n\n` : ""}${items.join("\n")}\n`, ); for (const op of ops) { const lines = [`\`${op.method.toUpperCase()} ${op.path}\``]; diff --git a/packages/docs-config/src/index.ts b/packages/docs-config/src/index.ts index 02d5b705..cd5160fb 100644 --- a/packages/docs-config/src/index.ts +++ b/packages/docs-config/src/index.ts @@ -106,3 +106,4 @@ export { } from "./analytics.js"; export { USER_CONTENT_PREFIX } from "./user-content.js"; +export { assertInDocumentRefs, findExternalRef } from "./openapi-refs.js"; diff --git a/packages/docs-config/src/openapi-refs.test.ts b/packages/docs-config/src/openapi-refs.test.ts new file mode 100644 index 00000000..361ad568 --- /dev/null +++ b/packages/docs-config/src/openapi-refs.test.ts @@ -0,0 +1,16 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { assertInDocumentRefs, findExternalRef } from "./openapi-refs.js"; + +test("in-document references pass", () => { + assert.equal(findExternalRef({ a: { $ref: "#/definitions/x" }, b: [{ $ref: "#/c" }] }), undefined); +}); + +test("a URL or file reference is found by its JSON pointer", () => { + assert.equal( + findExternalRef({ paths: { "/a/b": { get: { schema: { $ref: "https://example.com/x.json" } } } } }), + "/paths/~1a~1b/get/schema/$ref", + ); + assert.equal(findExternalRef({ list: [{}, { $ref: "../x.json" }] }), "/list/1/$ref"); + assert.throws(() => assertInDocumentRefs({ $ref: "../x.json" }, "swagger.json"), /\$ref at \/\$ref/); +}); diff --git a/packages/docs-config/src/openapi-refs.ts b/packages/docs-config/src/openapi-refs.ts new file mode 100644 index 00000000..31f7a278 --- /dev/null +++ b/packages/docs-config/src/openapi-refs.ts @@ -0,0 +1,32 @@ +const escapePointer = (key: string) => key.replace(/~/g, "~0").replace(/\//g, "~1"); + +/** + * The JSON pointer of the first `$ref` that is not an in-document reference + * (`#/...`), or `undefined` when there is none. An OpenAPI bundler fetches or + * reads any other reference at build time, so an API document has to be + * rejected before it reaches one. + */ +export function findExternalRef(value: unknown, pointer = ""): string | undefined { + if (Array.isArray(value)) { + for (const [index, item] of value.entries()) { + const found = findExternalRef(item, `${pointer}/${index}`); + if (found !== undefined) return found; + } + } else if (typeof value === "object" && value !== null) { + for (const [key, child] of Object.entries(value)) { + const at = `${pointer}/${escapePointer(key)}`; + if (key === "$ref" && (typeof child !== "string" || !child.startsWith("#/"))) return at; + const found = findExternalRef(child, at); + if (found !== undefined) return found; + } + } + return undefined; +} + +/** Throws, naming the JSON pointer, when the document holds a `$ref` that is not `#/...`. */ +export function assertInDocumentRefs(document: unknown, label: string): void { + const pointer = findExternalRef(document); + if (pointer !== undefined) { + throw new Error(`${label}: $ref at ${pointer || "/"} is not an in-document reference (#/...)`); + } +} diff --git a/packages/docs-next/src/openapi/index.tsx b/packages/docs-next/src/openapi/index.tsx index e4856348..b2b5c678 100644 --- a/packages/docs-next/src/openapi/index.tsx +++ b/packages/docs-next/src/openapi/index.tsx @@ -1,3 +1,4 @@ +import { assertInDocumentRefs } from "@coder/docs-config"; import type { Document } from "fumadocs-openapi"; import { createOpenAPI } from "fumadocs-openapi/server"; import type { RenderBody } from "../types.js"; @@ -78,6 +79,8 @@ export function createOpenApiRenderBody( const bundle = (versionId: string | undefined, document: Json): Promise => { let cached = bundled.get(versionId); if (!cached) { + // The bundler fetches or reads any other reference, so only in-document ones may reach it. + assertInDocumentRefs(document, "the API document"); const server = createOpenAPI({ input: { coder: () => document as Document } }); cached = server.getSchema("coder").then((schema) => schema.bundled as Json); bundled.set(versionId, cached); diff --git a/packages/docs-sources/src/contained-file.test.ts b/packages/docs-sources/src/contained-file.test.ts new file mode 100644 index 00000000..9408a0f3 --- /dev/null +++ b/packages/docs-sources/src/contained-file.test.ts @@ -0,0 +1,50 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import { readContainedFile } from "./contained-file.js"; + +async function checkout() { + const root = await mkdtemp(path.join(tmpdir(), "contained-file-")); + await mkdir(path.join(root, "coderd", "apidoc"), { recursive: true }); + return root; +} + +test("reads a regular file inside the checkout", async () => { + const root = await checkout(); + await writeFile(path.join(root, "coderd", "apidoc", "swagger.json"), "{}"); + assert.equal(await readContainedFile(root, "coderd/apidoc/swagger.json"), "{}"); +}); + +test("a missing file is undefined", async () => { + const root = await checkout(); + assert.equal(await readContainedFile(root, "coderd/apidoc/swagger.json"), undefined); +}); + +test("rejects a symlinked file without reading the target", async () => { + const root = await checkout(); + const outside = await mkdtemp(path.join(tmpdir(), "contained-file-secret-")); + await writeFile(path.join(outside, "secret"), "top secret"); + await symlink(path.join(outside, "secret"), path.join(root, "coderd", "apidoc", "swagger.json")); + await assert.rejects(readContainedFile(root, "coderd/apidoc/swagger.json"), (error: Error) => { + assert.match(error.message, /symbolic link/); + assert.doesNotMatch(error.message, /top secret/); + return true; + }); +}); + +test("rejects a symlinked directory on the way", async () => { + const root = await checkout(); + const outside = await mkdtemp(path.join(tmpdir(), "contained-file-dir-")); + await writeFile(path.join(outside, "swagger.json"), "{}"); + await symlink(outside, path.join(root, "coderd", "linked")); + await assert.rejects(readContainedFile(root, "coderd/linked/swagger.json"), /symbolic link/); +}); + +test("rejects an oversized file and a path that climbs out", async () => { + const root = await checkout(); + await writeFile(path.join(root, "coderd", "apidoc", "swagger.json"), "x".repeat(20)); + await assert.rejects(readContainedFile(root, "coderd/apidoc/swagger.json", 10), /per-file limit/); + await assert.rejects(readContainedFile(root, "../etc/passwd"), /inside the checkout/); +}); diff --git a/packages/docs-sources/src/contained-file.ts b/packages/docs-sources/src/contained-file.ts new file mode 100644 index 00000000..75bfb40b --- /dev/null +++ b/packages/docs-sources/src/contained-file.ts @@ -0,0 +1,54 @@ +import { lstat, readFile, realpath } from "node:fs/promises"; +import path from "node:path"; +import { DEFAULT_MAX_FILE_BYTES } from "./read-tree.js"; + +/** + * Reads one file of a checkout by its path relative to the checkout root, + * with the same guarantees the tree walk gives the docs tree: no symbolic + * link anywhere from the root down, a regular file, under the per-file size + * cap, and still inside the root once resolved. Returns `undefined` when the + * file does not exist. Errors name the path, never the content. + */ +export async function readContainedFile( + root: string, + relPath: string, + maxBytes: number = DEFAULT_MAX_FILE_BYTES, +): Promise { + if (path.isAbsolute(relPath) || relPath.split(/[\\/]/).includes("..")) { + throw new Error(`@coder/docs-sources: ${relPath} must be a path inside the checkout`); + } + const rootStat = await lstat(root); + if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) { + throw new Error(`@coder/docs-sources: ${root} is not a real directory`); + } + let current = root; + const segments = relPath.split(/[\\/]/).filter(Boolean); + for (const [index, segment] of segments.entries()) { + current = path.join(current, segment); + let info; + try { + info = await lstat(current); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; + throw error; + } + if (info.isSymbolicLink()) { + throw new Error(`@coder/docs-sources: ${relPath} passes through a symbolic link`); + } + const last = index === segments.length - 1; + if (last ? !info.isFile() : !info.isDirectory()) { + throw new Error(`@coder/docs-sources: ${relPath} is not a regular file`); + } + if (last && info.size > maxBytes) { + throw new Error( + `@coder/docs-sources: ${relPath} is ${info.size} bytes, over the ${maxBytes}-byte per-file limit`, + ); + } + } + const realRoot = await realpath(root); + const realFile = await realpath(current); + if (!realFile.startsWith(`${realRoot}${path.sep}`)) { + throw new Error(`@coder/docs-sources: ${relPath} resolves outside the checkout`); + } + return readFile(realFile, "utf8"); +} diff --git a/packages/docs-sources/src/index.ts b/packages/docs-sources/src/index.ts index 89bf6055..7f388be3 100644 --- a/packages/docs-sources/src/index.ts +++ b/packages/docs-sources/src/index.ts @@ -21,3 +21,4 @@ export { redactRepoUrl, } from "./git-refs.js"; export { readGitLastModified } from "./last-modified.js"; +export { readContainedFile } from "./contained-file.js"; From c2f01d2661b1ca8fe397cb3b6c3f0c507919314f Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 00:59:21 -0400 Subject: [PATCH 03/69] fix(api-reference): pass the axe pass on the API pages The method badges and links fumadocs-openapi draws use -600 and -400 shades that fall short of 4.5:1 on its card surface, and of 7:1 under More contrast, so the theme darkens or lightens them inside the API page only. Its code blocks leave their scroll regions unnamed, which made every block on a page the same landmark; each now carries its language as its name. The fixture API pages join the axe pass, and the fixture's moved anchors are approved in the URL parity check, since the tag and schemas pages redirect them. Assisted-by: AI --- apps/docs/fixtures/url-parity-approved.json | 51 ++++++++++++++++++- apps/docs/scripts/a11y-axe-helpers.mjs | 5 +- packages/docs-build/src/openapi-reference.ts | 26 +++++++--- packages/docs-config/src/openapi-refs.test.ts | 14 +++-- packages/docs-next/src/openapi/api-page.tsx | 24 ++++++++- packages/docs-next/src/openapi/index.tsx | 16 +++--- packages/docs-theme/src/brand.css | 45 ++++++++++++++++ 7 files changed, 162 insertions(+), 19 deletions(-) diff --git a/apps/docs/fixtures/url-parity-approved.json b/apps/docs/fixtures/url-parity-approved.json index fe51488c..0aa8c4d0 100644 --- a/apps/docs/fixtures/url-parity-approved.json +++ b/apps/docs/fixtures/url-parity-approved.json @@ -1 +1,50 @@ -[] +[ + { + "kind": "anchor-missing", + "url": "/docs/reference/api/users", + "anchor": "create-new-user", + "reason": "operation moved to its own page; the tag page redirects the anchor" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/users", + "anchor": "get-user-by-name", + "reason": "operation moved to its own page; the tag page redirects the anchor" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/users", + "anchor": "responses", + "reason": "per-operation subsection, now on the operation page" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/users", + "anchor": "responses-1", + "reason": "per-operation subsection, now on the operation page" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/workspaces", + "anchor": "list-workspaces", + "reason": "operation moved to its own page; the tag page redirects the anchor" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/workspaces", + "anchor": "responses", + "reason": "per-operation subsection, now on the operation page" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/schemas", + "anchor": "codersdkuser", + "reason": "schemas render on the operation pages; the schemas page redirects the anchor" + }, + { + "kind": "anchor-missing", + "url": "/docs/reference/api/schemas", + "anchor": "codersdkworkspacesresponse", + "reason": "schemas render on the operation pages; the schemas page redirects the anchor" + } +] diff --git a/apps/docs/scripts/a11y-axe-helpers.mjs b/apps/docs/scripts/a11y-axe-helpers.mjs index 082d5730..17505474 100644 --- a/apps/docs/scripts/a11y-axe-helpers.mjs +++ b/apps/docs/scripts/a11y-axe-helpers.mjs @@ -20,8 +20,11 @@ export const DEFAULT_PAGES = [ "/authoring/releases", "/authoring/callouts", "/authoring/states", + "/reference/api/users", + "/reference/api/users/create-new-user", + "/reference/api/workspaces/list-workspaces", ]; -export const DEFAULT_MOBILE_PAGES = ["/", "/authoring/tables"]; +export const DEFAULT_MOBILE_PAGES = ["/", "/authoring/tables", "/reference/api/users/create-new-user"]; // The search dialog is scanned open on this page, with a query the fixture corpus matches. export const SEARCH_PAGE = "/"; export const SEARCH_QUERY = "code"; diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 362c40cf..4262fbdc 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -1,4 +1,9 @@ -import { assertInDocumentRefs, type DocFile, type DocSource, type ManifestNode } from "@coder/docs-config"; +import { + assertInDocumentRefs, + type DocFile, + type DocSource, + type ManifestNode, +} from "@coder/docs-config"; import { buildDirRoutes, mapMdPath } from "@coder/docs-transforms"; import GithubSlugger from "github-slugger"; import { validate } from "oas-validator"; @@ -75,7 +80,9 @@ function schemaDepths(roots: unknown, schemas: Json): Map { } /** Converts Swagger 2.0 to OpenAPI 3, repairs the defects that make it invalid, and validates it. */ -export async function convertSwagger(swagger: unknown): Promise<{ document: Json; warnings: string[] }> { +export async function convertSwagger( + swagger: unknown, +): Promise<{ document: Json; warnings: string[] }> { const warnings: string[] = []; assertInDocumentRefs(swagger, "swagger.json"); const converted = await convertObj(swagger, { @@ -86,7 +93,8 @@ export async function convertSwagger(swagger: unknown): Promise<{ document: Json }); const document = converted.openapi; if (converted.patches) warnings.push(`swagger2openapi patched ${converted.patches} defect(s)`); - for (const warning of converted.warnings ?? []) warnings.push(`swagger2openapi: ${JSON.stringify(warning)}`); + for (const warning of converted.warnings ?? []) + warnings.push(`swagger2openapi: ${JSON.stringify(warning)}`); const components = isObject(document.components) ? document.components : {}; const schemes = isObject(components.securitySchemes) ? components.securitySchemes : {}; @@ -101,7 +109,9 @@ export async function convertSwagger(swagger: unknown): Promise<{ document: Json (name) => !(name in schemes), ); for (const name of unknown) { - warnings.push(`${method.toUpperCase()} ${route}: security scheme ${name} is not defined; dropped`); + warnings.push( + `${method.toUpperCase()} ${route}: security scheme ${name} is not defined; dropped`, + ); } return unknown.length === 0; }); @@ -191,7 +201,9 @@ export async function applyOpenApiReference( let group = byTag.get(tag); if (!group) byTag.set(tag, (group = { slugger: new GithubSlugger(), ops: [] })); const summary = - typeof operation.summary === "string" ? operation.summary : `${method.toUpperCase()} ${route}`; + typeof operation.summary === "string" + ? operation.summary + : `${method.toUpperCase()} ${route}`; group.ops.push({ method, path: route, @@ -242,7 +254,9 @@ export async function applyOpenApiReference( const anchor = schemaSlugger.slug(name); if (best) { schemaTargets.set(anchor, best); - schemaRows.push(`| \`${name}\` | [${cell(best.summary)}](./${best.file.slice(dir.length + 1)}) |`); + schemaRows.push( + `| \`${name}\` | [${cell(best.summary)}](./${best.file.slice(dir.length + 1)}) |`, + ); } else { schemaRows.push(`| \`${name}\` | Not used by a documented endpoint |`); } diff --git a/packages/docs-config/src/openapi-refs.test.ts b/packages/docs-config/src/openapi-refs.test.ts index 361ad568..81b9f5c3 100644 --- a/packages/docs-config/src/openapi-refs.test.ts +++ b/packages/docs-config/src/openapi-refs.test.ts @@ -3,14 +3,22 @@ import { test } from "node:test"; import { assertInDocumentRefs, findExternalRef } from "./openapi-refs.js"; test("in-document references pass", () => { - assert.equal(findExternalRef({ a: { $ref: "#/definitions/x" }, b: [{ $ref: "#/c" }] }), undefined); + assert.equal( + findExternalRef({ a: { $ref: "#/definitions/x" }, b: [{ $ref: "#/c" }] }), + undefined, + ); }); test("a URL or file reference is found by its JSON pointer", () => { assert.equal( - findExternalRef({ paths: { "/a/b": { get: { schema: { $ref: "https://example.com/x.json" } } } } }), + findExternalRef({ + paths: { "/a/b": { get: { schema: { $ref: "https://example.com/x.json" } } } }, + }), "/paths/~1a~1b/get/schema/$ref", ); assert.equal(findExternalRef({ list: [{}, { $ref: "../x.json" }] }), "/list/1/$ref"); - assert.throws(() => assertInDocumentRefs({ $ref: "../x.json" }, "swagger.json"), /\$ref at \/\$ref/); + assert.throws( + () => assertInDocumentRefs({ $ref: "../x.json" }, "swagger.json"), + /\$ref at \/\$ref/, + ); }); diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index 9d84a7f1..3e2c553c 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -1,9 +1,11 @@ "use client"; import { createShikiFactory } from "fumadocs-core/highlight/shiki"; +import type { CodeBlockProps } from "fumadocs-openapi"; import { createCodeUsageGeneratorRegistry } from "fumadocs-openapi/requests/generators"; import { curl } from "fumadocs-openapi/requests/generators/curl"; import { createOpenAPIPageBase } from "fumadocs-openapi/ui/base"; +import { DynamicCodeBlock } from "fumadocs-ui/components/dynamic-codeblock.core"; // Only the grammars and themes an API page uses (JSON, the cURL sample, TypeScript definitions), on the JavaScript regex engine (no WASM, no eval). const shiki = createShikiFactory({ @@ -30,10 +32,30 @@ const shiki = createShikiFactory({ const codeUsages = createCodeUsageGeneratorRegistry(); codeUsages.add("curl", curl); +const shikiOptions = { + themes: { light: "github-light-high-contrast", dark: "github-dark-default" }, +} as const; + +// fumadocs-openapi's default code block leaves its scroll region unnamed, so every block on a page is the same landmark. +function CodeBlock(props: CodeBlockProps) { + return ( + shiki.getOrInit()} + options={shikiOptions} + {...props} + codeblock={{ + ...props.codeblock, + viewportProps: { ...props.codeblock?.viewportProps, "aria-label": `${props.lang} code` }, + }} + /> + ); +} + /** One REST API operation, rendered by fumadocs-openapi from the document its page was given. */ export const ApiPage = createOpenAPIPageBase({ shiki, - shikiOptions: { themes: { light: "github-light-high-contrast", dark: "github-dark-default" } }, + shikiOptions, + components: { CodeBlock }, codeUsages, storageKeyPrefix: "coder-api-", }); diff --git a/packages/docs-next/src/openapi/index.tsx b/packages/docs-next/src/openapi/index.tsx index b2b5c678..1281f4e3 100644 --- a/packages/docs-next/src/openapi/index.tsx +++ b/packages/docs-next/src/openapi/index.tsx @@ -102,13 +102,15 @@ export function createOpenApiRenderBody( return { full: true, replace: ( - +
+ +
), }; } diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css index c8b6b9ed..402971ce 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -676,3 +676,48 @@ samp { visibility: hidden; transition-property: width, inset-block, transform, translate, background-color, visibility; } + +/* fumadocs-openapi's method badges and links are -600/-400 shades that fall short of 4.5:1 (7:1 for More contrast) on its card surface. */ +:root:not(.dark) .coder-api-page { + --color-green-600: oklch(45% 0.13 150); + --color-blue-600: oklch(48% 0.2 262); + --color-orange-600: oklch(50% 0.15 50); + --color-yellow-600: oklch(48% 0.11 85); + --color-red-600: oklch(50% 0.2 27); +} + +:root[data-contrast="more"]:not(.dark) .coder-api-page { + --color-green-600: oklch(38% 0.1 150); + --color-blue-600: oklch(40% 0.18 262); + --color-orange-600: oklch(42% 0.13 50); + --color-yellow-600: oklch(40% 0.09 85); + --color-red-600: oklch(42% 0.17 27); +} + +:root[data-contrast="more"].dark .coder-api-page { + --color-fd-primary: hsl(213 94% 82%); + --color-green-400: oklch(88% 0.15 150); + --color-blue-400: oklch(85% 0.1 262); + --color-orange-400: oklch(86% 0.1 60); + --color-yellow-400: oklch(90% 0.13 95); + --color-red-400: oklch(85% 0.1 25); +} + +@media (prefers-contrast: more) { + :root:not([data-contrast="standard"]):not(.dark) .coder-api-page { + --color-green-600: oklch(38% 0.1 150); + --color-blue-600: oklch(40% 0.18 262); + --color-orange-600: oklch(42% 0.13 50); + --color-yellow-600: oklch(40% 0.09 85); + --color-red-600: oklch(42% 0.17 27); + } + + :root:not([data-contrast="standard"]).dark .coder-api-page { + --color-fd-primary: hsl(213 94% 82%); + --color-green-400: oklch(88% 0.15 150); + --color-blue-400: oklch(85% 0.1 262); + --color-orange-400: oklch(86% 0.1 60); + --color-yellow-400: oklch(90% 0.13 95); + --color-red-400: oklch(85% 0.1 25); + } +} From 6168236fcd6fc2ae6245f3192b903921d03411b3 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 01:05:27 -0400 Subject: [PATCH 04/69] fix(docs-theme): recolour API links under More contrast without touching the theme token The contrast check only allows theme tokens in the known :root selectors, so the dark More-contrast override for the API page's links sets their colour directly instead of redefining --color-fd-primary. Assisted-by: AI --- apps/docs/scripts/a11y-axe-helpers.mjs | 6 +++++- packages/docs-theme/src/brand.css | 12 ++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/apps/docs/scripts/a11y-axe-helpers.mjs b/apps/docs/scripts/a11y-axe-helpers.mjs index 17505474..099bb96d 100644 --- a/apps/docs/scripts/a11y-axe-helpers.mjs +++ b/apps/docs/scripts/a11y-axe-helpers.mjs @@ -24,7 +24,11 @@ export const DEFAULT_PAGES = [ "/reference/api/users/create-new-user", "/reference/api/workspaces/list-workspaces", ]; -export const DEFAULT_MOBILE_PAGES = ["/", "/authoring/tables", "/reference/api/users/create-new-user"]; +export const DEFAULT_MOBILE_PAGES = [ + "/", + "/authoring/tables", + "/reference/api/users/create-new-user", +]; // The search dialog is scanned open on this page, with a query the fixture corpus matches. export const SEARCH_PAGE = "/"; export const SEARCH_QUERY = "code"; diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css index 402971ce..def077aa 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -695,7 +695,6 @@ samp { } :root[data-contrast="more"].dark .coder-api-page { - --color-fd-primary: hsl(213 94% 82%); --color-green-400: oklch(88% 0.15 150); --color-blue-400: oklch(85% 0.1 262); --color-orange-400: oklch(86% 0.1 60); @@ -713,7 +712,6 @@ samp { } :root:not([data-contrast="standard"]).dark .coder-api-page { - --color-fd-primary: hsl(213 94% 82%); --color-green-400: oklch(88% 0.15 150); --color-blue-400: oklch(85% 0.1 262); --color-orange-400: oklch(86% 0.1 60); @@ -721,3 +719,13 @@ samp { --color-red-400: oklch(85% 0.1 25); } } + +:root[data-contrast="more"].dark .coder-api-page .text-fd-primary { + color: hsl(213 94% 82%); +} + +@media (prefers-contrast: more) { + :root:not([data-contrast="standard"]).dark .coder-api-page .text-fd-primary { + color: hsl(213 94% 82%); + } +} From edf5a68e1c44745e0c6deeeffd7286ad5ee608ff Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 06:19:44 -0400 Subject: [PATCH 05/69] fix(api-reference): escape backslashes and Markdown syntax in operation summaries The tag and schemas pages put each summary in Markdown link text, and the old helper escaped table pipes but not the backslash that escapes them, so a summary ending in a backslash could break the table. Summaries are plain text, so every character Markdown would read as syntax is escaped. Assisted-by: AI --- packages/docs-build/src/openapi-reference.test.ts | 8 ++++++++ packages/docs-build/src/openapi-reference.ts | 11 ++++++++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index 0db2725d..f90c2ff1 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -89,3 +89,11 @@ test("a Swagger document with an external $ref is rejected before conversion", a ); } }); + +test("summaries are escaped where the tag and schemas pages put them in Markdown", async () => { + const tricky = structuredClone(swagger); + tricky.paths["/api/v2/workspaces"].get.summary = "List [all] a|b \\ *workspaces*"; + const { source: out } = await applyOpenApiReference(source, tricky); + const tagPage = out.files.find((file) => file.path === "reference/api/workspaces.md")?.content; + assert.match(tagPage ?? "", /- \[List \\\[all\\\] a\\\|b \\\\ \\\*workspaces\\\*\]\(/); +}); diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 4262fbdc..37ea0e34 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -43,7 +43,12 @@ const isObject = (value: unknown): value is Json => export const tagSlug = (tag: string): string => tag.toLowerCase().replace(/[^a-z0-9]/g, ""); -const cell = (text: string): string => text.replace(/\|/g, "\\|").replace(/\s+/g, " ").trim(); +// Summaries are plain text: escape what Markdown would read as link, table, or emphasis syntax. +const linkText = (text: string): string => + text + .replace(/[\\`*_[\]<>|]/g, (char) => `\\${char}`) + .replace(/\s+/g, " ") + .trim(); const frontmatter = (title: string): string => `---\ntitle: ${JSON.stringify(title)}\n---\n\n`; @@ -221,7 +226,7 @@ export async function applyOpenApiReference( for (const [tag, { ops }] of byTag) { const items = ops.map( (op) => - `- [${op.summary}](./${op.file.slice(dir.length + 1)}): \`${op.method.toUpperCase()} ${op.path}\``, + `- [${linkText(op.summary)}](./${op.file.slice(dir.length + 1)}): \`${op.method.toUpperCase()} ${op.path}\``, ); const description = tagInfo.get(tag); generated.set( @@ -255,7 +260,7 @@ export async function applyOpenApiReference( if (best) { schemaTargets.set(anchor, best); schemaRows.push( - `| \`${name}\` | [${cell(best.summary)}](./${best.file.slice(dir.length + 1)}) |`, + `| \`${name}\` | [${linkText(best.summary)}](./${best.file.slice(dir.length + 1)}) |`, ); } else { schemaRows.push(`| \`${name}\` | Not used by a documented endpoint |`); From 9ffecca98411a7e65ac25ff467f4022c707bc54a Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 07:03:17 -0400 Subject: [PATCH 06/69] feat(api-reference): show a copyable curl command instead of the playground The playground's Send can never reach a Coder deployment from the docs origin: coderd's CORS answers the Coder-Session-Token preflight with no Access-Control-Allow-Origin, and even CODER_DANGEROUS_ALLOW_ALL_CORS does not allow that header. It also kept the reader's token in sessionStorage on the docs origin. Each operation page now carries one curl command, built on the server from the spec and handed to fumadocs-openapi as the operation's x-codeSamples, so it renders in the same example panel and code block as before. The deployment URL comes from `coder whoami -o json` and the token from `coder login token`, both substituted by the shell, so the token is never typed, shown, or written to shell history. Path parameters and required query and header parameters stay {name} placeholders; a JSON body is the schema's example or a sample of its required fields (the first three fields when none are required), and operations without security send no token. The playground is off, the default code generators are replaced by an empty registry, and the server URL variable the playground needed is gone from the document. Assisted-by: AI --- .../docs-build/src/openapi-reference.test.ts | 14 +- packages/docs-build/src/openapi-reference.ts | 15 +- packages/docs-next/package.json | 2 + packages/docs-next/src/openapi/api-page.tsx | 24 ++- packages/docs-next/src/openapi/curl.test.ts | 192 ++++++++++++++++++ packages/docs-next/src/openapi/curl.ts | 170 ++++++++++++++++ packages/docs-next/src/openapi/index.tsx | 6 +- pnpm-lock.yaml | 6 + 8 files changed, 394 insertions(+), 35 deletions(-) create mode 100644 packages/docs-next/src/openapi/curl.test.ts create mode 100644 packages/docs-next/src/openapi/curl.ts diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index f90c2ff1..8f3a2da4 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -64,19 +64,9 @@ test("old tag and schema anchors redirect to the operation pages", async () => { ); }); -test("the try-it server is the reader's deployment, not the docs site", async () => { +test("the API document names no server, since readers call their own deployment", async () => { const { reference } = await applyOpenApiReference(source, swagger); - assert.deepEqual(reference.document.servers, [ - { - url: "{deployment}", - variables: { - deployment: { - default: "https://coder.example.com", - description: "The URL of your Coder deployment", - }, - }, - }, - ]); + assert.equal(reference.document.servers, undefined); }); test("a Swagger document with an external $ref is rejected before conversion", async () => { diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 37ea0e34..3113d6f5 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -32,8 +32,6 @@ export interface OpenApiReference { export interface ApplyOpenApiReferenceOptions { /** The docs-relative directory of the generated reference; defaults to `reference/api`. */ dir?: string; - /** The server URL template the try-it panel sends to; the reader fills in `{deployment}`. */ - server?: { url: string; variables?: Record }; } const METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"] as const; @@ -160,17 +158,8 @@ export async function applyOpenApiReference( ): Promise<{ source: DocSource; reference: OpenApiReference }> { const dir = options.dir ?? "reference/api"; const { document, warnings } = await convertSwagger(swagger); - document.servers = [ - options.server ?? { - url: "{deployment}", - variables: { - deployment: { - default: "https://coder.example.com", - description: "The URL of your Coder deployment", - }, - }, - }, - ]; + // Readers call their own deployment, whose URL the curl samples take from the Coder CLI. + delete document.servers; const paths = isObject(document.paths) ? document.paths : {}; const components = isObject(document.components) ? document.components : {}; diff --git a/packages/docs-next/package.json b/packages/docs-next/package.json index 0e9d2ab2..e8b01427 100644 --- a/packages/docs-next/package.json +++ b/packages/docs-next/package.json @@ -38,6 +38,8 @@ "@coder/docs-config": "workspace:*", "@coder/docs-manifest": "workspace:*", "@coder/docs-ui": "workspace:*", + "@fumadocs/json-schema": "0.3.5", + "@scalar/json-magic": "0.16.1", "fumadocs-core": "catalog:", "fumadocs-openapi": "12.5.4", "fumadocs-ui": "catalog:", diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index 3e2c553c..660638e6 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -3,7 +3,6 @@ import { createShikiFactory } from "fumadocs-core/highlight/shiki"; import type { CodeBlockProps } from "fumadocs-openapi"; import { createCodeUsageGeneratorRegistry } from "fumadocs-openapi/requests/generators"; -import { curl } from "fumadocs-openapi/requests/generators/curl"; import { createOpenAPIPageBase } from "fumadocs-openapi/ui/base"; import { DynamicCodeBlock } from "fumadocs-ui/components/dynamic-codeblock.core"; @@ -29,9 +28,6 @@ const shiki = createShikiFactory({ }, }); -const codeUsages = createCodeUsageGeneratorRegistry(); -codeUsages.add("curl", curl); - const shikiOptions = { themes: { light: "github-light-high-contrast", dark: "github-dark-default" }, } as const; @@ -51,11 +47,25 @@ function CodeBlock(props: CodeBlockProps) { ); } -/** One REST API operation, rendered by fumadocs-openapi from the document its page was given. */ +/** One REST API operation, rendered by fumadocs-openapi from the document its page was given, with the server-built curl sample instead of a playground. */ export const ApiPage = createOpenAPIPageBase({ shiki, shikiOptions, components: { CodeBlock }, - codeUsages, - storageKeyPrefix: "coder-api-", + // Empty, or fumadocs-openapi adds its own generators beside the operation's x-codeSamples. + codeUsages: createCodeUsageGeneratorRegistry(), + playground: { enabled: false }, + content: { + renderAPIExampleLayout: ({ selector, usageTabs, responseTabs }) => ( +
+ {selector} +

+ Needs the Coder CLI v2.31.1 or later, logged in to your deployment with{" "} + coder login <url>, and jq. +

+ {usageTabs} + {responseTabs} +
+ ), + }, }); diff --git a/packages/docs-next/src/openapi/curl.test.ts b/packages/docs-next/src/openapi/curl.test.ts new file mode 100644 index 00000000..b859c052 --- /dev/null +++ b/packages/docs-next/src/openapi/curl.test.ts @@ -0,0 +1,192 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { curlCommand, withCurlSample } from "./curl.js"; + +const document = { + openapi: "3.0.3", + info: { title: "Coder API", version: "2.0" }, + paths: { + "/api/v2/users/{user}": { + get: { + security: [{ CoderSessionToken: [] }], + parameters: [ + { name: "user", in: "path", required: true, schema: { type: "string" } }, + { name: "q", in: "query", required: false, schema: { type: "string" } }, + { name: "limit", in: "query", required: true, schema: { type: "integer" } }, + ], + responses: { "200": { description: "OK" } }, + }, + }, + "/api/v2/users": { + post: { + security: [{ CoderSessionToken: [] }], + requestBody: { + required: true, + content: { + "application/json": { schema: { $ref: "#/components/schemas/CreateUser" } }, + }, + }, + responses: { "201": { description: "Created" } }, + }, + }, + "/api/v2/buildinfo": { + get: { responses: { "200": { description: "OK" } } }, + }, + "/scim/v2/Users": { + get: { security: [{ Authorization: [] }], responses: { "200": { description: "OK" } } }, + }, + }, + components: { + securitySchemes: { + CoderSessionToken: { type: "apiKey", name: "Coder-Session-Token", in: "header" }, + Authorization: { type: "apiKey", name: "Authorization", in: "header" }, + }, + schemas: { + CreateUser: { + type: "object", + required: ["email", "username"], + properties: { + email: { type: "string", format: "email" }, + username: { type: "string" }, + name: { type: "string" }, + note: { type: "string", default: "it's" }, + }, + }, + }, + }, +}; + +test("a GET keeps path params as placeholders and adds only required query params", () => { + assert.equal( + curlCommand(document, "/api/v2/users/{user}", "get"), + [ + `curl -X GET "$(coder whoami -o json | jq -r '.[0].url')/api/v2/users/{user}?limit={limit}" \\`, + ` -H "Coder-Session-Token: $(coder login token)"`, + ].join("\n"), + ); +}); + +test("a JSON body is a sample of the schema's required fields", () => { + assert.equal( + curlCommand(document, "/api/v2/users", "post"), + [ + `curl -X POST "$(coder whoami -o json | jq -r '.[0].url')/api/v2/users" \\`, + ` -H "Coder-Session-Token: $(coder login token)" \\`, + ` -H "Content-Type: application/json" \\`, + ` -d '{`, + ` "email": "user@example.com",`, + ` "username": "string"`, + `}'`, + ].join("\n"), + ); +}); + +test("an operation without security sends no token", () => { + assert.equal( + curlCommand(document, "/api/v2/buildinfo", "get"), + `curl -X GET "$(coder whoami -o json | jq -r '.[0].url')/api/v2/buildinfo"`, + ); +}); + +test("another auth scheme gets a placeholder, never the session token", () => { + assert.equal( + curlCommand(document, "/scim/v2/Users", "get"), + [ + `curl -X GET "$(coder whoami -o json | jq -r '.[0].url')/scim/v2/Users" \\`, + ` -H "Authorization: {Authorization}"`, + ].join("\n"), + ); +}); + +test("single quotes in a body example are escaped for the shell", () => { + const withQuote = { + ...document, + paths: { + "/api/v2/users": { + post: { + requestBody: { content: { "application/json": { example: { note: "it's" } } } }, + responses: { "201": { description: "Created" } }, + }, + }, + }, + }; + assert.match( + curlCommand(withQuote, "/api/v2/users", "post"), + /-d '\{\n {2}"note": "it'\\''s"\n\}'$/, + ); +}); + +test("a body of only optional fields shows the first three instead of {}", () => { + const optional = { + ...document, + paths: { + "/api/v2/templates/{template}": { + patch: { + parameters: [{ name: "template", in: "path", required: true }], + requestBody: { + content: { + "application/json": { + schema: { + type: "object", + properties: { + a: { type: "boolean" }, + b: { type: "integer" }, + c: { type: "string" }, + d: { type: "string" }, + }, + }, + }, + }, + }, + responses: { "200": { description: "OK" } }, + }, + }, + }, + }; + assert.match( + curlCommand(optional, "/api/v2/templates/{template}", "patch"), + /-d '\{\n {2}"a": true,\n {2}"b": 0,\n {2}"c": "string"\n\}'$/, + ); +}); + +test("a Content-Type header parameter replaces the declared media type", () => { + const upload = { + ...document, + paths: { + "/api/v2/files": { + post: { + security: [{ CoderSessionToken: [] }], + parameters: [{ name: "Content-Type", in: "header", required: true }], + requestBody: { + content: { "application/x-www-form-urlencoded": { schema: { type: "object" } } }, + }, + responses: { "201": { description: "Created" } }, + }, + }, + }, + }; + assert.equal( + curlCommand(upload, "/api/v2/files", "post"), + [ + `curl -X POST "$(coder whoami -o json | jq -r '.[0].url')/api/v2/files" \\`, + ` -H "Coder-Session-Token: $(coder login token)" \\`, + ` -H "Content-Type: {Content-Type}" \\`, + ` --data-binary "@{file}"`, + ].join("\n"), + ); +}); + +test("the sample becomes the operation's only code sample without changing the input", () => { + const before = JSON.stringify(document); + const out = withCurlSample(document, "/api/v2/buildinfo", "get"); + assert.equal(JSON.stringify(document), before); + const samples = JSON.parse(JSON.stringify(out)).paths["/api/v2/buildinfo"].get["x-codeSamples"]; + assert.deepEqual(samples, [ + { + id: "curl", + lang: "bash", + label: "cURL", + source: `curl -X GET "$(coder whoami -o json | jq -r '.[0].url')/api/v2/buildinfo"`, + }, + ]); +}); diff --git a/packages/docs-next/src/openapi/curl.ts b/packages/docs-next/src/openapi/curl.ts new file mode 100644 index 00000000..47a877f3 --- /dev/null +++ b/packages/docs-next/src/openapi/curl.ts @@ -0,0 +1,170 @@ +import { type JsonSchema, dereference, sample } from "@fumadocs/json-schema"; +import { createMagicProxy, getRaw } from "@scalar/json-magic/magic-proxy"; + +type Json = Record; + +/** The reader's deployment URL and session token, read from their `coder` CLI login by the shell. */ +export const DEPLOYMENT_URL = `$(coder whoami -o json | jq -r '.[0].url')`; +export const SESSION_TOKEN = `$(coder login token)`; + +const isObject = (value: unknown): value is Json => + typeof value === "object" && value !== null && !Array.isArray(value); + +const resolve = (node: unknown): Json | undefined => { + const value = dereference(node); + return isObject(value) ? value : undefined; +}; + +/** Text inside double quotes, where the shell would otherwise expand `$`, backticks and backslashes. */ +const doubleQuoted = (text: string): string => `"${text.replace(/["$`\\]/g, "\\$&")}"`; + +const singleQuoted = (text: string): string => `'${text.replace(/'/g, `'\\''`)}'`; + +const placeholder = (name: string): string => `{${name}}`; + +interface Parameter { + name: string; + in: string; + required?: boolean; +} + +function parametersOf(pathItem: Json, operation: Json): Parameter[] { + const byKey = new Map(); + for (const list of [pathItem.parameters, operation.parameters]) { + if (!Array.isArray(list)) continue; + for (const item of list) { + const param = resolve(item); + if (typeof param?.name !== "string" || typeof param.in !== "string") continue; + byKey.set(`${param.in}:${param.name}`, { + name: param.name, + in: param.in, + required: param.required === true, + }); + } + } + return [...byKey.values()]; +} + +/** The auth headers of the first security alternative, preferring the session token; none when auth is optional. */ +function authHeaders(document: Json, operation: Json): string[] { + const requirements = (operation.security ?? document.security) as Json[] | undefined; + if (!Array.isArray(requirements) || requirements.length === 0) return []; + if (requirements.some((item) => isObject(item) && Object.keys(item).length === 0)) return []; + const schemes = resolve(resolve(document.components)?.securitySchemes) ?? {}; + const header = (key: string): string | undefined => { + const scheme = resolve(schemes[key]); + if (scheme?.type === "apiKey" && scheme.in === "header" && typeof scheme.name === "string") { + const value = scheme.name === "Coder-Session-Token" ? SESSION_TOKEN : placeholder(key); + return `-H "${scheme.name}: ${value}"`; + } + if (scheme?.type === "http" && String(scheme.scheme).toLowerCase() === "bearer") { + return `-H "Authorization: Bearer ${placeholder(key)}"`; + } + return undefined; + }; + const chosen = + requirements.find((item) => + Object.keys(item).some((key) => resolve(schemes[key])?.name === "Coder-Session-Token"), + ) ?? requirements[0]; + return Object.keys(chosen ?? {}) + .map(header) + .filter((line): line is string => line !== undefined); +} + +const isJson = (mediaType: string): boolean => + /^application\/(?:[\w.+-]+\+)?json\b/.test(mediaType); + +const isEmptyObject = (value: unknown): boolean => + isObject(value) && Object.keys(value).length === 0; + +function jsonSample(schema: JsonSchema, method: string): unknown { + const options = { skipReadOnly: method !== "get", skipWriteOnly: method === "get" }; + const required = sample(schema, { ...options, skipNonRequired: true }); + if (!isEmptyObject(required)) return required; + // A body of only optional fields, such as a PATCH, shows its first few instead of {}. + const full = sample(schema, options); + return isObject(full) ? Object.fromEntries(Object.entries(full).slice(0, 3)) : full; +} + +/** The body flags; `contentType` replaces the declared media type when the operation takes it as a header parameter. */ +function bodyLines(operation: Json, method: string, contentType?: string): string[] { + const body = resolve(operation.requestBody); + const content = resolve(body?.content); + if (!content) return []; + const types = Object.keys(content); + const type = types.find(isJson) ?? types[0]; + if (type === undefined) return []; + const media = resolve(content[type]) ?? {}; + if (isJson(type)) { + const examples = resolve(media.examples); + const firstExample = examples ? resolve(Object.values(examples)[0]) : undefined; + const value = + media.example !== undefined + ? getRaw(media.example) + : firstExample?.value !== undefined + ? getRaw(firstExample.value) + : jsonSample((media.schema ?? {}) as JsonSchema, method); + return [ + `-H "Content-Type: ${contentType ?? type}"`, + `-d ${singleQuoted(JSON.stringify(value, null, 2))}`, + ]; + } + if (type === "multipart/form-data") { + const schema = resolve(media.schema); + const required = Array.isArray(schema?.required) ? (schema.required as string[]) : []; + return required.map((name) => `-F ${doubleQuoted(`${name}=${placeholder(name)}`)}`); + } + return [`-H "Content-Type: ${contentType ?? type}"`, `--data-binary "@${placeholder("file")}"`]; +} + +/** + * A curl command for one operation that takes the deployment URL and session + * token from the reader's `coder` CLI login, so the token is never typed or + * shown. Path and required query and header parameters stay `{name}` + * placeholders for the reader to fill in; a JSON body is the schema's example, + * or a sample of its required fields. + */ +export function curlCommand(bundled: Json, path: string, method: string): string { + const document = createMagicProxy(bundled) as Json; + const pathItem = resolve(resolve(document.paths)?.[path]); + const operation = resolve(pathItem?.[method]); + if (!pathItem || !operation) throw new Error(`no ${method} ${path} in the API document`); + const params = parametersOf(pathItem, operation).filter((param) => param.required); + const isContentType = (param: Parameter) => + param.in === "header" && param.name.toLowerCase() === "content-type"; + const contentTypeParam = params.find(isContentType); + const query = params + .filter((param) => param.in === "query") + .map((param) => `${encodeURIComponent(param.name)}=${placeholder(param.name)}`) + .join("&"); + const url = `${DEPLOYMENT_URL}${doubleQuoted(`${path}${query ? `?${query}` : ""}`).slice(1)}`; + const lines = [ + `curl -X ${method.toUpperCase()} "${url}`, + ...authHeaders(document, operation), + ...params + .filter((param) => param.in === "header" && !isContentType(param)) + .map((param) => `-H ${doubleQuoted(`${param.name}: ${placeholder(param.name)}`)}`), + ...bodyLines(operation, method, contentTypeParam && placeholder(contentTypeParam.name)), + ]; + return lines.join(" \\\n "); +} + +/** The document with the operation's curl command as its only code sample, leaving the input untouched. */ +export function withCurlSample(bundled: Json, path: string, method: string): Json { + const source = curlCommand(bundled, path, method); + const paths = bundled.paths as Record; + const pathItem = paths[path] as Json; + return { + ...bundled, + paths: { + ...paths, + [path]: { + ...pathItem, + [method]: { + ...(pathItem[method] as Json), + "x-codeSamples": [{ id: "curl", lang: "bash", label: "cURL", source }], + }, + }, + }, + }; +} diff --git a/packages/docs-next/src/openapi/index.tsx b/packages/docs-next/src/openapi/index.tsx index 1281f4e3..b2184ceb 100644 --- a/packages/docs-next/src/openapi/index.tsx +++ b/packages/docs-next/src/openapi/index.tsx @@ -4,6 +4,7 @@ import { createOpenAPI } from "fumadocs-openapi/server"; import type { RenderBody } from "../types.js"; import { AnchorRedirect } from "./anchor-redirect.js"; import { ApiPage } from "./api-page-lazy.js"; +import { withCurlSample } from "./curl.js"; type Json = Record; @@ -59,7 +60,6 @@ export function pruneDocument(document: Json, path: string, method: string): Jso return { openapi: document.openapi, info: { title: info.title, version: info.version }, - servers: document.servers, ...(document.security ? { security: document.security } : {}), paths: { [path]: pathItem }, components: kept, @@ -94,8 +94,8 @@ export function createOpenApiRenderBody( const route = slugs.join("/"); const operation = data.operations[route]; if (operation) { - const document = pruneDocument( - await bundle(versionId, data.document), + const document = withCurlSample( + pruneDocument(await bundle(versionId, data.document), operation.path, operation.method), operation.path, operation.method, ); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f2000143..081ea10c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -392,6 +392,12 @@ importers: '@coder/docs-ui': specifier: workspace:* version: link:../docs-ui + '@fumadocs/json-schema': + specifier: 0.3.5 + version: 0.3.5(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + '@scalar/json-magic': + specifier: 0.16.1 + version: 0.16.1 fumadocs-core: specifier: 'catalog:' version: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) From c8ef253692b85f78eb2b7136610a75246a477ef2 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 08:04:51 -0400 Subject: [PATCH 07/69] feat(api-reference): bring back the playground beside the curl sample Both now ship. The Try in Playground panel is back as it was, with the {deployment} server variable, the Coder-Session-Token field and the coder-api- storage keys, while the Example Request sample stays the command that reads the URL and token from the Coder CLI. Its Send still cannot reach a deployment from the docs origin, which stays pending a security decision. The built-in code generators stay replaced by an empty registry, so the operation's own sample is the only one; the playground's request panel shows that same command rather than a live one with the typed token. The playground dialog is portalled out of the API page, so its method badge missed the page's contrast overrides and fell to 4.15:1 in light mode. The overrides now cover the portalled dialog too, and the axe pass scans the playground open in every mode so it stays covered. Assisted-by: AI --- apps/docs/scripts/a11y-axe-helpers.mjs | 3 ++ apps/docs/scripts/a11y-axe.mjs | 35 +++++++++++++++++-- apps/docs/scripts/a11y-axe.test.mjs | 14 ++++++++ .../docs-build/src/openapi-reference.test.ts | 14 ++++++-- packages/docs-build/src/openapi-reference.ts | 15 ++++++-- packages/docs-next/src/openapi/api-page.tsx | 4 +-- packages/docs-next/src/openapi/index.tsx | 1 + packages/docs-theme/src/brand.css | 15 ++++---- 8 files changed, 86 insertions(+), 15 deletions(-) diff --git a/apps/docs/scripts/a11y-axe-helpers.mjs b/apps/docs/scripts/a11y-axe-helpers.mjs index 099bb96d..0b838d2c 100644 --- a/apps/docs/scripts/a11y-axe-helpers.mjs +++ b/apps/docs/scripts/a11y-axe-helpers.mjs @@ -35,6 +35,9 @@ export const SEARCH_QUERY = "code"; export const SEARCH_LABEL = `${SEARCH_PAGE}#search`; // The display settings popover, scanned open on the search page. export const SETTINGS_LABEL = `${SEARCH_PAGE}#settings`; +// The API playground dialog, scanned open on an operation page with a request body. +export const PLAYGROUND_PAGE = "/reference/api/users/create-new-user"; +export const PLAYGROUND_LABEL = `${PLAYGROUND_PAGE}#playground`; export const MODES = ["light", "dark"]; export const MOBILE_MODES = MODES.map((mode) => `mobile-${mode}`); // The More contrast setting, held to WCAG AAA contrast. diff --git a/apps/docs/scripts/a11y-axe.mjs b/apps/docs/scripts/a11y-axe.mjs index 33b64a58..1529ed37 100644 --- a/apps/docs/scripts/a11y-axe.mjs +++ b/apps/docs/scripts/a11y-axe.mjs @@ -7,6 +7,8 @@ import { MOBILE_VIEWPORT, MODES, MORE_MODES, + PLAYGROUND_LABEL, + PLAYGROUND_PAGE, SEARCH_LABEL, SEARCH_PAGE, SEARCH_QUERY, @@ -55,7 +57,22 @@ async function openSettings(page) { await settle(page); } -async function scan({ browser, base, page: pagePath, mode, axeSource, search, settings }) { +async function openPlayground(page) { + await page.getByRole("button", { name: "Try in Playground" }).click(); + await page.locator('[role="dialog"]').getByRole("button", { name: /^Send/ }).waitFor(); + await settle(page); +} + +async function scan({ + browser, + base, + page: pagePath, + mode, + axeSource, + search, + settings, + playground, +}) { const scheme = colorSchemeOf(mode); const contrast = contrastOf(mode); const mobile = MOBILE_MODES.includes(mode) @@ -78,13 +95,20 @@ async function scan({ browser, base, page: pagePath, mode, axeSource, search, se await page.addScriptTag({ content: axeSource }); if (search) await openSearchWithMatch(page); if (settings) await openSettings(page); + if (playground) await openPlayground(page); const results = await page.evaluate( (options) => window.axe.run(document, options), axeOptions(mode), ); return results.violations.map((v) => ({ mode, - page: search ? SEARCH_LABEL : settings ? SETTINGS_LABEL : pagePath, + page: search + ? SEARCH_LABEL + : settings + ? SETTINGS_LABEL + : playground + ? PLAYGROUND_LABEL + : pagePath, rule: v.id, impact: v.impact, help: v.help, @@ -119,6 +143,11 @@ async function main() { search: true, })), ...desktopModes.map((mode) => ({ page: SEARCH_PAGE, mode, settings: true })), + ...[...desktopModes, ...MOBILE_MODES].map((mode) => ({ + page: PLAYGROUND_PAGE, + mode, + playground: true, + })), ]; const found = []; try { @@ -146,7 +175,7 @@ async function main() { } for (const entry of stale) console.log(`stale allowlist entry, remove it: ${entry}`); console.log( - `\n${runs.length} scans (${options.pages.length} pages x ${desktopModes.length} modes, ${mobilePages.length} x ${MOBILE_MODES.length} at ${MOBILE_VIEWPORT.width}px, the open search dialog in all ${desktopModes.length + MOBILE_MODES.length}, and the open display settings in ${desktopModes.length}): ` + + `\n${runs.length} scans (${options.pages.length} pages x ${desktopModes.length} modes, ${mobilePages.length} x ${MOBILE_MODES.length} at ${MOBILE_VIEWPORT.width}px, the open search dialog in all ${desktopModes.length + MOBILE_MODES.length}, the open display settings in ${desktopModes.length}, and the open API playground in ${desktopModes.length + MOBILE_MODES.length}): ` + `${violations.length} WCAG rule violations, ${allowed.length} allowlisted, ${failures.length} new; ` + `${bestPractice.length} best-practice findings (reported, not failing).`, ); diff --git a/apps/docs/scripts/a11y-axe.test.mjs b/apps/docs/scripts/a11y-axe.test.mjs index 6b9b721e..0503be7f 100644 --- a/apps/docs/scripts/a11y-axe.test.mjs +++ b/apps/docs/scripts/a11y-axe.test.mjs @@ -7,6 +7,8 @@ import { DEFAULT_MOBILE_PAGES, DEFAULT_PAGES, MORE_MODES, + PLAYGROUND_LABEL, + PLAYGROUND_PAGE, SEARCH_LABEL, SEARCH_PAGE, SEARCH_QUERY, @@ -158,6 +160,18 @@ test("the search dialog scan names a default page and gets its own allowlist lab assert.equal(failures.length, 1); }); +test("the playground scan opens on a scanned API page and gets its own allowlist label", () => { + assert.ok(DEFAULT_PAGES.includes(PLAYGROUND_PAGE)); + assert.ok(DEFAULT_MOBILE_PAGES.includes(PLAYGROUND_PAGE)); + assert.notEqual(PLAYGROUND_LABEL, PLAYGROUND_PAGE); + const { failures } = applyAllowlist( + [{ mode: "light", page: PLAYGROUND_LABEL, rule: "color-contrast" }], + [`tracked-x axe light ${PLAYGROUND_PAGE} color-contrast`], + DEFAULT_PAGES, + ); + assert.equal(failures.length, 1); +}); + test("More contrast modes scan both color schemes with the AAA contrast rule enabled", () => { assert.deepEqual(MORE_MODES, ["more-light", "more-dark"]); assert.deepEqual(MORE_MODES.map(colorSchemeOf), ["light", "dark"]); diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index 8f3a2da4..f90c2ff1 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -64,9 +64,19 @@ test("old tag and schema anchors redirect to the operation pages", async () => { ); }); -test("the API document names no server, since readers call their own deployment", async () => { +test("the try-it server is the reader's deployment, not the docs site", async () => { const { reference } = await applyOpenApiReference(source, swagger); - assert.equal(reference.document.servers, undefined); + assert.deepEqual(reference.document.servers, [ + { + url: "{deployment}", + variables: { + deployment: { + default: "https://coder.example.com", + description: "The URL of your Coder deployment", + }, + }, + }, + ]); }); test("a Swagger document with an external $ref is rejected before conversion", async () => { diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 3113d6f5..37ea0e34 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -32,6 +32,8 @@ export interface OpenApiReference { export interface ApplyOpenApiReferenceOptions { /** The docs-relative directory of the generated reference; defaults to `reference/api`. */ dir?: string; + /** The server URL template the try-it panel sends to; the reader fills in `{deployment}`. */ + server?: { url: string; variables?: Record }; } const METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"] as const; @@ -158,8 +160,17 @@ export async function applyOpenApiReference( ): Promise<{ source: DocSource; reference: OpenApiReference }> { const dir = options.dir ?? "reference/api"; const { document, warnings } = await convertSwagger(swagger); - // Readers call their own deployment, whose URL the curl samples take from the Coder CLI. - delete document.servers; + document.servers = [ + options.server ?? { + url: "{deployment}", + variables: { + deployment: { + default: "https://coder.example.com", + description: "The URL of your Coder deployment", + }, + }, + }, + ]; const paths = isObject(document.paths) ? document.paths : {}; const components = isObject(document.components) ? document.components : {}; diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index 660638e6..97087c4e 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -47,14 +47,14 @@ function CodeBlock(props: CodeBlockProps) { ); } -/** One REST API operation, rendered by fumadocs-openapi from the document its page was given, with the server-built curl sample instead of a playground. */ +/** One REST API operation, rendered by fumadocs-openapi from the document its page was given, with the server-built curl sample and the playground. */ export const ApiPage = createOpenAPIPageBase({ shiki, shikiOptions, components: { CodeBlock }, // Empty, or fumadocs-openapi adds its own generators beside the operation's x-codeSamples. codeUsages: createCodeUsageGeneratorRegistry(), - playground: { enabled: false }, + storageKeyPrefix: "coder-api-", content: { renderAPIExampleLayout: ({ selector, usageTabs, responseTabs }) => (
diff --git a/packages/docs-next/src/openapi/index.tsx b/packages/docs-next/src/openapi/index.tsx index b2184ceb..0534e91d 100644 --- a/packages/docs-next/src/openapi/index.tsx +++ b/packages/docs-next/src/openapi/index.tsx @@ -60,6 +60,7 @@ export function pruneDocument(document: Json, path: string, method: string): Jso return { openapi: document.openapi, info: { title: info.title, version: info.version }, + servers: document.servers, ...(document.security ? { security: document.security } : {}), paths: { [path]: pathItem }, components: kept, diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css index def077aa..a28fcbae 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -677,8 +677,8 @@ samp { transition-property: width, inset-block, transform, translate, background-color, visibility; } -/* fumadocs-openapi's method badges and links are -600/-400 shades that fall short of 4.5:1 (7:1 for More contrast) on its card surface. */ -:root:not(.dark) .coder-api-page { +/* fumadocs-openapi's method badges and links are -600/-400 shades that fall short of 4.5:1 (7:1 for More contrast) on its card surface; the playground dialog is portalled out of the page. */ +:root:not(.dark) :is(.coder-api-page, [data-base-ui-portal] > [role="dialog"]) { --color-green-600: oklch(45% 0.13 150); --color-blue-600: oklch(48% 0.2 262); --color-orange-600: oklch(50% 0.15 50); @@ -686,7 +686,8 @@ samp { --color-red-600: oklch(50% 0.2 27); } -:root[data-contrast="more"]:not(.dark) .coder-api-page { +:root[data-contrast="more"]:not(.dark) + :is(.coder-api-page, [data-base-ui-portal] > [role="dialog"]) { --color-green-600: oklch(38% 0.1 150); --color-blue-600: oklch(40% 0.18 262); --color-orange-600: oklch(42% 0.13 50); @@ -694,7 +695,7 @@ samp { --color-red-600: oklch(42% 0.17 27); } -:root[data-contrast="more"].dark .coder-api-page { +:root[data-contrast="more"].dark :is(.coder-api-page, [data-base-ui-portal] > [role="dialog"]) { --color-green-400: oklch(88% 0.15 150); --color-blue-400: oklch(85% 0.1 262); --color-orange-400: oklch(86% 0.1 60); @@ -703,7 +704,8 @@ samp { } @media (prefers-contrast: more) { - :root:not([data-contrast="standard"]):not(.dark) .coder-api-page { + :root:not([data-contrast="standard"]):not(.dark) + :is(.coder-api-page, [data-base-ui-portal] > [role="dialog"]) { --color-green-600: oklch(38% 0.1 150); --color-blue-600: oklch(40% 0.18 262); --color-orange-600: oklch(42% 0.13 50); @@ -711,7 +713,8 @@ samp { --color-red-600: oklch(42% 0.17 27); } - :root:not([data-contrast="standard"]).dark .coder-api-page { + :root:not([data-contrast="standard"]).dark + :is(.coder-api-page, [data-base-ui-portal] > [role="dialog"]) { --color-green-400: oklch(88% 0.15 150); --color-blue-400: oklch(85% 0.1 262); --color-orange-400: oklch(86% 0.1 60); From d3fcc4b1ea2c4cb455452a540119229b17247459 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 11:04:53 -0400 Subject: [PATCH 08/69] fix(ci): omit empty pr_number meta from preview deploys A preview dispatched by hand has no pull request, and Vercel now rejects the deploy with "meta.pr_number should NOT be shorter than 1 characters". Pass the pr_number meta only when one was given. Assisted-by: AI --- .github/workflows/docs-pr-preview.yml | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/.github/workflows/docs-pr-preview.yml b/.github/workflows/docs-pr-preview.yml index 5e9adc16..24e9a3e7 100644 --- a/.github/workflows/docs-pr-preview.yml +++ b/.github/workflows/docs-pr-preview.yml @@ -321,12 +321,14 @@ jobs: rm -rf "$stage" mkdir -p "$stage/.vercel" "$stage/$VERCEL_ROOT_DIRECTORY" mv .vercel/output "$stage/.vercel/output" + meta=(--meta content_repository="$CONTENT_REPOSITORY" --meta content_ref="$CONTENT_REF") + # Vercel rejects an empty meta value. + if [[ -n "$PR_NUMBER" ]]; then + meta+=(--meta pr_number="$PR_NUMBER") + fi stop=$(openssl rand -hex 16) echo "::stop-commands::${stop}" - url=$(pnpm exec vercel deploy --cwd "$stage" --prebuilt --target=preview --archive=tgz --yes \ - --meta content_repository="$CONTENT_REPOSITORY" \ - --meta content_ref="$CONTENT_REF" \ - --meta pr_number="$PR_NUMBER") + url=$(pnpm exec vercel deploy --cwd "$stage" --prebuilt --target=preview --archive=tgz --yes "${meta[@]}") echo "::${stop}::" [[ "$url" =~ ^https://[A-Za-z0-9.-]+$ ]] || { echo "the Vercel CLI did not print a deployment URL" >&2; exit 1; } echo "url=$url" >> "$GITHUB_OUTPUT" From e4b8377bf8f724fbad059bfa7ee3afb04f3bdc27 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 12:10:07 -0400 Subject: [PATCH 09/69] feat(api-reference): show code samples in curl, JavaScript, Python and Go Readers script the API in more than the shell, so each operation now carries four server-built samples, as tabs: curl, fetch, requests and net/http. Every sample reads the deployment URL and session token from CODER_URL and CODER_SESSION_TOKEN, the variables the coder CLI itself reads, instead of inlining `coder whoami` and `coder login token` substitutions, so a sample pasted into a script or CI job works as is. The request (placeholders for path and required query parameters, the JSON body sample, the auth header only when the operation needs auth) is built once and written out per language, with each language's own string escaping. curl.ts becomes code-samples.ts, and the lazy highlighter gains the JavaScript, Python and Go grammars. Assisted-by: AI --- packages/docs-next/src/openapi/api-page.tsx | 7 +- .../src/openapi/code-samples.test.ts | 503 ++++++++++++++++++ .../docs-next/src/openapi/code-samples.ts | 403 ++++++++++++++ packages/docs-next/src/openapi/curl.test.ts | 192 ------- packages/docs-next/src/openapi/curl.ts | 170 ------ packages/docs-next/src/openapi/index.tsx | 4 +- 6 files changed, 913 insertions(+), 366 deletions(-) create mode 100644 packages/docs-next/src/openapi/code-samples.test.ts create mode 100644 packages/docs-next/src/openapi/code-samples.ts delete mode 100644 packages/docs-next/src/openapi/curl.test.ts delete mode 100644 packages/docs-next/src/openapi/curl.ts diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index 97087c4e..095d5df7 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -6,7 +6,7 @@ import { createCodeUsageGeneratorRegistry } from "fumadocs-openapi/requests/gene import { createOpenAPIPageBase } from "fumadocs-openapi/ui/base"; import { DynamicCodeBlock } from "fumadocs-ui/components/dynamic-codeblock.core"; -// Only the grammars and themes an API page uses (JSON, the cURL sample, TypeScript definitions), on the JavaScript regex engine (no WASM, no eval). +// Only the grammars and themes an API page uses (JSON, the code samples, TypeScript definitions), on the JavaScript regex engine (no WASM, no eval). const shiki = createShikiFactory({ async init() { const [{ createHighlighterCore }, { createJavaScriptRegexEngine }] = await Promise.all([ @@ -19,6 +19,9 @@ const shiki = createShikiFactory({ import("shiki/langs/json.mjs"), import("shiki/langs/shellscript.mjs"), import("shiki/langs/typescript.mjs"), + import("shiki/langs/javascript.mjs"), + import("shiki/langs/python.mjs"), + import("shiki/langs/go.mjs"), ], themes: [ import("shiki/themes/github-light-high-contrast.mjs"), @@ -47,7 +50,7 @@ function CodeBlock(props: CodeBlockProps) { ); } -/** One REST API operation, rendered by fumadocs-openapi from the document its page was given, with the server-built curl sample and the playground. */ +/** One REST API operation, rendered by fumadocs-openapi from the document its page was given, with the server-built code samples and the playground. */ export const ApiPage = createOpenAPIPageBase({ shiki, shikiOptions, diff --git a/packages/docs-next/src/openapi/code-samples.test.ts b/packages/docs-next/src/openapi/code-samples.test.ts new file mode 100644 index 00000000..aa1c3edd --- /dev/null +++ b/packages/docs-next/src/openapi/code-samples.test.ts @@ -0,0 +1,503 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import test from "node:test"; +import { codeSamples, withCodeSamples } from "./code-samples.js"; + +const document = { + openapi: "3.0.3", + info: { title: "Coder API", version: "2.0" }, + paths: { + "/api/v2/users/{user}": { + get: { + security: [{ CoderSessionToken: [] }], + parameters: [ + { name: "user", in: "path", required: true, schema: { type: "string" } }, + { name: "q", in: "query", required: false, schema: { type: "string" } }, + { name: "limit", in: "query", required: true, schema: { type: "integer" } }, + ], + responses: { "200": { description: "OK" } }, + }, + }, + "/api/v2/users": { + post: { + security: [{ CoderSessionToken: [] }], + requestBody: { + required: true, + content: { + "application/json": { schema: { $ref: "#/components/schemas/CreateUser" } }, + }, + }, + responses: { "201": { description: "Created" } }, + }, + }, + "/api/v2/buildinfo": { + get: { responses: { "200": { description: "OK" } } }, + }, + "/scim/v2/Users": { + get: { security: [{ Authorization: [] }], responses: { "200": { description: "OK" } } }, + }, + }, + components: { + securitySchemes: { + CoderSessionToken: { type: "apiKey", name: "Coder-Session-Token", in: "header" }, + Authorization: { type: "apiKey", name: "Authorization", in: "header" }, + }, + schemas: { + CreateUser: { + type: "object", + required: ["email", "username"], + properties: { + email: { type: "string", format: "email" }, + username: { type: "string" }, + name: { type: "string" }, + note: { type: "string", default: "it's" }, + }, + }, + }, + }, +}; + +const sample = (doc: Record, path: string, method: string, id: string): string => { + const found = codeSamples(doc, path, method).find((item) => item.id === id); + if (!found) throw new Error(`no ${id} sample`); + return found.source; +}; + +const ENV = { CODER_URL: "https://coder.test", CODER_SESSION_TOKEN: "s3cret" }; + +/** The arguments the shell passes to curl when it runs the sample. */ +function curlArgs(source: string): string[] { + const stub = `curl() { for arg; do printf '%s\\0' "$arg"; done; }\n`; + const out = execFileSync("sh", ["-c", stub + source], { + env: { ...process.env, ...ENV }, + encoding: "utf8", + }); + return out.split("\0").slice(0, -1); +} + +interface FetchCall { + url: string; + init: { method: string; headers?: Record; body?: unknown }; +} + +/** The `fetch` call the JavaScript sample makes, with the environment set. */ +async function fetchCall(source: string): Promise { + const calls: FetchCall[] = []; + const fakeFetch = async (url: string, init: FetchCall["init"]) => { + calls.push({ url, init }); + return { status: 200, text: async () => "" }; + }; + const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; + await new AsyncFunction("fetch", "process", "console", source)( + fakeFetch, + { env: ENV }, + { log() {} }, + ); + assert.equal(calls.length, 1); + return calls[0] as FetchCall; +} + +const tricky = { + ...document, + paths: { + "/api/v2/users": { + post: { + security: [{ CoderSessionToken: [] }], + requestBody: { + content: { + "application/json": { + example: { note: 'it\'s "q" `tick` $HOME ${x} \\ back\nline' }, + }, + }, + }, + responses: { "201": { description: "Created" } }, + }, + }, + }, +}; +const trickyNote = 'it\'s "q" `tick` $HOME ${x} \\ back\nline'; + +test("there is one sample per language, in tab order", () => { + assert.deepEqual( + codeSamples(document, "/api/v2/buildinfo", "get").map(({ id, lang, label }) => ({ + id, + lang, + label, + })), + [ + { id: "curl", lang: "bash", label: "cURL" }, + { id: "javascript", lang: "javascript", label: "JavaScript" }, + { id: "python", lang: "python", label: "Python" }, + { id: "go", lang: "go", label: "Go" }, + ], + ); +}); + +test("no sample logs in or exports anything: they read CODER_URL and CODER_SESSION_TOKEN", () => { + for (const { source } of codeSamples(document, "/api/v2/users/{user}", "get")) { + assert.doesNotMatch(source, /coder (login|whoami)|export /); + assert.match(source, /CODER_URL/); + assert.match(source, /CODER_SESSION_TOKEN/); + } +}); + +test("curl: path params stay placeholders and only required query params are added", () => { + assert.equal( + sample(document, "/api/v2/users/{user}", "get", "curl"), + [ + `curl -X GET "$CODER_URL/api/v2/users/{user}?limit={limit}" \\`, + ` -H "Coder-Session-Token: $CODER_SESSION_TOKEN"`, + ].join("\n"), + ); +}); + +test("curl: a JSON body is a sample of the schema's required fields", () => { + assert.equal( + sample(document, "/api/v2/users", "post", "curl"), + [ + `curl -X POST "$CODER_URL/api/v2/users" \\`, + ` -H "Coder-Session-Token: $CODER_SESSION_TOKEN" \\`, + ` -H "Content-Type: application/json" \\`, + ` -d '{`, + ` "email": "user@example.com",`, + ` "username": "string"`, + `}'`, + ].join("\n"), + ); +}); + +test("curl: an operation without security sends no token", () => { + assert.equal( + sample(document, "/api/v2/buildinfo", "get", "curl"), + `curl -X GET "$CODER_URL/api/v2/buildinfo"`, + ); +}); + +test("curl: another auth scheme gets a placeholder, never the session token", () => { + assert.equal( + sample(document, "/scim/v2/Users", "get", "curl"), + [`curl -X GET "$CODER_URL/scim/v2/Users" \\`, ` -H "Authorization: {Authorization}"`].join( + "\n", + ), + ); +}); + +test("curl: the shell passes the body, URL and token through exactly", () => { + const args = curlArgs(sample(tricky, "/api/v2/users", "post", "curl")); + assert.equal(args[2], "https://coder.test/api/v2/users"); + assert.ok(args.includes("Coder-Session-Token: s3cret")); + assert.deepEqual(JSON.parse(args.at(-1) ?? ""), { note: trickyNote }); +}); + +test("curl: a path with shell syntax in it reaches curl unexpanded", () => { + const odd = { + ...document, + paths: { '/api/v2/$x/`y`/"z"': { get: { responses: { "200": { description: "OK" } } } } }, + }; + const args = curlArgs(sample(odd, '/api/v2/$x/`y`/"z"', "get", "curl")); + assert.equal(args[2], 'https://coder.test/api/v2/$x/`y`/"z"'); +}); + +test("curl: a body of only optional fields shows the first three instead of {}", () => { + const optional = { + ...document, + paths: { + "/api/v2/templates/{template}": { + patch: { + parameters: [{ name: "template", in: "path", required: true }], + requestBody: { + content: { + "application/json": { + schema: { + type: "object", + properties: { + a: { type: "boolean" }, + b: { type: "integer" }, + c: { type: "string" }, + d: { type: "string" }, + }, + }, + }, + }, + }, + responses: { "200": { description: "OK" } }, + }, + }, + }, + }; + assert.match( + sample(optional, "/api/v2/templates/{template}", "patch", "curl"), + /-d '\{\n {2}"a": true,\n {2}"b": 0,\n {2}"c": "string"\n\}'$/, + ); +}); + +const upload = { + ...document, + paths: { + "/api/v2/files": { + post: { + security: [{ CoderSessionToken: [] }], + parameters: [{ name: "Content-Type", in: "header", required: true }], + requestBody: { + content: { "application/x-tar": { schema: { type: "string", format: "binary" } } }, + }, + responses: { "201": { description: "Created" } }, + }, + }, + }, +}; + +test("curl: a Content-Type header parameter replaces the declared media type", () => { + assert.equal( + sample(upload, "/api/v2/files", "post", "curl"), + [ + `curl -X POST "$CODER_URL/api/v2/files" \\`, + ` -H "Coder-Session-Token: $CODER_SESSION_TOKEN" \\`, + ` -H "Content-Type: {Content-Type}" \\`, + ` --data-binary "@{file}"`, + ].join("\n"), + ); +}); + +const form = { + ...document, + paths: { + "/api/v2/form": { + post: { + requestBody: { + content: { + "multipart/form-data": { + schema: { + type: "object", + required: ["name"], + properties: { name: { type: "string" }, other: { type: "string" } }, + }, + }, + }, + }, + responses: { "200": { description: "OK" } }, + }, + }, + }, +}; + +test("curl: a multipart body sends its required fields", () => { + assert.equal( + sample(form, "/api/v2/form", "post", "curl"), + [`curl -X POST "$CODER_URL/api/v2/form" \\`, ` -F "name={name}"`].join("\n"), + ); +}); + +test("JavaScript: fetch with the URL and token from the environment", () => { + assert.equal( + sample(document, "/api/v2/users", "post", "javascript"), + [ + `const response = await fetch(process.env.CODER_URL + "/api/v2/users", {`, + ` method: "POST",`, + ` headers: {`, + ` "Coder-Session-Token": process.env.CODER_SESSION_TOKEN,`, + ` "Content-Type": "application/json",`, + ` },`, + ` body: JSON.stringify({`, + ` "email": "user@example.com",`, + ` "username": "string"`, + ` }),`, + `});`, + `console.log(response.status, await response.text());`, + ].join("\n"), + ); +}); + +test("JavaScript: no auth means no headers", () => { + assert.equal( + sample(document, "/api/v2/buildinfo", "get", "javascript"), + [ + `const response = await fetch(process.env.CODER_URL + "/api/v2/buildinfo", {`, + ` method: "GET",`, + `});`, + `console.log(response.status, await response.text());`, + ].join("\n"), + ); +}); + +test("JavaScript: the sample runs and sends the body, URL and token exactly", async () => { + const call = await fetchCall(sample(tricky, "/api/v2/users", "post", "javascript")); + assert.equal(call.url, "https://coder.test/api/v2/users"); + assert.equal(call.init.method, "POST"); + assert.equal(call.init.headers?.["Coder-Session-Token"], "s3cret"); + assert.deepEqual(JSON.parse(String(call.init.body)), { note: trickyNote }); +}); + +test("JavaScript: path and query placeholders and other auth schemes", async () => { + const get = await fetchCall(sample(document, "/api/v2/users/{user}", "get", "javascript")); + assert.equal(get.url, "https://coder.test/api/v2/users/{user}?limit={limit}"); + const scim = await fetchCall(sample(document, "/scim/v2/Users", "get", "javascript")); + assert.deepEqual(scim.init.headers, { Authorization: "{Authorization}" }); +}); + +test("JavaScript: a multipart body is FormData and a binary body is read from a file", async () => { + const multipart = await fetchCall(sample(form, "/api/v2/form", "post", "javascript")); + assert.ok(multipart.init.body instanceof FormData); + assert.equal(multipart.init.body.get("name"), "{name}"); + assert.equal(multipart.init.headers, undefined); + assert.match(sample(upload, "/api/v2/files", "post", "javascript"), /readFile\("\{file\}"\)/); +}); + +test("Python: requests with the URL and token from the environment", () => { + assert.equal( + sample(document, "/api/v2/users", "post", "python"), + [ + `import os`, + ``, + `import requests`, + ``, + `response = requests.post(`, + ` os.environ["CODER_URL"] + "/api/v2/users",`, + ` headers={`, + ` "Coder-Session-Token": os.environ["CODER_SESSION_TOKEN"],`, + ` },`, + ` json={`, + ` "email": "user@example.com",`, + ` "username": "string",`, + ` },`, + `)`, + `print(response.status_code, response.text)`, + ].join("\n"), + ); +}); + +test("Python: no auth and no body", () => { + assert.equal( + sample(document, "/api/v2/users/{user}", "get", "python").split("\n").slice(4).join("\n"), + [ + `response = requests.get(`, + ` os.environ["CODER_URL"] + "/api/v2/users/{user}?limit={limit}",`, + ` headers={`, + ` "Coder-Session-Token": os.environ["CODER_SESSION_TOKEN"],`, + ` },`, + `)`, + `print(response.status_code, response.text)`, + ].join("\n"), + ); + assert.match( + sample(document, "/api/v2/buildinfo", "get", "python"), + /^response = requests\.get\(\n {4}os\.environ\["CODER_URL"\] \+ "\/api\/v2\/buildinfo",\n\)$/m, + ); +}); + +test("Python: a body is a Python literal with True, False, None and escaped strings", () => { + const values = { + ...document, + paths: { + "/api/v2/users": { + post: { + requestBody: { + content: { + "application/json": { + example: { + a: true, + b: false, + c: null, + d: [1, "x"], + e: {}, + f: [], + note: trickyNote, + }, + }, + }, + }, + responses: { "201": { description: "Created" } }, + }, + }, + }, + }; + assert.match( + sample(values, "/api/v2/users", "post", "python"), + new RegExp( + [ + ` json=\\{`, + ` "a": True,`, + ` "b": False,`, + ` "c": None,`, + ` "d": \\[`, + ` 1,`, + ` "x",`, + ` \\],`, + ` "e": \\{\\},`, + ` "f": \\[\\],`, + ` "note": "it's \\\\"q\\\\" \`tick\` \\$HOME \\$\\{x\\} \\\\\\\\ back\\\\nline",`, + ` \\},`, + ].join("\n"), + ), + ); +}); + +test("Go: net/http with the URL and token from the environment", () => { + assert.equal( + sample(document, "/api/v2/users", "post", "go"), + [ + `package main`, + ``, + `import (`, + `\t"fmt"`, + `\t"io"`, + `\t"net/http"`, + `\t"os"`, + `\t"strings"`, + `)`, + ``, + `func main() {`, + `\tbody := strings.NewReader(\`{`, + ` "email": "user@example.com",`, + ` "username": "string"`, + `}\`)`, + `\treq, err := http.NewRequest(http.MethodPost, os.Getenv("CODER_URL")+"/api/v2/users", body)`, + `\tif err != nil {`, + `\t\tpanic(err)`, + `\t}`, + `\treq.Header.Set("Coder-Session-Token", os.Getenv("CODER_SESSION_TOKEN"))`, + `\treq.Header.Set("Content-Type", "application/json")`, + `\tresp, err := http.DefaultClient.Do(req)`, + `\tif err != nil {`, + `\t\tpanic(err)`, + `\t}`, + `\tdefer resp.Body.Close()`, + `\tout, err := io.ReadAll(resp.Body)`, + `\tif err != nil {`, + `\t\tpanic(err)`, + `\t}`, + `\tfmt.Println(resp.Status, string(out))`, + `}`, + ].join("\n"), + ); +}); + +test("Go: no body is nil and leaves strings unimported; no auth sets no header", () => { + const source = sample(document, "/api/v2/buildinfo", "get", "go"); + assert.match( + source, + /req, err := http\.NewRequest\(http\.MethodGet, os\.Getenv\("CODER_URL"\)\+"\/api\/v2\/buildinfo", nil\)/, + ); + assert.doesNotMatch(source, /"strings"|Header\.Set/); +}); + +test("Go: a body with a backtick is an interpreted string literal", () => { + const source = sample(tricky, "/api/v2/users", "post", "go"); + const literal = JSON.stringify(JSON.stringify({ note: trickyNote }, null, 2)); + assert.ok(source.includes(`body := strings.NewReader(${literal})`)); + assert.ok(literal.startsWith(String.raw`"{\n \"note\": \"it's \\\"q\\\" `)); +}); + +test("Go: a lone surrogate stays a JSON escape, never a Go \\u escape Go would reject", () => { + const lone = structuredClone(tricky); + lone.paths["/api/v2/users"].post.requestBody.content["application/json"].example.note = "\ud800`"; + assert.ok(sample(lone, "/api/v2/users", "post", "go").includes(String.raw`\"\\ud800`)); +}); + +test("the samples become the operation's only code samples without changing the input", () => { + const before = JSON.stringify(document); + const out = withCodeSamples(document, "/api/v2/buildinfo", "get"); + assert.equal(JSON.stringify(document), before); + const samples = JSON.parse(JSON.stringify(out)).paths["/api/v2/buildinfo"].get["x-codeSamples"]; + assert.deepEqual(samples, codeSamples(document, "/api/v2/buildinfo", "get")); +}); diff --git a/packages/docs-next/src/openapi/code-samples.ts b/packages/docs-next/src/openapi/code-samples.ts new file mode 100644 index 00000000..fa7560ba --- /dev/null +++ b/packages/docs-next/src/openapi/code-samples.ts @@ -0,0 +1,403 @@ +import { type JsonSchema, dereference, sample } from "@fumadocs/json-schema"; +import { createMagicProxy, getRaw } from "@scalar/json-magic/magic-proxy"; + +type Json = Record; + +/** The environment variables every sample reads, named as the `coder` CLI reads them. */ +export const DEPLOYMENT_URL_ENV = "CODER_URL"; +export const SESSION_TOKEN_ENV = "CODER_SESSION_TOKEN"; + +const isObject = (value: unknown): value is Json => + typeof value === "object" && value !== null && !Array.isArray(value); + +const resolve = (node: unknown): Json | undefined => { + const value = dereference(node); + return isObject(value) ? value : undefined; +}; + +const placeholder = (name: string): string => `{${name}}`; + +interface Parameter { + name: string; + in: string; + required?: boolean; +} + +function parametersOf(pathItem: Json, operation: Json): Parameter[] { + const byKey = new Map(); + for (const list of [pathItem.parameters, operation.parameters]) { + if (!Array.isArray(list)) continue; + for (const item of list) { + const param = resolve(item); + if (typeof param?.name !== "string" || typeof param.in !== "string") continue; + byKey.set(`${param.in}:${param.name}`, { + name: param.name, + in: param.in, + required: param.required === true, + }); + } + } + return [...byKey.values()]; +} + +/** A header whose value is either literal text or the session token from the environment. */ +type Header = { name: string; value: string } | { name: string; token: true }; + +type Body = + | { kind: "json"; contentType: string; value: unknown } + | { kind: "form"; fields: string[] } + | { kind: "binary"; contentType: string }; + +/** One operation's example request, which each language writes out in its own syntax. */ +export interface ExampleRequest { + method: string; + /** The path and required query string, with `{name}` placeholders, appended to the deployment URL. */ + url: string; + headers: Header[]; + body?: Body; +} + +/** The auth headers of the first security alternative, preferring the session token; none when auth is optional. */ +function authHeaders(document: Json, operation: Json): Header[] { + const requirements = (operation.security ?? document.security) as Json[] | undefined; + if (!Array.isArray(requirements) || requirements.length === 0) return []; + if (requirements.some((item) => isObject(item) && Object.keys(item).length === 0)) return []; + const schemes = resolve(resolve(document.components)?.securitySchemes) ?? {}; + const header = (key: string): Header | undefined => { + const scheme = resolve(schemes[key]); + if (scheme?.type === "apiKey" && scheme.in === "header" && typeof scheme.name === "string") { + return scheme.name === "Coder-Session-Token" + ? { name: scheme.name, token: true } + : { name: scheme.name, value: placeholder(key) }; + } + if (scheme?.type === "http" && String(scheme.scheme).toLowerCase() === "bearer") { + return { name: "Authorization", value: `Bearer ${placeholder(key)}` }; + } + return undefined; + }; + const chosen = + requirements.find((item) => + Object.keys(item).some((key) => resolve(schemes[key])?.name === "Coder-Session-Token"), + ) ?? requirements[0]; + return Object.keys(chosen ?? {}) + .map(header) + .filter((item): item is Header => item !== undefined); +} + +const isJson = (mediaType: string): boolean => + /^application\/(?:[\w.+-]+\+)?json\b/.test(mediaType); + +const isEmptyObject = (value: unknown): boolean => + isObject(value) && Object.keys(value).length === 0; + +function jsonSample(schema: JsonSchema, method: string): unknown { + const options = { skipReadOnly: method !== "get", skipWriteOnly: method === "get" }; + const required = sample(schema, { ...options, skipNonRequired: true }); + if (!isEmptyObject(required)) return required; + // A body of only optional fields, such as a PATCH, shows its first few instead of {}. + const full = sample(schema, options); + return isObject(full) ? Object.fromEntries(Object.entries(full).slice(0, 3)) : full; +} + +/** `contentType` replaces the declared media type when the operation takes it as a header parameter. */ +function bodyOf(operation: Json, method: string, contentType?: string): Body | undefined { + const body = resolve(operation.requestBody); + const content = resolve(body?.content); + if (!content) return undefined; + const types = Object.keys(content); + const type = types.find(isJson) ?? types[0]; + if (type === undefined) return undefined; + const media = resolve(content[type]) ?? {}; + if (isJson(type)) { + const examples = resolve(media.examples); + const firstExample = examples ? resolve(Object.values(examples)[0]) : undefined; + const value = + media.example !== undefined + ? getRaw(media.example) + : firstExample?.value !== undefined + ? getRaw(firstExample.value) + : jsonSample((media.schema ?? {}) as JsonSchema, method); + return { kind: "json", contentType: contentType ?? type, value }; + } + if (type === "multipart/form-data") { + const schema = resolve(media.schema); + const required = Array.isArray(schema?.required) ? (schema.required as string[]) : []; + return { kind: "form", fields: required }; + } + return { kind: "binary", contentType: contentType ?? type }; +} + +/** + * The example request for one operation. Path and required query and header + * parameters stay `{name}` placeholders for the reader to fill in; a JSON body + * is the schema's example, or a sample of its required fields. + */ +export function exampleRequest(bundled: Json, path: string, method: string): ExampleRequest { + const document = createMagicProxy(bundled) as Json; + const pathItem = resolve(resolve(document.paths)?.[path]); + const operation = resolve(pathItem?.[method]); + if (!pathItem || !operation) throw new Error(`no ${method} ${path} in the API document`); + const params = parametersOf(pathItem, operation).filter((param) => param.required); + const isContentType = (param: Parameter) => + param.in === "header" && param.name.toLowerCase() === "content-type"; + const contentTypeParam = params.find(isContentType); + const query = params + .filter((param) => param.in === "query") + .map((param) => `${encodeURIComponent(param.name)}=${placeholder(param.name)}`) + .join("&"); + const body = bodyOf(operation, method, contentTypeParam && placeholder(contentTypeParam.name)); + const headers: Header[] = [ + ...authHeaders(document, operation), + ...params + .filter((param) => param.in === "header" && !isContentType(param)) + .map((param) => ({ name: param.name, value: placeholder(param.name) })), + ]; + if (body && body.kind !== "form") headers.push({ name: "Content-Type", value: body.contentType }); + return { + method: method.toUpperCase(), + url: `${path}${query ? `?${query}` : ""}`, + headers, + ...(body ? { body } : {}), + }; +} + +const jsonText = (value: unknown, indent = 2): string => JSON.stringify(value, null, indent); + +/** Text inside double quotes, where the shell would otherwise expand `$`, backticks and backslashes. */ +const shellDoubleQuoted = (text: string): string => `"${text.replace(/["$`\\]/g, "\\$&")}"`; + +const shellSingleQuoted = (text: string): string => `'${text.replace(/'/g, `'\\''`)}'`; + +export function curlSample(request: ExampleRequest): string { + const { body } = request; + const lines = [ + `curl -X ${request.method} "$${DEPLOYMENT_URL_ENV}${shellDoubleQuoted(request.url).slice(1)}`, + ...request.headers.map((header) => + "token" in header + ? `-H "${header.name}: $${SESSION_TOKEN_ENV}"` + : `-H ${shellDoubleQuoted(`${header.name}: ${header.value}`)}`, + ), + ]; + if (body?.kind === "json") lines.push(`-d ${shellSingleQuoted(jsonText(body.value))}`); + if (body?.kind === "form") { + for (const name of body.fields) + lines.push(`-F ${shellDoubleQuoted(`${name}=${placeholder(name)}`)}`); + } + if (body?.kind === "binary") + lines.push(`--data-binary ${shellDoubleQuoted(`@${placeholder("file")}`)}`); + return lines.join(" \\\n "); +} + +const reindent = (text: string, prefix: string): string => text.replace(/\n/g, `\n${prefix}`); + +export function javascriptSample(request: ExampleRequest): string { + const { body } = request; + const lines: string[] = []; + if (body?.kind === "binary") lines.push(`import { readFile } from "node:fs/promises";`, ``); + if (body?.kind === "form") { + lines.push(`const form = new FormData();`); + for (const name of body.fields) { + lines.push(`form.append(${JSON.stringify(name)}, ${JSON.stringify(placeholder(name))});`); + } + lines.push(``); + } + lines.push( + `const response = await fetch(process.env.${DEPLOYMENT_URL_ENV} + ${JSON.stringify(request.url)}, {`, + ` method: ${JSON.stringify(request.method)},`, + ); + if (request.headers.length > 0) { + lines.push(` headers: {`); + for (const header of request.headers) { + const value = + "token" in header ? `process.env.${SESSION_TOKEN_ENV}` : JSON.stringify(header.value); + lines.push(` ${JSON.stringify(header.name)}: ${value},`); + } + lines.push(` },`); + } + if (body?.kind === "json") { + lines.push(` body: JSON.stringify(${reindent(jsonText(body.value), " ")}),`); + } + if (body?.kind === "form") lines.push(` body: form,`); + if (body?.kind === "binary") { + lines.push(` body: await readFile(${JSON.stringify(placeholder("file"))}),`); + } + lines.push(`});`, `console.log(response.status, await response.text());`); + return lines.join("\n"); +} + +/** A JSON value as a Python literal; a JSON string literal is also a valid Python one. */ +function pythonLiteral(value: unknown, indent: string): string { + const inner = `${indent} `; + if (value === null || value === undefined) return "None"; + if (value === true) return "True"; + if (value === false) return "False"; + if (Array.isArray(value)) { + if (value.length === 0) return "[]"; + return `[\n${value.map((item) => `${inner}${pythonLiteral(item, inner)},`).join("\n")}\n${indent}]`; + } + if (isObject(value)) { + const entries = Object.entries(value); + if (entries.length === 0) return "{}"; + return `{\n${entries.map(([key, item]) => `${inner}${JSON.stringify(key)}: ${pythonLiteral(item, inner)},`).join("\n")}\n${indent}}`; + } + return JSON.stringify(value); +} + +const PYTHON_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]); + +export function pythonSample(request: ExampleRequest): string { + const { body } = request; + const call = PYTHON_METHODS.has(request.method) + ? `requests.${request.method.toLowerCase()}(` + : `requests.request(\n ${JSON.stringify(request.method)},`; + const lines = [ + `import os`, + ``, + `import requests`, + ``, + `response = ${call}`, + ` os.environ["${DEPLOYMENT_URL_ENV}"] + ${JSON.stringify(request.url)},`, + ]; + // requests sets this one itself for `json=`. + const headers = request.headers.filter( + (header) => + !(body?.kind === "json" && "value" in header && header.value === "application/json"), + ); + if (headers.length > 0) { + lines.push(` headers={`); + for (const header of headers) { + const value = + "token" in header ? `os.environ["${SESSION_TOKEN_ENV}"]` : JSON.stringify(header.value); + lines.push(` ${JSON.stringify(header.name)}: ${value},`); + } + lines.push(` },`); + } + if (body?.kind === "json") lines.push(` json=${pythonLiteral(body.value, " ")},`); + if (body?.kind === "form") { + lines.push(` files={`); + for (const name of body.fields) { + lines.push(` ${JSON.stringify(name)}: (None, ${JSON.stringify(placeholder(name))}),`); + } + lines.push(` },`); + } + if (body?.kind === "binary") { + lines.push(` data=open(${JSON.stringify(placeholder("file"))}, "rb"),`); + } + lines.push(`)`, `print(response.status_code, response.text)`); + return lines.join("\n"); +} + +const GO_METHODS: Record = { + GET: "http.MethodGet", + POST: "http.MethodPost", + PUT: "http.MethodPut", + PATCH: "http.MethodPatch", + DELETE: "http.MethodDelete", + HEAD: "http.MethodHead", + OPTIONS: "http.MethodOptions", +}; + +/** A Go string literal for JSON text: raw when it can be, else interpreted, whose escapes JSON's match. */ +const goString = (json: string): string => + json.includes("`") ? JSON.stringify(json) : `\`${json}\``; + +const goCheck = [`\tif err != nil {`, `\t\tpanic(err)`, `\t}`]; + +export function goSample(request: ExampleRequest): string { + const { body } = request; + const imports = new Set(["fmt", "io", "net/http", "os"]); + const setup: string[] = []; + let reader = "nil"; + if (body?.kind === "json") { + imports.add("strings"); + setup.push(`\tbody := strings.NewReader(${goString(jsonText(body.value))})`); + reader = "body"; + } + if (body?.kind === "form") { + imports.add("bytes"); + imports.add("mime/multipart"); + setup.push(`\tvar body bytes.Buffer`, `\tform := multipart.NewWriter(&body)`); + for (const name of body.fields) { + setup.push( + `\tif err := form.WriteField(${JSON.stringify(name)}, ${JSON.stringify(placeholder(name))}); err != nil {`, + `\t\tpanic(err)`, + `\t}`, + ); + } + setup.push(`\tif err := form.Close(); err != nil {`, `\t\tpanic(err)`, `\t}`); + reader = "&body"; + } + if (body?.kind === "binary") { + setup.push(`\tbody, err := os.Open(${JSON.stringify(placeholder("file"))})`, ...goCheck); + setup.push(`\tdefer body.Close()`); + reader = "body"; + } + const method = GO_METHODS[request.method] ?? JSON.stringify(request.method); + const headers = request.headers.map((header) => + "token" in header + ? `\treq.Header.Set(${JSON.stringify(header.name)}, os.Getenv("${SESSION_TOKEN_ENV}"))` + : `\treq.Header.Set(${JSON.stringify(header.name)}, ${JSON.stringify(header.value)})`, + ); + if (body?.kind === "form") + headers.push(`\treq.Header.Set("Content-Type", form.FormDataContentType())`); + return [ + `package main`, + ``, + `import (`, + ...[...imports].sort().map((name) => `\t"${name}"`), + `)`, + ``, + `func main() {`, + ...setup, + `\treq, err := http.NewRequest(${method}, os.Getenv("${DEPLOYMENT_URL_ENV}")+${JSON.stringify(request.url)}, ${reader})`, + ...goCheck, + ...headers, + `\tresp, err := http.DefaultClient.Do(req)`, + ...goCheck, + `\tdefer resp.Body.Close()`, + `\tout, err := io.ReadAll(resp.Body)`, + ...goCheck, + `\tfmt.Println(resp.Status, string(out))`, + `}`, + ].join("\n"); +} + +export interface CodeSample { + id: string; + lang: string; + label: string; + source: string; +} + +/** The operation's example request in each language the reference shows, in tab order. */ +export function codeSamples(bundled: Json, path: string, method: string): CodeSample[] { + const request = exampleRequest(bundled, path, method); + return [ + { id: "curl", lang: "bash", label: "cURL", source: curlSample(request) }, + { + id: "javascript", + lang: "javascript", + label: "JavaScript", + source: javascriptSample(request), + }, + { id: "python", lang: "python", label: "Python", source: pythonSample(request) }, + { id: "go", lang: "go", label: "Go", source: goSample(request) }, + ]; +} + +/** The document with the operation's code samples as its only ones, leaving the input untouched. */ +export function withCodeSamples(bundled: Json, path: string, method: string): Json { + const samples = codeSamples(bundled, path, method); + const paths = bundled.paths as Record; + const pathItem = paths[path] as Json; + return { + ...bundled, + paths: { + ...paths, + [path]: { + ...pathItem, + [method]: { ...(pathItem[method] as Json), "x-codeSamples": samples }, + }, + }, + }; +} diff --git a/packages/docs-next/src/openapi/curl.test.ts b/packages/docs-next/src/openapi/curl.test.ts deleted file mode 100644 index b859c052..00000000 --- a/packages/docs-next/src/openapi/curl.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { curlCommand, withCurlSample } from "./curl.js"; - -const document = { - openapi: "3.0.3", - info: { title: "Coder API", version: "2.0" }, - paths: { - "/api/v2/users/{user}": { - get: { - security: [{ CoderSessionToken: [] }], - parameters: [ - { name: "user", in: "path", required: true, schema: { type: "string" } }, - { name: "q", in: "query", required: false, schema: { type: "string" } }, - { name: "limit", in: "query", required: true, schema: { type: "integer" } }, - ], - responses: { "200": { description: "OK" } }, - }, - }, - "/api/v2/users": { - post: { - security: [{ CoderSessionToken: [] }], - requestBody: { - required: true, - content: { - "application/json": { schema: { $ref: "#/components/schemas/CreateUser" } }, - }, - }, - responses: { "201": { description: "Created" } }, - }, - }, - "/api/v2/buildinfo": { - get: { responses: { "200": { description: "OK" } } }, - }, - "/scim/v2/Users": { - get: { security: [{ Authorization: [] }], responses: { "200": { description: "OK" } } }, - }, - }, - components: { - securitySchemes: { - CoderSessionToken: { type: "apiKey", name: "Coder-Session-Token", in: "header" }, - Authorization: { type: "apiKey", name: "Authorization", in: "header" }, - }, - schemas: { - CreateUser: { - type: "object", - required: ["email", "username"], - properties: { - email: { type: "string", format: "email" }, - username: { type: "string" }, - name: { type: "string" }, - note: { type: "string", default: "it's" }, - }, - }, - }, - }, -}; - -test("a GET keeps path params as placeholders and adds only required query params", () => { - assert.equal( - curlCommand(document, "/api/v2/users/{user}", "get"), - [ - `curl -X GET "$(coder whoami -o json | jq -r '.[0].url')/api/v2/users/{user}?limit={limit}" \\`, - ` -H "Coder-Session-Token: $(coder login token)"`, - ].join("\n"), - ); -}); - -test("a JSON body is a sample of the schema's required fields", () => { - assert.equal( - curlCommand(document, "/api/v2/users", "post"), - [ - `curl -X POST "$(coder whoami -o json | jq -r '.[0].url')/api/v2/users" \\`, - ` -H "Coder-Session-Token: $(coder login token)" \\`, - ` -H "Content-Type: application/json" \\`, - ` -d '{`, - ` "email": "user@example.com",`, - ` "username": "string"`, - `}'`, - ].join("\n"), - ); -}); - -test("an operation without security sends no token", () => { - assert.equal( - curlCommand(document, "/api/v2/buildinfo", "get"), - `curl -X GET "$(coder whoami -o json | jq -r '.[0].url')/api/v2/buildinfo"`, - ); -}); - -test("another auth scheme gets a placeholder, never the session token", () => { - assert.equal( - curlCommand(document, "/scim/v2/Users", "get"), - [ - `curl -X GET "$(coder whoami -o json | jq -r '.[0].url')/scim/v2/Users" \\`, - ` -H "Authorization: {Authorization}"`, - ].join("\n"), - ); -}); - -test("single quotes in a body example are escaped for the shell", () => { - const withQuote = { - ...document, - paths: { - "/api/v2/users": { - post: { - requestBody: { content: { "application/json": { example: { note: "it's" } } } }, - responses: { "201": { description: "Created" } }, - }, - }, - }, - }; - assert.match( - curlCommand(withQuote, "/api/v2/users", "post"), - /-d '\{\n {2}"note": "it'\\''s"\n\}'$/, - ); -}); - -test("a body of only optional fields shows the first three instead of {}", () => { - const optional = { - ...document, - paths: { - "/api/v2/templates/{template}": { - patch: { - parameters: [{ name: "template", in: "path", required: true }], - requestBody: { - content: { - "application/json": { - schema: { - type: "object", - properties: { - a: { type: "boolean" }, - b: { type: "integer" }, - c: { type: "string" }, - d: { type: "string" }, - }, - }, - }, - }, - }, - responses: { "200": { description: "OK" } }, - }, - }, - }, - }; - assert.match( - curlCommand(optional, "/api/v2/templates/{template}", "patch"), - /-d '\{\n {2}"a": true,\n {2}"b": 0,\n {2}"c": "string"\n\}'$/, - ); -}); - -test("a Content-Type header parameter replaces the declared media type", () => { - const upload = { - ...document, - paths: { - "/api/v2/files": { - post: { - security: [{ CoderSessionToken: [] }], - parameters: [{ name: "Content-Type", in: "header", required: true }], - requestBody: { - content: { "application/x-www-form-urlencoded": { schema: { type: "object" } } }, - }, - responses: { "201": { description: "Created" } }, - }, - }, - }, - }; - assert.equal( - curlCommand(upload, "/api/v2/files", "post"), - [ - `curl -X POST "$(coder whoami -o json | jq -r '.[0].url')/api/v2/files" \\`, - ` -H "Coder-Session-Token: $(coder login token)" \\`, - ` -H "Content-Type: {Content-Type}" \\`, - ` --data-binary "@{file}"`, - ].join("\n"), - ); -}); - -test("the sample becomes the operation's only code sample without changing the input", () => { - const before = JSON.stringify(document); - const out = withCurlSample(document, "/api/v2/buildinfo", "get"); - assert.equal(JSON.stringify(document), before); - const samples = JSON.parse(JSON.stringify(out)).paths["/api/v2/buildinfo"].get["x-codeSamples"]; - assert.deepEqual(samples, [ - { - id: "curl", - lang: "bash", - label: "cURL", - source: `curl -X GET "$(coder whoami -o json | jq -r '.[0].url')/api/v2/buildinfo"`, - }, - ]); -}); diff --git a/packages/docs-next/src/openapi/curl.ts b/packages/docs-next/src/openapi/curl.ts deleted file mode 100644 index 47a877f3..00000000 --- a/packages/docs-next/src/openapi/curl.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { type JsonSchema, dereference, sample } from "@fumadocs/json-schema"; -import { createMagicProxy, getRaw } from "@scalar/json-magic/magic-proxy"; - -type Json = Record; - -/** The reader's deployment URL and session token, read from their `coder` CLI login by the shell. */ -export const DEPLOYMENT_URL = `$(coder whoami -o json | jq -r '.[0].url')`; -export const SESSION_TOKEN = `$(coder login token)`; - -const isObject = (value: unknown): value is Json => - typeof value === "object" && value !== null && !Array.isArray(value); - -const resolve = (node: unknown): Json | undefined => { - const value = dereference(node); - return isObject(value) ? value : undefined; -}; - -/** Text inside double quotes, where the shell would otherwise expand `$`, backticks and backslashes. */ -const doubleQuoted = (text: string): string => `"${text.replace(/["$`\\]/g, "\\$&")}"`; - -const singleQuoted = (text: string): string => `'${text.replace(/'/g, `'\\''`)}'`; - -const placeholder = (name: string): string => `{${name}}`; - -interface Parameter { - name: string; - in: string; - required?: boolean; -} - -function parametersOf(pathItem: Json, operation: Json): Parameter[] { - const byKey = new Map(); - for (const list of [pathItem.parameters, operation.parameters]) { - if (!Array.isArray(list)) continue; - for (const item of list) { - const param = resolve(item); - if (typeof param?.name !== "string" || typeof param.in !== "string") continue; - byKey.set(`${param.in}:${param.name}`, { - name: param.name, - in: param.in, - required: param.required === true, - }); - } - } - return [...byKey.values()]; -} - -/** The auth headers of the first security alternative, preferring the session token; none when auth is optional. */ -function authHeaders(document: Json, operation: Json): string[] { - const requirements = (operation.security ?? document.security) as Json[] | undefined; - if (!Array.isArray(requirements) || requirements.length === 0) return []; - if (requirements.some((item) => isObject(item) && Object.keys(item).length === 0)) return []; - const schemes = resolve(resolve(document.components)?.securitySchemes) ?? {}; - const header = (key: string): string | undefined => { - const scheme = resolve(schemes[key]); - if (scheme?.type === "apiKey" && scheme.in === "header" && typeof scheme.name === "string") { - const value = scheme.name === "Coder-Session-Token" ? SESSION_TOKEN : placeholder(key); - return `-H "${scheme.name}: ${value}"`; - } - if (scheme?.type === "http" && String(scheme.scheme).toLowerCase() === "bearer") { - return `-H "Authorization: Bearer ${placeholder(key)}"`; - } - return undefined; - }; - const chosen = - requirements.find((item) => - Object.keys(item).some((key) => resolve(schemes[key])?.name === "Coder-Session-Token"), - ) ?? requirements[0]; - return Object.keys(chosen ?? {}) - .map(header) - .filter((line): line is string => line !== undefined); -} - -const isJson = (mediaType: string): boolean => - /^application\/(?:[\w.+-]+\+)?json\b/.test(mediaType); - -const isEmptyObject = (value: unknown): boolean => - isObject(value) && Object.keys(value).length === 0; - -function jsonSample(schema: JsonSchema, method: string): unknown { - const options = { skipReadOnly: method !== "get", skipWriteOnly: method === "get" }; - const required = sample(schema, { ...options, skipNonRequired: true }); - if (!isEmptyObject(required)) return required; - // A body of only optional fields, such as a PATCH, shows its first few instead of {}. - const full = sample(schema, options); - return isObject(full) ? Object.fromEntries(Object.entries(full).slice(0, 3)) : full; -} - -/** The body flags; `contentType` replaces the declared media type when the operation takes it as a header parameter. */ -function bodyLines(operation: Json, method: string, contentType?: string): string[] { - const body = resolve(operation.requestBody); - const content = resolve(body?.content); - if (!content) return []; - const types = Object.keys(content); - const type = types.find(isJson) ?? types[0]; - if (type === undefined) return []; - const media = resolve(content[type]) ?? {}; - if (isJson(type)) { - const examples = resolve(media.examples); - const firstExample = examples ? resolve(Object.values(examples)[0]) : undefined; - const value = - media.example !== undefined - ? getRaw(media.example) - : firstExample?.value !== undefined - ? getRaw(firstExample.value) - : jsonSample((media.schema ?? {}) as JsonSchema, method); - return [ - `-H "Content-Type: ${contentType ?? type}"`, - `-d ${singleQuoted(JSON.stringify(value, null, 2))}`, - ]; - } - if (type === "multipart/form-data") { - const schema = resolve(media.schema); - const required = Array.isArray(schema?.required) ? (schema.required as string[]) : []; - return required.map((name) => `-F ${doubleQuoted(`${name}=${placeholder(name)}`)}`); - } - return [`-H "Content-Type: ${contentType ?? type}"`, `--data-binary "@${placeholder("file")}"`]; -} - -/** - * A curl command for one operation that takes the deployment URL and session - * token from the reader's `coder` CLI login, so the token is never typed or - * shown. Path and required query and header parameters stay `{name}` - * placeholders for the reader to fill in; a JSON body is the schema's example, - * or a sample of its required fields. - */ -export function curlCommand(bundled: Json, path: string, method: string): string { - const document = createMagicProxy(bundled) as Json; - const pathItem = resolve(resolve(document.paths)?.[path]); - const operation = resolve(pathItem?.[method]); - if (!pathItem || !operation) throw new Error(`no ${method} ${path} in the API document`); - const params = parametersOf(pathItem, operation).filter((param) => param.required); - const isContentType = (param: Parameter) => - param.in === "header" && param.name.toLowerCase() === "content-type"; - const contentTypeParam = params.find(isContentType); - const query = params - .filter((param) => param.in === "query") - .map((param) => `${encodeURIComponent(param.name)}=${placeholder(param.name)}`) - .join("&"); - const url = `${DEPLOYMENT_URL}${doubleQuoted(`${path}${query ? `?${query}` : ""}`).slice(1)}`; - const lines = [ - `curl -X ${method.toUpperCase()} "${url}`, - ...authHeaders(document, operation), - ...params - .filter((param) => param.in === "header" && !isContentType(param)) - .map((param) => `-H ${doubleQuoted(`${param.name}: ${placeholder(param.name)}`)}`), - ...bodyLines(operation, method, contentTypeParam && placeholder(contentTypeParam.name)), - ]; - return lines.join(" \\\n "); -} - -/** The document with the operation's curl command as its only code sample, leaving the input untouched. */ -export function withCurlSample(bundled: Json, path: string, method: string): Json { - const source = curlCommand(bundled, path, method); - const paths = bundled.paths as Record; - const pathItem = paths[path] as Json; - return { - ...bundled, - paths: { - ...paths, - [path]: { - ...pathItem, - [method]: { - ...(pathItem[method] as Json), - "x-codeSamples": [{ id: "curl", lang: "bash", label: "cURL", source }], - }, - }, - }, - }; -} diff --git a/packages/docs-next/src/openapi/index.tsx b/packages/docs-next/src/openapi/index.tsx index 0534e91d..e304d3ea 100644 --- a/packages/docs-next/src/openapi/index.tsx +++ b/packages/docs-next/src/openapi/index.tsx @@ -4,7 +4,7 @@ import { createOpenAPI } from "fumadocs-openapi/server"; import type { RenderBody } from "../types.js"; import { AnchorRedirect } from "./anchor-redirect.js"; import { ApiPage } from "./api-page-lazy.js"; -import { withCurlSample } from "./curl.js"; +import { withCodeSamples } from "./code-samples.js"; type Json = Record; @@ -95,7 +95,7 @@ export function createOpenApiRenderBody( const route = slugs.join("/"); const operation = data.operations[route]; if (operation) { - const document = withCurlSample( + const document = withCodeSamples( pruneDocument(await bundle(versionId, data.document), operation.path, operation.method), operation.path, operation.method, From 00d053c0c92a52cc4e261d73e5f5605a6686a3c0 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 12:42:55 -0400 Subject: [PATCH 10/69] feat(api-reference): show each operation's method badge in the sidebar With one sidebar entry per operation, readers scan for the endpoint by its verb as much as its name, as on fumadocs.dev. fumadocs-openapi's own loader plugin draws the badge from a page's `_openapi.method` data, so the sync now records the method in each operation stub and passes a validated `_openapi: { method }` frontmatter through to the page, failing the sync on any other shape, and both apps load the plugin. The badge's -600/-400 colours fall short of 4.5:1 (7:1 under More contrast) on the sidebar too, so the existing contrast overrides now also cover the sidebar and the landing page's cards. Assisted-by: AI --- apps/docs/lib/sources.ts | 7 +-- apps/offlinedocs/lib/source.ts | 3 +- packages/docs-build/src/http-methods.ts | 11 +++++ .../docs-build/src/openapi-reference.test.ts | 9 ++++ packages/docs-build/src/openapi-reference.ts | 12 ++--- packages/docs-build/src/sync.test.ts | 37 ++++++++++++++++ packages/docs-build/src/sync.ts | 43 +++++++++++++++++- packages/docs-theme/src/brand.css | 44 ++++++++++++++++--- packages/docs-transforms/src/transform.ts | 6 +++ 9 files changed, 155 insertions(+), 17 deletions(-) create mode 100644 packages/docs-build/src/http-methods.ts diff --git a/apps/docs/lib/sources.ts b/apps/docs/lib/sources.ts index 665988bc..b37e470f 100644 --- a/apps/docs/lib/sources.ts +++ b/apps/docs/lib/sources.ts @@ -1,6 +1,7 @@ import type { DocsSource } from "@coder/docs-next"; import { navTitlePlugin, stateBadgesPlugin, versionBaseUrl } from "@coder/docs-next"; import { loader } from "fumadocs-core/source"; +import { openapiPlugin } from "fumadocs-openapi/server"; // The generated content collections stay below the package imports. This // module is the one place the seven route handlers (api/search and the llms @@ -17,8 +18,8 @@ import { versions } from "./versions"; // One Fumadocs source per version, each loaded with the version's URL prefix // so page URLs and relative links carry it (mainline `latest` sits at "/"), -// and with the plugin that puts a page's manifest state pills on its sidebar -// item. +// and with the plugins that put a page's manifest state pills, or an API +// operation's method badge, on its sidebar item. const collections = [docsV0, docsV1, docsV2, docsV3, docsV4, docsV5]; const byId = new Map( @@ -30,7 +31,7 @@ const byId = new Map( loader({ baseUrl: versionBaseUrl(version), source: collection.toFumadocsSource(), - plugins: [navTitlePlugin(), stateBadgesPlugin()], + plugins: [navTitlePlugin(), stateBadgesPlugin(), openapiPlugin()], }), ]; }), diff --git a/apps/offlinedocs/lib/source.ts b/apps/offlinedocs/lib/source.ts index 3c376176..37243ee7 100644 --- a/apps/offlinedocs/lib/source.ts +++ b/apps/offlinedocs/lib/source.ts @@ -1,5 +1,6 @@ import { navTitlePlugin, stateBadgesPlugin } from "@coder/docs-next"; import { loader } from "fumadocs-core/source"; +import { openapiPlugin } from "fumadocs-openapi/server"; // The generated collection stays below the package imports, as in // apps/docs/lib/sources.ts: the order Turbopack meets these imports in decides @@ -11,5 +12,5 @@ import { docs } from "@/.source/server"; export const source = loader({ baseUrl: "/", source: docs.toFumadocsSource(), - plugins: [navTitlePlugin(), stateBadgesPlugin()], + plugins: [navTitlePlugin(), stateBadgesPlugin(), openapiPlugin()], }); diff --git a/packages/docs-build/src/http-methods.ts b/packages/docs-build/src/http-methods.ts new file mode 100644 index 00000000..69998ad0 --- /dev/null +++ b/packages/docs-build/src/http-methods.ts @@ -0,0 +1,11 @@ +/** The operation keys of an OpenAPI path item, in the order the reference lists them. */ +export const HTTP_METHODS = [ + "get", + "put", + "post", + "delete", + "options", + "head", + "patch", + "trace", +] as const; diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index f90c2ff1..a026a061 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -52,6 +52,15 @@ test("each documented operation gets a page under its tag, named by the old anch ); }); +test("each operation page records its method for the sidebar's method badge", async () => { + const { source: out } = await applyOpenApiReference(source, swagger); + const page = out.files.find((file) => file.path === "reference/api/users/create-new-user.md"); + assert.match( + page?.content ?? "", + /^---\ntitle: "Create new user"\n_openapi:\n {2}method: post\n---\n/, + ); +}); + test("old tag and schema anchors redirect to the operation pages", async () => { const { reference } = await applyOpenApiReference(source, swagger); assert.equal( diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 37ea0e34..bf10b9bb 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -8,6 +8,7 @@ import { buildDirRoutes, mapMdPath } from "@coder/docs-transforms"; import GithubSlugger from "github-slugger"; import { validate } from "oas-validator"; import { convertObj } from "swagger2openapi"; +import { HTTP_METHODS } from "./http-methods.js"; type Json = Record; @@ -36,8 +37,6 @@ export interface ApplyOpenApiReferenceOptions { server?: { url: string; variables?: Record }; } -const METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"] as const; - const isObject = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value); @@ -50,7 +49,8 @@ const linkText = (text: string): string => .replace(/\s+/g, " ") .trim(); -const frontmatter = (title: string): string => `---\ntitle: ${JSON.stringify(title)}\n---\n\n`; +const frontmatter = (title: string, method?: string): string => + `---\ntitle: ${JSON.stringify(title)}\n${method ? `_openapi:\n method: ${method}\n` : ""}---\n\n`; function collectRefs(value: unknown, into: Set): void { if (Array.isArray(value)) { @@ -105,7 +105,7 @@ export async function convertSwagger( const schemes = isObject(components.securitySchemes) ? components.securitySchemes : {}; for (const [route, item] of Object.entries(isObject(document.paths) ? document.paths : {})) { if (!isObject(item)) continue; - for (const method of METHODS) { + for (const method of HTTP_METHODS) { const operation = item[method]; if (!isObject(operation)) continue; if (Array.isArray(operation.security)) { @@ -194,7 +194,7 @@ export async function applyOpenApiReference( const byTag = new Map(); for (const [route, item] of Object.entries(paths)) { if (!isObject(item)) continue; - for (const method of METHODS) { + for (const method of HTTP_METHODS) { const operation = item[method]; if (!isObject(operation)) continue; const apidocgen = operation["x-apidocgen"]; @@ -237,7 +237,7 @@ export async function applyOpenApiReference( const lines = [`\`${op.method.toUpperCase()} ${op.path}\``]; if (op.deprecated) lines.push("This endpoint is deprecated."); if (op.description) lines.push(op.description); - generated.set(op.file, `${frontmatter(op.summary)}${lines.join("\n\n")}\n`); + generated.set(op.file, `${frontmatter(op.summary, op.method)}${lines.join("\n\n")}\n`); } } diff --git a/packages/docs-build/src/sync.test.ts b/packages/docs-build/src/sync.test.ts index 8c77e5b1..f4bb65f3 100644 --- a/packages/docs-build/src/sync.test.ts +++ b/packages/docs-build/src/sync.test.ts @@ -972,6 +972,43 @@ for (const [label, value] of [ }); } +test("sync passes an operation page's _openapi method through for the sidebar badge", async () => { + const src = fixtureSource( + { + "index.md": "---\ntitle: List users\n_openapi:\n method: GET\n---\n\nBody\n", + "plain.md": "# Plain\n\nBody\n", + }, + { experiments: [] }, + ); + await syncDocSource(src, { contentDir, publicDir }); + assert.match(await read("index.md"), /^_openapi: \{"method":"get"\}$/m); + assert.doesNotMatch(await read("plain.md"), /_openapi/); +}); + +for (const [label, value] of [ + ["an unknown method", '{ method: "fetch" }'], + ["a method that is not a string", "{ method: 1 }"], + ["a key other than method", '{ method: "get", webhook: true }'], + ["not a mapping", '"get"'], +] as const) { + test(`sync rejects an _openapi that is ${label}, naming the file`, async () => { + const src = fixtureSource( + { "index.md": `---\ntitle: Home\n_openapi: ${value}\n---\n\nBody\n` }, + { experiments: [] }, + ); + await assert.rejects( + () => syncDocSource(src, { contentDir, publicDir }), + (err: unknown) => { + assert.ok(err instanceof DocSyncError); + assert.equal(err.issues.invalidOpenApi.length, 1); + assert.equal(err.issues.invalidOpenApi[0]?.source, "index.md"); + assert.match(err.message, /index\.md.*_openapi|_openapi.*index\.md/s); + return true; + }, + ); + }); +} + // The manifest is the only source of a page's state: the fixture puts it on // the manifest node, and the sync writes it as a JSON array (a valid YAML flow // sequence) so the page schema reads back exactly the manifest's list. diff --git a/packages/docs-build/src/sync.ts b/packages/docs-build/src/sync.ts index 68ad87d0..cfa4edc3 100644 --- a/packages/docs-build/src/sync.ts +++ b/packages/docs-build/src/sync.ts @@ -26,6 +26,7 @@ import { stripHtmlComments, } from "@coder/docs-transforms"; import { imageSize } from "@fumari/image-size"; +import { HTTP_METHODS } from "./http-methods.js"; import { MAX_INCLUDE_DEPTH, expandIncludes } from "./includes.js"; import { reservedAssetReason, reservedRouteReason } from "./reserved-routes.js"; @@ -258,6 +259,11 @@ export interface SyncIssues { * colour to render as a pill. */ invalidState: { source: string; value: string }[]; + /** + * Pages whose `_openapi` frontmatter is not `{ method }` with an HTTP + * method, the only shape the sidebar's method badge reads. + */ + invalidOpenApi: { source: string; reason: string }[]; } /** Summary returned by a successful `syncDocSource`. */ @@ -334,6 +340,7 @@ function emptyIssues(): SyncIssues { invalidPremiumCallout: [], invalidTocDepth: [], invalidState: [], + invalidOpenApi: [], }; } @@ -358,7 +365,8 @@ function hasIssues(i: SyncIssues): boolean { i.unknownExperiments.length > 0 || i.invalidPremiumCallout.length > 0 || i.invalidTocDepth.length > 0 || - i.invalidState.length > 0 + i.invalidState.length > 0 || + i.invalidOpenApi.length > 0 ); } @@ -504,9 +512,18 @@ function formatIssues(i: SyncIssues): string { .join("\n")}`, ); } + if (i.invalidOpenApi.length > 0) { + parts.push( + `${i.invalidOpenApi.length} page(s) with an invalid _openapi:\n${i.invalidOpenApi + .map((u) => ` ${u.source}: ${u.reason}`) + .join("\n")}`, + ); + } return `docs sync found ${parts.length} blocking issue group(s):\n${parts.join("\n\n")}`; } +const OPENAPI_METHODS = new Set(HTTP_METHODS); + function yamlString(s: string): string { return JSON.stringify(String(s)); } @@ -696,6 +713,7 @@ export async function syncDocSource( description: fmDescription, premiumCalloutRaw, tocDepthRaw, + openapiRaw, } = extracted; const title = route === "" && options.rootTitle !== undefined ? options.rootTitle : extractedTitle; @@ -827,6 +845,28 @@ export async function syncDocSource( } } + let openapiMethod: string | null = null; + if (openapiRaw !== undefined) { + const method = + typeof openapiRaw === "object" && openapiRaw !== null && !Array.isArray(openapiRaw) + ? (openapiRaw as Record).method + : undefined; + const keys = + typeof openapiRaw === "object" && openapiRaw !== null ? Object.keys(openapiRaw) : []; + if ( + typeof method === "string" && + OPENAPI_METHODS.has(method.toLowerCase()) && + keys.length === 1 + ) { + openapiMethod = method.toLowerCase(); + } else { + issues.invalidOpenApi.push({ + source: rel, + reason: `_openapi must be { method } with one of ${HTTP_METHODS.join(", ")}`, + }); + } + } + // The manifest's state list, deduped in manifest order; an unknown value // is reported and (in lenient mode) dropped, so the page schema never // sees a value it cannot render. @@ -904,6 +944,7 @@ export async function syncDocSource( if (states.length > 0) fm.push(`state: ${JSON.stringify(states)}`); if (navTitle !== undefined) fm.push(`nav_title: ${yamlString(navTitle)}`); if (tocDepth !== null) fm.push(`toc_depth: ${tocDepth}`); + if (openapiMethod !== null) fm.push(`_openapi: ${JSON.stringify({ method: openapiMethod })}`); if (Object.keys(experimentNames).length > 0) fm.push(`experiments: ${JSON.stringify(experimentNames)}`); const out = `---\n${fm.join("\n")}\n---\n\n${body.replace(/^\n+/, "")}`; diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css index a28fcbae..a8dfcd8f 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -677,8 +677,15 @@ samp { transition-property: width, inset-block, transform, translate, background-color, visibility; } -/* fumadocs-openapi's method badges and links are -600/-400 shades that fall short of 4.5:1 (7:1 for More contrast) on its card surface; the playground dialog is portalled out of the page. */ -:root:not(.dark) :is(.coder-api-page, [data-base-ui-portal] > [role="dialog"]) { +/* fumadocs-openapi's method badges (on API pages, the landing cards and the sidebar) and links are -600/-400 shades that fall short of 4.5:1 (7:1 for More contrast); the playground dialog is portalled out of the page. */ +:root:not(.dark) + :is( + .coder-api-page, + .coder-api-cards, + #nd-sidebar, + #nd-sidebar-mobile, + [data-base-ui-portal] > [role="dialog"] + ) { --color-green-600: oklch(45% 0.13 150); --color-blue-600: oklch(48% 0.2 262); --color-orange-600: oklch(50% 0.15 50); @@ -687,7 +694,13 @@ samp { } :root[data-contrast="more"]:not(.dark) - :is(.coder-api-page, [data-base-ui-portal] > [role="dialog"]) { + :is( + .coder-api-page, + .coder-api-cards, + #nd-sidebar, + #nd-sidebar-mobile, + [data-base-ui-portal] > [role="dialog"] + ) { --color-green-600: oklch(38% 0.1 150); --color-blue-600: oklch(40% 0.18 262); --color-orange-600: oklch(42% 0.13 50); @@ -695,7 +708,14 @@ samp { --color-red-600: oklch(42% 0.17 27); } -:root[data-contrast="more"].dark :is(.coder-api-page, [data-base-ui-portal] > [role="dialog"]) { +:root[data-contrast="more"].dark + :is( + .coder-api-page, + .coder-api-cards, + #nd-sidebar, + #nd-sidebar-mobile, + [data-base-ui-portal] > [role="dialog"] + ) { --color-green-400: oklch(88% 0.15 150); --color-blue-400: oklch(85% 0.1 262); --color-orange-400: oklch(86% 0.1 60); @@ -705,7 +725,13 @@ samp { @media (prefers-contrast: more) { :root:not([data-contrast="standard"]):not(.dark) - :is(.coder-api-page, [data-base-ui-portal] > [role="dialog"]) { + :is( + .coder-api-page, + .coder-api-cards, + #nd-sidebar, + #nd-sidebar-mobile, + [data-base-ui-portal] > [role="dialog"] + ) { --color-green-600: oklch(38% 0.1 150); --color-blue-600: oklch(40% 0.18 262); --color-orange-600: oklch(42% 0.13 50); @@ -714,7 +740,13 @@ samp { } :root:not([data-contrast="standard"]).dark - :is(.coder-api-page, [data-base-ui-portal] > [role="dialog"]) { + :is( + .coder-api-page, + .coder-api-cards, + #nd-sidebar, + #nd-sidebar-mobile, + [data-base-ui-portal] > [role="dialog"] + ) { --color-green-400: oklch(88% 0.15 150); --color-blue-400: oklch(85% 0.1 262); --color-orange-400: oklch(86% 0.1 60); diff --git a/packages/docs-transforms/src/transform.ts b/packages/docs-transforms/src/transform.ts index c845c265..4300462f 100644 --- a/packages/docs-transforms/src/transform.ts +++ b/packages/docs-transforms/src/transform.ts @@ -1050,6 +1050,8 @@ export function parseFrontmatter(content: string): { * anything else against the file. */ tocDepthRaw?: unknown; + /** The raw `_openapi` frontmatter value, on the same terms; the sync validates it. */ + openapiRaw?: unknown; endLine: number; } { const none = { title: null, description: null, premiumCallout: null, endLine: 0 }; @@ -1085,6 +1087,7 @@ export function parseFrontmatter(content: string): { endLine, ...(obj.premium_callout !== undefined ? { premiumCalloutRaw: obj.premium_callout } : {}), ...(obj.toc_depth !== undefined ? { tocDepthRaw: obj.toc_depth } : {}), + ...(obj._openapi !== undefined ? { openapiRaw: obj._openapi } : {}), }; } @@ -1105,6 +1108,8 @@ export function extractTitle( premiumCalloutRaw?: unknown; /** See `parseFrontmatter`'s `tocDepthRaw`; threaded through unchanged. */ tocDepthRaw?: unknown; + /** See `parseFrontmatter`'s `openapiRaw`; threaded through unchanged. */ + openapiRaw?: unknown; } { const fm = parseFrontmatter(content); const body = fm.endLine > 0 ? content.split("\n").slice(fm.endLine).join("\n") : content; @@ -1138,6 +1143,7 @@ export function extractTitle( premiumCallout: fm.premiumCallout, ...(fm.premiumCalloutRaw !== undefined ? { premiumCalloutRaw: fm.premiumCalloutRaw } : {}), ...(fm.tocDepthRaw !== undefined ? { tocDepthRaw: fm.tocDepthRaw } : {}), + ...(fm.openapiRaw !== undefined ? { openapiRaw: fm.openapiRaw } : {}), }; } From b3f81c3ae37b56a72b9fe4d5767d72db7938114d Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 12:46:23 -0400 Subject: [PATCH 11/69] feat(api-reference): set-up section and operation cards on the API landing page The code samples now read CODER_URL and CODER_SESSION_TOKEN, so the landing page tells readers how to set them: from an existing CLI login, or from a long-lived `coder tokens create` token kept in a secret store. The sync inserts that section before the page's first section, and each operation page's note above its samples links to it through the base-path-aware href. Below the page's own Markdown, every operation gets a fumadocs-ui card with its method badge and the first sentence of its description, grouped under one heading per tag in sidebar order. A render-body hook can now add the headings it renders to the page's table of contents, so "On this page" lists the tag sections. The cards are server-rendered with plain links stretched over each card, not client Links, so the few hundred of them add no hydration and no prefetching; the sync computes their heading ids with the same slugger over the page's own headings so none repeats. The language samples are now one tab each, where fumadocs-openapi's default is a select in the code block's header. Assisted-by: AI --- apps/docs/scripts/a11y-axe-helpers.mjs | 1 + apps/docs/scripts/openapi-source.mjs | 1 + .../docs-build/src/openapi-reference.test.ts | 78 ++++++++++ packages/docs-build/src/openapi-reference.ts | 134 +++++++++++++++++- packages/docs-next/src/openapi/api-page.tsx | 32 ++++- packages/docs-next/src/openapi/index.tsx | 31 +++- .../docs-next/src/openapi/landing.test.tsx | 107 ++++++++++++++ packages/docs-next/src/openapi/landing.tsx | 54 +++++++ .../src/openapi/method-badge.test.tsx | 32 +++++ .../docs-next/src/openapi/method-badge.tsx | 19 +++ .../src/openapi/samples-note.test.tsx | 27 ++++ .../docs-next/src/openapi/samples-note.tsx | 27 ++++ packages/docs-next/src/page.tsx | 5 +- packages/docs-next/src/render-body.test.tsx | 46 ++++++ packages/docs-next/src/render-body.tsx | 16 ++- packages/docs-next/src/types.ts | 9 +- packages/docs-next/src/versioned.tsx | 5 +- packages/docs-theme/src/brand.css | 30 ++++ packages/docs-transforms/src/index.ts | 1 + .../docs-transforms/src/transform.test.ts | 27 ++++ packages/docs-transforms/src/transform.ts | 18 +++ 21 files changed, 675 insertions(+), 25 deletions(-) create mode 100644 packages/docs-next/src/openapi/landing.test.tsx create mode 100644 packages/docs-next/src/openapi/landing.tsx create mode 100644 packages/docs-next/src/openapi/method-badge.test.tsx create mode 100644 packages/docs-next/src/openapi/method-badge.tsx create mode 100644 packages/docs-next/src/openapi/samples-note.test.tsx create mode 100644 packages/docs-next/src/openapi/samples-note.tsx create mode 100644 packages/docs-next/src/render-body.test.tsx diff --git a/apps/docs/scripts/a11y-axe-helpers.mjs b/apps/docs/scripts/a11y-axe-helpers.mjs index 0b838d2c..f8e174c0 100644 --- a/apps/docs/scripts/a11y-axe-helpers.mjs +++ b/apps/docs/scripts/a11y-axe-helpers.mjs @@ -20,6 +20,7 @@ export const DEFAULT_PAGES = [ "/authoring/releases", "/authoring/callouts", "/authoring/states", + "/reference/api", "/reference/api/users", "/reference/api/users/create-new-user", "/reference/api/workspaces/list-workspaces", diff --git a/apps/docs/scripts/openapi-source.mjs b/apps/docs/scripts/openapi-source.mjs index 8a91ee16..cf43d07c 100644 --- a/apps/docs/scripts/openapi-source.mjs +++ b/apps/docs/scripts/openapi-source.mjs @@ -82,6 +82,7 @@ export async function withOpenApiReference(appDir, version, source, swagger) { document: reference.document, operations: reference.operations, anchors: reference.anchors, + landing: reference.landing, }), ); console.log( diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index a026a061..6d84c307 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -106,3 +106,81 @@ test("summaries are escaped where the tag and schemas pages put them in Markdown const tagPage = out.files.find((file) => file.path === "reference/api/workspaces.md")?.content; assert.match(tagPage ?? "", /- \[List \\\[all\\\] a\\\|b \\\\ \\\*workspaces\\\*\]\(/); }); + +const withLanding = (content: string): DocSource => ({ + ...source, + files: source.files.map((file) => + file.path === "reference/api/index.md" ? { ...file, content } : file, + ), +}); + +const landingPage = (out: DocSource): string => + out.files.find((file) => file.path === "reference/api/index.md")?.content ?? ""; + +test("the landing page gets the environment setup section before its first section", async () => { + const { source: out, reference } = await applyOpenApiReference( + withLanding( + "# REST API\n\nIntro.\n\n```md\n## Not a heading\n```\n\n## Quickstart\n\nSteps.\n", + ), + swagger, + ); + const page = landingPage(out); + const setup = page.indexOf("## Set up your environment"); + assert.ok(setup > page.indexOf("## Not a heading"), "a heading in a code fence is not a section"); + assert.ok(setup < page.indexOf("## Quickstart")); + assert.match(page, /export CODER_URL="\$\(coder whoami -o json \| jq -r '\.\[0\]\.url'\)"/); + assert.match(page, /export CODER_SESSION_TOKEN="\$\(coder login token\)"/); + assert.match(page, /coder tokens create --name/); + assert.equal(reference.landing.setupId, "set-up-your-environment"); +}); + +test("the setup section is appended to a landing page with no sections", async () => { + const { source: out } = await applyOpenApiReference(source, swagger); + assert.match(landingPage(out), /^# REST API\n\n## Set up your environment\n/); +}); + +test("the landing sections follow the sidebar's tag order, one card per operation", async () => { + const { reference } = await applyOpenApiReference(source, swagger); + assert.equal(reference.landing.route, "reference/api"); + assert.deepEqual(reference.landing.sections, [ + { + title: "Users", + id: "users", + operations: [ + { route: "reference/api/users/create-new-user", title: "Create new user", method: "post" }, + { route: "reference/api/users/get-user-by-name", title: "Get user by name", method: "get" }, + ], + }, + { + title: "Workspaces", + id: "workspaces", + operations: [ + { + route: "reference/api/workspaces/list-workspaces", + title: "List workspaces", + method: "get", + description: "Returns the workspaces the caller can read, filtered by the search query.", + }, + ], + }, + ]); +}); + +test("a card's description is the first sentence of the operation's, as plain text", async () => { + const long = structuredClone(swagger); + long.paths["/api/v2/workspaces"].get.description = + "Lists [workspaces](https://example.com) with `q`.\nMore detail.\n\nSecond paragraph."; + const { reference } = await applyOpenApiReference(source, long); + const op = reference.landing.sections[1]?.operations[0]; + assert.equal(op?.description, "Lists workspaces with q."); +}); + +test("section ids never repeat a heading the landing page already has", async () => { + const { reference } = await applyOpenApiReference( + withLanding("# REST API\n\n## Users\n\n## Set up your environment\n"), + swagger, + ); + assert.equal(reference.landing.setupId, "set-up-your-environment"); + assert.equal(reference.landing.sections[0]?.id, "users-1"); + assert.equal(reference.landing.sections[1]?.id, "workspaces"); +}); diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index bf10b9bb..d0e361d5 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -4,7 +4,7 @@ import { type DocSource, type ManifestNode, } from "@coder/docs-config"; -import { buildDirRoutes, mapMdPath } from "@coder/docs-transforms"; +import { buildDirRoutes, findHeadings, mapMdPath, parseFrontmatter } from "@coder/docs-transforms"; import GithubSlugger from "github-slugger"; import { validate } from "oas-validator"; import { convertObj } from "swagger2openapi"; @@ -27,9 +27,32 @@ export interface OpenApiReference { document: Json; operations: Record; anchors: Record>; + landing: OpenApiLanding; warnings: string[]; } +/** An operation's card on the landing page. */ +export interface LandingOperation { + route: string; + title: string; + method: string; + description?: string; +} + +/** A tag's cards, under a heading of their own, in sidebar order. */ +export interface LandingSection { + title: string; + id: string; + operations: LandingOperation[]; +} + +/** The landing page (`index.md`): its route, its setup section's id, and its card sections. */ +export interface OpenApiLanding { + route: string; + setupId: string; + sections: LandingSection[]; +} + export interface ApplyOpenApiReferenceOptions { /** The docs-relative directory of the generated reference; defaults to `reference/api`. */ dir?: string; @@ -272,6 +295,12 @@ export async function applyOpenApiReference( `${frontmatter("Schemas")}Each endpoint's page documents the request and response schemas it uses. This table names, for each schema, the endpoint page that shows it most directly.\n\n| Schema | Shown on |\n| --- | --- |\n${schemaRows.join("\n")}\n`, ); + const landingFile = `${dir}/index.md`; + const landingSource = source.files.find((file) => file.path === landingFile); + if (!landingSource) throw new Error(`the source has no ${landingFile}`); + const landing = withSetupSection(landingSource.content); + generated.set(landingFile, landing.content); + const files: DocFile[] = [ ...source.files.filter((file) => !generated.has(file.path)), ...[...generated].map(([path, content]) => ({ path, content })), @@ -318,8 +347,109 @@ export async function applyOpenApiReference( for (const [anchor, op] of schemaTargets) schemaAnchors[anchor] = routeOf(op.file); anchors[routeOf(schemasFile)] = schemaAnchors; + const tagByFile = new Map([...byTag.keys()].map((tag) => [manifestPath(tagFile(tag)), tag])); + const sections: LandingSection[] = []; + for (const child of children) { + const tag = child.path === undefined ? undefined : tagByFile.get(child.path); + const group = tag === undefined ? undefined : byTag.get(tag); + if (tag === undefined || !group) continue; + sections.push({ + title: tag, + id: landing.slugger.slug(tag), + operations: group.ops.map((op) => { + const description = firstSentence(op.description); + return { + route: routeOf(op.file), + title: op.summary, + method: op.method, + ...(description ? { description } : {}), + }; + }), + }); + } + return { source: { ...source, files, manifest: { ...source.manifest, routes } }, - reference: { document, operations, anchors, warnings }, + reference: { + document, + operations, + anchors, + landing: { route: routeOf(landingFile), setupId: landing.setupId, sections }, + warnings, + }, }; } + +const SETUP_HEADING = "Set up your environment"; + +const SETUP_SECTION = `## ${SETUP_HEADING} + +The code samples on each endpoint's page read your deployment URL and a session token from two environment variables, \`CODER_URL\` and \`CODER_SESSION_TOKEN\`, the same ones the Coder CLI reads. + +If you are logged in with the Coder CLI v2.31.1 or later and have \`jq\` installed, set both from your login: + +\`\`\`sh +export CODER_URL="$(coder whoami -o json | jq -r '.[0].url')" +export CODER_SESSION_TOKEN="$(coder login token)" +\`\`\` + +For scripts and CI, create a long-lived token instead, with \`coder tokens create\` or under **Settings** > **Tokens** in the dashboard: + +\`\`\`sh +coder tokens create --name ci --lifetime 30d +\`\`\` + +Store the token in your secret store, and set the variables from it where the script runs: + +\`\`\`sh +export CODER_URL="https://coder.example.com" +export CODER_SESSION_TOKEN="$(cat /run/secrets/coder-token)" +\`\`\` + +Keep the token out of your shell history and out of committed files. +`; + +/** + * The landing page with the environment setup section before its first + * section, and a slugger that has seen every heading the rendered page will + * have, so the setup and card section ids match the page's own. + */ +function withSetupSection(content: string): { + content: string; + setupId: string; + slugger: GithubSlugger; +} { + const { endLine } = parseFrontmatter(content); + const lines = content.split("\n"); + // The sync drops the H1, so it never takes a slug. + const headings = findHeadings(lines.slice(endLine).join("\n")) + .filter((heading) => heading.depth > 1) + .map((heading) => ({ ...heading, line: heading.line + endLine })); + const at = headings.find((heading) => heading.depth === 2)?.line; + const slugger = new GithubSlugger(); + let setupId: string | undefined; + for (const heading of headings) { + if (heading.line === at) setupId = slugger.slug(SETUP_HEADING); + slugger.slug(heading.text); + } + setupId ??= slugger.slug(SETUP_HEADING); + const next = + at === undefined + ? `${content.replace(/\n*$/, "")}\n\n${SETUP_SECTION}` + : [...lines.slice(0, at), SETUP_SECTION, ...lines.slice(at)].join("\n"); + return { content: next, setupId, slugger }; +} + +/** The first sentence of an operation's Markdown description, as plain text for its card. */ +function firstSentence(markdown: string | undefined): string | undefined { + const paragraph = markdown?.trim().split(/\n\s*\n/)[0]; + if (!paragraph) return undefined; + const text = paragraph + .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/[`*]/g, "") + .replace(/\s+/g, " ") + .trim(); + const sentence = /^.*?[.!?](?=\s|$)/.exec(text)?.[0] ?? text; + if (sentence.length <= 200) return sentence || undefined; + return `${sentence.slice(0, sentence.lastIndexOf(" ", 199))}…`; +} diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index 095d5df7..d8d6ea0d 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -2,9 +2,12 @@ import { createShikiFactory } from "fumadocs-core/highlight/shiki"; import type { CodeBlockProps } from "fumadocs-openapi"; +import { useCodeUsage, useOperation } from "fumadocs-openapi/operation"; import { createCodeUsageGeneratorRegistry } from "fumadocs-openapi/requests/generators"; import { createOpenAPIPageBase } from "fumadocs-openapi/ui/base"; import { DynamicCodeBlock } from "fumadocs-ui/components/dynamic-codeblock.core"; +import { Tab, Tabs } from "fumadocs-ui/components/tabs"; +import { SamplesNote } from "./samples-note.js"; // Only the grammars and themes an API page uses (JSON, the code samples, TypeScript definitions), on the JavaScript regex engine (no WASM, no eval). const shiki = createShikiFactory({ @@ -50,6 +53,29 @@ function CodeBlock(props: CodeBlockProps) { ); } +function SampleCode({ id, lang }: { id: string; lang: string }) { + return ; +} + +// One tab per language, where fumadocs-openapi's default is a select in the code block's header. +function SampleTabs() { + const samples = Array.from(useOperation().codeUsages.map(), ([id, sample]) => ({ + id, + lang: sample.lang, + label: sample.label ?? sample.lang, + })); + if (samples.length === 0) return null; + return ( + sample.label)} className="mb-4"> + {samples.map((sample) => ( + + + + ))} + + ); +} + /** One REST API operation, rendered by fumadocs-openapi from the document its page was given, with the server-built code samples and the playground. */ export const ApiPage = createOpenAPIPageBase({ shiki, @@ -59,13 +85,11 @@ export const ApiPage = createOpenAPIPageBase({ codeUsages: createCodeUsageGeneratorRegistry(), storageKeyPrefix: "coder-api-", content: { + renderAPIExampleUsageTabs: () => , renderAPIExampleLayout: ({ selector, usageTabs, responseTabs }) => (
{selector} -

- Needs the Coder CLI v2.31.1 or later, logged in to your deployment with{" "} - coder login <url>, and jq. -

+ {usageTabs} {responseTabs}
diff --git a/packages/docs-next/src/openapi/index.tsx b/packages/docs-next/src/openapi/index.tsx index e304d3ea..da30f14c 100644 --- a/packages/docs-next/src/openapi/index.tsx +++ b/packages/docs-next/src/openapi/index.tsx @@ -5,6 +5,8 @@ import type { RenderBody } from "../types.js"; import { AnchorRedirect } from "./anchor-redirect.js"; import { ApiPage } from "./api-page-lazy.js"; import { withCodeSamples } from "./code-samples.js"; +import { ApiLanding, type OpenApiLandingData } from "./landing.js"; +import { SetupHrefProvider } from "./samples-note.js"; type Json = Record; @@ -13,6 +15,7 @@ export interface OpenApiPagesData { document: Json; operations: Record; anchors: Record>; + landing: OpenApiLandingData; } const isObject = (value: unknown): value is Json => @@ -93,8 +96,20 @@ export function createOpenApiRenderBody( const data = await load(versionId); if (!data) return undefined; const route = slugs.join("/"); + const { landing } = data; + if (route === landing.route) { + return { + after: , + toc: landing.sections.map((section) => ({ + title: section.title, + url: `#${section.id}`, + depth: 2, + })), + }; + } const operation = data.operations[route]; if (operation) { + const landingHref = hrefFor(landing.route); const document = withCodeSamples( pruneDocument(await bundle(versionId, data.document), operation.path, operation.method), operation.path, @@ -104,13 +119,15 @@ export function createOpenApiRenderBody( full: true, replace: (
- + + +
), }; diff --git a/packages/docs-next/src/openapi/landing.test.tsx b/packages/docs-next/src/openapi/landing.test.tsx new file mode 100644 index 00000000..9cd720a7 --- /dev/null +++ b/packages/docs-next/src/openapi/landing.test.tsx @@ -0,0 +1,107 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { renderToFragment } from "../../test/dom.js"; +import { createOpenApiRenderBody } from "./index.js"; +import { ApiLanding, type OpenApiLandingData } from "./landing.js"; + +const landing: OpenApiLandingData = { + route: "reference/api", + setupId: "set-up-your-environment", + sections: [ + { + title: "Users", + id: "users", + operations: [ + { route: "reference/api/users/create-new-user", title: "Create new user", method: "post" }, + { + route: "reference/api/users/get-user-by-name", + title: "Get user by name", + method: "get", + description: "Returns one user.", + }, + ], + }, + { + title: "Workspaces", + id: "workspaces", + operations: [ + { route: "reference/api/workspaces/delete", title: "Delete workspace", method: "delete" }, + ], + }, + ], +}; + +const hrefFor = (route: string) => `/beta-docs/${route}/`; + +const CARDS = ".coder-api-cards > [data-card]"; + +test("each tag is a section heading with a card per operation, in order", () => { + const page = renderToFragment(); + assert.deepEqual( + [...page.querySelectorAll("h2")].map((h2) => [h2.id, h2.querySelector("a")?.textContent]), + [ + ["users", "Users"], + ["workspaces", "Workspaces"], + ], + ); + const cards = [...page.querySelectorAll(CARDS)]; + assert.deepEqual( + cards.map((card) => { + const link = card.querySelector("h3 a"); + return { + href: link?.getAttribute("href"), + name: link?.textContent, + badge: link?.querySelector("span.font-mono")?.textContent, + description: card.querySelector("p")?.textContent ?? null, + }; + }), + [ + { + href: "/beta-docs/reference/api/users/create-new-user/", + name: "Create new user POST", + badge: "POST", + description: null, + }, + { + href: "/beta-docs/reference/api/users/get-user-by-name/", + name: "Get user by name GET", + badge: "GET", + description: "Returns one user.", + }, + { + href: "/beta-docs/reference/api/workspaces/delete/", + name: "Delete workspace DELETE", + badge: "DELETE", + description: null, + }, + ], + ); +}); + +test("an operation without a page gets no card rather than a dead link", () => { + const page = renderToFragment( + (route.endsWith("delete") ? undefined : hrefFor(route))} + />, + ); + assert.equal(page.querySelectorAll(CARDS).length, 2); + assert.equal(page.querySelectorAll("a:not([href])").length, 0); +}); + +test("the landing route gets the cards after its body and their headings in its TOC", async () => { + const renderBody = createOpenApiRenderBody(async () => ({ + document: {}, + operations: {}, + anchors: {}, + landing, + })); + const result = await renderBody({ versionId: undefined, slugs: ["reference", "api"], hrefFor }); + assert.equal(result?.replace, undefined, "the page's own Markdown stays"); + assert.deepEqual(result?.toc, [ + { title: "Users", url: "#users", depth: 2 }, + { title: "Workspaces", url: "#workspaces", depth: 2 }, + ]); + const after = renderToFragment(result?.after); + assert.equal(after.querySelectorAll(CARDS).length, 3); +}); diff --git a/packages/docs-next/src/openapi/landing.tsx b/packages/docs-next/src/openapi/landing.tsx new file mode 100644 index 00000000..c6e1350c --- /dev/null +++ b/packages/docs-next/src/openapi/landing.tsx @@ -0,0 +1,54 @@ +import { Card, Cards } from "fumadocs-ui/components/card"; +import { Heading } from "fumadocs-ui/components/heading"; +import { Fragment } from "react"; +import { MethodBadge } from "./method-badge.js"; + +/** What the sync's `applyOpenApiReference` records for the landing page's cards. */ +export interface OpenApiLandingData { + route: string; + setupId: string; + sections: { + title: string; + id: string; + operations: { route: string; title: string; method: string; description?: string }[]; + }[]; +} + +/** + * A card for every operation, under a heading per tag in sidebar order. The + * cards are server-rendered plain links (no client `Link`, so no prefetch), + * each stretched over its card by `.coder-api-cards` in the theme. + */ +export function ApiLanding({ + sections, + hrefFor, +}: { + sections: OpenApiLandingData["sections"]; + hrefFor: (route: string) => string | undefined; +}) { + return sections.map((section) => ( + + {/* Prose zeroes the margin of whatever follows an h2, as the first section does after bare text. */} + + {section.title} + + + {section.operations.map((operation) => { + const href = hrefFor(operation.route); + if (href === undefined) return null; + return ( + + {operation.title} + + } + description={operation.description} + /> + ); + })} + + + )); +} diff --git a/packages/docs-next/src/openapi/method-badge.test.tsx b/packages/docs-next/src/openapi/method-badge.test.tsx new file mode 100644 index 00000000..3e471914 --- /dev/null +++ b/packages/docs-next/src/openapi/method-badge.test.tsx @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { flattenTree } from "fumadocs-core/page-tree"; +import { type PageData, type VirtualFile, loader } from "fumadocs-core/source"; +import { openapiPlugin } from "fumadocs-openapi/server"; +import { renderToFragment } from "../../test/dom.js"; +import { MethodBadge } from "./method-badge.js"; + +type Files = VirtualFile<{ pageData: PageData & { _openapi?: unknown }; metaData: never }>[]; + +/** The badge fumadocs-openapi's loader plugin puts on the sidebar item of a page with the sync's `_openapi` frontmatter. */ +function sidebarBadge(method: string): Element | null { + const files: Files = [ + { type: "page", path: "api/op.md", data: { title: "Op", _openapi: { method } } }, + ]; + const docs = loader({ baseUrl: "/", source: { files }, plugins: [openapiPlugin()] }); + const item = flattenTree(docs.pageTree.children).find((node) => node.url === "/api/op"); + return renderToFragment(item?.name).querySelector("span"); +} + +for (const method of ["get", "post", "put", "patch", "delete"]) { + test(`the ${method.toUpperCase()} badge looks like the sidebar's, so the theme's contrast overrides cover both`, () => { + const sidebar = sidebarBadge(method); + const badge = renderToFragment().querySelector("span"); + assert.equal(sidebar?.textContent, method.toUpperCase()); + assert.equal(badge?.textContent, method.toUpperCase()); + const colors = (el: Element | null | undefined) => + [...(el?.classList ?? [])].filter((name) => /^(dark:)?text-[a-z]+-\d+$/.test(name)).sort(); + assert.deepEqual(colors(badge), colors(sidebar)); + assert.ok(colors(badge).length === 2); + }); +} diff --git a/packages/docs-next/src/openapi/method-badge.tsx b/packages/docs-next/src/openapi/method-badge.tsx new file mode 100644 index 00000000..db08f938 --- /dev/null +++ b/packages/docs-next/src/openapi/method-badge.tsx @@ -0,0 +1,19 @@ +// Mirrors MethodLabel in fumadocs-openapi 12.5.4 (ui/components/method-label), which the sidebar uses but the package does not export. +const COLORS: Record = { + PUT: "text-yellow-600 dark:text-yellow-400", + PATCH: "text-orange-600 dark:text-orange-400", + POST: "text-blue-600 dark:text-blue-400", + DELETE: "text-red-600 dark:text-red-400", +}; + +/** An HTTP method as the coloured badge the API reference's sidebar shows beside each operation. */ +export function MethodBadge({ method }: { method: string }) { + const label = method.toUpperCase(); + return ( + + {label} + + ); +} diff --git a/packages/docs-next/src/openapi/samples-note.test.tsx b/packages/docs-next/src/openapi/samples-note.test.tsx new file mode 100644 index 00000000..6b00b478 --- /dev/null +++ b/packages/docs-next/src/openapi/samples-note.test.tsx @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { renderToFragment } from "../../test/dom.js"; +import { SamplesNote, SetupHrefProvider } from "./samples-note.js"; + +test("the note names both variables and links to the setup section it is given", () => { + const note = renderToFragment( + + + , + ); + assert.deepEqual( + [...note.querySelectorAll("code")].map((code) => code.textContent), + ["CODER_URL", "CODER_SESSION_TOKEN"], + ); + assert.equal( + note.querySelector("a")?.getAttribute("href"), + "/beta-docs/reference/api/#set-up-your-environment", + ); + assert.doesNotMatch(note.textContent ?? "", /coder login|v2\.31/); +}); + +test("without a setup link the note has no link", () => { + const note = renderToFragment(); + assert.equal(note.querySelector("a"), null); + assert.match(note.textContent ?? "", /CODER_SESSION_TOKEN\.$/); +}); diff --git a/packages/docs-next/src/openapi/samples-note.tsx b/packages/docs-next/src/openapi/samples-note.tsx new file mode 100644 index 00000000..112136d8 --- /dev/null +++ b/packages/docs-next/src/openapi/samples-note.tsx @@ -0,0 +1,27 @@ +"use client"; + +import { type ReactNode, createContext, useContext } from "react"; + +const SetupHref = createContext(undefined); + +/** Gives the operation page's samples note the base-path-aware link to the landing page's setup section. */ +export function SetupHrefProvider({ href, children }: { href?: string; children: ReactNode }) { + return {children}; +} + +/** The line above the code samples naming the environment variables they read. */ +export function SamplesNote() { + const href = useContext(SetupHref); + return ( +

+ The samples read CODER_URL and CODER_SESSION_TOKEN + {href ? ( + <> + : set up your environment. + + ) : ( + "." + )} +

+ ); +} diff --git a/packages/docs-next/src/page.tsx b/packages/docs-next/src/page.tsx index 34aa6e08..e737bace 100644 --- a/packages/docs-next/src/page.tsx +++ b/packages/docs-next/src/page.tsx @@ -58,7 +58,7 @@ export function createDocsPage(source: DocsSource, options: DocsPageOptions = {} if (!page) notFound(); const MDX = page.data.body; - const { body, full } = await resolveBody( + const { body, data } = await resolveBody( options.renderBody, source, undefined, @@ -73,11 +73,12 @@ export function createDocsPage(source: DocsSource, options: DocsPageOptions = {} { assetBasePath: options.assetBasePath }, )} />, + page.data, ); return ( { + const { body, data: out } = await resolveBody( + async ({ hrefFor }) => ({ + after:

{hrefFor("reference/api/users")}

, + toc: [{ title: "Users", url: "#users", depth: 2 }], + }), + source, + undefined, + ["reference", "api"], + "/beta-docs", +

markdown

, + data, + ); + assert.deepEqual( + out.toc.map((item) => item.url), + ["#quickstart", "#users"], + ); + assert.equal(out.full, undefined); + const page = renderToFragment(body); + assert.equal(page.querySelector("p")?.textContent, "markdown"); + assert.equal(page.querySelector("h2")?.textContent, "/beta-docs/reference/api/users/"); +}); + +test("a page no hook touches keeps its own data", async () => { + const result = await resolveBody( + async () => undefined, + source, + undefined, + ["reference", "api"], + undefined, +

markdown

, + data, + ); + assert.equal(result.data, data); +}); diff --git a/packages/docs-next/src/render-body.tsx b/packages/docs-next/src/render-body.tsx index 562e55cc..89a67386 100644 --- a/packages/docs-next/src/render-body.tsx +++ b/packages/docs-next/src/render-body.tsx @@ -1,16 +1,18 @@ +import type { TableOfContents } from "fumadocs-core/toc"; import type { ReactNode } from "react"; import type { DocsSource, RenderBody } from "./types.js"; import { normalizeBasePath } from "./version-routing.js"; -/** The page body after an optional `renderBody` hook has had its say, and whether the page goes full width. */ -export async function resolveBody( +/** The page body after an optional `renderBody` hook has had its say, with the page data it changes. */ +export async function resolveBody( renderBody: RenderBody | undefined, source: DocsSource, versionId: string | undefined, slugs: string[], assetBasePath: string | undefined, markdown: ReactNode, -): Promise<{ body: ReactNode; full?: boolean }> { + data: Data, +): Promise<{ body: ReactNode; data: Data }> { const custom = await renderBody?.({ versionId, slugs, @@ -20,7 +22,7 @@ export async function resolveBody( return `${normalizeBasePath(assetBasePath)}${url.endsWith("/") ? url : `${url}/`}`; }, }); - if (!custom) return { body: markdown }; + if (!custom) return { body: markdown, data }; return { body: ( <> @@ -28,6 +30,10 @@ export async function resolveBody( {custom.after} ), - full: custom.full, + data: { + ...data, + ...(custom.full ? { full: true } : {}), + ...(custom.toc ? { toc: [...data.toc, ...custom.toc] } : {}), + }, }; } diff --git a/packages/docs-next/src/types.ts b/packages/docs-next/src/types.ts index a7f8e8ae..fedb8df0 100644 --- a/packages/docs-next/src/types.ts +++ b/packages/docs-next/src/types.ts @@ -103,9 +103,12 @@ export interface RenderBodyContext { /** * Replaces a page's rendered Markdown body (`replace`) or adds after it - * (`after`); `full` widens the page and drops its table of contents. - * `undefined` leaves the page as it is. + * (`after`); `full` widens the page and drops its table of contents, and + * `toc` adds the headings `after` renders to it. `undefined` leaves the page + * as it is. */ export type RenderBody = ( context: RenderBodyContext, -) => Promise<{ replace?: ReactNode; after?: ReactNode; full?: boolean } | undefined>; +) => Promise< + { replace?: ReactNode; after?: ReactNode; full?: boolean; toc?: TableOfContents } | undefined +>; diff --git a/packages/docs-next/src/versioned.tsx b/packages/docs-next/src/versioned.tsx index f800d352..5c8b1063 100644 --- a/packages/docs-next/src/versioned.tsx +++ b/packages/docs-next/src/versioned.tsx @@ -101,7 +101,7 @@ export function createVersionedDocs(options: VersionedDocsOptions) { if (!found) notFound(); const MDX = found.page.data.body; - const { body, full } = await resolveBody( + const { body, data } = await resolveBody( renderBody, found.source, found.version.id, @@ -113,10 +113,11 @@ export function createVersionedDocs(options: VersionedDocsOptions) { { assetBasePath }, )} />, + found.page.data, ); return ( [data-card] { + position: relative; +} + +.coder-api-cards > [data-card]:hover { + background-color: color-mix(in oklab, var(--color-fd-accent) 80%, transparent); +} + +.coder-api-cards > [data-card] a { + color: inherit; + text-decoration: none; +} + +.coder-api-cards > [data-card] a::after { + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; +} + +.coder-api-cards > [data-card] a:focus-visible { + outline: none; +} + +.coder-api-cards > [data-card]:has(a:focus-visible) { + outline: 2px solid var(--color-fd-ring); + outline-offset: 2px; +} diff --git a/packages/docs-transforms/src/index.ts b/packages/docs-transforms/src/index.ts index 6b83a184..448accea 100644 --- a/packages/docs-transforms/src/index.ts +++ b/packages/docs-transforms/src/index.ts @@ -24,6 +24,7 @@ export { parseFrontmatter, FrontmatterError, extractTitle, + findHeadings, rewriteTarget, rewriteContent, } from "./transform.js"; diff --git a/packages/docs-transforms/src/transform.test.ts b/packages/docs-transforms/src/transform.test.ts index 0201620d..a11ea508 100644 --- a/packages/docs-transforms/src/transform.test.ts +++ b/packages/docs-transforms/src/transform.test.ts @@ -7,6 +7,7 @@ import { escapeCurlyBraces, extractTitle, findIncludeDirectives, + findHeadings, isIndexFile, lastSeg, normalizeAngleBrackets, @@ -1267,3 +1268,29 @@ test("scanMarkdownNesting stays linear on a long line of container markers", () assert.ok(elapsed(() => scanMarkdownNesting(md)) < LINEAR_BUDGET_MS, md.slice(0, 6)); } }); + +test("findHeadings lists the prose ATX headings with their line, depth and plain text", () => { + assert.deepEqual( + findHeadings( + [ + "# Title", + "", + "```md", + "## In a fence", + "```", + "", + "
", + "## In an HTML block", + "
", + "", + "## Use `coder` with [links](./x.md) ##", + "### Deeper", + ].join("\n"), + ), + [ + { line: 0, depth: 1, text: "Title" }, + { line: 10, depth: 2, text: "Use coder with links" }, + { line: 11, depth: 3, text: "Deeper" }, + ], + ); +}); diff --git a/packages/docs-transforms/src/transform.ts b/packages/docs-transforms/src/transform.ts index 4300462f..da650e54 100644 --- a/packages/docs-transforms/src/transform.ts +++ b/packages/docs-transforms/src/transform.ts @@ -1147,6 +1147,24 @@ export function extractTitle( }; } +/** The prose ATX headings of a Markdown body, with their inline Markdown reduced to the text a slugger sees. */ +export function findHeadings(content: string): { line: number; depth: number; text: string }[] { + const headings: { line: number; depth: number; text: string }[] = []; + mapLines(stripHtmlComments(content).content, (line, info) => { + const match = + info.prose && !info.htmlBlock ? /^(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/.exec(line) : null; + if (match) { + const text = (match[2] as string) + .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/[`*]/g, "") + .trim(); + headings.push({ line: info.index, depth: (match[1] as string).length, text }); + } + return line; + }); + return headings; +} + // Context supplied to rewriteTarget/rewriteContent: image handling and the // resolvers that turn a docs-relative link into an output href. export interface RewriteContext { From 613dbf3b4358cc2383ddd2c1f6d8aac857d49c5e Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 13:04:44 -0400 Subject: [PATCH 12/69] fix(api-reference): name the playground's language select and recolour footer badges With four samples, the playground's code block shows fumadocs-openapi's language select, a combobox with no accessible name, which the axe pass fails as button-name; the code block now names it. The method badge also appears on the previous and next links in the page footer, where its -600 shades fell short of 4.5:1, so the contrast overrides cover the footer too. Assisted-by: AI --- packages/docs-next/src/openapi/api-page.tsx | 7 +++++++ packages/docs-theme/src/brand.css | 7 ++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index d8d6ea0d..c9f3a366 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -38,6 +38,12 @@ const shikiOptions = { themes: { light: "github-light-high-contrast", dark: "github-dark-default" }, } as const; +// The playground's language select (fumadocs-openapi 12.5.4 ExampleSelect) is a combobox with no accessible name. +function nameLanguageSelect(figure: HTMLElement | null) { + for (const select of figure?.querySelectorAll('[role="combobox"]:not([aria-label])') ?? []) + select.setAttribute("aria-label", "Sample language"); +} + // fumadocs-openapi's default code block leaves its scroll region unnamed, so every block on a page is the same landmark. function CodeBlock(props: CodeBlockProps) { return ( @@ -47,6 +53,7 @@ function CodeBlock(props: CodeBlockProps) { {...props} codeblock={{ ...props.codeblock, + ref: nameLanguageSelect, viewportProps: { ...props.codeblock?.viewportProps, "aria-label": `${props.lang} code` }, }} /> diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css index 256877fc..d77c092b 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -677,13 +677,14 @@ samp { transition-property: width, inset-block, transform, translate, background-color, visibility; } -/* fumadocs-openapi's method badges (on API pages, the landing cards and the sidebar) and links are -600/-400 shades that fall short of 4.5:1 (7:1 for More contrast); the playground dialog is portalled out of the page. */ +/* fumadocs-openapi's method badges (on API pages, the landing cards, the sidebar and the page footer) and links are -600/-400 shades that fall short of 4.5:1 (7:1 for More contrast); the playground dialog is portalled out of the page. */ :root:not(.dark) :is( .coder-api-page, .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, + #nd-page > footer, [data-base-ui-portal] > [role="dialog"] ) { --color-green-600: oklch(45% 0.13 150); @@ -699,6 +700,7 @@ samp { .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, + #nd-page > footer, [data-base-ui-portal] > [role="dialog"] ) { --color-green-600: oklch(38% 0.1 150); @@ -714,6 +716,7 @@ samp { .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, + #nd-page > footer, [data-base-ui-portal] > [role="dialog"] ) { --color-green-400: oklch(88% 0.15 150); @@ -730,6 +733,7 @@ samp { .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, + #nd-page > footer, [data-base-ui-portal] > [role="dialog"] ) { --color-green-600: oklch(38% 0.1 150); @@ -745,6 +749,7 @@ samp { .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, + #nd-page > footer, [data-base-ui-portal] > [role="dialog"] ) { --color-green-400: oklch(88% 0.15 150); From faa80fc28dc0d88496c7d8543dddcb20659af26f Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 13:38:50 -0400 Subject: [PATCH 13/69] feat(api-reference): hide the API playground for now Sending a request from the docs needs a proxy or a CORS change on each deployment, and the playground keeps the reader's session token in the browser. Until there is a decision on both, the operation pages show the code samples only, and the axe pass no longer opens the playground. Assisted-by: AI --- apps/docs/scripts/a11y-axe-helpers.mjs | 3 -- apps/docs/scripts/a11y-axe.mjs | 35 ++------------------- apps/docs/scripts/a11y-axe.test.mjs | 14 --------- packages/docs-next/src/openapi/api-page.tsx | 4 ++- 4 files changed, 6 insertions(+), 50 deletions(-) diff --git a/apps/docs/scripts/a11y-axe-helpers.mjs b/apps/docs/scripts/a11y-axe-helpers.mjs index f8e174c0..f302f49c 100644 --- a/apps/docs/scripts/a11y-axe-helpers.mjs +++ b/apps/docs/scripts/a11y-axe-helpers.mjs @@ -36,9 +36,6 @@ export const SEARCH_QUERY = "code"; export const SEARCH_LABEL = `${SEARCH_PAGE}#search`; // The display settings popover, scanned open on the search page. export const SETTINGS_LABEL = `${SEARCH_PAGE}#settings`; -// The API playground dialog, scanned open on an operation page with a request body. -export const PLAYGROUND_PAGE = "/reference/api/users/create-new-user"; -export const PLAYGROUND_LABEL = `${PLAYGROUND_PAGE}#playground`; export const MODES = ["light", "dark"]; export const MOBILE_MODES = MODES.map((mode) => `mobile-${mode}`); // The More contrast setting, held to WCAG AAA contrast. diff --git a/apps/docs/scripts/a11y-axe.mjs b/apps/docs/scripts/a11y-axe.mjs index 1529ed37..33b64a58 100644 --- a/apps/docs/scripts/a11y-axe.mjs +++ b/apps/docs/scripts/a11y-axe.mjs @@ -7,8 +7,6 @@ import { MOBILE_VIEWPORT, MODES, MORE_MODES, - PLAYGROUND_LABEL, - PLAYGROUND_PAGE, SEARCH_LABEL, SEARCH_PAGE, SEARCH_QUERY, @@ -57,22 +55,7 @@ async function openSettings(page) { await settle(page); } -async function openPlayground(page) { - await page.getByRole("button", { name: "Try in Playground" }).click(); - await page.locator('[role="dialog"]').getByRole("button", { name: /^Send/ }).waitFor(); - await settle(page); -} - -async function scan({ - browser, - base, - page: pagePath, - mode, - axeSource, - search, - settings, - playground, -}) { +async function scan({ browser, base, page: pagePath, mode, axeSource, search, settings }) { const scheme = colorSchemeOf(mode); const contrast = contrastOf(mode); const mobile = MOBILE_MODES.includes(mode) @@ -95,20 +78,13 @@ async function scan({ await page.addScriptTag({ content: axeSource }); if (search) await openSearchWithMatch(page); if (settings) await openSettings(page); - if (playground) await openPlayground(page); const results = await page.evaluate( (options) => window.axe.run(document, options), axeOptions(mode), ); return results.violations.map((v) => ({ mode, - page: search - ? SEARCH_LABEL - : settings - ? SETTINGS_LABEL - : playground - ? PLAYGROUND_LABEL - : pagePath, + page: search ? SEARCH_LABEL : settings ? SETTINGS_LABEL : pagePath, rule: v.id, impact: v.impact, help: v.help, @@ -143,11 +119,6 @@ async function main() { search: true, })), ...desktopModes.map((mode) => ({ page: SEARCH_PAGE, mode, settings: true })), - ...[...desktopModes, ...MOBILE_MODES].map((mode) => ({ - page: PLAYGROUND_PAGE, - mode, - playground: true, - })), ]; const found = []; try { @@ -175,7 +146,7 @@ async function main() { } for (const entry of stale) console.log(`stale allowlist entry, remove it: ${entry}`); console.log( - `\n${runs.length} scans (${options.pages.length} pages x ${desktopModes.length} modes, ${mobilePages.length} x ${MOBILE_MODES.length} at ${MOBILE_VIEWPORT.width}px, the open search dialog in all ${desktopModes.length + MOBILE_MODES.length}, the open display settings in ${desktopModes.length}, and the open API playground in ${desktopModes.length + MOBILE_MODES.length}): ` + + `\n${runs.length} scans (${options.pages.length} pages x ${desktopModes.length} modes, ${mobilePages.length} x ${MOBILE_MODES.length} at ${MOBILE_VIEWPORT.width}px, the open search dialog in all ${desktopModes.length + MOBILE_MODES.length}, and the open display settings in ${desktopModes.length}): ` + `${violations.length} WCAG rule violations, ${allowed.length} allowlisted, ${failures.length} new; ` + `${bestPractice.length} best-practice findings (reported, not failing).`, ); diff --git a/apps/docs/scripts/a11y-axe.test.mjs b/apps/docs/scripts/a11y-axe.test.mjs index 0503be7f..6b9b721e 100644 --- a/apps/docs/scripts/a11y-axe.test.mjs +++ b/apps/docs/scripts/a11y-axe.test.mjs @@ -7,8 +7,6 @@ import { DEFAULT_MOBILE_PAGES, DEFAULT_PAGES, MORE_MODES, - PLAYGROUND_LABEL, - PLAYGROUND_PAGE, SEARCH_LABEL, SEARCH_PAGE, SEARCH_QUERY, @@ -160,18 +158,6 @@ test("the search dialog scan names a default page and gets its own allowlist lab assert.equal(failures.length, 1); }); -test("the playground scan opens on a scanned API page and gets its own allowlist label", () => { - assert.ok(DEFAULT_PAGES.includes(PLAYGROUND_PAGE)); - assert.ok(DEFAULT_MOBILE_PAGES.includes(PLAYGROUND_PAGE)); - assert.notEqual(PLAYGROUND_LABEL, PLAYGROUND_PAGE); - const { failures } = applyAllowlist( - [{ mode: "light", page: PLAYGROUND_LABEL, rule: "color-contrast" }], - [`tracked-x axe light ${PLAYGROUND_PAGE} color-contrast`], - DEFAULT_PAGES, - ); - assert.equal(failures.length, 1); -}); - test("More contrast modes scan both color schemes with the AAA contrast rule enabled", () => { assert.deepEqual(MORE_MODES, ["more-light", "more-dark"]); assert.deepEqual(MORE_MODES.map(colorSchemeOf), ["light", "dark"]); diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index c9f3a366..ec21f16c 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -83,11 +83,13 @@ function SampleTabs() { ); } -/** One REST API operation, rendered by fumadocs-openapi from the document its page was given, with the server-built code samples and the playground. */ +/** One REST API operation, rendered by fumadocs-openapi from the document its page was given, with the server-built code samples. */ export const ApiPage = createOpenAPIPageBase({ shiki, shikiOptions, components: { CodeBlock }, + // Off until there is a decision on sending requests and holding the reader's token. + playground: { enabled: false }, // Empty, or fumadocs-openapi adds its own generators beside the operation's x-codeSamples. codeUsages: createCodeUsageGeneratorRegistry(), storageKeyPrefix: "coder-api-", From 6f04ff78b7b0bef9a07f9e807a45159f5b633242 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 13:43:31 -0400 Subject: [PATCH 14/69] fix(api-reference): stop a bad stored server URL from crashing operation pages fumadocs-openapi restores the reader's server URL from localStorage on every operation page, playground or not, and builds a URL from it with `new URL()`. A saved value such as " http://localhost:3142." made that throw from the code samples' `useCodeUsage`, and every operation page fell to the error boundary until the reader cleared storage. The sample tabs now show the server-built x-codeSamples text directly, since it never depended on the server, and the page trims the stored value before fumadocs-openapi reads it, removing it when it is still not an absolute HTTP(S) URL so the document's default server applies. Assisted-by: AI --- .../docs-next/src/openapi/api-page.test.tsx | 89 +++++++++++++++++++ packages/docs-next/src/openapi/api-page.tsx | 44 ++++++--- .../src/openapi/stored-server.test.ts | 48 ++++++++++ .../docs-next/src/openapi/stored-server.ts | 43 +++++++++ 4 files changed, 210 insertions(+), 14 deletions(-) create mode 100644 packages/docs-next/src/openapi/api-page.test.tsx create mode 100644 packages/docs-next/src/openapi/stored-server.test.ts create mode 100644 packages/docs-next/src/openapi/stored-server.ts diff --git a/packages/docs-next/src/openapi/api-page.test.tsx b/packages/docs-next/src/openapi/api-page.test.tsx new file mode 100644 index 00000000..1cd6ce1e --- /dev/null +++ b/packages/docs-next/src/openapi/api-page.test.tsx @@ -0,0 +1,89 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { FrameworkProvider } from "fumadocs-core/framework"; +import type { Document } from "fumadocs-openapi"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { ApiPage } from "./api-page.js"; +import { withCodeSamples } from "./code-samples.js"; + +const STORED_SERVER = "coder-api-server-url"; + +const document_ = withCodeSamples( + { + openapi: "3.0.3", + info: { title: "Coder API", version: "2.0" }, + servers: [ + { + url: "{deployment}", + variables: { deployment: { default: "https://coder.example.com" } }, + }, + ], + paths: { + "/api/v2/buildinfo": { + get: { summary: "Build info", responses: { "200": { description: "OK" } } }, + }, + }, + components: {}, + }, + "/api/v2/buildinfo", + "get", +); + +async function renderPage(): Promise<{ container: HTMLElement; unmount: () => Promise }> { + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + await act(async () => + root.render( + "/"} + useParams={() => ({})} + useRouter={() => ({ push() {}, refresh() {} })} + > + + , + ), + ); + await act(async () => new Promise((resolve) => setTimeout(resolve, 50))); + return { + container, + unmount: async () => { + await act(async () => root.unmount()); + container.remove(); + }, + }; +} + +for (const [label, deployment] of [ + ["a leading space and a trailing dot", " http://localhost:3142."], + ["not a URL at all", "not a url"], +] as const) { + test(`a stored server URL that is ${label} still renders the samples`, async () => { + localStorage.setItem( + STORED_SERVER, + JSON.stringify({ url: "{deployment}", variables: { deployment } }), + ); + const errors: unknown[] = []; + const onError = (event: ErrorEvent) => errors.push(event.error); + window.addEventListener("error", onError); + try { + const { container, unmount } = await renderPage(); + assert.deepEqual(errors, []); + const tabs = [...container.querySelectorAll('[role="tab"]')].map((tab) => tab.textContent); + for (const name of ["cURL", "JavaScript", "Python", "Go"]) + assert.ok(tabs.includes(name), name); + assert.equal(localStorage.getItem(STORED_SERVER), null, "the bad value is dropped"); + assert.match(container.textContent ?? "", /curl -X GET "\$CODER_URL\/api\/v2\/buildinfo"/); + await unmount(); + } finally { + window.removeEventListener("error", onError); + localStorage.clear(); + } + }); +} diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index ec21f16c..5737db0e 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -2,12 +2,14 @@ import { createShikiFactory } from "fumadocs-core/highlight/shiki"; import type { CodeBlockProps } from "fumadocs-openapi"; -import { useCodeUsage, useOperation } from "fumadocs-openapi/operation"; +import { useOperation } from "fumadocs-openapi/operation"; import { createCodeUsageGeneratorRegistry } from "fumadocs-openapi/requests/generators"; import { createOpenAPIPageBase } from "fumadocs-openapi/ui/base"; import { DynamicCodeBlock } from "fumadocs-ui/components/dynamic-codeblock.core"; import { Tab, Tabs } from "fumadocs-ui/components/tabs"; +import { type ComponentProps, useState } from "react"; import { SamplesNote } from "./samples-note.js"; +import { repairStoredServer } from "./stored-server.js"; // Only the grammars and themes an API page uses (JSON, the code samples, TypeScript definitions), on the JavaScript regex engine (no WASM, no eval). const shiki = createShikiFactory({ @@ -60,31 +62,36 @@ function CodeBlock(props: CodeBlockProps) { ); } -function SampleCode({ id, lang }: { id: string; lang: string }) { - return ; -} - // One tab per language, where fumadocs-openapi's default is a select in the code block's header. +// The samples are the server-built text as is, never run through fumadocs-openapi's generators, which resolve the reader's stored server URL. function SampleTabs() { - const samples = Array.from(useOperation().codeUsages.map(), ([id, sample]) => ({ - id, - lang: sample.lang, - label: sample.label ?? sample.lang, - })); + const samples = (useOperation().operation["x-codeSamples"] ?? []).flatMap((sample) => + typeof sample.source === "string" + ? [ + { + id: sample.id ?? sample.lang, + lang: sample.lang, + label: sample.label ?? sample.lang, + source: sample.source, + }, + ] + : [], + ); if (samples.length === 0) return null; return ( sample.label)} className="mb-4"> {samples.map((sample) => ( - + ))} ); } -/** One REST API operation, rendered by fumadocs-openapi from the document its page was given, with the server-built code samples. */ -export const ApiPage = createOpenAPIPageBase({ +const STORAGE_KEY_PREFIX = "coder-api-"; + +const OpenApiPage = createOpenAPIPageBase({ shiki, shikiOptions, components: { CodeBlock }, @@ -92,7 +99,7 @@ export const ApiPage = createOpenAPIPageBase({ playground: { enabled: false }, // Empty, or fumadocs-openapi adds its own generators beside the operation's x-codeSamples. codeUsages: createCodeUsageGeneratorRegistry(), - storageKeyPrefix: "coder-api-", + storageKeyPrefix: STORAGE_KEY_PREFIX, content: { renderAPIExampleUsageTabs: () => , renderAPIExampleLayout: ({ selector, usageTabs, responseTabs }) => ( @@ -105,3 +112,12 @@ export const ApiPage = createOpenAPIPageBase({ ), }, }); + +/** One REST API operation, rendered by fumadocs-openapi from the document its page was given, with the server-built code samples. */ +export function ApiPage(props: ComponentProps) { + // Before fumadocs-openapi's server store restores the value, in an effect of a child. + useState(() => { + if (typeof window !== "undefined") repairStoredServer(`${STORAGE_KEY_PREFIX}server-url`); + }); + return ; +} diff --git a/packages/docs-next/src/openapi/stored-server.test.ts b/packages/docs-next/src/openapi/stored-server.test.ts new file mode 100644 index 00000000..772604d6 --- /dev/null +++ b/packages/docs-next/src/openapi/stored-server.test.ts @@ -0,0 +1,48 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { repairStoredServer } from "./stored-server.js"; + +const KEY = "coder-api-server-url"; +const stored = (deployment: unknown, url = "{deployment}") => + JSON.stringify({ url, variables: { deployment } }); + +test.afterEach(() => localStorage.clear()); + +test("a valid stored server is left as it is", () => { + localStorage.setItem(KEY, stored("https://coder.example.com")); + repairStoredServer(KEY); + assert.equal(localStorage.getItem(KEY), stored("https://coder.example.com")); +}); + +test("surrounding white space is trimmed off a value that is otherwise valid", () => { + localStorage.setItem(KEY, stored(" https://coder.example.com\n")); + repairStoredServer(KEY); + assert.equal(localStorage.getItem(KEY), stored("https://coder.example.com")); +}); + +for (const [label, value] of [ + ["a trailing dot after the port", " http://localhost:3142."], + ["a relative URL", "not a url"], + ["a non-HTTP scheme", "javascript:alert(1)"], + ["empty", ""], + ["not a string", 42], +] as const) { + test(`a stored server that is ${label} is dropped, so the page falls back to the default`, () => { + localStorage.setItem(KEY, stored(value)); + repairStoredServer(KEY); + assert.equal(localStorage.getItem(KEY), null); + }); +} + +test("a stored value that is not the shape fumadocs-openapi writes is dropped", () => { + for (const value of ["{", "[]", JSON.stringify({ url: 1 }), JSON.stringify({ url: "x" })]) { + localStorage.setItem(KEY, value); + repairStoredServer(KEY); + assert.equal(localStorage.getItem(KEY), null, value); + } +}); + +test("nothing stored stays nothing", () => { + repairStoredServer(KEY); + assert.equal(localStorage.getItem(KEY), null); +}); diff --git a/packages/docs-next/src/openapi/stored-server.ts b/packages/docs-next/src/openapi/stored-server.ts new file mode 100644 index 00000000..f925940c --- /dev/null +++ b/packages/docs-next/src/openapi/stored-server.ts @@ -0,0 +1,43 @@ +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +function repaired(raw: string): string | undefined { + let value: unknown; + try { + value = JSON.parse(raw); + } catch { + return undefined; + } + if (!isRecord(value) || typeof value.url !== "string" || !isRecord(value.variables)) + return undefined; + const variables: Record = {}; + let url = value.url; + for (const [key, variable] of Object.entries(value.variables)) { + if (typeof variable !== "string") return undefined; + variables[key] = variable.trim(); + url = url.replaceAll(`{${key}}`, variables[key]); + } + const parsed = URL.canParse(url) ? new URL(url) : undefined; + if (parsed?.protocol !== "http:" && parsed?.protocol !== "https:") return undefined; + return JSON.stringify({ ...value, variables }); +} + +/** + * Trims the server URL fumadocs-openapi keeps in `localStorage`, and removes + * it when it is still not an absolute HTTP(S) URL, so the page falls back to + * the document's default server instead of throwing from `new URL()`. + */ +export function repairStoredServer(storageKey: string): void { + let raw: string | null; + try { + raw = localStorage.getItem(storageKey); + } catch { + return; + } + if (raw === null) return; + const next = repaired(raw); + try { + if (next === undefined) localStorage.removeItem(storageKey); + else if (next !== raw) localStorage.setItem(storageKey, next); + } catch {} +} From b928dd2dd4a0de4830f1769d9d97027dad686627 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 14:29:38 -0400 Subject: [PATCH 15/69] fix(api-reference): keep curl's @file argument out of the version-segment scan The version-segment scan reads a template literal starting `@${` as a hand-built version segment, and the curl sample's `--data-binary "@{file}"` was written that way. It is curl's read-from-file syntax, not a version, so the argument is now built without that template shape; the command it produces is unchanged, as the curl test pins. Assisted-by: AI --- packages/docs-next/src/openapi/code-samples.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/docs-next/src/openapi/code-samples.ts b/packages/docs-next/src/openapi/code-samples.ts index fa7560ba..260fb344 100644 --- a/packages/docs-next/src/openapi/code-samples.ts +++ b/packages/docs-next/src/openapi/code-samples.ts @@ -184,7 +184,7 @@ export function curlSample(request: ExampleRequest): string { lines.push(`-F ${shellDoubleQuoted(`${name}=${placeholder(name)}`)}`); } if (body?.kind === "binary") - lines.push(`--data-binary ${shellDoubleQuoted(`@${placeholder("file")}`)}`); + lines.push(`--data-binary ${shellDoubleQuoted("@".concat(placeholder("file")))}`); return lines.join(" \\\n "); } From 297dbdb6c41d31b78fdf1d4db844cd927a879977 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 14:38:18 -0400 Subject: [PATCH 16/69] fix(api-reference): trim the landing page's end without a backtracking regex CodeQL flagged the `/\n*$/` that stripped the landing page's trailing newlines before the setup section is appended: on input with many newlines it backtracks polynomially. `trimEnd()` does the same job in linear time and also drops trailing lines of only spaces, so the section always follows the page's last text with one blank line. Assisted-by: AI --- packages/docs-build/src/openapi-reference.test.ts | 8 ++++++++ packages/docs-build/src/openapi-reference.ts | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index 6d84c307..1cc5dec1 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -184,3 +184,11 @@ test("section ids never repeat a heading the landing page already has", async () assert.equal(reference.landing.sections[0]?.id, "users-1"); assert.equal(reference.landing.sections[1]?.id, "workspaces"); }); + +test("the appended setup section follows the page's text, not its trailing blank lines", async () => { + const { source: out } = await applyOpenApiReference( + withLanding(`# REST API\n\nIntro.\n\n\n \n`), + swagger, + ); + assert.match(landingPage(out), /Intro\.\n\n## Set up your environment\n/); +}); diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index d0e361d5..a79a7e6d 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -435,7 +435,7 @@ function withSetupSection(content: string): { setupId ??= slugger.slug(SETUP_HEADING); const next = at === undefined - ? `${content.replace(/\n*$/, "")}\n\n${SETUP_SECTION}` + ? `${content.trimEnd()}\n\n${SETUP_SECTION}` : [...lines.slice(0, at), SETUP_SECTION, ...lines.slice(at)].join("\n"); return { content: next, setupId, slugger }; } From 52aced84d0f519cf219bc5ade06f5af89b82b6d3 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 14:39:15 -0400 Subject: [PATCH 17/69] refactor(api-reference): move the sync's Swagger reading and reference output into packages The offline-docs builder kit ships apps/offlinedocs on its own, with only the published @coder packages and a fixed list of vendored scripts, so offlinedocs importing apps/docs/scripts/openapi-source.mjs broke the kit's build with a missing module. Reading the Swagger document from a docs tree or a clone now lives in @coder/docs-sources, beside the tree and git readers it is built on, and writing the reference data the page renderer reads lives in @coder/docs-build, beside applyOpenApiReference. Both sync scripts import them from there, and the app script and its test are gone. Assisted-by: AI --- apps/docs/scripts/openapi-source.mjs | 94 ------------------- apps/docs/scripts/sync-docs.mjs | 22 +++-- apps/offlinedocs/scripts/sync-docs.mjs | 14 ++- packages/docs-build/src/index.ts | 6 ++ .../docs-build/src/openapi-output.test.ts | 70 ++++++++++++++ packages/docs-build/src/openapi-output.ts | 57 +++++++++++ packages/docs-sources/src/index.ts | 1 + .../docs-sources/src/swagger.test.ts | 21 ++++- packages/docs-sources/src/swagger.ts | 55 +++++++++++ 9 files changed, 229 insertions(+), 111 deletions(-) delete mode 100644 apps/docs/scripts/openapi-source.mjs create mode 100644 packages/docs-build/src/openapi-output.test.ts create mode 100644 packages/docs-build/src/openapi-output.ts rename apps/docs/scripts/openapi-source.test.mjs => packages/docs-sources/src/swagger.test.ts (66%) create mode 100644 packages/docs-sources/src/swagger.ts diff --git a/apps/docs/scripts/openapi-source.mjs b/apps/docs/scripts/openapi-source.mjs deleted file mode 100644 index cf43d07c..00000000 --- a/apps/docs/scripts/openapi-source.mjs +++ /dev/null @@ -1,94 +0,0 @@ -// Where a version's Swagger document comes from, and where the sync leaves the -// generated API reference data for the page renderer. -import { execFile } from "node:child_process"; -import { mkdir, rm, writeFile } from "node:fs/promises"; -import path from "node:path"; -import { promisify } from "node:util"; -import { applyOpenApiReference } from "@coder/docs-build"; -import { DEFAULT_MAX_FILE_BYTES, readContainedFile } from "@coder/docs-sources"; - -const execFileAsync = promisify(execFile); -export const SWAGGER_PATH = "coderd/apidoc/swagger.json"; - -export const openApiDir = (appDir) => path.join(appDir, ".generated", "openapi"); - -function parseSwagger(text, where) { - try { - return JSON.parse(text); - } catch { - throw new Error(`${SWAGGER_PATH} at ${where} is not valid JSON`); - } -} - -/** - * The Swagger document of the checkout a `docs/` tree sits in, or undefined - * when there is none. Read with the docs tree's own guarantees: no symbolic - * links, a regular file under the per-file cap, inside the checkout. - */ -export async function swaggerFromTree(docsRoot) { - const checkout = path.dirname(path.resolve(docsRoot)); - const text = await readContainedFile(checkout, SWAGGER_PATH, DEFAULT_MAX_FILE_BYTES); - return text === undefined ? undefined : parseSwagger(text, checkout); -} - -/** The Swagger document at a ref of the sync's cached clone, or undefined when the ref has none. */ -export async function swaggerFromClone(cacheDir, ref) { - for (const rev of [`refs/remotes/origin/${ref}`, `refs/tags/${ref}`, ref]) { - let stdout; - try { - // A blob over the cap fails the read rather than being buffered. - ({ stdout } = await execFileAsync("git", ["-C", cacheDir, "show", `${rev}:${SWAGGER_PATH}`], { - maxBuffer: DEFAULT_MAX_FILE_BYTES, - })); - } catch (error) { - if (error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") { - throw new Error( - `${SWAGGER_PATH} at ${ref} is over the ${DEFAULT_MAX_FILE_BYTES}-byte limit`, - ); - } - continue; - } - return parseSwagger(stdout, ref); - } - return undefined; -} - -/** Which versions render the generated reference: the mainline only, unless DOCS_OPENAPI_VERSIONS=all. */ -export function rendersOpenApi(version, env = process.env) { - if (env.DOCS_OPENAPI === "0") return false; - return env.DOCS_OPENAPI_VERSIONS === "all" || version.latest === true; -} - -export async function clearOpenApi(appDir) { - await rm(openApiDir(appDir), { recursive: true, force: true }); -} - -/** - * Swap the version's Markdown API reference for one page per operation and - * write the data the renderer needs. Returns the source unchanged when there - * is no Swagger document. - */ -export async function withOpenApiReference(appDir, version, source, swagger) { - if (!swagger) { - console.warn(`[sync] ${version.id}: no ${SWAGGER_PATH}; keeping the Markdown API reference`); - return source; - } - const started = Date.now(); - const { source: next, reference } = await applyOpenApiReference(source, swagger); - await mkdir(openApiDir(appDir), { recursive: true }); - await writeFile( - path.join(openApiDir(appDir), `${version.id}.json`), - JSON.stringify({ - document: reference.document, - operations: reference.operations, - anchors: reference.anchors, - landing: reference.landing, - }), - ); - console.log( - `[sync] ${version.id}: API reference from ${SWAGGER_PATH}, ${Object.keys(reference.operations).length} operation pages in ${Date.now() - started} ms`, - ); - for (const warning of reference.warnings) - console.warn(`[sync] ${version.id}: openapi: ${warning}`); - return next; -} diff --git a/apps/docs/scripts/sync-docs.mjs b/apps/docs/scripts/sync-docs.mjs index 804a0c99..bc8decfa 100644 --- a/apps/docs/scripts/sync-docs.mjs +++ b/apps/docs/scripts/sync-docs.mjs @@ -13,10 +13,21 @@ import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; -import { syncDocSource, writeReleaseSchedule } from "@coder/docs-build"; +import { + clearOpenApi, + rendersOpenApi, + syncDocSource, + withOpenApiReference, + writeReleaseSchedule, +} from "@coder/docs-build"; import { parseReleaseSchedule, resolveVersionPipeline } from "@coder/docs-config"; import { versionBaseUrl } from "@coder/docs-next/version-routing"; -import { createGitRefsProvider, createLocalTreeProvider } from "@coder/docs-sources"; +import { + createGitRefsProvider, + createLocalTreeProvider, + swaggerFromClone, + swaggerFromTree, +} from "@coder/docs-sources"; import { versions } from "../lib/versions.ts"; import { assertPublishInputs, singleVersionFromEnv } from "./single-version.mjs"; import { @@ -31,13 +42,6 @@ import { releaseSchedulePath, slugManifestPath, } from "./sync-helpers.mjs"; -import { - clearOpenApi, - rendersOpenApi, - swaggerFromClone, - swaggerFromTree, - withOpenApiReference, -} from "./openapi-source.mjs"; import { readVersionRedirects } from "./version-redirects.mjs"; const execFileAsync = promisify(execFile); diff --git a/apps/offlinedocs/scripts/sync-docs.mjs b/apps/offlinedocs/scripts/sync-docs.mjs index 701fce27..cf864792 100644 --- a/apps/offlinedocs/scripts/sync-docs.mjs +++ b/apps/offlinedocs/scripts/sync-docs.mjs @@ -14,15 +14,19 @@ import { cp, mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { syncDocSource, writeReleaseSchedule } from "@coder/docs-build"; -import { parseReleaseSchedule } from "@coder/docs-config"; -import { createGitRefsProvider, createLocalTreeProvider } from "@coder/docs-sources"; import { clearOpenApi, + syncDocSource, + withOpenApiReference, + writeReleaseSchedule, +} from "@coder/docs-build"; +import { parseReleaseSchedule } from "@coder/docs-config"; +import { + createGitRefsProvider, + createLocalTreeProvider, swaggerFromClone, swaggerFromTree, - withOpenApiReference, -} from "../../docs/scripts/openapi-source.mjs"; +} from "@coder/docs-sources"; import { assertDeployHasCorpus, exportVersionFromEnv, diff --git a/packages/docs-build/src/index.ts b/packages/docs-build/src/index.ts index d67e4b60..f9175073 100644 --- a/packages/docs-build/src/index.ts +++ b/packages/docs-build/src/index.ts @@ -10,6 +10,12 @@ export { reservedRouteReason, } from "./reserved-routes.js"; export { applyOpenApiReference, convertSwagger, tagSlug } from "./openapi-reference.js"; +export { + clearOpenApi, + openApiDataDir, + rendersOpenApi, + withOpenApiReference, +} from "./openapi-output.js"; export type { ApplyOpenApiReferenceOptions, OpenApiOperationRef, diff --git a/packages/docs-build/src/openapi-output.test.ts b/packages/docs-build/src/openapi-output.test.ts new file mode 100644 index 00000000..1e7c2061 --- /dev/null +++ b/packages/docs-build/src/openapi-output.test.ts @@ -0,0 +1,70 @@ +import assert from "node:assert/strict"; +import { mkdtemp, readFile, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import type { DocSource } from "@coder/docs-config"; +import { + clearOpenApi, + openApiDataDir, + rendersOpenApi, + withOpenApiReference, +} from "./openapi-output.js"; + +const swagger = JSON.parse( + await readFile( + new URL("../../../apps/docs/fixtures/openapi/swagger.json", import.meta.url), + "utf8", + ), +); + +const source: DocSource = { + files: [ + { path: "reference/api/index.md", content: "# REST API\n" }, + { path: "reference/api/users.md", content: "# Users\n" }, + { path: "reference/api/workspaces.md", content: "# Workspaces\n" }, + { path: "reference/api/schemas.md", content: "# Schemas\n" }, + ], + images: [], + manifest: { + versions: ["main"], + routes: [ + { + title: "REST API", + path: "./reference/api/index.md", + children: [ + { title: "Users", path: "./reference/api/users.md" }, + { title: "Workspaces", path: "./reference/api/workspaces.md" }, + { title: "Schemas", path: "./reference/api/schemas.md" }, + ], + }, + ], + }, +}; + +const quiet = { log() {}, warn() {} }; + +test("only the mainline renders the reference, unless every version is asked for or it is off", () => { + assert.equal(rendersOpenApi({ id: "2.38", latest: true }, {}), true); + assert.equal(rendersOpenApi({ id: "2.37" }, {}), false); + assert.equal(rendersOpenApi({ id: "2.37" }, { DOCS_OPENAPI_VERSIONS: "all" }), true); + assert.equal(rendersOpenApi({ id: "2.38", latest: true }, { DOCS_OPENAPI: "0" }), false); +}); + +test("the version's reference data is written where the page renderer reads it", async () => { + const appDir = await mkdtemp(path.join(tmpdir(), "openapi-output-")); + const next = await withOpenApiReference(appDir, { id: "2.38" }, source, swagger, quiet); + assert.ok(next.files.some((file) => file.path === "reference/api/users/create-new-user.md")); + const data = JSON.parse(await readFile(path.join(openApiDataDir(appDir), "2.38.json"), "utf8")); + assert.deepEqual(Object.keys(data).sort(), ["anchors", "document", "landing", "operations"]); + assert.equal(data.landing.route, "reference/api"); + await clearOpenApi(appDir); + await assert.rejects(stat(openApiDataDir(appDir)), { code: "ENOENT" }); +}); + +test("a version without a Swagger document keeps its Markdown reference and writes nothing", async () => { + const appDir = await mkdtemp(path.join(tmpdir(), "openapi-output-")); + const next = await withOpenApiReference(appDir, { id: "2.10" }, source, undefined, quiet); + assert.equal(next, source); + await assert.rejects(stat(openApiDataDir(appDir)), { code: "ENOENT" }); +}); diff --git a/packages/docs-build/src/openapi-output.ts b/packages/docs-build/src/openapi-output.ts new file mode 100644 index 00000000..89ad29a2 --- /dev/null +++ b/packages/docs-build/src/openapi-output.ts @@ -0,0 +1,57 @@ +import { mkdir, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import type { DocSource } from "@coder/docs-config"; +import { applyOpenApiReference } from "./openapi-reference.js"; + +/** Where a sync leaves each version's REST API reference data, which the page renderer reads. */ +export const openApiDataDir = (appDir: string): string => + path.join(appDir, ".generated", "openapi"); + +/** Which versions render the generated reference: the mainline only, unless DOCS_OPENAPI_VERSIONS=all. */ +export function rendersOpenApi( + version: { latest?: boolean }, + env: Record = process.env, +): boolean { + if (env.DOCS_OPENAPI === "0") return false; + return env.DOCS_OPENAPI_VERSIONS === "all" || version.latest === true; +} + +export async function clearOpenApi(appDir: string): Promise { + await rm(openApiDataDir(appDir), { recursive: true, force: true }); +} + +/** + * Swaps the version's Markdown API reference for one page per operation and + * writes the data the renderer needs. Returns the source unchanged when there + * is no Swagger document. + */ +export async function withOpenApiReference( + appDir: string, + version: { id: string }, + source: DocSource, + swagger: unknown, + logger: Pick = console, +): Promise { + if (swagger === undefined) { + logger.warn(`[sync] ${version.id}: no Swagger document; keeping the Markdown API reference`); + return source; + } + const started = Date.now(); + const { source: next, reference } = await applyOpenApiReference(source, swagger); + await mkdir(openApiDataDir(appDir), { recursive: true }); + await writeFile( + path.join(openApiDataDir(appDir), `${version.id}.json`), + JSON.stringify({ + document: reference.document, + operations: reference.operations, + anchors: reference.anchors, + landing: reference.landing, + }), + ); + logger.log( + `[sync] ${version.id}: API reference, ${Object.keys(reference.operations).length} operation pages in ${Date.now() - started} ms`, + ); + for (const warning of reference.warnings) + logger.warn(`[sync] ${version.id}: openapi: ${warning}`); + return next; +} diff --git a/packages/docs-sources/src/index.ts b/packages/docs-sources/src/index.ts index 7f388be3..28fe8fa8 100644 --- a/packages/docs-sources/src/index.ts +++ b/packages/docs-sources/src/index.ts @@ -22,3 +22,4 @@ export { } from "./git-refs.js"; export { readGitLastModified } from "./last-modified.js"; export { readContainedFile } from "./contained-file.js"; +export { SWAGGER_PATH, swaggerFromClone, swaggerFromTree } from "./swagger.js"; diff --git a/apps/docs/scripts/openapi-source.test.mjs b/packages/docs-sources/src/swagger.test.ts similarity index 66% rename from apps/docs/scripts/openapi-source.test.mjs rename to packages/docs-sources/src/swagger.test.ts index 37f7c877..3322c42c 100644 --- a/apps/docs/scripts/openapi-source.test.mjs +++ b/packages/docs-sources/src/swagger.test.ts @@ -1,9 +1,10 @@ import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; import { mkdir, mkdtemp, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { test } from "node:test"; -import { swaggerFromTree } from "./openapi-source.mjs"; +import { swaggerFromClone, swaggerFromTree } from "./swagger.js"; async function checkout() { const root = await mkdtemp(path.join(tmpdir(), "openapi-source-")); @@ -26,7 +27,7 @@ test("a symlinked swagger.json is rejected and its target never surfaces", async path.join(outside, "secret.json"), path.join(root, "coderd", "apidoc", "swagger.json"), ); - await assert.rejects(swaggerFromTree(path.join(root, "docs")), (error) => { + await assert.rejects(swaggerFromTree(path.join(root, "docs")), (error: Error) => { assert.match(error.message, /symbolic link/); assert.doesNotMatch(error.message, /do-not-leak/); return true; @@ -36,9 +37,23 @@ test("a symlinked swagger.json is rejected and its target never surfaces", async test("invalid JSON is reported without the file's content", async () => { const root = await checkout(); await writeFile(path.join(root, "coderd", "apidoc", "swagger.json"), "not json do-not-leak"); - await assert.rejects(swaggerFromTree(path.join(root, "docs")), (error) => { + await assert.rejects(swaggerFromTree(path.join(root, "docs")), (error: Error) => { assert.match(error.message, /is not valid JSON/); assert.doesNotMatch(error.message, /do-not-leak/); return true; }); }); + +test("reads the Swagger document at a ref of a clone, and nothing at a ref without one", async () => { + const root = await checkout(); + await writeFile(path.join(root, "coderd", "apidoc", "swagger.json"), '{"swagger":"2.0"}'); + const git = (...args: string[]) => + execFileSync("git", ["-C", root, "-c", "user.name=t", "-c", "user.email=t@t", ...args]); + git("init", "-q", "-b", "main"); + git("add", "-A"); + git("commit", "-q", "-m", "swagger"); + git("tag", "v1"); + assert.deepEqual(await swaggerFromClone(root, "main"), { swagger: "2.0" }); + assert.deepEqual(await swaggerFromClone(root, "v1"), { swagger: "2.0" }); + assert.equal(await swaggerFromClone(root, "no-such-ref"), undefined); +}); diff --git a/packages/docs-sources/src/swagger.ts b/packages/docs-sources/src/swagger.ts new file mode 100644 index 00000000..70aa6b26 --- /dev/null +++ b/packages/docs-sources/src/swagger.ts @@ -0,0 +1,55 @@ +import { execFile } from "node:child_process"; +import path from "node:path"; +import { promisify } from "node:util"; +import { readContainedFile } from "./contained-file.js"; +import { DEFAULT_MAX_FILE_BYTES } from "./read-tree.js"; + +const execFileAsync = promisify(execFile); + +/** Where coder/coder keeps the Swagger 2.0 document the REST API reference is built from. */ +export const SWAGGER_PATH = "coderd/apidoc/swagger.json"; + +function parseSwagger(text: string, where: string): unknown { + try { + return JSON.parse(text); + } catch { + throw new Error(`${SWAGGER_PATH} at ${where} is not valid JSON`); + } +} + +/** + * The Swagger document of the checkout a `docs/` tree sits in, or undefined + * when there is none. Read with the docs tree's own guarantees: no symbolic + * links, a regular file under the per-file cap, inside the checkout. + */ +export async function swaggerFromTree(docsRoot: string): Promise { + const checkout = path.dirname(path.resolve(docsRoot)); + const text = await readContainedFile(checkout, SWAGGER_PATH, DEFAULT_MAX_FILE_BYTES); + return text === undefined ? undefined : parseSwagger(text, checkout); +} + +/** The Swagger document at a ref of a git clone, or undefined when the ref has none. */ +export async function swaggerFromClone(cacheDir: string, ref: string): Promise { + for (const rev of [`refs/remotes/origin/${ref}`, `refs/tags/${ref}`, ref]) { + let stdout: string; + try { + // A blob over the cap fails the read rather than being buffered. + ({ stdout } = await execFileAsync("git", ["-C", cacheDir, "show", `${rev}:${SWAGGER_PATH}`], { + maxBuffer: DEFAULT_MAX_FILE_BYTES, + })); + } catch (error) { + if ( + error instanceof Error && + "code" in error && + error.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" + ) { + throw new Error( + `${SWAGGER_PATH} at ${ref} is over the ${DEFAULT_MAX_FILE_BYTES}-byte limit`, + ); + } + continue; + } + return parseSwagger(stdout, ref); + } + return undefined; +} From 3ee6ec3c7a9a4247195cf904a370b5dcb7e9af36 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 15:16:40 -0400 Subject: [PATCH 18/69] fix(api-reference): fold an older Swagger document's basePath into its paths Releases up to about 2.29 declare `basePath: /api/v2` and paths without it, where newer ones put `/api/v2` in every path. The converter turned the base path into a server URL that the reference then replaces with the reader's deployment, so those versions' pages and code samples named `/users/{user}` instead of `/api/v2/users/{user}`. The base path is now prefixed onto each path before conversion, so every version's operations read the same way. Assisted-by: AI --- .../docs-build/src/openapi-reference.test.ts | 14 ++++++++++++++ packages/docs-build/src/openapi-reference.ts | 17 ++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index 1cc5dec1..6ec59dac 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -192,3 +192,17 @@ test("the appended setup section follows the page's text, not its trailing blank ); assert.match(landingPage(out), /Intro\.\n\n## Set up your environment\n/); }); + +test("an older document's basePath is folded into its paths, as newer documents write them", async () => { + const old = structuredClone(swagger); + old.basePath = "/api/v2"; + old.paths = Object.fromEntries( + Object.entries(old.paths).map(([route, item]) => [route.replace(/^\/api\/v2/, ""), item]), + ); + const { reference } = await applyOpenApiReference(source, old); + assert.deepEqual(reference.operations["reference/api/users/get-user-by-name"], { + method: "get", + path: "/api/v2/users/{user}", + }); + assert.ok(Object.keys(reference.document.paths as object).every((p) => p.startsWith("/api/v2/"))); +}); diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index a79a7e6d..afeb7200 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -107,13 +107,28 @@ function schemaDepths(roots: unknown, schemas: Json): Map { return depths; } +/** Older coder/coder documents give `/api/v2` as `basePath`; the samples and pages need it in each path. */ +function withBasePathInPaths(swagger: unknown): unknown { + if (!isObject(swagger) || typeof swagger.basePath !== "string" || !isObject(swagger.paths)) { + return swagger; + } + const base = swagger.basePath.replace(/\/+$/, ""); + const { basePath: _, ...rest } = swagger; + return { + ...rest, + paths: Object.fromEntries( + Object.entries(swagger.paths).map(([route, item]) => [`${base}${route}`, item]), + ), + }; +} + /** Converts Swagger 2.0 to OpenAPI 3, repairs the defects that make it invalid, and validates it. */ export async function convertSwagger( swagger: unknown, ): Promise<{ document: Json; warnings: string[] }> { const warnings: string[] = []; assertInDocumentRefs(swagger, "swagger.json"); - const converted = await convertObj(swagger, { + const converted = await convertObj(withBasePathInPaths(swagger), { patch: true, warnOnly: true, resolve: false, From 9273ff94bba7028483b2041b6447eb876d0fde11 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 15:16:40 -0400 Subject: [PATCH 19/69] feat(api-reference): render the generated reference for main and every version from 2.24 Only the mainline rendered the per-operation reference, so readers of stable, security, ESR and main pages still got the old single-page Markdown. Every Swagger document from 2.24 on converts cleanly, and 2.23 and older fail on duplicate operation ids, so the reference now renders for main and for every line and tag on 2.24 or newer, a future line included, and older versions keep Markdown. The floor is OPENAPI_MIN_LINE in @coder/docs-build, compared through a new isLineAtLeast helper in @coder/docs-manifest's version-segment module. DOCS_OPENAPI=0 still turns the reference off. DOCS_OPENAPI_VERSIONS=all is gone: it could only add versions that fail the conversion and break the sync. The fixture corpus uses 0.2 as its floor, so its 0.2 and main render the reference and its 0.1 keeps Markdown, and the offline export follows the same rule for the version it builds. Assisted-by: AI --- apps/docs/scripts/sync-docs.mjs | 7 ++++++- apps/offlinedocs/scripts/sync-docs.mjs | 3 ++- packages/docs-build/package.json | 1 + packages/docs-build/src/index.ts | 1 + .../docs-build/src/openapi-output.test.ts | 21 ++++++++++++++----- packages/docs-build/src/openapi-output.ts | 11 +++++++--- .../docs-manifest/src/version-segment.test.ts | 15 +++++++++++++ packages/docs-manifest/src/version-segment.ts | 14 +++++++++++++ pnpm-lock.yaml | 3 +++ 9 files changed, 66 insertions(+), 10 deletions(-) diff --git a/apps/docs/scripts/sync-docs.mjs b/apps/docs/scripts/sync-docs.mjs index bc8decfa..8ff153c6 100644 --- a/apps/docs/scripts/sync-docs.mjs +++ b/apps/docs/scripts/sync-docs.mjs @@ -14,6 +14,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; import { + OPENAPI_MIN_LINE, clearOpenApi, rendersOpenApi, syncDocSource, @@ -47,6 +48,7 @@ import { readVersionRedirects } from "./version-redirects.mjs"; const execFileAsync = promisify(execFile); const appDir = path.dirname(path.dirname(fileURLToPath(import.meta.url))); const cacheDir = path.join(appDir, ".cache", "docs-clone"); +const FIXTURE_OPENAPI_MIN_LINE = "0.2"; async function git(cwd, args, env) { await execFileAsync("git", args, { cwd, ...(env ? { env: { ...process.env, ...env } } : {}) }); @@ -114,6 +116,9 @@ if (single) { ); provider = createGitRefsProvider({ repo, versions, cacheDir, lastModified: true }); } +// The fixture's 0.2 renders the generated reference and its 0.1 keeps Markdown, as 2.24 and 2.23 do. +const usesFixture = !single && !process.env.DOCS_REPO; +const openApiMinLine = usesFixture ? FIXTURE_OPENAPI_MIN_LINE : OPENAPI_MIN_LINE; // Start from an empty content/ so switching between the fixture and a real // corpus never leaves a stale version directory behind. Clear the slug @@ -138,7 +143,7 @@ for (const version of latestLastSyncOrder(versions)) { let result; try { let source = await provider.loadVersion(version); - if (rendersOpenApi(version)) { + if (rendersOpenApi(version, process.env, openApiMinLine)) { const swagger = single ? await swaggerFromTree(process.env.DOCS_ROOT) : await swaggerFromClone(cacheDir, version.ref); diff --git a/apps/offlinedocs/scripts/sync-docs.mjs b/apps/offlinedocs/scripts/sync-docs.mjs index cf864792..b7977a1c 100644 --- a/apps/offlinedocs/scripts/sync-docs.mjs +++ b/apps/offlinedocs/scripts/sync-docs.mjs @@ -16,6 +16,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { clearOpenApi, + rendersOpenApi, syncDocSource, withOpenApiReference, writeReleaseSchedule, @@ -64,7 +65,7 @@ if (process.env.DOCS_ROOT) { await clearOpenApi(appDir); let source = await provider.loadVersion(version); -if (process.env.DOCS_ROOT || process.env.DOCS_REPO) { +if ((process.env.DOCS_ROOT || process.env.DOCS_REPO) && rendersOpenApi(version)) { const swagger = process.env.DOCS_ROOT ? await swaggerFromTree(process.env.DOCS_ROOT) : await swaggerFromClone(path.join(appDir, ".cache", "docs-clone"), version.ref); diff --git a/packages/docs-build/package.json b/packages/docs-build/package.json index ea02b6cb..f13fe6e5 100644 --- a/packages/docs-build/package.json +++ b/packages/docs-build/package.json @@ -24,6 +24,7 @@ }, "dependencies": { "@coder/docs-config": "workspace:*", + "@coder/docs-manifest": "workspace:*", "@coder/docs-transforms": "workspace:*", "@fumari/image-size": "0.1.1", "github-slugger": "2.0.0", diff --git a/packages/docs-build/src/index.ts b/packages/docs-build/src/index.ts index f9175073..f3787d33 100644 --- a/packages/docs-build/src/index.ts +++ b/packages/docs-build/src/index.ts @@ -11,6 +11,7 @@ export { } from "./reserved-routes.js"; export { applyOpenApiReference, convertSwagger, tagSlug } from "./openapi-reference.js"; export { + OPENAPI_MIN_LINE, clearOpenApi, openApiDataDir, rendersOpenApi, diff --git a/packages/docs-build/src/openapi-output.test.ts b/packages/docs-build/src/openapi-output.test.ts index 1e7c2061..107e0077 100644 --- a/packages/docs-build/src/openapi-output.test.ts +++ b/packages/docs-build/src/openapi-output.test.ts @@ -5,6 +5,7 @@ import path from "node:path"; import { test } from "node:test"; import type { DocSource } from "@coder/docs-config"; import { + OPENAPI_MIN_LINE, clearOpenApi, openApiDataDir, rendersOpenApi, @@ -44,11 +45,21 @@ const source: DocSource = { const quiet = { log() {}, warn() {} }; -test("only the mainline renders the reference, unless every version is asked for or it is off", () => { - assert.equal(rendersOpenApi({ id: "2.38", latest: true }, {}), true); - assert.equal(rendersOpenApi({ id: "2.37" }, {}), false); - assert.equal(rendersOpenApi({ id: "2.37" }, { DOCS_OPENAPI_VERSIONS: "all" }), true); - assert.equal(rendersOpenApi({ id: "2.38", latest: true }, { DOCS_OPENAPI: "0" }), false); +test(`main and every line or tag from ${OPENAPI_MIN_LINE} render the reference; older ones keep Markdown`, () => { + assert.equal(OPENAPI_MIN_LINE, "2.24"); + for (const id of ["main", "2.38", "2.24", "2.24.1", "2.39"]) + assert.equal(rendersOpenApi({ id }, {}), true, id); + for (const id of ["2.23", "2.23.9", "2.9"]) assert.equal(rendersOpenApi({ id }, {}), false, id); +}); + +test("DOCS_OPENAPI=0 keeps Markdown for every version", () => { + for (const id of ["main", "2.38"]) + assert.equal(rendersOpenApi({ id }, { DOCS_OPENAPI: "0" }), false); +}); + +test("a corpus with its own versions, such as the fixture, can set its own floor line", () => { + assert.equal(rendersOpenApi({ id: "0.2" }, {}, "0.2"), true); + assert.equal(rendersOpenApi({ id: "0.1" }, {}, "0.2"), false); }); test("the version's reference data is written where the page renderer reads it", async () => { diff --git a/packages/docs-build/src/openapi-output.ts b/packages/docs-build/src/openapi-output.ts index 89ad29a2..47561a26 100644 --- a/packages/docs-build/src/openapi-output.ts +++ b/packages/docs-build/src/openapi-output.ts @@ -1,19 +1,24 @@ import { mkdir, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import type { DocSource } from "@coder/docs-config"; +import { isLineAtLeast } from "@coder/docs-manifest/version-segment"; import { applyOpenApiReference } from "./openapi-reference.js"; /** Where a sync leaves each version's REST API reference data, which the page renderer reads. */ export const openApiDataDir = (appDir: string): string => path.join(appDir, ".generated", "openapi"); -/** Which versions render the generated reference: the mainline only, unless DOCS_OPENAPI_VERSIONS=all. */ +/** The oldest line whose Swagger document converts cleanly; older lines repeat operation ids. */ +export const OPENAPI_MIN_LINE = "2.24"; + +/** Whether a version renders the generated reference: main and every line or tag from `minLine`, unless DOCS_OPENAPI=0. */ export function rendersOpenApi( - version: { latest?: boolean }, + version: { id: string }, env: Record = process.env, + minLine: string = OPENAPI_MIN_LINE, ): boolean { if (env.DOCS_OPENAPI === "0") return false; - return env.DOCS_OPENAPI_VERSIONS === "all" || version.latest === true; + return isLineAtLeast(version.id, minLine); } export async function clearOpenApi(appDir: string): Promise { diff --git a/packages/docs-manifest/src/version-segment.test.ts b/packages/docs-manifest/src/version-segment.test.ts index a3ae096f..242f31e9 100644 --- a/packages/docs-manifest/src/version-segment.test.ts +++ b/packages/docs-manifest/src/version-segment.test.ts @@ -4,6 +4,7 @@ import { fixtureItems, withLayout } from "./test-fixtures.js"; import { parseManifestItems } from "./items.js"; import { CANONICAL_LAYOUT, + isLineAtLeast, isVersionShapedSegment, oldFormsServed, parseVersionSegment, @@ -145,3 +146,17 @@ test("a segment that only resembles a version parses to null", () => { assert.equal(parseVersionSegment(segment, manifest), null, JSON.stringify(segment)); } }); + +test("isLineAtLeast compares a line or tag's minor line with a floor line, and main is newest", () => { + assert.equal(isLineAtLeast("2.24", "2.24"), true); + assert.equal(isLineAtLeast("2.38", "2.24"), true); + assert.equal(isLineAtLeast("2.39", "2.24"), true); + assert.equal(isLineAtLeast("2.24.3", "2.24"), true); + assert.equal(isLineAtLeast("2.23", "2.24"), false); + assert.equal(isLineAtLeast("2.23.9", "2.24"), false); + assert.equal(isLineAtLeast("2.9", "2.24"), false, "minors compare as numbers, not text"); + assert.equal(isLineAtLeast("3.0", "2.24"), true); + assert.equal(isLineAtLeast("main", "2.24"), true); + assert.throws(() => isLineAtLeast("2.24", "main"), /not a line id/); + assert.throws(() => isLineAtLeast("v2.24", "2.24"), /not a version id/); +}); diff --git a/packages/docs-manifest/src/version-segment.ts b/packages/docs-manifest/src/version-segment.ts index 473fb699..72d6bf17 100644 --- a/packages/docs-manifest/src/version-segment.ts +++ b/packages/docs-manifest/src/version-segment.ts @@ -52,6 +52,20 @@ export function versionKind(id: string): VersionKind { throw new Error(`not a version id: ${JSON.stringify(id)}`); } +const minorParts = (id: string): [number, number] => { + const [major, minor] = id.split(".").map(Number); + return [major ?? 0, minor ?? 0]; +}; + +/** Whether a version is on the `floor` line or a newer one: a line or tag by its minor line, and main as the newest. */ +export function isLineAtLeast(id: string, floor: string): boolean { + if (!LINE_ID_PATTERN.test(floor)) throw new Error(`not a line id: ${JSON.stringify(floor)}`); + if (versionKind(id) === "dev") return true; + const [major, minor] = minorParts(id); + const [floorMajor, floorMinor] = minorParts(floor); + return major > floorMajor || (major === floorMajor && minor >= floorMinor); +} + /** The canonical first segment: `v2.38` for a line, `@v2.38.1` for a tag, `@main` for main. */ export function versionSegment(id: string): string { const kind = versionKind(id); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 05a7fcf6..ff0b935d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -317,6 +317,9 @@ importers: '@coder/docs-config': specifier: workspace:* version: link:../docs-config + '@coder/docs-manifest': + specifier: workspace:* + version: link:../docs-manifest '@coder/docs-transforms': specifier: workspace:* version: link:../docs-transforms From de909b0e4f37c70236a66da7b7a0bb71e116821f Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 15:24:51 -0400 Subject: [PATCH 20/69] feat(api-reference): filter the schemas page and group it by package The schemas page is one table of about 680 rows, which readers scroll or search with the browser to find one schema. The rows are now grouped by package prefix (codersdk, agentsdk, wsproxysdk, and Other for names without one), each group a collapsed native details element, and a labelled search box above them narrows the rows by name, with a polite live count ("12 of 682 schemas") and an empty-state message. While a filter is set, the groups with a match open and the rest hide; clearing it restores the groups the reader had open. Every row stays in the server HTML, so the page reads the same without JavaScript, and the Markdown twin keeps the plain table; the filter is a small client component that only hides rows. The old-anchor redirect now also follows a hash that changes after load, so a schema link followed while a filter is set still lands on its endpoint. The fixture document gains an agentsdk schema and an unprefixed one, and the axe pass now scans the schemas page. Assisted-by: AI --- apps/docs/fixtures/openapi/swagger.json | 8 + apps/docs/scripts/a11y-axe-helpers.mjs | 1 + packages/docs-build/src/index.ts | 1 + .../docs-build/src/openapi-output.test.ts | 8 +- packages/docs-build/src/openapi-output.ts | 1 + .../docs-build/src/openapi-reference.test.ts | 11 ++ packages/docs-build/src/openapi-reference.ts | 15 ++ .../src/openapi/anchor-redirect.test.tsx | 25 +++ .../docs-next/src/openapi/anchor-redirect.tsx | 13 +- packages/docs-next/src/openapi/index.tsx | 17 +- .../docs-next/src/openapi/landing.test.tsx | 1 + .../docs-next/src/openapi/schema-filter.tsx | 65 ++++++++ .../docs-next/src/openapi/schemas.test.tsx | 150 ++++++++++++++++++ packages/docs-next/src/openapi/schemas.tsx | 76 +++++++++ packages/docs-theme/src/brand.css | 45 ++++++ 15 files changed, 431 insertions(+), 6 deletions(-) create mode 100644 packages/docs-next/src/openapi/anchor-redirect.test.tsx create mode 100644 packages/docs-next/src/openapi/schema-filter.tsx create mode 100644 packages/docs-next/src/openapi/schemas.test.tsx create mode 100644 packages/docs-next/src/openapi/schemas.tsx diff --git a/apps/docs/fixtures/openapi/swagger.json b/apps/docs/fixtures/openapi/swagger.json index d7e63ada..7752f138 100644 --- a/apps/docs/fixtures/openapi/swagger.json +++ b/apps/docs/fixtures/openapi/swagger.json @@ -83,6 +83,14 @@ } }, "definitions": { + "Response": { + "type": "object", + "properties": { "message": { "type": "string" } } + }, + "agentsdk.Manifest": { + "type": "object", + "properties": { "agent_id": { "type": "string" } } + }, "codersdk.CreateUserRequest": { "type": "object", "required": ["email", "username"], diff --git a/apps/docs/scripts/a11y-axe-helpers.mjs b/apps/docs/scripts/a11y-axe-helpers.mjs index f302f49c..423d0647 100644 --- a/apps/docs/scripts/a11y-axe-helpers.mjs +++ b/apps/docs/scripts/a11y-axe-helpers.mjs @@ -21,6 +21,7 @@ export const DEFAULT_PAGES = [ "/authoring/callouts", "/authoring/states", "/reference/api", + "/reference/api/schemas", "/reference/api/users", "/reference/api/users/create-new-user", "/reference/api/workspaces/list-workspaces", diff --git a/packages/docs-build/src/index.ts b/packages/docs-build/src/index.ts index f3787d33..e47c4d19 100644 --- a/packages/docs-build/src/index.ts +++ b/packages/docs-build/src/index.ts @@ -21,4 +21,5 @@ export type { ApplyOpenApiReferenceOptions, OpenApiOperationRef, OpenApiReference, + OpenApiSchemas, } from "./openapi-reference.js"; diff --git a/packages/docs-build/src/openapi-output.test.ts b/packages/docs-build/src/openapi-output.test.ts index 107e0077..8a4fce4a 100644 --- a/packages/docs-build/src/openapi-output.test.ts +++ b/packages/docs-build/src/openapi-output.test.ts @@ -67,7 +67,13 @@ test("the version's reference data is written where the page renderer reads it", const next = await withOpenApiReference(appDir, { id: "2.38" }, source, swagger, quiet); assert.ok(next.files.some((file) => file.path === "reference/api/users/create-new-user.md")); const data = JSON.parse(await readFile(path.join(openApiDataDir(appDir), "2.38.json"), "utf8")); - assert.deepEqual(Object.keys(data).sort(), ["anchors", "document", "landing", "operations"]); + assert.deepEqual(Object.keys(data).sort(), [ + "anchors", + "document", + "landing", + "operations", + "schemas", + ]); assert.equal(data.landing.route, "reference/api"); await clearOpenApi(appDir); await assert.rejects(stat(openApiDataDir(appDir)), { code: "ENOENT" }); diff --git a/packages/docs-build/src/openapi-output.ts b/packages/docs-build/src/openapi-output.ts index 47561a26..2e11a5d0 100644 --- a/packages/docs-build/src/openapi-output.ts +++ b/packages/docs-build/src/openapi-output.ts @@ -51,6 +51,7 @@ export async function withOpenApiReference( operations: reference.operations, anchors: reference.anchors, landing: reference.landing, + schemas: reference.schemas, }), ); logger.log( diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index 6ec59dac..9df14bf4 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -206,3 +206,14 @@ test("an older document's basePath is folded into its paths, as newer documents }); assert.ok(Object.keys(reference.document.paths as object).every((p) => p.startsWith("/api/v2/"))); }); + +test("the schemas page's rows name each schema and the operation page that shows it", async () => { + const { reference } = await applyOpenApiReference(source, swagger); + assert.equal(reference.schemas.route, "reference/api/schemas"); + const byName = new Map(reference.schemas.rows.map((row) => [row.name, row])); + assert.deepEqual(byName.get("codersdk.Workspace"), { + name: "codersdk.Workspace", + operation: { title: "List workspaces", route: "reference/api/workspaces/list-workspaces" }, + }); + assert.equal(reference.schemas.rows.length, Object.keys(swagger.definitions).length); +}); diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index afeb7200..5800508d 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -28,9 +28,16 @@ export interface OpenApiReference { operations: Record; anchors: Record>; landing: OpenApiLanding; + schemas: OpenApiSchemas; warnings: string[]; } +/** The schemas page: its route, and each schema with the operation page that shows it most directly. */ +export interface OpenApiSchemas { + route: string; + rows: { name: string; operation?: { title: string; route: string } }[]; +} + /** An operation's card on the landing page. */ export interface LandingOperation { route: string; @@ -284,6 +291,7 @@ export async function applyOpenApiReference( const schemaTargets = new Map(); const schemaSlugger = new GithubSlugger(); const schemaAnchors: Record = {}; + const schemaList: { name: string; op?: Op }[] = []; for (const name of Object.keys(schemas)) { let best: Op | undefined; let bestDepth = Number.POSITIVE_INFINITY; @@ -295,6 +303,7 @@ export async function applyOpenApiReference( } } const anchor = schemaSlugger.slug(name); + schemaList.push(best ? { name, op: best } : { name }); if (best) { schemaTargets.set(anchor, best); schemaRows.push( @@ -390,6 +399,12 @@ export async function applyOpenApiReference( operations, anchors, landing: { route: routeOf(landingFile), setupId: landing.setupId, sections }, + schemas: { + route: routeOf(schemasFile), + rows: schemaList.map(({ name, op }) => + op ? { name, operation: { title: op.summary, route: routeOf(op.file) } } : { name }, + ), + }, warnings, }, }; diff --git a/packages/docs-next/src/openapi/anchor-redirect.test.tsx b/packages/docs-next/src/openapi/anchor-redirect.test.tsx new file mode 100644 index 00000000..6873861d --- /dev/null +++ b/packages/docs-next/src/openapi/anchor-redirect.test.tsx @@ -0,0 +1,25 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { AnchorRedirect } from "./anchor-redirect.js"; + +// A same-page target, so jsdom follows the redirect as a fragment navigation. +const TARGET = "/reference/api/schemas/#redirected"; + +test("a hash that arrives after the page loaded, with a filter typed, still redirects", async () => { + window.history.replaceState(null, "", "/reference/api/schemas/"); + const container = document.createElement("div"); + const input = container.appendChild(document.createElement("input")); + input.type = "search"; + input.value = "user"; + document.body.appendChild(container); + const root = createRoot(container.appendChild(document.createElement("div"))); + await act(async () => root.render()); + assert.equal(window.location.hash, ""); + window.location.hash = "codersdkuser"; + window.dispatchEvent(new HashChangeEvent("hashchange")); + assert.equal(window.location.hash, "#redirected"); + await act(async () => root.unmount()); + container.remove(); +}); diff --git a/packages/docs-next/src/openapi/anchor-redirect.tsx b/packages/docs-next/src/openapi/anchor-redirect.tsx index 48c981ce..acad8ccb 100644 --- a/packages/docs-next/src/openapi/anchor-redirect.tsx +++ b/packages/docs-next/src/openapi/anchor-redirect.tsx @@ -2,12 +2,17 @@ import { useEffect } from "react"; -/** Sends a link to an anchor of the old single-page reference on to the page that replaced it. */ +/** Sends a link to an anchor of the old single-page reference on to the page that replaced it, on load or when the hash changes. */ export function AnchorRedirect({ targets }: { targets: Record }) { useEffect(() => { - const anchor = decodeURIComponent(window.location.hash.slice(1)); - const target = anchor ? targets[anchor] : undefined; - if (target) window.location.replace(target); + const follow = () => { + const anchor = decodeURIComponent(window.location.hash.slice(1)); + const target = anchor ? targets[anchor] : undefined; + if (target) window.location.replace(target); + }; + follow(); + window.addEventListener("hashchange", follow); + return () => window.removeEventListener("hashchange", follow); }, [targets]); return null; } diff --git a/packages/docs-next/src/openapi/index.tsx b/packages/docs-next/src/openapi/index.tsx index da30f14c..f994ab32 100644 --- a/packages/docs-next/src/openapi/index.tsx +++ b/packages/docs-next/src/openapi/index.tsx @@ -7,6 +7,7 @@ import { ApiPage } from "./api-page-lazy.js"; import { withCodeSamples } from "./code-samples.js"; import { ApiLanding, type OpenApiLandingData } from "./landing.js"; import { SetupHrefProvider } from "./samples-note.js"; +import { type SchemaRow, SchemaTables } from "./schemas.js"; type Json = Record; @@ -16,6 +17,7 @@ export interface OpenApiPagesData { operations: Record; anchors: Record>; landing: OpenApiLandingData; + schemas: { route: string; rows: SchemaRow[] }; } const isObject = (value: unknown): value is Json => @@ -139,7 +141,20 @@ export function createOpenApiRenderBody( const href = hrefFor(target); if (href) targets[anchor] = href; } - return { after: }; + const redirect = ; + if (route !== data.schemas.route) return { after: redirect }; + return { + replace: ( + <> +

+ Each endpoint's page documents the request and response schemas it uses. These + tables name, for each schema, the endpoint page that shows it most directly. +

+ + + ), + after: redirect, + }; }; } diff --git a/packages/docs-next/src/openapi/landing.test.tsx b/packages/docs-next/src/openapi/landing.test.tsx index 9cd720a7..056ac8ef 100644 --- a/packages/docs-next/src/openapi/landing.test.tsx +++ b/packages/docs-next/src/openapi/landing.test.tsx @@ -94,6 +94,7 @@ test("the landing route gets the cards after its body and their headings in its document: {}, operations: {}, anchors: {}, + schemas: { route: "reference/api/schemas", rows: [] }, landing, })); const result = await renderBody({ versionId: undefined, slugs: ["reference", "api"], hrefFor }); diff --git a/packages/docs-next/src/openapi/schema-filter.tsx b/packages/docs-next/src/openapi/schema-filter.tsx new file mode 100644 index 00000000..64452ec5 --- /dev/null +++ b/packages/docs-next/src/openapi/schema-filter.tsx @@ -0,0 +1,65 @@ +"use client"; + +import { useEffect, useId, useRef, useState } from "react"; + +/** + * Narrows the server-rendered schema tables around it by name. The tables + * stay complete without JavaScript; this only hides rows, and opens the + * groups that match while a filter is set. + */ +export function SchemaFilter({ total }: { total: number }) { + const id = useId(); + const ref = useRef(null); + const [query, setQuery] = useState(""); + const [matches, setMatches] = useState(total); + const openBeforeFilter = useRef | undefined>(undefined); + + useEffect(() => { + const container = ref.current?.closest("[data-schemas]"); + if (!container) return; + const needle = query.trim().toLowerCase(); + const groups = [ + ...container.querySelectorAll("details[data-schema-group]"), + ]; + if (needle && !openBeforeFilter.current) { + openBeforeFilter.current = new Map(groups.map((group) => [group, group.open])); + } + let count = 0; + for (const group of groups) { + let groupMatches = 0; + for (const row of group.querySelectorAll("tr[data-schema-name]")) { + const match = row.dataset.schemaName?.includes(needle) ?? false; + row.hidden = !match; + if (match) groupMatches++; + } + count += groupMatches; + if (needle) { + group.hidden = groupMatches === 0; + group.open = groupMatches > 0; + } else { + group.hidden = false; + group.open = openBeforeFilter.current?.get(group) ?? group.open; + } + } + if (!needle) openBeforeFilter.current = undefined; + setMatches(count); + }, [query]); + + return ( +
+ + setQuery(event.target.value)} + /> +

{`${matches} of ${total} schemas`}

+ +
+ ); +} diff --git a/packages/docs-next/src/openapi/schemas.test.tsx b/packages/docs-next/src/openapi/schemas.test.tsx new file mode 100644 index 00000000..73489807 --- /dev/null +++ b/packages/docs-next/src/openapi/schemas.test.tsx @@ -0,0 +1,150 @@ +import assert from "node:assert/strict"; +import test, { type TestContext } from "node:test"; +import { act } from "react"; +import { hydrateRoot } from "react-dom/client"; +import { renderToString } from "react-dom/server"; +import { renderToFragment } from "../../test/dom.js"; +import { createOpenApiRenderBody } from "./index.js"; +import { SchemaTables, type SchemaRow } from "./schemas.js"; + +const rows: SchemaRow[] = [ + { + name: "codersdk.User", + operation: { title: "Get user", route: "reference/api/users/get-user" }, + }, + { name: "codersdk.UserStatus" }, + { name: "codersdk.Workspace", operation: { title: "List workspaces", route: "reference/api/w" } }, + { name: "agentsdk.Manifest", operation: { title: "Get manifest", route: "reference/api/m" } }, + { name: "wsproxysdk.RegisterRequest" }, + { name: "Response" }, +]; + +const hrefFor = (route: string) => `/beta-docs/${route}/`; +const page = () => ; + +test("the server HTML holds every row, in closed package groups, with Other last", () => { + const html = renderToFragment(page()); + assert.deepEqual( + [...html.querySelectorAll("tbody tr td:first-child")].map((td) => td.textContent), + [ + "agentsdk.Manifest", + "codersdk.User", + "codersdk.UserStatus", + "codersdk.Workspace", + "wsproxysdk.RegisterRequest", + "Response", + ], + ); + const groups = [...html.querySelectorAll("details")]; + assert.deepEqual( + groups.map((details) => details.querySelector("summary")?.textContent), + ["agentsdk (1)", "codersdk (3)", "wsproxysdk (1)", "Other (1)"], + ); + assert.ok(groups.every((details) => !details.open)); + assert.equal( + html.querySelector('a[href="/beta-docs/reference/api/users/get-user/"]')?.textContent, + "Get user", + ); + const input = html.querySelector("input"); + assert.equal(input?.getAttribute("type"), "search"); + assert.equal( + html.querySelector(`label[for="${input?.id}"]`)?.textContent, + "Filter schemas by name", + ); + const count = html.querySelector('[aria-live="polite"]'); + assert.equal(count?.textContent, "6 of 6 schemas"); +}); + +async function mount(t: TestContext) { + const container = document.createElement("div"); + container.innerHTML = renderToString(page()); + document.body.appendChild(container); + let root: ReturnType | undefined; + await act(async () => { + root = hydrateRoot(container, page()); + }); + t.after(async () => { + await act(async () => root?.unmount()); + container.remove(); + }); + const input = container.querySelector("input") as HTMLInputElement; + const type = async (text: string) => { + await act(async () => { + const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set; + setter?.call(input, text); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + }; + const visibleRows = () => + [...container.querySelectorAll("tbody tr")] + .filter((tr) => !(tr as HTMLElement).hidden) + .map((tr) => tr.querySelector("td")?.textContent); + const groups = () => + [...container.querySelectorAll("details")].map((details) => ({ + name: details.querySelector("summary")?.textContent, + open: details.open, + hidden: details.hidden, + })); + const count = () => container.querySelector('[aria-live="polite"]')?.textContent; + const empty = () => container.querySelector("[data-schema-empty]") as HTMLElement | null; + return { type, visibleRows, groups, count, empty }; +} + +test("typing narrows the rows by name, case-insensitively, and updates the count", async (t) => { + const view = await mount(t); + await view.type("USER"); + assert.deepEqual(view.visibleRows(), ["codersdk.User", "codersdk.UserStatus"]); + assert.equal(view.count(), "2 of 6 schemas"); + assert.equal(view.empty()?.hidden, true); +}); + +test("a filter opens the groups with a match and hides the rest; clearing it restores them", async (t) => { + const view = await mount(t); + await view.type("request"); + assert.deepEqual(view.groups(), [ + { name: "agentsdk (1)", open: false, hidden: true }, + { name: "codersdk (3)", open: false, hidden: true }, + { name: "wsproxysdk (1)", open: true, hidden: false }, + { name: "Other (1)", open: false, hidden: true }, + ]); + await view.type(""); + assert.ok(view.groups().every((group) => !group.open && !group.hidden)); + assert.equal(view.visibleRows().length, 6); + assert.equal(view.count(), "6 of 6 schemas"); +}); + +test("no match shows the empty state and a zero count", async (t) => { + const view = await mount(t); + await view.type("nothing-like-this"); + assert.equal(view.count(), "0 of 6 schemas"); + assert.equal(view.empty()?.hidden, false); + assert.match(view.empty()?.textContent ?? "", /No schema name contains “nothing-like-this”/); +}); + +test("a group a reader opened stays open after a filter is cleared", async (t) => { + const view = await mount(t); + const details = document.querySelectorAll("details")[0] as HTMLDetailsElement; + details.open = true; + await view.type("user"); + await view.type(""); + assert.equal(view.groups()[0]?.open, true); + assert.equal(view.groups()[1]?.open, false); +}); + +test("the schemas route renders the grouped tables in place of its Markdown table, and keeps the redirect", async () => { + const renderBody = createOpenApiRenderBody(async () => ({ + document: {}, + operations: {}, + anchors: { "reference/api/schemas": { codersdkuser: "reference/api/users/get-user" } }, + landing: { route: "reference/api", setupId: "set-up-your-environment", sections: [] }, + schemas: { route: "reference/api/schemas", rows }, + })); + const result = await renderBody({ + versionId: undefined, + slugs: ["reference", "api", "schemas"], + hrefFor, + }); + const body = renderToFragment(result?.replace); + assert.equal(body.querySelectorAll("tbody tr").length, rows.length); + assert.ok(result?.after, "the old-anchor redirect still renders"); +}); diff --git a/packages/docs-next/src/openapi/schemas.tsx b/packages/docs-next/src/openapi/schemas.tsx new file mode 100644 index 00000000..0a27fc45 --- /dev/null +++ b/packages/docs-next/src/openapi/schemas.tsx @@ -0,0 +1,76 @@ +import { SchemaFilter } from "./schema-filter.js"; + +/** One row of the schemas page: a schema and the operation page that shows it, if any does. */ +export interface SchemaRow { + name: string; + operation?: { title: string; route: string }; +} + +const OTHER = "Other"; + +function groupsOf(rows: SchemaRow[]): { name: string; rows: SchemaRow[] }[] { + const byPackage = new Map(); + for (const row of rows) { + const dot = row.name.indexOf("."); + const name = dot > 0 ? row.name.slice(0, dot) : OTHER; + let group = byPackage.get(name); + if (!group) byPackage.set(name, (group = [])); + group.push(row); + } + const names = [...byPackage.keys()] + .filter((name) => name !== OTHER) + .sort((a, b) => a.localeCompare(b)); + if (byPackage.has(OTHER)) names.push(OTHER); + return names.map((name) => ({ name, rows: byPackage.get(name) ?? [] })); +} + +/** + * The schemas page's table, one collapsed `
` per package prefix, with + * a filter above it. Every row is in the server HTML, so the page works the + * same without JavaScript. + */ +export function SchemaTables({ + rows, + hrefFor, +}: { + rows: SchemaRow[]; + hrefFor: (route: string) => string | undefined; +}) { + return ( +
+ + {groupsOf(rows).map((group) => ( +
+ {`${group.name} (${group.rows.length})`} + + + + + + + + + {group.rows.map((row) => { + const href = row.operation && hrefFor(row.operation.route); + return ( + + + + + ); + })} + +
SchemaShown on
+ {row.name} + + {row.operation && href ? ( + {row.operation.title} + ) : ( + "Not used by a documented endpoint" + )} +
+
+ ))} +
+ ); +} diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css index d77c092b..86ec39b6 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -799,3 +799,48 @@ samp { outline: 2px solid var(--color-fd-ring); outline-offset: 2px; } + +.coder-schema-filter { + display: grid; + gap: 0.375rem; + margin-block: 1.5rem 1rem; +} + +.coder-schema-filter label { + font-weight: 500; +} + +.coder-schema-filter input { + min-height: 2.5rem; + max-width: 28rem; + padding-inline: 0.75rem; + border: 1px solid var(--docs-control-border); + border-radius: 0.5rem; + background-color: var(--color-fd-background); + color: var(--color-fd-foreground); +} + +.coder-schema-filter p { + margin: 0; + font-size: 0.875rem; + color: var(--color-fd-muted-foreground); +} + +.coder-schema-group > summary { + display: flex; + align-items: center; + min-height: 2.5rem; + cursor: pointer; + font-weight: 600; +} + +.coder-schema-group > table { + margin-top: 0.25rem; +} + +@media (pointer: coarse) { + .coder-schema-filter input, + .coder-schema-group > summary { + min-height: 2.75rem; + } +} From 60aac3ddbd01916026f942c1c0ab13469f363312 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 15:55:15 -0400 Subject: [PATCH 21/69] fix(api-reference): keep the code-sample tabs clickable after a tall sample On an operation with a request body, selecting the Go tab left no way back to cURL: the sticky example column has a maximum height, so the flex layout shrank the sample tabs' tab list to nothing and the active sample's code region slid over it, taking every click meant for the other tabs. The tab list now keeps its size and the active sample shrinks and scrolls instead. The keyboard pass now also clicks every code-sample tab on an API operation page, in Chromium and Firefox at desktop and phone widths, so a covered tab fails CI. Assisted-by: AI --- apps/docs/scripts/a11y-keyboard-helpers.mjs | 10 +++++- apps/docs/scripts/a11y-keyboard.mjs | 34 +++++++++++++++++++-- apps/docs/scripts/a11y-keyboard.test.mjs | 24 ++++++++++++--- packages/docs-next/src/openapi/api-page.tsx | 6 +++- packages/docs-theme/src/brand.css | 16 ++++++++++ 5 files changed, 80 insertions(+), 10 deletions(-) diff --git a/apps/docs/scripts/a11y-keyboard-helpers.mjs b/apps/docs/scripts/a11y-keyboard-helpers.mjs index 9cebcd78..a7dffdd3 100644 --- a/apps/docs/scripts/a11y-keyboard-helpers.mjs +++ b/apps/docs/scripts/a11y-keyboard-helpers.mjs @@ -1,4 +1,6 @@ export const DEFAULT_PAGE = "/admin/users"; +// An API operation page with a request body, whose code-sample tabs are checked with the pointer. +export const DEFAULT_API_PAGE = "/reference/api/users/create-new-user"; export const BROWSERS = ["chromium", "firefox"]; export const VIEWPORTS = { desktop: { width: 1280, height: 800 }, @@ -9,7 +11,12 @@ export const SCHEMES = ["light", "dark"]; export const MIN_BORDER_CONTRAST = 3; export function parseArgs(argv) { - const options = { out: undefined, page: DEFAULT_PAGE, browsers: BROWSERS }; + const options = { + out: undefined, + page: DEFAULT_PAGE, + apiPage: DEFAULT_API_PAGE, + browsers: BROWSERS, + }; for (let i = 0; i < argv.length; i++) { const flag = argv[i]; const next = () => { @@ -19,6 +26,7 @@ export function parseArgs(argv) { }; if (flag === "--out") options.out = next(); else if (flag === "--page") options.page = next(); + else if (flag === "--api-page") options.apiPage = next(); else if (flag === "--browsers") { options.browsers = next().split(",").filter(Boolean); const unknown = options.browsers.filter((b) => !BROWSERS.includes(b)); diff --git a/apps/docs/scripts/a11y-keyboard.mjs b/apps/docs/scripts/a11y-keyboard.mjs index 34d6142b..bb4f703c 100644 --- a/apps/docs/scripts/a11y-keyboard.mjs +++ b/apps/docs/scripts/a11y-keyboard.mjs @@ -1,6 +1,7 @@ // Keyboard and focus checks axe cannot make: the skip link's Tab order and // focus hand-off, and the version switcher's outline contrast in the mobile -// drawer. Runs in Chromium and Firefox, at desktop and phone widths. +// drawer, and that each API code-sample tab takes a pointer click. Runs in +// Chromium and Firefox, at desktop and phone widths. import path from "node:path"; import { fileURLToPath } from "node:url"; import { loadPlaywright, serve } from "./a11y-browser.mjs"; @@ -112,7 +113,28 @@ async function checkDrawerSwitcher(page, fail) { return `switcher outline ${ratio.toFixed(2)}:1`; } -async function check({ browsers, base, pagePath, run }) { +// Each code-sample tab takes a pointer click, after the tallest sample has been shown, so no panel covers the tab list. +async function checkSampleTabs(page, fail) { + const tabs = page.locator(".coder-sample-tabs > [role=tablist] [role=tab]"); + const labels = await tabs.allTextContents(); + if (labels.length < 2) { + fail(`expected the code-sample tabs, found ${labels.length}`); + return "no sample tabs"; + } + for (const label of [...labels.slice(1), labels[0]]) { + const tab = tabs.filter({ hasText: new RegExp(`^${label}$`) }); + try { + await tab.click({ timeout: 5000 }); + } catch (error) { + fail(`the ${label} sample tab cannot be clicked: ${String(error.message).split("\n")[0]}`); + continue; + } + if ((await tab.getAttribute("aria-selected")) !== "true") fail(`${label} is not selected`); + } + return `${labels.length} sample tabs clickable`; +} + +async function check({ browsers, base, pagePath, apiPage, run }) { const failures = []; const fail = (message) => failures.push(`FAIL ${runName(run)} ${pagePath}: ${message}`); const mobile = run.viewport === "mobile"; @@ -133,6 +155,9 @@ async function check({ browsers, base, pagePath, run }) { await page.goto(base + pagePath, { waitUntil: "networkidle" }); notes.push(await checkDrawerSwitcher(page, fail)); } + const api = await page.goto(base + apiPage, { waitUntil: "networkidle" }); + if (!api?.ok()) throw new Error(`${apiPage} answered ${api?.status()}`); + notes.push(await checkSampleTabs(page, fail)); } finally { await context.close(); } @@ -154,6 +179,7 @@ async function main() { browsers, base: `http://127.0.0.1:${port}`, pagePath: options.page, + apiPage: options.apiPage, run, }); failures.push(...result.failures); @@ -167,7 +193,9 @@ async function main() { server.close(); } for (const failure of failures) console.log(failure); - console.log(`\n${runs.length} runs on ${options.page}: ${failures.length} failures.`); + console.log( + `\n${runs.length} runs on ${options.page} and ${options.apiPage}: ${failures.length} failures.`, + ); if (failures.length > 0) process.exitCode = 1; } diff --git a/apps/docs/scripts/a11y-keyboard.test.mjs b/apps/docs/scripts/a11y-keyboard.test.mjs index 03bc6c2a..e92d5cd2 100644 --- a/apps/docs/scripts/a11y-keyboard.test.mjs +++ b/apps/docs/scripts/a11y-keyboard.test.mjs @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { BROWSERS, + DEFAULT_API_PAGE, DEFAULT_PAGE, composite, contrastRatio, @@ -11,12 +12,25 @@ import { } from "./a11y-keyboard-helpers.mjs"; test("parseArgs defaults to both browsers and reads the flags", () => { - assert.deepEqual(parseArgs([]), { out: undefined, page: DEFAULT_PAGE, browsers: BROWSERS }); - assert.deepEqual(parseArgs(["--out", "o", "--page", "/install", "--browsers", "firefox"]), { - out: "o", - page: "/install", - browsers: ["firefox"], + assert.deepEqual(parseArgs([]), { + out: undefined, + page: DEFAULT_PAGE, + apiPage: DEFAULT_API_PAGE, + browsers: BROWSERS, }); + assert.deepEqual( + parseArgs([ + "--out", + "o", + "--page", + "/install", + "--api-page", + "/api/x", + "--browsers", + "firefox", + ]), + { out: "o", page: "/install", apiPage: "/api/x", browsers: ["firefox"] }, + ); assert.throws(() => parseArgs(["--browsers", "webkit"]), /Unknown browser webkit/); assert.throws(() => parseArgs(["--bogus"]), /Unknown flag/); assert.throws(() => parseArgs(["--page"]), /needs a value/); diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index 5737db0e..737594be 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -79,7 +79,11 @@ function SampleTabs() { ); if (samples.length === 0) return null; return ( - sample.label)} className="mb-4"> + sample.label)} + className="coder-sample-tabs mb-4" + > {samples.map((sample) => ( diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css index 86ec39b6..43a24eb0 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -844,3 +844,19 @@ samp { min-height: 2.75rem; } } + +/* The example column has a max height: the tab list keeps its size and the sample scrolls. */ +.coder-sample-tabs > [role="tablist"] { + flex-shrink: 0; +} + +.coder-sample-tabs > [role="tabpanel"][data-state="active"], +.coder-sample-tabs > [role="tabpanel"][data-state="active"] > figure { + display: flex; + flex-direction: column; + min-height: 0; +} + +.coder-sample-tabs > [role="tabpanel"] > figure > [role="region"] { + min-height: 0; +} From e9b2c56300e09a00be083e1a9ed59d33f31f7ce6 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 15:55:15 -0400 Subject: [PATCH 22/69] feat(api-reference): widen the example column to half the content width fumadocs-openapi fixes the example column at 400px, about 47 characters of code, so almost every sample scrolled sideways while the parameters column had room to spare. The operation layout, through fumadocs-openapi's renderOperationLayout hook, now gives the example column half the row, clamped between 400px and 640px, from the same container width at which the columns sit side by side; below it they still stack, and the column keeps its sticky position and maximum height. Assisted-by: AI --- packages/docs-next/src/openapi/api-page.tsx | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index 737594be..bbc620d0 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -106,6 +106,24 @@ const OpenApiPage = createOpenAPIPageBase({ storageKeyPrefix: STORAGE_KEY_PREFIX, content: { renderAPIExampleUsageTabs: () => , + // fumadocs-openapi 12.5.4's operation layout (ui/operation/index.js), with the example column half the width, between 400px and 640px, instead of a fixed 400px. + renderOperationLayout: (slots) => ( +
+
+ {slots.header} + {slots.apiPlayground} + {slots.description} + {slots.authSchemes} + {slots.parameters} + {slots.body} + {slots.responses} + {slots.callbacks} +
+
+ {slots.apiExample} +
+
+ ), renderAPIExampleLayout: ({ selector, usageTabs, responseTabs }) => (
{selector} From 54a0d15896ab33db984fa6fb8659c12fd3661620 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 15:55:15 -0400 Subject: [PATCH 23/69] feat(api-reference): format the code samples to fit the example column The longest line of a typical sample ran to 64 characters in cURL and 96 to 115 in JavaScript and Go, so most samples scrolled even in a wider column. Each sample now names the URL in a variable (and the session token, where the language reads it), curl puts the URL on its own continuation line, and a URL that would still not fit on one line is split before the path. Lines stay within SAMPLE_LINE_TARGET (64 characters) except a path too long to break, which a test pins over the test operations; the environment variables, placeholders, escaping and auth-only-when-needed are unchanged. Assisted-by: AI --- .../docs-next/src/openapi/api-page.test.tsx | 2 +- .../src/openapi/code-samples.test.ts | 121 +++++++++++++++--- .../docs-next/src/openapi/code-samples.ts | 54 ++++++-- 3 files changed, 146 insertions(+), 31 deletions(-) diff --git a/packages/docs-next/src/openapi/api-page.test.tsx b/packages/docs-next/src/openapi/api-page.test.tsx index 1cd6ce1e..828691bc 100644 --- a/packages/docs-next/src/openapi/api-page.test.tsx +++ b/packages/docs-next/src/openapi/api-page.test.tsx @@ -79,7 +79,7 @@ for (const [label, deployment] of [ for (const name of ["cURL", "JavaScript", "Python", "Go"]) assert.ok(tabs.includes(name), name); assert.equal(localStorage.getItem(STORED_SERVER), null, "the bad value is dropped"); - assert.match(container.textContent ?? "", /curl -X GET "\$CODER_URL\/api\/v2\/buildinfo"/); + assert.match(container.textContent ?? "", / -X GET \\\n {2}"\$CODER_URL\/api\/v2\/buildinfo"/); await unmount(); } finally { window.removeEventListener("error", onError); diff --git a/packages/docs-next/src/openapi/code-samples.test.ts b/packages/docs-next/src/openapi/code-samples.test.ts index aa1c3edd..c2926505 100644 --- a/packages/docs-next/src/openapi/code-samples.test.ts +++ b/packages/docs-next/src/openapi/code-samples.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import test from "node:test"; -import { codeSamples, withCodeSamples } from "./code-samples.js"; +import { SAMPLE_LINE_TARGET, codeSamples, withCodeSamples } from "./code-samples.js"; const document = { openapi: "3.0.3", @@ -145,7 +145,8 @@ test("curl: path params stay placeholders and only required query params are add assert.equal( sample(document, "/api/v2/users/{user}", "get", "curl"), [ - `curl -X GET "$CODER_URL/api/v2/users/{user}?limit={limit}" \\`, + `curl -X GET \\`, + ` "$CODER_URL/api/v2/users/{user}?limit={limit}" \\`, ` -H "Coder-Session-Token: $CODER_SESSION_TOKEN"`, ].join("\n"), ); @@ -155,7 +156,8 @@ test("curl: a JSON body is a sample of the schema's required fields", () => { assert.equal( sample(document, "/api/v2/users", "post", "curl"), [ - `curl -X POST "$CODER_URL/api/v2/users" \\`, + `curl -X POST \\`, + ` "$CODER_URL/api/v2/users" \\`, ` -H "Coder-Session-Token: $CODER_SESSION_TOKEN" \\`, ` -H "Content-Type: application/json" \\`, ` -d '{`, @@ -169,16 +171,18 @@ test("curl: a JSON body is a sample of the schema's required fields", () => { test("curl: an operation without security sends no token", () => { assert.equal( sample(document, "/api/v2/buildinfo", "get", "curl"), - `curl -X GET "$CODER_URL/api/v2/buildinfo"`, + [`curl -X GET \\`, ` "$CODER_URL/api/v2/buildinfo"`].join("\n"), ); }); test("curl: another auth scheme gets a placeholder, never the session token", () => { assert.equal( sample(document, "/scim/v2/Users", "get", "curl"), - [`curl -X GET "$CODER_URL/scim/v2/Users" \\`, ` -H "Authorization: {Authorization}"`].join( - "\n", - ), + [ + `curl -X GET \\`, + ` "$CODER_URL/scim/v2/Users" \\`, + ` -H "Authorization: {Authorization}"`, + ].join("\n"), ); }); @@ -251,7 +255,8 @@ test("curl: a Content-Type header parameter replaces the declared media type", ( assert.equal( sample(upload, "/api/v2/files", "post", "curl"), [ - `curl -X POST "$CODER_URL/api/v2/files" \\`, + `curl -X POST \\`, + ` "$CODER_URL/api/v2/files" \\`, ` -H "Coder-Session-Token: $CODER_SESSION_TOKEN" \\`, ` -H "Content-Type: {Content-Type}" \\`, ` --data-binary "@{file}"`, @@ -284,7 +289,7 @@ const form = { test("curl: a multipart body sends its required fields", () => { assert.equal( sample(form, "/api/v2/form", "post", "curl"), - [`curl -X POST "$CODER_URL/api/v2/form" \\`, ` -F "name={name}"`].join("\n"), + [`curl -X POST \\`, ` "$CODER_URL/api/v2/form" \\`, ` -F "name={name}"`].join("\n"), ); }); @@ -292,10 +297,12 @@ test("JavaScript: fetch with the URL and token from the environment", () => { assert.equal( sample(document, "/api/v2/users", "post", "javascript"), [ - `const response = await fetch(process.env.CODER_URL + "/api/v2/users", {`, + `const { CODER_URL, CODER_SESSION_TOKEN } = process.env;`, + "const url = `${CODER_URL}/api/v2/users`;", + `const response = await fetch(url, {`, ` method: "POST",`, ` headers: {`, - ` "Coder-Session-Token": process.env.CODER_SESSION_TOKEN,`, + ` "Coder-Session-Token": CODER_SESSION_TOKEN,`, ` "Content-Type": "application/json",`, ` },`, ` body: JSON.stringify({`, @@ -312,7 +319,9 @@ test("JavaScript: no auth means no headers", () => { assert.equal( sample(document, "/api/v2/buildinfo", "get", "javascript"), [ - `const response = await fetch(process.env.CODER_URL + "/api/v2/buildinfo", {`, + `const { CODER_URL } = process.env;`, + "const url = `${CODER_URL}/api/v2/buildinfo`;", + `const response = await fetch(url, {`, ` method: "GET",`, `});`, `console.log(response.status, await response.text());`, @@ -351,10 +360,12 @@ test("Python: requests with the URL and token from the environment", () => { ``, `import requests`, ``, + `url = os.environ["CODER_URL"] + "/api/v2/users"`, + `token = os.environ["CODER_SESSION_TOKEN"]`, `response = requests.post(`, - ` os.environ["CODER_URL"] + "/api/v2/users",`, + ` url,`, ` headers={`, - ` "Coder-Session-Token": os.environ["CODER_SESSION_TOKEN"],`, + ` "Coder-Session-Token": token,`, ` },`, ` json={`, ` "email": "user@example.com",`, @@ -370,10 +381,15 @@ test("Python: no auth and no body", () => { assert.equal( sample(document, "/api/v2/users/{user}", "get", "python").split("\n").slice(4).join("\n"), [ + `url = (`, + ` os.environ["CODER_URL"]`, + ` + "/api/v2/users/{user}?limit={limit}"`, + `)`, + `token = os.environ["CODER_SESSION_TOKEN"]`, `response = requests.get(`, - ` os.environ["CODER_URL"] + "/api/v2/users/{user}?limit={limit}",`, + ` url,`, ` headers={`, - ` "Coder-Session-Token": os.environ["CODER_SESSION_TOKEN"],`, + ` "Coder-Session-Token": token,`, ` },`, `)`, `print(response.status_code, response.text)`, @@ -381,7 +397,7 @@ test("Python: no auth and no body", () => { ); assert.match( sample(document, "/api/v2/buildinfo", "get", "python"), - /^response = requests\.get\(\n {4}os\.environ\["CODER_URL"\] \+ "\/api\/v2\/buildinfo",\n\)$/m, + /^url = os\.environ\["CODER_URL"\] \+ "\/api\/v2\/buildinfo"\nresponse = requests\.get\(\n {4}url,\n\)$/m, ); }); @@ -451,11 +467,13 @@ test("Go: net/http with the URL and token from the environment", () => { ` "email": "user@example.com",`, ` "username": "string"`, `}\`)`, - `\treq, err := http.NewRequest(http.MethodPost, os.Getenv("CODER_URL")+"/api/v2/users", body)`, + `\turl := os.Getenv("CODER_URL") + "/api/v2/users"`, + `\ttoken := os.Getenv("CODER_SESSION_TOKEN")`, + `\treq, err := http.NewRequest(http.MethodPost, url, body)`, `\tif err != nil {`, `\t\tpanic(err)`, `\t}`, - `\treq.Header.Set("Coder-Session-Token", os.Getenv("CODER_SESSION_TOKEN"))`, + `\treq.Header.Set("Coder-Session-Token", token)`, `\treq.Header.Set("Content-Type", "application/json")`, `\tresp, err := http.DefaultClient.Do(req)`, `\tif err != nil {`, @@ -476,9 +494,9 @@ test("Go: no body is nil and leaves strings unimported; no auth sets no header", const source = sample(document, "/api/v2/buildinfo", "get", "go"); assert.match( source, - /req, err := http\.NewRequest\(http\.MethodGet, os\.Getenv\("CODER_URL"\)\+"\/api\/v2\/buildinfo", nil\)/, + /url := os\.Getenv\("CODER_URL"\) \+ "\/api\/v2\/buildinfo"\n\treq, err := http\.NewRequest\(http\.MethodGet, url, nil\)/, ); - assert.doesNotMatch(source, /"strings"|Header\.Set/); + assert.doesNotMatch(source, /"strings"|Header\.Set|token/); }); test("Go: a body with a backtick is an interpreted string literal", () => { @@ -501,3 +519,64 @@ test("the samples become the operation's only code samples without changing the const samples = JSON.parse(JSON.stringify(out)).paths["/api/v2/buildinfo"].get["x-codeSamples"]; assert.deepEqual(samples, codeSamples(document, "/api/v2/buildinfo", "get")); }); + +const longPath = "/api/v2/organizations/{organization}/members/{user}/workspaces"; +const long = { + ...document, + paths: { + ...document.paths, + [longPath]: { + post: { + security: [{ CoderSessionToken: [] }], + parameters: [ + { name: "organization", in: "path", required: true }, + { name: "user", in: "path", required: true }, + ], + requestBody: { + content: { + "application/json": { example: { template_id: "string", name: "string" } }, + }, + }, + responses: { "201": { description: "Created" } }, + }, + }, + }, +}; + +test(`sample lines stay within ${SAMPLE_LINE_TARGET} characters, except a path too long to break`, () => { + const operations: [string, string][] = [ + ["/api/v2/users/{user}", "get"], + ["/api/v2/users", "post"], + ["/api/v2/buildinfo", "get"], + ["/scim/v2/Users", "get"], + [longPath, "post"], + ]; + for (const [path, method] of operations) { + for (const { label, source } of codeSamples(long, path, method)) { + for (const line of source.split("\n")) { + const width = line.replace(/\t/g, " ").length; + if (line.includes(path)) continue; + assert.ok(width <= SAMPLE_LINE_TARGET, `${label} ${method} ${path}: ${width}: ${line}`); + } + } + } +}); + +test("a URL that would not fit on one line is split before the path in every language", async () => { + const [shell, js, python, go] = codeSamples(long, longPath, "post").map((s) => s.source); + assert.ok(shell?.includes(` -X POST \\\n "$CODER_URL${longPath}" \\`)); + assert.ok(js?.includes(`const url =\n \`\${CODER_URL}${longPath}\`;`)); + assert.ok(python?.includes(`url = (\n os.environ["CODER_URL"]\n + "${longPath}"\n)`)); + assert.ok(go?.includes(`\turl := os.Getenv("CODER_URL") +\n\t\t"${longPath}"`)); + const call = await fetchCall(js ?? ""); + assert.equal(call.url, `https://coder.test${longPath}`); +}); + +test("JavaScript: a path with template-literal syntax in it reaches fetch as written", async () => { + const odd = { + ...document, + paths: { "/api/v2/`a`/${b}/\\c": { get: { responses: { "200": { description: "OK" } } } } }, + }; + const call = await fetchCall(sample(odd, "/api/v2/`a`/${b}/\\c", "get", "javascript")); + assert.equal(call.url, "https://coder.test/api/v2/`a`/${b}/\\c"); +}); diff --git a/packages/docs-next/src/openapi/code-samples.ts b/packages/docs-next/src/openapi/code-samples.ts index 260fb344..27fd7af0 100644 --- a/packages/docs-next/src/openapi/code-samples.ts +++ b/packages/docs-next/src/openapi/code-samples.ts @@ -171,7 +171,8 @@ const shellSingleQuoted = (text: string): string => `'${text.replace(/'/g, `'\\' export function curlSample(request: ExampleRequest): string { const { body } = request; const lines = [ - `curl -X ${request.method} "$${DEPLOYMENT_URL_ENV}${shellDoubleQuoted(request.url).slice(1)}`, + `curl -X ${request.method}`, + `"$${DEPLOYMENT_URL_ENV}${shellDoubleQuoted(request.url).slice(1)}`, ...request.headers.map((header) => "token" in header ? `-H "${header.name}: $${SESSION_TOKEN_ENV}"` @@ -190,6 +191,18 @@ export function curlSample(request: ExampleRequest): string { const reindent = (text: string, prefix: string): string => text.replace(/\n/g, `\n${prefix}`); +/** The longest line a sample aims for, so it fits the example column without scrolling; a long path alone can exceed it. */ +export const SAMPLE_LINE_TARGET = 64; + +const width = (line: string): number => line.replace(/\t/g, " ").length; + +/** The one-line form of a statement when it fits the target, else its broken form. */ +const fitOrBreak = (oneLine: string[], broken: string[]): string[] => + oneLine.every((line) => width(line) <= SAMPLE_LINE_TARGET) ? oneLine : broken; + +/** Text inside a JavaScript template literal, where a backtick, a backslash or `${` would end or change it. */ +const templateText = (text: string): string => text.replace(/[\\`]|\$\{/g, "\\$&"); + export function javascriptSample(request: ExampleRequest): string { const { body } = request; const lines: string[] = []; @@ -201,15 +214,19 @@ export function javascriptSample(request: ExampleRequest): string { } lines.push(``); } + const usesToken = request.headers.some((header) => "token" in header); + const env = usesToken ? `${DEPLOYMENT_URL_ENV}, ${SESSION_TOKEN_ENV}` : DEPLOYMENT_URL_ENV; + const url = `\`\${${DEPLOYMENT_URL_ENV}}${templateText(request.url)}\`;`; lines.push( - `const response = await fetch(process.env.${DEPLOYMENT_URL_ENV} + ${JSON.stringify(request.url)}, {`, + `const { ${env} } = process.env;`, + ...fitOrBreak([`const url = ${url}`], [`const url =`, ` ${url}`]), + `const response = await fetch(url, {`, ` method: ${JSON.stringify(request.method)},`, ); if (request.headers.length > 0) { lines.push(` headers: {`); for (const header of request.headers) { - const value = - "token" in header ? `process.env.${SESSION_TOKEN_ENV}` : JSON.stringify(header.value); + const value = "token" in header ? SESSION_TOKEN_ENV : JSON.stringify(header.value); lines.push(` ${JSON.stringify(header.name)}: ${value},`); } lines.push(` },`); @@ -255,8 +272,20 @@ export function pythonSample(request: ExampleRequest): string { ``, `import requests`, ``, + ...fitOrBreak( + [`url = os.environ["${DEPLOYMENT_URL_ENV}"] + ${JSON.stringify(request.url)}`], + [ + `url = (`, + ` os.environ["${DEPLOYMENT_URL_ENV}"]`, + ` + ${JSON.stringify(request.url)}`, + `)`, + ], + ), + ...(request.headers.some((header) => "token" in header) + ? [`token = os.environ["${SESSION_TOKEN_ENV}"]`] + : []), `response = ${call}`, - ` os.environ["${DEPLOYMENT_URL_ENV}"] + ${JSON.stringify(request.url)},`, + ` url,`, ]; // requests sets this one itself for `json=`. const headers = request.headers.filter( @@ -266,8 +295,7 @@ export function pythonSample(request: ExampleRequest): string { if (headers.length > 0) { lines.push(` headers={`); for (const header of headers) { - const value = - "token" in header ? `os.environ["${SESSION_TOKEN_ENV}"]` : JSON.stringify(header.value); + const value = "token" in header ? "token" : JSON.stringify(header.value); lines.push(` ${JSON.stringify(header.name)}: ${value},`); } lines.push(` },`); @@ -335,9 +363,12 @@ export function goSample(request: ExampleRequest): string { const method = GO_METHODS[request.method] ?? JSON.stringify(request.method); const headers = request.headers.map((header) => "token" in header - ? `\treq.Header.Set(${JSON.stringify(header.name)}, os.Getenv("${SESSION_TOKEN_ENV}"))` + ? `\treq.Header.Set(${JSON.stringify(header.name)}, token)` : `\treq.Header.Set(${JSON.stringify(header.name)}, ${JSON.stringify(header.value)})`, ); + const token = request.headers.some((header) => "token" in header) + ? [`\ttoken := os.Getenv("${SESSION_TOKEN_ENV}")`] + : []; if (body?.kind === "form") headers.push(`\treq.Header.Set("Content-Type", form.FormDataContentType())`); return [ @@ -349,7 +380,12 @@ export function goSample(request: ExampleRequest): string { ``, `func main() {`, ...setup, - `\treq, err := http.NewRequest(${method}, os.Getenv("${DEPLOYMENT_URL_ENV}")+${JSON.stringify(request.url)}, ${reader})`, + ...fitOrBreak( + [`\turl := os.Getenv("${DEPLOYMENT_URL_ENV}") + ${JSON.stringify(request.url)}`], + [`\turl := os.Getenv("${DEPLOYMENT_URL_ENV}") +`, `\t\t${JSON.stringify(request.url)}`], + ), + ...token, + `\treq, err := http.NewRequest(${method}, url, ${reader})`, ...goCheck, ...headers, `\tresp, err := http.DefaultClient.Do(req)`, From fc73bb6850109ab993e867c2117bd61bf6f120e9 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 17:02:04 -0400 Subject: [PATCH 24/69] style(api-reference): format the operation-page test Oxfmt wraps the curl assertion in the stored-server test, which went in over the width and failed the lint job's format check. Assisted-by: AI --- packages/docs-next/src/openapi/api-page.test.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/docs-next/src/openapi/api-page.test.tsx b/packages/docs-next/src/openapi/api-page.test.tsx index 828691bc..eddc9315 100644 --- a/packages/docs-next/src/openapi/api-page.test.tsx +++ b/packages/docs-next/src/openapi/api-page.test.tsx @@ -79,7 +79,10 @@ for (const [label, deployment] of [ for (const name of ["cURL", "JavaScript", "Python", "Go"]) assert.ok(tabs.includes(name), name); assert.equal(localStorage.getItem(STORED_SERVER), null, "the bad value is dropped"); - assert.match(container.textContent ?? "", / -X GET \\\n {2}"\$CODER_URL\/api\/v2\/buildinfo"/); + assert.match( + container.textContent ?? "", + / -X GET \\\n {2}"\$CODER_URL\/api\/v2\/buildinfo"/, + ); await unmount(); } finally { window.removeEventListener("error", onError); From 2f26d05a172cacff447ff8cc9850bf1d754dc71e Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 17:10:24 -0400 Subject: [PATCH 25/69] feat(api-reference): write each code sample as its language's formatter would Readers copy the samples into their own code, which their formatter then rewrites, so each sample is now exactly what that formatter prints: gofmt for Go, ruff format (Black's style, 88 columns) for Python, shfmt's defaults (tab-indented continuation lines) for the shell, and Prettier's defaults (80 columns) for JavaScript, which writes object keys unquoted where it can, adds trailing commas, puts a short array on one line, picks its quote by the fewer escapes and never breaks a template literal. Python strings follow Black's quote choice. The samples keep the environment variables, the URL in a variable, the token read once and the multi-line JSON body; where a formatter's own width joins lines the samples used to break, the formatter wins, and the line-length test now holds each language to that width. The docs build still writes the text itself. A new `code samples format` CI job, in build & check's needs, runs gofmt, ruff, shfmt and oxfmt with Prettier's defaults over every fixture sample, with shellcheck, sh -n, node --check and py_compile, and fails if any would change; ruff and shfmt are pinned, shfmt by sha256. The code-sample tabs show a tab as four columns. Assisted-by: AI --- .github/workflows/ci.yml | 53 ++++++- apps/docs/package.json | 1 + apps/docs/scripts/code-samples-format.mjs | 105 +++++++++++++ packages/docs-next/package.json | 4 + .../docs-next/src/openapi/api-page.test.tsx | 5 +- .../src/openapi/code-samples.test.ts | 142 ++++++++++++++---- .../docs-next/src/openapi/code-samples.ts | 130 ++++++++++++---- packages/docs-theme/src/brand.css | 5 + 8 files changed, 385 insertions(+), 60 deletions(-) create mode 100644 apps/docs/scripts/code-samples-format.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f29ef0fd..352a3b71 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -202,6 +202,46 @@ jobs: shellcheck --version actionlint -color + # Every API code sample must already be what its language's formatter writes. + code-samples-format: + name: code samples format + runs-on: ubuntu-latest + timeout-minutes: 15 + env: + RUFF_VERSION: 0.17.2 + SHFMT_VERSION: 3.14.1 + SHFMT_SHA256: 76e77641faa025814b77f153b29796b8e6fa2fca03e0c76a691608b86c7ea7bf + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: ./.github/actions/setup + - uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0 + with: + go-version: 1.25.x + cache: false + - name: Install ruff + run: pipx install "ruff==${RUFF_VERSION}" + - name: Install shfmt + run: | + set -euo pipefail + binary="shfmt_v${SHFMT_VERSION}_linux_amd64" + mkdir -p "$RUNNER_TEMP/shfmt-bin" + cd "$RUNNER_TEMP/shfmt-bin" + curl -fsSL -o "$binary" "https://github.com/mvdan/sh/releases/download/v${SHFMT_VERSION}/$binary" + echo "$SHFMT_SHA256 $binary" | sha256sum -c - + mv "$binary" shfmt + chmod +x shfmt + echo "$RUNNER_TEMP/shfmt-bin" >> "$GITHUB_PATH" + - name: Build the packages + run: pnpm turbo run build --filter='./packages/*' + - name: Check the samples + run: | + set -euo pipefail + go version + ruff --version + shfmt --version + shellcheck --version + pnpm --filter @coder/docs-site samples:format + # The CLI smoke-builds the kit from the packed files alone before packing it. dist-dry-run: name: public release dry run @@ -244,7 +284,18 @@ jobs: name: build & check if: always() needs: - [lint, build, e2e-stitch, e2e-single, a11y, test, test-matrix-guard, actionlint, dist-dry-run] + [ + lint, + build, + e2e-stitch, + e2e-single, + a11y, + test, + test-matrix-guard, + actionlint, + dist-dry-run, + code-samples-format, + ] runs-on: ubuntu-latest timeout-minutes: 5 steps: diff --git a/apps/docs/package.json b/apps/docs/package.json index 952db587..523e6873 100644 --- a/apps/docs/package.json +++ b/apps/docs/package.json @@ -26,6 +26,7 @@ "perf:probe": "node scripts/perf-probe.mjs", "a11y:axe": "node scripts/a11y-axe.mjs", "a11y:keyboard": "node scripts/a11y-keyboard.mjs", + "samples:format": "node scripts/code-samples-format.mjs", "a11y:live": "node scripts/a11y-live.mjs", "parity:urls": "node --import tsx scripts/url-parity.mjs --out out", "parity:urls:live": "node --import tsx scripts/url-parity.mjs --live https://coder.com/beta-docs", diff --git a/apps/docs/scripts/code-samples-format.mjs b/apps/docs/scripts/code-samples-format.mjs new file mode 100644 index 00000000..0647f5b8 --- /dev/null +++ b/apps/docs/scripts/code-samples-format.mjs @@ -0,0 +1,105 @@ +// Checks that every generated API code sample is already formatted the way +// its language's formatter formats it, and still parses: gofmt for Go, ruff +// format (Black's style) for Python, shfmt for the shell, and oxfmt with +// Prettier's defaults for JavaScript, plus shellcheck, sh -n, node --check and +// py_compile. The docs build never runs these tools; this proves the text it +// writes is what they would write. Defaults to the fixture document; pass +// --swagger to check a real one. +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { convertSwagger } from "@coder/docs-build"; +import { codeSamples } from "@coder/docs-next/openapi/code-samples"; + +const run = promisify(execFile); +const appDir = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +const oxfmt = path.join(appDir, "..", "..", "node_modules", ".bin", "oxfmt"); +const METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"]; +const EXTENSIONS = { curl: "sh", javascript: "mjs", python: "py", go: "go" }; + +function parseArgs(argv) { + const options = { swagger: path.join(appDir, "fixtures", "openapi", "swagger.json") }; + for (let i = 0; i < argv.length; i++) { + if (argv[i] === "--swagger" && argv[i + 1]) options.swagger = argv[++i]; + else throw new Error(`Unknown flag ${argv[i]}`); + } + return options; +} + +async function writeSamples(swagger, dir) { + const { document } = await convertSwagger(swagger); + let count = 0; + for (const [route, item] of Object.entries(document.paths ?? {})) { + for (const method of METHODS) { + if (!item?.[method]) continue; + const name = `${method}${route.replace(/[^\w]+/g, "_")}`; + for (const sample of codeSamples(document, route, method)) { + const folder = sample.id === "go" ? path.join(dir, "go", name) : path.join(dir, sample.id); + await mkdir(folder, { recursive: true }); + const file = sample.id === "go" ? "main.go" : `${name}.${EXTENSIONS[sample.id]}`; + await writeFile(path.join(folder, file), `${sample.source}\n`); + } + count++; + } + } + return count; +} + +const filesIn = async (dir) => (await readdir(dir)).map((file) => path.join(dir, file)); + +// A check fails when its command exits non-zero or prints anything for a clean run. +async function check(name, command, args, { quietWhenClean = false } = {}) { + try { + const { stdout } = await run(command, args, { maxBuffer: 64 * 1024 * 1024 }); + if (quietWhenClean && stdout.trim()) return `${name}:\n${stdout.trim()}`; + return undefined; + } catch (error) { + if (error.code === "ENOENT") return `${name}: ${command} is not installed`; + return `${name}:\n${`${error.stdout ?? ""}${error.stderr ?? ""}`.trim() || error.message}`; + } +} + +async function main() { + const options = parseArgs(process.argv.slice(2)); + const swagger = JSON.parse(await readFile(options.swagger, "utf8")); + const dir = await mkdtemp(path.join(tmpdir(), "code-samples-")); + try { + const count = await writeSamples(swagger, dir); + const config = path.join(dir, "prettier-defaults.json"); + await writeFile(config, "{}\n"); + const shell = await filesIn(path.join(dir, "curl")); + const python = await filesIn(path.join(dir, "python")); + const javascript = await filesIn(path.join(dir, "javascript")); + const failures = ( + await Promise.all([ + check("gofmt", "gofmt", ["-l", path.join(dir, "go")], { quietWhenClean: true }), + check("ruff format", "ruff", [ + "format", + "--check", + "--diff", + "--isolated", + "--no-cache", + ...python, + ]), + check("shfmt", "shfmt", ["-d", ...shell]), + check("oxfmt (Prettier defaults)", oxfmt, ["-c", config, "--check", ...javascript]), + check("shellcheck", "shellcheck", ["-s", "sh", ...shell]), + ...shell.map((file) => check(`sh -n ${path.basename(file)}`, "sh", ["-n", file])), + ...javascript.map((file) => + check(`node --check ${path.basename(file)}`, process.execPath, ["--check", file]), + ), + check("py_compile", "python3", ["-m", "py_compile", ...python]), + ]) + ).filter(Boolean); + for (const failure of failures) console.log(`FAIL ${failure}`); + console.log(`${count} operations, ${count * 4} samples: ${failures.length} failing checks.`); + if (failures.length > 0) process.exitCode = 1; + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +await main(); diff --git a/packages/docs-next/package.json b/packages/docs-next/package.json index e8b01427..c0a3a80e 100644 --- a/packages/docs-next/package.json +++ b/packages/docs-next/package.json @@ -23,6 +23,10 @@ "./openapi": { "types": "./dist/openapi/index.d.ts", "default": "./dist/openapi/index.js" + }, + "./openapi/code-samples": { + "types": "./dist/openapi/code-samples.d.ts", + "default": "./dist/openapi/code-samples.js" } }, "files": [ diff --git a/packages/docs-next/src/openapi/api-page.test.tsx b/packages/docs-next/src/openapi/api-page.test.tsx index eddc9315..19972428 100644 --- a/packages/docs-next/src/openapi/api-page.test.tsx +++ b/packages/docs-next/src/openapi/api-page.test.tsx @@ -79,10 +79,7 @@ for (const [label, deployment] of [ for (const name of ["cURL", "JavaScript", "Python", "Go"]) assert.ok(tabs.includes(name), name); assert.equal(localStorage.getItem(STORED_SERVER), null, "the bad value is dropped"); - assert.match( - container.textContent ?? "", - / -X GET \\\n {2}"\$CODER_URL\/api\/v2\/buildinfo"/, - ); + assert.match(container.textContent ?? "", / -X GET \\\n\t"\$CODER_URL\/api\/v2\/buildinfo"/); await unmount(); } finally { window.removeEventListener("error", onError); diff --git a/packages/docs-next/src/openapi/code-samples.test.ts b/packages/docs-next/src/openapi/code-samples.test.ts index c2926505..fe8c771f 100644 --- a/packages/docs-next/src/openapi/code-samples.test.ts +++ b/packages/docs-next/src/openapi/code-samples.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import test from "node:test"; -import { SAMPLE_LINE_TARGET, codeSamples, withCodeSamples } from "./code-samples.js"; +import { SAMPLE_LINE_WIDTH, codeSamples, withCodeSamples } from "./code-samples.js"; const document = { openapi: "3.0.3", @@ -146,8 +146,8 @@ test("curl: path params stay placeholders and only required query params are add sample(document, "/api/v2/users/{user}", "get", "curl"), [ `curl -X GET \\`, - ` "$CODER_URL/api/v2/users/{user}?limit={limit}" \\`, - ` -H "Coder-Session-Token: $CODER_SESSION_TOKEN"`, + `\t"$CODER_URL/api/v2/users/{user}?limit={limit}" \\`, + `\t-H "Coder-Session-Token: $CODER_SESSION_TOKEN"`, ].join("\n"), ); }); @@ -157,10 +157,10 @@ test("curl: a JSON body is a sample of the schema's required fields", () => { sample(document, "/api/v2/users", "post", "curl"), [ `curl -X POST \\`, - ` "$CODER_URL/api/v2/users" \\`, - ` -H "Coder-Session-Token: $CODER_SESSION_TOKEN" \\`, - ` -H "Content-Type: application/json" \\`, - ` -d '{`, + `\t"$CODER_URL/api/v2/users" \\`, + `\t-H "Coder-Session-Token: $CODER_SESSION_TOKEN" \\`, + `\t-H "Content-Type: application/json" \\`, + `\t-d '{`, ` "email": "user@example.com",`, ` "username": "string"`, `}'`, @@ -171,7 +171,7 @@ test("curl: a JSON body is a sample of the schema's required fields", () => { test("curl: an operation without security sends no token", () => { assert.equal( sample(document, "/api/v2/buildinfo", "get", "curl"), - [`curl -X GET \\`, ` "$CODER_URL/api/v2/buildinfo"`].join("\n"), + [`curl -X GET \\`, `\t"$CODER_URL/api/v2/buildinfo"`].join("\n"), ); }); @@ -180,8 +180,8 @@ test("curl: another auth scheme gets a placeholder, never the session token", () sample(document, "/scim/v2/Users", "get", "curl"), [ `curl -X GET \\`, - ` "$CODER_URL/scim/v2/Users" \\`, - ` -H "Authorization: {Authorization}"`, + `\t"$CODER_URL/scim/v2/Users" \\`, + `\t-H "Authorization: {Authorization}"`, ].join("\n"), ); }); @@ -256,10 +256,10 @@ test("curl: a Content-Type header parameter replaces the declared media type", ( sample(upload, "/api/v2/files", "post", "curl"), [ `curl -X POST \\`, - ` "$CODER_URL/api/v2/files" \\`, - ` -H "Coder-Session-Token: $CODER_SESSION_TOKEN" \\`, - ` -H "Content-Type: {Content-Type}" \\`, - ` --data-binary "@{file}"`, + `\t"$CODER_URL/api/v2/files" \\`, + `\t-H "Coder-Session-Token: $CODER_SESSION_TOKEN" \\`, + `\t-H "Content-Type: {Content-Type}" \\`, + `\t--data-binary "@{file}"`, ].join("\n"), ); }); @@ -289,7 +289,7 @@ const form = { test("curl: a multipart body sends its required fields", () => { assert.equal( sample(form, "/api/v2/form", "post", "curl"), - [`curl -X POST \\`, ` "$CODER_URL/api/v2/form" \\`, ` -F "name={name}"`].join("\n"), + [`curl -X POST \\`, `\t"$CODER_URL/api/v2/form" \\`, `\t-F "name={name}"`].join("\n"), ); }); @@ -306,8 +306,8 @@ test("JavaScript: fetch with the URL and token from the environment", () => { ` "Content-Type": "application/json",`, ` },`, ` body: JSON.stringify({`, - ` "email": "user@example.com",`, - ` "username": "string"`, + ` email: "user@example.com",`, + ` username: "string",`, ` }),`, `});`, `console.log(response.status, await response.text());`, @@ -381,10 +381,7 @@ test("Python: no auth and no body", () => { assert.equal( sample(document, "/api/v2/users/{user}", "get", "python").split("\n").slice(4).join("\n"), [ - `url = (`, - ` os.environ["CODER_URL"]`, - ` + "/api/v2/users/{user}?limit={limit}"`, - `)`, + `url = os.environ["CODER_URL"] + "/api/v2/users/{user}?limit={limit}"`, `token = os.environ["CODER_SESSION_TOKEN"]`, `response = requests.get(`, ` url,`, @@ -441,7 +438,7 @@ test("Python: a body is a Python literal with True, False, None and escaped stri ` \\],`, ` "e": \\{\\},`, ` "f": \\[\\],`, - ` "note": "it's \\\\"q\\\\" \`tick\` \\$HOME \\$\\{x\\} \\\\\\\\ back\\\\nline",`, + ` "note": 'it\\\\'s "q" \`tick\` \\$HOME \\$\\{x\\} \\\\\\\\ back\\\\nline',`, ` \\},`, ].join("\n"), ), @@ -543,7 +540,14 @@ const long = { }, }; -test(`sample lines stay within ${SAMPLE_LINE_TARGET} characters, except a path too long to break`, () => { +const WIDTH_BY_LABEL: Record = { + cURL: SAMPLE_LINE_WIDTH.curl, + JavaScript: SAMPLE_LINE_WIDTH.javascript, + Python: SAMPLE_LINE_WIDTH.python, + Go: SAMPLE_LINE_WIDTH.go, +}; + +test("sample lines stay within each language's width, except a path too long to break", () => { const operations: [string, string][] = [ ["/api/v2/users/{user}", "get"], ["/api/v2/users", "post"], @@ -556,22 +560,106 @@ test(`sample lines stay within ${SAMPLE_LINE_TARGET} characters, except a path t for (const line of source.split("\n")) { const width = line.replace(/\t/g, " ").length; if (line.includes(path)) continue; - assert.ok(width <= SAMPLE_LINE_TARGET, `${label} ${method} ${path}: ${width}: ${line}`); + const limit = WIDTH_BY_LABEL[label] ?? 0; + assert.ok(width <= limit, `${label} ${method} ${path}: ${width} > ${limit}: ${line}`); } } } }); -test("a URL that would not fit on one line is split before the path in every language", async () => { +test("a long URL is split where each language's formatter splits it", async () => { const [shell, js, python, go] = codeSamples(long, longPath, "post").map((s) => s.source); - assert.ok(shell?.includes(` -X POST \\\n "$CODER_URL${longPath}" \\`)); - assert.ok(js?.includes(`const url =\n \`\${CODER_URL}${longPath}\`;`)); + assert.ok(shell?.includes(` -X POST \\\n\t"$CODER_URL${longPath}" \\`)); + // Prettier never breaks a template literal. + assert.ok(js?.includes(`const url = \`\${CODER_URL}${longPath}\`;`)); assert.ok(python?.includes(`url = (\n os.environ["CODER_URL"]\n + "${longPath}"\n)`)); assert.ok(go?.includes(`\turl := os.Getenv("CODER_URL") +\n\t\t"${longPath}"`)); const call = await fetchCall(js ?? ""); assert.equal(call.url, `https://coder.test${longPath}`); }); +test("Python: a URL that fits Black's 88 columns inside parentheses stays on one line there", () => { + const path = "/api/v2/workspaceagents/{workspaceagent}/listening-ports"; + const doc = { + ...document, + paths: { [path]: { get: { responses: { "200": { description: "OK" } } } } }, + }; + assert.ok( + sample(doc, path, "get", "python").includes( + `url = (\n os.environ["CODER_URL"] + "${path}"\n)`, + ), + ); +}); + +const bodyOf = (example: unknown) => ({ + ...document, + paths: { + "/api/v2/users": { + post: { + requestBody: { content: { "application/json": { example } } }, + responses: { "201": { description: "Created" } }, + }, + }, + }, +}); + +test("JavaScript: the body is the literal Prettier prints, with keys unquoted where they can be", () => { + const source = sample( + bodyOf({ + "a-b": 1, + list: ["x", "y"], + objs: [{ id: "string", type: "*" }], + quoted: 'it\'s "q"', + plain: "it's", + e: {}, + f: [], + }), + "/api/v2/users", + "post", + "javascript", + ); + assert.ok( + source.includes( + [ + ` body: JSON.stringify({`, + ` "a-b": 1,`, + ` list: ["x", "y"],`, + ` objs: [`, + ` {`, + ` id: "string",`, + ` type: "*",`, + ` },`, + ` ],`, + ` quoted: 'it\\'s "q"',`, + ` plain: "it's",`, + ` e: {},`, + ` f: [],`, + ` }),`, + ].join("\n"), + ), + source, + ); +}); + +test("JavaScript: an array too long for one line puts one value per line", () => { + const items = Array.from({ length: 8 }, (_, index) => `value-number-${index}`); + const source = sample(bodyOf({ items }), "/api/v2/users", "post", "javascript"); + assert.ok(source.includes(` items: [\n "value-number-0",\n`), source); + assert.ok(source.includes(` "value-number-7",\n ],`), source); +}); + +test("Python: a string takes single quotes only when that needs fewer escapes, as Black does", () => { + const source = sample( + bodyOf({ a: 'it\'s "q"', b: "it's", c: 'say "hi"' }), + "/api/v2/users", + "post", + "python", + ); + assert.ok(source.includes(` "a": 'it\\'s "q"',`), source); + assert.ok(source.includes(` "b": "it's",`), source); + assert.ok(source.includes(` "c": 'say "hi"',`), source); +}); + test("JavaScript: a path with template-literal syntax in it reaches fetch as written", async () => { const odd = { ...document, diff --git a/packages/docs-next/src/openapi/code-samples.ts b/packages/docs-next/src/openapi/code-samples.ts index 27fd7af0..dbb4e3ee 100644 --- a/packages/docs-next/src/openapi/code-samples.ts +++ b/packages/docs-next/src/openapi/code-samples.ts @@ -186,19 +186,83 @@ export function curlSample(request: ExampleRequest): string { } if (body?.kind === "binary") lines.push(`--data-binary ${shellDoubleQuoted("@".concat(placeholder("file")))}`); - return lines.join(" \\\n "); + // shfmt indents a continued line with a tab. + return lines.join(" \\\n\t"); } -const reindent = (text: string, prefix: string): string => text.replace(/\n/g, `\n${prefix}`); - -/** The longest line a sample aims for, so it fits the example column without scrolling; a long path alone can exceed it. */ -export const SAMPLE_LINE_TARGET = 64; +/** + * The width each sample's lines are broken to: the formatter's own line width + * where it has one (Prettier 80, Black and ruff 88), and the column width the + * samples aim for in shell and Go, whose formatters have none. A path too long + * to break can exceed it. + */ +export const SAMPLE_LINE_WIDTH = { curl: 64, javascript: 80, python: 88, go: 64 } as const; const width = (line: string): number => line.replace(/\t/g, " ").length; -/** The one-line form of a statement when it fits the target, else its broken form. */ -const fitOrBreak = (oneLine: string[], broken: string[]): string[] => - oneLine.every((line) => width(line) <= SAMPLE_LINE_TARGET) ? oneLine : broken; +/** The one-line form of a statement when it fits the width, else its broken form. */ +const fitOrBreak = (limit: number, oneLine: string[], broken: string[]): string[] => + oneLine.every((line) => width(line) <= limit) ? oneLine : broken; + +/** A JavaScript string literal as Prettier writes it: double quotes unless the text holds more of them than single quotes. */ +function jsString(text: string): string { + const doubles = text.split('"').length - 1; + const singles = text.split("'").length - 1; + const inner = JSON.stringify(text).slice(1, -1); + if (doubles <= singles) return `"${inner}"`; + return `'${inner.replace(/\\(.)|(')/gs, (match, escaped?: string) => + escaped === undefined ? "\\'" : escaped === '"' ? '"' : match, + )}'`; +} + +const IDENTIFIER = /^[A-Za-z_$][\w$]*$/; + +const isEmptyCollection = (value: unknown): boolean => + (Array.isArray(value) && value.length === 0) || isEmptyObject(value); + +/** + * A JSON value as the JavaScript literal Prettier prints with its defaults: an + * object keeps one property per line and drops the quotes a key doesn't need, + * and an array of plain values goes on one line when it fits the 80 columns. + * `before` and `after` are the text on the value's first and last lines. + */ +function jsLiteral(value: unknown, indent: string, before: number, after: number): string { + const inner = `${indent} `; + if (Array.isArray(value)) { + if (value.length === 0) return "[]"; + const flat = + value.every((item) => !isObject(item) && !Array.isArray(item)) || + value.every((item) => isEmptyCollection(item) || (!isObject(item) && !Array.isArray(item))); + if (flat) { + const oneLine = `[${value.map((item) => jsLiteral(item, inner, 0, 0)).join(", ")}]`; + if (before + oneLine.length + after <= SAMPLE_LINE_WIDTH.javascript) return oneLine; + } + const items = value.map((item) => `${inner}${jsLiteral(item, inner, inner.length, 1)},`); + return `[\n${items.join("\n")}\n${indent}]`; + } + if (isObject(value)) { + const entries = Object.entries(value); + if (entries.length === 0) return "{}"; + const items = entries.map(([key, item]) => { + const name = IDENTIFIER.test(key) ? key : jsString(key); + const head = `${inner}${name}: `; + return `${head}${jsLiteral(item, inner, head.length, 1)},`; + }); + return `{\n${items.join("\n")}\n${indent}}`; + } + if (typeof value === "string") return jsString(value); + return JSON.stringify(value) ?? "null"; +} + +/** A Python string literal as Black writes it: double quotes, unless single quotes need fewer escapes. */ +function pythonString(text: string): string { + const inner = JSON.stringify(text).slice(1, -1); + const single = inner.replace(/\\(.)|(')/gs, (match, escaped?: string) => + escaped === undefined ? "\\'" : escaped === '"' ? '"' : match, + ); + const escapes = (body: string) => body.split("\\").length - 1; + return escapes(single) < escapes(inner) ? `'${single}'` : `"${inner}"`; +} /** Text inside a JavaScript template literal, where a backtick, a backslash or `${` would end or change it. */ const templateText = (text: string): string => text.replace(/[\\`]|\$\{/g, "\\$&"); @@ -210,7 +274,7 @@ export function javascriptSample(request: ExampleRequest): string { if (body?.kind === "form") { lines.push(`const form = new FormData();`); for (const name of body.fields) { - lines.push(`form.append(${JSON.stringify(name)}, ${JSON.stringify(placeholder(name))});`); + lines.push(`form.append(${jsString(name)}, ${jsString(placeholder(name))});`); } lines.push(``); } @@ -219,24 +283,27 @@ export function javascriptSample(request: ExampleRequest): string { const url = `\`\${${DEPLOYMENT_URL_ENV}}${templateText(request.url)}\`;`; lines.push( `const { ${env} } = process.env;`, - ...fitOrBreak([`const url = ${url}`], [`const url =`, ` ${url}`]), + // Prettier never breaks a template literal, however long. + `const url = ${url}`, `const response = await fetch(url, {`, - ` method: ${JSON.stringify(request.method)},`, + ` method: ${jsString(request.method)},`, ); if (request.headers.length > 0) { lines.push(` headers: {`); for (const header of request.headers) { - const value = "token" in header ? SESSION_TOKEN_ENV : JSON.stringify(header.value); - lines.push(` ${JSON.stringify(header.name)}: ${value},`); + const value = "token" in header ? SESSION_TOKEN_ENV : jsString(header.value); + const key = IDENTIFIER.test(header.name) ? header.name : jsString(header.name); + lines.push(` ${key}: ${value},`); } lines.push(` },`); } if (body?.kind === "json") { - lines.push(` body: JSON.stringify(${reindent(jsonText(body.value), " ")}),`); + const head = " body: JSON.stringify("; + lines.push(`${head}${jsLiteral(body.value, " ", head.length, 2)}),`); } if (body?.kind === "form") lines.push(` body: form,`); if (body?.kind === "binary") { - lines.push(` body: await readFile(${JSON.stringify(placeholder("file"))}),`); + lines.push(` body: await readFile(${jsString(placeholder("file"))}),`); } lines.push(`});`, `console.log(response.status, await response.text());`); return lines.join("\n"); @@ -255,8 +322,9 @@ function pythonLiteral(value: unknown, indent: string): string { if (isObject(value)) { const entries = Object.entries(value); if (entries.length === 0) return "{}"; - return `{\n${entries.map(([key, item]) => `${inner}${JSON.stringify(key)}: ${pythonLiteral(item, inner)},`).join("\n")}\n${indent}}`; + return `{\n${entries.map(([key, item]) => `${inner}${pythonString(key)}: ${pythonLiteral(item, inner)},`).join("\n")}\n${indent}}`; } + if (typeof value === "string") return pythonString(value); return JSON.stringify(value); } @@ -266,20 +334,25 @@ export function pythonSample(request: ExampleRequest): string { const { body } = request; const call = PYTHON_METHODS.has(request.method) ? `requests.${request.method.toLowerCase()}(` - : `requests.request(\n ${JSON.stringify(request.method)},`; + : `requests.request(\n ${pythonString(request.method)},`; const lines = [ `import os`, ``, `import requests`, ``, ...fitOrBreak( - [`url = os.environ["${DEPLOYMENT_URL_ENV}"] + ${JSON.stringify(request.url)}`], - [ - `url = (`, - ` os.environ["${DEPLOYMENT_URL_ENV}"]`, - ` + ${JSON.stringify(request.url)}`, - `)`, - ], + SAMPLE_LINE_WIDTH.python, + [`url = os.environ["${DEPLOYMENT_URL_ENV}"] + ${pythonString(request.url)}`], + fitOrBreak( + SAMPLE_LINE_WIDTH.python, + [`url = (`, ` os.environ["${DEPLOYMENT_URL_ENV}"] + ${pythonString(request.url)}`, `)`], + [ + `url = (`, + ` os.environ["${DEPLOYMENT_URL_ENV}"]`, + ` + ${pythonString(request.url)}`, + `)`, + ], + ), ), ...(request.headers.some((header) => "token" in header) ? [`token = os.environ["${SESSION_TOKEN_ENV}"]`] @@ -295,8 +368,8 @@ export function pythonSample(request: ExampleRequest): string { if (headers.length > 0) { lines.push(` headers={`); for (const header of headers) { - const value = "token" in header ? "token" : JSON.stringify(header.value); - lines.push(` ${JSON.stringify(header.name)}: ${value},`); + const value = "token" in header ? "token" : pythonString(header.value); + lines.push(` ${pythonString(header.name)}: ${value},`); } lines.push(` },`); } @@ -304,12 +377,12 @@ export function pythonSample(request: ExampleRequest): string { if (body?.kind === "form") { lines.push(` files={`); for (const name of body.fields) { - lines.push(` ${JSON.stringify(name)}: (None, ${JSON.stringify(placeholder(name))}),`); + lines.push(` ${pythonString(name)}: (None, ${pythonString(placeholder(name))}),`); } lines.push(` },`); } if (body?.kind === "binary") { - lines.push(` data=open(${JSON.stringify(placeholder("file"))}, "rb"),`); + lines.push(` data=open(${pythonString(placeholder("file"))}, "rb"),`); } lines.push(`)`, `print(response.status_code, response.text)`); return lines.join("\n"); @@ -381,6 +454,7 @@ export function goSample(request: ExampleRequest): string { `func main() {`, ...setup, ...fitOrBreak( + SAMPLE_LINE_WIDTH.go, [`\turl := os.Getenv("${DEPLOYMENT_URL_ENV}") + ${JSON.stringify(request.url)}`], [`\turl := os.Getenv("${DEPLOYMENT_URL_ENV}") +`, `\t\t${JSON.stringify(request.url)}`], ), diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css index 43a24eb0..c201d2c2 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -860,3 +860,8 @@ samp { .coder-sample-tabs > [role="tabpanel"] > figure > [role="region"] { min-height: 0; } + +/* gofmt and shfmt indent with tabs; four columns keeps the samples within the example column. */ +.coder-sample-tabs pre { + tab-size: 4; +} From 269b72ced8c89691607291c1f536036514fc245e Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 17:11:44 -0400 Subject: [PATCH 26/69] test(url-parity): approve main's API reference anchor deltas Main now renders the per-operation API reference in the fixture build, so its tag and schemas pages lose the same in-page anchors the mainline already lost. The operation and schema anchors reach their new pages through the client-side anchor redirect; the per-operation `responses` headings are not in the redirect map, so a link to one now lands at the top of the tag page, as it already does on the mainline. Assisted-by: AI --- apps/docs/fixtures/url-parity-approved.json | 48 +++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/apps/docs/fixtures/url-parity-approved.json b/apps/docs/fixtures/url-parity-approved.json index 0aa8c4d0..ff4ebfd3 100644 --- a/apps/docs/fixtures/url-parity-approved.json +++ b/apps/docs/fixtures/url-parity-approved.json @@ -46,5 +46,53 @@ "url": "/docs/reference/api/schemas", "anchor": "codersdkworkspacesresponse", "reason": "schemas render on the operation pages; the schemas page redirects the anchor" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/users", + "anchor": "create-new-user", + "reason": "main renders the per-operation reference; the tag page's anchor redirect sends it to the operation page" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/users", + "anchor": "get-user-by-name", + "reason": "main renders the per-operation reference; the tag page's anchor redirect sends it to the operation page" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/users", + "anchor": "responses", + "reason": "per-operation subsection, now on the operation page; not redirected, so the link lands at the top of the tag page" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/users", + "anchor": "responses-1", + "reason": "per-operation subsection, now on the operation page; not redirected, so the link lands at the top of the tag page" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/workspaces", + "anchor": "list-workspaces", + "reason": "main renders the per-operation reference; the tag page's anchor redirect sends it to the operation page" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/workspaces", + "anchor": "responses", + "reason": "per-operation subsection, now on the operation page; not redirected, so the link lands at the top of the tag page" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/schemas", + "anchor": "codersdkuser", + "reason": "main renders the per-operation reference; the schemas page's anchor redirect sends it to the operation page that shows the schema" + }, + { + "kind": "anchor-missing", + "url": "/docs/@main/reference/api/schemas", + "anchor": "codersdkworkspacesresponse", + "reason": "main renders the per-operation reference; the schemas page's anchor redirect sends it to the operation page that shows the schema" } ] From 4ad4c91282214d5e00749be53f0c9e9b06ea9bc7 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 17:12:38 -0400 Subject: [PATCH 27/69] fix(api-reference): trim a basePath's trailing slashes without a regex CodeQL flagged the `/\/+$/` that trims the Swagger basePath as slow on input with many slashes. A loop over the trailing slashes does the same in linear time; a test pins that trailing slashes go and a root basePath adds nothing. Assisted-by: AI --- packages/docs-build/src/openapi-reference.test.ts | 15 +++++++++++++++ packages/docs-build/src/openapi-reference.ts | 3 ++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index 9df14bf4..14147a75 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -217,3 +217,18 @@ test("the schemas page's rows name each schema and the operation page that shows }); assert.equal(reference.schemas.rows.length, Object.keys(swagger.definitions).length); }); + +test("a basePath's trailing slashes are dropped, and a root basePath adds nothing", async () => { + for (const [basePath, expected] of [ + ["/api/v2//", "/api/v2/users/{user}"], + ["/", "/users/{user}"], + ] as const) { + const old = structuredClone(swagger); + old.basePath = basePath; + old.paths = Object.fromEntries( + Object.entries(old.paths).map(([route, item]) => [route.replace(/^\/api\/v2/, ""), item]), + ); + const { reference } = await applyOpenApiReference(source, old); + assert.equal(reference.operations["reference/api/users/get-user-by-name"]?.path, expected); + } +}); diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 5800508d..a430dba7 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -119,7 +119,8 @@ function withBasePathInPaths(swagger: unknown): unknown { if (!isObject(swagger) || typeof swagger.basePath !== "string" || !isObject(swagger.paths)) { return swagger; } - const base = swagger.basePath.replace(/\/+$/, ""); + let base = swagger.basePath; + while (base.endsWith("/")) base = base.slice(0, -1); const { basePath: _, ...rest } = swagger; return { ...rest, From 9cad6635b2c7af1ae0ee09700fb471bfc58707b3 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 17:52:20 -0400 Subject: [PATCH 28/69] fix(ci): check out coderd/apidoc where the publish and historical syncs read it The sync builds the per-operation API reference from coder/coder's coderd/apidoc/swagger.json, which it reads from the checkout beside the docs/ tree. publish-version.yml checked out only docs, and historical-sync.yml sparse-checked-out only docs, so in both the Swagger document was never there: the sync warned and kept the Markdown reference, and a republish of main or 2.24 to 2.38 would have shipped the old reference with every step green while the PR preview, which already checks out coderd/apidoc, showed the new one. Both now add coderd/apidoc to the sparse checkout, the same two paths the preview uses; nothing else in either job changes. Assisted-by: AI --- .github/workflows/historical-sync.yml | 2 +- .github/workflows/publish-version.yml | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/historical-sync.yml b/.github/workflows/historical-sync.yml index a41701bd..2ae174d2 100644 --- a/.github/workflows/historical-sync.yml +++ b/.github/workflows/historical-sync.yml @@ -86,7 +86,7 @@ jobs: run: | set -euo pipefail git clone --quiet --depth 1 --branch "$TAG" --filter=blob:none --sparse https://github.com/coder/coder.git "$RUNNER_TEMP/coder" - git -C "$RUNNER_TEMP/coder" sparse-checkout set docs + git -C "$RUNNER_TEMP/coder" sparse-checkout set docs coderd/apidoc - name: Sync it with the default historical pipeline env: TAG: ${{ steps.ref.outputs.tag }} diff --git a/.github/workflows/publish-version.yml b/.github/workflows/publish-version.yml index f3404306..fcb0af0c 100644 --- a/.github/workflows/publish-version.yml +++ b/.github/workflows/publish-version.yml @@ -376,7 +376,10 @@ jobs: repository: ${{ env.CONTENT_REPOSITORY }} ref: ${{ steps.resolve.outputs.sha }} path: content - sparse-checkout: docs + # coderd/apidoc holds the Swagger document the API reference is built from. + sparse-checkout: | + docs + coderd/apidoc sparse-checkout-cone-mode: true # Full history, without blobs: the sitemap dates pages from git log. fetch-depth: 0 From 61042cca5aa337b0f70db218cd04061cc4b6a76f Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:02:51 -0400 Subject: [PATCH 29/69] fix(openapi): fail a publish that has no Swagger document for a version that renders the reference When rendersOpenApi selected a version but neither swaggerFromTree nor swaggerFromClone found coderd/apidoc/swagger.json, the sync logged a warning and kept the Markdown reference, so a publish could ship the old reference with every step green. withOpenApiReference now takes an options object with `required`, which both sync scripts set from DOCS_PUBLISH=1, the same switch that already makes the release schedule mandatory; local and preview builds still warn and fall back. Assisted-by: AI --- apps/docs/scripts/sync-docs.mjs | 4 +++- apps/offlinedocs/scripts/sync-docs.mjs | 4 +++- packages/docs-build/src/index.ts | 1 + .../docs-build/src/openapi-output.test.ts | 20 +++++++++++++++++-- packages/docs-build/src/openapi-output.ts | 13 ++++++++++-- 5 files changed, 36 insertions(+), 6 deletions(-) diff --git a/apps/docs/scripts/sync-docs.mjs b/apps/docs/scripts/sync-docs.mjs index 8ff153c6..d094f1fe 100644 --- a/apps/docs/scripts/sync-docs.mjs +++ b/apps/docs/scripts/sync-docs.mjs @@ -147,7 +147,9 @@ for (const version of latestLastSyncOrder(versions)) { const swagger = single ? await swaggerFromTree(process.env.DOCS_ROOT) : await swaggerFromClone(cacheDir, version.ref); - source = await withOpenApiReference(appDir, version, source, swagger); + source = await withOpenApiReference(appDir, version, source, swagger, { + required: process.env.DOCS_PUBLISH === "1", + }); } result = await syncDocSource(source, { contentDir: path.join(appDir, "content", version.id), diff --git a/apps/offlinedocs/scripts/sync-docs.mjs b/apps/offlinedocs/scripts/sync-docs.mjs index b7977a1c..00140a6d 100644 --- a/apps/offlinedocs/scripts/sync-docs.mjs +++ b/apps/offlinedocs/scripts/sync-docs.mjs @@ -69,7 +69,9 @@ if ((process.env.DOCS_ROOT || process.env.DOCS_REPO) && rendersOpenApi(version)) const swagger = process.env.DOCS_ROOT ? await swaggerFromTree(process.env.DOCS_ROOT) : await swaggerFromClone(path.join(appDir, ".cache", "docs-clone"), version.ref); - source = await withOpenApiReference(appDir, version, source, swagger); + source = await withOpenApiReference(appDir, version, source, swagger, { + required: process.env.DOCS_PUBLISH === "1", + }); } const result = await syncDocSource(source, { contentDir: path.join(appDir, "content", "docs"), diff --git a/packages/docs-build/src/index.ts b/packages/docs-build/src/index.ts index e47c4d19..98e3eef2 100644 --- a/packages/docs-build/src/index.ts +++ b/packages/docs-build/src/index.ts @@ -23,3 +23,4 @@ export type { OpenApiReference, OpenApiSchemas, } from "./openapi-reference.js"; +export type { WithOpenApiReferenceOptions } from "./openapi-output.js"; diff --git a/packages/docs-build/src/openapi-output.test.ts b/packages/docs-build/src/openapi-output.test.ts index 8a4fce4a..723ad790 100644 --- a/packages/docs-build/src/openapi-output.test.ts +++ b/packages/docs-build/src/openapi-output.test.ts @@ -64,7 +64,9 @@ test("a corpus with its own versions, such as the fixture, can set its own floor test("the version's reference data is written where the page renderer reads it", async () => { const appDir = await mkdtemp(path.join(tmpdir(), "openapi-output-")); - const next = await withOpenApiReference(appDir, { id: "2.38" }, source, swagger, quiet); + const next = await withOpenApiReference(appDir, { id: "2.38" }, source, swagger, { + logger: quiet, + }); assert.ok(next.files.some((file) => file.path === "reference/api/users/create-new-user.md")); const data = JSON.parse(await readFile(path.join(openApiDataDir(appDir), "2.38.json"), "utf8")); assert.deepEqual(Object.keys(data).sort(), [ @@ -81,7 +83,21 @@ test("the version's reference data is written where the page renderer reads it", test("a version without a Swagger document keeps its Markdown reference and writes nothing", async () => { const appDir = await mkdtemp(path.join(tmpdir(), "openapi-output-")); - const next = await withOpenApiReference(appDir, { id: "2.10" }, source, undefined, quiet); + const next = await withOpenApiReference(appDir, { id: "2.10" }, source, undefined, { + logger: quiet, + }); assert.equal(next, source); await assert.rejects(stat(openApiDataDir(appDir)), { code: "ENOENT" }); }); + +test("a publish fails rather than ship a selected version without its Swagger document", async () => { + const appDir = await mkdtemp(path.join(tmpdir(), "openapi-output-")); + await assert.rejects( + withOpenApiReference(appDir, { id: "2.38" }, source, undefined, { + logger: quiet, + required: true, + }), + /2\.38: no Swagger document \(coderd\/apidoc\/swagger\.json\)/, + ); + await assert.rejects(stat(openApiDataDir(appDir)), { code: "ENOENT" }); +}); diff --git a/packages/docs-build/src/openapi-output.ts b/packages/docs-build/src/openapi-output.ts index 2e11a5d0..cd21abe7 100644 --- a/packages/docs-build/src/openapi-output.ts +++ b/packages/docs-build/src/openapi-output.ts @@ -8,6 +8,12 @@ import { applyOpenApiReference } from "./openapi-reference.js"; export const openApiDataDir = (appDir: string): string => path.join(appDir, ".generated", "openapi"); +export interface WithOpenApiReferenceOptions { + logger?: Pick; + /** Throw instead of keeping the Markdown reference when there is no Swagger document: set for a publish. */ + required?: boolean; +} + /** The oldest line whose Swagger document converts cleanly; older lines repeat operation ids. */ export const OPENAPI_MIN_LINE = "2.24"; @@ -35,10 +41,13 @@ export async function withOpenApiReference( version: { id: string }, source: DocSource, swagger: unknown, - logger: Pick = console, + options: WithOpenApiReferenceOptions = {}, ): Promise { + const { logger = console, required = false } = options; if (swagger === undefined) { - logger.warn(`[sync] ${version.id}: no Swagger document; keeping the Markdown API reference`); + const message = `${version.id}: no Swagger document (coderd/apidoc/swagger.json)`; + if (required) throw new Error(`${message}, so a publish would ship the Markdown API reference`); + logger.warn(`[sync] ${message}; keeping the Markdown API reference`); return source; } const started = Date.now(); From d76947301d8e5651e12ae628b43b667e03456366 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:03:48 -0400 Subject: [PATCH 30/69] fix(offlinedocs): read the API reference data whatever DOCS_VERSION names The sync wrote the reference data as .json while lib/openapi.ts always read main.json, so an export with DOCS_VERSION=v2.38.1, the usage the offline kit documents, built green with every operation page reduced to its bare method-and-path stub. The single-version export now writes and reads one fixed name, docs.json, through a shared openApiDataFile helper, and withOpenApiReference takes a dataId option for it. Assisted-by: AI --- apps/offlinedocs/lib/openapi.ts | 4 +- apps/offlinedocs/scripts/sync-docs.mjs | 2 + apps/offlinedocs/scripts/sync-helpers.mjs | 9 ++++ .../offlinedocs/scripts/sync-helpers.test.mjs | 46 ++++++++++++++++++- .../docs-build/src/openapi-output.test.ts | 10 ++++ packages/docs-build/src/openapi-output.ts | 6 ++- 6 files changed, 72 insertions(+), 5 deletions(-) diff --git a/apps/offlinedocs/lib/openapi.ts b/apps/offlinedocs/lib/openapi.ts index d3a09684..0ba99ca7 100644 --- a/apps/offlinedocs/lib/openapi.ts +++ b/apps/offlinedocs/lib/openapi.ts @@ -1,12 +1,12 @@ import { readFile } from "node:fs/promises"; -import path from "node:path"; import { type OpenApiPagesData, createOpenApiRenderBody } from "@coder/docs-next/openapi"; +import { openApiDataFile } from "../scripts/sync-helpers.mjs"; let cached: Promise | undefined; // Read at render time rather than imported, so the document stays out of the server bundle. function load(): Promise { - cached ??= readFile(path.join(process.cwd(), ".generated", "openapi", "main.json"), "utf8").then( + cached ??= readFile(openApiDataFile(process.cwd()), "utf8").then( (text) => JSON.parse(text) as OpenApiPagesData, (error: NodeJS.ErrnoException) => { if (error.code === "ENOENT") return undefined; diff --git a/apps/offlinedocs/scripts/sync-docs.mjs b/apps/offlinedocs/scripts/sync-docs.mjs index 00140a6d..f587575a 100644 --- a/apps/offlinedocs/scripts/sync-docs.mjs +++ b/apps/offlinedocs/scripts/sync-docs.mjs @@ -30,6 +30,7 @@ import { } from "@coder/docs-sources"; import { assertDeployHasCorpus, + OPENAPI_DATA_ID, exportVersionFromEnv, githubBlobSourceLink, redactRepoUrl, @@ -71,6 +72,7 @@ if ((process.env.DOCS_ROOT || process.env.DOCS_REPO) && rendersOpenApi(version)) : await swaggerFromClone(path.join(appDir, ".cache", "docs-clone"), version.ref); source = await withOpenApiReference(appDir, version, source, swagger, { required: process.env.DOCS_PUBLISH === "1", + dataId: OPENAPI_DATA_ID, }); } const result = await syncDocSource(source, { diff --git a/apps/offlinedocs/scripts/sync-helpers.mjs b/apps/offlinedocs/scripts/sync-helpers.mjs index 434d736f..e460cbb6 100644 --- a/apps/offlinedocs/scripts/sync-helpers.mjs +++ b/apps/offlinedocs/scripts/sync-helpers.mjs @@ -2,6 +2,8 @@ // tested without running a sync. Kept app-local (duplicated in offlinedocs) // until @coder/docs-sources exports shared equivalents. +import path from "node:path"; + /** * Strip URL userinfo (`user:token@`) from a repo URL before it reaches any * console output or error message, so a token-in-URL setup never leaks to @@ -78,3 +80,10 @@ export function exportVersionFromEnv(env) { ); return { id: match[1], label: `v${match[1]}`, ref, latest: true }; } + +/** The API reference data's file name: fixed, not the version id, so any DOCS_VERSION finds it. */ +export const OPENAPI_DATA_ID = "docs"; + +/** Where `lib/openapi.ts` reads the API reference data the sync wrote. */ +export const openApiDataFile = (appDir) => + path.join(appDir, ".generated", "openapi", `${OPENAPI_DATA_ID}.json`); diff --git a/apps/offlinedocs/scripts/sync-helpers.test.mjs b/apps/offlinedocs/scripts/sync-helpers.test.mjs index e204c110..5e771002 100644 --- a/apps/offlinedocs/scripts/sync-helpers.test.mjs +++ b/apps/offlinedocs/scripts/sync-helpers.test.mjs @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; -import { readFile } from "node:fs/promises"; +import { mkdtemp, readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; import path from "node:path"; import { test } from "node:test"; import { fileURLToPath } from "node:url"; @@ -8,11 +9,14 @@ import { compileVercelHeaders, headersForPath, } from "../../docs/scripts/vercel-headers.mjs"; +import { withOpenApiReference } from "@coder/docs-build"; import { buildOutputConfig } from "./build-output-helpers.mjs"; import { + OPENAPI_DATA_ID, assertDeployHasCorpus, exportVersionFromEnv, githubBlobSourceLink, + openApiDataFile, redactRepoUrl, } from "./sync-helpers.mjs"; @@ -202,3 +206,43 @@ test("a DOCS_VERSION that isn't a version or main fails the sync", () => { assert.throws(() => exportVersionFromEnv({ DOCS_VERSION: value }), /DOCS_VERSION/, value); } }); + +const swagger = JSON.parse( + await readFile(new URL("../../docs/fixtures/openapi/swagger.json", import.meta.url), "utf8"), +); + +const source = { + files: [ + { path: "reference/api/index.md", content: "# REST API\n" }, + { path: "reference/api/users.md", content: "# Users\n" }, + { path: "reference/api/workspaces.md", content: "# Workspaces\n" }, + { path: "reference/api/schemas.md", content: "# Schemas\n" }, + ], + images: [], + manifest: { + versions: ["main"], + routes: [ + { + title: "REST API", + path: "./reference/api/index.md", + children: [ + { title: "Users", path: "./reference/api/users.md" }, + { title: "Workspaces", path: "./reference/api/workspaces.md" }, + { title: "Schemas", path: "./reference/api/schemas.md" }, + ], + }, + ], + }, +}; + +test("the reference data of a release export is where lib/openapi.ts reads it", async () => { + const exportDir = await mkdtemp(path.join(tmpdir(), "offline-openapi-")); + const version = exportVersionFromEnv({ DOCS_VERSION: "v2.38.1" }); + assert.equal(version.id, "2.38.1"); + await withOpenApiReference(exportDir, version, source, swagger, { + logger: { log() {}, warn() {} }, + dataId: OPENAPI_DATA_ID, + }); + const data = JSON.parse(await readFile(openApiDataFile(exportDir), "utf8")); + assert.ok(data.operations["reference/api/users/create-new-user"]); +}); diff --git a/packages/docs-build/src/openapi-output.test.ts b/packages/docs-build/src/openapi-output.test.ts index 723ad790..df945cf7 100644 --- a/packages/docs-build/src/openapi-output.test.ts +++ b/packages/docs-build/src/openapi-output.test.ts @@ -101,3 +101,13 @@ test("a publish fails rather than ship a selected version without its Swagger do ); await assert.rejects(stat(openApiDataDir(appDir)), { code: "ENOENT" }); }); + +test("a caller can name the data file, as the single-version offline export does", async () => { + const appDir = await mkdtemp(path.join(tmpdir(), "openapi-output-")); + await withOpenApiReference(appDir, { id: "2.38.1" }, source, swagger, { + logger: quiet, + dataId: "docs", + }); + const data = JSON.parse(await readFile(path.join(openApiDataDir(appDir), "docs.json"), "utf8")); + assert.equal(data.landing.route, "reference/api"); +}); diff --git a/packages/docs-build/src/openapi-output.ts b/packages/docs-build/src/openapi-output.ts index cd21abe7..80675301 100644 --- a/packages/docs-build/src/openapi-output.ts +++ b/packages/docs-build/src/openapi-output.ts @@ -12,6 +12,8 @@ export interface WithOpenApiReferenceOptions { logger?: Pick; /** Throw instead of keeping the Markdown reference when there is no Swagger document: set for a publish. */ required?: boolean; + /** The data file's name, without `.json`; defaults to the version id. */ + dataId?: string; } /** The oldest line whose Swagger document converts cleanly; older lines repeat operation ids. */ @@ -43,7 +45,7 @@ export async function withOpenApiReference( swagger: unknown, options: WithOpenApiReferenceOptions = {}, ): Promise { - const { logger = console, required = false } = options; + const { logger = console, required = false, dataId = version.id } = options; if (swagger === undefined) { const message = `${version.id}: no Swagger document (coderd/apidoc/swagger.json)`; if (required) throw new Error(`${message}, so a publish would ship the Markdown API reference`); @@ -54,7 +56,7 @@ export async function withOpenApiReference( const { source: next, reference } = await applyOpenApiReference(source, swagger); await mkdir(openApiDataDir(appDir), { recursive: true }); await writeFile( - path.join(openApiDataDir(appDir), `${version.id}.json`), + path.join(openApiDataDir(appDir), `${dataId}.json`), JSON.stringify({ document: reference.document, operations: reference.operations, From ba6389c829bada40b14674cd3f447f0493336d49 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:04:45 -0400 Subject: [PATCH 31/69] fix(openapi): let DOCS_OPENAPI reach the sync under turbo and fail on a value it doesn't know DOCS_OPENAPI is the rollback lever for the generated REST API reference, but turbo's strict env mode stripped it from the sync task, so `DOCS_OPENAPI=0 pnpm turbo run build --filter=@coder/docs-site`, the way the publisher builds, still rendered the new reference. It is now declared on `sync`, the only task that reads it; the app builds never call rendersOpenApi, so they don't list it. Only the exact string `0` turned it off before; now 0, false, off and no do in any case, and a value that is neither an off nor an on spelling throws, so a mistyped rollback can't silently ship the new reference. Assisted-by: AI --- apps/docs/README.md | 3 +++ packages/docs-build/src/openapi-output.test.ts | 18 +++++++++++++++--- packages/docs-build/src/openapi-output.ts | 13 +++++++++++-- turbo.json | 3 ++- 4 files changed, 31 insertions(+), 6 deletions(-) diff --git a/apps/docs/README.md b/apps/docs/README.md index c64665b8..b69f2ddc 100644 --- a/apps/docs/README.md +++ b/apps/docs/README.md @@ -122,6 +122,7 @@ This is the mode the public site is built in: the per-version publisher uses it | `DOCS_SITE_URL` | `https://coder.com/beta-docs` | Optional; the public origin plus base path, for `og:url` and the canonical link. | | `DOCS_HOME_URL` | `https://coder.com/` | Optional; the main site the sidebar footer links back to. | | `DOCS_ANALYTICS` | `1` | Optional; loads coder.com's consent manager and tag manager; see "Analytics". | +| `DOCS_OPENAPI` | `0` | Optional; `0`, `false`, `off` or `no` keeps the Markdown REST API reference. | A local single-version build, against a real coder/coder clone: @@ -136,6 +137,8 @@ Every task the publisher's `pnpm turbo run build --filter=@coder/docs-site` touc The build task declares the two social-card variables for the same reason: stripped, they take the preview image off every published page with nothing failing. `DOCS_HOME_URL` is declared there too; stripped, the published pages would lose their link back to the main site the same silent way. `DOCS_ANALYTICS` is declared for the same reason. +`DOCS_OPENAPI`, the switch that rolls the REST API reference back to Markdown, is declared on `sync`, the only task that reads it; stripped, the rollback would do nothing. +Any value other than the off and on spellings (`1`, `true`, `on`, `yes` or empty) fails the sync, so a mistyped rollback never ships the new reference silently. ### The corpus guard diff --git a/packages/docs-build/src/openapi-output.test.ts b/packages/docs-build/src/openapi-output.test.ts index df945cf7..0079d30f 100644 --- a/packages/docs-build/src/openapi-output.test.ts +++ b/packages/docs-build/src/openapi-output.test.ts @@ -52,9 +52,21 @@ test(`main and every line or tag from ${OPENAPI_MIN_LINE} render the reference; for (const id of ["2.23", "2.23.9", "2.9"]) assert.equal(rendersOpenApi({ id }, {}), false, id); }); -test("DOCS_OPENAPI=0 keeps Markdown for every version", () => { - for (const id of ["main", "2.38"]) - assert.equal(rendersOpenApi({ id }, { DOCS_OPENAPI: "0" }), false); +test("DOCS_OPENAPI=0, false, off or no, in any case, keeps Markdown for every version", () => { + for (const value of ["0", "false", "off", "no", "FALSE", "Off", " no "]) + for (const id of ["main", "2.38"]) + assert.equal(rendersOpenApi({ id }, { DOCS_OPENAPI: value }), false, value); +}); + +test("DOCS_OPENAPI unset, empty, 1, true, on or yes renders the reference", () => { + assert.equal(rendersOpenApi({ id: "main" }, {}), true); + for (const value of ["", "1", "true", "on", "yes", "TRUE"]) + assert.equal(rendersOpenApi({ id: "main" }, { DOCS_OPENAPI: value }), true, value); +}); + +test("an unrecognised DOCS_OPENAPI fails the sync rather than being ignored", () => { + for (const value of ["disabled", "nope", "2"]) + assert.throws(() => rendersOpenApi({ id: "main" }, { DOCS_OPENAPI: value }), /DOCS_OPENAPI/); }); test("a corpus with its own versions, such as the fixture, can set its own floor line", () => { diff --git a/packages/docs-build/src/openapi-output.ts b/packages/docs-build/src/openapi-output.ts index 80675301..6a651ae9 100644 --- a/packages/docs-build/src/openapi-output.ts +++ b/packages/docs-build/src/openapi-output.ts @@ -19,13 +19,22 @@ export interface WithOpenApiReferenceOptions { /** The oldest line whose Swagger document converts cleanly; older lines repeat operation ids. */ export const OPENAPI_MIN_LINE = "2.24"; -/** Whether a version renders the generated reference: main and every line or tag from `minLine`, unless DOCS_OPENAPI=0. */ +const OPENAPI_OFF = new Set(["0", "false", "off", "no"]); +const OPENAPI_ON = new Set(["", "1", "true", "on", "yes"]); + +/** Whether a version renders the generated reference: main and every line or tag from `minLine`, unless DOCS_OPENAPI turns it off. */ export function rendersOpenApi( version: { id: string }, env: Record = process.env, minLine: string = OPENAPI_MIN_LINE, ): boolean { - if (env.DOCS_OPENAPI === "0") return false; + const value = (env.DOCS_OPENAPI ?? "").trim().toLowerCase(); + if (OPENAPI_OFF.has(value)) return false; + if (!OPENAPI_ON.has(value)) { + throw new Error( + `DOCS_OPENAPI must be 0, false, off or no to keep the Markdown reference, or 1, true, on, yes or unset to render it; got ${JSON.stringify(env.DOCS_OPENAPI)}`, + ); + } return isLineAtLeast(version.id, minLine); } diff --git a/turbo.json b/turbo.json index a0decdff..757b3e67 100644 --- a/turbo.json +++ b/turbo.json @@ -32,7 +32,8 @@ "DOCS_ENGINE_SHA", "DOCS_PUBLISH", "DOCS_GITHUB_TOKEN", - "DOCS_RELEASE_SCHEDULE_FILE" + "DOCS_RELEASE_SCHEDULE_FILE", + "DOCS_OPENAPI" ] }, // The app builds consume content/ and public/ written by the uncacheable From 4658d8487ab067bc7c389cebe48baaa1c6497cff Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:06:06 -0400 Subject: [PATCH 32/69] fix(docs-sources): tell a missing Swagger document apart from a failed git read swaggerFromClone treated every `git show` failure other than the size cap as "this ref has no Swagger document", so a missing git, a broken clone or a failed lazy blob fetch on a blob:none clone quietly kept one version on the Markdown reference while the others switched. It now resolves the ref and then the path with `rev-parse --verify --quiet`, whose exit status 1 means "names nothing", reads the blob by id, and rethrows every other failure. A ref that resolves to no commit at all now throws instead of returning undefined, since the provider has already loaded that ref's docs. `--end-of-options` keeps a ref that starts with a dash from being read as an option. Assisted-by: AI --- packages/docs-sources/src/swagger.test.ts | 34 +++++++++++++++++--- packages/docs-sources/src/swagger.ts | 38 ++++++++++++++++++----- 2 files changed, 60 insertions(+), 12 deletions(-) diff --git a/packages/docs-sources/src/swagger.test.ts b/packages/docs-sources/src/swagger.test.ts index 3322c42c..2f908f04 100644 --- a/packages/docs-sources/src/swagger.test.ts +++ b/packages/docs-sources/src/swagger.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { mkdir, mkdtemp, symlink, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, stat, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { test } from "node:test"; @@ -44,16 +44,42 @@ test("invalid JSON is reported without the file's content", async () => { }); }); -test("reads the Swagger document at a ref of a clone, and nothing at a ref without one", async () => { +async function clone() { const root = await checkout(); - await writeFile(path.join(root, "coderd", "apidoc", "swagger.json"), '{"swagger":"2.0"}'); + await writeFile(path.join(root, "docs", "index.md"), "# Docs\n"); const git = (...args: string[]) => execFileSync("git", ["-C", root, "-c", "user.name=t", "-c", "user.email=t@t", ...args]); git("init", "-q", "-b", "main"); git("add", "-A"); + git("commit", "-q", "-m", "docs only"); + git("tag", "v0"); + await writeFile(path.join(root, "coderd", "apidoc", "swagger.json"), '{"swagger":"2.0"}'); + git("add", "-A"); git("commit", "-q", "-m", "swagger"); git("tag", "v1"); + return root; +} + +test("reads the Swagger document at a ref of a clone, and nothing at a ref without one", async () => { + const root = await clone(); assert.deepEqual(await swaggerFromClone(root, "main"), { swagger: "2.0" }); assert.deepEqual(await swaggerFromClone(root, "v1"), { swagger: "2.0" }); - assert.equal(await swaggerFromClone(root, "no-such-ref"), undefined); + assert.equal(await swaggerFromClone(root, "v0"), undefined); +}); + +test("a ref the clone doesn't have fails rather than reading as no Swagger document", async () => { + const root = await clone(); + await assert.rejects(swaggerFromClone(root, "no-such-ref"), /no-such-ref/); +}); + +test("a broken clone fails rather than reading as no Swagger document", async () => { + const notAClone = await mkdtemp(path.join(tmpdir(), "openapi-source-")); + await assert.rejects(swaggerFromClone(notAClone, "main")); +}); + +test("a ref that starts with a dash is never read as a git option", async () => { + const root = await clone(); + const out = path.join(await mkdtemp(path.join(tmpdir(), "openapi-source-")), "written"); + await assert.rejects(swaggerFromClone(root, `--output=${out}`)); + await assert.rejects(stat(out), { code: "ENOENT" }); }); diff --git a/packages/docs-sources/src/swagger.ts b/packages/docs-sources/src/swagger.ts index 70aa6b26..87950883 100644 --- a/packages/docs-sources/src/swagger.ts +++ b/packages/docs-sources/src/swagger.ts @@ -28,28 +28,50 @@ export async function swaggerFromTree(docsRoot: string): Promise { return text === undefined ? undefined : parseSwagger(text, checkout); } +const errorCode = (error: unknown): unknown => + error instanceof Error && "code" in error ? error.code : undefined; + +/** The object id `spec` names in the clone, or undefined when it names nothing; any other git failure throws. */ +async function resolveObject(cacheDir: string, spec: string): Promise { + try { + const { stdout } = await execFileAsync("git", [ + "-C", + cacheDir, + "rev-parse", + "--verify", + "--quiet", + "--end-of-options", + spec, + ]); + return stdout.trim(); + } catch (error) { + if (errorCode(error) === 1) return undefined; + throw error; + } +} + /** The Swagger document at a ref of a git clone, or undefined when the ref has none. */ export async function swaggerFromClone(cacheDir: string, ref: string): Promise { for (const rev of [`refs/remotes/origin/${ref}`, `refs/tags/${ref}`, ref]) { + const commit = await resolveObject(cacheDir, `${rev}^{commit}`); + if (commit === undefined) continue; + const blob = await resolveObject(cacheDir, `${commit}:${SWAGGER_PATH}`); + if (blob === undefined) return undefined; let stdout: string; try { // A blob over the cap fails the read rather than being buffered. - ({ stdout } = await execFileAsync("git", ["-C", cacheDir, "show", `${rev}:${SWAGGER_PATH}`], { + ({ stdout } = await execFileAsync("git", ["-C", cacheDir, "cat-file", "blob", blob], { maxBuffer: DEFAULT_MAX_FILE_BYTES, })); } catch (error) { - if ( - error instanceof Error && - "code" in error && - error.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" - ) { + if (errorCode(error) === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") { throw new Error( `${SWAGGER_PATH} at ${ref} is over the ${DEFAULT_MAX_FILE_BYTES}-byte limit`, ); } - continue; + throw error; } return parseSwagger(stdout, ref); } - return undefined; + throw new Error(`${JSON.stringify(ref)} is not a branch, tag or commit of the clone`); } From baacb1e1d986297b8f091ff1284adff42f045209 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:07:40 -0400 Subject: [PATCH 33/69] fix(docs-next): keep the old-anchor redirect from crashing on #% or following #constructor decodeURIComponent throws on a malformed fragment such as #%, and the first lookup runs inside the effect, so a mangled old link took every tag page and the schemas page down to the error boundary. The lookup also read inherited keys, so #constructor navigated to the text of Object's constructor. A fragment that doesn't decode is now ignored, and only the targets' own keys redirect. The existing test created a filter input that AnchorRedirect never read; it now renders the real SchemaTables beside the redirect, types a filter, checks the count narrowed, and then follows a late hash. Assisted-by: AI --- .../src/openapi/anchor-redirect.test.tsx | 79 +++++++++++++++---- .../docs-next/src/openapi/anchor-redirect.tsx | 9 ++- 2 files changed, 72 insertions(+), 16 deletions(-) diff --git a/packages/docs-next/src/openapi/anchor-redirect.test.tsx b/packages/docs-next/src/openapi/anchor-redirect.test.tsx index 6873861d..bba35f43 100644 --- a/packages/docs-next/src/openapi/anchor-redirect.test.tsx +++ b/packages/docs-next/src/openapi/anchor-redirect.test.tsx @@ -1,25 +1,76 @@ import assert from "node:assert/strict"; -import test from "node:test"; -import { act } from "react"; +import test, { type TestContext } from "node:test"; +import { act, type ReactNode } from "react"; import { createRoot } from "react-dom/client"; import { AnchorRedirect } from "./anchor-redirect.js"; +import { SchemaTables } from "./schemas.js"; +const PAGE = "/reference/api/schemas/"; // A same-page target, so jsdom follows the redirect as a fragment navigation. -const TARGET = "/reference/api/schemas/#redirected"; +const TARGET = `${PAGE}#redirected`; +const targets = { codersdkuser: TARGET }; -test("a hash that arrives after the page loaded, with a filter typed, still redirects", async () => { - window.history.replaceState(null, "", "/reference/api/schemas/"); - const container = document.createElement("div"); - const input = container.appendChild(document.createElement("input")); - input.type = "search"; - input.value = "user"; - document.body.appendChild(container); - const root = createRoot(container.appendChild(document.createElement("div"))); - await act(async () => root.render()); +async function mount(t: TestContext, url: string, node: ReactNode) { + window.history.replaceState(null, "", url); + const container = document.body.appendChild(document.createElement("div")); + const root = createRoot(container); + await act(async () => root.render(node)); + t.after(async () => { + await act(async () => root.unmount()); + container.remove(); + }); + return container; +} + +// jsdom reports a navigation away from the document, which it doesn't implement, through console.error. +function navigationsAway(t: TestContext) { + const error = t.mock.method(console, "error", () => {}); + return () => + error.mock.calls.filter((call) => String(call.arguments[0]).includes("navigation")).length; +} + +test("a hash that arrives after the page loaded, with a filter typed, still redirects", async (t) => { + const container = await mount( + t, + PAGE, + <> + undefined} + /> + + , + ); + const input = container.querySelector("input") as HTMLInputElement; + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, "user"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + assert.equal(container.querySelector('[aria-live="polite"]')?.textContent, "1 of 2 schemas"); assert.equal(window.location.hash, ""); window.location.hash = "codersdkuser"; window.dispatchEvent(new HashChangeEvent("hashchange")); assert.equal(window.location.hash, "#redirected"); - await act(async () => root.unmount()); - container.remove(); +}); + +test("a malformed hash such as #% is ignored instead of taking the page down", async (t) => { + const container = await mount( + t, + `${PAGE}#%`, + <> +

Schemas

+ + , + ); + assert.ok(container.querySelector("[data-still-here]")); + assert.equal(window.location.hash, "#%"); +}); + +test("an inherited key such as #constructor is not a target", async (t) => { + const navigations = navigationsAway(t); + await mount(t, `${PAGE}#constructor`, ); + window.location.hash = "toString"; + window.dispatchEvent(new HashChangeEvent("hashchange")); + assert.equal(navigations(), 0); + assert.equal(window.location.pathname, PAGE); }); diff --git a/packages/docs-next/src/openapi/anchor-redirect.tsx b/packages/docs-next/src/openapi/anchor-redirect.tsx index acad8ccb..2aa005bd 100644 --- a/packages/docs-next/src/openapi/anchor-redirect.tsx +++ b/packages/docs-next/src/openapi/anchor-redirect.tsx @@ -6,8 +6,13 @@ import { useEffect } from "react"; export function AnchorRedirect({ targets }: { targets: Record }) { useEffect(() => { const follow = () => { - const anchor = decodeURIComponent(window.location.hash.slice(1)); - const target = anchor ? targets[anchor] : undefined; + let anchor: string; + try { + anchor = decodeURIComponent(window.location.hash.slice(1)); + } catch { + return; + } + const target = Object.hasOwn(targets, anchor) ? targets[anchor] : undefined; if (target) window.location.replace(target); }; follow(); From f833e9d0594ac49e72f7aaacdf1cca9e7bf2519b Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:11:28 -0400 Subject: [PATCH 34/69] fix(docs-build): cap the card description's input before the quadratic link pattern The link-stripping pattern in firstSentence is quadratic, so a description opening with 100,000 `[` characters took about 4.5 s under the 25 MiB file cap, and a preview builds from a coder/coder PR's own Swagger document. Only the first sentence, at most 200 characters, is kept, so the input is cut to 2,000 characters first. A sentence with no space in its first 200 characters is now cut at 199 instead of being kept whole. Assisted-by: AI --- packages/docs-build/src/openapi-reference.test.ts | 9 +++++++++ packages/docs-build/src/openapi-reference.ts | 9 +++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index 14147a75..3b6e5d3f 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -175,6 +175,15 @@ test("a card's description is the first sentence of the operation's, as plain te assert.equal(op?.description, "Lists workspaces with q."); }); +test("a description that opens with a long run of [ takes no longer than an ordinary one", async () => { + const hostile = structuredClone(swagger); + hostile.paths["/api/v2/workspaces"].get.description = "[".repeat(100_000); + const started = performance.now(); + const { reference } = await applyOpenApiReference(source, hostile); + assert.ok(performance.now() - started < 1000, `took ${performance.now() - started} ms`); + assert.ok((reference.landing.sections[1]?.operations[0]?.description?.length ?? 0) <= 201); +}); + test("section ids never repeat a heading the landing page already has", async () => { const { reference } = await applyOpenApiReference( withLanding("# REST API\n\n## Users\n\n## Set up your environment\n"), diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index a430dba7..26b39536 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -473,7 +473,11 @@ function withSetupSection(content: string): { /** The first sentence of an operation's Markdown description, as plain text for its card. */ function firstSentence(markdown: string | undefined): string | undefined { - const paragraph = markdown?.trim().split(/\n\s*\n/)[0]; + // The link pattern below is quadratic, and only the first 200 characters are kept. + const paragraph = markdown + ?.trim() + .slice(0, 2000) + .split(/\n\s*\n/)[0]; if (!paragraph) return undefined; const text = paragraph .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") @@ -482,5 +486,6 @@ function firstSentence(markdown: string | undefined): string | undefined { .trim(); const sentence = /^.*?[.!?](?=\s|$)/.exec(text)?.[0] ?? text; if (sentence.length <= 200) return sentence || undefined; - return `${sentence.slice(0, sentence.lastIndexOf(" ", 199))}…`; + const space = sentence.lastIndexOf(" ", 199); + return `${sentence.slice(0, space > 0 ? space : 199)}…`; } From 844a8228f3064c32b6489d0953057b264d3d834a Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:12:21 -0400 Subject: [PATCH 35/69] fix(docs-build): fail when two generated API reference pages would share a path or route coder/coder owns the tag and summary names the page paths come from, and nothing checked them: tags that differ only in case or punctuation share a tagSlug and overwrote each other's page and sidebar children, a tag named Schemas or Index silently replaced the schemas or landing page, and a tag or summary with no sluggable characters produced a nameless page. Every generated page now goes through one writer that throws on a second write to the same path, an empty slug throws, and a generated page whose route another page already has (an operation summarised as Index beside its tag page) throws naming both files. Assisted-by: AI --- .../docs-build/src/openapi-reference.test.ts | 50 +++++++++++++++++++ packages/docs-build/src/openapi-reference.ts | 28 +++++++++-- 2 files changed, 73 insertions(+), 5 deletions(-) diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index 3b6e5d3f..e3aa1083 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -107,6 +107,56 @@ test("summaries are escaped where the tag and schemas pages put them in Markdown assert.match(tagPage ?? "", /- \[List \\\[all\\\] a\\\|b \\\\ \\\*workspaces\\\*\]\(/); }); +function retagged(changes: { tag?: string; summary?: string }[]) { + const doc = structuredClone(swagger); + const ops = [ + doc.paths["/api/v2/workspaces"].get, + doc.paths["/api/v2/users"].post, + doc.paths["/api/v2/users/{user}"].get, + ]; + changes.forEach((change, index) => { + if (change.tag !== undefined) ops[index].tags = [change.tag]; + if (change.summary !== undefined) ops[index].summary = change.summary; + }); + return doc; +} + +test("two tags that differ only in case or punctuation fail instead of overwriting each other", async () => { + await assert.rejects( + applyOpenApiReference(source, retagged([{ tag: "Templates" }, { tag: "templates" }])), + /reference\/api\/templates\.md is generated twice/, + ); +}); + +test("a tag named Schemas or Index fails instead of replacing the schemas or landing page", async () => { + await assert.rejects( + applyOpenApiReference(source, retagged([{ tag: "Schemas" }])), + /reference\/api\/schemas\.md is generated twice/, + ); + await assert.rejects( + applyOpenApiReference(source, retagged([{ tag: "Index" }])), + /reference\/api\/index\.md is generated twice/, + ); +}); + +test("an operation summarised as Index fails instead of taking its tag page's route", async () => { + await assert.rejects( + applyOpenApiReference(source, retagged([{}, { summary: "Index" }])), + /reference\/api\/users\/index\.md and reference\/api\/users\.md share the route reference\/api\/users/, + ); +}); + +test("a tag or summary with nothing to slug fails instead of writing a nameless page", async () => { + await assert.rejects( + applyOpenApiReference(source, retagged([{ tag: "!!!" }])), + /tag "!!!" has no characters to name its page by/, + ); + await assert.rejects( + applyOpenApiReference(source, retagged([{ summary: "!!!" }])), + /summary "!!!" has no characters to name its page by/, + ); +}); + const withLanding = (content: string): DocSource => ({ ...source, files: source.files.map((file) => diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 26b39536..8a496cde 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -70,6 +70,8 @@ export interface ApplyOpenApiReferenceOptions { const isObject = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value); +const UNNAMEABLE = "has no characters to name its page by"; + export const tagSlug = (tag: string): string => tag.toLowerCase().replace(/[^a-z0-9]/g, ""); // Summaries are plain text: escape what Markdown would read as link, table, or emphasis syntax. @@ -249,25 +251,32 @@ export async function applyOpenApiReference( Array.isArray(operation.tags) && typeof operation.tags[0] === "string" ? operation.tags[0] : "General"; + if (!tagSlug(tag)) throw new Error(`tag ${JSON.stringify(tag)} ${UNNAMEABLE}`); let group = byTag.get(tag); if (!group) byTag.set(tag, (group = { slugger: new GithubSlugger(), ops: [] })); const summary = typeof operation.summary === "string" ? operation.summary : `${method.toUpperCase()} ${route}`; + const slug = group.slugger.slug(summary); + if (!slug) throw new Error(`summary ${JSON.stringify(summary)} ${UNNAMEABLE}`); group.ops.push({ method, path: route, summary, description: typeof operation.description === "string" ? operation.description : undefined, deprecated: operation.deprecated === true, - file: `${dir}/${tagSlug(tag)}/${group.slugger.slug(summary)}.md`, + file: `${dir}/${tagSlug(tag)}/${slug}.md`, depths: schemaDepths([operation, item.parameters], schemas), }); } } const generated = new Map(); + const put = (path: string, content: string) => { + if (generated.has(path)) throw new Error(`${path} is generated twice`); + generated.set(path, content); + }; const tagFile = (tag: string) => `${dir}/${tagSlug(tag)}.md`; for (const [tag, { ops }] of byTag) { const items = ops.map( @@ -275,7 +284,7 @@ export async function applyOpenApiReference( `- [${linkText(op.summary)}](./${op.file.slice(dir.length + 1)}): \`${op.method.toUpperCase()} ${op.path}\``, ); const description = tagInfo.get(tag); - generated.set( + put( tagFile(tag), `${frontmatter(tag)}${description ? `${description}\n\n` : ""}${items.join("\n")}\n`, ); @@ -283,7 +292,7 @@ export async function applyOpenApiReference( const lines = [`\`${op.method.toUpperCase()} ${op.path}\``]; if (op.deprecated) lines.push("This endpoint is deprecated."); if (op.description) lines.push(op.description); - generated.set(op.file, `${frontmatter(op.summary, op.method)}${lines.join("\n\n")}\n`); + put(op.file, `${frontmatter(op.summary, op.method)}${lines.join("\n\n")}\n`); } } @@ -315,7 +324,7 @@ export async function applyOpenApiReference( } } const schemasFile = `${dir}/schemas.md`; - generated.set( + put( schemasFile, `${frontmatter("Schemas")}Each endpoint's page documents the request and response schemas it uses. This table names, for each schema, the endpoint page that shows it most directly.\n\n| Schema | Shown on |\n| --- | --- |\n${schemaRows.join("\n")}\n`, ); @@ -324,7 +333,7 @@ export async function applyOpenApiReference( const landingSource = source.files.find((file) => file.path === landingFile); if (!landingSource) throw new Error(`the source has no ${landingFile}`); const landing = withSetupSection(landingSource.content); - generated.set(landingFile, landing.content); + put(landingFile, landing.content); const files: DocFile[] = [ ...source.files.filter((file) => !generated.has(file.path)), @@ -358,6 +367,15 @@ export async function applyOpenApiReference( const mdPaths = files.map((file) => file.path).filter((path) => path.endsWith(".md")); const dirRoutes = buildDirRoutes(mdPaths); const routeOf = (file: string) => mapMdPath(file, dirRoutes).route; + const fileByRoute = new Map(); + for (const path of mdPaths) { + const route = routeOf(path); + const other = fileByRoute.get(route); + if (other !== undefined && (generated.has(path) || generated.has(other))) { + throw new Error(`${path} and ${other} share the route ${route}`); + } + fileByRoute.set(route, path); + } const operations: Record = {}; const anchors: Record> = {}; for (const [tag, { ops }] of byTag) { From b49ede50dd470cdb61673ae5887f7ff9dc21fd6c Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:12:56 -0400 Subject: [PATCH 36/69] fix(docs-build): define the CoderProvisionerKey scheme instead of dropping it GET /provisionerkeys/{provisionerkey} requires CoderProvisionerKey, a scheme coder/coder's Swagger document never declares, so the conversion dropped the requirement and left the operation with `security: []`: all four samples and the auth section said it takes no authentication. The scheme is now defined as the header coderd's provisioner daemon middleware reads, Coder-Provisioner-Daemon-Key (codersdk.ProvisionerDaemonKey), not the X-Coder-Provisioner-Key the review suggested, so the samples send it with a {CoderProvisionerKey} placeholder like the other schemes. Any other undeclared scheme is still dropped with a warning. Assisted-by: AI --- .../docs-build/src/openapi-reference.test.ts | 19 ++++++++++++++++++ packages/docs-build/src/openapi-reference.ts | 20 ++++++++++++++----- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index e3aa1083..a8d49f31 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -107,6 +107,25 @@ test("summaries are escaped where the tag and schemas pages put them in Markdown assert.match(tagPage ?? "", /- \[List \\\[all\\\] a\\\|b \\\\ \\\*workspaces\\\*\]\(/); }); +test("the undeclared CoderProvisionerKey scheme is defined as the header coderd reads", async () => { + const doc = structuredClone(swagger); + doc.paths["/api/v2/users/{user}"].get.security = [{ CoderProvisionerKey: [] }]; + doc.paths["/api/v2/users"].post.security = [{ Undeclared: [] }]; + const { reference } = await applyOpenApiReference(source, doc); + const { document: converted, warnings } = reference; + const components = converted.components as { securitySchemes: Record }; + assert.deepEqual(components.securitySchemes.CoderProvisionerKey, { + type: "apiKey", + in: "header", + name: "Coder-Provisioner-Daemon-Key", + }); + const paths = converted.paths as Record>; + assert.deepEqual(paths["/api/v2/users/{user}"]?.get?.security, [{ CoderProvisionerKey: [] }]); + assert.deepEqual(paths["/api/v2/users"]?.post?.security, []); + assert.ok(warnings.some((warning) => warning.includes("Undeclared is not defined"))); + assert.ok(!warnings.some((warning) => warning.includes("CoderProvisionerKey"))); +}); + function retagged(changes: { tag?: string; summary?: string }[]) { const doc = structuredClone(swagger); const ops = [ diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 8a496cde..5434a197 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -132,6 +132,11 @@ function withBasePathInPaths(swagger: unknown): unknown { }; } +/** Schemes coderd authenticates with but its Swagger document never declares, as `httpmw` reads them. */ +const UNDECLARED_SCHEMES: Record = { + CoderProvisionerKey: { type: "apiKey", in: "header", name: "Coder-Provisioner-Daemon-Key" }, +}; + /** Converts Swagger 2.0 to OpenAPI 3, repairs the defects that make it invalid, and validates it. */ export async function convertSwagger( swagger: unknown, @@ -149,8 +154,10 @@ export async function convertSwagger( for (const warning of converted.warnings ?? []) warnings.push(`swagger2openapi: ${JSON.stringify(warning)}`); - const components = isObject(document.components) ? document.components : {}; - const schemes = isObject(components.securitySchemes) ? components.securitySchemes : {}; + if (!isObject(document.components)) document.components = {}; + const components = document.components as Json; + if (!isObject(components.securitySchemes)) components.securitySchemes = {}; + const schemes = components.securitySchemes as Json; for (const [route, item] of Object.entries(isObject(document.paths) ? document.paths : {})) { if (!isObject(item)) continue; for (const method of HTTP_METHODS) { @@ -158,9 +165,12 @@ export async function convertSwagger( if (!isObject(operation)) continue; if (Array.isArray(operation.security)) { operation.security = operation.security.filter((requirement) => { - const unknown = Object.keys(isObject(requirement) ? requirement : {}).filter( - (name) => !(name in schemes), - ); + const unknown = Object.keys(isObject(requirement) ? requirement : {}).filter((name) => { + if (Object.hasOwn(schemes, name)) return false; + if (!Object.hasOwn(UNDECLARED_SCHEMES, name)) return true; + schemes[name] = UNDECLARED_SCHEMES[name]; + return false; + }); for (const name of unknown) { warnings.push( `${method.toUpperCase()} ${route}: security scheme ${name} is not defined; dropped`, From 64d4804a8eb89b7f16a08e9452f24de6f8a7e61e Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:14:02 -0400 Subject: [PATCH 37/69] fix(docs-build): fence an operation's path so a backtick can't end its code span The tag pages and each operation page write `METHOD /path` as a code span, and the path went in unescaped, so a backtick in it ended the span early. The span's fence is now one backtick longer than any run inside the path, padded when the path starts or ends with one. Schema names, the review's other case, can't carry a backtick or a pipe by the time they reach the schemas table: swagger2openapi rewrites component names to [A-Za-z0-9._-] (codersdk.A|B`C becomes codersdk.A_B_C), so that table is left as it is. Assisted-by: AI --- .../docs-build/src/openapi-reference.test.ts | 21 +++++++++++++++++++ packages/docs-build/src/openapi-reference.ts | 12 +++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index a8d49f31..4a24f2db 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { test } from "node:test"; import type { DocSource } from "@coder/docs-config"; +import { createProcessor } from "@mdx-js/mdx"; import { applyOpenApiReference } from "./openapi-reference.js"; const swagger = JSON.parse( @@ -176,6 +177,26 @@ test("a tag or summary with nothing to slug fails instead of writing a nameless ); }); +function inlineCode(markdown: string): string[] { + const values: string[] = []; + const visit = (node: { type: string; value?: string; children?: unknown[] }) => { + if (node.type === "inlineCode" && node.value !== undefined) values.push(node.value); + for (const child of node.children ?? []) visit(child as typeof node); + }; + visit(createProcessor({ format: "md" }).parse(markdown.replace(/^---\n[\s\S]*?\n---\n/, ""))); + return values; +} + +test("a path with a backtick stays one code span on its tag page and its own page", async () => { + const odd = structuredClone(swagger); + odd.paths["/api/v2/a`b``c"] = odd.paths["/api/v2/workspaces"]; + delete odd.paths["/api/v2/workspaces"]; + const { source: out } = await applyOpenApiReference(source, odd); + const page = (path: string) => out.files.find((file) => file.path === path)?.content ?? ""; + for (const path of ["reference/api/workspaces.md", "reference/api/workspaces/list-workspaces.md"]) + assert.deepEqual(inlineCode(page(path)), ["GET /api/v2/a`b``c"], path); +}); + const withLanding = (content: string): DocSource => ({ ...source, files: source.files.map((file) => diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 5434a197..de4b30e4 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -81,6 +81,14 @@ const linkText = (text: string): string => .replace(/\s+/g, " ") .trim(); +/** `text` as one Markdown code span, fenced by a backtick run longer than any inside it. */ +function codeSpan(text: string): string { + const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length)); + const fence = "`".repeat(longest + 1); + const pad = /^[`\s]|[`\s]$/.test(text) ? " " : ""; + return `${fence}${pad}${text}${pad}${fence}`; +} + const frontmatter = (title: string, method?: string): string => `---\ntitle: ${JSON.stringify(title)}\n${method ? `_openapi:\n method: ${method}\n` : ""}---\n\n`; @@ -291,7 +299,7 @@ export async function applyOpenApiReference( for (const [tag, { ops }] of byTag) { const items = ops.map( (op) => - `- [${linkText(op.summary)}](./${op.file.slice(dir.length + 1)}): \`${op.method.toUpperCase()} ${op.path}\``, + `- [${linkText(op.summary)}](./${op.file.slice(dir.length + 1)}): ${codeSpan(`${op.method.toUpperCase()} ${op.path}`)}`, ); const description = tagInfo.get(tag); put( @@ -299,7 +307,7 @@ export async function applyOpenApiReference( `${frontmatter(tag)}${description ? `${description}\n\n` : ""}${items.join("\n")}\n`, ); for (const op of ops) { - const lines = [`\`${op.method.toUpperCase()} ${op.path}\``]; + const lines = [codeSpan(`${op.method.toUpperCase()} ${op.path}`)]; if (op.deprecated) lines.push("This endpoint is deprecated."); if (op.description) lines.push(op.description); put(op.file, `${frontmatter(op.summary, op.method)}${lines.join("\n\n")}\n`); From d46b8c875df72b8350de54e19e08b75b9a7f4968 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:15:25 -0400 Subject: [PATCH 38/69] test(openapi): show the renderer and post-conversion $ref checks reject external references Only the pre-conversion check had a test. The renderer's check is the one that stops fumadocs-openapi's bundler fetching a URL or reading a file, so a document whose schema points at a local file holding a secret, a file:// URL or an https URL now has to be rejected before the bundler runs, without the file's content in the error; the test fails with the check removed. The post-conversion check can't be reached through applyOpenApiReference, because the pre-conversion check sees the same references first, so it moves into assertConvertedDocument and is tested on a really converted document with an external $ref put back in. Assisted-by: AI --- .../docs-build/src/openapi-reference.test.ts | 16 ++++- packages/docs-build/src/openapi-reference.ts | 7 ++- packages/docs-next/src/openapi/index.test.tsx | 58 +++++++++++++++++++ 3 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 packages/docs-next/src/openapi/index.test.tsx diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index 4a24f2db..534e232f 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -3,7 +3,7 @@ import { readFile } from "node:fs/promises"; import { test } from "node:test"; import type { DocSource } from "@coder/docs-config"; import { createProcessor } from "@mdx-js/mdx"; -import { applyOpenApiReference } from "./openapi-reference.js"; +import { applyOpenApiReference, assertConvertedDocument } from "./openapi-reference.js"; const swagger = JSON.parse( await readFile( @@ -100,6 +100,20 @@ test("a Swagger document with an external $ref is rejected before conversion", a } }); +test("a converted document with an external $ref is rejected before it can reach the renderer", async () => { + const { reference } = await applyOpenApiReference(source, swagger); + await assertConvertedDocument(reference.document); + for (const ref of ["https://example.com/schema.json", "/etc/passwd", "../x.json"]) { + const hostile = structuredClone(reference.document); + const schemas = (hostile.components as { schemas: Record }).schemas; + schemas["codersdk.User"] = { $ref: ref }; + await assert.rejects( + assertConvertedDocument(hostile), + /the converted OpenAPI document: \$ref at \/components\/schemas\/codersdk\.User\/\$ref is not an in-document reference/, + ); + } +}); + test("summaries are escaped where the tag and schemas pages put them in Markdown", async () => { const tricky = structuredClone(swagger); tricky.paths["/api/v2/workspaces"].get.summary = "List [all] a|b \\ *workspaces*"; diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index de4b30e4..4747283f 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -200,6 +200,12 @@ export async function convertSwagger( } } + await assertConvertedDocument(document); + return { document, warnings }; +} + +/** Throws when a converted document holds a `$ref` the renderer's bundler would fetch or read, or is not valid OpenAPI. */ +export async function assertConvertedDocument(document: Json): Promise { assertInDocumentRefs(document, "the converted OpenAPI document"); const result = await validate(document, { lint: false, @@ -208,7 +214,6 @@ export async function convertSwagger( resolve: false, }); if (!result.valid) throw new Error("the converted OpenAPI document is not valid"); - return { document, warnings }; } /** diff --git a/packages/docs-next/src/openapi/index.test.tsx b/packages/docs-next/src/openapi/index.test.tsx new file mode 100644 index 00000000..8cb027d2 --- /dev/null +++ b/packages/docs-next/src/openapi/index.test.tsx @@ -0,0 +1,58 @@ +import assert from "node:assert/strict"; +import { mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { createOpenApiRenderBody, type OpenApiPagesData } from "./index.js"; + +const ROUTE = "reference/api/secrets/get-secret"; + +function pagesData(spec: Record): OpenApiPagesData { + return { + document: spec, + operations: { [ROUTE]: { method: "get", path: "/api/v2/secret" } }, + anchors: {}, + landing: { route: "reference/api", setupId: "set-up-your-environment", sections: [] }, + schemas: { route: "reference/api/schemas", rows: [] }, + }; +} + +const withSchema = (schema: Record) => ({ + openapi: "3.0.3", + info: { title: "Coder API", version: "2.0" }, + paths: { + "/api/v2/secret": { + get: { + summary: "Get secret", + responses: { + "200": { + description: "OK", + content: { "application/json": { schema: { $ref: "#/components/schemas/Secret" } } }, + }, + }, + }, + }, + }, + components: { schemas: { Secret: schema } }, +}); + +test("an API document with an external $ref is rejected before the bundler can read it", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "openapi-ref-")); + const secret = path.join(dir, "secret.json"); + await writeFile(secret, JSON.stringify({ type: "string", description: "do-not-leak" })); + for (const ref of [secret, `file://${secret}`, "https://example.com/schema.json"]) { + const renderBody = createOpenApiRenderBody(async () => pagesData(withSchema({ $ref: ref }))); + await assert.rejects( + renderBody({ versionId: undefined, slugs: ROUTE.split("/"), hrefFor: (r) => `/${r}/` }), + (error: Error) => { + assert.match( + error.message, + /\$ref at \/components\/schemas\/Secret\/\$ref is not an in-document reference/, + ); + assert.doesNotMatch(error.message, /do-not-leak/); + return true; + }, + ref, + ); + } +}); From d07fa46863e2129b50439599d6e80668e564d27b Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:16:03 -0400 Subject: [PATCH 39/69] test(docs-next): pin what pruneDocument keeps of the API document pruneDocument carries the invariant that an operation page's props never hold the whole API, and nothing tested it: the route tests pass an empty document. The test prunes a document with a chain A to B to C, a schema D only another operation reaches, a cycle back from C to A and C to itself, and a path-level parameter whose schema is only reached through components.parameters, and checks the pruned page keeps exactly the operation, its path parameters, A, B, C and the parameter's schema, plus the security schemes, title and version, and that it terminates. Assisted-by: AI --- packages/docs-next/src/openapi/index.test.tsx | 70 +++++++++++++++++-- 1 file changed, 66 insertions(+), 4 deletions(-) diff --git a/packages/docs-next/src/openapi/index.test.tsx b/packages/docs-next/src/openapi/index.test.tsx index 8cb027d2..885d153c 100644 --- a/packages/docs-next/src/openapi/index.test.tsx +++ b/packages/docs-next/src/openapi/index.test.tsx @@ -3,7 +3,7 @@ import { mkdtemp, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; -import { createOpenApiRenderBody, type OpenApiPagesData } from "./index.js"; +import { createOpenApiRenderBody, type OpenApiPagesData, pruneDocument } from "./index.js"; const ROUTE = "reference/api/secrets/get-secret"; @@ -40,8 +40,8 @@ test("an API document with an external $ref is rejected before the bundler can r const dir = await mkdtemp(path.join(tmpdir(), "openapi-ref-")); const secret = path.join(dir, "secret.json"); await writeFile(secret, JSON.stringify({ type: "string", description: "do-not-leak" })); - for (const ref of [secret, `file://${secret}`, "https://example.com/schema.json"]) { - const renderBody = createOpenApiRenderBody(async () => pagesData(withSchema({ $ref: ref }))); + for (const target of [secret, `file://${secret}`, "https://example.com/schema.json"]) { + const renderBody = createOpenApiRenderBody(async () => pagesData(withSchema({ $ref: target }))); await assert.rejects( renderBody({ versionId: undefined, slugs: ROUTE.split("/"), hrefFor: (r) => `/${r}/` }), (error: Error) => { @@ -52,7 +52,69 @@ test("an API document with an external $ref is rejected before the bundler can r assert.doesNotMatch(error.message, /do-not-leak/); return true; }, - ref, + target, ); } }); + +const ref = (kind: string, name: string) => ({ $ref: `#/components/${kind}/${name}` }); + +const api = { + openapi: "3.0.3", + info: { title: "Coder API", version: "2.0", description: "Not carried." }, + servers: [{ url: "{deployment}" }], + paths: { + "/api/v2/a/{id}": { + parameters: [ref("parameters", "Id")], + get: { + responses: { + "200": { + description: "OK", + content: { "application/json": { schema: ref("schemas", "A") } }, + }, + }, + }, + }, + "/api/v2/d": { + get: { + responses: { + "200": { + description: "OK", + content: { "application/json": { schema: ref("schemas", "D") } }, + }, + }, + }, + }, + }, + components: { + securitySchemes: { + CoderSessionToken: { type: "apiKey", in: "header", name: "Coder-Session-Token" }, + }, + parameters: { Id: { name: "id", in: "path", required: true, schema: ref("schemas", "Id") } }, + schemas: { + A: { type: "object", properties: { b: ref("schemas", "B") } }, + B: { type: "array", items: ref("schemas", "C") }, + C: { type: "object", properties: { back: ref("schemas", "A"), self: ref("schemas", "C") } }, + D: { type: "string" }, + Id: { type: "string", format: "uuid" }, + }, + }, +}; + +test("a pruned page keeps its operation, its path's parameters and every schema they reach, and nothing else", () => { + const pruned = pruneDocument(api, "/api/v2/a/{id}", "get"); + assert.deepEqual(Object.keys(pruned.paths as object), ["/api/v2/a/{id}"]); + const item = (pruned.paths as Record>)["/api/v2/a/{id}"]; + assert.deepEqual(item?.parameters, [ref("parameters", "Id")]); + assert.deepEqual(Object.keys(item ?? {}).sort(), ["get", "parameters"]); + const components = pruned.components as Record>; + assert.deepEqual(Object.keys(components.schemas ?? {}).sort(), ["A", "B", "C", "Id"]); + assert.deepEqual(components.parameters, api.components.parameters); + assert.deepEqual(components.securitySchemes, api.components.securitySchemes); + assert.deepEqual(pruned.info, { title: "Coder API", version: "2.0" }); + assert.deepEqual(pruned.servers, api.servers); +}); + +test("pruning a page whose operation isn't in the document fails", () => { + assert.throws(() => pruneDocument(api, "/api/v2/a/{id}", "post"), /no post \/api\/v2\/a\/\{id\}/); +}); From 4de374ccf1fb56ba8bbf7b91571a8c09ca193f74 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:17:07 -0400 Subject: [PATCH 40/69] test(docs-next): exempt only a URL line whose path is too long from the sample width check The width test skipped every line containing the operation's path, however short, so a regression that put a header or the token on the URL line of /api/v2/buildinfo passed. A line is now exempt only when it is a URL line of its own (the path plus that language's fixed wrapper) and the path is too long to fit with it; such a regression fails the test now. The four widths are hard-coded, and a second test pins SAMPLE_LINE_WIDTH to them, so changing the constant can't pass silently. Assisted-by: AI --- .../src/openapi/code-samples.test.ts | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/packages/docs-next/src/openapi/code-samples.test.ts b/packages/docs-next/src/openapi/code-samples.test.ts index fe8c771f..fdcad1dd 100644 --- a/packages/docs-next/src/openapi/code-samples.test.ts +++ b/packages/docs-next/src/openapi/code-samples.test.ts @@ -540,14 +540,12 @@ const long = { }, }; -const WIDTH_BY_LABEL: Record = { - cURL: SAMPLE_LINE_WIDTH.curl, - JavaScript: SAMPLE_LINE_WIDTH.javascript, - Python: SAMPLE_LINE_WIDTH.python, - Go: SAMPLE_LINE_WIDTH.go, -}; +// Prettier's 80, Black's 88, and the 64 columns the shell and Go samples aim for. +const WIDTH_BY_LABEL: Record = { cURL: 64, JavaScript: 80, Python: 88, Go: 64 }; +// What each language puts around a URL line of its own: indent, quotes, `$CODER_URL`, `const url =`. +const URL_LINE_WRAPPER: Record = { cURL: 18, JavaScript: 27, Python: 8, Go: 10 }; -test("sample lines stay within each language's width, except a path too long to break", () => { +test("sample lines stay within each language's width, except a URL line whose path is too long to break", () => { const operations: [string, string][] = [ ["/api/v2/users/{user}", "get"], ["/api/v2/users", "post"], @@ -557,16 +555,22 @@ test("sample lines stay within each language's width, except a path too long to ]; for (const [path, method] of operations) { for (const { label, source } of codeSamples(long, path, method)) { + const limit = WIDTH_BY_LABEL[label] ?? 0; + const wrapper = URL_LINE_WRAPPER[label] ?? 0; for (const line of source.split("\n")) { const width = line.replace(/\t/g, " ").length; - if (line.includes(path)) continue; - const limit = WIDTH_BY_LABEL[label] ?? 0; + const urlLineOnly = line.includes(path) && width - path.length <= wrapper; + if (urlLineOnly && path.length + wrapper > limit) continue; assert.ok(width <= limit, `${label} ${method} ${path}: ${width} > ${limit}: ${line}`); } } } }); +test("the samples' widths are the formatters' own", () => { + assert.deepEqual(SAMPLE_LINE_WIDTH, { curl: 64, javascript: 80, python: 88, go: 64 }); +}); + test("a long URL is split where each language's formatter splits it", async () => { const [shell, js, python, go] = codeSamples(long, longPath, "post").map((s) => s.source); assert.ok(shell?.includes(` -X POST \\\n\t"$CODER_URL${longPath}" \\`)); From 04802819a381173e036d4d03b71827912bb9f34f Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:18:04 -0400 Subject: [PATCH 41/69] fix(docs-next): keep a multipart field name from turning the curl sample into a file upload curl reads `@`, `<` and `;type=` in a -F value as its own syntax and splits the field at its first `=`, and the multipart field names come from coder/coder's Swagger document with only shell escaping, so a required field named something like `f=@/etc/passwd;x` made the copied sample upload a local file to the reader's own deployment. The sample now sends each field with --form-string, whose value curl never interprets, and leaves out a field whose name holds `=`, which curl has no way to write. The other languages' samples name fields as plain strings and are unchanged. Assisted-by: AI --- .../src/openapi/code-samples.test.ts | 21 +++++++++++++++++-- .../docs-next/src/openapi/code-samples.ts | 5 +++-- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/docs-next/src/openapi/code-samples.test.ts b/packages/docs-next/src/openapi/code-samples.test.ts index fdcad1dd..bc895967 100644 --- a/packages/docs-next/src/openapi/code-samples.test.ts +++ b/packages/docs-next/src/openapi/code-samples.test.ts @@ -286,10 +286,27 @@ const form = { }, }; -test("curl: a multipart body sends its required fields", () => { +test("curl: a multipart body sends its required fields as literal strings", () => { assert.equal( sample(form, "/api/v2/form", "post", "curl"), - [`curl -X POST \\`, `\t"$CODER_URL/api/v2/form" \\`, `\t-F "name={name}"`].join("\n"), + [`curl -X POST \\`, `\t"$CODER_URL/api/v2/form" \\`, `\t--form-string "name={name}"`].join( + "\n", + ), + ); +}); + +test("curl: a field name curl would split at its = is left out, so it can't name a local file", () => { + const hostile = structuredClone(form); + hostile.paths["/api/v2/form"].post.requestBody.content["multipart/form-data"].schema.required = [ + "name", + "f=@/etc/passwd;x", + ]; + const curl = sample(hostile, "/api/v2/form", "post", "curl"); + assert.equal( + curl, + [`curl -X POST \\`, `\t"$CODER_URL/api/v2/form" \\`, `\t--form-string "name={name}"`].join( + "\n", + ), ); }); diff --git a/packages/docs-next/src/openapi/code-samples.ts b/packages/docs-next/src/openapi/code-samples.ts index dbb4e3ee..fc16d9c1 100644 --- a/packages/docs-next/src/openapi/code-samples.ts +++ b/packages/docs-next/src/openapi/code-samples.ts @@ -181,8 +181,9 @@ export function curlSample(request: ExampleRequest): string { ]; if (body?.kind === "json") lines.push(`-d ${shellSingleQuoted(jsonText(body.value))}`); if (body?.kind === "form") { - for (const name of body.fields) - lines.push(`-F ${shellDoubleQuoted(`${name}=${placeholder(name)}`)}`); + // curl splits a field at its first =, so such a name can't be written. + for (const name of body.fields.filter((field) => !field.includes("="))) + lines.push(`--form-string ${shellDoubleQuoted(`${name}=${placeholder(name)}`)}`); } if (body?.kind === "binary") lines.push(`--data-binary ${shellDoubleQuoted("@".concat(placeholder("file")))}`); From 9159efc163403303f06d311c1c219328c2389182 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:20:57 -0400 Subject: [PATCH 42/69] build(docs-next): move the API page's shiki to 4.5.0 so the site has one copy fumadocs-openapi 12.5.4 needs shiki ^4.5.0, which already moved fumadocs-core and fumadocs-ui, and so the whole site's highlighting, from 4.4.3 to 4.5.0 in this branch's lockfile, while docs-next still pinned 4.4.3 for the API page's own highlighter. Pinning 4.5.0 here drops the second copy from the lockfile. Assisted-by: AI --- packages/docs-next/package.json | 2 +- pnpm-lock.yaml | 85 +-------------------------------- 2 files changed, 3 insertions(+), 84 deletions(-) diff --git a/packages/docs-next/package.json b/packages/docs-next/package.json index c0a3a80e..f4ab7314 100644 --- a/packages/docs-next/package.json +++ b/packages/docs-next/package.json @@ -48,7 +48,7 @@ "fumadocs-openapi": "12.5.4", "fumadocs-ui": "catalog:", "lucide-react": "1.46.0", - "shiki": "4.4.3" + "shiki": "4.5.0" }, "peerDependencies": { "next": ">=16", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ff0b935d..5a28bf02 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -420,8 +420,8 @@ importers: specifier: 1.46.0 version: 1.46.0(react@19.2.7) shiki: - specifier: 4.4.3 - version: 4.4.3 + specifier: 4.5.0 + version: 4.5.0 devDependencies: '@coder/docs-transforms': specifier: workspace:* @@ -2372,58 +2372,30 @@ packages: resolution: {integrity: sha512-wkTbowGZAlDA5AhCAnBVft6y3veoE17P+okH/zrwM/BZWBSzPghGpa4BPTCg3+IzRmRP/8ZeaYO7LfxCDAEmcA==} engines: {node: '>=22'} - '@shikijs/core@4.4.3': - resolution: {integrity: sha512-QCR4q2ZO/ILJEuwiBMel4wdcTDb1JGwfjKTxPDF6x8ixOaluPrVqIn06C99AcRPhmYlBR56d/Fb+GN58GzExpg==} - engines: {node: '>=20'} - '@shikijs/core@4.5.0': resolution: {integrity: sha512-6CIgwq+bt2JZ3OSjb/nBkkwEf/CfpHcbam+Mg5Pllco7HAGRQ2/EFhZrrJtbyNTgKwknfVS+llsXGygiDGwJWw==} engines: {node: '>=20'} - '@shikijs/engine-javascript@4.4.3': - resolution: {integrity: sha512-FbOjFJp9VLdo1Wevs10BBtVxiTWwNLqZh5Gkhjgda/ioL15YOgeSl9n+6XMa3qRlPQzfhFNe641SrynFHYG0nQ==} - engines: {node: '>=20'} - '@shikijs/engine-javascript@4.5.0': resolution: {integrity: sha512-Ed6UdEj84LyYkwnxM5CvSMWAD+id9ExTYri0/+x41U9zrgNifPSS9lZm0JqBP0VfYI8yr8tY5nbNq9+p9R0kFA==} engines: {node: '>=20'} - '@shikijs/engine-oniguruma@4.4.3': - resolution: {integrity: sha512-EcOQkxdxGQrc1Row/cC2c96/v1dbZqGnEVu1qTuT/MJmp6+cXCvQussowVmCv5Tqr3KuY3c7IbM6HTW3LJ1k9w==} - engines: {node: '>=20'} - '@shikijs/engine-oniguruma@4.5.0': resolution: {integrity: sha512-dKVmbJecVdB9recl8a/CU4jdpNXyjJQrIcesIkpS70s5HS02ohpnCSpMUbotPnEUzbAcLQ+S4hwZYbkBBiTcJw==} engines: {node: '>=20'} - '@shikijs/langs@4.4.3': - resolution: {integrity: sha512-ePic0yfAJGOF83D5wBHK/00EjK65oahBYxFk5epgq33WRv7X9UuxLEV8PtR0szC0z8dl7INIpIodB99JRFlR+A==} - engines: {node: '>=20'} - '@shikijs/langs@4.5.0': resolution: {integrity: sha512-wwBTqwduXSz0X4v9Qa2EWeFaYJEw1clCncWjoRNQRbVDu3SPRTRWucnouYapKj3b8Q+sk/41Vbc4B5c8nuYzLA==} engines: {node: '>=20'} - '@shikijs/primitive@4.4.3': - resolution: {integrity: sha512-m0wBeLDQDeIxRdUmrCPdQqfuUamDwRL5isCfYbguKD6NiaKpVbsv+3J81DyIKgNW5h4WAIIr8T4EkgQrBBxvaQ==} - engines: {node: '>=20'} - '@shikijs/primitive@4.5.0': resolution: {integrity: sha512-UM7ShlA8oz0OWxLLO8BmO9Ip6fVqdkt8yF0EH7nOCqHfrx1eEAzF0ZUVK7L+I8NEgeu1PEWSRlxaiPPeCb4iDg==} engines: {node: '>=20'} - '@shikijs/themes@4.4.3': - resolution: {integrity: sha512-w8UHjeUnIR965KMWJHUPXOc2mNJUnK3vpVLYLvw5IYU2mnTTJ89E24OrJDBNiJDQ0qzb0tc4l7mrIXx5cFeIyw==} - engines: {node: '>=20'} - '@shikijs/themes@4.5.0': resolution: {integrity: sha512-zGb87H3UBbpuI4yoh5UguB1XbU+2BDU3kflM7UfZ+Cy2hWo9lBtqjSVK20gmLY6ukYl040hAypGXMgud9vul8Q==} engines: {node: '>=20'} - '@shikijs/types@4.4.3': - resolution: {integrity: sha512-UEJxmRR++MAGR6hugn0vgVS2W/6lWAts84FFSrnlH9sP0LNol7E5+NQ792pH8liWUhyMyjhTgSUH3k7iD7tc5g==} - engines: {node: '>=20'} - '@shikijs/types@4.5.0': resolution: {integrity: sha512-drtPrtD8N0DENyD2cyt6Ajy+IWsiCLgMxODwLTpvH1UsN6a9jf90tNTPjqwHvA+0Lzu9e0txk8DjfqH1p9UJRw==} engines: {node: '>=20'} @@ -4745,10 +4717,6 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} - shiki@4.4.3: - resolution: {integrity: sha512-Mb/GvXPHBAXdgGIcnfU5L3ldpn1XcxrGkPHwqgRx17/I2XRfqlFKk2vGkHWINn1kdXvzJZeuO3is6I9KLPFm0g==} - engines: {node: '>=20'} - shiki@4.5.0: resolution: {integrity: sha512-OcRW72ngQvc+MSVWBRIovC/BTW589iUE/Vxav7VeM4RcY9MUjqB+IR6ILG1k9nuW6LiG/nct9uma4/MBtnZbmQ==} engines: {node: '>=20'} @@ -6511,14 +6479,6 @@ snapshots: '@scalar/helpers': 0.16.4 '@scalar/openapi-types': 0.9.8 - '@shikijs/core@4.4.3': - dependencies: - '@shikijs/primitive': 4.4.3 - '@shikijs/types': 4.4.3 - '@shikijs/vscode-textmate': 10.0.2 - '@types/hast': 3.0.5 - hast-util-to-html: 9.0.5 - '@shikijs/core@4.5.0': dependencies: '@shikijs/primitive': 4.5.0 @@ -6527,61 +6487,31 @@ snapshots: '@types/hast': 3.0.5 hast-util-to-html: 9.0.5 - '@shikijs/engine-javascript@4.4.3': - dependencies: - '@shikijs/types': 4.4.3 - '@shikijs/vscode-textmate': 10.0.2 - oniguruma-to-es: 4.3.6 - '@shikijs/engine-javascript@4.5.0': dependencies: '@shikijs/types': 4.5.0 '@shikijs/vscode-textmate': 10.0.2 oniguruma-to-es: 4.3.6 - '@shikijs/engine-oniguruma@4.4.3': - dependencies: - '@shikijs/types': 4.4.3 - '@shikijs/vscode-textmate': 10.0.2 - '@shikijs/engine-oniguruma@4.5.0': dependencies: '@shikijs/types': 4.5.0 '@shikijs/vscode-textmate': 10.0.2 - '@shikijs/langs@4.4.3': - dependencies: - '@shikijs/types': 4.4.3 - '@shikijs/langs@4.5.0': dependencies: '@shikijs/types': 4.5.0 - '@shikijs/primitive@4.4.3': - dependencies: - '@shikijs/types': 4.4.3 - '@shikijs/vscode-textmate': 10.0.2 - '@types/hast': 3.0.5 - '@shikijs/primitive@4.5.0': dependencies: '@shikijs/types': 4.5.0 '@shikijs/vscode-textmate': 10.0.2 '@types/hast': 3.0.5 - '@shikijs/themes@4.4.3': - dependencies: - '@shikijs/types': 4.4.3 - '@shikijs/themes@4.5.0': dependencies: '@shikijs/types': 4.5.0 - '@shikijs/types@4.4.3': - dependencies: - '@shikijs/vscode-textmate': 10.0.2 - '@types/hast': 3.0.5 - '@shikijs/types@4.5.0': dependencies: '@shikijs/vscode-textmate': 10.0.2 @@ -9543,17 +9473,6 @@ snapshots: shebang-regex@3.0.0: {} - shiki@4.4.3: - dependencies: - '@shikijs/core': 4.4.3 - '@shikijs/engine-javascript': 4.4.3 - '@shikijs/engine-oniguruma': 4.4.3 - '@shikijs/langs': 4.4.3 - '@shikijs/themes': 4.4.3 - '@shikijs/types': 4.4.3 - '@shikijs/vscode-textmate': 10.0.2 - '@types/hast': 3.0.5 - shiki@4.5.0: dependencies: '@shikijs/core': 4.5.0 From e1e54c8ad47e34f6052da2f0e95023bf69a592a2 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:23:45 -0400 Subject: [PATCH 43/69] fix(docs-next): name the API page's response and example selects, and each sample's code region In fumadocs-openapi 12.5.4 the only ExampleSelect inside a code-block figure is the request-language select in CodeUsages, which renderAPIExampleUsageTabs replaces with our tabs, so the workaround that named it never found anything and is gone. The selects that remain, for the response status and for request and response examples (ui/operation/usage-tabs.js), sit outside the figure and had no name on any operation with more than one response. The example column now wraps those slots and names each combobox fumadocs-openapi renders there: Request example, Response status (in the response card's header) and Response example. A sample's scroll region is named by its tab label, such as "cURL sample", instead of the Shiki language id, which announced cURL as "shellscript code". The fixture's Create new user operation gets a 409 response, so the axe pass sees the status select. Assisted-by: AI --- apps/docs/fixtures/openapi/swagger.json | 3 +- .../docs-next/src/openapi/api-page.test.tsx | 62 ++++++++++++++++++- packages/docs-next/src/openapi/api-page.tsx | 58 +++++++++++++---- 3 files changed, 106 insertions(+), 17 deletions(-) diff --git a/apps/docs/fixtures/openapi/swagger.json b/apps/docs/fixtures/openapi/swagger.json index 7752f138..8d404808 100644 --- a/apps/docs/fixtures/openapi/swagger.json +++ b/apps/docs/fixtures/openapi/swagger.json @@ -46,7 +46,8 @@ } ], "responses": { - "201": { "description": "Created", "schema": { "$ref": "#/definitions/codersdk.User" } } + "201": { "description": "Created", "schema": { "$ref": "#/definitions/codersdk.User" } }, + "409": { "description": "A user with that username or email already exists" } } } }, diff --git a/packages/docs-next/src/openapi/api-page.test.tsx b/packages/docs-next/src/openapi/api-page.test.tsx index 19972428..e24d0421 100644 --- a/packages/docs-next/src/openapi/api-page.test.tsx +++ b/packages/docs-next/src/openapi/api-page.test.tsx @@ -30,7 +30,11 @@ const document_ = withCodeSamples( "get", ); -async function renderPage(): Promise<{ container: HTMLElement; unmount: () => Promise }> { +async function renderPage( + bundled: Record = document_, + path = "/api/v2/buildinfo", + method: "get" | "post" = "get", +): Promise<{ container: HTMLElement; unmount: () => Promise }> { const container = document.createElement("div"); document.body.appendChild(container); const root = createRoot(container); @@ -44,8 +48,8 @@ async function renderPage(): Promise<{ container: HTMLElement; unmount: () => Pr , ), @@ -87,3 +91,55 @@ for (const [label, deployment] of [ } }); } + +const json = (examples: Record) => ({ + "application/json": { + examples: Object.fromEntries( + Object.entries(examples).map(([name, value]) => [name, { summary: name, value }]), + ), + }, +}); + +const choices = withCodeSamples( + { + openapi: "3.0.3", + info: { title: "Coder API", version: "2.0" }, + paths: { + "/api/v2/templates": { + post: { + summary: "Create template", + requestBody: { + content: json({ Minimal: { name: "a" }, Full: { name: "a", icon: "b" } }), + }, + responses: { + "201": { description: "Created", content: json({ New: { id: 1 }, Copied: { id: 2 } }) }, + "409": { description: "Conflict", content: json({ Taken: { message: "taken" } }) }, + }, + }, + }, + }, + components: {}, + }, + "/api/v2/templates", + "post", +); + +test("every select in the example column has a name, and each code region is named by its tab", async () => { + const { container, unmount } = await renderPage(choices, "/api/v2/templates", "post"); + try { + const selects = [...container.querySelectorAll('[role="combobox"]')]; + assert.ok(selects.length >= 3, `${selects.length} selects`); + assert.deepEqual( + selects.map((select) => select.getAttribute("aria-label")), + ["Request example", "Response status", "Response example"], + ); + const regions = [...container.querySelectorAll('.coder-sample-tabs [role="region"]')]; + assert.deepEqual( + regions.map((region) => region.getAttribute("aria-label")), + ["cURL sample", "JavaScript sample", "Python sample", "Go sample"].slice(0, regions.length), + ); + assert.ok(regions.length > 0); + } finally { + await unmount(); + } +}); diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index bbc620d0..c73e568e 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -7,7 +7,7 @@ import { createCodeUsageGeneratorRegistry } from "fumadocs-openapi/requests/gene import { createOpenAPIPageBase } from "fumadocs-openapi/ui/base"; import { DynamicCodeBlock } from "fumadocs-ui/components/dynamic-codeblock.core"; import { Tab, Tabs } from "fumadocs-ui/components/tabs"; -import { type ComponentProps, useState } from "react"; +import { type ComponentProps, type ReactNode, useEffect, useRef, useState } from "react"; import { SamplesNote } from "./samples-note.js"; import { repairStoredServer } from "./stored-server.js"; @@ -40,14 +40,8 @@ const shikiOptions = { themes: { light: "github-light-high-contrast", dark: "github-dark-default" }, } as const; -// The playground's language select (fumadocs-openapi 12.5.4 ExampleSelect) is a combobox with no accessible name. -function nameLanguageSelect(figure: HTMLElement | null) { - for (const select of figure?.querySelectorAll('[role="combobox"]:not([aria-label])') ?? []) - select.setAttribute("aria-label", "Sample language"); -} - // fumadocs-openapi's default code block leaves its scroll region unnamed, so every block on a page is the same landmark. -function CodeBlock(props: CodeBlockProps) { +function CodeBlock({ name, ...props }: CodeBlockProps & { name?: string }) { return ( shiki.getOrInit()} @@ -55,13 +49,51 @@ function CodeBlock(props: CodeBlockProps) { {...props} codeblock={{ ...props.codeblock, - ref: nameLanguageSelect, - viewportProps: { ...props.codeblock?.viewportProps, "aria-label": `${props.lang} code` }, + viewportProps: { + ...props.codeblock?.viewportProps, + "aria-label": name ?? `${props.lang} code`, + }, }} /> ); } +// fumadocs-openapi 12.5.4's example and status selects (ui/operation/usage-tabs.js) have no accessible name. +function NamedSelects({ + name, + children, +}: { + name: (select: Element, root: Element) => string; + children: ReactNode; +}) { + const ref = useRef(null); + useEffect(() => { + const root = ref.current; + if (!root) return; + const label = () => { + for (const select of root.querySelectorAll('[role="combobox"]:not([aria-label])')) + select.setAttribute("aria-label", name(select, root)); + }; + label(); + const observer = new MutationObserver(label); + observer.observe(root, { childList: true, subtree: true }); + return () => observer.disconnect(); + }, [name]); + return ( +
+ {children} +
+ ); +} + +const requestExample = () => "Request example"; + +// The status select sits in the response card's header; an example select, below it. +const responseSelect = (select: Element, root: Element) => + root.firstElementChild?.firstElementChild?.contains(select) + ? "Response status" + : "Response example"; + // One tab per language, where fumadocs-openapi's default is a select in the code block's header. // The samples are the server-built text as is, never run through fumadocs-openapi's generators, which resolve the reader's stored server URL. function SampleTabs() { @@ -86,7 +118,7 @@ function SampleTabs() { > {samples.map((sample) => ( - + ))} @@ -126,10 +158,10 @@ const OpenApiPage = createOpenAPIPageBase({ ), renderAPIExampleLayout: ({ selector, usageTabs, responseTabs }) => (
- {selector} + {selector} {usageTabs} - {responseTabs} + {responseTabs}
), }, From bcdf21b40f79ce2b4e76a8e70848b6081fcecb45 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:24:48 -0400 Subject: [PATCH 44/69] docs: record how the REST API reference is built in ARCHITECTURE.md ARCHITECTURE.md said its package edges were verified against each package.json but still listed docs-build as depending only on docs-config and docs-transforms, and had nothing on the generated API reference. It now names docs-build's docs-manifest edge and its swagger2openapi and oas-validator base, and a new section covers the step that rewrites the DocSource before the sync, the _openapi frontmatter contract, the reference data file, the renderBody hook, the DOCS_OPENAPI rollback, the publish failing without a Swagger document, the assumption that swagger.json sits beside docs/ in every checkout, and the three in-document $ref checks. Assisted-by: AI --- ARCHITECTURE.md | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b883de1c..6fd47806 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -37,8 +37,8 @@ docs-ui ────► docs-config docs-theme (no dependencies) - `@coder/docs-config` is the root contract package and depends on no other workspace package. - `@coder/docs-sources` depends on `docs-config`. - `@coder/docs-transforms` depends on `docs-config` (for the `Manifest` and `DocSource` contracts its pure transforms consume, and the `StaticDocsRenderContext` a static compile resolves the `premium` condition against). -- `@coder/docs-build` depends on `docs-config` and `docs-transforms`. -- `@coder/docs-next` depends on `docs-config`, `docs-ui`, and the dependency-free `version-segment` subpath of `docs-manifest`. +- `@coder/docs-build` depends on `docs-config`, `docs-transforms`, and the `version-segment` subpath of `docs-manifest` (for `isLineAtLeast`, which picks the versions that render the generated REST API reference); its external base for that reference is `swagger2openapi` and `oas-validator`. +- `@coder/docs-next` depends on `docs-config`, `docs-ui`, and the dependency-free `version-segment` subpath of `docs-manifest`; its `openapi` subpath renders the REST API reference with `fumadocs-openapi`. - `@coder/docs-ui` depends on the zod-free `client` subpath of `docs-config` for the `DocsRenderContext` its runtime `Premium`/`Experimental` annotation components read (loading the zod parser only when a fetched context arrives), and on the `version-segment` subpath of `docs-manifest` for the runtime version switcher's links; its external base is `fumadocs-ui`. - `@coder/docs-theme` depends on nothing; it ships plain CSS. - `@coder/docs-manifest` depends on `docs-config` only. @@ -130,6 +130,7 @@ Keeping every subword piece and the first 5,000 or more vocabulary rows as well One version of the docs flows through four stages: 1. **Provider.** A `VersionsProvider` from `@coder/docs-sources` loads the version into a `DocSource`: raw `.md` files, the `manifest.json` sidebar model, resolved images, and optional redirects. + For a version that renders the generated REST API reference, the sync scripts then rewrite that `DocSource` before syncing it (refer to "The REST API reference" below). 2. **Sync.** `syncDocSource` (`@coder/docs-build`) validates the source (dead links, broken images, route collisions, stale manifest entries) and writes a Fumadocs content tree: `.md` files with injected frontmatter, rewritten links and image paths, per-directory `meta.json`, and copied images. Only pages named by the manifest are emitted. 3. **Compile.** `fumadocs-mdx` compiles the synced tree using `createCoderMdxOptions({ renderContext, linkPrefix })` (`@coder/docs-transforms/mdx-config`), of which `coderMdxOptions` is the default instance (no static context, no link prefix — the in-product runtime pipeline): the Coder remark stack (GitHub callouts, Coder tabs, `
` accordions, steps), then `rehype-raw` to reparse the corpus's raw HTML, then the sanitizer, then Shiki highlighting with a fallback language for unbundled fences. @@ -141,6 +142,25 @@ This design rests on a `.md`-only precondition: the sync emits only `.md` files, Emitting `.mdx` would let corpus content execute at compile time and bypass the sanitizer entirely. Refer to "Security: the corpus is untrusted" in the `@coder/docs-transforms` README for the full invariant. +### The REST API reference + +From 2.24 on, and on `main`, the REST API reference is built from coder/coder's Swagger 2.0 document rather than from the Markdown pages its generator writes. +`rendersOpenApi` (`@coder/docs-build`) picks those versions; `OPENAPI_MIN_LINE` is the oldest line, since older documents repeat operation ids. +`DOCS_OPENAPI` set to `0`, `false`, `off` or `no` keeps the Markdown reference for every version, and is the rollback; any value that is not an off or on spelling fails the sync. + +The Swagger document is read from the checkout the docs come from, never fetched. +`swaggerFromTree` (`@coder/docs-sources`) reads `coderd/apidoc/swagger.json` beside the `docs/` tree, so every checkout a sync runs on, the publisher's and the preview's sparse ones included, has to hold `coderd/apidoc` as well as `docs`; `swaggerFromClone` reads the same path at the version's ref of a git clone. +A version with no Swagger document keeps its Markdown reference with a warning, except when `DOCS_PUBLISH=1`, where the sync fails, so a publish never ships the old reference for a version that should have the new one. + +`withOpenApiReference` rewrites the version's `DocSource` before `syncDocSource` sees it: `applyOpenApiReference` converts the document to OpenAPI 3, adds one Markdown stub page per operation under its tag, turns each tag page and the schemas page into lists of links, and adds the setup section to the landing page. +Each stub carries `_openapi: { method }` in its frontmatter; the sync validates that shape and keeps it, and fumadocs-openapi's loader plugin reads it to draw the sidebar's method badge. +It also writes the version's reference data, the converted document plus the route of every operation page, the old anchors, the landing cards and the schema rows, to `.generated/openapi/.json` (`docs.json` in the single-version offline export), which the app reads at render time so the document stays out of the server bundle. +A generated page whose path or route another page already has fails the sync. + +The page route factories take a `renderBody` hook, which may replace a page's compiled Markdown body, add after it, widen it, or extend its table of contents. +`createOpenApiRenderBody` (`@coder/docs-next/openapi`) is that hook for the reference: an operation page renders through fumadocs-openapi from the document pruned to that operation and what it reaches, with code samples built on the server; the tag and schemas pages add a client redirect from the old single-page anchors; the landing page adds its cards. +Every `$ref` must be in-document (`#/...`) at three points, the Swagger document, the converted document, and the renderer's input, because fumadocs-openapi's bundler fetches or reads any other reference. + ## Design decisions These seams are decided and recorded, but not all are implemented yet. From 70ba22b5e30457295887f67cc6e9276053cea547 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:32:00 -0400 Subject: [PATCH 45/69] fix(docs-theme): give the schema groups a chevron that turns when they open The schemas page's group summaries are display: flex, which overrides the display: list-item that draws the disclosure marker, so the groups showed no expand affordance and looked the same open or closed. Each summary now draws a chevron from two borders that points right when closed and down when [open], in the text colour, with the native marker hidden so none comes back where flex is dropped. Checked in Chromium and Firefox against the fixture build. Assisted-by: AI --- packages/docs-theme/src/brand.css | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css index c201d2c2..9cde0945 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -832,6 +832,26 @@ samp { min-height: 2.5rem; cursor: pointer; font-weight: 600; + list-style: none; +} + +.coder-schema-group > summary::-webkit-details-marker { + display: none; +} + +.coder-schema-group > summary::before { + content: ""; + flex-shrink: 0; + width: 0.5rem; + height: 0.5rem; + margin-inline: 0.25rem 0.75rem; + border-block-end: 2px solid currentColor; + border-inline-end: 2px solid currentColor; + transform: rotate(-45deg); +} + +.coder-schema-group[open] > summary::before { + transform: rotate(45deg); } .coder-schema-group > table { From b01fdfb11d61a658f407cc7bb60cc3e09fcd31d7 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Wed, 28 Oct 2026 18:51:28 -0400 Subject: [PATCH 46/69] refactor(docs-build): name the converted-document check's parameter spec The check added for the post-conversion $ref test took a parameter named document, which shadows the global that AGENTS.md asks locals not to reuse. Assisted-by: AI --- packages/docs-build/src/openapi-reference.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 4747283f..8021e5c8 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -205,9 +205,9 @@ export async function convertSwagger( } /** Throws when a converted document holds a `$ref` the renderer's bundler would fetch or read, or is not valid OpenAPI. */ -export async function assertConvertedDocument(document: Json): Promise { - assertInDocumentRefs(document, "the converted OpenAPI document"); - const result = await validate(document, { +export async function assertConvertedDocument(spec: Json): Promise { + assertInDocumentRefs(spec, "the converted OpenAPI document"); + const result = await validate(spec, { lint: false, prettify: false, warnOnly: true, From 74a1d9ad0aad54eb24cf6873a46da3eddfb8b8c5 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Thu, 29 Oct 2026 14:54:16 -0400 Subject: [PATCH 47/69] feat(docs-next): keep fumadocs-openapi's API playground out of the build Turning the playground off only stopped it rendering. fumadocs-openapi's operation component still imports the playground client statically, and its page provider always mounts the playground auth provider, which on mount reads a pending OAuth flow from sessionStorage and can fetch a token endpoint. The request UI, fetcher, OAuth flows and the server proxy were all in the public site's and the offline export's JavaScript. withoutOpenApiPlayground, exported from @coder/docs-next/next-config, adds a Turbopack rule and a webpack rule that run a loader on those modules and replace each with an inert stub: the auth provider renders its children, the playground renders nothing, and every other export throws if called. The rule matches the resolved file path, so it holds however a module is imported; Turbopack's resolveAlias matches only the request string. Each app opts in by wrapping its Next config, so another app can still ship the real playground. A module that matches with no stub, or whose exports differ from its stub's, fails the build, and a test walks fumadocs-openapi's import graph from the entries the engine uses to show the stubs cut every path to the playground's code. The playground stays disabled in the page options too, and the theme no longer styles its dialog. Assisted-by: AI --- ARCHITECTURE.md | 1 + apps/docs/next.config.mjs | 33 ++--- apps/offlinedocs/next.config.mjs | 19 +-- packages/docs-build/src/openapi-reference.ts | 2 +- packages/docs-next/package.json | 5 + packages/docs-next/src/next-config.test.ts | 54 ++++++++ packages/docs-next/src/next-config.ts | 33 +++++ packages/docs-next/src/openapi/api-page.tsx | 2 +- .../src/openapi/playground-stub-loader.ts | 15 +++ .../src/openapi/playground-stubs.test.ts | 118 ++++++++++++++++++ .../docs-next/src/openapi/playground-stubs.ts | 89 +++++++++++++ packages/docs-theme/src/brand.css | 47 +------ pnpm-lock.yaml | 3 + 13 files changed, 355 insertions(+), 66 deletions(-) create mode 100644 packages/docs-next/src/next-config.test.ts create mode 100644 packages/docs-next/src/next-config.ts create mode 100644 packages/docs-next/src/openapi/playground-stub-loader.ts create mode 100644 packages/docs-next/src/openapi/playground-stubs.test.ts create mode 100644 packages/docs-next/src/openapi/playground-stubs.ts diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 8f59df48..7a541f22 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -160,6 +160,7 @@ A generated page whose path or route another page already has fails the sync. The page route factories take a `renderBody` hook, which may replace a page's compiled Markdown body, add after it, widen it, or extend its table of contents. `createOpenApiRenderBody` (`@coder/docs-next/openapi`) is that hook for the reference: an operation page renders through fumadocs-openapi from the document pruned to that operation and what it reaches, with code samples built on the server; the tag and schemas pages add a client redirect from the old single-page anchors; the landing page adds its cards. +fumadocs-openapi's API playground never ships: `withoutOpenApiPlayground` (`@coder/docs-next/next-config`) wraps the Next config of `apps/docs` and `apps/offlinedocs` and replaces the playground, its OAuth flows and fetcher, and the server proxy with inert stubs in every bundle, and `playground:check` fails a build whose JavaScript still holds that code. Every `$ref` must be in-document (`#/...`) at three points, the Swagger document, the converted document, and the renderer's input, because fumadocs-openapi's bundler fetches or reads any other reference. ## Design decisions diff --git a/apps/docs/next.config.mjs b/apps/docs/next.config.mjs index 97432733..76088251 100644 --- a/apps/docs/next.config.mjs +++ b/apps/docs/next.config.mjs @@ -1,4 +1,5 @@ import { fileURLToPath } from "node:url"; +import { withoutOpenApiPlayground } from "@coder/docs-next/next-config"; import { createMDX } from "fumadocs-mdx/next"; import { keyMdxLoaders, mdxPipelineDigest } from "./scripts/mdx-cache-key.mjs"; import { releaseSchedulePath } from "./scripts/sync-helpers.mjs"; @@ -36,19 +37,21 @@ const repoRoot = fileURLToPath(new URL("../..", import.meta.url)); const appDir = fileURLToPath(new URL(".", import.meta.url)); // Keys the Turbopack MDX loaders only; see mdx-cache-key.mjs for why webpack isn't covered. -export default keyMdxLoaders( - withMDX({ - // A static, serverless bundle: no live search route, no ISR. `next build` - // sets NODE_ENV=production, so builds always export; `next dev` stays a - // normal dev server. - output: process.env.NODE_ENV === "production" ? "export" : undefined, - trailingSlash: true, - images: { unoptimized: true }, - generateBuildId: () => stableBuildId(process.env), - // Build-memory headroom on an 8 GB machine; neither changes the export, and dev keeps its source maps. - experimental: { turbopackSourceMaps: process.env.NODE_ENV !== "production", cpus: 1 }, - ...(basePath ? { basePath } : {}), - ...(assetPrefix ? { assetPrefix } : {}), - }), - await mdxPipelineDigest(repoRoot, [releaseSchedulePath(appDir)]), +export default withoutOpenApiPlayground( + keyMdxLoaders( + withMDX({ + // A static, serverless bundle: no live search route, no ISR. `next build` + // sets NODE_ENV=production, so builds always export; `next dev` stays a + // normal dev server. + output: process.env.NODE_ENV === "production" ? "export" : undefined, + trailingSlash: true, + images: { unoptimized: true }, + generateBuildId: () => stableBuildId(process.env), + // Build-memory headroom on an 8 GB machine; neither changes the export, and dev keeps its source maps. + experimental: { turbopackSourceMaps: process.env.NODE_ENV !== "production", cpus: 1 }, + ...(basePath ? { basePath } : {}), + ...(assetPrefix ? { assetPrefix } : {}), + }), + await mdxPipelineDigest(repoRoot, [releaseSchedulePath(appDir)]), + ), ); diff --git a/apps/offlinedocs/next.config.mjs b/apps/offlinedocs/next.config.mjs index 0751a748..252b0215 100644 --- a/apps/offlinedocs/next.config.mjs +++ b/apps/offlinedocs/next.config.mjs @@ -1,3 +1,4 @@ +import { withoutOpenApiPlayground } from "@coder/docs-next/next-config"; import { createMDX } from "fumadocs-mdx/next"; // Vercel's build image sets NEXT_DEPLOYMENT_ID. When it is present, Next 16 @@ -15,11 +16,13 @@ delete process.env.NEXT_DEPLOYMENT_ID; const withMDX = createMDX(); -export default withMDX({ - // A static, serverless bundle: no live search route, no ISR. `next build` - // sets NODE_ENV=production, so builds always export; `next dev` stays a - // normal dev server. - output: process.env.NODE_ENV === "production" ? "export" : undefined, - trailingSlash: true, - images: { unoptimized: true }, -}); +export default withoutOpenApiPlayground( + withMDX({ + // A static, serverless bundle: no live search route, no ISR. `next build` + // sets NODE_ENV=production, so builds always export; `next dev` stays a + // normal dev server. + output: process.env.NODE_ENV === "production" ? "export" : undefined, + trailingSlash: true, + images: { unoptimized: true }, + }), +); diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 8021e5c8..ada95690 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -63,7 +63,7 @@ export interface OpenApiLanding { export interface ApplyOpenApiReferenceOptions { /** The docs-relative directory of the generated reference; defaults to `reference/api`. */ dir?: string; - /** The server URL template the try-it panel sends to; the reader fills in `{deployment}`. */ + /** The server URL template of the document, which an operation page shows with its path. */ server?: { url: string; variables?: Record }; } diff --git a/packages/docs-next/package.json b/packages/docs-next/package.json index f4ab7314..0bf290c4 100644 --- a/packages/docs-next/package.json +++ b/packages/docs-next/package.json @@ -27,6 +27,10 @@ "./openapi/code-samples": { "types": "./dist/openapi/code-samples.d.ts", "default": "./dist/openapi/code-samples.js" + }, + "./next-config": { + "types": "./dist/next-config.d.ts", + "default": "./dist/next-config.js" } }, "files": [ @@ -44,6 +48,7 @@ "@coder/docs-ui": "workspace:*", "@fumadocs/json-schema": "0.3.5", "@scalar/json-magic": "0.16.1", + "es-module-lexer": "1.7.0", "fumadocs-core": "catalog:", "fumadocs-openapi": "12.5.4", "fumadocs-ui": "catalog:", diff --git a/packages/docs-next/src/next-config.test.ts b/packages/docs-next/src/next-config.test.ts new file mode 100644 index 00000000..2557a841 --- /dev/null +++ b/packages/docs-next/src/next-config.test.ts @@ -0,0 +1,54 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { NextConfig } from "next"; +import { withoutOpenApiPlayground } from "./next-config.js"; +import { OPENAPI_PLAYGROUND_MODULE } from "./openapi/playground-stubs.js"; + +const LOADER = /[\\/]openapi[\\/]playground-stub-loader\.js$/; + +test("adds a Turbopack rule that runs the stub loader on the playground modules", () => { + const rules = withoutOpenApiPlayground({}).turbopack?.rules ?? {}; + assert.deepEqual(Object.keys(rules), ["*.js"]); + const rule = rules["*.js"]; + assert.ok(rule && !Array.isArray(rule)); + assert.deepEqual(rule.condition, { path: OPENAPI_PLAYGROUND_MODULE }); + assert.equal(rule.loaders?.length, 1); + assert.match(String(rule.loaders?.[0]), LOADER); +}); + +test("keeps the config's own Turbopack rules and options", () => { + const mdx = { loaders: ["mdx-loader"], as: "*.js" }; + const own = { condition: { path: /own/ }, loaders: ["own-loader"] }; + const config: NextConfig = { + trailingSlash: true, + turbopack: { resolveAlias: { a: "b" }, rules: { "*.mdx": mdx, "*.js": own } }, + }; + const out = withoutOpenApiPlayground(config); + assert.equal(out.trailingSlash, true); + assert.deepEqual(out.turbopack?.resolveAlias, { a: "b" }); + assert.equal(out.turbopack?.rules?.["*.mdx"], mdx); + const js = out.turbopack?.rules?.["*.js"]; + assert.ok(Array.isArray(js)); + assert.equal(js[0], own); + assert.equal(js.length, 2); +}); + +test("adds the same loader to webpack after the config's own webpack function", () => { + const calls: string[] = []; + const out = withoutOpenApiPlayground({ + webpack: (config: { module: { rules: unknown[] } }) => { + calls.push("own"); + config.module.rules.push("own-rule"); + return config; + }, + }); + const webpackConfig = { module: { rules: [] as unknown[] } }; + const result = out.webpack?.(webpackConfig, Object.create(null)); + assert.deepEqual(calls, ["own"]); + assert.equal(result, webpackConfig); + assert.equal(webpackConfig.module.rules[0], "own-rule"); + const added = webpackConfig.module.rules[1]; + assert.ok(added && typeof added === "object" && "test" in added && "use" in added); + assert.equal(added.test, OPENAPI_PLAYGROUND_MODULE); + assert.match(JSON.stringify(added.use), /playground-stub-loader\.js/); +}); diff --git a/packages/docs-next/src/next-config.ts b/packages/docs-next/src/next-config.ts new file mode 100644 index 00000000..8c1725e0 --- /dev/null +++ b/packages/docs-next/src/next-config.ts @@ -0,0 +1,33 @@ +import { fileURLToPath } from "node:url"; +import type { NextConfig } from "next"; +import { OPENAPI_PLAYGROUND_MODULE } from "./openapi/playground-stubs.js"; + +export { OPENAPI_PLAYGROUND_MARKERS } from "./openapi/playground-stubs.js"; + +const LOADER = fileURLToPath(new URL("./openapi/playground-stub-loader.js", import.meta.url)); + +interface WebpackConfig { + module: { rules: unknown[] }; +} + +/** + * `config` with fumadocs-openapi's API playground, OAuth flows, fetcher and + * proxy replaced by inert stubs in every Turbopack and webpack bundle, so none + * of their code is in the build. An app opts in by wrapping its config. + */ +export function withoutOpenApiPlayground(config: NextConfig): NextConfig { + const rule = { condition: { path: OPENAPI_PLAYGROUND_MODULE }, loaders: [LOADER] }; + const rules = { ...config.turbopack?.rules }; + const own = rules["*.js"]; + rules["*.js"] = own === undefined ? rule : [...(Array.isArray(own) ? own : [own]), rule]; + const ownWebpack = config.webpack; + return { + ...config, + turbopack: { ...config.turbopack, rules }, + webpack(webpackConfig: WebpackConfig, context) { + const out: WebpackConfig = ownWebpack ? ownWebpack(webpackConfig, context) : webpackConfig; + out.module.rules.push({ test: OPENAPI_PLAYGROUND_MODULE, use: [{ loader: LOADER }] }); + return out; + }, + }; +} diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index c73e568e..49ead49f 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -131,7 +131,7 @@ const OpenApiPage = createOpenAPIPageBase({ shiki, shikiOptions, components: { CodeBlock }, - // Off until there is a decision on sending requests and holding the reader's token. + // Never rendered; withoutOpenApiPlayground in each app's Next config also keeps its code out of the build. playground: { enabled: false }, // Empty, or fumadocs-openapi adds its own generators beside the operation's x-codeSamples. codeUsages: createCodeUsageGeneratorRegistry(), diff --git a/packages/docs-next/src/openapi/playground-stub-loader.ts b/packages/docs-next/src/openapi/playground-stub-loader.ts new file mode 100644 index 00000000..52d66d95 --- /dev/null +++ b/packages/docs-next/src/openapi/playground-stub-loader.ts @@ -0,0 +1,15 @@ +import { playgroundStub } from "./playground-stubs.js"; + +interface LoaderContext { + resourcePath: string; + async(): (error: Error | null, result?: string) => void; +} + +/** A webpack and Turbopack loader that replaces a fumadocs-openapi playground module with its inert stub. */ +export default function playgroundStubLoader(this: LoaderContext, source: string): void { + const callback = this.async(); + playgroundStub(this.resourcePath, source).then( + (stub) => callback(null, stub), + (error: Error) => callback(error), + ); +} diff --git a/packages/docs-next/src/openapi/playground-stubs.test.ts b/packages/docs-next/src/openapi/playground-stubs.test.ts new file mode 100644 index 00000000..c2445187 --- /dev/null +++ b/packages/docs-next/src/openapi/playground-stubs.test.ts @@ -0,0 +1,118 @@ +import assert from "node:assert/strict"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { init, parse } from "es-module-lexer"; +import { + OPENAPI_PLAYGROUND_MARKERS, + OPENAPI_PLAYGROUND_MODULE, + OPENAPI_PLAYGROUND_STUBBED, + playgroundStub, +} from "./playground-stubs.js"; + +const dist = path.dirname( + path.dirname(fileURLToPath(import.meta.resolve("fumadocs-openapi/ui/base"))), +); +const read = (rel: string) => readFileSync(path.join(dist, rel), "utf8"); +const markersIn = (source: string) => OPENAPI_PLAYGROUND_MARKERS.filter((m) => source.includes(m)); + +// The fumadocs-openapi modules the engine imports, as package.json's exports map them. +const ENTRIES = [ + "index.js", + "index.browser.js", + "operation.js", + "requests/generators/index.js", + "server/index.js", + "ui/base.js", +]; + +/** Every module reached from the entries over relative imports, each stubbed module replaced by its stub. */ +async function reachable(stubbed: boolean): Promise> { + await init; + const sources = new Map(); + const queue = [...ENTRIES]; + while (queue.length > 0) { + const rel = queue.pop(); + if (rel === undefined || sources.has(rel)) continue; + const file = path.join(dist, rel); + const source = + stubbed && OPENAPI_PLAYGROUND_MODULE.test(file) + ? await playgroundStub(file, read(rel)) + : read(rel); + sources.set(rel, source); + for (const { n } of parse(source, rel)[0]) { + if (n?.startsWith(".")) queue.push(path.posix.join(path.posix.dirname(rel), n)); + } + } + return sources; +} + +test("every stubbed module exists in the installed fumadocs-openapi", () => { + for (const rel of OPENAPI_PLAYGROUND_STUBBED) { + assert.ok(existsSync(path.join(dist, rel)), rel); + assert.match(path.join(dist, rel), OPENAPI_PLAYGROUND_MODULE); + } +}); + +test("each stub keeps its module's exports and holds none of the playground's code", async () => { + await init; + for (const rel of OPENAPI_PLAYGROUND_STUBBED) { + const source = read(rel); + const stub = await playgroundStub(path.join(dist, rel), source); + const names = (text: string) => + parse(text, rel)[1] + .map((e) => e.n) + .toSorted(); + assert.deepEqual(names(stub), names(source), rel); + assert.deepEqual(markersIn(stub), [], rel); + assert.equal(/\bfetch\(|sessionStorage|localStorage/.test(stub), false, rel); + } +}); + +test("every marker is in the code the stubs replace", () => { + const replaced = OPENAPI_PLAYGROUND_STUBBED.map(read).join("\n"); + for (const marker of OPENAPI_PLAYGROUND_MARKERS) assert.ok(replaced.includes(marker), marker); +}); + +test("the stubs cut every path from the engine's entries to playground code", async () => { + const unstubbed = [...(await reachable(false))].filter(([, s]) => markersIn(s).length > 0); + assert.ok(unstubbed.length > 0, "the entries reach no playground code even without the stubs"); + const stubbed = [...(await reachable(true))].filter(([, s]) => markersIn(s).length > 0); + assert.deepEqual( + stubbed.map(([rel]) => rel), + [], + ); +}); + +test("the stub of the auth provider renders its children", async () => { + const stub = await playgroundStub( + path.join(dist, "playground/auth.js"), + read("playground/auth.js"), + ); + const url = `data:text/javascript,${encodeURIComponent(stub.replace('"use client";', ""))}`; + const auth = (await import(url)) as { + PlaygroundAuthProvider: (p: { children: string }) => string; + }; + assert.equal(auth.PlaygroundAuthProvider({ children: "page" }), "page"); +}); + +test("a matched module with no stub, or with other exports, fails the build", async () => { + await assert.rejects( + playgroundStub(path.join(dist, "playground/index.js"), read("playground/index.js")), + /no inert stub/, + ); + await assert.rejects( + playgroundStub( + path.join(dist, "playground/fetcher.js"), + `${read("playground/fetcher.js")}\nexport const added = 1;`, + ), + /exports/, + ); +}); + +test("modules outside the playground are not matched", () => { + for (const rel of ["ui/operation/index.js", "utils/create-page.js", "server/index.js"]) { + assert.equal(OPENAPI_PLAYGROUND_MODULE.test(path.join(dist, rel)), false, rel); + } +}); diff --git a/packages/docs-next/src/openapi/playground-stubs.ts b/packages/docs-next/src/openapi/playground-stubs.ts new file mode 100644 index 00000000..4336958b --- /dev/null +++ b/packages/docs-next/src/openapi/playground-stubs.ts @@ -0,0 +1,89 @@ +import { init, parse } from "es-module-lexer"; + +/** fumadocs-openapi's modules that send requests or run auth flows: the API playground, its OAuth flows and fetcher, and the server's proxy and OAuth redirect handler. */ +export const OPENAPI_PLAYGROUND_MODULE = + /[\\/]fumadocs-openapi[\\/]dist[\\/]((?:ui[\\/])?playground[\\/][^\\/]+\.js|server[\\/](?:proxy|oauth)\.js)$/; + +/** Strings found only in those modules: JavaScript that holds one ships playground code. */ +export const OPENAPI_PLAYGROUND_MARKERS = [ + "fumadocs-openapi-flow", + "fumadocs-openapi-oauth", + "grant_type", + "device_code", + "proxyForwardCookie", + "is required for proxy url", +]; + +const unavailable = `function unavailable() { + throw new Error("fumadocs-openapi's API playground is not included in this build"); +}`; + +const STUBS: Record = { + "playground/auth.js": `"use client"; +${unavailable} +export function PlaygroundAuthProvider({ children }) { + return children; +} +export { + unavailable as finishOAuthFlow, + unavailable as requestOAuthToken, + unavailable as useAuthFields, + unavailable as useAuthRedirect, + unavailable as useOpenIdConnectFlows, + unavailable as usePlaygroundAuth, +}; +`, + "playground/fetcher.js": `${unavailable} +export { unavailable as createBrowserFetcher, unavailable as proxied }; +`, + "playground/use-playground.js": `"use client"; +${unavailable} +export { unavailable as usePlayground }; +`, + "ui/playground/client.js": `"use client"; +${unavailable} +export default function PlaygroundClient() { + return null; +} +export function DefaultResultDisplay() { + return null; +} +export const Custom = { useController: unavailable }; +`, + "server/proxy.js": `${unavailable} +export { unavailable as createProxy }; +`, + "server/oauth.js": `${unavailable} +export { unavailable as createOAuthHandler }; +`, +}; + +/** The modules that have a stub, relative to fumadocs-openapi's `dist/`. */ +export const OPENAPI_PLAYGROUND_STUBBED = Object.keys(STUBS); + +const exportNames = (source: string, file: string): string[] => + parse(source, file)[1] + .map((entry) => entry.n) + .toSorted(); + +/** + * The inert stand-in for the fumadocs-openapi module at `file`, whose own code + * is `source`. Rejects when the module has no stub or the stub's exports + * differ from the module's, so an upgrade that changes either fails the build. + */ +export async function playgroundStub(file: string, source: string): Promise { + await init; + const rel = OPENAPI_PLAYGROUND_MODULE.exec(file)?.[1]?.replaceAll("\\", "/"); + const stub = rel === undefined ? undefined : STUBS[rel]; + if (rel === undefined || stub === undefined) { + throw new Error(`no inert stub for ${file}; stub it in @coder/docs-next before using it`); + } + const want = exportNames(source, file); + const have = exportNames(stub, `${rel} stub`); + if (want.join() !== have.join()) { + throw new Error( + `fumadocs-openapi's ${rel} exports ${want.join(", ")}, but its stub exports ${have.join(", ")}`, + ); + } + return stub; +} diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css index 9cde0945..464ee18f 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -677,16 +677,9 @@ samp { transition-property: width, inset-block, transform, translate, background-color, visibility; } -/* fumadocs-openapi's method badges (on API pages, the landing cards, the sidebar and the page footer) and links are -600/-400 shades that fall short of 4.5:1 (7:1 for More contrast); the playground dialog is portalled out of the page. */ +/* fumadocs-openapi's method badges (on API pages, the landing cards, the sidebar and the page footer) and links are -600/-400 shades that fall short of 4.5:1 (7:1 for More contrast). */ :root:not(.dark) - :is( - .coder-api-page, - .coder-api-cards, - #nd-sidebar, - #nd-sidebar-mobile, - #nd-page > footer, - [data-base-ui-portal] > [role="dialog"] - ) { + :is(.coder-api-page, .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, #nd-page > footer) { --color-green-600: oklch(45% 0.13 150); --color-blue-600: oklch(48% 0.2 262); --color-orange-600: oklch(50% 0.15 50); @@ -695,14 +688,7 @@ samp { } :root[data-contrast="more"]:not(.dark) - :is( - .coder-api-page, - .coder-api-cards, - #nd-sidebar, - #nd-sidebar-mobile, - #nd-page > footer, - [data-base-ui-portal] > [role="dialog"] - ) { + :is(.coder-api-page, .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, #nd-page > footer) { --color-green-600: oklch(38% 0.1 150); --color-blue-600: oklch(40% 0.18 262); --color-orange-600: oklch(42% 0.13 50); @@ -711,14 +697,7 @@ samp { } :root[data-contrast="more"].dark - :is( - .coder-api-page, - .coder-api-cards, - #nd-sidebar, - #nd-sidebar-mobile, - #nd-page > footer, - [data-base-ui-portal] > [role="dialog"] - ) { + :is(.coder-api-page, .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, #nd-page > footer) { --color-green-400: oklch(88% 0.15 150); --color-blue-400: oklch(85% 0.1 262); --color-orange-400: oklch(86% 0.1 60); @@ -728,14 +707,7 @@ samp { @media (prefers-contrast: more) { :root:not([data-contrast="standard"]):not(.dark) - :is( - .coder-api-page, - .coder-api-cards, - #nd-sidebar, - #nd-sidebar-mobile, - #nd-page > footer, - [data-base-ui-portal] > [role="dialog"] - ) { + :is(.coder-api-page, .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, #nd-page > footer) { --color-green-600: oklch(38% 0.1 150); --color-blue-600: oklch(40% 0.18 262); --color-orange-600: oklch(42% 0.13 50); @@ -744,14 +716,7 @@ samp { } :root:not([data-contrast="standard"]).dark - :is( - .coder-api-page, - .coder-api-cards, - #nd-sidebar, - #nd-sidebar-mobile, - #nd-page > footer, - [data-base-ui-portal] > [role="dialog"] - ) { + :is(.coder-api-page, .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, #nd-page > footer) { --color-green-400: oklch(88% 0.15 150); --color-blue-400: oklch(85% 0.1 262); --color-orange-400: oklch(86% 0.1 60); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5a28bf02..796f8a04 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -407,6 +407,9 @@ importers: '@scalar/json-magic': specifier: 0.16.1 version: 0.16.1 + es-module-lexer: + specifier: 1.7.0 + version: 1.7.0 fumadocs-core: specifier: 'catalog:' version: 16.15.14(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.1(@types/node@22.20.1)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6) From effac499f84bbc7c3733a29b445f2ab385167018 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Thu, 29 Oct 2026 14:54:23 -0400 Subject: [PATCH 48/69] ci: fail a build whose export ships API playground code playground:check scans every JavaScript file under an export directory for strings only fumadocs-openapi's playground, OAuth flows, fetcher and proxy hold, and fails on any hit. The build job runs it on the public site's and the offline export's out/, and the release dry run runs it on the builder kit's own export, which installs the published packages. An app that keeps the playground is simply not checked. Against the export built before the stubs it reports one chunk holding five of the markers; after them, none. Assisted-by: AI --- .github/workflows/ci.yml | 4 ++ apps/dist-release/src/smoke.mjs | 9 ++++ apps/docs/package.json | 1 + apps/offlinedocs/package.json | 1 + .../scripts/playground-check-helpers.mjs | 30 ++++++++++++ apps/offlinedocs/scripts/playground-check.mjs | 16 +++++++ .../scripts/playground-check.test.mjs | 46 +++++++++++++++++++ 7 files changed, 107 insertions(+) create mode 100644 apps/offlinedocs/scripts/playground-check-helpers.mjs create mode 100644 apps/offlinedocs/scripts/playground-check.mjs create mode 100644 apps/offlinedocs/scripts/playground-check.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 393db0c1..b2c8a07f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,6 +48,10 @@ jobs: run: pnpm --filter @coder/docs-site csp:check - name: No zod in first-load JavaScript (apps/docs) run: pnpm --filter @coder/docs-site first-load:check + - name: No API playground code (apps/offlinedocs) + run: pnpm --filter @coder/offlinedocs playground:check + - name: No API playground code (apps/docs) + run: pnpm --filter @coder/docs-site playground:check - name: URL and anchor parity (apps/docs) run: pnpm --filter @coder/docs-site parity:urls diff --git a/apps/dist-release/src/smoke.mjs b/apps/dist-release/src/smoke.mjs index 5fe63e4f..81072613 100644 --- a/apps/dist-release/src/smoke.mjs +++ b/apps/dist-release/src/smoke.mjs @@ -81,6 +81,15 @@ export async function smokeTestKit({ kitDir, assetsDir, version }) { if (!new JSDOM(html).window.document.title.trim()) { throw new Error("the kit's out/index.html has an empty "); } + // Imported here, once the packages it reads are built. + const { findPlaygroundCode } = + await import("../../offlinedocs/scripts/playground-check-helpers.mjs"); + const playground = await findPlaygroundCode(path.join(built, "out")); + if (playground.length > 0) { + throw new Error( + `the kit's export ships API playground code: ${playground.map((hit) => hit.file).join(", ")}`, + ); + } await checkFinalizedLockfile(kitDir, path.join(work, "finalized")); } finally { diff --git a/apps/docs/package.json b/apps/docs/package.json index 523e6873..a9d40a8d 100644 --- a/apps/docs/package.json +++ b/apps/docs/package.json @@ -13,6 +13,7 @@ "build": "node --import tsx scripts/build-versions.mjs", "archive:layout": "node scripts/archive-layout.mjs", "csp:check": "node ../offlinedocs/scripts/csp-check.mjs .", + "playground:check": "node ../offlinedocs/scripts/playground-check.mjs out", "first-load:check": "node scripts/first-load-js.mjs", "pretypecheck": "[ -n \"$TURBO_HASH\" ] || pnpm run sync", "typecheck": "tsc -p tsconfig.json --noEmit", diff --git a/apps/offlinedocs/package.json b/apps/offlinedocs/package.json index ed986d00..4c185b29 100644 --- a/apps/offlinedocs/package.json +++ b/apps/offlinedocs/package.json @@ -13,6 +13,7 @@ "build": "next build && node ../docs/scripts/relocate-twins.mjs out && node ../docs/scripts/semantic-index.mjs out", "build:output": "node scripts/build-output.mjs", "csp:check": "node scripts/csp-check.mjs", + "playground:check": "node scripts/playground-check.mjs out", "analytics:check": "node scripts/analytics-check.mjs", "annotations:check": "node scripts/annotations-check.mjs", "pretypecheck": "[ -n \"$TURBO_HASH\" ] || pnpm run sync", diff --git a/apps/offlinedocs/scripts/playground-check-helpers.mjs b/apps/offlinedocs/scripts/playground-check-helpers.mjs new file mode 100644 index 00000000..230d596b --- /dev/null +++ b/apps/offlinedocs/scripts/playground-check-helpers.mjs @@ -0,0 +1,30 @@ +import { readFile, readdir } from "node:fs/promises"; +import path from "node:path"; +import { OPENAPI_PLAYGROUND_MARKERS } from "@coder/docs-next/next-config"; + +/** + * Every JavaScript file under a static export that holds fumadocs-openapi + * playground code, with the markers it holds. Throws when the directory is + * missing or has no JavaScript, so a broken build never passes as clean. + * @param {string} exportDir + * @returns {Promise<{ file: string, markers: string[] }[]>} + */ +export async function findPlaygroundCode(exportDir) { + const entries = await readdir(exportDir, { recursive: true, withFileTypes: true }).catch( + (error) => { + throw new Error(`playground-check: ${exportDir} is missing; build first (${error.message})`); + }, + ); + const files = entries + .filter((entry) => entry.isFile() && /\.[cm]?js$/.test(entry.name)) + .map((entry) => path.join(entry.parentPath, entry.name)) + .toSorted(); + if (files.length === 0) throw new Error(`playground-check: no JavaScript under ${exportDir}`); + const found = []; + for (const file of files) { + const text = await readFile(file, "utf8"); + const markers = OPENAPI_PLAYGROUND_MARKERS.filter((marker) => text.includes(marker)); + if (markers.length > 0) found.push({ file: path.relative(exportDir, file), markers }); + } + return found; +} diff --git a/apps/offlinedocs/scripts/playground-check.mjs b/apps/offlinedocs/scripts/playground-check.mjs new file mode 100644 index 00000000..b759c7ea --- /dev/null +++ b/apps/offlinedocs/scripts/playground-check.mjs @@ -0,0 +1,16 @@ +// Fails when a static export ships fumadocs-openapi playground code: `node playground-check.mjs <exportDir>`. +import path from "node:path"; +import { findPlaygroundCode } from "./playground-check-helpers.mjs"; + +if (!process.argv[2]) { + console.error("usage: node playground-check.mjs <exportDir>"); + process.exit(2); +} +const exportDir = path.resolve(process.cwd(), process.argv[2]); +const found = await findPlaygroundCode(exportDir); +if (found.length > 0) { + console.error(`[playground-check] API playground code in ${found.length} file(s):`); + for (const { file, markers } of found) console.error(` - ${file}: ${markers.join(", ")}`); + process.exit(1); +} +console.log(`[playground-check] ${exportDir}: no API playground code`); diff --git a/apps/offlinedocs/scripts/playground-check.test.mjs b/apps/offlinedocs/scripts/playground-check.test.mjs new file mode 100644 index 00000000..4bceb168 --- /dev/null +++ b/apps/offlinedocs/scripts/playground-check.test.mjs @@ -0,0 +1,46 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { OPENAPI_PLAYGROUND_MARKERS } from "@coder/docs-next/next-config"; +import { findPlaygroundCode } from "./playground-check-helpers.mjs"; + +async function exportWith(files) { + const dir = await mkdtemp(path.join(tmpdir(), "playground-check-")); + for (const [rel, text] of Object.entries(files)) { + await mkdir(path.dirname(path.join(dir, rel)), { recursive: true }); + await writeFile(path.join(dir, rel), text); + } + return dir; +} + +test("finds each marker in the export's JavaScript", async (t) => { + for (const marker of OPENAPI_PLAYGROUND_MARKERS) { + const dir = await exportWith({ + "_next/static/chunks/a.js": "console.log(1)", + "_next/static/chunks/b.js": `sessionStorage.getItem(${JSON.stringify(marker)})`, + }); + t.after(() => rm(dir, { recursive: true, force: true })); + assert.deepEqual(await findPlaygroundCode(dir), [ + { file: path.join("_next", "static", "chunks", "b.js"), markers: [marker] }, + ]); + } +}); + +test("passes an export without playground code, and ignores page data", async (t) => { + const dir = await exportWith({ + "_next/static/chunks/a.js": "console.log(1)", + "reference/api/index.html": "<p>grant_type</p>", + "reference/api/index.txt": "device_code", + }); + t.after(() => rm(dir, { recursive: true, force: true })); + assert.deepEqual(await findPlaygroundCode(dir), []); +}); + +test("fails closed on a missing export or one with no JavaScript", async (t) => { + const dir = await exportWith({ "index.html": "<p></p>" }); + t.after(() => rm(dir, { recursive: true, force: true })); + await assert.rejects(findPlaygroundCode(dir), /no JavaScript/); + await assert.rejects(findPlaygroundCode(path.join(dir, "missing")), /is missing/); +}); From 41e09d76ea3bd75889f8adba7d98e20ec2d59cda Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nickvigilante@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:57:13 -0400 Subject: [PATCH 49/69] test(docs-site): skip the playground stub loader when finding MDX loaders The Next config now carries withoutOpenApiPlayground's Turbopack rule, whose loader is a bare path rather than a { loader, options } entry, so the MDX cache-key test's loader lookup has to pass over it. Assisted-by: AI --- apps/docs/scripts/mdx-cache-key.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/docs/scripts/mdx-cache-key.test.mjs b/apps/docs/scripts/mdx-cache-key.test.mjs index 5fd0dfd2..49d36c6c 100644 --- a/apps/docs/scripts/mdx-cache-key.test.mjs +++ b/apps/docs/scripts/mdx-cache-key.test.mjs @@ -12,7 +12,7 @@ process.env._FUMADOCS_MDX = "1"; const fumadocsLoaders = (config) => Object.values(config.turbopack.rules) .flatMap((rule) => rule.loaders) - .filter((loader) => loader.loader.startsWith("fumadocs-mdx/")); + .filter((loader) => typeof loader === "object" && loader.loader.startsWith("fumadocs-mdx/")); async function fakeRepo() { const root = await mkdtemp(path.join(tmpdir(), "mdx-cache-key-")); From a3ace949402a582798e242ea260bd786aee21f8a Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nickvigilante@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:57:13 -0400 Subject: [PATCH 50/69] refactor(docs-config): hold the REST API reference contract in one module The sync writes the reference data and both apps read it back with a cast, but the writer and the reader each declared the file's shape, so a renamed field compiled on both sides and failed only when an API page rendered. The shape now lives in @coder/docs-config's openapi module as OpenApiPagesData and its parts; the writer checks its output with satisfies and the renderer reads the same type. An operation's method is an HttpMethod, which drops the cast at the fumadocs-openapi call. The module also holds what the packages kept private copies of: isObject (in json.ts, also used by docs-ui's versions document checks), collectRefs beside findExternalRef, HTTP_METHODS with isHttpMethod (the sync's _openapi check and the samples format check use it), the reference's directory, the CODER_URL and CODER_SESSION_TOKEN names the samples, their note and the setup section print, and the session token header. The client-safe parts are re-exported from /client, which still imports no package. Assisted-by: AI --- apps/docs/lib/openapi.ts | 3 +- apps/docs/scripts/code-samples-format.mjs | 4 +- apps/offlinedocs/lib/openapi.ts | 3 +- packages/docs-build/src/http-methods.ts | 11 -- packages/docs-build/src/index.ts | 7 +- packages/docs-build/src/openapi-output.ts | 4 +- packages/docs-build/src/openapi-reference.ts | 100 ++++--------- packages/docs-build/src/sync.ts | 28 ++-- packages/docs-config/src/client.ts | 22 +++ packages/docs-config/src/index.ts | 3 +- packages/docs-config/src/json.ts | 6 + packages/docs-config/src/openapi-refs.test.ts | 24 ---- packages/docs-config/src/openapi-refs.ts | 32 ----- packages/docs-config/src/openapi.test.ts | 61 ++++++++ packages/docs-config/src/openapi.ts | 133 ++++++++++++++++++ .../docs-next/src/openapi/code-samples.ts | 46 +++--- packages/docs-next/src/openapi/index.test.tsx | 3 +- packages/docs-next/src/openapi/index.tsx | 57 +++----- .../docs-next/src/openapi/landing.test.tsx | 5 +- packages/docs-next/src/openapi/landing.tsx | 14 +- .../docs-next/src/openapi/samples-note.tsx | 3 +- .../docs-next/src/openapi/schemas.test.tsx | 5 +- packages/docs-next/src/openapi/schemas.tsx | 13 +- .../docs-next/src/openapi/stored-server.ts | 5 +- .../docs-ui/src/runtime-version-switcher.tsx | 11 +- .../docs-ui/src/versions-document-client.ts | 9 +- 26 files changed, 341 insertions(+), 271 deletions(-) delete mode 100644 packages/docs-build/src/http-methods.ts create mode 100644 packages/docs-config/src/json.ts delete mode 100644 packages/docs-config/src/openapi-refs.test.ts delete mode 100644 packages/docs-config/src/openapi-refs.ts create mode 100644 packages/docs-config/src/openapi.test.ts create mode 100644 packages/docs-config/src/openapi.ts diff --git a/apps/docs/lib/openapi.ts b/apps/docs/lib/openapi.ts index 585bf4a9..94aeda40 100644 --- a/apps/docs/lib/openapi.ts +++ b/apps/docs/lib/openapi.ts @@ -1,6 +1,7 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; -import { type OpenApiPagesData, createOpenApiRenderBody } from "@coder/docs-next/openapi"; +import type { OpenApiPagesData } from "@coder/docs-config"; +import { createOpenApiRenderBody } from "@coder/docs-next/openapi"; const cache = new Map<string, Promise<OpenApiPagesData | undefined>>(); diff --git a/apps/docs/scripts/code-samples-format.mjs b/apps/docs/scripts/code-samples-format.mjs index 0647f5b8..17627119 100644 --- a/apps/docs/scripts/code-samples-format.mjs +++ b/apps/docs/scripts/code-samples-format.mjs @@ -12,12 +12,12 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; import { convertSwagger } from "@coder/docs-build"; +import { HTTP_METHODS } from "@coder/docs-config"; import { codeSamples } from "@coder/docs-next/openapi/code-samples"; const run = promisify(execFile); const appDir = path.dirname(path.dirname(fileURLToPath(import.meta.url))); const oxfmt = path.join(appDir, "..", "..", "node_modules", ".bin", "oxfmt"); -const METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"]; const EXTENSIONS = { curl: "sh", javascript: "mjs", python: "py", go: "go" }; function parseArgs(argv) { @@ -33,7 +33,7 @@ async function writeSamples(swagger, dir) { const { document } = await convertSwagger(swagger); let count = 0; for (const [route, item] of Object.entries(document.paths ?? {})) { - for (const method of METHODS) { + for (const method of HTTP_METHODS) { if (!item?.[method]) continue; const name = `${method}${route.replace(/[^\w]+/g, "_")}`; for (const sample of codeSamples(document, route, method)) { diff --git a/apps/offlinedocs/lib/openapi.ts b/apps/offlinedocs/lib/openapi.ts index 0ba99ca7..ae2c9c64 100644 --- a/apps/offlinedocs/lib/openapi.ts +++ b/apps/offlinedocs/lib/openapi.ts @@ -1,5 +1,6 @@ import { readFile } from "node:fs/promises"; -import { type OpenApiPagesData, createOpenApiRenderBody } from "@coder/docs-next/openapi"; +import type { OpenApiPagesData } from "@coder/docs-config"; +import { createOpenApiRenderBody } from "@coder/docs-next/openapi"; import { openApiDataFile } from "../scripts/sync-helpers.mjs"; let cached: Promise<OpenApiPagesData | undefined> | undefined; diff --git a/packages/docs-build/src/http-methods.ts b/packages/docs-build/src/http-methods.ts deleted file mode 100644 index 69998ad0..00000000 --- a/packages/docs-build/src/http-methods.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** The operation keys of an OpenAPI path item, in the order the reference lists them. */ -export const HTTP_METHODS = [ - "get", - "put", - "post", - "delete", - "options", - "head", - "patch", - "trace", -] as const; diff --git a/packages/docs-build/src/index.ts b/packages/docs-build/src/index.ts index 98e3eef2..f448f43a 100644 --- a/packages/docs-build/src/index.ts +++ b/packages/docs-build/src/index.ts @@ -17,10 +17,5 @@ export { rendersOpenApi, withOpenApiReference, } from "./openapi-output.js"; -export type { - ApplyOpenApiReferenceOptions, - OpenApiOperationRef, - OpenApiReference, - OpenApiSchemas, -} from "./openapi-reference.js"; +export type { ApplyOpenApiReferenceOptions, OpenApiReference } from "./openapi-reference.js"; export type { WithOpenApiReferenceOptions } from "./openapi-output.js"; diff --git a/packages/docs-build/src/openapi-output.ts b/packages/docs-build/src/openapi-output.ts index 6a651ae9..10d8fbc3 100644 --- a/packages/docs-build/src/openapi-output.ts +++ b/packages/docs-build/src/openapi-output.ts @@ -1,6 +1,6 @@ import { mkdir, rm, writeFile } from "node:fs/promises"; import path from "node:path"; -import type { DocSource } from "@coder/docs-config"; +import type { DocSource, OpenApiPagesData } from "@coder/docs-config"; import { isLineAtLeast } from "@coder/docs-manifest/version-segment"; import { applyOpenApiReference } from "./openapi-reference.js"; @@ -72,7 +72,7 @@ export async function withOpenApiReference( anchors: reference.anchors, landing: reference.landing, schemas: reference.schemas, - }), + } satisfies OpenApiPagesData), ); logger.log( `[sync] ${version.id}: API reference, ${Object.keys(reference.operations).length} operation pages in ${Date.now() - started} ms`, diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index ada95690..88287464 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -1,65 +1,33 @@ import { + API_REFERENCE_DIR, assertInDocumentRefs, + collectRefs, + DEPLOYMENT_URL_ENV, type DocFile, type DocSource, + HTTP_METHODS, + type HttpMethod, + isObject, + type JsonObject, type ManifestNode, + type OpenApiLandingSection, + type OpenApiOperationRef, + type OpenApiPagesData, + SESSION_TOKEN_ENV, } from "@coder/docs-config"; import { buildDirRoutes, findHeadings, mapMdPath, parseFrontmatter } from "@coder/docs-transforms"; import GithubSlugger from "github-slugger"; import { validate } from "oas-validator"; import { convertObj } from "swagger2openapi"; -import { HTTP_METHODS } from "./http-methods.js"; - -type Json = Record<string, unknown>; - -export interface OpenApiOperationRef { - method: string; - path: string; -} /** * The REST API reference built from coder/coder's Swagger 2.0 document: the - * OpenAPI 3 document the pages render from, the page route of every - * operation, and the old single-page anchors each tag page and the schemas - * page redirect to. + * data the page renderer reads, and what the conversion warned about. */ -export interface OpenApiReference { - document: Json; - operations: Record<string, OpenApiOperationRef>; - anchors: Record<string, Record<string, string>>; - landing: OpenApiLanding; - schemas: OpenApiSchemas; +export interface OpenApiReference extends OpenApiPagesData { warnings: string[]; } -/** The schemas page: its route, and each schema with the operation page that shows it most directly. */ -export interface OpenApiSchemas { - route: string; - rows: { name: string; operation?: { title: string; route: string } }[]; -} - -/** An operation's card on the landing page. */ -export interface LandingOperation { - route: string; - title: string; - method: string; - description?: string; -} - -/** A tag's cards, under a heading of their own, in sidebar order. */ -export interface LandingSection { - title: string; - id: string; - operations: LandingOperation[]; -} - -/** The landing page (`index.md`): its route, its setup section's id, and its card sections. */ -export interface OpenApiLanding { - route: string; - setupId: string; - sections: LandingSection[]; -} - export interface ApplyOpenApiReferenceOptions { /** The docs-relative directory of the generated reference; defaults to `reference/api`. */ dir?: string; @@ -67,9 +35,6 @@ export interface ApplyOpenApiReferenceOptions { server?: { url: string; variables?: Record<string, { default: string; description?: string }> }; } -const isObject = (value: unknown): value is Json => - typeof value === "object" && value !== null && !Array.isArray(value); - const UNNAMEABLE = "has no characters to name its page by"; export const tagSlug = (tag: string): string => tag.toLowerCase().replace(/[^a-z0-9]/g, ""); @@ -92,21 +57,10 @@ function codeSpan(text: string): string { const frontmatter = (title: string, method?: string): string => `---\ntitle: ${JSON.stringify(title)}\n${method ? `_openapi:\n method: ${method}\n` : ""}---\n\n`; -function collectRefs(value: unknown, into: Set<string>): void { - if (Array.isArray(value)) { - for (const item of value) collectRefs(item, into); - } else if (isObject(value)) { - for (const [key, child] of Object.entries(value)) { - if (key === "$ref" && typeof child === "string") into.add(child); - else collectRefs(child, into); - } - } -} - const SCHEMA_REF = "#/components/schemas/"; /** Each schema an operation reaches, with how many `$ref` hops away it is. */ -function schemaDepths(roots: unknown, schemas: Json): Map<string, number> { +function schemaDepths(roots: unknown, schemas: JsonObject): Map<string, number> { const depths = new Map<string, number>(); let frontier = new Set<string>(); collectRefs(roots, frontier); @@ -141,14 +95,14 @@ function withBasePathInPaths(swagger: unknown): unknown { } /** Schemes coderd authenticates with but its Swagger document never declares, as `httpmw` reads them. */ -const UNDECLARED_SCHEMES: Record<string, Json> = { +const UNDECLARED_SCHEMES: Record<string, JsonObject> = { CoderProvisionerKey: { type: "apiKey", in: "header", name: "Coder-Provisioner-Daemon-Key" }, }; /** Converts Swagger 2.0 to OpenAPI 3, repairs the defects that make it invalid, and validates it. */ export async function convertSwagger( swagger: unknown, -): Promise<{ document: Json; warnings: string[] }> { +): Promise<{ document: JsonObject; warnings: string[] }> { const warnings: string[] = []; assertInDocumentRefs(swagger, "swagger.json"); const converted = await convertObj(withBasePathInPaths(swagger), { @@ -163,9 +117,9 @@ export async function convertSwagger( warnings.push(`swagger2openapi: ${JSON.stringify(warning)}`); if (!isObject(document.components)) document.components = {}; - const components = document.components as Json; + const components = document.components as JsonObject; if (!isObject(components.securitySchemes)) components.securitySchemes = {}; - const schemes = components.securitySchemes as Json; + const schemes = components.securitySchemes as JsonObject; for (const [route, item] of Object.entries(isObject(document.paths) ? document.paths : {})) { if (!isObject(item)) continue; for (const method of HTTP_METHODS) { @@ -205,7 +159,7 @@ export async function convertSwagger( } /** Throws when a converted document holds a `$ref` the renderer's bundler would fetch or read, or is not valid OpenAPI. */ -export async function assertConvertedDocument(spec: Json): Promise<void> { +export async function assertConvertedDocument(spec: JsonObject): Promise<void> { assertInDocumentRefs(spec, "the converted OpenAPI document"); const result = await validate(spec, { lint: false, @@ -229,7 +183,7 @@ export async function applyOpenApiReference( swagger: unknown, options: ApplyOpenApiReferenceOptions = {}, ): Promise<{ source: DocSource; reference: OpenApiReference }> { - const dir = options.dir ?? "reference/api"; + const dir = options.dir ?? API_REFERENCE_DIR; const { document, warnings } = await convertSwagger(swagger); document.servers = [ options.server ?? { @@ -254,7 +208,7 @@ export async function applyOpenApiReference( } interface Op { - method: string; + method: HttpMethod; path: string; summary: string; description?: string; @@ -414,7 +368,7 @@ export async function applyOpenApiReference( anchors[routeOf(schemasFile)] = schemaAnchors; const tagByFile = new Map([...byTag.keys()].map((tag) => [manifestPath(tagFile(tag)), tag])); - const sections: LandingSection[] = []; + const sections: OpenApiLandingSection[] = []; for (const child of children) { const tag = child.path === undefined ? undefined : tagByFile.get(child.path); const group = tag === undefined ? undefined : byTag.get(tag); @@ -456,13 +410,13 @@ const SETUP_HEADING = "Set up your environment"; const SETUP_SECTION = `## ${SETUP_HEADING} -The code samples on each endpoint's page read your deployment URL and a session token from two environment variables, \`CODER_URL\` and \`CODER_SESSION_TOKEN\`, the same ones the Coder CLI reads. +The code samples on each endpoint's page read your deployment URL and a session token from two environment variables, \`${DEPLOYMENT_URL_ENV}\` and \`${SESSION_TOKEN_ENV}\`, the same ones the Coder CLI reads. If you are logged in with the Coder CLI v2.31.1 or later and have \`jq\` installed, set both from your login: \`\`\`sh -export CODER_URL="$(coder whoami -o json | jq -r '.[0].url')" -export CODER_SESSION_TOKEN="$(coder login token)" +export ${DEPLOYMENT_URL_ENV}="$(coder whoami -o json | jq -r '.[0].url')" +export ${SESSION_TOKEN_ENV}="$(coder login token)" \`\`\` For scripts and CI, create a long-lived token instead, with \`coder tokens create\` or under **Settings** > **Tokens** in the dashboard: @@ -474,8 +428,8 @@ coder tokens create --name ci --lifetime 30d Store the token in your secret store, and set the variables from it where the script runs: \`\`\`sh -export CODER_URL="https://coder.example.com" -export CODER_SESSION_TOKEN="$(cat /run/secrets/coder-token)" +export ${DEPLOYMENT_URL_ENV}="https://coder.example.com" +export ${SESSION_TOKEN_ENV}="$(cat /run/secrets/coder-token)" \`\`\` Keep the token out of your shell history and out of committed files. diff --git a/packages/docs-build/src/sync.ts b/packages/docs-build/src/sync.ts index 59a74565..3e358868 100644 --- a/packages/docs-build/src/sync.ts +++ b/packages/docs-build/src/sync.ts @@ -1,6 +1,14 @@ import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; -import { DOC_STATE_IDS, experimentDisplayName, isCodeTitle, isDocState } from "@coder/docs-config"; +import { + DOC_STATE_IDS, + experimentDisplayName, + HTTP_METHODS, + isCodeTitle, + isDocState, + isHttpMethod, + isObject, +} from "@coder/docs-config"; import type { DocImage, DocSource, ManifestIssue } from "@coder/docs-config"; import { FrontmatterError, @@ -26,7 +34,6 @@ import { stripHtmlComments, } from "@coder/docs-transforms"; import { imageSize } from "@fumari/image-size"; -import { HTTP_METHODS } from "./http-methods.js"; import { MAX_INCLUDE_DEPTH, expandIncludes } from "./includes.js"; import { reservedAssetReason, reservedRouteReason } from "./reserved-routes.js"; @@ -532,8 +539,6 @@ function formatIssues(i: SyncIssues): string { return `docs sync found ${parts.length} blocking issue group(s):\n${parts.join("\n\n")}`; } -const OPENAPI_METHODS = new Set<string>(HTTP_METHODS); - function yamlString(s: string): string { return JSON.stringify(String(s)); } @@ -877,17 +882,12 @@ export async function syncDocSource( let openapiMethod: string | null = null; if (openapiRaw !== undefined) { const method = - typeof openapiRaw === "object" && openapiRaw !== null && !Array.isArray(openapiRaw) - ? (openapiRaw as Record<string, unknown>).method + isObject(openapiRaw) && Object.keys(openapiRaw).length === 1 + ? openapiRaw.method : undefined; - const keys = - typeof openapiRaw === "object" && openapiRaw !== null ? Object.keys(openapiRaw) : []; - if ( - typeof method === "string" && - OPENAPI_METHODS.has(method.toLowerCase()) && - keys.length === 1 - ) { - openapiMethod = method.toLowerCase(); + const lower = typeof method === "string" ? method.toLowerCase() : undefined; + if (isHttpMethod(lower)) { + openapiMethod = lower; } else { issues.invalidOpenApi.push({ source: rel, diff --git a/packages/docs-config/src/client.ts b/packages/docs-config/src/client.ts index b6e09559..f90fcd93 100644 --- a/packages/docs-config/src/client.ts +++ b/packages/docs-config/src/client.ts @@ -37,3 +37,25 @@ export { isCodeTitle, stripCodeTitle } from "./code-title.js"; export { DOC_STATE_IDS, DOC_STATE_ROUTES, DOC_STATES, isDocState } from "./doc-states.js"; export type { DocState, DocStateId, DocStateLink, DocStateTone } from "./doc-states.js"; export { USER_CONTENT_PREFIX } from "./user-content.js"; + +export { + API_REFERENCE_DIR, + collectRefs, + DEPLOYMENT_URL_ENV, + HTTP_METHODS, + isApiReferenceSlug, + isHttpMethod, + SESSION_TOKEN_ENV, + SESSION_TOKEN_HEADER, +} from "./openapi.js"; +export type { + HttpMethod, + OpenApiLanding, + OpenApiLandingOperation, + OpenApiLandingSection, + OpenApiOperationRef, + OpenApiPagesData, + OpenApiSchemaRow, + OpenApiSchemas, +} from "./openapi.js"; +export { isObject, type JsonObject } from "./json.js"; diff --git a/packages/docs-config/src/index.ts b/packages/docs-config/src/index.ts index cd5160fb..28f40c7e 100644 --- a/packages/docs-config/src/index.ts +++ b/packages/docs-config/src/index.ts @@ -106,4 +106,5 @@ export { } from "./analytics.js"; export { USER_CONTENT_PREFIX } from "./user-content.js"; -export { assertInDocumentRefs, findExternalRef } from "./openapi-refs.js"; +export * from "./openapi.js"; +export { isObject, type JsonObject } from "./json.js"; diff --git a/packages/docs-config/src/json.ts b/packages/docs-config/src/json.ts new file mode 100644 index 00000000..d68593a1 --- /dev/null +++ b/packages/docs-config/src/json.ts @@ -0,0 +1,6 @@ +/** A parsed JSON object. */ +export type JsonObject = Record<string, unknown>; + +/** Whether `value` is a plain object: not `null`, not an array. */ +export const isObject = (value: unknown): value is JsonObject => + typeof value === "object" && value !== null && !Array.isArray(value); diff --git a/packages/docs-config/src/openapi-refs.test.ts b/packages/docs-config/src/openapi-refs.test.ts deleted file mode 100644 index 81b9f5c3..00000000 --- a/packages/docs-config/src/openapi-refs.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import assert from "node:assert/strict"; -import { test } from "node:test"; -import { assertInDocumentRefs, findExternalRef } from "./openapi-refs.js"; - -test("in-document references pass", () => { - assert.equal( - findExternalRef({ a: { $ref: "#/definitions/x" }, b: [{ $ref: "#/c" }] }), - undefined, - ); -}); - -test("a URL or file reference is found by its JSON pointer", () => { - assert.equal( - findExternalRef({ - paths: { "/a/b": { get: { schema: { $ref: "https://example.com/x.json" } } } }, - }), - "/paths/~1a~1b/get/schema/$ref", - ); - assert.equal(findExternalRef({ list: [{}, { $ref: "../x.json" }] }), "/list/1/$ref"); - assert.throws( - () => assertInDocumentRefs({ $ref: "../x.json" }, "swagger.json"), - /\$ref at \/\$ref/, - ); -}); diff --git a/packages/docs-config/src/openapi-refs.ts b/packages/docs-config/src/openapi-refs.ts deleted file mode 100644 index 31f7a278..00000000 --- a/packages/docs-config/src/openapi-refs.ts +++ /dev/null @@ -1,32 +0,0 @@ -const escapePointer = (key: string) => key.replace(/~/g, "~0").replace(/\//g, "~1"); - -/** - * The JSON pointer of the first `$ref` that is not an in-document reference - * (`#/...`), or `undefined` when there is none. An OpenAPI bundler fetches or - * reads any other reference at build time, so an API document has to be - * rejected before it reaches one. - */ -export function findExternalRef(value: unknown, pointer = ""): string | undefined { - if (Array.isArray(value)) { - for (const [index, item] of value.entries()) { - const found = findExternalRef(item, `${pointer}/${index}`); - if (found !== undefined) return found; - } - } else if (typeof value === "object" && value !== null) { - for (const [key, child] of Object.entries(value)) { - const at = `${pointer}/${escapePointer(key)}`; - if (key === "$ref" && (typeof child !== "string" || !child.startsWith("#/"))) return at; - const found = findExternalRef(child, at); - if (found !== undefined) return found; - } - } - return undefined; -} - -/** Throws, naming the JSON pointer, when the document holds a `$ref` that is not `#/...`. */ -export function assertInDocumentRefs(document: unknown, label: string): void { - const pointer = findExternalRef(document); - if (pointer !== undefined) { - throw new Error(`${label}: $ref at ${pointer || "/"} is not an in-document reference (#/...)`); - } -} diff --git a/packages/docs-config/src/openapi.test.ts b/packages/docs-config/src/openapi.test.ts new file mode 100644 index 00000000..13b4f9f5 --- /dev/null +++ b/packages/docs-config/src/openapi.test.ts @@ -0,0 +1,61 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + API_REFERENCE_DIR, + HTTP_METHODS, + assertInDocumentRefs, + collectRefs, + findExternalRef, + isApiReferenceSlug, + isHttpMethod, +} from "./openapi.js"; +import { isObject } from "./json.js"; + +test("in-document references pass", () => { + assert.equal( + findExternalRef({ a: { $ref: "#/definitions/x" }, b: [{ $ref: "#/c" }] }), + undefined, + ); +}); + +test("a URL or file reference is found by its JSON pointer", () => { + assert.equal( + findExternalRef({ + paths: { "/a/b": { get: { schema: { $ref: "https://example.com/x.json" } } } }, + }), + "/paths/~1a~1b/get/schema/$ref", + ); + assert.equal(findExternalRef({ list: [{}, { $ref: "../x.json" }] }), "/list/1/$ref"); + assert.throws( + () => assertInDocumentRefs({ $ref: "../x.json" }, "swagger.json"), + /\$ref at \/\$ref/, + ); +}); + +test("isObject accepts plain objects only", () => { + assert.equal(isObject({}), true); + assert.equal(isObject({ a: 1 }), true); + for (const value of [null, undefined, [], "x", 1, true]) assert.equal(isObject(value), false); +}); + +test("collectRefs gathers every string $ref, however deep", () => { + const refs = new Set<string>(); + collectRefs({ a: { $ref: "#/x" }, b: [{ c: { $ref: "#/y" } }, { $ref: 3 }], $ref: "#/z" }, refs); + assert.deepEqual([...refs].toSorted(), ["#/x", "#/y", "#/z"]); +}); + +test("isHttpMethod recognises an operation key", () => { + for (const method of HTTP_METHODS) assert.equal(isHttpMethod(method), true); + for (const value of ["GET", "parameters", "summary", 1, undefined]) { + assert.equal(isHttpMethod(value), false); + } +}); + +test("isApiReferenceSlug matches the reference and every page under it", () => { + assert.equal(API_REFERENCE_DIR, "reference/api"); + assert.equal(isApiReferenceSlug(["reference", "api"]), true); + assert.equal(isApiReferenceSlug(["reference", "api", "users", "get-user"]), true); + assert.equal(isApiReferenceSlug(["reference", "cli"]), false); + assert.equal(isApiReferenceSlug(["reference"]), false); + assert.equal(isApiReferenceSlug(["api", "reference"]), false); +}); diff --git a/packages/docs-config/src/openapi.ts b/packages/docs-config/src/openapi.ts new file mode 100644 index 00000000..6d259ec1 --- /dev/null +++ b/packages/docs-config/src/openapi.ts @@ -0,0 +1,133 @@ +import { isObject, type JsonObject } from "./json.js"; + +/** Adds every string `$ref` under `value` to `into`. */ +export function collectRefs(value: unknown, into: Set<string>): void { + if (Array.isArray(value)) { + for (const item of value) collectRefs(item, into); + } else if (isObject(value)) { + for (const [key, child] of Object.entries(value)) { + if (key === "$ref" && typeof child === "string") into.add(child); + else collectRefs(child, into); + } + } +} + +/** The operation keys of an OpenAPI path item, in the order the reference lists them. */ +export const HTTP_METHODS = [ + "get", + "put", + "post", + "delete", + "options", + "head", + "patch", + "trace", +] as const; + +export type HttpMethod = (typeof HTTP_METHODS)[number]; + +const HTTP_METHOD_SET: ReadonlySet<unknown> = new Set(HTTP_METHODS); + +export const isHttpMethod = (value: unknown): value is HttpMethod => HTTP_METHOD_SET.has(value); + +/** The docs-relative directory of the generated REST API reference. */ +export const API_REFERENCE_DIR = "reference/api"; + +const API_REFERENCE_SLUGS = API_REFERENCE_DIR.split("/"); + +/** Whether a page slug is the API reference's landing page or a page under it. */ +export const isApiReferenceSlug = (slugs: readonly string[]): boolean => + API_REFERENCE_SLUGS.every((segment, index) => slugs[index] === segment); + +/** The variable the code samples and the setup section read the deployment URL from. */ +export const DEPLOYMENT_URL_ENV = "CODER_URL"; +/** The variable the code samples and the setup section read the session token from. */ +export const SESSION_TOKEN_ENV = "CODER_SESSION_TOKEN"; +/** The header coderd reads a session token from. */ +export const SESSION_TOKEN_HEADER = "Coder-Session-Token"; + +/** The OpenAPI path item and method an operation page renders. */ +export interface OpenApiOperationRef { + method: HttpMethod; + path: string; +} + +/** An operation's card on the landing page. */ +export interface OpenApiLandingOperation { + route: string; + title: string; + method: HttpMethod; + description?: string; +} + +/** A tag's cards, under a heading of their own, in sidebar order. */ +export interface OpenApiLandingSection { + title: string; + id: string; + operations: OpenApiLandingOperation[]; +} + +/** The landing page: its route, its setup section's id, and its card sections. */ +export interface OpenApiLanding { + route: string; + setupId: string; + sections: OpenApiLandingSection[]; +} + +/** One row of the schemas page: a schema and the operation page that shows it most directly, if any does. */ +export interface OpenApiSchemaRow { + name: string; + operation?: { title: string; route: string }; +} + +/** The schemas page: its route and its rows. */ +export interface OpenApiSchemas { + route: string; + rows: OpenApiSchemaRow[]; +} + +/** + * One version's REST API reference data, as the sync writes it and the page + * renderer reads it: the OpenAPI 3 document, each operation page's route, the + * old single-page anchors, and the landing and schemas pages. + */ +export interface OpenApiPagesData { + document: JsonObject; + operations: Record<string, OpenApiOperationRef>; + anchors: Record<string, Record<string, string>>; + landing: OpenApiLanding; + schemas: OpenApiSchemas; +} + +const escapePointer = (key: string) => key.replace(/~/g, "~0").replace(/\//g, "~1"); + +/** + * The JSON pointer of the first `$ref` that is not an in-document reference + * (`#/...`), or `undefined` when there is none. An OpenAPI bundler fetches or + * reads any other reference at build time, so an API document has to be + * rejected before it reaches one. + */ +export function findExternalRef(value: unknown, pointer = ""): string | undefined { + if (Array.isArray(value)) { + for (const [index, item] of value.entries()) { + const found = findExternalRef(item, `${pointer}/${index}`); + if (found !== undefined) return found; + } + } else if (isObject(value)) { + for (const [key, child] of Object.entries(value)) { + const at = `${pointer}/${escapePointer(key)}`; + if (key === "$ref" && (typeof child !== "string" || !child.startsWith("#/"))) return at; + const found = findExternalRef(child, at); + if (found !== undefined) return found; + } + } + return undefined; +} + +/** Throws, naming the JSON pointer, when the document holds a `$ref` that is not `#/...`. */ +export function assertInDocumentRefs(document: unknown, label: string): void { + const pointer = findExternalRef(document); + if (pointer !== undefined) { + throw new Error(`${label}: $ref at ${pointer || "/"} is not an in-document reference (#/...)`); + } +} diff --git a/packages/docs-next/src/openapi/code-samples.ts b/packages/docs-next/src/openapi/code-samples.ts index fc16d9c1..826ebfa7 100644 --- a/packages/docs-next/src/openapi/code-samples.ts +++ b/packages/docs-next/src/openapi/code-samples.ts @@ -1,16 +1,14 @@ import { type JsonSchema, dereference, sample } from "@fumadocs/json-schema"; import { createMagicProxy, getRaw } from "@scalar/json-magic/magic-proxy"; - -type Json = Record<string, unknown>; - -/** The environment variables every sample reads, named as the `coder` CLI reads them. */ -export const DEPLOYMENT_URL_ENV = "CODER_URL"; -export const SESSION_TOKEN_ENV = "CODER_SESSION_TOKEN"; - -const isObject = (value: unknown): value is Json => - typeof value === "object" && value !== null && !Array.isArray(value); - -const resolve = (node: unknown): Json | undefined => { +import { + DEPLOYMENT_URL_ENV, + isObject, + type JsonObject, + SESSION_TOKEN_ENV, + SESSION_TOKEN_HEADER, +} from "@coder/docs-config/client"; + +const resolve = (node: unknown): JsonObject | undefined => { const value = dereference(node); return isObject(value) ? value : undefined; }; @@ -23,7 +21,7 @@ interface Parameter { required?: boolean; } -function parametersOf(pathItem: Json, operation: Json): Parameter[] { +function parametersOf(pathItem: JsonObject, operation: JsonObject): Parameter[] { const byKey = new Map<string, Parameter>(); for (const list of [pathItem.parameters, operation.parameters]) { if (!Array.isArray(list)) continue; @@ -58,15 +56,15 @@ export interface ExampleRequest { } /** The auth headers of the first security alternative, preferring the session token; none when auth is optional. */ -function authHeaders(document: Json, operation: Json): Header[] { - const requirements = (operation.security ?? document.security) as Json[] | undefined; +function authHeaders(document: JsonObject, operation: JsonObject): Header[] { + const requirements = (operation.security ?? document.security) as JsonObject[] | undefined; if (!Array.isArray(requirements) || requirements.length === 0) return []; if (requirements.some((item) => isObject(item) && Object.keys(item).length === 0)) return []; const schemes = resolve(resolve(document.components)?.securitySchemes) ?? {}; const header = (key: string): Header | undefined => { const scheme = resolve(schemes[key]); if (scheme?.type === "apiKey" && scheme.in === "header" && typeof scheme.name === "string") { - return scheme.name === "Coder-Session-Token" + return scheme.name === SESSION_TOKEN_HEADER ? { name: scheme.name, token: true } : { name: scheme.name, value: placeholder(key) }; } @@ -77,7 +75,7 @@ function authHeaders(document: Json, operation: Json): Header[] { }; const chosen = requirements.find((item) => - Object.keys(item).some((key) => resolve(schemes[key])?.name === "Coder-Session-Token"), + Object.keys(item).some((key) => resolve(schemes[key])?.name === SESSION_TOKEN_HEADER), ) ?? requirements[0]; return Object.keys(chosen ?? {}) .map(header) @@ -100,7 +98,7 @@ function jsonSample(schema: JsonSchema, method: string): unknown { } /** `contentType` replaces the declared media type when the operation takes it as a header parameter. */ -function bodyOf(operation: Json, method: string, contentType?: string): Body | undefined { +function bodyOf(operation: JsonObject, method: string, contentType?: string): Body | undefined { const body = resolve(operation.requestBody); const content = resolve(body?.content); if (!content) return undefined; @@ -132,8 +130,8 @@ function bodyOf(operation: Json, method: string, contentType?: string): Body | u * parameters stay `{name}` placeholders for the reader to fill in; a JSON body * is the schema's example, or a sample of its required fields. */ -export function exampleRequest(bundled: Json, path: string, method: string): ExampleRequest { - const document = createMagicProxy(bundled) as Json; +export function exampleRequest(bundled: JsonObject, path: string, method: string): ExampleRequest { + const document = createMagicProxy(bundled) as JsonObject; const pathItem = resolve(resolve(document.paths)?.[path]); const operation = resolve(pathItem?.[method]); if (!pathItem || !operation) throw new Error(`no ${method} ${path} in the API document`); @@ -481,7 +479,7 @@ export interface CodeSample { } /** The operation's example request in each language the reference shows, in tab order. */ -export function codeSamples(bundled: Json, path: string, method: string): CodeSample[] { +export function codeSamples(bundled: JsonObject, path: string, method: string): CodeSample[] { const request = exampleRequest(bundled, path, method); return [ { id: "curl", lang: "bash", label: "cURL", source: curlSample(request) }, @@ -497,17 +495,17 @@ export function codeSamples(bundled: Json, path: string, method: string): CodeSa } /** The document with the operation's code samples as its only ones, leaving the input untouched. */ -export function withCodeSamples(bundled: Json, path: string, method: string): Json { +export function withCodeSamples(bundled: JsonObject, path: string, method: string): JsonObject { const samples = codeSamples(bundled, path, method); - const paths = bundled.paths as Record<string, Json>; - const pathItem = paths[path] as Json; + const paths = bundled.paths as Record<string, JsonObject>; + const pathItem = paths[path] as JsonObject; return { ...bundled, paths: { ...paths, [path]: { ...pathItem, - [method]: { ...(pathItem[method] as Json), "x-codeSamples": samples }, + [method]: { ...(pathItem[method] as JsonObject), "x-codeSamples": samples }, }, }, }; diff --git a/packages/docs-next/src/openapi/index.test.tsx b/packages/docs-next/src/openapi/index.test.tsx index 885d153c..4a15affa 100644 --- a/packages/docs-next/src/openapi/index.test.tsx +++ b/packages/docs-next/src/openapi/index.test.tsx @@ -3,7 +3,8 @@ import { mkdtemp, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; -import { createOpenApiRenderBody, type OpenApiPagesData, pruneDocument } from "./index.js"; +import type { OpenApiPagesData } from "@coder/docs-config"; +import { createOpenApiRenderBody, pruneDocument } from "./index.js"; const ROUTE = "reference/api/secrets/get-secret"; diff --git a/packages/docs-next/src/openapi/index.tsx b/packages/docs-next/src/openapi/index.tsx index f994ab32..a543a6e2 100644 --- a/packages/docs-next/src/openapi/index.tsx +++ b/packages/docs-next/src/openapi/index.tsx @@ -1,49 +1,32 @@ -import { assertInDocumentRefs } from "@coder/docs-config"; +import { + assertInDocumentRefs, + collectRefs, + type HttpMethod, + isObject, + type JsonObject, + type OpenApiPagesData, +} from "@coder/docs-config"; import type { Document } from "fumadocs-openapi"; import { createOpenAPI } from "fumadocs-openapi/server"; import type { RenderBody } from "../types.js"; import { AnchorRedirect } from "./anchor-redirect.js"; import { ApiPage } from "./api-page-lazy.js"; import { withCodeSamples } from "./code-samples.js"; -import { ApiLanding, type OpenApiLandingData } from "./landing.js"; +import { ApiLanding } from "./landing.js"; import { SetupHrefProvider } from "./samples-note.js"; -import { type SchemaRow, SchemaTables } from "./schemas.js"; - -type Json = Record<string, unknown>; - -/** What the sync's `applyOpenApiReference` writes for one version. */ -export interface OpenApiPagesData { - document: Json; - operations: Record<string, { method: string; path: string }>; - anchors: Record<string, Record<string, string>>; - landing: OpenApiLandingData; - schemas: { route: string; rows: SchemaRow[] }; -} - -const isObject = (value: unknown): value is Json => - typeof value === "object" && value !== null && !Array.isArray(value); - -function collectRefs(value: unknown, into: Set<string>): void { - if (Array.isArray(value)) for (const item of value) collectRefs(item, into); - else if (isObject(value)) { - for (const [key, child] of Object.entries(value)) { - if (key === "$ref" && typeof child === "string") into.add(child); - else collectRefs(child, into); - } - } -} +import { SchemaTables } from "./schemas.js"; /** * The document cut down to one operation and the components it reaches, so a * page's props carry only what that page renders, not the whole API. */ -export function pruneDocument(document: Json, path: string, method: string): Json { - const paths = document.paths as Record<string, Json>; +export function pruneDocument(document: JsonObject, path: string, method: HttpMethod): JsonObject { + const paths = document.paths as Record<string, JsonObject>; const item = paths[path]; if (!item || !isObject(item[method])) throw new Error(`no ${method} ${path} in the API document`); - const components = (document.components ?? {}) as Record<string, Json>; - const kept: Record<string, Json> = { securitySchemes: components.securitySchemes ?? {} }; - const pathItem: Json = { [method]: item[method] }; + const components = (document.components ?? {}) as Record<string, JsonObject>; + const kept: Record<string, JsonObject> = { securitySchemes: components.securitySchemes ?? {} }; + const pathItem: JsonObject = { [method]: item[method] }; if (item.parameters) pathItem.parameters = item.parameters; const seen = new Set<string>(); let frontier = new Set<string>(); @@ -61,7 +44,7 @@ export function pruneDocument(document: Json, path: string, method: string): Jso } frontier = next; } - const info = (document.info ?? {}) as Json; + const info = (document.info ?? {}) as JsonObject; return { openapi: document.openapi, info: { title: info.title, version: info.version }, @@ -81,14 +64,14 @@ export function pruneDocument(document: Json, path: string, method: string): Jso export function createOpenApiRenderBody( load: (versionId: string | undefined) => Promise<OpenApiPagesData | undefined>, ): RenderBody { - const bundled = new Map<string | undefined, Promise<Json>>(); - const bundle = (versionId: string | undefined, document: Json): Promise<Json> => { + const bundled = new Map<string | undefined, Promise<JsonObject>>(); + const bundle = (versionId: string | undefined, document: JsonObject): Promise<JsonObject> => { let cached = bundled.get(versionId); if (!cached) { // The bundler fetches or reads any other reference, so only in-document ones may reach it. assertInDocumentRefs(document, "the API document"); const server = createOpenAPI({ input: { coder: () => document as Document } }); - cached = server.getSchema("coder").then((schema) => schema.bundled as Json); + cached = server.getSchema("coder").then((schema) => schema.bundled as JsonObject); bundled.set(versionId, cached); } return cached; @@ -126,7 +109,7 @@ export function createOpenApiRenderBody( document="coder" showTitle={false} showDescription - operations={[{ path: operation.path, method: operation.method as "get" }]} + operations={[{ path: operation.path, method: operation.method }]} payload={{ bundled: document as Document }} /> </SetupHrefProvider> diff --git a/packages/docs-next/src/openapi/landing.test.tsx b/packages/docs-next/src/openapi/landing.test.tsx index 056ac8ef..c84fb5fd 100644 --- a/packages/docs-next/src/openapi/landing.test.tsx +++ b/packages/docs-next/src/openapi/landing.test.tsx @@ -2,9 +2,10 @@ import assert from "node:assert/strict"; import test from "node:test"; import { renderToFragment } from "../../test/dom.js"; import { createOpenApiRenderBody } from "./index.js"; -import { ApiLanding, type OpenApiLandingData } from "./landing.js"; +import type { OpenApiLanding } from "@coder/docs-config/client"; +import { ApiLanding } from "./landing.js"; -const landing: OpenApiLandingData = { +const landing: OpenApiLanding = { route: "reference/api", setupId: "set-up-your-environment", sections: [ diff --git a/packages/docs-next/src/openapi/landing.tsx b/packages/docs-next/src/openapi/landing.tsx index c6e1350c..94b2e800 100644 --- a/packages/docs-next/src/openapi/landing.tsx +++ b/packages/docs-next/src/openapi/landing.tsx @@ -1,19 +1,9 @@ +import type { OpenApiLanding } from "@coder/docs-config/client"; import { Card, Cards } from "fumadocs-ui/components/card"; import { Heading } from "fumadocs-ui/components/heading"; import { Fragment } from "react"; import { MethodBadge } from "./method-badge.js"; -/** What the sync's `applyOpenApiReference` records for the landing page's cards. */ -export interface OpenApiLandingData { - route: string; - setupId: string; - sections: { - title: string; - id: string; - operations: { route: string; title: string; method: string; description?: string }[]; - }[]; -} - /** * A card for every operation, under a heading per tag in sidebar order. The * cards are server-rendered plain links (no client `Link`, so no prefetch), @@ -23,7 +13,7 @@ export function ApiLanding({ sections, hrefFor, }: { - sections: OpenApiLandingData["sections"]; + sections: OpenApiLanding["sections"]; hrefFor: (route: string) => string | undefined; }) { return sections.map((section) => ( diff --git a/packages/docs-next/src/openapi/samples-note.tsx b/packages/docs-next/src/openapi/samples-note.tsx index 112136d8..2684c721 100644 --- a/packages/docs-next/src/openapi/samples-note.tsx +++ b/packages/docs-next/src/openapi/samples-note.tsx @@ -1,5 +1,6 @@ "use client"; +import { DEPLOYMENT_URL_ENV, SESSION_TOKEN_ENV } from "@coder/docs-config/client"; import { type ReactNode, createContext, useContext } from "react"; const SetupHref = createContext<string | undefined>(undefined); @@ -14,7 +15,7 @@ export function SamplesNote() { const href = useContext(SetupHref); return ( <p className="mb-2 text-sm text-fd-muted-foreground"> - The samples read <code>CODER_URL</code> and <code>CODER_SESSION_TOKEN</code> + The samples read <code>{DEPLOYMENT_URL_ENV}</code> and <code>{SESSION_TOKEN_ENV}</code> {href ? ( <> : <a href={href}>set up your environment</a>. diff --git a/packages/docs-next/src/openapi/schemas.test.tsx b/packages/docs-next/src/openapi/schemas.test.tsx index 73489807..6b2ac95b 100644 --- a/packages/docs-next/src/openapi/schemas.test.tsx +++ b/packages/docs-next/src/openapi/schemas.test.tsx @@ -5,9 +5,10 @@ import { hydrateRoot } from "react-dom/client"; import { renderToString } from "react-dom/server"; import { renderToFragment } from "../../test/dom.js"; import { createOpenApiRenderBody } from "./index.js"; -import { SchemaTables, type SchemaRow } from "./schemas.js"; +import type { OpenApiSchemaRow } from "@coder/docs-config/client"; +import { SchemaTables } from "./schemas.js"; -const rows: SchemaRow[] = [ +const rows: OpenApiSchemaRow[] = [ { name: "codersdk.User", operation: { title: "Get user", route: "reference/api/users/get-user" }, diff --git a/packages/docs-next/src/openapi/schemas.tsx b/packages/docs-next/src/openapi/schemas.tsx index 0a27fc45..46acdaf3 100644 --- a/packages/docs-next/src/openapi/schemas.tsx +++ b/packages/docs-next/src/openapi/schemas.tsx @@ -1,15 +1,10 @@ +import type { OpenApiSchemaRow } from "@coder/docs-config/client"; import { SchemaFilter } from "./schema-filter.js"; -/** One row of the schemas page: a schema and the operation page that shows it, if any does. */ -export interface SchemaRow { - name: string; - operation?: { title: string; route: string }; -} - const OTHER = "Other"; -function groupsOf(rows: SchemaRow[]): { name: string; rows: SchemaRow[] }[] { - const byPackage = new Map<string, SchemaRow[]>(); +function groupsOf(rows: OpenApiSchemaRow[]): { name: string; rows: OpenApiSchemaRow[] }[] { + const byPackage = new Map<string, OpenApiSchemaRow[]>(); for (const row of rows) { const dot = row.name.indexOf("."); const name = dot > 0 ? row.name.slice(0, dot) : OTHER; @@ -33,7 +28,7 @@ export function SchemaTables({ rows, hrefFor, }: { - rows: SchemaRow[]; + rows: OpenApiSchemaRow[]; hrefFor: (route: string) => string | undefined; }) { return ( diff --git a/packages/docs-next/src/openapi/stored-server.ts b/packages/docs-next/src/openapi/stored-server.ts index f925940c..3a373051 100644 --- a/packages/docs-next/src/openapi/stored-server.ts +++ b/packages/docs-next/src/openapi/stored-server.ts @@ -1,5 +1,4 @@ -const isRecord = (value: unknown): value is Record<string, unknown> => - typeof value === "object" && value !== null && !Array.isArray(value); +import { isObject } from "@coder/docs-config/client"; function repaired(raw: string): string | undefined { let value: unknown; @@ -8,7 +7,7 @@ function repaired(raw: string): string | undefined { } catch { return undefined; } - if (!isRecord(value) || typeof value.url !== "string" || !isRecord(value.variables)) + if (!isObject(value) || typeof value.url !== "string" || !isObject(value.variables)) return undefined; const variables: Record<string, string> = {}; let url = value.url; diff --git a/packages/docs-ui/src/runtime-version-switcher.tsx b/packages/docs-ui/src/runtime-version-switcher.tsx index 041a1b5a..d051e1cc 100644 --- a/packages/docs-ui/src/runtime-version-switcher.tsx +++ b/packages/docs-ui/src/runtime-version-switcher.tsx @@ -1,5 +1,6 @@ "use client"; +import { isObject } from "@coder/docs-config/client"; import { DEV_ID, LINE_ID_PATTERN, @@ -41,13 +42,9 @@ interface VersionsDocumentTag { label?: string; } -function isRecord(value: unknown): value is Record<string, unknown> { - return typeof value === "object" && value !== null; -} - function isLine(value: unknown): value is VersionsDocumentLine { return ( - isRecord(value) && + isObject(value) && typeof value.id === "string" && LINE_ID_PATTERN.test(value.id) && typeof value.label === "string" && @@ -57,12 +54,12 @@ function isLine(value: unknown): value is VersionsDocumentLine { } function isDevelopment(value: unknown): value is VersionsDocumentDevelopment { - return isRecord(value) && value.id === DEV_ID && typeof value.label === "string"; + return isObject(value) && value.id === DEV_ID && typeof value.label === "string"; } function isTag(value: unknown): value is VersionsDocumentTag { return ( - isRecord(value) && + isObject(value) && typeof value.id === "string" && TAG_ID_PATTERN.test(value.id) && typeof value.line === "string" && diff --git a/packages/docs-ui/src/versions-document-client.ts b/packages/docs-ui/src/versions-document-client.ts index c6fa0dd1..dbeacbb4 100644 --- a/packages/docs-ui/src/versions-document-client.ts +++ b/packages/docs-ui/src/versions-document-client.ts @@ -1,5 +1,6 @@ "use client"; +import { isObject } from "@coder/docs-config/client"; import { useEffect, useRef, useState } from "react"; /** @@ -28,12 +29,8 @@ export type VersionsDocumentState = | { status: "ready"; document: VersionsDocumentShape } | { status: "error"; document: null }; -function isRecord(value: unknown): value is Record<string, unknown> { - return typeof value === "object" && value !== null; -} - function isBanner(value: unknown): value is VersionsDocumentBanner { - if (!isRecord(value)) return false; + if (!isObject(value)) return false; return ( typeof value.enabled === "boolean" && typeof value.legacyBase === "string" && @@ -43,7 +40,7 @@ function isBanner(value: unknown): value is VersionsDocumentBanner { } function asDocument(value: unknown): VersionsDocumentShape | null { - if (!isRecord(value) || value.schemaVersion !== 1 || !Array.isArray(value.lines)) return null; + if (!isObject(value) || value.schemaVersion !== 1 || !Array.isArray(value.lines)) return null; const banner = value.banner === undefined || value.banner === null ? null : value.banner; if (banner !== null && !isBanner(banner)) return null; return { From f2001fbd257fc5e22724ae35aef504264aea5608 Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nickvigilante@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:58:13 -0400 Subject: [PATCH 51/69] refactor: recognise the API reference with one predicate The sidebar collapse in the site's shell and the search index's API page check each spelled out reference/api. They now use API_REFERENCE_DIR and isApiReferenceSlug from the contract module, as the sync's default directory already does, and the shell builds the reference's URL prefix with versionHref instead of trimming a trailing slash off versionBaseUrl. Assisted-by: AI --- apps/docs/lib/versioned-shell.tsx | 17 ++++++++++++----- packages/docs-next/src/search.ts | 6 +++--- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/apps/docs/lib/versioned-shell.tsx b/apps/docs/lib/versioned-shell.tsx index ad61d40c..876935b3 100644 --- a/apps/docs/lib/versioned-shell.tsx +++ b/apps/docs/lib/versioned-shell.tsx @@ -1,7 +1,12 @@ import { latestSource, sourceFor, versionHasSlug } from "@/lib/sources"; import { versions } from "@/lib/versions"; -import { analyticsEnabled, stripCodeTitle } from "@coder/docs-config"; -import { DocsShell, resolveSlug, versionBaseUrl, versionSwitcherOptions } from "@coder/docs-next"; +import { + API_REFERENCE_DIR, + analyticsEnabled, + isApiReferenceSlug, + stripCodeTitle, +} from "@coder/docs-config"; +import { DocsShell, resolveSlug, versionHref, versionSwitcherOptions } from "@coder/docs-next"; import { collapseFoldersUnder } from "@coder/docs-next/openapi"; import { BetaBanner, CookiePreferencesButton, RuntimeVersionSwitcher } from "@coder/docs-ui"; import type { ReactNode } from "react"; @@ -74,11 +79,13 @@ export function VersionedShell({ slug, children }: { slug?: string[]; children: // deployment URL, the fetch fails and the build-time options stand. const versionsUrl = `${basePath}/versions.json`; // Operation pages are listed in the sidebar only while reading the API reference. - const inApiReference = resolved?.slug[0] === "reference" && resolved.slug[1] === "api"; - const versionBase = resolved ? versionBaseUrl(resolved.version).replace(/\/$/, "") : ""; + const inApiReference = resolved !== undefined && isApiReferenceSlug(resolved.slug); + const apiReference = resolved + ? versionHref(resolved.version, API_REFERENCE_DIR.split("/")) + : `/${API_REFERENCE_DIR}`; const tree = inApiReference ? undefined - : collapseFoldersUnder(source.pageTree, `${versionBase}/reference/api/`); + : collapseFoldersUnder(source.pageTree, `${apiReference}/`); return ( <DocsShell source={source} diff --git a/packages/docs-next/src/search.ts b/packages/docs-next/src/search.ts index d4ce5efd..49c74e1c 100644 --- a/packages/docs-next/src/search.ts +++ b/packages/docs-next/src/search.ts @@ -1,4 +1,4 @@ -import { stripCodeTitle } from "@coder/docs-config"; +import { API_REFERENCE_DIR, isApiReferenceSlug, stripCodeTitle } from "@coder/docs-config"; import type { StructuredData } from "fumadocs-core/mdx-plugins"; import { findPath } from "fumadocs-core/page-tree"; import { createFromSource } from "fumadocs-core/search/server"; @@ -185,9 +185,9 @@ async function loadToc(data: IndexablePageData): Promise<TableOfContents> { throw new Error("Cannot find the table of contents of an API reference page."); } -/** The generated REST API reference pages under `reference/api/`, not its hand-written index. */ +/** The generated REST API reference pages, not its hand-written index. */ function isApiReferencePage(slugs: readonly string[]): boolean { - return slugs.length > 2 && slugs[0] === "reference" && slugs[1] === "api"; + return isApiReferenceSlug(slugs) && slugs.join("/") !== API_REFERENCE_DIR; } const API_ROUTE = /^`?(?:GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) \/\S*`?$/; From 40d996a5d1313a07cb4b77c857ffdbb6b2816192 Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nickvigilante@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:00:27 -0400 Subject: [PATCH 52/69] refactor(docs-sources): read the API document from the version's checkout swaggerFromClone resolved the version's ref a second time, with rules of its own: it fell back to the bare ref, which resolveCommit deliberately never does, had no ambiguity check or moved-tag warning, and ran outside the provider's lock. Only the order of the sync's calls kept the docs and the Swagger document of one version on the same commit. Both providers now take an apiDocument path and put the parsed document on the DocSource they load. The git provider reads it from the worktree loadVersion already checked out at the resolved commit, and the local tree provider from beside the docs tree, both through readContainedFile. The sync scripts pass the source's document on and no longer branch on the provider. swaggerFromClone, swaggerFromTree and their git helpers are gone. Assisted-by: AI --- ARCHITECTURE.md | 3 +- apps/docs/scripts/sync-docs.mjs | 27 +++--- apps/offlinedocs/scripts/sync-docs.mjs | 19 ++--- packages/docs-config/src/content.ts | 6 ++ .../docs-sources/src/api-document.test.ts | 42 +++++++++ packages/docs-sources/src/api-document.ts | 24 ++++++ packages/docs-sources/src/git-refs.test.ts | 43 ++++++++++ packages/docs-sources/src/git-refs.ts | 17 +++- packages/docs-sources/src/index.ts | 2 +- packages/docs-sources/src/local-tree.test.ts | 23 ++++- packages/docs-sources/src/local-tree.ts | 21 ++++- packages/docs-sources/src/swagger.test.ts | 85 ------------------- packages/docs-sources/src/swagger.ts | 77 ----------------- 13 files changed, 195 insertions(+), 194 deletions(-) create mode 100644 packages/docs-sources/src/api-document.test.ts create mode 100644 packages/docs-sources/src/api-document.ts delete mode 100644 packages/docs-sources/src/swagger.test.ts delete mode 100644 packages/docs-sources/src/swagger.ts diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 7a541f22..0bbdcb88 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -150,7 +150,8 @@ From 2.24 on, and on `main`, the REST API reference is built from coder/coder's `DOCS_OPENAPI` set to `0`, `false`, `off` or `no` keeps the Markdown reference for every version, and is the rollback; any value that is not an off or on spelling fails the sync. The Swagger document is read from the checkout the docs come from, never fetched. -`swaggerFromTree` (`@coder/docs-sources`) reads `coderd/apidoc/swagger.json` beside the `docs/` tree, so every checkout a sync runs on, the publisher's and the preview's sparse ones included, has to hold `coderd/apidoc` as well as `docs`; `swaggerFromClone` reads the same path at the version's ref of a git clone. +Both `@coder/docs-sources` providers, given `apiDocument: SWAGGER_PATH`, read `coderd/apidoc/swagger.json` onto the version's `DocSource` as `apiDocument`. +The local tree provider reads it beside the `docs/` tree, so every checkout a sync runs on, the publisher's and the preview's sparse ones included, has to hold `coderd/apidoc` as well as `docs`; the git provider reads it from the worktree it loads the version's docs from, so both come from one commit resolution. A version with no Swagger document keeps its Markdown reference with a warning, except when `DOCS_PUBLISH=1`, where the sync fails, so a publish never ships the old reference for a version that should have the new one. `withOpenApiReference` rewrites the version's `DocSource` before `syncDocSource` sees it: `applyOpenApiReference` converts the document to OpenAPI 3, adds one Markdown stub page per operation under its tag, turns each tag page and the schemas page into lists of links, and adds the setup section to the landing page. diff --git a/apps/docs/scripts/sync-docs.mjs b/apps/docs/scripts/sync-docs.mjs index 9ba0280c..5dd3d41f 100644 --- a/apps/docs/scripts/sync-docs.mjs +++ b/apps/docs/scripts/sync-docs.mjs @@ -23,12 +23,7 @@ import { } from "@coder/docs-build"; import { parseReleaseSchedule, resolveVersionPipeline } from "@coder/docs-config"; import { versionBaseUrl } from "@coder/docs-next/version-routing"; -import { - createGitRefsProvider, - createLocalTreeProvider, - swaggerFromClone, - swaggerFromTree, -} from "@coder/docs-sources"; +import { SWAGGER_PATH, createGitRefsProvider, createLocalTreeProvider } from "@coder/docs-sources"; import { versions } from "../lib/versions.ts"; import { assertPublishInputs, singleVersionFromEnv } from "./single-version.mjs"; import { @@ -107,14 +102,25 @@ if (single) { } // Fail before the build, not after it, when this commit's redirects are invalid. await readVersionRedirects(docsRoot); - provider = createLocalTreeProvider({ docsRoot, version: single, lastModified: true }); + provider = createLocalTreeProvider({ + docsRoot, + version: single, + lastModified: true, + apiDocument: SWAGGER_PATH, + }); console.log(`[sync] corpus: local tree at ${docsRoot} as version ${single.id} (${single.ref})`); } else { const repo = process.env.DOCS_REPO ?? (await ensureFixtureRepo()); console.log( `[sync] corpus: git ${redactRepoUrl(repo)} (${versions.map((v) => v.ref).join(", ")})`, ); - provider = createGitRefsProvider({ repo, versions, cacheDir, lastModified: true }); + provider = createGitRefsProvider({ + repo, + versions, + cacheDir, + lastModified: true, + apiDocument: SWAGGER_PATH, + }); } // The fixture's 0.2 renders the generated reference and its 0.1 keeps Markdown, as 2.24 and 2.23 do. const usesFixture = !single && !process.env.DOCS_REPO; @@ -145,10 +151,7 @@ for (const version of latestLastSyncOrder(versions)) { try { let source = await provider.loadVersion(version); if (rendersOpenApi(version, process.env, openApiMinLine)) { - const swagger = single - ? await swaggerFromTree(process.env.DOCS_ROOT) - : await swaggerFromClone(cacheDir, version.ref); - source = await withOpenApiReference(appDir, version, source, swagger, { + source = await withOpenApiReference(appDir, version, source, source.apiDocument, { required: process.env.DOCS_PUBLISH === "1", }); } diff --git a/apps/offlinedocs/scripts/sync-docs.mjs b/apps/offlinedocs/scripts/sync-docs.mjs index f587575a..f33a3ac9 100644 --- a/apps/offlinedocs/scripts/sync-docs.mjs +++ b/apps/offlinedocs/scripts/sync-docs.mjs @@ -22,12 +22,7 @@ import { writeReleaseSchedule, } from "@coder/docs-build"; import { parseReleaseSchedule } from "@coder/docs-config"; -import { - createGitRefsProvider, - createLocalTreeProvider, - swaggerFromClone, - swaggerFromTree, -} from "@coder/docs-sources"; +import { SWAGGER_PATH, createGitRefsProvider, createLocalTreeProvider } from "@coder/docs-sources"; import { assertDeployHasCorpus, OPENAPI_DATA_ID, @@ -46,13 +41,18 @@ const version = exportVersionFromEnv(process.env); let provider; let sourceLink; if (process.env.DOCS_ROOT) { - provider = createLocalTreeProvider({ docsRoot: process.env.DOCS_ROOT, version }); + provider = createLocalTreeProvider({ + docsRoot: process.env.DOCS_ROOT, + version, + apiDocument: SWAGGER_PATH, + }); console.log(`[sync] corpus: local tree at ${process.env.DOCS_ROOT}`); } else if (process.env.DOCS_REPO) { provider = createGitRefsProvider({ repo: process.env.DOCS_REPO, versions: [version], cacheDir: path.join(appDir, ".cache", "docs-clone"), + apiDocument: SWAGGER_PATH, }); sourceLink = githubBlobSourceLink(process.env.DOCS_REPO, version.ref); console.log(`[sync] corpus: git ${redactRepoUrl(process.env.DOCS_REPO)} @ ${version.ref}`); @@ -67,10 +67,7 @@ if (process.env.DOCS_ROOT) { await clearOpenApi(appDir); let source = await provider.loadVersion(version); if ((process.env.DOCS_ROOT || process.env.DOCS_REPO) && rendersOpenApi(version)) { - const swagger = process.env.DOCS_ROOT - ? await swaggerFromTree(process.env.DOCS_ROOT) - : await swaggerFromClone(path.join(appDir, ".cache", "docs-clone"), version.ref); - source = await withOpenApiReference(appDir, version, source, swagger, { + source = await withOpenApiReference(appDir, version, source, source.apiDocument, { required: process.env.DOCS_PUBLISH === "1", dataId: OPENAPI_DATA_ID, }); diff --git a/packages/docs-config/src/content.ts b/packages/docs-config/src/content.ts index b53f9411..52eeceac 100644 --- a/packages/docs-config/src/content.ts +++ b/packages/docs-config/src/content.ts @@ -121,4 +121,10 @@ export interface DocSource { * when the provider was not asked for dates or has no history. */ lastModified?: ReadonlyMap<string, string>; + /** + * The version's API document (coder/coder's Swagger document), parsed, read + * from the same checkout as the docs. Absent when the provider was not asked + * for one or the version has none. + */ + apiDocument?: unknown; } diff --git a/packages/docs-sources/src/api-document.test.ts b/packages/docs-sources/src/api-document.test.ts new file mode 100644 index 00000000..a2262de1 --- /dev/null +++ b/packages/docs-sources/src/api-document.test.ts @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import { SWAGGER_PATH, readApiDocument } from "./api-document.js"; + +async function checkout() { + const root = await mkdtemp(path.join(tmpdir(), "openapi-source-")); + await mkdir(path.join(root, "docs")); + await mkdir(path.join(root, "coderd", "apidoc"), { recursive: true }); + return root; +} + +test("reads and parses the API document, and nothing when there is none", async () => { + const root = await checkout(); + assert.equal(await readApiDocument(root, SWAGGER_PATH), undefined); + await writeFile(path.join(root, SWAGGER_PATH), '{"swagger":"2.0"}'); + assert.deepEqual(await readApiDocument(root, SWAGGER_PATH), { swagger: "2.0" }); +}); + +test("a symlinked API document is rejected and its target never surfaces", async () => { + const root = await checkout(); + const outside = await mkdtemp(path.join(tmpdir(), "openapi-source-secret-")); + await writeFile(path.join(outside, "secret.json"), '{"secret":"do-not-leak"}'); + await symlink(path.join(outside, "secret.json"), path.join(root, SWAGGER_PATH)); + await assert.rejects(readApiDocument(root, SWAGGER_PATH), (error: Error) => { + assert.match(error.message, /symbolic link/); + assert.doesNotMatch(error.message, /do-not-leak/); + return true; + }); +}); + +test("invalid JSON is reported without the file's content", async () => { + const root = await checkout(); + await writeFile(path.join(root, SWAGGER_PATH), "not json do-not-leak"); + await assert.rejects(readApiDocument(root, SWAGGER_PATH), (error: Error) => { + assert.match(error.message, /is not valid JSON/); + assert.doesNotMatch(error.message, /do-not-leak/); + return true; + }); +}); diff --git a/packages/docs-sources/src/api-document.ts b/packages/docs-sources/src/api-document.ts new file mode 100644 index 00000000..9e0f6ab6 --- /dev/null +++ b/packages/docs-sources/src/api-document.ts @@ -0,0 +1,24 @@ +import { readContainedFile } from "./contained-file.js"; +import { DEFAULT_MAX_FILE_BYTES } from "./read-tree.js"; + +/** Where coder/coder keeps the Swagger 2.0 document the REST API reference is built from. */ +export const SWAGGER_PATH = "coderd/apidoc/swagger.json"; + +/** + * The JSON document at `relPath` in a checkout, or undefined when there is + * none. Read with the docs tree's own guarantees: no symbolic links, a + * regular file under the per-file cap, inside the checkout. + */ +export async function readApiDocument( + checkout: string, + relPath: string, + maxBytes: number = DEFAULT_MAX_FILE_BYTES, +): Promise<unknown> { + const text = await readContainedFile(checkout, relPath, maxBytes); + if (text === undefined) return undefined; + try { + return JSON.parse(text); + } catch { + throw new Error(`@coder/docs-sources: ${relPath} is not valid JSON`); + } +} diff --git a/packages/docs-sources/src/git-refs.test.ts b/packages/docs-sources/src/git-refs.test.ts index 7f5d7c73..c212b5ca 100644 --- a/packages/docs-sources/src/git-refs.test.ts +++ b/packages/docs-sources/src/git-refs.test.ts @@ -300,6 +300,49 @@ test("createGitRefsProvider applies each version's manifest policy", async () => await assert.rejects(() => provider.loadVersion(living), /invalid manifest\.json/); }); +test("createGitRefsProvider reads the API document from each version's own commit", async () => { + await git(repo, ["checkout", "-q", "preview"]); + await mkdir(path.join(repo, "coderd", "apidoc"), { recursive: true }); + await writeFile(path.join(repo, "coderd", "apidoc", "swagger.json"), '{"swagger":"2.0"}'); + await git(repo, ["add", "-A"]); + await git(repo, ["commit", "-m", "swagger"]); + await git(repo, ["checkout", "-q", "main"]); + const provider = createGitRefsProvider({ + repo, + versions, + cacheDir, + apiDocument: "coderd/apidoc/swagger.json", + }); + assert.deepEqual((await provider.loadVersion(versions[1] as DocVersion)).apiDocument, { + swagger: "2.0", + }); + const tagged = await provider.loadVersion(versions[0] as DocVersion); + assert.equal("apiDocument" in tagged, false); + const unasked = createGitRefsProvider({ repo, versions, cacheDir }); + assert.equal("apiDocument" in (await unasked.loadVersion(versions[1] as DocVersion)), false); +}); + +test("createGitRefsProvider refuses a committed symlink as the API document", async () => { + const secret = path.join(tmp, "secret.json"); + await writeFile(secret, '{"secret":"do-not-leak"}'); + await mkdir(path.join(repo, "coderd", "apidoc"), { recursive: true }); + await symlink(secret, path.join(repo, "coderd", "apidoc", "swagger.json")); + await git(repo, ["add", "-A"]); + await git(repo, ["commit", "-m", "symlinked swagger"]); + const main: DocVersion = { id: "main", label: "main", ref: "main" }; + const provider = createGitRefsProvider({ + repo, + versions: [main], + cacheDir, + apiDocument: "coderd/apidoc/swagger.json", + }); + await assert.rejects(provider.loadVersion(main), (error: Error) => { + assert.match(error.message, /symbolic link/); + assert.doesNotMatch(error.message, /do-not-leak/); + return true; + }); +}); + test("createGitRefsProvider rejects an unresolvable ref", async () => { const provider = createGitRefsProvider({ repo, versions, cacheDir }); await assert.rejects(() => provider.loadVersion({ id: "x", label: "X", ref: "does-not-exist" })); diff --git a/packages/docs-sources/src/git-refs.ts b/packages/docs-sources/src/git-refs.ts index 408fcb3b..6fb7a623 100644 --- a/packages/docs-sources/src/git-refs.ts +++ b/packages/docs-sources/src/git-refs.ts @@ -4,6 +4,7 @@ import type { Dirent } from "node:fs"; import { cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; +import { readApiDocument } from "./api-document.js"; import { type DocImage, type DocSource, @@ -62,6 +63,8 @@ export interface GitRefsProviderOptions extends Omit<ReadDocTreeOptions, "manife cacheDir: string; /** Subdirectory within the repo that holds the docs. Defaults to `docs`. */ docsPath?: string; + /** Repo-relative path of a JSON API document to read from each version's checkout onto its source as `apiDocument`. */ + apiDocument?: string; } /** @@ -153,7 +156,13 @@ interface GitCore { * worktree-based `loadVersion`. */ function createGitCore(options: Omit<GitRefsProviderOptions, "versions">): GitCore { - const { repo, cacheDir, docsPath = "docs", ...readOptions } = options; + const { + repo, + cacheDir, + docsPath = "docs", + apiDocument: apiDocumentPath, + ...readOptions + } = options; const worktreeRoot = path.join(cacheDir, STATE_DIR, "worktrees"); const imagesRoot = path.join(cacheDir, STATE_DIR, "images"); const maxFileBytes = readOptions.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES; @@ -208,7 +217,11 @@ function createGitCore(options: Omit<GitRefsProviderOptions, "versions">): GitCo maxFileBytes, maxTotalBytes, }); - return { ...source, images }; + const apiDocument = + apiDocumentPath === undefined + ? undefined + : await readApiDocument(worktree, apiDocumentPath, maxFileBytes); + return { ...source, images, ...(apiDocument === undefined ? {} : { apiDocument }) }; } finally { await runGit(["-C", cacheDir, "worktree", "remove", "--force", worktree]).catch( () => undefined, diff --git a/packages/docs-sources/src/index.ts b/packages/docs-sources/src/index.ts index 28fe8fa8..181f10e2 100644 --- a/packages/docs-sources/src/index.ts +++ b/packages/docs-sources/src/index.ts @@ -22,4 +22,4 @@ export { } from "./git-refs.js"; export { readGitLastModified } from "./last-modified.js"; export { readContainedFile } from "./contained-file.js"; -export { SWAGGER_PATH, swaggerFromClone, swaggerFromTree } from "./swagger.js"; +export { SWAGGER_PATH, readApiDocument } from "./api-document.js"; diff --git a/packages/docs-sources/src/local-tree.test.ts b/packages/docs-sources/src/local-tree.test.ts index 41733482..26d1e768 100644 --- a/packages/docs-sources/src/local-tree.test.ts +++ b/packages/docs-sources/src/local-tree.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, test } from "node:test"; @@ -82,3 +82,24 @@ test("createLocalTreeProvider honours a per-version manifest override", async () ); assert.equal(source.manifestIssues?.length, 1); }); + +test("createLocalTreeProvider reads the API document from the checkout around the docs tree", async () => { + const checkout = await mkdtemp(path.join(os.tmpdir(), "docs-sources-checkout-")); + try { + const docsRoot = path.join(checkout, "docs"); + await mkdir(docsRoot); + await writeFile( + path.join(docsRoot, "manifest.json"), + JSON.stringify({ versions: ["main"], routes: [{ title: "Home", path: "./index.md" }] }), + ); + await writeFile(path.join(docsRoot, "index.md"), "# Home\n"); + const apiDocument = "coderd/apidoc/swagger.json"; + const provider = createLocalTreeProvider({ docsRoot, version, apiDocument }); + assert.equal("apiDocument" in (await provider.loadVersion(version)), false); + await mkdir(path.join(checkout, "coderd", "apidoc"), { recursive: true }); + await writeFile(path.join(checkout, apiDocument), '{"swagger":"2.0"}'); + assert.deepEqual((await provider.loadVersion(version)).apiDocument, { swagger: "2.0" }); + } finally { + await rm(checkout, { recursive: true, force: true }); + } +}); diff --git a/packages/docs-sources/src/local-tree.ts b/packages/docs-sources/src/local-tree.ts index a9c078cc..5babb7d0 100644 --- a/packages/docs-sources/src/local-tree.ts +++ b/packages/docs-sources/src/local-tree.ts @@ -4,6 +4,8 @@ import { type VersionsProvider, resolveVersionPipeline, } from "@coder/docs-config"; +import path from "node:path"; +import { readApiDocument } from "./api-document.js"; import { type ReadDocTreeOptions, readDocTree } from "./read-tree.js"; export interface LocalTreeProviderOptions extends Omit<ReadDocTreeOptions, "manifestMode"> { @@ -16,6 +18,8 @@ export interface LocalTreeProviderOptions extends Omit<ReadDocTreeOptions, "mani * of whatever `strict` value a caller passes to `syncDocSource`. */ version: DocVersion; + /** Path, relative to the directory holding `docsRoot`, of a JSON API document to read onto the source as `apiDocument`. */ + apiDocument?: string; } /** @@ -25,13 +29,22 @@ export interface LocalTreeProviderOptions extends Omit<ReadDocTreeOptions, "mani * so `loadVersion` ignores which version it is handed. */ export function createLocalTreeProvider(options: LocalTreeProviderOptions): VersionsProvider { - const { docsRoot, version, ...readOptions } = options; + const { docsRoot, version, apiDocument: apiDocumentPath, ...readOptions } = options; return { listVersions: async (): Promise<DocVersion[]> => [version], - loadVersion: async (): Promise<DocSource> => - readDocTree(docsRoot, { + loadVersion: async (): Promise<DocSource> => { + const source = await readDocTree(docsRoot, { ...readOptions, manifestMode: resolveVersionPipeline(version).manifest, - }), + }); + if (apiDocumentPath === undefined) return source; + const checkout = path.dirname(path.resolve(docsRoot)); + const apiDocument = await readApiDocument( + checkout, + apiDocumentPath, + readOptions.maxFileBytes, + ); + return apiDocument === undefined ? source : { ...source, apiDocument }; + }, }; } diff --git a/packages/docs-sources/src/swagger.test.ts b/packages/docs-sources/src/swagger.test.ts deleted file mode 100644 index 2f908f04..00000000 --- a/packages/docs-sources/src/swagger.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; -import { mkdir, mkdtemp, stat, symlink, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import path from "node:path"; -import { test } from "node:test"; -import { swaggerFromClone, swaggerFromTree } from "./swagger.js"; - -async function checkout() { - const root = await mkdtemp(path.join(tmpdir(), "openapi-source-")); - await mkdir(path.join(root, "docs")); - await mkdir(path.join(root, "coderd", "apidoc"), { recursive: true }); - return root; -} - -test("reads the Swagger document beside the docs tree", async () => { - const root = await checkout(); - await writeFile(path.join(root, "coderd", "apidoc", "swagger.json"), '{"swagger":"2.0"}'); - assert.deepEqual(await swaggerFromTree(path.join(root, "docs")), { swagger: "2.0" }); -}); - -test("a symlinked swagger.json is rejected and its target never surfaces", async () => { - const root = await checkout(); - const outside = await mkdtemp(path.join(tmpdir(), "openapi-source-secret-")); - await writeFile(path.join(outside, "secret.json"), '{"secret":"do-not-leak"}'); - await symlink( - path.join(outside, "secret.json"), - path.join(root, "coderd", "apidoc", "swagger.json"), - ); - await assert.rejects(swaggerFromTree(path.join(root, "docs")), (error: Error) => { - assert.match(error.message, /symbolic link/); - assert.doesNotMatch(error.message, /do-not-leak/); - return true; - }); -}); - -test("invalid JSON is reported without the file's content", async () => { - const root = await checkout(); - await writeFile(path.join(root, "coderd", "apidoc", "swagger.json"), "not json do-not-leak"); - await assert.rejects(swaggerFromTree(path.join(root, "docs")), (error: Error) => { - assert.match(error.message, /is not valid JSON/); - assert.doesNotMatch(error.message, /do-not-leak/); - return true; - }); -}); - -async function clone() { - const root = await checkout(); - await writeFile(path.join(root, "docs", "index.md"), "# Docs\n"); - const git = (...args: string[]) => - execFileSync("git", ["-C", root, "-c", "user.name=t", "-c", "user.email=t@t", ...args]); - git("init", "-q", "-b", "main"); - git("add", "-A"); - git("commit", "-q", "-m", "docs only"); - git("tag", "v0"); - await writeFile(path.join(root, "coderd", "apidoc", "swagger.json"), '{"swagger":"2.0"}'); - git("add", "-A"); - git("commit", "-q", "-m", "swagger"); - git("tag", "v1"); - return root; -} - -test("reads the Swagger document at a ref of a clone, and nothing at a ref without one", async () => { - const root = await clone(); - assert.deepEqual(await swaggerFromClone(root, "main"), { swagger: "2.0" }); - assert.deepEqual(await swaggerFromClone(root, "v1"), { swagger: "2.0" }); - assert.equal(await swaggerFromClone(root, "v0"), undefined); -}); - -test("a ref the clone doesn't have fails rather than reading as no Swagger document", async () => { - const root = await clone(); - await assert.rejects(swaggerFromClone(root, "no-such-ref"), /no-such-ref/); -}); - -test("a broken clone fails rather than reading as no Swagger document", async () => { - const notAClone = await mkdtemp(path.join(tmpdir(), "openapi-source-")); - await assert.rejects(swaggerFromClone(notAClone, "main")); -}); - -test("a ref that starts with a dash is never read as a git option", async () => { - const root = await clone(); - const out = path.join(await mkdtemp(path.join(tmpdir(), "openapi-source-")), "written"); - await assert.rejects(swaggerFromClone(root, `--output=${out}`)); - await assert.rejects(stat(out), { code: "ENOENT" }); -}); diff --git a/packages/docs-sources/src/swagger.ts b/packages/docs-sources/src/swagger.ts deleted file mode 100644 index 87950883..00000000 --- a/packages/docs-sources/src/swagger.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { execFile } from "node:child_process"; -import path from "node:path"; -import { promisify } from "node:util"; -import { readContainedFile } from "./contained-file.js"; -import { DEFAULT_MAX_FILE_BYTES } from "./read-tree.js"; - -const execFileAsync = promisify(execFile); - -/** Where coder/coder keeps the Swagger 2.0 document the REST API reference is built from. */ -export const SWAGGER_PATH = "coderd/apidoc/swagger.json"; - -function parseSwagger(text: string, where: string): unknown { - try { - return JSON.parse(text); - } catch { - throw new Error(`${SWAGGER_PATH} at ${where} is not valid JSON`); - } -} - -/** - * The Swagger document of the checkout a `docs/` tree sits in, or undefined - * when there is none. Read with the docs tree's own guarantees: no symbolic - * links, a regular file under the per-file cap, inside the checkout. - */ -export async function swaggerFromTree(docsRoot: string): Promise<unknown> { - const checkout = path.dirname(path.resolve(docsRoot)); - const text = await readContainedFile(checkout, SWAGGER_PATH, DEFAULT_MAX_FILE_BYTES); - return text === undefined ? undefined : parseSwagger(text, checkout); -} - -const errorCode = (error: unknown): unknown => - error instanceof Error && "code" in error ? error.code : undefined; - -/** The object id `spec` names in the clone, or undefined when it names nothing; any other git failure throws. */ -async function resolveObject(cacheDir: string, spec: string): Promise<string | undefined> { - try { - const { stdout } = await execFileAsync("git", [ - "-C", - cacheDir, - "rev-parse", - "--verify", - "--quiet", - "--end-of-options", - spec, - ]); - return stdout.trim(); - } catch (error) { - if (errorCode(error) === 1) return undefined; - throw error; - } -} - -/** The Swagger document at a ref of a git clone, or undefined when the ref has none. */ -export async function swaggerFromClone(cacheDir: string, ref: string): Promise<unknown> { - for (const rev of [`refs/remotes/origin/${ref}`, `refs/tags/${ref}`, ref]) { - const commit = await resolveObject(cacheDir, `${rev}^{commit}`); - if (commit === undefined) continue; - const blob = await resolveObject(cacheDir, `${commit}:${SWAGGER_PATH}`); - if (blob === undefined) return undefined; - let stdout: string; - try { - // A blob over the cap fails the read rather than being buffered. - ({ stdout } = await execFileAsync("git", ["-C", cacheDir, "cat-file", "blob", blob], { - maxBuffer: DEFAULT_MAX_FILE_BYTES, - })); - } catch (error) { - if (errorCode(error) === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") { - throw new Error( - `${SWAGGER_PATH} at ${ref} is over the ${DEFAULT_MAX_FILE_BYTES}-byte limit`, - ); - } - throw error; - } - return parseSwagger(stdout, ref); - } - throw new Error(`${JSON.stringify(ref)} is not a branch, tag or commit of the clone`); -} From 2158fea7e83daf415aa70aa0850aab3027f75e97 Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nickvigilante@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:02:04 -0400 Subject: [PATCH 53/69] refactor: name the API reference data file and read it in one place The data directory was spelled out three times (docs-build's openApiDataDir, the site's loader and the offline export's helper), and both apps carried the same read-parse-memoize loader. openApiDataDir and openApiDataFile now live in @coder/docs-config, which the writer and the readers already depend on and which keeps swagger2openapi out of the Next server bundle, and openApiDataFile refuses an id that would leave the directory. createOpenApiDataLoader in @coder/docs-next/openapi is the one server-side reader: each app passes its directory and how a version maps to a file. Assisted-by: AI --- apps/docs/lib/openapi.ts | 29 ++----------- apps/offlinedocs/lib/openapi.ts | 24 +++-------- apps/offlinedocs/scripts/sync-helpers.mjs | 6 --- .../offlinedocs/scripts/sync-helpers.test.mjs | 4 +- packages/docs-build/src/index.ts | 1 - .../docs-build/src/openapi-output.test.ts | 3 +- packages/docs-build/src/openapi-output.ts | 14 +++---- packages/docs-config/src/index.ts | 1 + packages/docs-config/src/openapi-data.test.ts | 16 +++++++ packages/docs-config/src/openapi-data.ts | 13 ++++++ packages/docs-next/src/openapi/data.test.ts | 42 +++++++++++++++++++ packages/docs-next/src/openapi/data.ts | 31 ++++++++++++++ packages/docs-next/src/openapi/index.tsx | 1 + 13 files changed, 123 insertions(+), 62 deletions(-) create mode 100644 packages/docs-config/src/openapi-data.test.ts create mode 100644 packages/docs-config/src/openapi-data.ts create mode 100644 packages/docs-next/src/openapi/data.test.ts create mode 100644 packages/docs-next/src/openapi/data.ts diff --git a/apps/docs/lib/openapi.ts b/apps/docs/lib/openapi.ts index 94aeda40..c1462f26 100644 --- a/apps/docs/lib/openapi.ts +++ b/apps/docs/lib/openapi.ts @@ -1,26 +1,5 @@ -import { readFile } from "node:fs/promises"; -import path from "node:path"; -import type { OpenApiPagesData } from "@coder/docs-config"; -import { createOpenApiRenderBody } from "@coder/docs-next/openapi"; +import { createOpenApiDataLoader, createOpenApiRenderBody } from "@coder/docs-next/openapi"; -const cache = new Map<string, Promise<OpenApiPagesData | undefined>>(); - -// Read at render time rather than imported, so the document stays out of the server bundle. -function load(versionId: string | undefined): Promise<OpenApiPagesData | undefined> { - const id = versionId ?? ""; - let cached = cache.get(id); - if (!cached) { - const file = path.join(process.cwd(), ".generated", "openapi", `${id}.json`); - cached = readFile(file, "utf8").then( - (text) => JSON.parse(text) as OpenApiPagesData, - (error: NodeJS.ErrnoException) => { - if (error.code === "ENOENT") return undefined; - throw error; - }, - ); - cache.set(id, cached); - } - return cached; -} - -export const renderApiReference = createOpenApiRenderBody(load); +export const renderApiReference = createOpenApiRenderBody( + createOpenApiDataLoader(process.cwd(), (versionId) => versionId), +); diff --git a/apps/offlinedocs/lib/openapi.ts b/apps/offlinedocs/lib/openapi.ts index ae2c9c64..5a157a13 100644 --- a/apps/offlinedocs/lib/openapi.ts +++ b/apps/offlinedocs/lib/openapi.ts @@ -1,20 +1,6 @@ -import { readFile } from "node:fs/promises"; -import type { OpenApiPagesData } from "@coder/docs-config"; -import { createOpenApiRenderBody } from "@coder/docs-next/openapi"; -import { openApiDataFile } from "../scripts/sync-helpers.mjs"; +import { createOpenApiDataLoader, createOpenApiRenderBody } from "@coder/docs-next/openapi"; +import { OPENAPI_DATA_ID } from "../scripts/sync-helpers.mjs"; -let cached: Promise<OpenApiPagesData | undefined> | undefined; - -// Read at render time rather than imported, so the document stays out of the server bundle. -function load(): Promise<OpenApiPagesData | undefined> { - cached ??= readFile(openApiDataFile(process.cwd()), "utf8").then( - (text) => JSON.parse(text) as OpenApiPagesData, - (error: NodeJS.ErrnoException) => { - if (error.code === "ENOENT") return undefined; - throw error; - }, - ); - return cached; -} - -export const renderApiReference = createOpenApiRenderBody(load); +export const renderApiReference = createOpenApiRenderBody( + createOpenApiDataLoader(process.cwd(), () => OPENAPI_DATA_ID), +); diff --git a/apps/offlinedocs/scripts/sync-helpers.mjs b/apps/offlinedocs/scripts/sync-helpers.mjs index e460cbb6..6e94d725 100644 --- a/apps/offlinedocs/scripts/sync-helpers.mjs +++ b/apps/offlinedocs/scripts/sync-helpers.mjs @@ -2,8 +2,6 @@ // tested without running a sync. Kept app-local (duplicated in offlinedocs) // until @coder/docs-sources exports shared equivalents. -import path from "node:path"; - /** * Strip URL userinfo (`user:token@`) from a repo URL before it reaches any * console output or error message, so a token-in-URL setup never leaks to @@ -83,7 +81,3 @@ export function exportVersionFromEnv(env) { /** The API reference data's file name: fixed, not the version id, so any DOCS_VERSION finds it. */ export const OPENAPI_DATA_ID = "docs"; - -/** Where `lib/openapi.ts` reads the API reference data the sync wrote. */ -export const openApiDataFile = (appDir) => - path.join(appDir, ".generated", "openapi", `${OPENAPI_DATA_ID}.json`); diff --git a/apps/offlinedocs/scripts/sync-helpers.test.mjs b/apps/offlinedocs/scripts/sync-helpers.test.mjs index 5e771002..22e86632 100644 --- a/apps/offlinedocs/scripts/sync-helpers.test.mjs +++ b/apps/offlinedocs/scripts/sync-helpers.test.mjs @@ -10,13 +10,13 @@ import { headersForPath, } from "../../docs/scripts/vercel-headers.mjs"; import { withOpenApiReference } from "@coder/docs-build"; +import { openApiDataFile } from "@coder/docs-config"; import { buildOutputConfig } from "./build-output-helpers.mjs"; import { OPENAPI_DATA_ID, assertDeployHasCorpus, exportVersionFromEnv, githubBlobSourceLink, - openApiDataFile, redactRepoUrl, } from "./sync-helpers.mjs"; @@ -243,6 +243,6 @@ test("the reference data of a release export is where lib/openapi.ts reads it", logger: { log() {}, warn() {} }, dataId: OPENAPI_DATA_ID, }); - const data = JSON.parse(await readFile(openApiDataFile(exportDir), "utf8")); + const data = JSON.parse(await readFile(openApiDataFile(exportDir, OPENAPI_DATA_ID), "utf8")); assert.ok(data.operations["reference/api/users/create-new-user"]); }); diff --git a/packages/docs-build/src/index.ts b/packages/docs-build/src/index.ts index f448f43a..3f997287 100644 --- a/packages/docs-build/src/index.ts +++ b/packages/docs-build/src/index.ts @@ -13,7 +13,6 @@ export { applyOpenApiReference, convertSwagger, tagSlug } from "./openapi-refere export { OPENAPI_MIN_LINE, clearOpenApi, - openApiDataDir, rendersOpenApi, withOpenApiReference, } from "./openapi-output.js"; diff --git a/packages/docs-build/src/openapi-output.test.ts b/packages/docs-build/src/openapi-output.test.ts index 0079d30f..ebdc1360 100644 --- a/packages/docs-build/src/openapi-output.test.ts +++ b/packages/docs-build/src/openapi-output.test.ts @@ -3,11 +3,10 @@ import { mkdtemp, readFile, stat } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { test } from "node:test"; -import type { DocSource } from "@coder/docs-config"; +import { type DocSource, openApiDataDir } from "@coder/docs-config"; import { OPENAPI_MIN_LINE, clearOpenApi, - openApiDataDir, rendersOpenApi, withOpenApiReference, } from "./openapi-output.js"; diff --git a/packages/docs-build/src/openapi-output.ts b/packages/docs-build/src/openapi-output.ts index 10d8fbc3..db86144d 100644 --- a/packages/docs-build/src/openapi-output.ts +++ b/packages/docs-build/src/openapi-output.ts @@ -1,13 +1,13 @@ import { mkdir, rm, writeFile } from "node:fs/promises"; -import path from "node:path"; -import type { DocSource, OpenApiPagesData } from "@coder/docs-config"; +import { + type DocSource, + type OpenApiPagesData, + openApiDataDir, + openApiDataFile, +} from "@coder/docs-config"; import { isLineAtLeast } from "@coder/docs-manifest/version-segment"; import { applyOpenApiReference } from "./openapi-reference.js"; -/** Where a sync leaves each version's REST API reference data, which the page renderer reads. */ -export const openApiDataDir = (appDir: string): string => - path.join(appDir, ".generated", "openapi"); - export interface WithOpenApiReferenceOptions { logger?: Pick<Console, "log" | "warn">; /** Throw instead of keeping the Markdown reference when there is no Swagger document: set for a publish. */ @@ -65,7 +65,7 @@ export async function withOpenApiReference( const { source: next, reference } = await applyOpenApiReference(source, swagger); await mkdir(openApiDataDir(appDir), { recursive: true }); await writeFile( - path.join(openApiDataDir(appDir), `${dataId}.json`), + openApiDataFile(appDir, dataId), JSON.stringify({ document: reference.document, operations: reference.operations, diff --git a/packages/docs-config/src/index.ts b/packages/docs-config/src/index.ts index 28f40c7e..2ff15097 100644 --- a/packages/docs-config/src/index.ts +++ b/packages/docs-config/src/index.ts @@ -107,4 +107,5 @@ export { export { USER_CONTENT_PREFIX } from "./user-content.js"; export * from "./openapi.js"; +export { openApiDataDir, openApiDataFile } from "./openapi-data.js"; export { isObject, type JsonObject } from "./json.js"; diff --git a/packages/docs-config/src/openapi-data.test.ts b/packages/docs-config/src/openapi-data.test.ts new file mode 100644 index 00000000..ff9abc2d --- /dev/null +++ b/packages/docs-config/src/openapi-data.test.ts @@ -0,0 +1,16 @@ +import assert from "node:assert/strict"; +import path from "node:path"; +import { test } from "node:test"; +import { openApiDataDir, openApiDataFile } from "./openapi-data.js"; + +test("a version's data file sits in the app's generated openapi directory", () => { + const app = path.join("/srv", "app"); + assert.equal(openApiDataDir(app), path.join(app, ".generated", "openapi")); + assert.equal(openApiDataFile(app, "2.38"), path.join(app, ".generated", "openapi", "2.38.json")); +}); + +test("an id that would leave the directory is refused", () => { + for (const id of ["", "../x", "a/b", "a\\b", "."]) { + assert.throws(() => openApiDataFile("/srv/app", id), /data id/); + } +}); diff --git a/packages/docs-config/src/openapi-data.ts b/packages/docs-config/src/openapi-data.ts new file mode 100644 index 00000000..53140a83 --- /dev/null +++ b/packages/docs-config/src/openapi-data.ts @@ -0,0 +1,13 @@ +import path from "node:path"; + +/** Where a sync leaves each version's REST API reference data, which the page renderer reads. */ +export const openApiDataDir = (appDir: string): string => + path.join(appDir, ".generated", "openapi"); + +const DATA_ID = /^[\w-][\w.-]*$/; + +/** The data file of one version, named by `id`: the version id, or a fixed name for a single-version export. */ +export function openApiDataFile(appDir: string, id: string): string { + if (!DATA_ID.test(id)) throw new Error(`not an API reference data id: ${JSON.stringify(id)}`); + return path.join(openApiDataDir(appDir), `${id}.json`); +} diff --git a/packages/docs-next/src/openapi/data.test.ts b/packages/docs-next/src/openapi/data.test.ts new file mode 100644 index 00000000..b142158e --- /dev/null +++ b/packages/docs-next/src/openapi/data.test.ts @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { openApiDataFile } from "@coder/docs-config"; +import { createOpenApiDataLoader } from "./data.js"; + +async function appWith(files: Record<string, string>): Promise<string> { + const app = await mkdtemp(path.join(tmpdir(), "openapi-data-")); + for (const [id, text] of Object.entries(files)) { + const file = openApiDataFile(app, id); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, text); + } + return app; +} + +test("reads a version's data, once, and gives undefined for a version without any", async (t) => { + const app = await appWith({ "2.38": '{"operations":{}}' }); + t.after(() => rm(app, { recursive: true, force: true })); + const load = createOpenApiDataLoader(app, (versionId) => versionId); + const first = load("2.38"); + assert.equal(load("2.38"), first); + assert.deepEqual(await first, { operations: {} }); + assert.equal(await load("2.37"), undefined); + assert.equal(await load(undefined), undefined); +}); + +test("maps every version to one file when told to", async (t) => { + const app = await appWith({ docs: '{"operations":{"a":{}}}' }); + t.after(() => rm(app, { recursive: true, force: true })); + const load = createOpenApiDataLoader(app, () => "docs"); + assert.deepEqual(await load("2.38"), { operations: { a: {} } }); + assert.equal(load(undefined), load("2.38")); +}); + +test("a file that is not JSON fails rather than reading as no data", async (t) => { + const app = await appWith({ main: "not json" }); + t.after(() => rm(app, { recursive: true, force: true })); + await assert.rejects(createOpenApiDataLoader(app, () => "main")(undefined), SyntaxError); +}); diff --git a/packages/docs-next/src/openapi/data.ts b/packages/docs-next/src/openapi/data.ts new file mode 100644 index 00000000..49176480 --- /dev/null +++ b/packages/docs-next/src/openapi/data.ts @@ -0,0 +1,31 @@ +import { readFile } from "node:fs/promises"; +import { type OpenApiPagesData, openApiDataFile } from "@coder/docs-config"; + +/** + * Reads the REST API reference data a sync wrote under `appDir`, at render + * time rather than as an import, so the document stays out of the server + * bundle. `idFor` names a version's data file; a version with no file has no + * generated reference, nor does one `idFor` maps to undefined. Each file is read once. + */ +export function createOpenApiDataLoader( + appDir: string, + idFor: (versionId: string | undefined) => string | undefined, +): (versionId: string | undefined) => Promise<OpenApiPagesData | undefined> { + const cache = new Map<string, Promise<OpenApiPagesData | undefined>>(); + return (versionId) => { + const id = idFor(versionId); + if (id === undefined) return Promise.resolve(undefined); + let cached = cache.get(id); + if (!cached) { + cached = readFile(openApiDataFile(appDir, id), "utf8").then( + (text): OpenApiPagesData => JSON.parse(text), + (error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return undefined; + throw error; + }, + ); + cache.set(id, cached); + } + return cached; + }; +} diff --git a/packages/docs-next/src/openapi/index.tsx b/packages/docs-next/src/openapi/index.tsx index a543a6e2..01eed75c 100644 --- a/packages/docs-next/src/openapi/index.tsx +++ b/packages/docs-next/src/openapi/index.tsx @@ -141,4 +141,5 @@ export function createOpenApiRenderBody( }; } +export { createOpenApiDataLoader } from "./data.js"; export { collapseFoldersUnder } from "./tree.js"; From 12147a5165d36174b4d5fd251214b2ebccda5a63 Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nickvigilante@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:03:43 -0400 Subject: [PATCH 54/69] refactor(docs-next): build a page's served link with one pageHref The llms.txt writer, the open graph canonical URL and the API reference's hrefFor each joined a base and a page URL and added the trailing slash the exports serve. pageHref moves from llms.ts to version-routing.ts and all three call it. Assisted-by: AI --- packages/docs-next/src/llms.ts | 12 +----------- packages/docs-next/src/open-graph.ts | 5 ++--- packages/docs-next/src/render-body.tsx | 5 ++--- packages/docs-next/src/version-routing.test.ts | 7 +++++++ packages/docs-next/src/version-routing.ts | 10 ++++++++++ 5 files changed, 22 insertions(+), 17 deletions(-) diff --git a/packages/docs-next/src/llms.ts b/packages/docs-next/src/llms.ts index df7eaf8e..697aaafe 100644 --- a/packages/docs-next/src/llms.ts +++ b/packages/docs-next/src/llms.ts @@ -13,7 +13,7 @@ * untrusted, so nothing may render them as HTML; refer to the "Security: the * corpus is untrusted" section of `packages/docs-transforms/README.md`. */ -import { normalizeBasePath } from "./version-routing.js"; +import { normalizeBasePath, pageHref } from "./version-routing.js"; /** * The staging directory the twin routes generate into. A Next route segment @@ -149,16 +149,6 @@ function linkText(text: string): string { return oneLine(text).replace(/\\/g, "\\\\").replace(/]/g, "\\]"); } -/** - * A page's link as the export actually serves it. Both exports are built - * `trailingSlash: true` and the router redirects a bare page path, so the - * loader's own URL would cost every reader of this file one 308 per line. - */ -function pageHref(base: string, url: string): string { - const href = `${base}${url}`; - return href.endsWith("/") ? href : `${href}/`; -} - /** * A version's `llms.txt`, in the llmstxt.org shape: the version's heading, a * one-line description, and a `## Pages` list of every page with its diff --git a/packages/docs-next/src/open-graph.ts b/packages/docs-next/src/open-graph.ts index 626ac61a..f3b6799f 100644 --- a/packages/docs-next/src/open-graph.ts +++ b/packages/docs-next/src/open-graph.ts @@ -14,6 +14,7 @@ */ import { stripCodeTitle } from "@coder/docs-config"; import type { Metadata } from "next"; +import { pageHref } from "./version-routing.js"; /** * The header line the generator prints above the title. @@ -210,7 +211,5 @@ function pageUrl( siteUrl: string | undefined, segments: readonly string[] = [], ): string | undefined { - if (!siteUrl) return undefined; - const href = `${siteUrl}/${segments.join("/")}`; - return href.endsWith("/") ? href : `${href}/`; + return siteUrl ? pageHref(siteUrl, `/${segments.join("/")}`) : undefined; } diff --git a/packages/docs-next/src/render-body.tsx b/packages/docs-next/src/render-body.tsx index 89a67386..93b17042 100644 --- a/packages/docs-next/src/render-body.tsx +++ b/packages/docs-next/src/render-body.tsx @@ -1,7 +1,7 @@ import type { TableOfContents } from "fumadocs-core/toc"; import type { ReactNode } from "react"; import type { DocsSource, RenderBody } from "./types.js"; -import { normalizeBasePath } from "./version-routing.js"; +import { normalizeBasePath, pageHref } from "./version-routing.js"; /** The page body after an optional `renderBody` hook has had its say, with the page data it changes. */ export async function resolveBody<Data extends { toc: TableOfContents; full?: boolean }>( @@ -18,8 +18,7 @@ export async function resolveBody<Data extends { toc: TableOfContents; full?: bo slugs, hrefFor: (route) => { const url = source.getPage(route.split("/"))?.url; - if (url === undefined) return undefined; - return `${normalizeBasePath(assetBasePath)}${url.endsWith("/") ? url : `${url}/`}`; + return url === undefined ? undefined : pageHref(normalizeBasePath(assetBasePath), url); }, }); if (!custom) return { body: markdown, data }; diff --git a/packages/docs-next/src/version-routing.test.ts b/packages/docs-next/src/version-routing.test.ts index 78ffa4c9..873d275d 100644 --- a/packages/docs-next/src/version-routing.test.ts +++ b/packages/docs-next/src/version-routing.test.ts @@ -3,6 +3,7 @@ import test from "node:test"; import type { DocVersion } from "@coder/docs-config"; import { normalizeBasePath, + pageHref, resolveSlug, switchHref, versionBaseUrl, @@ -220,3 +221,9 @@ test("versionSwitcherOptions excludes hidden versions and flags the current one" assert.equal(options.find((o) => o.id === "2.19")?.href, "/v2.19/admin"); assert.equal(options.find((o) => o.id === "nick/preview")?.href, "/@nick/preview"); }); + +test("pageHref joins the base and the page URL with the trailing slash the exports serve", () => { + assert.equal(pageHref("", "/install"), "/install/"); + assert.equal(pageHref("/beta-docs", "/install/"), "/beta-docs/install/"); + assert.equal(pageHref("https://coder.com/docs", "/"), "https://coder.com/docs/"); +}); diff --git a/packages/docs-next/src/version-routing.ts b/packages/docs-next/src/version-routing.ts index 10e896c6..20f6dea4 100644 --- a/packages/docs-next/src/version-routing.ts +++ b/packages/docs-next/src/version-routing.ts @@ -233,3 +233,13 @@ export function versionSwitcherOptions( return option; }); } + +/** + * A page's link as the exports serve it: `base` and the loader's URL, with + * the trailing slash both exports are built with (`trailingSlash: true`), so + * the link costs no 308. + */ +export function pageHref(base: string, url: string): string { + const href = `${base}${url}`; + return href.endsWith("/") ? href : `${href}/`; +} From 9a5ef0654cca0d87d6421472642a1a76a5b3446b Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nickvigilante@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:04:42 -0400 Subject: [PATCH 55/69] refactor(docs-manifest): compare lines in isLineAtLeast with compareVersionIdsDesc minorParts repeated numericParts, and the comparison was the one compareVersionIdsDesc already makes. isLineAtLeast now compares the id's minor line with the floor through it; the test adds 10.0, 2.100.1, 0.1 and 0.2, which give the same answers as before. Assisted-by: AI --- packages/docs-manifest/src/version-segment.test.ts | 4 ++++ packages/docs-manifest/src/version-segment.ts | 9 +-------- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/packages/docs-manifest/src/version-segment.test.ts b/packages/docs-manifest/src/version-segment.test.ts index ae4b9787..78a96c9a 100644 --- a/packages/docs-manifest/src/version-segment.test.ts +++ b/packages/docs-manifest/src/version-segment.test.ts @@ -175,6 +175,10 @@ test("isLineAtLeast compares a line or tag's minor line with a floor line, and m assert.equal(isLineAtLeast("2.9", "2.24"), false, "minors compare as numbers, not text"); assert.equal(isLineAtLeast("3.0", "2.24"), true); assert.equal(isLineAtLeast("main", "2.24"), true); + assert.equal(isLineAtLeast("10.0", "2.24"), true); + assert.equal(isLineAtLeast("2.100.1", "2.24"), true); + assert.equal(isLineAtLeast("0.1", "0.2"), false); + assert.equal(isLineAtLeast("0.2", "0.2"), true); assert.throws(() => isLineAtLeast("2.24", "main"), /not a line id/); assert.throws(() => isLineAtLeast("v2.24", "2.24"), /not a version id/); }); diff --git a/packages/docs-manifest/src/version-segment.ts b/packages/docs-manifest/src/version-segment.ts index 12f45b63..c5e1672d 100644 --- a/packages/docs-manifest/src/version-segment.ts +++ b/packages/docs-manifest/src/version-segment.ts @@ -85,18 +85,11 @@ export function versionKind(id: string): VersionKind { throw new Error(`not a version id: ${JSON.stringify(id)}`); } -const minorParts = (id: string): [number, number] => { - const [major, minor] = id.split(".").map(Number); - return [major ?? 0, minor ?? 0]; -}; - /** Whether a version is on the `floor` line or a newer one: a line or tag by its minor line, and main as the newest. */ export function isLineAtLeast(id: string, floor: string): boolean { if (!LINE_ID_PATTERN.test(floor)) throw new Error(`not a line id: ${JSON.stringify(floor)}`); if (versionKind(id) === "dev") return true; - const [major, minor] = minorParts(id); - const [floorMajor, floorMinor] = minorParts(floor); - return major > floorMajor || (major === floorMajor && minor >= floorMinor); + return compareVersionIdsDesc(id.split(".").slice(0, 2).join("."), floor) <= 0; } /** The canonical first segment: `v2.38` for a line, `@v2.38.1` for a tag, `@main` for main. */ From 1f7e41c019322b3453789275abc44e4d2bdf3b3e Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nickvigilante@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:08:06 -0400 Subject: [PATCH 56/69] fix(docs-build): take the landing page's heading ids from the heading-id pass withSetupSection predicted the ids the landing page renders with its own heading regex and inline-Markdown stripping, while the page gets its ids from remarkClassicHeadingIds over the rendered heading text. The two differed for emphasis, inline HTML, escapes, step headings and indented headings, and when they did, the samples note's setup link and the card sections' TOC entries pointed at ids the page doesn't have. headingIds in @coder/docs-transforms replaces findHeadings: it runs the step-heading normalisation, remarkClassicHeadingIds and safeHeadingId over a page body and returns each heading's rendered id. The landing page's setup id is read from it, and the card sections are slugged after every id it returns. The card descriptions' Markdown stripping is now a named inlineMarkdownText helper. Assisted-by: AI --- .../docs-build/src/openapi-reference.test.ts | 10 ++++ packages/docs-build/src/openapi-reference.ts | 59 ++++++++++++------- packages/docs-transforms/src/index.ts | 2 +- .../docs-transforms/src/transform.test.ts | 27 ++++++--- packages/docs-transforms/src/transform.ts | 35 ++++++----- 5 files changed, 88 insertions(+), 45 deletions(-) diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index 534e232f..ba484614 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -345,3 +345,13 @@ test("a basePath's trailing slashes are dropped, and a root basePath adds nothin assert.equal(reference.operations["reference/api/users/get-user-by-name"]?.path, expected); } }); + +test("section ids follow the ids the landing page renders, not its heading source", async () => { + const { reference } = await applyOpenApiReference( + withLanding("# REST API\n\n### _Users_\n\n ## <kbd>Workspaces</kbd>\n"), + swagger, + ); + assert.equal(reference.landing.setupId, "set-up-your-environment"); + assert.equal(reference.landing.sections[0]?.id, "users-1"); + assert.equal(reference.landing.sections[1]?.id, "workspaces-1"); +}); diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 88287464..4eab04d2 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -15,7 +15,13 @@ import { type OpenApiPagesData, SESSION_TOKEN_ENV, } from "@coder/docs-config"; -import { buildDirRoutes, findHeadings, mapMdPath, parseFrontmatter } from "@coder/docs-transforms"; +import { + buildDirRoutes, + extractTitle, + headingIds, + mapMdPath, + parseFrontmatter, +} from "@coder/docs-transforms"; import GithubSlugger from "github-slugger"; import { validate } from "oas-validator"; import { convertObj } from "swagger2openapi"; @@ -435,37 +441,52 @@ export ${SESSION_TOKEN_ENV}="$(cat /run/secrets/coder-token)" Keep the token out of your shell history and out of committed files. `; +/** The ids the page renders for a landing source's headings, by 0-based line; the sync drops the H1, so it takes none. */ +function landingHeadingIds(content: string): Map<number, { depth: number; id: string }> { + const { endLine } = parseFrontmatter(content); + const { h1Line } = extractTitle(content, API_REFERENCE_DIR); + const body = content + .split("\n") + .map((line, index) => (index === h1Line ? "" : line)) + .slice(endLine) + .join("\n"); + return new Map( + headingIds(body).map(({ line, depth, id }) => [line + endLine, { depth, id }] as const), + ); +} + /** * The landing page with the environment setup section before its first - * section, and a slugger that has seen every heading the rendered page will - * have, so the setup and card section ids match the page's own. + * section, and a slugger that has seen every id the rendered page will have, + * so the setup and card section ids match the page's own. */ function withSetupSection(content: string): { content: string; setupId: string; slugger: GithubSlugger; } { - const { endLine } = parseFrontmatter(content); + const at = [...landingHeadingIds(content)].find(([, heading]) => heading.depth === 2)?.[0]; const lines = content.split("\n"); - // The sync drops the H1, so it never takes a slug. - const headings = findHeadings(lines.slice(endLine).join("\n")) - .filter((heading) => heading.depth > 1) - .map((heading) => ({ ...heading, line: heading.line + endLine })); - const at = headings.find((heading) => heading.depth === 2)?.line; - const slugger = new GithubSlugger(); - let setupId: string | undefined; - for (const heading of headings) { - if (heading.line === at) setupId = slugger.slug(SETUP_HEADING); - slugger.slug(heading.text); - } - setupId ??= slugger.slug(SETUP_HEADING); const next = at === undefined ? `${content.trimEnd()}\n\n${SETUP_SECTION}` : [...lines.slice(0, at), SETUP_SECTION, ...lines.slice(at)].join("\n"); + const ids = landingHeadingIds(next); + const setupId = ids.get(at ?? `${content.trimEnd()}\n`.split("\n").length)?.id; + if (setupId === undefined) throw new Error("the landing page's setup heading has no id"); + const slugger = new GithubSlugger(); + for (const { id } of ids.values()) slugger.slug(id); return { content: next, setupId, slugger }; } +/** Inline Markdown as plain text: links and images by their text, without code or emphasis markers. */ +const inlineMarkdownText = (markdown: string): string => + markdown + .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/[`*]/g, "") + .replace(/\s+/g, " ") + .trim(); + /** The first sentence of an operation's Markdown description, as plain text for its card. */ function firstSentence(markdown: string | undefined): string | undefined { // The link pattern below is quadratic, and only the first 200 characters are kept. @@ -474,11 +495,7 @@ function firstSentence(markdown: string | undefined): string | undefined { .slice(0, 2000) .split(/\n\s*\n/)[0]; if (!paragraph) return undefined; - const text = paragraph - .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") - .replace(/[`*]/g, "") - .replace(/\s+/g, " ") - .trim(); + const text = inlineMarkdownText(paragraph); const sentence = /^.*?[.!?](?=\s|$)/.exec(text)?.[0] ?? text; if (sentence.length <= 200) return sentence || undefined; const space = sentence.lastIndexOf(" ", 199); diff --git a/packages/docs-transforms/src/index.ts b/packages/docs-transforms/src/index.ts index 448accea..7dd35b87 100644 --- a/packages/docs-transforms/src/index.ts +++ b/packages/docs-transforms/src/index.ts @@ -24,7 +24,7 @@ export { parseFrontmatter, FrontmatterError, extractTitle, - findHeadings, + headingIds, rewriteTarget, rewriteContent, } from "./transform.js"; diff --git a/packages/docs-transforms/src/transform.test.ts b/packages/docs-transforms/src/transform.test.ts index a11ea508..41816488 100644 --- a/packages/docs-transforms/src/transform.test.ts +++ b/packages/docs-transforms/src/transform.test.ts @@ -7,7 +7,7 @@ import { escapeCurlyBraces, extractTitle, findIncludeDirectives, - findHeadings, + headingIds, isIndexFile, lastSeg, normalizeAngleBrackets, @@ -1269,12 +1269,10 @@ test("scanMarkdownNesting stays linear on a long line of container markers", () } }); -test("findHeadings lists the prose ATX headings with their line, depth and plain text", () => { +test("headingIds gives each heading the id the synced page renders with", () => { assert.deepEqual( - findHeadings( + headingIds( [ - "# Title", - "", "```md", "## In a fence", "```", @@ -1284,13 +1282,24 @@ test("findHeadings lists the prose ATX headings with their line, depth and plain "</div>", "", "## Use `coder` with [links](./x.md) ##", - "### Deeper", + "### An _emphasis_ heading", + " ## Indented", + "## Use <kbd>Ctrl</kbd> keys", + "## Step 1: Install", + "## Intro", + "## Intro", + "## __next data", ].join("\n"), ), [ - { line: 0, depth: 1, text: "Title" }, - { line: 10, depth: 2, text: "Use coder with links" }, - { line: 11, depth: 3, text: "Deeper" }, + { line: 8, depth: 2, id: "use-coder-with-links" }, + { line: 9, depth: 3, id: "an-emphasis-heading" }, + { line: 10, depth: 2, id: "indented" }, + { line: 11, depth: 2, id: "use-ctrl-keys" }, + { line: 12, depth: 2, id: "step-1-install" }, + { line: 13, depth: 2, id: "intro" }, + { line: 14, depth: 2, id: "intro-1" }, + { line: 15, depth: 2, id: "user-content-__next-data" }, ], ); }); diff --git a/packages/docs-transforms/src/transform.ts b/packages/docs-transforms/src/transform.ts index da650e54..14abecf9 100644 --- a/packages/docs-transforms/src/transform.ts +++ b/packages/docs-transforms/src/transform.ts @@ -11,7 +11,13 @@ import { tagTerminator, } from "./mdx-plugins/html-delimiters.js"; import type { MdastNode } from "./mdx-plugins/mdast.js"; -import { classicHeadingText } from "./mdx-plugins/remark-classic-heading-ids.js"; +import { + classicHeadingId, + classicHeadingText, + remarkClassicHeadingIds, + visitHeadings, +} from "./mdx-plugins/remark-classic-heading-ids.js"; +import { safeHeadingId } from "./mdx-plugins/remark-safe-heading-ids.js"; // The asset-extension set (images and videos) comes from the shared // @coder/docs-config contract so this link rewriter and the content loader @@ -1147,20 +1153,21 @@ export function extractTitle( }; } -/** The prose ATX headings of a Markdown body, with their inline Markdown reduced to the text a slugger sees. */ -export function findHeadings(content: string): { line: number; depth: number; text: string }[] { - const headings: { line: number; depth: number; text: string }[] = []; - mapLines(stripHtmlComments(content).content, (line, info) => { - const match = - info.prose && !info.htmlBlock ? /^(#{1,6})\s+(.+?)(?:\s+#+)?\s*$/.exec(line) : null; - if (match) { - const text = (match[2] as string) - .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") - .replace(/[`*]/g, "") - .trim(); - headings.push({ line: info.index, depth: (match[1] as string).length, text }); +/** + * The id each heading of a page body renders with, from the passes the sync + * and the MDX pipeline run: `normalizeStepHeadings`, `remarkClassicHeadingIds` + * and `safeHeadingId`. `line` is the heading's 0-based line in `body`. + */ +export function headingIds(body: string): { line: number; depth: number; id: string }[] { + const tree = fromMarkdown(stripHtmlComments(normalizeStepHeadings(body)).content) as MdastNode; + remarkClassicHeadingIds()(tree); + const headings: { line: number; depth: number; id: string }[] = []; + visitHeadings(tree, (heading) => { + const id = classicHeadingId(heading); + const line = heading.position?.start?.line; + if (id !== undefined && line !== undefined && heading.depth !== undefined) { + headings.push({ line: line - 1, depth: heading.depth, id: safeHeadingId(id) }); } - return line; }); return headings; } From 2f5bf5e49929d4050c13b56e8e359dfa17d05448 Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nickvigilante@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:08:28 -0400 Subject: [PATCH 57/69] refactor(docs-next): escape single-quoted sample strings in one place The JavaScript and Python string writers each turned a JSON string body into a single-quoted one with the same replacer. singleQuotedBody holds it, so the two languages' escaping can't drift apart. Assisted-by: AI --- packages/docs-next/src/openapi/code-samples.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/packages/docs-next/src/openapi/code-samples.ts b/packages/docs-next/src/openapi/code-samples.ts index 826ebfa7..9c876a14 100644 --- a/packages/docs-next/src/openapi/code-samples.ts +++ b/packages/docs-next/src/openapi/code-samples.ts @@ -203,15 +203,19 @@ const width = (line: string): number => line.replace(/\t/g, " ").length; const fitOrBreak = (limit: number, oneLine: string[], broken: string[]): string[] => oneLine.every((line) => width(line) <= limit) ? oneLine : broken; +/** The body of a JSON string literal, escaped for single quotes instead: ' escaped, " unescaped. */ +const singleQuotedBody = (jsonBody: string): string => + jsonBody.replace(/\\(.)|(')/gs, (match, escaped?: string) => + escaped === undefined ? "\\'" : escaped === '"' ? '"' : match, + ); + /** A JavaScript string literal as Prettier writes it: double quotes unless the text holds more of them than single quotes. */ function jsString(text: string): string { const doubles = text.split('"').length - 1; const singles = text.split("'").length - 1; const inner = JSON.stringify(text).slice(1, -1); if (doubles <= singles) return `"${inner}"`; - return `'${inner.replace(/\\(.)|(')/gs, (match, escaped?: string) => - escaped === undefined ? "\\'" : escaped === '"' ? '"' : match, - )}'`; + return `'${singleQuotedBody(inner)}'`; } const IDENTIFIER = /^[A-Za-z_$][\w$]*$/; @@ -256,9 +260,7 @@ function jsLiteral(value: unknown, indent: string, before: number, after: number /** A Python string literal as Black writes it: double quotes, unless single quotes need fewer escapes. */ function pythonString(text: string): string { const inner = JSON.stringify(text).slice(1, -1); - const single = inner.replace(/\\(.)|(')/gs, (match, escaped?: string) => - escaped === undefined ? "\\'" : escaped === '"' ? '"' : match, - ); + const single = singleQuotedBody(inner); const escapes = (body: string) => body.split("\\").length - 1; return escapes(single) < escapes(inner) ? `'${single}'` : `"${inner}"`; } From f1826335847802c94973dacbea2c23c5341e2692 Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nickvigilante@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:11:12 -0400 Subject: [PATCH 58/69] test(docs-next): mount client components and type into inputs with shared helpers The schemas, anchor-redirect and API page tests each built their own container, root, act and unmount, and two of them set an input's value through the native setter by hand. mountClient (client render, or server render then hydrate) and typeInto now live in test/dom.ts beside renderToFragment, and unmount through the test context. Assisted-by: AI --- .../src/openapi/anchor-redirect.test.tsx | 23 ++--- .../docs-next/src/openapi/api-page.test.tsx | 84 ++++++++----------- .../docs-next/src/openapi/schemas.test.tsx | 30 ++----- packages/docs-next/test/dom.ts | 42 +++++++++- 4 files changed, 88 insertions(+), 91 deletions(-) diff --git a/packages/docs-next/src/openapi/anchor-redirect.test.tsx b/packages/docs-next/src/openapi/anchor-redirect.test.tsx index bba35f43..5f2feade 100644 --- a/packages/docs-next/src/openapi/anchor-redirect.test.tsx +++ b/packages/docs-next/src/openapi/anchor-redirect.test.tsx @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test, { type TestContext } from "node:test"; -import { act, type ReactNode } from "react"; -import { createRoot } from "react-dom/client"; +import type { ReactNode } from "react"; +import { mountClient, typeInto } from "../../test/dom.js"; import { AnchorRedirect } from "./anchor-redirect.js"; import { SchemaTables } from "./schemas.js"; @@ -10,16 +10,9 @@ const PAGE = "/reference/api/schemas/"; const TARGET = `${PAGE}#redirected`; const targets = { codersdkuser: TARGET }; -async function mount(t: TestContext, url: string, node: ReactNode) { +function mount(t: TestContext, url: string, node: ReactNode): Promise<HTMLElement> { window.history.replaceState(null, "", url); - const container = document.body.appendChild(document.createElement("div")); - const root = createRoot(container); - await act(async () => root.render(node)); - t.after(async () => { - await act(async () => root.unmount()); - container.remove(); - }); - return container; + return mountClient(t, node); } // jsdom reports a navigation away from the document, which it doesn't implement, through console.error. @@ -41,11 +34,9 @@ test("a hash that arrives after the page loaded, with a filter typed, still redi <AnchorRedirect targets={targets} /> </>, ); - const input = container.querySelector("input") as HTMLInputElement; - await act(async () => { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, "user"); - input.dispatchEvent(new Event("input", { bubbles: true })); - }); + const input = container.querySelector("input"); + assert.ok(input); + await typeInto(input, "user"); assert.equal(container.querySelector('[aria-live="polite"]')?.textContent, "1 of 2 schemas"); assert.equal(window.location.hash, ""); window.location.hash = "codersdkuser"; diff --git a/packages/docs-next/src/openapi/api-page.test.tsx b/packages/docs-next/src/openapi/api-page.test.tsx index e24d0421..6052062b 100644 --- a/packages/docs-next/src/openapi/api-page.test.tsx +++ b/packages/docs-next/src/openapi/api-page.test.tsx @@ -1,9 +1,9 @@ import assert from "node:assert/strict"; -import test from "node:test"; +import test, { type TestContext } from "node:test"; import { FrameworkProvider } from "fumadocs-core/framework"; import type { Document } from "fumadocs-openapi"; import { act } from "react"; -import { createRoot } from "react-dom/client"; +import { mountClient } from "../../test/dom.js"; import { ApiPage } from "./api-page.js"; import { withCodeSamples } from "./code-samples.js"; @@ -31,44 +31,35 @@ const document_ = withCodeSamples( ); async function renderPage( + t: TestContext, bundled: Record<string, unknown> = document_, path = "/api/v2/buildinfo", method: "get" | "post" = "get", -): Promise<{ container: HTMLElement; unmount: () => Promise<void> }> { - const container = document.createElement("div"); - document.body.appendChild(container); - const root = createRoot(container); - await act(async () => - root.render( - <FrameworkProvider - usePathname={() => "/"} - useParams={() => ({})} - useRouter={() => ({ push() {}, refresh() {} })} - > - <ApiPage - document="coder" - showTitle={false} - operations={[{ path, method }]} - payload={{ bundled: bundled as Document }} - /> - </FrameworkProvider>, - ), +): Promise<HTMLElement> { + const container = await mountClient( + t, + <FrameworkProvider + usePathname={() => "/"} + useParams={() => ({})} + useRouter={() => ({ push() {}, refresh() {} })} + > + <ApiPage + document="coder" + showTitle={false} + operations={[{ path, method }]} + payload={{ bundled: bundled as Document }} + /> + </FrameworkProvider>, ); await act(async () => new Promise((resolve) => setTimeout(resolve, 50))); - return { - container, - unmount: async () => { - await act(async () => root.unmount()); - container.remove(); - }, - }; + return container; } for (const [label, deployment] of [ ["a leading space and a trailing dot", " http://localhost:3142."], ["not a URL at all", "not a url"], ] as const) { - test(`a stored server URL that is ${label} still renders the samples`, async () => { + test(`a stored server URL that is ${label} still renders the samples`, async (t) => { localStorage.setItem( STORED_SERVER, JSON.stringify({ url: "{deployment}", variables: { deployment } }), @@ -77,14 +68,13 @@ for (const [label, deployment] of [ const onError = (event: ErrorEvent) => errors.push(event.error); window.addEventListener("error", onError); try { - const { container, unmount } = await renderPage(); + const container = await renderPage(t); assert.deepEqual(errors, []); const tabs = [...container.querySelectorAll('[role="tab"]')].map((tab) => tab.textContent); for (const name of ["cURL", "JavaScript", "Python", "Go"]) assert.ok(tabs.includes(name), name); assert.equal(localStorage.getItem(STORED_SERVER), null, "the bad value is dropped"); assert.match(container.textContent ?? "", / -X GET \\\n\t"\$CODER_URL\/api\/v2\/buildinfo"/); - await unmount(); } finally { window.removeEventListener("error", onError); localStorage.clear(); @@ -124,22 +114,18 @@ const choices = withCodeSamples( "post", ); -test("every select in the example column has a name, and each code region is named by its tab", async () => { - const { container, unmount } = await renderPage(choices, "/api/v2/templates", "post"); - try { - const selects = [...container.querySelectorAll('[role="combobox"]')]; - assert.ok(selects.length >= 3, `${selects.length} selects`); - assert.deepEqual( - selects.map((select) => select.getAttribute("aria-label")), - ["Request example", "Response status", "Response example"], - ); - const regions = [...container.querySelectorAll('.coder-sample-tabs [role="region"]')]; - assert.deepEqual( - regions.map((region) => region.getAttribute("aria-label")), - ["cURL sample", "JavaScript sample", "Python sample", "Go sample"].slice(0, regions.length), - ); - assert.ok(regions.length > 0); - } finally { - await unmount(); - } +test("every select in the example column has a name, and each code region is named by its tab", async (t) => { + const container = await renderPage(t, choices, "/api/v2/templates", "post"); + const selects = [...container.querySelectorAll('[role="combobox"]')]; + assert.ok(selects.length >= 3, `${selects.length} selects`); + assert.deepEqual( + selects.map((select) => select.getAttribute("aria-label")), + ["Request example", "Response status", "Response example"], + ); + const regions = [...container.querySelectorAll('.coder-sample-tabs [role="region"]')]; + assert.deepEqual( + regions.map((region) => region.getAttribute("aria-label")), + ["cURL sample", "JavaScript sample", "Python sample", "Go sample"].slice(0, regions.length), + ); + assert.ok(regions.length > 0); }); diff --git a/packages/docs-next/src/openapi/schemas.test.tsx b/packages/docs-next/src/openapi/schemas.test.tsx index 6b2ac95b..5bc8f4b8 100644 --- a/packages/docs-next/src/openapi/schemas.test.tsx +++ b/packages/docs-next/src/openapi/schemas.test.tsx @@ -1,11 +1,8 @@ import assert from "node:assert/strict"; import test, { type TestContext } from "node:test"; -import { act } from "react"; -import { hydrateRoot } from "react-dom/client"; -import { renderToString } from "react-dom/server"; -import { renderToFragment } from "../../test/dom.js"; -import { createOpenApiRenderBody } from "./index.js"; import type { OpenApiSchemaRow } from "@coder/docs-config/client"; +import { mountClient, renderToFragment, typeInto } from "../../test/dom.js"; +import { createOpenApiRenderBody } from "./index.js"; import { SchemaTables } from "./schemas.js"; const rows: OpenApiSchemaRow[] = [ @@ -57,25 +54,10 @@ test("the server HTML holds every row, in closed package groups, with Other last }); async function mount(t: TestContext) { - const container = document.createElement("div"); - container.innerHTML = renderToString(page()); - document.body.appendChild(container); - let root: ReturnType<typeof hydrateRoot> | undefined; - await act(async () => { - root = hydrateRoot(container, page()); - }); - t.after(async () => { - await act(async () => root?.unmount()); - container.remove(); - }); - const input = container.querySelector("input") as HTMLInputElement; - const type = async (text: string) => { - await act(async () => { - const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set; - setter?.call(input, text); - input.dispatchEvent(new Event("input", { bubbles: true })); - }); - }; + const container = await mountClient(t, page(), { hydrate: true }); + const input = container.querySelector("input"); + assert.ok(input); + const type = (text: string) => typeInto(input, text); const visibleRows = () => [...container.querySelectorAll("tbody tr")] .filter((tr) => !(tr as HTMLElement).hidden) diff --git a/packages/docs-next/test/dom.ts b/packages/docs-next/test/dom.ts index 78158e82..1f9aabcb 100644 --- a/packages/docs-next/test/dom.ts +++ b/packages/docs-next/test/dom.ts @@ -1,5 +1,7 @@ -import type { ReactNode } from "react"; -import { renderToStaticMarkup } from "react-dom/server"; +import type { TestContext } from "node:test"; +import { act, type ReactNode } from "react"; +import { createRoot, hydrateRoot, type Root } from "react-dom/client"; +import { renderToStaticMarkup, renderToString } from "react-dom/server"; // Parsed by the jsdom that test/jsdom-setup.mjs installs, so tests query the DOM instead of matching markup as text. export function renderToFragment(node: ReactNode): DocumentFragment { @@ -7,3 +9,39 @@ export function renderToFragment(node: ReactNode): DocumentFragment { template.innerHTML = renderToStaticMarkup(node); return template.content; } + +/** + * Mounts `node` in a container in the document, rendered on the client or, + * with `hydrate`, server-rendered and then hydrated as a page would be. + * Unmounted and removed when the test ends. + */ +export async function mountClient( + t: TestContext, + node: ReactNode, + { hydrate = false }: { hydrate?: boolean } = {}, +): Promise<HTMLElement> { + const container = document.body.appendChild(document.createElement("div")); + let root: Root | undefined; + if (hydrate) { + container.innerHTML = renderToString(node); + await act(async () => { + root = hydrateRoot(container, node); + }); + } else { + root = createRoot(container); + await act(async () => root?.render(node)); + } + t.after(async () => { + await act(async () => root?.unmount()); + container.remove(); + }); + return container; +} + +/** Types `text` into a controlled input the way a reader does: React sees the value change. */ +export async function typeInto(input: HTMLInputElement, text: string): Promise<void> { + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, text); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); +} From dff041b6e1abf0de123b208671238c69656762cd Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nickvigilante@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:11:12 -0400 Subject: [PATCH 59/69] test(docs-next): pin each API page select's name to what the select shows The names come from the selects' place in fumadocs-openapi 12.5.4's markup, and the test checked them only in document order, so an upgrade that moved the status select could swap "Response status" and "Response example" and still pass, as axe would. The test now pairs each name with the value its select shows: the request example, a status code, the response example. Assisted-by: AI --- packages/docs-next/src/openapi/api-page.test.tsx | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/docs-next/src/openapi/api-page.test.tsx b/packages/docs-next/src/openapi/api-page.test.tsx index 6052062b..35eedf6e 100644 --- a/packages/docs-next/src/openapi/api-page.test.tsx +++ b/packages/docs-next/src/openapi/api-page.test.tsx @@ -117,10 +117,14 @@ const choices = withCodeSamples( test("every select in the example column has a name, and each code region is named by its tab", async (t) => { const container = await renderPage(t, choices, "/api/v2/templates", "post"); const selects = [...container.querySelectorAll('[role="combobox"]')]; - assert.ok(selects.length >= 3, `${selects.length} selects`); + // Each name against the value its select shows, so a reshuffled DOM can't swap two names unnoticed. assert.deepEqual( - selects.map((select) => select.getAttribute("aria-label")), - ["Request example", "Response status", "Response example"], + selects.map((select) => [select.getAttribute("aria-label"), select.textContent]), + [ + ["Request example", "Minimal"], + ["Response status", "201"], + ["Response example", "New"], + ], ); const regions = [...container.querySelectorAll('.coder-sample-tabs [role="region"]')]; assert.deepEqual( From bec26bba91453c0ea2306e43f344bb6599af34e5 Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nick.vigilante@coder.com> Date: Fri, 20 Nov 2026 17:13:26 +0000 Subject: [PATCH 60/69] build(deps): upgrade fumadocs-openapi to 12.6.1 and drop the workarounds it fixes 12.6.1 needs the Fumadocs 16.19 that main now has. Our direct shiki, lucide-react and @scalar/json-magic pins follow what it resolves, so the lockfile still holds one copy of shiki and lucide-react; json-magic has two because @fumadocs/json-schema 0.3.5, its latest, still needs 0.16. Upstream now names the example, status and example-response selects, so the wrapper that labelled them is gone and the test pins upstream's names. It also falls back to the page origin on an invalid stored server URL, so every bad value in the render tests still renders, and the repair that trimmed or dropped the value is removed. The playground auth module no longer exports PlaygroundAuthProvider, so its stub drops it and the provider test becomes one that every stubbed auth export throws. Assisted-by: AI --- apps/docs/package.json | 2 +- apps/offlinedocs/package.json | 2 +- packages/docs-next/package.json | 8 +- .../docs-next/src/openapi/api-page.test.tsx | 5 +- packages/docs-next/src/openapi/api-page.tsx | 47 +-- .../src/openapi/playground-stubs.test.ts | 10 +- .../docs-next/src/openapi/playground-stubs.ts | 3 - .../src/openapi/stored-server.test.ts | 48 --- .../docs-next/src/openapi/stored-server.ts | 42 --- pnpm-lock.yaml | 304 +++--------------- 10 files changed, 62 insertions(+), 409 deletions(-) delete mode 100644 packages/docs-next/src/openapi/stored-server.test.ts delete mode 100644 packages/docs-next/src/openapi/stored-server.ts diff --git a/apps/docs/package.json b/apps/docs/package.json index b9abcacd..44736494 100644 --- a/apps/docs/package.json +++ b/apps/docs/package.json @@ -58,7 +58,7 @@ "@vercel/blob": "catalog:", "fumadocs-core": "catalog:", "fumadocs-mdx": "catalog:", - "fumadocs-openapi": "12.5.4", + "fumadocs-openapi": "12.6.1", "fumadocs-ui": "catalog:", "next": "catalog:", "react": "catalog:", diff --git a/apps/offlinedocs/package.json b/apps/offlinedocs/package.json index 044c1b80..452c6002 100644 --- a/apps/offlinedocs/package.json +++ b/apps/offlinedocs/package.json @@ -33,7 +33,7 @@ "@fontsource-variable/geist-mono": "5.3.0", "fumadocs-core": "catalog:", "fumadocs-mdx": "catalog:", - "fumadocs-openapi": "12.5.4", + "fumadocs-openapi": "12.6.1", "fumadocs-ui": "catalog:", "next": "catalog:", "react": "catalog:", diff --git a/packages/docs-next/package.json b/packages/docs-next/package.json index 134dcef7..cec8f1ab 100644 --- a/packages/docs-next/package.json +++ b/packages/docs-next/package.json @@ -47,13 +47,13 @@ "@coder/docs-manifest": "workspace:*", "@coder/docs-ui": "workspace:*", "@fumadocs/json-schema": "0.3.5", - "@scalar/json-magic": "0.16.1", + "@scalar/json-magic": "0.18.0", "es-module-lexer": "1.7.0", "fumadocs-core": "catalog:", - "fumadocs-openapi": "12.5.4", + "fumadocs-openapi": "12.6.1", "fumadocs-ui": "catalog:", - "lucide-react": "1.46.0", - "shiki": "4.5.0" + "lucide-react": "1.73.0", + "shiki": "4.6.0" }, "peerDependencies": { "next": ">=16", diff --git a/packages/docs-next/src/openapi/api-page.test.tsx b/packages/docs-next/src/openapi/api-page.test.tsx index 35eedf6e..ae1d88f0 100644 --- a/packages/docs-next/src/openapi/api-page.test.tsx +++ b/packages/docs-next/src/openapi/api-page.test.tsx @@ -73,7 +73,6 @@ for (const [label, deployment] of [ const tabs = [...container.querySelectorAll('[role="tab"]')].map((tab) => tab.textContent); for (const name of ["cURL", "JavaScript", "Python", "Go"]) assert.ok(tabs.includes(name), name); - assert.equal(localStorage.getItem(STORED_SERVER), null, "the bad value is dropped"); assert.match(container.textContent ?? "", / -X GET \\\n\t"\$CODER_URL\/api\/v2\/buildinfo"/); } finally { window.removeEventListener("error", onError); @@ -121,9 +120,9 @@ test("every select in the example column has a name, and each code region is nam assert.deepEqual( selects.map((select) => [select.getAttribute("aria-label"), select.textContent]), [ - ["Request example", "Minimal"], + ["Example request", "Minimal"], ["Response status", "201"], - ["Response example", "New"], + ["Example", "New"], ], ); const regions = [...container.querySelectorAll('.coder-sample-tabs [role="region"]')]; diff --git a/packages/docs-next/src/openapi/api-page.tsx b/packages/docs-next/src/openapi/api-page.tsx index 49ead49f..d50f0b93 100644 --- a/packages/docs-next/src/openapi/api-page.tsx +++ b/packages/docs-next/src/openapi/api-page.tsx @@ -7,9 +7,8 @@ import { createCodeUsageGeneratorRegistry } from "fumadocs-openapi/requests/gene import { createOpenAPIPageBase } from "fumadocs-openapi/ui/base"; import { DynamicCodeBlock } from "fumadocs-ui/components/dynamic-codeblock.core"; import { Tab, Tabs } from "fumadocs-ui/components/tabs"; -import { type ComponentProps, type ReactNode, useEffect, useRef, useState } from "react"; +import type { ComponentProps } from "react"; import { SamplesNote } from "./samples-note.js"; -import { repairStoredServer } from "./stored-server.js"; // Only the grammars and themes an API page uses (JSON, the code samples, TypeScript definitions), on the JavaScript regex engine (no WASM, no eval). const shiki = createShikiFactory({ @@ -58,42 +57,6 @@ function CodeBlock({ name, ...props }: CodeBlockProps & { name?: string }) { ); } -// fumadocs-openapi 12.5.4's example and status selects (ui/operation/usage-tabs.js) have no accessible name. -function NamedSelects({ - name, - children, -}: { - name: (select: Element, root: Element) => string; - children: ReactNode; -}) { - const ref = useRef<HTMLDivElement>(null); - useEffect(() => { - const root = ref.current; - if (!root) return; - const label = () => { - for (const select of root.querySelectorAll('[role="combobox"]:not([aria-label])')) - select.setAttribute("aria-label", name(select, root)); - }; - label(); - const observer = new MutationObserver(label); - observer.observe(root, { childList: true, subtree: true }); - return () => observer.disconnect(); - }, [name]); - return ( - <div ref={ref} className="contents"> - {children} - </div> - ); -} - -const requestExample = () => "Request example"; - -// The status select sits in the response card's header; an example select, below it. -const responseSelect = (select: Element, root: Element) => - root.firstElementChild?.firstElementChild?.contains(select) - ? "Response status" - : "Response example"; - // One tab per language, where fumadocs-openapi's default is a select in the code block's header. // The samples are the server-built text as is, never run through fumadocs-openapi's generators, which resolve the reader's stored server URL. function SampleTabs() { @@ -158,10 +121,10 @@ const OpenApiPage = createOpenAPIPageBase({ ), renderAPIExampleLayout: ({ selector, usageTabs, responseTabs }) => ( <div className="flex min-h-0 flex-col prose-no-margin"> - <NamedSelects name={requestExample}>{selector}</NamedSelects> + {selector} <SamplesNote /> {usageTabs} - <NamedSelects name={responseSelect}>{responseTabs}</NamedSelects> + {responseTabs} </div> ), }, @@ -169,9 +132,5 @@ const OpenApiPage = createOpenAPIPageBase({ /** One REST API operation, rendered by fumadocs-openapi from the document its page was given, with the server-built code samples. */ export function ApiPage(props: ComponentProps<typeof OpenApiPage>) { - // Before fumadocs-openapi's server store restores the value, in an effect of a child. - useState(() => { - if (typeof window !== "undefined") repairStoredServer(`${STORAGE_KEY_PREFIX}server-url`); - }); return <OpenApiPage {...props} />; } diff --git a/packages/docs-next/src/openapi/playground-stubs.test.ts b/packages/docs-next/src/openapi/playground-stubs.test.ts index c2445187..af28f180 100644 --- a/packages/docs-next/src/openapi/playground-stubs.test.ts +++ b/packages/docs-next/src/openapi/playground-stubs.test.ts @@ -85,16 +85,16 @@ test("the stubs cut every path from the engine's entries to playground code", as ); }); -test("the stub of the auth provider renders its children", async () => { +test("every export of the auth stub throws instead of running an auth flow", async () => { const stub = await playgroundStub( path.join(dist, "playground/auth.js"), read("playground/auth.js"), ); const url = `data:text/javascript,${encodeURIComponent(stub.replace('"use client";', ""))}`; - const auth = (await import(url)) as { - PlaygroundAuthProvider: (p: { children: string }) => string; - }; - assert.equal(auth.PlaygroundAuthProvider({ children: "page" }), "page"); + const auth = (await import(url)) as Record<string, () => unknown>; + const names = Object.keys(auth); + assert.ok(names.length > 0, "the stub exports something"); + for (const name of names) assert.throws(() => auth[name]?.(), /not included in this build/, name); }); test("a matched module with no stub, or with other exports, fails the build", async () => { diff --git a/packages/docs-next/src/openapi/playground-stubs.ts b/packages/docs-next/src/openapi/playground-stubs.ts index 4336958b..181da8c7 100644 --- a/packages/docs-next/src/openapi/playground-stubs.ts +++ b/packages/docs-next/src/openapi/playground-stubs.ts @@ -21,9 +21,6 @@ const unavailable = `function unavailable() { const STUBS: Record<string, string> = { "playground/auth.js": `"use client"; ${unavailable} -export function PlaygroundAuthProvider({ children }) { - return children; -} export { unavailable as finishOAuthFlow, unavailable as requestOAuthToken, diff --git a/packages/docs-next/src/openapi/stored-server.test.ts b/packages/docs-next/src/openapi/stored-server.test.ts deleted file mode 100644 index 772604d6..00000000 --- a/packages/docs-next/src/openapi/stored-server.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { repairStoredServer } from "./stored-server.js"; - -const KEY = "coder-api-server-url"; -const stored = (deployment: unknown, url = "{deployment}") => - JSON.stringify({ url, variables: { deployment } }); - -test.afterEach(() => localStorage.clear()); - -test("a valid stored server is left as it is", () => { - localStorage.setItem(KEY, stored("https://coder.example.com")); - repairStoredServer(KEY); - assert.equal(localStorage.getItem(KEY), stored("https://coder.example.com")); -}); - -test("surrounding white space is trimmed off a value that is otherwise valid", () => { - localStorage.setItem(KEY, stored(" https://coder.example.com\n")); - repairStoredServer(KEY); - assert.equal(localStorage.getItem(KEY), stored("https://coder.example.com")); -}); - -for (const [label, value] of [ - ["a trailing dot after the port", " http://localhost:3142."], - ["a relative URL", "not a url"], - ["a non-HTTP scheme", "javascript:alert(1)"], - ["empty", ""], - ["not a string", 42], -] as const) { - test(`a stored server that is ${label} is dropped, so the page falls back to the default`, () => { - localStorage.setItem(KEY, stored(value)); - repairStoredServer(KEY); - assert.equal(localStorage.getItem(KEY), null); - }); -} - -test("a stored value that is not the shape fumadocs-openapi writes is dropped", () => { - for (const value of ["{", "[]", JSON.stringify({ url: 1 }), JSON.stringify({ url: "x" })]) { - localStorage.setItem(KEY, value); - repairStoredServer(KEY); - assert.equal(localStorage.getItem(KEY), null, value); - } -}); - -test("nothing stored stays nothing", () => { - repairStoredServer(KEY); - assert.equal(localStorage.getItem(KEY), null); -}); diff --git a/packages/docs-next/src/openapi/stored-server.ts b/packages/docs-next/src/openapi/stored-server.ts deleted file mode 100644 index 3a373051..00000000 --- a/packages/docs-next/src/openapi/stored-server.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { isObject } from "@coder/docs-config/client"; - -function repaired(raw: string): string | undefined { - let value: unknown; - try { - value = JSON.parse(raw); - } catch { - return undefined; - } - if (!isObject(value) || typeof value.url !== "string" || !isObject(value.variables)) - return undefined; - const variables: Record<string, string> = {}; - let url = value.url; - for (const [key, variable] of Object.entries(value.variables)) { - if (typeof variable !== "string") return undefined; - variables[key] = variable.trim(); - url = url.replaceAll(`{${key}}`, variables[key]); - } - const parsed = URL.canParse(url) ? new URL(url) : undefined; - if (parsed?.protocol !== "http:" && parsed?.protocol !== "https:") return undefined; - return JSON.stringify({ ...value, variables }); -} - -/** - * Trims the server URL fumadocs-openapi keeps in `localStorage`, and removes - * it when it is still not an absolute HTTP(S) URL, so the page falls back to - * the document's default server instead of throwing from `new URL()`. - */ -export function repairStoredServer(storageKey: string): void { - let raw: string | null; - try { - raw = localStorage.getItem(storageKey); - } catch { - return; - } - if (raw === null) return; - const next = repaired(raw); - try { - if (next === undefined) localStorage.removeItem(storageKey); - else if (next !== raw) localStorage.setItem(storageKey, next); - } catch {} -} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 40a4ba52..14278985 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -123,8 +123,8 @@ importers: specifier: 'catalog:' version: 15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) fumadocs-openapi: - specifier: 12.5.4 - version: 12.5.4(83fbde21deb18050b9b10d0b4220f1cf) + specifier: 12.6.1 + version: 12.6.1(83fbde21deb18050b9b10d0b4220f1cf) fumadocs-ui: specifier: 'catalog:' version: 16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) @@ -229,8 +229,8 @@ importers: specifier: 'catalog:' version: 15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) fumadocs-openapi: - specifier: 12.5.4 - version: 12.5.4(83fbde21deb18050b9b10d0b4220f1cf) + specifier: 12.6.1 + version: 12.6.1(83fbde21deb18050b9b10d0b4220f1cf) fumadocs-ui: specifier: 'catalog:' version: 16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) @@ -414,26 +414,26 @@ importers: specifier: 0.3.5 version: 0.3.5(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) '@scalar/json-magic': - specifier: 0.16.1 - version: 0.16.1 + specifier: 0.18.0 + version: 0.18.0 es-module-lexer: specifier: 1.7.0 version: 1.7.0 fumadocs-core: specifier: 'catalog:' - version: 16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7) + version: 16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7) fumadocs-openapi: - specifier: 12.5.4 - version: 12.5.4(72c83f477ec45a7a7588241f7ea64e9e) + specifier: 12.6.1 + version: 12.6.1(83fbde21deb18050b9b10d0b4220f1cf) fumadocs-ui: specifier: 'catalog:' - version: 16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) + version: 16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) lucide-react: - specifier: 1.46.0 - version: 1.46.0(react@19.2.7) + specifier: 1.73.0 + version: 1.73.0(@types/react@19.2.17)(react@19.2.7) shiki: - specifier: 4.5.0 - version: 4.5.0 + specifier: 4.6.0 + version: 4.6.0 devDependencies: '@coder/docs-transforms': specifier: workspace:* @@ -458,7 +458,7 @@ importers: version: 19.2.3(@types/react@19.2.17) fumadocs-mdx: specifier: 'catalog:' - version: 15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) + version: 15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7) jsdom: specifier: 25.0.1 version: 25.0.1 @@ -2884,6 +2884,10 @@ packages: resolution: {integrity: sha512-9eILWzUcAkHEuYMMvijpSIy69t+Vkq+NudLB/7lgARFTWqXfQpIxW1L3VH7ogKyRie5+E4CNZ3PSvlw6IIfLGw==} engines: {node: '>=22'} + '@scalar/helpers@0.17.0': + resolution: {integrity: sha512-/XzBJDB/nr/Nzkx/a8ow0WdWb5LIb6KsWrjv7TsQYolkCxOM6ZT+iEJ635QssQG33wEzAK0os5Xbiub6RUU+Ng==} + engines: {node: '>=22'} + '@scalar/helpers@0.18.1': resolution: {integrity: sha512-5/FsnE/4bCbr+h0OOgT1Zlnl4G7MKgPsZlzDN4KiBjpVCCZNHn7Px9gLOqtQSfsSqM/JFwUW+voZNVTODiL2BA==} engines: {node: '>=22'} @@ -2892,6 +2896,10 @@ packages: resolution: {integrity: sha512-yWQJUrkufUsShizF+rGKO4BoZ/ijMpnrgwRjtCA2cYqjxkQOYaQCd+WVF+b3ihmXE7amr768pLItFCx5UV/ObQ==} engines: {node: '>=22'} + '@scalar/json-magic@0.18.0': + resolution: {integrity: sha512-mz/H7H9gP2jZvViQS2cyOmqrBvLQwN5UdJ+5k77yBxV25D/6jh0BfGubQyxNwAqA62TP8JnEiIQ4gzbsMZvESw==} + engines: {node: '>=22.19.0'} + '@scalar/openapi-types@0.9.10': resolution: {integrity: sha512-rQVlvSLXvP3ljCY7BqKeJ07EjqtzJyaj1OTMVRVRBftmNmxupmmx1xNTnuLnaJIfGnrNEFLW7kyJofzH43wUPg==} engines: {node: '>=22'} @@ -2993,58 +3001,30 @@ packages: resolution: {integrity: sha512-qZIXHS84Pa9/KHnVFHjNh6Yk8v+U4Z7xfVPa+Bpa1bArZ8jNHL9NOEigZIb1rOx/KyCw0SDdrzQytcuiFSBmsg==} engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} - '@shikijs/core@4.5.0': - resolution: {integrity: sha512-6CIgwq+bt2JZ3OSjb/nBkkwEf/CfpHcbam+Mg5Pllco7HAGRQ2/EFhZrrJtbyNTgKwknfVS+llsXGygiDGwJWw==} - engines: {node: '>=20'} - '@shikijs/core@4.6.0': resolution: {integrity: sha512-bfd4OKgvoyXYiYmMRuleA656P4V7M/Du9lcTl38Ngm6KszMj7bq4J1IGZwSYR4c95Tv5UQALtYNWUwaI9UT3xw==} engines: {node: '>=20'} - '@shikijs/engine-javascript@4.5.0': - resolution: {integrity: sha512-Ed6UdEj84LyYkwnxM5CvSMWAD+id9ExTYri0/+x41U9zrgNifPSS9lZm0JqBP0VfYI8yr8tY5nbNq9+p9R0kFA==} - engines: {node: '>=20'} - '@shikijs/engine-javascript@4.6.0': resolution: {integrity: sha512-K0oqxFoL+kEMdz89mHLFO15Tsbv3kFZ6WR1cXZKMvLSc+oqaM00A6pyga1qSeXB22dP0tTiSApRcGBaKWsEccg==} engines: {node: '>=20'} - '@shikijs/engine-oniguruma@4.5.0': - resolution: {integrity: sha512-dKVmbJecVdB9recl8a/CU4jdpNXyjJQrIcesIkpS70s5HS02ohpnCSpMUbotPnEUzbAcLQ+S4hwZYbkBBiTcJw==} - engines: {node: '>=20'} - '@shikijs/engine-oniguruma@4.6.0': resolution: {integrity: sha512-aggd6Q7SuJOXNnsUbfG2XesxBJKBMAw/PDTUo9PyRjMaaJJ2dNrI+q0C+25ARXAK9yLHAlwxc9oRT2u68YKZ7w==} engines: {node: '>=20'} - '@shikijs/langs@4.5.0': - resolution: {integrity: sha512-wwBTqwduXSz0X4v9Qa2EWeFaYJEw1clCncWjoRNQRbVDu3SPRTRWucnouYapKj3b8Q+sk/41Vbc4B5c8nuYzLA==} - engines: {node: '>=20'} - '@shikijs/langs@4.6.0': resolution: {integrity: sha512-1yMEX3oCVV54LUq/ovfpRkDQoYDkcvjSWFFa/YLUDMiSoRzMi2uxLJYbv41ahT8Lu9lFMaa7hecd3Q39trqUyg==} engines: {node: '>=20'} - '@shikijs/primitive@4.5.0': - resolution: {integrity: sha512-UM7ShlA8oz0OWxLLO8BmO9Ip6fVqdkt8yF0EH7nOCqHfrx1eEAzF0ZUVK7L+I8NEgeu1PEWSRlxaiPPeCb4iDg==} - engines: {node: '>=20'} - '@shikijs/primitive@4.6.0': resolution: {integrity: sha512-c54+TQEo9ToqgfL/AU8FpjnV09+GA9Oa7M5ROkkXteZfp5XzpAJGXjjvZQFQioJOwm/w/6Z3lIzQstAkl8coag==} engines: {node: '>=20'} - '@shikijs/themes@4.5.0': - resolution: {integrity: sha512-zGb87H3UBbpuI4yoh5UguB1XbU+2BDU3kflM7UfZ+Cy2hWo9lBtqjSVK20gmLY6ukYl040hAypGXMgud9vul8Q==} - engines: {node: '>=20'} - '@shikijs/themes@4.6.0': resolution: {integrity: sha512-qHAVAs80RiGD+IRuH9G+JPDOEc9A/kHsng4EzCUCwB9bLzW6Z0y9WETh2YyCcADJBmfrIaJ1Jp7KBNP6FHkgtQ==} engines: {node: '>=20'} - '@shikijs/types@4.5.0': - resolution: {integrity: sha512-drtPrtD8N0DENyD2cyt6Ajy+IWsiCLgMxODwLTpvH1UsN6a9jf90tNTPjqwHvA+0Lzu9e0txk8DjfqH1p9UJRw==} - engines: {node: '>=20'} - '@shikijs/types@4.6.0': resolution: {integrity: sha512-+ENG1adsKt/X7cRYw1Nl7BEpBmPOjmQ7bR/eGmHuMlT8gtOFf3KEi5l31DJYyAWhW6Y6bjP1plU7FmaxWGENFw==} engines: {node: '>=20'} @@ -3730,10 +3710,6 @@ packages: resolution: {integrity: sha512-mxIojEAQcuEvT/lyXq+jf/3cO/KoA6z4CeNDGGevTybECPOMFCnQy3OPahluUkbqgPNGw5Bi78UC7Po6Lhy+NA==} engines: {node: '>= 14.16.0'} - chokidar@5.0.0: - resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==} - engines: {node: '>= 20.19.0'} - chokidar@6.0.0: resolution: {integrity: sha512-Ec2Z7wpcKBiMpR7DxteoqS/sq5G5d2A4fpxzPv6+fD7xNNdrTghn7L11YwV5EN1B3i72Erc3XVT5FkWIDx90+A==} engines: {node: '>= 22.22'} @@ -4222,13 +4198,13 @@ packages: vite: optional: true - fumadocs-openapi@12.5.4: - resolution: {integrity: sha512-HU+x8N/oeunn5nGWFJuXtHW6ZUdZpfZ/ekq1GW20/juD5p5ociRZbXQJlT7kCZs945WjdcadLL/IPVTWF1/kQA==} + fumadocs-openapi@12.6.1: + resolution: {integrity: sha512-ZaBinW7tr1oadHNqjOhho3gFbNCNC2OWwP4HHwRXxLU6irJjfOxRI7XlnsKqJ6UNrqhjsCcTJz8Ov2vT5IzlIQ==} peerDependencies: '@scalar/api-client-react': ^2.0.20 '@types/react': '*' - fumadocs-core: ^16.15.0 - fumadocs-ui: ^16.15.0 + fumadocs-core: ^16.17.11 + fumadocs-ui: ^16.17.8 json-schema-typed: '*' react: ^19.2.0 react-dom: ^19.2.0 @@ -4695,11 +4671,6 @@ packages: resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==} engines: {node: '>=10'} - lucide-react@1.46.0: - resolution: {integrity: sha512-Bv+FZXgZPrxc/NCl1e7JJVQFLdiCxYgxNVhqoV7X0p6I8ADJo8DxBnK1auH0fZz4AmqOJ3jgneL4f1i8LJQRAA==} - peerDependencies: - react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 - lucide-react@1.73.0: resolution: {integrity: sha512-fVOzGviL9mTfHenG1PbCfIceavyGlnpYNSYr+aGZHLRymAJ7DTP6KHuqt0uBkCKAoenr1UVkwSbDIYt2xIesEQ==} peerDependencies: @@ -5488,10 +5459,6 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} - shiki@4.5.0: - resolution: {integrity: sha512-OcRW72ngQvc+MSVWBRIovC/BTW589iUE/Vxav7VeM4RcY9MUjqB+IR6ILG1k9nuW6LiG/nct9uma4/MBtnZbmQ==} - engines: {node: '>=20'} - shiki@4.6.0: resolution: {integrity: sha512-imjLsVHgPuWhvpU3P+zOekvMYqnel7QmKsFC4Sn0fCuAvaaalBsxwKEsrU8Ko5BdFnZA6Go/8a0RzahS634UgA==} engines: {node: '>=20'} @@ -5783,6 +5750,10 @@ packages: resolution: {integrity: sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==} engines: {node: '>=20.18.1'} + undici@8.12.3: + resolution: {integrity: sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==} + engines: {node: '>=22.19.0'} + undici@8.12.4: resolution: {integrity: sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==} engines: {node: '>=22.19.0'} @@ -7536,6 +7507,8 @@ snapshots: '@scalar/helpers@0.16.4': {} + '@scalar/helpers@0.17.0': {} + '@scalar/helpers@0.18.1': {} '@scalar/json-magic@0.16.1': @@ -7545,6 +7518,13 @@ snapshots: undici: 7.30.1 yaml: 2.9.1 + '@scalar/json-magic@0.18.0': + dependencies: + '@scalar/helpers': 0.17.0 + pathe: 2.0.3 + undici: 8.12.3 + yaml: 2.9.1 + '@scalar/openapi-types@0.9.10': {} '@scalar/openapi-upgrader@0.4.11': @@ -7677,14 +7657,6 @@ snapshots: '@sentry/core': 11.9.0 '@sentry/server-utils': 11.9.0 - '@shikijs/core@4.5.0': - dependencies: - '@shikijs/primitive': 4.5.0 - '@shikijs/types': 4.5.0 - '@shikijs/vscode-textmate': 10.1.0 - '@types/hast': 3.0.5 - hast-util-to-html: 9.0.5 - '@shikijs/core@4.6.0': dependencies: '@shikijs/primitive': 4.6.0 @@ -7693,61 +7665,31 @@ snapshots: '@types/hast': 3.0.5 hast-util-to-html: 9.0.6 - '@shikijs/engine-javascript@4.5.0': - dependencies: - '@shikijs/types': 4.5.0 - '@shikijs/vscode-textmate': 10.1.0 - oniguruma-to-es: 4.3.6 - '@shikijs/engine-javascript@4.6.0': dependencies: '@shikijs/types': 4.6.0 '@shikijs/vscode-textmate': 10.1.0 oniguruma-to-es: 4.3.6 - '@shikijs/engine-oniguruma@4.5.0': - dependencies: - '@shikijs/types': 4.5.0 - '@shikijs/vscode-textmate': 10.1.0 - '@shikijs/engine-oniguruma@4.6.0': dependencies: '@shikijs/types': 4.6.0 '@shikijs/vscode-textmate': 10.1.0 - '@shikijs/langs@4.5.0': - dependencies: - '@shikijs/types': 4.5.0 - '@shikijs/langs@4.6.0': dependencies: '@shikijs/types': 4.6.0 - '@shikijs/primitive@4.5.0': - dependencies: - '@shikijs/types': 4.5.0 - '@shikijs/vscode-textmate': 10.1.0 - '@types/hast': 3.0.5 - '@shikijs/primitive@4.6.0': dependencies: '@shikijs/types': 4.6.0 '@shikijs/vscode-textmate': 10.1.0 '@types/hast': 3.0.5 - '@shikijs/themes@4.5.0': - dependencies: - '@shikijs/types': 4.5.0 - '@shikijs/themes@4.6.0': dependencies: '@shikijs/types': 4.6.0 - '@shikijs/types@4.5.0': - dependencies: - '@shikijs/vscode-textmate': 10.1.0 - '@types/hast': 3.0.5 - '@shikijs/types@4.6.0': dependencies: '@shikijs/vscode-textmate': 10.1.0 @@ -8586,10 +8528,6 @@ snapshots: dependencies: readdirp: 4.1.2 - chokidar@5.0.0: - dependencies: - readdirp: 5.1.1 - chokidar@6.0.0: dependencies: readdirp: 5.1.1 @@ -9007,43 +8945,6 @@ snapshots: fsevents@2.3.3: optional: true - fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7): - dependencies: - '@fumari/image-size': 0.1.1 - acorn: 8.19.0 - acorn-jsx: 5.3.2(acorn@8.19.0) - estree-util-value-to-estree: 3.5.0 - github-slugger: 2.0.0 - hast-util-from-dom: 5.0.1 - hast-util-to-estree: 3.1.3 - mdast-util-mdx: 3.0.0 - micromark: 4.0.3 - micromark-extension-gfm-table: 2.1.2 - npm-to-yarn: 3.2.0 - remark: 15.0.1 - remark-gfm: 4.0.1 - remark-rehype: 11.1.2 - scroll-into-view-if-needed: 3.1.0 - shiki: 4.6.0 - tinyglobby: 0.2.17 - unified: 11.0.5 - vfile: 6.0.3 - yaml: 2.9.1 - zbsearch: 4.0.4 - optionalDependencies: - '@mdx-js/mdx': 3.1.1 - '@types/estree-jsx': 1.0.5 - '@types/hast': 3.0.5 - '@types/mdast': 4.0.4 - '@types/react': 19.2.17 - lucide-react: 1.46.0(react@19.2.7) - next: 16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - react: 19.2.7 - react-dom: 19.2.7(react@19.2.7) - zod: 4.6.7 - transitivePeerDependencies: - - supports-color - fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6): dependencies: '@fumari/image-size': 0.1.1 @@ -9118,40 +9019,6 @@ snapshots: transitivePeerDependencies: - supports-color - fumadocs-mdx@15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7): - dependencies: - '@mdx-js/mdx': 3.1.1 - '@standard-schema/spec': 1.1.0 - acorn: 8.19.0 - acorn-jsx: 5.3.2(acorn@8.19.0) - chokidar: 6.0.0 - esbuild: 0.28.2 - estree-util-value-to-estree: 3.5.0 - fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7) - github-slugger: 2.0.0 - magic-string: 1.4.5 - mdast-util-from-markdown: 2.1.0 - mdast-util-mdx: 3.0.0 - micromark-extension-mdxjs-esm: 3.0.0 - picocolors: 1.1.1 - picomatch: 4.0.7 - tinyexec: 1.3.1 - tinyglobby: 0.2.17 - unified: 11.0.5 - unist-util-remove-position: 5.0.0 - vfile: 6.0.3 - yaml: 2.9.1 - yuku-analyzer: 0.19.0 - zod: 4.6.7 - optionalDependencies: - '@types/mdast': 4.0.4 - '@types/mdx': 2.0.14 - '@types/react': 19.2.17 - next: 16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - react: 19.2.7 - transitivePeerDependencies: - - supports-color - fumadocs-mdx@15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.6))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react@19.2.7): dependencies: '@mdx-js/mdx': 3.1.1 @@ -9220,59 +9087,27 @@ snapshots: transitivePeerDependencies: - supports-color - fumadocs-openapi@12.5.4(72c83f477ec45a7a7588241f7ea64e9e): + fumadocs-openapi@12.6.1(83fbde21deb18050b9b10d0b4220f1cf): dependencies: '@base-ui/react': 1.9.0(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) '@fuma-translate/react': 1.0.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) '@fumadocs/json-schema': 0.3.5(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) '@fumari/json-schema-ts': 1.0.2 '@fumari/stf': 1.1.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@scalar/json-magic': 0.16.1 + '@scalar/json-magic': 0.18.0 '@scalar/openapi-upgrader': 0.4.11 - chokidar: 5.0.0 - class-variance-authority: 0.7.1 - cn: 0.5.2 - fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7) - fumadocs-ui: 16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) - github-slugger: 2.0.0 - hast-util-to-jsx-runtime: 2.3.6 - lucide-react: 1.73.0(@types/react@19.2.17)(react@19.2.7) - react: 19.2.7 - react-dom: 19.2.7(react@19.2.7) - remark: 15.0.1 - remark-rehype: 11.1.2 - shiki: 4.5.0 - undici: 8.12.4 - yaml: 2.9.1 - optionalDependencies: - '@types/react': 19.2.17 - transitivePeerDependencies: - - '@date-fns/tz' - - date-fns - - supports-color - - fumadocs-openapi@12.5.4(83fbde21deb18050b9b10d0b4220f1cf): - dependencies: - '@base-ui/react': 1.9.0(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@fuma-translate/react': 1.0.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@fumadocs/json-schema': 0.3.5(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@fumari/json-schema-ts': 1.0.2 - '@fumari/stf': 1.1.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@scalar/json-magic': 0.16.1 - '@scalar/openapi-upgrader': 0.4.11 - chokidar: 5.0.0 + chokidar: 6.0.0 class-variance-authority: 0.7.1 cn: 0.5.2 fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7) fumadocs-ui: 16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3) github-slugger: 2.0.0 - hast-util-to-jsx-runtime: 2.3.6 lucide-react: 1.73.0(@types/react@19.2.17)(react@19.2.7) react: 19.2.7 react-dom: 19.2.7(react@19.2.7) remark: 15.0.1 remark-rehype: 11.1.2 - shiki: 4.5.0 + shiki: 4.6.0 undici: 8.12.4 yaml: 2.9.1 optionalDependencies: @@ -9282,40 +9117,6 @@ snapshots: - date-fns - supports-color - fumadocs-ui@16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3): - dependencies: - '@fuma-translate/react': 1.0.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@fumadocs/tailwind': 0.1.5(tailwindcss@4.3.3) - '@radix-ui/react-accordion': 1.3.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-collapsible': 1.2.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-dialog': 1.3.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-direction': 1.2.0(@types/react@19.2.17)(react@19.2.7) - '@radix-ui/react-navigation-menu': 1.4.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-popover': 1.3.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-presence': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-scroll-area': 1.4.0(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - '@radix-ui/react-slot': 1.5.0(@types/react@19.2.17)(react@19.2.7) - '@radix-ui/react-tabs': 1.2.1(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - class-variance-authority: 0.7.1 - cn: 0.5.2 - fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.46.0(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7) - lucide-react: 1.73.0(@types/react@19.2.17)(react@19.2.7) - motion: 14.14.0(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - next-themes: 0.4.6(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - react: 19.2.7 - react-dom: 19.2.7(react@19.2.7) - react-remove-scroll: 2.7.2(@types/react@19.2.17)(react@19.2.7) - scroll-into-view-if-needed: 3.1.0 - shiki: 4.6.0 - optionalDependencies: - '@types/mdx': 2.0.14 - '@types/react': 19.2.17 - next: 16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) - transitivePeerDependencies: - - '@types/react-dom' - - remix - - tailwindcss - fumadocs-ui@16.19.0(@types/mdx@2.0.14)(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.2.17)(lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.7))(next@16.4.5(@opentelemetry/api@1.10.0)(@types/node@24.19.2)(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(tailwindcss@4.3.3): dependencies: '@fuma-translate/react': 1.0.2(@types/react@19.2.17)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) @@ -9859,10 +9660,6 @@ snapshots: dependencies: yallist: 4.0.0 - lucide-react@1.46.0(react@19.2.7): - dependencies: - react: 19.2.7 - lucide-react@1.73.0(@types/react@19.2.17)(react@19.2.7): dependencies: react: 19.2.7 @@ -11109,17 +10906,6 @@ snapshots: shebang-regex@3.0.0: {} - shiki@4.5.0: - dependencies: - '@shikijs/core': 4.5.0 - '@shikijs/engine-javascript': 4.5.0 - '@shikijs/engine-oniguruma': 4.5.0 - '@shikijs/langs': 4.5.0 - '@shikijs/themes': 4.5.0 - '@shikijs/types': 4.5.0 - '@shikijs/vscode-textmate': 10.1.0 - '@types/hast': 3.0.5 - shiki@4.6.0: dependencies: '@shikijs/core': 4.6.0 @@ -11454,6 +11240,8 @@ snapshots: undici@7.30.1: {} + undici@8.12.3: {} + undici@8.12.4: {} unicorn-magic@0.4.1: {} From e75537ff71623a17b26e35dd9a8aa49e44f3026d Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nick.vigilante@coder.com> Date: Mon, 23 Nov 2026 23:36:46 +0000 Subject: [PATCH 61/69] fix(docs-theme): give API example figures the dark code window The dark token colours from the code window rule landed on fumadocs-openapi's light example card, which fails color-contrast in the light modes. Give the transparent example figures the code window background, and drop the last font-weight above 500. Assisted-by: AI --- packages/docs-theme/scripts/brand.test.mjs | 30 ++++++++++++++++++++++ packages/docs-theme/src/brand.css | 7 ++++- 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 packages/docs-theme/scripts/brand.test.mjs diff --git a/packages/docs-theme/scripts/brand.test.mjs b/packages/docs-theme/scripts/brand.test.mjs new file mode 100644 index 00000000..0a4372b4 --- /dev/null +++ b/packages/docs-theme/scripts/brand.test.mjs @@ -0,0 +1,30 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { test } from "node:test"; +import postcss from "postcss"; + +const brand = postcss.parse( + await readFile(new URL("../src/brand.css", import.meta.url), "utf8"), +); + +const normalize = (selector) => selector.replace(/\s+/g, " "); + +test("an API page's example figures are dark code windows like every other code block", () => { + const backgrounds = []; + brand.walkRules((rule) => { + const selectors = rule.selectors.map(normalize); + if (!selectors.includes(".coder-api-page figure.shiki.bg-transparent:not(.not-fumadocs-codeblock *)")) { + return; + } + rule.walkDecls("background-color", (decl) => backgrounds.push(decl.value)); + }); + assert.deepEqual(backgrounds, ["var(--docs-code-bg)"]); +}); + +test("the theme asks for no weight above Medium", () => { + const heavy = []; + brand.walkDecls("font-weight", (decl) => { + if (Number(decl.value) > 500) heavy.push(`${decl.parent.selector}: ${decl.value}`); + }); + assert.deepEqual(heavy, []); +}); diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css index 4f194a97..4fc75c76 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -889,6 +889,11 @@ figure.shiki:not(.not-fumadocs-codeblock *) pre { opacity: 1; } +/* fumadocs-openapi draws its example figure transparent on a light card, so the dark token colours need the dark window behind them. */ +.coder-api-page figure.shiki.bg-transparent:not(.not-fumadocs-codeblock *) { + background-color: var(--docs-code-bg); +} + /* fumadocs-openapi's method badges (on API pages, the landing cards, the sidebar and the page footer) and links are -600/-400 shades that fall short of 4.5:1 (7:1 for More contrast). */ :root:not(.dark) :is(.coder-api-page, .coder-api-cards, #nd-sidebar, #nd-sidebar-mobile, #nd-page > footer) { @@ -1008,7 +1013,7 @@ figure.shiki:not(.not-fumadocs-codeblock *) pre { align-items: center; min-height: 2.5rem; cursor: pointer; - font-weight: 600; + font-weight: 500; list-style: none; } From 410fc595c3a0e2bb56e28e0edd799235e8b7cf16 Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nick.vigilante@coder.com> Date: Mon, 23 Nov 2026 23:37:50 +0000 Subject: [PATCH 62/69] fix(docs-config): keep node:path out of the package root openApiDataDir and openApiDataFile imported node:path, and the root is read by docs-ui client code, so a webpack build failed on the node: scheme. Plain string joins give the same paths, and a test now walks the root's imports for any node: module. Assisted-by: AI --- packages/docs-config/src/client-entry.test.ts | 6 ++++++ packages/docs-config/src/openapi-data.ts | 7 ++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/packages/docs-config/src/client-entry.test.ts b/packages/docs-config/src/client-entry.test.ts index 69a5c70b..07157d31 100644 --- a/packages/docs-config/src/client-entry.test.ts +++ b/packages/docs-config/src/client-entry.test.ts @@ -36,3 +36,9 @@ test("the client entry imports no package, so it never bundles zod", () => { test("the import-graph walk sees zod behind the package root", () => { assert.ok(importGraph("index.ts").packages.includes("zod")); }); + +test("the package root imports no node: module, so a webpack build of client code can read it", () => { + const { files, packages } = importGraph("index.ts"); + const builtins = packages.filter((name) => name.startsWith("node:")); + assert.deepEqual(builtins, [], `index.ts reaches ${builtins.join(", ")} via ${files.join(", ")}`); +}); diff --git a/packages/docs-config/src/openapi-data.ts b/packages/docs-config/src/openapi-data.ts index 53140a83..e40cbe48 100644 --- a/packages/docs-config/src/openapi-data.ts +++ b/packages/docs-config/src/openapi-data.ts @@ -1,13 +1,10 @@ -import path from "node:path"; - /** Where a sync leaves each version's REST API reference data, which the page renderer reads. */ -export const openApiDataDir = (appDir: string): string => - path.join(appDir, ".generated", "openapi"); +export const openApiDataDir = (appDir: string): string => `${appDir}/.generated/openapi`; const DATA_ID = /^[\w-][\w.-]*$/; /** The data file of one version, named by `id`: the version id, or a fixed name for a single-version export. */ export function openApiDataFile(appDir: string, id: string): string { if (!DATA_ID.test(id)) throw new Error(`not an API reference data id: ${JSON.stringify(id)}`); - return path.join(openApiDataDir(appDir), `${id}.json`); + return `${openApiDataDir(appDir)}/${id}.json`; } From ae799b00e88caa596ab39e87a6f6430479524613 Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nick.vigilante@coder.com> Date: Tue, 24 Nov 2026 00:18:21 +0000 Subject: [PATCH 63/69] fix(docs-build): fence schema names as code spans in the schemas table A name goes through codeSpan() and has its pipes escaped, so it can't end its cell. swagger2openapi already rewrites such names, so this guards the table rather than fixing a reachable break. Assisted-by: AI --- packages/docs-build/src/openapi-reference.test.ts | 9 +++++++++ packages/docs-build/src/openapi-reference.ts | 6 ++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index ba484614..aa6a6570 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -122,6 +122,15 @@ test("summaries are escaped where the tag and schemas pages put them in Markdown assert.match(tagPage ?? "", /- \[List \\\[all\\\] a\\\|b \\\\ \\\*workspaces\\\*\]\(/); }); +test("a schema name with a pipe or a backtick stays inside its table cell", async () => { + const tricky = structuredClone(swagger); + tricky.definitions["a|b`c"] = { type: "object" }; + const { source: out } = await applyOpenApiReference(source, tricky); + const page = out.files.find((file) => file.path === "reference/api/schemas.md")?.content ?? ""; + const row = page.split("\n").find((line) => line.includes("a_b_c")); + assert.equal(row, "| `a_b_c` | Not used by a documented endpoint |"); +}); + test("the undeclared CoderProvisionerKey scheme is defined as the header coderd reads", async () => { const doc = structuredClone(swagger); doc.paths["/api/v2/users/{user}"].get.security = [{ CoderProvisionerKey: [] }]; diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 4eab04d2..8d78b13a 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -60,6 +60,8 @@ function codeSpan(text: string): string { return `${fence}${pad}${text}${pad}${fence}`; } +const cell = (markdown: string): string => markdown.replace(/\|/g, "\\|"); + const frontmatter = (title: string, method?: string): string => `---\ntitle: ${JSON.stringify(title)}\n${method ? `_openapi:\n method: ${method}\n` : ""}---\n\n`; @@ -300,10 +302,10 @@ export async function applyOpenApiReference( if (best) { schemaTargets.set(anchor, best); schemaRows.push( - `| \`${name}\` | [${linkText(best.summary)}](./${best.file.slice(dir.length + 1)}) |`, + `| ${cell(codeSpan(name))} | [${linkText(best.summary)}](./${best.file.slice(dir.length + 1)}) |`, ); } else { - schemaRows.push(`| \`${name}\` | Not used by a documented endpoint |`); + schemaRows.push(`| ${cell(codeSpan(name))} | Not used by a documented endpoint |`); } } const schemasFile = `${dir}/schemas.md`; From 328316fa8bbeca7caa594e8d4f61551fd9ff221a Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nick.vigilante@coder.com> Date: Tue, 24 Nov 2026 00:18:21 +0000 Subject: [PATCH 64/69] fix(docs-next): leave = field names out of all four API samples The shell sample cannot write a multipart field whose name holds an =, while the JavaScript, Python and Go samples kept it, so the samples sent different fields. The form body now drops such names once, for every language. Assisted-by: AI --- packages/docs-next/src/openapi/code-samples.test.ts | 13 +++++++++++++ packages/docs-next/src/openapi/code-samples.ts | 6 +++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/packages/docs-next/src/openapi/code-samples.test.ts b/packages/docs-next/src/openapi/code-samples.test.ts index bc895967..3b0acab6 100644 --- a/packages/docs-next/src/openapi/code-samples.test.ts +++ b/packages/docs-next/src/openapi/code-samples.test.ts @@ -310,6 +310,19 @@ test("curl: a field name curl would split at its = is left out, so it can't name ); }); +test("a field name with an = is left out of all four samples, so they send the same fields", () => { + const hostile = structuredClone(form); + hostile.paths["/api/v2/form"].post.requestBody.content["multipart/form-data"].schema.required = [ + "name", + "f=@/etc/passwd;x", + ]; + for (const id of ["curl", "javascript", "python", "go"]) { + const source = sample(hostile, "/api/v2/form", "post", id); + assert.ok(source.includes("{name}"), `${id} sends name`); + assert.ok(!source.includes("passwd"), `${id} leaves the = field out`); + } +}); + test("JavaScript: fetch with the URL and token from the environment", () => { assert.equal( sample(document, "/api/v2/users", "post", "javascript"), diff --git a/packages/docs-next/src/openapi/code-samples.ts b/packages/docs-next/src/openapi/code-samples.ts index 9c876a14..ca771acf 100644 --- a/packages/docs-next/src/openapi/code-samples.ts +++ b/packages/docs-next/src/openapi/code-samples.ts @@ -120,7 +120,8 @@ function bodyOf(operation: JsonObject, method: string, contentType?: string): Bo if (type === "multipart/form-data") { const schema = resolve(media.schema); const required = Array.isArray(schema?.required) ? (schema.required as string[]) : []; - return { kind: "form", fields: required }; + // curl splits a field at its first =, so such a name can't be written there; every sample leaves it out. + return { kind: "form", fields: required.filter((field) => !field.includes("=")) }; } return { kind: "binary", contentType: contentType ?? type }; } @@ -179,8 +180,7 @@ export function curlSample(request: ExampleRequest): string { ]; if (body?.kind === "json") lines.push(`-d ${shellSingleQuoted(jsonText(body.value))}`); if (body?.kind === "form") { - // curl splits a field at its first =, so such a name can't be written. - for (const name of body.fields.filter((field) => !field.includes("="))) + for (const name of body.fields) lines.push(`--form-string ${shellDoubleQuoted(`${name}=${placeholder(name)}`)}`); } if (body?.kind === "binary") From 8d10c2d1e4f2cc7fba53334a639f197b380af6b6 Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nick.vigilante@coder.com> Date: Tue, 24 Nov 2026 00:18:21 +0000 Subject: [PATCH 65/69] fix(docs-next): decode JSON Pointer escapes when pruning an API document A reference to a component whose name holds / or ~ is written with ~1 or ~0, so the pruned document dropped it. Decode each segment before the lookup. Assisted-by: AI --- packages/docs-next/src/openapi/index.test.tsx | 23 +++++++++++++++++++ packages/docs-next/src/openapi/index.tsx | 8 ++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/docs-next/src/openapi/index.test.tsx b/packages/docs-next/src/openapi/index.test.tsx index 4a15affa..17dadbb1 100644 --- a/packages/docs-next/src/openapi/index.test.tsx +++ b/packages/docs-next/src/openapi/index.test.tsx @@ -116,6 +116,29 @@ test("a pruned page keeps its operation, its path's parameters and every schema assert.deepEqual(pruned.servers, api.servers); }); +test("a component whose name holds / or ~ is kept when its reference escapes them", () => { + const document = { + openapi: "3.0.3", + info: { title: "T", version: "1" }, + paths: { + "/x": { + get: { + responses: { + "200": { + description: "OK", + content: { "application/json": { schema: { $ref: "#/components/schemas/a~1b~0c" } } }, + }, + }, + }, + }, + }, + components: { schemas: { "a/b~c": { type: "string" } } }, + }; + const pruned = pruneDocument(document, "/x", "get"); + const components = pruned.components as Record<string, Record<string, unknown>>; + assert.deepEqual(Object.keys(components.schemas ?? {}), ["a/b~c"]); +}); + test("pruning a page whose operation isn't in the document fails", () => { assert.throws(() => pruneDocument(api, "/api/v2/a/{id}", "post"), /no post \/api\/v2\/a\/\{id\}/); }); diff --git a/packages/docs-next/src/openapi/index.tsx b/packages/docs-next/src/openapi/index.tsx index 01eed75c..636d5e53 100644 --- a/packages/docs-next/src/openapi/index.tsx +++ b/packages/docs-next/src/openapi/index.tsx @@ -16,6 +16,9 @@ import { ApiLanding } from "./landing.js"; import { SetupHrefProvider } from "./samples-note.js"; import { SchemaTables } from "./schemas.js"; +const unescapePointer = (segment: string): string => + segment.replace(/~1/g, "/").replace(/~0/g, "~"); + /** * The document cut down to one operation and the components it reaches, so a * page's props carry only what that page renders, not the whole API. @@ -36,7 +39,10 @@ export function pruneDocument(document: JsonObject, path: string, method: HttpMe for (const ref of frontier) { if (seen.has(ref) || !ref.startsWith("#/components/")) continue; seen.add(ref); - const [kind, name] = ref.slice("#/components/".length).split("/") as [string, string]; + const [kind, name] = ref.slice("#/components/".length).split("/").map(unescapePointer) as [ + string, + string, + ]; const value = components[kind]?.[name]; if (value === undefined) continue; (kept[kind] ??= {})[name] = value; From 5eceeac88bafb32a8956224d874cf7865047da6f Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nick.vigilante@coder.com> Date: Tue, 24 Nov 2026 00:20:13 +0000 Subject: [PATCH 66/69] style(docs-theme): format the brand stylesheet test Assisted-by: AI --- packages/docs-theme/scripts/brand.test.mjs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/docs-theme/scripts/brand.test.mjs b/packages/docs-theme/scripts/brand.test.mjs index 0a4372b4..6b0603c5 100644 --- a/packages/docs-theme/scripts/brand.test.mjs +++ b/packages/docs-theme/scripts/brand.test.mjs @@ -3,9 +3,7 @@ import { readFile } from "node:fs/promises"; import { test } from "node:test"; import postcss from "postcss"; -const brand = postcss.parse( - await readFile(new URL("../src/brand.css", import.meta.url), "utf8"), -); +const brand = postcss.parse(await readFile(new URL("../src/brand.css", import.meta.url), "utf8")); const normalize = (selector) => selector.replace(/\s+/g, " "); @@ -13,7 +11,11 @@ test("an API page's example figures are dark code windows like every other code const backgrounds = []; brand.walkRules((rule) => { const selectors = rule.selectors.map(normalize); - if (!selectors.includes(".coder-api-page figure.shiki.bg-transparent:not(.not-fumadocs-codeblock *)")) { + if ( + !selectors.includes( + ".coder-api-page figure.shiki.bg-transparent:not(.not-fumadocs-codeblock *)", + ) + ) { return; } rule.walkDecls("background-color", (decl) => backgrounds.push(decl.value)); From 1e469ac0e4b6bb186f6b260a0e4afa11d038de86 Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nick.vigilante@coder.com> Date: Tue, 24 Nov 2026 18:51:37 +0000 Subject: [PATCH 67/69] fix(docs-theme): use weight 500 for the heading # link The theme uses 500 only, and the weight test fails on the 600 that main's heading link brought in. Assisted-by: AI --- packages/docs-theme/src/brand.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/docs-theme/src/brand.css b/packages/docs-theme/src/brand.css index 90d4533e..cfa3a494 100644 --- a/packages/docs-theme/src/brand.css +++ b/packages/docs-theme/src/brand.css @@ -913,7 +913,7 @@ figure.shiki:not(.not-fumadocs-codeblock *) pre { min-width: 1.5rem; min-height: 1.5rem; border-radius: 0.375rem; - font-weight: 600; + font-weight: 500; color: var(--color-fd-muted-foreground); text-decoration: none; opacity: 0; From 00a4c215df0a5f8800dd7a3cb093406019c17f19 Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nick.vigilante@coder.com> Date: Tue, 24 Nov 2026 20:05:16 +0000 Subject: [PATCH 68/69] fix(docs-transforms): refuse over-nested Markdown before headingIds parses it The OpenAPI landing preprocessing runs headingIds before sync's nesting check, so a deeply nested blockquote or list in the API landing page reached the Markdown parser first. headingIds now scans the body and throws past the same MAX_MARKDOWN_NESTING_DEPTH sync enforces, which is exported from one place and imported by sync. Assisted-by: AI --- packages/docs-build/src/openapi-output.test.ts | 16 ++++++++++++++++ packages/docs-build/src/sync.ts | 9 +-------- packages/docs-transforms/src/index.ts | 2 ++ packages/docs-transforms/src/transform.test.ts | 7 +++++++ packages/docs-transforms/src/transform.ts | 17 ++++++++++++++++- 5 files changed, 42 insertions(+), 9 deletions(-) diff --git a/packages/docs-build/src/openapi-output.test.ts b/packages/docs-build/src/openapi-output.test.ts index ebdc1360..e4548bc8 100644 --- a/packages/docs-build/src/openapi-output.test.ts +++ b/packages/docs-build/src/openapi-output.test.ts @@ -92,6 +92,22 @@ test("the version's reference data is written where the page renderer reads it", await assert.rejects(stat(openApiDataDir(appDir)), { code: "ENOENT" }); }); +test("an API landing page nested past the Markdown cap is rejected before it is parsed", async () => { + const appDir = await mkdtemp(path.join(tmpdir(), "openapi-output-")); + const deep: DocSource = { + ...source, + files: source.files.map((file) => + file.path === "reference/api/index.md" + ? { ...file, content: `# REST API\n\n${">".repeat(101)} deep\n` } + : file, + ), + }; + await assert.rejects( + withOpenApiReference(appDir, { id: "2.38" }, deep, swagger, { logger: quiet }), + /nested 101 levels/, + ); +}); + test("a version without a Swagger document keeps its Markdown reference and writes nothing", async () => { const appDir = await mkdtemp(path.join(tmpdir(), "openapi-output-")); const next = await withOpenApiReference(appDir, { id: "2.10" }, source, undefined, { diff --git a/packages/docs-build/src/sync.ts b/packages/docs-build/src/sync.ts index 6da6649c..bc3eb4b2 100644 --- a/packages/docs-build/src/sync.ts +++ b/packages/docs-build/src/sync.ts @@ -34,6 +34,7 @@ import { rewriteLegacyReleaseCalendar, scanHtmlContent, scanMarkdownNesting, + MAX_MARKDOWN_NESTING_DEPTH, selfCloseVoidElements, stripBadgeLines, stripDoctoc, @@ -52,14 +53,6 @@ import { reservedAssetReason, reservedRouteReason } from "./reserved-routes.js"; */ const MAX_HTML_NESTING_DEPTH = 100; -/** - * Maximum blockquote and list nesting depth allowed in one page. The real - * corpus nests a few levels; the Markdown parser takes minutes on a thousand - * and the compile overflows the stack, so deeper nesting fails here, before - * anything parses the page. - */ -const MAX_MARKDOWN_NESTING_DEPTH = 100; - /** * Maximum length of a `premium_callout` frontmatter value. It renders as a * short note above a gated section, not a place for a whole page of prose. diff --git a/packages/docs-transforms/src/index.ts b/packages/docs-transforms/src/index.ts index c91865ee..9f5072af 100644 --- a/packages/docs-transforms/src/index.ts +++ b/packages/docs-transforms/src/index.ts @@ -22,6 +22,7 @@ export { selfCloseVoidElements, scanHtmlContent, scanMarkdownNesting, + MAX_MARKDOWN_NESTING_DEPTH, findIncludeDirectives, parseFrontmatter, FrontmatterError, @@ -61,6 +62,7 @@ export { trimSlashes, trimTrailingSlashes } from "./slashes.js"; export { MAX_SEO_TITLE_CHARS, isSeoTitle } from "./seo-title.js"; + export { isHtml } from "./mdx-plugins/mdast.js"; export type { MdastNode } from "./mdx-plugins/mdast.js"; diff --git a/packages/docs-transforms/src/transform.test.ts b/packages/docs-transforms/src/transform.test.ts index 08b64fd8..f5a90322 100644 --- a/packages/docs-transforms/src/transform.test.ts +++ b/packages/docs-transforms/src/transform.test.ts @@ -8,6 +8,7 @@ import { extractTitle, findIncludeDirectives, headingIds, + MAX_MARKDOWN_NESTING_DEPTH, isIndexFile, lastSeg, normalizeAngleBrackets, @@ -1457,6 +1458,12 @@ test("scanMarkdownNesting stays linear on a long line of container markers", () } }); +test("headingIds refuses a body nested past the cap instead of parsing it", () => { + const nested = (depth: number) => `${">".repeat(depth)} deep\n\n## Heading\n`; + assert.equal(headingIds(nested(MAX_MARKDOWN_NESTING_DEPTH)).length, 1); + assert.throws(() => headingIds(nested(MAX_MARKDOWN_NESTING_DEPTH + 1)), /nested 101 levels/); +}); + test("headingIds gives each heading the id the synced page renders with", () => { assert.deepEqual( headingIds( diff --git a/packages/docs-transforms/src/transform.ts b/packages/docs-transforms/src/transform.ts index 1cb1d54d..0182f9b7 100644 --- a/packages/docs-transforms/src/transform.ts +++ b/packages/docs-transforms/src/transform.ts @@ -1048,6 +1048,14 @@ function containerDepth(line: string): number { return lists > 0 ? depth + Math.floor(indent / 2) : depth; } +/** + * Maximum blockquote and list nesting depth allowed in one page. The real + * corpus nests a few levels; the Markdown parser takes minutes on a thousand + * and the compile overflows the stack, so deeper nesting fails before + * anything parses the page. + */ +export const MAX_MARKDOWN_NESTING_DEPTH = 100; + // Measure blockquote and list nesting line by line, outside fenced code and // raw HTML blocks, without parsing. A deeply nested container recurses in // every later stage (the Markdown parser takes minutes on it, then the @@ -1215,7 +1223,14 @@ export function extractTitle( * and `safeHeadingId`. `line` is the heading's 0-based line in `body`. */ export function headingIds(body: string): { line: number; depth: number; id: string }[] { - const tree = fromMarkdown(stripHtmlComments(normalizeStepHeadings(body)).content) as MdastNode; + const content = stripHtmlComments(normalizeStepHeadings(body)).content; + const nesting = scanMarkdownNesting(content); + if (nesting.maxDepth > MAX_MARKDOWN_NESTING_DEPTH) { + throw new Error( + `blockquotes or lists nested ${nesting.maxDepth} levels at line ${nesting.line}, past the ${MAX_MARKDOWN_NESTING_DEPTH} allowed`, + ); + } + const tree = fromMarkdown(content) as MdastNode; remarkClassicHeadingIds()(tree); const headings: { line: number; depth: number; id: string }[] = []; visitHeadings(tree, (heading) => { From 7912137b997760fd7cbd9c6d8341ff922e6f470c Mon Sep 17 00:00:00 2001 From: Nick Vigilante <nick.vigilante@coder.com> Date: Tue, 24 Nov 2026 20:05:16 +0000 Subject: [PATCH 69/69] fix(docs-build): protect generated API section ids from Next.js bootstrap names A Swagger tag named __next_f became a landing section id that never passed through safeHeadingId, so the DOM id shadowed the Flight global. Section ids are now allocated from the protected slug, so deduplication sees final values and the rendered headings and TOC links use the same ids. safeHeadingId is exported from docs-transforms for reuse. Assisted-by: AI --- .../docs-build/src/openapi-reference.test.ts | 12 ++++++++++ packages/docs-build/src/openapi-reference.ts | 5 ++-- .../docs-next/src/openapi/landing.test.tsx | 24 +++++++++++++++++++ packages/docs-transforms/src/index.ts | 1 + 4 files changed, 40 insertions(+), 2 deletions(-) diff --git a/packages/docs-build/src/openapi-reference.test.ts b/packages/docs-build/src/openapi-reference.test.ts index aa6a6570..4132bbca 100644 --- a/packages/docs-build/src/openapi-reference.test.ts +++ b/packages/docs-build/src/openapi-reference.test.ts @@ -307,6 +307,18 @@ test("section ids never repeat a heading the landing page already has", async () assert.equal(reference.landing.sections[1]?.id, "workspaces"); }); +test("a tag named for a Next.js bootstrap global gets a protected section id, and two tags cannot collide on it", async () => { + const { reference } = await applyOpenApiReference( + source, + retagged([{ tag: "__next_f" }, { tag: "user-content-__next_f" }, { tag: "__NEXT_DATA__" }]), + ); + const idOf = (title: string) => + reference.landing.sections.find((section) => section.title === title)?.id; + assert.equal(idOf("__next_f"), "user-content-__next_f"); + assert.equal(idOf("user-content-__next_f"), "user-content-__next_f-1"); + assert.equal(idOf("__NEXT_DATA__"), "user-content-__next_data__"); +}); + test("the appended setup section follows the page's text, not its trailing blank lines", async () => { const { source: out } = await applyOpenApiReference( withLanding(`# REST API\n\nIntro.\n\n\n \n`), diff --git a/packages/docs-build/src/openapi-reference.ts b/packages/docs-build/src/openapi-reference.ts index 8d78b13a..067a1161 100644 --- a/packages/docs-build/src/openapi-reference.ts +++ b/packages/docs-build/src/openapi-reference.ts @@ -21,8 +21,9 @@ import { headingIds, mapMdPath, parseFrontmatter, + safeHeadingId, } from "@coder/docs-transforms"; -import GithubSlugger from "github-slugger"; +import GithubSlugger, { slug as slugify } from "github-slugger"; import { validate } from "oas-validator"; import { convertObj } from "swagger2openapi"; @@ -383,7 +384,7 @@ export async function applyOpenApiReference( if (tag === undefined || !group) continue; sections.push({ title: tag, - id: landing.slugger.slug(tag), + id: landing.slugger.slug(safeHeadingId(slugify(tag))), operations: group.ops.map((op) => { const description = firstSentence(op.description); return { diff --git a/packages/docs-next/src/openapi/landing.test.tsx b/packages/docs-next/src/openapi/landing.test.tsx index c84fb5fd..0456f16d 100644 --- a/packages/docs-next/src/openapi/landing.test.tsx +++ b/packages/docs-next/src/openapi/landing.test.tsx @@ -107,3 +107,27 @@ test("the landing route gets the cards after its body and their headings in its const after = renderToFragment(result?.after); assert.equal(after.querySelectorAll(CARDS).length, 3); }); + +test("a protected section id is the heading id and the TOC link, unchanged", async () => { + const reserved: OpenApiLanding = { + ...landing, + sections: [{ title: "__next_f", id: "user-content-__next_f", operations: [] }], + }; + const renderBody = createOpenApiRenderBody(async () => ({ + document: {}, + operations: {}, + anchors: {}, + schemas: { route: "reference/api/schemas", rows: [] }, + landing: reserved, + })); + const result = await renderBody({ versionId: undefined, slugs: ["reference", "api"], hrefFor }); + assert.deepEqual( + result?.toc?.map((entry) => entry.url), + ["#user-content-__next_f"], + ); + const after = renderToFragment(result?.after); + assert.deepEqual( + [...after.querySelectorAll("h2")].map((h2) => h2.id), + ["user-content-__next_f"], + ); +}); diff --git a/packages/docs-transforms/src/index.ts b/packages/docs-transforms/src/index.ts index 9f5072af..77b8642a 100644 --- a/packages/docs-transforms/src/index.ts +++ b/packages/docs-transforms/src/index.ts @@ -62,6 +62,7 @@ export { trimSlashes, trimTrailingSlashes } from "./slashes.js"; export { MAX_SEO_TITLE_CHARS, isSeoTitle } from "./seo-title.js"; +export { safeHeadingId } from "./mdx-plugins/remark-safe-heading-ids.js"; export { isHtml } from "./mdx-plugins/mdast.js"; export type { MdastNode } from "./mdx-plugins/mdast.js";