Helpers (Node.js)

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

Link to this sectionInstallation

Terminal
npm install @iii-dev/helpers

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

Link to this sectionhttp

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

Import

import { ... } from '@iii-dev/helpers/http'

Link to this sectionFunctions

Link to this sectionhttp

Helper that wraps an HTTP-style handler (with separate req/res arguments) into the function handler format expected by the SDK. res.status() and res.headers() send the set_status / set_headers messages the HTTP worker reads; the body goes through res.write() or res.stream. The SDK closes a response the handler used when it returns, and aborts it when it throws; return an HttpResponse instead for a buffered response.

Signature

http(callback: (req: HttpStreamingRequest, res: HttpStreamingResponse) => Promise<void | HttpResponse<number, string | Buffer<ArrayBufferLike> | Record<string, unknown>>>) => (req: HttpInternalRequest) => Promise<void | HttpResponse<number, string | Buffer<ArrayBufferLike> | Record<string, unknown>>>
callback(req: HttpStreamingRequest, res: HttpStreamingResponse) => Promise<void | HttpResponse<number, string | Buffer<ArrayBufferLike> | Record<string, unknown>>>required

Async handler receiving a streaming request and response.

Link to this sectionTypes

HttpAuthConfig · HttpMethod · HttpRequest · HttpResponse

Link to this sectionHttpAuthConfig

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.
type HttpAuthConfig = { secret_key: string; type: "hmac" } | { token_key: string; type: "bearer" } | { header: string; type: "api_key"; value_key: string }

Link to this sectionHttpMethod

HTTP method accepted by HttpInvocationConfig. Distinct from the methods an http::on-request route takes, which also cover HEAD/OPTIONS.

type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"

Link to this sectionHttpRequest

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_bodyHttpInputStreamYesThe raw request body, as an InputStream of iii-sdk: read it, or pass it on unread.

Link to this sectionHttpResponse

Structured buffered HTTP response returned from function handlers.

NameTypeRequiredDescription
bodyTBodyNoResponse body.
headersRecord<string, string>NoResponse headers.
status_codeTStatusYesHTTP status code.

Link to this sectionobservability

Logger, OpenTelemetry config, and span helpers.

Import

import { ... } from '@iii-dev/helpers/observability'

Link to this sectionFunctions

Link to this sectioncurrentSpanId

Extract the current span ID from the active span context.

Signature

currentSpanId() => string | undefined

Link to this sectioncurrentSpanIsRecording

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

Signature

currentSpanIsRecording() => boolean

Link to this sectioncurrentTraceId

Extract the current trace ID from the active span context.

Signature

currentTraceId() => string | undefined

Link to this sectionexecuteTracedRequest

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

executeTracedRequest(input: RequestInfo | URL, init?: TracedFetchInit) => Promise<Response>

Link to this sectionParameters

inputRequestInfo | URLrequired

The resource to fetch: a URL string, URL, or Request.

initTracedFetchInit

Fetch options, plus an optional tracer to create the span.


Link to this sectionextractBaggage

Extract baggage from a W3C baggage header string.

Signature

extractBaggage(baggage: string) => Context

Link to this sectionParameters

baggagestringrequired

W3C baggage header value to parse.


Link to this sectionextractContext

Extract both trace context and baggage from their respective headers.

Signature

extractContext(traceparent?: string, baggage?: string) => Context

Link to this sectionParameters

traceparentstring

W3C traceparent header value to parse.

baggagestring

W3C baggage header value to parse.


Link to this sectionextractTraceparent

Extract a trace context from a W3C traceparent header string.

Signature

extractTraceparent(traceparent: string) => Context

Link to this sectionParameters

traceparentstringrequired

W3C traceparent header value to parse.


Link to this sectionflushOtel

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

flushOtel() => Promise<void>

Link to this sectiongetAllBaggage

Get all baggage entries from the current context.

Signature

getAllBaggage() => Record<string, string>

