Skip to Content
API Reference

API Reference

Core

initSegment

Createsd Next.js App Route handlers used by the main Optional Catch-all Segment . The function accepts the following options:

  • segmentName?: string - the name of the segment that’s going to be used in the route. Default is empty string (root segment).
  • controllers: Record<string, Function> - the list of Controllers.
  • exposeValidation?: boolean - set to false if you want to hide validation logic from the client-side code.
  • emitSchema?: boolean - set to true if you want to emit the schema for the segment. The schema is going to be emitted to the .vovk-schema folder.
  • onError?: (err: Error, req: VovkRequest) => void | Promise<void> - called on Controller exceptions, can be used to log errors by a third-party service. The second argument can be utilised to retrieve request URL, authorisation info, and other useful information about the failed request.

JSONLinesResponse

JSONLinesResponse is a utility class for creating responses in the JSON Lines format. It extends the standard Response class and adds support for streaming JSON objects as individual lines. See JSON Lines documentation for more info.

Decorators

@get, @post, @put, @patch, @del, @head, @options

HTTP method decorators define an HTTP method for a handler. They accept two optional arguments:

  • path? = '' - the path for the route.
  • opts?: { cors?: boolean, headers?: Record<string, string>, staticParams?: Record<string, string>[] } - options for the route. If cors is set to true, it will add CORS headers to the response and make OPTIONS HTTP method be properly handled. headers is an object with headers to be added to the response. staticParams (@get decorator only) is an array of objects with static parameters that can be used in the route path, e.g. [{ id: '123' }].
import { get } from 'vovk'; export default class HelloController { @get('world', { cors: true, headers: { 'x-hello': 'world' }, staticParams: [{ id: '123' }] }) static getHelloWorld(req, { id }: { id: string }) { return { hello: 'world', id }; } }

Each decorator has an .auto() method that can be used to generate the path automatically based on the controller and method names. It accepts the same options as the decorator itself.

import { get } from 'vovk'; export default class HelloController { @get.auto({ cors: true, headers: { 'x-hello': 'world' }, staticParams: [{ id: '123' }] }) static getHelloWorld(req, { id }: { id: string }) { return { hello: 'world', id }; } }

@prefix

@prefix(p: string) decorator used to prepend a sub-path to the endpoint. It’s usage is optional.

import { prefix, get } from 'vovk'; @prefix('hello') export default class HelloController { @get('world') static getHelloWorld() { return { hello: 'world' }; } }

@operation

@operation(openAPIOperationObject) decorator can be used to add OpenAPI documentation to the controller method. It accepts an object with summary, description and other OpenAPI Operation Object properties.

import { operation } from 'vovk'; export default class HelloController { @operation({ summary: 'Get Hello World', description: 'Returns a hello world message', }) @get('world') static getHelloWorld() { return { hello: 'world' }; } }

Utils

createDecorator

createDecorator is a higher-order function that produces a decorator factory (a function that returns a decorator) for controller class methods. It accepts a middleware function with the following parameters:

