import { type ApiDocument, type ApiOperation, type ApiSchema, type ApiSecurityScheme, findType, type ParameterLocation, requiredSchemes, } from "@docspack/lapis"; /** * Turning an operation plus some values into an actual HTTP request. * * Three things need this and they must agree: the code samples on a reference page, the console * that sends the request from the browser, and the example line in the text an agent is answered * with. A sample that differs from what the console sends is a sample that is wrong for whoever * trusted it, and the only way to keep three renderings honest is to give them one builder. * * The builder takes a `RequestTarget` rather than the whole document, which is what lets the * browser console use it: the console is handed one serialized target — a few hundred bytes — * instead of a document that may be megabytes, and still calls the same function the build-time * samples were generated with. */ /** Everything about an operation that affects the request, and nothing else. */ export interface RequestTarget { readonly method: string; /** Template path, braces included. */ readonly path: string; readonly servers: readonly string[]; readonly parameters: readonly { readonly name: string; readonly location: ParameterLocation; readonly required: boolean; }[]; /** Media type of the request body, when the operation takes one. */ readonly mediaType?: string; /** The scheme a credential is sent under. Absent means the operation needs none. */ readonly scheme?: ApiSecurityScheme; } export interface RequestValues { readonly path?: Readonly>; readonly query?: Readonly>; readonly header?: Readonly>; readonly body?: string; /** Bearer token, API key, or `user:password` for basic — whatever the scheme needs. */ readonly credential?: string; /** Base URL. Defaults to the target's first server. */ readonly server?: string; } export interface BuiltRequest { readonly method: string; readonly url: string; /** Header name and value pairs, in a stable order so a rendering does not churn. */ readonly headers: readonly (readonly [string, string])[]; readonly body?: string; /** * Path parameters with no value supplied. The request is still built — with the template * segment left in place — because a half-filled URL is what a reader needs to see while they * are still filling the form in. */ readonly missing: readonly string[]; } /** The request-shaped view of an operation. The only thing the console needs to be given. */ export function requestTarget(document: ApiDocument, operation: ApiOperation): RequestTarget { const scheme = requiredSchemes(document, operation)[0]; return { method: operation.method, path: operation.path, servers: operation.servers.map((server) => server.url), parameters: operation.parameters.map((parameter) => ({ name: parameter.name, location: parameter.location, required: parameter.required, })), ...(operation.body === undefined ? {} : { mediaType: operation.body.mediaType }), ...(scheme === undefined ? {} : { scheme }), }; } export function buildRequest(target: RequestTarget, values: RequestValues = {}): BuiltRequest { const base = (values.server ?? target.servers[0] ?? "").replace(/\/$/, ""); const missing: string[] = []; const path = target.path.replace(/\{([^}]+)\}/g, (whole, name: string) => { const value = values.path?.[name]; if (value === undefined || value.length === 0) { missing.push(name); return whole; } return encodeURIComponent(value); }); const query = new URLSearchParams(); for (const parameter of target.parameters) { if (parameter.location !== "query") continue; const value = values.query?.[parameter.name]; if (value === undefined || value.length === 0) continue; query.set(parameter.name, value); } const headers = new Map(); for (const parameter of target.parameters) { if (parameter.location !== "header") continue; const value = values.header?.[parameter.name]; if (value !== undefined && value.length > 0) headers.set(parameter.name, value); } if (target.mediaType !== undefined && values.body !== undefined && values.body.length > 0) { headers.set("Content-Type", target.mediaType); } if (values.credential !== undefined && values.credential.length > 0) { applyCredential(target.scheme, values.credential, headers, query); } const search = query.toString(); return { method: target.method, url: `${base}${path}${search.length === 0 ? "" : `?${search}`}`, headers: [...headers.entries()], ...(values.body === undefined || values.body.length === 0 ? {} : { body: values.body }), missing, }; } /** * Where a credential goes. * * One scheme, the first the operation declares. Sending every scheme's credential at once is how * a request gets rejected for being over-authenticated, and a reader who has one token has one * token. */ function applyCredential( scheme: ApiSecurityScheme | undefined, credential: string, headers: Map, query: URLSearchParams, ): void { if (scheme === undefined) return; switch (scheme.kind) { case "bearer": case "oauth2": case "openIdConnect": headers.set("Authorization", `Bearer ${credential}`); return; case "basic": // Already-encoded input is passed through: a reader who pasted the base64 from another tool // would otherwise have it encoded twice, and the failure looks like a wrong password. headers.set( "Authorization", `Basic ${credential.includes(":") ? base64(credential) : credential}`, ); return; case "apiKey": if (scheme.in === "query") query.set(scheme.parameterName ?? scheme.name, credential); else headers.set(scheme.parameterName ?? scheme.name, credential); return; default: return; } } function base64(value: string): string { // Works in both runtimes this package is used from: Node for the CLI, the browser for the // console. if (typeof btoa === "function") return btoa(value); return Buffer.from(value, "utf8").toString("base64"); } /** What a credential is called, so a form label and a sample placeholder name the same thing. */ export function credentialName( target: RequestTarget, ): { readonly label: string; readonly env: string } | undefined { const scheme = target.scheme; if (scheme === undefined) return undefined; switch (scheme.kind) { case "bearer": case "oauth2": case "openIdConnect": return { label: "Bearer token", env: "API_TOKEN" }; case "basic": return { label: "user:password", env: "API_CREDENTIALS" }; case "apiKey": return { label: scheme.parameterName ?? scheme.name, env: "API_KEY" }; default: return undefined; } } /** * Plausible values for every input, taken from the document wherever it says anything. * * A sample with real-looking values is the difference between documentation a reader copies and * documentation a reader reads. Where the document supplies an example, a default or an enum, that * is used; otherwise the value is a visibly-fake placeholder rather than an invented constant, * because a sample that looks filled in and is not is the one a reader pastes. */ export function exampleValues(document: ApiDocument, operation: ApiOperation): RequestValues { const path: Record = {}; const query: Record = {}; const header: Record = {}; for (const parameter of operation.parameters) { const value = placeholder(document, parameter.schema, parameter.name); if (parameter.location === "path") path[parameter.name] = value; // Only required query and header parameters are filled in. An optional one in every sample // teaches the reader that it is needed. else if (parameter.required && parameter.location === "query") query[parameter.name] = value; else if (parameter.required && parameter.location === "header") header[parameter.name] = value; } const body = exampleBody(document, operation); return { path, query, header, ...(body === undefined ? {} : { body }) }; } /** The body a sample sends: the document's own example when it has one, else one from the schema. */ export function exampleBody(document: ApiDocument, operation: ApiOperation): string | undefined { const body = operation.body; if (body === undefined) return undefined; if (body.example !== undefined) return body.example; const value = exampleFor(document, body.schema, 0); return value === undefined ? undefined : JSON.stringify(value, null, 2); } /** The response a reference page shows: the document's example, else one generated from the schema. */ export function exampleResponse( document: ApiDocument, schema: ApiSchema | undefined, declared?: string, ): string | undefined { if (declared !== undefined) return declared; if (schema === undefined) return undefined; const value = exampleFor(document, schema, 0); return value === undefined ? undefined : JSON.stringify(value, null, 2); } /** * How deep a generated example goes before it stops. Matches the parser's expansion limit. * * Depth counts nesting in the value — a field inside an object, an element inside an array — and * not the hops through `$ref` taken to find a shape. Counting those too spent the budget twice as * fast as the value got deeper, and the cost was silent: `Invoice.lines[].unit_price` came out as * `{"amount": null, "currency": null}` in the example beside the response, three named types * deep in a document nobody would call large. Every named type is still reached through a field * or an element, so recursion — a `Comment` whose replies are `Comment` — still terminates here. */ const MAX_DEPTH = 6; function exampleFor(document: ApiDocument, schema: ApiSchema, depth: number): unknown { if (depth > MAX_DEPTH) return null; if (schema.ref !== undefined) { const type = findType(document, schema.ref); // A reference the document never declared: the parser keeps the name, and an example cannot // be invented for a shape nobody wrote down. if (type === undefined) return null; return exampleFor(document, type.schema, depth); } // The document's own example first: it is the only one of the three that was written by somebody // who knows what a real value looks like. if (schema.example !== undefined) return parseJson(schema.example); if (schema.default !== undefined) return parseJson(schema.default); if (schema.enum?.[0] !== undefined) return parseJson(schema.enum[0]); switch (schema.kind) { case "string": return scalarString(schema); case "integer": case "number": return 0; case "boolean": return false; case "null": return null; case "array": return schema.items === undefined ? [] : [exampleFor(document, schema.items, depth + 1)]; case "object": { const value: Record = {}; // Required fields only. An example carrying every optional field is an example a reader // sends verbatim, and then wonders why their record has eleven empty strings in it. for (const field of schema.fields ?? []) { if (field.required) value[field.name] = exampleFor(document, field.schema, depth + 1); } return value; } default: return schema.union?.[0] === undefined ? null : exampleFor(document, schema.union[0], depth + 1); } } function scalarString(schema: ApiSchema): string { switch (schema.format) { case "date": return "2026-01-31"; case "date-time": return "2026-01-31T12:00:00Z"; case "email": return "person@example.com"; case "uri": case "url": return "https://example.com"; case "uuid": return "00000000-0000-0000-0000-000000000000"; default: return "string"; } } /** A visibly-fake value for a parameter, derived from its type so the shape is still right. */ function placeholder(document: ApiDocument, schema: ApiSchema, name: string): string { const generated = exampleFor(document, schema, 0); if (typeof generated === "string" && generated !== "string") return generated; if (typeof generated === "number" || typeof generated === "boolean") return String(generated); return `<${name}>`; } function parseJson(rendered: string): unknown { try { return JSON.parse(rendered); } catch { // The parser renders a string default as the string itself rather than as JSON, so this is the // expected path for every `default: "usd"` in every document. return rendered; } }