Skip to main content

Installation

API reference for the @iii-dev/helpers package (Node.js / TypeScript).

http

HTTP request/response types, auth config, and the http helper. Import

Functions

http

Helper that wraps an HTTP-style handler (with separate req/res arguments) into the function handler format expected by the SDK. Signature
callback
(req: HttpStreamingRequest, res: HttpStreamingResponse) => Promise<void | HttpResponse<number, string | Buffer<ArrayBufferLike> | Record<string, unknown>>>
required
Async handler receiving a streaming request and response.

Types

HttpAuthConfig · HttpInvocationConfig · HttpMethod · HttpRequest · HttpResponse

HttpAuthConfig

Authentication configuration for HTTP-invoked functions.
  • hmac: HMAC signature verification using a shared secret.
  • bearer: Bearer token authentication.
  • api_key: API key sent via a custom header.

HttpInvocationConfig

Configuration for an HTTP-invoked function (Lambda, Cloudflare Workers, etc.).
NameTypeRequiredDescription
authHttpAuthConfigNoAuthentication configuration.
headersRecord<string, string>NoCustom headers to send with the request.
methodHttpMethodNoHTTP method. Defaults to POST.
timeout_msnumberNoTimeout in milliseconds.
urlstringYesURL to invoke.

HttpMethod

HTTP method accepted by HttpInvocationConfig. Distinct from the core builtin_triggers HTTP method enum, which also covers HEAD/OPTIONS.

HttpRequest

Incoming buffered HTTP request received by a function handler.
NameTypeRequiredDescription
bodyTBodyYesParsed request body.
headersRecord<string, string | string[]>YesRequest headers.
methodstringYesHTTP method of the request (e.g. GET, POST).
path_paramsRecord<string, string>YesPath parameters extracted from the matched route.
query_paramsRecord<string, string | string[]>YesQuery-string parameters from the request URL.
request_bodyHttpStreamReaderYesStreaming reader for the raw request body.

HttpResponse

Structured buffered HTTP response returned from function handlers.
NameTypeRequiredDescription
bodyTBodyNoResponse body.
headersRecord<string, string>NoResponse headers.
status_codeTStatusYesHTTP status code.

observability

Logger, OpenTelemetry config, and span helpers. Import

Functions

currentSpanId

Extract the current span ID from the active span context. Signature

currentSpanIsRecording

Returns false when there is no active span or the sampler dropped it. Signature

currentTraceId

Extract the current trace ID from the active span context. Signature

executeTracedRequest

Execute a fetch request inside an OTel CLIENT span. Mirrors the Rust execute_traced_request shape: injects W3C traceparent into outgoing headers, records HTTP semantic-convention attributes, and sets ERROR span status for HTTP responses with status >= 400 or network errors. Signature

Parameters

input
RequestInfo | URL
required
The resource to fetch: a URL string, URL, or Request.
init
TracedFetchInit
Fetch options, plus an optional tracer to create the span.

extractBaggage

Extract baggage from a W3C baggage header string. Signature

Parameters

baggage
string
required
W3C baggage header value to parse.

extractContext

Extract both trace context and baggage from their respective headers. Signature

Parameters

traceparent
string
W3C traceparent header value to parse.
baggage
string
W3C baggage header value to parse.

extractTraceparent

Extract a trace context from a W3C traceparent header string. Signature

Parameters

traceparent
string
required
W3C traceparent header value to parse.

flushOtel

Force-flush all OTel providers without tearing them down. Counterpart to shutdownOtel. Use before short-lived process exits where you want pending spans/metrics/logs delivered but plan to keep using OTel afterwards. Signature

getAllBaggage

Get all baggage entries from the current context. Signature

getBaggageEntry

Get a baggage entry from the current context. Signature

Parameters

key
string
required
Baggage entry key to read.

getLogger

Get the OpenTelemetry logger instance. Signature

initOtel

Initialize OpenTelemetry with the given configuration. This should be called once at application startup. Signature

