Files
supabase/apps/docs/internals/api-request-body-markdown.ts
Alexis Aguilar 6ac0f3f231 fix(docs): include request bodies in the Management API markdown reference (#54343)
## Problem

Agents can't find request body fields for Management API endpoints. In
an eval for the access control guide
([DOCS-1489](https://linear.app/supabase/issue/DOCS-1489)), an agent
read the [Create organization
invitations](https://supabase.com/docs/reference/api/v2-create-organization-invitations)
page and concluded the body accepts only an email. It refused to invite
someone scoped to one project, even though the API accepts `role` and
`projects`.

Reference pages have no `.md` version. Their markdown 404 points agents
to the markdown reference (`llms/api.txt`), which lists path and query
parameters but no request body for any endpoint.

Resolves part of
[DOCS-1823](https://linear.app/supabase/issue/DOCS-1823).

## Solution

Each endpoint with a request body gets a **Request body** section in the
markdown reference. It lists every field as a nested list with its type,
whether it's required, its description, accepted values, defaults, and
constraints. Unions list each option by name, and map-like objects show
the shape of their values.

This changes only the generated markdown. Reference pages render the
same as before.

Reference pages don't have their own `.md` versions yet. That's tracked
in [DOCS-1332](https://linear.app/supabase/issue/DOCS-1332). The new
renderer takes one endpoint's request body and returns markdown, so a
per-page generator can reuse it.

## Follow-ups

- **Reference page HTML (rest of DOCS-1823):** nested schema fields
still reach the HTML only after someone opens their control. Moving
these controls to native `<details>` also needs three fixes found in
review:
- A union option puts an `<li>` inside another `<li>`, which breaks the
list once the content is in the HTML.
- The **Items** control for an array of union items, such as the
notebook `cells` array, opens an empty panel.
- The new summary styles repeat the current trigger's styles. They
should share one base.
- **Parameters:** path and query parameters still use the older one-line
format, so their accepted values don't appear in the markdown reference.
For example, `continent` on the available regions endpoint lists no
values.
- **Shared schema helpers:** the renderer copies `asSchemaArray` from
`Reference.ui.tsx` and adds its own schema type. Sharing both through
`Reference.api.utils.ts` keeps the HTML and the markdown in step.

## Review category (docs PRs only)

- [ ] Critical: needs a review as soon as possible
- [ ] Urgent: the feature ships soon, or it's blocking something else
- [x] Moderate: good to have soon, not urgent
- [ ] Low: get to it when you can

## Review instructions

1. Open the [Management API markdown reference on the
preview](https://docs-git-alexisa-docs-1823-supabase.vercel.app/docs/markdown/reference/api.md).
On production, the same file is served at `/llms/api.txt`.
2. Under **Creates organization invitations**, see the **Request body**
section with `data`, `type`, `attributes`, `email`, `role`, `projects`,
and `require_sso`.
3. Under **Assign or change an organization member role**, see
`data.attributes.role` and `projects`.

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
2026-12-01 11:15:33 -07:00

244 lines
8.5 KiB
TypeScript

type JsonSchema = {
$ref?: string
type?: string
title?: string
description?: string
enum?: Array<unknown>
const?: unknown
default?: unknown
format?: string
items?: JsonSchema
properties?: Record<string, JsonSchema>
additionalProperties?: boolean | JsonSchema
propertyNames?: JsonSchema
required?: Array<string>
allOf?: Array<JsonSchema>
anyOf?: Array<JsonSchema>
oneOf?: Array<JsonSchema>
deprecated?: boolean
nullable?: boolean
minimum?: number
maximum?: number
exclusiveMinimum?: number | boolean
exclusiveMaximum?: number | boolean
minLength?: number
maxLength?: number
minItems?: number
maxItems?: number
pattern?: string
}
export type RequestBody = {
required?: boolean
content?: Record<string, { schema?: JsonSchema }>
}
const INDENT = ' '
function asArray(value: unknown): Array<JsonSchema> {
if (Array.isArray(value)) return value
if (value && typeof value === 'object') return [value as JsonSchema]
return []
}
function isNullType(schema: JsonSchema): boolean {
return schema.type === 'null'
}
function combinator(
schema: JsonSchema
): { label: string; options: Array<JsonSchema>; nullable: boolean } | null {
const found = schema.allOf
? { label: 'All of the following', options: asArray(schema.allOf) }
: schema.anyOf
? { label: 'Any of the following', options: asArray(schema.anyOf) }
: schema.oneOf
? { label: 'One of the following', options: asArray(schema.oneOf) }
: null
if (!found) return null
const options = found.options.filter((option) => !isNullType(option))
return { ...found, options, nullable: options.length < found.options.length }
}
function withSingleOption(schema: JsonSchema): JsonSchema {
const options = combinator(schema)
if (options?.options.length !== 1) return schema
return { ...options.options[0], ...schema, allOf: undefined, anyOf: undefined, oneOf: undefined }
}
function mapValueSchema(schema: JsonSchema): JsonSchema | null {
const value = schema.additionalProperties
return value && typeof value === 'object' && Object.keys(value).length ? value : null
}
function isNullable(schema: JsonSchema): boolean {
return Boolean(schema.nullable || combinator(schema)?.nullable)
}
function typeName(schema: JsonSchema): string {
if (schema.$ref) return schema.$ref.split('/').pop() || 'object'
const options = combinator(schema)
if (options) {
return Array.from(new Set(options.options.map(typeName))).join(' or ')
}
if (schema.type === 'array') {
return schema.items ? `array of ${typeName(schema.items)}` : 'array'
}
const mapValue = mapValueSchema(schema)
if (mapValue && !schema.properties) return `object of ${typeName(mapValue)}`
return schema.type ?? (schema.properties || mapValue ? 'object' : 'any')
}
function inlineCode(text: string): string {
const longestRun = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length))
const fence = '`'.repeat(longestRun + 1)
const padding = longestRun ? ' ' : ''
return `${fence}${padding}${text}${padding}${fence}`
}
function formatValue(value: unknown): string {
return inlineCode(typeof value === 'string' && value !== '' ? value : JSON.stringify(value))
}
function isRealBound(value: number | undefined): value is number {
return value !== undefined && Math.abs(value) < Number.MAX_SAFE_INTEGER
}
function bounds(schema: JsonSchema): Array<string> {
const notes: Array<string> = []
if (isRealBound(schema.minimum)) {
notes.push(`${schema.exclusiveMinimum === true ? 'greater than' : 'minimum'} ${schema.minimum}`)
}
if (typeof schema.exclusiveMinimum === 'number') {
notes.push(`greater than ${schema.exclusiveMinimum}`)
}
if (isRealBound(schema.maximum)) {
notes.push(`${schema.exclusiveMaximum === true ? 'less than' : 'maximum'} ${schema.maximum}`)
}
if (typeof schema.exclusiveMaximum === 'number') {
notes.push(`less than ${schema.exclusiveMaximum}`)
}
return notes
}
function constraints(schema: JsonSchema): Array<string> {
const notes: Array<string> = []
if (schema.format) notes.push(`format ${inlineCode(schema.format)}`)
notes.push(...bounds(schema))
if (schema.minLength !== undefined) notes.push(`min length ${schema.minLength}`)
if (schema.maxLength !== undefined) notes.push(`max length ${schema.maxLength}`)
if (schema.minItems !== undefined) notes.push(`min items ${schema.minItems}`)
if (schema.maxItems !== undefined) notes.push(`max items ${schema.maxItems}`)
if (schema.pattern) notes.push(`pattern ${inlineCode(schema.pattern)}`)
if (schema.propertyNames?.pattern) {
notes.push(`key pattern ${inlineCode(schema.propertyNames.pattern)}`)
}
if (schema.propertyNames?.enum) {
notes.push(`keys ${schema.propertyNames.enum.map(formatValue).join(', ')}`)
}
if (schema.additionalProperties === false) notes.push('no other keys')
if (schema.type === 'array' && schema.items) {
const itemLimits = constraints(schema.items)
if (itemLimits.length) notes.push(`each item: ${itemLimits.join(', ')}`)
}
return notes
}
function enumValues(schema: JsonSchema): Array<unknown> | undefined {
if (schema.enum) return schema.enum
if (schema.const !== undefined) return [schema.const]
if (schema.type === 'array' && schema.items) return enumValues(schema.items)
return undefined
}
function indentContinuation(text: string, indent: string): string {
return text
.trim()
.split('\n')
.map((line, index) => (index === 0 || !line.trim() ? line : `${indent}${line}`))
.join('\n')
}
function renderChildren(rawSchema: JsonSchema, depth: number): Array<string> {
const schema = withSingleOption(rawSchema)
const options = combinator(schema)
if (options) {
return [
`${INDENT.repeat(depth)}- ${options.label}:`,
...options.options.flatMap((option, index) => [
`${INDENT.repeat(depth + 1)}- Option ${index + 1}${option.title ? `: ${option.title}` : ''} (${typeName(option)})${notesFor(option, INDENT.repeat(depth + 2))}`,
...renderChildren(option, depth + 2),
]),
]
}
if (schema.type === 'array' && schema.items) {
return renderChildren(schema.items, depth)
}
const lines = Object.entries(schema.properties ?? {}).flatMap(([name, property]) => [
renderProperty(name, property, schema.required?.includes(name) ?? false, depth),
...renderChildren(property, depth + 1),
])
const mapValue = mapValueSchema(schema)
if (mapValue) {
lines.push(
`${INDENT.repeat(depth)}- Any other key (${typeName(mapValue)}${
isNullable(mapValue) ? ', nullable' : ''
})${notesFor(mapValue, INDENT.repeat(depth + 1))}`,
...renderChildren(mapValue, depth + 1)
)
}
return lines
}
function notesFor(rawSchema: JsonSchema, continuationIndent: string): string {
const schema = withSingleOption(rawSchema)
const notes: Array<string> = []
const values = enumValues(schema)
if (values?.length) notes.push(`Accepted values: ${values.map(formatValue).join(', ')}.`)
if (schema.default !== undefined) notes.push(`Default: ${formatValue(schema.default)}.`)
const limits = constraints(schema)
if (limits.length) notes.push(`Constraints: ${limits.join(', ')}.`)
const description = schema.description?.trim()
? indentContinuation(schema.description, continuationIndent)
: ''
const separator = description.includes('\n')
? `\n\n${continuationIndent}`
: /[.!?:]$/.test(description)
? ' '
: '. '
const text = [description, notes.join(' ')].filter(Boolean).join(separator)
return text ? `: ${text}` : ''
}
function renderProperty(
name: string,
schema: JsonSchema,
required: boolean,
depth: number
): string {
const details = [typeName(schema), required ? 'required' : 'optional']
if (schema.deprecated) details.push('deprecated')
if (isNullable(schema)) details.push('nullable')
return `${INDENT.repeat(depth)}- ${inlineCode(name)} (${details.join(', ')})${notesFor(schema, INDENT.repeat(depth + 1))}`
}
export function renderRequestBodyMarkdown(requestBody: RequestBody | undefined): string | null {
const bodies = Object.entries(requestBody?.content ?? {}).flatMap(([contentType, value]) =>
value?.schema ? [{ contentType, schema: value.schema }] : []
)
if (!bodies.length) return null
const blocks = bodies.map(({ contentType, schema }) => {
const summary = `Content type ${inlineCode(contentType)} (${typeName(schema)}${
requestBody?.required ? ', required' : ''
})${notesFor(schema, '')}`
return [summary, renderChildren(schema, 0).join('\n')].filter(Boolean).join('\n\n')
})
return `### Request body\n\n${blocks.join('\n\n')}`
}