@crawlee/browser-pool 4.0.0-beta.19 → 4.0.0-beta.190

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +14 -14
  2. package/abstract-classes/browser-controller.d.ts +91 -14
  3. package/abstract-classes/browser-controller.js +61 -24
  4. package/abstract-classes/browser-plugin.d.ts +48 -17
  5. package/abstract-classes/browser-plugin.js +69 -13
  6. package/anonymize-proxy.d.ts +5 -2
  7. package/anonymize-proxy.js +9 -5
  8. package/browser-pool.d.ts +106 -29
  9. package/browser-pool.js +250 -87
  10. package/container-proxy-server.d.ts +0 -1
  11. package/container-proxy-server.js +0 -1
  12. package/events.d.ts +2 -3
  13. package/events.js +0 -1
  14. package/fingerprinting/hooks.d.ts +0 -1
  15. package/fingerprinting/hooks.js +26 -10
  16. package/fingerprinting/types.d.ts +3 -4
  17. package/fingerprinting/types.js +0 -1
  18. package/fingerprinting/utils.d.ts +0 -1
  19. package/fingerprinting/utils.js +5 -6
  20. package/index.d.ts +14 -7
  21. package/index.js +5 -3
  22. package/launch-context.d.ts +20 -5
  23. package/launch-context.js +21 -10
  24. package/package.json +9 -9
  25. package/playwright/playwright-browser.d.ts +2 -6
  26. package/playwright/playwright-browser.js +16 -17
  27. package/playwright/playwright-controller.d.ts +0 -1
  28. package/playwright/playwright-controller.js +9 -6
  29. package/playwright/playwright-plugin.d.ts +10 -7
  30. package/playwright/playwright-plugin.js +40 -16
  31. package/proxy-server.d.ts +0 -1
  32. package/proxy-server.js +0 -1
  33. package/puppeteer/puppeteer-controller.d.ts +0 -1
  34. package/puppeteer/puppeteer-controller.js +28 -20
  35. package/puppeteer/puppeteer-plugin.d.ts +5 -3
  36. package/puppeteer/puppeteer-plugin.js +83 -46
  37. package/remote-browser-pool.d.ts +170 -0
  38. package/remote-browser-pool.js +202 -0
  39. package/remote-browser-provider.d.ts +83 -0
  40. package/remote-browser-provider.js +67 -0
  41. package/utils.d.ts +7 -1
  42. package/utils.js +19 -1
  43. package/abstract-classes/browser-controller.d.ts.map +0 -1
  44. package/abstract-classes/browser-controller.js.map +0 -1
  45. package/abstract-classes/browser-plugin.d.ts.map +0 -1
  46. package/abstract-classes/browser-plugin.js.map +0 -1
  47. package/anonymize-proxy.d.ts.map +0 -1
  48. package/anonymize-proxy.js.map +0 -1
  49. package/browser-pool.d.ts.map +0 -1
  50. package/browser-pool.js.map +0 -1
  51. package/container-proxy-server.d.ts.map +0 -1
  52. package/container-proxy-server.js.map +0 -1
  53. package/events.d.ts.map +0 -1
  54. package/events.js.map +0 -1
  55. package/fingerprinting/hooks.d.ts.map +0 -1
  56. package/fingerprinting/hooks.js.map +0 -1
  57. package/fingerprinting/types.d.ts.map +0 -1
  58. package/fingerprinting/types.js.map +0 -1
  59. package/fingerprinting/utils.d.ts.map +0 -1
  60. package/fingerprinting/utils.js.map +0 -1
  61. package/index.d.ts.map +0 -1
  62. package/index.js.map +0 -1
  63. package/launch-context.d.ts.map +0 -1
  64. package/launch-context.js.map +0 -1
  65. package/logger.d.ts +0 -3
  66. package/logger.d.ts.map +0 -1
  67. package/logger.js +0 -5
  68. package/logger.js.map +0 -1
  69. package/playwright/playwright-browser.d.ts.map +0 -1
  70. package/playwright/playwright-browser.js.map +0 -1
  71. package/playwright/playwright-controller.d.ts.map +0 -1
  72. package/playwright/playwright-controller.js.map +0 -1
  73. package/playwright/playwright-plugin.d.ts.map +0 -1
  74. package/playwright/playwright-plugin.js.map +0 -1
  75. package/proxy-server.d.ts.map +0 -1
  76. package/proxy-server.js.map +0 -1
  77. package/puppeteer/puppeteer-controller.d.ts.map +0 -1
  78. package/puppeteer/puppeteer-controller.js.map +0 -1
  79. package/puppeteer/puppeteer-plugin.d.ts.map +0 -1
  80. package/puppeteer/puppeteer-plugin.js.map +0 -1
  81. package/utils.d.ts.map +0 -1
  82. package/utils.js.map +0 -1
