Skip to content

@ottervoice/provider-utils

Documentation


Documentation / @ottervoice/provider-utils

Shared utilities for authors of OtterVoice providers, including client-safe credential brokers, HTTP error normalization, SSE parsing, and WebSocket ASR session helpers.

Terminal window
npm install @ottervoice/core @ottervoice/provider-utils
import {
createCredentialResolver,
normalizeHttpError,
parseSSEStream,
} from '@ottervoice/provider-utils';

Application code normally consumes one of the official provider packages instead of importing this package directly.

Documentation · GitHub

MIT

Defined in: websocket.ts:48

Result of decoding one vendor WebSocket text frame inside WebSocketASRConfig.decode. Omit fields that do not apply; return undefined from decode to skip the message entirely.

Property Type Description Defined in
error? NormalizedVoiceError Provider-reported or decode-time failure for this frame. websocket.ts:54
final? ASRResult Finalized transcript segment, if this frame ends an utterance. websocket.ts:52
partial? ASRResult Incremental (non-final) transcript, if this frame carries one. websocket.ts:50

Defined in: credential.ts:11

Body posted to CredentialOptions.tokenBrokerUrl.

Property Type Description Defined in
provider string Vendor id echoed to the broker (e.g. deepgram, openrouter). credential.ts:13
purpose CredentialPurpose Why the token is needed so the broker can scope permissions. credential.ts:15
sessionId? string Optional client session id for audit / rate limits. credential.ts:17

Defined in: credential.ts:24

Short-lived auth material returned by a token broker (or synthesized from CredentialOptions.apiKey). Use via createCredentialResolver.

Property Type Description Defined in
expiresAt? number Epoch millis after which the token must be refreshed. credential.ts:30
token string Bearer / API token used for upstream auth. credential.ts:28
url? string Optional signed URL (e.g. a websocket endpoint) returned by the broker. credential.ts:26

Defined in: credential.ts:38

Auth input for provider factories. Prefer CredentialOptions.tokenBrokerUrl on browsers and apps; reserve CredentialOptions.apiKey for trusted server-side runtimes only.

Property Type Description Defined in
apiKey? string A long-lived key (server-side only — never ship to clients). credential.ts:40
fetch? FetchLike Custom fetch implementation (tests / React Native polyfills). credential.ts:44
now? () => number Clock override for deterministic expiry checks in tests. credential.ts:46
tokenBrokerUrl? string Endpoint that mints short-lived tokens (client-safe). credential.ts:42

Defined in: http.ts:30

Options for normalizeHttpError. Use when mapping vendor HTTP failures into OtterVoice’s shared error shape.

Property Type Description Defined in
failureCode? VoiceErrorCode Code to use for ordinary 4xx failures (e.g. llm_failed, tts_failed). http.ts:34
provider? string Vendor id attached to the resulting NormalizedVoiceError. http.ts:32

Defined in: websocket.ts:62

Vendor-agnostic knobs for createWebSocketASRSession. Wire encodeAudio / decode to the specific ASR protocol; this config owns only the session plumbing.

Property Type Description Defined in
decode (data) => | ASRDecodeResult | undefined Decode a (text) server message into transcripts. Return undefined to skip. websocket.ts:70
encodeAudio (chunk) => string | ArrayBufferLike | ArrayBufferView<ArrayBufferLike> Encode an audio chunk into a WS payload. websocket.ts:68
finishMessage? string Optional message sent on stop() to flush the stream. websocket.ts:72
provider string Vendor id used in emitted NormalizedVoiceErrors. websocket.ts:66
ws WebSocketLike Open (or about-to-open) socket used for the ASR stream. websocket.ts:64

Defined in: websocket.ts:13

Minimal browser/Node WebSocket surface used by createWebSocketASRSession. Prefer the platform constructor via resolveWebSocket, or inject a mock in tests.

Property Type Description Defined in
binaryType? string Prefer 'arraybuffer' when the peer sends binary frames. websocket.ts:15
addEventListener(type, listener): void;

Defined in: websocket.ts:21

Subscribe to open / message / error / close (and peers).

Parameter Type
type string
listener (event) => void

void

close(code?, reason?): void;

Defined in: websocket.ts:19

Close the socket; optional close code and reason.

