Skip to content

Handler Reference ​

The complete authoring surface for v2 handlers. Read Custom Presets first for the conceptual overview — this page is the symbol-by-symbol reference.

All symbols ship from @trapi/core (no typescript dependency).

HandlerContext ​

Decorator handlers receive a HandlerContext as the first argument to apply:

typescript
type HandlerContext = {
    host: { name: string; parentName?: string };
    decorator: { name: string; location?: { file: string; line: number } };
    argument: (index: number) => DecoratorArgument | undefined;
    arguments: () => DecoratorArgument[];
    typeArgument: (index: number) => DecoratorTypeArgument | undefined;
    typeArguments: () => DecoratorTypeArgument[];
    parameterType: () => Type | undefined;
};

type DecoratorArgument = {
    raw: unknown;
    kind: 'literal' | 'object' | 'array' | 'identifier' | 'unresolvable';
};

type DecoratorTypeArgument = {
    resolve: () => Type;
};
MethodReturnsNotes
host.nameclass / method / parameter name as written in sourcealways defined
host.parentNameenclosing class namepopulated for method and parameter handlers
decorator.namethe decorator name as written in sourcelets a handler name the decorator in an error message
decorator.locationfile and 1-based line of the decoratorset when the source file is available
argument(i)the i-th positional argumentundefined if the user wrote fewer args
arguments()every positional argumentuse for spread-like semantics (@Tags('a','b','c'))
typeArgument(i)the i-th generic type argument as a lazy resolver.resolve() triggers the TS type checker — only call when needed
typeArguments()every type argument lazilysame lazy semantics
parameterType()the resolved type of the parameter being decoratedparameter handlers only — returns undefined for controller/method handlers

Argument kinds ​

DecoratorArgument.kind discriminates how the argument was written:

kindWhat it isExampleraw shape
'literal'string / number / boolean / null literal@Path('/users')the literal value
'identifier'reference that the compiler folds to a constant@Path(USERS_PATH), an imported or re-exported constant, PATHS.users, an enum member, or a template expression whose substitutions are all constantsthe resolved value
'array'array literal@Tags('a', ['b', 'c']) second argstring[] (or mixed)
'object'object literal@Security({ bearer: ['scope'] })Record<string, unknown>
'unresolvable'argument the static analyser couldn't reduce@Example(buildExample())undefined

Always check kind before reading raw — unresolvable arguments carry no value.

typescript
parameter({
    match: { name: 'Query', on: 'parameter' },
    apply: (ctx, draft) => {
        const arg = ctx.argument(0);
        if (arg?.kind === 'literal' && typeof arg.raw === 'string') {
            draft.in = ParamKind.QueryProp;
            draft.name = arg.raw;
        } else {
            draft.in = ParamKind.Query;
        }
    },
});

JsDocHandlerContext ​

JSDoc handlers receive a different context shape:

typescript
type JsDocHandlerContext = {
    host: { name: string; parentName?: string };
    source: JsDocSource;
    parameterType: () => Type | undefined;
};

type JsDocSource = {
    tag: string;                          // e.g. 'summary' for `/** @summary ... */`
    text?: string;                        // text after the tag
    typeExpression?: { resolve: () => Type };  // e.g. `@type {string}` typedef
    parameterName?: string;               // for `@param <name>` style tags
    target: 'class' | 'method' | 'parameter' | 'property';
    host: { name: string; parentName?: string };
};

source.text covers most cases:

typescript
methodJsDoc({
    match: { tag: 'summary' },
    apply: (ctx, draft) => {
        if (ctx.source.text) draft.summary = ctx.source.text;
    },
});

Decorator handlers always run before JSDoc handlers on the same node — JSDoc acts as the override layer.

Draft fields with special handling ​

Most draft fields are copied onto the finished Controller/Method/Parameter as they are. These are interpreted by the generator:

Context parameters ​

A parameter handler that sets draft.in = ParamKind.Context marks a framework object (request, response, next, a whole headers or params bag). The parameter produces no OpenAPI parameter, and the generator stops before it resolves the parameter's TypeScript type: nothing reachable only through that type reaches referenceTypes or the document's schemas. A type that a real parameter, the body or a response also references is still registered through that route.

typescript
parameter({
    match: { name: 'Request', on: 'parameter' },
    apply: (_ctx, draft) => { draft.in = ParamKind.Context; },
});

