@crawlee/playwright 4.0.0-rc.2 → 4.0.0

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.
package/README.md CHANGED
@@ -34,7 +34,7 @@ Crawlee is available as the [`crawlee`](https://www.npmjs.com/package/crawlee) N
34
34
 
35
35
  We recommend visiting the [Introduction tutorial](https://crawlee.dev/js/docs/introduction) in Crawlee documentation for more information.
36
36
 
37
- > Crawlee requires **Node.js 22.13 or higher**.
37
+ > Crawlee requires **Node.js 22.15 or higher**.
38
38
 
39
39
  ### With Crawlee CLI
40
40
 
@@ -144,6 +144,10 @@ Crawlee is open-source and runs anywhere, but since it's developed by [Apify](ht
144
144
 
145
145
  If you find any bug or issue with Crawlee, please [submit an issue on GitHub](https://github.com/apify/crawlee/issues). For questions, you can ask on [Stack Overflow](https://stackoverflow.com/questions/tagged/apify), in GitHub Discussions or you can join our [Discord server](https://discord.com/invite/jyEM2PRvMU).
146
146
 
147
+ ## Supported versions
148
+
149
+ New features and bug fixes land in the latest major version. The previous major version keeps receiving fixes for high and critical severity vulnerabilities for 12 months after the next major is released, and reaches end of life after that. See the [security policy](https://github.com/apify/crawlee/security/policy) for the current status of each version and for how to report a vulnerability.
150
+
147
151
  ## Contributing
148
152
 
149
153
  Your code contributions are welcome, and you'll be praised to eternity! If you have any ideas for improvements, either submit an issue or create a pull request. For contribution guidelines and the code of conduct, see [CONTRIBUTING.md](https://github.com/apify/crawlee/blob/master/CONTRIBUTING.md).
@@ -1,8 +1,9 @@
1
1
  import type { BrowserHook, LoadedRequest, RouterHandler, RouteSchemas, RoutesFromSchemas } from '@crawlee/browser';
2
- import type { BasicCrawlerOptions, CrawlingContext, EnqueueLinksOptions, GetUserDataFromRequest, RouterRoutes } from '@crawlee/basic';
2
+ import type { BasicCrawlerOptions, CrawlingContext, EnqueueLinksOptions, ExtractLinksOptions, GetUserDataFromRequest, RouterRoutes } from '@crawlee/basic';
3
3
  import { BasicCrawler } from '@crawlee/basic';
4
4
  import { CrawlingRequest } from '@crawlee/browser';
5
- import type { StorageTransactionView } from '@crawlee/core';
5
+ import type { CheerioCrawlerOptions } from '@crawlee/cheerio';
6
+ import type { AddRequestsBatchedResult, StorageTransactionView } from '@crawlee/core';
6
7
  import type { Dictionary, Awaitable } from '@crawlee/types';
7
8
  import { type Cheerio, type CheerioAPI } from 'cheerio';
8
9
  import type { AnyNode } from 'domhandler';
@@ -82,7 +83,18 @@ export interface AdaptivePlaywrightCrawlerContext<UserData extends Dictionary =
82
83
  * ```
83
84
  */
84
85
  parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioAPI>;
85
- enqueueLinks(options?: EnqueueLinksOptions): Promise<unknown>;
86
+ /**
87
+ * Extracts URLs from the current page, without adding them to the request queue.
88
+ * In a browser, it first waits for an element matching the selector, with a 5s timeout.
89
+ */
90
+ extractLinks(options?: ExtractLinksOptions): Promise<string[]>;
91
+ /**
92
+ * Extracts URLs from the current page and adds them to the request queue.
93
+ *
94
+ * By default, the requests are buffered until the crawler settles on this attempt's result, so the returned
95
+ * `requestId` of a newly added request is provisional, and nothing is added when the attempt is discarded.
96
+ */
97
+ enqueueLinks(options?: EnqueueLinksOptions): Promise<AddRequestsBatchedResult>;
86
98
  }
87
99
  interface AdaptiveHookContext extends Pick<AdaptivePlaywrightCrawlerContext, 'id' | 'session' | 'proxyInfo' | 'log' | 'extendTimeout'> {
88
100
  page?: Page;
@@ -98,7 +110,20 @@ export interface AdaptiveResultContext {
98
110
  /** The request whose handler produced the results. */
99
111
  request: CrawlingRequest;
100
112
  }
101
- export interface AdaptivePlaywrightCrawlerOptions<ContextExtension = Dictionary<never>, ExtendedContext extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<AdaptivePlaywrightCrawlerContext['request']>>, StatisticStateExtension extends AdaptivePlaywrightCrawlerStatisticState = AdaptivePlaywrightCrawlerStatisticState> extends Omit<BasicCrawlerOptions<AdaptivePlaywrightCrawlerContext, ContextExtension, ExtendedContext, Routes, StatisticStateExtension>, 'preNavigationHooks' | 'postNavigationHooks' | 'contextPipelineBuilder'>, Pick<PlaywrightCrawlerOptions, 'launchContext' | 'headless' | 'browserPool' | 'remoteBrowser'> {
113
+ export interface AdaptivePlaywrightCrawlerOptions<ContextExtension = Dictionary<never>, ExtendedContext extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<AdaptivePlaywrightCrawlerContext['request']>>, StatisticStateExtension extends AdaptivePlaywrightCrawlerStatisticState = AdaptivePlaywrightCrawlerStatisticState> extends Omit<BasicCrawlerOptions<AdaptivePlaywrightCrawlerContext, ContextExtension, ExtendedContext, Routes, StatisticStateExtension>, 'preNavigationHooks' | 'postNavigationHooks' | 'contextPipelineBuilder'> {
114
+ /**
115
+ * If set to `true`, TLS/SSL certificate errors are ignored in both attempts: see
116
+ * {@link HttpCrawlerOptions.ignoreTlsErrors} for the HTTP-only one, the browser gets Playwright's
117
+ * `ignoreHTTPSErrors` launch option. Can't be combined with `browserOptions.browserPool`,
118
+ * `browserOptions.remoteBrowser` or `browserOptions.launchContext.useIncognitoPages`, which don't use the launch options.
119
+ *
120
+ * @default false
121
+ */
122
+ ignoreTlsErrors?: boolean;
123
+ /** Options of the HTTP-only attempt, forwarded to its {@link CheerioCrawler}. */
124
+ httpOptions?: Pick<CheerioCrawlerOptions, 'additionalMimeTypes'>;
125
+ /** Options of the browser attempt, forwarded to its {@link PlaywrightCrawler}. */
126
+ browserOptions?: Pick<PlaywrightCrawlerOptions, 'launchContext' | 'headless' | 'browserPool' | 'remoteBrowser' | 'ignoreIframes'>;
102
127
  /**
103
128
  * Timeout for the navigation phase of each attempt, in seconds, shared by the `preNavigationHooks`, the
104
129
  * navigation and the `postNavigationHooks`. Applies to both the HTTP-only and the browser attempt. When not
@@ -1,6 +1,6 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { isDeepStrictEqual } from 'node:util';
3
- import { BasicCrawler, ContextPipeline, ContextPipelineInitializationError, ContextPipelineInterruptedError, navigationDeadlineKey, RequestHandlerError, resolveBaseUrlForEnqueueLinksFiltering, Router, Statistics, } from '@crawlee/basic';
3
+ import { BasicCrawler, ContextPipeline, ContextPipelineCleanupError, ContextPipelineInitializationError, ContextPipelineInterruptedError, navigationDeadlineKey, RequestHandlerError, resolveBaseUrlForEnqueueLinksFiltering, Router, Statistics, } from '@crawlee/basic';
4
4
  import { CrawlingRequest, extractUrlsFromPage } from '@crawlee/browser';
5
5
  import { CheerioCrawler } from '@crawlee/cheerio';
6
6
  import { ResponseWithUrl } from '@crawlee/http-client';
@@ -10,6 +10,86 @@ import { z } from 'zod';
10
10
  import { addTimeoutToPromise } from '@apify/timeout';
11
11
  import { PlaywrightCrawler } from './playwright-crawler.js';
12
12
  import { RenderingTypePredictor, } from './utils/rendering-type-prediction.js';
13
+ /**
14
+ * A failed attempt stops before its cleanups (closing the page) until released, so the error handlers still get an
15
+ * open page, as in `BasicCrawler`.
16
+ */
17
+ class Attempt {
18
+ transaction;
19
+ #failure = Promise.withResolvers();
20
+ #failed = false;
21
+ #cleanupsReleased = Promise.withResolvers();
22
+ #call;
23
+ #context;
24
+ #heldBeforeCleanups = false;
25
+ #releaseDeferred = false;
26
+ constructor(transaction) {
27
+ this.transaction = transaction;
28
+ this.#failure.promise.catch(() => { });
29
+ }
30
+ /** Settles without waiting for a failed run's cleanups. */
31
+ async run(pipeline, context, consumer) {
32
+ this.#context = context;
33
+ this.#call = pipeline.call(context, consumer, async (error) => {
34
+ this.#heldBeforeCleanups = true;
35
+ this.fail(error);
36
+ await this.#cleanupsReleased.promise;
37
+ throw error;
38
+ });
39
+ await Promise.race([this.#call, this.#failure.promise]);
40
+ }
41
+ fail(reason) {
42
+ this.#failed = true;
43
+ this.#failure.reject(reason);
44
+ }
45
+ /** Stops waiting for `handler` once the run fails - a timeout does not stop it. */
46
+ abandonable(handler) {
47
+ return async (context) => {
48
+ // The run may have failed before the handler starts - then it never starts.
49
+ if (this.#failed) {
50
+ return this.#failure.promise;
51
+ }
52
+ return Promise.race([handler(context), this.#failure.promise]);
53
+ };
54
+ }
55
+ /** Idempotent. */
56
+ async release() {
57
+ this.#cleanupsReleased.resolve();
58
+ // Not waited for if still in a middleware or a non-abandonable handler.
59
+ if (this.#heldBeforeCleanups) {
60
+ await this.#call?.catch((error) => {
61
+ if (error instanceof ContextPipelineCleanupError)
62
+ throw error;
63
+ });
64
+ }
65
+ }
66
+ /** Lets the error handlers, which get the outer `context`, use this attempt's page and helpers. */
67
+ exposeToErrorHandlers(context) {
68
+ this.#releaseDeferred = true;
69
+ // Before the attempt's own `registerDeferredCleanup` replaces the outer one below.
70
+ context.registerDeferredCleanup(async () => this.release());
71
+ const descriptors = Object.getOwnPropertyDescriptors(this.#context ?? {});
72
+ for (const key of Reflect.ownKeys(descriptors)) {
73
+ // The attempt-bound helpers (non-configurable, see `#crawlOne`) and the navigation deadline stay here.
74
+ if (descriptors[key].configurable === false || key === navigationDeadlineKey) {
75
+ delete descriptors[key];
76
+ }
77
+ }
78
+ Object.defineProperties(context, descriptors);
79
+ }
80
+ async settle() {
81
+ try {
82
+ if (!this.#releaseDeferred) {
83
+ await this.release();
84
+ }
85
+ }
86
+ finally {
87
+ // Closed even when a cleanup threw - the writes it still holds must never reach storage.
88
+ this.transaction.rollback();
89
+ this.transaction.dispose();
90
+ }
91
+ }
92
+ }
13
93
  const adaptiveStatisticStateSchema = z.object({
14
94
  /** How many requests were handled by the HTTP-only request handler. */
15
95
  httpOnlyRequestHandlerRuns: z.number().default(0),
@@ -89,7 +169,9 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
89
169
  */
90
170
  #shutDown = false;
91
171
  constructor(options = {}) {
92
- const { requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, shouldPropagateError, resultComparator, statistics, requestHandlerTimeoutSecs = 60, errorHandler, failedRequestHandler, preNavigationHooks = [], postNavigationHooks = [], extendContext, transactionalStorage, navigationTimeoutSecs, launchContext, headless, browserPool, remoteBrowser, ...rest } = options;
172
+ const {
173
+ // Not forwarded to the inner crawlers - an ID may only be held by one live crawler.
174
+ id, requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, shouldPropagateError, resultComparator, statistics, requestHandlerTimeoutSecs = 60, errorHandler, failedRequestHandler, preNavigationHooks = [], postNavigationHooks = [], extendContext, transactionalStorage, navigationTimeoutSecs, ignoreTlsErrors = false, httpOptions, browserOptions, ...rest } = options;
93
175
  // The user's value is replaced by `false` in the `super` call below — validate it separately,
94
176
  // wrapped in an object so the error still names the field.
95
177
  parseArgument({ transactionalStorage }, z.object({ transactionalStorage: BasicCrawler.optionsShape.transactionalStorage }), 'AdaptivePlaywrightCrawlerOptions');
@@ -111,8 +193,14 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
111
193
  'attempts. `transactionalStorage: false` is therefore not supported; a write policy ' +
112
194
  'object is accepted and forwarded to the per-attempt transactions.');
113
195
  }
196
+ const { browserPool, remoteBrowser, launchContext } = browserOptions ?? {};
197
+ if (ignoreTlsErrors && (browserPool || remoteBrowser || launchContext?.useIncognitoPages)) {
198
+ throw new Error('AdaptivePlaywrightCrawler: `ignoreTlsErrors` cannot be combined with `browserPool`, `remoteBrowser` ' +
199
+ 'or `launchContext.useIncognitoPages` - configure the browser to ignore TLS errors yourself.');
200
+ }
114
201
  super({
115
202
  ...rest,
203
+ id,
116
204
  errorHandler,
117
205
  failedRequestHandler,
118
206
  requestHandler,
@@ -134,7 +222,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
134
222
  this.#individualRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
135
223
  // `renderingTypeDetectionRatio` only configures the default predictor - an injected one brings its own
136
224
  // detection ratio (and its own state), so the option is ignored in that case.
137
- this.#renderingTypePredictor = OwnedOrInjected.resolve(renderingTypePredictor, () => new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio }));
225
+ this.#renderingTypePredictor = OwnedOrInjected.resolve(renderingTypePredictor, () => new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio, id }));
138
226
  this.#attemptWritePolicy = {
139
227
  requestQueue: 'deferred',
140
228
  ...(typeof transactionalStorage === 'object' ? transactionalStorage : {}),
@@ -166,6 +254,8 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
166
254
  // each hook's overrides at runtime regardless of the static type.
167
255
  const staticCrawler = new CheerioCrawler({
168
256
  ...rest,
257
+ ...httpOptions,
258
+ ignoreTlsErrors,
169
259
  statistics: new Statistics({ persistenceOptions: { enable: false } }),
170
260
  preNavigationHooks,
171
261
  postNavigationHooks,
@@ -174,15 +264,18 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
174
264
  });
175
265
  const browserCrawler = new PlaywrightCrawler({
176
266
  ...rest,
267
+ ...browserOptions,
268
+ ...(ignoreTlsErrors && {
269
+ launchContext: {
270
+ ...launchContext,
271
+ launchOptions: { ...launchContext?.launchOptions, ignoreHTTPSErrors: true },
272
+ },
273
+ }),
177
274
  statistics: new Statistics({ persistenceOptions: { enable: false } }),
178
275
  preNavigationHooks: preNavigationHooks,
179
276
  postNavigationHooks: postNavigationHooks,
180
277
  extendContext,
181
278
  navigationTimeoutSecs,
182
- launchContext,
183
- headless,
184
- browserPool,
185
- remoteBrowser,
186
279
  });
187
280
  this.#staticCrawler = staticCrawler;
188
281
  this.#browserCrawler = browserCrawler;
@@ -239,69 +332,81 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
239
332
  get parseWithCheerio() {
240
333
  throw new Error(errorMessage('parseWithCheerio'));
241
334
  },
335
+ get extractLinks() {
336
+ throw new Error(errorMessage('extractLinks'));
337
+ },
242
338
  get enqueueLinks() {
243
339
  throw new Error(errorMessage('enqueueLinks'));
244
340
  },
245
341
  }));
246
342
  }
