Most routes answered by a v1 handler showed an empty body and
`data: unknown` in /docs/v2. Each now documents what its handler reads
and answers, and every path and query parameter is described.
- `documented: { body?, response? }` on v1Route/defineRoute, with shared
shapes in src/v2/docs.ts. Documentation only: not enforced, so nothing
that works can start failing; outside production a body or answer that
doesn't fit is logged ("doesn't match its documented schema").
- QUERY_HELP / PATH_HELP describe common parameters; empty bodies say
"No body needed".
- Declared the funnel's eventIds and webhook deliveries' status/before.
- tests/v2Docs.test.ts keeps the document complete; frontend types
regenerated, three call sites' types tightened (no payload change).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
122 lines
5.9 KiB
TypeScript
122 lines
5.9 KiB
TypeScript
import { z } from 'zod';
|
|
import { routes as allRoutes, type AnyRoute, type Access } from './route';
|
|
import { ERROR_STATUS } from './errors';
|
|
import { PATH_HELP, QUERY_HELP } from './docs';
|
|
|
|
/**
|
|
* 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<string, unknown>;
|
|
|
|
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<Access, string> = {
|
|
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<string, JsonSchema>; required?: string[] };
|
|
for (const [name, prop] of Object.entries(json.properties || {})) {
|
|
const { description: own, ...propSchema } = prop as JsonSchema & { description?: string };
|
|
const description = own || (where === 'query' ? QUERY_HELP[name] : PATH_HELP[name]);
|
|
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;
|
|
}
|
|
|
|
/** A JSON body; one with nothing in it (an action that takes no input) says so. */
|
|
function requestBody(schema: JsonSchema) {
|
|
const empty = !(schema as { properties?: object }).properties || !Object.keys((schema as { properties: object }).properties).length;
|
|
return empty
|
|
? { required: true, description: 'No body needed: send an empty object.', content: { 'application/json': { schema } } }
|
|
: { required: true, content: { 'application/json': { schema } } };
|
|
}
|
|
|
|
export function buildOpenApi(opts: { version: string; serverUrl?: string; list?: AnyRoute[] }) {
|
|
const list = opts.list ?? allRoutes;
|
|
const paths: Record<string, Record<string, unknown>> = {};
|
|
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.upload
|
|
? { requestBody: { required: true, content: { 'multipart/form-data': { schema: { type: 'object', required: [def.upload.field], properties: { [def.upload.field]: { type: 'string', format: 'binary', description: def.upload.description } } } } } } }
|
|
: (def.documented?.body || def.body) ? { requestBody: requestBody(toSchema((def.documented?.body || def.body)!, 'input')) } : {}),
|
|
responses: {
|
|
[String(def.status ?? 200)]: def.file
|
|
? { description: 'The file', content: { [def.file.contentType]: { schema: { type: 'string' } } } }
|
|
: { description: 'OK', content: { 'application/json': { schema: toSchema(def.documented?.response ? z.object({ data: def.documented.response }) : 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 <token>`.',
|
|
'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 },
|
|
},
|
|
};
|
|
}
|