Link to this sectiongetBaggageEntry

Get a baggage entry from the current context.

Signature

getBaggageEntry(key: string) => string | undefined

Link to this sectionParameters

keystringrequired

Baggage entry key to read.


Link to this sectiongetLogger

Get the OpenTelemetry logger instance.

Signature

getLogger() => Logger | null

Link to this sectioninitOtel

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

Signature

initOtel(config: OtelConfig) => void

Link to this sectionParameters

configOtelConfigrequired

OpenTelemetry configuration; env vars fill in unset fields.


Link to this sectioninjectBaggage

Inject the current baggage into a W3C baggage header string.

Signature

injectBaggage() => string | undefined

Link to this sectioninjectTraceparent

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

Signature

injectTraceparent() => string | undefined

Link to this sectionpatchGlobalFetch

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

Signature

patchGlobalFetch(tracer: Tracer) => void

Link to this sectionParameters

tracerTracerrequired

Tracer used to create the client span for each request.


Link to this sectionrecordSpanEvent

No-op when the current span is not recording.

Signature

recordSpanEvent(name: string, attrs?: Attributes) => void

Link to this sectionParameters

namestringrequired

Name of the event to add to the active span.

attrsAttributes

Optional attributes to attach to the event.


Link to this sectionredact

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

Signature

redact(value: unknown) => unknown

Link to this sectionParameters

valueunknownrequired

The value to recursively redact.


Link to this sectionredactAndTruncate

Redact then serialize to JSON, optionally capped at maxBytes.

Signature

redactAndTruncate(value: unknown, maxBytes: number | null) => { json: string; truncated: boolean }

Link to this sectionParameters

valueunknownrequired

The value to redact and serialize.

maxBytesnumber | nullrequired

Maximum serialized size in bytes; null leaves it uncapped.


Link to this sectionregisterWorkerGauges

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

Signature

registerWorkerGauges(meter: Meter, options: WorkerGaugesOptions) => void

Link to this sectionParameters

meterMeterrequired
optionsWorkerGaugesOptionsrequired

Link to this sectionremoveBaggageEntry

Remove a baggage entry from the current context.

Signature

removeBaggageEntry(key: string) => Context

Link to this sectionParameters

keystringrequired

Baggage entry key to remove.


Link to this sectionresolveMaxBytesFromEnv

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

Signature

resolveMaxBytesFromEnv() => number | null

Link to this sectionsafeStringify

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

Signature

safeStringify(value: unknown) => string

Link to this sectionParameters

valueunknownrequired

The value to serialize to JSON.


Link to this sectionsetBaggageEntry

Set a baggage entry in the current context.

Signature

setBaggageEntry(key: string, value: string) => Context

Link to this sectionParameters

keystringrequired

Baggage entry key to set.

valuestringrequired

Baggage entry value to set.


Link to this sectionsetCurrentSpanAttribute

No-op when the current span is not recording.

Signature

setCurrentSpanAttribute(key: string, value: AttributeValue) => void

Link to this sectionParameters

keystringrequired

Attribute key to set on the active span.

valueAttributeValuerequired

Attribute value to set.


Link to this sectionsetCurrentSpanError

No-op when there is no active span.

Signature

setCurrentSpanError(message: string) => void

Link to this sectionParameters

messagestringrequired

Error message to set as the span's error status.


Link to this sectionshutdownOtel

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

Signature

shutdownOtel() => Promise<void>

Link to this sectionstopWorkerGauges

Stop and unregister the worker resource gauges.

Signature

stopWorkerGauges() => void

Link to this sectionunpatchGlobalFetch

Restore globalThis.fetch to its original implementation.

Signature

unpatchGlobalFetch() => void

Link to this sectionwithSpan

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

Signature

withSpan(name: string, options: { kind?: SpanKind; traceparent?: string }, fn: (span: Span) => Promise<T>) => Promise<T>

Link to this sectionParameters

namestringrequired

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.

