diff --git a/README.md b/README.md index 62742c7..1d4ac39 100644 --- a/README.md +++ b/README.md @@ -126,8 +126,23 @@ Schema tables handle: - Nested objects: flattened as indented dotted rows (e.g., `owner.guid`) - Arrays of objects: expanded inline with their properties - `allOf` composition: merged into a single property table +- `anyOf`/`oneOf` composition: typed by the alternatives joined with `|` + (`object|null`, `string|integer`); a nullable object also lists the object's + properties, and a request or response body lists each alternative in turn - Property attributes: required, read-only, nullable, default, minimum/maximum, enum, example, format +### Field tables and `llms-txt` + +Quarto builds each `.llms.md` page from the rendered HTML with Pandoc's GFM +writer. A GFM table cell holds inline content only, so Pandoc writes `[TABLE]` +in place of any table with a paragraph break, list or line break in a cell. + +Each field table is therefore emitted twice, inside +`content-hidden`/`content-visible` blocks with `when-format="llms-txt"`: the +table for the HTML page, and a bullet list with one item per field for +`.llms.md`, where descriptions keep their paragraphs, lists and code blocks. +Quarto removes the list from the HTML page and its search index. + ## Project structure ```text @@ -143,6 +158,7 @@ quarto-openapi/ refs.ts # $ref resolution sections.ts # path grouping and endpoint rendering schema.ts # schema-to-table conversion + fields.ts # Name/Type/Description field tables markdown.ts # list table and markdown utilities escape.ts # makes description prose safe as markdown tests/ # node:test suites for lib/ diff --git a/_extensions/quarto-openapi/lib/fields.ts b/_extensions/quarto-openapi/lib/fields.ts new file mode 100644 index 0000000..b82daf0 --- /dev/null +++ b/_extensions/quarto-openapi/lib/fields.ts @@ -0,0 +1,82 @@ +/** + * Field tables: the Name / Type / Description tables for parameters and schema + * properties. + * + * Quarto builds a page's `.llms.md` by converting its rendered HTML with + * Pandoc's GFM writer. A GFM table cell holds inline content only, so a + * description with a second paragraph, a list or a line break would turn the + * whole table into `[TABLE]`. Each field table therefore comes in two forms: + * the list table for every format but `llms-txt`, and for `llms-txt` a bullet + * list with one item per field, where any markdown fits. Quarto keeps the + * `llms-txt` form out of the HTML page and its search index. + */ + +import { listTable } from "./markdown.ts"; + +export interface FieldRow { + /** The field's name, dotted for nested properties (`owner.guid`). */ + name: string; + /** Nesting level; 0 for top-level fields. */ + depth: number; + /** The type label, without code formatting. */ + type: string; + /** The field's description as markdown, possibly empty. */ + description: string; + /** Attribute sentences such as "Required. Example: `x`.", possibly empty. */ + attributes: string; +} + +/** The description followed by the attributes, as separate paragraphs. */ +function details(row: FieldRow): string { + return [row.description.trim(), row.attributes] + .filter((part) => part !== "") + .join("\n\n"); +} + +function nameCell(row: FieldRow): string { + return row.depth > 0 + ? `[\`${row.name}\`]{.schema-nest-${row.depth}}` + : `\`${row.name}\``; +} + +/** + * The `llms-txt` form: one loose list item per field, headed by its name and + * type, with the details as the item's blocks. + */ +function fieldList(rows: FieldRow[]): string[] { + const lines: string[] = []; + for (const row of rows) { + lines.push(`- \`${row.name}\` (\`${row.type}\`)`, ""); + const text = details(row); + if (text === "") continue; + for (const line of text.split("\n")) { + lines.push(line === "" ? "" : ` ${line}`); + } + lines.push(""); + } + return lines; +} + +/** Render rows as a field table, plus its `llms-txt` form. */ +export function fieldTable(rows: FieldRow[]): string[] { + if (rows.length === 0) return []; + + const table = listTable( + ["Name", "Type", "Description"], + rows.map((row) => ({ + cells: [nameCell(row), `\`${row.type}\``, details(row)], + })), + ); + return [ + '::: {.content-hidden when-format="llms-txt"}', + "", + ...table, + "", + ":::", + "", + '::: {.content-visible when-format="llms-txt"}', + "", + ...fieldList(rows), + ":::", + ]; +} diff --git a/_extensions/quarto-openapi/lib/markdown.ts b/_extensions/quarto-openapi/lib/markdown.ts index 4c1bdbc..e03c71c 100644 --- a/_extensions/quarto-openapi/lib/markdown.ts +++ b/_extensions/quarto-openapi/lib/markdown.ts @@ -74,8 +74,9 @@ export function listTable(headers: string[], rows: TableRow[]): string[] { lines.push(""); const emitGroup = (cellLines: string[][]) => { - // Loose when any cell holds more than one block. - const loose = cellLines.some((cl) => cl.some((line) => line === "")); + // Loose when any cell holds more than one block. An empty cell is one + // empty line, not a block separator. + const loose = cellLines.some((cl) => cl.length > 1 && cl.includes("")); cellLines.forEach((cl, col) => { if (loose && col > 0) lines.push(""); lines.push((col === 0 ? "* * " : " * ") + cl[0]); diff --git a/_extensions/quarto-openapi/lib/refs.ts b/_extensions/quarto-openapi/lib/refs.ts index bbdca5d..07e6739 100644 --- a/_extensions/quarto-openapi/lib/refs.ts +++ b/_extensions/quarto-openapi/lib/refs.ts @@ -41,8 +41,11 @@ export function expandRefs( if (isReference(obj)) { const ref = obj.$ref; if (seen.has(ref)) { - // Circular reference — return a stub to avoid infinite recursion - return { description: `(circular reference: ${ref})` } as T; + // Circular reference: a stub that names the schema it would repeat. + return { + description: `(circular reference: ${ref})`, + "x-circular-ref": ref, + } as T; } const resolved = resolveRef(spec, ref); if (resolved === undefined) { diff --git a/_extensions/quarto-openapi/lib/schema.ts b/_extensions/quarto-openapi/lib/schema.ts index 68fb0a4..49a2b5c 100644 --- a/_extensions/quarto-openapi/lib/schema.ts +++ b/_extensions/quarto-openapi/lib/schema.ts @@ -2,20 +2,14 @@ * Convert OpenAPI Schema objects to markdown property tables. * * Handles: primitives, objects (including nested via flattened rows), - * arrays, allOf composition, and property attributes. + * arrays, maps, allOf/anyOf/oneOf composition, and property attributes. */ import type { Schema, Reference } from "./types.ts"; import { isReference } from "./types.ts"; import type { OpenAPISpec } from "./types.ts"; import { resolve } from "./refs.ts"; -import { listTable, type TableRow } from "./markdown.ts"; - -interface PropertyRow { - name: string; - type: string; - description: string; -} +import { fieldTable, type FieldRow } from "./fields.ts"; /** * Render a schema as markdown lines (description + property table). @@ -24,7 +18,7 @@ export function renderSchema( spec: OpenAPISpec, schema: Schema | Reference, ): string[] { - const resolved = isReference(schema) ? resolve(spec, schema) : schema; + const resolved = normalize(spec, schema); const lines: string[] = []; if (resolved.description) { @@ -32,21 +26,13 @@ export function renderSchema( lines.push(""); } - if (resolved.allOf) { - return renderAllOf(spec, resolved, lines); - } - const type = resolved.type; if (type === "array") { return renderArray(spec, resolved, lines); } - if ( - !resolved.properties && - resolved.additionalProperties !== undefined && - resolved.additionalProperties !== false - ) { + if (isMap(resolved)) { return renderMap(spec, resolved, lines); } @@ -54,52 +40,76 @@ export function renderSchema( return renderObject(spec, resolved, lines); } + const alternatives = resolved.anyOf ?? resolved.oneOf; + if (!type && alternatives) { + return renderAlternatives(spec, alternatives, lines); + } + // Primitive type if (type) { - lines.push(formatPrimitiveType(resolved)); + lines.push(formatPrimitiveType(spec, resolved)); } return lines; } -function renderAllOf( - spec: OpenAPISpec, - schema: Schema, - lines: string[], -): string[] { - // Merge all properties from allOf schemas into a single object - const merged = mergeAllOf(spec, schema.allOf!); - return renderObject(spec, merged, lines); -} - /** - * Merge allOf schemas into a single schema with combined properties. + * A schema with its `$ref` resolved and its `allOf` members merged into it. + * Properties and required lists combine; for any other keyword the schema's + * own value wins, then the first member that sets it. */ -function mergeAllOf( - spec: OpenAPISpec, - schemas: (Schema | Reference)[], -): Schema { - const merged: Schema = { type: "object", properties: {}, required: [] }; - - for (const s of schemas) { - const resolved = isReference(s) ? resolve(spec, s) : s; +function normalize(spec: OpenAPISpec, schema: Schema | Reference): Schema { + const resolved = isReference(schema) ? resolve(spec, schema) : schema; + if (!resolved.allOf) return resolved; + + const { allOf, ...own } = resolved; + const merged: Record & Schema = {}; + const add = (part: Schema, override: boolean) => { + for (const [key, value] of Object.entries(part)) { + if (key === "properties") { + merged.properties = { ...merged.properties, ...part.properties }; + } else if (key === "required") { + merged.required = [...(merged.required ?? []), ...part.required!]; + } else if (override || merged[key] === undefined) { + merged[key] = value; + } + } + }; + for (const member of allOf) add(normalize(spec, member), false); + add(own, true); + return merged; +} - // Recursively merge nested allOf - const effective = - resolved.allOf ? mergeAllOf(spec, resolved.allOf) : resolved; +/** Whether a schema is a map: `additionalProperties` and no fixed properties. */ +function isMap(schema: Schema): boolean { + return ( + !schema.properties && + schema.additionalProperties !== undefined && + schema.additionalProperties !== false + ); +} - if (effective.properties) { - merged.properties = { ...merged.properties, ...effective.properties }; - } - if (effective.required) { - merged.required = [...(merged.required || []), ...effective.required]; - } - if (effective.description && !merged.description) { - merged.description = effective.description; - } - } +/** Whether a schema describes an object whose properties can be listed. */ +function isObjectLike(schema: Schema): boolean { + return schema.type === "object" || !!schema.properties; +} - return merged; +/** + * Render each alternative of an `anyOf`/`oneOf` in turn, then say whether + * `null` is also allowed. + */ +function renderAlternatives( + spec: OpenAPISpec, + members: (Schema | Reference)[], + lines: string[], +): string[] { + const alternatives = members.filter((m) => !isNullMarker(m)); + alternatives.forEach((member, i) => { + if (i > 0) lines.push("", "Or:", ""); + lines.push(...renderSchema(spec, member)); + }); + if (alternatives.length < members.length) lines.push("", "Or `null`."); + return lines; } function renderArray( @@ -112,17 +122,18 @@ function renderArray( return lines; } - const items = isReference(schema.items) - ? resolve(spec, schema.items) - : schema.items; + const items = normalize(spec, schema.items); - if (items.type === "object" || items.properties || items.allOf) { + if (isObjectLike(items)) { lines.push("Array of objects:"); lines.push(""); lines.push(...renderSchema(spec, items)); + } else if (!items.type && (items.anyOf || items.oneOf)) { + lines.push("Array of:"); + lines.push(""); + lines.push(...renderSchema(spec, items)); } else { - const itemType = formatPrimitiveType(items); - lines.push(`Array of ${itemType}`); + lines.push(`Array of ${formatPrimitiveType(spec, items)}`); } return lines; @@ -140,17 +151,13 @@ function renderMap( } return lines; } - const valueSchema = isReference(ap) ? resolve(spec, ap) : ap; - if ( - valueSchema.type === "object" || - valueSchema.properties || - valueSchema.allOf - ) { + const valueSchema = normalize(spec, ap); + if (isObjectLike(valueSchema)) { lines.push("Map of string to object:"); lines.push(""); lines.push(...renderSchema(spec, valueSchema)); } else { - lines.push(`Map of string to ${formatPrimitiveType(valueSchema)}`); + lines.push(`Map of string to ${formatPrimitiveType(spec, valueSchema)}`); } return lines; } @@ -165,20 +172,14 @@ function renderObject( return lines; } - const rows = flattenProperties(spec, schema.properties, schema.required, ""); - if (rows.length === 0) return lines; - - const tableRows: TableRow[] = rows.map((row) => ({ - cells: [row.name, row.type, row.description], - })); - - lines.push(...listTable(["Name", "Type", "Description"], tableRows)); + const rows = flattenProperties(spec, schema.properties, schema.required); + lines.push(...fieldTable(rows)); return lines; } /** * Flatten object properties into rows, recursing into nested objects - * with indented dotted path names. + * with dotted path names. */ function flattenProperties( spec: OpenAPISpec, @@ -186,128 +187,32 @@ function flattenProperties( required?: string[], prefix: string = "", depth: number = 0, -): PropertyRow[] { - const rows: PropertyRow[] = []; +): FieldRow[] { + const rows: FieldRow[] = []; const requiredSet = new Set(required || []); for (const [name, prop] of Object.entries(properties)) { - const resolved = isReference(prop) ? resolve(spec, prop) : prop; - const displayName = prefix ? `${prefix}.${name}` : name; - const nameCell = depth > 0 - ? `[\`${displayName}\`]{.schema-nest-${depth}}` - : `\`${displayName}\``; - - if ( - (resolved.type === "object" || resolved.properties) && - resolved.properties && - !resolved.allOf - ) { - // Nested object: emit a row for the object itself, then recurse - rows.push({ - name: nameCell, - type: "`object`", - description: resolved.description || "", - }); + const schema = normalize(spec, prop); + const path = prefix ? `${prefix}.${name}` : name; + rows.push({ + name: path, + depth, + type: formatTypeString(spec, schema), + description: schema.description ?? "", + attributes: attributesOf(schema, requiredSet.has(name)), + }); + + const nested = nestedFields(spec, schema); + if (nested?.fields.properties) { rows.push( ...flattenProperties( spec, - resolved.properties, - resolved.required, - displayName, + nested.fields.properties, + nested.fields.required, + path + nested.suffix, depth + 1, ), ); - } else if (resolved.allOf) { - const merged = mergeAllOf(spec, resolved.allOf); - rows.push({ - name: nameCell, - type: "`object`", - description: resolved.description || merged.description || "", - }); - if (merged.properties) { - rows.push( - ...flattenProperties( - spec, - merged.properties, - merged.required, - displayName, - depth + 1, - ), - ); - } - } else if (resolved.type === "array" && resolved.items) { - const items = isReference(resolved.items) - ? resolve(spec, resolved.items) - : resolved.items; - - if (items.type === "object" || items.properties || items.allOf) { - rows.push({ - name: nameCell, - type: "`[object]`", - description: buildDescription(resolved, requiredSet.has(name)), - }); - const effective = items.allOf ? mergeAllOf(spec, items.allOf) : items; - if (effective.properties) { - rows.push( - ...flattenProperties( - spec, - effective.properties, - effective.required, - `${displayName}[]`, - depth + 1, - ), - ); - } - } else { - const itemType = items.type || "unknown"; - rows.push({ - name: nameCell, - type: `\`[${itemType}]\``, - description: buildDescription(resolved, requiredSet.has(name)), - }); - } - } else if ( - !resolved.properties && - resolved.additionalProperties !== undefined && - resolved.additionalProperties !== false - ) { - // Typed map: additionalProperties is a schema, $ref, or `true`. - const ap = resolved.additionalProperties; - const valueType = mapValueTypeLabel(spec, ap); - rows.push({ - name: nameCell, - type: `\`map[string, ${valueType}]\``, - description: buildDescription(resolved, requiredSet.has(name)), - }); - if (ap !== true) { - const valueSchema = isReference(ap) ? resolve(spec, ap) : ap; - if ( - valueSchema.type === "object" || - valueSchema.properties || - valueSchema.allOf - ) { - const effective = valueSchema.allOf - ? mergeAllOf(spec, valueSchema.allOf) - : valueSchema; - if (effective.properties) { - rows.push( - ...flattenProperties( - spec, - effective.properties, - effective.required, - `${displayName}{}`, - depth + 1, - ), - ); - } - } - } - } else { - rows.push({ - name: nameCell, - type: `\`${formatTypeString(resolved)}\``, - description: buildDescription(resolved, requiredSet.has(name)), - }); } } @@ -315,15 +220,37 @@ function flattenProperties( } /** - * Build a description string including property attributes. + * The object whose properties a field's child rows list, and the suffix its + * child names take after the field's name: `[]` steps into array items, `{}` + * into map values. A nullable object (`anyOf: [{ $ref }, { nullable: true }]`) + * lists the object's properties. */ -function buildDescription(schema: Schema, isRequired: boolean): string { - const parts: string[] = []; - - if (schema.description) { - parts.push(schema.description.trim()); +function nestedFields( + spec: OpenAPISpec, + schema: Schema, +): { fields: Schema; suffix: string } | undefined { + if (schema.properties) return { fields: schema, suffix: "" }; + + const inner = + schema.type === "array" && schema.items + ? { schema: schema.items, suffix: "[]" } + : isMap(schema) && typeof schema.additionalProperties === "object" + ? { schema: schema.additionalProperties, suffix: "{}" } + : undefined; + if (inner) { + const found = nestedFields(spec, normalize(spec, inner.schema)); + return found && { ...found, suffix: inner.suffix + found.suffix }; } + const alternative = soleAlternative(spec, schema); + return alternative && nestedFields(spec, alternative); +} + +/** + * The attribute sentences shown after a field's description, such as + * "Required. Example: `x`.", or "" when the field has none. + */ +export function attributesOf(schema: Schema, isRequired: boolean): string { const attrs: string[] = []; if (isRequired) attrs.push("Required"); if (schema.readOnly) attrs.push("Read-only"); @@ -339,44 +266,102 @@ function buildDescription(schema: Schema, isRequired: boolean): string { if (schema.example !== undefined) attrs.push(`Example: \`${formatValue(schema.example)}\``); - if (attrs.length > 0) { - if (parts.length > 0) parts.push(""); - parts.push(attrs.join(". ") + "."); - } - - return parts.join("\n"); + return attrs.length > 0 ? attrs.join(". ") + "." : ""; } const semanticFormats = new Set(["date-time", "date", "time", "duration", "uuid", "uri", "uri-reference", "email", "hostname", "ipv4", "ipv6", "byte", "binary", "password"]); -function mapValueTypeLabel( - _spec: OpenAPISpec, - value: Schema | Reference | boolean, -): string { - if (value === true) return "any"; - if (value === false) return "object"; - if (isReference(value)) { - return value.$ref.split("/").pop() || "object"; +/** + * Whether a schema only marks its parent as nullable, like the second member + * of `anyOf: [{ $ref }, { nullable: true }]`. + */ +function isNullMarker(schema: Schema | Reference): boolean { + if (isReference(schema)) return false; + if (schema.type === "null") return true; + return ( + schema.nullable === true && + Object.keys(schema).every((k) => k === "nullable" || k === "description") + ); +} + +/** + * The one schema an `anyOf` or `oneOf` allows besides null, or undefined when + * there is no such composition or it has more than one alternative. + */ +function soleAlternative(spec: OpenAPISpec, schema: Schema): Schema | undefined { + const members = schema.anyOf ?? schema.oneOf; + if (!members) return undefined; + const alternatives = members.filter((m) => !isNullMarker(m)); + return alternatives.length === 1 + ? normalize(spec, alternatives[0]) + : undefined; +} + +/** The last segment of a `$ref`, which names the schema it points to. */ +function refName(ref: string): string { + return ref.split("/").pop() || "object"; +} + +/** + * A short name for the type a schema allows: its `type`; `[item]` for an + * array; `map[string, value]` for a map; the alternatives joined by `|` for + * `anyOf`/`oneOf`; the schema's name where a `$ref` would recurse; and `any` + * for a schema that does not constrain the type. + */ +function typeLabel(spec: OpenAPISpec, schema: Schema | Reference): string { + const s = normalize(spec, schema); + if (s["x-circular-ref"]) return refName(s["x-circular-ref"]); + if (s.type === "array" || (!s.type && s.items)) { + return `[${s.items ? typeLabel(spec, s.items) : "any"}]`; + } + if (isMap(s)) { + const ap = s.additionalProperties!; + const value = + ap === true + ? "any" + : isReference(ap) + ? refName(ap.$ref) + : typeLabel(spec, ap as Schema); + return `map[string, ${value}]`; } - if (value.type === "object" || value.properties || value.allOf) return "object"; - return value.type || "object"; + if (s.type) return s.type; + const members = s.anyOf ?? s.oneOf; + if (members) { + const labels = members.flatMap((m) => { + if (isNullMarker(m)) return ["null"]; + const label = typeLabel(spec, m); + return !isReference(m) && m.nullable ? [label, "null"] : [label]; + }); + return [...new Set(labels)].join("|"); + } + if (s.properties) return "object"; + return "any"; } -function formatTypeString(schema: Schema): string { - let type = schema.type || "unknown"; +/** + * The type label for a field: the type, its format when the format says + * something about the value (or any format, with `anyFormat`), and `|null` + * when nullable. + */ +export function formatTypeString( + spec: OpenAPISpec, + schema: Schema, + anyFormat = false, +): string { + let type = typeLabel(spec, schema); - if (schema.format && semanticFormats.has(schema.format)) { + if (schema.format && (anyFormat || semanticFormats.has(schema.format))) { type = `${type} (${schema.format})`; } - if (schema.nullable) { + if (schema.nullable && !type.split("|").includes("null")) { type = `${type}|null`; } return type; } -function formatPrimitiveType(schema: Schema): string { - const parts = [schema.type || "unknown"]; +function formatPrimitiveType(spec: OpenAPISpec, schema: Schema): string { + const parts = [typeLabel(spec, schema)]; if (schema.format && semanticFormats.has(schema.format)) parts.push(`(${schema.format})`); return parts.join(" "); } diff --git a/_extensions/quarto-openapi/lib/sections.ts b/_extensions/quarto-openapi/lib/sections.ts index de10ce7..8e1be03 100644 --- a/_extensions/quarto-openapi/lib/sections.ts +++ b/_extensions/quarto-openapi/lib/sections.ts @@ -15,7 +15,7 @@ import type { } from "./types.ts"; import { HTTP_METHODS, isReference } from "./types.ts"; import { resolve } from "./refs.ts"; -import { renderSchema } from "./schema.ts"; +import { attributesOf, formatTypeString, renderSchema } from "./schema.ts"; import { stripCode } from "./escape.ts"; import { autoIdentifier, @@ -23,9 +23,8 @@ import { heading, methodBadge, pathToAnchor, - listTable, - type TableRow, } from "./markdown.ts"; +import { fieldTable, type FieldRow } from "./fields.ts"; export interface Section { /** Resource name, e.g., "content", "bundles" */ @@ -523,30 +522,20 @@ function renderParameters( lines.push(""); } - const rows: TableRow[] = params.map((param) => { + const rows: FieldRow[] = params.map((param) => { const schema = param.schema ? resolve(spec, param.schema) : undefined; - - const typeParts: string[] = []; - if (schema?.type) typeParts.push(schema.type); - if (schema?.format) typeParts.push(`(${schema.format})`); - const typeStr = typeParts.length > 0 ? typeParts.join(" ") : "string"; - - const descParts: string[] = []; - if (param.description) descParts.push(param.description.trim()); - if (param.required) descParts.push("Required."); - return { - cells: [ - `\`${param.name}\``, - `\`${typeStr}\``, - descParts.join(" "), - ], + name: param.name, + depth: 0, + type: schema ? formatTypeString(spec, schema, true) : "string", + description: param.description ?? "", + attributes: attributesOf(schema ?? {}, !!param.required), }; }); - lines.push(...listTable(["Name", "Type", "Description"], rows)); + lines.push(...fieldTable(rows)); lines.push(""); } diff --git a/_extensions/quarto-openapi/lib/types.ts b/_extensions/quarto-openapi/lib/types.ts index f091379..82b582d 100644 --- a/_extensions/quarto-openapi/lib/types.ts +++ b/_extensions/quarto-openapi/lib/types.ts @@ -112,6 +112,8 @@ export interface Schema { maxLength?: number; pattern?: string; additionalProperties?: boolean | Schema | Reference; + /** Set by expandRefs on the stub that ends a circular `$ref`. */ + "x-circular-ref"?: string; } export interface Reference { diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/fields.ts b/example/_extensions/posit-dev/quarto-openapi/lib/fields.ts new file mode 100644 index 0000000..b82daf0 --- /dev/null +++ b/example/_extensions/posit-dev/quarto-openapi/lib/fields.ts @@ -0,0 +1,82 @@ +/** + * Field tables: the Name / Type / Description tables for parameters and schema + * properties. + * + * Quarto builds a page's `.llms.md` by converting its rendered HTML with + * Pandoc's GFM writer. A GFM table cell holds inline content only, so a + * description with a second paragraph, a list or a line break would turn the + * whole table into `[TABLE]`. Each field table therefore comes in two forms: + * the list table for every format but `llms-txt`, and for `llms-txt` a bullet + * list with one item per field, where any markdown fits. Quarto keeps the + * `llms-txt` form out of the HTML page and its search index. + */ + +import { listTable } from "./markdown.ts"; + +export interface FieldRow { + /** The field's name, dotted for nested properties (`owner.guid`). */ + name: string; + /** Nesting level; 0 for top-level fields. */ + depth: number; + /** The type label, without code formatting. */ + type: string; + /** The field's description as markdown, possibly empty. */ + description: string; + /** Attribute sentences such as "Required. Example: `x`.", possibly empty. */ + attributes: string; +} + +/** The description followed by the attributes, as separate paragraphs. */ +function details(row: FieldRow): string { + return [row.description.trim(), row.attributes] + .filter((part) => part !== "") + .join("\n\n"); +} + +function nameCell(row: FieldRow): string { + return row.depth > 0 + ? `[\`${row.name}\`]{.schema-nest-${row.depth}}` + : `\`${row.name}\``; +} + +/** + * The `llms-txt` form: one loose list item per field, headed by its name and + * type, with the details as the item's blocks. + */ +function fieldList(rows: FieldRow[]): string[] { + const lines: string[] = []; + for (const row of rows) { + lines.push(`- \`${row.name}\` (\`${row.type}\`)`, ""); + const text = details(row); + if (text === "") continue; + for (const line of text.split("\n")) { + lines.push(line === "" ? "" : ` ${line}`); + } + lines.push(""); + } + return lines; +} + +/** Render rows as a field table, plus its `llms-txt` form. */ +export function fieldTable(rows: FieldRow[]): string[] { + if (rows.length === 0) return []; + + const table = listTable( + ["Name", "Type", "Description"], + rows.map((row) => ({ + cells: [nameCell(row), `\`${row.type}\``, details(row)], + })), + ); + return [ + '::: {.content-hidden when-format="llms-txt"}', + "", + ...table, + "", + ":::", + "", + '::: {.content-visible when-format="llms-txt"}', + "", + ...fieldList(rows), + ":::", + ]; +} diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/markdown.ts b/example/_extensions/posit-dev/quarto-openapi/lib/markdown.ts index 4c1bdbc..e03c71c 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/markdown.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/markdown.ts @@ -74,8 +74,9 @@ export function listTable(headers: string[], rows: TableRow[]): string[] { lines.push(""); const emitGroup = (cellLines: string[][]) => { - // Loose when any cell holds more than one block. - const loose = cellLines.some((cl) => cl.some((line) => line === "")); + // Loose when any cell holds more than one block. An empty cell is one + // empty line, not a block separator. + const loose = cellLines.some((cl) => cl.length > 1 && cl.includes("")); cellLines.forEach((cl, col) => { if (loose && col > 0) lines.push(""); lines.push((col === 0 ? "* * " : " * ") + cl[0]); diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/refs.ts b/example/_extensions/posit-dev/quarto-openapi/lib/refs.ts index bbdca5d..07e6739 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/refs.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/refs.ts @@ -41,8 +41,11 @@ export function expandRefs( if (isReference(obj)) { const ref = obj.$ref; if (seen.has(ref)) { - // Circular reference — return a stub to avoid infinite recursion - return { description: `(circular reference: ${ref})` } as T; + // Circular reference: a stub that names the schema it would repeat. + return { + description: `(circular reference: ${ref})`, + "x-circular-ref": ref, + } as T; } const resolved = resolveRef(spec, ref); if (resolved === undefined) { diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts b/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts index 68fb0a4..49a2b5c 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/schema.ts @@ -2,20 +2,14 @@ * Convert OpenAPI Schema objects to markdown property tables. * * Handles: primitives, objects (including nested via flattened rows), - * arrays, allOf composition, and property attributes. + * arrays, maps, allOf/anyOf/oneOf composition, and property attributes. */ import type { Schema, Reference } from "./types.ts"; import { isReference } from "./types.ts"; import type { OpenAPISpec } from "./types.ts"; import { resolve } from "./refs.ts"; -import { listTable, type TableRow } from "./markdown.ts"; - -interface PropertyRow { - name: string; - type: string; - description: string; -} +import { fieldTable, type FieldRow } from "./fields.ts"; /** * Render a schema as markdown lines (description + property table). @@ -24,7 +18,7 @@ export function renderSchema( spec: OpenAPISpec, schema: Schema | Reference, ): string[] { - const resolved = isReference(schema) ? resolve(spec, schema) : schema; + const resolved = normalize(spec, schema); const lines: string[] = []; if (resolved.description) { @@ -32,21 +26,13 @@ export function renderSchema( lines.push(""); } - if (resolved.allOf) { - return renderAllOf(spec, resolved, lines); - } - const type = resolved.type; if (type === "array") { return renderArray(spec, resolved, lines); } - if ( - !resolved.properties && - resolved.additionalProperties !== undefined && - resolved.additionalProperties !== false - ) { + if (isMap(resolved)) { return renderMap(spec, resolved, lines); } @@ -54,52 +40,76 @@ export function renderSchema( return renderObject(spec, resolved, lines); } + const alternatives = resolved.anyOf ?? resolved.oneOf; + if (!type && alternatives) { + return renderAlternatives(spec, alternatives, lines); + } + // Primitive type if (type) { - lines.push(formatPrimitiveType(resolved)); + lines.push(formatPrimitiveType(spec, resolved)); } return lines; } -function renderAllOf( - spec: OpenAPISpec, - schema: Schema, - lines: string[], -): string[] { - // Merge all properties from allOf schemas into a single object - const merged = mergeAllOf(spec, schema.allOf!); - return renderObject(spec, merged, lines); -} - /** - * Merge allOf schemas into a single schema with combined properties. + * A schema with its `$ref` resolved and its `allOf` members merged into it. + * Properties and required lists combine; for any other keyword the schema's + * own value wins, then the first member that sets it. */ -function mergeAllOf( - spec: OpenAPISpec, - schemas: (Schema | Reference)[], -): Schema { - const merged: Schema = { type: "object", properties: {}, required: [] }; - - for (const s of schemas) { - const resolved = isReference(s) ? resolve(spec, s) : s; +function normalize(spec: OpenAPISpec, schema: Schema | Reference): Schema { + const resolved = isReference(schema) ? resolve(spec, schema) : schema; + if (!resolved.allOf) return resolved; + + const { allOf, ...own } = resolved; + const merged: Record & Schema = {}; + const add = (part: Schema, override: boolean) => { + for (const [key, value] of Object.entries(part)) { + if (key === "properties") { + merged.properties = { ...merged.properties, ...part.properties }; + } else if (key === "required") { + merged.required = [...(merged.required ?? []), ...part.required!]; + } else if (override || merged[key] === undefined) { + merged[key] = value; + } + } + }; + for (const member of allOf) add(normalize(spec, member), false); + add(own, true); + return merged; +} - // Recursively merge nested allOf - const effective = - resolved.allOf ? mergeAllOf(spec, resolved.allOf) : resolved; +/** Whether a schema is a map: `additionalProperties` and no fixed properties. */ +function isMap(schema: Schema): boolean { + return ( + !schema.properties && + schema.additionalProperties !== undefined && + schema.additionalProperties !== false + ); +} - if (effective.properties) { - merged.properties = { ...merged.properties, ...effective.properties }; - } - if (effective.required) { - merged.required = [...(merged.required || []), ...effective.required]; - } - if (effective.description && !merged.description) { - merged.description = effective.description; - } - } +/** Whether a schema describes an object whose properties can be listed. */ +function isObjectLike(schema: Schema): boolean { + return schema.type === "object" || !!schema.properties; +} - return merged; +/** + * Render each alternative of an `anyOf`/`oneOf` in turn, then say whether + * `null` is also allowed. + */ +function renderAlternatives( + spec: OpenAPISpec, + members: (Schema | Reference)[], + lines: string[], +): string[] { + const alternatives = members.filter((m) => !isNullMarker(m)); + alternatives.forEach((member, i) => { + if (i > 0) lines.push("", "Or:", ""); + lines.push(...renderSchema(spec, member)); + }); + if (alternatives.length < members.length) lines.push("", "Or `null`."); + return lines; } function renderArray( @@ -112,17 +122,18 @@ function renderArray( return lines; } - const items = isReference(schema.items) - ? resolve(spec, schema.items) - : schema.items; + const items = normalize(spec, schema.items); - if (items.type === "object" || items.properties || items.allOf) { + if (isObjectLike(items)) { lines.push("Array of objects:"); lines.push(""); lines.push(...renderSchema(spec, items)); + } else if (!items.type && (items.anyOf || items.oneOf)) { + lines.push("Array of:"); + lines.push(""); + lines.push(...renderSchema(spec, items)); } else { - const itemType = formatPrimitiveType(items); - lines.push(`Array of ${itemType}`); + lines.push(`Array of ${formatPrimitiveType(spec, items)}`); } return lines; @@ -140,17 +151,13 @@ function renderMap( } return lines; } - const valueSchema = isReference(ap) ? resolve(spec, ap) : ap; - if ( - valueSchema.type === "object" || - valueSchema.properties || - valueSchema.allOf - ) { + const valueSchema = normalize(spec, ap); + if (isObjectLike(valueSchema)) { lines.push("Map of string to object:"); lines.push(""); lines.push(...renderSchema(spec, valueSchema)); } else { - lines.push(`Map of string to ${formatPrimitiveType(valueSchema)}`); + lines.push(`Map of string to ${formatPrimitiveType(spec, valueSchema)}`); } return lines; } @@ -165,20 +172,14 @@ function renderObject( return lines; } - const rows = flattenProperties(spec, schema.properties, schema.required, ""); - if (rows.length === 0) return lines; - - const tableRows: TableRow[] = rows.map((row) => ({ - cells: [row.name, row.type, row.description], - })); - - lines.push(...listTable(["Name", "Type", "Description"], tableRows)); + const rows = flattenProperties(spec, schema.properties, schema.required); + lines.push(...fieldTable(rows)); return lines; } /** * Flatten object properties into rows, recursing into nested objects - * with indented dotted path names. + * with dotted path names. */ function flattenProperties( spec: OpenAPISpec, @@ -186,128 +187,32 @@ function flattenProperties( required?: string[], prefix: string = "", depth: number = 0, -): PropertyRow[] { - const rows: PropertyRow[] = []; +): FieldRow[] { + const rows: FieldRow[] = []; const requiredSet = new Set(required || []); for (const [name, prop] of Object.entries(properties)) { - const resolved = isReference(prop) ? resolve(spec, prop) : prop; - const displayName = prefix ? `${prefix}.${name}` : name; - const nameCell = depth > 0 - ? `[\`${displayName}\`]{.schema-nest-${depth}}` - : `\`${displayName}\``; - - if ( - (resolved.type === "object" || resolved.properties) && - resolved.properties && - !resolved.allOf - ) { - // Nested object: emit a row for the object itself, then recurse - rows.push({ - name: nameCell, - type: "`object`", - description: resolved.description || "", - }); + const schema = normalize(spec, prop); + const path = prefix ? `${prefix}.${name}` : name; + rows.push({ + name: path, + depth, + type: formatTypeString(spec, schema), + description: schema.description ?? "", + attributes: attributesOf(schema, requiredSet.has(name)), + }); + + const nested = nestedFields(spec, schema); + if (nested?.fields.properties) { rows.push( ...flattenProperties( spec, - resolved.properties, - resolved.required, - displayName, + nested.fields.properties, + nested.fields.required, + path + nested.suffix, depth + 1, ), ); - } else if (resolved.allOf) { - const merged = mergeAllOf(spec, resolved.allOf); - rows.push({ - name: nameCell, - type: "`object`", - description: resolved.description || merged.description || "", - }); - if (merged.properties) { - rows.push( - ...flattenProperties( - spec, - merged.properties, - merged.required, - displayName, - depth + 1, - ), - ); - } - } else if (resolved.type === "array" && resolved.items) { - const items = isReference(resolved.items) - ? resolve(spec, resolved.items) - : resolved.items; - - if (items.type === "object" || items.properties || items.allOf) { - rows.push({ - name: nameCell, - type: "`[object]`", - description: buildDescription(resolved, requiredSet.has(name)), - }); - const effective = items.allOf ? mergeAllOf(spec, items.allOf) : items; - if (effective.properties) { - rows.push( - ...flattenProperties( - spec, - effective.properties, - effective.required, - `${displayName}[]`, - depth + 1, - ), - ); - } - } else { - const itemType = items.type || "unknown"; - rows.push({ - name: nameCell, - type: `\`[${itemType}]\``, - description: buildDescription(resolved, requiredSet.has(name)), - }); - } - } else if ( - !resolved.properties && - resolved.additionalProperties !== undefined && - resolved.additionalProperties !== false - ) { - // Typed map: additionalProperties is a schema, $ref, or `true`. - const ap = resolved.additionalProperties; - const valueType = mapValueTypeLabel(spec, ap); - rows.push({ - name: nameCell, - type: `\`map[string, ${valueType}]\``, - description: buildDescription(resolved, requiredSet.has(name)), - }); - if (ap !== true) { - const valueSchema = isReference(ap) ? resolve(spec, ap) : ap; - if ( - valueSchema.type === "object" || - valueSchema.properties || - valueSchema.allOf - ) { - const effective = valueSchema.allOf - ? mergeAllOf(spec, valueSchema.allOf) - : valueSchema; - if (effective.properties) { - rows.push( - ...flattenProperties( - spec, - effective.properties, - effective.required, - `${displayName}{}`, - depth + 1, - ), - ); - } - } - } - } else { - rows.push({ - name: nameCell, - type: `\`${formatTypeString(resolved)}\``, - description: buildDescription(resolved, requiredSet.has(name)), - }); } } @@ -315,15 +220,37 @@ function flattenProperties( } /** - * Build a description string including property attributes. + * The object whose properties a field's child rows list, and the suffix its + * child names take after the field's name: `[]` steps into array items, `{}` + * into map values. A nullable object (`anyOf: [{ $ref }, { nullable: true }]`) + * lists the object's properties. */ -function buildDescription(schema: Schema, isRequired: boolean): string { - const parts: string[] = []; - - if (schema.description) { - parts.push(schema.description.trim()); +function nestedFields( + spec: OpenAPISpec, + schema: Schema, +): { fields: Schema; suffix: string } | undefined { + if (schema.properties) return { fields: schema, suffix: "" }; + + const inner = + schema.type === "array" && schema.items + ? { schema: schema.items, suffix: "[]" } + : isMap(schema) && typeof schema.additionalProperties === "object" + ? { schema: schema.additionalProperties, suffix: "{}" } + : undefined; + if (inner) { + const found = nestedFields(spec, normalize(spec, inner.schema)); + return found && { ...found, suffix: inner.suffix + found.suffix }; } + const alternative = soleAlternative(spec, schema); + return alternative && nestedFields(spec, alternative); +} + +/** + * The attribute sentences shown after a field's description, such as + * "Required. Example: `x`.", or "" when the field has none. + */ +export function attributesOf(schema: Schema, isRequired: boolean): string { const attrs: string[] = []; if (isRequired) attrs.push("Required"); if (schema.readOnly) attrs.push("Read-only"); @@ -339,44 +266,102 @@ function buildDescription(schema: Schema, isRequired: boolean): string { if (schema.example !== undefined) attrs.push(`Example: \`${formatValue(schema.example)}\``); - if (attrs.length > 0) { - if (parts.length > 0) parts.push(""); - parts.push(attrs.join(". ") + "."); - } - - return parts.join("\n"); + return attrs.length > 0 ? attrs.join(". ") + "." : ""; } const semanticFormats = new Set(["date-time", "date", "time", "duration", "uuid", "uri", "uri-reference", "email", "hostname", "ipv4", "ipv6", "byte", "binary", "password"]); -function mapValueTypeLabel( - _spec: OpenAPISpec, - value: Schema | Reference | boolean, -): string { - if (value === true) return "any"; - if (value === false) return "object"; - if (isReference(value)) { - return value.$ref.split("/").pop() || "object"; +/** + * Whether a schema only marks its parent as nullable, like the second member + * of `anyOf: [{ $ref }, { nullable: true }]`. + */ +function isNullMarker(schema: Schema | Reference): boolean { + if (isReference(schema)) return false; + if (schema.type === "null") return true; + return ( + schema.nullable === true && + Object.keys(schema).every((k) => k === "nullable" || k === "description") + ); +} + +/** + * The one schema an `anyOf` or `oneOf` allows besides null, or undefined when + * there is no such composition or it has more than one alternative. + */ +function soleAlternative(spec: OpenAPISpec, schema: Schema): Schema | undefined { + const members = schema.anyOf ?? schema.oneOf; + if (!members) return undefined; + const alternatives = members.filter((m) => !isNullMarker(m)); + return alternatives.length === 1 + ? normalize(spec, alternatives[0]) + : undefined; +} + +/** The last segment of a `$ref`, which names the schema it points to. */ +function refName(ref: string): string { + return ref.split("/").pop() || "object"; +} + +/** + * A short name for the type a schema allows: its `type`; `[item]` for an + * array; `map[string, value]` for a map; the alternatives joined by `|` for + * `anyOf`/`oneOf`; the schema's name where a `$ref` would recurse; and `any` + * for a schema that does not constrain the type. + */ +function typeLabel(spec: OpenAPISpec, schema: Schema | Reference): string { + const s = normalize(spec, schema); + if (s["x-circular-ref"]) return refName(s["x-circular-ref"]); + if (s.type === "array" || (!s.type && s.items)) { + return `[${s.items ? typeLabel(spec, s.items) : "any"}]`; + } + if (isMap(s)) { + const ap = s.additionalProperties!; + const value = + ap === true + ? "any" + : isReference(ap) + ? refName(ap.$ref) + : typeLabel(spec, ap as Schema); + return `map[string, ${value}]`; } - if (value.type === "object" || value.properties || value.allOf) return "object"; - return value.type || "object"; + if (s.type) return s.type; + const members = s.anyOf ?? s.oneOf; + if (members) { + const labels = members.flatMap((m) => { + if (isNullMarker(m)) return ["null"]; + const label = typeLabel(spec, m); + return !isReference(m) && m.nullable ? [label, "null"] : [label]; + }); + return [...new Set(labels)].join("|"); + } + if (s.properties) return "object"; + return "any"; } -function formatTypeString(schema: Schema): string { - let type = schema.type || "unknown"; +/** + * The type label for a field: the type, its format when the format says + * something about the value (or any format, with `anyFormat`), and `|null` + * when nullable. + */ +export function formatTypeString( + spec: OpenAPISpec, + schema: Schema, + anyFormat = false, +): string { + let type = typeLabel(spec, schema); - if (schema.format && semanticFormats.has(schema.format)) { + if (schema.format && (anyFormat || semanticFormats.has(schema.format))) { type = `${type} (${schema.format})`; } - if (schema.nullable) { + if (schema.nullable && !type.split("|").includes("null")) { type = `${type}|null`; } return type; } -function formatPrimitiveType(schema: Schema): string { - const parts = [schema.type || "unknown"]; +function formatPrimitiveType(spec: OpenAPISpec, schema: Schema): string { + const parts = [typeLabel(spec, schema)]; if (schema.format && semanticFormats.has(schema.format)) parts.push(`(${schema.format})`); return parts.join(" "); } diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/sections.ts b/example/_extensions/posit-dev/quarto-openapi/lib/sections.ts index de10ce7..8e1be03 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/sections.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/sections.ts @@ -15,7 +15,7 @@ import type { } from "./types.ts"; import { HTTP_METHODS, isReference } from "./types.ts"; import { resolve } from "./refs.ts"; -import { renderSchema } from "./schema.ts"; +import { attributesOf, formatTypeString, renderSchema } from "./schema.ts"; import { stripCode } from "./escape.ts"; import { autoIdentifier, @@ -23,9 +23,8 @@ import { heading, methodBadge, pathToAnchor, - listTable, - type TableRow, } from "./markdown.ts"; +import { fieldTable, type FieldRow } from "./fields.ts"; export interface Section { /** Resource name, e.g., "content", "bundles" */ @@ -523,30 +522,20 @@ function renderParameters( lines.push(""); } - const rows: TableRow[] = params.map((param) => { + const rows: FieldRow[] = params.map((param) => { const schema = param.schema ? resolve(spec, param.schema) : undefined; - - const typeParts: string[] = []; - if (schema?.type) typeParts.push(schema.type); - if (schema?.format) typeParts.push(`(${schema.format})`); - const typeStr = typeParts.length > 0 ? typeParts.join(" ") : "string"; - - const descParts: string[] = []; - if (param.description) descParts.push(param.description.trim()); - if (param.required) descParts.push("Required."); - return { - cells: [ - `\`${param.name}\``, - `\`${typeStr}\``, - descParts.join(" "), - ], + name: param.name, + depth: 0, + type: schema ? formatTypeString(spec, schema, true) : "string", + description: param.description ?? "", + attributes: attributesOf(schema ?? {}, !!param.required), }; }); - lines.push(...listTable(["Name", "Type", "Description"], rows)); + lines.push(...fieldTable(rows)); lines.push(""); } diff --git a/example/_extensions/posit-dev/quarto-openapi/lib/types.ts b/example/_extensions/posit-dev/quarto-openapi/lib/types.ts index f091379..82b582d 100644 --- a/example/_extensions/posit-dev/quarto-openapi/lib/types.ts +++ b/example/_extensions/posit-dev/quarto-openapi/lib/types.ts @@ -112,6 +112,8 @@ export interface Schema { maxLength?: number; pattern?: string; additionalProperties?: boolean | Schema | Reference; + /** Set by expandRefs on the stub that ends a circular `$ref`. */ + "x-circular-ref"?: string; } export interface Reference { diff --git a/tests/fields_test.ts b/tests/fields_test.ts new file mode 100644 index 0000000..f1af282 --- /dev/null +++ b/tests/fields_test.ts @@ -0,0 +1,91 @@ +import { test } from "node:test"; +import { assertEquals, assertStringIncludes } from "./assert.ts"; +import { + fieldTable, + type FieldRow, +} from "../_extensions/quarto-openapi/lib/fields.ts"; + +function field(overrides: Partial): FieldRow { + return { + name: "guid", + depth: 0, + type: "string", + description: "", + attributes: "", + ...overrides, + }; +} + +const HIDDEN_OPEN = '::: {.content-hidden when-format="llms-txt"}'; +const VISIBLE_OPEN = '::: {.content-visible when-format="llms-txt"}'; + +/** The table form and the `llms-txt` form, as text. */ +function forms(lines: string[]): { table: string; list: string } { + const text = lines.join("\n"); + const split = text.indexOf(VISIBLE_OPEN); + return { table: text.slice(0, split), list: text.slice(split) }; +} + +test("fieldTable: the table is hidden from llms-txt and a list stands in", () => { + const lines = fieldTable([field({ description: "The identifier." })]); + assertEquals(lines[0], HIDDEN_OPEN); + assertEquals(lines.filter((l) => l === VISIBLE_OPEN).length, 1); + assertEquals(lines.at(-1), ":::"); + const { table, list } = forms(lines); + assertStringIncludes(table, "* * `guid`\n * `string`\n * The identifier."); + assertStringIncludes(list, "- `guid` (`string`)\n\n The identifier."); +}); + +test("fieldTable: attributes follow the description as their own paragraph", () => { + const { table, list } = forms( + fieldTable([ + field({ description: "The identifier.", attributes: "Required." }), + ]), + ); + assertStringIncludes(table, " * The identifier.\n\n Required."); + assertStringIncludes(list, " The identifier.\n\n Required."); +}); + +test("fieldTable: block content stays in the cell and in the list item", () => { + const description = [ + "Accepted values:", + "", + "- `a`: first", + "- `b`: second", + "", + "```json", + "{}", + "```", + ].join("\n"); + const { table, list } = forms(fieldTable([field({ description })])); + assertStringIncludes( + table, + " * Accepted values:\n\n - `a`: first\n - `b`: second\n\n" + + " ```json\n {}\n ```", + ); + assertStringIncludes( + list, + "- `guid` (`string`)\n\n Accepted values:\n\n - `a`: first\n" + + " - `b`: second\n\n ```json\n {}\n ```", + ); +}); + +test("fieldTable: a field with no details is a bare list item", () => { + const { list } = forms(fieldTable([field({}), field({ name: "next" })])); + assertStringIncludes(list, "- `guid` (`string`)\n\n- `next` (`string`)"); +}); + +test("fieldTable: nested names keep their indentation class in the table", () => { + const { table, list } = forms( + fieldTable([ + field({ name: "owner", type: "object" }), + field({ name: "owner.guid", depth: 1 }), + ]), + ); + assertStringIncludes(table, "* * [`owner.guid`]{.schema-nest-1}"); + assertStringIncludes(list, "- `owner.guid` (`string`)"); +}); + +test("fieldTable: no rows, no table", () => { + assertEquals(fieldTable([]), []); +}); diff --git a/tests/markdown_test.ts b/tests/markdown_test.ts index 304ebf7..e20ec5e 100644 --- a/tests/markdown_test.ts +++ b/tests/markdown_test.ts @@ -92,6 +92,14 @@ test("listTable: a cell holding two blocks emits a loose list", () => { assertStringIncludes(output, "* * `id`\n\n * `string`\n\n * First paragraph.\n\n Second paragraph."); }); +test("listTable: an empty cell keeps the row tight", () => { + const rows: TableRow[] = [{ cells: ["`id`", "`string`", ""] }]; + + const output = listTable(["Name", "Type", "Description"], rows).join("\n"); + + assertStringIncludes(output, "* * `id`\n * `string`\n * \n"); +}); + test("listTable: cell text is emitted verbatim, whatever its length", () => { const rows: TableRow[] = [ { cells: ["`temp_ticket`", "`string`", "See [ref](#get-/v1/some/path) for details."] }, diff --git a/tests/quarto_render_test.ts b/tests/quarto_render_test.ts index 3d6769e..51f4bfa 100644 --- a/tests/quarto_render_test.ts +++ b/tests/quarto_render_test.ts @@ -18,6 +18,7 @@ import { join } from "node:path"; import { promisify } from "node:util"; import { assert, assertEquals, assertStringIncludes } from "./assert.ts"; import { listTable } from "../_extensions/quarto-openapi/lib/markdown.ts"; +import { fieldTable } from "../_extensions/quarto-openapi/lib/fields.ts"; import { escapePathBracesOutsideCode } from "../_extensions/quarto-openapi/lib/escape.ts"; const execFileAsync = promisify(execFile); @@ -56,6 +57,30 @@ async function render(markdown: string): Promise { } } +/** + * Render `markdown` as the only page of a website with `llms-txt` on, and + * return the page's HTML and the `.llms.md` Quarto derives from it. + */ +async function renderSite( + markdown: string, +): Promise<{ html: string; llms: string }> { + const dir = await mkdtemp(join(tmpdir(), "quarto-openapi-llms-")); + try { + await writeFile( + join(dir, "_quarto.yml"), + "project:\n type: website\nwebsite:\n title: Test\n llms-txt: true\n", + ); + await writeFile(join(dir, "index.qmd"), markdown); + await execFileAsync("quarto", ["render"], { cwd: dir }); + return { + html: await readFile(join(dir, "_site", "index.html"), "utf8"), + llms: await readFile(join(dir, "_site", "index.llms.md"), "utf8"), + }; + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + /** The first `` element in `html`, which is the one under test. */ function tableOf(html: string): string { const table = html.match(//)?.[0]; @@ -149,3 +174,72 @@ test("Quarto renders a fenced cell and escaped braces verbatim", { skip }, async assertStringIncludes(table, "GET /v1/widgets/{widget-id}/keys/{key2}."); assertEquals(table.includes("\\{"), false, `braces left escaped:\n${table}`); }); + +test("A field table survives into llms-txt output", { skip }, async () => { + // Quarto converts the rendered HTML to GFM for `.llms.md`, and Pandoc writes + // `[TABLE]` for any table with block content in a cell. + const markdown = [ + "---", + "title: Fields", + "---", + "", + ...fieldTable([ + { + name: "guid", + depth: 0, + type: "string", + description: "The identifier.\n\nAssigned by the server.", + attributes: "Required. Example: `abc`.", + }, + { + name: "mode", + depth: 0, + type: "string", + description: "How it runs:\n\n- `fast`: skips checks\n- `safe`: checks first", + attributes: "", + }, + { + name: "note", + depth: 0, + type: "string", + description: "Line one`
`{=html}line two.", + attributes: "", + }, + { + name: "owner.name", + depth: 1, + type: "string", + description: "", + attributes: "Read-only.", + }, + ]), + "", + ].join("\n"); + + const { html, llms } = await renderSite(markdown); + + assertEquals(llms.includes("[TABLE]"), false, `table dropped:\n${llms}`); + assertStringIncludes( + llms, + "- `guid` (`string`)\n\n The identifier.\n\n Assigned by the server." + + "\n\n Required. Example: `abc`.", + ); + assertStringIncludes( + llms, + "- `mode` (`string`)\n\n How it runs:\n\n - `fast`: skips checks\n" + + " - `safe`: checks first", + ); + // Pandoc writes a hard line break as trailing spaces or as a backslash, + // depending on its version. + assert( + /- `note` \(`string`\)\n\n {2}Line one(?: {2,}|\\)\n {2}line two\./.test(llms), + `line break lost:\n${llms}`, + ); + assertStringIncludes(llms, "- `owner.name` (`string`)\n\n Read-only."); + + // The page keeps the table, with the list inside its row, and nothing of + // the llms-txt form. + const table = tableOf(html); + assertStringIncludes(table, "
  • fast: skips checks
  • "); + assertEquals(html.includes("(string)"), false, html); +}); diff --git a/tests/render_test.ts b/tests/render_test.ts index c921f9b..c3b374d 100644 --- a/tests/render_test.ts +++ b/tests/render_test.ts @@ -170,6 +170,45 @@ test("renderSection: parameters rendered as grid table", () => { assertStringIncludes(output, "Max items"); }); +test("renderSection: parameter types and attributes come from the schema", () => { + const spec = minimalSpec({ + "/v1/pets": { + get: { + operationId: "listPets", + summary: "List pets", + parameters: [ + { + name: "id", + in: "query", + schema: { anyOf: [{ type: "integer" }, { type: "string" }] }, + }, + { + name: "tag", + in: "query", + required: true, + schema: { oneOf: [{ type: "string" }, { nullable: true }] }, + }, + { + name: "size", + in: "query", + schema: { type: "integer", format: "int64", enum: [1, 2], default: 1 }, + }, + ], + responses: { "200": { description: "OK" } }, + }, + }, + }); + + const output = renderedSection(spec); + + assertStringIncludes(output, "* * `id`\n * `integer|string`"); + assertStringIncludes(output, "* * `tag`\n * `string|null`\n * Required."); + assertStringIncludes( + output, + "* * `size`\n * `integer (int64)`\n * Default: `1`. Enum: `1`, `2`.", + ); +}); + test("renderSection: parameters heading has scoped anchor ID", () => { const spec = minimalSpec({ "/v1/pets": { diff --git a/tests/schema_test.ts b/tests/schema_test.ts index e43d3b3..4b099f0 100644 --- a/tests/schema_test.ts +++ b/tests/schema_test.ts @@ -1,6 +1,7 @@ import { test } from "node:test"; import { assert, + assertFalse, assertEquals, assertStringIncludes, } from "./assert.ts"; @@ -429,3 +430,212 @@ test("renderSchema: enum values go through the same formatter as defaults", () = assertStringIncludes(output, 'Enum: `""`, `fast`, `null`'); }); + +test("renderSchema: a nullable reference is typed and expanded", () => { + const spec = specWithSchemas({ + Source: { + type: "object", + required: ["choice"], + properties: { + choice: { type: "string", enum: ["git", "none"] }, + gitUrl: { type: "string" }, + }, + }, + Values: { + type: "object", + required: ["source"], + properties: { + source: { + description: "Where the source lives.", + anyOf: [ + { $ref: "#/components/schemas/Source" } as unknown as Schema, + { nullable: true }, + ], + }, + }, + }, + }); + // Through a $ref, as request and response bodies usually are: every + // nested $ref is expanded before the table is built. + const output = rendered( + spec, + { $ref: "#/components/schemas/Values" } as unknown as Schema, + ); + + assertStringIncludes( + output, + "* * `source`\n\n * `object|null`\n\n * Where the source lives.\n\n Required.", + ); + assertStringIncludes(output, "* * [`source.choice`]{.schema-nest-1}"); + assertStringIncludes(output, "* * [`source.gitUrl`]{.schema-nest-1}"); + assertFalse(output.includes("unknown"), output); +}); + +test("renderSchema: alternatives are joined with |", () => { + const output = rendered(specWithSchemas(), { + type: "object", + properties: { + id: { anyOf: [{ type: "string" }, { type: "integer" }] }, + label: { oneOf: [{ type: "string" }, { nullable: true }] }, + pet: { + oneOf: [ + { type: "object", properties: { purrs: { type: "boolean" } } }, + { type: "object", properties: { barks: { type: "boolean" } } }, + ], + }, + }, + }); + + assertStringIncludes(output, "* * `id`\n * `string|integer`"); + assertStringIncludes(output, "* * `label`\n * `string|null`"); + assertStringIncludes(output, "* * `pet`\n * `object`"); + // Neither alternative is listed as if it were the only one. + assertFalse(output.includes("pet.purrs"), output); +}); + +test("renderSchema: a schema with no type constraint is any", () => { + const output = rendered(specWithSchemas(), { + type: "object", + properties: { value: { description: "Any JSON value." } }, + }); + assertStringIncludes(output, "* * `value`\n * `any`"); +}); + +test("renderSchema: a recursive nullable reference ends at the cycle", () => { + const spec = specWithSchemas({ + Expr: { + type: "object", + properties: { + operator: { type: "string" }, + operands: { + type: "array", + items: { $ref: "#/components/schemas/Expr" } as unknown as Schema, + }, + }, + }, + Field: { + type: "object", + properties: { + visible: { + anyOf: [ + { $ref: "#/components/schemas/Expr" } as unknown as Schema, + { nullable: true }, + ], + }, + }, + }, + }); + const output = rendered( + spec, + { $ref: "#/components/schemas/Field" } as unknown as Schema, + ); + + assertStringIncludes(output, "* * `visible`\n * `object|null`"); + assertStringIncludes(output, "[`visible.operator`]{.schema-nest-1}"); + // The cycle ends where the reference repeats, named by the schema. + assertStringIncludes( + output, + "* * [`visible.operands`]{.schema-nest-1}\n * `[Expr]`", + ); +}); + +test("renderSchema: allOf around a primitive keeps its type and enum", () => { + const spec = specWithSchemas({ + Status: { type: "string", enum: ["on", "off"] }, + }); + const output = rendered(spec, { + type: "object", + required: ["status"], + properties: { + status: { + description: "Current status.", + allOf: [{ $ref: "#/components/schemas/Status" } as unknown as Schema], + }, + }, + }); + + assertStringIncludes(output, "* * `status`\n\n * `string`"); + assertStringIncludes(output, "Current status.\n\n Required. Enum: `on`, `off`."); +}); + +test("renderSchema: object rows carry attributes and nullability", () => { + const spec = specWithSchemas({ + Owner: { type: "object", properties: { guid: { type: "string" } } }, + }); + const owner = { $ref: "#/components/schemas/Owner" } as unknown as Schema; + const output = rendered(spec, { + type: "object", + required: ["owner"], + properties: { + owner, + backup: { allOf: [owner], nullable: true }, + }, + }); + + assertStringIncludes(output, "* * `owner`\n * `object`\n * Required."); + assertStringIncludes(output, "* * `backup`\n * `object|null`"); + assertStringIncludes(output, "[`backup.guid`]{.schema-nest-1}"); +}); + +test("renderSchema: alternative members contribute their own null", () => { + const output = rendered(specWithSchemas(), { + type: "object", + properties: { + id: { anyOf: [{ type: "string", nullable: true }, { type: "integer" }] }, + tags: { + anyOf: [{ type: "array", items: { type: "string" } }, { nullable: true }], + }, + counts: { + type: "object", + additionalProperties: { anyOf: [{ type: "string" }, { type: "integer" }] }, + }, + }, + }); + + assertStringIncludes(output, "* * `id`\n * `string|null|integer`"); + assertStringIncludes(output, "* * `tags`\n * `[string]|null`"); + assertStringIncludes(output, "* * `counts`\n * `map[string, string|integer]`"); +}); + +test("renderSchema: a nullable array of references lists the item fields", () => { + const spec = specWithSchemas({ + Tag: { type: "object", properties: { label: { type: "string" } } }, + }); + const output = rendered(spec, { + type: "object", + properties: { + tags: { + anyOf: [ + { + type: "array", + items: { $ref: "#/components/schemas/Tag" } as unknown as Schema, + }, + { nullable: true }, + ], + }, + }, + }); + + assertStringIncludes(output, "* * `tags`\n * `[object]|null`"); + assertStringIncludes(output, "[`tags[].label`]{.schema-nest-1}"); +}); + +test("renderSchema: a top-level oneOf renders each alternative", () => { + const spec = specWithSchemas({ + Cat: { type: "object", properties: { purrs: { type: "boolean" } } }, + Dog: { type: "object", properties: { barks: { type: "boolean" } } }, + }); + const output = rendered(spec, { + oneOf: [ + { $ref: "#/components/schemas/Cat" } as unknown as Schema, + { $ref: "#/components/schemas/Dog" } as unknown as Schema, + { nullable: true }, + ], + }); + + const purrs = output.indexOf("`purrs`"); + const or = output.indexOf("\nOr:\n"); + const barks = output.indexOf("`barks`"); + assert(purrs > 0 && or > purrs && barks > or, output); + assertStringIncludes(output, "Or `null`."); +});