Skip to content
Logic SDK
Esc
↑↓navigate↵open⌘Jpreview
On this page

API

Look up registry options, definers, callers, and context members.

init types definitions and creates the registry factory.

init

const { query, mutation, action, event, listener, cron, error, createRegistry } = init<Config>();
Field Type
scope Required. App-defined scope.
db Shared database type or ReadWrite<Reader, Tx>.
services Dependencies for actions, listeners, and crons.
config Plain settings for every ctx.
meta Metadata shape for functions, listeners, and crons.

createRegistry

Use the same init for the registry, functions, listeners, and crons.

Mutations need a database adapter. If init declares db, supply database. Supply services and config if their types require fields. Module keys prefix IDs.

PropType
modulesMods

One entry per module: `{ bookings, availability }` with `import * as bookings from "./bookings"`.

TypeMods
database?DatabaseOptions

`database: { adapter: drizzleAdapter(db) }`, with `transactionAttempts` when 3 isn't right.

TypeDatabaseOptions
services?object
Typeobject
config?object

Settings every function reads as `ctx.config`. Plain data: it's copied and frozen.

Typeobject
jobs?JobsOptions

Background work: `jobs: { adapter: databaseQueue(), scope: { store, load } }`. Default: in-process, scope as-is (nothing waits).

TypeJobsOptions
wrap?(call: Call, next: () => Promise<unknown>) => Promise<unknown>

Wraps every call, including ones that fail validation or authorization: logging, tracing, audit.

Type(call: Call, next: () => Promise<unknown>) => Promise<unknown>
waitUntil?(promise: Promise<unknown>) => void

Serverless: let listeners finish after the response. Pass the platform's global: `import { waitUntil } from "cloudflare:workers"` or `import { waitUntil } from "@vercel/functions"`. Without it, `run` waits for listeners, unless a worker in this process takes them (`work(registry)` on Node or Bun, with `databaseQueue`): then the request answers at once.

Type(promise: Promise<unknown>) => void
onError?(error: unknown, info: FailureInfo) => void

Failures no caller waits for: jobs, and the work after commit that runs them. They never fail the caller.

Type(error: unknown, info: FailureInfo) => void
now?() => Date
Type() => Date

By default, wrap runs next(), onError logs to console.error, and now reads the clock.

Database options

PropType
adapterA
TypeA
transactionAttempts?number
Typenumber

Job options

PropType
failed?FailedJobs

Where failed jobs are kept when your adapter can't keep them itself (a queue on its own), like Laravel's `failed` driver: `failed: failedJobs()`. `registry.jobs.failed`, `retry` and `forget` then work on it.

TypeFailedJobs
maxEventDepth?number

Max chain of listener → mutation → event → listener… before queueing stops, reported. Calls `ctx.schedule` runs right away count too, so a function that schedules itself with no delay stops the same way. Default 8 (real chains are 2 or 3).

Typenumber
queues?readonly string[]

Queues besides `"default"`, for listeners, crons and `ctx.schedule` (`queue: "mail"`): `queues: ["mail", "reports"]`. A worker takes them in the order it lists them (`work(registry, { queues: ["mail", "default"] })`). A name not declared here is refused, at `createRegistry` or at the call.

Typereadonly string[]
adapter?JobsAdapter

`inProcess()` (default), or a durable one like `databaseQueue()`. Its own options go in its factory.

TypeJobsAdapter
scope?JobScope<S, T, Db, Cf>

How a job gets its scope, applied in every adapter, `inProcess()` and tests included. Required with an adapter that keeps jobs to run later (`createRegistry` refuses one without `load`): such a job runs as the scope `load` rebuilds, with today's roles.

TypeJobScope<S, T, Db, Cf>
PropType
store?(scope: S) => T

What a job keeps of the scope it was queued as: ids, as plain JSON. Sync, from the scope only.

Type(scope: S) => T
load?(ctx: LoadCtx<Db, Cf>, stored: T) => S | null | Promise<S | null>

