Routes API
Generated public TypeScript reference for @relkit/routes.
Common APIs
For configuration and examples, read define, middleware, routes.
For a complete workflow, follow upload product images, connect react, register users in a transaction, email password sign in, create and build an api.
Frontend usage
Call a defined route shows the client side of this capability.
Public imports
@relkit/routes— 91 exports
All exported APIs
Names link to their complete contracts. Re-exports share their original contract; legacy exports keep their separate identity. Examples link to the API’s inline sample, a maintained repository usage, or the shared module walkthrough.
define-middleware.ts
defineMiddleware
Defines one automatically discovered path-scoped HTTP middleware handler.
Throws
TypeError for an invalid path or handler.
Example
import { defineMiddleware } from "@relkit/app/routes";
export default defineMiddleware("/orders/*", async (context, next) => {
if (context.req.header("authorization") === undefined) {
return context.json({ error: "unauthorized" }, 401);
}
await next();
});
Signature
declare const defineMiddleware: (
path: string,
handler: MiddlewareHandler,
) => MiddlewareDescriptor<string>;
Since v0.1.0
MiddlewareContext
Signature
declare const MiddlewareContext: MiddlewareContext;
MiddlewareDescriptor
Signature
declare const MiddlewareDescriptor: MiddlewareDescriptor<Id>;
MiddlewareHandler
Signature
declare const MiddlewareHandler: MiddlewareHandler;
defineMiddlewareEffect
Defines path-scoped middleware through a typed Effect.
Example
Effect.runSync(defineMiddlewareEffect("/orders/*", handler));
Signature
declare const defineMiddlewareEffect: (
path: string,
handler: MiddlewareHandler,
) => Effect.Effect<MiddlewareDescriptor<string>, RouteOperationError, never>;
isMiddlewareDescriptor
Checks a middleware descriptor synchronously.
Example
isMiddlewareDescriptor(value);
Signature
declare const isMiddlewareDescriptor: (value: unknown) => value is MiddlewareDescriptor;
isMiddlewareDescriptorEffect
Checks a middleware descriptor through Effect.
Example
Effect.runSync(isMiddlewareDescriptorEffect(value));
Signature
declare const isMiddlewareDescriptorEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
isMiddlewarePath
Checks a middleware path synchronously.
Example
isMiddlewarePath("/orders/*");
Signature
declare const isMiddlewarePath: (value: unknown) => value is string;
isMiddlewarePathEffect
Checks an HTTP middleware path through Effect.
Example
Effect.runSync(isMiddlewarePathEffect("/orders/*"));
Signature
declare const isMiddlewarePathEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
define-middleware.types.ts
MiddlewareContext (interface)
Invocation-scoped capabilities provided to middleware.
Example
const context: MiddlewareContext = relkit;
Signature
export interface MiddlewareContext {
readonly signal: AbortSignal;
readonly env: ResolvedApplicationEnv;
readonly auth: AuthContext;
readonly log: PublicLogger;
readonly time: PublicClock;
readonly trace: PublicTrace;
}
MiddlewareDescriptor (interface)
Frozen descriptor for one middleware handler.
Example
const descriptor: MiddlewareDescriptor = defineMiddleware("/orders", handler);
Signature
export interface MiddlewareDescriptor<Id extends string = string> extends DescriptorBase<
"middleware",
Id
> {
readonly path: string;
readonly handler: MiddlewareHandler;
}
MiddlewareHandler (type alias)
A path-scoped HTTP middleware callback.
Example
const handler: MiddlewareHandler = async (_context, next) => next();
Signature
type MiddlewareHandler = (
context: Context,
next: Next,
relkit: MiddlewareContext,
) => MaybePromise<Response | void>;
define-route.ts
defineRoute
Defines one HTTP method exported by a nested route.ts module.
The compiler derives the method from the named export and the path from the
file. Omit id for a source-derived route identity, and omit request and
responses when schema-based inference represents the transport; explicit
mappings replace inference completely. Matching path names map into reusable
function input.
Throws
TypeError for invalid authoring input.
Example
A GET route with inferred path and query input
```ts
import { defineFunction } from "@relkit/app/functions"
import { defineRoute } from "@relkit/app/routes"
import { z } from "@relkit/app/schema"
const listOrders = defineFunction({
id: "orders.list",
input: z.object({ status: z.string().optional() }),
output: z.object({ count: z.number().int() }),
handler: async () => ({ count: 0 })
})
export const GET = defineRoute({ target: listOrders })
**Signature**
```ts
declare const defineRoute: { <const Id extends string, const Handler extends RawRouteOptions<Id>["handler"]>(options: RawRouteOptions<Id, Handler>): RawRouteDescriptor<Id, Handler>; <const Id extends string, const Target extends FunctionRefAny, const Request extends HttpRequestMapping | undefined = undefined>(options: FunctionRouteOptions<Id, Target, Request>): FunctionRouteDescriptor<Id, Target, Request>; }
Since v0.1.0
Backend and frontend example
Backend — these maintained files define the operation used by the frontend below.
/** Maps the HTTP endpoint to its owning service's public member. */
import { defineRoute } from "@relkit/app/routes";
import echo from "@app/services/echo/service.js";
export const POST = defineRoute({
target: echo.echo,
});
Frontend
After frontend installation, contract pull, and provider setup,
call this POST /echo operation with its domain input. The route produces both the React selector
POST /echo and the TypeScript operation route.post.echo.
Render this component under RelkitClientProvider. Clicking the button sends { message } and
displays the inferred { message: string } result:
"use client";
/** Calls the documented POST /echo function route after an explicit user action. */
import { useRelkitClient, useRouteMutation } from "@relkit/client/react";
/** Sends domain input and renders the validated output; the hook owns mutation state.
* @returns An Echo button with pending, failure, and success feedback. */
export function EchoButton() {
const { status } = useRelkitClient();
const echo = useRouteMutation("POST /echo");
return (
<section>
<button
disabled={status !== "ready" || echo.isPending}
onClick={() => echo.mutate({ message: "Hello from the frontend" })}
>
Send message
</button>
{echo.isPending && <p role="status">Sending…</p>}
{echo.isError && <p role="alert">{String(echo.error)}</p>}
{echo.isSuccess && <p>{echo.data.message}</p>}
</section>
);
}Without React, load the browser identity before the mutation and call the generated operation:
/** Calls the Echo contract from a TypeScript browser frontend without React or backend source imports. */
import { createClient } from "@relkit/client";
/** Sends one message over RPC using types from the caller's pulled contract.
* @param baseUrl - Public backend origin, or the frontend origin when proxying RPC.
* @param message - Nonempty message accepted by the Echo function.
* @returns The validated message output; transport and application failures reject. */
export async function echoMessage(baseUrl: string, message: string) {
const response = await fetch(new URL("/_relkit/v1/client/identity", baseUrl), {
credentials: "include",
cache: "no-store",
});
if (!response.ok) throw new Error(`Identity request failed (${response.status})`);
const identity = await response.json();
if (
!identity ||
typeof identity.identityScope !== "string" ||
typeof identity.sessionEpoch !== "string"
) {
throw new Error("The backend returned an invalid client identity");
}
const client = createClient({
baseUrl,
headers: {
"x-relkit-identity-scope": identity.identityScope,
"x-relkit-session-epoch": identity.sessionEpoch,
},
});
return client["route.post.echo"]({ message });
}The React provider performs this identity step for hooks.
These calls use RPC over /rpc, with the same authorization and policy. Pass domain input rather
than assembling the route’s REST mapping. Raw handlers and routes with client: false do not
generate these operations. Never import the backend descriptor into the browser.
Reference: useRouteMutation,
createClient. Continue with mutations.
“./route.types.js” (namespace export)
Re-exports all named exports from the “./route.types.js” module.
Signature
export * from "./route.types.js";
defineRouteEffect
Defines a raw or function route through Effect.
Example
Effect.runSync(defineRouteEffect({ target: listOrders }));
Signature
declare const defineRouteEffect: {
<const Id extends string, const Handler extends RawRouteOptions<Id>["handler"]>(
options: RawRouteOptions<Id, Handler>,
): Effect.Effect<RawRouteDescriptor<Id, Handler>, RouteOperationError>;
<
const Id extends string,
const Target extends FunctionRefAny,
const Request extends HttpRequestMapping | undefined = undefined,
>(
options: FunctionRouteOptions<Id, Target, Request>,
): Effect.Effect<FunctionRouteDescriptor<Id, Target, Request>, RouteOperationError>;
};
define-service-routes.ts
SERVICE_ROUTE_METHODS
Signature
declare const SERVICE_ROUTE_METHODS: readonly [
"GET",
"POST",
"PUT",
"PATCH",
"DELETE",
"HEAD",
"OPTIONS",
];
ServiceRouteEntry
Signature
declare const ServiceRouteEntry: ServiceRouteEntry<Service>;
ServiceRouteMethod
Signature
declare const ServiceRouteMethod: ServiceRouteMethod;
ServiceRouteOptions
Signature
declare const ServiceRouteOptions: ServiceRouteOptions<Name, Target>;
ServiceRoutesOptions
Signature
declare const ServiceRoutesOptions: Partial<
Readonly<Record<ServiceRouteMethod, ServiceRouteEntry<Service>>>
>;
ServiceRoutesResult
Signature
declare const ServiceRoutesResult: Readonly<{
[Method in keyof Options]: FunctionRouteDescriptor<
string,
Extract<
ServiceFunctions<Service>[Extract<
EntryName<Options[Method]>,
Extract<keyof ServiceFunctions<Service>, string>
>],
FunctionRefAny
>,
EntryRequest<Options[Method]>
>;
}>;
defineServiceRoutes
Creates explicit HTTP routes for a service synchronously.
Throws
TypeError for invalid method or member references.
Example
defineServiceRoutes(service, { GET: "list" });
Signature
declare const defineServiceRoutes: <
const Service extends ServiceDescriptor<string, any, any>,
const Options extends ServiceRoutesOptions<Service>,
>(
service: Service,
options: Options & Record<Exclude<keyof Options, ServiceRouteMethod>, never>,
) => ServiceRoutesResult<Service, Options>;
Backend and frontend example
Backend — these maintained files define the operation used by the frontend below.
/**
* Maps order HTTP operations to public service members with the existing request
* and rate-limit policies. The rate-limit reference addresses the declared cache
* by its stable identity without importing a private service implementation.
*/
import { defineServiceRoutes, http } from "@relkit/app/routes";
import { z } from "@relkit/app/schema";
import orders from "../../services/orders/service.js";
export const { GET, POST } = defineServiceRoutes(orders, {
GET: "searchOrders",
POST: {
member: "createOrder",
request: http.input({
orderId: http.header("idempotency-key"),
customerEmail: http.header("x-customer-email"),
sku: http.body("sku"),
quantity: http.body("quantity"),
}),
rateLimit: {
limit: 20,
windowMs: 60_000,
key: http.header("x-customer-email"),
store: {
ref: { kind: "cache", id: "orders.rate-limits" },
key: z.string(),
value: z.number().int().nonnegative(),
},
},
successStatus: 201,
},
});
Frontend
After frontend setup and pulling this backend’s contract,
render this component under RelkitClientProvider. Each exported service-route method produces
its own typed operation: GET /orders reads the search count, while POST /orders creates an order.
"use client";
/** Calls both commerce service-route methods using their generated domain inputs inside the frontend provider. */
import { useRelkitClient, useRoute, useRouteMutation } from "@relkit/client/react";
/** Reads the Orders search count and submits one explicit creation without replaying a failed write.
* @returns Typed query results, creation feedback, and an action available after identity is ready. */
export function Orders() {
const { status } = useRelkitClient();
const orders = useRoute("GET /orders", { input: { status: "pending" } });
const create = useRouteMutation("POST /orders");
return (
<section>
{orders.isPending && <p role="status">Loading orders…</p>}
{orders.data && <p>{orders.data.count} orders</p>}
{orders.isError && <p role="alert">{orders.error.message}</p>}
<button
disabled={status !== "ready" || !create.isIdle}
onClick={() =>
create.mutate({
orderId: crypto.randomUUID(),
customerEmail: "reader@example.com",
sku: "book",
quantity: 1,
})
}
>
Create an order
</button>
{create.isPending && <p role="status">Creating…</p>}
{create.isSuccess && <p>Created: {create.data.orderId}</p>}
{create.isError && (
<p role="alert">{create.error.message}. Check the outcome before retrying.</p>
)}
</section>
);
}
status, count, and the creation input come from the selected functions’ schemas. RPC receives
orderId and customerEmail as input fields even though REST maps them from headers. A service’s
public member alone is not a browser endpoint: the client-exposed route supplies that boundary.
Reference: useRoute, useRouteMutation.
See request mapping for the REST side and
mutations for submission and recovery behavior.
defineServiceRoutesEffect
Creates explicit service routes through an Effect.
Example
Effect.runSync(defineServiceRoutesEffect(service, { GET: "list" }));
Signature
declare const defineServiceRoutesEffect: <
const Service extends ServiceDescriptor<string, any, any>,
const Options extends Partial<Readonly<Record<ServiceRouteMethod, ServiceRouteEntry<Service>>>>,
>(
service: Service,
options: Options & Record<Exclude<keyof Options, ServiceRouteMethod>, never>,
) => Effect.Effect<
Readonly<{
[Method in keyof Options]: FunctionRouteDescriptor<
string,
Extract<
ServiceFunctions<Service>[Extract<
EntryName<Options[Method]>,
Extract<keyof ServiceFunctions<Service>, string>
>],
FunctionRefAny
>,
EntryRequest<Options[Method]>
>;
}>,
RouteOperationError,
never
>;
define-service-routes.types.ts
ServiceRouteEntry (type alias)
Member name or options for a service route.
Example
type Entry = ServiceRouteEntry<typeof service>;
Signature
type ServiceRouteEntry<Service> = {
[Name in ServiceFunctionName<Service>]:
Name | ServiceRouteOptions<Name, ServiceFunction<Service, Name>>;
}[ServiceFunctionName<Service>];
ServiceRouteMethod (type alias)
Explicit HTTP methods supported by a service route table.
Example
const method: ServiceRouteMethod = "GET";
Signature
type ServiceRouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
ServiceRouteOptions (type alias)
Expanded options selecting one service function.
Example
type Options = ServiceRouteOptions<"list", typeof list>;
Signature
type ServiceRouteOptions<Name extends string, Target extends FunctionRefAny> = Omit<
FunctionRouteOptions<string, Target, HttpRequestMapping | undefined>,
"target"
> & { readonly member: Name };
ServiceRoutesOptions (type alias)
Partial HTTP method table for a service.
Example
type Options = ServiceRoutesOptions<typeof service>;
Signature
type ServiceRoutesOptions<Service> = Partial<
Readonly<Record<ServiceRouteMethod, ServiceRouteEntry<Service>>>
>;
ServiceRoutesResult (type alias)
Route descriptors inferred from a service route table.
Example
type Routes = ServiceRoutesResult<typeof service, { GET: "list" }>;
Signature
type ServiceRoutesResult<Service, Options> = Readonly<{
[Method in keyof Options]: FunctionRouteDescriptor<
string,
ServiceFunction<Service, Extract<EntryName<Options[Method]>, ServiceFunctionName<Service>>>,
EntryRequest<Options[Method]>
>;
}>;
http-dsl-mapping-validation.ts
assertMapping
Asserts a serializable mapping synchronously.
Throws
TypeError for invalid mapping values.
Example
assertMapping(http.path("id"));
Signature
declare const assertMapping: (value: unknown) => asserts value is HttpMappingNode;
assertMappingEffect
Asserts a serializable mapping through Effect.
Example
Effect.runSync(assertMappingEffect(http.path("id")));
Signature
declare const assertMappingEffect: (
value: unknown,
) => Effect.Effect<void, RouteOperationError, never>;
assertMappingValue
Validates a mapping inside an already observed operation.
Throws
RouteInputError for an invalid mapping.
Example
assertMappingValue({ kind: "path", name: "id" });
Signature
declare const assertMappingValue: (value: unknown) => asserts value is HttpMappingNode;
assertRequestMapping
Asserts a request input mapping synchronously.
Throws
TypeError for invalid request mappings.
Example
assertRequestMapping(http.input({}));
Signature
declare const assertRequestMapping: (value: unknown) => asserts value is HttpRequestMapping;
assertRequestMappingEffect
Asserts a request input mapping through Effect.
Example
Effect.runSync(assertRequestMappingEffect(http.input({})));
Signature
declare const assertRequestMappingEffect: (
value: unknown,
) => Effect.Effect<void, RouteOperationError, never>;
assertRequestMappingValue
Validates a request mapping inside an already observed operation.
Throws
RouteInputError for an invalid request mapping.
Example
assertRequestMappingValue({ kind: "input", fields: {} });
Signature
declare const assertRequestMappingValue: (value: unknown) => asserts value is HttpRequestMapping;
isHttpMapping
Checks a serializable mapping synchronously.
Example
isHttpMapping(http.path("id"));
Signature
declare const isHttpMapping: (value: unknown) => value is HttpMappingNode;
isHttpMappingEffect
Checks a serializable mapping through Effect.
Example
Effect.runSync(isHttpMappingEffect(http.path("id")));
Signature
declare const isHttpMappingEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
isHttpRequestMapping
Checks a request input mapping synchronously.
Example
isHttpRequestMapping(http.input({}));
Signature
declare const isHttpRequestMapping: (value: unknown) => value is HttpRequestMapping;
isHttpRequestMappingEffect
Checks a request input mapping through Effect.
Example
Effect.runSync(isHttpRequestMappingEffect(http.input({})));
Signature
declare const isHttpRequestMappingEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
isMappingValue
Checks a non-root mapping during recursive validation.
Example
isMappingValue(http.path("id"));
Signature
declare const isMappingValue: (value: unknown) => value is HttpMappingNode;
http-dsl-methods.types.ts
HttpDslMethods (interface)
Constructor methods for serializable HTTP mappings.
Example
const request = http.input({ id: http.path("id") });
Signature
export interface HttpDslMethods extends HttpDslSources {
/** Named request fields.
* @param fields - Serializable field mappings.
* @returns An input mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.input({ id: http.path("id") });
*/
input<const S extends HttpMappingShape>(fields: S): HttpInputMapping<S>;
/** Named nested fields.
* @param fields - Serializable field mappings.
* @returns A nested object mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.nested({ id: http.path("id") });
*/
nested<const S extends HttpMappingShape>(fields: S): HttpNestedMapping<S>;
/** A serializable constant.
* @param value - JSON-compatible value.
* @returns A constant mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.constant("all");
*/
constant<const V extends JsonValue>(value: V): HttpConstantMapping<V>;
/** An optional source value.
* @param value - Existing mapping node.
* @returns An optional mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.optional(http.query("page"));
*/
optional<const M extends HttpMappingNode>(value: M): HttpOptionalMapping<M>;
/** A source value with a fallback.
* @param value - Existing mapping node
* @param fallback - JSON-compatible default.
* @returns A default mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.default(http.query("page"), "1");
*/
default<const M extends HttpMappingNode, const V extends JsonValue>(
value: M,
fallback: V,
): HttpDefaultMapping<M, V>;
/** A registered transformation.
* @param transform - Reference or stable ID
* @param value - Optional input mapping.
* @returns A transform mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.transform("text.upper", http.body("name"));
*/
transform<const T extends HttpTransformRef | string, const M extends HttpMappingNode>(
transform: T,
value?: M,
): HttpTransformMapping<TransformOutput<T>>;
/** A successful response.
* @param status - HTTP status
* @param schema - Optional body schema.
* @returns A response mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.success(200);
*/
success(status: number, schema?: StandardSchemaV1): HttpResponseMapping;
/** An error response.
* @param errorId - Stable error ID
* @param status - HTTP status
* @param schema - Optional body schema.
* @returns An error response mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.error("not-found", 404);
*/
error(errorId: string, status: number, schema?: StandardSchemaV1): HttpResponseMapping;
/** A validation failure response.
* @param status - HTTP status
* @param schema - Optional body schema.
* @returns A validation-error mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.validationError(422);
*/
validationError(status?: number, schema?: StandardSchemaV1): HttpResponseMapping;
/** A named response.
* @param id - Stable response ID
* @param status - HTTP status
* @param schema - Optional body schema.
* @returns A named response mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.response("accepted", 202);
*/
response(id: string, status: number, schema?: StandardSchemaV1): HttpResponseMapping;
/** A middleware continue decision.
* @returns A continue decision.
* @example http.continue();
*/
continue(): ContinueMapping;
/** A middleware response decision.
* @param response - Mapping or stable response ID
* @param body - Optional body mapping.
* @returns A respond decision.
* @throws TypeError when the mapping input is invalid.
* @example http.respond("accepted");
*/
respond(response: HttpResponseMapping | string, body?: HttpMappingNode): RespondMapping;
}
http-dsl-operations.ts
httpEffects
Effect implementations for each HTTP mapping constructor.
Example
Effect.runSync(httpEffects.input({ id: httpEffects.path("id") }));
Signature
declare const httpEffects: {
constant: <const V extends JsonValue>(
value: V,
) => Effect.Effect<HttpConstantMapping<V>, RouteOperationError, never>;
optional: <const M extends HttpMappingNode>(
value: M,
) => Effect.Effect<HttpOptionalMapping<M>, RouteOperationError, never>;
default: <const M extends HttpMappingNode, const V extends JsonValue>(
value: M,
fallback: V,
) => Effect.Effect<HttpDefaultMapping<M, V>, RouteOperationError, never>;
transform: <const T extends HttpTransformRef | string, const M extends HttpMappingNode>(
transform: T,
value?: M | undefined,
) => Effect.Effect<HttpTransformMapping<TransformOutput<T>>, RouteOperationError, never>;
success: (
status: number,
schema?: StandardSchemaV1<unknown, unknown> | undefined,
) => Effect.Effect<HttpResponseMapping, RouteOperationError, never>;
error: (
errorId: string,
status: number,
schema?: StandardSchemaV1<unknown, unknown> | undefined,
) => Effect.Effect<HttpResponseMapping, RouteOperationError, never>;
validationError: (
status?: number | undefined,
schema?: StandardSchemaV1<unknown, unknown> | undefined,
) => Effect.Effect<HttpResponseMapping, RouteOperationError, never>;
response: (
id: string,
status: number,
schema?: StandardSchemaV1<unknown, unknown> | undefined,
) => Effect.Effect<HttpResponseMapping, RouteOperationError, never>;
continue: () => Effect.Effect<ContinueMapping, RouteOperationError, never>;
respond: (
response: string | HttpResponseMapping,
body?: HttpMappingNode | undefined,
) => Effect.Effect<RespondMapping, RouteOperationError, never>;
input: <const S extends HttpMappingShape>(
fields: S,
) => Effect.Effect<HttpInputMapping<S>, RouteOperationError, never>;
nested: <const S extends HttpMappingShape>(
fields: S,
) => Effect.Effect<HttpNestedMapping<S>, RouteOperationError, never>;
path: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
pathSegments: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
query: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
header: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
cookie: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
body: (
name?: string | undefined,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
wholeBody: () => Effect.Effect<HttpWholeBodyMapping<unknown>, RouteOperationError, never>;
multipart: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
multipartAll: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
};
http-dsl-response-validation.ts
assertResponse
Asserts a response mapping synchronously.
Throws
TypeError for invalid response mappings.
Example
assertResponse(http.success(200));
Signature
declare const assertResponse: (value: unknown) => HttpResponseMapping;
assertResponseEffect
Asserts a response mapping through Effect.
Example
Effect.runSync(assertResponseEffect(http.success(200)));
Signature
declare const assertResponseEffect: (
value: unknown,
) => Effect.Effect<HttpResponseMapping, RouteOperationError, never>;
assertResponseValue
Validates a response inside an already observed operation.
Throws
RouteInputError for an invalid response.
Example
assertResponseValue({ kind: "success", id: "success.200", status: 200 });
Signature
declare const assertResponseValue: (value: unknown) => HttpResponseMapping;
isHttpResponseMapping
Checks a response mapping synchronously.
Example
isHttpResponseMapping(http.success(200));
Signature
declare const isHttpResponseMapping: (value: unknown) => value is HttpResponseMapping;
isHttpResponseMappingEffect
Checks a response mapping through Effect.
Example
Effect.runSync(isHttpResponseMappingEffect(http.success(200)));
Signature
declare const isHttpResponseMappingEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
isMiddlewareDecision
Checks a middleware response decision synchronously.
Example
isMiddlewareDecision(http.continue());
Signature
declare const isMiddlewareDecision: (value: unknown) => value is MiddlewareDecisionMapping;
isMiddlewareDecisionEffect
Checks a middleware response decision through Effect.
Example
Effect.runSync(isMiddlewareDecisionEffect(http.continue()));
Signature
declare const isMiddlewareDecisionEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
http-dsl-source-operations.ts
httpSourceEffects
Effect constructors for request input and source mappings.
Example
Effect.runSync(httpSourceEffects.path("id"));
Signature
declare const httpSourceEffects: {
input: <const S extends HttpMappingShape>(
fields: S,
) => Effect.Effect<HttpInputMapping<S>, RouteOperationError, never>;
nested: <const S extends HttpMappingShape>(
fields: S,
) => Effect.Effect<HttpNestedMapping<S>, RouteOperationError, never>;
path: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
pathSegments: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
query: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
header: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
cookie: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
body: (
name?: string | undefined,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
wholeBody: () => Effect.Effect<HttpWholeBodyMapping<unknown>, RouteOperationError, never>;
multipart: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
multipartAll: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
};
http-dsl-sources.types.ts
HttpDslSources (interface)
Source constructors for serializable HTTP request mappings.
Example
const id = http.path("id");
Signature
export interface HttpDslSources {
/** One path parameter.
* @param name - Path parameter name
* @returns A path source mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.path("id");
*/
path(name: string): HttpPathMapping;
/** Maps a named path parameter with optionality or a default.
* @param name - Source name.
* @param options - Optionality or JSON fallback.
* @returns A source mapping, optionally wrapped by a default or optional node.
* @throws TypeError when the mapping input is invalid.
* @example http.path("id", { optional: true });
*/
path(name: string, options: HttpSourceOptions): HttpMappingNode;
/** Captured path segments.
* @param name - Segment parameter name
* @returns A path segments mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.pathSegments("parts");
*/
pathSegments(name: string): HttpPathSegmentsMapping;
/** Maps a captured path segments with optionality or a default.
* @param name - Source name.
* @param options - Optionality or JSON fallback.
* @returns A source mapping, optionally wrapped by a default or optional node.
* @throws TypeError when the mapping input is invalid.
* @example http.pathSegments("parts", { optional: true });
*/
pathSegments(name: string, options: HttpSourceOptions): HttpMappingNode;
/** One query parameter.
* @param name - Query parameter name
* @returns A query source mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.query("page");
*/
query(name: string): HttpQueryMapping;
/** Maps a named query parameter with optionality or a default.
* @param name - Source name.
* @param options - Optionality or JSON fallback.
* @returns A source mapping, optionally wrapped by a default or optional node.
* @throws TypeError when the mapping input is invalid.
* @example http.query("page", { default: "1" });
*/
query(name: string, options: HttpSourceOptions): HttpMappingNode;
/** One request header.
* @param name - Header name
* @returns A header source mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.header("authorization");
*/
header(name: string): HttpHeaderMapping;
/** Maps a named request header with optionality or a default.
* @param name - Source name.
* @param options - Optionality or JSON fallback.
* @returns A source mapping, optionally wrapped by a default or optional node.
* @throws TypeError when the mapping input is invalid.
* @example http.header("authorization", { optional: true });
*/
header(name: string, options: HttpSourceOptions): HttpMappingNode;
/** One request cookie.
* @param name - Cookie name
* @returns A cookie source mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.cookie("session");
*/
cookie(name: string): HttpCookieMapping;
/** Maps a named request cookie with optionality or a default.
* @param name - Source name.
* @param options - Optionality or JSON fallback.
* @returns A source mapping, optionally wrapped by a default or optional node.
* @throws TypeError when the mapping input is invalid.
* @example http.cookie("session", { optional: true });
*/
cookie(name: string, options: HttpSourceOptions): HttpMappingNode;
/** The whole body or one body field.
* @param name - Optional body field name
* @param options - Optionality or fallback.
* @returns A body source mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.body("name");
*/
/** The complete request body.
* @returns A whole-body mapping.
* @example http.body();
*/
body(): HttpWholeBodyMapping;
/** Maps one named body field.
* @param name - Body field name.
* @returns A body field mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.body("name");
*/
body(name: string): HttpBodyMapping;
/** Maps a named body field with optionality or a default.
* @param name - Source name.
* @param options - Optionality or JSON fallback.
* @returns A source mapping, optionally wrapped by a default or optional node.
* @throws TypeError when the mapping input is invalid.
* @example http.body("name", { optional: true });
*/
body(name: string, options: HttpSourceOptions): HttpMappingNode;
/** The complete request body.
* @returns A whole-body mapping.
* @example http.wholeBody();
*/
wholeBody(): HttpWholeBodyMapping;
/** One multipart form field.
* @param name - Form field name
* @returns A multipart source mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.multipart("photo");
*/
multipart(name: string): HttpMultipartMapping;
/** Maps a named multipart field with optionality or a default.
* @param name - Source name.
* @param options - Optionality or JSON fallback.
* @returns A source mapping, optionally wrapped by a default or optional node.
* @throws TypeError when the mapping input is invalid.
* @example http.multipart("photo", { optional: true });
*/
multipart(name: string, options: HttpSourceOptions): HttpMappingNode;
/** All values of one multipart field.
* @param name - Form field name
* @returns A multipart-array source mapping.
* @throws TypeError when the mapping input is invalid.
* @example http.multipartAll("files");
*/
multipartAll(name: string): HttpMultipartAllMapping;
/** Maps a all values of a multipart field with optionality or a default.
* @param name - Source name.
* @param options - Optionality or JSON fallback.
* @returns A source mapping, optionally wrapped by a default or optional node.
* @throws TypeError when the mapping input is invalid.
* @example http.multipartAll("files", { optional: true });
*/
multipartAll(name: string, options: HttpSourceOptions): HttpMappingNode;
}
http-dsl-validation.ts
“./http-dsl-mapping-validation.js” (namespace export)
Re-exports all named exports from the “./http-dsl-mapping-validation.js” module.
Signature
export * from "./http-dsl-mapping-validation.js";
“./http-dsl-response-validation.js” (namespace export)
Re-exports all named exports from the “./http-dsl-response-validation.js” module.
Signature
export * from "./http-dsl-response-validation.js";
“./http-dsl-value-validation.js” (namespace export)
Re-exports all named exports from the “./http-dsl-value-validation.js” module.
Signature
export * from "./http-dsl-value-validation.js";
http-dsl-value-validation.ts
assertSchema
Asserts a Standard Schema validator synchronously.
Throws
TypeError for invalid schemas.
Example
assertSchema(schema, "response schema");
Signature
declare const assertSchema: (value: unknown, name: string) => asserts value is StandardSchemaV1;
assertSchemaEffect
Asserts a Standard Schema validator through Effect.
Example
Effect.runSync(assertSchemaEffect(schema, "response schema"));
Signature
declare const assertSchemaEffect: (
value: unknown,
name: string,
) => Effect.Effect<void, RouteOperationError, never>;
assertSchemaValue
Validates a schema inside an already observed operation.
Throws
RouteInputError for an invalid schema.
Example
assertSchemaValue(schema, "response schema");
Signature
declare const assertSchemaValue: (
value: unknown,
name: string,
) => asserts value is StandardSchemaV1;
isJsonValue
Checks JSON compatibility without leaking a validation exception.
Example
isJsonValue({ ok: true });
Signature
declare const isJsonValue: (value: unknown) => value is JsonValue;
isRecord
Checks an ordinary non-array object synchronously.
Example
isRecord({});
Signature
declare const isRecord: (value: unknown) => value is Record<string, any>;
isRecordEffect
Checks an ordinary non-array object through Effect.
Example
Effect.runSync(isRecordEffect({}));
Signature
declare const isRecordEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
isRecordValue
Checks the object shape inside another observed operation.
Example
isRecordValue({ kind: "path" });
Signature
declare const isRecordValue: (value: unknown) => value is Record<string, any>;
isSchema
Checks a Standard Schema validator synchronously.
Example
isSchema(schema);
Signature
declare const isSchema: (value: unknown) => value is StandardSchemaV1;
isSchemaEffect
Checks a Standard Schema validator through Effect.
Example
Effect.runSync(isSchemaEffect(schema));
Signature
declare const isSchemaEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
isSchemaValue
Checks the Standard Schema shape inside a parent operation.
Example
isSchemaValue(z.string());
Signature
declare const isSchemaValue: (value: unknown) => value is StandardSchemaV1;
isStatus
Checks an HTTP response status synchronously.
Example
isStatus(200);
Signature
declare const isStatus: (value: unknown) => value is number;
isStatusEffect
Checks an HTTP response status through Effect.
Example
Effect.runSync(isStatusEffect(200));
Signature
declare const isStatusEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
isStatusValue
Checks an HTTP status inside response validation.
Example
isStatusValue(200);
Signature
declare const isStatusValue: (value: unknown) => value is number;
ownKeys
Checks that a mapping has only its allowed own property names.
Example
ownKeys({ kind: "continue" }, "kind");
Signature
declare const ownKeys: (value: object, ...keys: string[]) => boolean;
http-dsl-values.ts
httpValue
Internal pure constructors evaluated only inside the public Effect operations.
Signature
declare const httpValue: HttpDsl;
isTransformRefValue
Checks a transform reference without running another Effect adapter.
Example
isTransformRefValue({ ref: { kind: "transform", id: "x" }, schema });
Signature
declare const isTransformRefValue: (value: unknown) => value is HttpTransformRef;
http-dsl.ts
“./http-dsl.types.js” (namespace export)
Re-exports all named exports from the “./http-dsl.types.js” module.
Signature
export * from "./http-dsl.types.js";
assertRequestMapping
Signature
declare const assertRequestMapping: (value: unknown) => asserts value is HttpRequestMapping;
assertRequestMappingEffect
Signature
declare const assertRequestMappingEffect: (
value: unknown,
) => Effect.Effect<void, RouteOperationError, never>;
assertResponse
Signature
declare const assertResponse: (value: unknown) => HttpResponseMapping;
assertResponseEffect
Signature
declare const assertResponseEffect: (
value: unknown,
) => Effect.Effect<HttpResponseMapping, RouteOperationError, never>;
defineRequestTransform
Alias for request transform definitions.
Throws
TypeError for invalid transform input.
Example
defineRequestTransform({ schema });
Signature
declare const defineRequestTransform: <
const Id extends string,
const Schema extends StandardSchemaV1,
>(
options: DefineTransformOptions<Id, Schema>,
) => HttpTransformDescriptor<Id, Schema>;
defineRequestTransformEffect
Effect alias for request transform definitions.
Example
Effect.runSync(defineRequestTransformEffect({ schema }));
Signature
declare const defineRequestTransformEffect: <
const Id extends string,
const Schema extends StandardSchemaV1,
>(
options: DefineTransformOptions<Id, Schema>,
) => Effect.Effect<HttpTransformDescriptor<Id, Schema>, RouteOperationError, never>;
defineTransform
Defines a serializable HTTP transform.
Throws
TypeError for invalid input or a closure-bearing transform.
Example
defineTransform({ schema });
Signature
declare const defineTransform: <const Id extends string, const Schema extends StandardSchemaV1>(
options: DefineTransformOptions<Id, Schema>,
) => HttpTransformDescriptor<Id, Schema>;
defineTransformEffect
Defines a serializable transform through Effect.
Example
Effect.runSync(defineTransformEffect({ schema }));
Signature
declare const defineTransformEffect: <
const Id extends string,
const Schema extends StandardSchemaV1,
>(
options: DefineTransformOptions<Id, Schema>,
) => Effect.Effect<HttpTransformDescriptor<Id, Schema>, RouteOperationError, never>;
http
Creates serializable HTTP request and response mappings.
Example
const request = http.input({ id: http.path("id") });
Signature
declare const http: HttpDsl;
httpEffects
Signature
declare const httpEffects: {
constant: <const V extends JsonValue>(
value: V,
) => Effect.Effect<HttpConstantMapping<V>, RouteOperationError, never>;
optional: <const M extends HttpMappingNode>(
value: M,
) => Effect.Effect<HttpOptionalMapping<M>, RouteOperationError, never>;
default: <const M extends HttpMappingNode, const V extends JsonValue>(
value: M,
fallback: V,
) => Effect.Effect<HttpDefaultMapping<M, V>, RouteOperationError, never>;
transform: <const T extends HttpTransformRef | string, const M extends HttpMappingNode>(
transform: T,
value?: M | undefined,
) => Effect.Effect<HttpTransformMapping<TransformOutput<T>>, RouteOperationError, never>;
success: (
status: number,
schema?: StandardSchemaV1<unknown, unknown> | undefined,
) => Effect.Effect<HttpResponseMapping, RouteOperationError, never>;
error: (
errorId: string,
status: number,
schema?: StandardSchemaV1<unknown, unknown> | undefined,
) => Effect.Effect<HttpResponseMapping, RouteOperationError, never>;
validationError: (
status?: number | undefined,
schema?: StandardSchemaV1<unknown, unknown> | undefined,
) => Effect.Effect<HttpResponseMapping, RouteOperationError, never>;
response: (
id: string,
status: number,
schema?: StandardSchemaV1<unknown, unknown> | undefined,
) => Effect.Effect<HttpResponseMapping, RouteOperationError, never>;
continue: () => Effect.Effect<ContinueMapping, RouteOperationError, never>;
respond: (
response: string | HttpResponseMapping,
body?: HttpMappingNode | undefined,
) => Effect.Effect<RespondMapping, RouteOperationError, never>;
input: <const S extends HttpMappingShape>(
fields: S,
) => Effect.Effect<HttpInputMapping<S>, RouteOperationError, never>;
nested: <const S extends HttpMappingShape>(
fields: S,
) => Effect.Effect<HttpNestedMapping<S>, RouteOperationError, never>;
path: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
pathSegments: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
query: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
header: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
cookie: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
body: (
name?: string | undefined,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
wholeBody: () => Effect.Effect<HttpWholeBodyMapping<unknown>, RouteOperationError, never>;
multipart: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
multipartAll: (
name: string,
options?: HttpSourceOptions | undefined,
) => Effect.Effect<HttpMappingNode, RouteOperationError, never>;
};
isHttpMapping
Signature
declare const isHttpMapping: (value: unknown) => value is HttpMappingNode;
isHttpMappingEffect
Signature
declare const isHttpMappingEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
isHttpRequestMapping
Signature
declare const isHttpRequestMapping: (value: unknown) => value is HttpRequestMapping;
isHttpRequestMappingEffect
Signature
declare const isHttpRequestMappingEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
isHttpResponseMapping
Signature
declare const isHttpResponseMapping: (value: unknown) => value is HttpResponseMapping;
isHttpResponseMappingEffect
Signature
declare const isHttpResponseMappingEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
isMiddlewareDecision
Signature
declare const isMiddlewareDecision: (value: unknown) => value is MiddlewareDecisionMapping;
isMiddlewareDecisionEffect
Signature
declare const isMiddlewareDecisionEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
isTransformRef
Checks a transform reference synchronously.
Example
isTransformRef(transform);
Signature
declare const isTransformRef: (value: unknown) => value is HttpTransformRef;
isTransformRefEffect
Checks a transform reference through Effect.
Example
Effect.runSync(isTransformRefEffect(transform));
Signature
declare const isTransformRefEffect: (
value: unknown,
) => Effect.Effect<boolean, RouteOperationError, never>;
http-dsl.types.ts
“./http-mapping.types.js” (namespace export)
Re-exports all named exports from the “./http-mapping.types.js” module.
Signature
export * from "./http-mapping.types.js";
ContinueMapping (interface)
Middleware decision that delegates to the next handler.
Example
const decision: ContinueMapping = http.continue();
Signature
export interface ContinueMapping {
readonly kind: "continue";
}
DefineTransformOptions (interface)
Authoring options for a serializable transform.
Example
type Options = DefineTransformOptions<"text.upper", typeof schema>;
Signature
export interface DefineTransformOptions<
Id extends string,
Schema extends StandardSchemaV1,
> extends DescriptorMetadata {
readonly id?: Id;
readonly schema: Schema;
}
HttpDsl (interface)
Synchronous HTTP mapping constructor API.
Example
const request = http.input({ id: http.path("id") });
Signature
export interface HttpDsl extends HttpDslMethods {}
HttpMethod (type alias)
HTTP methods recognized by the compiler.
Example
const method: HttpMethod = "GET";
Signature
type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS" | "ALL";
HttpRequestContentType (type alias)
Supported explicit request content types.
Example
const accept: HttpRequestContentType = "application/json";
Signature
type HttpRequestContentType = "application/json" | "multipart/form-data";
HttpResponseMapping (interface)
Serializable response status and schema mapping.
Example
const response: HttpResponseMapping = http.success(200);
Signature
export interface HttpResponseMapping {
readonly kind: "success" | "error" | "validation-error" | "response";
readonly id: string;
readonly status: number;
readonly errorId?: string;
readonly schema?: StandardSchemaV1;
}
HttpTransformDescriptor (interface)
Frozen authoring descriptor for a transform.
Example
type Upper = HttpTransformDescriptor<"text.upper", typeof schema>;
Signature
export interface HttpTransformDescriptor<
Id extends string,
Schema extends StandardSchemaV1,
> extends HttpTransformRef<Id, Schema> {
readonly kind: "transform";
readonly id: Id;
}
HttpTransformRef (interface)
Transform reference paired with its output schema.
Example
const ref: HttpTransformRef = { ref: transform.ref, schema: transform.schema };
Signature
export interface HttpTransformRef<
Id extends string = string,
Schema extends StandardSchemaV1 = StandardSchemaV1,
> {
readonly ref: TransformReference<Id>;
readonly schema: Schema;
}
MiddlewareDecisionMapping (type alias)
Union of middleware response decisions.
Example
const decision: MiddlewareDecisionMapping = http.continue();
Signature
type MiddlewareDecisionMapping = ContinueMapping | RespondMapping;
RespondMapping (interface)
Middleware decision selecting a response mapping.
Example
const decision: RespondMapping = http.respond("success.200");
Signature
export interface RespondMapping {
readonly kind: "respond";
readonly responseId: string;
readonly body?: HttpMappingNode;
}
TransformOutput (type alias)
Output type inferred from a transform schema.
Example
type Output = TransformOutput<typeof transform>;
Signature
type TransformOutput<T> = T extends { readonly schema: infer Schema }
? Schema extends StandardSchemaV1
? InferOutput<Schema>
: unknown
: unknown;
TransformReference (interface)
Stable serializable transform identity.
Example
const ref: TransformReference = { kind: "transform", id: "text.upper" };
Signature
export interface TransformReference<Id extends string = string> {
readonly kind: "transform";
readonly id: Id;
}
http-mapping.types.ts
HttpBodyMapping (interface)
One named field from a request body.
Example
const mapping: HttpBodyMapping = http.body("name");
Signature
export interface HttpBodyMapping<Output = unknown> extends HttpMapping<Output> {
readonly kind: "body";
readonly name: string;
}
HttpConstantMapping (interface)
A serializable constant input.
Example
const mapping: HttpConstantMapping<string> = http.constant("all");
Signature
export interface HttpConstantMapping<
Output extends JsonValue = JsonValue,
> extends HttpMapping<Output> {
readonly kind: "constant";
readonly value: Output;
}
HttpCookieMapping (interface)
One named request cookie.
Example
const mapping: HttpCookieMapping = http.cookie("session");
Signature
export interface HttpCookieMapping<Output = string> extends HttpMapping<Output> {
readonly kind: "cookie";
readonly name: string;
}
HttpDefaultMapping (interface)
A source mapping with a serializable fallback.
Example
const mapping: HttpDefaultMapping = http.default(http.query("page"), "1");
Signature
export interface HttpDefaultMapping<
M extends HttpMappingNode = HttpMappingNode,
Default extends JsonValue = JsonValue,
> extends HttpMapping<Exclude<HttpMappingOutput<M>, undefined> | Default> {
readonly kind: "default";
readonly value: M;
readonly default: Default;
}
HttpHeaderMapping (interface)
One named request header.
Example
const mapping: HttpHeaderMapping = http.header("authorization");
Signature
export interface HttpHeaderMapping<Output = string> extends HttpMapping<Output> {
readonly kind: "header";
readonly name: string;
}
HttpInputMapping (interface)
The root request input assembled from field mappings.
Example
const mapping: HttpInputMapping = http.input({ id: http.path("id") });
Signature
export interface HttpInputMapping<
S extends HttpMappingShape = HttpMappingShape,
> extends HttpMapping<MappingShapeOutput<S>> {
readonly kind: "input";
readonly fields: S;
}
HttpMapping (interface)
Base phantom output contract for every HTTP mapping.
Example
const mapping: HttpMapping<string> = http.path("id");
Signature
export interface HttpMapping<Output = unknown> {
readonly __output?: Output;
}
HttpMappingNode (type alias)
Union of supported serializable request mapping nodes.
Example
const mapping: HttpMappingNode = http.path("id");
Signature
type HttpMappingNode =
| HttpPathMapping
| HttpPathSegmentsMapping
| HttpQueryMapping
| HttpHeaderMapping
| HttpCookieMapping
| HttpBodyMapping
| HttpWholeBodyMapping
| HttpMultipartMapping
| HttpMultipartAllMapping
| HttpConstantMapping
| HttpInputMapping
| HttpNestedMapping
| HttpOptionalMapping
| HttpDefaultMapping
| HttpTransformMapping;
HttpMappingOutput (type alias)
Output value inferred from one mapping node.
Example
type Output = HttpMappingOutput<HttpPathMapping>;
Signature
type HttpMappingOutput<M> = M extends HttpMapping<infer Output> ? Output : never;
HttpMappingShape (type alias)
Named fields in a nested or request input mapping.
Example
const fields: HttpMappingShape = { id: http.path("id") };
Signature
type HttpMappingShape = Readonly<Record<string, HttpMappingNode>>;
HttpMultipartAllMapping (interface)
All values of a multipart form field.
Example
const mapping: HttpMultipartAllMapping = http.multipartAll("files");
Signature
export interface HttpMultipartAllMapping<
Output = readonly (string | File)[],
> extends HttpMapping<Output> {
readonly kind: "multipart-all";
readonly name: string;
}
HttpMultipartMapping (interface)
One multipart form field.
Example
const mapping: HttpMultipartMapping = http.multipart("photo");
Signature
export interface HttpMultipartMapping<Output = string | File> extends HttpMapping<Output> {
readonly kind: "multipart";
readonly name: string;
}
HttpNestedMapping (interface)
A nested object assembled from field mappings.
Example
const mapping: HttpNestedMapping = http.nested({ id: http.path("id") });
Signature
export interface HttpNestedMapping<
S extends HttpMappingShape = HttpMappingShape,
> extends HttpMapping<MappingShapeOutput<S>> {
readonly kind: "nested";
readonly fields: S;
}
HttpOptionalMapping (interface)
A source mapping whose absence is allowed.
Example
const mapping: HttpOptionalMapping = http.optional(http.query("page"));
Signature
export interface HttpOptionalMapping<
M extends HttpMappingNode = HttpMappingNode,
> extends HttpMapping<HttpMappingOutput<M> | undefined> {
readonly kind: "optional";
readonly value: M;
}
HttpPathMapping (interface)
One named route path parameter.
Example
const mapping: HttpPathMapping = http.path("id");
Signature
export interface HttpPathMapping<Output = string> extends HttpMapping<Output> {
readonly kind: "path";
readonly name: string;
}
HttpPathSegmentsMapping (interface)
All segments captured by a route path parameter.
Example
const mapping: HttpPathSegmentsMapping = http.pathSegments("parts");
Signature
export interface HttpPathSegmentsMapping<Output = readonly string[]> extends HttpMapping<Output> {
readonly kind: "path-segments";
readonly name: string;
}
HttpQueryMapping (interface)
One named query parameter.
Example
const mapping: HttpQueryMapping = http.query("page");
Signature
export interface HttpQueryMapping<Output = string> extends HttpMapping<Output> {
readonly kind: "query";
readonly name: string;
}
HttpRequestMapping (type alias)
The required root shape for explicit request mapping.
Example
const mapping: HttpRequestMapping = http.input({ id: http.path("id") });
Signature
type HttpRequestMapping = HttpInputMapping;
HttpSourceOptions (interface)
Optionality and fallback options for one request source.
Example
const options: HttpSourceOptions = { optional: true };
Signature
export interface HttpSourceOptions {
readonly optional?: boolean;
readonly default?: JsonValue;
}
HttpTransformMapping (interface)
A value transformed by a registered transform ID.
Example
const mapping: HttpTransformMapping = http.transform("upper", http.body("name"));
Signature
export interface HttpTransformMapping<Output = unknown> extends HttpMapping<Output> {
readonly kind: "transform";
readonly transformId: string;
readonly value: HttpMappingNode;
}
HttpWholeBodyMapping (interface)
The complete request body.
Example
const mapping: HttpWholeBodyMapping = http.wholeBody();
Signature
export interface HttpWholeBodyMapping<Output = unknown> extends HttpMapping<Output> {
readonly kind: "whole-body";
}
MappingShapeOutput (type alias)
Output shape inferred from named mapping fields.
Example
type Output = MappingShapeOutput<{ id: HttpPathMapping }>;
Signature
type MappingShapeOutput<S extends HttpMappingShape> = {
readonly [K in keyof S]: HttpMappingOutput<S[K]>;
};
index.ts
“./define-middleware.js” (namespace export)
Re-exports all named exports from the “./define-middleware.js” module.
Signature
export * from "./define-middleware.js";
“./define-route.js” (namespace export)
Re-exports all named exports from the “./define-route.js” module.
Signature
export * from "./define-route.js";
“./define-service-routes.js” (namespace export)
Re-exports all named exports from the “./define-service-routes.js” module.
Signature
export * from "./define-service-routes.js";
“./http-dsl.js” (namespace export)
Re-exports all named exports from the “./http-dsl.js” module.
Signature
export * from "./http-dsl.js";
“./route-module.types.js” (namespace export)
Re-exports all named exports from the “./route-module.types.js” module.
Signature
export * from "./route-module.types.js";
“./route.types.js” (namespace export)
Re-exports all named exports from the “./route.types.js” module.
Signature
export * from "./route.types.js";
HttpRateLimitKey
Signature
declare const HttpRateLimitKey: HttpRateLimitKey;
RouteInputError
Signature
declare const RouteInputError: typeof RouteInputError;
RouteOperation
Signature
declare const RouteOperation: RouteOperation;
RouteOperationError
Signature
declare const RouteOperationError: typeof RouteOperationError;
RouteRateLimit
Signature
declare const RouteRateLimit: RouteRateLimit;
RouteTelemetry
Signature
declare const RouteTelemetry: typeof RouteTelemetry;
RouteTelemetryLive
Signature
declare const RouteTelemetryLive: Layer<RouteTelemetry, never, never>;
RouteTelemetryService
Signature
declare const RouteTelemetryService: RouteTelemetryService;
route-auth.ts
BetterAuthRegistration
Signature
declare const BetterAuthRegistration: BetterAuthRegistration;
copyProtectedPaths
Validates and copies protected route patterns synchronously.
Throws
TypeError for invalid patterns.
Example
copyProtectedPaths(["/admin/*"]);
Signature
declare const copyProtectedPaths: (values: readonly string[] | undefined) => readonly string[];
copyProtectedPathsEffect
Validates and copies protected paths through Effect.
Example
Effect.runSync(copyProtectedPathsEffect(["/admin/*"]));
Signature
declare const copyProtectedPathsEffect: (
values: ReadonlyArray<string> | undefined,
) => Effect.Effect<ReadonlyArray<string>, RouteOperationError, never>;
copyProtectedValues
Copies protected paths inside an already observed operation.
Throws
RouteInputError for an invalid pattern.
Example
copyProtectedValues(["/admin/*"]);
Signature
declare const copyProtectedValues: (values: readonly string[] | undefined) => readonly string[];
readBetterAuthRegistration
Reads a Better Auth handler registration synchronously.
Throws
TypeError for malformed handler input.
Example
readBetterAuthRegistration(handler);
Signature
declare const readBetterAuthRegistration: (
handler: RawRouteOptions<string>["handler"],
) => BetterAuthRegistration | undefined;
readBetterAuthRegistrationEffect
Reads a Better Auth handler registration through Effect.
Example
Effect.runSync(readBetterAuthRegistrationEffect(handler));
Signature
declare const readBetterAuthRegistrationEffect: (
handler: RawHttpHandler,
) => Effect.Effect<BetterAuthRegistration | undefined, RouteOperationError, never>;
readRegistrationValue
Reads registration metadata inside an already observed operation.
Example
readRegistrationValue(handler);
Signature
declare const readRegistrationValue: (
handler: RawRouteOptions<string>["handler"],
) => BetterAuthRegistration | undefined;
route-auth.types.ts
Better Auth identity attached to a raw handler.
Example
const registration: BetterAuthRegistration = {
kind: "better-auth",
service: { ref: { kind: "service", id: "auth" } },
};
BetterAuthRegistration (interface)
Better Auth identity attached to a raw handler.
Example
const registration: BetterAuthRegistration = {
kind: "better-auth",
service: { ref: { kind: "service", id: "auth" } },
};
Signature
export interface BetterAuthRegistration {
readonly kind: "better-auth";
readonly service: { readonly ref: { readonly kind: "service"; readonly id: string } };
}
route-client.ts
copyClient
Copies a client policy for synchronous authoring.
Throws
TypeError when the policy is invalid.
Example
copyClient({ operation: "query" });
Signature
declare const copyClient: (value: unknown) => RouteClientPolicy | undefined;
copyClientEffect
Copies a client policy through a typed Effect.
Example
Effect.runSync(copyClientEffect({ operation: "query" }));
Signature
declare const copyClientEffect: (
value: unknown,
) => Effect.Effect<RouteClientPolicy | undefined, RouteOperationError, never>;
copyClientValue
Copies client policy inside an already observed operation.
Throws
RouteInputError for an invalid policy.
Example
copyClientValue({ operation: "query" });
Signature
declare const copyClientValue: (value: unknown) => RouteClientPolicy | undefined;
copyStream
Copies a native stream policy for synchronous authoring.
Throws
TypeError when the policy or output schema is incompatible.
Example
copyStream(undefined, output);
Signature
declare const copyStream: (
value: unknown,
output: StandardSchemaV1,
) => { readonly format: NativeStreamFormat } | undefined;
copyStreamEffect
Copies a native stream policy through a typed Effect.
Example
Effect.runSync(copyStreamEffect(undefined, output));
Signature
declare const copyStreamEffect: (
value: unknown,
output: StandardSchemaV1<unknown, unknown>,
) => Effect.Effect<{ readonly format: NativeStreamFormat } | undefined, RouteOperationError, never>;
copyStreamValue
Copies stream policy inside an already observed operation.
Throws
RouteInputError for invalid stream settings.
Example
copyStreamValue({ format: "sse" }, streamOutput);
Signature
declare const copyStreamValue: (
value: unknown,
output: StandardSchemaV1,
) => { readonly format: NativeStreamFormat } | undefined;
route-definition.ts
prepareRouteValue
Validates route options before acquiring an unbound identity.
Throws
RouteInputError for invalid route inputs.
Example
prepareRouteValue({ target })("orders.get");
Signature
declare const prepareRouteValue: (
options:
| FunctionRouteOptions<string, FunctionRefAny, HttpRequestMapping | undefined>
| RawRouteOptions<string>,
) => (id: string) => RouteDescriptor<string>;
route-module.types.ts
RouteModuleContract (type alias)
Expected types for a route module’s exports, used by generated module validators. Rejects untyped exports and requires at least one named HTTP method.
Signature
type RouteModuleContract<Module, Parameters extends string = never> = keyof Module extends never
? { readonly __relkit_route_method_required: never }
: {
readonly [Method in keyof Module]: Method extends RouteModuleMethod
? CheckedRoute<Module[Method], Method, Parameters>
: never;
};
RouteModuleMethod (type alias)
Value exports accepted by a filesystem route module.
Signature
type RouteModuleMethod = ServiceRouteMethod | "ALL";
route-observability.ts
RouteInputError (class)
Marks invalid route authoring input while preserving TypeError compatibility.
Example
throw new RouteInputError("Route target is invalid");
Signature
declare class RouteInputError
RouteOperation
Signature
declare const RouteOperation: RouteOperation;
RouteOperationError (class)
Expected failure from a route authoring Effect.
Example
const error = new RouteOperationError({
operation: "route.define",
reason: "Invalid route",
cause: new TypeError("Invalid route"),
});
Signature
declare class RouteOperationError
RouteTelemetry (class)
Injectable observer for route authoring operations.
Example
Effect.provide(defineRouteEffect(options), RouteTelemetryLive);
Signature
declare class RouteTelemetry
RouteTelemetryLive
Default route observer with an Effect span, counters, and duration histogram.
Example
Effect.runSync(Effect.provide(Effect.void, RouteTelemetryLive));
Signature
declare const RouteTelemetryLive: Layer.Layer<RouteTelemetry, never, never>;
RouteTelemetryService
Signature
declare const RouteTelemetryService: RouteTelemetryService;
measureRoute
Records route metrics without creating a second span inside named Effect functions.
Example
measureRoute("route.define", Effect.succeed(route));
Signature
declare const measureRoute: <A, E, R>(
operation: RouteOperation,
effect: Effect.Effect<A, E, R>,
) => Effect.Effect<A, E, R>;
observeRoute
Observes a route operation with an injectable test observer.
Example
observeRoute("route.define", Effect.succeed(route));
Signature
declare const observeRoute: <A, E, R>(
operation: RouteOperation,
effect: Effect.Effect<A, E, R>,
) => Effect.Effect<A, E, R>;
routeAttempt
Evaluates a calculation inside an already observed route operation.
Example
yield * routeAttempt("route.define", () => descriptor);
Signature
declare const routeAttempt: <A>(
operation: RouteOperation,
evaluate: () => A,
) => Effect.Effect<A, RouteOperationError>;
routeIdentity
Acquires an unbound route identity through the caller’s IdentityStore Layer.
Example
yield * routeIdentity("middleware.define");
Signature
declare const routeIdentity: (
operation: RouteOperation,
) => Effect.Effect<string, RouteOperationError>;
routeTry
Evaluates synchronous authoring logic inside a typed and observed Effect.
Example
routeTry("route.define", () => descriptor);
Signature
declare const routeTry: <A>(
operation: RouteOperation,
evaluate: () => A,
) => Effect.Effect<A, RouteOperationError>;
runRouteSync
Runs a synchronous compatibility API and restores its original error.
Throws
The original validation error or an unexpected defect.
Example
runRouteSync(Effect.succeed(true));
Signature
declare const runRouteSync: <A, E>(effect: Effect.Effect<A, E>) => A;
route-observability.types.ts
RouteOperation (type alias)
Bounded name for a route authoring operation.
Example
const operation: RouteOperation = "route.define";
Signature
type RouteOperation =
| "middleware.define"
| "middleware.is-descriptor"
| "middleware.is-path"
| "route.define"
| "service-routes.define"
| "auth.read-registration"
| "auth.copy-protected"
| "client.copy"
| "stream.copy"
| "options.copy-rate-limit"
| "options.positive"
| "options.success-status"
| "dsl.define-transform"
| "dsl.is-transform-ref"
| "dsl.input"
| "dsl.nested"
| "dsl.source"
| "dsl.whole-body"
| "dsl.constant"
| "dsl.optional"
| "dsl.default"
| "dsl.transform"
| "dsl.response"
| "dsl.continue"
| "dsl.respond"
| "validation.is-mapping"
| "validation.assert-mapping"
| "validation.is-request"
| "validation.assert-request"
| "validation.is-response"
| "validation.assert-response"
| "validation.is-decision"
| "validation.is-schema"
| "validation.assert-schema"
| "validation.is-status"
| "validation.is-record";
RouteTelemetryService (interface)
Replaceable observer for route operations.
Example
const telemetry: RouteTelemetryService = { observe: (_operation, effect) => effect };
Signature
export interface RouteTelemetryService {
/**
* Measures an operation without changing its success or failure channel.
* @param operation - Fixed route operation name.
* @param effect - Work to observe.
* @returns The observed Effect with unchanged channels.
* @example telemetry.observe("route.define", Effect.succeed(route));
*/
readonly observe: <A, E, R>(
operation: RouteOperation,
effect: Effect.Effect<A, E, R>,
) => Effect.Effect<A, E, R>;
}
route-options.ts
HttpRateLimitKey
Signature
declare const HttpRateLimitKey: HttpRateLimitKey;
RouteRateLimit
Signature
declare const RouteRateLimit: RouteRateLimit;
copyRateLimit
Copies a route rate-limit policy synchronously.
Throws
TypeError for invalid policy fields.
Example
copyRateLimit(undefined);
Signature
declare const copyRateLimit: (value: RouteRateLimit | undefined) => RouteRateLimit | undefined;
copyRateLimitEffect
Copies a rate-limit policy through Effect.
Example
Effect.runSync(copyRateLimitEffect(undefined));
Signature
declare const copyRateLimitEffect: (
value: RouteRateLimit | undefined,
) => Effect.Effect<RouteRateLimit | undefined, RouteOperationError, never>;
copyRateLimitValue
Copies a rate limit inside an already observed operation.
Throws
RouteInputError for invalid policy fields.
Example
copyRateLimitValue(undefined);
Signature
declare const copyRateLimitValue: (value: RouteRateLimit | undefined) => RouteRateLimit | undefined;
positive
Validates an optional positive integer synchronously.
Throws
TypeError for nonpositive or unsafe integers.
Example
positive(5, "timeoutMs");
Signature
declare const positive: (value: number | undefined, name: string) => number | undefined;
positiveEffect
Validates an optional positive integer through Effect.
Example
Effect.runSync(positiveEffect(5, "timeoutMs"));
Signature
declare const positiveEffect: (
value: number | undefined,
name: string,
) => Effect.Effect<number | undefined, RouteOperationError, never>;
positiveValue
Checks an optional positive integer inside an already observed operation.
Throws
RouteInputError for invalid integers.
Example
positiveValue(5, "timeoutMs");
Signature
declare const positiveValue: (value: number | undefined, name: string) => number | undefined;
successStatus
Validates an optional HTTP success status synchronously.
Throws
TypeError for values outside 200–299.
Example
successStatus(201);
Signature
declare const successStatus: (value: number | undefined) => number | undefined;
successStatusEffect
Validates a success status through Effect.
Example
Effect.runSync(successStatusEffect(201));
Signature
declare const successStatusEffect: (
value: number | undefined,
) => Effect.Effect<number | undefined, RouteOperationError, never>;
successStatusValue
Checks an optional success status inside an already observed operation.
Throws
RouteInputError for invalid statuses.
Example
successStatusValue(201);
Signature
declare const successStatusValue: (value: number | undefined) => number | undefined;
route-options.types.ts
HttpRateLimitKey (type alias)
Scalar request source used for rate-limit keys.
Example
const key: HttpRateLimitKey = http.header("x-api-key");
Signature
type HttpRateLimitKey =
HttpPathMapping | HttpQueryMapping | HttpHeaderMapping | HttpCookieMapping | HttpConstantMapping;
RouteRateLimit (interface)
Immutable per-route rate-limit policy.
Example
const policy: RouteRateLimit = { limit: 10, windowMs: 60_000, key: http.header("x-api-key") };
Signature
export interface RouteRateLimit {
readonly limit: number;
readonly windowMs: number;
readonly key: HttpRateLimitKey;
readonly store?: CacheRefAny;
}
route.types.ts
FunctionRouteDescriptor (interface)
Frozen descriptor for a function-backed route.
Example
type Route = FunctionRouteDescriptor<"orders.get">;
Signature
export interface FunctionRouteDescriptor<
Id extends string,
Target extends FunctionRefAny = FunctionRefAny,
Request extends HttpRequestMapping | undefined = HttpRequestMapping | undefined,
> extends DescriptorBase<"route", Id> {
readonly method?: HttpMethod;
readonly path?: string;
readonly runtimePaths?: readonly string[];
readonly target: Target;
readonly accept?: HttpRequestContentType;
readonly request?: Request;
readonly responses?: readonly HttpResponseMapping[];
readonly successStatus?: number;
readonly maxBodyBytes?: number;
readonly rateLimit?: RouteRateLimit;
readonly timeoutMs?: number;
readonly client?: RouteClientPolicy;
readonly stream?: { readonly format: NativeStreamFormat };
}
FunctionRouteOptions (interface)
Authoring options for a function-backed route.
Example
type Options = FunctionRouteOptions<"orders.get", typeof getOrder>;
Signature
export interface FunctionRouteOptions<
Id extends string,
Target extends FunctionRefAny,
Request extends HttpRequestMapping | undefined = undefined,
> extends RouteSharedOptions<Id> {
readonly target: Target;
readonly handler?: never;
readonly accept?: HttpRequestContentType;
readonly request?: Request;
readonly responses?: readonly HttpResponseMapping[];
readonly successStatus?: number;
readonly maxBodyBytes?: number;
readonly rateLimit?: RouteRateLimit;
readonly timeoutMs?: number;
readonly client?: RouteClientPolicy;
readonly stream?: { readonly format: NativeStreamFormat };
}
NativeStreamFormat (type alias)
Native streaming transport formats.
Example
const format: NativeStreamFormat = "sse";
Signature
type NativeStreamFormat = "sse" | "text" | "bytes";
RawHttpHandler (type alias)
A raw HTTP handler receiving the incoming Request.
Example
const handler: RawHttpHandler = () => new Response("ok");
Signature
type RawHttpHandler = (request: Request) => MaybePromise<Response>;
RawRouteDescriptor (interface)
Frozen descriptor for a raw HTTP route.
Example
type Route = RawRouteDescriptor<"health">;
Signature
export interface RawRouteDescriptor<
Id extends string,
Handler extends RawHttpHandler = RawHttpHandler,
> extends DescriptorBase<"route", Id> {
readonly method?: HttpMethod;
readonly path?: string;
readonly runtimePaths?: readonly string[];
readonly raw: true;
readonly handler: Handler;
readonly auth?: {
readonly kind: "better-auth";
readonly protected: readonly string[];
readonly service: { readonly ref: { readonly kind: "service"; readonly id: string } };
};
}
RawRouteOptions (interface)
Authoring options for a raw HTTP route.
Example
const options: RawRouteOptions<"health"> = { handler: () => new Response("ok") };
Signature
export interface RawRouteOptions<
Id extends string,
Handler extends RawHttpHandler = RawHttpHandler,
> extends RouteSharedOptions<Id> {
readonly handler: Handler;
readonly target?: never;
readonly auth?: {
readonly protected?: readonly string[];
};
}
RouteClientPolicy (type alias)
Client exposure and operation policy for a route.
Example
const policy: RouteClientPolicy = { operation: "query" };
Signature
type RouteClientPolicy = false | { readonly operation?: "query" | "mutation" };
RouteDescriptor (type alias)
Union of function-backed and raw route descriptors.
Example
type Route = RouteDescriptor<"orders.get">;
Signature
type RouteDescriptor<
Id extends string,
Target extends FunctionRefAny = FunctionRefAny,
Request extends HttpRequestMapping | undefined = HttpRequestMapping | undefined,
> = FunctionRouteDescriptor<Id, Target, Request> | RawRouteDescriptor<Id>;