247
343
  async #adaptCheerioContext(cheerioContext) {
344
+ const extractLinks = async (options = {}) => extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
248
345
  return {
249
346
  get page() {
250
347
  throw new Error('Page object was used in HTTP-only request handler');
251
348
  },
252
- enqueueLinks: async (options = {}) => {
253
- const urls = extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
254
- return (await this.#enqueueLinks(urls, options, cheerioContext.request));
255
- },
256
- // The HTTP crawler has already consumed the body; hand out a fresh copy, like the browser side does.
257
- // HTML bodies are already decoded to UTF-8, so `arrayBuffer()` may disagree with the original headers.
258
- response: new ResponseWithUrl(cheerioContext.body, cheerioContext.response),
349
+ extractLinks,
350
+ enqueueLinks: async (options = {}) => this.#enqueueLinks(await extractLinks(options), options, cheerioContext.request),
351
+ // `skipNavigation` keeps the inner throwing getter. The body is already consumed (and decoded to UTF-8).
352
+ ...(cheerioContext.request.skipNavigation
353
+ ? {}
354
+ : { response: new ResponseWithUrl(cheerioContext.body, cheerioContext.response) }),
259
355
  };
260
356
  }
261
357
  async #adaptPlaywrightContext(playwrightContext) {
262
- // Capture the original response to avoid infinite recursion when the getter is copied to the context
263
- const originalResponse = playwrightContext.response;
264
- // `headers()` can return repeated headers (e.g. `set-cookie`) joined with `\n`, which `Headers` rejects
265
- const headers = new Headers();
266
- for (const { name, value } of await originalResponse.headersArray()) {
267
- headers.append(name, value);
358
+ // Capture the original response to avoid infinite recursion when the getter is copied to the context.
359
+ // The inner getter throws with `skipNavigation` or when navigation produced no response; it then stays.
360
+ let originalResponse;
361
+ try {
362
+ originalResponse = playwrightContext.response;
268
363
  }
269
- return {
270
- response: new ResponseWithUrl(Uint8Array.from(await originalResponse.body()), {
364
+ catch { }
365
+ let response;
366
+ if (originalResponse) {
367
+ // `headers()` can return repeated headers (e.g. `set-cookie`) joined with `\n`, which `Headers` rejects
368
+ const headers = new Headers();
369
+ for (const { name, value } of await originalResponse.headersArray()) {
370
+ headers.append(name, value);
371
+ }
372
+ // `body()` throws for redirects, `304` cache hits included, and for responses the page navigated away from
373
+ const body = await originalResponse
374
+ .body()
375
+ .catch(async () => Buffer.from(await playwrightContext.page.content()));
376
+ response = new ResponseWithUrl(Uint8Array.from(body), {
271
377
  headers,
272
378
  status: originalResponse.status(),
273
379
  statusText: originalResponse.statusText(),
274
380
  url: originalResponse.url(),
275
- }),
276
- enqueueLinks: async (options = {}, timeoutMs = 5000) => {
277
- // TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
278
- const selector = options.selector ?? 'a';
279
- const locator = playwrightContext.page.locator(selector).first();
280
- // Wait for client-rendered links, but like the HTTP side, enqueue nothing when there are none.
281
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' }).catch((error) => {
282
- if (error.name !== 'TimeoutError')
283
- throw error;
284
- });
285
- const urls = await extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl);
286
- return (await this.#enqueueLinks(urls, options, playwrightContext.request));
287
- },
381
+ });
382
+ }
383
+ const extractLinks = async (options = {}, timeoutMs = 5000) => {
384
+ // TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
385
+ const selector = options.selector ?? 'a';
386
+ const locator = playwrightContext.page.locator(selector).first();
387
+ // Wait for client-rendered links, but like the HTTP side, return nothing when there are none.
388
+ await locator.waitFor({ timeout: timeoutMs, state: 'attached' }).catch((error) => {
389
+ if (error.name !== 'TimeoutError')
390
+ throw error;
391
+ });
392
+ return extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl);
393
+ };
394
+ return {
395
+ ...(response && { response }),
396
+ extractLinks,
397
+ enqueueLinks: async (options = {}, timeoutMs = 5000) => this.#enqueueLinks(await extractLinks(options, timeoutMs), options, playwrightContext.request),
288
398
  };