The scope a job runs as, rebuilt from what `store` saved with today's roles: `null` discards the job. Read through `ctx.db`, as a query does, so a test's rows are visible. Write `store` first so TypeScript infers `stored`.

Type(ctx: LoadCtx<Db, Cf>, stored: T) => S | null | Promise<S | null>

See when load is required.

Registry and caller

Member Result
registry.as(scope) A caller bound to the scope.
registry.definitions Registered definitions and their IDs.
registry.idOf(definition) Registered ID. Throws for unregistered definitions.
registry.jobs Job operations.
caller.scope Bound scope.
caller.run(fn, input?, options?) Output or a thrown error.
caller.try(fn, input?, options?) { ok: true, value } or { ok: false, error }. Unexpected exceptions still throw.

Omit input only if its type permits undefined.

Call options

PropType
scope?S

The whole scope for this call and everything it runs, never merged: `{ scope: { ...ctx.scope, locale: "es" } }` to render in another language, `{ scope: { kind: "system", job: "reports.weekly" } }` to act as someone else on purpose. The callee's policy sees it. Whole, so it's one of your scope's variants: a patch could build one that isn't.

TypeS
signal?AbortSignal

Checked before this call starts. Inside, actions get it as `ctx.signal` to pass on (`fetch(url, { signal })`). Never checked between your steps, so a caller who gives up can't leave a workflow half done.

TypeAbortSignal

Context members

Member Query Mutation Action Listener Cron
scope, config, error, now() Yes Yes Yes Yes Yes
run Queries Queries and mutations All functions All functions All functions
db Reader Transaction
services, signal Yes Yes Yes
emit, schedule Yes
event Yes
cron Yes
  • db. Nested queries use the open transaction.
  • event. Includes id, name, parsed payload, occurredAt, and attempt.
  • cron. Includes id, scheduledAt, and attempt.
  • signal. Comes from the call or the listener’s timeout.

Definers

Each definer’s id accepts ASCII letters, digits, _, and -. It defaults to the export name. Preserve IDs that queued jobs or clients reference.

query, mutation, action

Field Value
handler Required. Async (ctx, input).
input Input schema. Omit for a function without input.
output Output schema. Omit to return the handler’s value unchanged.
authorize Sync policy. A type guard narrows ctx.scope. Publish only with a policy.
meta Metadata typed by init.

event and error

Definer Field Value
event payload Required schema.
error kind Any kind except invalid. Defaults to rejected.
error details Sync schema. The error carries the parsed details.
error message String with optional $field or function of parsed details. Defaults by kind.
error meta Error metadata.

listener and cron

Definer Field Value
Both handler Required. Async (ctx, payload) or, for a cron, (ctx).
Both attempts Total attempts. Default 1.
Both queue Declared queue. Default default.
Both meta Metadata typed by init.
Both retry Sync predicate for application errors. Default conflict.
Both failed Async (ctx, payload, error) or, for a cron, (ctx, error).
Listener event Required. Returns the event definition.
Listener when Sync payload filter. Default accepts all.
Listener scope Sync function of parsed payload. Default emitter scope.
Listener delay Seconds before first attempt. Default 0.
Listener key Value for ordered delivery. Exclusive with unique.
Listener unique Value for dropping later jobs while one waits.
Listener timeout Seconds per attempt. Aborts ctx.signal.
Cron schedule Required five-field schedule.
Cron timezone IANA time zone. Default UTC.
Cron scope Required whole scope.

Type helpers

Type Result
Input<typeof fn> Input before validation. Also accepts a schema type.
Output<typeof fn> Return type. For a schema, the parsed type.
AppErrorOf<typeof registry> Error union typed by code.
CallerOf<typeof registry> Caller with the registry’s scope and errors.
EventOf<typeof registry> Union of { name, payload } with unparsed payload types.

See also

Was this page helpful?