Success status ​

The generator documents a method's return type as a response of its own: 200 with the return type as schema (204 for a void method), unless a handler already pushed a response at that status. A route that answers 201 or 202 on success sets draft.successStatus, and the return type is documented under that status instead; no 200 is added.

typescript
import { method, readNumber, readString } from '@trapi/core';

// @Status(202)
method({
    match: { name: 'Status', on: 'method' },
    apply: (ctx, draft) => {
        const arg = ctx.argument(0);
        const status = readString(arg) ?? readNumber(arg);

        if (status !== undefined) {
            draft.successStatus = String(status);
        }
    },
});
  • The value is one three-digit HTTP status code (201, 202, 204). Anything else (a range such as 2XX, an empty string, 'undefined' from a missing argument) fails generation with GENERATOR_SUCCESS_STATUS_INVALID.
  • A response a handler pushed at the same status keeps its description, schema and examples; it receives the return type as its schema only when it declares none, and the draft.defaultResponseExamples (@Example) only when it has no examples of its own. When handlers pushed several responses at that status, the last one receives them: it is the one the generated document keeps.
  • The generated response is described by the status's HTTP reason phrase (201 → Created, 202 → Accepted, …), except 200 → Ok and 204 → No content; a status without a registered phrase reads Ok. To describe it yourself, declare the description at that status with the preset's description decorator, for example @Status(201) with @Description(201, 'The user was created.'): the return type fills that response's schema.
  • 204, 205 and 304 carry no body: under one of them the generated response has no schema whatever the return type, and a handler response at that status is not given one. Method.type still holds the real return type.
  • Other handler responses (400, 500, …) stay as they are. A 200 declared on the method, on the controller or document-wide (data.responses of @trapi/swagger) still appears on a method with another success status: the implicit 200 no longer covers it. A method's own response still wins over a document response at the same status.
  • When two handlers set the field, the last one wins.
  • Without successStatus the return type stays under 200/204, described as Ok/No content, and a handler response at 200 keeps whatever schema it declared.

Success media types ​

draft.produces applies to every response of the operation. draft.successProduces scopes media types to the response that carries the return type — a route that streams a PDF on success but answers errors as JSON:

typescript
import { method, readStringOrStringArray } from '@trapi/core';

// @SuccessProduces('application/pdf') — only the success response is a PDF
method({
    match: { name: 'SuccessProduces', on: 'method' },
    apply: (ctx, draft) => {
        const types = readStringOrStringArray(ctx.argument(0));

        if (types) {
            draft.successProduces.push(...types);
        }
    },
});
  • ControllerDraft.successProduces covers every method of the controller, inherited base-class methods included. A method with a non-empty list of its own uses that list instead of the controller's; the two are not merged.
  • The list becomes the produces of the response at the success status: the generated one, or a handler response at that status that declares no produces of its own.
  • A response without a body gets no media types: the generated 204 of a void method, an explicit successStatus of 204, 205 or 304, or a handler response that ends up without a schema.
  • OpenAPI 3.x emits the list as the content types of that one response. Swagger 2.0 has media types only per operation: when the operation declares no produces of its own, the response's list becomes the operation's and so applies to every response.

Finalize hooks ​

A handler sees the draft as the handlers before it left it. When decorators depend on each other (a status decorator that changes what a produces decorator means, a returns decorator that is only valid on a non-void method), a preset reconciles them once, after every handler ran:

typescript
type Preset = {
    // …
    finalizeMethod?: (ctx: MethodFinalizeContext, draft: MethodDraft) => void;
    finalizeController?: (ctx: ControllerFinalizeContext, draft: ControllerDraft) => void;
};

type MethodFinalizeContext = {
    host: { name: string; parentName?: string };
    returnType: () => Type;
};