289
399
  }
290
400
  /**
291
- * Runs one request handler attempt inside its own {@link StorageTransaction}, wrapping the inner
292
- * (static or browser) context pipeline. The transaction is pushed to `transactions` *at creation
293
- * time, before the `try`*, as failed attempts are routine here. The caller owns the outcome and
294
- * disposal, including closing or reverting the {@link ContextModifications}.
401
+ * Runs one request handler attempt inside the attempt's {@link StorageTransaction}, wrapping the inner
402
+ * (static or browser) context pipeline. The caller owns the outcome and settles the attempt, including
403
+ * closing or reverting the {@link ContextModifications}.
295
404
  *
296
405
  * `request` defaults to the context's; a detection rerun passes a copy so it sees the request as it
297
406
  * was before the browser attempt.
298
407
  */
299
- async #crawlOne(renderingType, context, useStateFunction, transactions, request = context.request) {
300
- const transaction = createStorageTransaction({
301
- policy: this.#attemptWritePolicy,
302
- commitTimeoutMillis: this.internalTimeoutMillis,
303
- });
304
- transactions.push(transaction);
408
+ async #crawlOne(renderingType, context, useStateFunction, attempt, request = context.request) {
409
+ const { transaction } = attempt;
305
410
  const logs = [];
306
411
  const contextModifications = {
307
412
  request: new MutationJournal(),
@@ -326,32 +431,13 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
326
431
  for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(attemptBoundContextHelpers))) {
327
432
  Object.defineProperty(subCrawlerContext, key, { ...descriptor, configurable: false });
328
433
  }
