| 1 | /** |
| 2 | * Bun platform socket entry point for Effect sockets. |
| 3 | * |
| 4 | * This module re-exports the shared Node socket constructors for TCP clients, |
| 5 | * Unix domain socket clients, and adapters from existing Node `Duplex` streams. |
| 6 | * It also provides Bun WebSocket layers using `globalThis.WebSocket`, including |
| 7 | * a constructor layer and a `Socket.Socket` layer for a WebSocket URL. |
| 8 | * |
| 9 | * @since 4.0.0 |
| 10 | */ |
| 11 | import type * as Duration from "effect/Duration" |
| 12 | import type { Effect } from "effect/Effect" |
| 13 | import { flow } from "effect/Function" |
| 14 | import * as Layer from "effect/Layer" |
| 15 | import * as Socket from "effect/socket/Socket" |
| 16 | |
| 17 | /** |
| 18 | * @since 4.0.0 |
| 19 | */ |
| 20 | export * from "@effect/platform-node-shared/NodeSocket" |
| 21 | |
| 22 | /** |
| 23 | * Provides a `Socket.WebSocketConstructor` backed by Bun's global |
| 24 | * `WebSocket` implementation. |
| 25 | * |
| 26 | * @category layers |
| 27 | * @since 4.0.0 |
| 28 | */ |
| 29 | export const layerWebSocketConstructor: Layer.Layer< |
| 30 | Socket.WebSocketConstructor |
| 31 | > = Layer.succeed(Socket.WebSocketConstructor)( |
| 32 | (url, options) => |
| 33 | // Bun accepts `WebSocketOptions`, but `bun-types` selects the DOM overload |
| 34 | // when `lib.dom` is loaded and hides those constructor options. |
| 35 | new globalThis.WebSocket(url, options as string | Array<string> | undefined) |
| 36 | ) |
| 37 | |
| 38 | /** |
| 39 | * Creates a `Socket.Socket` layer for a WebSocket URL using Bun's global |
| 40 | * `WebSocket` constructor, honoring protocol, open-timeout, and |
| 41 | * high-water-mark options. |
| 42 | * |
| 43 | * @category layers |
| 44 | * @since 4.0.0 |
| 45 | */ |
| 46 | export const layerWebSocket: ( |
| 47 | url: string | Effect<string>, |
| 48 | options?: { |
| 49 | readonly openTimeout?: Duration.Input | undefined |
| 50 | readonly protocols?: string | Array<string> | undefined |
| 51 | readonly highWaterMark?: number | undefined |
| 52 | } | undefined |
| 53 | ) => Layer.Layer<Socket.Socket, never, never> = flow( |
| 54 | Socket.makeWebSocket, |
| 55 | Layer.effect(Socket.Socket), |
| 56 | Layer.provide(layerWebSocketConstructor) |
| 57 | ) |