import { createDecorator, get } from 'vovk'; const myDecorator = createDecorator( (req, next, a: string, b: number) => { // do something with the request }, (a: string, b: number) => { // modify schema here } ); export default class MyController { @get.auto() @myDecorator('foo', 1) // Passes 'foo' as 'a', and 1 as 'b' static doSomething() { // ... } }

See decorators docs for more info.

fetcher

Function that creates a data fetching layer for the RPC client. It handles HTTP requests, client-side validation, and response parsing. It’s imported by the generated TypeScript, ESM and CJS files and can be customized at config. A new fetcher can be created using createFetcher function.

createFetcher

Function that creates a custom fetcher for the RPC client. It accepts a generic type parameter that defines the options for the resulting RPC methods. The function returns a fetcher function that is going to be used in the createRPC function.

./src/lib/fetcher.ts
import { createFetcher } from 'vovk'; export const fetcher = createFetcher<{ successMessage?: string; // "Successfully created a new user" useAuth?: boolean; // if true, Authorization header will be set someOtherCustomFlag?: boolean; // any custom flag that you want to pass to the RPC method }>({ prepareRequestInit: async (init, { useAuth, someOtherCustomFlag }) => { // ... return { ...init, headers: { ...init.headers, ...(useAuth ? { Authorization: 'Bearer token' } : {}), }, }; }, transformResponse: async (data, { someOtherCustomFlag }) => { // ... return { ...data, }; }, onSuccess: async (data, { successMessage }) => { if (successMessage) { alert(successMessage); } }, onError: async (error) => { alert(error.message); }, });

generateStaticAPI

Function that generates API that is generated at build time instead of on-demand at request time. It accepts a record of controllers and an optional slug that is used to generate the static API path. The function returns an array of static parameters that can be used in the generateStaticParams function.

src/app/api/[[...vovk]]/route.ts
// ... export type Controllers = typeof controllers; export function generateStaticParams() { return generateStaticAPI(controllers); } export const { GET } = initSegment({ controllers });

See static segment documentation for more info.

withValidationLibrary (advanced)

A lower-order function that allows to create custom validation function for controller methods. See source code of Zod 3 validation library  for an example.

createStandardValidation

Creates a custom validation library that uses Standard Schema. The only option of this function is toJSONSchema function that defines how to convert the models to JSON Schema format.

src/lib/withArk.ts
import type { type } from 'arktype'; import { createStandardValidation } from 'vovk'; export const withArk = createStandardValidation({ toJSONSchema: (model: type) => model.toJsonSchema(), });
src/modules/user/UserController.ts
import { prefix, post, operation } from 'vovk'; import { type } from 'arktype'; import { withArk } from '@/lib/withArk'; @prefix('users') export default class UserController { @operation({ summary: 'Update user', description: 'Update user by ID with', }) @post('{id}') static updateUser = withArk({ body: type({ name: type('string').describe('User full name'), age: type('0 < number < 120').describe('User age'), email: type('string.email').describe('User email'), }), // ... async handle(req, { id }) { // ... }, }); }

multitenant

A Next.js middleware  utility that routes subdomains to specific segments. For more info check multitenant guide.

// ... middleware ... const { action, destination, message, subdomains } = multitenant({ requestUrl: request.url, requestHost: request.headers.get('host') ?? '', targetHost: process.env.VERCEL ? 'multitenant.vovk.dev' : 'localhost:3000', overrides: { // ... }, }); // ...

createLLMTools

An utility function that turns RPC modules or controllers into LLM tools, based on input schemas of their methods. For more info check AI tools guide.

import { createLLMTools } from 'vovk'; import { UserRPC } from 'vovk-client'; import TaskController from '@/modules/task/TaskController'; const { tools, toolsByName } = createLLMTools({ meta: { hello: 'world' }, modules: { UserRPC, TaskController, }, resultFormatter: (result) => `Result: ${JSON.stringify(result, null, 2)}`, onExecute: (result, { moduleName, handlerName, body, query, params }) => console.log(`${moduleName}.${handlerName} executed with`, { body, query, params, result, }), onError: (e) => console.error("Error", e), });

modules

Key-value object where keys are module names and values are objects with methods. Each method should have schema: VovkHandlerSchema property, and either of isRPC: true (for RPC modules) or fn function (for Controllers).

onExecute

Called after each tool execution. Accepts 2 arguments: result - the result of the tool execution, and an object with extra info.

onError

Called when an error is thrown during tool execution. Accepts 1 argument: the error object.

resultFormatter: 'mcp' | Function

A function that formats the result of the tool execution. It accepts 2 argument: the result of the tool execution and the handler schema: VovkHandlerSchema. The function should return data in format that’s sent back to the LLM when function is executed. If set to 'mcp', it will format the result in a way that is compatible with MCP  format ({ content: [{ type: 'text', text: 'Serialized result text' }] }).

meta

Data that’s going to be passed as meta property of each function (controller handler or RPC method). See meta for more info.

caller (advanced)

The low level function that calls the handler function or RPC method. Check source code  of defaultCaller function for more info.

createValidateOnClient

Creates validateOnClient function is used to define how client-side validation should be performed for RPC methods for all segments or for some segments. createValidateOnClient accepts validate property that accepts input data, validation schema, and some additional options, and returns the validated data or throws an error if validation fails.

./src/lib/validateOnClient.ts
import { validateData } from 'validation-library'; import { createValidateOnClient, HttpException, HttpStatus } from 'vovk'; export const validateOnClient = createValidateOnClient({ validate: async (input, schema, meta) => { const isValid = validateData(input, schema); if (!isValid) { throw new HttpException(HttpStatus.NULL, 'Validation failed'); } return input; }, });

For more details on client-side validation, see the Client Validation section.

progressive

An experimental utility function that allows to make one request and get multiple resppnses, each resolved as a promise separately.

const { users: usersPromise, tasks: tasksPromise } = progressive(ProgressiveRPC.streamProgressiveResponse);

HttpException

TODO

Types and enums

VovkRequest

Extends the Next.js built-in NextRequest object in order to make it return proper types for .json(), .nextUrl.searchParams but also adds vovk property that provides more advanced input retrieval methods. See vovk request documentation for more info.

HttpStatus enum

Used to throw and catch errors thrown by the server. Notice NULL member. It can be used to simulate HTTP errors on client validation errors (this approach is used at vovk-zod ).

export enum HttpStatus { NULL = 0, CONTINUE = 100, SWITCHING_PROTOCOLS = 101, PROCESSING = 102, EARLYHINTS = 103, OK = 200, CREATED = 201, ACCEPTED = 202, NON_AUTHORITATIVE_INFORMATION = 203, NO_CONTENT = 204, RESET_CONTENT = 205, PARTIAL_CONTENT = 206, AMBIGUOUS = 300, MOVED_PERMANENTLY = 301, FOUND = 302, SEE_OTHER = 303, NOT_MODIFIED = 304, TEMPORARY_REDIRECT = 307, PERMANENT_REDIRECT = 308, BAD_REQUEST = 400, UNAUTHORIZED = 401, PAYMENT_REQUIRED = 402, FORBIDDEN = 403, NOT_FOUND = 404, METHOD_NOT_ALLOWED = 405, NOT_ACCEPTABLE = 406, PROXY_AUTHENTICATION_REQUIRED = 407, REQUEST_TIMEOUT = 408, CONFLICT = 409, GONE = 410, LENGTH_REQUIRED = 411, PRECONDITION_FAILED = 412, PAYLOAD_TOO_LARGE = 413, URI_TOO_LONG = 414, UNSUPPORTED_MEDIA_TYPE = 415, REQUESTED_RANGE_NOT_SATISFIABLE = 416, EXPECTATION_FAILED = 417, I_AM_A_TEAPOT = 418, MISDIRECTED = 421, UNPROCESSABLE_ENTITY = 422, FAILED_DEPENDENCY = 424, PRECONDITION_REQUIRED = 428, TOO_MANY_REQUESTS = 429, INTERNAL_SERVER_ERROR = 500, NOT_IMPLEMENTED = 501, BAD_GATEWAY = 502, SERVICE_UNAVAILABLE = 503, GATEWAY_TIMEOUT = 504, HTTP_VERSION_NOT_SUPPORTED = 505, }

VovkSchema

The full schema of composed client or for a segment in segmented client. Can be represented as { segments: { [key: string]: VovkSegmentSchema }; meta?: VovkMetaSchema }.

VovkSegmentSchema

The schema of a segment. Contains segment information and a record of controllers. Can be represented as { controllers: { [key: string]: VovkControllerSchema }; segmentName: string; segmentType: 'segment' | 'mixin' }.

VovkControllerSchema

The schema of a controller. Can be represented as { rpcModuleName: string; originalControllerName?: string; prefix?: string; forceApiRoot?: string; handlers: { [key: string]: VovkHandlerSchema } }.

VovkHandlerSchema

The schema of a handler. Contains paths, HTTP methods, validation schemas, etc.

VovkMetaSchema

The schema of the meta information.

VovkOutput

Allows to infer the output type of the controller method or RPC method when output validation is used: VovkOutput<typeof MyController.method> or VovkOutput<typeof MyRPC.method>.

VovkIteration

Allows to infer the iteration type of the controller method or RPC method when iteration validation is used: VovkIteration<typeof MyController.method> or VovkIteration<typeof MyRPC.method>.

VovkBody

Allows to infer the type of the request input body of the controller method or RPC method when body validation is used: VovkBody<typeof MyController.method> or VovkBody<typeof MyRPC.method>.

VovkQuery

Allows to infer the type of the request query of the controller method or RPC method when query validation is used: VovkQuery<typeof MyController.method> or VovkQuery<typeof MyRPC.method>.

VovkParams

Allows to infer the type of the request params of the controller method or RPC method when params validation is used: VovkParams<typeof MyController.method> or VovkParams<typeof MyRPC.method>.

VovkReturnType

As output validation isn’t required, the VovkReturnType type allows to infer the returned type of the controller method or RPC method: VovkReturnType<typeof MyController.method> or VovkReturnType<typeof MyRPC.method>.

VovkYieldType

As iteration validation isn’t required, the VovkYieldType type allows to infer the yielded type of the controller method or RPC method: VovkYieldType<typeof MyController.method> or VovkYieldType<typeof MyRPC.method>.

VovkConfig

The shape of the config file.

VovkLLMTool

The shape of the LLM tool created by createLLMTools function.

System functions for additional hacking (advanced)

createVovkApp

An internal function that creates the Vovk.ts app with the decorators and init function.

export const { get, post, put, patch, del, head, options, prefix, initSegment } = createVovkApp();

createRPC

Function that creates RPC modules out of schema and types inferred from controllers. It’s imported by the generated TypeScript, ESM and CJS files and can be customized at config.

createCodeSamples

Creates code samples that are used by Scalar and README.md generators.

openAPIToVovkSchema

Converts OpenAPI schema to Vovk.ts schema.

vovkSchemaToOpenAPI

Converts Vovk.ts schema to OpenAPI schema.

resolveGeneratorConfigValues

Resolves the generator config values for specific case (if it’s a bundle, segmented or composed client, etc) based on the provided schema and options.

System types

KnownAny

The only type that isn’t named with Vovk prefix, represents any.

VovkRPCModule

An object that represents an RPC module created by createRPC function.

VovkFetcher

An object that represents a fetcher function used to make API requests.

VovkFetcherOptions

An object that represents the options for the fetcher function.

VovkStreamAsyncIterable

The iterable object returned by an RPC method for JSONLines responses. Besides Symbol.asyncIterator, Symbol.dispose, Symbol.asyncDispose methods, it also contains status property with HTTP status code, asPromise method that resolves all data as a single promise, onIterate method that accepts a callback function and calls it on each iteration, and cancel method that cancels the request.

const response = await StreamRPC.streamLines(); for await (const item of response) { console.log(item); } const allItems = await response.asPromise();

VovkValidateOnClient

A function that represents the client-side validation function created by createValidateOnClient function.

VovkErrorResponse

The shape of error responses.

VovkTypedMethod

An internal type used by withValidationLibrary function that adds required types to the controller method for further inference.

VovkBasicJSONSchema

A basic JSON Schema object used internally with type, properties, and all other JSON Schema keywords.

VovkSchemaIdEnum

An enum that contains IDs of the JSON Schema files that are generated by Vovk.ts.

export enum VovkSchemaIdEnum { META = 'https://vovk.dev/api/schema/v3/meta.json', CONFIG = 'https://vovk.dev/api/schema/v3/config.json', SEGMENT = 'https://vovk.dev/api/schema/v3/segment.json', SCHEMA = 'https://vovk.dev/api/schema/v3/schema.json', }

VovkOperationObject

Extends OperationObject imported from openapi3-ts/oas31  package by adding LLM-tool-specific properties that start with x-tool-.

VovkValidationType

A union type of possible validation types.

export type VovkValidationType = 'body' | 'query' | 'params' | 'output' | 'iteration';

VovkStrictConfig

An internal type that represents the config file with all default values applied.

VovkGeneratorConfig

The configuration options for the generator that can be defined as root-level generatorConfig, generatorConfig.segments[segmentName], bundle.generatorConfig, templateDef.generatorConfig in the config file. The actual values are resolved by resolveGeneratorConfigValues function.

VovkReadmeConfig

The configuration options for the README generation at VovkGeneratorConfig.readme, such as banner, installCommand or description.

VovkSamplesConfig

The configuration options for the code samples generation at VovkGeneratorConfig.samples, such as apiRoot or headers.

VovkOpenAPIMixin

The configuration options for the OpenAPI generation at VovkGeneratorConfig.openAPIMixin. See OpenAPI Mixins for more info.

Last updated on