Skip to content

Bun's WebSocket client implementation doesn't correctly handle close events #3392

@vladfrangu

Description

@vladfrangu

What version of Bun is running?

0.6.9

What platform is your computer?

Darwin 23.0.0 arm64 arm

What steps can reproduce the bug?

I've attached the code that reproduces this issue. I've been encountering this while trying to make discord.js use bun's (and deno's) globally available WebSocket and fetch implementations (which is hopefully almost done once this gets solved 👀).

To reproduce this, run the same code in bun and deno. Deno accurately emits a Close event, whereas bun emits a message event followed by a close event with the wrong close code (which is the main problem)

Code to test
/// <reference types="DOM" />

const ws = new WebSocket('wss://gateway.discord.gg');

ws.onmessage = (event) => {
	console.log(event);
};

ws.onerror = (event) => {
	console.error(event);
};

ws.onclose = (event) => {
	console.log(event);
};

ws.onopen = () => {
	ws.send(
		JSON.stringify({
			op: 2,
			d: {
				token: 'MTEyMjE3MzcxNjYzODIwODAwMA.Go0ZrX.owo',
				intents: 0,
				shard: [0, 16],
				properties: {
					os: 'macos',
					browser: 'owo',
					device: 'owo',
				},
			},
		}),
	);
};

What is the expected behavior?

Bun's WebSocket behavior should more-less match node's ws and deno's WebSocket when it comes to close codes

What do you see instead?

https://gist.github.com/vladfrangu/31afb281caee8de06fe73655b1c9b408

Additional information

I'm aware that, for what it's worth, Bun now supports djs natively (since 0.6.3 iirc), however I feel like using the native WebSocket provided by the runtime (where applicable) is the more optimal choice, especially for performance

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions