From a2acec69bfa5411583595d430704f48f1a2e98ac Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sun, 2 Aug 2026 20:47:18 -0500 Subject: [PATCH] feat(openapi): document constrained route params Signed-off-by: Diego Resendez --- src/http/router.ts | 4 ++-- src/openapi.ts | 33 ++++++++++++++++++++++++--------- test/openapi.test.ts | 27 +++++++++++++++++++++++++-- test/router.test.ts | 5 +++++ 4 files changed, 56 insertions(+), 13 deletions(-) diff --git a/src/http/router.ts b/src/http/router.ts index 647e146..de3b350 100644 --- a/src/http/router.ts +++ b/src/http/router.ts @@ -1,6 +1,6 @@ import type { RouteDef, MatchedRoute } from './types'; -type CompiledSegment = +export type CompiledSegment = | { kind: 'static'; value: string } | { kind: 'param'; name: string; constraint?: RegExp; constraintSource?: string } | { kind: 'catchAll'; name: string }; @@ -147,7 +147,7 @@ export function compilePattern(pattern: string): CompiledPattern { if (pattern.includes('//')) throw new Error(`invalid route pattern '${pattern}': repeated slash`); const normalized = pattern.length > 1 && pattern.endsWith('/') ? pattern.slice(0, -1) : pattern; - const rawSegments = normalized.split('/').slice(1); + const rawSegments = normalized === '/' ? [] : normalized.split('/').slice(1); const segments = compileSegments(pattern, rawSegments); const compiled: CompiledPattern = { source: pattern, diff --git a/src/openapi.ts b/src/openapi.ts index 4acf4f4..fb765b7 100644 --- a/src/openapi.ts +++ b/src/openapi.ts @@ -1,5 +1,6 @@ import type { ArgSpec } from './params'; import type { Transport } from './metadata'; +import { compilePattern } from './http/router'; /** Minimal per-route input the OpenAPI projection needs, derived from a route plan. */ export interface OpenApiRoute { @@ -23,23 +24,37 @@ export interface OpenApiDoc { paths: Record>; } -type Parameter = { name: string; in: 'path' | 'query' | 'header'; required: boolean; schema: { type: 'string' } }; +type Parameter = { + name: string; + in: 'path' | 'query' | 'header'; + required: boolean; + schema: { type: 'string'; pattern?: string }; +}; /** Converts a route pattern to an OpenAPI path template: `/users/:id` → `/users/{id}`, `:rest*` → `{rest}`. */ function templatePath(pattern: string): string { - const segments = pattern - .split('/') - .filter(Boolean) - .map((seg) => (seg.startsWith(':') ? `{${seg.slice(1).replace(/\*$/, '')}}` : seg)); + const segments = compilePattern(pattern).segments.map((segment) => + segment.kind === 'static' ? segment.value : `{${segment.name}}`, + ); return `/${segments.join('/')}`; } /** Every `:name` (and `:name*`) segment of a pattern becomes a required path parameter. */ function pathParams(pattern: string): Parameter[] { - return pattern - .split('/') - .filter((seg) => seg.startsWith(':')) - .map((seg) => ({ name: seg.slice(1).replace(/\*$/, ''), in: 'path', required: true, schema: { type: 'string' } })); + return compilePattern(pattern).segments.flatMap((segment): Parameter[] => { + if (segment.kind === 'static') return []; + return [ + { + name: segment.name, + in: 'path', + required: true, + schema: { + type: 'string', + ...(segment.kind === 'param' && segment.constraintSource ? { pattern: segment.constraintSource } : {}), + }, + }, + ]; + }); } /** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */ diff --git a/test/openapi.test.ts b/test/openapi.test.ts index 94f04ed..da0c459 100644 --- a/test/openapi.test.ts +++ b/test/openapi.test.ts @@ -1,7 +1,7 @@ import 'reflect-metadata'; import { describe, it, expect } from 'vitest'; import { createApp } from '../src/app'; -import { Route, Get, Post, Ws, Module } from '../src/metadata'; +import { Route, Get, Head, Options, Post, Ws, Module } from '../src/metadata'; import { param, query, headers, body } from '../src/params'; const numSchema = { @@ -14,7 +14,13 @@ const numSchema = { @Route('/users') class Users { - @Get('/:id') get(@param('id') _id: string, @query('expand') _e: string, @headers('x-trace') _t: string) { + @Get('/:id(\\d+)') get(@param('id') _id: string, @query('expand') _e: string, @headers('x-trace') _t: string) { + return {}; + } + @Head('/:id(\\d+)') head() { + return {}; + } + @Options('/:id(\\d+)') options() { return {}; } @Post('/') create(@body() _b: unknown) { @@ -52,6 +58,23 @@ describe('app.openapi()', () => { expect(byName).toEqual({ id: 'path', expand: 'query', 'x-trace': 'header' }); }); + it('projects a constrained param into schema.pattern', () => { + const op = doc.paths['/api/users/{id}'].get as any; + expect(op.parameters).toContainEqual({ + name: 'id', + in: 'path', + required: true, + schema: { type: 'string', pattern: '\\d+' }, + }); + }); + + it('includes explicit HEAD and OPTIONS without inventing automatic operations', () => { + expect(doc.paths['/api/users/{id}'].head).toBeDefined(); + expect(doc.paths['/api/users/{id}'].options).toBeDefined(); + expect(doc.paths['/api/users/search'].head).toBeUndefined(); + expect(doc.paths['/api/users/search'].options).toBeUndefined(); + }); + 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(); diff --git a/test/router.test.ts b/test/router.test.ts index ffcf34b..72177ba 100644 --- a/test/router.test.ts +++ b/test/router.test.ts @@ -17,6 +17,11 @@ const route = (method: string, pattern: string): RouteDef => ({ }); describe('matchPattern', () => { + it('matches the root pattern only at root', () => { + expect(matchPattern('/', '/')).toEqual({}); + expect(matchPattern('/', '/users')).toBeUndefined(); + }); + it('matches static and :param segments, decoding params', () => { expect(matchPattern('/users/:id', '/users/a%20b')).toEqual({ id: 'a b' }); expect(matchPattern('/users/:id', '/users')).toBeUndefined();