package/README.md CHANGED
@@ -1,23 +1,23 @@
1
1
  <h1 align="center">
2
2
  <a href="https://crawlee.dev">
3
3
  <picture>
4
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true">
5
- <img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500">
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true" />
5
+ <img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500" />
6
6
  </picture>
7
7
  </a>
8
- <br>
8
+ <br />
9
9
  <small>A web scraping and browser automation library</small>
10
10
  </h1>
11
11
 
12
- <p align=center>
13
- <a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
12
+ <p align="center">
13
+ <a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" width="250" height="55"/></a>
14
14
  </p>
15
15
 
16
- <p align=center>
17
- <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" style="max-width: 100%;"></a>
18
- <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" style="max-width: 100%;"></a>
19
- <a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" style="max-width: 100%;"></a>
20
- <a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" style="max-width: 100%;"></a>
16
+ <p align="center">
17
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" /></a>
18
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" /></a>
19
+ <a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" /></a>
20
+ <a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" /></a>
21
21
  </p>
22
22
 
23
23
  Crawlee covers your crawling and scraping end-to-end and **helps you build reliable scrapers. Fast.**
@@ -89,7 +89,7 @@ By default, Crawlee stores data to `./storage` in the current working directory.
89
89
  We provide automated beta builds for every merged code change in Crawlee. You can find them in the npm [list of releases](https://www.npmjs.com/package/crawlee?activeTab=versions). If you want to test new features or bug fixes before we release them, feel free to install a beta build like this:
90
90
 
91
91
  ```bash
92
- npm install crawlee@3.12.3-beta.13
92
+ npm install crawlee@next
93
93
  ```
94
94
 
95
95
  If you also use the [Apify SDK](https://github.com/apify/apify-sdk-js), you need to specify dependency overrides in your `package.json` file so that you don't end up with multiple versions of Crawlee installed:
@@ -98,9 +98,9 @@ If you also use the [Apify SDK](https://github.com/apify/apify-sdk-js), you need
98
98
  {
99
99
  "overrides": {
100
100
  "apify": {
101
- "@crawlee/core": "3.12.3-beta.13",
102
- "@crawlee/types": "3.12.3-beta.13",
103
- "@crawlee/utils": "3.12.3-beta.13"
101
+ "@crawlee/core": "$crawlee",
102
+ "@crawlee/types": "$crawlee",
103
+ "@crawlee/utils": "$crawlee"
104
104
  }
105
105
  }
106
106
  }
@@ -1,9 +1,73 @@
1
+ import { type CrawleeLogger } from '@crawlee/core';
1
2
  import type { Cookie, Dictionary } from '@crawlee/types';
2
3
  import { TypedEmitter } from 'tiny-typed-emitter';
3
4
  import { BROWSER_CONTROLLER_EVENTS } from '../events.js';
4
5
  import type { LaunchContext } from '../launch-context.js';
5
6
  import type { UnwrapPromise } from '../utils.js';
6
7
  import type { BrowserPlugin, CommonBrowser, CommonLibrary } from './browser-plugin.js';
8
+ /**
9
+ * The subset of the browser-pool `LaunchContext` that {@link IBrowserController} exposes.
10
+ * Other fields are only available on the concrete `LaunchContext` class.
11
+ */
12
+ export interface IBrowserLaunchContext {
13
+ /**
14
+ * The proxy URL the browser was launched with, if any.
15
+ */
16
+ proxyUrl?: string;
17
+ /**
18
+ * The fingerprint applied to the browser, if fingerprinting is enabled.
19
+ * Typed as `unknown` here; cast to the concrete `LaunchContext` if you
20
+ * need the structured shape.
21
+ */
22
+ fingerprint?: unknown;
23
+ /**
24
+ * `true` if each page in this browser uses its own context.
25
+ */
26
+ useIncognitoPages?: boolean;
27
+ /**
28
+ * The actual options the browser was launched with, after pre-launch hooks.
29
+ */
30
+ launchOptions?: Dictionary | undefined;
31
+ }
32
+ /**
33
+ * The minimal public contract of a browser controller.
34
+ *
35
+ * Coordination with the pool (page-counting, `activate`, `assignBrowser`, lifecycle
36
+ * promises, …) is intentionally **not** part of this contract.
37
+ *
38
+ * @category Browser management
39
+ */
40
+ export interface IBrowserController<Page = unknown> {
41
+ /**
42
+ * A stable identifier for this controller instance. Useful for tracking
43
+ * which browser served which request.
44
+ */
45
+ readonly id: string;
46
+ /**
47
+ * The configuration the underlying browser was launched with — proxy URL,
48
+ * fingerprint, session, launcher-specific options, etc.
49
+ */
50
+ readonly launchContext: IBrowserLaunchContext;
51
+ /**
52
+ * The raw browser handle from the underlying automation library
53
+ * (Puppeteer `Browser`, Playwright `Browser`/`BrowserContext`, …).
54
+ * Escape hatch for things the controller does not expose directly.
55
+ */
56
+ readonly browser: unknown;
57
+ /**
58
+ * Reads cookies for the given page.
59
+ */
60
+ getCookies(page: Page): Promise<Cookie[]>;
61
+ /**
62
+ * Writes cookies for the given page.
63
+ */
64
+ setCookies(page: Page, cookies: Cookie[]): Promise<void>;
65
+ /**
66
+ * Gracefully closes the browser this controller owns. After this resolves,
67
+ * the controller is no longer usable.
68
+ */
69
+ close(): Promise<void>;
70
+ }
7
71
  export interface BrowserControllerEvents<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']>>> {
8
72
  [BROWSER_CONTROLLER_EVENTS.BROWSER_CLOSED]: (controller: BrowserController<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>) => void;
9
73
  }
@@ -15,12 +79,14 @@ export interface BrowserControllerEvents<Library extends CommonLibrary, LibraryO
15
79
  * for the specialized classes, because it's the same for all of them.
16
80
  * @hideconstructor
17
81
  */
18
- export declare abstract class BrowserController<Library extends CommonLibrary = 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 TypedEmitter<BrowserControllerEvents<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>> {
19
- id: string;
82
+ export declare abstract class BrowserController<Library extends CommonLibrary = 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 TypedEmitter<BrowserControllerEvents<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>> implements IBrowserController<NewPageResult> {
83
+ #private;
84
+ readonly id: string;
85
+ protected readonly log: CrawleeLogger;
20
86
  /**
21
87
  * The `BrowserPlugin` instance used to launch the browser.
22
88
  */
23
- browserPlugin: BrowserPlugin<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>;
89
+ readonly browserPlugin: BrowserPlugin<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>;
24
90
  /**
25
91
  * Browser representation of the underlying automation library.
26
92
  */
@@ -30,12 +96,7 @@ export declare abstract class BrowserController<Library extends CommonLibrary =
30
96
  */
31
97
  launchContext: LaunchContext<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>;
32
98
  /**
33
- * The proxy tier tied to this browser controller.
34
- * `undefined` if no tiered proxy is used.
35
- */
36
- proxyTier?: number;
37
- /**
38
- * The proxy URL used by the browser controller. This is set every time the browser controller uses proxy (even the tiered one).
99
+ * The proxy URL used by the browser controller.
39
100
  * `undefined` if no proxy is used
40
101
  */
41
102
  proxyUrl?: string;
@@ -43,10 +104,10 @@ export declare abstract class BrowserController<Library extends CommonLibrary =
43
104
  activePages: number;
44
105
  totalPages: number;
45
106
  lastPageOpenedAt: number;
46
- private _activate;
47
- private isActivePromise;
48
- private commitBrowser;
49
- private hasBrowserPromise;
107
+ /**
108
+ * Returns a promise that resolves once the browser controller has been activated.
109
+ */
110
+ waitForActive(): Promise<void>;
50
111
  constructor(browserPlugin: BrowserPlugin<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>);
51
112
  /**
52
113
  * Activates the BrowserController. If you try to open new pages before
@@ -77,6 +138,23 @@ export declare abstract class BrowserController<Library extends CommonLibrary =
77
138
  * @ignore
78
139
  */
79
140
  newPage(pageOptions?: NewPageOptions): Promise<NewPageResult>;
141
+ /**
142
+ * Accounts for a page no longer being open. Callable from either side and safe to call twice:
143
+ * the page's own `close` event, or the pool when it gives up on a close that never settles.
144
+ * Tracked in a `WeakSet` rather than via `isClosed()`, because that reports the same event.
145
+ * @internal
146
+ */
147
+ registerPageClosed(page: NewPageResult): void;
148
+ /**
149
+ * Registers cleanup belonging to a single page: an anonymizing proxy server, an incognito
150
+ * context. It runs from `registerPageClosed`, so it happens whether the page closed on its own
151
+ * or the pool gave up on a close that never settled, and it runs at most once.
152
+ *
153
+ * Hanging it off the page's `close` event instead leaks it in exactly the case this controller
154
+ * now handles, because that event does not arrive for a page the browser never destroyed.
155
+ * @ignore
156
+ */
157
+ protected registerPageTeardown(page: NewPageResult, teardown: () => Promise<void>): void;
80
158
  setCookies(page: NewPageResult, cookies: Cookie[]): Promise<void>;
81
159
  getCookies(page: NewPageResult): Promise<Cookie[]>;
82
160
  /**
@@ -104,4 +182,3 @@ export declare abstract class BrowserController<Library extends CommonLibrary =
104
182
  */
105
183
  abstract normalizeProxyOptions(proxyUrl: string | undefined, pageOptions: any): Record<string, unknown>;
106
184
  }
107
- //# sourceMappingURL=browser-controller.d.ts.map
@@ -1,7 +1,8 @@
1
+ import { serviceLocator } from '@crawlee/core';
1
2
  import { nanoid } from 'nanoid';
2
3
  import { TypedEmitter } from 'tiny-typed-emitter';
3
4
  import { tryCancel } from '@apify/timeout';
4
- import { log } from '../logger.js';
5
+ import { BROWSER_CONTROLLER_EVENTS } from '../events.js';
5
6
  const PROCESS_KILL_TIMEOUT_MILLIS = 5000;
6
7
  /**
7
8
  * The `BrowserController` serves two purposes. First, it is the base class that
@@ -13,6 +14,7 @@ const PROCESS_KILL_TIMEOUT_MILLIS = 5000;
13
14
  */
14
15
  export class BrowserController extends TypedEmitter {
15
16
  id = nanoid();
17
+ log;
16
18
  /**
17
19
  * The `BrowserPlugin` instance used to launch the browser.
18
20
  */
@@ -26,29 +28,33 @@ export class BrowserController extends TypedEmitter {
26
28
  */
27
29
  launchContext = undefined;
28
30
  /**
29
- * The proxy tier tied to this browser controller.
30
- * `undefined` if no tiered proxy is used.
31
- */
32
- proxyTier;
33
- /**
34
- * The proxy URL used by the browser controller. This is set every time the browser controller uses proxy (even the tiered one).
31
+ * The proxy URL used by the browser controller.
35
32
  * `undefined` if no proxy is used
36
33
  */
37
34
  proxyUrl;
38
35
  isActive = false;
39
36
  activePages = 0;
37
+ #closedPages = new WeakSet();
38
+ #pageTeardowns = new WeakMap();
40
39
  totalPages = 0;
41
40
  lastPageOpenedAt = Date.now();
42
- _activate;
43
- isActivePromise = new Promise((resolve) => {
44
- this._activate = resolve;
41
+ #activate;
42
+ #isActivePromise = new Promise((resolve) => {
43
+ this.#activate = resolve;
45
44
  });
46
- commitBrowser;
47
- hasBrowserPromise = new Promise((resolve) => {
48
- this.commitBrowser = resolve;
45
+ /**
46
+ * Returns a promise that resolves once the browser controller has been activated.
47
+ */
48
+ async waitForActive() {
49
+ await this.#isActivePromise;
50
+ }
51
+ #commitBrowser;
52
+ #hasBrowserPromise = new Promise((resolve) => {
53
+ this.#commitBrowser = resolve;
49
54
  });
50
55
  constructor(browserPlugin) {
51
56
  super();
57
+ this.log = serviceLocator.getLogger().child({ prefix: 'BrowserPool' });
52
58
  this.browserPlugin = browserPlugin;
53
59
  }
54
60
  /**
@@ -61,7 +67,7 @@ export class BrowserController extends TypedEmitter {
61
67
  if (!this.browser) {
62
68
  throw new Error('Cannot activate BrowserController without an assigned browser.');
63
69
  }
64
- this._activate();
70
+ this.#activate();
65
71
  this.isActive = true;
66
72
  }
67
73
  /**
@@ -73,7 +79,7 @@ export class BrowserController extends TypedEmitter {
73
79
  }
74
80
  this.browser = browser;
75
81
  this.launchContext = launchContext;
76
- this.commitBrowser();
82
+ this.#commitBrowser();
77
83
  }
78
84
  /**
79
85
  * Gracefully closes the browser and makes sure
@@ -82,21 +88,22 @@ export class BrowserController extends TypedEmitter {
82
88
  * Emits 'browserClosed' event.
83
89
  */
84
90
  async close() {
85
- await this.hasBrowserPromise;
91
+ await this.#hasBrowserPromise;
86
92
  try {
87
93
  await this._close();
88
94
  // TODO: shouldn't this go in a finally instead?
89
95
  this.isActive = false;
90
96
  }
91
97
  catch (error) {
92
- log.debug(`Could not close browser.\nCause: ${error.message}`, { id: this.id });
98
+ this.log.debug(`Could not close browser.\nCause: ${error.message}`, { id: this.id });
93
99
  }
94
- this.emit("browserClosed" /* BROWSER_CONTROLLER_EVENTS.BROWSER_CLOSED */, this);
95
- setTimeout(() => {
100
+ this.emit(BROWSER_CONTROLLER_EVENTS.BROWSER_CLOSED, this);
101
+ const killTimer = setTimeout(() => {
96
102
  this._kill().catch((err) => {
97
- log.debug(`Could not kill browser.\nCause: ${err.message}`, { id: this.id });
103
+ this.log.debug(`Could not kill browser.\nCause: ${err.message}`, { id: this.id });
98
104
  });
99
105
  }, PROCESS_KILL_TIMEOUT_MILLIS);
106
+ killTimer.unref();
100
107
  }
101
108
  /**
102
109
  * Immediately kills the browser process.
@@ -104,9 +111,9 @@ export class BrowserController extends TypedEmitter {
104
111
  * Emits 'browserClosed' event.
105
112
  */
106
113
  async kill() {
107
- await this.hasBrowserPromise;
114
+ await this.#hasBrowserPromise;
108
115
  await this._kill();
109
- this.emit("browserClosed" /* BROWSER_CONTROLLER_EVENTS.BROWSER_CLOSED */, this);
116
+ this.emit(BROWSER_CONTROLLER_EVENTS.BROWSER_CLOSED, this);
110
117
  }
111
118
  /**
112
119
  * Opens new browser page.
@@ -115,12 +122,43 @@ export class BrowserController extends TypedEmitter {
115
122
  async newPage(pageOptions) {
116
123
  this.activePages++;
117
124
  this.totalPages++;
118
- await this.isActivePromise;
125
+ await this.#isActivePromise;
119
126
  const page = await this._newPage(pageOptions);
120
127
  tryCancel();
121
128
  this.lastPageOpenedAt = Date.now();
122
129
  return page;
123
130
  }
131
+ /**
132
+ * Accounts for a page no longer being open. Callable from either side and safe to call twice:
133
+ * the page's own `close` event, or the pool when it gives up on a close that never settles.
134
+ * Tracked in a `WeakSet` rather than via `isClosed()`, because that reports the same event.
135
+ * @internal
136
+ */
137
+ registerPageClosed(page) {
138
+ if (this.#closedPages.has(page))
139
+ return;
140
+ this.#closedPages.add(page);
141
+ this.activePages--;
142
+ const teardown = this.#pageTeardowns.get(page);
143
+ if (!teardown)
144
+ return;
145
+ this.#pageTeardowns.delete(page);
146
+ teardown().catch((error) => {
147
+ this.log.debug(`Could not clean up after a closed page.\nCause:${error.message}`, { id: this.id });
148
+ });
149
+ }
150
+ /**
151
+ * Registers cleanup belonging to a single page: an anonymizing proxy server, an incognito
152
+ * context. It runs from `registerPageClosed`, so it happens whether the page closed on its own
153
+ * or the pool gave up on a close that never settled, and it runs at most once.
154
+ *
155
+ * Hanging it off the page's `close` event instead leaks it in exactly the case this controller
156
+ * now handles, because that event does not arrive for a page the browser never destroyed.
157
+ * @ignore
158
+ */
159
+ registerPageTeardown(page, teardown) {
160
+ this.#pageTeardowns.set(page, teardown);
161
+ }
124
162
  async setCookies(page, cookies) {
125
163
  return this._setCookies(page, cookies);
126
164
  }
@@ -128,4 +166,3 @@ export class BrowserController extends TypedEmitter {
128
166
  return this._getCookies(page);
129
167
  }
130
168
  }
131
- //# sourceMappingURL=browser-controller.js.map
@@ -1,8 +1,9 @@
1
- import { CriticalError } from '@crawlee/core';
1
+ import { type CrawleeLogger, CriticalError } from '@crawlee/core';
2
2
  import type { Dictionary } from '@crawlee/types';
3
3
  import type { LaunchContextOptions } from '../launch-context.js';
4
4
  import { LaunchContext } from '../launch-context.js';
5
- import type { UnwrapPromise } from '../utils.js';
5
+ import type { RemoteConnection, RemoteConnectionParameters } from '../remote-browser-pool.js';
6
+ import { type UnwrapPromise } from '../utils.js';
6
7
  import type { BrowserController } from './browser-controller.js';
7
8
  /**
8
9
  * The default User Agent used by `PlaywrightCrawler`, `launchPlaywright`, 'PuppeteerCrawler' and 'launchPuppeteer'
@@ -11,8 +12,6 @@ import type { BrowserController } from './browser-controller.js';
11
12
  * - without using a fingerprint,
12
13
  * - without specifying a user agent.
13
14
  * Last updated on 2022-05-05.
14
- *
15
- * After you update it here, please update it also in jsdom-crawler.ts
16
15
  */
17
16
  export declare const DEFAULT_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36";
18
17
  /**
@@ -27,14 +26,13 @@ export interface CommonLibrary {
27
26
  launch(opts?: Dictionary): Promise<CommonBrowser>;
28
27
  name?: () => string;
29
28
  }
30
- /** @internal */
31
29
  export interface CommonBrowser {
32
30
  newPage(...args: unknown[]): Promise<CommonPage>;
33
31
  }
34
- /** @internal */
35
32
  export interface CommonPage {
36
33
  close(...args: unknown[]): Promise<unknown>;
37
34
  url(): string | Promise<string>;
35
+ evaluate(pageFunction: ((...args: any[]) => unknown) | string, ...args: unknown[]): Promise<unknown>;
38
36
  }
39
37
  export interface BrowserPluginOptions<LibraryOptions> {
40
38
  /**
@@ -68,6 +66,11 @@ export interface BrowserPluginOptions<LibraryOptions> {
68
66
  * Might cause performance issues, as Crawlee might launch too many browser instances.
69
67
  */
70
68
  browserPerProxy?: boolean;
69
+ /**
70
+ * If set to `true`, TLS certificate errors from the upstream proxy will be ignored.
71
+ * This is useful when using HTTPS proxies with self-signed certificates.
72
+ */
73
+ ignoreProxyCertificate?: boolean;
71
74
  }
72
75
  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'>> {
73
76
  }
@@ -78,14 +81,43 @@ export interface CreateLaunchContextOptions<Library extends CommonLibrary, Libra
78
81
  * feed them to {@link BrowserPool} for use.
79
82
  */
80
83
  export declare abstract class BrowserPlugin<Library extends CommonLibrary = 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']>>> {
81
- name: string;
82
- library: Library;
83
- launchOptions: LibraryOptions;
84
- proxyUrl?: string;
85
- userDataDir?: string;
84
+ readonly name: string;
85
+ protected readonly log: CrawleeLogger;
86
+ readonly library: Library;
87
+ readonly launchOptions: LibraryOptions;
88
+ readonly proxyUrl?: string;
89
+ readonly userDataDir?: string;
86
90
  useIncognitoPages: boolean;
87
- browserPerProxy?: boolean;
91
+ readonly browserPerProxy?: boolean;
92
+ readonly ignoreProxyCertificate?: boolean;
93
+ /**
94
+ * Set by {@link RemoteBrowserPool} when this plugin connects to a remote browser service instead of
95
+ * launching locally. Holds the bridge the plugin uses to resolve endpoints and release sessions; all
96
+ * remote-session policy lives in the pool, not here.
97
+ *
98
+ * @internal
99
+ */
100
+ remoteConnection?: RemoteConnection;
101
+ /** Static connect() parameters for a remote connection (protocol, headers, …). @internal */
102
+ remoteConnectionParameters?: RemoteConnectionParameters;
88
103
  constructor(library: Library, options?: BrowserPluginOptions<LibraryOptions>);
104
+ /**
105
+ * Configures this plugin to connect to a remote browser using the given {@link RemoteConnection}.
106
+ * Called by {@link RemoteBrowserPool}; subclasses may override to apply library-specific defaults
107
+ * (e.g. forcing incognito pages).
108
+ *
109
+ * @internal
110
+ */
111
+ useRemoteConnection(connection: RemoteConnection, parameters?: RemoteConnectionParameters): void;
112
+ /**
113
+ * Resolves a remote endpoint via the injected {@link RemoteConnection}, stores the session token on
114
+ * the launch context (so the controller can release it on close), and runs the library-specific `connect`.
115
+ * On failure the session is released and the error is wrapped in a {@link BrowserLaunchError}.
116
+ *
117
+ * Subclasses implement only the `connect` callback — the resolve / token / release / error-wrap scaffolding
118
+ * lives here so it stays identical across plugins.
119
+ */
120
+ protected connectToRemoteBrowser(launchContext: LaunchContext<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>, connect: (url: string) => Promise<LaunchResult>): Promise<LaunchResult>;
89
121
  /**
90
122
  * Creates a `LaunchContext` with all the information needed
91
123
  * to launch a browser. Aside from library specific launch options,
@@ -98,13 +130,13 @@ export declare abstract class BrowserPlugin<Library extends CommonLibrary = Comm
98
130
  * Launches the browser using provided launch context.
99
131
  */
100
132
  launch(launchContext?: LaunchContext<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>): Promise<LaunchResult>;
101
- private _mergeArgsToHideWebdriver;
102
- protected _throwAugmentedLaunchError(cause: unknown, executablePath: string | undefined, dockerImage: string, moduleInstallCommand: string): never;
133
+ private mergeArgsToHideWebdriver;
134
+ protected throwAugmentedLaunchError(cause: unknown, executablePath: string | undefined, dockerImage: string, moduleInstallCommand: string): never;
103
135
  /**
104
136
  * @private
105
137
  */
106
- protected abstract _addProxyToLaunchOptions(launchContext: LaunchContext<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>): Promise<void>;
107
- protected abstract _isChromiumBasedBrowser(launchContext: LaunchContext<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>): boolean;
138
+ protected abstract addProxyToLaunchOptions(launchContext: LaunchContext<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>): Promise<void>;
139
+ protected abstract isChromiumBasedBrowser(launchContext: LaunchContext<Library, LibraryOptions, LaunchResult, NewPageOptions, NewPageResult>): boolean;
108
140
  /**
109
141
  * @private
110
142
  */
@@ -113,4 +145,3 @@ export declare abstract class BrowserPlugin<Library extends CommonLibrary = Comm
113
145
  export declare class BrowserLaunchError extends CriticalError {
114
146
  constructor(...args: ConstructorParameters<typeof CriticalError>);
115
147
  }
116
- //# sourceMappingURL=browser-plugin.d.ts.map
@@ -1,6 +1,7 @@
1
- import { CriticalError } from '@crawlee/core';
1
+ import { CriticalError, serviceLocator } from '@crawlee/core';
2
2
  import merge from 'lodash.merge';
3
3
  import { LaunchContext } from '../launch-context.js';
4
+ import { sanitizeEndpointForLog } from '../utils.js';
4
5
  /**
5
6
  * The default User Agent used by `PlaywrightCrawler`, `launchPlaywright`, 'PuppeteerCrawler' and 'launchPuppeteer'
6
7
  * when Chromium/Chrome browser is launched:
@@ -8,8 +9,6 @@ import { LaunchContext } from '../launch-context.js';
8
9
  * - without using a fingerprint,
9
10
  * - without specifying a user agent.
10
11
  * Last updated on 2022-05-05.
11
- *
12
- * After you update it here, please update it also in jsdom-crawler.ts
13
12
  */
14
13
  export const DEFAULT_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36';
15
14
  /**
@@ -20,20 +19,73 @@ export const DEFAULT_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_
20
19
  */
21
20
  export class BrowserPlugin {
22
21
  name = this.constructor.name;
22
+ log;
23
23
  library;
24
24
  launchOptions;
25
25
  proxyUrl;
26
26
  userDataDir;
27
27
  useIncognitoPages;
28
28
  browserPerProxy;
29
+ ignoreProxyCertificate;
30
+ /**
31
+ * Set by {@link RemoteBrowserPool} when this plugin connects to a remote browser service instead of
32
+ * launching locally. Holds the bridge the plugin uses to resolve endpoints and release sessions; all
33
+ * remote-session policy lives in the pool, not here.
34
+ *
35
+ * @internal
36
+ */
37
+ remoteConnection;
38
+ /** Static connect() parameters for a remote connection (protocol, headers, …). @internal */
39
+ remoteConnectionParameters;
29
40
  constructor(library, options = {}) {
30
- const { launchOptions = {}, proxyUrl, userDataDir, useIncognitoPages = false, browserPerProxy = false, } = options;
41
+ const { launchOptions = {}, proxyUrl, userDataDir, useIncognitoPages = false, browserPerProxy = false, ignoreProxyCertificate = false, } = options;
42
+ this.log = serviceLocator.getLogger().child({ prefix: 'BrowserPool' });
31
43
  this.library = library;
32
44
  this.launchOptions = launchOptions;
33
45
  this.proxyUrl = proxyUrl && new URL(proxyUrl).href.slice(0, -1);
34
46
  this.userDataDir = userDataDir;
35
47
  this.useIncognitoPages = useIncognitoPages;
36
48
  this.browserPerProxy = browserPerProxy;
49
+ this.ignoreProxyCertificate = ignoreProxyCertificate;
50
+ }
51
+ /**
52
+ * Configures this plugin to connect to a remote browser using the given {@link RemoteConnection}.
53
+ * Called by {@link RemoteBrowserPool}; subclasses may override to apply library-specific defaults
54
+ * (e.g. forcing incognito pages).
55
+ *
56
+ * @internal
57
+ */
58
+ useRemoteConnection(connection, parameters = {}) {
59
+ this.remoteConnection = connection;
60
+ this.remoteConnectionParameters = parameters;
61
+ }
62
+ /**
63
+ * Resolves a remote endpoint via the injected {@link RemoteConnection}, stores the session token on
64
+ * the launch context (so the controller can release it on close), and runs the library-specific `connect`.
65
+ * On failure the session is released and the error is wrapped in a {@link BrowserLaunchError}.
66
+ *
67
+ * Subclasses implement only the `connect` callback — the resolve / token / release / error-wrap scaffolding
68
+ * lives here so it stays identical across plugins.
69
+ */
70
+ async connectToRemoteBrowser(launchContext, connect) {
71
+ const connection = this.remoteConnection;
72
+ let url;
73
+ let token;
74
+ try {
75
+ ({ url, token } = await connection.resolve({ proxyUrl: launchContext.proxyUrl }));
76
+ }
77
+ catch (cause) {
78
+ throw new BrowserLaunchError('Failed to resolve the remote browser endpoint.', { cause });
79
+ }
80
+ launchContext.remoteToken = token;
81
+ try {
82
+ return await connect(url);
83
+ }
84
+ catch (cause) {
85
+ await connection.release(token);
86
+ throw new BrowserLaunchError(`Failed to connect to remote browser at "${sanitizeEndpointForLog(url)}". ` +
87
+ 'Check that the endpoint is reachable and accepts the configured protocol.', { cause });
88
+ }
37
89
  }
38
90
  /**
39
91
  * Creates a `LaunchContext` with all the information needed
@@ -42,7 +94,7 @@ export class BrowserPlugin {
42
94
  * management of the pool and extra features.
43
95
  */
44
96
  createLaunchContext(options = {}) {
45
- const { id, launchOptions = {}, proxyUrl = this.proxyUrl, useIncognitoPages = this.useIncognitoPages, userDataDir = this.userDataDir, browserPerProxy = this.browserPerProxy, proxyTier, } = options;
97
+ const { id, launchOptions = {}, proxyUrl = this.proxyUrl, useIncognitoPages = this.useIncognitoPages, userDataDir = this.userDataDir, browserPerProxy = this.browserPerProxy, ignoreProxyCertificate = this.ignoreProxyCertificate, isRemote = !!this.remoteConnection, } = options;
46
98
  return new LaunchContext({
47
99
  id,
48
100
  launchOptions: merge({}, this.launchOptions, launchOptions),
@@ -51,21 +103,23 @@ export class BrowserPlugin {
51
103
  useIncognitoPages,
52
104
  userDataDir,
53
105
  browserPerProxy,
54
- proxyTier,
106
+ ignoreProxyCertificate,
107
+ isRemote,
55
108
  });
56
109
  }
57
110
  /**
58
111
  * Launches the browser using provided launch context.
59
112
  */
60
113
  async launch(launchContext = this.createLaunchContext()) {
114
+ // launchOptions is only used by the local launch path below — remote connections ignore it.
61
115
  launchContext.launchOptions ??= {};
62
116
  const { proxyUrl, launchOptions } = launchContext;
63
- if (proxyUrl) {
64
- await this._addProxyToLaunchOptions(launchContext);
117
+ if (proxyUrl && !launchContext.isRemote) {
118
+ await this.addProxyToLaunchOptions(launchContext);
65
119
  }
66
- if (this._isChromiumBasedBrowser(launchContext)) {
120
+ if (!launchContext.isRemote && this.isChromiumBasedBrowser(launchContext)) {
67
121
  // This will set the args for chromium based browsers to hide the webdriver.
68
- launchOptions.args = this._mergeArgsToHideWebdriver(launchOptions.args);
122
+ launchOptions.args = this.mergeArgsToHideWebdriver(launchOptions.args);
69
123
  // When User-Agent is not set, and we're using Chromium in headless mode,
70
124
  // it is better to use DEFAULT_USER_AGENT to reduce chance of detection,
71
125
  // as otherwise 'HeadlessChrome' is present in User-Agent string.
@@ -74,9 +128,12 @@ export class BrowserPlugin {
74
128
  launchOptions.args.push(`--user-agent=${DEFAULT_USER_AGENT}`);
75
129
  }
76
130
  }
131
+ if (launchContext.isRemote) {
132
+ this.log.info('Connecting to remote browser (skipping local proxy and webdriver stealth configuration).');
133
+ }
77
134
  return this._launch(launchContext);
78
135
  }
79
- _mergeArgsToHideWebdriver(originalArgs) {
136
+ mergeArgsToHideWebdriver(originalArgs) {
80
137
  if (!originalArgs?.length) {
81
138
  return ['--disable-blink-features=AutomationControlled'];
82
139
  }
@@ -89,7 +146,7 @@ export class BrowserPlugin {
89
146
  }
90
147
  return originalArgs;
91
148
  }
92
- _throwAugmentedLaunchError(cause, executablePath, dockerImage, moduleInstallCommand) {
149
+ throwAugmentedLaunchError(cause, executablePath, dockerImage, moduleInstallCommand) {
93
150
  const errorMessage = ['Failed to launch browser. Please check the following:'];
94
151
  if (executablePath) {
95
152
  errorMessage.push(`- Check whether the provided executable path "${executablePath}" is correct.`);
@@ -118,4 +175,3 @@ export class BrowserLaunchError extends CriticalError {
118
175
  });
119
176
  }
120
177
  }
121
- //# sourceMappingURL=browser-plugin.js.map