329
- // The timeout below does not stop the request handler, and the pipeline closes the page only after the handler
330
- // settles. Racing the handler against this lets a timed-out attempt release its page right away.
331
- const attemptFailed = new AbortController();
332
434
  try {
333
- // Any failure - middleware or handler - ends up in the `ok: false` branch below.
334
- const rethrow = (error) => {
335
- throw error;
336
- };
337
- const abandonableRequestHandler = async (crawlingContext) => {
338
- // The attempt may have failed before the handler starts, and a late abort listener would never fire.
339
- attemptFailed.signal.throwIfAborted();
340
- return Promise.race([
341
- this.requestHandler(crawlingContext),
342
- new Promise((_resolve, reject) => {
343
- attemptFailed.signal.addEventListener('abort', () => reject(attemptFailed.signal.reason), {
344
- once: true,
345
- });
346
- }),
347
- ]);
348
- };
349
435
  const callAdaptiveRequestHandler = async () => {
350
436
  if (renderingType === 'static') {
351
- await this.#staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this), rethrow);
437
+ await attempt.run(this.#staticContextPipeline, subCrawlerContext, this.requestHandler.bind(this));
352
438
  }
353
439
  else if (renderingType === 'clientOnly') {
354
- await this.#browserContextPipeline.call(subCrawlerContext, abandonableRequestHandler, rethrow);
440
+ await attempt.run(this.#browserContextPipeline, subCrawlerContext, attempt.abandonable(this.requestHandler.bind(this)));
355
441
  }
356
442
  };
357
443
  // this crawler overrides `runRequestHandler` and times each rendering-type run itself, so it has
@@ -362,7 +448,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
362
448
  return { ok: true, transaction, contextModifications, logs };
363
449
  }
364
450
  catch (error) {
365
- attemptFailed.abort(error);
451
+ attempt.fail(error);
366
452
  return { ok: false, error, transaction, contextModifications, logs };
367
453
  }
368
454
  }
@@ -372,18 +458,25 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
372
458
  if (!shouldDetectRenderingType) {
373
459
  crawlingContext.log.debug(`Predicted rendering type ${renderingTypePrediction.renderingType} for ${crawlingContext.request.url}`);
374
460
  }
375
- // Every transaction created for this request - up to two, since the static-then-browser
376
- // fall-through and the browser-then-detection pair are mutually exclusive. Disposed in the
377
- // `finally` below, not earlier: the comparators read the journals after `crawlOne` returns.
378
- const transactions = [];
461
+ // Settled only in the `finally` below - the comparators read the journals after `crawlOne` returns.
462
+ const attempts = [];
463
+ const startAttempt = () => {
464
+ const attempt = new Attempt(createStorageTransaction({
465
+ policy: this.#attemptWritePolicy,
466
+ commitTimeoutMillis: this.internalTimeoutMillis,
467
+ }));
468
+ attempts.push(attempt);
469
+ return attempt;
470
+ };
379
471
  try {
380
472
  // A result the `resultChecker` rejected is as good as a detection saying the page needs a browser - but
381
473
  // only once the browser run has succeeded. A thrown error says nothing about rendering.
382
- let httpResultRejected = false;
474
+ let resultCheckerRejectedHttpResult = false;
383
475
  if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
384
476
  crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
385
477
  this.statistics.state.httpOnlyRequestHandlerRuns++;
386
- const plainHTTPRun = await this.#crawlOne('static', crawlingContext, crawlingContext.useState, transactions);
478
+ const httpAttempt = startAttempt();
479
+ const plainHTTPRun = await this.#crawlOne('static', crawlingContext, crawlingContext.useState, httpAttempt);
387
480
  if (plainHTTPRun.ok &&
388
481
  this.#resultChecker(plainHTTPRun.transaction, { request: crawlingContext.request })) {
389
482
  crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
@@ -401,25 +494,29 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
401
494
  if (actualError instanceof ContextPipelineInterruptedError ||
402
495
  (await this.#shouldPropagateError(actualError, crawlingContext))) {
403
496
  this.#keepContextModifications(plainHTTPRun.contextModifications);
497
+ httpAttempt.exposeToErrorHandlers(crawlingContext);
404
498
  throw actualError;
405
499
  }
406
500
  crawlingContext.log.exception(actualError, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
501
+ await httpAttempt.release();
407
502
  }
408
503
  else {
409
504
  crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
410
505
  this.statistics.state.renderingTypeMispredictions++;
411
- httpResultRejected = true;
506
+ resultCheckerRejectedHttpResult = true;
412
507
  }
413
508
  // The browser attempt starts from the request and state as they were before the rejected one.
414
509
  this.#discardContextModifications(plainHTTPRun.contextModifications, crawlingContext);
415
510
  }
416
511
  crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
417
512
  this.statistics.state.browserRequestHandlerRuns++;
418
- const browserRun = await this.#crawlOne('clientOnly', crawlingContext, crawlingContext.useState, transactions);
513
+ const browserAttempt = startAttempt();
514
+ const browserRun = await this.#crawlOne('clientOnly', crawlingContext, crawlingContext.useState, browserAttempt);
419
515
  if (!browserRun.ok) {
420
516
  // A failed browser attempt is handed to the retry logic with its writes - `userData` stashed for the
421
517
  // next attempt must survive.
422
518
  this.#keepContextModifications(browserRun.contextModifications);
519
+ browserAttempt.exposeToErrorHandlers(crawlingContext);
423
520
  throw browserRun.error;
424
521
  }
425
522
  try {
@@ -432,7 +529,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
432
529
  this.#keepContextModifications(browserRun.contextModifications);
433
530
  }
434
531
  // Past the shutdown fence, `teardown()` has already drained - and possibly torn down the predictor.
435
- if (httpResultRejected && !this.#shutDown) {
532
+ if (resultCheckerRejectedHttpResult && !this.#shutDown) {
436
533
  this.#storeRenderingType(crawlingContext.request, 'clientOnly');
437
534
  }
438
535
  if (shouldDetectRenderingType) {
@@ -444,7 +541,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
444
541
  // away with it.
445
542
  const { request: requestJournal, state: stateJournal } = browserRun.contextModifications;
446
543
  let stateCopy;
447
- const plainHTTPRun = await this.#crawlOne('static', crawlingContext, async (defaultValue) => (stateCopy ??= stateJournal.undoOnto(JSON.parse(JSON.stringify(await crawlingContext.useState(defaultValue))))), transactions, requestJournal.undoOnto(CrawlingRequest.fromSchema(JSON.parse(JSON.stringify(crawlingContext.request)))));
544
+ const plainHTTPRun = await this.#crawlOne('static', crawlingContext, async (defaultValue) => (stateCopy ??= stateJournal.undoOnto(JSON.parse(JSON.stringify(await crawlingContext.useState(defaultValue))))), startAttempt(), requestJournal.undoOnto(CrawlingRequest.fromSchema(JSON.parse(JSON.stringify(crawlingContext.request)))));
448
545
  const detectionResult = (() => {
449
546
  if (!plainHTTPRun.ok) {
450
547
  return 'clientOnly';
@@ -469,11 +566,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
469
566
  }
470
567
  }
471
568
  finally {
472
- // A still-open transaction here belongs to a discarded attempt - roll it back, then release.
473
- for (const transaction of transactions) {
474
- transaction.rollback();
475
- transaction.dispose();
476
- }
569
+ await Promise.all(attempts.map(async (attempt) => attempt.settle()));
477
570
  }
478
571
  }
479
572
  #keepContextModifications(modifications) {
@@ -159,13 +159,10 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
159
159
  }>>;
160
160
  }, z.core.$strict>]>>;
161
161
  onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
162
- // @ts-ignore optional peer dependency or compatibility with es2022
163
- httpClient: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/http-client").BaseHttpClient>>;
162
+ httpClient: z.ZodOptional<z.ZodType<Dictionary, unknown, z.core.$ZodTypeInternals<Dictionary, unknown>>>;
164
163
  // @ts-ignore optional peer dependency or compatibility with es2022
165
164
  configuration: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").Configuration>>;
166
165
  storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
167
- // @ts-ignore optional peer dependency or compatibility with es2022
168
- eventManager: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").EventManager>>;
169
166
  logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
170
167
  minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
171
168
  maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
@@ -219,13 +216,10 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
219
216
  }>>;
220
217
  }, z.core.$strict>]>>;