Link to this sectionTypes

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

Link to this sectionBaggageSpanProcessor

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


Link to this sectionLogger

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.


Link to this sectionOtelConfig

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.
engineWsHeadersRecord<string, string>NoHTTP headers sent on the telemetry WebSocket handshake (e.g. Authorization).
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.

Link to this sectionOtelLogEvent

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)

Link to this sectionReconnectionConfig

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)

Link to this sectionTracedFetchInit

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

Link to this sectionWorkerGaugesOptions

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

Link to this sectionWorkerMetricsCollector

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.


Link to this sectionWorkerMetricsCollectorOptions

Configuration options for the WorkerMetricsCollector.

NameTypeRequiredDescription
eventLoopResolutionMsnumberNoEvent loop delay histogram resolution in milliseconds.
Lower values provide more accurate measurements but use more resources.

Link to this sectionqueue

Queue enqueue result types.

Import

import { ... } from '@iii-dev/helpers/queue'

Link to this sectionTypes

EnqueueResult

Link to this sectionEnqueueResult

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

NameTypeRequiredDescription
messageReceiptIdstringYesUnique receipt ID for the enqueued message.

Link to this sectionstream

Stream change events, IO inputs, and update operations.

Import

import { ... } from '@iii-dev/helpers/stream'

Link to this sectionTypes

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).

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.

Link to this sectionUpdateDecrement

Decrement a numeric field by a given amount.

NameTypeRequiredDescription
bynumberYesAmount to decrement by.
pathstringYesFirst-level field path.
type"decrement"Yes-

Link to this sectionUpdateIncrement

Increment a numeric field by a given amount.

NameTypeRequiredDescription
bynumberYesAmount to increment by.
pathstringYesFirst-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.

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.

Link to this sectionUpdateOp

Union of all atomic update operations supported by streams.

type UpdateOp = UpdateSet | UpdateIncrement | UpdateDecrement | UpdateAppend | UpdateRemove | UpdateMerge

Link to this sectionUpdateOpError

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.

Link to this sectionUpdateRemove

Remove a field at the given path.

NameTypeRequiredDescription
pathstringYesFirst-level field path.
type"remove"Yes-

Link to this sectionUpdateSet

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.

Link to this sectionworker-connection-manager

RBAC auth and registration callback types.

Import

import { ... } from '@iii-dev/helpers/worker-connection-manager'

Link to this sectionTypes

AuthInput · AuthResult · OnFunctionRegistrationInput · OnFunctionRegistrationResult

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.

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.

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.

NameTypeRequiredDescription
allow_function_registrationbooleanNoWhether the worker may register new functions. Defaults to true if omitted.
allowed_functionsstring[]NoAdditional function IDs to allow beyond the expose_functions config, in the default namespace only. Put per-namespace grants in namespaces. Defaults to [] if omitted.
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.
namespacesRecord<string, string[]>NoGrants scoped to one namespace each: { orders: ['svc::*'] }. A value is an
exact function ID or a wildcard, in either the bare (svc::*) or the
match("svc::*") spelling.

The keys are also the namespaces the session may declare on
engine::workers::register. Omit this map to add no namespace-scoped
grants: the session may declare any namespace, and only
allowed_functions and expose_functions apply.

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.

NameTypeRequiredDescription
args_formatRecord<string, unknown>NoJSON Schema of the args its observers pass; sent when the registration sets it.
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.
namespacestringNoNamespace the function registers in. The same id can exist in several
namespaces, so the hook needs this to authorize per namespace.
observablebooleanYesfalse: nobody may observe the function; always sent.
privatebooleanYesOnly 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.

NameTypeRequiredDescription
args_formatRecord<string, unknown>NoReplaces the registration's args_format.
descriptionstringNoMapped description.
function_idstringNoMapped function ID.
metadataRecord<string, unknown>NoMapped metadata.
observablebooleanNoReplaces the registration's observable.
privatebooleanNoReplaces the registration's private.