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
address
string
required
WebSocket URL of the III engine (e.g. ws://localhost:49134).
options
InitOptions
Optional InitOptions for worker name, timeouts, reconnection, and OTel.

Methods

registerTrigger

Registers a new trigger. A trigger is a way to invoke a function when a certain event occurs. Signature
trigger
RegisterTriggerInput
required
The trigger to register.

registerFunction

Registers a new function with a local handler or an HTTP invocation config. Signature
functionId
string
required
Unique identifier for the function.
handler
HttpInvocationConfig | RemoteFunctionHandler<any, any>
required
Async handler for local execution, or an HTTP invocation config for external functions (Lambda, Cloudflare Workers, etc.).
options
RegisterFunctionOptions
Optional function registration options (description, request/response formats, metadata).

trigger

Invokes a function using a request object. Signature
request
TriggerRequest<TInput>
required
The trigger request containing function_id, payload, and optional action/timeout.

registerTriggerType

Registers a new trigger type. A trigger type is a way to invoke a function when a certain event occurs. Signature
triggerType
RegisterTriggerTypeInput
required
The trigger type to register.
handler
TriggerHandler<TConfig>
required
The handler for the trigger type.

unregisterTriggerType

Unregisters a trigger type. Signature
triggerType
RegisterTriggerTypeInput
required
The trigger type to unregister.

shutdown

Gracefully shutdown the iii, cleaning up all resources. Signature

Example

Subpath Exports

The iii-sdk package provides additional entry points:
Import pathContents
iii-sdk/channelChannel, ChannelReader, ChannelWriter, StreamChannelRef
iii-sdk/engineEngineFunctions, EngineTriggers, RemoteFunctionHandler
iii-sdk/errorsInvocationError, InvocationErrorInit, isErrorBody
iii-sdk/helpersChannelDirection, ChannelItem, createChannel, createStream, extractChannelRefs, isChannelRef
iii-sdkEnqueueResult, IIIClient, InitOptions, InvocationError, InvocationErrorInit, JsonValue, MiddlewareFunctionInput, StreamRequest, StreamResponse, TelemetryOptions, TriggerAction, registerWorker
iii-sdk/protocolErrorBody, MessageType, RegisterFunctionFormat, RegisterFunctionInput, RegisterFunctionMessage, RegisterFunctionOptions, RegisterTriggerInput, RegisterTriggerMessage, RegisterTriggerTypeInput, RegisterTriggerTypeMessage, TriggerRequest
iii-sdk/runtimeFunctionRef, IIIConnectionState, TriggerTypeRef
iii-sdk/stateIState, StateDeleteInput, StateDeleteResult, StateEventData, StateEventType, StateGetInput, StateListInput, StateSetInput, StateSetResult, StateUpdateInput, StateUpdateResult
iii-sdk/streamIStream
iii-sdk/triggerTrigger, TriggerConfig, TriggerHandler

Types

iii-sdk

EnqueueResult · InitOptions · JsonValue · MiddlewareFunctionInput · StreamRequest · StreamResponse · TelemetryOptions · TriggerAction

EnqueueResult

Result returned when a function is invoked with TriggerAction.Enqueue.
NameTypeRequiredDescription
messageReceiptIdstringYesUnique receipt ID for the enqueued message.

InitOptions

Configuration options passed to registerWorker.
NameTypeRequiredDescription
enableMetricsReportingbooleanNoEnable worker metrics via OpenTelemetry. Defaults to true.
headersRecord<string, string>NoCustom HTTP headers sent during the WebSocket handshake.
invocationTimeoutMsnumberNoDefault timeout for worker.trigger() invocations in milliseconds. Defaults to 30000.
otelOmit<OtelConfig, "engineWsUrl">NoOpenTelemetry configuration. OTel is initialized automatically by default.
Set { enabled: false } or env OTEL_ENABLED=false/0/no/off to disable.
The engineWsUrl is set automatically from the III address.
reconnectionConfigPartial<IIIReconnectionConfig>NoWebSocket reconnection behavior.
workerDescriptionstringNoOne-line, human/LLM-readable summary of what this worker does.
Surfaces in engine::workers::list / engine::workers::info.
workerNamestringNoDisplay name for this worker. Defaults to hostname:pid.

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.

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.
NameTypeRequiredDescription
actionTriggerActionNoRouting action, if any.
contextRecord<string, unknown>YesAuth context returned by the auth function for this session.
function_idstringYesID of the function being invoked.
payloadRecord<string, unknown>YesPayload sent by the caller.

StreamRequest

Incoming streaming request received by a function registered with a stream trigger.

StreamResponse

Response object passed to streaming function handlers. Use status() and headers() to set response metadata, write to stream for streaming responses, and call close() when done.
NameTypeRequiredDescription
close() => voidYesClose the response.
headers(headers: Record<string, string>) => voidYesSet response headers.
status(statusCode: number) => voidYesSet the HTTP status code.
streamNodeJS.WritableStreamYesWritable stream for the response body.

TelemetryOptions

Worker metadata reported to the engine (language, framework, project).
NameTypeRequiredDescription
amplitude_api_keystringNoAmplitude API key for product analytics.
frameworkstringNoFramework name, if applicable.
languagestringNoProgramming language of the worker.
project_namestringNoName of the project this worker belongs to.

TriggerAction

Factory object that constructs routing actions for IIIClient.trigger.
NameTypeRequiredDescription
Enqueue(opts: { queue: string }) => { queue: string; type: "enqueue" }YesRoutes the invocation through a named queue. The engine enqueues the job,
acknowledges the caller with { messageReceiptId }, and processes it
asynchronously.

Requires a queue worker in the project. Run iii worker add queue.
Without it the trigger rejects with enqueue_error (no queue provider).
Void() => { type: "void" }YesFire-and-forget routing. The engine forwards the invocation without
waiting for a response or queuing the job.

iii-sdk/channel

Channel · ChannelReader · ChannelWriter · StreamChannelRef

Channel

A streaming channel pair for worker-to-worker data transfer. Created via the createChannel helper from iii-sdk/helpers.
NameTypeRequiredDescription
readerChannelReaderYesReader end of the channel.
readerRefStreamChannelRefYesSerializable reference to the reader (can be sent to other workers).
writerChannelWriterYesWriter end of the channel.
writerRefStreamChannelRefYesSerializable reference to the writer (can be sent to other workers).

ChannelReader

Read end of a streaming channel. Provides both a Node.js Readable stream for binary data and an onMessage callback for structured text messages.
NameTypeRequiredDescription
streamReadableYesNode.js Readable stream for binary data.

ChannelWriter

Write end of a streaming channel. Provides both a Node.js Writable stream and a sendMessage method for sending structured text messages.
NameTypeRequiredDescription
streamWritableYesNode.js Writable stream for binary data.

StreamChannelRef

Serializable reference to one end of a streaming channel. Can be included in invocation payloads to pass channel endpoints between workers.
NameTypeRequiredDescription
access_keystringYesAccess key for authentication.
channel_idstringYesUnique channel identifier.
direction"read" | "write"YesWhether this ref is for reading or writing.

iii-sdk/engine

EngineFunctions · EngineTriggers · RemoteFunctionHandler

EngineFunctions

Engine function paths for internal operations. Naming note: LIST_TRIGGERS / INFO_TRIGGERS cover trigger TYPES (templates). LIST_REGISTERED_TRIGGERS / INFO_REGISTERED_TRIGGERS cover trigger INSTANCES (subscriber rows). The old engine::trigger-types::list builtin has been removed and is now served by engine::triggers::list.
NameTypeRequiredDescription
INFO_FUNCTIONS"engine::functions::info"Yes-
INFO_REGISTERED_TRIGGERS"engine::registered-triggers::info"Yes-
INFO_TRIGGERS"engine::triggers::info"Yes-
INFO_WORKERS"engine::workers::info"Yes-
LIST_FUNCTIONS"engine::functions::list"Yes-
LIST_REGISTERED_TRIGGERS"engine::registered-triggers::list"Yes-
LIST_TRIGGERS"engine::triggers::list"Yes-
LIST_WORKERS"engine::workers::list"Yes-
REGISTER_WORKER"engine::workers::register"Yes-

EngineTriggers

Engine trigger types
NameTypeRequiredDescription
FUNCTIONS_AVAILABLE"engine::functions-available"Yes-
LOG"log"Yes-

RemoteFunctionHandler

Async function handler for a registered function. Receives the invocation payload and an optional per-invocation metadata value, and returns the result. 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

InvocationError

NameTypeRequiredDescription
codestringYes-
function_idstringNo-
stacktracestringNo-

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.
NameTypeRequiredDescription
codestringYes-
function_idstringNo-
messagestringYes-
stacktracestringNo-

iii-sdk/helpers

ChannelDirection · ChannelItem

ChannelDirection

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

ChannelItem

Discriminated runtime tag for an item observed on a streaming channel. Mirrors the Rust SDK’s ChannelItem enum (Text / Binary). Carrier for factory + type-guard helpers so callers can construct and discriminate channel items without depending on Rust-specific shape.

iii-sdk/protocol

ErrorBody · MessageType · RegisterFunctionFormat · RegisterFunctionInput · RegisterFunctionMessage · RegisterFunctionOptions · RegisterTriggerInput · RegisterTriggerMessage · RegisterTriggerTypeInput · RegisterTriggerTypeMessage · TriggerRequest

ErrorBody

NameTypeRequiredDescription
codestringYes-
messagestringYes-
stacktracestringNo-

MessageType

NameTypeRequiredDescription
InvocationResult"invocationresult"Yes-
InvokeFunction"invokefunction"Yes-
RegisterFunction"registerfunction"Yes-
RegisterTrigger"registertrigger"Yes-
RegisterTriggerType"registertriggertype"Yes-
TriggerRegistrationResult"triggerregistrationresult"Yes-
UnregisterFunction"unregisterfunction"Yes-
UnregisterTrigger"unregistertrigger"Yes-
UnregisterTriggerType"unregistertriggertype"Yes-
WorkerRegistered"workerregistered"Yes-

RegisterFunctionFormat

NameTypeRequiredDescription
descriptionstringNoThe description of the parameter.
itemsunknownNoThe items of the parameter (for arrays).
namestringNoThe name of the parameter.
propertiesRecord<string, unknown>NoThe body of the parameter (for objects).
requiredstring[]NoWhether the parameter is required.
type"string" | "number" | "boolean" | "object" | "array" | "null" | "map" | "integer"NoThe type of the parameter.
[key: string]unknownNo-

RegisterFunctionInput

NameTypeRequiredDescription
descriptionstringNoThe description of the function.
idstringYesThe path of the function (use :: for namespacing, e.g. external::my_lambda).
invocationHttpInvocationConfigNoHTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.).
metadataRecord<string, unknown>NoArbitrary metadata attached to the function.
request_formatRegisterFunctionFormatNoThe request format of the function.
response_formatRegisterFunctionFormatNoThe response format of the function.

