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

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.

HttpResponse

Structured buffered HTTP response returned from function handlers.

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.

OtelLogEvent

OTEL Log Event from the engine

ReconnectionConfig

Configuration for WebSocket reconnection behavior

TracedFetchInit


WorkerGaugesOptions


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.

queue

Queue enqueue result types. Import

Types

EnqueueResult

EnqueueResult

Result returned when a function is invoked with TriggerAction.Enqueue.

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.

StreamAuthResult

Result of stream authentication.

StreamChangeEvent

Handler input for stream triggers, fired when an item changes via stream::set, stream::update, or stream::delete.

StreamChangeEventDetail

Detail of a stream change event containing the mutation type and data.

StreamContext

Context type extracted from StreamAuthResult.

StreamDeleteInput

Input for deleting a stream item.

StreamDeleteResult

Result of a stream delete operation.

StreamGetInput

Input for retrieving a single stream item.

StreamJoinLeaveEvent

Event payload for stream join/leave events.

StreamJoinLeaveTriggerConfig

Trigger config for stream:join and stream:leave triggers.

StreamJoinResult

Result of a stream join request.

StreamListGroupsInput

Input for listing all groups in a stream.

StreamListInput

Input for listing all items in a stream group.

StreamSetInput

Input for setting a stream item.

StreamSetResult

Result of a stream set operation.

StreamTriggerConfig

Trigger config for stream triggers. Filters which item changes fire the handler.

StreamUpdateInput

Input for atomically updating a stream item.

StreamUpdateResult

Result of a stream update operation.

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.

UpdateDecrement

Decrement a numeric field by a given amount.

UpdateIncrement

Increment a numeric field by a given amount.

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.

UpdateOp

Union of all atomic update operations supported by streams.

UpdateOpError

Per-op error returned by state::update / stream::update.

UpdateRemove

Remove a field at the given path.

UpdateSet

Set a field at the given path to a value.

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.

AuthResult

Return value from the RBAC auth function. Controls which functions the authenticated worker can invoke and what context is forwarded to the middleware.

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.

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.

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.

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.

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.

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.