Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

refactor: Extract remote logic from abstract browser pool (#4197)

Jan Buchard89341258323
diff --git a/docs/guides/remote_browser.mdx b/docs/guides/remote_browser.mdx
index 61e7a64b2..bb0c5a159 100644
--- a/docs/guides/remote_browser.mdx
+++ b/docs/guides/remote_browser.mdx
@@ -18,7 +18,7 @@ Use this when you need IPs in specific regions, want to offload CPU/memory from
## How it works
-Set the crawler's `remoteBrowser` option with the connection details. The crawler builds a <ApiLink to="browser-pool/class/RemoteBrowserPool">`RemoteBrowserPool`</ApiLink> around its own browser plugin, so the connection is always for the matching browser — there's no plugin to construct and no way to mismatch the pool with the crawler. The pool (an <ApiLink to="browser-pool/interface/IBrowserPool">`IBrowserPool`</ApiLink> wrapping the regular <ApiLink to="browser-pool/class/BrowserPool">`BrowserPool`</ApiLink>) owns everything remote: resolving the endpoint, releasing sessions when browsers close, and capping how many remote browsers run at once.
+Set the crawler's `remoteBrowser` option with the connection details. The crawler builds its regular <ApiLink to="browser-pool/class/BrowserPool">`BrowserPool`</ApiLink> around a remote variant of its own browser plugin (<ApiLink to="browser-pool/class/RemotePlaywrightPlugin">`RemotePlaywrightPlugin`</ApiLink> or <ApiLink to="browser-pool/class/RemotePuppeteerPlugin">`RemotePuppeteerPlugin`</ApiLink>), so the connection is always for the matching browser — there's no plugin to construct and no way to mismatch the pool with the crawler. The plugin owns everything remote: resolving the endpoint per launch, connecting with the library's `connect()`, and releasing the session when the browser disconnects.
## Basic usage
@@ -42,42 +42,53 @@ Point the pool at the local endpoint with `endpoint: 'ws://localhost:3000'`.
## Custom provider
-For services with a session-create / session-release lifecycle, extend <ApiLink to="browser-pool/class/RemoteBrowserProvider">`RemoteBrowserProvider`</ApiLink> and pass the instance as the pool's `endpoint`. `connect()` runs once per browser launch and returns the connection URL plus an optional `context` object passed back to `release()`. `maxOpenBrowsers` set on the provider is adopted by the pool.
+For services with a session-create / session-release lifecycle, extend <ApiLink to="browser-pool/class/RemoteBrowserProvider">`RemoteBrowserProvider`</ApiLink> and pass the instance as the `endpoint`. `connect()` runs once per browser launch and returns the connection URL plus an optional `context` object passed back to `release()`. `maxOpenBrowsers` set on the provider is adopted by the crawler's pool.
<CodeBlock language="ts" title="src/main.ts">{RemoteBrowserProviderSource}</CodeBlock>
## Puppeteer
-<ApiLink to="puppeteer-crawler/class/PuppeteerCrawler">`PuppeteerCrawler`</ApiLink> works the same way — build the pool with a `PuppeteerPlugin`. Puppeteer connects over CDP:
+<ApiLink to="puppeteer-crawler/class/PuppeteerCrawler">`PuppeteerCrawler`</ApiLink> accepts the same `remoteBrowser` option. Puppeteer connects over CDP:
<CodeBlock language="ts" title="src/main.ts">{RemoteBrowserPuppeteerSource}</CodeBlock>
-For Playwright you can choose the protocol via the `remoteBrowser.connection.protocol` option: `'cdp'` (default, `connectOverCDP()`) or `'playwright'` (`connect()`, Playwright's own WebSocket protocol).
+For Playwright you can choose the protocol via the `remoteBrowser.protocol` option: `'cdp'` (default, `connectOverCDP()`) or `'playwright'` (`connect()`, Playwright's own WebSocket protocol).
-## Sharing a pool across crawlers
+## Tuning or sharing the pool
-`remoteBrowser` builds a pool the crawler owns and tears down. To share one remote pool across multiple crawlers, construct a <ApiLink to="browser-pool/class/RemoteBrowserPool">`RemoteBrowserPool`</ApiLink> yourself and pass it as the `browserPool` option instead — a pool supplied that way is never destroyed by the crawler, so you control its lifecycle. Use `remoteBrowser` *or* `browserPool`, not both.
+`remoteBrowser` builds a pool the crawler owns and tears down. To tune the pool, or to share one across multiple crawlers, pass the same `remoteBrowser` to the pool factory for your crawler (<ApiLink to="playwright-crawler/function/playwrightBrowserPool">`playwrightBrowserPool()`</ApiLink>, <ApiLink to="puppeteer-crawler/function/puppeteerBrowserPool">`puppeteerBrowserPool()`</ApiLink>) and hand the result over as `browserPool` instead — a pool supplied that way is never destroyed by the crawler, so you control its lifecycle. Use `remoteBrowser` *or* `browserPool`, not both.
Declare it with `await using` and the browsers (and their remote sessions) are released once you are done with the pool:
```ts
-import { PlaywrightPlugin, RemoteBrowserPool } from '@crawlee/browser-pool';
-import { PlaywrightCrawler } from 'crawlee';
-import playwright from 'playwright';
+import { PlaywrightCrawler, playwrightBrowserPool } from 'crawlee';
-await using browserPool = new RemoteBrowserPool({
- browserPlugins: [new PlaywrightPlugin(playwright.chromium)],
- endpoint: 'wss://production-sfo.browserless.io?token=xxx',
- maxOpenBrowsers: 2,
+await using browserPool = playwrightBrowserPool({
+ remoteBrowser: { endpoint: 'wss://production-sfo.browserless.io?token=xxx', maxOpenBrowsers: 2 },
+ maxOpenPagesPerBrowser: 5,
});
await new PlaywrightCrawler({ browserPool, requestHandler: async () => { /* ... */ } }).run(['https://crawlee.dev']);
await new PlaywrightCrawler({ browserPool, requestHandler: async () => { /* ... */ } }).run(['https://apify.com']);
```
+Building the pool from `@crawlee/browser-pool` directly works too, and lets you rotate between several services — the pool round-robins over its plugins:
+
+```ts
+import { BrowserPool, RemotePlaywrightPlugin } from '@crawlee/browser-pool';
+import playwright from 'playwright';
+
+const browserPool = new BrowserPool({
+ browserPlugins: [
+ new RemotePlaywrightPlugin(playwright.chromium, { endpoint: 'wss://production-sfo.browserless.io?token=xxx' }),
+ new RemotePlaywrightPlugin(playwright.chromium, { endpoint: 'wss://connect.browserbase.com?apiKey=xxx' }),
+ ],
+});
+```
+
:::note Requires Node.js 24
-The `await using` syntax needs Node.js 24 or later. On Node.js 22 call <ApiLink to="browser-pool/class/RemoteBrowserPool#destroy">`destroy()`</ApiLink> yourself instead — it is what the disposal hook calls anyway.
+The `await using` syntax needs Node.js 24 or later. On Node.js 22 call <ApiLink to="browser-pool/class/BrowserPool#destroy">`destroy()`</ApiLink> yourself instead — it is what the disposal hook calls anyway.
:::
@@ -89,5 +100,5 @@ The `await using` syntax needs Node.js 24 or later. On Node.js 22 call <ApiLink
## Further reading
-- <ApiLink to="browser-pool/class/RemoteBrowserPool">`RemoteBrowserPool` API reference</ApiLink>
+- <ApiLink to="browser-pool/class/RemotePlaywrightPlugin">`RemotePlaywrightPlugin`</ApiLink> / <ApiLink to="browser-pool/class/RemotePuppeteerPlugin">`RemotePuppeteerPlugin`</ApiLink> API reference
- <ApiLink to="browser-pool/class/RemoteBrowserProvider">`RemoteBrowserProvider` API reference</ApiLink>
diff --git a/docs/public-api/crawlee-browser-pool.api.md b/docs/public-api/crawlee-browser-pool.api.md
index 11ab2356e..6f7ecf9bc 100644
--- a/docs/public-api/crawlee-browser-pool.api.md
+++ b/docs/public-api/crawlee-browser-pool.api.md
@@ -100,7 +100,6 @@ export abstract class BrowserPlugin<Library extends CommonLibrary = CommonLibrar
protected abstract addProxyToLaunchOptions(launchContext: LaunchContext<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>): Promise<void>;
// (undocumented)
readonly browserPerProxy?: boolean;
- protected connectToRemoteBrowser(launchContext: LaunchContext<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>, connect: (url: string) => Promise<LaunchResult>): Promise<LaunchResult>;
// (undocumented)
abstract createController(): BrowserController<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>;
createLaunchContext(options?: CreateLaunchContextOptions<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>): LaunchContext<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>;
@@ -209,6 +208,7 @@ export interface BrowserPoolOptions<Plugin extends BrowserPlugin = BrowserPlugin
closeInactiveBrowserAfterSecs?: number;
// (undocumented)
fingerprintOptions?: FingerprintOptions;
+ maxOpenBrowsers?: number;
maxOpenPagesPerBrowser?: number;
operationTimeoutSecs?: number;
retireBrowserAfterPageCount?: number;
@@ -243,9 +243,6 @@ export interface CommonPage {
url(): string | Promise<string>;
}
-// @public
-export type CrawlerRemoteBrowserOptions = Omit<RemoteBrowserPoolOptions, 'browserPlugins' | 'browserPoolOptions'>;
-
// @public (undocumented)
export interface CreateLaunchContextOptions<Library extends CommonLibrary, LibraryOptions extends Dictionary | undefined = Parameters<Library['launch']>[0], LaunchResult extends CommonBrowser = UnwrapPromise<ReturnType<Library['launch']>>, NewPageOptions = Parameters<LaunchResult['newPage']>[0], NewPageResult = UnwrapPromise<ReturnType<LaunchResult['newPage']>>> extends Partial<Omit<LaunchContextOptions<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>, 'browserPlugin'>> {
}
@@ -434,6 +431,9 @@ export class PuppeteerController extends BrowserController<typeof Puppeteer, Pup
protected _setCookies(page: PuppeteerTypes.Page, cookies: Cookie[]): Promise<void>;
}
+// @public (undocumented)
+export type PuppeteerLaunchContext = LaunchContext<typeof Puppeteer, PuppeteerTypes.LaunchOptions, PuppeteerTypes.Browser, PuppeteerNewPageOptions>;
+
// Not exported by the entry point; reachable only as a referenced type.
// @public (undocumented)
interface PuppeteerNewPageOptions extends PuppeteerTypes.BrowserContextOptions {
@@ -452,7 +452,7 @@ export class PuppeteerPlugin extends BrowserPlugin<typeof Puppeteer, PuppeteerTy
// (undocumented)
protected isChromiumBasedBrowser(_launchContext: LaunchContext<typeof Puppeteer, PuppeteerTypes.LaunchOptions, PuppeteerTypes.Browser, PuppeteerNewPageOptions>): boolean;
// (undocumented)
- protected _launch(launchContext: LaunchContext<typeof Puppeteer, PuppeteerTypes.LaunchOptions, PuppeteerTypes.Browser, PuppeteerNewPageOptions>): Promise<PuppeteerTypes.Browser>;
+ protected _launch(launchContext: PuppeteerLaunchContext): Promise<PuppeteerTypes.Browser>;
}
// @public
@@ -461,32 +461,9 @@ export type RemoteBrowserEndpoint = string | ((options?: {
}) => string | ResolvedRemoteEndpoint | Promise<string | ResolvedRemoteEndpoint>);
// @public
-export class RemoteBrowserPool<Page = unknown> implements IBrowserPool<Page> {
- // (undocumented)
- [Symbol.asyncDispose](): Promise<void>;
- constructor(options: RemoteBrowserPoolOptions);
- // (undocumented)
- closePage(page: Page, options?: {
- error?: Error;
- }): Promise<void>;
- destroy(): Promise<void>;
- // (undocumented)
- extractPageState(page: Page): Promise<PageState>;
- // (undocumented)
- injectPageState(page: Page, state: PageState): Promise<void>;
- get maxOpenBrowsers(): number;
- set maxOpenBrowsers(value: number);
- newPage(options?: NewPageOptions): Promise<Page>;
- releaseAllBrowsers(): Promise<void>;
-}
-
-// @public (undocumented)
-export interface RemoteBrowserPoolOptions {
- browserPlugins: BrowserPlugin[];
- browserPoolOptions?: Omit<BrowserPoolOptions, 'browserPlugins'> & BrowserPoolHooks<any, any, any>;
- connection?: RemoteConnectionParameters;
+export interface RemoteBrowserOptions {
+ connectOptions?: Record<string, unknown>;
endpoint: RemoteBrowserEndpoint | RemoteBrowserProvider<any>;
- maxOpenBrowsers?: number;
release?: (info: {
endpoint: string;
context?: Record<string, unknown>;
@@ -509,22 +486,34 @@ export abstract class RemoteBrowserProvider<TContext extends Record<string, unkn
}
// @public
-export interface RemoteConnection {
- release(token: number): Promise<void>;
- resolve(options?: {
- proxyUrl?: string;
- }): Promise<{
- url: string;
- token: number;
- }>;
+export class RemotePlaywrightPlugin extends PlaywrightPlugin {
+ constructor(library: BrowserType, options: RemotePlaywrightPluginOptions);
+ // (undocumented)
+ createLaunchContext(options?: CreateLaunchContextOptions<BrowserType>): LaunchContext<BrowserType>;
+ launch(launchContext?: LaunchContext<BrowserType>): Promise<Browser>;
+ // (undocumented)
+ protected _launch(launchContext: LaunchContext<BrowserType>): Promise<Browser>;
}
-// @public
-export interface RemoteConnectionParameters {
- connectOptions?: Record<string, unknown>;
+// @public (undocumented)
+export interface RemotePlaywrightPluginOptions extends BrowserPluginOptions<SafeParameters<BrowserType['launch']>[0]>, RemoteBrowserOptions {
protocol?: 'cdp' | 'playwright';
}
+// @public
+export class RemotePuppeteerPlugin extends PuppeteerPlugin {
+ constructor(library: typeof Puppeteer, options: RemotePuppeteerPluginOptions);
+ // (undocumented)
+ createLaunchContext(options?: CreateLaunchContextOptions<typeof Puppeteer, PuppeteerTypes.LaunchOptions, PuppeteerTypes.Browser, PuppeteerNewPageOptions>): PuppeteerLaunchContext;
+ launch(launchContext?: PuppeteerLaunchContext): Promise<PuppeteerTypes.Browser>;
+ // (undocumented)
+ protected _launch(launchContext: PuppeteerLaunchContext): Promise<PuppeteerTypes.Browser>;
+}
+
+// @public (undocumented)
+export interface RemotePuppeteerPluginOptions extends BrowserPluginOptions<PuppeteerTypes.LaunchOptions>, RemoteBrowserOptions {
+}
+
// @public
export interface ResolvedRemoteEndpoint {
context?: Record<string, unknown>;
diff --git a/docs/public-api/crawlee-browser.api.md b/docs/public-api/crawlee-browser.api.md
index 57b6a61d0..0fde6f225 100644
--- a/docs/public-api/crawlee-browser.api.md
+++ b/docs/public-api/crawlee-browser.api.md
@@ -8,10 +8,9 @@ import type { AddRequestsBatchedResult } from '@crawlee/basic';
import type { Awaitable } from '@crawlee/types';
import { BasicCrawler } from '@crawlee/basic';
import { BasicCrawlerOptions } from '@crawlee/basic';
-import type { BrowserPluginOptions } from '@crawlee/browser-pool';
+import { BrowserPluginOptions } from '@crawlee/browser-pool';
import type { CommonPage } from '@crawlee/browser-pool';
import { ContextPipeline } from '@crawlee/basic';
-import type { CrawlerRemoteBrowserOptions } from '@crawlee/browser-pool';
import type { CrawlingContext } from '@crawlee/basic';
import { CrawlingRequest } from '@crawlee/basic';
import type { Dictionary } from '@crawlee/types';
@@ -21,6 +20,7 @@ import type { ExtractLinksOptions } from '@crawlee/basic';
import type { GetUserDataFromRequest } from '@crawlee/basic';
import type { IBrowserPool } from '@crawlee/types';
import type { LoadedRequest } from '@crawlee/basic';
+import { RemoteBrowserOptions } from '@crawlee/browser-pool';
import type { RequestHandler } from '@crawlee/basic';
import type { RouterHandler } from '@crawlee/basic';
@@ -89,6 +89,11 @@ export interface BrowserLaunchContext<TOptions, Launcher> extends BrowserPluginO
userDataDir?: string;
}
+// @public
+export interface CrawlerRemoteBrowserOptions extends RemoteBrowserOptions {
+ maxOpenBrowsers?: number;
+}
+
// @public
export type OwnedBrowserPool<Page> = IBrowserPool<Page> & {
releaseAllBrowsers: () => Promise<void>;
diff --git a/docs/public-api/crawlee-playwright.api.md b/docs/public-api/crawlee-playwright.api.md
index 35b9801f8..1048eb280 100644
--- a/docs/public-api/crawlee-playwright.api.md
+++ b/docs/public-api/crawlee-playwright.api.md
@@ -22,6 +22,7 @@ import type { BrowserType } from 'playwright';
import { Cheerio } from 'cheerio';
import { CheerioAPI } from 'cheerio';
import { Configuration } from '@crawlee/browser';
+import type { CrawlerRemoteBrowserOptions } from '@crawlee/browser';
import type { CrawlingContext } from '@crawlee/basic';
import type { CrawlingRequest } from '@crawlee/browser';
import type { Dictionary } from '@crawlee/types';
@@ -35,8 +36,6 @@ import type { LoadedRequest } from '@crawlee/browser';
import type { Page } from 'playwright';
import type { PlaywrightPlugin } from '@crawlee/browser-pool';
import type { RecoverableStatePersistenceOptions } from '@crawlee/core';
-import type { RemoteBrowserPool } from '@crawlee/browser-pool';
-import type { RemoteBrowserPoolOptions } from '@crawlee/browser-pool';
import type { Request as Request_2 } from '@crawlee/core';
import { Request as Request_3 } from '@crawlee/browser';
import type { RequestTransform } from '@crawlee/browser';
@@ -282,6 +281,7 @@ export interface PlaywrightBrowserPoolOptions extends Omit<BrowserPoolOptions, '
configuration?: Configuration;
headless?: boolean;
launchContext?: PlaywrightLaunchContext;
+ remoteBrowser?: PlaywrightRemoteBrowserOptions;
}
declare namespace playwrightClickElements {
@@ -321,6 +321,7 @@ export interface PlaywrightCrawlerOptions<ContextExtension = Dictionary<never>,
launchContext?: PlaywrightLaunchContext;
postNavigationHooks?: BrowserHook<PlaywrightCrawlingContext<GetUserDataFromRequest<ExtendedContext['request']>>, ContextExtension>[];
preNavigationHooks?: BrowserHook<PlaywrightCrawlingContext<GetUserDataFromRequest<ExtendedContext['request']>>, ContextExtension>[];
+ remoteBrowser?: PlaywrightRemoteBrowserOptions;
}
// @public (undocumented)
@@ -350,6 +351,11 @@ export interface PlaywrightLaunchContext extends BrowserLaunchContext<LaunchOpti
userDataDir?: string;
}
+// @public
+export interface PlaywrightRemoteBrowserOptions extends CrawlerRemoteBrowserOptions {
+ protocol?: 'cdp' | 'playwright';
+}
+
declare namespace playwrightUtils {
export {
injectFile,
@@ -374,13 +380,6 @@ declare namespace playwrightUtils {
}
}
-// @public
-export function remotePlaywrightBrowserPool(options: RemotePlaywrightBrowserPoolOptions): RemoteBrowserPool<Page>;
-
-// @public (undocumented)
-export interface RemotePlaywrightBrowserPoolOptions extends Pick<PlaywrightBrowserPoolOptions, 'launchContext' | 'headless' | 'configuration'>, Omit<RemoteBrowserPoolOptions, 'browserPlugins'> {
-}
-
// @public (undocumented)
export type RenderingType = 'clientOnly' | 'static';
diff --git a/docs/public-api/crawlee-puppeteer.api.md b/docs/public-api/crawlee-puppeteer.api.md
index 6fa4ac053..4358b1fde 100644
--- a/docs/public-api/crawlee-puppeteer.api.md
+++ b/docs/public-api/crawlee-puppeteer.api.md
@@ -17,6 +17,7 @@ import type { BrowserPoolOptions } from '@crawlee/browser-pool';
import type { CheerioAPI } from 'cheerio';
import type { ClickOptions } from 'puppeteer';
import { Configuration } from '@crawlee/browser';
+import type { CrawlerRemoteBrowserOptions } from '@crawlee/browser';
import { Dictionary } from '@crawlee/types';
import type { GetUserDataFromRequest } from '@crawlee/browser';
import type { HTTPRequest } from 'puppeteer';
@@ -24,8 +25,6 @@ import type { HTTPResponse } from 'puppeteer';
import { IRequestManager } from '@crawlee/browser';
import type { Page } from 'puppeteer';
import { PuppeteerPlugin } from '@crawlee/browser-pool';
-import type { RemoteBrowserPool } from '@crawlee/browser-pool';
-import type { RemoteBrowserPoolOptions } from '@crawlee/browser-pool';
import { Request as Request_2 } from '@crawlee/browser';
import type { RequestTransform } from '@crawlee/browser';
import type { RouterHandler } from '@crawlee/browser';
@@ -142,6 +141,7 @@ export interface PuppeteerBrowserPoolOptions extends Omit<BrowserPoolOptions, 'b
configuration?: Configuration;
headless?: boolean | 'new' | 'old';
launchContext?: PuppeteerLaunchContext;
+ remoteBrowser?: CrawlerRemoteBrowserOptions;
}
// @public (undocumented)
@@ -224,13 +224,6 @@ declare namespace puppeteerUtils {
}
}
-// @public
-export function remotePuppeteerBrowserPool(options: RemotePuppeteerBrowserPoolOptions): RemoteBrowserPool<Page>;
-
-// @public (undocumented)
-export interface RemotePuppeteerBrowserPoolOptions extends Pick<PuppeteerBrowserPoolOptions, 'launchContext' | 'headless' | 'configuration'>, Omit<RemoteBrowserPoolOptions, 'browserPlugins'> {
-}
-
// @public
function removeInterceptRequestHandler(page: Page, handler: InterceptHandler): Promise<void>;
diff --git a/docs/public-api/crawlee-stagehand.api.md b/docs/public-api/crawlee-stagehand.api.md
index c47a8cf87..a257c2895 100644
--- a/docs/public-api/crawlee-stagehand.api.md
+++ b/docs/public-api/crawlee-stagehand.api.md
@@ -32,8 +32,6 @@ import { ModelConfiguration } from '@browserbasehq/stagehand';
import type { NonStreamingAgentInstance } from '@browserbasehq/stagehand';
import { ObserveOptions } from '@browserbasehq/stagehand';
import type { Page } from 'playwright';
-import type { RemoteBrowserPool } from '@crawlee/browser-pool';
-import type { RemoteBrowserPoolOptions } from '@crawlee/browser-pool';
import type { RequestHandler } from '@crawlee/browser';
import type { Response as Response_2 } from 'playwright';
import type { RouterHandler } from '@crawlee/browser';
@@ -67,13 +65,6 @@ export { ModelConfiguration }
export { ObserveOptions }
-// @public
-export function remoteStagehandBrowserPool(options: RemoteStagehandBrowserPoolOptions): RemoteBrowserPool<Page>;
-
-// @public (undocumented)
-export interface RemoteStagehandBrowserPoolOptions extends Pick<StagehandBrowserPoolOptions, 'launchContext' | 'stagehandOptions' | 'headless' | 'configuration'>, Omit<RemoteBrowserPoolOptions, 'browserPlugins'> {
-}
-
export { Stagehand }
// @public
diff --git a/docs/upgrading/upgrading_v4.md b/docs/upgrading/upgrading_v4.md
index 4a3139464..eaf3a5350 100644
--- a/docs/upgrading/upgrading_v4.md
+++ b/docs/upgrading/upgrading_v4.md
@@ -76,7 +76,7 @@ Support for older node versions was dropped.
### Collaborators you own are disposable
-A crawler never tears down an instance it did not build, so anything you construct and pass in — `SessionPool`, `ConcurrencySystem`, `BrowserPool`, `RemoteBrowserPool`, `RenderingTypePredictor` — is yours to shut down. All of them implement `Symbol.asyncDispose`, so `await using` does it for you:
+A crawler never tears down an instance it did not build, so anything you construct and pass in — `SessionPool`, `ConcurrencySystem`, `BrowserPool`, `RenderingTypePredictor` — is yours to shut down. All of them implement `Symbol.asyncDispose`, so `await using` does it for you:
```typescript
await using concurrencySystem = new ConcurrencySystem({ maxConcurrency: 20 });
@@ -499,13 +499,13 @@ In v4, when `saveResponseCookies` is enabled (the default), browser cookies are
`browserPoolOptions` is gone from every browser crawler. It was a second way of configuring the very pool that the `browserPool` option accepts, and the two could not be combined — passing a pool made the options silently disappear.
-Build the pool with the factory that matches your crawler instead. Each factory takes every `BrowserPool` option plus the crawler's own `launchContext` and `headless`, and derives the browser plugin from them, so the pool can never mismatch the crawler it is passed to:
+Build the pool with the factory that matches your crawler instead. Each factory takes every `BrowserPool` option plus the crawler's own `launchContext`, `headless` and `remoteBrowser`, and derives the browser plugin from them, so the pool can never mismatch the crawler it is passed to:
-| crawler | factory | remote counterpart |
-| --- | --- | --- |
-| `PlaywrightCrawler` | `playwrightBrowserPool()` | `remotePlaywrightBrowserPool()` |
-| `PuppeteerCrawler` | `puppeteerBrowserPool()` | `remotePuppeteerBrowserPool()` |
-| `StagehandCrawler` | `stagehandBrowserPool()` | `remoteStagehandBrowserPool()` |
+| crawler | factory |
+| --- | --- |
+| `PlaywrightCrawler` | `playwrightBrowserPool()` |
+| `PuppeteerCrawler` | `puppeteerBrowserPool()` |
+| `StagehandCrawler` | `stagehandBrowserPool()` |
**Before:**
```typescript
@@ -527,7 +527,7 @@ const crawler = new PlaywrightCrawler({
Building the pool outside the crawler has one consequence worth knowing: a pool passed as `browserPool` is borrowed, so the crawler never destroys it, and the options that would have configured a pool of the crawler's own — `launchContext`, `headless` and `remoteBrowser` — are now **rejected** instead of silently ignored. Move them into the factory call.
-`remoteBrowser` keeps working on its own for the terse case; reach for a `remote*BrowserPool()` factory when you also want to tune the pool wrapping the remote connection, or to share one remote pool between crawlers.
+`remoteBrowser` keeps working on its own for the terse case; pass the same `remoteBrowser` to the factory when you also want to tune the pool, or to share one remote pool between crawlers. Remote connections are owned by the `RemotePlaywrightPlugin` / `RemotePuppeteerPlugin` classes from `@crawlee/browser-pool` — there is no separate `RemoteBrowserPool`; `BrowserPool` itself accepts `maxOpenBrowsers`. `StagehandCrawler` does not support `remoteBrowser` (it throws) — Stagehand manages its own browser via `stagehandOptions.env`.
`headless` is now declared on each concrete crawler rather than on `BrowserCrawler`, so the puppeteer-only `'new'` and `'old'` values are only accepted by `PuppeteerCrawler`.
@@ -1394,7 +1394,7 @@ If you called the standalone `playwrightUtils.handleCloudflareChallenge(page, ur
### `PlaywrightLauncher` is no longer exported
-`PlaywrightLauncher` was an implementation detail of `launchPlaywright()` and the Playwright browser pools, and it is no longer part of `@crawlee/playwright`'s (or `crawlee`'s) public exports. Use `launchPlaywright(launchContext, configuration)` to get a `Browser`, or `playwrightBrowserPool()` / `remotePlaywrightBrowserPool()` when you need a pool. `PlaywrightLaunchContext` is still exported, so the options object can still be typed.
+`PlaywrightLauncher` was an implementation detail of `launchPlaywright()` and the Playwright browser pools, and it is no longer part of `@crawlee/playwright`'s (or `crawlee`'s) public exports. Use `launchPlaywright(launchContext, configuration)` to get a `Browser`, or `playwrightBrowserPool()` when you need a pool. `PlaywrightLaunchContext` is still exported, so the options object can still be typed.
### `BrowserCrawler.launchContext` was removed
@@ -2410,7 +2410,7 @@ A few Stagehand-specific option types were tightened:
- The `StagehandRequestHandler` type was removed. It was never referenced by `StagehandCrawlerOptions.requestHandler`, which uses `RequestHandler<StagehandCrawlingContext>` — use that instead.
- The `stagehandUtils` namespace was removed. Its only member was internal glue that was never part of the documented surface.
- The `AgentResult` re-export was removed. Import it from `@browserbasehq/stagehand` directly — it is a non-optional peer dependency, so it is already installed.
-- `StagehandLaunchContext.stagehandOptions` was removed. It never had any effect: the value was always overwritten by the `stagehandOptions` option on the crawler and on `stagehandBrowserPool()` / `remoteStagehandBrowserPool()`. Pass `stagehandOptions` at the top level instead.
+- `StagehandLaunchContext.stagehandOptions` was removed. It never had any effect: the value was always overwritten by the `stagehandOptions` option on the crawler and on `stagehandBrowserPool()`. Pass `stagehandOptions` at the top level instead.
- `StagehandPlugin.stagehandOptions` is now private and `StagehandPlugin.getStagehandForBrowser()` is gone. Reach the `Stagehand` instance through the crawling context's `stagehand` property.
## Appendix: removed symbols
diff --git a/packages/browser-crawler/src/internals/browser-crawler.ts b/packages/browser-crawler/src/internals/browser-crawler.ts
index f1fb4814e..8faf3e8de 100644
--- a/packages/browser-crawler/src/internals/browser-crawler.ts
+++ b/packages/browser-crawler/src/internals/browser-crawler.ts
@@ -32,7 +32,7 @@ import {
toughCookieToBrowserPoolCookie,
validators,
} from '@crawlee/basic';
-import type { CommonPage, CrawlerRemoteBrowserOptions } from '@crawlee/browser-pool';
+import type { CommonPage } from '@crawlee/browser-pool';
import type { Awaitable, Cookie as CookieObject, Dictionary, IBrowserPool } from '@crawlee/types';
import {
assertBrowserPoolNotConfigured,
@@ -47,6 +47,8 @@ import { z } from 'zod';
import { addTimeoutToPromise, TimeoutError, tryCancel } from '@apify/timeout';
+import type { CrawlerRemoteBrowserOptions } from './browser-launcher.js';
+
interface BaseResponse {
status(): number;
/** Optional because only Playwright and Puppeteer responses are guaranteed to carry it. */
@@ -143,14 +145,13 @@ export interface BrowserCrawlerOptions<
/**
* Connect to a remote browser service (Browserbase, Browserless, Steel, …) instead of launching locally.
*
- * The crawler builds a {@apilink RemoteBrowserPool} around its own browser plugin, so the connection is
- * always for the right browser — there is no plugin to construct and no way to mismatch the pool with the
- * crawler. Supply the connection details only: a static `endpoint` URL, a function returning one per launch,
- * or a {@apilink RemoteBrowserProvider}.
+ * The crawler builds its pool around a remote variant of its own browser plugin, so the connection is always
+ * for the right browser. Supply the connection details only: a static `endpoint` URL, a function returning one
+ * per launch, or a {@apilink RemoteBrowserProvider}.
*
- * Cannot be combined with `browserPool`. To tune the pool wrapping the remote connection, or to share it
- * across crawlers, build it with the remote factory for your crawler ({@apilink remotePlaywrightBrowserPool},
- * {@apilink remotePuppeteerBrowserPool}, {@apilink remoteStagehandBrowserPool}) and pass it as `browserPool`.
+ * Cannot be combined with `browserPool`. To tune the pool, or to share it across crawlers, pass the same
+ * `remoteBrowser` to the pool factory for your crawler ({@apilink playwrightBrowserPool},
+ * {@apilink puppeteerBrowserPool}) and pass the result as `browserPool`.
*/
remoteBrowser?: CrawlerRemoteBrowserOptions;
diff --git a/packages/browser-crawler/src/internals/browser-launcher.ts b/packages/browser-crawler/src/internals/browser-launcher.ts
index f3a5fe28e..1fda8fa3e 100644
--- a/packages/browser-crawler/src/internals/browser-launcher.ts
+++ b/packages/browser-crawler/src/internals/browser-launcher.ts
@@ -3,14 +3,15 @@ import { createRequire } from 'node:module';
import os from 'node:os';
import { Configuration, serviceLocator } from '@crawlee/basic';
-import type {
- BrowserPlugin,
- BrowserPluginOptions,
- BrowserPoolHooks,
- BrowserPoolOptions,
- RemoteBrowserPoolOptions,
+import {
+ type BrowserPlugin,
+ type BrowserPluginOptions,
+ BrowserPool,
+ type BrowserPoolHooks,
+ type BrowserPoolOptions,
+ type RemoteBrowserOptions,
+ RemoteBrowserProvider,
} from '@crawlee/browser-pool';
-import { BrowserPool, RemoteBrowserPool } from '@crawlee/browser-pool';
import type { Constructor, Dictionary } from '@crawlee/types';
import { schemas } from '@crawlee/utils/internal';
import { z } from 'zod';
@@ -103,9 +104,16 @@ type LauncherBrowserPoolOptions = Omit<BrowserPoolOptions, 'browserPlugins'> & {
};
/**
- * The {@apilink RemoteBrowserPool} counterpart of {@apilink LauncherBrowserPoolOptions}.
+ * The remote-connection configuration a browser crawler accepts on its `remoteBrowser` option. Library-specific
+ * connect settings (e.g. Playwright's `protocol`) are added by the concrete crawler's options.
*/
-type LauncherRemoteBrowserPoolOptions = Omit<RemoteBrowserPoolOptions, 'browserPlugins'>;
+export interface CrawlerRemoteBrowserOptions extends RemoteBrowserOptions {
+ /**
+ * Maximum number of remote browsers open at once; see {@apilink BrowserPoolOptions.maxOpenBrowsers}. Defaults
+ * to the {@apilink RemoteBrowserProvider.maxOpenBrowsers|provider's value}, or `Infinity`.
+ */
+ maxOpenBrowsers?: number;
+}
/**
* Abstract class for creating browser launchers, such as `PlaywrightLauncher` and `PuppeteerLauncher`.
@@ -123,8 +131,9 @@ export abstract class BrowserLauncher<
useChrome?: boolean;
launchOptions: Dictionary;
otherLaunchContextProps: Dictionary;
- // to be provided by child classes;
+ // to be provided by child classes; `RemotePlugin` only by those supporting remote browsers
Plugin!: T;
+ RemotePlugin?: T;
userAgent?: string;
/**
@@ -192,44 +201,54 @@ export abstract class BrowserLauncher<
/**
* @ignore
*/
- createBrowserPlugin(): Plugin {
- return new this.Plugin(this.launcher, {
+ createBrowserPlugin(remoteBrowser?: CrawlerRemoteBrowserOptions): Plugin {
+ const options = {
proxyUrl: this.proxyUrl,
launchOptions: this.createLaunchOptions(),
...this.otherLaunchContextProps,
- });
+ };
+
+ if (!remoteBrowser) {
+ return new this.Plugin(this.launcher, options);
+ }
+
+ if (!this.RemotePlugin) {
+ throw new Error(`${this.constructor.name} does not support remote browsers.`);
+ }
+
+ const { maxOpenBrowsers: _, ...remoteOptions } = remoteBrowser;
+ return new this.RemotePlugin(this.launcher, { ...options, ...remoteOptions });
}
/**
* Builds a {@apilink BrowserPool} running a single plugin for this launcher's browser. Shared body of the
* per-library `*BrowserPool()` factories, which exist so that configuring a pool never requires assembling
* a plugin by hand — and therefore never lets the plugin drift away from the crawler it is used with.
+ * With `remoteBrowser`, the plugin connects to a remote browser service instead of launching locally.
* @internal
*/
- createBrowserPool(options: LauncherBrowserPoolOptions = {}): BrowserPool<{ browserPlugins: [Plugin] }, [Plugin]> {
+ createBrowserPool({
+ remoteBrowser,
+ ...options
+ }: LauncherBrowserPoolOptions & { remoteBrowser?: CrawlerRemoteBrowserOptions } = {}): BrowserPool<
+ { browserPlugins: [Plugin] },
+ [Plugin]
+ > {
+ const provider = remoteBrowser?.endpoint instanceof RemoteBrowserProvider ? remoteBrowser.endpoint : undefined;
+ const maxOpenBrowsers = options.maxOpenBrowsers ?? remoteBrowser?.maxOpenBrowsers ?? provider?.maxOpenBrowsers;
+
// The hook types `BrowserPool` derives from `Plugin` are unresolvable while `Plugin` is still a free type
// parameter, so the argument cannot be checked here. The concrete `*BrowserPool()` factories are where the
// caller-facing hook types get pinned down.
return new BrowserPool<{ browserPlugins: [Plugin] }, [Plugin]>({
...this.#resolveFingerprinting(options),
- browserPlugins: [this.createBrowserPlugin()],
+ ...(maxOpenBrowsers !== undefined && { maxOpenBrowsers }),
+ browserPlugins: [this.createBrowserPlugin(remoteBrowser)],
} as any);
}
/**
- * The {@apilink RemoteBrowserPool} counterpart of {@apilink BrowserLauncher.createBrowserPool}: the launcher
- * supplies the plugin, the caller supplies the remote connection details.
- * @internal
- */
- createRemoteBrowserPool<Page>(options: LauncherRemoteBrowserPoolOptions): RemoteBrowserPool<Page> {
- return new RemoteBrowserPool<Page>({
- ...options,
- browserPlugins: [this.createBrowserPlugin()],
- browserPoolOptions: this.#resolveFingerprinting(options.browserPoolOptions ?? {}),
- });
- }
- /**
* A custom `userAgent` and Crawlee's fingerprint injection would both write the same headers, so an
* explicitly requested user agent wins.
*/
diff --git a/packages/browser-pool/src/abstract-classes/browser-plugin.ts b/packages/browser-pool/src/abstract-classes/browser-plugin.ts
index f1cfbc9ec..5de62b320 100644
--- a/packages/browser-pool/src/abstract-classes/browser-plugin.ts
+++ b/packages/browser-pool/src/abstract-classes/browser-plugin.ts
@@ -4,8 +4,7 @@ import merge from 'lodash.merge';
import type { LaunchContextOptions } from '../launch-context.js';
import { LaunchContext } from '../launch-context.js';
-import type { RemoteConnection, RemoteConnectionParameters } from '../remote-browser-pool.js';
-import { sanitizeEndpointForLog, type UnwrapPromise } from '../utils.js';
+import type { UnwrapPromise } from '../utils.js';
import type { BrowserController } from './browser-controller.js';
/**
@@ -123,18 +122,6 @@ export abstract class BrowserPlugin<
readonly ignoreProxyCertificate?: boolean;
- /**
- * Set by {@apilink RemoteBrowserPool} when this plugin connects to a remote browser service instead of
- * launching locally. Holds the bridge the plugin uses to resolve endpoints and release sessions; all
- * remote-session policy lives in the pool, not here.
- *
- * @internal
- */
- remoteConnection?: RemoteConnection;
-
- /** Static connect() parameters for a remote connection (protocol, headers, …). @internal */
- remoteConnectionParameters?: RemoteConnectionParameters;
-
constructor(library: Library, options: BrowserPluginOptions<LibraryOptions> = {}) {
const {
launchOptions = {} as LibraryOptions,
@@ -155,54 +142,6 @@ export abstract class BrowserPlugin<
this.ignoreProxyCertificate = ignoreProxyCertificate;
}
- /**
- * Configures this plugin to connect to a remote browser using the given {@apilink RemoteConnection}.
- * Called by {@apilink RemoteBrowserPool}; subclasses may override to apply library-specific defaults
- * (e.g. forcing incognito pages).
- *
- * @internal
- */
- useRemoteConnection(connection: RemoteConnection, parameters: RemoteConnectionParameters = {}): void {
- this.remoteConnection = connection;
- this.remoteConnectionParameters = parameters;
- }
-
- /**
- * Resolves a remote endpoint via the injected {@apilink RemoteConnection}, stores the session token on
- * the launch context (so the controller can release it on close), and runs the library-specific `connect`.
- * On failure the session is released and the error is wrapped in a {@apilink BrowserLaunchError}.
- *
- * Subclasses implement only the `connect` callback — the resolve / token / release / error-wrap scaffolding
- * lives here so it stays identical across plugins.
- */
- protected async connectToRemoteBrowser(
- launchContext: LaunchContext<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>,
- connect: (url: string) => Promise<LaunchResult>,
- ): Promise<LaunchResult> {
- const connection = this.remoteConnection!;
-
- let url: string;
- let token: number;
- try {
- ({ url, token } = await connection.resolve({ proxyUrl: launchContext.proxyUrl }));
- } catch (cause) {
- throw new BrowserLaunchError('Failed to resolve the remote browser endpoint.', { cause });
- }
-
- launchContext.remoteToken = token;
-
- try {
- return await connect(url);
- } catch (cause) {
- await connection.release(token);
- throw new BrowserLaunchError(
- `Failed to connect to remote browser at "${sanitizeEndpointForLog(url)}". ` +
- 'Check that the endpoint is reachable and accepts the configured protocol.',
- { cause },
- );
- }
- }
-
/**
* Creates a `LaunchContext` with all the information needed
* to launch a browser. Aside from library specific launch options,
@@ -220,7 +159,7 @@ export abstract class BrowserPlugin<
userDataDir = this.userDataDir,
browserPerProxy = this.browserPerProxy,
ignoreProxyCertificate = this.ignoreProxyCertificate,
- isRemote = !!this.remoteConnection,
+ isRemote,
} = options;
return new LaunchContext({
@@ -256,16 +195,15 @@ export abstract class BrowserPlugin<
NewPageResult
> = this.createLaunchContext(),
): Promise<LaunchResult> {
- // launchOptions is only used by the local launch path below — remote connections ignore it.
launchContext.launchOptions ??= {} as LibraryOptions;
const { proxyUrl, launchOptions } = launchContext;
- if (proxyUrl && !launchContext.isRemote) {
+ if (proxyUrl) {
await this.addProxyToLaunchOptions(launchContext);
}
- if (!launchContext.isRemote && this.isChromiumBasedBrowser(launchContext)) {
+ if (this.isChromiumBasedBrowser(launchContext)) {
// This will set the args for chromium based browsers to hide the webdriver.
(launchOptions as Dictionary).args = this.#mergeArgsToHideWebdriver(launchOptions!.args);
// When User-Agent is not set, and we're using Chromium in headless mode,
@@ -277,10 +215,6 @@ export abstract class BrowserPlugin<
}
}
- if (launchContext.isRemote) {
- this.log.info('Connecting to remote browser (skipping local proxy and webdriver stealth configuration).');
- }
-
return this._launch(launchContext);
}
diff --git a/packages/browser-pool/src/browser-pool.ts b/packages/browser-pool/src/browser-pool.ts
index 9ba7f42a2..42ebc0555 100644
--- a/packages/browser-pool/src/browser-pool.ts
+++ b/packages/browser-pool/src/browser-pool.ts
@@ -1,5 +1,3 @@
-import { AsyncResource } from 'node:async_hooks';
-
import { type CrawleeLogger, SessionError, serviceLocator } from '@crawlee/core';
import type { IBrowserPool, NewPageOptions, PageState } from '@crawlee/types';
import { parseArgument, schemas } from '@crawlee/utils/internal';
@@ -29,10 +27,12 @@ import type { InferBrowserPluginArray, UnwrapPromise } from './utils.js';
const PAGE_CLOSE_TIMEOUT_MILLIS = 5000;
const PAGE_CLOSE_KILL_TIMEOUT_MILLIS = 1000;
const BROWSER_KILLER_INTERVAL_MILLIS = 10 * 1000;
+const SLOT_POLL_INTERVAL_MILLIS = 500;
const browserPoolOptionsSchema = z.strictObject({
browserPlugins: schemas.anyArray.refine((value) => value.length >= 1, 'Expected a non-empty array'),
maxOpenPagesPerBrowser: schemas.anyNumber.default(20),
+ maxOpenBrowsers: schemas.anyNumber.default(Infinity),
retireBrowserAfterPageCount: schemas.anyNumber.default(100),
operationTimeoutSecs: schemas.anyNumber.default(15),
closeInactiveBrowserAfterSecs: schemas.anyNumber.default(300),
@@ -93,6 +93,16 @@ export interface BrowserPoolOptions<Plugin extends BrowserPlugin = BrowserPlugin
* @default 20
*/
maxOpenPagesPerBrowser?: number;
+ /**
+ * Maximum number of browser processes alive at once. A browser counts from the moment its launch starts until it
+ * actually closes — a retired browser that is still finishing its last pages still occupies a slot. Once the
+ * limit is reached, {@apilink BrowserPool.newPage|newPage} waits for a slot (a browser closing, or an open
+ * browser with page capacity to spare) instead of launching another. Set it to a remote browser service's
+ * concurrent-session limit to avoid `429` errors.
+ *
+ * @default Infinity
+ */
+ maxOpenBrowsers?: number;
/**
* Browsers tend to get bloated after processing a lot of pages. This option
* configures the maximum number of processed pages after which the browser will
@@ -328,9 +338,6 @@ export class BrowserPool<
{
browserPlugins: BrowserPlugins;
- /** @internal */
- maxOpenBrowsers: number;
-
/** @internal */
fingerprintOptions: FingerprintOptions;
@@ -343,6 +350,7 @@ export class BrowserPool<
fingerprintCache?: QuickLRU<string, BrowserFingerprintWithHeaders>;
readonly #maxOpenPagesPerBrowser: number;
+ readonly #maxOpenBrowsers: number;
readonly #retireBrowserAfterPageCount: number;
readonly #operationTimeoutMillis: number;
readonly #closeInactiveBrowserAfterMillis: number;
@@ -373,6 +381,9 @@ export class BrowserPool<
#limiter = pLimit(1);
#log!: CrawleeLogger;
+ /** Shared by all `newPage` callers waiting for a free slot, so they don't each register their own listeners. */
+ #capacityChange?: Promise<void>;
+
constructor(options: Options & BrowserPoolHooks<BrowserControllerReturn, LaunchContextReturn, PageReturn>) {
super();
this.#log = serviceLocator.getLogger().child({ prefix: 'BrowserPool' });
@@ -380,6 +391,7 @@ export class BrowserPool<
const {
browserPlugins,
maxOpenPagesPerBrowser,
+ maxOpenBrowsers,
retireBrowserAfterPageCount,
operationTimeoutSecs,
closeInactiveBrowserAfterSecs,
@@ -410,7 +422,7 @@ export class BrowserPool<
}
this.browserPlugins = browserPlugins as unknown as BrowserPlugins;
- this.maxOpenBrowsers = Infinity;
+ this.#maxOpenBrowsers = maxOpenBrowsers;
this.fingerprintOptions = fingerprintOptions;
this.#maxOpenPagesPerBrowser = maxOpenPagesPerBrowser;
this.#retireBrowserAfterPageCount = retireBrowserAfterPageCount;
@@ -498,32 +510,21 @@ export class BrowserPool<
throw new Error('Provided browserPlugin is not one of the plugins used by BrowserPool.');
}
- // Bind the limiter callback to the current async-hooks context. p-limit
- // otherwise resumes queued callbacks in the previous task's
- // AsyncLocalStorage context, leaking aborted cancelTasks across unrelated
- // requests (https://github.com/apify/crawlee/issues/3670). Mirrors the
- // fix p-limit landed upstream in v5 (sindresorhus/p-limit#71); v5 is an
- // ESM-only rewrite, so we can't bump it in Crawlee v3.
- // Besides the cancelTask leak, the wrapper also keeps the per-request *storage transaction*
- // ALS-scoped: without it, a queued callback would resume in the previous request's async
- // context and run request B's storage writes inside request A's transaction.
- // TODO(crawlee@v4): bump p-limit to v5 and drop this AsyncResource.bind wrapper.
// Limiter is necessary - https://github.com/apify/crawlee/issues/1126
- return this.#limiter(
- AsyncResource.bind(async () => {
- let browserController = this.#pickBrowserWithFreeCapacity(browserPlugin, { proxyUrl });
-
- if (!browserController)
- browserController = await this.#launchBrowser(id, {
- browserPlugin,
- proxyUrl,
- ignoreTlsErrors,
- });
- tryCancel();
-
- return await this.#createPageForBrowser(id, browserController, pageOptions, proxyUrl, ignoreTlsErrors);
- }),
- );
+ return this.#limiter(async () => {
+ let browserController = this.#pickBrowserWithFreeCapacity(browserPlugin, { proxyUrl });
+
+ // Checked under the limiter so concurrent waiters can't all pass on the same freed slot.
+ while (!browserController && !this.hasFreeBrowserSlot()) {
+ await this.#nextCapacityChange();
+ browserController = this.#pickBrowserWithFreeCapacity(browserPlugin, { proxyUrl });
+ }
+
+ browserController ??= await this.#launchBrowser(id, { browserPlugin, proxyUrl, ignoreTlsErrors });
+ tryCancel();
+
+ return await this.#createPageForBrowser(id, browserController, pageOptions, proxyUrl, ignoreTlsErrors);
+ });
}
/**
@@ -1037,11 +1038,6 @@ export class BrowserPool<
* Returns `true` if the pool can accept a new browser launch without exceeding `maxOpenBrowsers`.
* Counts starting, active, and retired browsers.
*
- * A plain `BrowserPool` leaves `maxOpenBrowsers` at `Infinity`, so this only returns `false` when something
- * has set a cap — {@apilink RemoteBrowserPool} does, from its own
- * {@apilink RemoteBrowserPoolOptions.maxOpenBrowsers|`maxOpenBrowsers`} option. There is no
- * `BrowserPoolOptions` key for it.
- *
* @internal
*/
hasFreeBrowserSlot(): boolean {
@@ -1049,19 +1045,30 @@ export class BrowserPool<
this.#startingBrowserControllers.size +
this.activeBrowserControllers.size +
this.retiredBrowserControllers.size;
- return total < this.maxOpenBrowsers;
+ return total < this.#maxOpenBrowsers;
}
/**
- * Returns `true` if any active browser has room for another page.
- *
- * @internal
+ * Resolves on the next browser-retired / page-closed event, or after a short fallback interval. All
+ * concurrently-waiting `newPage` calls share a single promise (and a single pair of event listeners) per tick.
*/
- hasActiveBrowserWithFreeCapacity(): boolean {
- for (const controller of this.activeBrowserControllers) {
- if (controller.activePages < this.#maxOpenPagesPerBrowser) return true;
- }
- return false;
+ #nextCapacityChange(): Promise<void> {
+ this.#capacityChange ??= new Promise<void>((resolve) => {
+ const done = () => {
+ clearTimeout(timer);
+ this.off(BROWSER_POOL_EVENTS.BROWSER_RETIRED, done);
+ this.off(BROWSER_POOL_EVENTS.PAGE_CLOSED, done);
+ this.#capacityChange = undefined;
+ resolve();
+ };
+
+ const timer = setTimeout(done, SLOT_POLL_INTERVAL_MILLIS);
+ timer.unref?.();
+ this.once(BROWSER_POOL_EVENTS.BROWSER_RETIRED, done);
+ this.once(BROWSER_POOL_EVENTS.PAGE_CLOSED, done);
+ });
+
+ return this.#capacityChange;
}
#initializeFingerprinting(): void {
diff --git a/packages/browser-pool/src/index.ts b/packages/browser-pool/src/index.ts
index 33638b088..8f6098081 100644
--- a/packages/browser-pool/src/index.ts
+++ b/packages/browser-pool/src/index.ts
@@ -24,7 +24,9 @@
*/
export * from './browser-pool.js';
export * from './playwright/playwright-plugin.js';
+export * from './playwright/remote-playwright-plugin.js';
export * from './puppeteer/puppeteer-plugin.js';
+export * from './puppeteer/remote-puppeteer-plugin.js';
export * from './events.js';
export type { FingerprintGeneratorOptions } from './fingerprinting/types.js';
export { BrowserName, DeviceCategory, OperatingSystemsName } from './fingerprinting/types.js';
@@ -47,15 +49,7 @@ export { BrowserPlugin, BrowserLaunchError, DEFAULT_USER_AGENT } from './abstrac
export type { LaunchContextOptions } from './launch-context.js';
export { LaunchContext } from './launch-context.js';
export { RemoteBrowserProvider } from './remote-browser-provider.js';
-export { RemoteBrowserPool } from './remote-browser-pool.js';
-export type {
- RemoteBrowserPoolOptions,
- CrawlerRemoteBrowserOptions,
- RemoteBrowserEndpoint,
- ResolvedRemoteEndpoint,
- RemoteConnection,
- RemoteConnectionParameters,
-} from './remote-browser-pool.js';
+export type { RemoteBrowserEndpoint, RemoteBrowserOptions, ResolvedRemoteEndpoint } from './remote-browser-plugin.js';
export type { InferBrowserPluginArray, UnwrapPromise } from './utils.js';
export { anonymizeProxySugar, type AnonymizeProxySugarOptions } from './anonymize-proxy.js';
export type { IBrowserPool, NewPageOptions } from '@crawlee/types';
diff --git a/packages/browser-pool/src/launch-context.ts b/packages/browser-pool/src/launch-context.ts
index 858b3fa6c..1c31a9a3a 100644
--- a/packages/browser-pool/src/launch-context.ts
+++ b/packages/browser-pool/src/launch-context.ts
@@ -86,13 +86,6 @@ export class LaunchContext<
fingerprint?: BrowserFingerprintWithHeaders;
- /**
- * Token identifying the remote browser session this context connected to, set by the plugin and read by
- * the {@apilink RemoteBrowserPool} to release the session on close. Only present for remote connections.
- * @internal
- */
- remoteToken?: number;
-
[K: PropertyKey]: unknown;
constructor(options: LaunchContextOptions<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>) {
@@ -121,7 +114,7 @@ export class LaunchContext<
// Computed here (not in a field initializer) so that all fields already exist; the accessors live on
// the prototype, so they are never own keys and have to be listed explicitly.
- this.#reservedFieldNames = [...Reflect.ownKeys(this), 'proxyUrl', 'remoteToken', 'extend'];
+ this.#reservedFieldNames = [...Reflect.ownKeys(this), 'proxyUrl', 'extend'];
}
/**
diff --git a/packages/browser-pool/src/playwright/playwright-plugin.ts b/packages/browser-pool/src/playwright/playwright-plugin.ts
index 0dc3add59..e3d9175a2 100644
--- a/packages/browser-pool/src/playwright/playwright-plugin.ts
+++ b/packages/browser-pool/src/playwright/playwright-plugin.ts
@@ -6,7 +6,6 @@ import { BrowserPlugin } from '../abstract-classes/browser-plugin.js';
import { anonymizeProxySugar } from '../anonymize-proxy.js';
import type { LaunchContext } from '../launch-context.js';
import { getLocalProxyAddress } from '../proxy-server.js';
-import type { RemoteConnection, RemoteConnectionParameters } from '../remote-browser-pool.js';
import type { SafeParameters } from '../utils.js';
import { PlaywrightBrowser as PlaywrightBrowserWithPersistentContext } from './playwright-browser.js';
import { PlaywrightController } from './playwright-controller.js';
@@ -18,36 +17,7 @@ export class PlaywrightPlugin extends BrowserPlugin<
> {
#browserVersion?: string;
- /**
- * Playwright remote connections only support incognito pages — `connect()` / `connectOverCDP()` don't
- * accept persistent contexts. Force it on (and inform the user) when wired for a remote connection.
- *
- * @internal
- */
- override useRemoteConnection(connection: RemoteConnection, parameters: RemoteConnectionParameters = {}): void {
- super.useRemoteConnection(connection, parameters);
-
- if (!this.useIncognitoPages) {
- this.log.info(
- 'Remote Playwright connection — useIncognitoPages forced to true. ' +
- 'Pages will not share cookies/storage between each other; use the SessionPool for shared state.',
- );
- }
- this.useIncognitoPages = true;
- }
-
protected async _launch(launchContext: LaunchContext<BrowserType>): Promise<PlaywrightBrowser> {
- if (this.remoteConnection) {
- return this.connectToRemoteBrowser(launchContext, async (url) => {
- const connectOptions = (this.remoteConnectionParameters?.connectOptions ?? {}) as any;
- if (this.remoteConnectionParameters?.protocol === 'playwright') {
- this.log.info('Connecting to remote browser via connect (Playwright WebSocket).');
- return this.library.connect(url, connectOptions);
- }
- this.log.info('Connecting to remote browser via connectOverCDP.');
- return this.library.connectOverCDP(url, connectOptions);
- });
- }
const { launchOptions, useIncognitoPages, userDataDir, proxyUrl } = launchContext;
let browser: PlaywrightBrowser;
diff --git a/packages/browser-pool/src/playwright/remote-playwright-plugin.ts b/packages/browser-pool/src/playwright/remote-playwright-plugin.ts
new file mode 100644
index 000000000..c929131a0
--- /dev/null
+++ b/packages/browser-pool/src/playwright/remote-playwright-plugin.ts
@@ -0,0 +1,63 @@
+import type { Browser as PlaywrightBrowser, BrowserType } from 'playwright';
+
+import type { BrowserPluginOptions, CreateLaunchContextOptions } from '../abstract-classes/browser-plugin.js';
+import type { LaunchContext } from '../launch-context.js';
+import { connectRemoteBrowser, type RemoteBrowserOptions } from '../remote-browser-plugin.js';
+import type { SafeParameters } from '../utils.js';
+import { PlaywrightPlugin } from './playwright-plugin.js';
+
+export interface RemotePlaywrightPluginOptions
+ extends BrowserPluginOptions<SafeParameters<BrowserType['launch']>[0]>, RemoteBrowserOptions {
+ /**
+ * Which protocol to connect with. `'cdp'` uses `connectOverCDP()` (the default), `'playwright'` uses
+ * `connect()` (Playwright's own WebSocket protocol, for endpoints started with `launchServer()`).
+ */
+ protocol?: 'cdp' | 'playwright';
+}
+
+/**
+ * A {@apilink PlaywrightPlugin} that connects to a remote browser service (Browserbase, Browserless, Steel, …)
+ * instead of launching locally. `launchOptions` are ignored — the remote service owns the browser.
+ *
+ * Remote connections only support incognito pages (`connect()` / `connectOverCDP()` don't accept persistent
+ * contexts), so `useIncognitoPages` is always `true`.
+ */
+export class RemotePlaywrightPlugin extends PlaywrightPlugin {
+ readonly #remote: RemotePlaywrightPluginOptions;
+
+ constructor(library: BrowserType, options: RemotePlaywrightPluginOptions) {
+ super(library, { ...options, useIncognitoPages: true });
+ this.#remote = options;
+
+ if (options.useIncognitoPages === false) {
+ this.log.info(
+ 'Remote Playwright connection — useIncognitoPages forced to true. ' +
+ 'Pages will not share cookies/storage between each other; use the SessionPool for shared state.',
+ );
+ }
+ }
+
+ override createLaunchContext(options: CreateLaunchContextOptions<BrowserType> = {}): LaunchContext<BrowserType> {
+ return super.createLaunchContext({ ...options, isRemote: true });
+ }
+
+ /** Skips the local proxy and webdriver-stealth preparation; the remote service owns the browser. */
+ override async launch(
+ launchContext: LaunchContext<BrowserType> = this.createLaunchContext(),
+ ): Promise<PlaywrightBrowser> {
+ return this._launch(launchContext);
+ }
+
+ protected override async _launch(launchContext: LaunchContext<BrowserType>): Promise<PlaywrightBrowser> {
+ const { protocol, connectOptions = {} } = this.#remote;
+
+ return connectRemoteBrowser(this.#remote, launchContext.proxyUrl, this.log, async (url) => {
+ if (protocol === 'playwright') {
+ this.log.info('Connecting to remote browser via connect (Playwright WebSocket).');
+ return this.library.connect(url, connectOptions);
+ }
+ this.log.info('Connecting to remote browser via connectOverCDP.');
+ return this.library.connectOverCDP(url, connectOptions);
+ });
+ }
+}
diff --git a/packages/browser-pool/src/puppeteer/puppeteer-controller.ts b/packages/browser-pool/src/puppeteer/puppeteer-controller.ts
index c912b879e..efa799c3a 100644
--- a/packages/browser-pool/src/puppeteer/puppeteer-controller.ts
+++ b/packages/browser-pool/src/puppeteer/puppeteer-controller.ts
@@ -1,7 +1,5 @@
import type { Cookie } from '@crawlee/types';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type Puppeteer from 'puppeteer';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type * as PuppeteerTypes from 'puppeteer';
import { tryCancel } from '@apify/timeout';
diff --git a/packages/browser-pool/src/puppeteer/puppeteer-plugin.ts b/packages/browser-pool/src/puppeteer/puppeteer-plugin.ts
index 620780dc4..e317aa2d9 100644
--- a/packages/browser-pool/src/puppeteer/puppeteer-plugin.ts
+++ b/packages/browser-pool/src/puppeteer/puppeteer-plugin.ts
@@ -1,128 +1,112 @@
import { readFile } from 'node:fs/promises';
import type { Dictionary } from '@crawlee/types';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type Puppeteer from 'puppeteer';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type * as PuppeteerTypes from 'puppeteer';
import { BrowserPlugin } from '../abstract-classes/browser-plugin.js';
import { anonymizeProxySugar } from '../anonymize-proxy.js';
import type { LaunchContext } from '../launch-context.js';
-import type { RemoteConnection, RemoteConnectionParameters } from '../remote-browser-pool.js';
import { noop } from '../utils.js';
import type { PuppeteerNewPageOptions } from './puppeteer-controller.js';
import { PuppeteerController } from './puppeteer-controller.js';
const PROXY_SERVER_ARG = '--proxy-server=';
+export type PuppeteerLaunchContext = LaunchContext<
+ typeof Puppeteer,
+ PuppeteerTypes.LaunchOptions,
+ PuppeteerTypes.Browser,
+ PuppeteerNewPageOptions
+>;
+
export class PuppeteerPlugin extends BrowserPlugin<
typeof Puppeteer,
PuppeteerTypes.LaunchOptions,
PuppeteerTypes.Browser,
PuppeteerNewPageOptions
> {
- /**
- * Pages share cookies/storage on the remote browser (Puppeteer defaults to non-incognito).
- *
- * @internal
- */
- override useRemoteConnection(connection: RemoteConnection, parameters: RemoteConnectionParameters = {}): void {
- super.useRemoteConnection(connection, parameters);
+ protected async _launch(launchContext: PuppeteerLaunchContext): Promise<PuppeteerTypes.Browser> {
+ const oldPuppeteerVersion = await this.isOldPuppeteerVersion();
+ const { launchOptions, userDataDir, experimentalContainers, proxyUrl } = launchContext;
- if (!this.useIncognitoPages) {
- this.log.info(
- 'Remote Puppeteer connection — pages will share cookies and storage on the remote ' +
- 'browser instance (useIncognitoPages defaults to false).',
- );
+ if (experimentalContainers) {
+ throw new Error('Experimental containers are only available with Playwright');
}
- }
- protected async _launch(
- launchContext: LaunchContext<
- typeof Puppeteer,
- PuppeteerTypes.LaunchOptions,
- PuppeteerTypes.Browser,
- PuppeteerNewPageOptions
- >,
- ): Promise<PuppeteerTypes.Browser> {
- let oldPuppeteerVersion = false;
+ launchOptions!.userDataDir = launchOptions!.userDataDir ?? userDataDir;
- try {
- const jsonPath = require.resolve('puppeteer/package.json');
- const parsed = JSON.parse(await readFile(jsonPath, 'utf-8'));
- const version = +parsed.version.split('.')[0];
- oldPuppeteerVersion = version < 22;
- } catch {
- // ignore
+ if (launchOptions!.headless === false) {
+ if (Array.isArray(launchOptions!.args)) {
+ launchOptions!.args.push('--disable-site-isolation-trials');
+ } else {
+ launchOptions!.args = ['--disable-site-isolation-trials'];
+ }
}
- const { useIncognitoPages, proxyUrl, ignoreProxyCertificate } = launchContext;
-
- let browser: PuppeteerTypes.Browser;
-
- if (this.remoteConnection) {
- browser = await this.connectToRemoteBrowser(launchContext, async (url) => {
- const connectOptions = this.remoteConnectionParameters?.connectOptions ?? {};
- this.log.info('Connecting to remote browser via connect (CDP).');
- return this.library.connect({ ...connectOptions, browserWSEndpoint: url });
- });
- } else {
- const { launchOptions, userDataDir, experimentalContainers } = launchContext;
+ if (launchOptions!.headless === true && oldPuppeteerVersion) {
+ launchOptions!.headless = 'new' as any;
+ }
- if (experimentalContainers) {
- throw new Error('Experimental containers are only available with Playwright');
- }
+ const [anonymizedProxyUrl, close] = await anonymizeProxySugar(proxyUrl, undefined, undefined, {
+ ignoreProxyCertificate: launchContext.ignoreProxyCertificate,
+ });
- launchOptions!.userDataDir = launchOptions!.userDataDir ?? userDataDir;
+ if (proxyUrl) {
+ const proxyArg = `${PROXY_SERVER_ARG}${anonymizedProxyUrl ?? proxyUrl}`;
- if (launchOptions!.headless === false) {
- if (Array.isArray(launchOptions!.args)) {
- launchOptions!.args.push('--disable-site-isolation-trials');
- } else {
- launchOptions!.args = ['--disable-site-isolation-trials'];
- }
+ if (Array.isArray(launchOptions!.args)) {
+ launchOptions!.args.push(proxyArg);
+ } else {
+ launchOptions!.args = [proxyArg];
}
+ }
- if (launchOptions!.headless === true && oldPuppeteerVersion) {
- launchOptions!.headless = 'new' as any;
- }
+ let browser: PuppeteerTypes.Browser;
+ try {
+ browser = await this.library.launch(launchOptions);
- {
- const [anonymizedProxyUrl, close] = await anonymizeProxySugar(proxyUrl, undefined, undefined, {
- ignoreProxyCertificate: launchContext.ignoreProxyCertificate,
+ if (anonymizedProxyUrl) {
+ browser.on('disconnected', async () => {
+ await close();
});
+ }
+ } catch (error: any) {
+ await close();
+
+ this.throwAugmentedLaunchError(
+ error,
+ launchContext.launchOptions?.executablePath,
+ '`apify/actor-node-puppeteer-chrome`',
+ "Try installing a browser, if it's missing, by running `npx @puppeteer/browsers install chromium --path [path]` and pointing `executablePath` to the downloaded executable (https://pptr.dev/browsers-api)",
+ );
+ }
- if (proxyUrl) {
- const proxyArg = `${PROXY_SERVER_ARG}${anonymizedProxyUrl ?? proxyUrl}`;
-
- if (Array.isArray(launchOptions!.args)) {
- launchOptions!.args.push(proxyArg);
- } else {
- launchOptions!.args = [proxyArg];
- }
- }
-
- try {
- browser = await this.library.launch(launchOptions);
-
- if (anonymizedProxyUrl) {
- browser.on('disconnected', async () => {
- await close();
- });
- }
- } catch (error: any) {
- await close();
+ return this.wrapBrowser(browser, launchContext, oldPuppeteerVersion);
+ }
- this.throwAugmentedLaunchError(
- error,
- launchContext.launchOptions?.executablePath,
- '`apify/actor-node-puppeteer-chrome`',
- "Try installing a browser, if it's missing, by running `npx @puppeteer/browsers install chromium --path [path]` and pointing `executablePath` to the downloaded executable (https://pptr.dev/browsers-api)",
- );
- }
- }
+ /** @internal */
+ protected async isOldPuppeteerVersion(): Promise<boolean> {
+ try {
+ const jsonPath = require.resolve('puppeteer/package.json');
+ const parsed = JSON.parse(await readFile(jsonPath, 'utf-8'));
+ return +parsed.version.split('.')[0] < 22;
+ } catch {
+ return false;
}
+ }
+
+ /**
+ * Attaches page crash handling and the incognito-context-per-page `newPage` proxy. Shared by the local launch
+ * and {@apilink RemotePuppeteerPlugin}.
+ * @internal
+ */
+ protected wrapBrowser(
+ browser: PuppeteerTypes.Browser,
+ launchContext: PuppeteerLaunchContext,
+ oldPuppeteerVersion: boolean,
+ ): PuppeteerTypes.Browser {
+ const { useIncognitoPages, proxyUrl, ignoreProxyCertificate, isRemote } = launchContext;
const targetCreatedHandler = async (target: PuppeteerTypes.Target) => {
try {
@@ -141,8 +125,7 @@ export class PuppeteerPlugin extends BrowserPlugin<
browser.on('targetcreated', targetCreatedHandler);
- // Clean up the listener when a remote browser disconnects to prevent leaks
- if (this.remoteConnection) {
+ if (isRemote) {
browser.once('disconnected', () => {
browser.off('targetcreated', targetCreatedHandler);
});
@@ -173,8 +156,8 @@ export class PuppeteerPlugin extends BrowserPlugin<
let page: PuppeteerTypes.Page;
if (useIncognitoPages) {
- // Skip proxy setup for remote connections — proxy is managed by the remote service.
- const effectiveProxyUrl = this.remoteConnection ? undefined : proxyUrl;
+ // Proxy is managed by the remote service.
+ const effectiveProxyUrl = isRemote ? undefined : proxyUrl;
const [anonymizedProxyUrl, close] = effectiveProxyUrl
? await anonymizeProxySugar(effectiveProxyUrl, undefined, undefined, {
ignoreProxyCertificate,
diff --git a/packages/browser-pool/src/puppeteer/remote-puppeteer-plugin.ts b/packages/browser-pool/src/puppeteer/remote-puppeteer-plugin.ts
new file mode 100644
index 000000000..3844c2800
--- /dev/null
+++ b/packages/browser-pool/src/puppeteer/remote-puppeteer-plugin.ts
@@ -0,0 +1,57 @@
+import type Puppeteer from 'puppeteer';
+import type * as PuppeteerTypes from 'puppeteer';
+
+import type { BrowserPluginOptions, CreateLaunchContextOptions } from '../abstract-classes/browser-plugin.js';
+import { connectRemoteBrowser, type RemoteBrowserOptions } from '../remote-browser-plugin.js';
+import type { PuppeteerNewPageOptions } from './puppeteer-controller.js';
+import { type PuppeteerLaunchContext, PuppeteerPlugin } from './puppeteer-plugin.js';
+
+export interface RemotePuppeteerPluginOptions
+ extends BrowserPluginOptions<PuppeteerTypes.LaunchOptions>, RemoteBrowserOptions {}
+
+/**
+ * A {@apilink PuppeteerPlugin} that connects to a remote browser service (Browserbase, Browserless, Steel, …)
+ * over CDP instead of launching locally. `launchOptions` are ignored — the remote service owns the browser.
+ */
+export class RemotePuppeteerPlugin extends PuppeteerPlugin {
+ readonly #remote: RemotePuppeteerPluginOptions;
+
+ constructor(library: typeof Puppeteer, options: RemotePuppeteerPluginOptions) {
+ super(library, options);
+ this.#remote = options;
+
+ if (!this.useIncognitoPages) {
+ this.log.info(
+ 'Remote Puppeteer connection — pages will share cookies and storage on the remote ' +
+ 'browser instance (useIncognitoPages defaults to false).',
+ );
+ }
+ }
+
+ override createLaunchContext(
+ options: CreateLaunchContextOptions<
+ typeof Puppeteer,
+ PuppeteerTypes.LaunchOptions,
+ PuppeteerTypes.Browser,
+ PuppeteerNewPageOptions
+ > = {},
+ ): PuppeteerLaunchContext {
+ return super.createLaunchContext({ ...options, isRemote: true });
+ }
+
+ /** Skips the local proxy and webdriver-stealth preparation; the remote service owns the browser. */
+ override async launch(
+ launchContext: PuppeteerLaunchContext = this.createLaunchContext(),
+ ): Promise<PuppeteerTypes.Browser> {
+ return this._launch(launchContext);
+ }
+
+ protected override async _launch(launchContext: PuppeteerLaunchContext): Promise<PuppeteerTypes.Browser> {
+ const browser = await connectRemoteBrowser(this.#remote, launchContext.proxyUrl, this.log, async (url) => {
+ this.log.info('Connecting to remote browser via connect (CDP).');
+ return this.library.connect({ ...this.#remote.connectOptions, browserWSEndpoint: url });
+ });
+
+ return this.wrapBrowser(browser, launchContext, await this.isOldPuppeteerVersion());
+ }
+}
diff --git a/packages/browser-pool/src/remote-browser-plugin.ts b/packages/browser-pool/src/remote-browser-plugin.ts
new file mode 100644
index 000000000..acba90a26
--- /dev/null
+++ b/packages/browser-pool/src/remote-browser-plugin.ts
@@ -0,0 +1,116 @@
+import type { CrawleeLogger } from '@crawlee/core';
+
+import { BrowserLaunchError } from './abstract-classes/browser-plugin.js';
+import { RemoteBrowserProvider } from './remote-browser-provider.js';
+import { sanitizeEndpointForLog } from './utils.js';
+
+/**
+ * The result of resolving a remote browser endpoint: the URL to connect to plus an optional opaque
+ * `context` object that is handed back to `release`.
+ */
+export interface ResolvedRemoteEndpoint {
+ /** The WebSocket / CDP URL to connect to. */
+ url: string;
+ /** Opaque per-session data (e.g. a session ID) passed back to `release`. */
+ context?: Record<string, unknown>;
+}
+
+/**
+ * A remote browser endpoint: either a static URL string, or a function called once per browser launch
+ * that returns the URL (optionally with a `context` for `release`). The function receives the proxy URL
+ * Crawlee resolved for the browser, so it can be forwarded to services that accept an external proxy.
+ */
+export type RemoteBrowserEndpoint =
+ | string
+ | ((options?: { proxyUrl?: string }) => string | ResolvedRemoteEndpoint | Promise<string | ResolvedRemoteEndpoint>);
+
+/** Options shared by all remote browser plugins. */
+export interface RemoteBrowserOptions {
+ /**
+ * The remote browser endpoint: a static URL, a function returning one per launch, or a
+ * {@apilink RemoteBrowserProvider} instance encapsulating a session create/release lifecycle.
+ */
+ endpoint: RemoteBrowserEndpoint | RemoteBrowserProvider<any>;
+ /**
+ * Cleanup callback invoked when the browser disconnects or the connection fails right after the endpoint
+ * resolved. Receives the `context` returned by a function endpoint. Errors are caught and logged. Ignored
+ * when `endpoint` is a {@apilink RemoteBrowserProvider} (its own `release()` is used instead).
+ */
+ release?: (info: { endpoint: string; context?: Record<string, unknown> }) => unknown;
+ /** Extra options forwarded to the library `connect()` call (endpoint excluded). */
+ connectOptions?: Record<string, unknown>;
+}
+
+/**
+ * Resolves `endpoint` for one launch, runs the library-specific `connect`, and ties the session's `release` to
+ * the browser's `disconnected` event. On connect failure the session is released and the error is wrapped in a
+ * {@apilink BrowserLaunchError}.
+ *
+ * @internal
+ */
+export async function connectRemoteBrowser<
+ Browser extends { on(event: 'disconnected', listener: () => void): unknown },
+>(
+ options: RemoteBrowserOptions,
+ proxyUrl: string | undefined,
+ log: CrawleeLogger,
+ connect: (url: string) => Promise<Browser>,
+): Promise<Browser> {
+ let resolved: ResolvedRemoteEndpoint;
+ try {
+ resolved = await resolveEndpoint(options.endpoint, proxyUrl);
+ } catch (cause) {
+ throw new BrowserLaunchError('Failed to resolve the remote browser endpoint.', { cause });
+ }
+
+ let released = false;
+ const release = async () => {
+ if (released) return;
+ released = true;
+ try {
+ if (options.endpoint instanceof RemoteBrowserProvider) {
+ await options.endpoint.release(resolved.context ?? {});
+ } else {
+ await options.release?.({ endpoint: resolved.url, context: resolved.context });
+ }
+ } catch (err) {
+ log.warning('Remote browser release() failed.', { error: (err as Error)?.message });
+ }
+ };
+
+ let browser: Browser;
+ try {
+ browser = await connect(resolved.url);
+ } catch (cause) {
+ await release();
+ throw new BrowserLaunchError(
+ `Failed to connect to remote browser at "${sanitizeEndpointForLog(resolved.url)}". ` +
+ 'Check that the endpoint is reachable and accepts the configured protocol.',
+ { cause },
+ );
+ }
+
+ browser.on('disconnected', release);
+ return browser;
+}
+
+async function resolveEndpoint(
+ endpoint: RemoteBrowserOptions['endpoint'],
+ proxyUrl: string | undefined,
+): Promise<ResolvedRemoteEndpoint> {
+ const resolved =
+ endpoint instanceof RemoteBrowserProvider
+ ? await endpoint.connect({ proxyUrl })
+ : typeof endpoint === 'function'
+ ? await endpoint({ proxyUrl })
+ : endpoint;
+
+ if (typeof resolved === 'string') {
+ if (!resolved) throw new Error('Remote browser endpoint resolved to an empty string.');
+ return { url: resolved };
+ }
+ if (!resolved?.url) {
+ throw new Error("Remote browser endpoint() must return a URL string or an object with a non-empty 'url'.");
+ }
+ return resolved;
+}
diff --git a/packages/browser-pool/src/remote-browser-pool.ts b/packages/browser-pool/src/remote-browser-pool.ts
deleted file mode 100644
index 9c3865a2e..000000000
--- a/packages/browser-pool/src/remote-browser-pool.ts
+++ /dev/null
@@ -1,349 +0,0 @@
-import { type CrawleeLogger, serviceLocator } from '@crawlee/core';
-import type { IBrowserPool, NewPageOptions, PageState } from '@crawlee/types';
-
-import type { BrowserController } from './abstract-classes/browser-controller.js';
-import type { BrowserPlugin } from './abstract-classes/browser-plugin.js';
-import { BrowserPool } from './browser-pool.js';
-import type { BrowserPoolHooks, BrowserPoolOptions } from './browser-pool.js';
-import { BROWSER_CONTROLLER_EVENTS, BROWSER_POOL_EVENTS } from './events.js';
-import { RemoteBrowserProvider } from './remote-browser-provider.js';
-
-/**
- * The result of resolving a remote browser endpoint: the URL to connect to plus an optional opaque
- * `context` object that is handed back to `release`.
- */
-export interface ResolvedRemoteEndpoint {
- /** The browser endpoint URL to connect to. */
- url: string;
- /** Opaque metadata passed back to `release()` — e.g. session IDs, API tokens. */
- context?: Record<string, unknown>;
-}
-
-/**
- * A remote browser endpoint: either a static URL string, or a function called once per browser launch
- * that returns a URL (optionally with a `context` for `release`).
- *
- * The function receives the `proxyUrl` resolved by Crawlee's proxy configuration for the launch, so it
- * can forward it to the remote service's proxy API.
- */
-export type RemoteBrowserEndpoint =
- | string
- | ((options?: { proxyUrl?: string }) => string | ResolvedRemoteEndpoint | Promise<string | ResolvedRemoteEndpoint>);
-
-/**
- * The bridge a {@apilink RemoteBrowserPool} injects into a {@apilink BrowserPlugin} so the plugin can
- * connect to a remote browser without owning any remote-session policy.
- *
- * The plugin only knows how to make the library-specific `connect()` call; everything else — resolving
- * the endpoint, calling the user's `release()`, and guaranteeing release fires at most once — lives in
- * the pool. The plugin calls {@apilink RemoteConnection.resolve|resolve} before connecting, stores the
- * returned `token` on its launch context, and the controller later calls
- * {@apilink RemoteConnection.release|release} with that token when the browser closes.
- */
-export interface RemoteConnection {
- /** Resolves the endpoint for a single browser launch. The `token` identifies the session for release. */
- resolve(options?: { proxyUrl?: string }): Promise<{ url: string; token: number }>;
- /** Releases the remote session for `token`. Idempotent — safe to call from both `close()` and `kill()`. */
- release(token: number): Promise<void>;
-}
-
-/**
- * Owns the lifecycle of remote browser sessions for a single {@apilink RemoteBrowserPool}: endpoint
- * resolution, the user's `release()` callback, and a release-at-most-once guarantee. Implements
- * {@apilink RemoteConnection} so it can be injected into a plugin.
- */
-class RemoteSessionRegistry implements RemoteConnection {
- readonly #sessions = new Map<number, { url: string; context?: Record<string, unknown>; released: boolean }>();
- #nextToken = 0;
-
- readonly #endpoint: RemoteBrowserEndpoint;
- readonly #onRelease: ((info: { endpoint: string; context?: Record<string, unknown> }) => unknown) | undefined;
- readonly #log: CrawleeLogger;
-
- constructor(
- endpoint: RemoteBrowserEndpoint,
- onRelease: ((info: { endpoint: string; context?: Record<string, unknown> }) => unknown) | undefined,
- log: CrawleeLogger,
- ) {
- this.#endpoint = endpoint;
- this.#onRelease = onRelease;
- this.#log = log;
- }
-
- async resolve(options?: { proxyUrl?: string }): Promise<{ url: string; token: number }> {
- const resolved = typeof this.#endpoint === 'function' ? await this.#endpoint(options) : this.#endpoint;
-
- let result: ResolvedRemoteEndpoint;
- if (typeof resolved === 'string') {
- if (!resolved) throw new Error('Remote browser endpoint resolved to an empty string.');
- result = { url: resolved };
- } else if (!resolved?.url) {
- throw new Error("Remote browser endpoint() must return a URL string or an object with a non-empty 'url'.");
- } else {
- result = resolved;
- }
-
- const token = this.#nextToken++;
- this.#sessions.set(token, { url: result.url, context: result.context, released: false });
- return { url: result.url, token };
- }
-
- async release(token: number): Promise<void> {
- const session = this.#sessions.get(token);
- // Release at most once per session — guards a close()/teardown race (the `released` flag is set
- // synchronously before the awaited onRelease, so releaseAll() can't double-fire an in-flight release).
- if (!session || session.released) return;
- session.released = true;
-
- try {
- await this.#onRelease?.({ endpoint: session.url, context: session.context });
- } catch (err) {
- this.#log.warning('Remote browser release() failed.', { error: (err as Error)?.message });
- } finally {
- this.#sessions.delete(token);
- }
- }
-
- /** Releases every session that is still open. Called on pool teardown so no remote session leaks. */
- async releaseAll(): Promise<void> {
- await Promise.all([...this.#sessions.keys()].map(async (token) => this.release(token)));
- }
-}
-
-/**
- * Per-plugin remote connection parameters, passed to {@apilink BrowserPlugin.useRemoteConnection}.
- * The endpoint is supplied per-launch via {@apilink RemoteConnection}; these are the static connect()
- * parameters (protocol, headers, timeouts, …).
- */
-export interface RemoteConnectionParameters {
- /**
- * Playwright only: which protocol to connect with. `'cdp'` uses `connectOverCDP()` (the default),
- * `'playwright'` uses `connect()` (Playwright's own WebSocket protocol). Ignored by Puppeteer.
- */
- protocol?: 'cdp' | 'playwright';
- /** Extra options forwarded to the library `connect()` / `connectOverCDP()` call (endpoint excluded). */
- connectOptions?: Record<string, unknown>;
-}
-
-export interface RemoteBrowserPoolOptions {
- /**
- * The browser plugin(s) used to connect to the remote service — e.g. `new PlaywrightPlugin(playwright.chromium)`
- * or `new PuppeteerPlugin(puppeteer)`. The pool configures them for remote connection; do not set a local
- * `launchOptions` on them.
- */
- browserPlugins: BrowserPlugin[];
- /**
- * The remote browser endpoint: a static URL, a function returning one per launch, or a
- * {@apilink RemoteBrowserProvider} instance encapsulating a session create/release lifecycle.
- */
- endpoint: RemoteBrowserEndpoint | RemoteBrowserProvider<any>;
- /**
- * Cleanup callback invoked when a browser closes, crashes, or the pool is destroyed. Receives the
- * `context` returned by a function endpoint. Errors are caught and logged. Ignored when `endpoint`
- * is a {@apilink RemoteBrowserProvider} (its own `release()` is used instead).
- */
- release?: (info: { endpoint: string; context?: Record<string, unknown> }) => unknown;
- /**
- * Maximum number of remote browsers open at once. When reached, {@apilink RemoteBrowserPool.newPage|newPage}
- * waits for a browser to close before connecting a new one. Set it to your service's concurrent-session limit
- * to avoid `429` errors. Defaults to the {@apilink RemoteBrowserProvider.maxOpenBrowsers|provider's value}, or
- * `Infinity`.
- */
- maxOpenBrowsers?: number;
- /** Static connect() parameters (Playwright protocol selection, headers, timeouts, …). */
- connection?: RemoteConnectionParameters;
- /** Extra {@apilink BrowserPool} options (lifecycle hooks, page limits, fingerprinting, …). */
- browserPoolOptions?: Omit<BrowserPoolOptions, 'browserPlugins'> & BrowserPoolHooks<any, any, any>;
- /**
- * Fallback poll interval (ms) while waiting for a free browser slot. The wait is event-driven; this only bounds it.
- * @default 500
- * @internal
- */
- slotPollIntervalMillis?: number;
-}
-
-/**
- * The remote-connection configuration a browser crawler accepts on its `remoteBrowser` option: the
- * {@apilink RemoteBrowserPoolOptions} minus the `browserPlugins` (the crawler builds the correct one for its
- * browser, which is what makes this path mismatch-proof) and minus `browserPoolOptions` — tuning the wrapping
- * pool means building the pool yourself, through the `remote*BrowserPool()` factory for your crawler.
- */
-export type CrawlerRemoteBrowserOptions = Omit<RemoteBrowserPoolOptions, 'browserPlugins' | 'browserPoolOptions'>;
-
-/**
- * An {@apilink IBrowserPool} implementation for remote browser services.
- *
- * Unlike configuring a remote browser through a crawler's `launchContext`, this pool is the single owner
- * of all remote-session concerns:
- * - **endpoint resolution** — static URL, per-launch function, or {@apilink RemoteBrowserProvider};
- * - **release lifecycle** — `release()` fires exactly once per session on close/crash/teardown (no leaks,
- * no double-release);
- * - **concurrency** — {@apilink RemoteBrowserPoolOptions.maxOpenBrowsers|maxOpenBrowsers} is enforced inside
- * {@apilink RemoteBrowserPool.newPage|newPage}, which waits for a free slot rather than overshooting.
- *
- * The wrapped {@apilink BrowserPool} and its plugin only perform the library-specific `connect()` call.
- *
- * Pass an instance as the crawler's `browserPool` option:
- *
- * ```typescript
- * import { PlaywrightPlugin, RemoteBrowserPool } from '@crawlee/browser-pool';
- * import { PlaywrightCrawler } from 'crawlee';
- * import playwright from 'playwright';
- *
- * const browserPool = new RemoteBrowserPool({
- * browserPlugins: [new PlaywrightPlugin(playwright.chromium)],
- * endpoint: 'wss://production-sfo.browserless.io?token=xxx',
- * maxOpenBrowsers: 2,
- * });
- *
- * const crawler = new PlaywrightCrawler({ browserPool });
- * ```
- *
- * @category Browser management
- */
-export class RemoteBrowserPool<Page = unknown> implements IBrowserPool<Page> {
- /**
- * The wrapped pool that performs the remote connections and serves pages.
- *
- * @internal
- */
- readonly browserPool: BrowserPool;
-
- /** The wrapped pool viewed through the {@apilink IBrowserPool} contract (the bare type widens pages to `never`). */
- readonly #pool: IBrowserPool<Page>;
-
- readonly #registry: RemoteSessionRegistry;
- readonly #slotPollIntervalMillis: number;
- readonly #log: CrawleeLogger;
-
- /** Shared by all `newPage` callers waiting for a free slot, so they don't each register their own listeners. */
- #capacityChange?: Promise<void>;
-
- constructor(options: RemoteBrowserPoolOptions) {
- const {
- browserPlugins,
- endpoint,
- release,
- maxOpenBrowsers,
- connection = {},
- browserPoolOptions = {},
- slotPollIntervalMillis = 500,
- } = options;
-
- this.#log = serviceLocator.getLogger().child({ prefix: 'RemoteBrowserPool' });
- this.#slotPollIntervalMillis = slotPollIntervalMillis;
-
- // A RemoteBrowserProvider carries its own endpoint, release, and maxOpenBrowsers.
- const provider = endpoint instanceof RemoteBrowserProvider ? endpoint : undefined;
- const resolvedEndpoint: RemoteBrowserEndpoint = provider
- ? (opts) => provider.connect(opts)
- : (endpoint as RemoteBrowserEndpoint);
- const resolvedRelease = provider
- ? ({ context }: { context?: Record<string, unknown> }) => provider.release(context as any)
- : release;
- const resolvedMax = maxOpenBrowsers ?? provider?.maxOpenBrowsers;
-
- this.#registry = new RemoteSessionRegistry(resolvedEndpoint, resolvedRelease, this.#log);
-
- // Wire every plugin for remote connection.
- for (const plugin of browserPlugins) {
- plugin.useRemoteConnection(this.#registry, connection);
- }
-
- this.browserPool = new BrowserPool({ ...browserPoolOptions, browserPlugins }) as unknown as BrowserPool;
- this.#pool = this.browserPool as unknown as IBrowserPool<Page>;
-
- // Release a browser's remote session once it closes. The registry dedupes (close() schedules a delayed
- // kill(), so BROWSER_CLOSED can fire twice), and destroy()'s releaseAll() backstops any that never close.
- this.browserPool.on(BROWSER_POOL_EVENTS.BROWSER_LAUNCHED, (controller: BrowserController) => {
- controller.once(BROWSER_CONTROLLER_EVENTS.BROWSER_CLOSED, () => {
- const token = controller.launchContext.remoteToken;
- if (token !== undefined) void this.#registry.release(token);
- });
- });
-
- if (resolvedMax !== undefined) {
- this.browserPool.maxOpenBrowsers = resolvedMax;
- }
- }
-
- /** Maximum number of remote browsers that may be open at the same time. */
- get maxOpenBrowsers(): number {
- return this.browserPool.maxOpenBrowsers;
- }
-
- set maxOpenBrowsers(value: number) {
- this.browserPool.maxOpenBrowsers = value;
- }
-
- /**
- * Opens a new page, waiting first until {@apilink RemoteBrowserPoolOptions.maxOpenBrowsers|maxOpenBrowsers}
- * allows it (either a new browser slot is free, or an active browser still has page capacity).
- */
- async newPage(options?: NewPageOptions): Promise<Page> {
- await this.#waitForFreeSlot();
- return this.#pool.newPage(options);
- }
-
- async closePage(page: Page, options?: { error?: Error }): Promise<void> {
- return this.#pool.closePage(page, options);
- }
-
- async extractPageState(page: Page): Promise<PageState> {
- return this.#pool.extractPageState(page);
- }
-
- async injectPageState(page: Page, state: PageState): Promise<void> {
- return this.#pool.injectPageState(page, state);
- }
-
- /**
- * Closes all browsers and releases their remote sessions, leaving the pool usable. Closing a browser is what
- * releases its session (see the constructor), so this needs no separate release pass.
- */
- async releaseAllBrowsers(): Promise<void> {
- await this.browserPool.releaseAllBrowsers();
- }
-
- async [Symbol.asyncDispose](): Promise<void> {
- await this.destroy();
- }
-
- /** Closes all browsers, releases any still-open remote sessions, and tears down the wrapped pool. */
- async destroy(): Promise<void> {
- await this.browserPool.destroy();
- // Backstop: release any sessions whose browser never emitted a close (e.g. dropped on teardown).
- await this.#registry.releaseAll();
- }
-
- /** Resolves once the wrapped pool can serve another page without exceeding `maxOpenBrowsers`. */
- async #waitForFreeSlot(): Promise<void> {
- while (!this.browserPool.hasFreeBrowserSlot() && !this.browserPool.hasActiveBrowserWithFreeCapacity()) {
- await this.#nextCapacityChange();
- }
- }
-
- /**
- * Resolves on the next browser-retired / page-closed event, or after `slotPollIntervalMillis`. All
- * concurrently-waiting `newPage` calls share a single promise (and a single pair of event listeners)
- * per tick, so a fleet of saturated callers doesn't fan out into N listener pairs on the pool.
- */
- #nextCapacityChange(): Promise<void> {
- this.#capacityChange ??= new Promise<void>((resolve) => {
- const done = () => {
- clearTimeout(timer);
- this.browserPool.off(BROWSER_POOL_EVENTS.BROWSER_RETIRED, done);
- this.browserPool.off(BROWSER_POOL_EVENTS.PAGE_CLOSED, done);
- this.#capacityChange = undefined;
- resolve();
- };
-
- const timer = setTimeout(done, this.#slotPollIntervalMillis);
- timer.unref?.();
- this.browserPool.once(BROWSER_POOL_EVENTS.BROWSER_RETIRED, done);
- this.browserPool.once(BROWSER_POOL_EVENTS.PAGE_CLOSED, done);
- });
-
- return this.#capacityChange;
- }
-}
diff --git a/packages/browser-pool/src/remote-browser-provider.ts b/packages/browser-pool/src/remote-browser-provider.ts
index 425d61ca6..32f10ae7e 100644
--- a/packages/browser-pool/src/remote-browser-provider.ts
+++ b/packages/browser-pool/src/remote-browser-provider.ts
@@ -2,20 +2,18 @@
* Abstract base class for remote browser service providers.
*
* Implement this class to encapsulate the lifecycle of a remote browser session
- * (creation, connection URL resolution, and cleanup). {@apilink RemoteBrowserPool}
- * calls {@link connect} once per browser launch and {@link release} when the browser
- * closes, crashes, the pool is destroyed, or the connection fails during launch.
+ * (creation, connection URL resolution, and cleanup). A remote browser plugin
+ * ({@apilink RemotePlaywrightPlugin}, {@apilink RemotePuppeteerPlugin}) calls {@link connect}
+ * once per browser launch and {@link release} when the browser disconnects or the connection
+ * fails during launch.
*
- * Pass the provider instance as the `endpoint` of a {@apilink RemoteBrowserPool}, then
- * hand the pool to a crawler via its `browserPool` option:
+ * Pass the provider instance as the `endpoint` of a remote plugin, or as the crawler's
+ * `remoteBrowser.endpoint`:
*
* ```typescript
- * const browserPool = new RemoteBrowserPool({
- * browserPlugins: [new PlaywrightPlugin(playwright.chromium)],
- * endpoint: new MyProvider(),
+ * const crawler = new PlaywrightCrawler({
+ * remoteBrowser: { endpoint: new MyProvider() },
* });
- *
- * const crawler = new PlaywrightCrawler({ browserPool });
* ```
*
* **Example — simple static endpoint (e.g. Browserless):**
diff --git a/packages/browser-pool/test/remote-browser-pool.test.ts b/packages/browser-pool/test/remote-browser-pool.test.ts
deleted file mode 100644
index d02e9391a..000000000
--- a/packages/browser-pool/test/remote-browser-pool.test.ts
+++ /dev/null
@@ -1,250 +0,0 @@
-import { vi } from 'vitest';
-
-import { serviceLocator } from '@crawlee/core';
-import type { CrawleeLogger } from '@crawlee/core';
-
-import { EventEmitter } from 'node:events';
-
-import { BROWSER_CONTROLLER_EVENTS, BROWSER_POOL_EVENTS } from '../src/events.js';
-import type { RemoteConnection } from '../src/remote-browser-pool.js';
-import { RemoteBrowserPool } from '../src/remote-browser-pool.js';
-import { RemoteBrowserProvider } from '../src/remote-browser-provider.js';
-
-function createMockLogger(): CrawleeLogger {
- const logger: any = {
- child: vi.fn(() => logger),
- error: vi.fn(),
- exception: vi.fn(),
- softFail: vi.fn(),
- warning: vi.fn(),
- warningOnce: vi.fn(),
- info: vi.fn(),
- debug: vi.fn(),
- perf: vi.fn(),
- deprecated: vi.fn(),
- getOptions: vi.fn(() => ({})),
- setOptions: vi.fn(),
- setLevel: vi.fn(),
- getLevel: vi.fn(),
- };
- return logger;
-}
-
-/**
- * A stand-in plugin that captures the {@link RemoteConnection} the pool injects, so tests can drive
- * endpoint resolution / release directly without launching a real browser.
- */
-function createCapturingPlugin() {
- let connection: RemoteConnection | undefined;
- const plugin: any = {
- useRemoteConnection: (conn: RemoteConnection) => {
- connection = conn;
- },
- };
- return { plugin, getConnection: () => connection! };
-}
-
-beforeEach(() => {
- serviceLocator.setLogger(createMockLogger());
-});
-
-describe('RemoteBrowserPool — endpoint resolution', () => {
- it('resolves a static string endpoint', async () => {
- const { plugin, getConnection } = createCapturingPlugin();
- const pool = new RemoteBrowserPool({ browserPlugins: [plugin], endpoint: 'wss://remote:9222' });
-
- const { url, token } = await getConnection().resolve();
-
- expect(url).toBe('wss://remote:9222');
- expect(typeof token).toBe('number');
- await pool.destroy();
- });
-
- it('resolves a function endpoint and forwards proxyUrl', async () => {
- const endpoint = vi.fn(() => 'wss://dynamic:9222');
- const { plugin, getConnection } = createCapturingPlugin();
- const pool = new RemoteBrowserPool({ browserPlugins: [plugin], endpoint });
-
- const { url } = await getConnection().resolve({ proxyUrl: 'http://proxy:8080' });
-
- expect(url).toBe('wss://dynamic:9222');
- expect(endpoint).toHaveBeenCalledWith({ proxyUrl: 'http://proxy:8080' });
- await pool.destroy();
- });
-
- it('throws when an endpoint resolves to an empty string', async () => {
- const { plugin, getConnection } = createCapturingPlugin();
- const pool = new RemoteBrowserPool({ browserPlugins: [plugin], endpoint: () => '' });
-
- await expect(getConnection().resolve()).rejects.toThrow(/empty string/);
- await pool.destroy();
- });
-
- it('throws when a function endpoint returns an object without a url', async () => {
- const { plugin, getConnection } = createCapturingPlugin();
- const pool = new RemoteBrowserPool({ browserPlugins: [plugin], endpoint: () => ({}) as any });
-
- await expect(getConnection().resolve()).rejects.toThrow(/non-empty 'url'/);
- await pool.destroy();
- });
-});
-
-describe('RemoteBrowserPool — release lifecycle', () => {
- it('calls release with the context from a function endpoint, exactly once', async () => {
- const release = vi.fn();
- const { plugin, getConnection } = createCapturingPlugin();
- const pool = new RemoteBrowserPool({
- browserPlugins: [plugin],
- endpoint: () => ({ url: 'wss://remote:9222', context: { id: 'sess-1' } }),
- release,
- });
-
- const { token } = await getConnection().resolve();
- await getConnection().release(token);
- await getConnection().release(token); // second call must be a no-op (close()+kill())
-
- expect(release).toHaveBeenCalledTimes(1);
- expect(release).toHaveBeenCalledWith({ endpoint: 'wss://remote:9222', context: { id: 'sess-1' } });
- await pool.destroy();
- });
-
- it('releases a browser session when its controller closes', async () => {
- const release = vi.fn();
- const { plugin, getConnection } = createCapturingPlugin();
- const pool = new RemoteBrowserPool({ browserPlugins: [plugin], endpoint: 'wss://remote:9222', release });
-
- const { token } = await getConnection().resolve();
-
- // Mimic the inner pool launching a controller, then that controller closing.
- const controller: any = new EventEmitter();
- controller.launchContext = { remoteToken: token };
- pool.browserPool.emit(BROWSER_POOL_EVENTS.BROWSER_LAUNCHED, controller);
- controller.emit(BROWSER_CONTROLLER_EVENTS.BROWSER_CLOSED, controller);
-
- expect(release).toHaveBeenCalledTimes(1);
- expect(release).toHaveBeenCalledWith({ endpoint: 'wss://remote:9222', context: undefined });
- await pool.destroy();
- });
-
- it('releases all still-open sessions on destroy()', async () => {
- const release = vi.fn();
- const { plugin, getConnection } = createCapturingPlugin();
- const pool = new RemoteBrowserPool({ browserPlugins: [plugin], endpoint: 'wss://remote:9222', release });
-
- await getConnection().resolve();
- await getConnection().resolve();
-
- await pool.destroy();
-
- expect(release).toHaveBeenCalledTimes(2);
- });
-
- it('swallows errors thrown by release()', async () => {
- const release = vi.fn(() => {
- throw new Error('release boom');
- });
- const { plugin, getConnection } = createCapturingPlugin();
- const pool = new RemoteBrowserPool({ browserPlugins: [plugin], endpoint: 'wss://remote:9222', release });
-
- const { token } = await getConnection().resolve();
- await expect(getConnection().release(token)).resolves.toBeUndefined();
- await pool.destroy();
- });
-});
-
-describe('RemoteBrowserPool — RemoteBrowserProvider endpoint', () => {
- class TestProvider extends RemoteBrowserProvider<{ id: string }> {
- override maxOpenBrowsers = 3;
- connect = vi.fn(async () => ({ url: 'wss://provider:9222', context: { id: 'sess-1' } }));
- override release = vi.fn(async () => {});
- }
-
- it('wires connect/release and adopts the provider maxOpenBrowsers', async () => {
- const provider = new TestProvider();
- const { plugin, getConnection } = createCapturingPlugin();
- const pool = new RemoteBrowserPool({ browserPlugins: [plugin], endpoint: provider });
-
- expect(pool.maxOpenBrowsers).toBe(3);
-
- const { url, token } = await getConnection().resolve({ proxyUrl: 'http://proxy:8080' });
- expect(url).toBe('wss://provider:9222');
- expect(provider.connect).toHaveBeenCalledWith({ proxyUrl: 'http://proxy:8080' });
-
- await getConnection().release(token);
- expect(provider.release).toHaveBeenCalledWith({ id: 'sess-1' });
- await pool.destroy();
- });
-
- it('an explicit maxOpenBrowsers overrides the provider value', async () => {
- const { plugin } = createCapturingPlugin();
- const pool = new RemoteBrowserPool({
- browserPlugins: [plugin],
- endpoint: new TestProvider(),
- maxOpenBrowsers: 7,
- });
-
- expect(pool.maxOpenBrowsers).toBe(7);
- await pool.destroy();
- });
-});
-
-describe('RemoteBrowserPool — maxOpenBrowsers throttle', () => {
- it('proxies maxOpenBrowsers to the wrapped pool', async () => {
- const { plugin } = createCapturingPlugin();
- const pool = new RemoteBrowserPool({
- browserPlugins: [plugin],
- endpoint: 'wss://remote:9222',
- maxOpenBrowsers: 2,
- });
-
- expect(pool.browserPool.maxOpenBrowsers).toBe(2);
- pool.maxOpenBrowsers = 5;
- expect(pool.browserPool.maxOpenBrowsers).toBe(5);
- await pool.destroy();
- });
-
- it('opens immediately when a browser slot is free', async () => {
- const { plugin } = createCapturingPlugin();
- const pool = new RemoteBrowserPool({
- browserPlugins: [plugin],
- endpoint: 'wss://remote:9222',
- maxOpenBrowsers: 2,
- });
-
- pool.browserPool.hasFreeBrowserSlot = vi.fn(() => true);
- pool.browserPool.hasActiveBrowserWithFreeCapacity = vi.fn(() => false);
- const newPage = vi.fn(async () => ({ id: 'p' }));
- (pool.browserPool as any).newPage = newPage;
-
- await pool.newPage({ id: 'p' });
- expect(newPage).toHaveBeenCalledOnce();
- await pool.destroy();
- });
-
- it('waits while at capacity, then opens once a browser is retired', async () => {
- const { plugin } = createCapturingPlugin();
- const pool = new RemoteBrowserPool({
- browserPlugins: [plugin],
- endpoint: 'wss://remote:9222',
- maxOpenBrowsers: 1,
- slotPollIntervalMillis: 50,
- });
-
- let atCapacity = true;
- pool.browserPool.hasFreeBrowserSlot = vi.fn(() => !atCapacity);
- pool.browserPool.hasActiveBrowserWithFreeCapacity = vi.fn(() => false);
- const newPage = vi.fn(async () => ({ id: 'p' }));
- (pool.browserPool as any).newPage = newPage;
-
- const pagePromise = pool.newPage();
- await new Promise((r) => setTimeout(r, 20));
- expect(newPage).not.toHaveBeenCalled();
-
- atCapacity = false;
- pool.browserPool.emit(BROWSER_POOL_EVENTS.BROWSER_RETIRED, {} as any);
-
- await pagePromise;
- expect(newPage).toHaveBeenCalledOnce();
- await pool.destroy();
- });
-});
diff --git a/packages/browser-pool/test/remote-browser.test.ts b/packages/browser-pool/test/remote-browser.test.ts
index abeaad02c..df5dda360 100644
--- a/packages/browser-pool/test/remote-browser.test.ts
+++ b/packages/browser-pool/test/remote-browser.test.ts
@@ -1,11 +1,17 @@
+import { setImmediate as flush } from 'node:timers/promises';
+
import { vi } from 'vitest';
import { serviceLocator } from '@crawlee/core';
import type { CrawleeLogger } from '@crawlee/core';
+import { BrowserPool } from '../src/browser-pool.js';
+import { BROWSER_POOL_EVENTS } from '../src/events.js';
import { PlaywrightPlugin } from '../src/playwright/playwright-plugin.js';
-import { PuppeteerPlugin } from '../src/puppeteer/puppeteer-plugin.js';
-import type { RemoteConnection } from '../src/remote-browser-pool.js';
+import { RemotePlaywrightPlugin } from '../src/playwright/remote-playwright-plugin.js';
+import { RemotePuppeteerPlugin } from '../src/puppeteer/remote-puppeteer-plugin.js';
+import type { RemoteBrowserEndpoint, ResolvedRemoteEndpoint } from '../src/remote-browser-plugin.js';
+import { RemoteBrowserProvider } from '../src/remote-browser-provider.js';
// ---------------------------------------------------------------------------
// Mock helpers
@@ -20,6 +26,7 @@ function createMockPage() {
};
}
+/** A fake browser whose `disconnected` listeners can be fired via `disconnect()`. */
function createMockBrowser() {
const page = createMockPage();
const mockContext = {
@@ -28,11 +35,12 @@ function createMockBrowser() {
on: vi.fn(),
once: vi.fn(),
};
+ const listeners: Record<string, (() => void)[]> = {};
return {
newPage: vi.fn().mockResolvedValue(createMockPage()),
close: vi.fn().mockResolvedValue(undefined),
contexts: vi.fn(() => [mockContext]),
- on: vi.fn(),
+ on: vi.fn((event: string, cb: () => void) => (listeners[event] ??= []).push(cb)),
off: vi.fn(),
once: vi.fn(),
version: vi.fn(() => '120.0.0'),
@@ -41,6 +49,7 @@ function createMockBrowser() {
userAgent: vi.fn().mockResolvedValue('mock-ua'),
createBrowserContext: vi.fn().mockResolvedValue(mockContext),
createIncognitoBrowserContext: vi.fn().mockResolvedValue(mockContext),
+ disconnect: () => listeners.disconnected?.forEach((cb) => cb()),
};
}
@@ -82,20 +91,6 @@ function createMockLogger(): CrawleeLogger & { warning: ReturnType<typeof vi.fn>
return logger;
}
-/** A fake {@link RemoteConnection} that resolves to a fixed URL and records release() calls. */
-function createConnection(
- url = 'wss://remote:9222',
- context?: Record<string, unknown>,
-): RemoteConnection & {
- resolve: ReturnType<typeof vi.fn>;
- release: ReturnType<typeof vi.fn>;
-} {
- return {
- resolve: vi.fn(async (_options?: { proxyUrl?: string }) => ({ url, token: 42, context })),
- release: vi.fn(async () => {}),
- } as any;
-}
-
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
@@ -107,10 +102,12 @@ beforeEach(() => {
serviceLocator.setLogger(mockLogger);
});
-describe('Remote connection — PlaywrightPlugin', () => {
- it('useRemoteConnection forces incognito pages on and marks the launch context remote', () => {
- const plugin = new PlaywrightPlugin(createMockPlaywrightLibrary() as any, { useIncognitoPages: false });
- plugin.useRemoteConnection(createConnection());
+describe('RemotePlaywrightPlugin', () => {
+ it('forces incognito pages on and marks the launch context remote', () => {
+ const plugin = new RemotePlaywrightPlugin(createMockPlaywrightLibrary() as any, {
+ endpoint: 'wss://remote:9222',
+ useIncognitoPages: false,
+ });
expect(plugin.useIncognitoPages).toBe(true);
expect(plugin.createLaunchContext().isRemote).toBe(true);
@@ -118,59 +115,115 @@ describe('Remote connection — PlaywrightPlugin', () => {
it('connects via connectOverCDP by default and skips a local launch', async () => {
const lib = createMockPlaywrightLibrary();
- const plugin = new PlaywrightPlugin(lib as any);
- const connection = createConnection('http://remote:9222');
- plugin.useRemoteConnection(connection, { connectOptions: { timeout: 5000 } });
+ const plugin = new RemotePlaywrightPlugin(lib as any, {
+ endpoint: 'http://remote:9222',
+ connectOptions: { timeout: 5000 },
+ });
- const ctx = plugin.createLaunchContext();
- await plugin.launch(ctx);
+ await plugin.launch();
- expect(connection.resolve).toHaveBeenCalledTimes(1);
expect(lib.connectOverCDP).toHaveBeenCalledWith('http://remote:9222', { timeout: 5000 });
expect(lib.connect).not.toHaveBeenCalled();
expect(lib.launch).not.toHaveBeenCalled();
- expect(ctx.remoteToken).toBe(42);
});
it("connects via connect() when protocol is 'playwright'", async () => {
const lib = createMockPlaywrightLibrary();
- const plugin = new PlaywrightPlugin(lib as any);
- plugin.useRemoteConnection(createConnection('ws://remote:3000'), { protocol: 'playwright' });
+ const plugin = new RemotePlaywrightPlugin(lib as any, { endpoint: 'ws://remote:3000', protocol: 'playwright' });
- await plugin.launch(plugin.createLaunchContext());
+ await plugin.launch();
expect(lib.connect).toHaveBeenCalledWith('ws://remote:3000', {});
expect(lib.connectOverCDP).not.toHaveBeenCalled();
});
+ it('passes the launch proxy URL to a function endpoint and releases with its context on disconnect', async () => {
+ const browser = createMockBrowser();
+ const lib = createMockPlaywrightLibrary(browser);
+ const endpoint = vi.fn(async () => ({ url: 'wss://remote:9222', context: { id: 'sess-1' } }));
+ const release = vi.fn();
+ const plugin = new RemotePlaywrightPlugin(lib as any, { endpoint, release });
+
+ await plugin.launch(plugin.createLaunchContext({ proxyUrl: 'http://proxy:8080' }));
+ expect(endpoint).toHaveBeenCalledWith({ proxyUrl: 'http://proxy:8080' });
+ expect(release).not.toHaveBeenCalled();
+
+ browser.disconnect();
+ browser.disconnect();
+ await flush();
+ expect(release).toHaveBeenCalledExactlyOnceWith({ endpoint: 'wss://remote:9222', context: { id: 'sess-1' } });
+ });
+
it('releases the session and throws BrowserLaunchError when connect fails', async () => {
const lib = createMockPlaywrightLibrary();
lib.connectOverCDP.mockRejectedValueOnce(new Error('ECONNREFUSED'));
- const plugin = new PlaywrightPlugin(lib as any);
- const connection = createConnection();
- plugin.useRemoteConnection(connection);
+ const release = vi.fn();
+ const plugin = new RemotePlaywrightPlugin(lib as any, { endpoint: 'wss://remote:9222', release });
- await expect(plugin.launch(plugin.createLaunchContext())).rejects.toThrow(
- /Failed to connect to remote browser/,
- );
- expect(connection.release).toHaveBeenCalledWith(42);
+ await expect(plugin.launch()).rejects.toThrow(/Failed to connect to remote browser/);
+ expect(release).toHaveBeenCalledExactlyOnceWith({ endpoint: 'wss://remote:9222', context: undefined });
});
- it('throws BrowserLaunchError (without connecting) when endpoint resolution fails', async () => {
+ it.each<[string, RemoteBrowserEndpoint, RegExp]>([
+ ['an empty string', () => '', /empty string/],
+ ['an object without url', () => ({}) as ResolvedRemoteEndpoint, /non-empty 'url'/],
+ [
+ 'a throwing function',
+ async () => {
+ throw new Error('no session');
+ },
+ /no session/,
+ ],
+ ])('throws BrowserLaunchError without connecting when the endpoint resolves to %s', async (_, endpoint, cause) => {
const lib = createMockPlaywrightLibrary();
- const plugin = new PlaywrightPlugin(lib as any);
- const connection = createConnection();
- connection.resolve.mockRejectedValueOnce(new Error('no session'));
- plugin.useRemoteConnection(connection);
+ const release = vi.fn();
+ const plugin = new RemotePlaywrightPlugin(lib as any, { endpoint, release });
- await expect(plugin.launch(plugin.createLaunchContext())).rejects.toThrow(
- /resolve the remote browser endpoint/,
- );
+ await expect(plugin.launch()).rejects.toMatchObject({
+ message: expect.stringMatching(/resolve the remote browser endpoint/),
+ cause: expect.objectContaining({ message: expect.stringMatching(cause) }),
+ });
expect(lib.connectOverCDP).not.toHaveBeenCalled();
- expect(connection.release).not.toHaveBeenCalled();
+ expect(release).not.toHaveBeenCalled();
});
- it('a plain plugin (no remote connection) launches locally', async () => {
+ it('a release() failure is logged, not thrown', async () => {
+ const browser = createMockBrowser();
+ const lib = createMockPlaywrightLibrary(browser);
+ const plugin = new RemotePlaywrightPlugin(lib as any, {
+ endpoint: 'wss://remote:9222',
+ release: async () => {
+ throw new Error('boom');
+ },
+ });
+
+ await plugin.launch();
+ browser.disconnect();
+ await flush();
+
+ expect(mockLogger.warning).toHaveBeenCalledWith('Remote browser release() failed.', { error: 'boom' });
+ });
+
+ it('uses a RemoteBrowserProvider for connect and release', async () => {
+ class TestProvider extends RemoteBrowserProvider<{ id: string }> {
+ connect = vi.fn(async () => ({ url: 'wss://provider:9222', context: { id: 'sess-1' } }));
+ override release = vi.fn(async () => {});
+ }
+ const provider = new TestProvider();
+ const browser = createMockBrowser();
+ const lib = createMockPlaywrightLibrary(browser);
+ const plugin = new RemotePlaywrightPlugin(lib as any, { endpoint: provider });
+
+ await plugin.launch(plugin.createLaunchContext({ proxyUrl: 'http://proxy:8080' }));
+ expect(provider.connect).toHaveBeenCalledWith({ proxyUrl: 'http://proxy:8080' });
+ expect(lib.connectOverCDP).toHaveBeenCalledWith('wss://provider:9222', {});
+
+ browser.disconnect();
+ await flush();
+ expect(provider.release).toHaveBeenCalledExactlyOnceWith({ id: 'sess-1' });
+ });
+
+ it('a plain PlaywrightPlugin launches locally', async () => {
const lib = createMockPlaywrightLibrary();
const plugin = new PlaywrightPlugin(lib as any);
@@ -179,42 +232,78 @@ describe('Remote connection — PlaywrightPlugin', () => {
expect(lib.launch).toHaveBeenCalledTimes(1);
expect(lib.connect).not.toHaveBeenCalled();
expect(lib.connectOverCDP).not.toHaveBeenCalled();
+ expect(plugin.createLaunchContext().isRemote).toBe(false);
});
});
-describe('Remote connection — PuppeteerPlugin', () => {
+describe('RemotePuppeteerPlugin', () => {
it('connects via connect() with the resolved endpoint and skips a local launch', async () => {
const lib = createMockPuppeteerLibrary();
- const plugin = new PuppeteerPlugin(lib as any);
- const connection = createConnection('ws://remote:9222');
- plugin.useRemoteConnection(connection, { connectOptions: { protocolTimeout: 1000 } });
+ const plugin = new RemotePuppeteerPlugin(lib as any, {
+ endpoint: 'ws://remote:9222',
+ connectOptions: { protocolTimeout: 1000 },
+ });
- const ctx = plugin.createLaunchContext();
- await plugin.launch(ctx);
+ await plugin.launch();
- expect(connection.resolve).toHaveBeenCalledTimes(1);
expect(lib.connect).toHaveBeenCalledWith({ protocolTimeout: 1000, browserWSEndpoint: 'ws://remote:9222' });
expect(lib.launch).not.toHaveBeenCalled();
- expect(ctx.remoteToken).toBe(42);
+ expect(plugin.createLaunchContext().isRemote).toBe(true);
});
it('releases the session and throws BrowserLaunchError when connect fails', async () => {
const lib = createMockPuppeteerLibrary();
lib.connect.mockRejectedValueOnce(new Error('ECONNREFUSED'));
- const plugin = new PuppeteerPlugin(lib as any);
- const connection = createConnection();
- plugin.useRemoteConnection(connection);
-
- await expect(plugin.launch(plugin.createLaunchContext())).rejects.toThrow(
- /Failed to connect to remote browser/,
- );
- expect(connection.release).toHaveBeenCalledWith(42);
+ const release = vi.fn();
+ const plugin = new RemotePuppeteerPlugin(lib as any, { endpoint: 'wss://remote:9222', release });
+
+ await expect(plugin.launch()).rejects.toThrow(/Failed to connect to remote browser/);
+ expect(release).toHaveBeenCalledOnce();
+ });
+});
+
+describe('BrowserPool maxOpenBrowsers', () => {
+ /** Short-circuits the launch so tests only observe *when* the pool tries to launch. */
+ function createPool() {
+ const plugin = new PlaywrightPlugin(createMockPlaywrightLibrary() as any);
+ const launch = vi.spyOn(plugin, 'launch').mockRejectedValue(new Error('stop here'));
+ return { pool: new BrowserPool({ browserPlugins: [plugin], maxOpenBrowsers: 1 }), launch };
+ }
+
+ it('newPage waits while at capacity, then launches once a browser is retired', async () => {
+ const { pool, launch } = createPool();
+ let atCapacity = true;
+ pool.hasFreeBrowserSlot = vi.fn(() => !atCapacity);
+
+ const pagePromise = pool.newPage();
+ await flush();
+ expect(launch).not.toHaveBeenCalled();
+
+ atCapacity = false;
+ pool.emit(BROWSER_POOL_EVENTS.BROWSER_RETIRED, {} as any);
+
+ await expect(pagePromise).rejects.toThrow('stop here');
+ expect(launch).toHaveBeenCalledOnce();
+ await pool.destroy();
});
- it('marks the launch context remote', () => {
- const plugin = new PuppeteerPlugin(createMockPuppeteerLibrary() as any);
- plugin.useRemoteConnection(createConnection());
+ it('a single freed slot lets exactly one waiter launch', async () => {
+ const { pool, launch } = createPool();
+ let freeSlots = 0;
+ pool.hasFreeBrowserSlot = vi.fn(() => freeSlots-- > 0);
- expect(plugin.createLaunchContext().isRemote).toBe(true);
+ const first = pool.newPage();
+ const second = pool.newPage();
+ await flush();
+
+ freeSlots = 1;
+ pool.emit(BROWSER_POOL_EVENTS.BROWSER_RETIRED, {} as any);
+
+ await expect(first).rejects.toThrow('stop here');
+ await flush();
+ expect(launch).toHaveBeenCalledOnce();
+
+ second.catch(() => {});
+ await pool.destroy();
});
});
diff --git a/packages/playwright-crawler/src/internals/playwright-browser-pool.ts b/packages/playwright-crawler/src/internals/playwright-browser-pool.ts
index 8c6a781e3..d36af8a01 100644
--- a/packages/playwright-crawler/src/internals/playwright-browser-pool.ts
+++ b/packages/playwright-crawler/src/internals/playwright-browser-pool.ts
@@ -1,17 +1,19 @@
-import type { Configuration } from '@crawlee/browser';
-import type {
- BrowserPool,
- BrowserPoolHooks,
- BrowserPoolOptions,
- PlaywrightPlugin,
- RemoteBrowserPool,
- RemoteBrowserPoolOptions,
-} from '@crawlee/browser-pool';
+import type { Configuration, CrawlerRemoteBrowserOptions } from '@crawlee/browser';
+import type { BrowserPool, BrowserPoolHooks, BrowserPoolOptions, PlaywrightPlugin } from '@crawlee/browser-pool';
import type { Page } from 'playwright';
import type { PlaywrightLaunchContext } from './playwright-launcher.js';
import { PlaywrightLauncher } from './playwright-launcher.js';
+/** {@apilink BrowserCrawlerOptions.remoteBrowser|`remoteBrowser`} for Playwright, with the protocol to connect over. */
+export interface PlaywrightRemoteBrowserOptions extends CrawlerRemoteBrowserOptions {
+ /**
+ * `'cdp'` uses `connectOverCDP()` (the default), `'playwright'` uses `connect()` (Playwright's own WebSocket
+ * protocol, for endpoints started with `launchServer()`).
+ */
+ protocol?: 'cdp' | 'playwright';
+}
+
/** A {@apilink BrowserPool} of Playwright browsers, as built by {@apilink playwrightBrowserPool}. */
export type PlaywrightBrowserPool = BrowserPool<{ browserPlugins: [PlaywrightPlugin] }, [PlaywrightPlugin]>;
@@ -34,12 +36,10 @@ export interface PlaywrightBrowserPoolOptions
/** Configuration to read the browser defaults from. Defaults to the global configuration. */
configuration?: Configuration;
-}
-export interface RemotePlaywrightBrowserPoolOptions
- extends
- Pick<PlaywrightBrowserPoolOptions, 'launchContext' | 'headless' | 'configuration'>,
- Omit<RemoteBrowserPoolOptions, 'browserPlugins'> {}
+ /** Connect to a remote browser service instead of launching locally; see {@apilink BrowserCrawlerOptions.remoteBrowser}. */
+ remoteBrowser?: PlaywrightRemoteBrowserOptions;
+}
/**
* Builds a {@apilink BrowserPool} of Playwright browsers to pass to a {@apilink PlaywrightCrawler} as its
@@ -71,35 +71,6 @@ export function playwrightBrowserPool(options: PlaywrightBrowserPoolOptions = {}
return playwrightLauncher(launchContext, headless, configuration).createBrowserPool(poolOptions);
}
-/**
- * The {@apilink RemoteBrowserPool} counterpart of {@apilink playwrightBrowserPool}: connects to a remote browser
- * service (Browserbase, Browserless, Steel, ...) with a Playwright plugin derived from `launchContext`.
- *
- * A {@apilink PlaywrightCrawler} accepts the same connection details directly via
- * {@apilink BrowserCrawlerOptions.remoteBrowser|`remoteBrowser`}; reach for this factory when you also need to
- * tune the wrapping pool, or to share one remote pool between crawlers.
- *
- * **Example usage:**
- *
- * ```javascript
- * const crawler = new PlaywrightCrawler({
- * browserPool: remotePlaywrightBrowserPool({
- * endpoint: 'wss://production-sfo.browserless.io?token=xxx',
- * maxOpenBrowsers: 2,
- * browserPoolOptions: { useFingerprints: false },
- * }),
- * requestHandler: async ({ page }) => { ... },
- * });
- * ```
- *
- * @category Browser management
- */
-export function remotePlaywrightBrowserPool(options: RemotePlaywrightBrowserPoolOptions): RemoteBrowserPool<Page> {
- const { launchContext, headless, configuration, ...remoteOptions } = options;
-
- return playwrightLauncher(launchContext, headless, configuration).createRemoteBrowserPool<Page>(remoteOptions);
-}
-
function playwrightLauncher(
launchContext: PlaywrightLaunchContext = {},
headless?: boolean,
diff --git a/packages/playwright-crawler/src/internals/playwright-crawler.ts b/packages/playwright-crawler/src/internals/playwright-crawler.ts
index 28e5c23eb..bb69c5960 100644
--- a/packages/playwright-crawler/src/internals/playwright-crawler.ts
+++ b/packages/playwright-crawler/src/internals/playwright-crawler.ts
@@ -17,7 +17,7 @@ import type { Download, Page, Response } from 'playwright';
import { z } from 'zod';
import type { EnqueueLinksByClickingElementsOptions } from './enqueue-links/click-elements.js';
-import { playwrightBrowserPool, remotePlaywrightBrowserPool } from './playwright-browser-pool.js';
+import { playwrightBrowserPool, type PlaywrightRemoteBrowserOptions } from './playwright-browser-pool.js';
import type { PlaywrightLaunchContext } from './playwright-launcher.js';
import type {
BlockRequestsOptions,
@@ -79,6 +79,9 @@ export interface PlaywrightCrawlerOptions<
*/
headless?: boolean;
+ /** See {@apilink BrowserCrawlerOptions.remoteBrowser}; Playwright additionally lets you pick the `protocol`. */
+ remoteBrowser?: PlaywrightRemoteBrowserOptions;
+
/**
* Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies
* or browser properties before navigation. The function receives the `crawlingContext`; the options object
@@ -250,9 +253,7 @@ export class PlaywrightCrawler<
>),
configuration,
browserPoolBuilder: (remoteBrowser) =>
- remoteBrowser
- ? remotePlaywrightBrowserPool({ ...remoteBrowser, launchContext, headless, configuration })
- : playwrightBrowserPool({ launchContext, headless, configuration }),
+ playwrightBrowserPool({ launchContext, headless, configuration, remoteBrowser }),
contextPipelineBuilder: () => this.#buildContextPipeline(),
});
}
diff --git a/packages/playwright-crawler/src/internals/playwright-launcher.ts b/packages/playwright-crawler/src/internals/playwright-launcher.ts
index 63636d7e7..5fe6ab425 100644
--- a/packages/playwright-crawler/src/internals/playwright-launcher.ts
+++ b/packages/playwright-crawler/src/internals/playwright-launcher.ts
@@ -1,6 +1,6 @@
import type { BrowserLaunchContext } from '@crawlee/browser';
import { BrowserLauncher, Configuration } from '@crawlee/browser';
-import { PlaywrightPlugin } from '@crawlee/browser-pool';
+import { PlaywrightPlugin, RemotePlaywrightPlugin } from '@crawlee/browser-pool';
import { parseArgument, schemas } from '@crawlee/utils/internal';
import type { Browser, BrowserType, LaunchOptions } from 'playwright';
import { z } from 'zod';
@@ -121,6 +121,7 @@ export class PlaywrightLauncher extends BrowserLauncher<PlaywrightPlugin> {
);
this.Plugin = PlaywrightPlugin;
+ this.RemotePlugin = RemotePlaywrightPlugin;
}
}
diff --git a/packages/puppeteer-crawler/src/internals/enqueue-links/click-elements.ts b/packages/puppeteer-crawler/src/internals/enqueue-links/click-elements.ts
index 886e9b0e7..7c5bb0725 100644
--- a/packages/puppeteer-crawler/src/internals/enqueue-links/click-elements.ts
+++ b/packages/puppeteer-crawler/src/internals/enqueue-links/click-elements.ts
@@ -19,7 +19,6 @@ import {
} from '@crawlee/browser';
import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
import { parseArgument, schemas } from '@crawlee/utils/internal';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { ClickOptions, Frame, HTTPRequest as PuppeteerRequest, Page, Target } from 'puppeteer';
import { z } from 'zod';
diff --git a/packages/puppeteer-crawler/src/internals/puppeteer-browser-pool.ts b/packages/puppeteer-crawler/src/internals/puppeteer-browser-pool.ts
index 58efd0ae8..bf4236370 100644
--- a/packages/puppeteer-crawler/src/internals/puppeteer-browser-pool.ts
+++ b/packages/puppeteer-crawler/src/internals/puppeteer-browser-pool.ts
@@ -1,13 +1,5 @@
-import type { Configuration } from '@crawlee/browser';
-import type {
- BrowserPool,
- BrowserPoolHooks,
- BrowserPoolOptions,
- PuppeteerPlugin,
- RemoteBrowserPool,
- RemoteBrowserPoolOptions,
-} from '@crawlee/browser-pool';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
+import type { Configuration, CrawlerRemoteBrowserOptions } from '@crawlee/browser';
+import type { BrowserPool, BrowserPoolHooks, BrowserPoolOptions, PuppeteerPlugin } from '@crawlee/browser-pool';
import type { Page } from 'puppeteer';
import type { PuppeteerLaunchContext } from './puppeteer-launcher.js';
@@ -35,12 +27,10 @@ export interface PuppeteerBrowserPoolOptions
/** Configuration to read the browser defaults from. Defaults to the global configuration. */
configuration?: Configuration;
-}
-export interface RemotePuppeteerBrowserPoolOptions
- extends
- Pick<PuppeteerBrowserPoolOptions, 'launchContext' | 'headless' | 'configuration'>,
- Omit<RemoteBrowserPoolOptions, 'browserPlugins'> {}
+ /** Connect to a remote browser service instead of launching locally; see {@apilink BrowserCrawlerOptions.remoteBrowser}. */
+ remoteBrowser?: CrawlerRemoteBrowserOptions;
+}
/**
* Builds a {@apilink BrowserPool} of Puppeteer browsers to pass to a {@apilink PuppeteerCrawler} as its
@@ -69,22 +59,6 @@ export function puppeteerBrowserPool(options: PuppeteerBrowserPoolOptions = {}):
return puppeteerLauncher(launchContext, headless, configuration).createBrowserPool(poolOptions);
}
-/**
- * The {@apilink RemoteBrowserPool} counterpart of {@apilink puppeteerBrowserPool}: connects to a remote browser
- * service (Browserbase, Browserless, Steel, ...) with a Puppeteer plugin derived from `launchContext`.
- *
- * A {@apilink PuppeteerCrawler} accepts the same connection details directly via
- * {@apilink BrowserCrawlerOptions.remoteBrowser|`remoteBrowser`}; reach for this factory when you also need to
- * tune the wrapping pool, or to share one remote pool between crawlers.
- *
- * @category Browser management
- */
-export function remotePuppeteerBrowserPool(options: RemotePuppeteerBrowserPoolOptions): RemoteBrowserPool<Page> {
- const { launchContext, headless, configuration, ...remoteOptions } = options;
-
- return puppeteerLauncher(launchContext, headless, configuration).createRemoteBrowserPool<Page>(remoteOptions);
-}
-
function puppeteerLauncher(
launchContext: PuppeteerLaunchContext = {},
headless?: boolean | 'new' | 'old',
diff --git a/packages/puppeteer-crawler/src/internals/puppeteer-crawler.ts b/packages/puppeteer-crawler/src/internals/puppeteer-crawler.ts
index 41e5c648c..175964e36 100644
--- a/packages/puppeteer-crawler/src/internals/puppeteer-crawler.ts
+++ b/packages/puppeteer-crawler/src/internals/puppeteer-crawler.ts
@@ -14,12 +14,11 @@ import { BrowserCrawler, RequestState, Router } from '@crawlee/browser';
import { serviceLocator } from '@crawlee/core';
import type { Dictionary } from '@crawlee/types';
import { assertBrowserPoolNotConfigured, parseArgument, schemas } from '@crawlee/utils/internal';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { HTTPResponse, Page } from 'puppeteer';
import { z } from 'zod';
import type { EnqueueLinksByClickingElementsOptions } from './enqueue-links/click-elements.js';
-import { puppeteerBrowserPool, remotePuppeteerBrowserPool } from './puppeteer-browser-pool.js';
+import { puppeteerBrowserPool } from './puppeteer-browser-pool.js';
import type { PuppeteerLaunchContext } from './puppeteer-launcher.js';
import type { InterceptHandler } from './utils/puppeteer_request_interception.js';
import type {
@@ -247,9 +246,7 @@ export class PuppeteerCrawler<
configuration,
proxyConfiguration,
browserPoolBuilder: (remoteBrowser) =>
- remoteBrowser
- ? remotePuppeteerBrowserPool({ ...remoteBrowser, launchContext, headless, configuration })
- : puppeteerBrowserPool({ launchContext, headless, configuration }),
+ puppeteerBrowserPool({ launchContext, headless, configuration, remoteBrowser }),
contextPipelineBuilder: () => this.#buildContextPipeline(),
});
}
diff --git a/packages/puppeteer-crawler/src/internals/puppeteer-launcher.ts b/packages/puppeteer-crawler/src/internals/puppeteer-launcher.ts
index 4de77c462..cc50440fb 100644
--- a/packages/puppeteer-crawler/src/internals/puppeteer-launcher.ts
+++ b/packages/puppeteer-crawler/src/internals/puppeteer-launcher.ts
@@ -1,8 +1,7 @@
import type { BrowserLaunchContext } from '@crawlee/browser';
import { BrowserLauncher, Configuration } from '@crawlee/browser';
-import { PuppeteerPlugin } from '@crawlee/browser-pool';
+import { PuppeteerPlugin, RemotePuppeteerPlugin } from '@crawlee/browser-pool';
import { parseArgument, schemas } from '@crawlee/utils/internal';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { Browser } from 'puppeteer';
import { z } from 'zod';
@@ -106,6 +105,7 @@ export class PuppeteerLauncher extends BrowserLauncher<PuppeteerPlugin, unknown>
);
this.Plugin = PuppeteerPlugin;
+ this.RemotePlugin = RemotePuppeteerPlugin;
}
protected override getDefaultHeadlessOption(): boolean {
diff --git a/packages/puppeteer-crawler/src/internals/utils/puppeteer_request_interception.ts b/packages/puppeteer-crawler/src/internals/utils/puppeteer_request_interception.ts
index 5477016e7..99767d264 100644
--- a/packages/puppeteer-crawler/src/internals/utils/puppeteer_request_interception.ts
+++ b/packages/puppeteer-crawler/src/internals/utils/puppeteer_request_interception.ts
@@ -3,7 +3,6 @@ import { EventEmitter } from 'node:events';
import { serviceLocator } from '@crawlee/browser';
import type { Dictionary } from '@crawlee/types';
import { parseArgument, schemas } from '@crawlee/utils/internal';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { HTTPRequest, HTTPRequest as PuppeteerRequest, Page } from 'puppeteer';
export type InterceptHandler = (request: PuppeteerRequest) => unknown;
diff --git a/packages/puppeteer-crawler/src/internals/utils/puppeteer_utils.ts b/packages/puppeteer-crawler/src/internals/utils/puppeteer_utils.ts
index 49c0e8d6b..d15ee2418 100644
--- a/packages/puppeteer-crawler/src/internals/utils/puppeteer_utils.ts
+++ b/packages/puppeteer-crawler/src/internals/utils/puppeteer_utils.ts
@@ -29,7 +29,6 @@ import type { CheerioAPI } from 'cheerio';
import { sleep } from '@crawlee/utils';
import { expandShadowRoots, parseArgument, schemas } from '@crawlee/utils/internal';
import type { ProtocolMapping } from 'devtools-protocol/types/protocol-mapping.js';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { HTTPRequest as PuppeteerRequest, HTTPResponse, Page } from 'puppeteer';
import { z } from 'zod';
diff --git a/packages/stagehand-crawler/src/index.ts b/packages/stagehand-crawler/src/index.ts
index 71d92b4d0..f2616a50c 100644
--- a/packages/stagehand-crawler/src/index.ts
+++ b/packages/stagehand-crawler/src/index.ts
@@ -57,12 +57,8 @@ export * from '@crawlee/browser';
export { StagehandCrawler, createStagehandRouter } from './internals/stagehand-crawler';
// Export the browser pool factories, which are how a pool with non-default options reaches the crawler
-export { stagehandBrowserPool, remoteStagehandBrowserPool } from './internals/stagehand-browser-pool';
-export type {
- StagehandBrowserPool,
- StagehandBrowserPoolOptions,
- RemoteStagehandBrowserPoolOptions,
-} from './internals/stagehand-browser-pool';
+export { stagehandBrowserPool } from './internals/stagehand-browser-pool';
+export type { StagehandBrowserPool, StagehandBrowserPoolOptions } from './internals/stagehand-browser-pool';
// Export types
export type {
diff --git a/packages/stagehand-crawler/src/internals/stagehand-browser-pool.ts b/packages/stagehand-crawler/src/internals/stagehand-browser-pool.ts
index 8e92a8245..4ebdc5a0a 100644
--- a/packages/stagehand-crawler/src/internals/stagehand-browser-pool.ts
+++ b/packages/stagehand-crawler/src/internals/stagehand-browser-pool.ts
@@ -1,11 +1,5 @@
import type { Configuration } from '@crawlee/browser';
-import type {
- BrowserPool,
- BrowserPoolHooks,
- BrowserPoolOptions,
- RemoteBrowserPool,
- RemoteBrowserPoolOptions,
-} from '@crawlee/browser-pool';
+import type { BrowserPool, BrowserPoolHooks, BrowserPoolOptions } from '@crawlee/browser-pool';
import type { Page } from 'playwright';
import type { StagehandOptions } from './stagehand-crawler';
@@ -40,11 +34,6 @@ export interface StagehandBrowserPoolOptions
configuration?: Configuration;
}
-export interface RemoteStagehandBrowserPoolOptions
- extends
- Pick<StagehandBrowserPoolOptions, 'launchContext' | 'stagehandOptions' | 'headless' | 'configuration'>,
- Omit<RemoteBrowserPoolOptions, 'browserPlugins'> {}
-
/**
* Builds a {@apilink BrowserPool} of Stagehand browsers to pass to a {@apilink StagehandCrawler} as its
* {@apilink BrowserCrawlerOptions.browserPool|`browserPool`}.
@@ -76,24 +65,6 @@ export function stagehandBrowserPool(options: StagehandBrowserPoolOptions = {}):
return stagehandLauncher(launchContext, stagehandOptions, headless, configuration).createBrowserPool(poolOptions);
}
-/**
- * The {@apilink RemoteBrowserPool} counterpart of {@apilink stagehandBrowserPool}: connects to a remote browser
- * service with a Stagehand plugin derived from `launchContext` and `stagehandOptions`.
- *
- * A {@apilink StagehandCrawler} accepts the same connection details directly via
- * {@apilink BrowserCrawlerOptions.remoteBrowser|`remoteBrowser`}; reach for this factory when you also need to
- * tune the wrapping pool, or to share one remote pool between crawlers.
- *
- * @category Browser management
- */
-export function remoteStagehandBrowserPool(options: RemoteStagehandBrowserPoolOptions): RemoteBrowserPool<Page> {
- const { launchContext, stagehandOptions, headless, configuration, ...remoteOptions } = options;
-
- return stagehandLauncher(launchContext, stagehandOptions, headless, configuration).createRemoteBrowserPool<Page>(
- remoteOptions,
- );
-}
-
function stagehandLauncher(
launchContext: StagehandLaunchContext = {},
stagehandOptions: StagehandOptions = {},
diff --git a/packages/stagehand-crawler/src/internals/stagehand-crawler.ts b/packages/stagehand-crawler/src/internals/stagehand-crawler.ts
index 6c29fae76..e8ec72048 100644
--- a/packages/stagehand-crawler/src/internals/stagehand-crawler.ts
+++ b/packages/stagehand-crawler/src/internals/stagehand-crawler.ts
@@ -31,7 +31,7 @@ import { assertBrowserPoolNotConfigured, parseArgument, schemas } from '@crawlee
import type { Page, Response } from 'playwright';
import { z } from 'zod';
-import { remoteStagehandBrowserPool, stagehandBrowserPool } from './stagehand-browser-pool';
+import { stagehandBrowserPool } from './stagehand-browser-pool';
import type { StagehandController } from './stagehand-controller';
import type { StagehandLaunchContext } from './stagehand-launcher';
import { enhancePageWithStagehand } from './utils/stagehand-utils';
@@ -449,21 +449,22 @@ export class StagehandCrawler<
configuration,
// The pool serves plain Playwright pages - a page only becomes a `StagehandPage` further down the
// pipeline, once `setUpStagehand` enhances it - so its page type is narrower than the crawler's.
- browserPoolBuilder: (remoteBrowser) =>
- (remoteBrowser
- ? remoteStagehandBrowserPool({
- ...remoteBrowser,
- launchContext,
- stagehandOptions,
- headless,
- configuration,
- })
- : stagehandBrowserPool({
- launchContext,
- stagehandOptions,
- headless,
- configuration,
- })) as unknown as OwnedBrowserPool<StagehandPage>,
+ browserPoolBuilder: (remoteBrowser) => {
+ // Stagehand manages its own browser (local or Browserbase), so a Crawlee-level remote connection
+ // would be silently ignored.
+ if (remoteBrowser) {
+ throw new Error(
+ 'StagehandCrawler does not support `remoteBrowser`. Use `stagehandOptions.env: "BROWSERBASE"` instead.',
+ );
+ }
+
+ return stagehandBrowserPool({
+ launchContext,
+ stagehandOptions,
+ headless,
+ configuration,
+ }) as unknown as OwnedBrowserPool<StagehandPage>;
+ },
contextPipelineBuilder: () => this.#buildContextPipeline(),
});
}
diff --git a/test/browser-pool/browser-plugins/plugins.test.ts b/test/browser-pool/browser-plugins/plugins.test.ts
index 44cfb6241..761fa6ae9 100644
--- a/test/browser-pool/browser-plugins/plugins.test.ts
+++ b/test/browser-pool/browser-plugins/plugins.test.ts
@@ -14,9 +14,7 @@ import {
} from '@crawlee/browser-pool';
import playwright from 'playwright';
import type { Server as ProxyChainServer } from 'proxy-chain';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { Browser } from 'puppeteer';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), vitest executes tests as ESM, so its alllll gooooood
import puppeteer from 'puppeteer';
import { runExampleComServer } from '../../shared/_helper.js';
diff --git a/test/browser-pool/browser-pool.test.ts b/test/browser-pool/browser-pool.test.ts
index 69fea27ec..22b212f2c 100644
--- a/test/browser-pool/browser-pool.test.ts
+++ b/test/browser-pool/browser-pool.test.ts
@@ -5,9 +5,7 @@ import { sleep } from 'crawlee';
import type { BrowserFingerprintWithHeaders } from 'fingerprint-generator';
import playwright from 'playwright';
import type { Server as ProxyChainServer } from 'proxy-chain';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { Page } from 'puppeteer';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), vitest executes tests as ESM, so its alllll gooooood
import puppeteer from 'puppeteer';
import { addTimeoutToPromise, tryCancel } from '@apify/timeout';
diff --git a/test/browser-pool/launch-context.test.ts b/test/browser-pool/launch-context.test.ts
index 49965037d..29530661e 100644
--- a/test/browser-pool/launch-context.test.ts
+++ b/test/browser-pool/launch-context.test.ts
@@ -15,16 +15,8 @@ describe('LaunchContext', () => {
test('extend() rejects every declared field as reserved', () => {
const context = createLaunchContext();
- // Includes `fingerprint`, `proxyUrl` and `remoteToken`, which slipped through the check in v3.
- const reservedKeys = [
- 'id',
- 'browserPlugin',
- 'launchOptions',
- 'fingerprint',
- 'proxyUrl',
- 'remoteToken',
- 'extend',
- ];
+ // Includes `fingerprint` and `proxyUrl`, which slipped through the check in v3.
+ const reservedKeys = ['id', 'browserPlugin', 'launchOptions', 'fingerprint', 'proxyUrl', 'extend'];
for (const key of reservedKeys) {
expect(() => context.extend({ [key]: 'anything' })).toThrow(
diff --git a/test/core/browser_launchers/puppeteer_launcher.test.ts b/test/core/browser_launchers/puppeteer_launcher.test.ts
index 15020c406..ee1f92fce 100644
--- a/test/core/browser_launchers/puppeteer_launcher.test.ts
+++ b/test/core/browser_launchers/puppeteer_launcher.test.ts
@@ -12,7 +12,6 @@ import basicAuthParser from 'basic-auth-parser';
// @ts-expect-error no types
import portastic from 'portastic';
import { createProxy } from 'proxy';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { Browser, Page } from 'puppeteer';
import { runExampleComServer } from '../../shared/_helper.js';
diff --git a/test/core/crawlers/basic_browser_crawler.ts b/test/core/crawlers/basic_browser_crawler.ts
index 4d5dbdd9d..b1cc5808f 100644
--- a/test/core/crawlers/basic_browser_crawler.ts
+++ b/test/core/crawlers/basic_browser_crawler.ts
@@ -1,5 +1,5 @@
-import type { BrowserPlugin, BrowserPoolHooks, BrowserPoolOptions, PuppeteerPlugin } from '@crawlee/browser-pool';
-import { BrowserPool, RemoteBrowserPool } from '@crawlee/browser-pool';
+import type { BrowserPoolHooks, BrowserPoolOptions, PuppeteerPlugin } from '@crawlee/browser-pool';
+import { BrowserPool, RemotePuppeteerPlugin } from '@crawlee/browser-pool';
import type {
BrowserCrawlerOptions,
BrowserCrawlingContext,
@@ -8,8 +8,7 @@ import type {
} from '@crawlee/puppeteer';
import { BrowserCrawler } from '@crawlee/puppeteer';
import type { Dictionary } from '@crawlee/types';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
-import type { HTTPResponse, Page } from 'puppeteer';
+import puppeteer, { type HTTPResponse, type Page } from 'puppeteer';
export type TestCrawlingContext = BrowserCrawlingContext<Page, HTTPResponse, Dictionary>;
@@ -36,9 +35,9 @@ export class BrowserCrawlerTest extends BrowserCrawler<Page, HTTPResponse, TestC
...browserCrawlerOptions,
browserPoolBuilder: (remoteBrowser) =>
remoteBrowser
- ? new RemoteBrowserPool<Page>({
- ...remoteBrowser,
- browserPlugins: browserPoolOptions!.browserPlugins as unknown as BrowserPlugin[],
+ ? new BrowserPool({
+ maxOpenBrowsers: remoteBrowser.maxOpenBrowsers,
+ browserPlugins: [new RemotePuppeteerPlugin(puppeteer, remoteBrowser)],
})
: new BrowserPool(browserPoolOptions!),
contextPipelineBuilder: () => this.buildContextPipeline(),
diff --git a/test/core/crawlers/browser_crawler.test.ts b/test/core/crawlers/browser_crawler.test.ts
index 89f2e5899..de8ccde1a 100644
--- a/test/core/crawlers/browser_crawler.test.ts
+++ b/test/core/crawlers/browser_crawler.test.ts
@@ -6,7 +6,7 @@ import {
BrowserPool as BrowserPoolClass,
OperatingSystemsName,
PuppeteerPlugin,
- RemoteBrowserPool,
+ RemotePuppeteerPlugin,
} from '@crawlee/browser-pool';
import {
BLOCKED_STATUS_CODES,
@@ -19,9 +19,7 @@ import { bindMethodsToServiceLocator, MemoryStorageBackend, serviceLocator, Serv
import type { PuppeteerGoToOptions } from '@crawlee/puppeteer';
import { EnqueueStrategy, ProxyConfiguration, Request, RequestList, RequestState, Session } from '@crawlee/puppeteer';
import { sleep } from '@crawlee/utils';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { HTTPResponse } from 'puppeteer';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), vitest executes tests as ESM, so its alllll gooooood
import puppeteer from 'puppeteer';
import { runExampleComServer } from '../../shared/_helper.js';
@@ -204,17 +202,16 @@ describe('BrowserCrawler', () => {
}
});
- test.concurrent('builds and owns a RemoteBrowserPool from the remoteBrowser option', async () => {
+ test.concurrent('builds and owns a remote browser pool from the remoteBrowser option', async () => {
const crawler = new BrowserCrawlerTest({
- remoteBrowser: { endpoint: 'ws://remote:9222', maxOpenBrowsers: 2 },
- browserPoolOptions: { browserPlugins: [new PuppeteerPlugin(puppeteer)] },
+ remoteBrowser: { endpoint: 'ws://remote:9222' },
requestHandler: async () => {},
});
- expect(crawler.browserPool).toBeInstanceOf(RemoteBrowserPool);
- expect((crawler.browserPool as RemoteBrowserPool).maxOpenBrowsers).toBe(2);
+ const pool = crawler.browserPool as BrowserPool;
+ expect(pool.browserPlugins[0]).toBeInstanceOf(RemotePuppeteerPlugin);
- await (crawler.browserPool as RemoteBrowserPool).destroy();
+ await pool.destroy();
});
test.concurrent('rejects remoteBrowser when a browserPool is passed in', async () => {
diff --git a/test/core/enqueue_links/click_elements.test.ts b/test/core/enqueue_links/click_elements.test.ts
index 5c82a4776..3b0cfc31b 100644
--- a/test/core/enqueue_links/click_elements.test.ts
+++ b/test/core/enqueue_links/click_elements.test.ts
@@ -12,7 +12,6 @@ import {
serviceLocator,
} from 'crawlee';
import type { Browser as PWBrowser, Page as PWPage } from 'playwright';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { Browser as PPBrowser, Page as PPPage, Target } from 'puppeteer';
// `clickElements` and `clickElementsAndInterceptNavigationRequests` are internals of @crawlee/puppeteer
// and are deliberately not part of its public surface, so reach them through the source module.
diff --git a/test/core/puppeteer_request_interception.test.ts b/test/core/puppeteer_request_interception.test.ts
index 87a830fd9..86afae96c 100644
--- a/test/core/puppeteer_request_interception.test.ts
+++ b/test/core/puppeteer_request_interception.test.ts
@@ -2,7 +2,6 @@ import type { Server } from 'node:http';
import { sleep } from '@crawlee/utils';
import { launchPuppeteer, puppeteerUtils } from 'crawlee';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { HTTPRequest } from 'puppeteer';
import { runExampleComServer } from '../shared/_helper.js';
diff --git a/test/core/puppeteer_utils.test.ts b/test/core/puppeteer_utils.test.ts
index db26d77f3..1ad902824 100644
--- a/test/core/puppeteer_utils.test.ts
+++ b/test/core/puppeteer_utils.test.ts
@@ -3,7 +3,6 @@ import path from 'node:path';
import { MemoryStorageBackend, serviceLocator } from '@crawlee/core';
import { KeyValueStore, launchPuppeteer, puppeteerUtils, Request } from '@crawlee/puppeteer';
-// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { Browser, Page } from 'puppeteer';
import { runExampleComServer } from '../shared/_helper.js';
diff --git a/test/integration/remote-browser-incognito.test.ts b/test/integration/remote-browser-incognito.test.ts
index daae0453d..cd73b37c1 100644
--- a/test/integration/remote-browser-incognito.test.ts
+++ b/test/integration/remote-browser-incognito.test.ts
@@ -11,7 +11,7 @@
*
* With the wrapper removed, request 2's body should report no cookies.
*/
-import { PlaywrightCrawler, remotePlaywrightBrowserPool } from 'crawlee';
+import { PlaywrightCrawler, playwrightBrowserPool } from 'crawlee';
import { expect, test } from 'vitest';
import { BROWSERLESS_URL, httpbin } from './helpers.js';
@@ -26,18 +26,15 @@ test.skipIf(!process.env.CRAWLEE_DIFFICULT_TESTS)(
// Tuning the pool that wraps the remote connection means building it here rather than using the
// crawler's terser `remoteBrowser` option - and owning its teardown as a result.
- const browserPool = remotePlaywrightBrowserPool({
- endpoint: BROWSERLESS_URL,
- maxOpenBrowsers: 1,
- browserPoolOptions: {
- retireBrowserAfterPageCount: 10, // keep the same browser across both requests
- maxOpenPagesPerBrowser: 2,
- postPageCreateHooks: [
- (page: object, browserController: { id: string }) => {
- controllerIdByPage.set(page, browserController.id);
- },
- ],
- },
+ const browserPool = playwrightBrowserPool({
+ remoteBrowser: { endpoint: BROWSERLESS_URL, maxOpenBrowsers: 1 },
+ retireBrowserAfterPageCount: 10, // keep the same browser across both requests
+ maxOpenPagesPerBrowser: 2,
+ postPageCreateHooks: [
+ (page, browserController) => {
+ controllerIdByPage.set(page, browserController.id);
+ },
+ ],
});
const crawler = new PlaywrightCrawler({