type ControllerFinalizeContext = {
    host: { name: string; parentName?: string };
};
typescript
const preset: Preset = {
    name: 'my-app/preset',
    methods: [/* … */],
    finalizeMethod: (ctx, draft) => {
        // A method returning a Buffer streams octets, unless a decorator chose its media types.
        if (draft.successProduces.length === 0 && ctx.returnType().typeName === 'buffer') {
            draft.successProduces.push('application/octet-stream');
        }
    },
};
  • finalizeMethod runs once per route method — a verb was set and the method is not hidden — after its decorator and JSDoc handlers, and before the success status is checked and the default response is built. A finalizer that hides the method or clears draft.verb removes it from the controller.
  • ctx.returnType() resolves the method's return type at most once: repeated calls and the default response built afterwards share the result.
  • finalizeController runs only for a class a controller handler claimed (draft.paths set), after its decorator and JSDoc handlers and before its methods are generated, so it cannot see the methods. A finalizer that unsets draft.paths drops the class as a controller.
  • Along an extends chain the parents' finalizers run first, then the preset's own, then those of an inline registry. A preset reached through more than one extends path contributes its handlers and its finalizer once. Finalizers are always additive: there is no replaces for them.
  • A throwing finalizer fails generation, like a throwing handler.

Things to know:

  • Resolving a type registers every named type it reaches in the document's schemas. Call ctx.returnType() only once the method is known to stay visible: a method the finalizer hides afterwards still leaves its return type's named types in the schemas. The same holds for a return type documented under a no-content status (204, 205, 304): no response references it, but its named types are still in the schemas.
  • A method finalizer runs before the parts derived from the method signature are added. The method's leading JSDoc comment still wins over draft.description, and the parameters derived from the signature are not on the draft; only handler-contributed ones are.
  • The strict readers (requireArgument, requireNumber, requireString) name the decorator from ctx.decorator. A hand-built HandlerContext without it reports the decorator as <unknown>; build test contexts with createHandlerContext instead.

replaces semantics ​

When a preset uses extends, parent handlers run additively by default. To shadow a parent handler, set replaces:

typescript
type ReplacesPolicy = true | string;

The three cases:

replaces: true — shadow every parent ​

typescript
const preset: Preset = {
    name: 'my-app/preset',
    extends: ['@trapi/preset-decorators-express', '@my-org/legacy-preset'],
    controllers: [
        controller({
            match: { name: 'Controller', on: 'class' },
            replaces: true,                   // shadows BOTH parents' Controller handlers
            apply: (ctx, draft) => { /* ... */ },
        }),
    ],
};

Use when you want full control over a decorator and don't care which parent contributed the original handler.

replaces: '<presetName>' — shadow one specific parent ​

typescript
controller({
    match: { name: 'Controller', on: 'class' },
    replaces: '@trapi/preset-decorators-express',   // shadows only the express preset's handler
    apply: (ctx, draft) => { /* ... */ },
});

Use when extending multiple presets and you only want to override one.

Same-preset siblings — always additive ​

typescript
const preset: Preset = {
    name: 'my-app/preset',
    methods: [
        method({ match: { name: 'Get', on: 'method' }, apply: (_ctx, draft) => { draft.verb = 'get'; } }),
        method({ match: { name: 'Get', on: 'method' }, apply: (_ctx, draft) => { draft.tags.push('http'); } }),
    ],
};

Both run, in source order. replaces only affects inherited handlers — it has no effect on handlers in the same preset.

Strict mode ​

loadRegistry(preset, { resolver, strict: true }) throws CoreError(PRESET_REPLACES_NO_MATCH) when a replaces entry doesn't shadow any parent. Useful as a CI gate when the parent preset evolves.

Apply helpers ​

Three writer helpers cut handler boilerplate.

into(key) ​

Scalar writer. Use for fields that hold a single value (path, description, verb, …). Object/array/unresolvable arguments are intentionally ignored — use append for arrays.

typescript
into(key).positional(index)        // read positional arg, write to draft[key]
into(key).typeArgument(index = 0)  // resolve type arg, write to draft[key]
typescript
method({ match: { name: 'Path', on: 'method' }, apply: into('path').positional(0) });

append(key) ​

Array writer. Use for fields that hold lists (tags, produces, security, …). Array arguments are flattened; scalar arguments are pushed as-is.

typescript
append(key).positional(index)   // push the i-th argument
append(key).positionalAll()     // push every argument (spread-style decorators)
typescript
method({ match: { name: 'Tags', on: 'method' }, apply: append('tags').positionalAll() });

flag(key, value = true) ​

Unconditional setter — useful for boolean flags or fixed values that don't depend on argument shape.