Parameter Type
code? number
reason? string

void

send(data): void;

Defined in: websocket.ts:17

Send a text or binary frame to the peer.

Parameter Type
data string | ArrayBufferLike | ArrayBufferView<ArrayBufferLike>

void

type CredentialPurpose = "asr" | "llm" | "tts" | "pronunciation";

Defined in: credential.ts:8

Why a short-lived credential is being minted. Sent as BrokerRequest.purpose so the broker can scope permissions.


type FetchLike = (input, init?) => Promise<Response>;

Defined in: http.ts:11

Minimal fetch-compatible callable. Inject a custom impl for tests or React Native polyfills; otherwise resolveFetch uses globalThis.fetch.

Parameter Type
input RequestInfo | URL
init? RequestInit

Promise<Response>


type WebSocketCtor = (url, protocols?) => WebSocketLike;

Defined in: websocket.ts:28

Constructible WebSocket type returning a WebSocketLike. Passed to resolveWebSocket when the runtime has no global WebSocket.

Parameter Type
url string
protocols? string | string[]

WebSocketLike

function createCredentialResolver(options, request): () => Promise<BrokerToken>;

Defined in: credential.ts:61

Returns a resolver that yields a usable BrokerToken. Prefers a static apiKey; otherwise calls the token broker and caches the result until just before it expires.

Parameter Type Description
options CredentialOptions Static key and/or broker URL.
request BrokerRequest Provider + purpose posted to the broker when minting.

Async function that resolves a fresh-enough BrokerToken.

() => Promise<BrokerToken>


function createWebSocketASRSession(config): ASRSession;

Defined in: websocket.ts:84

Build an ASRSession over a WebSocket. Audio sent before the socket opens is queued and flushed on open. Vendor specifics live entirely in encodeAudio/decode, keeping this plumbing reusable and testable.

Parameter Type Description
config WebSocketASRConfig Socket, provider id, and encode/decode hooks. See WebSocketASRConfig.

ASRSession

An ASRSession bound to the given socket.


function normalizeHttpError(
status,
body,
options?): NormalizedVoiceError;

Defined in: http.ts:46

Map an HTTP status + body into a NormalizedVoiceError, with sensible retryable/quota/rate-limit handling shared by every HTTP provider.

Parameter Type Description
status number HTTP status code from the failed response.
body string Response body text (may be empty).
options HttpErrorOptions Provider id and non-2xx / non-5xx failure code.

NormalizedVoiceError

A normalized error suitable for VoiceError or event emission.


function parseSSEStream(stream): AsyncGenerator<string>;

Defined in: sse.ts:9

Parse a Server-Sent-Events byte stream into successive data: payload strings. Comment lines (:), blank lines, and non-data: fields are skipped. Lines split across chunk boundaries are buffered.

Parameter Type Description
stream ReadableStream<Uint8Array<ArrayBufferLike>> Byte stream from Response.body (or a test fixture).

AsyncGenerator<string>

Async generator yielding trimmed data: field values.


function readBody(res): Promise<string>;

Defined in: http.ts:83

Read a response body as text, returning '' if the body cannot be read.

Parameter Type Description
res Response Fetch Response whose body to consume.

Promise<string>

Body text, or an empty string on read failure.


function resolveFetch(fetchImpl?): FetchLike;

Defined in: http.ts:22

Resolve the fetch implementation, preferring an injected one.

Parameter Type Description
fetchImpl? FetchLike Optional override; when omitted, uses globalThis.fetch.

FetchLike

A FetchLike ready for HTTP calls.


function resolveWebSocket(ctor?): WebSocketCtor;

Defined in: websocket.ts:39

Resolve the WebSocket constructor, preferring an injected one.

Parameter Type Description
ctor? WebSocketCtor Optional override for tests or non-browser runtimes.

WebSocketCtor

A WebSocketCtor ready to open sockets.


function streamFromStrings(chunks): ReadableStream<Uint8Array<ArrayBufferLike>>;

Defined in: sse.ts:46

Build a ReadableStream<Uint8Array> from string chunks (handy for tests).

Parameter Type Description
chunks string[] UTF-8 string fragments enqueued in order.

ReadableStream<Uint8Array<ArrayBufferLike>>

A readable byte stream suitable for parseSSEStream.