Skip to main content

Installation

Initialization

registerWorker

Register the worker with a iii instance, returns a connected worker client. The WebSocket connection is established automatically. Signature
string
WebSocket URL of the III engine. Omit to resolve it from process.env.III_URL, falling back to DEFAULT_ENGINE_URL.
InitOptions
Optional InitOptions for worker name, timeouts, reconnection, and OTel.

Methods

registerFunction

Registers a new function with a local handler or an HTTP invocation config. The handler’s return value is what the function’s observers observe; an event source’s handler returns the event it is called with. HTTP-invoked functions (HttpInvocationConfig) are deprecated (iii-http-functions) and will be removed in an upcoming release: register a handler that makes the HTTP call instead. Migration guide: https://iii.dev/docs/upgrading/migrate-from-http-functions Every call of the function, local or routed, runs the handler and then goes to the observers that want it (onObservationMatch; by default all of them): the function’s onObservationDeliver hook delivers it, or iii does, to those whose capture and filters match. iii evaluates capture and filters where the call is: the engine for a call it routes to this worker, and the SDK for a call this worker makes to its own function in-process, through an index of the filters’ equality conditions. What the worker does when the function is observed is set with the hooks (onObserverAdded, onObserverRemoved, onObservationMatch, onObservationDeliver), by id or on the returned FunctionRef. The SDK acks no observer before this call returns, so a hook set by id before it, chained on its result, or set later in the same synchronous block runs for every observer. A function that sets args_format, private: true, observable: false, an onObservationMatch hook or an onObservationDeliver hook needs an engine with observe.v2: it is registered once the connection’s engine advertised it, and against an older engine it stays unregistered (logged once, UNSUPPORTED). Signature
string
required
Unique identifier for the function.
HttpInvocationConfig | RemoteFunctionHandler<I, O>
required
Handler for local execution, or an HTTP invocation config for external functions (Lambda, Cloudflare Workers, etc.).
RegisterFunctionOptions
Optional RegisterFunctionOptions: description, request/response formats, metadata, args_format, private, observable, localDispatch.

call

Invokes a function: by id, or the target of an observer of a function this worker hosts ({ observer, payload }). Signature
CallRequest<TInput>
required
The call request: function_id (or observer), payload, and optional action/timeout.

observe

Observes a function: every call of source that passes its filters runs target, a registered function. Returns synchronously (also before the connection is up); the observer is replayed with the same id on reconnect. Errors show up as state error and reject ready(). An error answer to its observe is the engine’s refusal, the handle’s final answer: the engine holds no observer for it, it is not replayed, and its dispose() sends nothing. Signature
string | ObserveSource
required
What is observed: a function id, or function_id, args (read by the worker that hosts the function), filters, capture.
Target
required
The function to invoke.
ObserverOptions
id, max_fires, expires_in_ms, max_in_flight, metadata.

trigger

Deprecated. Use IIIClient.call, the same function.
Invokes a function using a request object. Signature

Parameters

CallRequest<TInput>
required

currentInvocation

The invocation the calling code runs in (remote or local handler, or the function’s deliver hook), or undefined outside any handler. Signature

getAddress

Engine address this worker resolved to: the explicit registerWorker argument, else III_URL, else ws://127.0.0.1:49134. Signature

getConnectionState

The current WebSocket connection state. 'failed' is terminal: it follows a fatal registration rejection (see getFatalError). Mirrors the Python/Rust SDKs’ get_connection_state(). Signature

getFatalError

The fatal registration rejection that terminated this connection, if any (e.g. a WORKER_NAMESPACE_CONFLICT); undefined while healthy. Mirrors the Python (_fatal_error) and Rust (fatal_error()) SDKs. Signature

isObserved

Whether a call of a function this worker hosts would reach anyone. Without a call: any active observer. With a call, on a function matched by keys: an observer filed under one of the call’s keys. On any other function the call is not read. Signature

Parameters

string
required
Partial<Call<unknown, unknown>>

observers

The active observers of a function this worker hosts (empty for any other). Signature

