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

BrowserSession.ts

198 lines7.2 KB

1import type { Session } from "electron";
2import { session } from "electron";
3import * as Context from "effect/Context";
4import * as Crypto from "effect/Crypto";
5import * as Effect from "effect/Effect";
6import * as Encoding from "effect/Encoding";
7import * as Layer from "effect/Layer";
8import * as PlatformError from "effect/PlatformError";
9import * as Schema from "effect/Schema";
10import * as SynchronizedRef from "effect/SynchronizedRef";
11​
12const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
13​
14// Permissions granted to preview web content. `clipboard-sanitized-write` is the
15// Electron permission behind `navigator.clipboard.writeText()` — note it is NOT
16// `clipboard-write`, which is not a valid Electron permission name. Async
17// clipboard writes are gated by the permission *check* handler (not only the
18// request handler), so both handlers must allow it; otherwise built-in "Copy"
19// buttons — e.g. the Next.js / Vercel error overlay — fail with
20// `Failed to execute 'writeText' on 'Clipboard': Write permission denied`.
21const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
22 "clipboard-read",
23 "clipboard-sanitized-write",
24 "notifications",
25 "geolocation",
26]);
27​
28export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
29 "BrowserSessionPartitionDerivationError",
30 {
31 scope: Schema.String,
32 cause: Schema.instanceOf(PlatformError.PlatformError),
33 },
34) {
35 override get message(): string {
36 return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
37 }
39​
40export class BrowserSessionCreationError extends Schema.TaggedErrorClass<BrowserSessionCreationError>()(
41 "BrowserSessionCreationError",
42 {
43 scope: Schema.String,
44 partition: Schema.String,
45 cause: Schema.Defect(),
46 },
47) {
48 override get message(): string {
49 return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
50 }
52​
53export class BrowserSessionStorageClearError extends Schema.TaggedErrorClass<BrowserSessionStorageClearError>()(
54 "BrowserSessionStorageClearError",
55 {
56 partition: Schema.String,
57 cause: Schema.Defect(),
58 },
59) {
60 override get message(): string {
61 return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
62 }
64​
65export class BrowserSessionCacheClearError extends Schema.TaggedErrorClass<BrowserSessionCacheClearError>()(
66 "BrowserSessionCacheClearError",
67 {
68 partition: Schema.String,
69 cause: Schema.Defect(),
70 },
71) {
72 override get message(): string {
73 return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
74 }
76​
77export const BrowserSessionGetSessionError = Schema.Union([
78 BrowserSessionPartitionDerivationError,
79 BrowserSessionCreationError,
80]);
81export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
82export const isBrowserSessionGetSessionError = Schema.is(BrowserSessionGetSessionError);
83​
84export const BrowserSessionError = Schema.Union([
85 BrowserSessionPartitionDerivationError,
86 BrowserSessionCreationError,
87 BrowserSessionStorageClearError,
88 BrowserSessionCacheClearError,
89]);
90export type BrowserSessionError = typeof BrowserSessionError.Type;
91export const isBrowserSessionError = Schema.is(BrowserSessionError);
92​
93export class BrowserSession extends Context.Service<
94 BrowserSession,
95 {
96 readonly getPartition: (
97 scope?: string,
98 ) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
99 readonly isPartition: (partition: string) => boolean;
100 readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
101 readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
102 readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
103 }
104>()("@t3tools/desktop/preview/BrowserSession") {}
105​
106export const make = Effect.gen(function* BrowserSessionMake() {
107 const crypto = yield* Crypto.Crypto;
108 const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
109​
110 const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
111 const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(scope)).pipe(
112 Effect.mapError(
113 (cause) =>
114 new BrowserSessionPartitionDerivationError({
115 scope,
116 cause,
117 }),
118 ),
119 );
120 return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
121 });
122​
123 const getSession = Effect.fn("BrowserSession.getSession")(function* (scope = "shared") {
124 const partition = yield* getPartition(scope);
125 return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
126 const existing = sessions.get(partition);
127 if (existing) return Effect.succeed([existing, sessions] as const);
128 return Effect.try({
129 try: () => {
130 const browserSession = session.fromPartition(partition);
131 const userAgent = browserSession
132 .getUserAgent()
133 .replace(/Electron\/[\d.]+ /, "")
134 .replace(/\s*t3code\/[\d.]+/, "");
135 browserSession.setUserAgent(userAgent);
136 browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
137 callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
138 });
139 browserSession.setPermissionCheckHandler((_webContents, permission) =>
140 ALLOWED_PREVIEW_PERMISSIONS.has(permission),
141 );
142 const next = new Map(sessions);
143 next.set(partition, browserSession);
144 return [browserSession, next] as const;
145 },
146 catch: (cause) =>
147 new BrowserSessionCreationError({
148 scope,
149 partition,
150 cause,
151 }),
152 });
153 });
154 });
155​
156 return BrowserSession.of({
157 getPartition,
158 isPartition: (partition) => partition.startsWith(PREVIEW_PARTITION_PREFIX),
159 getSession,
160 clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
161 const sessions = yield* SynchronizedRef.get(sessionsRef);
162 yield* Effect.all(
163 [...sessions.entries()].map(([partition, browserSession]) =>
164 Effect.tryPromise({
165 try: () =>
166 browserSession.clearStorageData({
167 storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
168 }),
169 catch: (cause) =>
170 new BrowserSessionStorageClearError({
171 partition,
172 cause,
173 }),
174 }),
175 ),
176 { concurrency: "unbounded", discard: true },
177 );
178 }),
179 clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
180 const sessions = yield* SynchronizedRef.get(sessionsRef);
181 yield* Effect.all(
182 [...sessions.entries()].map(([partition, browserSession]) =>
183 Effect.tryPromise({
184 try: () => browserSession.clearCache(),
185 catch: (cause) =>
186 new BrowserSessionCacheClearError({
187 partition,
188 cause,
189 }),
190 }),
191 ),
192 { concurrency: "unbounded", discard: true },
193 );
194 }),
195 });
196}).pipe(Effect.withSpan("BrowserSession.make"));
197​
198export const layer = Layer.effect(BrowserSession, make);