fix(bun): add ws error handler for Node/Deno parity; hoist TextDecoder

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-09 22:00:23 -05:00
1 parent 3d21117a07
commit 82824e5f6d
1 file changed
+9 -1
+9 -1
View File
@@ -16,6 +16,7 @@ interface BunWebSocketHandler {
open?(ws: BunServerWebSocket): void;
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
close?(ws: BunServerWebSocket, code: number, reason: string): void;
error?(ws: BunServerWebSocket, error?: unknown): void;
}
interface BunServer {
port: number;
@@ -32,6 +33,8 @@ interface BunServeOptions {
type BunServeShortOptions = { port?: number; hostname?: string };
declare const Bun: { serve(options: BunServeOptions): BunServer };
const decoder = new TextDecoder();
/** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */
interface BunConnData {
wsReq: WsRequest;
@@ -119,13 +122,18 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServer {
message(ws, message) {
const { inbound } = ws.data as BunConnData;
// decode binary to UTF-8 to match Node's Buffer.toString() (cross-adapter parity)
inbound.push(typeof message === 'string' ? message : new TextDecoder().decode(message));
inbound.push(typeof message === 'string' ? message : decoder.decode(message));
},
close(ws) {
const { inbound, ac } = ws.data as BunConnData;
inbound.close();
ac.abort();
},
error(ws) {
const { inbound, ac } = ws.data as BunConnData;
inbound.fail(new Error('websocket error'));
ac.abort();
},
},
});
}