feat: per-route body limits, custom error rendering, OpenAPI generation
CI / build (push) Has been cancelled

Three capabilities that share the same request/route metadata:

- **Per-route upload limits** — `@Post('/x', { maxBodyBytes, maxParts })`
  overrides the server-wide `limits` for one route (falls back to the
  global default), mirroring the existing per-route `duplicates`.

- **Custom error rendering** — `createApp({ onError })` takes over how any
  error becomes a response (HTML, RFC 7807, content-negotiated), covering
  the whole surface: handler/step throws, 404, 405, 413, 400. Returns a
  response or undefined to fall back to the default JSON. Also wires the
  previously-unused `HttpError` `body` field so `throw new HttpError(409,
  'conflict', { code })` renders a structured payload. Default behavior is
  unchanged when no hook is set.

- **OpenAPI 3.1** — `app.openapi(info?)` projects the route graph into a
  structural spec (paths, methods, path/query/header params, request-body
  presence, systematic error responses); opt-in `GET /__openapi__` via
  `devOpenapi`. Body/response schemas stay generic (Standard Schema exposes
  no JSON Schema) — the full `@Produce` mode is post-beta.

Docs: new error-handling and OpenAPI guides, plus reference updates.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-08 08:29:17 -05:00
1 parent 7c20d74fe4
commit 2db5de6858
19 files changed
+811 -100

No files matched your search

