@kyneta/websocket-transport 1.3.0 → 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/server-transport.ts","../src/connection.ts"],"sourcesContent":["// server-adapter — Websocket server adapter for @kyneta/exchange.\n//\n// Manages Websocket connections from clients, encoding/decoding via the\n// kyneta wire format. Framework-agnostic — works with any Websocket\n// library through the Socket interface.\n//\n// Usage with Bun:\n// import { WebsocketServerTransport } from \"@kyneta/websocket-network-adapter/server\"\n// import { createBunWebsocketHandlers } from \"@kyneta/websocket-network-adapter/bun\"\n//\n// const serverAdapter = new WebsocketServerTransport()\n// Bun.serve({\n// websocket: createBunWebsocketHandlers(serverAdapter),\n// fetch(req, server) { server.upgrade(req); return new Response(\"\", { status: 101 }) },\n// })\n//\n// Usage with Node.js `ws`:\n// import { WebsocketServerTransport, wrapNodeWebsocket } from \"@kyneta/websocket-network-adapter/server\"\n// import { WebSocketServer } from \"ws\"\n//\n// const serverAdapter = new WebsocketServerTransport()\n// const wss = new WebSocketServer({ server })\n// wss.on(\"connection\", (ws) => {\n// const { start } = serverAdapter.handleConnection({ socket: wrapNodeWebsocket(ws) })\n// start()\n// })\n//\n// Ported from @loro-extended/adapter-websocket's WsServerNetworkAdapter with\n// kyneta naming conventions and the kyneta 5-message protocol.\n\nimport type { ChannelMsg, GeneratedChannel, PeerId } from \"@kyneta/transport\"\nimport { Transport } from \"@kyneta/transport\"\nimport {\n DEFAULT_FRAGMENT_THRESHOLD,\n WebsocketConnection,\n} from \"./connection.js\"\nimport type {\n WebsocketConnectionOptions,\n WebsocketConnectionResult,\n} from \"./types.js\"\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Options for the Websocket server adapter.\n */\nexport interface WebsocketServerTransportOptions {\n /**\n * Fragment threshold in bytes. Messages larger than this are fragmented.\n * Set to 0 to disable fragmentation (not recommended for cloud deployments).\n * Default: 100KB (safe for AWS API Gateway's 128KB limit)\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 = \"ws-\"\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// WebsocketServerTransport\n// ---------------------------------------------------------------------------\n\n/**\n * Websocket server network adapter.\n *\n * Framework-agnostic — works with any Websocket library through the\n * `Socket` interface. Use `handleConnection()` to integrate with your\n * framework's Websocket upgrade handler.\n *\n * Each client connection is tracked as a `WebsocketConnection` keyed\n * by peer ID. The adapter creates a channel per connection and routes\n * outbound messages through the connection's send method.\n *\n * The connection handshake follows a two-phase protocol:\n * 1. Server sends text `\"ready\"` signal (transport-level)\n * 2. Client sends `establish-request` (protocol-level)\n * 3. Server responds with `establish-response` (handled by Synchronizer)\n *\n * The server does NOT call `establishChannel()` — it waits for the\n * client's establish-request to avoid a race condition where the binary\n * establish-request could arrive before the client has processed \"ready\".\n */\nexport class WebsocketServerTransport extends Transport<PeerId> {\n #connections = new Map<PeerId, WebsocketConnection>()\n readonly #fragmentThreshold: number\n\n constructor(options?: WebsocketServerTransportOptions) {\n super({ transportType: \"websocket-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 handleConnection()\n }\n\n async onStop(): Promise<void> {\n // Disconnect all active connections\n for (const connection of this.#connections.values()) {\n connection.close(1001, \"Server shutting down\")\n }\n this.#connections.clear()\n }\n\n // ==========================================================================\n // Connection management\n // ==========================================================================\n\n /**\n * Handle a new Websocket connection.\n *\n * Call this from your framework's Websocket upgrade handler.\n * Returns a connection handle and a `start()` function that begins\n * message processing and sends the \"ready\" signal.\n *\n * @param options - Connection options including the Socket and optional peer ID\n * @returns A connection handle and start function\n *\n * @example Bun\n * ```typescript\n * const { start } = serverAdapter.handleConnection({\n * socket: wrapBunWebsocket(ws),\n * })\n * start()\n * ```\n *\n * @example Node.js ws\n * ```typescript\n * wss.on(\"connection\", (ws) => {\n * const { start } = serverAdapter.handleConnection({\n * socket: wrapNodeWebsocket(ws),\n * })\n * start()\n * })\n * ```\n */\n handleConnection(\n options: WebsocketConnectionOptions,\n ): WebsocketConnectionResult {\n const { socket, peerId: providedPeerId } = options\n\n // Generate peer ID if not provided\n const peerId = providedPeerId ?? generatePeerId()\n\n // Check for existing connection with same peer ID\n const existingConnection = this.#connections.get(peerId)\n if (existingConnection) {\n existingConnection.close(1000, \"Replaced by new connection\")\n this.unregisterConnection(peerId)\n }\n\n // Create channel for this peer\n const channel = this.addChannel(peerId)\n\n // Create connection object with fragmentation config\n const connection = new WebsocketConnection(\n peerId,\n channel.channelId,\n socket,\n {\n fragmentThreshold: this.#fragmentThreshold,\n },\n )\n connection._setChannel(channel)\n\n // Store connection\n this.#connections.set(peerId, connection)\n\n // Set up close handler\n socket.onClose((_code, _reason) => {\n this.unregisterConnection(peerId)\n })\n\n socket.onError(_error => {\n this.unregisterConnection(peerId)\n })\n\n return {\n connection,\n start: () => {\n connection.start()\n\n // Send ready signal to client so it knows the server is ready\n // This is a transport-level signal, separate from protocol-level establishment\n connection.sendReady()\n\n // NOTE: We do NOT call establishChannel() here.\n // The client will send establish-request after receiving \"ready\".\n // Our channel gets established when the Synchronizer receives\n // and processes that establish-request.\n //\n // This prevents a race condition where our binary establish-request\n // could arrive before the client has processed \"ready\" and created\n // its channel.\n },\n }\n }\n\n /**\n * Get an active connection by peer ID.\n */\n getConnection(peerId: PeerId): WebsocketConnection | undefined {\n return this.#connections.get(peerId)\n }\n\n /**\n * Get all active connections.\n */\n getAllConnections(): WebsocketConnection[] {\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 * Unregister a connection, removing its channel and cleaning up state.\n */\n unregisterConnection(peerId: PeerId): void {\n const connection = this.#connections.get(peerId)\n if (connection) {\n this.removeChannel(connection.channelId)\n this.#connections.delete(peerId)\n }\n }\n\n /**\n * Broadcast a message to all connected peers.\n */\n broadcast(msg: ChannelMsg): void {\n for (const connection of this.#connections.values()) {\n connection.send(msg)\n }\n }\n\n /**\n * Get the number of connected peers.\n */\n get connectionCount(): number {\n return this.#connections.size\n }\n}\n","// connection — WebsocketConnection for server-side peer connections.\n//\n// Wraps a Socket + CBOR codec + FragmentReassembler to provide\n// send/receive for ChannelMsg over a single Websocket connection.\n//\n// Used by WebsocketServerTransport to manage individual client connections.\n// The client adapter handles its own encoding/decoding inline since it\n// manages a single socket with reconnection logic.\n//\n// Ported from @loro-extended/adapter-websocket's WsConnection with\n// kyneta naming conventions and the kyneta wire format.\n\nimport type { Channel, ChannelMsg, PeerId } from \"@kyneta/transport\"\nimport {\n decodeBinaryMessages,\n encodeBinaryAndSend,\n FragmentReassembler,\n} from \"@kyneta/wire\"\nimport type { Socket } from \"./types.js\"\n\n/**\n * Default fragment threshold in bytes.\n * Messages larger than this are fragmented for cloud infrastructure compatibility.\n * AWS API Gateway has a 128KB limit, so 100KB provides a safe margin.\n */\nexport const DEFAULT_FRAGMENT_THRESHOLD = 100 * 1024\n\n/**\n * Configuration for creating a WebsocketConnection.\n */\nexport interface WebsocketConnectionConfig {\n /**\n * Fragment threshold in bytes. Messages larger than this are fragmented.\n * Set to 0 to disable fragmentation (not recommended for cloud deployments).\n * Default: 100KB (safe for AWS API Gateway's 128KB limit)\n */\n fragmentThreshold?: number\n}\n\n/**\n * Represents a single Websocket connection to a peer (server-side).\n *\n * Manages encoding, framing, fragmentation, and reassembly for one\n * connected client. Created by `WebsocketServerTransport.handleConnection()`.\n *\n * The connection uses the CBOR codec for binary transport — this is\n * the natural choice for Websocket's binary frame support.\n */\nexport class WebsocketConnection {\n readonly peerId: PeerId\n readonly channelId: number\n\n #socket: Socket\n #channel: Channel | null = null\n #started = false\n\n // Fragmentation support\n readonly #fragmentThreshold: number\n readonly #reassembler: FragmentReassembler\n\n constructor(\n peerId: PeerId,\n channelId: number,\n socket: Socket,\n config?: WebsocketConnectionConfig,\n ) {\n this.peerId = peerId\n this.channelId = channelId\n this.#socket = socket\n this.#fragmentThreshold =\n config?.fragmentThreshold ?? DEFAULT_FRAGMENT_THRESHOLD\n this.#reassembler = new FragmentReassembler({\n timeoutMs: 10_000,\n onTimeout: (frameId: string) => {\n console.warn(\n `[WebsocketConnection] Fragment batch timed out: ${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 * Start processing messages on this connection.\n *\n * Sets up the message handler on the socket. Must be called after\n * the connection is fully set up (channel assigned, stored in adapter).\n */\n start(): void {\n if (this.#started) {\n return\n }\n this.#started = true\n\n this.#socket.onMessage(data => {\n this.#handleMessage(data)\n })\n }\n\n /**\n * Send a ChannelMsg through the Websocket.\n *\n * Encodes via CBOR codec → frame → fragment if needed → socket.send().\n */\n send(msg: ChannelMsg): void {\n if (this.#socket.readyState !== \"open\") {\n return\n }\n\n encodeBinaryAndSend(msg, this.#fragmentThreshold, data =>\n this.#socket.send(data),\n )\n }\n\n /**\n * Send a \"ready\" signal to the client.\n *\n * This is a transport-level text message that tells the client the\n * server is ready to receive protocol messages. The client creates\n * its channel and sends establish-request after receiving this.\n */\n sendReady(): void {\n if (this.#socket.readyState !== \"open\") {\n return\n }\n this.#socket.send(\"ready\")\n }\n\n /**\n * Close the connection and clean up resources.\n */\n close(code?: number, reason?: string): void {\n this.#reassembler.dispose()\n this.#socket.close(code, reason)\n }\n\n // ==========================================================================\n // INTERNAL — message handling\n // ==========================================================================\n\n /**\n * Handle an incoming message from the Websocket.\n */\n #handleMessage(data: Uint8Array | string): void {\n // Handle keepalive ping/pong (text frames)\n if (typeof data === \"string\") {\n this.#handleKeepalive(data)\n return\n }\n\n // Handle binary protocol messages through shared decode pipeline\n try {\n const messages = decodeBinaryMessages(data, this.#reassembler)\n if (messages) {\n for (const msg of messages) {\n this.#handleChannelMessage(msg)\n }\n }\n } catch (error) {\n console.error(\"Failed to decode wire message:\", error)\n }\n }\n\n /**\n * Handle a decoded channel message.\n *\n * Delivers messages synchronously. The Synchronizer's receive queue\n * handles recursion prevention by queuing messages and processing\n * them iteratively.\n */\n #handleChannelMessage(msg: ChannelMsg): void {\n if (!this.#channel) {\n console.error(\"Cannot handle message: channel not set\")\n return\n }\n\n // Deliver synchronously — the Synchronizer's receive queue prevents recursion\n this.#channel.onReceive(msg)\n }\n\n /**\n * Handle keepalive ping/pong messages.\n */\n #handleKeepalive(text: string): void {\n if (text === \"ping\") {\n this.#socket.send(\"pong\")\n }\n // Ignore \"pong\" and \"ready\" responses\n }\n}\n"],"mappings":";;;;;;AA+BA,SAAS,iBAAiB;;;AClB1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAQA,IAAM,6BAA6B,MAAM;AAuBzC,IAAM,sBAAN,MAA0B;AAAA,EACtB;AAAA,EACA;AAAA,EAET;AAAA,EACA,WAA2B;AAAA,EAC3B,WAAW;AAAA;AAAA,EAGF;AAAA,EACA;AAAA,EAET,YACE,QACA,WACA,QACA,QACA;AACA,SAAK,SAAS;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C,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,qBAAqB,QAAsB;AACzC,UAAM,aAAa,KAAK,aAAa,IAAI,MAAM;AAC/C,QAAI,YAAY;AACd,WAAK,cAAc,WAAW,SAAS;AACvC,WAAK,aAAa,OAAO,MAAM;AAAA,IACjC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,UAAU,KAAuB;AAC/B,eAAW,cAAc,KAAK,aAAa,OAAO,GAAG;AACnD,iBAAW,KAAK,GAAG;AAAA,IACrB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,kBAA0B;AAC5B,WAAO,KAAK,aAAa;AAAA,EAC3B;AACF;","names":[]}
1
+ {"version":3,"file":"server.js","names":["#fragmentThreshold","#reassembler","#socket","#channel","#started","#handleMessage","#handleKeepalive","#handleChannelMessage","#fragmentThreshold","#connections"],"sources":["../src/connection.ts","../src/server-transport.ts","../src/service-client.ts"],"sourcesContent":["// connection — WebsocketConnection for server-side peer connections.\n//\n// Wraps a Socket + CBOR codec + FragmentReassembler to provide\n// send/receive for ChannelMsg over a single Websocket connection.\n//\n// Used by WebsocketServerTransport to manage individual client connections.\n// The client adapter handles its own encoding/decoding inline since it\n// manages a single socket with reconnection logic.\n//\n// Ported from @loro-extended/adapter-websocket's WsConnection with\n// kyneta naming conventions and the kyneta wire format.\n\nimport type { Channel, ChannelMsg, PeerId } from \"@kyneta/transport\"\nimport {\n decodeBinaryMessages,\n encodeBinaryAndSend,\n FragmentReassembler,\n} from \"@kyneta/wire\"\nimport type { Socket } from \"./types.js\"\n\n/**\n * Default fragment threshold in bytes.\n * Messages larger than this are fragmented for cloud infrastructure compatibility.\n * AWS API Gateway has a 128KB limit, so 100KB provides a safe margin.\n */\nexport const DEFAULT_FRAGMENT_THRESHOLD = 100 * 1024\n\n/**\n * Configuration for creating a WebsocketConnection.\n */\nexport interface WebsocketConnectionConfig {\n /**\n * Fragment threshold in bytes. Messages larger than this are fragmented.\n * Set to 0 to disable fragmentation (not recommended for cloud deployments).\n * Default: 100KB (safe for AWS API Gateway's 128KB limit)\n */\n fragmentThreshold?: number\n}\n\n/**\n * Represents a single Websocket connection to a peer (server-side).\n *\n * Manages encoding, framing, fragmentation, and reassembly for one\n * connected client. Created by `WebsocketServerTransport.handleConnection()`.\n *\n * The connection uses the CBOR codec for binary transport — this is\n * the natural choice for Websocket's binary frame support.\n */\nexport class WebsocketConnection {\n readonly peerId: PeerId\n readonly channelId: number\n\n #socket: Socket\n #channel: Channel | null = null\n #started = false\n\n // Fragmentation support\n readonly #fragmentThreshold: number\n readonly #reassembler: FragmentReassembler\n\n constructor(\n peerId: PeerId,\n channelId: number,\n socket: Socket,\n config?: WebsocketConnectionConfig,\n ) {\n this.peerId = peerId\n this.channelId = channelId\n this.#socket = socket\n this.#fragmentThreshold =\n config?.fragmentThreshold ?? DEFAULT_FRAGMENT_THRESHOLD\n this.#reassembler = new FragmentReassembler({\n timeoutMs: 10_000,\n onTimeout: (frameId: string) => {\n console.warn(\n `[WebsocketConnection] Fragment batch timed out: ${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 * Start processing messages on this connection.\n *\n * Sets up the message handler on the socket. Must be called after\n * the connection is fully set up (channel assigned, stored in adapter).\n */\n start(): void {\n if (this.#started) {\n return\n }\n this.#started = true\n\n this.#socket.onMessage(data => {\n this.#handleMessage(data)\n })\n }\n\n /**\n * Send a ChannelMsg through the Websocket.\n *\n * Encodes via CBOR codec → frame → fragment if needed → socket.send().\n */\n send(msg: ChannelMsg): void {\n if (this.#socket.readyState !== \"open\") {\n return\n }\n\n encodeBinaryAndSend(msg, this.#fragmentThreshold, data =>\n this.#socket.send(data),\n )\n }\n\n /**\n * Send a \"ready\" signal to the client.\n *\n * This is a transport-level text message that tells the client the\n * server is ready to receive protocol messages. The client creates\n * its channel and sends establish after receiving this.\n */\n sendReady(): void {\n if (this.#socket.readyState !== \"open\") {\n return\n }\n this.#socket.send(\"ready\")\n }\n\n /**\n * Close the connection and clean up resources.\n */\n close(code?: number, reason?: string): void {\n this.#reassembler.dispose()\n this.#socket.close(code, reason)\n }\n\n // ==========================================================================\n // INTERNAL — message handling\n // ==========================================================================\n\n /**\n * Handle an incoming message from the Websocket.\n */\n #handleMessage(data: Uint8Array | string): void {\n // Handle keepalive ping/pong (text frames)\n if (typeof data === \"string\") {\n this.#handleKeepalive(data)\n return\n }\n\n // Handle binary protocol messages through shared decode pipeline\n try {\n const messages = decodeBinaryMessages(data, this.#reassembler)\n if (messages) {\n for (const msg of messages) {\n this.#handleChannelMessage(msg)\n }\n }\n } catch (error) {\n console.error(\"Failed to decode wire message:\", error)\n }\n }\n\n /**\n * Handle a decoded channel message.\n *\n * Delivers messages synchronously. The Synchronizer's receive queue\n * handles recursion prevention by queuing messages and processing\n * them iteratively.\n */\n #handleChannelMessage(msg: ChannelMsg): void {\n if (!this.#channel) {\n console.error(\"Cannot handle message: channel not set\")\n return\n }\n\n // Deliver synchronously — the Synchronizer's receive queue prevents recursion\n this.#channel.onReceive(msg)\n }\n\n /**\n * Handle keepalive ping/pong messages.\n */\n #handleKeepalive(text: string): void {\n if (text === \"ping\") {\n this.#socket.send(\"pong\")\n }\n // Ignore \"pong\" and \"ready\" responses\n }\n}\n","// server-adapter — Websocket server adapter for @kyneta/exchange.\n//\n// Manages Websocket connections from clients, encoding/decoding via the\n// kyneta wire format. Framework-agnostic — works with any Websocket\n// library through the Socket interface.\n//\n// Usage with Bun:\n// import { WebsocketServerTransport } from \"@kyneta/websocket-transport/server\"\n// import { createBunWebsocketHandlers } from \"@kyneta/websocket-transport/bun\"\n//\n// const serverAdapter = new WebsocketServerTransport()\n// Bun.serve({\n// websocket: createBunWebsocketHandlers(serverAdapter),\n// fetch(req, server) { server.upgrade(req); return new Response(\"\", { status: 101 }) },\n// })\n//\n// Usage with Node.js `ws`:\n// import { WebsocketServerTransport, wrapNodeWebsocket } from \"@kyneta/websocket-transport/server\"\n// import { WebSocketServer } from \"ws\"\n//\n// const serverAdapter = new WebsocketServerTransport()\n// const wss = new WebSocketServer({ server })\n// wss.on(\"connection\", (ws) => {\n// const { start } = serverAdapter.handleConnection({ socket: wrapNodeWebsocket(ws) })\n// start()\n// })\n//\n// Ported from @loro-extended/adapter-websocket's WsServerNetworkAdapter with\n// kyneta naming conventions and the kyneta 5-message protocol.\n\nimport type { ChannelMsg, GeneratedChannel, PeerId } from \"@kyneta/transport\"\nimport { Transport } from \"@kyneta/transport\"\nimport {\n DEFAULT_FRAGMENT_THRESHOLD,\n WebsocketConnection,\n} from \"./connection.js\"\nimport type {\n WebsocketConnectionOptions,\n WebsocketConnectionResult,\n} from \"./types.js\"\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Options for the Websocket server adapter.\n */\nexport interface WebsocketServerTransportOptions {\n /**\n * Fragment threshold in bytes. Messages larger than this are fragmented.\n * Set to 0 to disable fragmentation (not recommended for cloud deployments).\n * Default: 100KB (safe for AWS API Gateway's 128KB limit)\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 = \"ws-\"\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// WebsocketServerTransport\n// ---------------------------------------------------------------------------\n\n/**\n * Websocket server network adapter.\n *\n * Framework-agnostic — works with any Websocket library through the\n * `Socket` interface. Use `handleConnection()` to integrate with your\n * framework's Websocket upgrade handler.\n *\n * Each client connection is tracked as a `WebsocketConnection` keyed\n * by peer ID. The adapter creates a channel per connection and routes\n * outbound messages through the connection's send method.\n *\n * The connection handshake follows a two-phase protocol:\n * 1. Server sends text `\"ready\"` signal (transport-level)\n * 2. Client sends `establish` (protocol-level)\n * 3. Server upgrades channel and sends present (handled by Synchronizer)\n *\n * The server does NOT call `establishChannel()` — it waits for the\n * client's establish to avoid a race condition where the binary\n * establish could arrive before the client has processed \"ready\".\n */\nexport class WebsocketServerTransport extends Transport<PeerId> {\n #connections = new Map<PeerId, WebsocketConnection>()\n readonly #fragmentThreshold: number\n\n constructor(options?: WebsocketServerTransportOptions) {\n super({ transportType: \"websocket-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 handleConnection()\n }\n\n async onStop(): Promise<void> {\n // Disconnect all active connections\n for (const connection of this.#connections.values()) {\n connection.close(1001, \"Server shutting down\")\n }\n this.#connections.clear()\n }\n\n // ==========================================================================\n // Connection management\n // ==========================================================================\n\n /**\n * Handle a new Websocket connection.\n *\n * Call this from your framework's Websocket upgrade handler.\n * Returns a connection handle and a `start()` function that begins\n * message processing and sends the \"ready\" signal.\n *\n * @param options - Connection options including the Socket and optional peer ID\n * @returns A connection handle and start function\n *\n * @example Bun\n * ```typescript\n * const { start } = serverAdapter.handleConnection({\n * socket: wrapBunWebsocket(ws),\n * })\n * start()\n * ```\n *\n * @example Node.js ws\n * ```typescript\n * wss.on(\"connection\", (ws) => {\n * const { start } = serverAdapter.handleConnection({\n * socket: wrapNodeWebsocket(ws),\n * })\n * start()\n * })\n * ```\n */\n handleConnection(\n options: WebsocketConnectionOptions,\n ): WebsocketConnectionResult {\n const { socket, peerId: providedPeerId } = options\n\n // Generate peer ID if not provided\n const peerId = providedPeerId ?? generatePeerId()\n\n // Check for existing connection with same peer ID\n const existingConnection = this.#connections.get(peerId)\n if (existingConnection) {\n existingConnection.close(1000, \"Replaced by new connection\")\n this.unregisterConnection(peerId)\n }\n\n // Create channel for this peer\n const channel = this.addChannel(peerId)\n\n // Create connection object with fragmentation config\n const connection = new WebsocketConnection(\n peerId,\n channel.channelId,\n socket,\n {\n fragmentThreshold: this.#fragmentThreshold,\n },\n )\n connection._setChannel(channel)\n\n // Store connection\n this.#connections.set(peerId, connection)\n\n // Set up close handler\n socket.onClose((_code, _reason) => {\n this.unregisterConnection(peerId)\n })\n\n socket.onError(_error => {\n this.unregisterConnection(peerId)\n })\n\n return {\n connection,\n start: () => {\n connection.start()\n\n // Send ready signal to client so it knows the server is ready\n // This is a transport-level signal, separate from protocol-level establishment\n connection.sendReady()\n\n // NOTE: We do NOT call establishChannel() here.\n // The client will send establish after receiving \"ready\".\n // Our channel gets established when the Synchronizer receives\n // and processes that establish message.\n //\n // This prevents a race condition where our binary establish\n // could arrive before the client has processed \"ready\" and created\n // its channel.\n },\n }\n }\n\n /**\n * Get an active connection by peer ID.\n */\n getConnection(peerId: PeerId): WebsocketConnection | undefined {\n return this.#connections.get(peerId)\n }\n\n /**\n * Get all active connections.\n */\n getAllConnections(): WebsocketConnection[] {\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 * Unregister a connection, removing its channel and cleaning up state.\n */\n unregisterConnection(peerId: PeerId): void {\n const connection = this.#connections.get(peerId)\n if (connection) {\n this.removeChannel(connection.channelId)\n this.#connections.delete(peerId)\n }\n }\n\n /**\n * Broadcast a message to all connected peers.\n */\n broadcast(msg: ChannelMsg): void {\n for (const connection of this.#connections.values()) {\n connection.send(msg)\n }\n }\n\n /**\n * Get the number of connected peers.\n */\n get connectionCount(): number {\n return this.#connections.size\n }\n}\n","// service-client — service-to-service WebSocket client factory.\n//\n// Extracted from client-transport.ts so that the service client factory\n// lives in the `./server` entry point (where it belongs) rather than\n// the `./browser` entry point. Backend code imports from `./server`;\n// browser code imports from `./browser`.\n\nimport type { TransportFactory } from \"@kyneta/transport\"\nimport {\n type WebsocketClientOptions,\n WebsocketClientTransport,\n} from \"./client-transport.js\"\n\n/**\n * Options for service-to-service Websocket connections.\n *\n * Identical to `WebsocketClientOptions` — the `headers` field is always\n * available on the base options. This alias exists for API clarity:\n * importing `ServiceWebsocketClientOptions` from `./server` signals\n * intent and pairs with `createServiceWebsocketClient`.\n */\nexport type ServiceWebsocketClientOptions = WebsocketClientOptions\n\n/**\n * Create a Websocket client transport for service-to-service connections.\n *\n * This factory is for backend environments (Bun, Node.js) where you need\n * to pass authentication headers during the Websocket upgrade.\n *\n * Note: Headers are a Bun/Node-specific extension. The browser WebSocket API\n * does not support custom headers. For browser clients, use\n * `createWebsocketClient()` and authenticate via URL query parameters.\n *\n * @example\n * ```typescript\n * import { createServiceWebsocketClient } from \"@kyneta/websocket-transport/server\"\n *\n * const exchange = new Exchange({\n * transports: [createServiceWebsocketClient({\n * url: \"ws://primary-server:3000/ws\",\n * WebSocket,\n * headers: { Authorization: \"Bearer token\" },\n * reconnect: { enabled: true },\n * })],\n * })\n * ```\n */\nexport function createServiceWebsocketClient(\n options: ServiceWebsocketClientOptions,\n): TransportFactory {\n return () => new WebsocketClientTransport(options)\n}\n"],"mappings":";;;;;;;;;AAyBA,MAAa,6BAA6B,MAAM;;;;;;;;;;AAuBhD,IAAa,sBAAb,MAAiC;CAC/B;CACA;CAEA;CACA,W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AAU;AACvB,QAAK,qBAAqB,OAAO;IACjC;AAEF,SAAO;GACL;GACA,aAAa;AACX,eAAW,OAAO;AAIlB,eAAW,WAAW;;GAWzB;;;;;CAMH,cAAc,QAAiD;AAC7D,SAAO,MAAA,YAAkB,IAAI,OAAO;;;;;CAMtC,oBAA2C;AACzC,SAAO,MAAM,KAAK,MAAA,YAAkB,QAAQ,CAAC;;;;;CAM/C,YAAY,QAAyB;AACnC,SAAO,MAAA,YAAkB,IAAI,OAAO;;;;;CAMtC,qBAAqB,QAAsB;EACzC,MAAM,aAAa,MAAA,YAAkB,IAAI,OAAO;AAChD,MAAI,YAAY;AACd,QAAK,cAAc,WAAW,UAAU;AACxC,SAAA,YAAkB,OAAO,OAAO;;;;;;CAOpC,UAAU,KAAuB;AAC/B,OAAK,MAAM,cAAc,MAAA,YAAkB,QAAQ,CACjD,YAAW,KAAK,IAAI;;;;;CAOxB,IAAI,kBAA0B;AAC5B,SAAO,MAAA,YAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACtO7B,SAAgB,6BACd,SACkB;AAClB,cAAa,IAAI,yBAAyB,QAAQ"}
@@ -0,0 +1,199 @@
1
+ import { PeerId, StateTransition, TransitionListener } from "@kyneta/transport";
2
+
3
+ //#region src/types.d.ts
4
+ /**
5
+ * WebSocket readyState constants per the WHATWG WebSocket spec.
6
+ * Replaces references to `WebSocket.CONNECTING`, `WebSocket.OPEN`, etc.
7
+ * so that shared code never depends on the browser global.
8
+ */
9
+ declare const READY_STATE: {
10
+ readonly CONNECTING: 0;
11
+ readonly OPEN: 1;
12
+ readonly CLOSING: 2;
13
+ readonly CLOSED: 3;
14
+ };
15
+ /** Minimal message event — only the fields the transport accesses. */
16
+ interface WebSocketMessageEvent {
17
+ readonly data: string | ArrayBuffer;
18
+ }
19
+ /** Minimal close event — only the fields the transport accesses. */
20
+ interface WebSocketCloseEvent {
21
+ readonly code: number;
22
+ readonly reason: string;
23
+ }
24
+ /**
25
+ * Structural type for a constructed WebSocket instance.
26
+ *
27
+ * Covers the browser's `WebSocket`, the `ws` library's `WebSocket`,
28
+ * and Bun's client `WebSocket` — all satisfy this interface without casting.
29
+ *
30
+ * The client transport uses `addEventListener`/`removeEventListener` for
31
+ * one-shot connection handlers with explicit cleanup during the connect
32
+ * phase. This is why `WebSocketLike` exists alongside the server-side
33
+ * `Socket` interface (which uses single-callback registration).
34
+ */
35
+ interface WebSocketLike {
36
+ readonly readyState: number;
37
+ binaryType: string;
38
+ send(data: string | ArrayBuffer): void;
39
+ close(code?: number, reason?: string): void;
40
+ addEventListener(type: string, listener: (event: any) => void): void;
41
+ removeEventListener(type: string, listener: (event: any) => void): void;
42
+ }
43
+ /**
44
+ * Structural type for a WebSocket constructor.
45
+ *
46
+ * Type safety for constructor arguments is intentionally at the options
47
+ * layer (`WebsocketClientOptions.headers`), not here. The `...rest: any[]`
48
+ * absorbs both the browser's `protocols` arg and backend's `{ headers }`
49
+ * arg without requiring the transport to know which runtime it's in.
50
+ */
51
+ type WebSocketConstructor = new (url: string, ...rest: any[]) => WebSocketLike;
52
+ /**
53
+ * Websocket ready states — mirrors the standard WebSocket readyState
54
+ * values as human-readable strings.
55
+ */
56
+ type SocketReadyState = "connecting" | "open" | "closing" | "closed";
57
+ /**
58
+ * Framework-agnostic Websocket interface.
59
+ *
60
+ * This allows the adapter to work with any Websocket library:
61
+ * - Browser `WebSocket` via `wrapStandardWebsocket()`
62
+ * - Node.js `ws` library via `wrapNodeWebsocket()`
63
+ * - Bun `ServerWebSocket` via `wrapBunWebsocket()`
64
+ *
65
+ * The interface is intentionally minimal — only the operations the
66
+ * adapter needs are exposed.
67
+ */
68
+ interface Socket {
69
+ /** Send binary or text data through the Websocket. */
70
+ send(data: Uint8Array | string): void;
71
+ /** Close the Websocket connection. */
72
+ close(code?: number, reason?: string): void;
73
+ /** Register a handler for incoming messages (binary or text). */
74
+ onMessage(handler: (data: Uint8Array | string) => void): void;
75
+ /** Register a handler for connection close. */
76
+ onClose(handler: (code: number, reason: string) => void): void;
77
+ /** Register a handler for errors. */
78
+ onError(handler: (error: Error) => void): void;
79
+ /** The current ready state of the Websocket. */
80
+ readonly readyState: SocketReadyState;
81
+ }
82
+ /**
83
+ * Options for handling a new Websocket connection on the server.
84
+ */
85
+ interface WebsocketConnectionOptions {
86
+ /** The Websocket instance, wrapped in the Socket interface. */
87
+ socket: Socket;
88
+ /** Optional peer ID extracted from the upgrade request. */
89
+ peerId?: PeerId;
90
+ /** Optional authentication token from the upgrade request. */
91
+ authToken?: string;
92
+ }
93
+ /**
94
+ * Handle for an active Websocket connection.
95
+ */
96
+ interface WebsocketConnectionHandle {
97
+ /** The peer ID for this connection. */
98
+ readonly peerId: PeerId;
99
+ /** The channel ID for this connection. */
100
+ readonly channelId: number;
101
+ /** Close the connection. */
102
+ close(code?: number, reason?: string): void;
103
+ }
104
+ /**
105
+ * Result of handling a Websocket connection on the server.
106
+ */
107
+ interface WebsocketConnectionResult {
108
+ /** The connection handle for managing this peer. */
109
+ connection: WebsocketConnectionHandle;
110
+ /** Call this to start processing messages. */
111
+ start(): void;
112
+ }
113
+ /**
114
+ * Discriminated union describing why a Websocket connection was lost.
115
+ */
116
+ type DisconnectReason = {
117
+ type: "intentional";
118
+ } | {
119
+ type: "error";
120
+ error: Error;
121
+ } | {
122
+ type: "closed";
123
+ code: number;
124
+ reason: string;
125
+ } | {
126
+ type: "max-retries-exceeded";
127
+ attempts: number;
128
+ } | {
129
+ type: "not-started";
130
+ };
131
+ /**
132
+ * All possible states of the Websocket client.
133
+ *
134
+ * State machine transitions:
135
+ * ```
136
+ * disconnected → connecting → connected → ready
137
+ * ↓ ↓ ↓
138
+ * reconnecting ← ─ ┴ ─ ─ ─ ─ ┘
139
+ * ↓
140
+ * connecting (retry)
141
+ * ↓
142
+ * disconnected (max retries)
143
+ * ```
144
+ */
145
+ type WebsocketClientState = {
146
+ status: "disconnected";
147
+ reason?: DisconnectReason;
148
+ } | {
149
+ status: "connecting";
150
+ attempt: number;
151
+ } | {
152
+ status: "connected";
153
+ } | {
154
+ status: "ready";
155
+ } | {
156
+ status: "reconnecting";
157
+ attempt: number;
158
+ nextAttemptMs: number;
159
+ };
160
+ /**
161
+ * A state transition event for websocket client states.
162
+ * Specialized from the generic `StateTransition<S>`.
163
+ */
164
+ type WebsocketClientStateTransition = StateTransition<WebsocketClientState>;
165
+ /**
166
+ * Listener for websocket client state transitions.
167
+ * Specialized from the generic `TransitionListener<S>`.
168
+ */
169
+ type TransitionListener$1 = TransitionListener<WebsocketClientState>;
170
+ /**
171
+ * Wrap a standard `WebSocket` (browser or Node.js `ws` via `ws` package
172
+ * in `WebSocket`-compatible mode) into the `Socket` interface.
173
+ *
174
+ * Handles `ArrayBuffer`, `Blob`, and string messages.
175
+ */
176
+ declare function wrapStandardWebsocket(ws: WebSocket): Socket;
177
+ /**
178
+ * The minimal interface we need from the Node.js `ws` library's `WebSocket`.
179
+ *
180
+ * Using a structural type rather than importing `ws` — consumers provide
181
+ * the actual `ws` instance, we just need these methods.
182
+ */
183
+ interface NodeWebsocketLike {
184
+ send(data: Uint8Array | string): void;
185
+ close(code?: number, reason?: string): void;
186
+ on(event: "message", handler: (data: Buffer | ArrayBuffer | string, isBinary: boolean) => void): void;
187
+ on(event: "close", handler: (code: number, reason: Buffer) => void): void;
188
+ on(event: "error", handler: (error: Error) => void): void;
189
+ readyState: number;
190
+ }
191
+ /**
192
+ * Wrap a Node.js `ws` library WebSocket into the `Socket` interface.
193
+ *
194
+ * Handles `Buffer` → `Uint8Array` conversion for binary messages.
195
+ */
196
+ declare function wrapNodeWebsocket(ws: NodeWebsocketLike): Socket;
197
+ //#endregion
198
+ export { wrapStandardWebsocket as _, SocketReadyState as a, WebSocketConstructor as c, WebsocketClientState as d, WebsocketClientStateTransition as f, wrapNodeWebsocket as g, WebsocketConnectionResult as h, Socket as i, WebSocketLike as l, WebsocketConnectionOptions as m, NodeWebsocketLike as n, TransitionListener$1 as o, WebsocketConnectionHandle as p, READY_STATE as r, WebSocketCloseEvent as s, DisconnectReason as t, WebSocketMessageEvent as u };
199
+ //# sourceMappingURL=types-CJAcr1Df.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-CJAcr1Df.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;AAyBA;;;cAAa,WAAA;EAAA;;;;;;UAYI,qBAAA;EAAA,SACN,IAAA,WAAe,WAAA;AAAA;;UAIT,mBAAA;EAAA,SACN,IAAA;EAAA,SACA,MAAA;AAAA;;;AAkBX;;;;;;;;;UAAiB,aAAA;EAAA,SACN,UAAA;EACT,UAAA;EACA,IAAA,CAAK,IAAA,WAAe,WAAA;EACpB,KAAA,CAAM,IAAA,WAAe,MAAA;EACrB,gBAAA,CAAiB,IAAA,UAAc,QAAA,GAAW,KAAA;EAC1C,mBAAA,CAAoB,IAAA,UAAc,QAAA,GAAW,KAAA;AAAA;;;;;;AAW/C;;;KAAY,oBAAA,QACV,GAAA,aACG,IAAA,YACA,aAAA;;;;;KAUO,gBAAA;AAAZ;;;;;AAiBA;;;;;;AAjBA,UAiBiB,MAAA;EAiBsB;EAfrC,IAAA,CAAK,IAAA,EAAM,UAAA;EAAX;EAGA,KAAA,CAAM,IAAA,WAAe,MAAA;EAHhB;EAML,SAAA,CAAU,OAAA,GAAU,IAAA,EAAM,UAAA;EAHpB;EAMN,OAAA,CAAQ,OAAA,GAAU,IAAA,UAAc,MAAA;EAHhC;EAMA,OAAA,CAAQ,OAAA,GAAU,KAAA,EAAO,KAAA;EANL;EAAA,SASX,UAAA,EAAY,gBAAA;AAAA;;;;UAUN,0BAAA;EAbU;EAezB,MAAA,EAAQ,MAAA;EAfA;EAkBR,MAAA,GAAS,MAAA;EAfY;EAkBrB,SAAA;AAAA;AARF;;;AAAA,UAciB,yBAAA;EAZf;EAAA,SAcS,MAAA,EAAQ,MAAA;EAXjB;EAAA,SAcS,SAAA;EAXT;EAcA,KAAA,CAAM,IAAA,WAAe,MAAA;AAAA;AARvB;;;AAAA,UAciB,yBAAA;EAZN;EAcT,UAAA,EAAY,yBAAA;EAXH;EAcT,KAAA;AAAA;;;;KAUU,gBAAA;EACN,IAAA;AAAA;EACA,IAAA;EAAe,KAAA,EAAO,KAAA;AAAA;EACtB,IAAA;EAAgB,IAAA;EAAc,MAAA;AAAA;EAC9B,IAAA;EAA8B,QAAA;AAAA;EAC9B,IAAA;AAAA;;;;;;;;;;;AAoBN;;;;KAAY,oBAAA;EACN,MAAA;EAAwB,MAAA,GAAS,gBAAA;AAAA;EACjC,MAAA;EAAsB,OAAA;AAAA;EACtB,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAAwB,OAAA;EAAiB,aAAA;AAAA;;;AAa/C;;KAPY,8BAAA,GACV,eAAA,CAAgB,oBAAA;;;AAkBlB;;KAZY,oBAAA,GAAqB,kBAAA,CAA0B,oBAAA;;;;;;;iBAY3C,qBAAA,CAAsB,EAAA,EAAI,SAAA,GAAY,MAAA;;;;;;;UAkErC,iBAAA;EACf,IAAA,CAAK,IAAA,EAAM,UAAA;EACX,KAAA,CAAM,IAAA,WAAe,MAAA;EACrB,EAAA,CACE,KAAA,aACA,OAAA,GAAU,IAAA,EAAM,MAAA,GAAS,WAAA,WAAsB,QAAA;EAEjD,EAAA,CAAG,KAAA,WAAgB,OAAA,GAAU,IAAA,UAAc,MAAA,EAAQ,MAAA;EACnD,EAAA,CAAG,KAAA,WAAgB,OAAA,GAAU,KAAA,EAAO,KAAA;EACpC,UAAA;AAAA;;;;;;iBAQc,iBAAA,CAAkB,EAAA,EAAI,iBAAA,GAAoB,MAAA"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kyneta/websocket-transport",
3
- "version": "1.3.0",
4
- "description": "Websocket network adapter for @kyneta/exchange — client, server, and Bun integration",
3
+ "version": "1.4.0",
4
+ "description": "Websocket network adapter for @kyneta/exchange — browser, server, and Bun integration",
5
5
  "author": "Duane Johnson",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -18,9 +18,9 @@
