The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type * as runtime from "@cloudflare/workers-types"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as HttpClientError from "effect/http/HttpClientError"; |
| 4 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 5 | import * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 6 | import * as Url from "effect/http/Url"; |
| 7 | import * as Option from "effect/Option"; |
| 8 | import * as Result from "effect/Result"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | |
| 11 | /** |
| 12 | * Send an Effect `HttpClientRequest` through a runtime `Fetcher` binding |
| 13 | * (service binding, mTLS certificate, ...) and adapt the response. |
| 14 | * |
| 15 | * Internal: shared by the fetcher-shaped `Binding.Service`s and not exported |
| 16 | * from the Workers barrel. |
| 17 | * |
| 18 | * @internal |
| 19 | */ |
| 20 | export const fetchWithFetcher = ( |
| 21 | fetcher: runtime.Fetcher, |
| 22 | request: HttpClientRequest.HttpClientRequest, |
| 23 | description: string, |
| 24 | ): Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.RequestError> => { |
| 25 | const urlResult = Url.make( |
| 26 | request.url, |
| 27 | request.urlParams, |
| 28 | request.hash.pipe(Option.getOrUndefined), |
| 29 | ); |
| 30 | if (Result.isFailure(urlResult)) { |
| 31 | return Effect.fail( |
| 32 | new HttpClientError.InvalidUrlError({ |
| 33 | request, |
| 34 | cause: urlResult.failure, |
| 35 | description: "Failed to construct URL", |
| 36 | }), |
| 37 | ); |
| 38 | } |
| 39 | const url = urlResult.success; |
| 40 | |
| 41 | const send = (body: BodyInit | undefined) => |
| 42 | Effect.map( |
| 43 | Effect.tryPromise({ |
| 44 | try: () => |
| 45 | fetcher.fetch( |
| 46 | url.toString() as runtime.RequestInfo, |
| 47 | { |
| 48 | method: request.method, |
| 49 | headers: request.headers as unknown as runtime.HeadersInit, |
| 50 | body, |
| 51 | duplex: request.body._tag === "Stream" ? "half" : undefined, |
| 52 | } as runtime.RequestInit, |
| 53 | ) as unknown as Promise<Response>, |
| 54 | catch: (cause) => new HttpClientError.TransportError({ request, cause, description }), |
| 55 | }), |
| 56 | (response) => HttpClientResponse.fromWeb(request, response), |
| 57 | ); |
| 58 | |
| 59 | switch (request.body._tag) { |
| 60 | case "Raw": |
| 61 | case "Uint8Array": |
| 62 | return send(request.body.body as BodyInit); |
| 63 | case "FormData": |
| 64 | return send(request.body.formData); |
| 65 | case "Stream": |
| 66 | return Effect.flatMap( |
| 67 | Effect.mapError( |
| 68 | Stream.toReadableStreamEffect(request.body.stream), |
| 69 | (cause) => |
| 70 | new HttpClientError.EncodeError({ |
| 71 | request, |
| 72 | cause, |
| 73 | description: "Failed to encode stream body", |
| 74 | }), |
| 75 | ), |
| 76 | send, |
| 77 | ); |
| 78 | default: |
| 79 | return send(undefined); |
| 80 | } |
| 81 | }; |