@kyneta/sse-transport 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -116,7 +116,9 @@ const exchange = new Exchange({
116
116
 
117
117
  ## Connection Lifecycle
118
118
 
119
- The client adapter manages connection state through a validated state machine. Unlike the WebSocket adapter, SSE has no separate "ready" signal — the connection is usable as soon as `EventSource.onopen` fires.
119
+ The client connection lifecycle is a `Program<SseClientMsg, SseClientState, SseClientEffect>` from `@kyneta/machine` — a pure Mealy machine with data effects. Unlike the WebSocket adapter, SSE has no separate "ready" signal — the connection is usable as soon as `EventSource.onopen` fires, giving a 4-state lifecycle.
120
+
121
+ The `SseClientTransport` class is a thin imperative shell that interprets data effects as I/O (FC/IS design). The program itself is deterministically testable — every state × event combination is covered by pure data tests (no `EventSource`, no timing, never flaky).
120
122
 
121
123
  ```/dev/null/state-machine.txt#L1-7
122
124
  disconnected → connecting → connected
@@ -142,12 +144,18 @@ disconnected → connecting → connected
142
144
  3. Client creates its channel, calls `establishChannel()`
143
145
  4. Synchronizer exchanges `establish-request` / `establish-response`
144
146
 
145
- ### EventSource Reconnection
147
+ ### EventSource Error Handling
148
+
149
+ On `EventSource.onerror`, the program produces a `close-event-source` effect and transitions to `reconnecting` (or `disconnected` if retries are exhausted). The imperative shell **closes the EventSource immediately**, preventing the browser's built-in `EventSource` reconnection from running. This gives the program full control over backoff timing and attempt counting — reconnect delays are computed purely as data effects (`start-reconnect-timer`).
146
150
 
147
- On `EventSource.onerror`, the adapter **closes the EventSource immediately** and takes over reconnection via the state machine's backoff logic. This prevents the browser's built-in `EventSource` reconnection from running, giving full control over backoff timing and attempt counting.
151
+ ### POST Retry
152
+
153
+ Client→server messages are sent via HTTP POST. POST failures (network errors, non-2xx responses) are retried with exponential backoff at the transport level — this is an imperative-shell concern, not part of the connection lifecycle program.
148
154
 
149
155
  ### Observing State
150
156
 
157
+ The public observation API is powered by `createObservableProgram` from `@kyneta/machine`:
158
+
151
159
  ```/dev/null/observe-state.ts#L1-18
152
160
  import { createSseClient } from "@kyneta/sse-network-adapter/client"
153
161
 
@@ -119,7 +119,7 @@ var SseConnection = class {
119
119
  };
120
120
 
121
121
  // src/server-transport.ts
122
- import { Transport } from "@kyneta/exchange";
122
+ import { Transport } from "@kyneta/transport";
123
123
  function generatePeerId() {
124
124
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
125
125
  let result = "sse-";
@@ -252,4 +252,4 @@ export {
252
252
  SseConnection,
253
253
  SseServerTransport
254
254
  };
255
- //# sourceMappingURL=chunk-TR4Y3HFB.js.map
255
+ //# sourceMappingURL=chunk-ZBE5AMNA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/connection.ts","../src/server-transport.ts"],"sourcesContent":["// connection — SseConnection for server-side peer connections.\n//\n// Wraps a TextReassembler + textCodec to provide send/receive for\n// ChannelMsg over a single SSE connection.\n//\n// Used by SseServerTransport to manage individual client connections.\n// The client adapter handles its own encoding/decoding inline since it\n// manages a single EventSource with reconnection logic.\n//\n// The sendFn receives pre-encoded text frame strings. Framework\n// integrations just wrap them in SSE syntax:\n// Express: res.write(`data: ${textFrame}\\n\\n`)\n// Hono: stream.writeSSE({ data: textFrame })\n\nimport type { Channel, ChannelMsg, PeerId } from \"@kyneta/transport\"\nimport {\n encodeTextComplete,\n fragmentTextPayload,\n TextReassembler,\n textCodec,\n} from \"@kyneta/wire\"\n\n/**\n * Default fragment threshold in characters for outbound SSE messages.\n * 60K chars provides a safety margin below typical infrastructure limits.\n */\nexport const DEFAULT_FRAGMENT_THRESHOLD = 60_000\n\n/**\n * Configuration for creating an SseConnection.\n */\nexport interface SseConnectionConfig {\n /**\n * Fragment threshold in characters. Messages larger than this are fragmented.\n * Set to 0 to disable fragmentation.\n * Default: 60000 (60K chars)\n */\n fragmentThreshold?: number\n}\n\n/**\n * Represents a single SSE connection to a peer (server-side).\n *\n * Manages encoding, framing, fragmentation, and reassembly for one\n * connected client. Created by `SseServerTransport.registerConnection()`.\n *\n * The connection uses the text codec for transport — this is the natural\n * choice for SSE's text-only protocol.\n */\nexport class SseConnection {\n readonly peerId: PeerId\n readonly channelId: number\n\n #channel: Channel | null = null\n #sendFn: ((textFrame: string) => void) | null = null\n #onDisconnect: (() => void) | null = null\n\n // Fragmentation support\n readonly #fragmentThreshold: number\n\n /**\n * Text reassembler for handling fragmented POST bodies.\n * Each connection has its own reassembler to track in-flight fragment batches.\n */\n readonly reassembler: TextReassembler\n\n constructor(peerId: PeerId, channelId: number, config?: SseConnectionConfig) {\n this.peerId = peerId\n this.channelId = channelId\n this.#fragmentThreshold =\n config?.fragmentThreshold ?? DEFAULT_FRAGMENT_THRESHOLD\n this.reassembler = new TextReassembler({\n timeoutMs: 10_000,\n onTimeout: (frameId: string) => {\n console.warn(\n `[SseConnection] Fragment batch timed out for peer ${peerId}: ${frameId}`,\n )\n },\n })\n }\n\n // ==========================================================================\n // INTERNAL API — for adapter use\n // ==========================================================================\n\n /**\n * Set the channel reference.\n * Called by the adapter when the channel is created.\n * @internal\n */\n _setChannel(channel: Channel): void {\n this.#channel = channel\n }\n\n // ==========================================================================\n // PUBLIC API\n // ==========================================================================\n\n /**\n * Set the function to call when sending messages to this peer.\n *\n * The function receives a fully encoded text frame string.\n * The framework integration just wraps it in SSE syntax:\n * - Express: `res.write(\\`data: \\${textFrame}\\\\n\\\\n\\`)`\n * - Hono: `stream.writeSSE({ data: textFrame })`\n *\n * @param sendFn Function that writes a text frame string to the SSE stream\n */\n setSendFunction(sendFn: (textFrame: string) => void): void {\n this.#sendFn = sendFn\n }\n\n /**\n * Set the function to call when this connection is disconnected.\n */\n setDisconnectHandler(handler: () => void): void {\n this.#onDisconnect = handler\n }\n\n /**\n * Send a ChannelMsg to the peer through the SSE stream.\n *\n * Encodes via textCodec → text frame → fragment if needed → sendFn().\n * Encoding and fragmentation are the connection's concern — the\n * framework integration only needs to write strings.\n */\n send(msg: ChannelMsg): void {\n if (!this.#sendFn) {\n throw new Error(\n `Cannot send message: send function not set for peer ${this.peerId}`,\n )\n }\n\n // Encode to text wire format\n const textFrame = encodeTextComplete(textCodec, msg)\n\n // Fragment large payloads\n if (\n this.#fragmentThreshold > 0 &&\n textFrame.length > this.#fragmentThreshold\n ) {\n const payload = JSON.stringify(textCodec.encode(msg))\n const fragments = fragmentTextPayload(payload, this.#fragmentThreshold)\n for (const fragment of fragments) {\n this.#sendFn(fragment)\n }\n } else {\n this.#sendFn(textFrame)\n }\n }\n\n /**\n * Receive a message from the peer and route it to the channel.\n *\n * Called by the framework integration after parsing a POST body\n * through `parseTextPostBody`.\n */\n receive(msg: ChannelMsg): void {\n if (!this.#channel) {\n throw new Error(\n `Cannot receive message: channel not set for peer ${this.peerId}`,\n )\n }\n this.#channel.onReceive(msg)\n }\n\n /**\n * Disconnect this connection.\n */\n disconnect(): void {\n this.#onDisconnect?.()\n }\n\n /**\n * Dispose of resources held by this connection.\n * Must be called when the connection is closed to prevent timer leaks.\n */\n dispose(): void {\n this.reassembler.dispose()\n }\n}\n","// server-adapter — SSE server adapter for @kyneta/exchange.\n//\n// Manages SSE connections from clients, encoding/decoding via the\n// kyneta text wire format. Framework-agnostic — works with any HTTP\n// framework through the SseConnection's setSendFunction() callback.\n//\n// Usage with Express:\n// import { SseServerTransport } from \"@kyneta/sse-network-adapter/server\"\n// import { createSseExpressRouter } from \"@kyneta/sse-network-adapter/express\"\n//\n// const serverAdapter = new SseServerTransport()\n// app.use(\"/sse\", createSseExpressRouter(serverAdapter))\n//\n// Usage with Hono:\n// import { SseServerTransport } from \"@kyneta/sse-network-adapter/server\"\n// import { parseTextPostBody } from \"@kyneta/sse-network-adapter/express\"\n//\n// const serverAdapter = new SseServerTransport()\n// // Wire up GET /events and POST /sync manually using\n// // serverAdapter.registerConnection() and parseTextPostBody()\n\nimport type { ChannelMsg, GeneratedChannel, PeerId } from \"@kyneta/transport\"\nimport { Transport } from \"@kyneta/transport\"\nimport { DEFAULT_FRAGMENT_THRESHOLD, SseConnection } from \"./connection.js\"\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Options for the SSE server adapter.\n */\nexport interface SseServerTransportOptions {\n /**\n * Fragment threshold in characters. Messages larger than this are fragmented\n * into multiple SSE events.\n * Set to 0 to disable fragmentation.\n * Default: 60000 (60K chars)\n */\n fragmentThreshold?: number\n}\n\n// ---------------------------------------------------------------------------\n// Peer ID generation\n// ---------------------------------------------------------------------------\n\n/**\n * Generate a random peer ID for connections that don't provide one.\n */\nfunction generatePeerId(): PeerId {\n const chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"\n let result = \"sse-\"\n for (let i = 0; i < 12; i++) {\n result += chars.charAt(Math.floor(Math.random() * chars.length))\n }\n return result\n}\n\n// ---------------------------------------------------------------------------\n// SseServerTransport\n// ---------------------------------------------------------------------------\n\n/**\n * SSE server network adapter.\n *\n * Framework-agnostic — works with any HTTP framework through the\n * `SseConnection.setSendFunction()` callback. Use `registerConnection()`\n * to integrate with your framework's SSE endpoint handler.\n *\n * Each client connection is tracked as an `SseConnection` keyed by peer ID.\n * The adapter creates a channel per connection and routes outbound messages\n * through the connection's send method (which encodes to text wire format\n * and calls the injected sendFn).\n *\n * The connection handshake:\n * 1. Client opens EventSource (GET /events)\n * 2. Server calls `registerConnection(peerId)` → creates channel\n * 3. Client's EventSource.onopen fires → client sends establish-request (POST)\n * 4. Server receives establish-request → Synchronizer responds with establish-response (SSE)\n *\n * The server does NOT call `establishChannel()` — it waits for the client's\n * establish-request, which arrives via POST after the EventSource is open.\n */\nexport class SseServerTransport extends Transport<PeerId> {\n #connections = new Map<PeerId, SseConnection>()\n readonly #fragmentThreshold: number\n\n constructor(options?: SseServerTransportOptions) {\n super({ transportType: \"sse-server\" })\n this.#fragmentThreshold =\n options?.fragmentThreshold ?? DEFAULT_FRAGMENT_THRESHOLD\n }\n\n // ==========================================================================\n // Adapter abstract method implementations\n // ==========================================================================\n\n protected generate(peerId: PeerId): GeneratedChannel {\n return {\n transportType: this.transportType,\n send: (msg: ChannelMsg) => {\n const connection = this.#connections.get(peerId)\n if (connection) {\n connection.send(msg)\n }\n },\n stop: () => {\n this.unregisterConnection(peerId)\n },\n }\n }\n\n async onStart(): Promise<void> {\n // Server adapter starts passively — connections arrive via registerConnection()\n }\n\n async onStop(): Promise<void> {\n // Disconnect all active connections\n for (const connection of this.#connections.values()) {\n connection.disconnect()\n }\n this.#connections.clear()\n }\n\n // ==========================================================================\n // Connection management\n // ==========================================================================\n\n /**\n * Register a new peer connection.\n *\n * Call this from your framework's SSE endpoint handler when a client\n * connects via EventSource. Returns an `SseConnection` that you wire\n * up with `setSendFunction()` and `setDisconnectHandler()`.\n *\n * @param peerId The unique identifier for the peer (from query param or header)\n * @returns An SseConnection object for managing the connection\n *\n * @example Express\n * ```typescript\n * const connection = serverAdapter.registerConnection(peerId)\n * connection.setSendFunction((textFrame) => {\n * res.write(`data: ${textFrame}\\n\\n`)\n * })\n * ```\n *\n * @example Hono\n * ```typescript\n * const connection = serverAdapter.registerConnection(peerId)\n * connection.setSendFunction((textFrame) => {\n * stream.writeSSE({ data: textFrame })\n * })\n * ```\n */\n registerConnection(peerId?: PeerId): SseConnection {\n const resolvedPeerId = peerId ?? generatePeerId()\n\n // Check for existing connection and clean it up\n const existingConnection = this.#connections.get(resolvedPeerId)\n if (existingConnection) {\n existingConnection.dispose()\n this.unregisterConnection(resolvedPeerId)\n }\n\n // Create channel for this peer\n const channel = this.addChannel(resolvedPeerId)\n\n // Create connection object with fragmentation config\n const connection = new SseConnection(resolvedPeerId, channel.channelId, {\n fragmentThreshold: this.#fragmentThreshold,\n })\n connection._setChannel(channel)\n\n // Store connection\n this.#connections.set(resolvedPeerId, connection)\n\n return connection\n }\n\n /**\n * Unregister a peer connection.\n *\n * Removes the channel, disposes the connection's reassembler,\n * and cleans up tracking state. Called automatically when the\n * client disconnects (via req.on(\"close\")) or manually.\n *\n * @param peerId The unique identifier for the peer\n */\n unregisterConnection(peerId: PeerId): void {\n const connection = this.#connections.get(peerId)\n if (connection) {\n connection.dispose()\n this.removeChannel(connection.channelId)\n this.#connections.delete(peerId)\n }\n }\n\n /**\n * Get an active connection by peer ID.\n */\n getConnection(peerId: PeerId): SseConnection | undefined {\n return this.#connections.get(peerId)\n }\n\n /**\n * Get all active connections.\n */\n getAllConnections(): SseConnection[] {\n return Array.from(this.#connections.values())\n }\n\n /**\n * Check if a peer is connected.\n */\n isConnected(peerId: PeerId): boolean {\n return this.#connections.has(peerId)\n }\n\n /**\n * Get the number of connected peers.\n */\n get connectionCount(): number {\n return this.#connections.size\n }\n}\n"],"mappings":";AAeA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMA,IAAM,6BAA6B;AAuBnC,IAAM,gBAAN,MAAoB;AAAA,EAChB;AAAA,EACA;AAAA,EAET,WAA2B;AAAA,EAC3B,UAAgD;AAAA,EAChD,gBAAqC;AAAA;AAAA,EAG5B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA,EAET,YAAY,QAAgB,WAAmB,QAA8B;AAC3E,SAAK,SAAS;AACd,SAAK,YAAY;AACjB,SAAK,qBACH,QAAQ,qBAAqB;AAC/B,SAAK,cAAc,IAAI,gBAAgB;AAAA,MACrC,WAAW;AAAA,MACX,WAAW,CAAC,YAAoB;AAC9B,gBAAQ;AAAA,UACN,qDAAqD,MAAM,KAAK,OAAO;AAAA,QACzE;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,YAAY,SAAwB;AAClC,SAAK,WAAW;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBA,gBAAgB,QAA2C;AACzD,SAAK,UAA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;AAAA;AAAA;AAAA,EAWA,qBAAqB,QAAsB;AACzC,UAAM,aAAa,KAAK,aAAa,IAAI,MAAM;AAC/C,QAAI,YAAY;AACd,iBAAW,QAAQ;AACnB,WAAK,cAAc,WAAW,SAAS;AACvC,WAAK,aAAa,OAAO,MAAM;AAAA,IACjC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,cAAc,QAA2C;AACvD,WAAO,KAAK,aAAa,IAAI,MAAM;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA,EAKA,oBAAqC;AACnC,WAAO,MAAM,KAAK,KAAK,aAAa,OAAO,CAAC;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA,EAKA,YAAY,QAAyB;AACnC,WAAO,KAAK,aAAa,IAAI,MAAM;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,kBAA0B;AAC5B,WAAO,KAAK,aAAa;AAAA,EAC3B;AACF;","names":[]}
package/dist/client.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import { PeerId, Transport, TransitionListener, GeneratedChannel, TransportFactory, ClientStateMachine } from '@kyneta/exchange';
2
- export { StateTransition, TransitionListener } from '@kyneta/exchange';
3
- import { b as SseClientLifecycleEvents, c as SseClientState } from './types-BTgljZGe.js';
4
- export { D as DisconnectReason } from './types-BTgljZGe.js';
1
+ import { StateTransition, TransitionListener, Program } from '@kyneta/machine';
2
+ export { StateTransition, TransitionListener } from '@kyneta/machine';
3
+ import { PeerId, Transport, GeneratedChannel, TransportFactory, ReconnectOptions } from '@kyneta/transport';
4
+ import { b as SseClientLifecycleEvents, c as SseClientState } from './types-DaVaqfwF.js';
5
+ export { D as DisconnectReason } from './types-DaVaqfwF.js';
5
6
 
6
7
  /**
7
8
  * Default fragment threshold in characters.
@@ -35,6 +36,10 @@ interface SseClientOptions {
35
36
  /** Lifecycle event callbacks. */
36
37
  lifecycle?: SseClientLifecycleEvents;
37
38
  }
39
+ /**
40
+ * State transition event for SSE client states.
41
+ */
42
+ type SseClientStateTransition = StateTransition<SseClientState>;
38
43
  /**
39
44
  * SSE client network adapter for @kyneta/exchange.
40
45
  *
@@ -44,19 +49,21 @@ interface SseClientOptions {
44
49
  *
45
50
  * Both directions use the text wire format (`textCodec` + text framing).
46
51
  *
52
+ * Internally, the connection lifecycle is a `Program<Msg, Model, Fx>` —
53
+ * a pure Mealy machine whose transitions are deterministically testable.
54
+ * This class is the imperative shell that interprets data effects as I/O.
55
+ *
47
56
  * @example
48
57
  * ```typescript
49
- * import { createSseClient } from "@kyneta/sse-network-adapter/client"
50
- *
51
- * const adapter = createSseClient({
52
- * postUrl: "/sync",
53
- * eventSourceUrl: (peerId) => `/events?peerId=${peerId}`,
54
- * reconnect: { enabled: true },
55
- * })
58
+ * import { createSseClient } from "@kyneta/sse-transport/client"
56
59
  *
57
60
  * const exchange = new Exchange({
58
61
  * identity: { peerId: "browser-client" },
59
- * transports: [adapter],
62
+ * transports: [createSseClient({
63
+ * postUrl: "/sync",
64
+ * eventSourceUrl: (peerId) => `/events?peerId=${peerId}`,
65
+ * reconnect: { enabled: true },
66
+ * })],
60
67
  * })
61
68
  * ```
62
69
  */
@@ -64,12 +71,11 @@ declare class SseClientTransport extends Transport<void> {
64
71
  #private;
65
72
  constructor(options: SseClientOptions);
66
73
  /**
67
- * Get the current state of the connection.
74
+ * Get the current connection state.
68
75
  */
69
76
  getState(): SseClientState;
70
77
  /**
71
78
  * Subscribe to state transitions.
72
- * @returns Unsubscribe function
73
79
  */
74
80
  subscribeToTransitions(listener: TransitionListener<SseClientState>): () => void;
75
81
  /**
@@ -85,7 +91,7 @@ declare class SseClientTransport extends Transport<void> {
85
91
  timeoutMs?: number;
86
92
  }): Promise<SseClientState>;
87
93
  /**
88
- * Check if the client is connected (EventSource open, channel established).
94
+ * Whether the client is connected and ready to send/receive.
89
95
  */
90
96
  get isConnected(): boolean;
91
97
  protected generate(): GeneratedChannel;
@@ -97,7 +103,7 @@ declare class SseClientTransport extends Transport<void> {
97
103
  *
98
104
  * @example
99
105
  * ```typescript
100
- * import { createSseClient } from "@kyneta/sse-network-adapter/client"
106
+ * import { createSseClient } from "@kyneta/sse-transport/client"
101
107
  *
102
108
  * const exchange = new Exchange({
103
109
  * transports: [createSseClient({
@@ -110,35 +116,48 @@ declare class SseClientTransport extends Transport<void> {
110
116
  */
111
117
  declare function createSseClient(options: SseClientOptions): TransportFactory;
112
118
 
119
+ type SseClientMsg = {
120
+ type: "start";
121
+ } | {
122
+ type: "event-source-opened";
123
+ } | {
124
+ type: "event-source-error";
125
+ } | {
126
+ type: "stop";
127
+ } | {
128
+ type: "reconnect-timer-fired";
129
+ };
130
+ type SseClientEffect = {
131
+ type: "create-event-source";
132
+ url: string;
133
+ attempt: number;
134
+ } | {
135
+ type: "close-event-source";
136
+ } | {
137
+ type: "add-channel-and-establish";
138
+ } | {
139
+ type: "remove-channel";
140
+ } | {
141
+ type: "start-reconnect-timer";
142
+ delayMs: number;
143
+ } | {
144
+ type: "cancel-reconnect-timer";
145
+ } | {
146
+ type: "abort-pending-posts";
147
+ };
148
+ interface SseClientProgramOptions {
149
+ url: string;
150
+ reconnect?: Partial<ReconnectOptions>;
151
+ /** Inject jitter source for deterministic testing. Default: () => Math.random() * 1000 */
152
+ jitterFn?: () => number;
153
+ }
113
154
  /**
114
- * Observable state machine for SSE client connection lifecycle.
155
+ * Create the SSE client connection lifecycle program — a pure Mealy machine.
115
156
  *
116
- * Extends the generic `ClientStateMachine<SseClientState>` with
117
- * an SSE-specific convenience helper. Unlike the WebSocket state machine,
118
- * SSE has no `"ready"` state — the connection is usable as soon as
119
- * `EventSource.onopen` fires.
120
- *
121
- * Usage:
122
- * ```typescript
123
- * const sm = new SseClientStateMachine()
124
- *
125
- * sm.subscribeToTransitions(({ from, to }) => {
126
- * console.log(`${from.status} → ${to.status}`)
127
- * })
128
- *
129
- * sm.transition({ status: "connecting", attempt: 1 })
130
- * sm.transition({ status: "connected" })
131
- *
132
- * // Transitions are delivered asynchronously via microtask
133
- * // Listener will see: disconnected → connecting, connecting → connected
134
- * ```
157
+ * The returned `Program<SseClientMsg, SseClientState, SseClientEffect>`
158
+ * encodes every state transition and effect as inspectable data. The imperative
159
+ * shell interprets `SseClientEffect` as actual I/O.
135
160
  */
136
- declare class SseClientStateMachine extends ClientStateMachine<SseClientState> {
137
- constructor();
138
- /**
139
- * Check if the client is connected (EventSource open, channel established).
140
- */
141
- isConnected(): boolean;
142
- }
161
+ declare function createSseClientProgram(options: SseClientProgramOptions): Program<SseClientMsg, SseClientState, SseClientEffect>;
143
162
 
144
- export { DEFAULT_FRAGMENT_THRESHOLD, SseClientLifecycleEvents, type SseClientOptions, SseClientState, SseClientStateMachine, SseClientTransport, createSseClient };
163
+ export { DEFAULT_FRAGMENT_THRESHOLD, type SseClientEffect, SseClientLifecycleEvents, type SseClientMsg, type SseClientOptions, type SseClientProgramOptions, SseClientState, type SseClientStateTransition, SseClientTransport, createSseClient, createSseClientProgram };