Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Owns Playwright resources outside the Effect runtime.
2import { INCOGNITO_BROWSER_PROFILE_ID } from "@t3tools/contracts";
3import { constVoid } from "effect/Function";
4import * as NodeFSP from "node:fs/promises";
5import * as NodeModule from "node:module";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8import type { Browser, BrowserContext, CDPSession } from "playwright-core";
9
10import { sandboxDisabled } from "./PreviewBrowserHost.ts";
11
12// Playwright needs its files on disk. createRequire also resolves it from a Node SEA executable.
13const requirePlaywright = NodeModule.createRequire(import.meta.url);
14const loadPlaywright = () =>
15 requirePlaywright("playwright-core") as typeof import("playwright-core");
16
17interface Options {
18 readonly profilesDir: string;
19 /** The shared headless browser's executable, installing it on first use. */
20 readonly executable: () => Promise<string>;
21 /** Replaces a failed launch's error with the host setup it is missing, if any. */
22 readonly diagnose?: (executable: string, cause: unknown) => Promise<unknown>;
23 readonly env?: NodeJS.ProcessEnv;
24 readonly onContextClose?: (context: BrowserContext) => void;
25}
26
27const UA_PLATFORMS: Partial<Record<NodeJS.Platform, string>> = {
28 darwin: "macOS",
29 linux: "Linux",
30 win32: "Windows",
31};
32
33/**
34 * The headless shell's identity as the Chrome it is built from: its user agent
35 * without `HeadlessChrome`, and client hints whose brands agree with it. Sites
36 * block a user agent that disagrees with `Sec-CH-UA`, so both change together.
37 */
38const chromeIdentity = (
39 headlessUserAgent: string,
40 host: { readonly platform: NodeJS.Platform; readonly arch: string; readonly release: string },
41) => {
42 const version = /HeadlessChrome\/((\d+)[\d.]*)/.exec(headlessUserAgent);
43 const fullVersion = version?.[1];
44 const major = version?.[2];
45 if (!version || !fullVersion || !major) return null;
46 // Chrome's GREASE brand and order for this major version, as the shell reports them.
47 const brands = (names: (version: string) => string) => [
48 { brand: "Chromium", version: names(major) },
49 { brand: "Google Chrome", version: names(major) },
50 { brand: "Not A(Brand", version: names("99") },
51 ];
52 return {
53 // Chrome reduces its user agent to the major version.
54 userAgent: headlessUserAgent.replace(version[0], `Chrome/${major}.0.0.0`),
55 userAgentMetadata: {
56 brands: brands((value) => value),
57 fullVersionList: brands((value) => (value === major ? fullVersion : `${value}.0.0.0`)),
58 platform: UA_PLATFORMS[host.platform] ?? "Unknown",
59 platformVersion: host.platform === "linux" ? host.release : "",
60 architecture: host.arch.startsWith("arm") ? "arm" : "x86",
61 bitness: host.arch.endsWith("64") ? "64" : "32",
62 model: "",
63 mobile: false,
64 wow64: false,
65 },
66 };
67};
68
69/**
70 * Presents a headless page as plain Chrome. Applies to the page, its frames,
71 * and its workers; a popup gets its own call once it becomes a tab.
72 */
73export const presentAsChrome = async (
74 cdp: CDPSession,
75 host: { readonly platform: NodeJS.Platform; readonly arch: string },
76) => {
77 const { userAgent } = await cdp.send("Browser.getVersion");
78 const identity = chromeIdentity(userAgent, { ...host, release: NodeOS.release() });
79 if (identity) await cdp.send("Emulation.setUserAgentOverride", identity);
80};
81
82/** Persistent human profiles keep their storage; isolated agents share a browser, never a context. */
83export class ServerBrowserContexts {
84 private readonly options: Options;
85 private readonly contexts = new Map<string, Promise<BrowserContext>>();
86 /** Profile clears in progress; a context for that profile opens after its storage is gone. */
87 private readonly clearing = new Map<string, Promise<void>>();
88 private browser: Promise<Browser> | undefined;
89 private closing: Promise<void> | undefined;
90
91 constructor(options: Options) {
92 this.options = options;
93 }
94
95 private async launchOptions() {
96 const executablePath = await this.options.executable();
97 const env = this.options.env ?? process.env;
98 return {
99 executablePath,
100 env,
101 // People drive these tabs, so they must not announce automation (navigator.webdriver).
102 args: [
103 "--disable-gpu",
104 "--force-device-scale-factor=2",
105 "--disable-blink-features=AutomationControlled",
106 ],
107 ignoreDefaultArgs: ["--enable-automation"],
108 headless: true,
109 // Only an explicit operator opt-out disables sandboxing. Launch errors never do.
110 chromiumSandbox: !sandboxDisabled(env),
111 };
112 }
113
114 private async launch<A>(options: { readonly executablePath: string }, start: () => Promise<A>) {
115 try {
116 return await start();
117 } catch (cause) {
118 throw (await this.options.diagnose?.(options.executablePath, cause)) ?? cause;
119 }
120 }
121
122 private sharedBrowser() {
123 if (!this.browser) {
124 const launched = this.launchOptions().then(async (options) => {
125 const { chromium } = loadPlaywright();
126 const browser = await this.launch(options, () => chromium.launch(options));
127 browser.on("disconnected", () => {
128 if (this.browser === launched) this.browser = undefined;
129 });
130 return browser;
131 });
132 this.browser = launched;
133 void launched.catch(() => {
134 if (this.browser === launched) this.browser = undefined;
135 });
136 }
137 return this.browser;
138 }
139
140 contextFor(profileId: string, isolationKey?: string): Promise<BrowserContext> {
141 if (this.closing) return Promise.reject(new Error("The preview browser is closed."));
142 const key = JSON.stringify([profileId, isolationKey ?? null]);
143 const cached = this.contexts.get(key);
144 if (cached) return cached;
145 const cleared = this.clearing.get(key)?.catch(constVoid) ?? Promise.resolve();
146 const pending = cleared
147 .then(() => this.createContext(profileId, isolationKey))
148 .then(async (context) => {
149 context.on("close", () => {
150 if (this.contexts.get(key) === pending) this.contexts.delete(key);
151 this.options.onContextClose?.(context);
152 });
153 for (const page of context.pages()) await page.close().catch(constVoid);
154 if (this.closing) {
155 await context.close().catch(constVoid);
156 throw new Error("The preview browser is closed.");
157 }
158 return context;
159 });
160 this.contexts.set(key, pending);
161 void pending.catch(() => {
162 if (this.contexts.get(key) === pending) this.contexts.delete(key);
163 });
164 return pending;
165 }
166
167 private async createContext(profileId: string, isolationKey?: string) {
168 const contextOptions = { viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 };
169 if (isolationKey !== undefined || profileId === INCOGNITO_BROWSER_PROFILE_ID) {
170 const browser = await this.sharedBrowser();
171 return browser.newContext(contextOptions);
172 }
173 const directory = this.profileDirectory(profileId);
174 const options = await this.launchOptions();
175 const { chromium } = loadPlaywright();
176 await NodeFSP.mkdir(directory, { recursive: true });
177 return this.launch(options, () =>
178 chromium.launchPersistentContext(directory, { ...options, ...contextOptions }),
179 );
180 }
181
182 private profileDirectory(profileId: string) {
183 const encoded = encodeURIComponent(profileId);
184 return NodePath.join(
185 this.options.profilesDir,
186 profileId === "." || profileId === ".." ? encoded.replaceAll(".", "%2E") : encoded,
187 );
188 }
189
190 /** A throwaway page in the shared browser, for work that must not touch a tab's own storage. */
191 async scratchPage() {
192 if (this.closing) throw new Error("The preview browser is closed.");
193 const context = await (await this.sharedBrowser()).newContext();
194 const page = await context.newPage();
195 page.once("close", () => void context.close().catch(constVoid));
196 return page;
197 }
198
199 /**
200 * Drives a page the desktop app renders, through the CDP endpoint its relay
201 * serves. The page keeps the desktop's storage, size, and window.
202 */
203 async connectDesktopPage(endpoint: string) {
204 const { chromium } = loadPlaywright();
205 const browser = await chromium.connectOverCDP(endpoint, { timeout: 15_000 });
206 const page = browser.contexts().flatMap((context) => context.pages())[0];
207 if (!page) {
208 await browser.close().catch(constVoid);
209 throw new Error("The desktop tab has no page.");
210 }
211 return { browser, page };
212 }
213
214 /** Closes a human profile's persistent context, ending its tabs, then deletes its storage. */
215 async clearProfile(profileId: string) {
216 if (profileId === INCOGNITO_BROWSER_PROFILE_ID) return;
217 const key = JSON.stringify([profileId, null]);
218 const clearing = (async () => {
219 const pending = this.contexts.get(key);
220 if (pending) {
221 this.contexts.delete(key);
222 const context = await pending.catch(() => undefined);
223 await context?.close();
224 }
225 await NodeFSP.rm(this.profileDirectory(profileId), { recursive: true, force: true });
226 })();
227 this.clearing.set(key, clearing);
228 try {
229 await clearing;
230 } finally {
231 if (this.clearing.get(key) === clearing) this.clearing.delete(key);
232 }
233 }
234
235 close() {
236 this.closing ??= this.dispose();
237 return this.closing;
238 }
239
240 private async dispose() {
241 await Promise.allSettled(
242 [...this.contexts.values()].map(async (pending) => (await pending).close()),
243 );
244 const browser = await this.browser?.catch(() => undefined);
245 await browser?.close().catch(constVoid);
246 this.contexts.clear();
247 }
248}