import * as NativeHttpClient from "@effect/ui-native/NativeHttpClient" import { TestDevice } from "@effect/ui-native/testing" import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" import * as Fiber from "effect/Fiber" import * as HttpClient from "effect/http/HttpClient" import * as HttpClientRequest from "effect/http/HttpClientRequest" import * as Layer from "effect/Layer" import * as Scope from "effect/Scope" import * as Stream from "effect/Stream" import { assert, describe, it } from "vitest" const NodeFormData = FormData const run = ( platform: TestDevice.Platform, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, test: (client: HttpClient.HttpClient) => Effect.Effect ) => Effect.runPromise( Effect.gen(function*() { ;(yield* TestDevice.TestDevice).setFetch(Object.assign(fetch, { preconnect: () => {} })) return yield* test(yield* HttpClient.HttpClient) }).pipe( Effect.provide( Layer.merge(NativeHttpClient.layer, TestDevice.layer(platform)) ) ) ) describe("NativeHttpClient", () => { it.each(["android", "ios"] as const)( "on %s, streams a text body as it arrives and aborts the request once the stream stops", async (platform) => { let body!: ReadableStreamDefaultController let cancelled = false // A body that ignores the request's signal, so only cancelling the // reader stops it. const stream = new ReadableStream({ start: (controller) => void (body = controller), cancel: () => void (cancelled = true) }) await run( platform, async () => new Response(stream), (client) => Effect.gen(function*() { const response = yield* client.get("https://api.test/rpc") const first = yield* response.stream.pipe( Stream.decodeText, Stream.take(1), Stream.runCollect, Effect.forkChild ) body.enqueue(new TextEncoder().encode("{\"id\":1}\n")) assert.deepStrictEqual(yield* Fiber.join(first), ["{\"id\":1}\n"]) yield* Effect.sleep(1) assert.isTrue(cancelled) assert.isFalse(stream.locked) }) ) } ) it("doesn't read the upload or send a request whose scope closes first", async () => { let sent = 0 let pulled = 0 await run("android", async () => { sent++ return new Response("") }, (client) => Effect.gen(function*() { const charge = (body: Stream.Stream) => HttpClient.withScope(client).execute( HttpClientRequest.post("https://api.test/charge").pipe( HttpClientRequest.bodyStream(body) ) ).pipe(Effect.flip) const closed = yield* Scope.make() yield* Scope.close(closed, Exit.void) const counted = Stream.fromEffect( Effect.sync(() => (pulled++, new Uint8Array(1))) ) const before = yield* charge(counted).pipe(Scope.provide(closed)) // The upload closes the scope while it is read. const own = yield* Scope.make() const closing = yield* charge( Stream.fromEffect( Scope.close(own, Exit.void).pipe(Effect.andThen(Effect.never)) ) ).pipe(Scope.provide(own)) assert.strictEqual(before.reason._tag, "TransportError") assert.strictEqual(closing.reason._tag, "TransportError") yield* Effect.sleep(1) assert.strictEqual(pulled, 0) assert.strictEqual(sent, 0) })) }) it("reads whole bodies, as text or as exact bytes, and sends request bodies", async () => { const bytes = new Uint8Array([0xff, 0, 1]) await run( "android", async (url, init) => { switch (new URL(url as string).pathname) { case "/echo": return new Response(init!.body) case "/form": return Response.json(Object.fromEntries(init!.body as FormData)) case "/bytes": return new Response(bytes, { headers: { "content-type": "Application/Octet-Stream" } }) default: throw new Error("offline") } }, (client) => Effect.gen(function*() { const echo = (request: HttpClientRequest.HttpClientRequest) => Effect.flatMap(client.execute(request), (response) => response.json) assert.deepStrictEqual( yield* echo( HttpClientRequest.post("https://api.test/echo").pipe( HttpClientRequest.bodyJsonUnsafe({ a: 1 }) ) ), { a: 1 } ) assert.deepStrictEqual( yield* echo( HttpClientRequest.post("https://api.test/echo").pipe( HttpClientRequest.bodyStream( Stream.make(new TextEncoder().encode("[2]")) ) ) ), [2] ) assert.deepStrictEqual( yield* echo( HttpClientRequest.post("https://api.test/form").pipe( HttpClientRequest.bodyFormDataRecord({ name: "Ada" }) ) ), { name: "Ada" } ) // Native uploads a file part from its uri, which the fake can't read. const photo = new FormData() photo.append("name", "Ada") photo.append("photo", { uri: "file:///photo.jpg", name: "photo.jpg", type: "image/jpeg" } as any) const failed = yield* Effect.flip(client.execute( HttpClientRequest.post("https://api.test/form").pipe( HttpClientRequest.bodyFormData(photo) ) )) assert.strictEqual(failed.reason._tag, "TransportError") assert.include(String(failed.reason.cause), "file:///photo.jpg") const get = (path: string) => Effect.flatMap( client.get(`https://api.test${path}`), (response) => response.arrayBuffer ) assert.deepStrictEqual( new Uint8Array( yield* get("/bytes").pipe( Effect.provideService(NativeHttpClient.ResponseType, "binary") ) ), bytes ) assert.strictEqual( (yield* Effect.flip(get("/bytes"))).reason._tag, "DecodeError" ) assert.strictEqual( (yield* Effect.flip(get("/offline"))).reason._tag, "TransportError" ) }) ) }) // Alone, as it changes globals the other tests use. it("installs the globals a request needs where React Native lacks them", { concurrent: false }, async () => { const names = ["URL", "URLSearchParams", "AbortController", "FormData"] const saved = names.map((name) => (globalThis as any)[name]) // TestDevice's FormData is React Native's only while it's up. await Effect.runPromise(Effect.scoped(Layer.build(TestDevice.layer("ios")))) assert.strictEqual(globalThis.FormData, NodeFormData) try { for (const name of names) delete (globalThis as any)[name] await Effect.runPromise( Effect.scoped(Layer.build(NativeHttpClient.layer)) ) const request = HttpClientRequest.post("https://api.test/form").pipe( HttpClientRequest.bodyFormDataRecord({ name: "Ada" }) ) assert.deepStrictEqual( (request.body as any).formData.getParts().map((part: any) => part.string), ["Ada"] ) for (const name of names) assert.isFunction((globalThis as any)[name]) } finally { names.forEach((name, i) => ((globalThis as any)[name] = saved[i])) } }) })