Parameters

config
OtelConfig
required
OpenTelemetry configuration; env vars fill in unset fields.

injectBaggage

Inject the current baggage into a W3C baggage header string. Signature

injectTraceparent

Inject the current trace context into a W3C traceparent header string. Signature

patchGlobalFetch

Patch globalThis.fetch to create OTel CLIENT spans for every HTTP request. Signature

Parameters

tracer
Tracer
required
Tracer used to create the client span for each request.

recordSpanEvent

No-op when the current span is not recording. Signature

Parameters

name
string
required
Name of the event to add to the active span.
attrs
Attributes
Optional attributes to attach to the event.

redact

Recursively redact values of sensitive keys. Returns a new value. Signature

Parameters

value
unknown
required
The value to recursively redact.

redactAndTruncate

Redact then serialize to JSON, optionally capped at maxBytes. Signature

Parameters

value
unknown
required
The value to redact and serialize.
maxBytes
number | null
required
Maximum serialized size in bytes; null leaves it uncapped.

registerWorkerGauges

Register OpenTelemetry observable gauges that report worker resource metrics (CPU, memory, event-loop) on each collection cycle. Signature

Parameters

meter
Meter
required
options
WorkerGaugesOptions
required

removeBaggageEntry

Remove a baggage entry from the current context. Signature

Parameters

key
string
required
Baggage entry key to remove.

resolveMaxBytesFromEnv

Resolve the payload byte cap from the environment, returning undefined when unset. Signature

safeStringify

Safely stringify a value, handling circular references, BigInt, and other edge cases. Returns “[unserializable]” if serialization fails for any reason. Signature

Parameters

value
unknown
required
The value to serialize to JSON.

setBaggageEntry

Set a baggage entry in the current context. Signature

Parameters

key
string
required
Baggage entry key to set.
value
string
required
Baggage entry value to set.

setCurrentSpanAttribute

No-op when the current span is not recording. Signature

Parameters

key
string
required
Attribute key to set on the active span.
value
AttributeValue
required
Attribute value to set.

setCurrentSpanError

No-op when there is no active span. Signature

Parameters

message
string
required
Error message to set as the span’s error status.

shutdownOtel

Shut down OpenTelemetry, best-effort flushing any pending data before teardown. Signature

stopWorkerGauges

Stop and unregister the worker resource gauges. Signature

unpatchGlobalFetch

Restore globalThis.fetch to its original implementation. Signature

withSpan

Start a new span with the given name and run the callback within it. Signature

Parameters

name
string
required
Name of the span to create.
options
{ kind?: SpanKind; traceparent?: string }
required
Span options: kind sets the span kind, traceparent sets the parent context from a W3C traceparent header.
fn
(span: Span) => Promise<T>
required
Callback run inside the active span; its result is returned.

Types

BaggageSpanProcessor · Logger · OtelConfig · OtelLogEvent · ReconnectionConfig · TracedFetchInit · WorkerGaugesOptions · WorkerMetricsCollector · WorkerMetricsCollectorOptions

BaggageSpanProcessor

OpenTelemetry span processor that copies OTel baggage entries onto each started span as attributes.

Logger

Structured logger that emits logs as OpenTelemetry LogRecords. Every log call automatically captures the active trace and span context, correlating your logs with distributed traces without any manual wiring. When OTel is not initialized, Logger gracefully falls back to console.*. Pass structured data as the second argument to any log method. Using an object of key-value pairs (instead of string interpolation) lets you filter, aggregate, and build dashboards in your observability backend.

OtelConfig

