@hyperfrontend/immutable-api-utils/built-in-copy/websocket

websocket

Locked, prototype-pollution-resistant copy of the global WebSocket constructor.

A factory wrapping WebSocket is captured at module-load time and frozen into a tamper-proof namespace, so socket construction stays trustworthy even if the global is later patched. Effective only when imported before any untrusted code has had a chance to mutate the prototype chain.

On a runtime without a WebSocket global (Node.js before 22) the module still imports: the ready-state constants hold the values the WebSocket standard fixes, and createWebSocket throws a TypeError.

API Reference§

ƒ Functions

§function

createWebSocket(url: string | URL, protocols?: string | string[]): WebSocket

(Safe copy) Creates a new WebSocket using the captured WebSocket constructor. Use this instead of new WebSocket().
Parameters
NameTypeDescription
§url
string | URLThe URL to connect to.
§protocols?
string | string[]Optional sub-protocol string or array of strings.
Returns
WebSocket
A new WebSocket instance.
Example

Creating WebSocket connection

const socket = createWebSocket('wss://api.example.com/stream')
socket.onmessage = (event) => console.log(event.data)

● Variables

§type

CONNECTING

WebSocket ready state constants (safe copies).
§type

WebSocket

(Safe copy) Namespace object containing all WebSocket utilities. Note: Importing this imports all methods in this namespace (no tree-shaking).