Parameters

string
required

onObservationDeliver

Delivers each call of a function itself: hook receives the call and the observers that matched it (a snapshot taken when the call started), and what it returns (or throws) is what the caller gets back. iii delivers nothing for that function: the hook calls through observers and applies their filters with obs.matches(call). Without it, iii delivers every call to the matching observers whose capture and filters accept it, and the caller gets the handler’s result. null removes the hook. A function with a deliver hook needs an engine with observe.v2: against an older one it stays unregistered, and the SDK logs UNSUPPORTED once. Signature
string
required
DeliverHook<I, O, R> | null
required

onObservationMatch

Says which observers want each call of a function. By default every observer wants every call. A predicate (obs, call) => boolean is asked once per observation (for every call, once for each active observer); { observer, call } key functions are computed once per observer, when it is accepted, and once per call, and an observer wants a call when they share a key (the SDK keeps an index). The observers’ capture, filters and policy still apply. A hook set while observers are active rebuilds the index from them. null removes the hook, predicate or keys: every observer gets every call again. A function with a match hook needs an engine with observe.v2: against an older one it stays unregistered, and the SDK logs UNSUPPORTED once. Signature
string
required
MatchHook<I, O> | null
required

onObserverAdded

Runs hook when an observer of any function this worker hosts is added, before the SDK acks it; with a function id, for that function only. When both are set, the worker’s runs first. Throw to reject the observer. null removes the hook. Hooks set by id stay in place across unregister() and a later registration of the same id. A hook set while the function already has active observers runs for each of them at once (a throw late-rejects that observer), and the SDK logs a warning. Signature
string
AddedHook | null
required

onObserverRemoved

Runs hook once for every accepted observer when it is removed (on unobserve, disposal, unregister, late rejection); with a function id, for that function only. When both are set, the function’s runs first. An error it throws is logged. null removes the hook. Signature

Parameters

string
RemovedHook | null
required

pipe

Creates a pipe: an InputStream and an OutputStream joined through the engine; what is written into output is read from input. Put either end in a payload or a result for the other side to use: it travels as its ref. This worker owns the pipe and must stay connected until the other side attached. A source or a sink placed in a payload gets its pipe from the SDK, so most code does not need this: use it for an end that must exist before its source does, a two-way session (two pipes), or a pipe handed to a call made later. Signature
PipeOptions
bufferSize: frames the engine holds before the reader attached.

shutdown

Gracefully shutdown the iii, cleaning up all resources. Signature

Example

Subpath Exports

The iii-sdk package provides additional entry points:

Types

iii-sdk

AddedHook · Call · CallAction · Caller · CallerInfo · Capture · DeliverHook · EnqueueResult · Filter · InitOptions · InputStream · InputStreamSource · InvocationContext · JsonValue · Key · MatchHook · MatchKeys · MatchPredicate · MiddlewareFunctionInput · Observed · Observer · ObserveReason · ObserverHandle · ObserverOptions · ObserverState · ObserveSource · OutputStream · OutputStreamSink · Pipe · PipeOptions · RemovedHook · StreamFrame · StreamInfo · StreamRequest · StreamResponse · Target · TelemetryOptions

AddedHook

Runs when an observer of a function is added, before the SDK acks it. Throw to reject the observer: an ObserveRejection sets the code, anything else is OBSERVE_REJECTED; after 30 s it is rejected with OWNER_TIMEOUT.

Call

One call of a function, as its host delivers it: what the handler was called with and what it returned (or threw). Observers observe output, the handler’s return value.

CallAction

Factory object that constructs routing actions for IIIClient.call.

Caller

Who started an invocation: the worker (worker_id / worker_name, stamped by the engine), and the function and invocation the call was made from.

CallerInfo

A caller as the SDK knows it: every field may be missing (a top-level call has no function; a call made before WorkerRegistered has no worker id).

Capture

A field an observer captures. Default ['input', 'output', 'caller'].

DeliverHook