typescript
controller({ match: { name: 'Hidden', on: 'class' }, apply: flag('hidden') });
method({ match: { name: 'GetOnly', on: 'method' }, apply: flag('verb', 'get') });

Argument readers ​

Lower-level helpers that handle the common kind checks:

HelperAcceptsReturns
readString(arg)'literal' string, 'identifier' resolving to stringstring | undefined
readNumber(arg)'literal' number, 'identifier' resolving to number (a const, a numeric enum member, an as const member)number | undefined
readBoolean(arg)'literal' booleanboolean | undefined
readStringOrStringArray(arg)string literal/identifier OR array of all-stringsstring[] | undefined

readStringOrStringArray is all-or-nothing — if any array element is non-string the helper returns undefined, never a partial array.

typescript
parameter({
    match: { name: 'Header', on: 'parameter' },
    apply: (ctx, draft) => {
        const name = readString(ctx.argument(0));
        draft.in = ParamKind.Header;
        if (name) draft.name = name;
    },
});

Strict readers ​

The readers above return undefined both for a missing argument and for one they cannot read, so a handler that falls back to a default documents @Status(computeStatus()) as if it had no argument. The strict readers tell the two apart:

typescript
function requireArgument<T>(
    ctx: HandlerContext,
    index: number,
    read: (arg: DecoratorArgument) => T | undefined,
    expected: string,
): T | undefined;

function requireNumber(ctx: HandlerContext, index: number): number | undefined;
function requireString(ctx: HandlerContext, index: number): string | undefined;

They return undefined when the argument is absent and the value when read produces one. When the argument is present but read returns undefined, they throw a CoreError with code DECORATOR_ARGUMENT_INVALID. The message names the decorator, the argument index, the expected shape, Class.method, and file:line when the location is known. requireNumber and requireString wrap readNumber and readString.

typescript
import { method, readNumber, readString, requireArgument } from '@trapi/core';

// @Status(201), @Status('201'), @Status(HttpStatus.Created)
method({
    match: { name: 'Status', on: 'method' },
    apply: (ctx, draft) => {
        const status = requireArgument(
            ctx,
            0,
            (arg) => readString(arg) ?? readNumber(arg),
            'a status code (string or number)',
        );

        if (status !== undefined) {
            draft.successStatus = String(status);
        }
    },
});

Path helpers ​

Two convenience wrappers around the readers for the most common shapes.

setControllerPaths(draft, arg) ​

Reads the first argument as a string-or-string-array and writes to draft.paths, defaulting to [''] when missing or unresolvable. Use inside a controller(...) handler.

typescript
controller({
    match: { name: 'Controller', on: 'class' },
    apply: (ctx, draft) => setControllerPaths(draft, ctx.argument(0)),
});

setMethodPath(draft, arg) ​

Reads the first argument as a string and writes to draft.path if present. Leaves the field untouched otherwise (the orchestrator initialises it to '').

typescript
method({
    match: { name: 'Get', on: 'method' },
    apply: (ctx, draft) => {
        draft.verb = 'get';
        setMethodPath(draft, ctx.argument(0));
    },
});

Markers ​

marker tags a handler with a semantic concept the type resolver consults. Closed concept set:

typescript
type ResolverMarker =
    | 'hidden'
    | 'deprecated'
    | 'extension'
    | { numeric: 'int' | 'long' | 'float' | 'double' };
MarkerUsed byEffect
'hidden'resolverexcludes the class/method/property from the spec
'deprecated'resolverflags as deprecated
'extension'resolverreads x-* extensions (key/value from positional args 0/1) on properties
{ numeric: 'int' | 'long' | 'float' | 'double' }resolvernarrows number to the specified numeric kind

MarkerName and NumericKind are as const objects with the same value union, so MarkerName.Hidden and 'hidden' both type-check.

typescript
import { MarkerName, NumericKind, controller, flag, parameter } from '@trapi/core';

controller({
    match: { name: 'Skip', on: 'class' },         // renamed @Skip
    apply: flag('hidden'),
    marker: MarkerName.Hidden,                    // resolver treats @Skip as hidden
});

parameter({
    match: { name: 'AsInteger', on: 'parameter' }, // renamed @AsInteger
    apply: (_ctx, draft) => {
        draft.validators.isInt = { value: 'int' };
    },
    marker: { numeric: NumericKind.Int },
});

