@crawlee/cli 4.0.0-beta.33 → 4.0.0-beta.330

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 (33) hide show
  1. package/README.md +15 -11
  2. package/commands/{CreateProjectCommand.d.ts → create-project-command.d.ts} +0 -1
  3. package/commands/{CreateProjectCommand.js → create-project-command.js} +4 -6
  4. package/commands/{InstallPlaywrightBrowsersCommand.d.ts → install-playwright-browsers-command.d.ts} +0 -1
  5. package/commands/{InstallPlaywrightBrowsersCommand.js → install-playwright-browsers-command.js} +0 -1
  6. package/commands/{RunProjectCommand.d.ts → run-project-command.d.ts} +0 -1
  7. package/commands/{RunProjectCommand.js → run-project-command.js} +0 -1
  8. package/commands/upgrade-command.d.ts +19 -0
  9. package/commands/upgrade-command.js +150 -0
  10. package/index.d.ts +0 -1
  11. package/index.js +16 -5
  12. package/package.json +10 -10
  13. package/skills/crawlee-upgrade/SKILL.md +20 -0
  14. package/skills/crawlee-upgrade-v4/SKILL.md +45 -0
  15. package/skills/crawlee-upgrade-v4/guide/autoscaling.md +256 -0
  16. package/skills/crawlee-upgrade-v4/guide/browser-management.md +174 -0
  17. package/skills/crawlee-upgrade-v4/guide/http-clients.md +108 -0
  18. package/skills/crawlee-upgrade-v4/guide/internals.md +130 -0
  19. package/skills/crawlee-upgrade-v4/guide/removed-symbols.md +63 -0
  20. package/skills/crawlee-upgrade-v4/guide/request-loaders.md +241 -0
  21. package/skills/crawlee-upgrade-v4/guide/sessions-and-proxies.md +164 -0
  22. package/skills/crawlee-upgrade-v4/guide/statistics.md +56 -0
  23. package/skills/crawlee-upgrade-v4/guide/storage-backends.md +170 -0
  24. package/skills/crawlee-upgrade-v4/guide/upgrading-v4.md +1310 -0
  25. package/skills/crawlee-upgrade-v4/guide/utils-and-types.md +52 -0
  26. package/commands/CreateProjectCommand.d.ts.map +0 -1
  27. package/commands/CreateProjectCommand.js.map +0 -1
  28. package/commands/InstallPlaywrightBrowsersCommand.d.ts.map +0 -1
  29. package/commands/InstallPlaywrightBrowsersCommand.js.map +0 -1
  30. package/commands/RunProjectCommand.d.ts.map +0 -1
  31. package/commands/RunProjectCommand.js.map +0 -1
  32. package/index.d.ts.map +0 -1
  33. package/index.js.map +0 -1