Configuration for OpenTelemetry initialization.
NameTypeRequiredDescription
enabledbooleanNoWhether OpenTelemetry export is enabled. Defaults to true. Set to false or OTEL_ENABLED=false/0/no/off to disable.
engineWsUrlstringNoIII Engine WebSocket URL. Defaults to III_URL or “ws://localhost:49134”.
fetchInstrumentationEnabledbooleanNoWhether to auto-instrument globalThis.fetch calls. Defaults to true. Works on Node.js, Bun, and Deno. Set to false to disable.
instrumentationsInstrumentation<InstrumentationConfig>[]NoOpenTelemetry instrumentations to register (e.g., PrismaInstrumentation).
logsBatchSizenumberNoMaximum number of log records exported per batch. Defaults to 1.
logsFlushIntervalMsnumberNoLog processor flush delay in milliseconds. Defaults to 100ms. Env override: OTEL_LOGS_FLUSH_INTERVAL_MS.
metricsEnabledbooleanNoWhether OpenTelemetry metrics export is enabled. Defaults to true. Set to false or OTEL_METRICS_ENABLED=false/0/no/off to disable.
metricsExportIntervalMsnumberNoMetrics export interval in milliseconds. Defaults to 60000 (60 seconds).
reconnectionConfigPartial<ReconnectionConfig>NoOptional reconnection configuration for the WebSocket connection.
serviceInstanceIdstringNoThe service instance ID to report. Defaults to SERVICE_INSTANCE_ID env var or auto-generated UUID.
serviceNamestringNoThe service name to report. Defaults to OTEL_SERVICE_NAME or “iii-node”.
serviceNamespacestringNoThe service namespace to report. Defaults to SERVICE_NAMESPACE env var.
serviceVersionstringNoThe service version to report. Defaults to SERVICE_VERSION env var or “unknown”.
spansFlushIntervalMsnumberNoSpan processor flush delay in milliseconds. Defaults to 100ms. This is how
long an ended span waits in the batch buffer before it is flushed to the
engine, the OpenTelemetry default of 5000ms is what makes traces appear
seconds after the action. Env override: OTEL_SPANS_FLUSH_INTERVAL_MS.

OtelLogEvent

OTEL Log Event from the engine
NameTypeRequiredDescription
attributesRecord<string, unknown>YesStructured attributes
bodystringYesLog message body
instrumentation_scope_namestringNoInstrumentation scope name (if available)
instrumentation_scope_versionstringNoInstrumentation scope version (if available)
observed_timestamp_unix_nanonumberYesObserved timestamp in Unix nanoseconds
resourceRecord<string, string>YesResource attributes from the emitting service
service_namestringYesService name that emitted the log
severity_numbernumberYesOTEL severity number (1-24): TRACE=1-4, DEBUG=5-8, INFO=9-12, WARN=13-16, ERROR=17-20, FATAL=21-24
severity_textstringYesSeverity text (e.g., “INFO”, “WARN”, “ERROR”)
span_idstringNoSpan ID for correlation (if available)
timestamp_unix_nanonumberYesTimestamp in Unix nanoseconds
trace_idstringNoTrace ID for correlation (if available)

ReconnectionConfig

Configuration for WebSocket reconnection behavior
NameTypeRequiredDescription
backoffMultipliernumberYesExponential backoff multiplier (default: 2)
initialDelayMsnumberYesStarting delay in milliseconds (default: 1000ms)
jitterFactornumberYesRandom jitter factor 0-1 (default: 0.3)
maxDelayMsnumberYesMaximum delay cap in milliseconds (default: 30000ms)
maxRetriesnumberYesMaximum retry attempts, -1 for infinite (default: -1)

TracedFetchInit

NameTypeRequiredDescription
tracerTracerNoTracer used to create the client span for the outgoing request.

WorkerGaugesOptions

NameTypeRequiredDescription
workerIdstringYesStable identifier of the worker the gauges are reported for.
workerNamestringNoHuman-readable name of the worker.

WorkerMetricsCollector

Collects worker resource metrics including CPU, memory, and event loop lag. Uses the Node.js monitorEventLoopDelay API for high-precision event loop delay measurements instead of manual setImmediate timing.

WorkerMetricsCollectorOptions

