Link to this sectionInstallation
npm install iii-browser-sdkLink to this sectionInitialization
Link to this sectionregisterWorker
Register the worker with a iii instance, returns a connected worker client. The WebSocket connection is established automatically.
Signature
registerWorker(address: string, options?: InitOptions) => ISdkimport { registerWorker } from 'iii-browser-sdk'
const worker = registerWorker('ws://localhost:49135')Link to this sectionMethods
Link to this sectionregisterFunction
Registers a new function with a local handler that runs in the browser session. HTTP invocation configs are a Node.js SDK feature. The handler's return value is what the function's observers observe; an event source's handler returns the event it is called with.
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
registerFunction(functionId: string, handler: RemoteFunctionHandler<I, O>, options?: RegisterFunctionOptions) => FunctionRef<I, O>// Local handler
const ref = worker.registerFunction(
'greet',
async (data: { name: string }) => ({ message: `Hello, ${data.name}!` }),
{ description: 'Returns a greeting' },
)
// An event source: observed by everyone, called only by this page, set up
// for each observer by its args
worker
.registerFunction('ui::on-click', (click: Click) => click, { args_format: ClickArgs, private: true })
.onObserverAdded((obs) => targets.retain(obs.args.selector as string))
.onObserverRemoved((obs) => targets.release(obs.args.selector as string))
// Later, remove the function
ref.unregister()Link to this sectioncall
Invokes a function: by id, or the target of an observer of a function
this worker hosts ({ observer, payload }).
Signature
call(request: CallRequest<TInput>) => Promise<TOutput>// Synchronous invocation
const result = await worker.call<{ name: string }, { message: string }>({
function_id: 'greet',
payload: { name: 'World' },
timeoutMs: 5000,
})
console.log(result.message) // "Hello, World!"
// Fire-and-forget
await worker.call({
function_id: 'send-email',
payload: { to: 'user@example.com' },
action: CallAction.Void(),
})
// Enqueue for async processing (the queue must be declared in the
// queue worker's queue_configs)
const receipt = await worker.call({
function_id: 'process-order',
payload: { orderId: '123' },
action: CallAction.Enqueue({ queue: 'orders' }),
})
// Through an observer, in the function's deliver hook: runs its target,
// with its policy and metadata
const response = await worker.call({ observer: route.obs, payload: request })Link to this sectionobserve
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(); against
an engine without observe that is UNSUPPORTED. 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
observe(source: string | ObserveSource, target: Target, options?: ObserverOptions) => ObserverHandleworker.registerFunction('ui::order-shipped', async ({ input }: Observed) => toast(input))
// every successful call of orders::ship
worker.observe('orders::ship', 'ui::order-shipped')
// only this customer's
const shipped = worker.observe(
{ function_id: 'orders::ship', filters: { 'input.customer_id': { $eq: customerId } } },
'ui::order-shipped',
)
await shipped.ready()Link to this sectiontrigger
Invokes a function using a request object.
Signature
trigger(request: CallRequest<TInput>) => Promise<TOutput>Link to this sectionParameters
Link to this sectionaddConnectionStateListener
Subscribe to connection-state transitions. The handler is fired immediately with the current state, then on every transition. Multiple listeners are supported. Returns an unsubscribe function.
Signature
addConnectionStateListener(handler: (state: IIIConnectionState) => void) => () => voidconst unsub = worker.addConnectionStateListener((state) => {
console.log('connection state:', state)
})
// Later, stop receiving updates
unsub()Link to this sectioncurrentInvocation
The invocation the calling code runs in (remote or local handler, or the
function's deliver hook), or undefined outside any handler.
Browsers have no AsyncLocalStorage: the SDK knows the invocation while
the handler runs synchronously, up to its first await; after it this
returns undefined. Read it before awaiting, and re-enter it with
ISdk.withInvocation for calls made after.
Code after an await, outside ISdk.withInvocation, runs outside any
invocation, but its calls are not treated as new chains: they carry the
observe_depth of the deepest invocation running on this page, so the
engine's loop guard (max_observe_depth) still stops an observer cycle
whose target awaits before calling back. With several invocations
running this over-counts, and a legitimate chain may stop early. They
carry a caller and traceparent only when that is unambiguous (one
invocation is running, and it is an observe activation or its function's
deliver hook is running); otherwise none. An invocation that never
settles stops counting as running after 10 minutes (a local call: at its
timeout). Local calls nest the same way: a self-recursion that awaits
before each call goes through the engine past 64 levels, while calls
started together count as one level. A limitation: local calls started in
separate ticks while earlier ones still run also look nested, so a long,
wide fan-out may send some through the engine (same results). While the
socket is closed none is: a function this worker hosts then runs here up
to 256 local calls deep, and past that the call fails at once with
LOCAL_DEPTH_EXCEEDED (a runaway recursion must not freeze the page).
Signature
currentInvocation() => InvocationContext | undefinedLink to this sectionExample
worker.registerFunction('ui::checkout', async (cart) => {
const inv = worker.currentInvocation() // { function_id, invocation_id, caller, observe_depth, ... }
const quote = await fetchQuote(cart)
return worker.withInvocation(inv, () => worker.call({ function_id: 'orders::create', payload: quote }))
})Link to this sectiongetFatalError
The fatal registration rejection that terminated this connection, if any
(e.g. a WORKER_NAMESPACE_CONFLICT); undefined while healthy. Mirrors the
Node/Python/Rust SDKs.
Signature
getFatalError() => RegistrationRejectedError | undefinedLink to this sectionisObserved
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
isObserved(functionId: string, call?: Partial<Call<unknown, unknown>>) => booleanLink to this sectionParameters
Link to this sectionobservers
The active observers of a function this worker hosts (empty for any other).
Signature
observers(functionId: string) => readonly Observer[]Link to this sectionParameters
Link to this sectiononObservationDeliver
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.
The hook runs in the function's invocation: up to its first await in
its scope, and after it as the invocation the page falls back to while it
is the only one running (see ISdk.withInvocation).
Signature
onObservationDeliver(functionId: string, hook: DeliverHook<I, O, R> | null) => ISdkworker.onObservationDeliver('ui::on-command', async (call) => {
const handler = commands.match(call.input)
if (!handler) return { handled: false }
if (!handler.obs.matches(call)) return { handled: false }
return worker.call({ observer: handler.obs, payload: call.input })
})Link to this sectiononObservationMatch
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
onObservationMatch(functionId: string, hook: MatchPredicate<I, O> | null) => ISdk
onObservationMatch(functionId: string, hook: MatchKeys<I, O>) => ISdk
onObservationMatch(functionId: string, hook: MatchHook<I, O> | null) => ISdk// an observer of selector X gets the clicks on X
worker.onObservationMatch('ui::on-click', (obs, call) => obs.args.selector === call.input.selector)
// many observers: keys, one lookup per key
worker.onObservationMatch('ui::on-click', {
observer: (obs) => obs.args.selector as string,
call: (call) => call.input.selector,
})Link to this sectiononObserverAdded
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
onObserverAdded(hook: AddedHook | null) => ISdk
onObserverAdded(functionId: string, hook: AddedHook | null) => ISdk// every function this page hosts: keep the event stream open while anything is observed
worker.onObserverAdded(async () => { await events.retain() })
// one function, by id
worker.onObserverAdded('ui::on-click', (obs) => targets.retain(obs.args.selector as string))Link to this sectiononObserverRemoved
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
onObserverRemoved(hook: RemovedHook | null) => ISdk
onObserverRemoved(functionId: string, hook: RemovedHook | null) => ISdkLink to this sectionParameters
Link to this sectionpipe
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
pipe(options?: PipeOptions) => Promise<Pipe>const pipe = await worker.pipe()
const result = worker.call({ function_id: 'files::process', payload: { body: pipe.input } })
await file.stream().pipeTo(pipe.output.toWebStream())
await resultLink to this sectionshutdown
Gracefully shutdown the iii, cleaning up all resources.
Signature
shutdown() => Promise<void>Link to this sectionExample
await worker.shutdown()Link to this sectionwithInvocation
Runs fn inside invocation (what ISdk.currentInvocation
returned), and returns what fn returns. Calls fn makes before its own
first await (call, currentInvocation) belong to that invocation:
they carry its caller, observe_depth and traceparent. When fn
returns a promise, the invocation counts as running until it settles, so
fn's code after an await gets the fallback below. undefined runs
fn outside any invocation.
Code after an await, outside withInvocation, runs outside any
invocation, but its calls are not treated as new chains: they carry the
observe_depth of the deepest invocation running on this page, so the
engine's loop guard (max_observe_depth) still stops an observer cycle
whose target awaits before calling back. With several invocations
running this over-counts, and a legitimate chain may stop early. They
carry a caller and traceparent only when that is unambiguous (one
invocation is running, and it is an observe activation or its function's
deliver hook is running); otherwise none. An invocation that never
settles stops counting as running after 10 minutes (a local call: at its
timeout). Local calls nest the same way: a self-recursion that awaits
before each call goes through the engine past 64 levels, while calls
started together count as one level. A limitation: local calls started in
separate ticks while earlier ones still run also look nested, so a long,
wide fan-out may send some through the engine (same results). While the
socket is closed none is: a function this worker hosts then runs here up
to 256 local calls deep, and past that the call fails at once with
LOCAL_DEPTH_EXCEEDED (a runaway recursion must not freeze the page).
Signature
withInvocation(invocation: InvocationContext | undefined, fn: () => T) => TLink to this sectionParameters
Link to this sectionSubpath Exports
The iii-browser-sdk package provides additional entry points:
| Import path | Contents |
|---|---|
iii-browser-sdk | AddedHook, ApiRequest, ApiResponse, AuthInput, AuthResult, Call, CallAction, CallRequest, Caller, CallerInfo, Capture, DeliverHook, EngineFunctions, EngineSources, EnqueueResult, Filter, FunctionRef, IIIConnectionState, IIIReconnectionConfig, ISdk, InitOptions, InputStream, InputStreamSource, InvocationContext, InvocationError, InvocationErrorInit, Key, MatchHook, MatchKeys, MatchPredicate, MessageType, MiddlewareFunctionInput, ObserveReason, ObserveRejection, ObserveSource, Observed, Observer, ObserverHandle, ObserverOptions, ObserverState, OnFunctionRegistrationInput, OnFunctionRegistrationResult, OpenEnum, OutputStream, OutputStreamSink, Pipe, PipeOptions, RegisterFunctionFormat, RegisterFunctionInput, RegisterFunctionMessage, RegisterFunctionOptions, RegistrationRejectedError, RegistrationRejectedInit, RemoteFunctionHandler, RemovedHook, StreamAbortedError, StreamFrame, StreamInfo, Target, registerWorker |
iii-browser-sdk/protocol | ChannelDirection, ChannelItem, StreamChannelRef, extractChannelRefs, isChannelRef |
iii-browser-sdk/state | DeleteResult, IState, StateDeleteInput, StateDeleteResult, StateEventData, StateEventType, StateGetInput, StateListInput, StateSetInput, StateSetResult, StateUpdateInput, StateUpdateResult |
iii-browser-sdk/stream | MergePath, UpdateAppend, UpdateDecrement, UpdateIncrement, UpdateMerge, UpdateOp, UpdateOpError, UpdateRemove, UpdateSet |
Link to this sectionTypes
Link to this sectioniii-browser-sdk
AddedHook · ApiRequest · ApiResponse · AuthInput · AuthResult · Call · CallAction · Caller · CallerInfo · CallRequest · Capture · DeliverHook · EngineFunctions · EngineSources · EnqueueResult · Filter · FunctionRef · IIIConnectionState · IIIReconnectionConfig · InitOptions · InputStream · InputStreamSource · InvocationContext · InvocationError · InvocationErrorInit · Key · MatchHook · MatchKeys · MatchPredicate · MessageType · MiddlewareFunctionInput · Observed · Observer · ObserveReason · ObserveRejection · ObserverHandle · ObserverOptions · ObserverState · ObserveSource · OnFunctionRegistrationInput · OnFunctionRegistrationResult · OpenEnum · OutputStream · OutputStreamSink · Pipe · PipeOptions · RegisterFunctionFormat · RegisterFunctionInput · RegisterFunctionMessage · RegisterFunctionOptions · RegistrationRejectedError · RegistrationRejectedInit · RemoteFunctionHandler · RemovedHook · StreamAbortedError · StreamFrame · StreamInfo · Target
Link to this sectionAddedHook
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.
type AddedHook = (obs: Observer) => void | Promise<void>Link to this sectionApiRequest
The HTTP request an http::on-request route's target receives.
| Name | Type | Required | Description |
|---|---|---|---|
body | TBody | Yes | - |
headers | Record<string, string | string[]> | Yes | - |
method | string | Yes | - |
path_params | Record<string, string> | Yes | - |
query_params | Record<string, string | string[]> | Yes | - |
Link to this sectionApiResponse
The response an http::on-request route's target returns.
| Name | Type | Required | Description |
|---|---|---|---|
body | TBody | No | Response body. |
headers | Record<string, string> | No | Response headers. |
status_code | TStatus | Yes | HTTP status code. |
Link to this sectionAuthInput
Input passed to the RBAC auth function during WebSocket upgrade. Contains the HTTP headers, query parameters, and client IP from the connecting worker's upgrade request.
| Name | Type | Required | Description |
|---|---|---|---|
headers | Record<string, string> | Yes | HTTP headers from the WebSocket upgrade request. |
ip_address | string | Yes | IP address of the connecting client. |
query_params | Record<string, string[]> | Yes | Query parameters from the upgrade URL. Each key maps to an array of values to support repeated keys. |
Link to this sectionAuthResult
Return value from the RBAC auth function. Controls which functions the authenticated worker can invoke and what context is forwarded to the middleware.
| Name | Type | Required | Description |
|---|---|---|---|
allow_function_registration | boolean | No | Whether the worker may register new functions. Defaults to true if omitted. |
allowed_functions | string[] | No | Additional function IDs to allow beyond the expose_functions config, in the default namespace only. Put per-namespace grants in namespaces. Defaults to [] if omitted. |
context | Record<string, unknown> | No | Arbitrary context forwarded to the middleware function on every invocation. Defaults to {} if omitted. |
forbidden_functions | string[] | No | Function IDs to deny even if they match expose_functions. Takes precedence over allowed. Defaults to [] if omitted. |
function_registration_prefix | string | No | Optional prefix applied to all function IDs registered by this worker. |
namespaces | Record<string, string[]> | No | Grants scoped to one namespace each: { orders: ['svc::*'] }. A value is anexact function ID or a wildcard, in either the bare ( svc::*) or thematch("svc::*") spelling.The keys are also the namespaces the session may declare on engine::workers::register. Omit to scope nothing: the session declares anynamespace, and only allowed_functions and expose_functions apply. |
Link to this sectionCall
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.
| Name | Type | Required | Description |
|---|---|---|---|
caller | Caller | No | Who made the call; absent for a call made outside any handler. |
error | { code: string; message: string; stacktrace?: string } | No | What the handler threw. |
function_id | string | Yes | - |
input | I | Yes | - |
invocation_id | string | Yes | - |
metadata | Record<string, unknown> | No | - |
output | O | No | The handler's return value: what observers observe. |
status | "error" | "success" | Yes | - |
Link to this sectionCallAction
Factory object that constructs routing actions for ISdk.call.
| Name | Type | Required | Description |
|---|---|---|---|
Enqueue | (opts: { queue: string }) => { queue: string; type: "enqueue" } | Yes | Routes the invocation through a named queue. The engine enqueues the job, acknowledges the caller with { messageReceiptId }, and processes itasynchronously. |
Void | () => { type: "void" } | Yes | Fire-and-forget routing. The engine forwards the invocation without waiting for a response or queuing the job. |
Link to this sectionCaller
Who started an invocation: the worker (worker_id / worker_name, stamped
by the engine), and the function and invocation the call was made from.
| Name | Type | Required | Description |
|---|---|---|---|
function_id | string | No | The handler the call was made from; absent for top-level calls. |
invocation_id | string | No | - |
parent | Omit<Caller, "parent"> | No | The caller of that handler, one level only. |
worker_id | string | No | Absent on activations, whose caller is the engine (worker_name: 'iii-engine'). |
worker_name | string | No | - |
Link to this sectionCallerInfo
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).
type CallerInfo = Partial<Omit<Caller, "parent">> & { parent?: Partial<Omit<Caller, "parent">> }Link to this sectionCallRequest
Request object passed to ISdk.call: a function by id, or the target of an observer.
type CallRequest = { action?: CallAction; baggage?: string; dispatch?: "auto" | "remote"; function_id: string; metadata?: unknown; namespace?: string; observer?: never; payload: TInput; timeoutMs?: number; traceparent?: string } | { action?: CallAction; function_id?: never; metadata?: never; observer: Observer; payload: TInput; timeoutMs?: number }Link to this sectionCapture
A field an observer captures. Default ['input', 'output', 'caller'].
type Capture = "input" | "output" | "error" | "caller" | "metadata"Link to this sectionDeliverHook
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.
Browsers have no AsyncLocalStorage: the hook runs in the invocation's
scope up to its first await. A call it makes after one still has the
invocation as its caller while that invocation is the only one running on
the page; to be sure, read iii.currentInvocation() first and re-enter it
with iii.withInvocation(inv, fn). A call through an observer is routed to
the observer's target either way.
type DeliverHook = (call: Call<I, O>, observers: readonly Observer[]) => R | Promise<R>Link to this sectionEngineFunctions
Engine function paths for internal operations.
| Name | Type | Required | Description |
|---|---|---|---|
INFO_FUNCTIONS | "engine::functions::info" | Yes | - |
INFO_WORKERS | "engine::workers::info" | Yes | - |
LIST_FUNCTIONS | "engine::functions::list" | Yes | - |
LIST_WORKERS | "engine::workers::list" | Yes | - |
REGISTER_WORKER | "engine::workers::register" | Yes | - |
Link to this sectionEngineSources
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.
| Name | Type | Required | Description |
|---|---|---|---|
CONFIGURATION_UPDATED | "configuration::on-updated" | Yes | The engine's configuration was reloaded. |
FUNCTIONS_CHANGED | "engine::on-functions-changed" | Yes | A function was registered or unregistered; each row carries observer_count. |
LOG | "observability::on-log" | Yes | A log record. |
OBSERVERS_CHANGED | "engine::on-observers-changed" | Yes | An observer changed state: { observer_id, function_id, target, state, reason? }. |
SPAN | "observability::on-span" | Yes | A finished span. |
WORKERS_CHANGED | "engine::on-workers-changed" | Yes | A worker connected or left. |
Link to this sectionEnqueueResult
Result returned when a function is called with CallAction.Enqueue.
| Name | Type | Required | Description |
|---|---|---|---|
messageReceiptId | string | Yes | Unique receipt ID for the enqueued message. |
Link to this sectionFilter
A declarative filter over input, output, error, caller and
metadata, with explicit operators only:
{ 'input.amount': { $gte: 500 } }. See the filter language reference.
type Filter = Record<string, unknown>Link to this sectionFunctionRef
Handle returned by ISdk.registerFunction: the client's hook methods with the function id filled in. Each method returns the handle, so calls chain.
| Name | Type | Required | Description |
|---|---|---|---|
id | string | Yes | The unique function identifier. |
isObserved | (call?: Partial<Call<I, unknown>>) => boolean | Yes | ISdk.isObserved for this registration: skip building an event nobody receives. Without a call it is one load of this registration's active set. |
observers | () => readonly Observer[] | Yes | The active observers of this registration, as this host sees them (none once the function is unregistered, also after the id is registered again). |
onObservationDeliver | (hook: DeliverHook<I, O, R> | null) => FunctionRef<I, O> | Yes | ISdk.onObservationDeliver for this function. |
onObservationMatch | (hook: MatchHook<I, O> | null) => FunctionRef<I, O> | Yes | ISdk.onObservationMatch for this function. |
onObserverAdded | (hook: AddedHook | null) => FunctionRef<I, O> | Yes | ISdk.onObserverAdded for this function. |
onObserverRemoved | (hook: RemovedHook | null) => FunctionRef<I, O> | Yes | ISdk.onObserverRemoved for this function. |
unregister | () => void | Yes | Removes this function from the engine. Its hooks stay in place for a later registration of the id. |
Link to this sectionIIIConnectionState
Connection state for the III WebSocket
type IIIConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting" | "failed"Link to this sectionIIIReconnectionConfig
Configuration for WebSocket reconnection behavior
| Name | Type | Required | Description |
|---|---|---|---|
backoffMultiplier | number | Yes | Exponential backoff multiplier (default: 2) |
initialDelayMs | number | Yes | Starting delay in milliseconds (default: 1000ms) |
jitterFactor | number | Yes | Random jitter factor 0-1 (default: 0.3) |
maxDelayMs | number | Yes | Maximum delay cap in milliseconds (default: 30000ms) |
maxRetries | number | Yes | Maximum retry attempts, -1 for infinite (default: -1) |
Link to this sectionInitOptions
Configuration options passed to registerWorker.
| Name | Type | Required | Description |
|---|---|---|---|
headers | Record<string, string> | No | Browser WebSocket connections authenticate via query parameters or cookies; the headers option is ignored. |
invocationTimeoutMs | number | No | Default timeout for worker.call() invocations in milliseconds. Defaults to 30000. |
namespace | string | No | Namespace this worker registers under. When omitted the engine applies itsdefault namespace. Scopes worker and function registrations soidentically-named entries can coexist across namespaces. The browser has no process.env, so there is no environment-variable fallback: pass theoption explicitly. |
reconnectionConfig | Partial<IIIReconnectionConfig> | No | WebSocket reconnection behavior. |
workerName | string | No | Name this worker announces to the engine. Defaults to a uniquebrowser:<random> per client: a browser has no pid to disambiguate by, andthe engine allows only one live worker per name in a namespace, so two tabs sharing a fixed name would evict each other. |
Link to this sectionInputStream
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 Web
ReadableStream, a Blob or File, an async generator, an
InputStream, or a Node Readable from a Node worker). Build one yourself
with InputStream.from.
A stream has one reader: read it once, with one of for await,
bytes, text, lines, messages, frames
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.
Link to this sectionInputStreamSource
What InputStream.from reads from.
type InputStreamSource = InputStream | ReadableStream<Uint8Array> | Blob | Uint8Array | ArrayBuffer | string | AsyncIterable<Uint8Array | string> | Iterable<Uint8Array | string>Link to this sectionInvocationContext
The invocation the current code runs in, in every handler, remote or
local (iii.currentInvocation()).
Browsers have no AsyncLocalStorage, so the SDK knows it only while the
handler runs synchronously: up to its first await. To keep it across an
await, read it first and re-enter it with iii.withInvocation(inv, fn).
| Name | Type | Required | Description |
|---|---|---|---|
activation | { activation_id?: string; observer_id: string } | No | Set when this invocation is the activation of an observer's target. |
baggage | string | No | The W3C baggage that came with traceparent. |
caller | CallerInfo | No | - |
function_id | string | Yes | - |
invocation_id | string | Yes | - |
observe_depth | number | Yes | - |
traceparent | string | No | The W3C traceparent the invocation arrived with (or was called with,for a local call). Calls made inside the handler forward it. Browser SDK only: there is no OpenTelemetry context to carry it. |
Link to this sectionInvocationError
An error the SDK raises itself for an invocation, with a machine-readable
code: LOCAL_DEPTH_EXCEEDED (a local call nested too deep while the
socket is closed) and payload_too_large. Mirrors the Node SDK.
A call the engine answers with an error rejects with the engine's error
body ({ code, message, stacktrace? }), and so does a locally dispatched
call whose handler or deliver hook throws: both paths reject with the same
value.
| Name | Type | Required | Description |
|---|---|---|---|
code | string | Yes | - |
function_id | string | No | - |
stacktrace | string | No | - |
Link to this sectionInvocationErrorInit
Fields used to construct an InvocationError.
| Name | Type | Required | Description |
|---|---|---|---|
code | string | Yes | - |
function_id | string | No | - |
message | string | Yes | - |
stacktrace | string | No | - |
Link to this sectionKey
A match key, or several: an observer wants a call when they share one.
type Key = string | readonly string[]Link to this sectionMatchHook
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.
type MatchHook = MatchPredicate<I, O> | MatchKeys<I, O>Link to this sectionMatchKeys
onObservationMatch as keys: an observer wants a call when they share a key,
and the SDK keeps an index instead of asking every observer.
| Name | Type | Required | Description |
|---|---|---|---|
call | (call: Call<I, O>) => Key | Yes | What this call is. |
observer | (obs: Observer) => Key | Yes | What this observer listens for, computed once when it is accepted. |
Link to this sectionMatchPredicate
onObservationMatch as a predicate: whether this observer wants this call.
type MatchPredicate = (obs: Observer, call: Call<I, O>) => booleanLink to this sectionMessageType
| Name | Type | Required | Description |
|---|---|---|---|
FunctionRegistered | "functionregistered" | Yes | Engine → host: the registerfunction ack, with the function's full observer set. |
InvocationResult | "invocationresult" | Yes | - |
InvocationsObserved | "invocationsobserved" | Yes | Host → engine: the calls of its functions that observers matched, batched. |
InvokeFunction | "invokefunction" | Yes | - |
LocalInvocationStats | "localinvocationstats" | Yes | Host → engine: periodic counts of local invocations and report drops. |
Observe | "observe" | Yes | Observing worker → engine: create (or idempotently replay) an observer. |
ObserverAck | "observerack" | Yes | Host → engine: accept (or reject) an added observer. |
ObserverAdded | "observeradded" | Yes | Engine → host: one observer attached to a function this connection hosts. |
ObserveResult | "observeresult" | Yes | Engine → observing worker: the reply to observe (also on replay). |
ObserverRemoved | "observerremoved" | Yes | Engine → host: one observer detached. |
ObserverStateChanged | "observerstatechanged" | Yes | Engine → observing worker: an observer's lifecycle transition. |
Reattach | "reattach" | Yes | - |
RegisterFunction | "registerfunction" | Yes | - |
RegistrationRejected | "registrationrejected" | Yes | - |
Unobserve | "unobserve" | Yes | Observing worker → engine: dispose an observer this connection owns. |
UnregisterFunction | "unregisterfunction" | Yes | - |
WorkerRegistered | "workerregistered" | Yes | - |
Link to this sectionMiddlewareFunctionInput
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.
| Name | Type | Required | Description |
|---|---|---|---|
action | CallAction | No | Routing action, if any. |
context | Record<string, unknown> | Yes | Auth context returned by the auth function for this session. |
function_id | string | Yes | ID of the function being invoked. |
namespace | string | No | Target namespace the invoke addressed; forward the call here to stay in the caller's namespace. Absent → the engine's default namespace. |
payload | Record<string, unknown> | Yes | Payload sent by the caller. |
Link to this sectionObserved
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.
| Name | Type | Required | Description |
|---|---|---|---|
activation_id | string | Yes | - |
caller | Caller | No | - |
duration_ms | number | Yes | - |
error | { code: string; message: string } | No | - |
function_id | string | Yes | - |
input | I | No | - |
invocation_id | string | Yes | - |
metadata | Record<string, unknown> | No | - |
namespace | string | Yes | - |
observer_id | string | Yes | - |
output | O | No | - |
started_at_ms | number | Yes | - |
status | "error" | "success" | Yes | - |
Link to this sectionObserver
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.
| Name | Type | Required | Description |
|---|---|---|---|
args | Record<string, unknown> | Yes | The observer's args, validated against the function's args_format by the engine. |
capture | Capture[] | Yes | - |
filters | Filter | Yes | The observer's filters, normalized. |
function_id | string | Yes | The observed function (one this worker hosts). |
id | string | Yes | - |
target | string | Yes | The target function id. |
accepted | () => Promise<void> | Yes | Resolves once the SDK has acked the observer. A call made after it resolves reaches an active observer, so a provider sends an observer its initial state from here: a call through it ( iii.call({ observer: obs, payload })), which runs its target alonewith the payload as given. Rejects with an ObserveRejection when the observer is rejected first. |
matches | (call: Partial<Call>) => boolean | Yes | Whether call reaches this observer: its capture fires on the call'sstatus (absent reads as 'success') and its filters match the call. |
reject | (code: string, message: string) => void | Yes | Late rejection of an active observer (e.g. after a config reload). It stops receiving calls at once, its onObserverRemoved hooks run, and itstays rejected across reconnects until the engine adds it again. |
Link to this sectionObserveReason
A state reason or an error: a machine-readable code and a message.
| Name | Type | Required | Description |
|---|---|---|---|
code | string | Yes | - |
message | string | Yes | - |
Link to this sectionObserveRejection
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.
| Name | Type | Required | Description |
|---|---|---|---|
code | string | Yes | - |
Link to this sectionObserverHandle
What iii.observe returns, synchronously.
| Name | Type | Required | Description |
|---|---|---|---|
id | string | Yes | - |
reason | ObserveReason | No | Why the observer is in its state (error, suspended, disposed). |
state | ObserverState | Yes | - |
dispose | () => Promise<void> | Yes | Removes the observer (unobserve). It is not replayed on reconnect.After the engine refused the observe, it sends nothing. It resolves atonce in every case and awaits no answer from the engine, also when it is called before the answer to the observe arrives. |
onStateChange | (listener: (state: ObserverState, reason?: ObserveReason) => void) => () => void | Yes | Calls listener on every state change, in order; returns theunsubscribe function. Listeners are called asynchronously (never on the connection's read path), so they may call the client. |
ready | () => Promise<void> | Yes | Resolves when the observer is active; rejects with anObserveRejection carrying the code when it turns error ordisposed first. |
Link to this sectionObserverOptions
The observer itself: its id, policy and metadata.
| Name | Type | Required | Description |
|---|---|---|---|
expires_in_ms | number | No | The observer is disposed this many milliseconds after it is created (EXPIRED). Default: never. |
id | string | No | Default: a random UUID, stable across replays. The handle holds it until it is disposed: an observe of an id a handle of this client holdsthrows an ObserveRejection with code OBSERVER_ID_CONFLICT andsends nothing. |
max_fires | number | No | The observer is disposed after this many activations (MAX_FIRES). Default: unlimited. |
max_in_flight | number | No | Activations running at once; further ones queue, then drop as OVERFLOW.Default: the engine's observers.default_max_in_flight (64). |
metadata | Record<string, unknown> | No | Delivered as the metadata sidecar of every activation. |
Link to this sectionObserverState
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.
type ObserverState = "pending" | "active" | "suspended" | "error" | "disposed"Link to this sectionObserveSource
The left side of iii.observe: what is observed.
| Name | Type | Required | Description |
|---|---|---|---|
args | Record<string, unknown> | No | For the worker that hosts the function: what to set up and which calls to deliver (a table, a cron expression, a route). The engine validates them against the function's args_format. |
capture | Capture[] | No | What the target's payload carries, and with it which outcomes fire the target. Default ['input', 'output', 'caller'].- input and output fire on success, error fires on error.- caller and metadata only add to the payload: a capture must nameat least one of input, output, error (INVALID_ARGS otherwise).- [] fires on success, with the top-level fields only.So the default fires on success, ['error', 'caller'] on errors, and['input', 'error'] on both. A success's payload never has error, anerror's never has output. |
filters | Filter | No | Which calls reach the target, by input, output, error, caller and metadata; {} (or absent) = every call. |
function_id | string | Yes | The observed function. |
namespace | string | No | Defaults to this worker's namespace (engine::* and configuration::* resolve to default). |
Link to this sectionOnFunctionRegistrationInput
Input passed to the on_function_registration_function_id hook
when a worker attempts to register a function through the RBAC port.
Return an OnFunctionRegistrationResult with the (possibly mapped)
fields, or throw to deny the registration.
| Name | Type | Required | Description |
|---|---|---|---|
args_format | Record<string, unknown> | No | JSON Schema of the args its observers pass; sent when the registration sets it. |
context | Record<string, unknown> | Yes | Auth context from AuthResult.context for this session. |
description | string | No | Human-readable description of the function. |
function_id | string | Yes | ID of the function being registered. |
metadata | Record<string, unknown> | No | Arbitrary metadata attached to the function. |
namespace | string | No | Namespace the function registers in. The same id can exist in several namespaces, so the hook needs this to authorize per namespace. |
observable | boolean | Yes | false: nobody may observe the function; always sent. |
private | boolean | Yes | Only the registering worker may call the function; always sent. |
Link to this sectionOnFunctionRegistrationResult
Result returned from the on_function_registration_function_id hook.
All fields are optional; omitted fields keep the original value from the
registration request.
| Name | Type | Required | Description |
|---|---|---|---|
args_format | Record<string, unknown> | No | Replaces the registration's args_format. |
description | string | No | Mapped description. |
function_id | string | No | Mapped function ID. |
metadata | Record<string, unknown> | No | Mapped metadata. |
observable | boolean | No | Replaces the registration's observable. |
private | boolean | No | Replaces the registration's private. |
Link to this sectionOpenEnum
A wire enum that a newer peer may extend: decoders keep a value they do not know instead of failing the frame.
type OpenEnum = T | string & objectLink to this sectionOutputStream
The write side of a stream. A field of a handler's input arrives as one when
the caller put a sink there (a Web WritableStream, an OutputStream, or a
Node Writable from a Node worker); 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.
Link to this sectionOutputStreamSink
What OutputStream.to writes into.
type OutputStreamSink = WritableStream<Uint8Array>Link to this sectionPipe
The two ends of a pipe made by ISdk.pipe: what is written into
output is read from input. Either end can be put in a payload or a result.
| Name | Type | Required | Description |
|---|---|---|---|
input | InputStream | Yes | The read end. |
output | OutputStream | Yes | The write end. |
Link to this sectionPipeOptions
Options of ISdk.pipe.
| Name | Type | Required | Description |
|---|---|---|---|
bufferSize | number | No | Frames the engine holds for the pipe before its reader attached (engine default when omitted). |
Link to this sectionRegisterFunctionFormat
| Name | Type | Required | Description |
|---|---|---|---|
description | string | No | The description of the parameter |
items | unknown | No | The items of the parameter (for arrays) |
name | string | No | The name of the parameter |
properties | Record<string, unknown> | No | The body of the parameter (for objects) |
required | string[] | No | Whether the parameter is required |
type | "string" | "number" | "boolean" | "object" | "array" | "null" | "map" | "integer" | No | The type of the parameter |
[key: string] | unknown | No | - |
Link to this sectionRegisterFunctionInput
type RegisterFunctionInput = Omit<RegisterFunctionMessage, "message_type">| Name | Type | Required | Description |
|---|---|---|---|
args_format | RegisterFunctionFormat | No | JSON Schema of the args an observer of this function passes. Theengine validates every observer's args against it ( INVALID_ARGS)before the added hooks run, and refuses a schema that is not valid ( INVALID_ARGS_FORMAT). A function without it takes no args. |
description | string | No | Human-readable summary of the function, listed by discovery ( engine::functions::list). |
id | string | Yes | The path of the function (use :: for namespacing, e.g. external::my_lambda) |
metadata | Record<string, unknown> | No | Arbitrary metadata attached to the function, stored with it and listed by discovery ( engine::functions::list). It is distinct from the per-callmetadata a handler receives. |
observable | boolean | No | false: nobody may observe the function (NOT_OBSERVABLE), for onewhose payloads carry credentials. Default true; sent only when false. |
private | boolean | No | Only this worker may call the function: the engine answers a call from any other connection with FORBIDDEN, and refuses the function as anobserver's target. Any worker may observe it, and its observers receive every call this worker makes. For event sources, whose calls from anywhere else would be forged events. This worker's own calls pass the input and the result by reference: the handler and hooks treat both as read-only. Default false; sent only when true. |
request_format | RegisterFunctionFormat | No | JSON Schema of the call's input. |
response_format | RegisterFunctionFormat | No | JSON Schema of the handler's return value: what the function's observers observe. |
Link to this sectionRegisterFunctionMessage
| Name | Type | Required | Description |
|---|---|---|---|
args_format | RegisterFunctionFormat | No | JSON Schema of the args an observer of this function passes. Theengine validates every observer's args against it ( INVALID_ARGS)before the added hooks run, and refuses a schema that is not valid ( INVALID_ARGS_FORMAT). A function without it takes no args. |
description | string | No | Human-readable summary of the function, listed by discovery ( engine::functions::list). |
id | string | Yes | The path of the function (use :: for namespacing, e.g. external::my_lambda) |
message_type | MessageType.RegisterFunction | Yes | - |
metadata | Record<string, unknown> | No | Arbitrary metadata attached to the function, stored with it and listed by discovery ( engine::functions::list). It is distinct from the per-callmetadata a handler receives. |
observable | boolean | No | false: nobody may observe the function (NOT_OBSERVABLE), for onewhose payloads carry credentials. Default true; sent only when false. |
private | boolean | No | Only this worker may call the function: the engine answers a call from any other connection with FORBIDDEN, and refuses the function as anobserver's target. Any worker may observe it, and its observers receive every call this worker makes. For event sources, whose calls from anywhere else would be forged events. This worker's own calls pass the input and the result by reference: the handler and hooks treat both as read-only. Default false; sent only when true. |
request_format | RegisterFunctionFormat | No | JSON Schema of the call's input. |
response_format | RegisterFunctionFormat | No | JSON Schema of the handler's return value: what the function's observers observe. |
Link to this sectionRegisterFunctionOptions
Options of ISdk.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.
type RegisterFunctionOptions = Omit<RegisterFunctionMessage, "message_type" | "id"> & { localDispatch?: boolean }| Name | Type | Required | Description |
|---|---|---|---|
args_format | RegisterFunctionFormat | No | JSON Schema of the args an observer of this function passes. Theengine validates every observer's args against it ( INVALID_ARGS)before the added hooks run, and refuses a schema that is not valid ( INVALID_ARGS_FORMAT). A function without it takes no args. |
description | string | No | Human-readable summary of the function, listed by discovery ( engine::functions::list). |
localDispatch | boolean | No | Calls this worker makes to its own function run in-process once the engine confirmed it (default true). Set false for a handler that mustalways run through the engine. |
metadata | Record<string, unknown> | No | Arbitrary metadata attached to the function, stored with it and listed by discovery ( engine::functions::list). It is distinct from the per-callmetadata a handler receives. |
observable | boolean | No | false: nobody may observe the function (NOT_OBSERVABLE), for onewhose payloads carry credentials. Default true; sent only when false. |
private | boolean | No | Only this worker may call the function: the engine answers a call from any other connection with FORBIDDEN, and refuses the function as anobserver's target. Any worker may observe it, and its observers receive every call this worker makes. For event sources, whose calls from anywhere else would be forged events. This worker's own calls pass the input and the result by reference: the handler and hooks treat both as read-only. Default false; sent only when true. |
request_format | RegisterFunctionFormat | No | JSON Schema of the call's input. |
response_format | RegisterFunctionFormat | No | JSON Schema of the handler's return value: what the function's observers observe. |
Link to this sectionRegistrationRejectedError
A terminal registration rejection from the engine. Thrown into every pending
invocation and exposed via getFatalError() when a worker-name collision
(or other non-retryable rejection) closes the connection for good.
| Name | Type | Required | Description |
|---|---|---|---|
code | string | Yes | - |
function_id | string | No | - |
namespace | string | Yes | - |
owner_worker_id | string | Yes | - |
worker_name | string | No | - |
Link to this sectionRegistrationRejectedInit
| Name | Type | Required | Description |
|---|---|---|---|
code | string | Yes | - |
function_id | string | No | - |
namespace | string | Yes | - |
owner_worker_id | string | Yes | - |
worker_name | string | No | - |
Link to this sectionRemoteFunctionHandler
Handler of a registered function. Receives the invocation payload and its
metadata (CallRequest.metadata of the call, or an observer's metadata
sidecar on an activation) and returns the result (or a promise of it). The
return value is what the function's observers observe.
type RemoteFunctionHandler = (data: TInput, metadata?: unknown) => TOutput | Promise<TOutput>Link to this sectionRemovedHook
Runs once for every accepted observer when it is removed. An error it throws is logged.
type RemovedHook = (obs: Observer) => void | Promise<void>Link to this sectionStreamAbortedError
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). Mirrors the Node SDK.
reason is what the reader was told. Across the engine that is the
engine's text (channel writer aborted: closed with code 4011 for a browser
writer), not the writer's own reason: the engine does not relay it.
| Name | Type | Required | Description |
|---|---|---|---|
code | string | Yes | - |
function_id | string | No | - |
reason | string | Yes | Why the stream was aborted, as the reader learned it. |
stacktrace | string | No | - |
Link to this sectionStreamFrame
One frame of InputStream.frames: bytes, or a text message.
type StreamFrame = { type: "binary"; value: Uint8Array } | { type: "text"; value: string }Link to this sectionStreamInfo
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.
| Name | Type | Required | Description |
|---|---|---|---|
direction | "read" | "write" | Yes | - |
id | string | Yes | - |
stream | true | Yes | - |
Link to this sectionTarget
The right side of iii.observe: a registered function.
type Target = string | { function_id: string; namespace?: string }Link to this sectioniii-browser-sdk/protocol
ChannelDirection · ChannelItem · StreamChannelRef
Link to this sectionChannelDirection
Direction of a streaming channel endpoint. Mirrors the Rust SDK's
ChannelDirection enum and matches the literal values used by
StreamChannelRef.direction.
type ChannelDirection = typeof ChannelDirection[keyof typeof ChannelDirection]Link to this sectionChannelItem
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.
type ChannelItem = { type: "text"; value: string } | { type: "binary"; value: Uint8Array }Link to this sectionStreamChannelRef
Serializable reference to one end of a streaming channel. Can be included in invocation payloads to pass channel endpoints between workers.
| Name | Type | Required | Description |
|---|---|---|---|
access_key | string | Yes | Access key for authentication. |
channel_id | string | Yes | Unique channel identifier. |
direction | "read" | "write" | Yes | Whether this ref is for reading or writing. |
Link to this sectioniii-browser-sdk/state
DeleteResult · IState · StateDeleteInput · StateDeleteResult · StateEventData · StateEventType · StateGetInput · StateListInput · StateSetInput · StateSetResult · StateUpdateInput · StateUpdateResult
Link to this sectionDeleteResult
Result of a state delete operation.
| Name | Type | Required | Description |
|---|---|---|---|
old_value | any | No | Previous value (if it existed). |
Link to this sectionIState
Interface for state management operations. Available via the iii-browser-sdk/state
subpath export.
| Name | Type | Required | Description |
|---|---|---|---|
delete | (input: StateDeleteInput) => Promise<DeleteResult> | Yes | Delete a state value. |
get | (input: StateGetInput) => Promise<TData | null> | Yes | Retrieve a value by scope and key. |
list | (input: StateListInput) => Promise<TData[]> | Yes | List all values in a scope. |
set | (input: StateSetInput) => Promise<StateSetResult<TData> | null> | Yes | Set (create or overwrite) a state value. |
update | (input: StateUpdateInput) => Promise<StateUpdateResult<TData> | null> | Yes | Apply atomic update operations to a state value. |
Link to this sectionStateDeleteInput
Input for deleting a state value.
| Name | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Key within the scope. |
scope | string | Yes | State scope (namespace). |
Link to this sectionStateDeleteResult
Result of a state delete operation.
| Name | Type | Required | Description |
|---|---|---|---|
old_value | any | No | Previous value (if it existed). |
Link to this sectionStateEventData
Payload for state change events.
| Name | Type | Required | Description |
|---|---|---|---|
event_type | StateEventType | Yes | Type of state change. |
key | string | Yes | Key within the scope. |
new_value | TData | No | New value (for create/update events). |
old_value | TData | No | Previous value (for update/delete events). |
scope | string | Yes | State scope (namespace). |
type | "state" | Yes | - |
Link to this sectionStateEventType
Types of state change events.
| Name | Type | Required | Description |
|---|---|---|---|
Created | "state:created" | Yes | - |
Deleted | "state:deleted" | Yes | - |
Updated | "state:updated" | Yes | - |
Link to this sectionStateGetInput
Input for retrieving a state value.
| Name | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Key within the scope. |
scope | string | Yes | State scope (namespace). |
Link to this sectionStateListInput
Input for listing all values in a state scope.
| Name | Type | Required | Description |
|---|---|---|---|
scope | string | Yes | State scope (namespace). |
Link to this sectionStateSetInput
Input for setting a state value.
| Name | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Key within the scope. |
scope | string | Yes | State scope (namespace). |
value | any | Yes | Value to store. |
Link to this sectionStateSetResult
Result of a state set operation.
| Name | Type | Required | Description |
|---|---|---|---|
new_value | TData | Yes | New value that was stored. |
old_value | TData | No | Previous value (if it existed). |
Link to this sectionStateUpdateInput
Input for atomically updating a state value.
| Name | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Key within the scope. |
ops | UpdateOp[] | Yes | Ordered list of update operations to apply atomically. |
scope | string | Yes | State scope (namespace). |
Link to this sectionStateUpdateResult
Result of a state update operation.
| Name | Type | Required | Description |
|---|---|---|---|
errors | UpdateOpError[] | No | Per-op errors. Currently emitted only by the merge op wheninput violates validation bounds. Field omitted when empty. |
new_value | TData | Yes | New value after the update. |
old_value | TData | No | Previous value (if it existed). |
Link to this sectioniii-browser-sdk/stream
MergePath · UpdateAppend · UpdateDecrement · UpdateIncrement · UpdateMerge · UpdateOp · UpdateOpError · UpdateRemove · UpdateSet
Link to this sectionMergePath
Path target for a UpdateMerge op. Accepts:
- a single string (legacy / first-level field)
- an array of literal segments (nested path; each element is one literal key, dots are NOT interpreted as separators)
Omit path, pass "", or pass [] to target the root value.
type MergePath = string | string[]Link to this sectionUpdateAppend
Append an element to an array, concatenate a string, or push a new
value at a nested path. The target is the root (when path is
omitted, empty, or []), a single first-level key (when path is
a non-empty string), or an arbitrary nested location (when path
is an array of literal segments). See MergePath.
Engine semantics: missing/null intermediates along a nested path are
auto-created; missing leaves on a nested path always become arrays
(no string-concat tier); existing object/scalar leaves return
append.type_mismatch. Each path segment is a literal key,
["a.b"] targets a single key named "a.b", not a → b.
| Name | Type | Required | Description |
|---|---|---|---|
path | MergePath | No | Optional path to the append target. Accepts a single first-level key (legacy string) or an array of literal segments for nestedappend. See MergePath (the same shape is reused). |
type | "append" | Yes | - |
value | any | Yes | Value to append. String targets only accept string values. |
Link to this sectionUpdateDecrement
Decrement a numeric field by a given amount.
| Name | Type | Required | Description |
|---|---|---|---|
by | number | Yes | Amount to decrement by. |
path | string | Yes | First-level field path. |
type | "decrement" | Yes | - |
Link to this sectionUpdateIncrement
Increment a numeric field by a given amount.
| Name | Type | Required | Description |
|---|---|---|---|
by | number | Yes | Amount to increment by. |
path | string | Yes | First-level field path. |
type | "increment" | Yes | - |
Link to this sectionUpdateMerge
Shallow-merge an object into the target. The target is the root
(when path is omitted/empty) or an arbitrary nested location
specified by an array of literal segments. See MergePath.
Validation: invalid paths/values (depth > 32, segment > 256 bytes,
value depth > 16, > 1024 top-level keys, or any
__proto__/constructor/prototype segment or top-level key) are
rejected with a structured error in the response's errors array.
| Name | Type | Required | Description |
|---|---|---|---|
path | MergePath | No | Optional path to the merge target. See MergePath. |
type | "merge" | Yes | - |
value | any | Yes | Object to merge. Must be a JSON object. |
Link to this sectionUpdateOp
Union of all atomic update operations supported by streams.
type UpdateOp = UpdateSet | UpdateIncrement | UpdateDecrement | UpdateAppend | UpdateRemove | UpdateMergeLink to this sectionUpdateOpError
Per-op error returned by state::update / stream::update.
| Name | Type | Required | Description |
|---|---|---|---|
code | string | Yes | Stable error code, e.g. "merge.path.too_deep". |
doc_url | string | No | Optional documentation URL. |
message | string | Yes | Human-readable description with concrete numbers when applicable. |
op_index | number | Yes | Index of the offending op within the original ops array. |
Link to this sectionUpdateRemove
Remove a field at the given path.
| Name | Type | Required | Description |
|---|---|---|---|
path | string | Yes | First-level field path. |
type | "remove" | Yes | - |
Link to this sectionUpdateSet
Set a field at the given path to a value.
| Name | Type | Required | Description |
|---|---|---|---|
path | string | Yes | First-level field path. Use an empty string to target the root value. |
type | "set" | Yes | - |
value | any | Yes | Value to set. |