HTTP and streaming events
@ancrel/client-core uses the Fetch and Web Streams APIs available in Node 22+, browsers, and workers. Each stream is a lazy async iterable. Iteration starts the request. Breaking out of the loop releases its reader.
Read a snapshot and follow updates
The example reads a snapshot, then resumes a GET feed from the cursor in that snapshot. A trailing slash in baseUrl makes relative paths resolve inside that directory. A leading slash in a request path resolves from the origin.
Live example
Open playground ↗App.tsx
import { createHttpClient, subscribe, type HttpClientOptions } from '@ancrel/client-core'
// The snapshot and event feed share an opaque cursor. Resume immediately after the snapshot.
export default async function readUpdates(client: HttpClientOptions, signal?: AbortSignal) {
const snapshot = await createHttpClient(client).json<{ cursor: string; messages: string[] }>('snapshot', { signal })
const messages = [...snapshot.messages]
const frames = subscribe({
url: 'updates',
client,
signal,
cursor: snapshot.cursor,
commitCursor: 'on-dispatch',
onUnexpectedEof: 'error',
isTerminal: frame => frame.event === 'done',
})
for await (const frame of frames) {
if (frame.event === 'message') messages.push(frame.data)
}
return messages
}
Expected behavior
Resume from a snapshot
The snapshot returns the message Before and cursor 6. The GET subscription sends after=6 and Last-Event-ID: 6. The example appends After and stops at the done event. The result is ["Before", "After"].
An HTTP client can take a Fetch implementation and a headers object or factory. The client calls the factory for each request and awaits its result. Request headers override defaults case-insensitively. json<T>() returns undefined for a 204 or an empty body. text() reads plain text, unwraps JSON strings and objects with a string content field, and pretty-prints other JSON values.
An unsuccessful HTTP response throws HttpError. Use status for the HTTP status and code and details for structured error information. For an unparseable error body, rawBody preserves the server's text.
Decode or resume a feed
decodeSse(body, { signal }) yields frames with raw string data. Each data: line adds one line to the payload, including empty lines. Comments are ignored. The decoder retains the last valid ID across frames, clears it on an empty ID, and exposes a valid retry: value on its frame. The final data frame is delivered even when the transport ends without a blank line.
subscribe() sends the cursor in both the after query parameter and the Last-Event-ID header. Choose when an observed ID becomes the cursor for the next connection.
on-id(default) commits as soon as a complete ID line arrives. A disconnect during the remaining lines can therefore advance beyond an unfinished event.on-dispatchcommits when a complete data frame is dispatched. A disconnect during an event resumes from the last dispatched frame.
A terminal predicate sees every dispatched frame. When it returns true, the terminal frame is the final value. For a clean EOF without a terminal frame, onUnexpectedEof accepts close (default), reconnect, or error. The error policy throws an HttpError with code UNEXPECTED_EOF.
Failed connections and interrupted GET reads retry after 1200 ms by default. Each consecutive failure multiplies the delay by 1.8 up to 10000 ms. A successful connection resets the delay. The backoff option accepts initialMs, factor, maxMs, and fractional jitter. Jitter defaults to zero. The reconnect schedule uses these settings. Passing an AbortSignal stops reads and pending retries.
Stream a command result
import { postStream } from '@ancrel/client-core'
for await (const frame of postStream('commands', { text: 'Hello' }, {
client: { baseUrl: 'https://example.test/api/' },
signal,
isDone: frame => frame.event === 'complete',
})) {
consume(frame.data)
}
postStream() submits JSON once and requests an event stream. Its default completion predicate recognizes SSE events named done or interrupted. Supply isDone when the server encodes completion in the payload. An EOF before completion throws HttpError with code UNEXPECTED_EOF and the response status.
Migration from a POST 404 fallback
The previous application retried a missing streaming endpoint with a separate ordinary POST. Here a 404 reaches the caller as an HttpError. Automatic redirects are disabled for command requests to prevent resubmission. Applications supporting older servers can select an endpoint before sending or use their own idempotency protocol to handle an ambiguous submission.
Exports
createHttpClientHttpErrordecodeSsesubscribepostStreamHttpClientHttpClientOptionsSseFrameSubscribeOptionsPostStreamOptions
Constraints
- Supply a completion predicate for application-specific terminal frames.
- Choose the GET cursor commit and unexpected EOF policies to match the server protocol.
- Use a Fetch-compatible runtime with Web Streams and UTF-8 decoding.
Anti-patterns
- Replaying a POST after a lost connection without an application-level idempotency guarantee.
- Parsing every SSE payload as JSON before inspecting the event type.