221
218
  onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
222
- // @ts-ignore optional peer dependency or compatibility with es2022
223
- httpClient: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/http-client").BaseHttpClient>>;
219
+ httpClient: z.ZodOptional<z.ZodType<Dictionary, unknown, z.core.$ZodTypeInternals<Dictionary, unknown>>>;
224
220
  // @ts-ignore optional peer dependency or compatibility with es2022
225
221
  configuration: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").Configuration>>;
226
222
  storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
227
- // @ts-ignore optional peer dependency or compatibility with es2022
228
- eventManager: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").EventManager>>;
229
223
  logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
230
224
  minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
231
225
  maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
@@ -257,6 +251,11 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
257
251
  * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
258
252
  * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
259
253
  *
254
+ * Cloudflare serves its challenge pages with a 403 status, which is part of the default `blockedStatusCodes`.
255
+ * Keep it there - the hook runs before the blocked-status check and replaces the response on a solved
256
+ * challenge, so solved requests pass it, while unsolved or undetected challenges keep the 403 and get
257
+ * retried with a fresh session.
258
+ *
260
259
  * **Example usage**
261
260
  * ```ts
262
261
  * import { PlaywrightCrawler, handleCloudflareChallengeHook } from 'crawlee';
@@ -1,4 +1,5 @@
1
- import { BrowserCrawler, RequestState, Router, serviceLocator } from '@crawlee/browser';
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { BrowserCrawler, DownloadStartedError, RequestState, Router, serviceLocator } from '@crawlee/browser';
2
3
  import { assertBrowserPoolNotConfigured, parseArgument, schemas } from '@crawlee/utils/internal';
3
4
  import { z } from 'zod';
4
5
  import { playwrightBrowserPool } from './playwright-browser-pool.js';
@@ -107,7 +108,25 @@ export class PlaywrightCrawler extends BrowserCrawler {
107
108
  return this.buildContextPipeline().compose(this.#enhanceContext.bind(this));
108
109
  }
109
110
  async navigationHandler(crawlingContext, gotoOptions) {
110
- return gotoExtended(crawlingContext.page, crawlingContext.request, gotoOptions);
111
+ const { page } = crawlingContext;
112
+ const { promise: downloadStarted, resolve } = Promise.withResolvers();
113
+ const onDownload = () => resolve();
114
+ page.once('download', onDownload);
115
+ try {
116
+ return await gotoExtended(page, crawlingContext.request, gotoOptions);
117
+ }
118
+ catch (error) {
119
+ // `goto` can reject before the `download` event arrives, and `listDownloads()` would miss it.
120
+ // ponytail: fixed 5 s bound, tie it to the navigation window if downloads start slower than that
121
+ if (error.message?.includes('Download is starting')) {
122
+ await Promise.race([downloadStarted, delay(5_000, undefined, { ref: false })]);
123
+ throw new DownloadStartedError(error.message, { cause: error });
124
+ }
125
+ throw error;
126
+ }
127
+ finally {
128
+ page.off('download', onDownload);
129
+ }
111
130
  }
112
131
  async #enhanceContext(context) {
113
132
  const waitForSelector = async (selector, timeoutMs = 5_000) => {
@@ -159,7 +178,14 @@ export class PlaywrightCrawler extends BrowserCrawler {
159
178
  }),
160
179
  compileScript: (scriptString, ctx) => compileScript(scriptString, ctx),
161
180
  handleCloudflareChallenge: async (options) => {
162
- return handleCloudflareChallenge(context.page, context.request.url, options);
181
+ let response;
182
+ try {
183
+ response = context.response;
184
+ }
185
+ catch {
186
+ // the getter throws before navigation, with `skipNavigation`, and when navigation produced no response
187
+ }
188
+ return handleCloudflareChallenge(context.page, context.request.url, options, response);
163
189
  },
164
190
  };
165
191
  }
@@ -168,6 +194,11 @@ export class PlaywrightCrawler extends BrowserCrawler {
168
194
  * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
169
195
  * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
170
196
  *
197
+ * Cloudflare serves its challenge pages with a 403 status, which is part of the default `blockedStatusCodes`.
198
+ * Keep it there - the hook runs before the blocked-status check and replaces the response on a solved
199
+ * challenge, so solved requests pass it, while unsolved or undetected challenges keep the 403 and get
200
+ * retried with a fresh session.
201
+ *
171
202
  * **Example usage**
172
203
  * ```ts