Configuration options for the WorkerMetricsCollector.
NameTypeRequiredDescription
eventLoopResolutionMsnumberNoEvent loop delay histogram resolution in milliseconds.
Lower values provide more accurate measurements but use more resources.

queue

Queue enqueue result types. Import

Types

EnqueueResult

EnqueueResult

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

stream

Stream trigger configs, change events, IO inputs, and update operations. Import

Types

MergePath · StreamAuthInput · StreamAuthResult · StreamChangeEvent · StreamChangeEventDetail · StreamContext · StreamDeleteInput · StreamDeleteResult · StreamGetInput · StreamJoinLeaveEvent · StreamJoinLeaveTriggerConfig · StreamJoinResult · StreamListGroupsInput · StreamListInput · StreamSetInput · StreamSetResult · StreamTriggerConfig · StreamUpdateInput · StreamUpdateResult · UpdateAppend · UpdateDecrement · UpdateIncrement · UpdateMerge · UpdateOp · UpdateOpError · UpdateRemove · UpdateSet

MergePath

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.

StreamAuthInput

Input for stream authentication.
NameTypeRequiredDescription
addrstringYesClient address.
headersRecord<string, string>YesRequest headers.
pathstringYesRequest path.
query_paramsRecord<string, string[]>YesQuery parameters.

StreamAuthResult

Result of stream authentication.
NameTypeRequiredDescription
contextanyNoArbitrary context passed to stream handlers after authentication.

StreamChangeEvent

Handler input for stream triggers, fired when an item changes via stream::set, stream::update, or stream::delete.
NameTypeRequiredDescription
eventStreamChangeEventDetailYesThe event detail containing mutation type and data.
groupIdstringYesThe group where the change occurred.
idstringNoThe item ID that changed.
streamNamestringYesThe stream where the change occurred.
timestampnumberYesUnix timestamp of the event.
type"stream"YesThe event type.

StreamChangeEventDetail

Detail of a stream change event containing the mutation type and data.
NameTypeRequiredDescription
dataanyYesThe data associated with the event.
type"create" | "update" | "delete"YesThe kind of mutation (create, update, or delete).

StreamContext

Context type extracted from StreamAuthResult.

StreamDeleteInput

Input for deleting a stream item.
NameTypeRequiredDescription
group_idstringYesGroup identifier.
item_idstringYesItem identifier.
stream_namestringYesName of the stream.

StreamDeleteResult

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

StreamGetInput

Input for retrieving a single stream item.
NameTypeRequiredDescription
group_idstringYesGroup identifier.
item_idstringYesItem identifier.
stream_namestringYesName of the stream.

StreamJoinLeaveEvent

Event payload for stream join/leave events.
NameTypeRequiredDescription
contextanyNoAuth context from StreamAuthResult.
group_idstringYesGroup identifier.
idstringNoItem identifier (if applicable).
stream_namestringYesName of the stream.
subscription_idstringYesUnique subscription identifier.

StreamJoinLeaveTriggerConfig

Trigger config for stream:join and stream:leave triggers.
NameTypeRequiredDescription
condition_function_idstringNoFunction ID for conditional execution. If it returns false, the handler is skipped.

StreamJoinResult

Result of a stream join request.
NameTypeRequiredDescription
unauthorizedbooleanYesWhether the join was unauthorized.

StreamListGroupsInput

Input for listing all groups in a stream.
NameTypeRequiredDescription
stream_namestringYesName of the stream.

StreamListInput

Input for listing all items in a stream group.
NameTypeRequiredDescription
group_idstringYesGroup identifier.
stream_namestringYesName of the stream.

StreamSetInput

Input for setting a stream item.
NameTypeRequiredDescription
dataanyYesData to store.
group_idstringYesGroup identifier.
item_idstringYesItem identifier.
stream_namestringYesName of the stream.

StreamSetResult

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

StreamTriggerConfig