JSDoc handlers carry markers too — marker: 'deprecated' on a JSDoc handler matching tag: 'gone' makes the resolver treat @gone as deprecated.

Registry construction ​

For programmatic wiring (custom generators, fixture-driven tests, ad-hoc handler injection):

createRegistry(input?) ​

typescript
function createRegistry(input?: Partial<Registry>): Registry;

Build a Registry, optionally seeded with handler arrays and the finalizer arrays methodFinalizers / controllerFinalizers. Any kind omitted from input falls back to an empty array. The provided arrays are copied — mutating the result does not affect input.

typescript
import { createRegistry, method } from '@trapi/core';

const registry = createRegistry({
    methods: [
        method({ match: { name: 'Get', on: 'method' }, apply: (_ctx, draft) => { draft.verb = 'get'; } }),
    ],
});

await generateMetadata({ entryPoint: 'src/**/*.ts', registry });

mergeRegistries(a, b) ​

typescript
function mergeRegistries(a: Registry, b: Registry): Registry;

Concatenate two registries kind-by-kind, finalizers included. Earlier handlers run first inside the orchestrator, so callers wanting override-by-running-later semantics should pass the dominant registry as b.

validatePreset(input) ​

typescript
async function validatePreset(input: unknown): Promise<Preset>;

Validate an unknown value against the v2 Preset zod schema. Throws with a path to the offending field. Useful when loading user-supplied presets without going through loadRegistry (e.g. building tooling around presets).

Marker discovery ​

For tooling that needs to enumerate decorator names by concept:

namesForMarker(registry, predicate) ​

typescript
function namesForMarker(
    registry: Registry,
    predicate: (marker: ResolverMarker) => boolean,
): Set<string>;

Collect the unique decorator names whose marker matches the predicate. Used by the type resolver to find preset-renamed decorators.

typescript
import { namesForMarker, isHiddenMarker } from '@trapi/core';

const hiddenDecoratorNames = namesForMarker(registry, isHiddenMarker);
// → Set { 'Hidden', 'Skip' } if the preset registers both

Predicate helpers ship alongside: isHiddenMarker, isDeprecatedMarker, isExtensionMarker, numericMarkerKind (returns the numeric kind or undefined).

tagsForMarker(registry, predicate) ​

typescript
function tagsForMarker(
    registry: Registry,
    predicate: (marker: ResolverMarker) => boolean,
): Set<string>;

JSDoc analogue — collects unique JSDoc tag names whose marker matches.

Identity helpers ​

typescript
const controller = (handler: ControllerHandler): ControllerHandler => handler;
const method = (handler: MethodHandler): MethodHandler => handler;
const parameter = (handler: ParameterHandler): ParameterHandler => handler;
const controllerJsDoc = (handler: ControllerJsDocHandler): ControllerJsDocHandler => handler;
const methodJsDoc = (handler: MethodJsDocHandler): MethodJsDocHandler => handler;
const parameterJsDoc = (handler: ParameterJsDocHandler): ParameterJsDocHandler => handler;

Pure pass-through. Their job is to preserve the narrow handler type at the declaration site so TypeScript catches match.on typos and apply-signature mismatches inline.

Test helpers ​

@trapi/core/test-helpers (or import { ... } from '@trapi/core') exports utilities for unit-testing handlers without a TypeScript program:

typescript
import {
    literalArg, identifierArg, arrayArg, objectArg, unresolvableArg, typeArg,
    createHandlerContext,
    newControllerDraft,
} from '@trapi/core';

const ctx = createHandlerContext({
    host: { name: 'UsersController' },
    args: [literalArg('/users')],
});

const draft = newControllerDraft({ name: 'UsersController', location: 'test.ts' });
controllerHandler.apply(ctx, draft);

expect(draft.paths).toEqual(['/users']);
HelperBuilds
literalArg(value){ kind: 'literal', raw: value }
identifierArg(value){ kind: 'identifier', raw: value }
arrayArg(items){ kind: 'array', raw: items }
objectArg(obj){ kind: 'object', raw: obj }
unresolvableArg(){ kind: 'unresolvable', raw: undefined }
typeArg(type){ resolve: () => type }
createHandlerContext({ host?, args?, typeArgs?, parameterType?, decorator? })a HandlerContext (decorator defaults to { name: 'Test' })