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 readonly executable: () => Promise<string>;
20 /**
21 * A path that starts `executable`, such as one that moves Chrome out of the server's cgroup.
22 * Released after the whole launch call, since Playwright retries the same path after a glibc race.
23 */
24 readonly launcher?: (
25 executable: string,
26 ) => Promise<{ readonly path: string; readonly release: () => Promise<void> } | undefined>;
27 readonly diagnose?: (executable: string, cause: unknown) => Promise<unknown>;
28 readonly env?: NodeJS.ProcessEnv;
29 readonly onContextClose?: (context: BrowserContext) => void;
30}
31
32const UA_PLATFORMS: Partial<Record<NodeJS.Platform, string>> = {
33 darwin: "macOS",
34 linux: "Linux",
35 win32: "Windows",
36};
37
38/** Change user agent and Sec-CH-UA together; sites block mismatches. */
39const chromeIdentity = (
40 headlessUserAgent: string,
41 host: { readonly platform: NodeJS.Platform; readonly arch: string; readonly release: string },
42) => {
43 const version = /HeadlessChrome\/((\d+)[\d.]*)/.exec(headlessUserAgent);
44 const fullVersion = version?.[1];
45 const major = version?.[2];
46 if (!version || !fullVersion || !major) return null;
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 userAgent: headlessUserAgent.replace(version[0], `Chrome/${major}.0.0.0`),
54 userAgentMetadata: {
55 brands: brands((value) => value),
56 fullVersionList: brands((value) => (value === major ? fullVersion : `${value}.0.0.0`)),
57 platform: UA_PLATFORMS[host.platform] ?? "Unknown",
58 platformVersion: host.platform === "linux" ? host.release : "",
59 architecture: host.arch.startsWith("arm") ? "arm" : "x86",
60 bitness: host.arch.endsWith("64") ? "64" : "32",
61 model: "",
62 mobile: false,
63 wow64: false,
64 },
65 };
66};
67
68export const presentAsChrome = async (
69 cdp: CDPSession,
70 host: { readonly platform: NodeJS.Platform; readonly arch: string },
71) => {
72 const { userAgent } = await cdp.send("Browser.getVersion");
73 const identity = chromeIdentity(userAgent, { ...host, release: NodeOS.release() });
74 if (identity) await cdp.send("Emulation.setUserAgentOverride", identity);
75};
76
77export class ServerBrowserContexts {
78 private readonly options: Options;
79 private readonly contexts = new Map<string, Promise<BrowserContext>>();
80 private readonly clearing = new Map<string, Promise<void>>();
81 private browser: Promise<Browser> | undefined;
82 private closing: Promise<void> | undefined;
83
84 constructor(options: Options) {
85 this.options = options;
86 }
87
88 private async launchOptions() {
89 const executable = await this.options.executable();
90 const env = this.options.env ?? process.env;
91 return {
92 executable,
93 env,
94 args: [
95 "--disable-gpu",
96 "--force-device-scale-factor=2",
97 "--disable-blink-features=AutomationControlled",
98 ],
99 ignoreDefaultArgs: ["--enable-automation"],
100 headless: true,
101 // Only an explicit operator opt-out disables sandboxing. Launch errors never do.
102 chromiumSandbox: !sandboxDisabled(env),
103 };
104 }
105
106 private async launch<A>(executable: string, start: (executablePath: string) => Promise<A>) {
107 let release: (() => Promise<void>) | undefined;
108 try {
109 const launcher = await this.options.launcher?.(executable);
110 release = launcher?.release;
111 return await start(launcher?.path ?? executable);
112 } catch (cause) {
113 throw (await this.options.diagnose?.(executable, cause)) ?? cause;
114 } finally {
115 await release?.().catch(constVoid);
116 }
117 }
118
119 private sharedBrowser() {
120 if (!this.browser) {
121 const launched = this.launchOptions().then(async ({ executable, ...options }) => {
122 const { chromium } = loadPlaywright();
123 const browser = await this.launch(executable, (executablePath) =>
124 chromium.launch({ ...options, executablePath }),
125 );
126 browser.on("disconnected", () => {
127 if (this.browser === launched) this.browser = undefined;
128 });
129 return browser;
130 });
131 this.browser = launched;
132 void launched.catch(() => {
133 if (this.browser === launched) this.browser = undefined;
134 });
135 }
136 return this.browser;
137 }
138
139 contextFor(profileId: string, isolationKey?: string): Promise<BrowserContext> {
140 if (this.closing) return Promise.reject(new Error("The preview browser is closed."));
141 const key = JSON.stringify([profileId, isolationKey ?? null]);
142 const cached = this.contexts.get(key);
143 if (cached) return cached;
144 const cleared = this.clearing.get(key)?.catch(constVoid) ?? Promise.resolve();
145 const pending = cleared
146 .then(() => this.createContext(profileId, isolationKey))
147 .then(async (context) => {
148 context.on("close", () => {
149 if (this.contexts.get(key) === pending) this.contexts.delete(key);
150 this.options.onContextClose?.(context);
151 });
152 for (const page of context.pages()) await page.close().catch(constVoid);
153 if (this.closing) {
154 await context.close().catch(constVoid);
155 throw new Error("The preview browser is closed.");
156 }
157 return context;
158 });
159 this.contexts.set(key, pending);
160 void pending.catch(() => {
161 if (this.contexts.get(key) === pending) this.contexts.delete(key);
162 });
163 return pending;
164 }
165
166 private async createContext(profileId: string, isolationKey?: string) {
167 const contextOptions = { viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 };
168 if (isolationKey !== undefined || profileId === INCOGNITO_BROWSER_PROFILE_ID) {
169 const browser = await this.sharedBrowser();
170 return browser.newContext(contextOptions);
171 }
172 const directory = this.profileDirectory(profileId);
173 await NodeFSP.mkdir(directory, { recursive: true });
174 const { executable, ...options } = await this.launchOptions();
175 const { chromium } = loadPlaywright();
176 return this.launch(executable, (executablePath) =>
177 chromium.launchPersistentContext(directory, {
178 ...options,
179 ...contextOptions,
180 executablePath,
181 }),
182 );
183 }
184
185 private profileDirectory(profileId: string) {
186 const encoded = encodeURIComponent(profileId);
187 return NodePath.join(
188 this.options.profilesDir,
189 profileId === "." || profileId === ".." ? encoded.replaceAll(".", "%2E") : encoded,
190 );
191 }
192
193 async scratchPage() {
194 if (this.closing) throw new Error("The preview browser is closed.");
195 const context = await (await this.sharedBrowser()).newContext();
196 const page = await context.newPage();
197 page.once("close", () => void context.close().catch(constVoid));
198 return page;
199 }
200
201 async connectDesktopPage(endpoint: string) {
202 const { chromium } = loadPlaywright();
203 const browser = await chromium.connectOverCDP(endpoint, { timeout: 15_000 });
204 const page = browser.contexts().flatMap((context) => context.pages())[0];
205 if (!page) {
206 await browser.close().catch(constVoid);
207 throw new Error("The desktop tab has no page.");
208 }
209 return { browser, page };
210 }
211
212 async clearProfile(profileId: string) {
213 if (profileId === INCOGNITO_BROWSER_PROFILE_ID) return;
214 const key = JSON.stringify([profileId, null]);
215 const clearing = (async () => {
216 const pending = this.contexts.get(key);
217 if (pending) {
218 this.contexts.delete(key);
219 const context = await pending.catch(() => undefined);
220 await context?.close();
221 }
222 await NodeFSP.rm(this.profileDirectory(profileId), { recursive: true, force: true });
223 })();
224 this.clearing.set(key, clearing);
225 try {
226 await clearing;
227 } finally {
228 if (this.clearing.get(key) === clearing) this.clearing.delete(key);
229 }
230 }
231
232 close() {
233 this.closing ??= this.dispose();
234 return this.closing;
235 }
236
237 private async dispose() {
238 await Promise.allSettled(
239 [...this.contexts.values()].map(async (pending) => (await pending).close()),
240 );
241 const browser = await this.browser?.catch(() => undefined);
242 await browser?.close().catch(constVoid);
243 this.contexts.clear();
244 }
245}