RegisterFunctionMessage

NameTypeRequiredDescription
descriptionstringNoThe description of the function.
idstringYesThe path of the function (use :: for namespacing, e.g. external::my_lambda).
invocationHttpInvocationConfigNoHTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.).
message_typeMessageType.RegisterFunctionYes-
metadataRecord<string, unknown>NoArbitrary metadata attached to the function.
request_formatRegisterFunctionFormatNoThe request format of the function.
response_formatRegisterFunctionFormatNoThe response format of the function.

RegisterFunctionOptions

NameTypeRequiredDescription
descriptionstringNoThe description of the function.
invocationHttpInvocationConfigNoHTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.).
metadataRecord<string, unknown>NoArbitrary metadata attached to the function.
request_formatRegisterFunctionFormatNoThe request format of the function.
response_formatRegisterFunctionFormatNoThe response format of the function.

RegisterTriggerInput

NameTypeRequiredDescription
configunknownYesTrigger-type-specific configuration, matching the shape the trigger type expects.
function_idstringYesID of the function this trigger invokes when it fires.
metadataRecord<string, unknown>NoArbitrary user-specifiable metadata supplied to the triggered handler function on every invocation.
typestringYesIdentifier of the registered trigger type this trigger uses (e.g. storage::object-created, http).

RegisterTriggerMessage

