import { APP, defineController, defineModule, type AppInfo, type AviModule, type GuardRef, type MiddlewareRef, type RouteInfo, type StandardSchemaV1, } from '@avijs/core'; export type JsonSchema = Record; // OpenApiModule's own route, left out of the document. const MODULE_NAME = 'OpenApiModule'; const CONTROLLER_NAME = 'OpenApiController'; export interface OpenApiOptions { info: { title: string; version: string; description?: string }; servers?: readonly { url: string; description?: string }[]; /** * Converts a route schema to JSON Schema. Without it, schemas that implement Standard JSON * Schema (`~standard.jsonSchema`) are converted; other schemas are left undocumented. Any object * is accepted, so converters with their own JSON Schema types fit without a cast. */ toJsonSchema?: (schema: StandardSchemaV1, io: 'input' | 'output') => object | undefined; } export interface OpenApiDocument { openapi: '3.1.0'; info: OpenApiOptions['info']; servers?: OpenApiOptions['servers']; paths: Record>; components: { schemas: Record }; } interface Parameter { name: string; in: 'path' | 'query'; required: boolean; schema: JsonSchema; } interface Operation { summary?: string; description?: string; tags?: readonly string[]; operationId?: string; deprecated?: boolean; parameters?: Parameter[]; requestBody?: { required: true; content: { 'application/json': { schema: JsonSchema } } }; responses: Record< string, { description: string; content?: Record } >; } const VALIDATION_ERROR: JsonSchema = { type: 'object', required: ['statusCode', 'error', 'message'], properties: { statusCode: { type: 'integer' }, error: { type: 'string' }, message: { type: 'string' }, details: { type: 'object', properties: { issues: { type: 'array', items: { type: 'object', properties: { in: { enum: ['params', 'query', 'body'] }, path: { type: 'array', items: { type: ['string', 'number'] } }, message: { type: 'string' }, }, }, }, }, }, }, }; /** Builds an OpenAPI 3.1 document from an initialized app's routes and schemas. */ export function generateOpenApi(app: AppInfo, options: OpenApiOptions): OpenApiDocument { const toJson = options.toJsonSchema ?? standardJsonSchema; const convert = (route: RouteInfo, part: 'params' | 'query' | 'body' | 'response') => { const schema = route.schema?.[part]; if (!schema) return undefined; try { return toJson(schema, part === 'response' ? 'output' : 'input') as JsonSchema | undefined; } catch (error) { const reason = error instanceof Error ? error.message : String(error); throw new Error( `Cannot convert the ${part} schema of ${route.method} ${route.path} to JSON Schema: ${reason}`, { cause: error }, ); } }; const paths: OpenApiDocument['paths'] = {}; let usesValidation = false; for (const route of [...app.routes()].sort(byPath)) { if (route.module === MODULE_NAME && route.controller === CONTROLLER_NAME) continue; // exclude is Avi.js's own: it never goes into the document. const { exclude, ...docs } = route.openapi ?? {}; if (exclude) continue; const { path, names } = openApiPath(route.path); const operation: Operation = { ...docs, responses: {} }; const parameters: Parameter[] = []; const params = objectProperties(convert(route, 'params')); for (const name of names) { parameters.push({ name, in: 'path', required: true, schema: params.properties[name === 'wildcard' ? '*' : name] ?? { type: 'string' }, }); } const query = objectProperties(convert(route, 'query')); for (const [name, schema] of Object.entries(query.properties)) { parameters.push({ name, in: 'query', required: query.required.includes(name), schema }); } if (parameters.length > 0) operation.parameters = parameters; if (route.schema?.body) { const body = convert(route, 'body') ?? {}; operation.requestBody = { required: true, content: { 'application/json': { schema: body } } }; } const response = convert(route, 'response'); operation.responses['200'] = response ? { description: 'OK', content: { 'application/json': { schema: response } } } : { description: 'OK' }; if (route.schema?.params || route.schema?.query || route.schema?.body) { usesValidation = true; operation.responses['400'] = { description: 'Validation failed', content: { 'application/json': { schema: { $ref: '#/components/schemas/ValidationError' } }, }, }; } (paths[path] ??= {})[route.method.toLowerCase()] = operation; } return { openapi: '3.1.0', info: options.info, ...(options.servers ? { servers: options.servers } : {}), paths, components: { schemas: usesValidation ? { ValidationError: VALIDATION_ERROR } : {} }, }; } /** `/users/:id/*` → `/users/{id}/{wildcard}`, with the parameter names in order. */ export function openApiPath(path: string): { path: string; names: string[] } { const names: string[] = []; const converted = path .split('/') .map((segment) => { if (segment.startsWith(':')) { names.push(segment.slice(1)); return `{${segment.slice(1)}}`; } if (segment === '*') { names.push('wildcard'); return '{wildcard}'; } return segment; }) .join('/'); return { path: converted, names }; } function standardJsonSchema( schema: StandardSchemaV1, io: 'input' | 'output', ): JsonSchema | undefined { const converter = ( schema['~standard'] as { jsonSchema?: Partial JsonSchema>>; } ).jsonSchema?.[io]; return typeof converter === 'function' ? converter({ target: 'draft-2020-12' }) : undefined; } function objectProperties(schema: JsonSchema | undefined): { properties: Record; required: string[]; } { const properties = (schema?.['properties'] ?? {}) as Record; const required = Array.isArray(schema?.['required']) ? (schema['required'] as string[]) : []; return { properties, required }; } function byPath(a: RouteInfo, b: RouteInfo): number { return a.path === b.path ? a.method.localeCompare(b.method) : a.path.localeCompare(b.path); } export interface OpenApiModuleOptions extends OpenApiOptions { /** Where the document is served. Default `/openapi.json`. */ readonly path?: string; /** Guards for the document's route, such as one that only lets staff read it. */ readonly guards?: readonly GuardRef[]; readonly middleware?: readonly MiddlewareRef[]; } export const OpenApiModule = { /** * Serves the app's OpenAPI document, built from its routes on the first request and then kept. * Its own route is left out of the document. */ forRoot(options: OpenApiModuleOptions): AviModule { const { path = '/openapi.json', guards = [], middleware = [], ...document } = options; // Per app, so two apps registering this module never share a document. const built = new WeakMap(); return defineModule({ name: MODULE_NAME, controllers: [ defineController({ name: CONTROLLER_NAME, inject: [APP], guards, middleware, routes: (app) => [ { method: 'GET', path, handler: () => { let found = built.get(app); if (!found) built.set(app, (found = generateOpenApi(app, document))); return found; }, }, ], }), ], }); }, };