Functions API
Generated public TypeScript reference for relkit/functions.
Common APIs
For configuration and examples, read Functions, Declared errors, effect.
For a complete workflow, follow from express or hono, relkit 0 9, upload product images, connect react, cache product prices, react to order events, register users in a transaction.
Frontend usage
Call a public service operation shows the client side of this capability.
Most-used APIs
These entries carry each API’s contract and example. The complete reference follows.
defineFunction
Defines the graph-visible executable unit shared by HTTP, background, tool, and agent calls.
The id is optional for source-scoped functions; the compiler derives it from the
source/export hierarchy. Durable resources keep explicit IDs. The handler receives
validated reusable input and an invocation-scoped context. Declare every function it calls
under dependencies.functions and call it through context.functions, so the common engine
preserves validation, service policy, limits, and telemetry.
Throws
TypeError for invalid definition inputs.
Example
import { defineFunction } from "relkit/functions";
import { z } from "relkit/schema";
const greet = defineFunction({
input: z.object({ name: z.string() }),
output: z.object({ message: z.string() }),
handler: async ({ name }, context) => {
context.log.info("greeting requested");
return { message: `Hello, ${name}!` };
},
});
const welcome = defineFunction({
input: z.object({ name: z.string() }),
output: z.object({ message: z.string() }),
dependencies: { functions: { greet } },
handler: ({ name }, context) => context.functions.greet({ name }),
});
void welcome;
Signature
declare const defineFunction: DefineFunction;
Since v0.1.0
Backend and frontend example
Backend — these maintained files define the operation used by the frontend below.
/** Validates order input, calls the declared pricing function, and returns the calculated order. */
import { defineFunction } from "relkit/functions";
import { z } from "zod";
import priceOrder from "@app/services/orders/functions/price-order.function.js";
const orderInput = z.object({
orderId: z.string().min(1),
sku: z.string().min(1),
quantity: z.number().int().positive(),
});
const orderOutput = z.object({
orderId: z.string(),
sku: z.string(),
totalCents: z.number().int().nonnegative(),
});
const createOrder = defineFunction({
input: orderInput,
output: orderOutput,
dependencies: { functions: { priceOrder } },
handler: async (input, context) => {
const { totalCents } = await context.functions.priceOrder({ quantity: input.quantity });
const order = {
orderId: input.orderId,
sku: input.sku,
totalCents,
};
return order;
},
});
export default createOrder;
/** Maps the HTTP endpoint to its owning service's public member. */
import { defineServiceRoutes } from "relkit/routes";
import orders from "@app/services/orders/service.js";
export default defineServiceRoutes(orders, {
POST: { member: "createOrder", successStatus: 201 },
});
Frontend
After frontend setup and pulling this API example’s contract,
render this component under RelkitClientProvider:
"use client";
/** Calls the API example's Orders function through its public route, retaining the generated input and price result. */
import { api } from "@relkit/client";
import { useRelkitClient, useRouteMutation } from "@relkit/client/react";
/** Creates one order in the API example without importing the backend service.
* @returns A guarded submission action and its typed price or failure. */
export function CreateOrder() {
const { status } = useRelkitClient();
const create = useRouteMutation(api.orders.createOrder);
return (
<section>
<button
disabled={status !== "ready" || !create.isIdle}
onClick={() => create.mutate({ orderId: crypto.randomUUID(), sku: "book", quantity: 2 })}
>
Create an order
</button>
{create.isPending && <p role="status">Creating…</p>}
{create.isSuccess && <p>Total: {create.data.totalCents} cents</p>}
{create.isError && (
<p role="alert">{create.error.message}. Check the outcome before retrying.</p>
)}
</section>
);
}
This calls the same createOrder function through POST /orders, reached as
api.orders.createOrder: orderId, sku, and quantity
come from its input schema, and totalCents comes from its output schema. The browser calls RPC;
it never imports the descriptor or calls the function directly. Service membership needs a client-exposed
route to become a browser operation.
Reference: useRouteMutation.
Continue with mutation state and recovery.
defineError
Defines a typed application error.
Throws
TypeError for invalid schema, retry, HTTP status, or message.
Example
import { defineError } from "relkit/functions";
import { z } from "relkit/schema";
const NotFound = defineError({
id: "orders.not-found",
data: z.object({ id: z.string() }),
message: "Missing",
});
const error = new NotFound({ id: "order-1" });
Signature
declare const defineError: <const Id extends string, const DataSchema extends StandardSchemaV1>(
options: DefineErrorOptions<Id, DataSchema>,
) => ErrorDescriptor<Id, InferOutput<DataSchema>, DataSchema>;
Since v0.1.0
Complete reference
Public imports
relkit/functions— 137 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.
client-maps.types.ts
AgentClientFor (type alias)
Typed callable client for an agent descriptor.
Example
const invoke: AgentClientFor<typeof agent> = async (input) => output;
Signature
type AgentClientFor<T> = (input: InputOf<T>) => Promise<OutputOf<T>>;
AgentClients (type alias)
Named agent clients projected from dependencies.
Example
const agents: AgentClients<typeof dependencies.agents> = context.agents;
Signature
type AgentClients<M> = {
readonly [Name in keyof NonNullable<M> & string]: AgentClientFor<NonNullable<M>[Name]>;
};
BucketClientFor (type alias)
Bucket client exposed for a declared bucket.
Example
const client: BucketClientFor<typeof bucket> = buckets.uploads;
Signature
type BucketClientFor<T> = BucketClient;
BucketClients (type alias)
Named bucket clients projected from dependencies.
Example
const buckets: BucketClients<typeof dependencies.buckets> = context.buckets;
Signature
type BucketClients<M> = {
readonly [Name in keyof NonNullable<M> & string]: BucketClientFor<NonNullable<M>[Name]>;
};
CacheClientFor (type alias)
Key and value typed cache client.
Example
const client: CacheClientFor<typeof cache> = caches.sessions;
Signature
type CacheClientFor<T> = CacheClient<KeyOf<T>, ValueOf<T>>;
CacheClients (type alias)
Named cache clients projected from dependencies.
Example
const cache: CacheClients<typeof dependencies.cache> = context.cache;
Signature
type CacheClients<M> = {
readonly [Name in keyof NonNullable<M> & string]: CacheClientFor<NonNullable<M>[Name]>;
};
DatabaseClientFor (type alias)
Handler context of a database service declared under dependencies.databases.
Database integrations map their service descriptors through Relkit.DatabaseContexts.
Example
const db: DatabaseClientFor<typeof database> = context.databases.main;
Signature
type DatabaseClientFor<T> = [Relkit.DatabaseContexts<T>[keyof Relkit.DatabaseContexts<T>]] extends [
never,
]
? Readonly<Record<string, unknown>>
: Relkit.DatabaseContexts<T>[keyof Relkit.DatabaseContexts<T>];
DatabaseClients (type alias)
Named database contexts projected from dependencies.
Example
const databases: DatabaseClients<typeof dependencies.databases> = context.databases;
Signature
type DatabaseClients<M> = {
readonly [Name in keyof NonNullable<M> & string]: DatabaseClientFor<NonNullable<M>[Name]>;
};
EventClientFor (type alias)
Typed publish client for an event descriptor.
Example
const client: EventClientFor<typeof event> = events.created;
Signature
type EventClientFor<T> = {
/** Publishes an event.
* @param payload - Event payload.
* @param options - Optional key and attributes.
* @returns Accepted event envelope.
* @example await events.created.publish(payload);
*/
publish(
payload: EventInputOf<T>,
options?: EventPublishOptions,
): Promise<EventPublishResult<EventIdOf<T>, EventVersionOf<T>, EventOutputOf<T>>>;
};
EventClients (type alias)
Named event clients projected from published events.
Example
const events: EventClients<typeof published> = context.events;
Signature
type EventClients<M> = {
readonly [Name in keyof NonNullable<M> & string]: EventClientFor<NonNullable<M>[Name]>;
};
FunctionClientFor (type alias)
Typed callable client for a function declared under dependencies.functions.
Example
const price: FunctionClientFor<typeof priceOrder> = context.functions.priceOrder;
Signature
type FunctionClientFor<T> = (input: InputOf<T>) => Promise<OutputOf<T>>;
FunctionClients (type alias)
Named function clients projected from dependencies.
Example
const functions: FunctionClients<typeof dependencies.functions> = context.functions;
Signature
type FunctionClients<M> = {
readonly [Name in keyof NonNullable<M> & string]: FunctionClientFor<NonNullable<M>[Name]>;
};
JobClientFor (type alias)
Typed trigger client for a job descriptor.
Example
const client: JobClientFor<typeof job> = jobs.sendReceipt;
Signature
type JobClientFor<T> = {
/** Triggers a run of the job's task.
* @param input - Task input.
* @param options - Optional scheduling and idempotency controls.
* @returns Handle for the new run.
* @example await jobs.sendReceipt.trigger(input);
*/
trigger(input: InputOf<T>, options?: TaskTriggerOptions): Promise<RunHandle>;
};
JobClients (type alias)
Named job clients projected from dependencies.
Example
const jobs: JobClients<typeof dependencies.jobs> = context.jobs;
Signature
type JobClients<M> = {
readonly [Name in keyof NonNullable<M> & string]: JobClientFor<NonNullable<M>[Name]>;
};
TaskClientFor (type alias)
Typed trigger client for a task descriptor.
Example
const client: TaskClientFor<typeof task> = tasks.send;
Signature
type TaskClientFor<T> = {
/** Triggers a task run.
* @param input - Task input.
* @param options - Optional scheduling and idempotency controls.
* @returns Handle for the new run.
* @example await tasks.send.trigger(input);
*/
trigger(input: InputOf<T>, options?: TaskTriggerOptions): Promise<RunHandle>;
};
TaskClients (type alias)
Named task clients projected from dependencies.
Example
const tasks: TaskClients<typeof dependencies.tasks> = context.tasks;
Signature
type TaskClients<M> = {
readonly [Name in keyof NonNullable<M> & string]: TaskClientFor<NonNullable<M>[Name]>;
};
TaskTriggerOptions (interface)
Scheduling and idempotency options for a task.
Example
await tasks.send.trigger(input, { operationId: "send-1" });
Signature
export interface TaskTriggerOptions {
readonly operationId?: string;
readonly idempotencyKey?: string;
readonly delay?: string;
readonly at?: string;
readonly tags?: readonly string[];
readonly correlationId?: string;
}
clients.types.ts
“./client-maps.types.js” (namespace export)
Re-exports all named exports from the “./client-maps.types.js” module.
Signature
export * from "./client-maps.types.js";
BucketClient
Signature
declare const BucketClient: BucketClient;
BucketObjectMetadata
Signature
declare const BucketObjectMetadata: BucketObjectMetadata;
BucketPutOptions
Signature
declare const BucketPutOptions: BucketPutOptions;
CacheClient
Signature
declare const CacheClient: CacheClient<Key, Value>;
CacheOperationOptions
Signature
declare const CacheOperationOptions: CacheOperationOptions;
EventAttributeValue (type alias)
Scalar value accepted in event attributes.
Example
const value: EventAttributeValue = true;
Signature
type EventAttributeValue = string | number | boolean;
EventPublishOptions (interface)
Metadata supplied with an event publication.
Example
await events.publish(payload, { key: "order-1" });
Signature
export interface EventPublishOptions {
readonly key?: string;
readonly attributes?: Readonly<Record<string, EventAttributeValue>>;
}
EventPublishResult (interface)
Accepted event envelope returned by publication.
Example
const published: EventPublishResult = await events.publish(payload);
Signature
export interface EventPublishResult<
Id extends string = string,
Version extends number = number,
Payload = unknown,
> extends EventEnvelope<Id, Version, Payload> {
readonly accepted: true;
}
create-relkit.ts
createRelkit(config): a runtime handle for scripts, seeders and other frameworks. It runs the
built application’s activation with no HTTP listener, event consumers or job workers.
ApplicationBuildUnavailableError (class)
Raised when createRelkit finds no usable build of the application.
Signature
declare class ApplicationBuildUnavailableError {
constructor(entry: string, reason: string);
}
code (property)
Signature
readonly code: "RELKIT_APPLICATION_BUILD_UNAVAILABLE"
CreateRelkitOptions (interface)
Options for createRelkit.
Signature
export interface CreateRelkitOptions {
/** Project root that holds `.relkit/build`; defaults to the current directory. */
readonly root?: string;
}
StandaloneRelkitHandle (type alias)
A runtime handle that owns its providers until close() releases them.
Example
const relkit = await createRelkit(config);
await relkit.close();
Signature
type StandaloneRelkitHandle = RelkitHandle & {
/** Releases the providers the handle started; calling it again does nothing.
* @returns Completion after every provider is released.
* @example await relkit.close();
*/
readonly close: () => Promise<void>;
};
createRelkit
Starts a runtime handle for code that runs outside the application, such as a seed script. Only the providers the application’s graph needs are activated; nothing listens for requests.
Throws
ApplicationBuildUnavailableError when the build is missing or predates createRelkit.
Example
const relkit = await createRelkit(config);
await relkit.database.orders.insert({ data: { id: "o1", totalCents: 100 } });
await relkit.close();
Signature
declare const createRelkit: (
config: { readonly ref: { readonly kind: "app" } },
options?: CreateRelkitOptions,
) => Promise<StandaloneRelkitHandle>;
define-error-validation.ts
assertErrorSchema
Asserts a declared error data schema.
Throws
TypeError for a nonstandard schema.
Example
assertErrorSchema(z.string());
Signature
declare const assertErrorSchema: (value: unknown) => asserts value is StandardSchemaV1;
assertErrorSchemaEffect
Validates a Standard Schema through Effect.
Example
Effect.runSync(assertErrorSchemaEffect(z.string()));
Signature
declare const assertErrorSchemaEffect: (
value: unknown,
) => Effect.Effect<StandardSchemaV1<unknown, unknown>, FunctionOperationError, never>;
isErrorDescriptor
Recognizes a declared error descriptor.
Example
if (isErrorDescriptor(value)) console.log(value.id);
Signature
declare const isErrorDescriptor: (value: unknown) => value is ErrorDescriptorAny;
isErrorDescriptorEffect
Checks a declared error descriptor through Effect.
Example
Effect.runSync(isErrorDescriptorEffect(value));
Signature
declare const isErrorDescriptorEffect: (
value: unknown,
) => Effect.Effect<boolean, FunctionOperationError, never>;
isRecord
Recognizes a nonarray record-like value.
Example
isRecord({ id: "one" });
Signature
declare const isRecord: (value: unknown) => value is Record<PropertyKey, unknown>;
isRecordEffect
Checks a record-like value through Effect.
Example
Effect.runSync(isRecordEffect({}));
Signature
declare const isRecordEffect: (
value: unknown,
) => Effect.Effect<boolean, FunctionOperationError, never>;
validateErrorHttp
Validates a declared error HTTP mapping.
Throws
TypeError for an invalid status.
Example
validateErrorHttp({ status: 404 });
Signature
declare const validateErrorHttp: (http: ErrorHttpMapping | undefined) => void;
validateErrorHttpEffect
Validates an HTTP status mapping through Effect.
Example
Effect.runSync(validateErrorHttpEffect({ status: 404 }));
Signature
declare const validateErrorHttpEffect: (
http: ErrorHttpMapping | undefined,
) => Effect.Effect<void, FunctionOperationError, never>;
define-error.ts
defineErrorEffect
Defines a typed application error with safe data, transport metadata, and an optional retry hint.
The compiler derives omitted IDs. Omitted retry means never; later only hints to durable work.
Example
const NotFound = Effect.runSync(
defineErrorEffect({
id: "orders.not-found",
data: z.object({ orderId: z.string() }),
message: ({ orderId }) => `Order ${orderId} was not found`,
}),
);
new NotFound({ orderId: "order-1" });
Signature
declare const defineErrorEffect: <
const Id extends string,
const DataSchema extends StandardSchemaV1,
>(
options: DefineErrorOptions<Id, DataSchema>,
) => Effect.Effect<
ErrorDescriptor<Id, InferOutput<DataSchema>, DataSchema>,
FunctionOperationError,
never
>;
Since v0.1.0
DeclaredError (class)
Validated application error instance.
Example
const error = new NotFound({ id: "one" });
Signature
declare class DeclaredError<Id, Data> {
constructor(
id: Id,
ref: ErrorRef<Id>,
data: Data,
message: string,
retry: ErrorRetry,
afterMs: number | undefined,
http: ErrorHttpMapping | undefined,
);
}
id (property)
Signature
readonly id: Id
ref (property)
Signature
readonly ref: ErrorRef<Id>
data (property)
Signature
readonly data: Data
retry (property)
Signature
readonly retry: ErrorRetry
afterMs (property)
Signature
readonly afterMs: number | undefined
http (property)
Signature
readonly http: ErrorHttpMapping | undefined
DefineErrorOptions
Options for constructing a declared error descriptor.
Example
defineError({ id: "orders.not-found", data: z.object({ id: z.string() }), message: "Missing" });
Signature
export interface DefineErrorOptions<
Id extends string,
DataSchema extends StandardSchemaV1,
> extends DescriptorMetadata {
/** The error's public code; required because it must not change when the file moves. */
readonly id: Id;
/** Schema of the details callers receive with the error. */
readonly data: DataSchema;
/** Text of the error: a string, or a function that builds it from `data`. */
readonly message: string | ((data: InferOutput<DataSchema>) => string);