+269 -64
View File
@@ -1,13 +1,17 @@
import 'reflect-metadata';
import { describe, expect, it, test, vi } from 'vitest';
import { Provider, Step, Route, Get, Module, Transformer } from '../src/metadata';
import { Provider, Step, Route, Get, Post, Module, Transformer } from '../src/metadata';
import { JsonTransformer } from '../src/transformers';
import { Unauthorized } from '../src/signals';
import { createApp } from '../src/app';
import { needs, param, query } from '../src/params';
import { needs, param, query, body } from '../src/params';
@Provider({ provides: 'db' })
class Db { provide() { return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } }; } }
class Db {
provide() {
return { db: { find: (t: string) => (t === 'good' ? { id: 'u1' } : null) } };
}
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Auth {
@@ -22,7 +26,9 @@ class Auth {
class UserCtl {
@Get('/:id')
@Transformer(JsonTransformer)
getUser(@needs('user') user: any, @param('id') id: string) { return { id, user }; }
getUser(@needs('user') user: any, @param('id') id: string) {
return { id, user };
}
}
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [UserCtl] })
@@ -54,7 +60,11 @@ test('a logger plugin observes step:enter without mutating the chain', async ()
test('required provider failure aborts boot', () => {
@Provider({ provides: 'broken' })
class Broken { provide() { throw new Error('cannot connect'); } }
class Broken {
provide() {
throw new Error('cannot connect');
}
}
@Module({ mountpoint: '/x', providers: [Broken], steps: [], controllers: [] })
class BrokenModule {}
@@ -65,15 +75,23 @@ test('required provider failure aborts boot', () => {
test('optional provider failure warns but does not abort boot', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
@Provider({ provides: 'cache', optional: true })
class FlakyCache { provide() { throw new Error('cache down'); } }
class FlakyCache {
provide() {
throw new Error('cache down');
}
}
@Route('/ping')
class PingCtl { @Get('/') ping() { return { ok: true }; } }
class PingCtl {
@Get('/') ping() {
return { ok: true };
}
}
@Module({ mountpoint: '/sys', providers: [FlakyCache], steps: [], controllers: [PingCtl] })
class SysModule {}
const app = createApp({ modules: [SysModule] });
expect(app.degraded()).toEqual([]); // nothing degraded until boot runs
const server = await app.listen(0); // must NOT throw
const server = await app.listen(0); // must NOT throw
expect(warn).toHaveBeenCalledWith(expect.stringContaining("optional provider 'cache' failed"));
// boot ends with a summary of everything running degraded, and it is queryable on the app
expect(warn).toHaveBeenCalledWith(expect.stringContaining('started with 1 degraded optional provider(s): cache'));
@@ -86,7 +104,9 @@ test('handler receives @query value through a live request', async () => {
@Route('/search')
class SearchCtl {
@Get('/')
run(@query('q') q: string) { return { q }; }
run(@query('q') q: string) {
return { q };
}
}
@Module({ mountpoint: '/s', providers: [], steps: [], controllers: [SearchCtl] })
class SearchModule {}
@@ -103,19 +123,31 @@ test('boot fails when a handler needs something nothing provides', () => {
@Route('/things')
class ThingCtl {
@Get('/')
list(@needs('missing') _m: any) { return []; }
list(@needs('missing') _m: any) {
return [];
}
}
@Module({ mountpoint: '/t', providers: [], steps: [], controllers: [ThingCtl] })
class ThingModule {}
expect(() => createApp({ modules: [ThingModule] }))
.toThrow(/handler 'list' needs 'missing'/);
expect(() => createApp({ modules: [ThingModule] })).toThrow(/handler 'list' needs 'missing'/);
});
it('boot error for a misspelled @needs suggests the closest token', () => {
@Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } }
@Route('/u') class Ctl { @Get('/x') x(@needs('usr') u: any) { return { u }; } }
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {}
@Step({ provides: 'user', needs: [] })
class Auth {
run() {
return { user: 1 };
}
}
@Route('/u')
class Ctl {
@Get('/x') x(@needs('usr') u: any) {
return { u };
}
}
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/did you mean 'user'\?/);
});
@@ -128,10 +160,14 @@ describe('app streaming wiring', () => {
@Route('/')
class Ctl {
@Sse('/ticks') ticks() {
return (async function* () { yield { t: 1 }; yield { t: 2 }; })();
return (async function* () {
yield { t: 1 };
yield { t: 2 };
})();
}
}
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const addr = server.address() as import('net').AddressInfo;
@@ -147,11 +183,15 @@ describe('app streaming wiring', () => {
class Ctl {
@Ws('/echo') echo(@inbound() inc: AsyncIterable<string>) {
const out = channel<string>();
(async () => { for await (const m of inc) out.push(`re:${m}`); out.close(); })();
(async () => {
for await (const m of inc) out.push(`re:${m}`);
out.close();
})();
return out;
}
}
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const addr = server.address() as import('net').AddressInfo;
@@ -161,7 +201,8 @@ describe('app streaming wiring', () => {
const got = new Promise<string>((r) => client.on('message', (d: Buffer) => r(d.toString())));
client.send('yo');
expect(await got).toBe('re:yo');
client.close(); server.close();
client.close();
server.close();
});
});
@@ -169,53 +210,97 @@ describe('per-route subgraph slicing', () => {
it('a route that does not @needs a step does not run it', async () => {
const ran: string[] = [];
@Step({ provides: 'tracked', needs: [] })
class Tracked { run() { ran.push('tracked'); return { tracked: true }; } }
class Tracked {
run() {
ran.push('tracked');
return { tracked: true };
}
}
@Route('/')
class Ctl {
@Get('/needs') needs(@needs('tracked') t: any) { return { t }; }
@Get('/free') free() { return { ok: true }; }
@Get('/needs') needs(@needs('tracked') t: any) {
return { t };
}
@Get('/free') free() {
return { ok: true };
}
}
@Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] }) class M {}
@Module({ mountpoint: '/', steps: [Tracked], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const port = (server.address() as any).port;
await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json());
expect(ran).toEqual([]); // step did NOT run for /free
expect(ran).toEqual([]); // step did NOT run for /free
await fetch(`http://127.0.0.1:${port}/needs`).then((r) => r.json());
expect(ran).toEqual(['tracked']); // step ran for /needs
expect(app.inspect('/free').map((l) => l.kind)).toEqual(['handler']); // no step in the chain
expect(ran).toEqual(['tracked']); // step ran for /needs
expect(app.inspect('/free').map((l) => l.kind)).toEqual(['handler']); // no step in the chain
server.close();
});
it('a side-effect step (provides: []) added by a plugin runs unconditionally', async () => {
// NB: @Step always provides exactly one token (always sliceable). provides:[] only arises via a plugin's scope.add.
const ran: string[] = [];
const observer = (api: any) => api.scope.add({ kind: 'step', name: 'obs', needs: [], provides: [], run: () => { ran.push('obs'); return {}; } });
const observer = (api: any) =>
api.scope.add({
kind: 'step',
name: 'obs',
needs: [],
provides: [],
run: () => {
ran.push('obs');
return {};
},
});
@Route('/')
class Ctl { @Get('/free') free() { return { ok: true }; } }
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
class Ctl {
@Get('/free') free() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [observer] });
const server = await app.listen(0);
const port = (server.address() as any).port;
await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json());
expect(ran).toEqual(['obs']); // ran despite the route @needs-ing nothing
expect(ran).toEqual(['obs']); // ran despite the route @needs-ing nothing
server.close();
});
it('an always-run observer step receives its declared needs even when the route does not need them', async () => {
let seen: any;
const observer = (api: any) => api.scope.add({ kind: 'step', name: 'audit', needs: ['user'], provides: [], run: (ctx: any) => { seen = ctx.user; return {}; } });
const observer = (api: any) =>
api.scope.add({
kind: 'step',
name: 'audit',
needs: ['user'],
provides: [],
run: (ctx: any) => {
seen = ctx.user;
return {};
},
});
@Step({ provides: 'user', needs: [] })
class Auth { run() { return { user: { id: 'u1' } }; } }
class Auth {
run() {
return { user: { id: 'u1' } };
}
}
@Route('/')
class Ctl { @Get('/free') free() { return { ok: true }; } } // does NOT @needs('user')
@Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] }) class M {}
class Ctl {
@Get('/free') free() {
return { ok: true };
}
} // does NOT @needs('user')
@Module({ mountpoint: '/', steps: [Auth], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [observer] });
const server = await app.listen(0);
const port = (server.address() as any).port;
await fetch(`http://127.0.0.1:${port}/free`).then((r) => r.json());
expect(seen).toEqual({ id: 'u1' }); // observer got user, not undefined
expect(seen).toEqual({ id: 'u1' }); // observer got user, not undefined
server.close();
});
});
@@ -225,10 +310,26 @@ import { toMermaid as renderMermaid } from '../src/graph-viz';
describe('app.graph / explain', () => {
it('graph() returns nodes (with origin/needs/provides) and routes with their sliced chain', async () => {
@Provider({ provides: 'db' }) class Db { provide() { return { db: 1 }; } }
@Step({ provides: 'user', needs: ['db'] }) class Auth { run() { return { user: 1 }; } }
@Route('/u') class Ctl { @Get('/:id') get(@needs('user') u: any) { return { u }; } }
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] }) class M {}
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: 1 };
}
}
@Step({ provides: 'user', needs: ['db'] })
class Auth {
run() {
return { user: 1 };
}
}
@Route('/u')
class Ctl {
@Get('/:id') get(@needs('user') u: any) {
return { u };
}
}
@Module({ mountpoint: '/api', providers: [Db], steps: [Auth], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const g = app.graph();
expect(g.nodes.find((n) => n.name === 'db')).toMatchObject({ kind: 'provider', origin: 'module:M' });
@@ -239,9 +340,20 @@ describe('app.graph / explain', () => {
});
it('explain() returns the rich chain with origin and a handler entry', async () => {
@Step({ provides: 'user', needs: [] }) class Auth { run() { return { user: 1 }; } }
@Route('/u') class Ctl { @Get('/me') me(@needs('user') u: any) { return { u }; } }
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] }) class M {}
@Step({ provides: 'user', needs: [] })
class Auth {
run() {
return { user: 1 };
}
}
@Route('/u')
class Ctl {
@Get('/me') me(@needs('user') u: any) {
return { u };
}
}
@Module({ mountpoint: '/api', steps: [Auth], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const e = app.explain('/api/u/me');
expect(e).toMatchObject({ pattern: '/api/u/me', method: 'GET', transport: 'buffer' });
@@ -253,8 +365,14 @@ describe('app.graph / explain', () => {
describe('devGraph endpoint', () => {
const portOf = (s: any) => (s.address() as any).port;
it('serves /__graph__ as HTML when devGraph:true', async () => {
@Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
@Route('/u')
class Ctl {
@Get('/me') me() {
return { ok: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], devGraph: true });
const s = await app.listen(0);
const html = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`).then((r) => r.text());
@@ -266,8 +384,14 @@ describe('devGraph endpoint', () => {
s.close();
});
it('does NOT mount /__graph__ without devGraph', async () => {
@Route('/u') class Ctl { @Get('/me') me() { return { ok: 1 }; } }
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
@Route('/u')
class Ctl {
@Get('/me') me() {
return { ok: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const s = await app.listen(0);
const res = await fetch(`http://127.0.0.1:${portOf(s)}/__graph__`);
@@ -279,17 +403,26 @@ describe('devGraph endpoint', () => {
describe('graceful shutdown', () => {
it('app.close() stops accepting and resolves, even with an SSE stream open', async () => {
@Route('/')
class Ctl { @Sse('/ticks') ticks() { return (async function* () { yield { t: 1 }; await new Promise((r) => setTimeout(r, 1000)); yield { t: 2 }; })(); } }
@Module({ mountpoint: '/', controllers: [Ctl] }) class M {}
class Ctl {
@Sse('/ticks') ticks() {
return (async function* () {
yield { t: 1 };
await new Promise((r) => setTimeout(r, 1000));
yield { t: 2 };
})();
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const server = await app.listen(0);
const port = (server.address() as any).port;
const res = await fetch(`http://127.0.0.1:${port}/ticks`, { headers: { accept: 'text/event-stream' } });
const reader = res.body!.getReader();
await reader.read(); // first event; stream still open
await reader.read(); // first event; stream still open
await app.close(); // must NOT hang despite the open stream
await app.close(); // must NOT hang despite the open stream
await expect(fetch(`http://127.0.0.1:${port}/ticks`).then((r) => r.text())).rejects.toThrow();
reader.cancel().catch(() => {});
});
@@ -298,26 +431,54 @@ describe('graceful shutdown', () => {
describe('overrides', () => {
const portOf = (s: any) => (s.address() as any).port;
it('overrides a provider token with a plain value (wrapped as a merge object)', async () => {
@Provider({ provides: 'db' }) class Db { provide() { return { db: { real: true } }; } }
@Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: { real: true } };
}
}
@Route('/u')
class Ctl {
@Get('/x') x(@needs('db') db: any) {
return { db };
}
}
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], overrides: { db: { fake: true } } });
const s = await app.listen(0);
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: { fake: true } });
s.close();
});
it('overrides with a function runner', async () => {
@Provider({ provides: 'db' }) class Db { provide() { return { db: 'real' }; } }
@Route('/u') class Ctl { @Get('/x') x(@needs('db') db: any) { return { db }; } }
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] }) class M {}
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: 'real' };
}
}
@Route('/u')
class Ctl {
@Get('/x') x(@needs('db') db: any) {
return { db };
}
}
@Module({ mountpoint: '/api', providers: [Db], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], overrides: { db: () => ({ db: 'fn' }) } });
const s = await app.listen(0);
expect(await fetch(`http://127.0.0.1:${portOf(s)}/api/u/x`).then((r) => r.json())).toEqual({ db: 'fn' });
s.close();
});
it('rejects an override for an unknown token', async () => {
@Route('/u') class Ctl { @Get('/x') x() { return { ok: 1 }; } }
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
@Route('/u')
class Ctl {
@Get('/x') x() {
return { ok: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], overrides: { nope: 1 } });
await expect(app.listen(0)).rejects.toThrow(/unknown token 'nope'/);
});
@@ -325,8 +486,14 @@ describe('overrides', () => {
describe('rooms auto-provide', () => {
it('injects a built-in rooms instance resolvable via @needs("rooms")', async () => {
@Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: Rooms) { return { ok: rooms instanceof Rooms }; } }
@Module({ mountpoint: '/api', controllers: [Ctl] }) class M {}
@Route('/r')
class Ctl {
@Get('/x') x(@needs('rooms') rooms: Rooms) {
return { ok: rooms instanceof Rooms };
}
}
@Module({ mountpoint: '/api', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
const s = await app.listen(0);
const port = (s.address() as any).port;
@@ -334,9 +501,47 @@ describe('rooms auto-provide', () => {
s.close();
});
it('a user-declared rooms provider wins (no duplicate-name throw)', () => {
@Provider({ provides: 'rooms' }) class MyRooms { provide() { return { rooms: { custom: true } }; } }
@Route('/r') class Ctl { @Get('/x') x(@needs('rooms') rooms: any) { return rooms; } }
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] }) class M {}
@Provider({ provides: 'rooms' })
class MyRooms {
provide() {
return { rooms: { custom: true } };
}
}
@Route('/r')
class Ctl {
@Get('/x') x(@needs('rooms') rooms: any) {
return rooms;
}
}
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).not.toThrow();
});
});
test('per-route maxBodyBytes overrides the server default', async () => {
@Route('/up')
class C {
@Post('/small', { maxBodyBytes: 10 }) small(@body() _b: unknown) {
return { ok: true };
}
@Post('/big') big(@body() _b: unknown) {
return { ok: true };
}
}
@Module({ mountpoint: '/', providers: [], steps: [], controllers: [C] })
class M {}
const app = createApp({ modules: [M], limits: { maxBodyBytes: 1000 } });
const server = await app.listen(0);
const port = (server.address() as any).port;
const payload = JSON.stringify({ x: 'aaaaaaaaaaaaaaaaaaaa' }); // ~30 bytes, over the route's 10-byte cap
const opts = { method: 'POST', headers: { 'content-type': 'application/json' }, body: payload };
const tight = await fetch(`http://127.0.0.1:${port}/up/small`, opts);
expect(tight.status).toBe(413); // per-route cap of 10 bytes
const loose = await fetch(`http://127.0.0.1:${port}/up/big`, opts);
expect(loose.status).toBe(200); // falls back to the server's 1000-byte limit
server.close();
});
+82
View File
@@ -0,0 +1,82 @@
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp } from '../src/app';
import { Route, Get, Module } from '../src/metadata';
import { HttpError, Unauthorized, isHttpError } from '../src/signals';
import type { ErrorRenderer } from '../src/transformers';
// Renders every error as HTML, reading the status off HttpError when present.
const htmlErrors: ErrorRenderer = (error) => ({
status: isHttpError(error) ? error.status : 500,
headers: { 'content-type': 'text/html' },
body: `<h1>${isHttpError(error) ? error.status : 500}</h1>`,
});
@Route('/x')
class Ctl {
@Get('/boom') boom() {
throw new Unauthorized('nope');
}
@Get('/ok') ok() {
return { ok: true };
}
@Get('/teapot') teapot() {
throw new HttpError(418, 'short and stout', { code: 'TEA', reason: 'short and stout' });
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
async function serve(onError?: ErrorRenderer) {
const app = createApp({ modules: [M], onError });
const server = await app.listen(0);
const port = (server.address() as any).port;
return { server, base: `http://127.0.0.1:${port}` };
}
describe('onError renderer', () => {
it('renders a handler-thrown error through the hook (HTML, right status)', async () => {
const { server, base } = await serve(htmlErrors);
const res = await fetch(`${base}/x/boom`);
expect(res.status).toBe(401);
expect(res.headers.get('content-type')).toBe('text/html');
expect(await res.text()).toBe('<h1>401</h1>');
server.close();
});
it('renders infra errors too — a no-route 404 goes through the hook', async () => {
const { server, base } = await serve(htmlErrors);
const res = await fetch(`${base}/nope`);
expect(res.status).toBe(404);
expect(res.headers.get('content-type')).toBe('text/html');
expect(await res.text()).toBe('<h1>404</h1>');
server.close();
});
it('falls back to the default JSON when the hook returns undefined', async () => {
const { server, base } = await serve(() => undefined);
const res = await fetch(`${base}/x/boom`);
expect(res.status).toBe(401);
expect(res.headers.get('content-type')).toBe('application/json');
expect(await res.json()).toEqual({ error: 'nope' });
server.close();
});
it('with no hook, behavior is unchanged (default JSON 404)', async () => {
const { server, base } = await serve();
const res = await fetch(`${base}/nope`);
expect(res.status).toBe(404);
expect(await res.json()).toEqual({ error: 'Not Found' });
server.close();
});
});
describe('HttpError body', () => {
it('an HttpError carrying a body renders that payload instead of { error: message }', async () => {
const { server, base } = await serve();
const res = await fetch(`${base}/x/teapot`);
expect(res.status).toBe(418);
expect(await res.json()).toEqual({ code: 'TEA', reason: 'short and stout' });
server.close();
});
});
+83
View File
@@ -0,0 +1,83 @@
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp } from '../src/app';
import { Route, Get, Post, Ws, Module } from '../src/metadata';
import { param, query, headers, body } from '../src/params';
const numSchema = {
'~standard': {
version: 1 as const,
vendor: 'test',
validate: (v: unknown) => ({ value: Number(v) }),
},
};
@Route('/users')
class Users {
@Get('/:id') get(@param('id') _id: string, @query('expand') _e: string, @headers('x-trace') _t: string) {
return {};
}
@Post('/') create(@body() _b: unknown) {
return {};
}
@Get('/:id/files/:path*') files(@param('path') _p: string) {
return {};
}
@Get('/search') search(@query('n', numSchema) _n: number) {
return {};
}
@Ws('/live') live() {
return (async function* () {})();
}
}
@Module({ mountpoint: '/api', controllers: [Users] })
class M {}
describe('app.openapi()', () => {
const doc = createApp({ modules: [M] }).openapi({ title: 'Demo', version: '1.2.3' });
it('emits a 3.1 doc with info overrides', () => {
expect(doc.openapi).toBe('3.1.0');
expect(doc.info).toEqual({ title: 'Demo', version: '1.2.3' });
});
it('templates path params: /users/:id → /users/{id}', () => {
expect(doc.paths['/api/users/{id}']).toBeDefined();
expect(doc.paths['/api/users/{id}/files/{path}']).toBeDefined();
});
it('derives path, query, and header parameters from the handler signature', () => {
const op = doc.paths['/api/users/{id}'].get as any;
const byName = Object.fromEntries(op.parameters.map((p: any) => [p.name, p.in]));
expect(byName).toEqual({ id: 'path', expand: 'query', 'x-trace': 'header' });
});
it('marks routes that take a body with requestBody', () => {
const op = doc.paths['/api/users'].post as any;
expect(op.requestBody.content['application/json']).toBeDefined();
});
it('adds a 422 response when an argument is validated by a schema', () => {
const op = doc.paths['/api/users/search'].get as any;
expect(op.responses['422']).toBeDefined();
expect((doc.paths['/api/users/{id}'].get as any).responses['422']).toBeUndefined();
});
it('omits WebSocket routes', () => {
expect(doc.paths['/api/users/live']).toBeUndefined();
});
});
describe('GET /__openapi__', () => {
it('serves the document as JSON when devOpenapi is enabled', async () => {
const app = createApp({ modules: [M], devOpenapi: true });
const server = await app.listen(0);
const port = (server.address() as any).port;
const res = await fetch(`http://127.0.0.1:${port}/__openapi__`);
expect(res.headers.get('content-type')).toBe('application/json');
const json = (await res.json()) as any;
expect(json.openapi).toBe('3.1.0');
expect(json.paths['/api/users/{id}']).toBeDefined();
server.close();
});
});