Example 1
Example 1
import { SsePlugin } from '@setu-ts/sse-plugin'; import { CAPABILITIES, ISseService } from '@setu-ts/common'; const app = createApplication(); app.register(SsePlugin({ heartbeatMs: 15000, retryMs: 3000 })); await app.start({ port: 3000 }); app.router.get('/events', async (ctx) => { const sse = ctx.services.get<ISseService>(CAPABILITIES.SSE); const conn = sse.open(ctx); conn.send({ id: '1', data: 'hello world' }); return conn.result; });
Implements IConn.
-
close(): void
Close the connection (idempotent).
-
comment(text: string): void
Enqueue a plain-text comment frame.
-
id: string
Unique connection ID.
-
isOpen(): boolean
Whether this connection is still open.
-
lastEventId: string | null
The client's
Last-Event-IDheader value, if present. -
result: HandlerResult
The
HandlerResultobtained fromctx.response.stream()— set in constructor. -
send(msg: SseMessage): void
Enqueue an encoded SSE message.
Implements IService.
-
channel(name: string): SseChannel
Return or create a named channel.
-
channelCount(): number
Number of channels the registry currently holds.
-
closeAll(): void
Close all live connections (used during shutdown).
-
connectionCount(): number
Current number of open connections.
-
deliverRemoteFrame(frame: RealtimeFrame): void
Delivers a message that arrived from another replica to this replica's local channel members.
-
open(ctx: IRequestContext): ISseConnection
Open a new SSE connection for the given request context.
-
peek(name: string): SseChannel | undefined
Return the named channel if it already exists, without creating it.
Creates the SsePlugin.
A live SSE connection backed by a ReadableStream.
-
close(): void
Closes the connection: clears the heartbeat, closes the stream controller, and marks the connection as closed. Idempotent.
-
comment(text: string): void
Enqueues a plain-text comment frame (
: <text>\n\n) — commonly used as a keep-alive heartbeat. -
id: string
Unique connection ID.
-
isOpen: boolean
Whether this connection is still open.
-
lastEventId: string | null
The client's
Last-Event-IDheader value, if present. -
result: HandlerResult
The
HandlerResultobtained fromctx.response.stream(). The handler returns this value so the kernel maps it to the correct web response. -
send(msg: SseMessage): void
Enqueues an encoded SSE frame for the connected client.
Service contract for the SSE hub — registered by the SsePlugin under
CAPABILITIES.SSE.
-
channel(name: string): SseChannel
Returns or creates a named channel.
-
channelCount: number
Number of channels the registry currently holds.
-
connectionCount: number
Current number of open connections.
-
open(ctx: IRequestContext): ISseConnection
Opens a new SSE connection for the given request context.
-
peek(name: string): SseChannel | undefined
Returns the named channel if one already exists, without creating it.
A named broadcast channel within the SSE hub.
-
add(conn: ISseConnection): void
Adds a connection to this channel's membership.
-
publish(msg: SseMessage): void
Publishes a message to every open member of this channel, skipping any connection whose
ISseConnection.isOpenisfalse. -
remove(conn: ISseConnection): void
Removes a connection from this channel's membership.
-
size: number
Number of currently open connections in this channel.
A single SSE event payload.
-
data: JsonValue
Event data. A
stringis written literally (split on\ninto multipledata:lines); any non-string isJSON.stringify-ed.undefinedis forbidden — use{}or omit the message instead. -
event: string
Event type name — sent as
event:field. -
id: string
Unique event identifier — sent as
id:field; enablesLast-Event-IDresume. -
retry: number
Reconnection time in milliseconds — sent as
retry:field.
Options for the SsePlugin.
-
heartbeatMs: number
Heartbeat interval in milliseconds. When set, the plugin schedules a repeating
: heartbeat\n\ncomment frame. Omit to disable (no timer created). -
retryMs: number
Reconnection time in milliseconds. When set, the first bytes on every new stream are
retry: <ms>advertising the reconnect delay. Omit to send noretry:field. -
scalingNotice: boolean
Whether to log one
infoline at registration when no realtime backplane is registered, stating that channels broadcast in-process only. Defaults totrue.
Forwards a local publish to peers on other replicas.
Standard capability tokens provided by the first-party plugins.
-
AUDIT: string
Audit trail logging.
-
AUTH: string
Authentication service.
-
AUTHORIZATION: string
Authorization service (RBAC, permissions).
-
CACHE: string
Key/value caching.
-
CLI_COMMAND: string
CLI command contributions (multi-provider).
-
CLOUDFLARE: string
Cloudflare Workers platform bindings (KV, R2, D1, Queues, service and Durable Object namespaces) published as one typed accessor.
-
COMMAND_BUS: string
Command bus (CQRS).
-
CONFIG: string
Configuration access.
-
CQRS: string
CQRS facade.
-
DATABASE: string
Database access (repositories, unit of work).
-
DECORATOR_HANDLER: string
Decorator handler contributions (multi-provider).
-
DI_CONTAINER: string
Optional dependency injection container.
-
EVENTS: string
In-memory domain event bus.
-
FEATURE_FLAGS: string
Feature flag evaluation.
-
GRAPHQL: string
GraphQL plugin — schema-first and code-first GraphQL-over-HTTP.
-
GRPC: string
gRPC plugin — server-side Connect/gRPC/gRPC-Web co-serving.
-
HEALTH: string
Health checks.
-
HEALTH_INDICATOR: string
Health indicator contributions (multi-provider).
-
HTTP_ADAPTER: string
HTTP server adapter — the runtime plugin registers its IHttpAdapter here.
-
JWT: string
JWT sign/verify service.
-
LOGGER: string
Structured logger.
-
MAIL: string
Email sending.
-
MESSAGING: string
Message broker for integration events.
-
METADATA_STORE: string
Decorator metadata store (from the DecoratorPlugin, when registered).
-
METRICS: string
Metrics collection.
-
METRIC_REGISTRATION: string
Metric registration contributions (multi-provider).
-
MULTI_TENANCY: string
Multi-tenancy service.
-
NOTIFICATION: string
Multi-channel notifications.
-
OPENAPI: string
OpenAPI spec contribution and generation.
-
OPENAPI_SCHEMA: string
OpenAPI schema contributions (multi-provider).
-
QUERY_BUS: string
Query bus (CQRS).
-
QUEUE: string
Background job queue.
-
REALTIME_BACKPLANE: string
Pub/sub transport carrying real-time broadcasts between application instances, so WebSocket rooms and SSE channels fan out across replicas. Consumed optionally — absent means purely in-process broadcasting.
-
RESILIENCE: string
Resilience patterns (circuit breaker, retry, timeout, bulkhead).
-
RUNTIME: string
Runtime services provided by the RuntimePlugin. Mandatory in every application.
-
SCHEDULER: string
Job scheduling (cron, delayed, recurring).
-
SECRETS: string
Secret management.
-
SERVICE_DISCOVERY: string
Service discovery — logical service name to reachable instances.
-
SESSION: string
Cookie-backed sessions for server-rendered applications.
-
SSE: string
Server-Sent Events (SSE) hub for in-process real-time broadcasting.
-
SSR: string
Server-side rendering (SSR) — React Router or similar framework.
-
STATIC_FILES: string
Static file serving plugin.
-
STORAGE: string
File storage.
-
TELEMETRY: string
Distributed tracing.
-
VALIDATION: string
Request/data validation.
-
VIEW: string
View rendering (server-rendered HTML) — an
IViewEnginethat turns a view component and its props into an HTML string, so a handler can answer with markup it did not concatenate by hand. -
WEBSOCKET: string
WebSocket hub for bidirectional real-time messaging.
-
WORKER_POOL: string
Worker-thread pool for CPU-bound tasks.
Usage
import * as Server_Sent_Events__SSE__plugin_for_real_time__one_way_server_to_client_messaging_over__text_event_stream___Built_on_the_Milestone_42_streaming_primitive___IResponse_stream_______IRequestContext_signal____ from "sse-plugin/src/index.ts";