173
204
  * import { PlaywrightCrawler, handleCloudflareChallengeHook } from 'crawlee';
@@ -319,22 +319,29 @@ export interface HandleCloudflareChallengeOptions {
319
319
  *
320
320
  * On a successfully solved challenge the page is reloaded and the new {@link Response} is returned, so
321
321
  * it can be propagated back to the crawling context via a hook return value (see
322
- * {@link handleCloudflareChallengeHook}).
322
+ * {@link handleCloudflareChallengeHook}). Thanks to that, the 403 status of the challenge page does not
323
+ * need to be removed from `blockedStatusCodes` - a solved challenge replaces the response before the
324
+ * blocked-status check runs, and an unsolved one is retried with a fresh session.
323
325
  *
324
326
  * Works best with camoufox.
325
327
  *
326
328
  * **Example usage**
327
329
  * ```ts
328
330
  * postNavigationHooks: [
329
- * async (context) => ({ response: await context.handleCloudflareChallenge() }),
331
+ * async (context) => {
332
+ * const response = await context.handleCloudflareChallenge();
333
+ * // `{ response: undefined }` would replace the navigation response and skip the blocked-status check
334
+ * return response && { response };
335
+ * },
330
336
  * ],
331
337
  * ```
332
338
  *
333
339
  * @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object
334
340
  * @param url current URL for request identification, only used for logging
335
341
  * @param [options]
342
+ * @param [response] navigation response, used to poll for late-rendered challenge markup when it signals a likely challenge
336
343
  */