Delivers each call of a function itself (onObservationDeliver): it receives the call and the observers that matched it (a snapshot taken when the call started), and what it returns (or throws) is what the caller gets back. A thrown ObserveRejection, or the error of a call it made, reaches the caller with its code; any other error as invocation_failed. iii delivers nothing for that function; the hook calls through observers (worker.call({ observer, payload })) and applies their filters with obs.matches(call). It runs inside the function’s invocation, so the calls it makes have that invocation as their caller.

EnqueueResult

Result returned when a function is called with CallAction.Enqueue.

Filter

A declarative filter over input, output, error, caller and metadata, with explicit operators only: { 'input.amount': { $gte: 500 } }. See the filter language reference.

InitOptions

Configuration options passed to registerWorker.

InputStream

The read side of a stream. A field of a handler’s input or of a call’s result arrives as one when the sender put a source there (a Node Readable, a Web ReadableStream, a Blob, an async generator, or an InputStream). Build one yourself with InputStream.from. A stream has one reader: read it once, with one of for await, bytes, text, lines, messages, frames, toReadable or toWebStream. Call tee first for two. Pass it on unread in a payload or a result and its ref travels instead: no bytes go through this worker. Inside a handler, a stream the handler started reading and did not finish is cancelled when the handler returns. A stream carries bytes (binary frames) and, separately, JSON messages (text frames): byte reads skip the messages, messages skips the bytes, and frames yields both in order. An abort surfaces as a StreamAbortedError from the read, after the data sent before it.

InputStreamSource

What InputStream.from reads from.

InvocationContext

The invocation the current code runs in, in every handler, remote or local (iii.currentInvocation()).

JsonValue

Any JSON value: the TypeScript equivalent of the engine’s arbitrary-JSON wire values (Rust serde_json::Value). Used where the wire contract is “any JSON”, e.g. per-invocation metadata.

Key

A match key, or several: an observer wants a call when they share one.

MatchHook

Which observers want each call of a function (onObservationMatch). By default every observer wants every call. A predicate is asked once per observation: for every call, once for each active observer (a throw counts as no match for that observer). Keys are computed once per observer, when it is accepted, and once per call. The observers’ capture, filters and policy still apply. Setting it to null removes it: every observer gets every call again.

MatchKeys

onObservationMatch as keys: an observer wants a call when they share a key, and the SDK keeps an index instead of asking every observer.

MatchPredicate

onObservationMatch as a predicate: whether this observer wants this call.

MiddlewareFunctionInput

Input passed to the RBAC middleware function on every function invocation through the RBAC port. The middleware can inspect, modify, or reject the call before it reaches the target function.

Observed

What an observer’s target receives when iii delivers: the top-level fields, plus whichever of the observer’s capture apply to the outcome. Fields not captured, or that do not apply, are absent.

Observer

An observer as the worker that hosts its function sees it (the hooks, FunctionRef.observers()): its args, filters, target and capture. Who observes, the observer’s metadata and its policy stay with the engine.

ObserveReason

A state reason or an error: a machine-readable code and a message.

ObserverHandle

What iii.observe returns, synchronously.

ObserverOptions

The observer itself: its id, policy and metadata.

ObserverState

An observer’s lifecycle: pending (no host yet, waiting for the host’s ack, or no target yet) → active or error; suspended while its worker or target is away; disposed at the end.

ObserveSource

The left side of iii.observe: what is observed.

OutputStream

The write side of a stream. A field of a handler’s input arrives as one when the caller put a sink there (a Node Writable, a Web WritableStream, or an OutputStream); the call resolves once what the handler wrote reached the sink. Build one yourself with OutputStream.to. Inside a handler, a stream the handler wrote to (or bridged) is closed when the handler returns and aborted when it throws, unless it was closed, aborted, sent on, or kept open with keepOpen. One the handler never touched is closed when it returns, whatever it returns. In an observer activation (an HTTP route target), it is closed only when the handler returns undefined or null, and left alone otherwise: the HTTP worker reads an untouched response and a value as a buffered response.