NameTypeRequiredDescription
configunknownYesTrigger-type-specific configuration, matching the shape the trigger type expects.
function_idstringYesID of the function this trigger invokes when it fires.
idstringYesUnique trigger identifier, generated by the SDK during registration.
message_typeMessageType.RegisterTriggerYesWire discriminator; always MessageType.RegisterTrigger.
metadataRecord<string, unknown>NoArbitrary user-specifiable metadata supplied to the triggered handler function on every invocation.
typestringYesIdentifier of the registered trigger type this trigger uses (e.g. storage::object-created, http).

RegisterTriggerTypeInput

NameTypeRequiredDescription
descriptionstringYesHuman-readable description of what this trigger type does.
idstringYesUnique identifier for the trigger type (e.g. state, durable:subscriber).

RegisterTriggerTypeMessage

NameTypeRequiredDescription
descriptionstringYesHuman-readable description of what this trigger type does.
idstringYesUnique identifier for the trigger type (e.g. state, durable:subscriber).
message_typeMessageType.RegisterTriggerTypeYes-

TriggerRequest

Request object passed to IIIClient.trigger.
NameTypeRequiredDescription
actionTriggerActionNoSets how the trigger is routed. Omit for a synchronous request/response. Specify for a specific routing scheme (e.g. TriggerAction.Enqueue(), TriggerAction.Void()).
function_idstringYesID of the function to invoke.
metadataunknownNoArbitrary user-specifiable metadata supplied to the triggered handler function on every invocation.
payloadTInputYesInput data passed to the function.
timeoutMsnumberNoOverride the default invocation timeout, in milliseconds.

