import { z } from 'zod'; import { routes as allRoutes, type AnyRoute, type Access } from './route'; import { ERROR_STATUS } from './errors'; /** * The OpenAPI 3.1 document for /api/v2, built from the route declarations (route.ts), so it is * always what the code does. Served at /api/v2/openapi.json, shown at /docs/v2. */ type JsonSchema = Record; const toSchema = (schema: z.ZodType, io: 'input' | 'output'): JsonSchema => { const { $schema: _drop, ...rest } = z.toJSONSchema(schema, { io, unrepresentable: 'any' }) as JsonSchema; return rest; }; const ACCESS_TEXT: Record = { public: 'Anyone.', optional: 'Anyone; signed-in staff may see more.', user: 'Any signed-in person.', staff: 'Staff, supervisors and admins.', supervisor: 'Supervisors and admins.', admin: 'Admins only.', }; const errorSchema = { type: 'object', required: ['error'], properties: { error: { type: 'object', required: ['code', 'message'], properties: { code: { type: 'string', enum: Object.keys(ERROR_STATUS) }, message: { type: 'string' }, fields: { type: 'object', additionalProperties: { type: 'string' }, description: 'Per-field problems (VALIDATION_FAILED only)' }, reason: { type: 'string', description: 'A more specific cause when there is one, e.g. TWO_FACTOR_REQUIRED, IMPERSONATION_ENDED, LICENCE_READ_ONLY, OTHER_CAMPUS' }, }, }, }, }; const errorResponse = (description: string) => ({ description, content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } } }); function parameters(def: AnyRoute) { const out: JsonSchema[] = []; const add = (schema: z.ZodType | undefined, where: 'path' | 'query') => { if (!schema) return; const json = toSchema(schema, 'input') as { properties?: Record; required?: string[] }; for (const [name, prop] of Object.entries(json.properties || {})) { const { description, ...propSchema } = prop as JsonSchema & { description?: string }; out.push({ name, in: where, required: where === 'path' || (json.required || []).includes(name), ...(description ? { description } : {}), schema: propSchema }); } }; add(def.params, 'path'); add(def.query, 'query'); return out; } export function buildOpenApi(opts: { version: string; serverUrl?: string; list?: AnyRoute[] }) { const list = opts.list ?? allRoutes; const paths: Record> = {}; for (const def of list) { const path = def.path.replace(/:(\w+)/g, '{$1}'); const secured = def.access !== 'public' && def.access !== 'optional'; paths[path] ||= {}; paths[path][def.method] = { tags: [def.tag], summary: def.summary, description: [def.description, `**Who:** ${ACCESS_TEXT[def.access]}`].filter(Boolean).join('\n\n'), operationId: `${def.method}${path.replace(/[{}]/g, '').split('/').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join('')}`, ...(secured ? { security: [{ bearerAuth: [] }] } : def.access === 'optional' ? { security: [{}, { bearerAuth: [] }] } : {}), parameters: parameters(def), ...(def.body ? { requestBody: { required: true, content: { 'application/json': { schema: toSchema(def.body, 'input') } } } } : {}), responses: { [String(def.status ?? 200)]: { description: 'OK', content: { 'application/json': { schema: toSchema(def.response, 'output') } } }, ...(def.params || def.query || def.body ? { 400: errorResponse('Validation failed (VALIDATION_FAILED)') } : {}), ...(secured ? { 401: errorResponse('Not signed in (UNAUTHENTICATED)') } : {}), ...(secured && def.access !== 'user' ? { 403: errorResponse('Not allowed for this role (FORBIDDEN)') } : {}), ...(def.params ? { 404: errorResponse('Not found (NOT_FOUND)') } : {}), }, }; } return { openapi: '3.1.0', info: { title: 'Cross Events API', version: opts.version, description: [ 'Version 2 of the Cross Events API. Every response is JSON:', '- a single item is `{ "data": { … } }`;', '- a list is `{ "data": [ … ], "meta": { "page", "limit", "total", "pages" } }`, paged with `?page=` and `?limit=` (at most 100);', '- an error is `{ "error": { "code", "message", "fields"? } }` with a stable `code`.', '', 'Dates are ISO 8601 in UTC; amounts are in rand. Sign in through the app and send the token as `Authorization: Bearer `.', 'Version 1 (`/api/…`) keeps working while the app moves over; it will be removed in 2.0.', ].join('\n'), }, servers: [{ url: opts.serverUrl ?? '/api/v2' }], tags: Array.from(new Set(list.map(r => r.tag))).map(name => ({ name })), paths, components: { securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' } }, schemas: { Error: errorSchema }, }, }; }