Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

httpLayer.ts

58 lines1.8 KB

1import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
5​
6import { readDesktopPrimaryBearerToken } from "./desktopAuth";
7import { resolvePrimaryEnvironmentHttpUrl } from "./target";
8​
9function isSameOriginBrowserPrimary(): boolean {
10 if (
11 typeof window === "undefined" ||
12 window.desktopBridge !== undefined ||
13 window.nativeApi !== undefined ||
14 !window.location.origin.startsWith("http")
15 ) {
16 return false;
17 }
18​
19 return new URL(resolvePrimaryEnvironmentHttpUrl("/")).origin === window.location.origin;
21​
22function withPrimaryBearerToken(client: HttpClient.HttpClient): HttpClient.HttpClient {
23 return client.pipe(
24 HttpClient.mapRequestEffect((request) =>
25 Effect.promise(readDesktopPrimaryBearerToken).pipe(
26 Effect.map((bearerToken) =>
27 bearerToken ? HttpClientRequest.bearerToken(request, bearerToken) : request,
28 ),
29 ),
30 ),
31 );
33​
34export function makePrimaryEnvironmentHttpLayer() {
35 return Layer.unwrap(
36 Effect.sync(() => {
37 const baseLayer = remoteHttpClientLayer(globalThis.fetch);
38 if (isSameOriginBrowserPrimary()) {
39 return Layer.merge(
40 baseLayer,
41 Layer.succeed(FetchHttpClient.RequestInit, { credentials: "include" }),
42 );
43 }
44​
45 const bearerClientLayer = Layer.effect(
46 HttpClient.HttpClient,
47 Effect.map(HttpClient.HttpClient, withPrimaryBearerToken),
48 ).pipe(Layer.provide(baseLayer));
49​
50 return Layer.merge(
51 bearerClientLayer,
52 Layer.succeed(FetchHttpClient.RequestInit, { credentials: "omit" }),
53 );
54 }),
55 );
57​
58export const primaryEnvironmentHttpLayer = makePrimaryEnvironmentHttpLayer();