iii-sdk/runtime

FunctionRef · IIIConnectionState · TriggerTypeRef

FunctionRef

Handle returned by IIIClient.registerFunction. Contains the function’s id and an unregister() method.
NameTypeRequiredDescription
idstringYesThe unique function identifier.
unregister() => voidYesRemoves this function from the engine.

IIIConnectionState

Connection state for the III WebSocket

TriggerTypeRef

Typed handle returned by IIIClient.registerTriggerType. Provides convenience methods to register triggers and functions scoped to this trigger type, so callers don’t need to repeat the type field.
NameTypeRequiredDescription
idstringYesThe trigger type identifier.
registerFunction(functionId: string, handler: RemoteFunctionHandler, config: TConfig, metadata?: Record<string, unknown>) => FunctionRefYesRegister a function and immediately bind it to this trigger type.
registerTrigger(functionId: string, config: TConfig, metadata?: Record<string, unknown>) => TriggerYesRegister a trigger bound to this trigger type.
unregister() => voidYesUnregister this trigger type from the engine.

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.
NameTypeRequiredDescription
delete(input: StateDeleteInput) => Promise<StateDeleteResult>YesDelete a state value.
get(input: StateGetInput) => Promise<TData | null>YesRetrieve a value by scope and key.
list(input: StateListInput) => Promise<TData[]>YesList all values in a scope.
set(input: StateSetInput) => Promise<StateSetResult<TData> | null>YesSet (create or overwrite) a state value.
update(input: StateUpdateInput) => Promise<StateUpdateResult<TData> | null>YesApply atomic update operations to a state value.