18
18
  "src"
19
19
  ],
20
20
  "exports": {
21
- "./client": {
22
- "types": "./dist/client.d.ts",
23
- "import": "./dist/client.js"
21
+ "./browser": {
22
+ "types": "./dist/browser.d.ts",
23
+ "import": "./dist/browser.js"
24
24
  },
25
25
  "./server": {
26
26
  "types": "./dist/server.d.ts",
@@ -33,24 +33,24 @@
33
33
  "./src/*": "./src/*"
34
34
  },
35
35
  "peerDependencies": {
36
- "@kyneta/transport": "^1.3.0",
37
- "@kyneta/machine": "^1.3.0",
38
- "@kyneta/wire": "^1.3.0"
36
+ "@kyneta/machine": "^1.4.0",
37
+ "@kyneta/transport": "^1.4.0",
38
+ "@kyneta/wire": "^1.4.0"
39
39
  },
40
40
  "devDependencies": {
41
41
  "@types/node": "^22",
42
42
  "bun-types": "latest",
43
- "tsup": "^8.5.0",
43
+ "tsdown": "^0.21.9",
44
44
  "typescript": "^5.9.2",
45
45
  "vitest": "^4.0.17",
46
- "@kyneta/exchange": "^1.3.0",
47
- "@kyneta/transport": "^1.3.0",
48
- "@kyneta/schema": "^1.3.0",
49
- "@kyneta/wire": "^1.3.0",
50
- "@kyneta/machine": "^1.3.0"
46
+ "@kyneta/exchange": "^1.4.0",
47
+ "@kyneta/schema": "^1.4.0",
48
+ "@kyneta/transport": "^1.4.0",
49
+ "@kyneta/wire": "^1.4.0",
50
+ "@kyneta/machine": "^1.4.0"
51
51
  },
52
52
  "scripts": {
53
- "build": "tsup",
53
+ "build": "tsdown",
54
54
  "test": "verify logic",
55
55
  "verify": "verify"
56
56
  }
@@ -0,0 +1,167 @@
1
+ // client-transport.test — unit tests for the websocket client transport's
2
+ // constructor injection and header-passing behavior.
3
+ //
4
+ // These tests verify two properties:
5
+ // 1. The transport uses the caller-provided WebSocket constructor.
6
+ // 2. When `headers` are provided, they're passed as `{ headers }` in the
7
+ // second argument. When absent, the constructor is called with just the URL.
8
+
9
+ import type { PeerIdentityDetails, TransportContext } from "@kyneta/transport"
10
+ import { describe, expect, it, vi } from "vitest"
11
+ import { WebsocketClientTransport } from "../client-transport.js"
12
+ import type { WebSocketConstructor, WebSocketLike } from "../types.js"
13
+
14
+ // ---------------------------------------------------------------------------
15
+ // Mock WebSocket
16
+ // ---------------------------------------------------------------------------
17
+
18
+ interface MockCall {
19
+ url: string
20
+ rest: any[]
21
+ }
22
+
23
+ /**
24
+ * Create a mock WebSocket class that records constructor invocations
25
+ * and implements WebSocketLike with no-op methods.
26
+ */
27
+ function createMockWebSocketClass() {
28
+ const calls: MockCall[] = []
29
+
30
+ const MockWebSocket = vi.fn(function (
31
+ this: WebSocketLike,
32
+ url: string,
33
+ ...rest: any[]
34
+ ) {
35
+ calls.push({ url, rest })
36
+ ;(this as any).readyState = 0
37
+ ;(this as any).binaryType = "blob"
38
+ ;(this as any).send = vi.fn()
39
+ ;(this as any).close = vi.fn()
40
+ ;(this as any).addEventListener = vi.fn()
41
+ ;(this as any).removeEventListener = vi.fn()
42
+ }) as unknown as WebSocketConstructor
43
+
44
+ return { MockWebSocket, calls }
45
+ }
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // Transport lifecycle helpers
49
+ // ---------------------------------------------------------------------------
50
+
51
+ const testIdentity: PeerIdentityDetails = {
52
+ peerId: "test-peer-123",
53
+ name: "Test Peer",
54
+ type: "user",
55
+ }
56
+
57
+ function createTransportContext(
58
+ overrides: Partial<TransportContext> = {},
59
+ ): TransportContext {
60
+ return {
61
+ identity: testIdentity,
62
+ onChannelReceive: vi.fn(),
63
+ onChannelAdded: vi.fn(),
64
+ onChannelRemoved: vi.fn(),
65
+ onChannelEstablish: vi.fn(),
66
+ ...overrides,
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Initialize and start a WebsocketClientTransport through the full
72
+ * Transport lifecycle so the program's "create-websocket" effect fires.
73
+ */
74
+ async function startTransport(transport: WebsocketClientTransport) {
75
+ const ctx = createTransportContext()
76
+ transport._initialize(ctx)
77
+ await transport._start()
78
+ }
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // Tests
82
+ // ---------------------------------------------------------------------------
83
+
84
+ describe("WebsocketClientTransport — constructor injection", () => {
85
+ it("calls the provided WebSocket constructor with the URL", async () => {
86
+ const { MockWebSocket, calls } = createMockWebSocketClass()
87
+
88
+ const transport = new WebsocketClientTransport({
89
+ url: "ws://localhost:9999/ws",
90
+ WebSocket: MockWebSocket,
91
+ reconnect: { enabled: false },
92
+ })
93
+
94
+ await startTransport(transport)
95
+
96
+ expect(calls).toHaveLength(1)
97
+ expect(calls[0]!.url).toBe("ws://localhost:9999/ws")
98
+ })
99
+
100
+ it("resolves URL function with peerId before passing to constructor", async () => {
101
+ const { MockWebSocket, calls } = createMockWebSocketClass()
102
+
103
+ const transport = new WebsocketClientTransport({
104
+ url: peerId => `ws://localhost:9999/ws/${peerId}`,
105
+ WebSocket: MockWebSocket,
106
+ reconnect: { enabled: false },
107
+ })
108
+
109
+ await startTransport(transport)
110
+
111
+ expect(calls).toHaveLength(1)
112
+ expect(calls[0]!.url).toBe(`ws://localhost:9999/ws/${testIdentity.peerId}`)
113
+ })
114
+ })
115
+
116
+ describe("WebsocketClientTransport — header passing", () => {
117
+ it("passes { headers } as second arg when headers are non-empty", async () => {
118
+ const headers = {
119
+ Authorization: "Bearer test-token",
120
+ "X-Custom": "value",
121
+ }
122
+ const { MockWebSocket, calls } = createMockWebSocketClass()
123
+
124
+ const transport = new WebsocketClientTransport({
125
+ url: "ws://localhost:9999/ws",
126
+ WebSocket: MockWebSocket,
127
+ headers,
128
+ reconnect: { enabled: false },
129
+ })
130
+
131
+ await startTransport(transport)
132
+
133
+ expect(calls).toHaveLength(1)
134
+ expect(calls[0]!.rest).toEqual([{ headers }])
135
+ })
136
+
137
+ it("omits second arg when headers are not provided", async () => {
138
+ const { MockWebSocket, calls } = createMockWebSocketClass()
139
+
140
+ const transport = new WebsocketClientTransport({
141
+ url: "ws://localhost:9999/ws",
142
+ WebSocket: MockWebSocket,
143
+ reconnect: { enabled: false },
144
+ })
145
+
146
+ await startTransport(transport)
147
+
148
+ expect(calls).toHaveLength(1)
149
+ expect(calls[0]!.rest).toEqual([])
150
+ })
151
+
152
+ it("omits second arg when headers is an empty object", async () => {
153
+ const { MockWebSocket, calls } = createMockWebSocketClass()
154
+
155
+ const transport = new WebsocketClientTransport({
156
+ url: "ws://localhost:9999/ws",
157
+ WebSocket: MockWebSocket,
158
+ headers: {},
159
+ reconnect: { enabled: false },
160
+ })
161
+
162
+ await startTransport(transport)
163
+
164
+ expect(calls).toHaveLength(1)
165
+ expect(calls[0]!.rest).toEqual([])
166
+ })
167
+ })
@@ -1,7 +1,10 @@
1
- // client — barrel export for @kyneta/websocket-network-adapter/client.
1
+ // browser — barrel export for @kyneta/websocket-transport/browser.
2
2
  //
3
- // This is the client-side entry point. It exports everything needed
4
- // to create a Websocket client adapter for browser or service connections.
3
+ // This is the browser-side entry point. It exports everything needed
4
+ // to create a Websocket client transport for browser-to-server connections.
5
+ //
6
+ // Service-to-service connections (with headers) are in `./server`.
7
+ // The `wrapStandardWebsocket` wrapper is a server-side concern — use `./server`.
5
8
 
6
9
  // ---------------------------------------------------------------------------
7
10
  // Client program (pure Mealy machine)
@@ -15,19 +18,14 @@ export {
15
18
  } from "./client-program.js"
16
19
 
17
20
  // ---------------------------------------------------------------------------
18
- // Client transport + factory functions
21
+ // Client transport + factory function
19
22
  // ---------------------------------------------------------------------------
20
23
 
21
24
  export {
22
- createServiceWebsocketClient,
23
25
  createWebsocketClient,
24
26
  DEFAULT_FRAGMENT_THRESHOLD,
25
- type DisconnectReason,
26
- type ServiceWebsocketClientOptions,
27
27
  type WebsocketClientLifecycleEvents,
28
28
  type WebsocketClientOptions,
29
- type WebsocketClientState,
30
- type WebsocketClientStateTransition,
31
29
  WebsocketClientTransport,
32
30
  } from "./client-transport.js"
33
31
 
@@ -36,9 +34,16 @@ export {
36
34
  // ---------------------------------------------------------------------------
37
35
 
38
36
  export type {
37
+ DisconnectReason,
39
38
  Socket,
40
39
  SocketReadyState,
41
40
  TransitionListener,
41
+ WebSocketCloseEvent,
42
+ WebSocketConstructor,
43
+ WebSocketLike,
44
+ WebSocketMessageEvent,
45
+ WebsocketClientState,
46
+ WebsocketClientStateTransition,
42
47
  } from "./types.js"
43
48
 
44
- export { wrapStandardWebsocket } from "./types.js"
49
+ export { READY_STATE } from "./types.js"
@@ -1,4 +1,4 @@
1
- // bun-websocket — Bun-specific Websocket wrapper for @kyneta/websocket-network-adapter.
1
+ // bun-websocket — Bun-specific Websocket wrapper for @kyneta/websocket-transport.
2
2
  //
3
3
  // Provides a wrapper to adapt Bun's ServerWebSocket to the Socket interface
4
4
  // expected by WebsocketServerTransport.
@@ -50,8 +50,8 @@ export type BunWebsocketData = {
50
50
  *
51
51
  * @example
52
52
  * ```typescript
53
- * import { WebsocketServerTransport } from "@kyneta/websocket-network-adapter/server"
54
- * import { wrapBunWebsocket, type BunWebsocketData } from "@kyneta/websocket-network-adapter/bun"
53
+ * import { WebsocketServerTransport } from "@kyneta/websocket-transport/server"
54
+ * import { wrapBunWebsocket, type BunWebsocketData } from "@kyneta/websocket-transport/bun"
55
55
  *
56
56
  * const serverAdapter = new WebsocketServerTransport()
57
57
  *
@@ -123,8 +123,8 @@ export function wrapBunWebsocket(
123
123
  *
124
124
  * @example
125
125
  * ```typescript
126
- * import { WebsocketServerTransport } from "@kyneta/websocket-network-adapter/server"
127
- * import { createBunWebsocketHandlers, type BunWebsocketData } from "@kyneta/websocket-network-adapter/bun"
126
+ * import { WebsocketServerTransport } from "@kyneta/websocket-transport/server"
127
+ * import { createBunWebsocketHandlers, type BunWebsocketData } from "@kyneta/websocket-transport/bun"
128
128
  *
129
129
  * const serverAdapter = new WebsocketServerTransport()
130
130
  *
package/src/bun.ts CHANGED
@@ -1,4 +1,4 @@
1
- // bun — barrel export for @kyneta/websocket-network-adapter/bun.
1
+ // bun — barrel export for @kyneta/websocket-transport/bun.
2
2
  //
3
3
  // This is the Bun-specific entry point. It exports everything needed
4
4
  // to integrate WebsocketServerTransport with Bun's WebSocket API.