Open History to see the last commit
1/**
2 * Node.js socket constructors and layers for Effect sockets.
3 *
4 * This module re-exports the shared Node socket support for TCP connections,
5 * Unix domain socket connections, and Node `Duplex` streams. It also provides
6 * WebSocket constructor layers: one that uses `globalThis.WebSocket` when
7 * present and falls back to `ws`, one that always uses `ws`, and one that
8 * creates a `Socket.Socket` layer for a WebSocket URL.
9 *
10 * @since 4.0.0
11 */
12import { NodeWS as WS } from "@effect/platform-node-shared/NodeSocket"
13import type * as Duration from "effect/Duration"
14import type * as Effect from "effect/Effect"
15import { flow } from "effect/Function"
16import * as Layer from "effect/Layer"
17import * as Socket from "effect/unstable/socket/Socket"
18
19/**
20 * @since 4.0.0
21 */
22export * from "@effect/platform-node-shared/NodeSocket"
23
24/**
25 * Provides a `Socket.WebSocketConstructor`, using `globalThis.WebSocket` when
26 * available and falling back to the `ws` package otherwise.
27 *
28 * @category layers
29 * @since 4.0.0
30 */
31export const layerWebSocketConstructor: Layer.Layer<
32 Socket.WebSocketConstructor
33> = Layer.sync(Socket.WebSocketConstructor)(() => {
34 if ("WebSocket" in globalThis) {
35 return (url, protocols) => new globalThis.WebSocket(url, protocols)
36 }
37 return (url, protocols) => new WS.WebSocket(url, protocols) as unknown as globalThis.WebSocket
38})
39
40/**
41 * Provides a `Socket.WebSocketConstructor` backed explicitly by the `ws`
42 * package.
43 *
44 * @category layers
45 * @since 4.0.0
46 */
47export const layerWebSocketConstructorWS: Layer.Layer<
48 Socket.WebSocketConstructor
49> = Layer.succeed(Socket.WebSocketConstructor)(
50 (url, protocols) => new WS.WebSocket(url, protocols) as unknown as globalThis.WebSocket
51)
52
53/**
54 * Creates a `Socket.Socket` layer for a WebSocket URL using the Node WebSocket
55 * constructor layer, honoring protocol, open-timeout, and close-code error
56 * options.
57 *
58 * @category layers
59 * @since 4.0.0
60 */
61export const layerWebSocket: (
62 url: string | Effect.Effect<string>,
63 options?: {
64 readonly closeCodeIsError?: ((code: number) => boolean) | undefined
65 readonly openTimeout?: Duration.Input | undefined
66 readonly protocols?: string | Array<string> | undefined
67 } | undefined
68) => Layer.Layer<Socket.Socket, never, never> = flow(
69 Socket.makeWebSocket,
70 Layer.effect(Socket.Socket),
71 Layer.provide(layerWebSocketConstructor)
72)