OutputStreamSink

What OutputStream.to writes into.

Pipe

The two ends of a pipe made by IIIClient.pipe: what is written into output is read from input. Either end can be put in a payload or a result.

PipeOptions

Options of IIIClient.pipe.

RemovedHook

Runs once for every accepted observer when it is removed. An error it throws is logged.

StreamFrame

One frame of InputStream.frames: bytes, or a text message.

StreamInfo

What an observer’s target sees in place of a stream that the observed call carried in its input or output: that a stream was there, its direction and its channel id, without the access key (a stream has one reader, and it is the observed function). The engine still sends the key on the wire; the SDK drops it.

StreamRequest

Incoming streaming request received by a function that serves an HTTP route.

StreamResponse

Response object passed to streaming function handlers (the http helper of @iii-dev/helpers/http). Use status() and headers() to set response metadata, write() or stream for the body, and close() when done.

Target

The right side of iii.observe: a registered function.

TelemetryOptions

Worker metadata reported to the engine (language, framework, project).

iii-sdk/engine

EngineFunctions · EngineSources · RemoteFunctionHandler

EngineFunctions

Engine function paths for internal operations.

EngineSources

The event sources the engine hosts: private functions whose handler returns the event, observed with iii.observe(EngineSources.X, target). None takes args; filter on the event (input) instead.

RemoteFunctionHandler

Handler of a registered function. Receives the invocation payload and an optional per-invocation metadata value, and returns the result (or a promise of it). The return value is what the function’s observers observe. metadata is arbitrary JSON travelling on a separate channel from the payload. It is undefined when the caller did not attach any. Existing single-argument handlers keep working; they ignore the extra argument.

iii-sdk/errors

InvocationError · InvocationErrorInit · ObserveRejection · RegistrationRejectedError · RegistrationRejectedInit · StreamAbortedError

InvocationError


InvocationErrorInit

Typed error surfaced when an invocation dispatched over the SDK fails, RBAC rejection (FORBIDDEN), handler-level failure, or a timeout waiting for the engine to respond. Wraps the wire ErrorBody shape plus the function_id that was targeted, so callers get a single error type across all failure modes and can disambiguate via err.code. Before this existed, rejection values were plain ErrorBody-shaped objects, which printed as [object Object] when stringified, leaving developers to grep through SDK source to figure out what tripped. The class name, code prefix in the message, and function_id field together make a rejection self-describing.

ObserveRejection

Thrown by an onObserverAdded hook to reject an observer with a code of its own (HTTP_ROUTE_CONFLICT, INVALID_CRON_EXPRESSION, …); any other error rejects it with OBSERVE_REJECTED. Also the error ObserverHandle.ready() rejects with when the observer turns error or disposed.

RegistrationRejectedError

Fatal error surfaced when the engine rejects this worker’s identity because another live worker owns the same (namespace, worker_name), or when an unknown rejection code is received. The SDK stops and does not reconnect. A FUNCTION_NAMESPACE_CONFLICT is non-fatal and is logged instead of being surfaced through this class. The wire fields identify the contested registration and its current owner.

RegistrationRejectedInit

Fields used to construct a RegistrationRejectedError.

StreamAbortedError

A stream failed instead of ending: its writer aborted it (a source that threw, a handler that threw while writing, out.abort()), or its socket was lost. Thrown by the reads of an InputStream after the data sent before the abort, and the error a call rejects with when a sink it passed was aborted (code is STREAM_ABORTED in both cases). reason is what the reader was told. Across the engine that is the engine’s text (channel writer aborted: closed with code 1011), not the writer’s own reason: the engine does not relay it.

iii-sdk/protocol

