import {OpenAPIV3} from "openapi-types"; import { CodeBlockTab, DefinitionProperty, Example, ExampleGroup, Reference, SymbolDef, UniformPluginArgs, OpenAPIReferenceContext } from "@xyd-js/uniform"; import {XDocs, XDocsSidebar, XDocsPage, XDocsMeta, XDocsOperationMeta, XDocsSchemaMeta} from "./types"; import {componentPagePath, explicitPagePath, kebabCase, operationPagePath} from "./pagePaths"; import {DEFAULT_OBJECTS_LAYOUT, objectsGroupOf, objectsLayoutOf, operationPathsOf} from "../const"; import {objectTypeConstant} from "../component-links"; import type {ObjectsLayout, uniformOasOptions} from "../types"; interface NavigationGroup { id: string title: string beta: boolean } type ComponentMeta = XDocsSchemaMeta type ExtensionSchema = OpenAPIV3.Document & { "x-docs"?: XDocs } type NavigationGroupMap = { [id: string]: NavigationGroup & { index: number } } interface OperationExample { request: string | { [lang: string]: string } response: string | { [lang: string]: string } } type Examples = string | OperationExample | OperationExample[] export function uniformPluginXDocsSidebar({ references, defer, }: UniformPluginArgs) { let schema: ExtensionSchema | undefined const refByOperationId: { [key: string]: Reference } = {} const refByComponentSchema: { [key: string]: Reference } = {} // `x-docs.hidden` refs (operations and component schemas alike) — dropped // from the GENERATED navigation in the defer below. An `x-docs.sidebar` // that lists one explicitly still shows it: the sidebar is a complete // enumeration and wins over the per-page flag. const hiddenRefs = new Set() // The converter options travel on the reference list (`__internal_options`, // set by the converter and by the native shim alike): `objectsGroup` names // the object pages' group, `objectsLayout` says where an object page with // a resource group goes, `operationPaths` how a page without an // `x-docs.path` gets its canonical (see `uniformOasOptions`). // @ts-ignore const options: uniformOasOptions | undefined = typeof references.__internal_options === "function" // @ts-ignore ? references.__internal_options() : undefined const objectsGroup = objectsGroupOf(options) const objectsLayout = objectsLayoutOf(options) const derivePaths = operationPathsOf(options) === "title" defer(() => { if (!schema) { return {} } // @ts-ignore if (typeof references.__internal_options === "function") { // @ts-ignore const options = references.__internal_options() if (options?.regions?.length) { // A page's own rows: the per-page conversion covers one region, // so the navigation is not this pass's business — but the links // on the page still have to land on pages that exist, and a // one-page reference list cannot say which do. The document can. if (Array.isArray(references)) { relinkSchemaLinks(references, schemaPageLinks(schema, derivePaths)) } return {} } } const output: Reference[] = [] const xDocs = schema["x-docs"] if (!xDocs?.sidebar) { // No sidebar: the generated navigation, minus the hidden refs — and, // under the grouped objects layout, the objects group's own order. // Two pages at one path (`x-docs.path`, or two summaries that // derive the same canonical) are an error here, naming both. if (Array.isArray(references)) { let kept = hiddenRefs.size ? references.filter(ref => !hiddenRefs.has(ref)) : [...references] if (objectsLayout === "grouped") { kept = orderObjectsGroup(kept) } checkPagePaths(kept) references.length = 0 references.push(...kept) relinkSchemaLinks(references, pageLinksOf(references)) } return {} } const navigationMap: NavigationGroupMap = {} // Process sidebar groups for (let i = 0; i < xDocs.sidebar.length; i++) { const navGroup: XDocsSidebar = xDocs.sidebar[i] if (!navGroup) { continue } const uniqueKey = `${navGroup.group}-${i}` navigationMap[uniqueKey] = { id: navGroup.group, title: navGroup.group, beta: false, index: i } } // Process each group and its nested pages for (let i = 0; i < xDocs.sidebar.length; i++) { const group: XDocsSidebar = xDocs.sidebar[i] const uniqueKey = `${group.group}-${i}` const navGroup = navigationMap[uniqueKey] if (!navGroup) { console.warn(`No navigation group found for group: ${group.group}`) continue } if (!Array.isArray(group.pages)) { continue } // Process nested groups and pages // `?? ""` matches the Rust port (crates/apitoolchain_openapi/src/xdocs.rs:141, // `.unwrap_or("")`). Without it, an x-docs sidebar entry with `pages:` but no // `group:` put `undefined` into the group path; pluginNavigation uses that value // as an OBJECT KEY, and `Object.keys({[undefined]: 1})` is `["undefined"]` — the // STRING. A truthy string renders a real header, so the sidebar showed a group // literally titled "undefined" where a header-less separator was intended. // Reproducer: examples/openapi/todos-api.yaml:25. processGroupPages(xDocs, group.pages, [group.group ?? ""], navGroup, output) } // Clear references and set from output if (Array.isArray(references)) { references.length = 0 references.push(...output) relinkSchemaLinks(references, pageLinksOf(references)) } else { references = output[0] || references } return {} }) function processGroupPages( xDocs: XDocs, pages: (XDocsSidebar | XDocsPage)[], groupPath: string[], navGroup: NavigationGroup & { index: number }, output: Reference[], parentPath?: string ) { for (const page of pages) { if ('pages' in page && Array.isArray(page.pages)) { // This is a nested group processGroupPages(xDocs, page.pages, [...groupPath, page.group ?? ""], navGroup, output, page.path) } else if ('type' in page && 'key' in page) { // This is a page processPage(xDocs, page, groupPath, navGroup, output, parentPath) } } } function processPage( xDocs: XDocs, page: XDocsPage, groupPath: string[], navGroup: NavigationGroup & { index: number }, output: Reference[], parentPath?: string ) { let uniformRef: Reference | undefined switch (page.type) { case "endpoint": { const operationRef = refByOperationId[page.key] if (!operationRef) { console.warn(`No operation found for key: ${page.key} in group ${groupPath.join('/')}`) return } uniformRef = operationRef break } case "object": { const componentRef = refByComponentSchema[page.key] if (!componentRef) { console.warn(`No component schema found for key: ${page.key} in group ${groupPath.join('/')}`) return } const selector = componentRef.__UNSAFE_selector if (!selector || typeof selector !== "function") { return } const component = selector("[component]") as OpenAPIV3.SchemaObject | undefined if (!component) { console.warn(`No component schema found for key: ${page.key} in group ${groupPath.join('/')}`) return } // The same lookup as the generated navigation (on the schema // itself, else on the first `allOf` member that carries one), // so a listed page reads its `name` from the same place in // both modes. A page without any `x-docs` keeps its defaults // — the sidebar lists it, so it exists. const componentMeta: ComponentMeta | undefined = componentXDocs(component) uniformRef = componentRef if (!componentMeta) { break } componentRef.title = componentMeta.name || componentRef.title if (componentMeta.example) { const exampleGroups = oasXDocsExamples(componentMeta.example) uniformRef.examples = { groups: exampleGroups, } } break } default: { console.warn(`Unknown page type: ${page.type} in group ${groupPath.join('/')}`) return } } if (!uniformRef) { return } const canonical = sidebarPageCanonical( xDocs, page, parentPath, (uniformRef.context as OpenAPIReferenceContext | undefined)?.path ) if (canonical !== undefined) { uniformRef.canonical = canonical } if (!uniformRef.context) { uniformRef.context = {} } uniformRef.context.group = groupPath output.push(uniformRef) } return function pluginXDocsSidebarInner(ref: Reference) { // @ts-ignore const selector = ref.__UNSAFE_selector if (!selector || typeof selector !== "function") { return } const oapSchema = selector("[schema]") if (!oapSchema) { return } schema = oapSchema const ctx = ref.context as OpenAPIReferenceContext | undefined if (ctx?.componentSchema) { refByComponentSchema[ctx.componentSchema] = ref // The schema's own `x-docs` — honoured here, outside sidebar mode, // exactly like an operation's (`name` → title, `group` → sidebar // group, `hidden`). The sidebar pass re-reads `name` for the object // pages it lists. const component = selector("[component]") as OpenAPIV3.SchemaObject | undefined const meta = componentXDocs(component) if (meta && applyDocsMeta(ref, meta, objectsGroup, objectsLayout)) { hiddenRefs.add(ref) } // The page's path: its `x-docs.path`, else (title mode) the one // derived from its group and label. The links are relinked from the // final list in the defer, so they follow. const canonical = componentPageCanonical(component, ctx.componentSchema, meta, derivePaths) if (canonical !== undefined) { ref.canonical = canonical } } const methodPath = selector("[method] [path]") as OpenAPIV3.OperationObject | undefined if (!methodPath) { return } const oapMethod = selector("[method]") if (!oapMethod) { return } const operationId = methodPath.operationId if (operationId) { refByOperationId[operationId] = ref } const methodId = (oapMethod?.httpMethod?.toUpperCase() + " " + oapMethod?.path || "").trim() if (methodId) { refByOperationId[methodId] = ref } const meta = (methodPath as any)["x-docs"] as XDocsOperationMeta | undefined if (meta) { if (applyDocsMeta(ref, meta, undefined)) { hiddenRefs.add(ref) } if (!ref.description) { ref.description = methodPath.summary || "" } if (meta.examples) { const exampleGroups = oasXDocsExamples(meta.examples as Examples) ref.examples = { groups: exampleGroups, } } if (meta.returns) { if (ref.definitions?.length) { ref.definitions[ref.definitions.length - 1] = { title: ref.definitions[ref.definitions.length - 1].title, description: meta.returns, properties: [] } } else { ref.definitions = [ { title: "Response", description: meta.returns, properties: [] } ] } } } // The page's path: its `x-docs.path`, else (title mode) the one derived // from its group (set above) and its verb-first summary. const canonical = operationPageCanonical(ref, methodPath, meta, derivePaths) if (canonical !== undefined) { ref.canonical = canonical } } } /** A component page's canonical when something other than the converter * decides it: its `x-docs.path`, else — under `operationPaths: "title"` — the * derived `/