/** * An `HttpClient` on React Native's `Networking` module with incremental * text responses and buffered binary responses. * * **Details** * * React Native's `fetch` has no response body stream, so reading * `FetchHttpClient`'s `response.stream` fails with `EmptyBody`. * {@link layer} supports NDJSON RPC without `@effect/ui-native/networking`. * * {@link ResponseType} defaults to `"text"`, which streams decoded text * as UTF-8 bytes. Set it to `"binary"` to preserve exact bytes, emitted in * one chunk after completion. Text mode rejects known binary content * types, such as msgpack or images, with a `DecodeError`. * * **Gotchas** * * - A request body stream is read whole before it is sent: native can't * stream an upload. * - A request body is a string, bytes or React Native's `FormData`. Any * other body, such as a `Blob`, fails with an `EncodeError`. * - A response body streams once: after `stream`, the other readers fail. * - `cookies` is always empty: native keeps them. * * **Example** (NDJSON RPC over HTTP) * * ```ts * import { NativeHttpClient } from "@effect/ui-native" * import { Layer } from "effect" * import { RpcClient, RpcSerialization } from "effect/rpc" * * export const Protocol = RpcClient.layerProtocolHttp({ * url: "https://api.example.com/rpc" * }).pipe(Layer.provide([NativeHttpClient.layer, RpcSerialization.layerNdjson])) * ``` * * @stability experimental * @since 4.2.0 */ import * as Cause from "effect/Cause" import * as Context from "effect/Context" import * as Effect from "effect/Effect" import * as Base64 from "effect/encoding/Base64" import * as Cookies from "effect/http/Cookies" import * as Headers from "effect/http/Headers" import * as HttpClient from "effect/http/HttpClient" import * as HttpClientError from "effect/http/HttpClientError" import type * as HttpClientRequest from "effect/http/HttpClientRequest" import * as HttpClientResponse from "effect/http/HttpClientResponse" import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage" import * as UrlParams from "effect/http/UrlParams" import * as Inspectable from "effect/Inspectable" import type * as Layer from "effect/Layer" import * as Option from "effect/Option" import { pipeArguments } from "effect/Pipeable" import * as Queue from "effect/Queue" import * as Result from "effect/Result" import type * as Schema from "effect/Schema" import type * as Socket from "effect/socket/Socket" import * as Stream from "effect/Stream" import { URL, URLSearchParams } from "react-native/Libraries/Blob/URL" import NativeFormData from "react-native/Libraries/Network/FormData" import { perDevice } from "./kit/internal/device.ts" import * as Native from "./Native.ts" /** * How native delivers a response body: `"text"` decodes it and streams it * as it arrives, `"binary"` delivers the exact bytes once it completes. * Read when a request is sent, so it can be set for one request. * * @stability experimental * @category references * @since 4.2.0 */ export const ResponseType: Context.Reference<"text" | "binary"> = Context .Reference<"text" | "binary">( "@effect/ui-native/NativeHttpClient/ResponseType", { defaultValue: () => "text" } ) class Exchange { readonly chunks: Array = [] /** Native's `didReceiveNetworkResponse` payload: id, status, headers, url. */ head: Array | undefined = undefined /** `undefined` while it loads, `null` once complete, else native's error. */ error: string | null | undefined = undefined id: number | undefined = undefined readonly listeners = new Set<() => void>() readonly networking: any readonly exchanges: Map constructor(networking: any, exchanges: Map) { this.networking = networking this.exchanges = exchanges } notify() { for (const listener of this.listeners) listener() } end(error: string | null) { if (this.error !== undefined) return this.error = error this.notify() } start(id: number) { this.id = id this.exchanges.set(id, this) } // The signal's listener, so it keeps only the exchange alive. readonly abort = () => { if (this.id === undefined || this.error !== undefined) return this.exchanges.delete(this.id) this.networking.abortRequest(this.id) this.end("aborted") } } // One set of listeners per device, dispatching by request id. const exchangesOf = perDevice((device) => { const exchanges = new Map() const on = ( event: string, f: (exchange: Exchange, payload: Array) => void ) => device.on(event, (payload: Array) => { const exchange = exchanges.get(payload[0]) if (exchange !== undefined) f(exchange, payload) }) on("didReceiveNetworkResponse", (exchange, payload) => { exchange.head = payload exchange.notify() }) const data = (exchange: Exchange, [, chunk]: Array) => { exchange.chunks.push(chunk) exchange.notify() } on("didReceiveNetworkData", data) on("didReceiveNetworkIncrementalData", data) on("didCompleteNetworkResponse", (exchange, [id, error]) => { exchanges.delete(id) exchange.end(error ?? null) }) return exchanges }) // Start Android request IDs high to avoid collisions with React Native's XHR. let nextId = 0x40000000 const convert = (body: any): object | undefined => body == null ? {} : typeof body === "string" ? { string: body } : body instanceof ArrayBuffer || ArrayBuffer.isView(body) ? { base64: Base64.encode( ArrayBuffer.isView(body) ? new Uint8Array(body.buffer, body.byteOffset, body.byteLength) : new Uint8Array(body) ) } : typeof body.getParts === "function" ? { formData: body.getParts() } : undefined const client = HttpClient.make((request, url, signal, fiber) => { const transportError = (cause: unknown) => new HttpClientError.HttpClientError({ reason: new HttpClientError.TransportError({ request, cause }) }) const encodeError = ( options: { readonly description: string } | { readonly cause: unknown } ) => new HttpClientError.HttpClientError({ reason: new HttpClientError.EncodeError({ request, ...options }) }) const send = (data: any) => Effect.callback< HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError >((resume) => { const fail = (cause: unknown) => resume(Effect.fail(transportError(cause))) if (signal.aborted) return fail(signal.reason) const device = fiber.getRef(Native.Device) const networking = device.module("Networking") if (networking === undefined) { return fail("React Native's Networking module isn't available") } const binary = fiber.getRef(ResponseType) === "binary" const exchange = new Exchange(networking, exchangesOf(device)) const ready = () => { const head = exchange.head if (head === undefined) { if (exchange.error !== undefined) fail(exchange.error) return } exchange.listeners.delete(ready) resume(Effect.succeed( new Response( request, head[1], Headers.fromInput(head[2] ?? {}), head[3] || url.href.split("#")[0], exchange, binary ) )) } exchange.listeners.add(ready) const started = (id: number) => { exchange.start(id) // iOS assigns the ID asynchronously; cancellation may arrive first. if (signal.aborted) exchange.abort() } signal.addEventListener("abort", exchange.abort, { once: true }) const devToolsRequestId = (globalThis as any).__NETWORK_REPORTER__ ?.createDevToolsRequestId() const responseType = binary ? "base64" : "text" if (device.os === "android") { data.formData?.forEach((part: any) => { part.headers = Object.entries(part.headers) }) started(nextId++) networking.sendRequest( request.method, url.href, exchange.id, Object.entries(request.headers), { ...data, devToolsRequestId }, responseType, !binary, 0, true ) } else { networking.sendRequest({ method: request.method, url: url.href, data, headers: { ...request.headers }, responseType, incrementalUpdates: !binary, timeout: 0, withCredentials: true, unstable_devToolsRequestId: devToolsRequestId }, started) } }) if (signal.aborted) return Effect.fail(transportError(signal.reason)) const body = request.body if (body._tag !== "Stream") { const data = convert( body._tag === "Empty" ? undefined : body._tag === "FormData" ? body.formData : body.body ) return data ? send(data) : Effect.fail(encodeError({ description: "React Native's Networking module can't send this body: send a string, bytes, or React Native's FormData" })) } // Native requires a buffered upload; scope closure cancels the read. const aborted = Effect.callback( (resume) => { const onAbort = () => resume(Effect.fail(transportError(signal.reason))) // The upload starts first, and may have closed the scope already. if (signal.aborted) return onAbort() signal.addEventListener("abort", onAbort) return Effect.sync(() => signal.removeEventListener("abort", onAbort)) } ) return Effect.raceFirst( Effect.mapError( Stream.mkUint8Array(body.stream), (cause) => encodeError({ cause }) ), aborted ).pipe(Effect.flatMap((bytes) => send({ base64: Base64.encode(bytes) }))) }) // Native decodes these as text badly: iOS drops them, Android garbles them. const binaryType = /^(?:image|audio|video|font)\/|^application\/(?:octet-stream|(?:x-)?msgpack|(?:x-)?protobuf|pdf|zip|gzip|wasm)\b/i let encoder: TextEncoder | undefined class Response extends Inspectable.Class implements HttpClientResponse.HttpClientResponse { readonly [HttpIncomingMessage.TypeId]: typeof HttpIncomingMessage.TypeId = HttpIncomingMessage.TypeId readonly [HttpClientResponse.TypeId]: typeof HttpClientResponse.TypeId = HttpClientResponse.TypeId readonly cookies: Cookies.Cookies = Cookies.empty readonly remoteAddress: Option.Option = Option.none() readonly request: HttpClientRequest.HttpClientRequest readonly status: number readonly headers: Headers.Headers readonly url: string private readonly exchange: Exchange private readonly binary: boolean private streamed = false constructor( request: HttpClientRequest.HttpClientRequest, status: number, headers: Headers.Headers, url: string, exchange: Exchange, binary: boolean ) { super() this.request = request this.status = status this.headers = headers this.url = url this.exchange = exchange this.binary = binary } private decodeError( description: string, cause?: unknown ): HttpClientError.HttpClientError { return new HttpClientError.HttpClientError({ reason: new HttpClientError.DecodeError({ request: this.request, response: this, description, cause }) }) } private failed(error: string): HttpClientError.HttpClientError { return this.decodeError(`The response failed: ${error}`, error) } private unreadable(): HttpClientError.HttpClientError | undefined { const type = this.headers["content-type"] if (!this.binary && type !== undefined && binaryType.test(type)) { return this.decodeError( `A ${type} body can't be read as text: set NativeHttpClient.ResponseType to "binary"` ) } if (this.streamed) { return this.decodeError("The body was already read as a stream") } const error = this.exchange.error if (error) return this.failed(error) } private bytes(chunk: string): Uint8Array | HttpClientError.HttpClientError { if (!this.binary) return (encoder ??= new TextEncoder()).encode(chunk) const bytes = Base64.decode(chunk) return Result.isSuccess(bytes) ? bytes.success : this.decodeError("Native sent invalid base64", bytes.failure) } /** The whole body, as native sent it. */ private get loaded(): Effect.Effect { return Effect.callback((resume) => { const exchange = this.exchange const done = () => { const error = this.unreadable() if (error) return resume(Effect.fail(error)) if (exchange.error === undefined) return // Cache the joined body for repeat reads. const body = exchange.chunks.splice(0).join("") exchange.chunks.push(body) resume(Effect.succeed(body)) } exchange.listeners.add(done) done() return Effect.sync(() => exchange.listeners.delete(done)) }) } get stream(): Stream.Stream { return Stream.callback( (queue) => Effect.acquireRelease( Effect.sync(() => { const exchange = this.exchange const fail = (error: HttpClientError.HttpClientError) => { Queue.failCauseUnsafe(queue, Cause.fail(error)) } const unreadable = this.unreadable() if (unreadable) return fail(unreadable) this.streamed = true const flush = () => { const chunks = exchange.chunks for (const chunk of chunks) { if (chunk === "") continue const bytes = this.bytes(chunk) if (!(bytes instanceof Uint8Array)) return fail(bytes) Queue.offerUnsafe(queue, bytes) } // Release consumed chunks from long-lived streams. chunks.length = 0 if (exchange.error === null) Queue.endUnsafe(queue) else if (exchange.error !== undefined) { fail(this.failed(exchange.error)) } } exchange.listeners.add(flush) flush() return flush }), (flush) => Effect.sync(() => flush && this.exchange.listeners.delete(flush)) ) ) } get text(): Effect.Effect { return this.binary ? Effect.map( this.arrayBuffer, (buffer) => new TextDecoder().decode(buffer) ) : this.loaded } get arrayBuffer(): Effect.Effect< ArrayBuffer, HttpClientError.HttpClientError > { return Effect.flatMap(this.loaded, (body) => { const bytes = this.bytes(body) return bytes instanceof Uint8Array ? Effect.succeed(bytes.buffer as ArrayBuffer) : Effect.fail(bytes) }) } get json(): Effect.Effect { return Effect.flatMap(this.text, (text) => Effect.try({ try: () => text === "" ? null : JSON.parse(text), catch: (cause) => this.decodeError("The body isn't JSON", cause) })) } get urlParamsBody(): Effect.Effect< UrlParams.UrlParams, HttpClientError.HttpClientError > { return Effect.map( this.text, (text) => UrlParams.fromInput(new URLSearchParams(text)) ) } get formData(): Effect.Effect { return Effect.fail( this.decodeError("React Native can't read a multipart body") ) } get upgrade(): Effect.Effect { return Effect.fail( new HttpClientError.HttpClientError({ reason: new HttpClientError.StatusCodeError({ request: this.request, response: this, description: "React Native can't hand over the connection of an HTTP upgrade" }) }) ) } toJSON(): unknown { return HttpIncomingMessage.inspect(this, { _id: "HttpClientResponse", request: this.request.toJSON(), status: this.status }) } pipe() { return pipeArguments(this, arguments) } } // Supply AbortController without bundling React Native's XHR stack. class Signal { aborted = false reason: unknown = undefined onabort: ((event: object) => void) | null = null listeners: Array<(event: object) => void> = [] addEventListener(type: string, listener: (event: object) => void) { if (type === "abort") this.listeners.push(listener) } removeEventListener(type: string, listener: (event: object) => void) { const index = this.listeners.indexOf(listener) if (type === "abort" && index !== -1) this.listeners.splice(index, 1) } throwIfAborted() { if (this.aborted) throw this.reason } } class Controller { readonly signal = new Signal() abort(reason?: unknown) { const signal = this.signal if (signal.aborted) return signal.aborted = true signal.reason = reason ?? Object.assign( new Error("This operation was aborted"), { name: "AbortError" } ) const event = { type: "abort", target: signal } signal.onabort?.(event) for (const listener of signal.listeners.splice(0)) listener(event) } } /** * Provides `HttpClient` through React Native's `Networking` module and * installs missing `URL`, `URLSearchParams`, `AbortController` and `FormData` * globals. * * @stability experimental * @category layers * @since 4.2.0 */ export const layer: Layer.Layer = HttpClient .layerMergedContext(Effect.sync(() => { const global = globalThis as any global.URL ??= URL global.URLSearchParams ??= URLSearchParams global.AbortController ??= Controller global.FormData ??= NativeFormData return client }))