Trigger config for stream triggers. Filters which item changes fire the handler.
NameTypeRequiredDescription
condition_function_idstringNoFunction ID for conditional execution. If it returns false, the handler is skipped.
group_idstringNoIf set, only changes within this group fire the handler.
item_idstringNoIf set, only changes to this specific item fire the handler.
stream_namestringYesStream name to watch. Only changes on this stream fire the handler.

StreamUpdateInput

Input for atomically updating a stream item.
NameTypeRequiredDescription
group_idstringYesGroup identifier.
item_idstringYesItem identifier.
opsUpdateOp[]YesOrdered list of update operations to apply atomically.
stream_namestringYesName of the stream.

StreamUpdateResult

Result of a stream update operation.
NameTypeRequiredDescription
errorsUpdateOpError[]NoPer-op errors. Emitted by merge and append for validation
rejections (path depth/size, value depth, or a
__proto__/constructor/prototype segment or top-level key)
and by append for the case-2 append.type_mismatch and
append.target_not_object surfaces. Successfully applied ops are
still reflected in new_value. The field is omitted from the
JSON wire when empty.
new_valueTDataYesNew value after the update.
old_valueTDataNoPrevious value (if it existed).

UpdateAppend

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). Engine semantics:
  • Missing or non-object intermediates along a nested path are auto-replaced with {} so a stray null or scalar never blocks future appends.
  • At the leaf:
    • missing/null + nested path → [value] (always an array)
    • missing/null + single-string path → string-as-string for the string-concat tier, otherwise [value]
    • existing array → push
    • existing string + string value → concatenate
    • existing object/scalar at the leaf → append.type_mismatch
  • Each path segment is a literal key. ["a.b"] targets a single key named "a.b", not a → b.
Validation: invalid paths (depth > 32 segments, segment > 256 bytes, or any __proto__/constructor/prototype segment) are rejected with a structured error in the errors field of the state::update / stream::update response. The append does not apply when an error is returned for that op.
NameTypeRequiredDescription
pathMergePathNoOptional path to the append target. Accepts a single first-level
key (legacy string) or an array of literal segments for nested
append. See MergePath (the same shape is reused).
type"append"Yes-
valueanyYesValue to append. String targets only accept string values.

UpdateDecrement

Decrement a numeric field by a given amount.
NameTypeRequiredDescription
bynumberYesAmount to decrement by.
pathstringYesFirst-level field path.
type"decrement"Yes-

UpdateIncrement

Increment a numeric field by a given amount.
NameTypeRequiredDescription
bynumberYesAmount to increment by.
pathstringYesFirst-level field path.
type"increment"Yes-

UpdateMerge

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. Engine semantics:
  • Missing or non-object intermediates along the path are auto-replaced with {} so a stray null or scalar never blocks future merges.
  • The merge is shallow at the target, top-level keys of value replace same-named keys; siblings are preserved.
  • Each path segment is a literal key. ["a.b"] writes a single key named "a.b", not a → b.