ActivationWire · CallerWire · CallRequest · CaptureWire · ChannelDirection · ChannelItem · DroppedReportStatsWire · ErrorBody · FunctionRegisteredMessage · InvocationResultMessage · InvocationsObservedMessage · LocalFunctionStatsWire · LocalInvocationStatsMessage · MessageType · ObservedItemWire · ObserveMessage · ObserverAckMessage · ObserverAddedMessage · ObserveResultMessage · ObserverInfoWire · ObserverRemovedMessage · ObserverStateChangedMessage · ObserveSourceWire · RegisterFunctionFormat · RegisterFunctionInput · RegisterFunctionMessage · RegisterFunctionOptions · RegistrationRejectedMessage · StreamChannelRef · UnobserveMessage

ActivationWire

InvokeFunction.activation: present on every activation of an observer’s target.

CallerWire

Who started an invocation. Engine → worker: worker_id / worker_name are stamped by the engine from the calling connection. Worker → engine: the SDK sends function_id, invocation_id and parent (the caller of the handler the call was made from, one level only).

CallRequest

Request object passed to IIIClient.call: a function by id, or the target of an observer.

CaptureWire

What an observer captures (capture): the fields its target’s payload carries, and with them the outcomes that fire it.

ChannelDirection

Direction of a streaming channel endpoint. Mirrors the Rust SDK’s ChannelDirection enum and matches the literal values used by StreamChannelRef.direction.

ChannelItem

One frame of a channel: a binary frame carries bytes, a text frame a message. Mirrors the Rust SDK’s ChannelItem enum (Text / Binary); InputStream.frames() yields these.

DroppedReportStatsWire


ErrorBody


FunctionRegisteredMessage


InvocationResultMessage


InvocationsObservedMessage


LocalFunctionStatsWire


LocalInvocationStatsMessage


MessageType


ObservedItemWire

One local call of a hosted function, with the observers its delivery selected.

ObserveMessage


ObserverAckMessage


ObserverAddedMessage


ObserveResultMessage


ObserverInfoWire

An observer as the host of its function sees it: never the observer’s metadata, policy or connection. target is the target function id.

ObserverRemovedMessage


ObserverStateChangedMessage


ObserveSourceWire

observe.source: the left side of iii.observe.

RegisterFunctionFormat


RegisterFunctionInput


RegisterFunctionMessage


RegisterFunctionOptions

Options of IIIClient.registerFunction: what describes the function to the engine (description, formats, metadata, args_format, private, observable), and what the SDK does with it (localDispatch). What the worker does when the function is observed is set with hooks.

RegistrationRejectedMessage

Sent by the engine when it refuses a registration. The code decides severity:
  • WORKER_NAMESPACE_CONFLICT: another worker already holds this (namespace, worker_name). The engine closes the connection — fatal: the SDK stops the worker and does not reconnect.
  • FUNCTION_NAMESPACE_CONFLICT: another worker already exports this one function_id. The engine keeps the connection open — non-fatal: only that registration is refused and the worker keeps serving its other functions.
  • INVALID_ARGS_FORMAT (the function’s args_format is not a valid JSON Schema) and UNSUPPORTED: only that function is refused, the connection stays open.

StreamChannelRef

Serializable reference to one end of a streaming channel. Can be included in invocation payloads to pass channel endpoints between workers.

UnobserveMessage

iii-sdk/runtime

FunctionRef · IIIConnectionState

FunctionRef

Handle returned by IIIClient.registerFunction: the client’s hook methods with the function id filled in. Each method returns the handle, so calls chain.

IIIConnectionState

Connection state for the III WebSocket

iii-sdk/state

IState · StateDeleteInput · StateDeleteResult · StateEventData · StateEventType · StateGetInput · StateListInput · StateSetInput · StateSetResult · StateUpdateInput · StateUpdateResult

IState

Interface for state management operations. Available via the iii-sdk/state subpath export.

StateDeleteInput

Input for deleting a state value.

StateDeleteResult

Result of a state delete operation.

StateEventData

Payload for state change events.

StateEventType

Types of state change events.

StateGetInput

Input for retrieving a state value.

StateListInput

Input for listing all values in a state scope.

StateSetInput

Input for setting a state value.

StateSetResult

Result of a state set operation.

StateUpdateInput

Input for atomically updating a state value.

StateUpdateResult

Result of a state update operation.