Open History to see the last commit
1/**
2 * Native Deno implementation of the Effect `HttpServer`.
3 *
4 * `Deno.serve` can only upgrade requests to WebSocket, so other HTTP/1.1
5 * upgrades fail. Serve them with `NodeHttpServer` from
6 * `@effect/platform-node`, which runs on Deno's `node:http`.
7 *
8 * Over HTTP/1.1, `Deno.serve` can stop delivering the request body once the
9 * handler has returned a streamed response, so a handler that streams its
10 * response while still reading the request payload can stall
11 * (denoland/deno#36966).
12 *
13 * `Deno.serve` negotiates HTTP/2 on its own: over TLS with browsers, and in
14 * cleartext with clients that request it. Deno 2.8.3 to 2.9.2 panic and exit
15 * when an HTTP/2 client cancels a request while its handler is still running
16 * (denoland/deno#36053), so this package requires Deno 2.9.3 or newer.
17 *
18 * @stability unstable
19 * @since 4.0.0
20 */
21import * as Channel from "effect/Channel"
22import * as Config from "effect/Config"
23import type { ConfigError } from "effect/Config"
24import * as Context from "effect/Context"
25import * as Duration from "effect/Duration"
26import * as Effect from "effect/Effect"
27import * as Fiber from "effect/Fiber"
28import type * as FileSystem from "effect/FileSystem"
29import { constVoid, flow } from "effect/Function"
30import * as Cookies from "effect/http/Cookies"
31import * as Etag from "effect/http/Etag"
32import * as FetchHttpClient from "effect/http/FetchHttpClient"
33import * as Headers from "effect/http/Headers"
34import type * as HttpBody from "effect/http/HttpBody"
35import type { HttpClient } from "effect/http/HttpClient"
36import * as HttpEffect from "effect/http/HttpEffect"
37import * as IncomingMessage from "effect/http/HttpIncomingMessage"
38import type { HttpMethod } from "effect/http/HttpMethod"
39import type { HttpPlatform } from "effect/http/HttpPlatform"
40import * as Server from "effect/http/HttpServer"
41import * as Error from "effect/http/HttpServerError"
42import * as ServerRequest from "effect/http/HttpServerRequest"
43import * as ServerResponse from "effect/http/HttpServerResponse"
44import type * as Multipart from "effect/http/Multipart"
45import * as UrlParams from "effect/http/UrlParams"
46import * as Inspectable from "effect/Inspectable"
47import * as Layer from "effect/Layer"
48import * as NetAddress from "effect/net/NetAddress"
49import * as Option from "effect/Option"
50import type * as Path from "effect/Path"
51import type * as Record from "effect/Record"
52import type * as Schema from "effect/Schema"
53import * as Scope from "effect/Scope"
54import * as Socket from "effect/socket/Socket"
55import * as Stream from "effect/Stream"
56import * as Platform from "./DenoHttpPlatform.ts"
57import * as DenoMultipart from "./DenoMultipart.ts"
58import * as DenoServices from "./DenoServices.ts"
59
60/**
61 * Native Deno TCP, TLS, or Unix serve options managed by the scoped server.
62 *
63 * **Details**
64 *
65 * `signal` and `onError` are omitted because the scope and Effect HTTP handler
66 * own server and failure lifecycles. Server constructors additionally accept
67 * WebSocket settings that apply to every upgrade; `protocol` therefore cannot
68 * vary per request.
69 *
70 * @stability unstable
71 * @category options
72 * @since 4.0.0
73 */
74export type ServeOptions =
75 | (Omit<Deno.ServeTcpOptions, "signal" | "onError"> & Partial<Deno.TlsCertifiedKeyPem>)
76 | Omit<Deno.ServeUnixOptions, "signal" | "onError">
77
78/**
79 * Creates a scoped native Deno HTTP server.
80 *
81 * @stability unstable
82 * @category constructors
83 * @since 4.0.0
84 */
85export const make = Effect.fnUntraced(function*(
86 options: ServeOptions & {
87 readonly disablePreemptiveShutdown?: boolean | undefined
88 readonly gracefulShutdownTimeout?: Duration.Input | undefined
89 readonly websocket?: Deno.UpgradeWebSocketOptions | undefined
90 }
91) {
92 const scope = yield* Effect.scope
93 type Handler = (request: Request, info: Deno.ServeHandlerInfo<Deno.NetAddr | Deno.UnixAddr>) => Promise<Response>
94 const notFound: Handler = (_request, _info) => Promise.resolve(new Response("not found", { status: 404 }))
95 const handlerStack: Array<Handler> = [notFound]
96 let currentHandler = notFound
97 const {
98 disablePreemptiveShutdown,
99 gracefulShutdownTimeout,
100 websocket,
101 ...serveOptions
102 } = options
103 const server = Deno.serve(
104 serveOptions as Deno.ServeTcpOptions,
105 (request, info) =>
106 request.method === "CONNECT"
107 ? Promise.resolve(new Response(null, { status: 501 }))
108 : currentHandler(request, info)
109 ) as Deno.HttpServer<Deno.NetAddr | Deno.UnixAddr>
110
111 const shutdown = yield* Effect.promise(() => server.shutdown()).pipe(Effect.cached)
112 const preemptiveShutdown = disablePreemptiveShutdown ? Effect.void : Effect.timeoutOrElse(shutdown, {
113 duration: gracefulShutdownTimeout ?? Duration.seconds(20),
114 orElse: () => Effect.void
115 })
116
117 yield* Scope.addFinalizer(scope, shutdown)
118
119 const serverAddress = server.addr
120 const address = yield* (serverAddress.transport === "unix"
121 ? Effect.succeed(NetAddress.unixPathAddress(serverAddress.path))
122 : Effect.fromResult(NetAddress.inetAddressFromIpString(
123 (serverAddress as Deno.NetAddr).hostname,
124 (serverAddress as Deno.NetAddr).port
125 )).pipe(Effect.mapError((cause) => new Error.ServeError({ cause }))))
126
127 return Server.make({
128 address,
129 serve: Effect.fnUntraced(function*(httpApp, middleware) {
130 const parent = yield* Effect.fiber
131 const services = parent.context
132 const serveScope = Context.getUnsafe(services, Scope.Scope)
133 const scope = Scope.forkUnsafe(serveScope, "parallel")
134
135 const httpEffect = HttpEffect.toHandled(httpApp, (request, response) => {
136 const denoRequest = request as DenoServerRequest
137 if (upgradedSources.has(denoRequest.source)) {
138 return Effect.as(cancelResponseBody(response.body), upgradedResponse)
139 }
140 return Effect.matchCauseEffect(makeResponse(request, response, services, scope), {
141 onSuccess: (webResponse) => Effect.sync(() => denoRequest.resolve(webResponse)),
142 // Answer the request without waiting for body cleanup, which may never settle
143 onFailure: (cause) => {
144 denoRequest.resolve(new Response(undefined, { status: 500 }))
145 if (response.body._tag === "Raw" && response.body.body instanceof ReadableStream) {
146 cancelStreamUnsafe(response.body.body)
147 }
148 return Effect.failCause(cause)
149 }
150 })
151 }, middleware)
152
153 function handler(
154 request: Request,
155 info: Deno.ServeHandlerInfo<Deno.NetAddr | Deno.UnixAddr>
156 ): Promise<Response> {
157 return new Promise<Response>((resolve) => {
158 const context = Context.add(
159 services,
160 ServerRequest.HttpServerRequest,
161 new DenoServerRequest(request, info.remoteAddr, resolve, removeHost(request.url), websocket)
162 )
163 const fiber = Fiber.runIn(Effect.runForkWith(context)(httpEffect), scope)
164 request.signal.addEventListener("abort", () => {
165 fiber.interruptUnsafe(parent.id, Error.ClientAbort.annotation)
166 }, { once: true })
167 })
168 }
169
170 yield* Scope.addFinalizerExit(serveScope, () => {
171 const index = handlerStack.lastIndexOf(handler)
172 if (index !== -1) handlerStack.splice(index, 1)
173 currentHandler = handlerStack[handlerStack.length - 1] ?? notFound
174 return preemptiveShutdown
175 })
176 handlerStack.push(handler)
177 currentHandler = handler
178 })
179 })
180})
181
182const makeResponse = Effect.fnUntraced(function*(
183 request: ServerRequest.HttpServerRequest,
184 response: ServerResponse.HttpServerResponse,
185 context: Context.Context<never>,
186 scope: Scope.Scope
187) {
188 if (ServerResponse.omitsBody(response, request.method === "HEAD")) {
189 yield* cancelResponseBody(response.body)
190 return ServerResponse.toWeb(response, { withoutBody: true })
191 }
192 const fields: {
193 headers: globalThis.Headers
194 status?: number
195 statusText?: string
196 } = {
197 headers: new globalThis.Headers(response.headers),
198 status: response.status
199 }
200
201 if (!Cookies.isEmpty(response.cookies)) {
202 for (const header of Cookies.toSetCookieHeaders(response.cookies)) {
203 fields.headers.append("set-cookie", header)
204 }
205 }
206 if (response.statusText !== undefined) fields.statusText = response.statusText
207
208 const body = response.body
209 switch (body._tag) {
210 case "Empty":
211 return new Response(undefined, fields)
212 case "Uint8Array":
213 case "Raw": {
214 if (body.body instanceof Response) {
215 return ServerResponse.toWeb(response)
216 }
217 return new Response(body.body as any, fields)
218 }
219 case "FormData":
220 return new Response(body.formData as any, fields)
221 case "Stream": {
222 // Validate the fields before the stream takes over the request scope, as only reading it would close the scope
223 // oxlint-disable-next-line no-new
224 new Response(new ReadableStream(), fields)
225 const stream = (HttpEffect.scopeTransferToStream(response).body as HttpBody.Stream).stream
226 return new Response(
227 Stream.toReadableStreamWith(
228 // Attach before transforming: startup can suspend. Register the request finalizer before the first pull.
229 Stream.fromChannel(Channel.fromTransform((upstream, streamScope) =>
230 Effect.withFiber((fiber) => {
231 Fiber.runIn(fiber, scope)
232 return Channel.toTransform(stream.channel)(upstream, streamScope)
233 })
234 )),
235 context
236 ),
237 fields
238 )
239 }
240 }
241})
242
243/**
244 * Provides only the native Deno HTTP server.
245 *
246 * @stability unstable
247 * @category layers
248 * @since 4.0.0
249 */
250export const layerServer: (
251 options: ServeOptions & {
252 readonly disablePreemptiveShutdown?: boolean | undefined
253 readonly gracefulShutdownTimeout?: Duration.Input | undefined
254 readonly websocket?: Deno.UpgradeWebSocketOptions | undefined
255 }
256) => Layer.Layer<Server.HttpServer, Error.ServeError> = flow(
257 make,
258 Layer.effect(Server.HttpServer)
259)
260
261/**
262 * Provides Deno HTTP platform services and the standard Deno service set.
263 *
264 * @stability unstable
265 * @category layers
266 * @since 4.0.0
267 */
268export const layerHttpServices: Layer.Layer<HttpPlatform | Etag.Generator | DenoServices.DenoServices> = Layer.mergeAll(
269 Platform.layer,
270 Etag.layerWeak,
271 DenoServices.layer
272)
273
274/**
275 * Provides a native Deno HTTP server together with Deno HTTP services.
276 *
277 * @stability unstable
278 * @category layers
279 * @since 4.0.0
280 */
281export const layer = (
282 options: ServeOptions & {
283 readonly disablePreemptiveShutdown?: boolean | undefined
284 readonly gracefulShutdownTimeout?: Duration.Input | undefined
285 readonly websocket?: Deno.UpgradeWebSocketOptions | undefined
286 }
287): Layer.Layer<Server.HttpServer | HttpPlatform | Etag.Generator | DenoServices.DenoServices, Error.ServeError> =>
288 Layer.mergeAll(layerServer(options), layerHttpServices)
289
290/**
291 * Starts a Deno HTTP server on an ephemeral loopback port for tests.
292 *
293 * @stability unstable
294 * @category testing
295 * @since 4.0.0
296 */
297export const layerTest: Layer.Layer<
298 Server.HttpServer | HttpPlatform | FileSystem.FileSystem | Etag.Generator | Path.Path | HttpClient
299> = Server.layerTestClient.pipe(
300 Layer.provide(FetchHttpClient.layer.pipe(
301 Layer.provide(Layer.succeed(FetchHttpClient.RequestInit)({ keepalive: false }))
302 )),
303 Layer.provideMerge(Layer.orDie(layer({ hostname: "127.0.0.1", port: 0, onListen: () => {} })))
304)
305
306/**
307 * Creates the Deno HTTP server and support-services layer from configurable options.
308 *
309 * @stability unstable
310 * @category layers
311 * @since 4.0.0
312 */
313export const layerConfig = (
314 options: Config.Wrap<
315 ServeOptions & {
316 readonly disablePreemptiveShutdown?: boolean | undefined
317 readonly gracefulShutdownTimeout?: Duration.Input | undefined
318 readonly websocket?: Deno.UpgradeWebSocketOptions | undefined
319 }
320 >
321): Layer.Layer<
322 Server.HttpServer | HttpPlatform | FileSystem.FileSystem | Etag.Generator | Path.Path,
323 ConfigError | Error.ServeError
324> =>
325 Layer.mergeAll(
326 Layer.effect(Server.HttpServer)(Effect.flatMap(Config.unwrap(options), make)),
327 layerHttpServices
328 )
329
330const formDecoder = new TextDecoder("utf-8", { ignoreBOM: true })
331
332class DenoServerRequest extends Inspectable.Class implements ServerRequest.HttpServerRequest {
333 readonly [ServerRequest.TypeId]: typeof ServerRequest.TypeId
334 readonly [IncomingMessage.TypeId]: typeof IncomingMessage.TypeId
335 readonly source: Request
336 readonly remoteAddr: Deno.NetAddr | Deno.UnixAddr
337 readonly url: string
338 readonly websocketOptions: Deno.UpgradeWebSocketOptions | undefined
339 public resolve: (response: Response) => void
340 public headersOverride?: Headers.Headers | undefined
341 private remoteAddressOverride?: Option.Option<string> | undefined
342 private peerAddressOverride?: Option.Option<string> | undefined
343 readonly protocol: "http" | "https" | undefined
344
345 constructor(
346 source: Request,
347 remoteAddr: Deno.NetAddr | Deno.UnixAddr,
348 resolve: (response: Response) => void,
349 url: string,
350 websocketOptions: Deno.UpgradeWebSocketOptions | undefined,
351 headersOverride?: Headers.Headers,
352 remoteAddressOverride?: Option.Option<string>,
353 peerAddressOverride?: Option.Option<string>,
354 protocol?: "http" | "https"
355 ) {
356 super()
357 this[ServerRequest.TypeId] = ServerRequest.TypeId
358 this[IncomingMessage.TypeId] = IncomingMessage.TypeId
359 this.source = source
360 this.remoteAddr = remoteAddr
361 this.resolve = resolve
362 this.url = url
363 this.websocketOptions = websocketOptions
364 this.headersOverride = headersOverride
365 this.remoteAddressOverride = remoteAddressOverride
366 this.peerAddressOverride = peerAddressOverride
367 this.protocol = protocol
368 }
369 toJSON(): unknown {
370 return IncomingMessage.inspect(this, {
371 _id: "HttpServerRequest",
372 method: this.method,
373 url: UrlParams.redactUrl(this.originalUrl)
374 })
375 }
376 modify(options: {
377 readonly url?: string | undefined
378 readonly headers?: Headers.Headers | undefined
379 readonly remoteAddress?: Option.Option<string> | undefined
380 readonly peerAddress?: Option.Option<string> | undefined
381 readonly protocol?: "http" | "https" | undefined
382 }) {
383 return new DenoServerRequest(
384 this.source,
385 this.remoteAddr,
386 this.resolve,
387 options.url ?? this.url,
388 this.websocketOptions,
389 options.headers ?? this.headersOverride,
390 "remoteAddress" in options ? options.remoteAddress : this.remoteAddressOverride,
391 options.peerAddress ?? this.peerAddressOverride,
392 options.protocol ?? this.protocol
393 )
394 }
395 get method(): HttpMethod {
396 return this.source.method.toUpperCase() as HttpMethod
397 }
398 get originalUrl() {
399 return this.source.url
400 }
401 get remoteAddress(): Option.Option<string> {
402 return this.remoteAddressOverride ?? (this.remoteAddr.transport === "tcp"
403 ? Option.some(this.remoteAddr.hostname)
404 : Option.none())
405 }
406 get peerAddress(): Option.Option<string> {
407 return this.peerAddressOverride ?? this.remoteAddress
408 }
409 get headers(): Headers.Headers {
410 if (this.headersOverride === undefined) {
411 const headers = Headers.fromInput(this.source.headers)
412 // Deno builds the URL from the request authority, ahead of Host.
413 // Preserve its raw form; URL.host lowercases names and strips default ports.
414 const host = urlAuthority(this.source.url)
415 this.headersOverride = host === undefined || headers.host === host ? headers : Headers.set(headers, "host", host)
416 }
417 return this.headersOverride
418 }
419
420 private cachedCookies: Record.ReadonlyRecord<string, string> | undefined
421 get cookies() {
422 return this.cachedCookies ??= Cookies.parseHeader(this.headers.cookie ?? "")
423 }
424
425 get stream(): Stream.Stream<Uint8Array, Error.HttpServerError> {
426 return this.source.body
427 ? Stream.fromReadableStream({
428 evaluate: () => this.source.body ?? emptyReadableStream,
429 onError: (cause) =>
430 new Error.HttpServerError({
431 reason: new Error.RequestParseError({ request: this, cause })
432 })
433 })
434 : Stream.fail(
435 new Error.HttpServerError({
436 reason: new Error.RequestParseError({
437 request: this,
438 description: "can not create stream from empty body"
439 })
440 })
441 )
442 }
443
444 private textEffect: Effect.Effect<string, Error.HttpServerError> | undefined
445 get text(): Effect.Effect<string, Error.HttpServerError> {
446 return this.textEffect ??= Effect.map(this.arrayBuffer, (buffer) => new TextDecoder().decode(buffer))
447 }
448 get json(): Effect.Effect<Schema.Json, Error.HttpServerError> {
449 return Effect.flatMap(this.text, (_) =>
450 Effect.try({
451 try: () => JSON.parse(_) as Schema.Json,
452 catch: (cause) =>
453 new Error.HttpServerError({
454 reason: new Error.RequestParseError({ request: this, cause })
455 })
456 }))
457 }
458 get urlParamsBody(): Effect.Effect<UrlParams.UrlParams, Error.HttpServerError> {
459 return Effect.flatMap(this.arrayBuffer, (bytes) =>
460 Effect.try({
461 // A leading "?" is form data; URLSearchParams would drop it as a query prefix.
462 try: () => UrlParams.fromInput(new URLSearchParams(formDecoder.decode(bytes).replace(/^\?/, "%3F"))),
463 catch: (cause) =>
464 new Error.HttpServerError({
465 reason: new Error.RequestParseError({ request: this, cause })
466 })
467 }))
468 }
469
470 private multipartEffect:
471 | Effect.Effect<Multipart.Persisted, Multipart.MultipartError, Scope.Scope | FileSystem.FileSystem | Path.Path>
472 | undefined
473 get multipart(): Effect.Effect<
474 Multipart.Persisted,
475 Multipart.MultipartError,
476 Scope.Scope | FileSystem.FileSystem | Path.Path
477 > {
478 return this.multipartEffect ??= Effect.runSync(Effect.cached(DenoMultipart.persisted(this.source)))
479 }
480 get multipartStream(): Stream.Stream<Multipart.Part, Multipart.MultipartError> {
481 return DenoMultipart.stream(this.source)
482 }
483
484 private arrayBufferEffect: Effect.Effect<ArrayBuffer, Error.HttpServerError> | undefined
485 get arrayBuffer(): Effect.Effect<ArrayBuffer, Error.HttpServerError> {
486 if (this.arrayBufferEffect) return this.arrayBufferEffect
487 this.arrayBufferEffect = Effect.runSync(Effect.cached(
488 // Reuse the Web reader so that MaxBodySize is enforced.
489 Effect.mapError(ServerRequest.fromWeb(this.source).arrayBuffer, (error) => {
490 if (error.reason._tag !== "RequestParseError") return error
491 const { cause, reason } = error.reason
492 return new Error.HttpServerError({
493 reason: new Error.RequestParseError({ request: this, cause, ...(reason && { reason }) })
494 })
495 })
496 ))
497 return this.arrayBufferEffect
498 }
499
500 upgradeWith(
501 options: { readonly headers?: Headers.Input | undefined }
502 ): Effect.Effect<Socket.Socket, Error.HttpServerError> {
503 if (Object.keys(Headers.fromInput(options.headers)).length === 0) return this.upgrade
504 return Effect.fail(
505 new Error.HttpServerError({
506 reason: new Error.InternalError({
507 request: this,
508 description: "WebSocket upgrades do not support custom response headers"
509 })
510 })
511 )
512 }
513
514 get upgrade(): Effect.Effect<Socket.Socket, Error.HttpServerError> {
515 return Effect.flatMap(
516 Effect.try({
517 try: () => Deno.upgradeWebSocket(this.source, this.websocketOptions),
518 catch: (cause) =>
519 new Error.HttpServerError({
520 reason: new Error.RequestParseError({
521 request: this,
522 cause,
523 description: isRawUpgrade(this.source)
524 ? "Deno.serve only supports WebSocket upgrades"
525 : "Not an upgradeable ServerRequest"
526 })
527 })
528 }),
529 (upgrade) => {
530 const ws = bufferedWebSocket(upgrade.socket)
531 upgradedSources.add(this.source)
532 this.resolve(upgrade.response)
533 return Socket.fromWebSocket(
534 Effect.acquireRelease(
535 Effect.succeed(ws),
536 () => Effect.sync(() => upgrade.socket.close(1000))
537 )
538 )
539 }
540 )
541 }
542}
543
544// Deno's WebSocket cannot be paused, so events that arrive between the
545// upgrade and the first reader acquisition would be lost. This facade buffers
546// message, error, and close events until listeners attach, then replays them
547// so they come out of the first pull.
548const bufferedWebSocket = (ws: WebSocket): Socket.WebSocketLike => {
549 interface Entry {
550 readonly listener: (event: Socket.WebSocketEvent) => void
551 readonly once: boolean
552 }
553 const listeners = new Map<string, Array<Entry>>()
554 const buffered: Array<[string, Socket.WebSocketEvent]> = []
555 let buffering = true
556
557 ws.binaryType = "arraybuffer"
558
559 function removeListener(type: string, listener: (event: Socket.WebSocketEvent) => void) {
560 const entries = listeners.get(type)
561 if (!entries) return
562 const index = entries.findIndex((entry) => entry.listener === listener)
563 if (index >= 0) entries.splice(index, 1)
564 }
565 function dispatch(type: string, event: Socket.WebSocketEvent) {
566 const entries = listeners.get(type)
567 if (!entries || entries.length === 0) return
568 for (const entry of entries.slice()) {
569 if (entry.once) removeListener(type, entry.listener)
570 entry.listener(event)
571 }
572 }
573 function onEvent(type: string) {
574 return (event: Event) => {
575 const wsEvent = event as unknown as Socket.WebSocketEvent
576 if (buffering) {
577 buffered.push([type, wsEvent])
578 } else {
579 dispatch(type, wsEvent)
580 }
581 }
582 }
583 ws.addEventListener("message", onEvent("message"))
584 ws.addEventListener("error", onEvent("error"))
585 ws.addEventListener("close", onEvent("close"))
586
587 function replay() {
588 if (!buffering) return
589 buffering = false
590 for (const [type, event] of buffered.splice(0)) {
591 dispatch(type, event)
592 }
593 }
594
595 return {
596 get readyState() {
597 return ws.readyState
598 },
599 addEventListener(type, listener, options) {
600 if (type === "open") {
601 ws.addEventListener(type, listener as EventListener, options as AddEventListenerOptions)
602 return
603 }
604 let entries = listeners.get(type)
605 if (!entries) {
606 entries = []
607 listeners.set(type, entries)
608 }
609 entries.push({ listener, once: options?.once === true })
610 if (buffering) queueMicrotask(replay)
611 },
612 removeEventListener(type, listener) {
613 if (type === "open") {
614 ws.removeEventListener(type, listener as EventListener)
615 return
616 }
617 removeListener(type, listener)
618 },
619 close: (code, reason) => ws.close(code, reason),
620 send: (data) => ws.send(data)
621 }
622}
623
624// Reported to middleware in place of the handler's discarded response.
625const upgradedResponse = ServerResponse.empty({ status: 101 })
626
627// Keyed by source so request copies from `modify` share the upgrade state.
628const upgradedSources = new WeakSet<Request>()
629
630const isRawUpgrade = (request: Request): boolean => {
631 const protocol = request.headers.get("upgrade")
632 return protocol !== null && protocol.toLowerCase() !== "websocket"
633}
634
635const cancelResponseBody = (body: HttpBody.HttpBody): Effect.Effect<void> => {
636 if (body._tag === "Raw" && typeof ReadableStream !== "undefined" && body.body instanceof ReadableStream) {
637 const stream = body.body
638 return Effect.ignoreCause(Effect.promise(() => stream.cancel()))
639 }
640 return Effect.void
641}
642
643const cancelStreamUnsafe = (stream: ReadableStream): void => {
644 void stream.cancel().catch(constVoid)
645}
646
647const emptyReadableStream = new ReadableStream<Uint8Array>({
648 start(controller) {
649 controller.enqueue(new Uint8Array())
650 controller.close()
651 }
652})
653
654const authorityPattern = /^[^:/?#]+:\/\/([^/?#]*)/
655const urlAuthority = (url: string): string | undefined => authorityPattern.exec(url)?.[1]
656
657const removeHost = (url: string) => {
658 if (url[0] === "/") return url
659 const index = url.indexOf("/", url.indexOf("//") + 2)
660 return index === -1 ? "/" : url.slice(index)
661}