Validation: invalid paths/values (depth > 32 segments, 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 errors field of the state::update / stream::update response. The merge does not apply when an error is returned for that op.
NameTypeRequiredDescription
pathMergePathNoOptional path to the merge target. See MergePath.
type"merge"Yes-
valueanyYesObject to merge. Must be a JSON object.

UpdateOp

Union of all atomic update operations supported by streams.

UpdateOpError

Per-op error returned by state::update / stream::update.
NameTypeRequiredDescription
codestringYesStable error code, e.g. "merge.path.too_deep".
doc_urlstringNoOptional documentation URL.
messagestringYesHuman-readable description with concrete numbers when applicable.
op_indexnumberYesIndex of the offending op within the original ops array.

UpdateRemove

Remove a field at the given path.
NameTypeRequiredDescription
pathstringYesFirst-level field path.
type"remove"Yes-

UpdateSet

Set a field at the given path to a value.
NameTypeRequiredDescription
pathstringYesFirst-level field path. Use an empty string to target the root value.
type"set"Yes-
valueanyYesValue to set.

worker-connection-manager

RBAC auth and registration callback types. Import

Types

AuthInput · AuthResult · OnFunctionRegistrationInput · OnFunctionRegistrationResult · OnTriggerRegistrationInput · OnTriggerRegistrationResult · OnTriggerTypeRegistrationInput · OnTriggerTypeRegistrationResult

AuthInput

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.
NameTypeRequiredDescription
headersRecord<string, string>YesHTTP headers from the WebSocket upgrade request.
ip_addressstringYesIP address of the connecting client.
query_paramsRecord<string, string[]>YesQuery parameters from the upgrade URL. Each key maps to an array of values to support repeated keys.

AuthResult

Return value from the RBAC auth function. Controls which functions the authenticated worker can invoke and what context is forwarded to the middleware.
NameTypeRequiredDescription
allow_function_registrationbooleanNoWhether the worker may register new functions. Defaults to true if omitted.
allow_trigger_type_registrationbooleanNoWhether the worker may register new trigger types. Defaults to false if omitted.
allowed_functionsstring[]NoAdditional function IDs to allow beyond the expose_functions config. Defaults to [] if omitted.
allowed_trigger_typesstring[]NoTrigger type IDs the worker may register triggers for. When omitted, all types are allowed.
contextRecord<string, unknown>NoArbitrary context forwarded to the middleware function on every invocation. Defaults to {} if omitted.
forbidden_functionsstring[]NoFunction IDs to deny even if they match expose_functions. Takes precedence over allowed. Defaults to [] if omitted.
function_registration_prefixstringNoOptional prefix applied to all function IDs registered by this worker.

OnFunctionRegistrationInput

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.
NameTypeRequiredDescription
contextRecord<string, unknown>YesAuth context from AuthResult.context for this session.
descriptionstringNoHuman-readable description of the function.
function_idstringYesID of the function being registered.
metadataRecord<string, unknown>NoArbitrary metadata attached to the function.

OnFunctionRegistrationResult

Result returned from the on_function_registration_function_id hook. All fields are optional; omitted fields keep the original value from the registration request.
NameTypeRequiredDescription
descriptionstringNoMapped description.
function_idstringNoMapped function ID.
metadataRecord<string, unknown>NoMapped metadata.

OnTriggerRegistrationInput

Input passed to the on_trigger_registration_function_id hook when a worker attempts to register a trigger through the RBAC port. Return an OnTriggerRegistrationResult with the (possibly mapped) fields, or throw to deny the registration.
NameTypeRequiredDescription
configunknownYesTrigger-specific configuration.
contextRecord<string, unknown>YesAuth context from AuthResult.context for this session.
function_idstringYesID of the function this trigger is bound to.
metadataRecord<string, unknown>NoArbitrary metadata attached to the trigger.
trigger_idstringYesID of the trigger being registered.
trigger_typestringYesTrigger type identifier.

OnTriggerRegistrationResult

Result returned from the on_trigger_registration_function_id hook. All fields are optional; omitted fields keep the original value from the registration request.
NameTypeRequiredDescription
configunknownNoMapped trigger configuration.
function_idstringNoMapped function ID.
trigger_idstringNoMapped trigger ID.
trigger_typestringNoMapped trigger type.

OnTriggerTypeRegistrationInput

Input passed to the on_trigger_type_registration_function_id hook when a worker attempts to register a new trigger type through the RBAC port. Return an OnTriggerTypeRegistrationResult with the (possibly mapped) fields, or throw to deny the registration.
NameTypeRequiredDescription
contextRecord<string, unknown>YesAuth context from AuthResult.context for this session.
descriptionstringYesHuman-readable description of the trigger type.
trigger_type_idstringYesID of the trigger type being registered.

OnTriggerTypeRegistrationResult

Result returned from the on_trigger_type_registration_function_id hook. All fields are optional; omitted fields keep the original value from the registration request.
NameTypeRequiredDescription
descriptionstringNoMapped description.
trigger_type_idstringNoMapped trigger type ID.