The best way to control Claude Code, Codex and more from any computer or phone

main
ts 79 lines 2.61 KB
Raw
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 * @stability unstable
10 * @since 4.0.0
11 */
12 import type * as Duration from "effect/Duration"
13 import type { Effect } from "effect/Effect"
14 import { flow } from "effect/Function"
15 import * as Layer from "effect/Layer"
16 import * as Socket from "effect/socket/Socket"
17
18 /**
19 * @since 4.0.0
20 */
21 export * from "@effect/platform-node-shared/NodeSocket"
22
23 /**
24 * Provides a `Socket.WebSocketConstructor` backed by Bun's global
25 * `WebSocket` implementation, supporting handshake headers and subprotocols
26 * together in client options objects.
27 *
28 * @stability unstable
29 * @category layers
30 * @since 4.0.0
31 */
32 export const layerWebSocketConstructor: Layer.Layer<
33 Socket.WebSocketConstructor
34 > = Layer.succeed(Socket.WebSocketConstructor)(
35 (url, options) => {
36 if (options === undefined || typeof options === "string" || Array.isArray(options)) {
37 return new globalThis.WebSocket(url, options)
38 }
39 // Bun accepts `WebSocketOptions`, but `bun-types` selects the DOM
40 // overload when `lib.dom` is loaded and hides those constructor options.
41 const WebSocket = globalThis.WebSocket as unknown as {
42 new(
43 url: string,
44 options: {
45 protocols?: Array<string> | undefined
46 headers?: Readonly<Record<string, string>> | undefined
47 }
48 ): globalThis.WebSocket
49 }
50 return new WebSocket(url, {
51 // Bun requires a sequence for `protocols` in its options object.
52 protocols: typeof options.protocols === "string" ? [options.protocols] : options.protocols,
53 headers: options.headers
54 })
55 }
56 )
57
58 /**
59 * Creates a `Socket.Socket` layer for a WebSocket URL using Bun's global
60 * `WebSocket` constructor, honoring protocol, handshake-header, open-timeout, and
61 * high-water-mark options.
62 *
63 * @stability unstable
64 * @category layers
65 * @since 4.0.0
66 */
67 export const layerWebSocket: (
68 url: string | Effect<string>,
69 options?: {
70 readonly openTimeout?: Duration.Input | undefined
71 readonly protocols?: string | Array<string> | undefined
72 readonly headers?: Readonly<Record<string, string>> | undefined
73 readonly highWaterMark?: number | undefined
74 } | undefined
75 ) => Layer.Layer<Socket.Socket, never, never> = flow(
76 Socket.makeWebSocket,
77 Layer.effect(Socket.Socket),
78 Layer.provide(layerWebSocketConstructor)
79 )