@kyneta/sse-transport 1.3.1 → 1.4.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client-transport.ts","../src/client-program.ts"],"sourcesContent":["// client-transport — SSE client transport for @kyneta/exchange.\n//\n// Thin imperative shell around the pure client program (client-program.ts).\n// The program produces data effects; this module interprets them as I/O.\n//\n// FC/IS design:\n// - client-program.ts: pure Mealy machine (functional core)\n// - client-transport.ts: effect executor (imperative shell)\n//\n// Uses two HTTP channels:\n// - EventSource (GET) for server→client messages\n// - fetch POST for client→server messages\n//\n// Both directions use the text wire format (textCodec + text framing).\n//\n// Features:\n// - Pure Mealy machine for connection lifecycle (client-program.ts)\n// - Exponential backoff reconnection with jitter\n// - POST retry with exponential backoff\n// - Text-level fragmentation for large payloads\n// - Inbound TextReassembler for fragmented SSE messages\n// - Observable connection state via subscribeToTransitions()\n//\n// The connection handshake:\n// 1. Client creates EventSource, waits for open\n// 2. EventSource.onopen fires → client creates channel + calls establishChannel()\n// 3. Synchronizer exchanges establish-request / establish-response via POST + SSE\n//\n// On EventSource.onerror, the adapter closes the EventSource immediately and\n// takes over reconnection via the program's backoff logic, rather than\n// letting the browser's built-in EventSource reconnection run.\n\nimport type {\n ObservableHandle,\n StateTransition,\n TransitionListener,\n} from \"@kyneta/machine\"\nimport { createObservableProgram } from \"@kyneta/machine\"\nimport type {\n Channel,\n ChannelMsg,\n GeneratedChannel,\n PeerId,\n TransportFactory,\n} from \"@kyneta/transport\"\nimport { Transport } from \"@kyneta/transport\"\nimport {\n encodeTextComplete,\n fragmentTextPayload,\n TextReassembler,\n textCodec,\n} from \"@kyneta/wire\"\nimport {\n createSseClientProgram,\n type SseClientEffect,\n type SseClientMsg,\n} from \"./client-program.js\"\nimport type {\n DisconnectReason,\n SseClientLifecycleEvents,\n SseClientState,\n} from \"./types.js\"\n\n// Re-export state types for convenience\nexport type { DisconnectReason, SseClientLifecycleEvents, SseClientState }\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Default fragment threshold in characters.\n * 60K chars provides a safety margin below typical 100KB body-parser limits,\n * accounting for JSON overhead and potential base64 expansion.\n */\nexport const DEFAULT_FRAGMENT_THRESHOLD = 60_000\n\n/**\n * Options for the SSE client adapter.\n */\nexport interface SseClientOptions {\n /** URL for POST requests (client→server). String or function of peerId. */\n postUrl: string | ((peerId: PeerId) => string)\n\n /** URL for SSE EventSource (server→client). String or function of peerId. */\n eventSourceUrl: string | ((peerId: PeerId) => string)\n\n /** Reconnection options for EventSource. */\n reconnect?: {\n enabled?: boolean\n maxAttempts?: number\n baseDelay?: number\n maxDelay?: number\n }\n\n /** POST retry options. */\n postRetry?: {\n maxAttempts?: number\n baseDelay?: number\n maxDelay?: number\n }\n\n /** Fragment threshold in characters. Default: 60000 (60K chars). */\n fragmentThreshold?: number\n\n /** Lifecycle event callbacks. */\n lifecycle?: SseClientLifecycleEvents\n}\n\n/**\n * Default POST retry options.\n */\nconst DEFAULT_POST_RETRY = {\n maxAttempts: 3,\n baseDelay: 1000,\n maxDelay: 10000,\n}\n\n// ---------------------------------------------------------------------------\n// State transition type alias\n// ---------------------------------------------------------------------------\n\n/**\n * State transition event for SSE client states.\n */\nexport type SseClientStateTransition = StateTransition<SseClientState>\n\n// ---------------------------------------------------------------------------\n// SseClientTransport\n// ---------------------------------------------------------------------------\n\n/**\n * SSE client network adapter for @kyneta/exchange.\n *\n * Uses two HTTP channels:\n * - **EventSource** (GET, long-lived) for server→client messages\n * - **fetch POST** for client→server messages\n *\n * Both directions use the text wire format (`textCodec` + text framing).\n *\n * Internally, the connection lifecycle is a `Program<Msg, Model, Fx>` —\n * a pure Mealy machine whose transitions are deterministically testable.\n * This class is the imperative shell that interprets data effects as I/O.\n *\n * @example\n * ```typescript\n * import { createSseClient } from \"@kyneta/sse-transport/client\"\n *\n * const exchange = new Exchange({\n * identity: { peerId: \"browser-client\" },\n * transports: [createSseClient({\n * postUrl: \"/sync\",\n * eventSourceUrl: (peerId) => `/events?peerId=${peerId}`,\n * reconnect: { enabled: true },\n * })],\n * })\n * ```\n */\nexport class SseClientTransport extends Transport<void> {\n #peerId?: PeerId\n #options: SseClientOptions\n\n // Observable program handle — created in onStart(), drives all state\n #handle: ObservableHandle<SseClientMsg, SseClientState>\n\n // Executor-local I/O state — not in the program model\n #eventSource?: EventSource\n #serverChannel?: Channel\n #reconnectTimer?: ReturnType<typeof setTimeout>\n\n // Fragmentation\n readonly #fragmentThreshold: number\n\n // Inbound reassembly for fragmented SSE messages from server\n readonly #reassembler: TextReassembler\n\n // POST retry\n #currentRetryAbortController?: AbortController\n\n constructor(options: SseClientOptions) {\n super({ transportType: \"sse-client\" })\n this.#options = options\n this.#fragmentThreshold =\n options.fragmentThreshold ?? DEFAULT_FRAGMENT_THRESHOLD\n this.#reassembler = new TextReassembler({\n timeoutMs: 10_000,\n })\n\n // Create the program with a placeholder URL — the executor resolves the\n // real eventSourceUrl (which may be a function of peerId) at effect time.\n // The URL in the program is used only as a marker; the executor overrides it.\n const program = createSseClientProgram({\n url: \"__deferred__\",\n reconnect: options.reconnect,\n })\n\n this.#handle = createObservableProgram(program, (effect, dispatch) => {\n this.#executeEffect(effect, dispatch)\n })\n\n // Set up lifecycle event forwarding\n this.#setupLifecycleEvents()\n }\n\n // ==========================================================================\n // Lifecycle event forwarding\n // ==========================================================================\n\n /**\n * Subscribe to the observable handle's transitions and forward them to\n * the lifecycle callbacks. `wasConnectedBefore` is observer-local state,\n * not in the program model.\n */\n #setupLifecycleEvents(): void {\n let wasConnectedBefore = false\n\n this.#handle.subscribeToTransitions(transition => {\n // Forward to onStateChange callback\n this.#options.lifecycle?.onStateChange?.(transition)\n\n const { from, to } = transition\n\n // onDisconnect: transitioning TO disconnected\n if (to.status === \"disconnected\" && to.reason) {\n this.#options.lifecycle?.onDisconnect?.(to.reason)\n }\n\n // onReconnecting: transitioning TO reconnecting\n if (to.status === \"reconnecting\") {\n this.#options.lifecycle?.onReconnecting?.(to.attempt, to.nextAttemptMs)\n }\n\n // onReconnected: from reconnecting/connecting TO connected (after prior connection)\n if (\n wasConnectedBefore &&\n (from.status === \"reconnecting\" || from.status === \"connecting\") &&\n to.status === \"connected\"\n ) {\n this.#options.lifecycle?.onReconnected?.()\n }\n\n // Track whether we've ever been connected\n if (to.status === \"connected\") {\n wasConnectedBefore = true\n }\n\n // Reset on intentional disconnect (stop)\n if (to.status === \"disconnected\" && to.reason?.type === \"intentional\") {\n wasConnectedBefore = false\n }\n })\n }\n\n // ==========================================================================\n // Effect executor — interprets data effects as I/O\n // ==========================================================================\n\n #executeEffect(\n effect: SseClientEffect,\n dispatch: (msg: SseClientMsg) => void,\n ): void {\n switch (effect.type) {\n case \"create-event-source\": {\n this.#doCreateEventSource(dispatch)\n break\n }\n\n case \"close-event-source\": {\n if (this.#eventSource) {\n this.#eventSource.onopen = null\n this.#eventSource.onmessage = null\n this.#eventSource.onerror = null\n this.#eventSource.close()\n this.#eventSource = undefined\n }\n break\n }\n\n case \"add-channel-and-establish\": {\n // Remove any stale channel from a previous connection\n if (this.#serverChannel) {\n this.removeChannel(this.#serverChannel.channelId)\n this.#serverChannel = undefined\n }\n\n this.#serverChannel = this.addChannel()\n\n // No \"ready\" handshake — establish immediately\n this.establishChannel(this.#serverChannel.channelId)\n break\n }\n\n case \"remove-channel\": {\n if (this.#serverChannel) {\n this.removeChannel(this.#serverChannel.channelId)\n this.#serverChannel = undefined\n }\n break\n }\n\n case \"start-reconnect-timer\": {\n this.#reconnectTimer = setTimeout(() => {\n this.#reconnectTimer = undefined\n dispatch({ type: \"reconnect-timer-fired\" })\n }, effect.delayMs)\n break\n }\n\n case \"cancel-reconnect-timer\": {\n if (this.#reconnectTimer !== undefined) {\n clearTimeout(this.#reconnectTimer)\n this.#reconnectTimer = undefined\n }\n break\n }\n\n case \"abort-pending-posts\": {\n if (this.#currentRetryAbortController) {\n this.#currentRetryAbortController.abort()\n this.#currentRetryAbortController = undefined\n }\n break\n }\n }\n }\n\n /**\n * Create an EventSource and wire up event handlers.\n * The URL is resolved here (may be a function of peerId).\n */\n #doCreateEventSource(dispatch: (msg: SseClientMsg) => void): void {\n if (!this.#peerId) {\n throw new Error(\"Cannot connect: peerId not set\")\n }\n\n // Resolve URL — may be a string or function of peerId\n const url =\n typeof this.#options.eventSourceUrl === \"function\"\n ? this.#options.eventSourceUrl(this.#peerId)\n : this.#options.eventSourceUrl\n\n try {\n this.#eventSource = new EventSource(url)\n\n this.#eventSource.onopen = () => {\n dispatch({ type: \"event-source-opened\" })\n }\n\n this.#eventSource.onmessage = (event: MessageEvent) => {\n this.#handleMessage(event)\n }\n\n this.#eventSource.onerror = () => {\n dispatch({ type: \"event-source-error\" })\n }\n } catch (_error) {\n // EventSource constructor threw (e.g. invalid URL) — treat as error\n dispatch({ type: \"event-source-error\" })\n }\n }\n\n // ==========================================================================\n // State observation — delegated to the observable handle\n // ==========================================================================\n\n /**\n * Get the current connection state.\n */\n getState(): SseClientState {\n return this.#handle.getState()\n }\n\n /**\n * Subscribe to state transitions.\n */\n subscribeToTransitions(\n listener: TransitionListener<SseClientState>,\n ): () => void {\n return this.#handle.subscribeToTransitions(listener)\n }\n\n /**\n * Wait for a specific state.\n */\n waitForState(\n predicate: (state: SseClientState) => boolean,\n options?: { timeoutMs?: number },\n ): Promise<SseClientState> {\n return this.#handle.waitForState(predicate, options)\n }\n\n /**\n * Wait for a specific status.\n */\n waitForStatus(\n status: SseClientState[\"status\"],\n options?: { timeoutMs?: number },\n ): Promise<SseClientState> {\n return this.#handle.waitForStatus(status, options)\n }\n\n /**\n * Whether the client is connected and ready to send/receive.\n */\n get isConnected(): boolean {\n return this.#handle.getState().status === \"connected\"\n }\n\n // ==========================================================================\n // Transport abstract method implementations\n // ==========================================================================\n\n protected generate(): GeneratedChannel {\n return {\n transportType: this.transportType,\n send: (msg: ChannelMsg) => {\n if (!this.#peerId) {\n return\n }\n\n // Check if EventSource is closed before sending\n // readyState: 0=CONNECTING, 1=OPEN, 2=CLOSED\n if (!this.#eventSource || this.#eventSource.readyState === 2) {\n return\n }\n\n // Resolve the postUrl with the peerId\n const resolvedPostUrl =\n typeof this.#options.postUrl === \"function\"\n ? this.#options.postUrl(this.#peerId)\n : this.#options.postUrl\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(\n payload,\n this.#fragmentThreshold,\n )\n for (const fragment of fragments) {\n void this.#sendTextWithRetry(resolvedPostUrl, fragment)\n }\n } else {\n void this.#sendTextWithRetry(resolvedPostUrl, textFrame)\n }\n },\n stop: () => {\n // Don't call disconnect here — channel.stop() is called when\n // the channel is removed, which can happen during effect execution.\n // The actual disconnect is handled by onStop() or the program.\n },\n }\n }\n\n async onStart(): Promise<void> {\n if (!this.identity) {\n throw new Error(\n \"Adapter not properly initialized — identity not available\",\n )\n }\n this.#peerId = this.identity.peerId\n this.#handle.dispatch({ type: \"start\" })\n }\n\n async onStop(): Promise<void> {\n this.#reassembler.dispose()\n this.#handle.dispatch({ type: \"stop\" })\n }\n\n // ==========================================================================\n // Inbound message handling\n // ==========================================================================\n\n /**\n * Handle incoming SSE message.\n *\n * Each SSE `data:` event contains a text wire frame string.\n * Feed it through the TextReassembler to handle both complete\n * and fragmented frames.\n */\n #handleMessage(event: MessageEvent): void {\n if (!this.#serverChannel) {\n return\n }\n\n const data = event.data\n if (typeof data !== \"string\") {\n return\n }\n\n // Feed through reassembler (handles both complete and fragment frames)\n const result = this.#reassembler.receive(data)\n\n if (result.status === \"complete\") {\n try {\n // Two-step decode: Frame<string> → JSON.parse → textCodec.decode\n const parsed = JSON.parse(result.frame.content.payload)\n const messages = textCodec.decode(parsed)\n for (const msg of messages) {\n this.#serverChannel.onReceive(msg)\n }\n } catch (error) {\n console.error(\"Failed to decode SSE message:\", error)\n }\n } else if (result.status === \"error\") {\n console.error(\"SSE message reassembly error:\", result.error)\n }\n // \"pending\" status means we're waiting for more fragments — nothing to do\n }\n\n // ==========================================================================\n // POST sending with retry\n // ==========================================================================\n\n /**\n * Send a text frame via POST with retry logic.\n */\n async #sendTextWithRetry(url: string, textFrame: string): Promise<void> {\n let attempt = 0\n const postRetryOpts = {\n ...DEFAULT_POST_RETRY,\n ...this.#options.postRetry,\n }\n const { maxAttempts, baseDelay, maxDelay } = postRetryOpts\n\n while (attempt < maxAttempts) {\n try {\n if (!this.#currentRetryAbortController) {\n this.#currentRetryAbortController = new AbortController()\n }\n\n if (!this.#peerId) {\n throw new Error(\"PeerId not available for retry\")\n }\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"text/plain\",\n \"X-Peer-Id\": this.#peerId,\n },\n body: textFrame,\n signal: this.#currentRetryAbortController.signal,\n })\n\n if (!response.ok) {\n // Don't retry on client errors (4xx)\n if (response.status >= 400 && response.status < 500) {\n throw new Error(`Failed to send message: ${response.statusText}`)\n }\n throw new Error(`Server error: ${response.statusText}`)\n }\n\n // Success\n this.#currentRetryAbortController = undefined\n return\n } catch (error: unknown) {\n attempt++\n\n const err = error as Error\n\n // If aborted, stop retrying\n if (err.name === \"AbortError\") {\n throw error\n }\n\n // If controller was cleared (e.g. by abort-pending-posts effect), stop retrying\n if (!this.#currentRetryAbortController) {\n const abortError = new Error(\"Retry aborted by connection reset\")\n abortError.name = \"AbortError\"\n throw abortError\n }\n\n // If max attempts reached, throw the last error\n if (attempt >= maxAttempts) {\n this.#currentRetryAbortController = undefined\n throw error\n }\n\n // Calculate delay with exponential backoff and jitter\n const delay = Math.min(\n baseDelay * 2 ** (attempt - 1) + Math.random() * 100,\n maxDelay,\n )\n\n // Wait for delay or abort signal\n await new Promise<void>((resolve, reject) => {\n if (this.#currentRetryAbortController?.signal.aborted) {\n const error = new Error(\"Retry aborted\")\n error.name = \"AbortError\"\n reject(error)\n return\n }\n\n const timer = setTimeout(() => {\n cleanup()\n resolve()\n }, delay)\n\n const onAbort = () => {\n clearTimeout(timer)\n cleanup()\n const error = new Error(\"Retry aborted\")\n error.name = \"AbortError\"\n reject(error)\n }\n\n const cleanup = () => {\n this.#currentRetryAbortController?.signal.removeEventListener(\n \"abort\",\n onAbort,\n )\n }\n\n this.#currentRetryAbortController?.signal.addEventListener(\n \"abort\",\n onAbort,\n )\n })\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory function\n// ---------------------------------------------------------------------------\n\n/**\n * Create an SSE client adapter for browser-to-server connections.\n *\n * @example\n * ```typescript\n * import { createSseClient } from \"@kyneta/sse-transport/client\"\n *\n * const exchange = new Exchange({\n * transports: [createSseClient({\n * postUrl: \"/sync\",\n * eventSourceUrl: (peerId) => `/events?peerId=${peerId}`,\n * reconnect: { enabled: true },\n * })],\n * })\n * ```\n */\nexport function createSseClient(options: SseClientOptions): TransportFactory {\n return () => new SseClientTransport(options)\n}\n","// client-program — pure Mealy machine for SSE client connection lifecycle.\n//\n// The client program encodes every state transition and effect as data.\n// The imperative shell (client-transport.ts) interprets effects as I/O.\n// Tests assert on data — no EventSource, no timing, never flaky.\n//\n// Algebra: Program<SseClientMsg, SseClientState, SseClientEffect>\n// Interpreter: client-transport.ts executeClientEffect()\n\nimport type { Program } from \"@kyneta/machine\"\nimport type { ReconnectOptions } from \"@kyneta/transport\"\nimport { computeBackoffDelay, DEFAULT_RECONNECT } from \"@kyneta/transport\"\n\nimport type { DisconnectReason, SseClientState } from \"./types.js\"\n\n// ---------------------------------------------------------------------------\n// Messages\n// ---------------------------------------------------------------------------\n\nexport type SseClientMsg =\n | { type: \"start\" }\n | { type: \"event-source-opened\" }\n | { type: \"event-source-error\" }\n | { type: \"stop\" }\n | { type: \"reconnect-timer-fired\" }\n\n// ---------------------------------------------------------------------------\n// Effects (data — interpreted by the imperative shell)\n// ---------------------------------------------------------------------------\n\nexport type SseClientEffect =\n | { type: \"create-event-source\"; url: string; attempt: number }\n | { type: \"close-event-source\" }\n | { type: \"add-channel-and-establish\" }\n | { type: \"remove-channel\" }\n | { type: \"start-reconnect-timer\"; delayMs: number }\n | { type: \"cancel-reconnect-timer\" }\n | { type: \"abort-pending-posts\" }\n\n// ---------------------------------------------------------------------------\n// Program factory\n// ---------------------------------------------------------------------------\n\nexport interface SseClientProgramOptions {\n url: string\n reconnect?: Partial<ReconnectOptions>\n /** Inject jitter source for deterministic testing. Default: () => Math.random() * 1000 */\n jitterFn?: () => number\n}\n\n/**\n * Create the SSE client connection lifecycle program — a pure Mealy machine.\n *\n * The returned `Program<SseClientMsg, SseClientState, SseClientEffect>`\n * encodes every state transition and effect as inspectable data. The imperative\n * shell interprets `SseClientEffect` as actual I/O.\n */\nexport function createSseClientProgram(\n options: SseClientProgramOptions,\n): Program<SseClientMsg, SseClientState, SseClientEffect> {\n const { url, jitterFn = () => Math.random() * 1000 } = options\n const reconnect: ReconnectOptions = {\n ...DEFAULT_RECONNECT,\n ...options.reconnect,\n }\n\n /**\n * Attempt to transition into reconnecting, or give up and disconnect.\n *\n * Pure — computes the next state and effects from the current attempt\n * count and reconnect configuration. Returns a tuple suitable for\n * spreading into an `update` return.\n */\n function tryReconnect(\n currentAttempt: number,\n reason: DisconnectReason,\n ...extraEffects: SseClientEffect[]\n ): [SseClientState, ...SseClientEffect[]] {\n if (!reconnect.enabled) {\n return [{ status: \"disconnected\", reason }, ...extraEffects]\n }\n\n if (currentAttempt >= reconnect.maxAttempts) {\n return [\n {\n status: \"disconnected\",\n reason: { type: \"max-retries-exceeded\", attempts: currentAttempt },\n },\n ...extraEffects,\n ]\n }\n\n const delay = computeBackoffDelay(\n currentAttempt + 1,\n reconnect.baseDelay,\n reconnect.maxDelay,\n jitterFn(),\n )\n\n return [\n {\n status: \"reconnecting\",\n attempt: currentAttempt + 1,\n nextAttemptMs: delay,\n },\n ...extraEffects,\n { type: \"start-reconnect-timer\", delayMs: delay },\n ]\n }\n\n return {\n init: [{ status: \"disconnected\" }],\n\n update(msg, model): [SseClientState, ...SseClientEffect[]] {\n switch (msg.type) {\n // -----------------------------------------------------------------\n // start\n // -----------------------------------------------------------------\n case \"start\": {\n if (model.status !== \"disconnected\") return [model]\n return [\n { status: \"connecting\", attempt: 1 },\n { type: \"create-event-source\", url, attempt: 1 },\n ]\n }\n\n // -----------------------------------------------------------------\n // event-source-opened\n // -----------------------------------------------------------------\n case \"event-source-opened\": {\n if (model.status !== \"connecting\") return [model]\n return [\n { status: \"connected\" },\n { type: \"add-channel-and-establish\" },\n ]\n }\n\n // -----------------------------------------------------------------\n // event-source-error\n // -----------------------------------------------------------------\n case \"event-source-error\": {\n const reason: DisconnectReason = {\n type: \"error\",\n error: new Error(\"EventSource connection error\"),\n }\n\n if (model.status === \"connecting\") {\n return tryReconnect(model.attempt, reason, {\n type: \"close-event-source\",\n })\n }\n\n if (model.status === \"connected\") {\n return tryReconnect(\n 0,\n reason,\n { type: \"remove-channel\" },\n { type: \"close-event-source\" },\n { type: \"abort-pending-posts\" },\n )\n }\n\n return [model]\n }\n\n // -----------------------------------------------------------------\n // reconnect-timer-fired\n // -----------------------------------------------------------------\n case \"reconnect-timer-fired\": {\n if (model.status !== \"reconnecting\") return [model]\n return [\n { status: \"connecting\", attempt: model.attempt },\n { type: \"create-event-source\", url, attempt: model.attempt },\n ]\n }\n\n // -----------------------------------------------------------------\n // stop\n // -----------------------------------------------------------------\n case \"stop\": {\n if (model.status === \"disconnected\") return [model]\n\n const effects: SseClientEffect[] = [\n { type: \"cancel-reconnect-timer\" },\n ]\n\n if (model.status === \"connecting\") {\n effects.push({ type: \"close-event-source\" })\n }\n\n if (model.status === \"connected\") {\n effects.push(\n { type: \"close-event-source\" },\n { type: \"remove-channel\" },\n { type: \"abort-pending-posts\" },\n )\n }\n\n return [\n { status: \"disconnected\", reason: { type: \"intentional\" } },\n ...effects,\n ]\n }\n }\n },\n }\n}\n"],"mappings":";;;AAqCA,SAAS,+BAA+B;A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,SAA6C;AAC3E,SAAO,MAAM,IAAI,mBAAmB,OAAO;AAC7C;","names":["error"]}
1
+ {"version":3,"file":"client.js","names":["#fragmentThreshold","#reassembler","#options","#handle","#executeEffect","#setupLifecycleEvents","#doCreateEventSource","#eventSource","#serverChannel","#reconnectTimer","#currentRetryAbortController","#peerId","#handleMessage","#sendTextWithRetry"],"sources":["../src/client-program.ts","../src/client-transport.ts"],"sourcesContent":["// client-program — pure Mealy machine for SSE client connection lifecycle.\n//\n// The client program encodes every state transition and effect as data.\n// The imperative shell (client-transport.ts) interprets effects as I/O.\n// Tests assert on data — no EventSource, no timing, never flaky.\n//\n// Algebra: Program<SseClientMsg, SseClientState, SseClientEffect>\n// Interpreter: client-transport.ts executeClientEffect()\n\nimport type { Program } from \"@kyneta/machine\"\nimport type { ReconnectOptions } from \"@kyneta/transport\"\nimport { computeBackoffDelay, DEFAULT_RECONNECT } from \"@kyneta/transport\"\n\nimport type { DisconnectReason, SseClientState } from \"./types.js\"\n\n// ---------------------------------------------------------------------------\n// Messages\n// ---------------------------------------------------------------------------\n\nexport type SseClientMsg =\n | { type: \"start\" }\n | { type: \"event-source-opened\" }\n | { type: \"event-source-error\" }\n | { type: \"stop\" }\n | { type: \"reconnect-timer-fired\" }\n\n// ---------------------------------------------------------------------------\n// Effects (data — interpreted by the imperative shell)\n// ---------------------------------------------------------------------------\n\nexport type SseClientEffect =\n | { type: \"create-event-source\"; url: string; attempt: number }\n | { type: \"close-event-source\" }\n | { type: \"add-channel-and-establish\" }\n | { type: \"remove-channel\" }\n | { type: \"start-reconnect-timer\"; delayMs: number }\n | { type: \"cancel-reconnect-timer\" }\n | { type: \"abort-pending-posts\" }\n\n// ---------------------------------------------------------------------------\n// Program factory\n// ---------------------------------------------------------------------------\n\nexport interface SseClientProgramOptions {\n url: string\n reconnect?: Partial<ReconnectOptions>\n /** Inject jitter source for deterministic testing. Default: () => Math.random() * 1000 */\n jitterFn?: () => number\n}\n\n/**\n * Create the SSE client connection lifecycle program — a pure Mealy machine.\n *\n * The returned `Program<SseClientMsg, SseClientState, SseClientEffect>`\n * encodes every state transition and effect as inspectable data. The imperative\n * shell interprets `SseClientEffect` as actual I/O.\n */\nexport function createSseClientProgram(\n options: SseClientProgramOptions,\n): Program<SseClientMsg, SseClientState, SseClientEffect> {\n const { url, jitterFn = () => Math.random() * 1000 } = options\n const reconnect: ReconnectOptions = {\n ...DEFAULT_RECONNECT,\n ...options.reconnect,\n }\n\n /**\n * Attempt to transition into reconnecting, or give up and disconnect.\n *\n * Pure — computes the next state and effects from the current attempt\n * count and reconnect configuration. Returns a tuple suitable for\n * spreading into an `update` return.\n */\n function tryReconnect(\n currentAttempt: number,\n reason: DisconnectReason,\n ...extraEffects: SseClientEffect[]\n ): [SseClientState, ...SseClientEffect[]] {\n if (!reconnect.enabled) {\n return [{ status: \"disconnected\", reason }, ...extraEffects]\n }\n\n if (currentAttempt >= reconnect.maxAttempts) {\n return [\n {\n status: \"disconnected\",\n reason: { type: \"max-retries-exceeded\", attempts: currentAttempt },\n },\n ...extraEffects,\n ]\n }\n\n const delay = computeBackoffDelay(\n currentAttempt + 1,\n reconnect.baseDelay,\n reconnect.maxDelay,\n jitterFn(),\n )\n\n return [\n {\n status: \"reconnecting\",\n attempt: currentAttempt + 1,\n nextAttemptMs: delay,\n },\n ...extraEffects,\n { type: \"start-reconnect-timer\", delayMs: delay },\n ]\n }\n\n return {\n init: [{ status: \"disconnected\" }],\n\n update(msg, model): [SseClientState, ...SseClientEffect[]] {\n switch (msg.type) {\n // -----------------------------------------------------------------\n // start\n // -----------------------------------------------------------------\n case \"start\": {\n if (model.status !== \"disconnected\") return [model]\n return [\n { status: \"connecting\", attempt: 1 },\n { type: \"create-event-source\", url, attempt: 1 },\n ]\n }\n\n // -----------------------------------------------------------------\n // event-source-opened\n // -----------------------------------------------------------------\n case \"event-source-opened\": {\n if (model.status !== \"connecting\") return [model]\n return [\n { status: \"connected\" },\n { type: \"add-channel-and-establish\" },\n ]\n }\n\n // -----------------------------------------------------------------\n // event-source-error\n // -----------------------------------------------------------------\n case \"event-source-error\": {\n const reason: DisconnectReason = {\n type: \"error\",\n error: new Error(\"EventSource connection error\"),\n }\n\n if (model.status === \"connecting\") {\n return tryReconnect(model.attempt, reason, {\n type: \"close-event-source\",\n })\n }\n\n if (model.status === \"connected\") {\n return tryReconnect(\n 0,\n reason,\n { type: \"remove-channel\" },\n { type: \"close-event-source\" },\n { type: \"abort-pending-posts\" },\n )\n }\n\n return [model]\n }\n\n // -----------------------------------------------------------------\n // reconnect-timer-fired\n // -----------------------------------------------------------------\n case \"reconnect-timer-fired\": {\n if (model.status !== \"reconnecting\") return [model]\n return [\n { status: \"connecting\", attempt: model.attempt },\n { type: \"create-event-source\", url, attempt: model.attempt },\n ]\n }\n\n // -----------------------------------------------------------------\n // stop\n // -----------------------------------------------------------------\n case \"stop\": {\n if (model.status === \"disconnected\") return [model]\n\n const effects: SseClientEffect[] = [\n { type: \"cancel-reconnect-timer\" },\n ]\n\n if (model.status === \"connecting\") {\n effects.push({ type: \"close-event-source\" })\n }\n\n if (model.status === \"connected\") {\n effects.push(\n { type: \"close-event-source\" },\n { type: \"remove-channel\" },\n { type: \"abort-pending-posts\" },\n )\n }\n\n return [\n { status: \"disconnected\", reason: { type: \"intentional\" } },\n ...effects,\n ]\n }\n }\n },\n }\n}\n","// client-transport — SSE client transport for @kyneta/exchange.\n//\n// Thin imperative shell around the pure client program (client-program.ts).\n// The program produces data effects; this module interprets them as I/O.\n//\n// FC/IS design:\n// - client-program.ts: pure Mealy machine (functional core)\n// - client-transport.ts: effect executor (imperative shell)\n//\n// Uses two HTTP channels:\n// - EventSource (GET) for server→client messages\n// - fetch POST for client→server messages\n//\n// Both directions use the text wire format (textCodec + text framing).\n//\n// Features:\n// - Pure Mealy machine for connection lifecycle (client-program.ts)\n// - Exponential backoff reconnection with jitter\n// - POST retry with exponential backoff\n// - Text-level fragmentation for large payloads\n// - Inbound TextReassembler for fragmented SSE messages\n// - Observable connection state via subscribeToTransitions()\n//\n// The connection handshake:\n// 1. Client creates EventSource, waits for open\n// 2. EventSource.onopen fires → client creates channel + calls establishChannel()\n// 3. Synchronizer exchanges establish messages via POST + SSE\n//\n// On EventSource.onerror, the adapter closes the EventSource immediately and\n// takes over reconnection via the program's backoff logic, rather than\n// letting the browser's built-in EventSource reconnection run.\n\nimport type {\n ObservableHandle,\n StateTransition,\n TransitionListener,\n} from \"@kyneta/machine\"\nimport { createObservableProgram } from \"@kyneta/machine\"\nimport type {\n Channel,\n ChannelMsg,\n GeneratedChannel,\n PeerId,\n TransportFactory,\n} from \"@kyneta/transport\"\nimport { Transport } from \"@kyneta/transport\"\nimport {\n encodeTextComplete,\n fragmentTextPayload,\n TextReassembler,\n textCodec,\n} from \"@kyneta/wire\"\nimport {\n createSseClientProgram,\n type SseClientEffect,\n type SseClientMsg,\n} from \"./client-program.js\"\nimport type {\n DisconnectReason,\n SseClientLifecycleEvents,\n SseClientState,\n} from \"./types.js\"\n\n// Re-export state types for convenience\nexport type { DisconnectReason, SseClientLifecycleEvents, SseClientState }\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Default fragment threshold in characters.\n * 60K chars provides a safety margin below typical 100KB body-parser limits,\n * accounting for JSON overhead and potential base64 expansion.\n */\nexport const DEFAULT_FRAGMENT_THRESHOLD = 60_000\n\n/**\n * Options for the SSE client adapter.\n */\nexport interface SseClientOptions {\n /** URL for POST requests (client→server). String or function of peerId. */\n postUrl: string | ((peerId: PeerId) => string)\n\n /** URL for SSE EventSource (server→client). String or function of peerId. */\n eventSourceUrl: string | ((peerId: PeerId) => string)\n\n /** Reconnection options for EventSource. */\n reconnect?: {\n enabled?: boolean\n maxAttempts?: number\n baseDelay?: number\n maxDelay?: number\n }\n\n /** POST retry options. */\n postRetry?: {\n maxAttempts?: number\n baseDelay?: number\n maxDelay?: number\n }\n\n /** Fragment threshold in characters. Default: 60000 (60K chars). */\n fragmentThreshold?: number\n\n /** Lifecycle event callbacks. */\n lifecycle?: SseClientLifecycleEvents\n}\n\n/**\n * Default POST retry options.\n */\nconst DEFAULT_POST_RETRY = {\n maxAttempts: 3,\n baseDelay: 1000,\n maxDelay: 10000,\n}\n\n// ---------------------------------------------------------------------------\n// State transition type alias\n// ---------------------------------------------------------------------------\n\n/**\n * State transition event for SSE client states.\n */\nexport type SseClientStateTransition = StateTransition<SseClientState>\n\n// ---------------------------------------------------------------------------\n// SseClientTransport\n// ---------------------------------------------------------------------------\n\n/**\n * SSE client network adapter for @kyneta/exchange.\n *\n * Uses two HTTP channels:\n * - **EventSource** (GET, long-lived) for server→client messages\n * - **fetch POST** for client→server messages\n *\n * Both directions use the text wire format (`textCodec` + text framing).\n *\n * Internally, the connection lifecycle is a `Program<Msg, Model, Fx>` —\n * a pure Mealy machine whose transitions are deterministically testable.\n * This class is the imperative shell that interprets data effects as I/O.\n *\n * @example\n * ```typescript\n * import { createSseClient } from \"@kyneta/sse-transport/client\"\n *\n * const exchange = new Exchange({\n * id: \"browser-client\",\n * transports: [createSseClient({\n * postUrl: \"/sync\",\n * eventSourceUrl: (peerId) => `/events?peerId=${peerId}`,\n * reconnect: { enabled: true },\n * })],\n * })\n * ```\n */\nexport class SseClientTransport extends Transport<void> {\n #peerId?: PeerId\n #options: SseClientOptions\n\n // Observable program handle — created in onStart(), drives all state\n #handle: ObservableHandle<SseClientMsg, SseClientState>\n\n // Executor-local I/O state — not in the program model\n #eventSource?: EventSource\n #serverChannel?: Channel\n #reconnectTimer?: ReturnType<typeof setTimeout>\n\n // Fragmentation\n readonly #fragmentThreshold: number\n\n // Inbound reassembly for fragmented SSE messages from server\n readonly #reassembler: TextReassembler\n\n // POST retry\n #currentRetryAbortController?: AbortController\n\n constructor(options: SseClientOptions) {\n super({ transportType: \"sse-client\" })\n this.#options = options\n this.#fragmentThreshold =\n options.fragmentThreshold ?? DEFAULT_FRAGMENT_THRESHOLD\n this.#reassembler = new TextReassembler({\n timeoutMs: 10_000,\n })\n\n // Create the program with a placeholder URL — the executor resolves the\n // real eventSourceUrl (which may be a function of peerId) at effect time.\n // The URL in the program is used only as a marker; the executor overrides it.\n const program = createSseClientProgram({\n url: \"__deferred__\",\n reconnect: options.reconnect,\n })\n\n this.#handle = createObservableProgram(program, (effect, dispatch) => {\n this.#executeEffect(effect, dispatch)\n })\n\n // Set up lifecycle event forwarding\n this.#setupLifecycleEvents()\n }\n\n // ==========================================================================\n // Lifecycle event forwarding\n // ==========================================================================\n\n /**\n * Subscribe to the observable handle's transitions and forward them to\n * the lifecycle callbacks. `wasConnectedBefore` is observer-local state,\n * not in the program model.\n */\n #setupLifecycleEvents(): void {\n let wasConnectedBefore = false\n\n this.#handle.subscribeToTransitions(transition => {\n // Forward to onStateChange callback\n this.#options.lifecycle?.onStateChange?.(transition)\n\n const { from, to } = transition\n\n // onDisconnect: transitioning TO disconnected\n if (to.status === \"disconnected\" && to.reason) {\n this.#options.lifecycle?.onDisconnect?.(to.reason)\n }\n\n // onReconnecting: transitioning TO reconnecting\n if (to.status === \"reconnecting\") {\n this.#options.lifecycle?.onReconnecting?.(to.attempt, to.nextAttemptMs)\n }\n\n // onReconnected: from reconnecting/connecting TO connected (after prior connection)\n if (\n wasConnectedBefore &&\n (from.status === \"reconnecting\" || from.status === \"connecting\") &&\n to.status === \"connected\"\n ) {\n this.#options.lifecycle?.onReconnected?.()\n }\n\n // Track whether we've ever been connected\n if (to.status === \"connected\") {\n wasConnectedBefore = true\n }\n\n // Reset on intentional disconnect (stop)\n if (to.status === \"disconnected\" && to.reason?.type === \"intentional\") {\n wasConnectedBefore = false\n }\n })\n }\n\n // ==========================================================================\n // Effect executor — interprets data effects as I/O\n // ==========================================================================\n\n #executeEffect(\n effect: SseClientEffect,\n dispatch: (msg: SseClientMsg) => void,\n ): void {\n switch (effect.type) {\n case \"create-event-source\": {\n this.#doCreateEventSource(dispatch)\n break\n }\n\n case \"close-event-source\": {\n if (this.#eventSource) {\n this.#eventSource.onopen = null\n this.#eventSource.onmessage = null\n this.#eventSource.onerror = null\n this.#eventSource.close()\n this.#eventSource = undefined\n }\n break\n }\n\n case \"add-channel-and-establish\": {\n // Remove any stale channel from a previous connection\n if (this.#serverChannel) {\n this.removeChannel(this.#serverChannel.channelId)\n this.#serverChannel = undefined\n }\n\n this.#serverChannel = this.addChannel()\n\n // No \"ready\" handshake — establish immediately\n this.establishChannel(this.#serverChannel.channelId)\n break\n }\n\n case \"remove-channel\": {\n if (this.#serverChannel) {\n this.removeChannel(this.#serverChannel.channelId)\n this.#serverChannel = undefined\n }\n break\n }\n\n case \"start-reconnect-timer\": {\n this.#reconnectTimer = setTimeout(() => {\n this.#reconnectTimer = undefined\n dispatch({ type: \"reconnect-timer-fired\" })\n }, effect.delayMs)\n break\n }\n\n case \"cancel-reconnect-timer\": {\n if (this.#reconnectTimer !== undefined) {\n clearTimeout(this.#reconnectTimer)\n this.#reconnectTimer = undefined\n }\n break\n }\n\n case \"abort-pending-posts\": {\n if (this.#currentRetryAbortController) {\n this.#currentRetryAbortController.abort()\n this.#currentRetryAbortController = undefined\n }\n break\n }\n }\n }\n\n /**\n * Create an EventSource and wire up event handlers.\n * The URL is resolved here (may be a function of peerId).\n */\n #doCreateEventSource(dispatch: (msg: SseClientMsg) => void): void {\n if (!this.#peerId) {\n throw new Error(\"Cannot connect: peerId not set\")\n }\n\n // Resolve URL — may be a string or function of peerId\n const url =\n typeof this.#options.eventSourceUrl === \"function\"\n ? this.#options.eventSourceUrl(this.#peerId)\n : this.#options.eventSourceUrl\n\n try {\n this.#eventSource = new EventSource(url)\n\n this.#eventSource.onopen = () => {\n dispatch({ type: \"event-source-opened\" })\n }\n\n this.#eventSource.onmessage = (event: MessageEvent) => {\n this.#handleMessage(event)\n }\n\n this.#eventSource.onerror = () => {\n dispatch({ type: \"event-source-error\" })\n }\n } catch (_error) {\n // EventSource constructor threw (e.g. invalid URL) — treat as error\n dispatch({ type: \"event-source-error\" })\n }\n }\n\n // ==========================================================================\n // State observation — delegated to the observable handle\n // ==========================================================================\n\n /**\n * Get the current connection state.\n */\n getState(): SseClientState {\n return this.#handle.getState()\n }\n\n /**\n * Subscribe to state transitions.\n */\n subscribeToTransitions(\n listener: TransitionListener<SseClientState>,\n ): () => void {\n return this.#handle.subscribeToTransitions(listener)\n }\n\n /**\n * Wait for a specific state.\n */\n waitForState(\n predicate: (state: SseClientState) => boolean,\n options?: { timeoutMs?: number },\n ): Promise<SseClientState> {\n return this.#handle.waitForState(predicate, options)\n }\n\n /**\n * Wait for a specific status.\n */\n waitForStatus(\n status: SseClientState[\"status\"],\n options?: { timeoutMs?: number },\n ): Promise<SseClientState> {\n return this.#handle.waitForStatus(status, options)\n }\n\n /**\n * Whether the client is connected and ready to send/receive.\n */\n get isConnected(): boolean {\n return this.#handle.getState().status === \"connected\"\n }\n\n // ==========================================================================\n // Transport abstract method implementations\n // ==========================================================================\n\n protected generate(): GeneratedChannel {\n return {\n transportType: this.transportType,\n send: (msg: ChannelMsg) => {\n if (!this.#peerId) {\n return\n }\n\n // Check if EventSource is closed before sending\n // readyState: 0=CONNECTING, 1=OPEN, 2=CLOSED\n if (!this.#eventSource || this.#eventSource.readyState === 2) {\n return\n }\n\n // Resolve the postUrl with the peerId\n const resolvedPostUrl =\n typeof this.#options.postUrl === \"function\"\n ? this.#options.postUrl(this.#peerId)\n : this.#options.postUrl\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(\n payload,\n this.#fragmentThreshold,\n )\n for (const fragment of fragments) {\n void this.#sendTextWithRetry(resolvedPostUrl, fragment)\n }\n } else {\n void this.#sendTextWithRetry(resolvedPostUrl, textFrame)\n }\n },\n stop: () => {\n // Don't call disconnect here — channel.stop() is called when\n // the channel is removed, which can happen during effect execution.\n // The actual disconnect is handled by onStop() or the program.\n },\n }\n }\n\n async onStart(): Promise<void> {\n if (!this.identity) {\n throw new Error(\n \"Adapter not properly initialized — identity not available\",\n )\n }\n this.#peerId = this.identity.peerId\n this.#handle.dispatch({ type: \"start\" })\n }\n\n async onStop(): Promise<void> {\n this.#reassembler.dispose()\n this.#handle.dispatch({ type: \"stop\" })\n }\n\n // ==========================================================================\n // Inbound message handling\n // ==========================================================================\n\n /**\n * Handle incoming SSE message.\n *\n * Each SSE `data:` event contains a text wire frame string.\n * Feed it through the TextReassembler to handle both complete\n * and fragmented frames.\n */\n #handleMessage(event: MessageEvent): void {\n if (!this.#serverChannel) {\n return\n }\n\n const data = event.data\n if (typeof data !== \"string\") {\n return\n }\n\n // Feed through reassembler (handles both complete and fragment frames)\n const result = this.#reassembler.receive(data)\n\n if (result.status === \"complete\") {\n try {\n // Two-step decode: Frame<string> → JSON.parse → textCodec.decode\n const parsed = JSON.parse(result.frame.content.payload)\n const messages = textCodec.decode(parsed)\n for (const msg of messages) {\n this.#serverChannel.onReceive(msg)\n }\n } catch (error) {\n console.error(\"Failed to decode SSE message:\", error)\n }\n } else if (result.status === \"error\") {\n console.error(\"SSE message reassembly error:\", result.error)\n }\n // \"pending\" status means we're waiting for more fragments — nothing to do\n }\n\n // ==========================================================================\n // POST sending with retry\n // ==========================================================================\n\n /**\n * Send a text frame via POST with retry logic.\n */\n async #sendTextWithRetry(url: string, textFrame: string): Promise<void> {\n let attempt = 0\n const postRetryOpts = {\n ...DEFAULT_POST_RETRY,\n ...this.#options.postRetry,\n }\n const { maxAttempts, baseDelay, maxDelay } = postRetryOpts\n\n while (attempt < maxAttempts) {\n try {\n if (!this.#currentRetryAbortController) {\n this.#currentRetryAbortController = new AbortController()\n }\n\n if (!this.#peerId) {\n throw new Error(\"PeerId not available for retry\")\n }\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"text/plain\",\n \"X-Peer-Id\": this.#peerId,\n },\n body: textFrame,\n signal: this.#currentRetryAbortController.signal,\n })\n\n if (!response.ok) {\n // Don't retry on client errors (4xx)\n if (response.status >= 400 && response.status < 500) {\n throw new Error(`Failed to send message: ${response.statusText}`)\n }\n throw new Error(`Server error: ${response.statusText}`)\n }\n\n // Success\n this.#currentRetryAbortController = undefined\n return\n } catch (error: unknown) {\n attempt++\n\n const err = error as Error\n\n // If aborted, stop retrying\n if (err.name === \"AbortError\") {\n throw error\n }\n\n // If controller was cleared (e.g. by abort-pending-posts effect), stop retrying\n if (!this.#currentRetryAbortController) {\n const abortError = new Error(\"Retry aborted by connection reset\")\n abortError.name = \"AbortError\"\n throw abortError\n }\n\n // If max attempts reached, throw the last error\n if (attempt >= maxAttempts) {\n this.#currentRetryAbortController = undefined\n throw error\n }\n\n // Calculate delay with exponential backoff and jitter\n const delay = Math.min(\n baseDelay * 2 ** (attempt - 1) + Math.random() * 100,\n maxDelay,\n )\n\n // Wait for delay or abort signal\n await new Promise<void>((resolve, reject) => {\n if (this.#currentRetryAbortController?.signal.aborted) {\n const error = new Error(\"Retry aborted\")\n error.name = \"AbortError\"\n reject(error)\n return\n }\n\n const timer = setTimeout(() => {\n cleanup()\n resolve()\n }, delay)\n\n const onAbort = () => {\n clearTimeout(timer)\n cleanup()\n const error = new Error(\"Retry aborted\")\n error.name = \"AbortError\"\n reject(error)\n }\n\n const cleanup = () => {\n this.#currentRetryAbortController?.signal.removeEventListener(\n \"abort\",\n onAbort,\n )\n }\n\n this.#currentRetryAbortController?.signal.addEventListener(\n \"abort\",\n onAbort,\n )\n })\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory function\n// ---------------------------------------------------------------------------\n\n/**\n * Create an SSE client adapter for browser-to-server connections.\n *\n * @example\n * ```typescript\n * import { createSseClient } from \"@kyneta/sse-transport/client\"\n *\n * const exchange = new Exchange({\n * transports: [createSseClient({\n * postUrl: \"/sync\",\n * eventSourceUrl: (peerId) => `/events?peerId=${peerId}`,\n * reconnect: { enabled: true },\n * })],\n * })\n * ```\n */\nexport function createSseClient(options: SseClientOptions):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AA0BV,SAAgB,gBAAgB,SAA6C;AAC3E,cAAa,IAAI,mBAAmB,QAAQ"}
package/dist/express.d.ts CHANGED
@@ -1,34 +1,35 @@
1
- import { PeerId, ChannelMsg } from '@kyneta/transport';
2
- import { Request, Router } from 'express';
3
- import { b as SseServerTransport } from './server-transport-D9l5s5PV.js';
4
- import { TextReassembler } from '@kyneta/wire';
1
+ import { t as SseServerTransport } from "./server-transport-C0bHmtVV.js";
2
+ import { ChannelMsg, PeerId } from "@kyneta/transport";
3
+ import { TextReassembler } from "@kyneta/wire";
4
+ import { Request, Router } from "express";
5
5
 
6
+ //#region src/express-router.d.ts
6
7
  interface SseExpressRouterOptions {
7
- /**
8
- * Path for the sync endpoint where clients POST messages.
9
- * @default "/sync"
10
- */
11
- syncPath?: string;
12
- /**
13
- * Path for the events endpoint where clients connect via SSE.
14
- * @default "/events"
15
- */
16
- eventsPath?: string;
17
- /**
18
- * Interval in milliseconds for sending heartbeat comments to keep connections alive.
19
- * @default 30000 (30 seconds)
20
- */
21
- heartbeatInterval?: number;
22
- /**
23
- * Custom function to extract peerId from the sync request.
24
- * By default, reads from the "x-peer-id" header.
25
- */
26
- getPeerIdFromSyncRequest?: (req: Request) => PeerId | undefined;
27
- /**
28
- * Custom function to extract peerId from the events request.
29
- * By default, reads from the "peerId" query parameter.
30
- */
31
- getPeerIdFromEventsRequest?: (req: Request) => PeerId | undefined;
8
+ /**
9
+ * Path for the sync endpoint where clients POST messages.
10
+ * @default "/sync"
11
+ */
12
+ syncPath?: string;
13
+ /**
14
+ * Path for the events endpoint where clients connect via SSE.
15
+ * @default "/events"
16
+ */
17
+ eventsPath?: string;
18
+ /**
19
+ * Interval in milliseconds for sending heartbeat comments to keep connections alive.
20
+ * @default 30000 (30 seconds)
21
+ */
22
+ heartbeatInterval?: number;
23
+ /**
24
+ * Custom function to extract peerId from the sync request.
25
+ * By default, reads from the "x-peer-id" header.
26
+ */
27
+ getPeerIdFromSyncRequest?: (req: Request) => PeerId | undefined;
28
+ /**
29
+ * Custom function to extract peerId from the events request.
30
+ * By default, reads from the "peerId" query parameter.
31
+ */
32
+ getPeerIdFromEventsRequest?: (req: Request) => PeerId | undefined;
32
33
  }
33
34
  /**
34
35
  * Create an Express router for SSE server adapter.
@@ -57,7 +58,7 @@ interface SseExpressRouterOptions {
57
58
  *
58
59
  * const serverAdapter = new SseServerTransport()
59
60
  * const exchange = new Exchange({
60
- * identity: { peerId: "server", name: "server", type: "service" },
61
+ * id: { peerId: "server", name: "server", type: "service" },
61
62
  * transports: [() => serverAdapter],
62
63
  * })
63
64
  *
@@ -69,19 +70,20 @@ interface SseExpressRouterOptions {
69
70
  * ```
70
71
  */
71
72
  declare function createSseExpressRouter(adapter: SseServerTransport, options?: SseExpressRouterOptions): Router;
72
-
73
+ //#endregion
74
+ //#region src/sse-handler.d.ts
73
75
  /**
74
76
  * Response to send back to the client after processing a POST.
75
77
  */
76
78
  interface SsePostResponse {
77
- status: 200 | 202 | 400;
78
- body: {
79
- ok: true;
80
- } | {
81
- pending: true;
82
- } | {
83
- error: string;
84
- };
79
+ status: 200 | 202 | 400;
80
+ body: {
81
+ ok: true;
82
+ } | {
83
+ pending: true;
84
+ } | {
85
+ error: string;
86
+ };
85
87
  }
86
88
  /**
87
89
  * Result of parsing a text POST body.
@@ -92,15 +94,15 @@ interface SsePostResponse {
92
94
  * - "error": Decode/reassembly error
93
95
  */
94
96
  type SsePostResult = {
95
- type: "messages";
96
- messages: ChannelMsg[];
97
- response: SsePostResponse;
97
+ type: "messages";
98
+ messages: ChannelMsg[];
99
+ response: SsePostResponse;
98
100
  } | {
99
- type: "pending";
100
- response: SsePostResponse;
101
+ type: "pending";
102
+ response: SsePostResponse;
101
103
  } | {
102
- type: "error";
103
- response: SsePostResponse;
104
+ type: "error";
105
+ response: SsePostResponse;
104
106
  };
105
107
  /**
106
108
  * Parse a text POST body through the reassembler.
@@ -131,5 +133,6 @@ type SsePostResult = {
131
133
  * ```
132
134
  */
133
135
  declare function parseTextPostBody(reassembler: TextReassembler, body: string): SsePostResult;
134
-
136
+ //#endregion
135
137
  export { type SseExpressRouterOptions, type SsePostResponse, type SsePostResult, SseServerTransport, createSseExpressRouter, parseTextPostBody };
138
+ //# sourceMappingURL=express.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"express.d.ts","names":[],"sources":["../src/express-router.ts","../src/sse-handler.ts"],"mappings":";;;;;;UAsBiB,uBAAA;;;AAAjB;;EAKE,QAAA;EAkBiC;;;;EAZjC,UAAA;EAkBqD;;;;EAZrD,iBAAA;EAMiC;;;;EAAjC,wBAAA,IAA4B,GAAA,EAAK,OAAA,KAAY,MAAA;EAMf;;;;EAA9B,0BAAA,IAA8B,GAAA,EAAK,OAAA,KAAY,MAAA;AAAA;;;;;;;;;;;;;;;;;AC1BjD;;;;;;;;;;;AAaA;;;;;;;;;;;iBD0DgB,sBAAA,CACd,OAAA,EAAS,kBAAA,EACT,OAAA,GAAS,uBAAA,GACR,MAAA;;;;;;UC1Ec,eAAA;EACf,MAAA;EACA,IAAA;IAAQ,EAAA;EAAA;IAAe,OAAA;EAAA;IAAoB,KAAA;EAAA;AAAA;;;;;;;;;KAWjC,aAAA;EACN,IAAA;EAAkB,QAAA,EAAU,UAAA;EAAc,QAAA,EAAU,eAAA;AAAA;EACpD,IAAA;EAAiB,QAAA,EAAU,eAAA;AAAA;EAC3B,IAAA;EAAe,QAAA,EAAU,eAAA;AAAA;;;;;;;;;;;;;AAhB/B;;;;;;;;;;;AAaA;;;;;iBAqCgB,iBAAA,CACd,WAAA,EAAa,eAAA,EACb,IAAA,WACC,aAAA"}