StateDeleteInput

Input for deleting a state value.
NameTypeRequiredDescription
keystringYesKey within the scope.
scopestringYesState scope (namespace).

StateDeleteResult

Result of a state delete operation.
NameTypeRequiredDescription
old_valueanyNoPrevious value (if it existed).

StateEventData

Payload for state change events.
NameTypeRequiredDescription
event_typeStateEventTypeYesType of state change.
keystringYesKey within the scope.
new_valueTDataNoNew value (for create/update events).
old_valueTDataNoPrevious value (for update/delete events).
scopestringYesState scope (namespace).
type"state"Yes-

StateEventType

Types of state change events.
NameTypeRequiredDescription
Created"state:created"Yes-
Deleted"state:deleted"Yes-
Updated"state:updated"Yes-

StateGetInput

Input for retrieving a state value.
NameTypeRequiredDescription
keystringYesKey within the scope.
scopestringYesState scope (namespace).

StateListInput

Input for listing all values in a state scope.
NameTypeRequiredDescription
scopestringYesState scope (namespace).

StateSetInput

Input for setting a state value.
NameTypeRequiredDescription
keystringYesKey within the scope.
scopestringYesState scope (namespace).
valueanyYesValue to store.

StateSetResult

Result of a state set operation.
NameTypeRequiredDescription
new_valueTDataYesNew value that was stored.
old_valueTDataNoPrevious value (if it existed).

StateUpdateInput

Input for atomically updating a state value.
NameTypeRequiredDescription
keystringYesKey within the scope.
opsUpdateOp[]YesOrdered list of update operations to apply atomically.
scopestringYesState scope (namespace).

StateUpdateResult

Result of a state update operation.
NameTypeRequiredDescription
errorsUpdateOpError[]NoPer-op errors. Currently emitted only by the merge op when input
violates the validation bounds. See UpdateOpError and the
UpdateMerge JSDoc in ./stream for the error codes. Field is
omitted from the JSON wire when empty.
new_valueTDataYesNew value after the update.
old_valueTDataNoPrevious value (if it existed).

iii-sdk/stream

IStream

IStream

Interface for custom stream implementations. Passed to IIIClient.createStream to override the engine’s built-in stream storage.
NameTypeRequiredDescription
delete(input: StreamDeleteInput) => Promise<StreamDeleteResult>YesDelete a stream item.
get(input: StreamGetInput) => Promise<TData | null>YesRetrieve a single item by group and item ID.
list(input: StreamListInput) => Promise<TData[]>YesList all items in a group.
listGroups(input: StreamListGroupsInput) => Promise<string[]>YesList all group IDs in a stream.
set(input: StreamSetInput) => Promise<StreamSetResult<TData> | null>YesSet (create or overwrite) a stream item.
update(input: StreamUpdateInput) => Promise<StreamUpdateResult<TData> | null>YesApply atomic update operations to a stream item.

iii-sdk/trigger

Trigger · TriggerConfig · TriggerHandler

Trigger

Handle returned by IIIClient.registerTrigger. Use unregister() to remove the trigger from the engine.
NameTypeRequiredDescription
unregister() => voidYesRemoves this trigger from the engine.

TriggerConfig

Configuration passed to a trigger handler when a trigger instance is registered or unregistered.
NameTypeRequiredDescription
configTConfigYesTrigger-specific configuration.
function_idstringYesFunction to invoke when the trigger fires.
idstringYesTrigger instance ID.
metadataRecord<string, unknown>NoArbitrary user-specifiable metadata supplied to the triggered handler function on every invocation.

TriggerHandler

Handler interface for custom trigger types. Passed to IIIClient.registerTriggerType.
NameTypeRequiredDescription
registerTrigger(config: TriggerConfig<TConfig>) => Promise<void>YesCalled when a trigger instance is registered.
unregisterTrigger(config: TriggerConfig<TConfig>) => Promise<void>YesCalled when a trigger instance is unregistered.