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