337
- export declare function handleCloudflareChallenge(page: Page, url: string, options?: HandleCloudflareChallengeOptions): Promise<Response | undefined>;
344
+ export declare function handleCloudflareChallenge(page: Page, url: string, options?: HandleCloudflareChallengeOptions, response?: Response): Promise<Response | undefined>;
338
345
  export interface PlaywrightContextUtils {
339
346
  /**
340
347
  * Injects a JavaScript file into current `page`.
@@ -535,7 +542,11 @@ export interface PlaywrightContextUtils {
535
542
  * **Example usage**
536
543
  * ```ts
537
544
  * postNavigationHooks: [
538
- * async (context) => ({ response: await context.handleCloudflareChallenge() }),
545
+ * async (context) => {
546
+ * const response = await context.handleCloudflareChallenge();
547
+ * // `{ response: undefined }` would replace the navigation response and skip the blocked-status check
548
+ * return response && { response };
549
+ * },
539
550
  * ],
540
551
  * ```
541
552
  *
@@ -22,7 +22,7 @@ import { createRequire } from 'node:module';
22
22
  import vm from 'node:vm';
23
23
  import { Configuration, KeyValueStore, serviceLocator, SessionError, validators } from '@crawlee/browser';
24
24
  import { sleep } from '@crawlee/utils';
25
- import { expandShadowRoots, parseArgument, schemas } from '@crawlee/utils/internal';
25
+ import { expandShadowRoots, parseArgument, schemas, snapshotPageWithIframes } from '@crawlee/utils/internal';
26
26
  import { z } from 'zod';
27
27
  import { LruCache } from '@apify/datastructures';
28
28
  import { enqueueLinksByClickingElements } from '../enqueue-links/click-elements.js';
@@ -400,35 +400,27 @@ export async function saveSnapshot(page, options = {}) {
400
400
  */
401
401
  export async function parseWithCheerio(page, ignoreShadowRoots = false, ignoreIframes = false) {
402
402
  parseArgument(page, validators.browserPage);
403
- const html = ignoreShadowRoots
404
- ? null
405
- : (await page.evaluate(`(${expandShadowRoots.toString()})(document)`));
406
- const pageContent = html || (await page.content());
403
+ const snapshot = await page.evaluateHandle(`(${snapshotPageWithIframes.toString()})(document, ${ignoreShadowRoots ? 'null' : expandShadowRoots.toString()})`);
404
+ const pageContent = (await (await snapshot.getProperty('html')).jsonValue());
407
405
  // Full cheerio (parse5) import for browser compliant parser
408
406
  const { load } = await import('cheerio');
409
407
  const $ = load(pageContent);
410
408
  if (page.frames().length > 1 && !ignoreIframes) {
411
- const frames = await page.$$('iframe');
412
- const cheerioIframes = $('iframe').toArray();
413
- if (frames.length !== cheerioIframes.length) {
414
- serviceLocator
415
- .getLogger()
416
- .warning(`parseWithCheerio: iframe count mismatch between live DOM (${frames.length}) and page snapshot (${cheerioIframes.length}). Some iframes may not be expanded.`);
417
- }
418
- await Promise.all(frames.map(async (frame, index) => {
409
+ const iframes = await (await snapshot.getProperty('iframes')).getProperties();
410
+ await Promise.all([...iframes].map(async ([id, handle]) => {
419
411
  try {
420
- const iframe = await frame.contentFrame();
421
- if (iframe && cheerioIframes[index]) {
412
+ const iframe = await handle.asElement()?.contentFrame();
413
+ if (iframe) {
422
414
  const getIframeHTML = async () => {
423
415
  try {
424
- return iframe.locator('body').first().innerHTML();
416
+ return await iframe.locator('body').first().innerHTML();
425
417
  }
426
418
  catch {
427
419
  return iframe.content();
428
420
  }
429
421
  };
430
422
  const contents = await getIframeHTML();
431
- $(cheerioIframes[index]).replaceWith(`<div class="crawlee-iframe-replacement">${contents}</div>`);
423
+ $(`iframe[data-crawlee-iframe-id="${id}"]`).replaceWith(`<div class="crawlee-iframe-replacement">${contents}</div>`);
432
424
  }
433
425
  }
434
426
  catch (error) {
@@ -436,6 +428,8 @@ export async function parseWithCheerio(page, ignoreShadowRoots = false, ignoreIf
436
428
  }
437
429
  }));
438
430
  }
431
+ await snapshot.dispose();
432
+ $('[data-crawlee-iframe-id]').removeAttr('data-crawlee-iframe-id');
439
433
  return $;
440
434
  }
441
435
  /**
@@ -447,50 +441,74 @@ export async function parseWithCheerio(page, ignoreShadowRoots = false, ignoreIf
447
441
  *
448
442
  * On a successfully solved challenge the page is reloaded and the new {@link Response} is returned, so
449
443
  * it can be propagated back to the crawling context via a hook return value (see
450
- * {@link handleCloudflareChallengeHook}).
444
+ * {@link handleCloudflareChallengeHook}). Thanks to that, the 403 status of the challenge page does not
445
+ * need to be removed from `blockedStatusCodes` - a solved challenge replaces the response before the
446
+ * blocked-status check runs, and an unsolved one is retried with a fresh session.
451
447
  *
452
448
  * Works best with camoufox.
453
449
  *
454
450
  * **Example usage**
455
451
  * ```ts
456
452
  * postNavigationHooks: [
457
- * async (context) => ({ response: await context.handleCloudflareChallenge() }),
453
+ * async (context) => {
454
+ * const response = await context.handleCloudflareChallenge();
455
+ * // `{ response: undefined }` would replace the navigation response and skip the blocked-status check
456
+ * return response && { response };
457
+ * },
458
458
  * ],
459
459
  * ```
460
460
  *
461
461
  * @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object
462
462
  * @param url current URL for request identification, only used for logging
463
463
  * @param [options]
464
+ * @param [response] navigation response, used to poll for late-rendered challenge markup when it signals a likely challenge
464
465
  */
465
- export async function handleCloudflareChallenge(page, url, options = {}) {
466
- options.isBlockedCallback ??= async () => {
467
- const isBlocked = await page.evaluate(() => {
468
- return document.querySelector('h1')?.textContent?.trim().includes('Sorry, you have been blocked');
466
+ export async function handleCloudflareChallenge(page, url, options = {}, response) {
467
+ // The options object may outlive this call (the pre-wrapped hook reuses one instance for all
468
+ // requests and retries), so the defaults are kept local instead of being memoized on `options` -
469
+ // memoizing them would pin the closed-over `page` of the first call forever.
470
+ const isBlockedCallback = options.isBlockedCallback ??
471
+ (async (p) => {
472
+ const isBlocked = await p.evaluate(() => {
473
+ return document.querySelector('h1')?.textContent?.trim().includes('Sorry, you have been blocked');
474
+ });
475
+ return !!isBlocked;
469
476
  });
470
- return !!isBlocked;
471
- };
472
- options.isChallengeCallback ??= async () => {
473
- return await page.evaluate(async () => {
474
- // Cloudflare keeps reshuffling the wrapper elements between `.footer-inner` and `.ray-id`,
475
- // so only the stable outer classes are matched.
476
- return !!document.querySelector('.footer .footer-inner .ray-id');
477
+ const isChallengeCallback = options.isChallengeCallback ??
478
+ (async (p) => {
479
+ return await p.evaluate(async () => {
480
+ // Cloudflare keeps reshuffling the wrapper elements between `.footer-inner` and `.ray-id`,
481
+ // so only the stable outer classes are matched.
482
+ return !!document.querySelector('.footer .footer-inner .ray-id');
483
+ });
477
484
  });
478
- };
479
485
  const retryBlocked = async () => {
480
- const isBlocked = await options.isBlockedCallback(page).catch(() => false);
486
+ const isBlocked = await isBlockedCallback(page).catch(() => false);
481
487
  if (isBlocked) {
482
488
  throw new SessionError(`Blocked by Cloudflare when processing ${url}`);
483
489
  }
484
490
  };
485
491
  // check if we ended up on the CF challenge page
486
492
  const isChallenge = async () => {
487
- return options.isChallengeCallback(page).catch(async () => {
493
+ return isChallengeCallback(page).catch(async () => {
488
494
  // the challenge page navigates itself, which destroys the context of an in-flight check
489
495
  await page.waitForLoadState('domcontentloaded').catch(() => { });
490
- return options.isChallengeCallback(page).catch(() => false);
496
+ return isChallengeCallback(page).catch(() => false);
491
497
  });
492
498
  };
493
- if (!(await isChallenge())) {
499
+ // The challenge markup can finish rendering only after the `load` event, so when the response signals
500
+ // a likely challenge, poll for it instead of checking once. A 403 alone is not enough - it must come
501
+ // from Cloudflare (the `cf-ray` header), so 403s served by other stacks keep failing fast.
502
+ const headers = response?.headers() ?? {};
503
+ const likelyChallenge = headers['cf-mitigated'] === 'challenge' || (response?.status() === 403 && 'cf-ray' in headers);
504
+ let detected = await isChallenge();
505
+ for (let i = 0; !detected && likelyChallenge && i < 10; i++) {
506
+ // a hard-blocked page never turns into a challenge, so fail fast instead of finishing the poll
507
+ await retryBlocked();
508
+ await sleep(500);
509
+ detected = await isChallenge();
510
+ }
511
+ if (!detected) {
494
512
  await retryBlocked();
495
513
  return undefined;
496
514
  }
@@ -4,6 +4,12 @@ export type RenderingType = 'clientOnly' | 'static';
4
4
  export interface RenderingTypePredictorOptions {
5
5
  /** A number between 0 and 1 that determines the desired ratio of rendering type detections */
6
6
  detectionRatio: number;
7
+ /**
8
+ * Unique identifier for this predictor instance. Used to generate a unique persistence key when
9
+ * `persistenceOptions.persistStateKey` is not provided. If not provided, an auto-incrementing ID is used.
10
+ * Explicit IDs share one namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`.
11
+ */
12
+ id?: string | number;
7
13
  persistenceOptions?: Partial<RecoverableStatePersistenceOptions>;
8
14
  }
9
15
  /**
@@ -36,7 +42,9 @@ export interface IRenderingTypePredictor {
36
42
  */
37
43
  export declare class RenderingTypePredictor implements IRenderingTypePredictor {
38
44
  #private;
39
- constructor({ detectionRatio, persistenceOptions }: RenderingTypePredictorOptions);
45
+ /** The identifier used in the default persistence key. */
46
+ readonly id: string;
47
+ constructor({ detectionRatio, id, persistenceOptions }: RenderingTypePredictorOptions);
40
48
  /**
41
49
  * Initialize the predictor by restoring persisted state.
42
50
  */
@@ -64,16 +64,20 @@ const stateCodec = z.codec(persistedState, predictorState, {
64
64
  * Stores rendering type information for previously crawled URLs and predicts the rendering type for URLs that have yet to be crawled and recommends when rendering type detection should be performed.
65
65
  */
66
66
  export class RenderingTypePredictor {
67
+ static #nextId = 0;
68
+ /** The identifier used in the default persistence key. */
69
+ id;
67
70
  #detectionRatio;
68
71
  #state;
69
- constructor({ detectionRatio, persistenceOptions }) {
72
+ constructor({ detectionRatio, id, persistenceOptions }) {
73
+ this.id = id != null ? String(id) : String(RenderingTypePredictor.#nextId++);
70
74
  this.#detectionRatio = detectionRatio;
71
75
  this.#state = new RecoverableState({
72
76
  defaultState: () => stateCodec.decode({}),
73
77
  // The codec validates in the decode direction, so it is a Standard Schema as-is; encoding needs a call.
74
78
  deserialize: stateCodec,
75
79
  serialize: (state) => stateCodec.encode(state),
76
- persistStateKey: 'rendering-type-predictor-state',
80
+ persistStateKey: `CRAWLEE_RENDERING_TYPE_PREDICTOR_STATE_${this.id}`,
77
81
  persistenceEnabled: true,
78
82
  ...persistenceOptions,
79
83
  });
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@crawlee/playwright",
3
- "version": "4.0.0-rc.2",
3
+ "version": "4.0.0",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
- "node": ">=22.13.0"
6
+ "node": ">=22.15.0"
7
7
  },
8
8
  "type": "module",
9
9
  "exports": {
@@ -48,18 +48,18 @@
48
48
  },
49
49
  "dependencies": {
50
50
  "@apify/datastructures": "^3.0.1",
51
- "@apify/timeout": "^1.0.1",
52
- "@crawlee/basic": "4.0.0-rc.2",
53
- "@crawlee/browser": "4.0.0-rc.2",
54
- "@crawlee/browser-pool": "4.0.0-rc.2",
55
- "@crawlee/cheerio": "4.0.0-rc.2",
56
- "@crawlee/core": "4.0.0-rc.2",
57
- "@crawlee/http-client": "4.0.0-rc.2",
58
- "@crawlee/types": "4.0.0-rc.2",
59
- "@crawlee/utils": "4.0.0-rc.2",
51
+ "@apify/timeout": "^1.1.0",
52
+ "@crawlee/basic": "4.0.0",
53
+ "@crawlee/browser": "4.0.0",
54
+ "@crawlee/browser-pool": "4.0.0",
55
+ "@crawlee/cheerio": "4.0.0",
56
+ "@crawlee/core": "4.0.0",
57
+ "@crawlee/http-client": "4.0.0",
58
+ "@crawlee/types": "4.0.0",
59
+ "@crawlee/utils": "4.0.0",
60
60
  "cheerio": "^1.2.0",
61
61
  "domhandler": "^6.0.1",
62
- "jquery": "^3.7.1",
62
+ "jquery": "^3.8.0",
63
63
  "ml-logistic-regression": "^2.0.0",
64
64
  "ml-matrix": "^6.15.1",
65
65
  "string-comparison": "^1.3.0",
@@ -81,5 +81,5 @@
81
81
  }
82
82
  }
83
83
  },
84
- "gitHead": "a9b623229cd7d1bff5063fc82940efebaea47165"
84
+ "gitHead": "4c53f840dba3644b987eb61b57577e68b502f33e"
85
85
  }