import { downgradeSpecV31ToV30, downgradeSpecV32ToV31 } from '@openapi-spec/downgrader' import { Router } from '@openapi-spec/router' import { COMMON_ERROR_STATUSES } from '@orpc/client' import type { AnyProcedureContract, AnySchema, RouterContract } from '@orpc/contract' import type { JsonSchema, JsonSchemaConverter, JsonSchemaConverterDirection, } from '@orpc/json-schema' import { combineJsonSchemasWithComposition, DelegatingJsonSchemaConverter, hoistRecursiveRefToDef, StandardJsonSchemaConverter, } from '@orpc/json-schema' import type { AnyProcedure, AnyRouter } from '@orpc/server' import { walkProcedureContractsAsync } from '@orpc/server' import type { Public, Value } from '@orpc/shared' import { clone, mergeHttpPath, pathToHttpPath, toArray, value } from '@orpc/shared' import { DEFAULT_OPENAPI_METHOD } from './constants' import type { OpenAPIMeta } from './meta' import { getOpenAPIMeta } from './meta' import { OpenAPIComponentRegistry } from './openapi-generator-components' import type { OpenAPIErrorBodyDefinition, OpenAPIOperationContext, } from './openapi-generator-operation' import { buildErrorResponse, buildRequest, buildSuccessResponse, OpenAPIGeneratorError, toOpenAPIPath, } from './openapi-generator-operation' import { OpenAPIJsonSerializer } from './openapi-json-serializer' import type { OpenAPIDocument, OpenAPIV3_2, OpenAPIVersion } from './types' import { getDynamicPathParams } from './utils' export { OpenAPIGeneratorError } from './openapi-generator-operation' export type { OpenAPIErrorBodyDefinition } from './openapi-generator-operation' export interface OpenAPIGeneratorOptions { converters?: JsonSchemaConverter[] | undefined /** * The serializer used to serialize the generated OpenAPI documentation */ serializer?: Public | undefined } export interface OpenAPIGeneratorGenerateOptions { /** * The OpenAPI version of the generated document. * The document is generated as OpenAPI 3.2 and downgraded when an older version is requested. * The minor version selects the conversion, the document carries the exact value, such as `3.1.0`. * * @default '3.2.0' */ version?: TVersion | undefined /** * OpenAPI 3.2 document fields to start from, such as `info`, `servers`, or `components`. * They are downgraded with the rest of the document when an older `version` is requested. * The `openapi` field is derived from `version`. */ base?: Partial> | undefined /** * Root-level `$defs` are always moved into `components.schemas`. * Use this to customize the component name of a hoisted def. * * @remarks * - Characters OpenAPI does not allow in component keys (anything but `a-z`, `A-Z`, `0-9`, `.`, `_`, `-`) * are replaced by `_` in the returned name, e.g. `User Profile` becomes `User_Profile`. * - The returned name is a preference, conflicting names are still postfixed (`Planet`, `PlanetInput`, `Planet2`, ...). * * @default defName => defName */ componentName?: ((defName: string, defSchema: JsonSchema) => string) | undefined /** * Filter procedures. Return `false` to exclude a procedure from the OpenAPI specification. * * @default true */ filter?: | Value | undefined /** * Define a custom JSON schema for the error response body when using * type-safe errors. Helps align ORPC error formatting with existing API * response standards or conventions. * * @remarks * - Return `defaultSchema()` to keep the default schema, or `null | undefined` to document an empty body, matching an `errorResponseBodyEncoder` that returns `undefined`. * - The schema is an OpenAPI 3.2 Schema Object, it is downgraded with the rest of the document when an older `version` is requested. */ errorResponseBodySchema?: | Value< JsonSchema | null | undefined, [ definedErrors: OpenAPIErrorBodyDefinition[], status: number, defaultSchema: () => JsonSchema, ] > | undefined /** * Media type of error responses in the generated document, e.g. `application/problem+json`. * Should match the handler's `errorResponseContentType`. * * @default 'application/json' */ errorResponseContentType?: string | undefined /** * Mapping ORPCError Code -> HTTP Status Code * Codes missing from it fall back to `DEFAULT_ERROR_STATUS` (400). * * @default COMMON_ERROR_STATUSES */ errorStatuses?: Record | undefined } /** * Generates an OpenAPI document from a contract or router. * Relies on JSON schema converters to translate input, output, and error schemas into JSON Schemas. * * @see {@link https://orpc.dev/docs/openapi/specification#openapi-generator | OpenAPI Specification - OpenAPI Generator} */ export class OpenAPIGenerator { private readonly serializer: Public private readonly converter: Pick constructor(options: OpenAPIGeneratorOptions = {}) { this.serializer = options.serializer ?? new OpenAPIJsonSerializer() this.converter = new DelegatingJsonSchemaConverter([ ...toArray(options.converters), new StandardJsonSchemaConverter(), ]) } async generate( router: RouterContract | AnyRouter, options: OpenAPIGeneratorGenerateOptions = {}, ): Promise> { const version: OpenAPIVersion = options.version ?? '3.2.0' const doc: OpenAPIV3_2.OpenAPIObject = { ...clone(options.base), openapi: '3.2.0', info: options.base?.info ?? { title: 'API Reference', version: '0.0.0' }, } const ctx: OpenAPIOperationContext = { registry: new OpenAPIComponentRegistry(doc, options.componentName), convertSchemas: (schemas, direction) => this.convertSchemas(schemas, direction), errorStatuses: options.errorStatuses ?? COMMON_ERROR_STATUSES, errorResponseBodySchema: options.errorResponseBodySchema, errorResponseContentType: options.errorResponseContentType ?? 'application/json', } const errors: string[] = [] const routeOwners = new Map() const operationIdOwners = new Map() const routes = new Router() await walkProcedureContractsAsync(router, (contract, path) => { if (value(options.filter, contract, path) === false) { return } const procedurePath = path.length ? path.join('.') : '(root)' try { const def = contract['~orpc'] const meta = getOpenAPIMeta(contract) const method = (meta?.method ?? DEFAULT_OPENAPI_METHOD).toLowerCase() as Lowercase< NonNullable > if (method === 'query' && !version.startsWith('3.2.')) { throw new OpenAPIGeneratorError( `QUERY operations require OpenAPI 3.2, but version "${version}" was requested.`, ) } const postPath = meta?.path ?? pathToHttpPath(path) const httpPath = meta?.prefix ? mergeHttpPath(meta.prefix, postPath) : postPath try { routes.add(method.toUpperCase(), httpPath, undefined) } catch (e) { throw new OpenAPIGeneratorError( `${(e as Error).message}\n The OpenAPI handler can't route it.`, ) } const dynamicPathParams = getDynamicPathParams(httpPath) const openApiPath = toOpenAPIPath(httpPath, dynamicPathParams) let operation: OpenAPIV3_2.OperationObject if (meta?.spec !== undefined && typeof meta.spec !== 'function') { operation = meta.spec } else { operation = { operationId: meta?.operationId ?? path.join('.'), summary: meta?.summary, description: meta?.description, deprecated: meta?.deprecated, tags: meta?.tags?.map((tag) => tag), } buildRequest(ctx, operation, def, meta, dynamicPathParams) buildSuccessResponse(ctx, operation, def, meta) buildErrorResponse(ctx, operation, def) } if (typeof meta?.spec === 'function') { operation = meta.spec(operation) } const routeKey = `${method} ${toOpenAPIPath( httpPath, dynamicPathParams?.map((p) => ({ ...p, parameterName: '' })), )}` const routeOwner = routeOwners.get(routeKey) if (routeOwner !== undefined) { throw new OpenAPIGeneratorError( `${method.toUpperCase()} ${openApiPath} is already documented by the procedure at ${routeOwner}.\n` + ` OpenAPI allows one operation per method and path (path param names are ignored).\n` + ` Fix: change the method or path of one of them.`, ) } const { operationId } = operation if (operationId !== undefined) { const operationIdOwner = operationIdOwners.get(operationId) if (operationIdOwner !== undefined) { throw new OpenAPIGeneratorError( `operationId "${operationId}" is already used by the procedure at ${operationIdOwner}.\n` + ` OpenAPI requires operationIds to be unique. Fix: give one of them a different operationId.`, ) } operationIdOwners.set(operationId, procedurePath) } routeOwners.set(routeKey, procedurePath) doc.paths ??= {} doc.paths[openApiPath] ??= {} doc.paths[openApiPath][method] = operation } catch (e) { if (!(e instanceof OpenAPIGeneratorError)) { throw e } errors.push(`Procedure at ${procedurePath}: ${e.message}`) } }) if (errors.length) { throw new OpenAPIGeneratorError( `[OpenAPIGenerator] Failed to generate the OpenAPI document (${errors.length} error${errors.length === 1 ? '' : 's'}):\n\n${errors.join('\n\n')}`, ) } // serialize first so the downgraders work on JSON values, e.g. `Infinity` as `null` const serialized = this.serializer.serializeJson(doc).json as OpenAPIV3_2.OpenAPIObject return toVersionedOpenAPIDocument(serialized, version) as OpenAPIDocument } private convertSchema( schema: AnySchema | undefined, direction: JsonSchemaConverterDirection, ): [JsonSchema, boolean] { const [jsonSchema, optional] = this.converter.convert(schema as any, direction) // composing or hoisting would retarget root-relative refs (`#`, `#/properties/...`), // so move a schema that points into itself under a def first return [hoistRecursiveRefToDef(strip$schemaField(jsonSchema)), optional] } private convertSchemas( schemas: AnySchema[] | undefined, direction: JsonSchemaConverterDirection, ): [JsonSchema, boolean] { if (!schemas || schemas.length <= 1) { return this.convertSchema(schemas?.[0], direction) } const results = schemas.map((s) => this.convertSchema(s, direction)) return [ combineJsonSchemasWithComposition( 'allOf', results.map(([jsonSchema]) => jsonSchema), ), results.every(([, optional]) => optional), ] } } function toVersionedOpenAPIDocument( doc: OpenAPIV3_2.OpenAPIObject, version: OpenAPIVersion, ): OpenAPIDocument { const downgraded = version.startsWith('3.2.') ? doc : version.startsWith('3.1.') ? downgradeSpecV32ToV31(doc) : downgradeSpecV31ToV30(downgradeSpecV32ToV31(doc)) return { ...downgraded, openapi: version } as OpenAPIDocument } function strip$schemaField(schema: JsonSchema): JsonSchema { if (typeof schema !== 'object') { return schema } const { $schema: _schema, ...rest } = schema return rest }