@@ -0,0 +1,256 @@
1
+ ---
2
+ id: autoscaling
3
+ title: 'Upgrading to v4: autoscaling'
4
+ sidebar_label: Autoscaling
5
+ sidebar_position: 8
6
+ slug: /upgrading/upgrading-to-v4/autoscaling
7
+ ---
8
+
9
+ The `minConcurrency` / `maxConcurrency` / `maxRequestsPerMinute` crawler options work as before. This section matters when you used `autoscaledPoolOptions`, drove an `AutoscaledPool` directly, or configured snapshotting and system status. This page is part of the [Upgrading to v4](./upgrading-v4.md) guide.
10
+
11
+ ## Autoscaling moved to `ConcurrencySystem`
12
+
13
+ Everything that decides whether there is free compute for one more task — snapshotting, the system-status evaluation, the concurrency budget and the scaling logic — moved out of `AutoscaledPool` into a new `ConcurrencySystem`. What is left of the pool is a bare task loop, which is now **internal**: crawlers build and drive one for themselves, and `ConcurrencySystem` is the only part of this you configure.
14
+
15
+ The point is sharing: inject one instance into several crawlers to cap their **combined** concurrency against a single budget, instead of letting each scale independently and oversubscribe the host. The option is typed as `IConcurrencySystem`, a minimal read-only contract, so an alternative governor can be substituted; `ConcurrencySystem` is the canonical implementation and the one crawlers build by default.
16
+
17
+ :::info Who starts and stops it
18
+
19
+ Whoever *builds* a `ConcurrencySystem` owns its lifecycle. Crawlers do that for the default system they build per run. One **you** supply is yours to `start()` and `stop()`, because no crawler can know when the last borrower has finished. Forgetting to start it makes `run()` **throw**; stopping it while a crawler is still running only **warns**. Read `isRunning` to check whether a system handed to you was already started by its owner.
20
+
21
+ :::
22
+
23
+ Every migration below has the same shape — build, start, run, stop:
24
+
25
+ ```typescript
26
+ import { CheerioCrawler, ConcurrencySystem } from 'crawlee';
27
+
28
+ const concurrencySystem = new ConcurrencySystem({ maxConcurrency: 20 });
29
+ await concurrencySystem.start();
30
+
31
+ // One crawler, or several: a shared instance caps their combined concurrency.
32
+ const a = new CheerioCrawler({ concurrencySystem, requestHandler });
33
+ const b = new CheerioCrawler({ concurrencySystem, requestHandler });
34
+
35
+ try {
36
+ await Promise.all([a.run(), b.run()]);
37
+ } finally {
38
+ await concurrencySystem.stop();
39
+ }
40
+ ```
41
+
42
+ On Node.js 24, `await using` replaces the `try`/`finally` — see [collaborators you own are disposable](./upgrading-v4.md#collaborators-you-own-are-disposable).
43
+
44
+ ### `AutoscaledPool` is no longer public API
45
+
46
+ `AutoscaledPool` is `@internal` in v4, along with `AutoscaledPoolOptions`. It is still exported from `@crawlee/basic` (and re-exported by `crawlee`), so nothing breaks at import time — but with all the configuration moved to the `ConcurrencySystem`, what remains is a bare parallel task runner. It can change without a major bump, so avoid depending on it; if you only wanted bounded parallelism, a `p-limit`-style helper is a better fit than an internal Crawlee class.
47
+
48
+ The crawler's `autoscaledPool` property is **removed** as a result. Everything it was reached for has a crawler-level counterpart:
49
+
50
+ | Before | After |
51
+ |---|---|
52
+ | `await crawler.autoscaledPool.pause(secs)` | `await crawler.pause(secs)` |
53
+ | `crawler.autoscaledPool.resume()` | `crawler.resume()` |
54
+ | `await crawler.autoscaledPool.abort()` | `await crawler.teardown()` — or `crawler.stop()`, to let in-flight requests finish |
55
+ | `crawler.autoscaledPool.desiredConcurrency` | `crawler.concurrencySystem?.desiredConcurrency` |
56
+ | `crawler.autoscaledPool.currentConcurrency` | `crawler.concurrencySystem?.currentConcurrency` |
57
+
58
+ ```typescript
59
+ const crawler = new CheerioCrawler({
60
+ async requestHandler({ log }) {
61
+ log.info(`Currently running ${crawler.concurrencySystem?.currentConcurrency} requests in parallel.`);
62
+ },
63
+ });
64
+ ```
65
+
66
+ `crawler.concurrencySystem` is `undefined` until `run()` has resolved it, and a crawler-owned default is rebuilt for every run — so read it during a run rather than caching it across runs. A system *you* injected is simply the instance you passed in.
67
+
68
+ The getter is typed as the read-only `IConcurrencySystem` and has no setters, so retuning concurrency mid-crawl means owning the instance:
69
+
70
+ ```typescript
71
+ const concurrencySystem = new ConcurrencySystem({ maxConcurrency: 50 });
72
+
73
+ const crawler = new CheerioCrawler({
74
+ concurrencySystem,
75
+ requestHandler,
76
+ errorHandler: async ({ response }) => {
77
+ if (response?.status === 429) concurrencySystem.maxConcurrency = 10;
78
+ },
79
+ });
80
+ ```
81
+
82
+ `crawler.pause()` resolves once the requests already in flight have settled, and leaves `run()` pending until you `resume()` — unlike `crawler.stop()`, which ends the run gracefully. One behavioral consequence of the split: pausing no longer suspends autoscaling, because the autoscaling interval belongs to the `ConcurrencySystem`, which knows nothing about its borrowers' pause state — deliberately, since other crawlers sharing it may still need scaling. A paused crawler's system keeps evaluating (and possibly scaling down) the desired concurrency and keeps emitting its periodic state log. Scaling *up* stays effectively blocked, as the current concurrency drains below the ratio required for a scale-up. To silence the system during a long pause, `stop()` it (if you own it) and `start()` it again before resuming; a restart discards the snapshots taken before it, so the pause is not mistaken for load.
83
+
84
+ #### If you were driving an `AutoscaledPool` directly
85
+
86
+ All scaling and load-monitoring options were **removed** from `AutoscaledPoolOptions` and now live on `ConcurrencySystemOptions`: `minConcurrency`, `maxConcurrency`, `desiredConcurrency`, `desiredConcurrencyRatio`, `scaleUpStepRatio`, `scaleDownStepRatio`, `loggingIntervalSecs`, `autoscaleIntervalSecs`, and `maxTasksPerMinute`, plus the load-signal configuration described [below](#load-signal-options-restructured). The `snapshotterOptions` and `systemStatusOptions` bags are both gone, as are the `minConcurrency`/`maxConcurrency` accessors and every setter (`desiredConcurrency` and `currentConcurrency` remain as read-only getters, joined by a new read-only `system` getter). In their place, `AutoscaledPoolOptions` gained a **required** `concurrencySystem`, plus a **required** `consumer` — the pool's identity (`{ id }`), which it presents to the governor on every capacity query and booking so that a shared one can tell several pools' tasks apart.
87
+
88
+ **Before:**
89
+ ```typescript
90
+ const pool = new AutoscaledPool({
91
+ minConcurrency: 5,
92
+ maxConcurrency: 50,
93
+ maxTasksPerMinute: 120,
94
+ runTaskFunction: async () => { /* ... */ },
95
+ isTaskReadyFunction: async () => true,
96
+ isFinishedFunction: async () => false,
97
+ });
98
+ await pool.run();
99
+ ```
100
+
101
+ **After:**
102
+ ```typescript
103
+ import { AutoscaledPool, ConcurrencySystem } from '@crawlee/basic';
104
+
105
+ const concurrencySystem = new ConcurrencySystem({
106
+ minConcurrency: 5,
107
+ maxConcurrency: 50,
108
+ maxTasksPerMinute: 120,
109
+ });
110
+ await concurrencySystem.start();
111
+
112
+ const pool = new AutoscaledPool({
113
+ concurrencySystem,
114
+ consumer: { id: 'my-pool' },
115
+ runTaskFunction: async () => { /* ... */ },
116
+ isTaskReadyFunction: async () => true,
117
+ isFinishedFunction: async () => false,
118
+ });
119
+
120
+ try {
121
+ await pool.run();
122
+ } finally {
123
+ await concurrencySystem.stop();
124
+ }
125
+ ```
126
+
127
+ ### `autoscaledPoolOptions` is now `taskLoopOptions`, and no longer carries concurrency config
128
+
129
+ The crawler option was renamed — it was named after a class that is now internal — and narrowed to **only** the task-loop predicates `isFinishedFunction` and `isTaskReadyFunction`. Its type changed from `AutoscaledPoolOptions` to `TaskLoopPredicates`. Concurrency configuration goes through either the `minConcurrency` / `maxConcurrency` / `initialConcurrency` / `maxRequestsPerMinute` shortcuts (which configure the crawler's default `ConcurrencySystem`), or — for anything finer — a supplied `concurrencySystem`. The new `initialConcurrency` shortcut replaces `autoscaledPoolOptions.desiredConcurrency` and defaults to `minConcurrency` (`HttpCrawler` and its subclasses default to 10 instead, see the preset below).
130
+
131
+ Two options that used to live here — `maybeRunIntervalSecs` and `taskTimeoutSecs` — did *not* move to the `ConcurrencySystem` and have no replacement: the crawler's task-loop cadence is no longer configurable. The third, `log`, is gone from the crawler option too: the crawler passes its own logger to the default system, and a `ConcurrencySystem` you build takes a `log` option.
132
+
133
+ **Before:**
134
+ ```typescript
135
+ const crawler = new CheerioCrawler({
136
+ autoscaledPoolOptions: {
137
+ desiredConcurrency: 10,
138
+ maxTasksPerMinute: 120,
139
+ systemStatusOptions: { currentHistorySecs: 10 },
140
+ },
141
+ requestHandler,
142
+ });
143
+ ```
144
+
145
+ **After:**
146
+ ```typescript
147
+ const concurrencySystem = new ConcurrencySystem({
148
+ desiredConcurrency: 10,
149
+ maxTasksPerMinute: 120,
150
+ currentHistorySecs: 10,
151
+ });
152
+
153
+ const crawler = new CheerioCrawler({ concurrencySystem, requestHandler });
154
+ ```
155
+
156
+ The shortcuts cannot be combined with a supplied `concurrencySystem` — they configure the default system that a supplied one replaces, so the crawler constructor **throws** rather than dropping a limit you asked for. For the common case, the shortcuts are all you need and no `ConcurrencySystem` is involved:
157
+
158
+ ```typescript
159
+ const crawler = new CheerioCrawler({
160
+ minConcurrency: 5,
161
+ maxConcurrency: 50,
162
+ initialConcurrency: 10,
163
+ maxRequestsPerMinute: 120,
164
+ requestHandler,
165
+ });
166
+ ```
167
+
168
+ A supplied system also replaces the default *wholesale*, including any crawler-specific tuning that default carried. `HttpCrawler` and its subclasses (`CheerioCrawler`, `JSDOMCrawler`, …) ship a preset — a higher `desiredConcurrency` and a relaxed event loop signal — exported as `HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS`; spread it in to keep it:
169
+
170
+ ```typescript
171
+ import { ConcurrencySystem, HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS } from 'crawlee';
172
+
173
+ const concurrencySystem = new ConcurrencySystem({
174
+ ...HTTP_OPTIMIZED_CONCURRENCY_SYSTEM_OPTIONS,
175
+ maxConcurrency: 50,
176
+ });
177
+ ```
178
+
179
+ ## Load-signal options restructured
180
+
181
+ The per-resource load-signal configuration was consolidated. It used to be spread across flat `SnapshotterOptions` fields, the `max*OverloadedRatio` options on `SystemStatusOptions`, and a separate `loadSignals` array — three places, two of them named after classes that are now internal. All of it now lives in a single `loadSignals` bag on `ConcurrencySystemOptions`: one options bag per built-in signal (each carrying its own limits *and* its `overloadedRatio`), plus `custom` for your own implementations.
182
+
183
+ **Before:**
184
+ ```typescript
185
+ new AutoscaledPool({
186
+ snapshotterOptions: {
187
+ maxUsedMemoryRatio: 0.8,
188
+ eventLoopSnapshotIntervalSecs: 2,
189
+ maxBlockedMillis: 100,
190
+ clientSnapshotIntervalSecs: 1,
191
+ maxClientErrors: 3,
192
+ snapshotHistorySecs: 60,
193
+ },
194
+ systemStatusOptions: {
195
+ maxMemoryOverloadedRatio: 0.2,
196
+ maxEventLoopOverloadedRatio: 0.7,
197
+ maxCpuOverloadedRatio: 0.4,
198
+ maxClientOverloadedRatio: 0.3,
199
+ currentHistorySecs: 10,
200
+ loadSignals: [myProxyHealthSignal],
201
+ },
202
+ // ...
203
+ });
204
+ ```
205
+
206
+ **After:**
207
+ ```typescript
208
+ new ConcurrencySystem({
209
+ loadSignals: {
210
+ memory: { maxUsedRatio: 0.8, overloadedRatio: 0.2 },
211
+ eventLoop: { snapshotIntervalSecs: 2, maxBlockedMillis: 100, overloadedRatio: 0.7 },
212
+ cpu: { overloadedRatio: 0.4 },
213
+ storageBackend: { snapshotIntervalSecs: 1, maxErrors: 3, overloadedRatio: 0.3 },
214
+ custom: [myProxyHealthSignal],
215
+ },
216
+ // the two evaluation windows are policy, alongside the scaling options
217
+ snapshotHistorySecs: 60,
218
+ currentHistorySecs: 10,
219
+ });
220
+ ```
221
+
222
+ The signal that watches storage rate-limit errors follows the [`StorageClient` → `StorageBackend` rename](./storage-backends.md#storagebackend-interface-simplified): the option is `loadSignals.storageBackend`, the class `StorageBackendLoadSignal`, and its verdict is reported as `SystemInfo.storageBackendInfo`. The type of that verdict, `ClientInfo`, is now `LoadSignalInfo` — it backs every signal's entry, not just this one.
223
+
224
+ In detail: the four `max*OverloadedRatio` options of `SystemStatusOptions` were **removed** (each signal now owns its overload ratio, set in its own bag), custom signals moved from `systemStatusOptions.loadSignals` to `loadSignals.custom`, and the two evaluation windows — `snapshotHistorySecs` (autoscaling) and `currentHistorySecs` (task gating) — are plain options on `ConcurrencySystemOptions`, since they apply to every signal alike rather than to any one of them.
225
+
226
+ If you built the signals yourself, the factory functions `createCpuLoadSignal()`, `createEventLoopLoadSignal()` and `createClientLoadSignal()` are **removed**, together with the `ClientLoadSignal`, `ClientLoadSignalOptions` and `ClientSnapshot` types. Construct the classes instead — `new CpuLoadSignal(options)`, `new EventLoopLoadSignal(options)`, `new StorageBackendLoadSignal(options)` — alongside `MemoryLoadSignal`, which already was one. Their option names lost the per-resource prefixes, as in the example above:
227
+
228
+ | v3 | v4 |
229
+ | --- | --- |
230
+ | `MemoryLoadSignalOptions.maxUsedMemoryRatio` | `maxUsedRatio` |
231
+ | `EventLoopLoadSignalOptions.eventLoopSnapshotIntervalSecs` | `snapshotIntervalSecs` |
232
+ | `ClientLoadSignalOptions.clientSnapshotIntervalSecs` | `StorageBackendLoadSignalOptions.snapshotIntervalSecs` |
233
+ | `ClientLoadSignalOptions.maxClientErrors` | `StorageBackendLoadSignalOptions.maxErrors` |
234
+ | `ClientLoadSignalOptions.client`, `CpuLoadSignalOptions.config`, `MemoryLoadSignalOptions.config` / `log` | *(removed — the signals read the storage backend and event manager from the `serviceLocator`)* |
235
+
236
+ Two related capabilities are new, and covered in the [scaling guide](https://crawlee.dev/js/docs/next/guides/scaling-crawlers#load-signals): a built-in signal can be switched **off** with `false`, and each built-in is also a public class (`MemoryLoadSignal`, `EventLoopLoadSignal`, `CpuLoadSignal`, `StorageBackendLoadSignal`) you can construct to wrap or adapt.
237
+
238
+ A duplicate signal name now **throws**, where naming a custom signal after a built-in (`memInfo`, `eventLoopInfo`, `cpuInfo`, or `clientInfo`, now `storageBackendInfo`) used to look like an override but never was one: the built-in kept running and kept holding concurrency down, while your signal only overwrote its field in the reported `SystemInfo`. To take a built-in's place, switch it off:
239
+
240
+ ```typescript
241
+ new ConcurrencySystem({
242
+ loadSignals: {
243
+ // Without `memory: false`, this throws — the built-in memory signal is still enabled.
244
+ memory: false,
245
+ custom: [myMemorySignal], // free to take over the vacated `memInfo` field
246
+ },
247
+ });
248
+ ```
249
+
250
+ `Snapshotter` and `SystemStatus` are no longer public API, along with `SnapshotterOptions` and `SystemStatusOptions` — they are implementation details of the `ConcurrencySystem`, which is now the only supported entry point to load monitoring; read the resulting `SystemInfo` through `ConcurrencySystem.getCurrentStatus()`. Still public: the configuration types, the four built-in signal classes, and the extension surface (`LoadSignal`, `SnapshotStore`, `LoadSignalStartContext`). The concrete snapshot types the built-ins produce are *not* — `getSample()` returns plain `LoadSnapshot` values.
251
+
252
+ ### Both evaluation windows are now requested from every signal
253
+
254
+ Overload is evaluated over two windows: `currentHistorySecs` (default 5s) gates whether another task may start, and `snapshotHistorySecs` (default 30s) drives autoscaling. The long one used to be implicit — `getHistoricalStatus()` asked each signal for *everything it had retained*, so a custom signal keeping five minutes of snapshots silently made autoscaling reason over five minutes of history for that resource while the built-ins used 30 seconds. Both are now requested explicitly from every signal, and `LoadSignal.start()` receives the wider of the two as `maxSampleWindowMillis` so retention can be sized to match.
255
+
256
+ You are affected if a custom signal retains **more** history than `snapshotHistorySecs` (its stale snapshots no longer influence scaling), or if its `getSample()` ignores the `sampleDurationMillis` argument, in which case it still contributes everything it has. On the API side, `snapshotHistoryMillis` was removed from the per-signal option types and `SnapshotStore` lost both its constructor argument and the `fromInterval`/`fromEvent` factories; call `useSampleWindow(maxSampleWindowMillis)` and `clear()` from your `start()` instead, as a store that is never given a window retains everything. The [scaling guide](https://crawlee.dev/js/docs/next/guides/scaling-crawlers#load-signals) has a worked example.
@@ -0,0 +1,174 @@
1
+ ---
2
+ id: browser-management
3
+ title: 'Upgrading to v4: browser management'
4
+ sidebar_label: Browser management
5
+ sidebar_position: 3
6
+ slug: /upgrading/upgrading-to-v4/browser-management
7
+ ---
8
+
9
+ Applies when you construct a `BrowserPool` yourself, reach for `browserController`, or tune `AdaptivePlaywrightCrawler` internals. This page is part of the [Upgrading to v4](./upgrading-v4.md) guide.
10
+
11
+ ## Custom `BrowserPool` implementations via the `IBrowserPool` interface
12
+
13
+ Browser crawlers now accept any object implementing the new `IBrowserPool` interface as their `browserPool` option, not just instances of the built-in `BrowserPool`. The interface follows the classic acquire/release pattern, plus a pair of helpers for moving state between the crawling session and the page:
14
+
15
+ - **`newPage(options?)`** — opens a new page. An optional `session` can be passed as a best-effort hint — the pool may use it for proxy configuration, fingerprinting, etc., but nothing is guaranteed.
16
+ - **`closePage(page, options?)`** — signals the pool that the caller is done with the page. If the optional `error` is a `SessionError`, the session that served the page is finished. A plain `SessionError` means it was blocked, so the pool should purge all state associated with it (e.g. retire the underlying browser). The `SessionRetiredError` subclass means the session merely reached its `maxUsageCount` or `maxAgeSecs`, and a pool may keep a warm page instead.
17
+ - **`extractPageState(page)`** — reads the relevant state (currently cookies) out of a page so the crawler can persist it back into the session.
18
+ - **`injectPageState(page, state)`** — the counterpart to `extractPageState`; seeds a page with state (currently cookies) before navigation. Isolation between pages is best-effort and depends on the pool implementation.
19
+
20
+ Lifecycle (`destroy`) is the responsibility of whoever owns the pool: a custom pool you construct yourself is never owned by the crawler, so the crawler never tears it down. This makes it straightforward to plug in a remote browser farm, a session-aware pool, or another custom browser-management strategy without subclassing `BrowserPool`.
21
+
22
+ ```typescript
23
+ import { PuppeteerCrawler } from '@crawlee/puppeteer';
24
+ import { BrowserPool, PuppeteerPlugin, type IBrowserPool } from '@crawlee/browser-pool';
25
+ import puppeteer from 'puppeteer';
26
+
27
+ const sharedPool = new BrowserPool({ browserPlugins: [new PuppeteerPlugin(puppeteer)] });
28
+
29
+ const crawler = new PuppeteerCrawler({
30
+ browserPool: sharedPool,
31
+ requestHandler: async ({ page }) => {
32
+ // …
33
+ },
34
+ });
35
+
36
+ // You own `sharedPool` — destroy it yourself when you're done.
37
+ await crawler.run();
38
+ await sharedPool.destroy();
39
+ ```
40
+
41
+ The `crawler.browserPool` property is now **read-only** (a getter). It was previously a writable field, so any code that reassigned it after construction (`crawler.browserPool = myPool`) no longer works — pass your pool via the `browserPool` constructor option instead.
42
+
43
+ ## `@crawlee/browser-pool` is no longer re-exported from `crawlee`
44
+
45
+ The meta-package used to `export *` from `@crawlee/browser-pool`, which made `BrowserPool`, `PuppeteerPlugin`, `PlaywrightPlugin`, `BrowserController`, `LaunchContext`, the fingerprint enums and the `IBrowserPool` / `NewPageOptions` interfaces importable from `crawlee`. They no longer are. Add `@crawlee/browser-pool` to your dependencies and import them from there:
46
+
47
+ ```diff
48
+ -import { BrowserPool, PlaywrightPlugin } from 'crawlee';
49
+ +import { BrowserPool, PlaywrightPlugin } from '@crawlee/browser-pool';
50
+ ```
51
+
52
+ The crawler-facing factories `playwrightBrowserPool()` and `puppeteerBrowserPool()` still come from `crawlee` and their respective crawler packages. For a remote connection, pass `remoteBrowser` to the regular factory; there are no separate `remote*BrowserPool()` functions. Building a pool this way needs no extra dependency.
53
+
54
+ ## `BrowserCrawlingContext.browserController` has been removed
55
+
56
+ The `browserController` property is no longer part of the crawling context (`BrowserCrawlingContext`). Browser controller management is now fully internal to the pool — the crawler interacts with the pool only through the `IBrowserPool` interface (`newPage`, `closePage`, `extractPageState`, and `injectPageState`).
57
+
58
+ If you previously used `browserController` in your request handlers, here is how to migrate the most common patterns:
59
+
60
+ **Cookies** — Cookie injection and persistence are now handled automatically by the crawler and the pool. You no longer need to call `browserController.getCookies()` or `browserController.setCookies()` manually.
61
+
62
+ **Proxy info** — Access proxy information via `session.proxyInfo` instead of `browserController.launchContext.proxyUrl`. TLS-error handling moved along with it: the pool reads `session.proxyInfo.ignoreTlsErrors`, so the `IBrowserPool` `newPage()` options have no `ignoreTlsErrors` field (the built-in `BrowserPool.newPage()` still accepts one as an explicit override). If you need to disable TLS verification for some other reason, set `ignoreHTTPSErrors` (Playwright) / `acceptInsecureCerts` (Puppeteer) through the browser's `launchOptions`.
63
+
64
+ **Direct browser access** — If you need the raw browser or controller instance (e.g. for Puppeteer/Playwright-specific APIs), construct a `BrowserPool` yourself, pass it to the crawler, and reference it directly in your handler — no cast needed:
65
+
66
+ ```typescript
67
+ import { BrowserPool, PuppeteerPlugin } from '@crawlee/browser-pool';
68
+ import { PuppeteerCrawler } from '@crawlee/puppeteer';
69
+ import puppeteer from 'puppeteer';
70
+
71
+ const pool = new BrowserPool({ browserPlugins: [new PuppeteerPlugin(puppeteer)] });
72
+
73
+ const crawler = new PuppeteerCrawler({
74
+ browserPool: pool,
75
+ requestHandler: async ({ page }) => {
76
+ const controller = pool.getBrowserControllerByPage(page);
77
+ // controller.browser, controller.launchContext, etc.
78
+ },
79
+ });
80
+
81
+ await crawler.run();
82
+ // You own the pool — tear it down yourself.
83
+ await pool.destroy();
84
+ ```
85
+
86
+ Note that this couples your code to the built-in `BrowserPool` — custom `IBrowserPool` implementations may not expose controllers at all.
87
+
88
+ ## Puppeteer cookies are now read and written at the browser-context level
89
+
90
+ The `PuppeteerController._getCookies` / `_setCookies` methods (used internally by the session pool to sync cookies between a `Session` and a Puppeteer page) now call `page.browserContext().cookies()` / `setCookie()` instead of the deprecated `page.cookies()` / `page.setCookie()`. The page-level API was removed in newer Puppeteer releases.
91
+
92
+ This aligns the Puppeteer controller with the Playwright controller, which has always worked at the context level.
93
+
94
+ **What changes in practice**
95
+ - Cookie reads return every cookie stored in the page's browser context, not just cookies matching the page's current URL. If your `Session` relied on the URL-scoped filtering (for example, to avoid pulling cookies that belong to other tabs in the same context), you'll now see the full set.
96
+ - Cookie writes are applied to the whole browser context. When pages share a context, cookies the crawler syncs from a session's cookie jar are visible to every other page in that context.
97
+
98
+ With `useIncognitoPages: true`, each page gets its own browser context, so each session owns its cookies and you should not notice any difference. With the default `useIncognitoPages: false`, pages share the browser's default context, so cookies written for one session become visible to other sessions' pages in that browser.
99
+
100
+ **Cookie `url` field** — the old `page.setCookie()` auto-filled a missing `url` on each cookie with the page's current URL. The new `browserContext().setCookie()` does not; Chromium rejects cookies that carry neither `url` nor `domain`. Crawlee's internal `_setCookies` keeps the old behavior by back-filling `page.url()` for any cookie that has neither field set, but if you call `browserContext().setCookie()` directly (outside of Crawlee) you need to provide one of them yourself.
101
+
102
+ ## Custom rendering type predictors via the `IRenderingTypePredictor` interface
103
+
104
+ The `renderingTypePredictor` option of `AdaptivePlaywrightCrawler` is now typed as the new `IRenderingTypePredictor` interface — `predict(request)` and `storeResult(requests, renderingType)`, nothing else, either of which may return a promise. The built-in `RenderingTypePredictor` implements it, so passing one still works.
105
+
106
+ What changed is the lifecycle: the crawler used to call `initialize()` on the predictor it was given, even though it did not create it. It now follows the same own-only-what-you-built rule as the session and browser pools — a predictor you pass in is *borrowed*, so setting it up is your job, and `initialize` is not part of the interface at all. The built-in predictor restores its persisted state in `initialize()` and will throw `Recoverable state has not yet been loaded` from `predict()` if it is never called:
107
+
108
+ ```typescript
109
+ import { AdaptivePlaywrightCrawler, RenderingTypePredictor } from '@crawlee/playwright';
110
+
111
+ const renderingTypePredictor = new RenderingTypePredictor({ detectionRatio: 0.1 });
112
+ // You own the predictor — initialize it yourself (this used to be done by the crawler).
113
+ await renderingTypePredictor.initialize();
114
+
115
+ const crawler = new AdaptivePlaywrightCrawler({
116
+ renderingTypePredictor,
117
+ requestHandler: async ({ pushData }) => {
118
+ // …
119
+ },
120
+ });
121
+ ```
122
+
123
+ If you don't pass a predictor, nothing changes: the crawler builds one from `renderingTypeDetectionRatio` and, since it owns that one, initializes it for you.
124
+
125
+ **Asynchronous predictors** — `predict()` is awaited before the crawler routes the request, so prefer loading whatever it needs up front over per-request I/O. `storeResult()` is *not* awaited per detection: the crawler tracks the promise it returns and drains everything still pending in `teardown()`, so a predictor that batches its writes can rely on them landing before the crawl ends. That wait is bounded by the internal timeout (`CRAWLEE_INTERNAL_TIMEOUT`), `crawler.drainRenderingDetections()` performs it on demand, and `crawler.inFlightRenderingTypeDetectionCount` reports what is still outstanding.
126
+
127
+ `teardown()` stops new detections from starting before it drains, so ending a `keepAlive` crawl by tearing it down from outside `run()` cannot leave a detection unpersisted either.
128
+
129
+ ## Remove `experimentalContainers` option
130
+
131
+ This experimental option relied on an outdated manifest version for browser extensions, it is not possible to achieve this with the currently supported versions.
132
+
133
+ ## `PlaywrightLauncher` is no longer exported
134
+
135
+ `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.
136
+
137
+ ## `BrowserCrawler.launchContext` was removed
138
+
139
+ The `launchContext` property on crawler instances is gone. The `launchContext` **option** is unchanged on `PlaywrightCrawler`, `PuppeteerCrawler` and `StagehandCrawler` — only the echo of it on the instance is gone. If you were reading `crawler.launchContext`, keep your own reference to the object you passed in.
140
+
141
+ The abstract `BrowserCrawler` base class also lost its `LaunchOptions` type parameter, which existed only to type that field, along with `InternalBrowserPoolOptions`; its type parameters now start with the page and response types. Custom crawlers extending `BrowserCrawler` must update their type arguments:
142
+
143
+ ```diff
144
+ -class MyCrawler extends BrowserCrawler<BrowserPoolOptions, LaunchOptions, MyCrawlingContext> {
145
+ +class MyCrawler extends BrowserCrawler<Page, Response, MyCrawlingContext> {
146
+ ```
147
+
148
+ ## Unused browser options are now rejected instead of ignored
149
+
150
+ `PlaywrightCrawler` no longer accepts a top-level `launcher` option, and `PlaywrightLaunchContext` no longer accepts `launchContextOptions`; both were silently ignored and are now reported as unknown options by the constructors' validation. Pass the browser type as `launchContext.launcher`, and persistent-context settings inside `launchContext.launchOptions`.
151
+
152
+ ## Dead v3 fingerprinting types are removed
153
+
154
+ `BrowserSpecification`, `GetFingerprintReturn` and `@crawlee/browser-pool`'s own `FingerprintGenerator` interface (which shadowed `fingerprint-generator`'s class of the same name) are no longer exported. They had no consumers — `BrowserPool.fingerprintGenerator` is typed by `fingerprint-generator`'s `FingerprintGenerator`, and `fingerprintGeneratorOptions` is still typed by `FingerprintGeneratorOptions`.
155
+
156
+ ## `BROWSER_POOL_EVENTS.BROWSER_CLOSED` was removed
157
+
158
+ It was never emitted. Listen for `BROWSER_CONTROLLER_EVENTS.BROWSER_CLOSED` on a `BrowserController` instead.
159
+
160
+ ## `BrowserPool` internals are private
161
+
162
+ `pages`, `pageIds`, `pageCounter`, `pageToBrowserController`, `startingBrowserControllers`, `activeBrowserControllers`, `retiredBrowserControllers`, `operationTimeoutMillis`, `closeInactiveBrowserAfterMillis`, `maxOpenPagesPerBrowser`, `retireBrowserAfterPageCount` and `useFingerprints` are no longer readable or writable from outside the pool. Use `getPage()`, `getPageId()` and `getBrowserControllerByPage()` to reach pages, the `browserLaunched` / `browserRetired` / `pageCreated` / `pageClosed` events to observe the pool's lifecycle, and pass the corresponding `BrowserPoolOptions` at construction instead of assigning to the mirrors afterwards — the options themselves are unchanged.
163
+
164
+ The six hook arrays (`preLaunchHooks`, `postLaunchHooks`, `prePageCreateHooks`, `postPageCreateHooks`, `prePageCloseHooks`, `postPageCloseHooks`) are private too. Supply hooks through the constructor options; mutating or replacing the arrays on a live pool is no longer possible.
165
+
166
+ ```diff
167
+ -const browserPool = new BrowserPool({ browserPlugins: [plugin] });
168
+ -browserPool.postLaunchHooks.push(myHook);
169
+ +const browserPool = new BrowserPool({ browserPlugins: [plugin], postLaunchHooks: [myHook] });
170
+ ```
171
+
172
+ `BrowserController.log` and `BrowserPlugin.log` are no longer part of the public type surface either. Subclasses inside `@crawlee/browser-pool` still use them, but they are not covered by backwards-compatibility guarantees — get your own logger from `serviceLocator.getLogger()`.
173
+
174
+ Several more members are `@internal`, and remain present at runtime only: `BrowserPool.fingerprintInjector`, `.fingerprintCache`, `.fingerprintOptions`; `BrowserController.isActive`, `.totalPages`, `.lastPageOpenedAt`, `.normalizeProxyOptions()`; `AnonymizeProxySugarOptions`; and the `PlaywrightBrowser` constructor. The `_close` / `_kill` / `_newPage` / `_getCookies` / `_setCookies` hooks on `BrowserController` and the `_launch` / `addProxyToLaunchOptions` / `isChromiumBasedBrowser` hooks on `BrowserPlugin` are *not* in that list: they carry no release tag, on the abstract declarations and on the `PlaywrightController` / `PuppeteerController` / `PlaywrightPlugin` / `PuppeteerPlugin` overrides alike, and remain the extension contract for your own subclasses.
@@ -0,0 +1,108 @@
1
+ ---
2
+ id: http-clients
3
+ title: 'Upgrading to v4: HTTP clients'
4
+ sidebar_label: HTTP clients
5
+ sidebar_position: 5
6
+ slug: /upgrading/upgrading-to-v4/http-clients
7
+ ---
8
+
9
+ Applies when you implemented `BaseHttpClient` yourself, or imported `gotScraping` from `@crawlee/utils`. This page is part of the [Upgrading to v4](./upgrading-v4.md) guide.
10
+
11
+ ## HTTP client packages and `BaseHttpClient` reshaped
12
+
13
+ The HTTP client abstraction moved out of `@crawlee/core` into two new packages, and its shape changed to match the native `fetch` model.
14
+
15
+ - **`@crawlee/http-client`** (new) now owns the `BaseHttpClient` abstract base class, along with `FetchHttpClient`, `ResponseWithUrl`, and `CustomFetchOptions`.
16
+ - **`@crawlee/got-scraping-client`** (new) provides `GotScrapingHttpClient` — the `got-scraping`-backed client — as an opt-in dependency, so `got-scraping` is no longer pulled into every install.
17
+
18
+ `BaseHttpClient` was redesigned around `fetch`. In v3 it declared `sendRequest<TResponseType>(request): Promise<HttpResponse>` and `stream(request): Promise<StreamingHttpResponse>`; in v4 subclasses implement a single `protected abstract fetch(input: Request, init?): Promise<Response>` and the base class provides `sendRequest(request, options?): Promise<Response>`. There is no `stream()` method anymore — a `Response` already exposes `body` as a stream. The following symbols that were part of the old `@crawlee/core` HTTP surface are **removed**: `HttpResponse`, `StreamingHttpResponse`, `ResponseTypes` and `BaseHttpResponseData`. `processHttpRequestOptions` is no longer public either; it remains reachable from `@crawlee/utils/internal` without semver guarantees.
19
+
20
+ If you implemented a custom HTTP client:
21
+
22
+ **Before:**
23
+ ```typescript
24
+ import { BaseHttpClient, HttpRequest, HttpResponse } from '@crawlee/core';
25
+
26
+ class MyClient implements BaseHttpClient {
27
+ async sendRequest<T>(request: HttpRequest<T>): Promise<HttpResponse<T>> { /* ... */ }
28
+ async stream(request: HttpRequest) { /* ... */ }
29
+ }
30
+ ```
31
+
32
+ **After:**
33
+ ```typescript
34
+ import { BaseHttpClient, type CustomFetchOptions } from '@crawlee/http-client';
35
+
36
+ class MyClient extends BaseHttpClient {
37
+ protected async fetch(input: Request, init?: RequestInit & CustomFetchOptions): Promise<Response> {
38
+ // return a native Response; sendRequest() is inherited from BaseHttpClient
39
+ }
40
+ }
41
+ ```
42
+
43
+ ### Removed `@crawlee/types` HTTP types
44
+
45
+ The `RedirectHandler` type (exported from `@crawlee/core` in v3) has been removed. It was the redirect-callback type for `BaseHttpClient.stream()`, which no longer exists in v4 — a custom HTTP client now only implements `fetch()`, as shown above. If you referenced it, delete the reference; there is no replacement.
46
+
47
+ The `BrowserLikeResponse` interface has been removed. It was a v3-era shim for reading `url()` and `headers()` off a got-style response during cookie handling, and has had no consumer since HTTP responses became standard `Response` objects. Read `response.url` and `response.headers` directly instead.
48
+
49
+ ### Removed `HttpRequest` properties
50
+
51
+ The following properties have been removed from `HttpRequest`, as v4's HTTP client contract is `fetch`-shaped and read none of them:
52
+
53
+ - `headerGenerator`, `headerGeneratorOptions`, `useHeaderGenerator` — header and fingerprint generation is now the HTTP client implementation's concern. `ImpitHttpClient` derives headers from the session fingerprint automatically; configure it through the client's own constructor options.
54
+ - `sessionToken` — fingerprint stability is now keyed off the `Session` passed via `SendRequestOptions.session`.
55
+ - `insecureHTTPParser` — no longer supported; there is no equivalent in the `fetch`-based clients.
56
+ - `throwHttpErrors` — `sendRequest` never throws on an HTTP error status; inspect `response.status` yourself. The crawler's `additionalHttpErrorStatusCodes` / `ignoreHttpErrorStatusCodes` options only cover the crawled request itself.
57
+ - `responseType` (and the `HttpRequest<TResponseType>` type parameter) — read the body from the returned `Response` with `response.json()` / `response.text()` / `response.bytes()`.
58
+ - `maxRedirects` — redirect following is handled inside `BaseHttpClient.sendRequest` and capped at 10 redirects; it is no longer configurable per request.
59
+ - `encoding` — a `Response` has no decoding option. Decode the bytes yourself, e.g. `new TextDecoder('latin1').decode(await response.arrayBuffer())`.
60
+
61
+ `followRedirect` now only accepts a boolean. With `followRedirect: false`, `sendRequest` returns the redirect response instead of following it; the predicate form is gone.
62
+
63
+ ### Remaining `HttpRequest` properties changed type
64
+
65
+ `HttpRequest` and `HttpRequestOptions` (the first argument of `context.sendRequest()`) moved from `@crawlee/core` to `@crawlee/types`, and no longer accept arbitrary extra keys. The properties that stayed are no longer got-shaped:
66
+
67
+ | Property | v3 | v4 |
68
+ | --- | --- | --- |
69
+ | `headers` | plain object | a `Headers` instance — a plain object throws at runtime |
70
+ | `timeout` | got's object, e.g. `{ request: 5000 }` | a number of milliseconds |
71
+ | `body` | `string`, `Buffer`, `Readable`, generator or form data | `Readable` — wrap other values in `Readable.from()`, or use `json` / `form` |
72
+ | `cookieJar` | any got-compatible jar | a `tough-cookie` `CookieJar` |
73
+
74
+ **Before:**
75
+ ```typescript
76
+ await sendRequest({
77
+ url,
78
+ headers: { accept: 'application/json' },
79
+ timeout: { request: 5000 },
80
+ });
81
+ ```
82
+
83
+ **After:**
84
+ ```typescript
85
+ await sendRequest({
86
+ url,
87
+ headers: new Headers({ accept: 'application/json' }),
88
+ timeout: 5000,
89
+ });
90
+ ```
91
+
92
+ `followRedirect` and `encoding` are still declared, but nothing reads them: redirects are always followed, and the body is decoded when you call `response.text()` / `response.json()`.
93
+
94
+ ### `gotScraping` is no longer exported from `@crawlee/utils`
95
+
96
+ The `gotScraping` singleton previously exported from `@crawlee/utils` has been removed. If you used it as the crawler's HTTP client, use the new `GotScrapingHttpClient` instead:
97
+
98
+ ```typescript
99
+ import { CheerioCrawler } from 'crawlee';
100
+ import { GotScrapingHttpClient } from '@crawlee/got-scraping-client';
101
+
102
+ const crawler = new CheerioCrawler({
103
+ httpClient: new GotScrapingHttpClient(),
104
+ requestHandler: async ({ $ }) => { /* ... */ },
105
+ });
106
+ ```
107
+
108
+ If you called `gotScraping(...)` directly for one-off requests unrelated to Crawlee, depend on the [`got-scraping`](https://www.npmjs.com/package/got-scraping) package directly instead.