@crawlee/playwright 4.0.0-beta.32 → 4.0.0-beta.321

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 (32) hide show
  1. package/README.md +15 -15
  2. package/index.d.ts +4 -3
  3. package/index.js +2 -2
  4. package/internals/adaptive-playwright-crawler.d.ts +144 -80
  5. package/internals/adaptive-playwright-crawler.js +501 -309
  6. package/internals/enqueue-links/click-elements.d.ts +21 -58
  7. package/internals/enqueue-links/click-elements.js +48 -61
  8. package/internals/playwright-browser-pool.d.ts +55 -0
  9. package/internals/playwright-browser-pool.js +34 -0
  10. package/internals/playwright-crawler.d.ts +183 -171
  11. package/internals/playwright-crawler.js +122 -77
  12. package/internals/playwright-launcher.d.ts +30 -20
  13. package/internals/playwright-launcher.js +24 -18
  14. package/internals/utils/playwright-utils.d.ts +73 -54
  15. package/internals/utils/playwright-utils.js +138 -140
  16. package/internals/utils/rendering-type-prediction.d.ts +34 -14
  17. package/internals/utils/rendering-type-prediction.js +87 -35
  18. package/package.json +20 -23
  19. package/index.d.ts.map +0 -1
  20. package/index.js.map +0 -1
  21. package/internals/adaptive-playwright-crawler.d.ts.map +0 -1
  22. package/internals/adaptive-playwright-crawler.js.map +0 -1
  23. package/internals/enqueue-links/click-elements.d.ts.map +0 -1
  24. package/internals/enqueue-links/click-elements.js.map +0 -1
  25. package/internals/playwright-crawler.d.ts.map +0 -1
  26. package/internals/playwright-crawler.js.map +0 -1
  27. package/internals/playwright-launcher.d.ts.map +0 -1
  28. package/internals/playwright-launcher.js.map +0 -1
  29. package/internals/utils/playwright-utils.d.ts.map +0 -1
  30. package/internals/utils/playwright-utils.js.map +0 -1
  31. package/internals/utils/rendering-type-prediction.d.ts.map +0 -1
  32. package/internals/utils/rendering-type-prediction.js.map +0 -1
@@ -1,47 +1,31 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
1
2
  import { isDeepStrictEqual } from 'node:util';
2
- import { BasicCrawler } from '@crawlee/basic';
3
- import { extractUrlsFromPage } from '@crawlee/browser';
3
+ import { BasicCrawler, ContextPipeline, ContextPipelineInitializationError, ContextPipelineInterruptedError, navigationDeadlineKey, RequestHandlerError, resolveBaseUrlForEnqueueLinksFiltering, Router, Statistics, } from '@crawlee/basic';
4
+ import { CrawlingRequest, extractUrlsFromPage } from '@crawlee/browser';
4
5
  import { CheerioCrawler } from '@crawlee/cheerio';
5
- import { RequestHandlerError, RequestHandlerResult, resolveBaseUrlForEnqueueLinksFiltering, Router, serviceLocator, Statistics, withCheckedStorageAccess, } from '@crawlee/core';
6
- import { extractUrlsFromCheerio } from '@crawlee/utils';
6
+ import { ResponseWithUrl } from '@crawlee/http-client';
7
+ import { createStorageTransaction, EnqueueStrategy, OwnedOrInjected } from '@crawlee/core';
8
+ import { extractUrlsFromCheerio, MutationJournal, parseArgument } from '@crawlee/utils/internal';
9
+ import { z } from 'zod';
7
10
  import { addTimeoutToPromise } from '@apify/timeout';
8
11
  import { PlaywrightCrawler } from './playwright-crawler.js';
9
- import { RenderingTypePredictor } from './utils/rendering-type-prediction.js';
10
- class AdaptivePlaywrightCrawlerStatistics extends Statistics {
11
- state = null; // this needs to be assigned for a valid override, but the initialization is done by a reset() call from the parent constructor
12
- constructor(options = {}) {
13
- super(options);
14
- this.reset();
15
- }
16
- reset() {
17
- super.reset();
18
- this.state.httpOnlyRequestHandlerRuns = 0;
19
- this.state.browserRequestHandlerRuns = 0;
20
- this.state.renderingTypeMispredictions = 0;
21
- }
22
- async _maybeLoadStatistics() {
23
- await super._maybeLoadStatistics();
24
- const savedState = await this.keyValueStore?.getValue(this.persistStateKey);
25
- if (!savedState) {
26
- return;
27
- }
28
- this.state.httpOnlyRequestHandlerRuns = savedState.httpOnlyRequestHandlerRuns;
29
- this.state.browserRequestHandlerRuns = savedState.browserRequestHandlerRuns;
30
- this.state.renderingTypeMispredictions = savedState.renderingTypeMispredictions;
31
- }
32
- trackHttpOnlyRequestHandlerRun() {
33
- this.state.httpOnlyRequestHandlerRuns ??= 0;
34
- this.state.httpOnlyRequestHandlerRuns += 1;
35
- }
36
- trackBrowserRequestHandlerRun() {
37
- this.state.browserRequestHandlerRuns ??= 0;
38
- this.state.browserRequestHandlerRuns += 1;
39
- }
40
- trackRenderingTypeMisprediction() {
41
- this.state.renderingTypeMispredictions ??= 0;
42
- this.state.renderingTypeMispredictions += 1;
43
- }
44
- }
12
+ import { RenderingTypePredictor, } from './utils/rendering-type-prediction.js';
13
+ const adaptiveStatisticStateSchema = z.object({
14
+ /** How many requests were handled by the HTTP-only request handler. */
15
+ httpOnlyRequestHandlerRuns: z.number().default(0),
16
+ /** How many requests were handled in a browser. */
17
+ browserRequestHandlerRuns: z.number().default(0),
18
+ /** How many times the HTTP-only handler produced a result the `resultChecker` rejected. */
19
+ renderingTypeMispredictions: z.number().default(0),
20
+ });
21
+ /**
22
+ * The {@link AdaptivePlaywrightCrawlerStatisticState} fields as a {@link Statistics} state extension, defaults
23
+ * and all. A {@link Statistics} instance to be injected into an {@link AdaptivePlaywrightCrawler} has to carry
24
+ * them - `deserialize.extend()` your own fields onto this one and pass the result as `stateExtension`.
25
+ */
26
+ export const adaptivePlaywrightCrawlerStatisticState = {
27
+ deserialize: adaptiveStatisticStateSchema,
28
+ };
45
29
  const proxyLogMethods = [
46
30
  'error',
47
31
  'exception',
@@ -60,9 +44,9 @@ const proxyLogMethods = [
60
44
  * ```javascript
61
45
  * const crawler = new AdaptivePlaywrightCrawler({
62
46
  * renderingTypeDetectionRatio: 0.1,
63
- * async requestHandler({ querySelector, pushData, enqueueLinks, request, log }) {
47
+ * async requestHandler({ querySelectorAll, pushData, enqueueLinks, request, log }) {
64
48
  * // This function is called to extract data from a single web page
65
- * const $prices = await querySelector('span.price')
49
+ * const $prices = await querySelectorAll('span.price')
66
50
  *
67
51
  * await pushData({
68
52
  * url: request.url,
@@ -78,40 +62,93 @@ const proxyLogMethods = [
78
62
  * 'http://www.example.com/page-2',
79
63
  * ]);
80
64
  * ```
81
- *
82
- * @experimental
83
65
  */
84
66
  export class AdaptivePlaywrightCrawler extends BasicCrawler {
85
- renderingTypePredictor;
86
- resultChecker;
87
- resultComparator;
88
- preventDirectStorageAccess;
89
- staticContextPipeline;
90
- browserContextPipeline;
91
- individualRequestHandlerTimeoutMillis;
92
- resultObjects = new WeakMap();
93
- teardownHooks = [];
67
+ #renderingTypePredictor;
68
+ #resultChecker;
69
+ #shouldPropagateError;
70
+ #resultComparator;
71
+ #staticContextPipeline;
72
+ #browserContextPipeline;
73
+ #individualRequestHandlerTimeoutMillis;
74
+ /**
75
+ * The write policy of the per-attempt transactions. Defaults the request queue to `deferred`:
76
+ * a discarded attempt's enqueues must never reach the queue.
77
+ */
78
+ #attemptWritePolicy;
79
+ /** Owns the browser pool this crawler's runs use, so its per-run resources are released with ours. */
80
+ #browserCrawler;
81
+ /** Nothing of its state is per-run, but it owns a session pool that outlives one. */
82
+ #staticCrawler;
83
+ /**
84
+ * In-flight rendering type detections, plus the pending results of an asynchronous `storeResult`.
85
+ */
86
+ #activeDetections = new Set();
87
+ /**
88
+ * Set once `teardown()` starts, so that requests still in the pool stop opening new detections.
89
+ */
90
+ #shutDown = false;
94
91
  constructor(options = {}) {
95
- const { requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, resultComparator, statisticsOptions, preventDirectStorageAccess = true, requestHandlerTimeoutSecs = 60, errorHandler, failedRequestHandler, preNavigationHooks, postNavigationHooks, extendContext, contextPipelineBuilder, ...rest } = 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;
93
+ // The user's value is replaced by `false` in the `super` call below — validate it separately,
94
+ // wrapped in an object so the error still names the field.
95
+ parseArgument({ transactionalStorage }, z.object({ transactionalStorage: BasicCrawler.optionsShape.transactionalStorage }), 'AdaptivePlaywrightCrawlerOptions');
96
+ // The extra fields are only tracked if the injected instance was built with them - the types enforce that,
97
+ // but plain JS callers would otherwise silently increment `undefined` into a sticky `NaN`. Extend
98
+ // `adaptivePlaywrightCrawlerStatisticState` to satisfy this.
99
+ if (statistics !== undefined) {
100
+ parseArgument(statistics.state, z.object({
101
+ httpOnlyRequestHandlerRuns: z.number(),
102
+ browserRequestHandlerRuns: z.number(),
103
+ renderingTypeMispredictions: z.number(),
104
+ }), 'statistics.state');
105
+ }
106
+ // Per-attempt buffering is load-bearing here: the handler runs up to twice per request and the
107
+ // losing attempt's writes must be discardable.
108
+ if (transactionalStorage === false) {
109
+ throw new Error('AdaptivePlaywrightCrawler requires transactional storage - it runs the request handler ' +
110
+ 'multiple times per request and must be able to discard the storage writes of losing ' +
111
+ 'attempts. `transactionalStorage: false` is therefore not supported; a write policy ' +
112
+ 'object is accepted and forwarded to the per-attempt transactions.');
113
+ }
96
114
  super({
97
115
  ...rest,
98
116
  errorHandler,
99
117
  failedRequestHandler,
100
118
  requestHandler,
101
- contextPipelineBuilder: contextPipelineBuilder ?? (() => this.buildContextPipeline()),
119
+ requestHandlerTimeoutSecs,
120
+ // The base would build a `Statistics` without the adaptive fields, so provide a default that has them.
121
+ // The cast covers a `StatisticStateExtension` that adds further fields - those can only come from an
122
+ // injected instance, in which case this default is never built.
123
+ statistics: statistics ??
124
+ new Statistics({
125
+ logMessage: `${AdaptivePlaywrightCrawler.name} request statistics:`,
126
+ stateExtension: adaptivePlaywrightCrawlerStatisticState,
127
+ }),
128
+ contextPipelineBuilder: () => this.#buildContextPipeline(),
129
+ // The base crawler must not wrap requests in a transaction of its own - this crawler opens
130
+ // one per request handler attempt in `crawlOne` instead, forwarding the write policy of the
131
+ // user-facing option (validated above) to those.
132
+ transactionalStorage: false,
102
133
  });
103
- this.individualRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
104
- this.renderingTypePredictor =
105
- renderingTypePredictor ?? new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio });
106
- this.resultChecker = resultChecker ?? (() => true);
134
+ this.#individualRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
135
+ // `renderingTypeDetectionRatio` only configures the default predictor - an injected one brings its own
136
+ // detection ratio (and its own state), so the option is ignored in that case.
137
+ this.#renderingTypePredictor = OwnedOrInjected.resolve(renderingTypePredictor, () => new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio }));
138
+ this.#attemptWritePolicy = {
139
+ requestQueue: 'deferred',
140
+ ...(typeof transactionalStorage === 'object' ? transactionalStorage : {}),
141
+ };
142
+ this.#resultChecker = resultChecker ?? (() => true);
143
+ this.#shouldPropagateError = shouldPropagateError ?? (() => false);
107
144
  if (resultComparator !== undefined) {
108
- this.resultComparator = resultComparator;
145
+ this.#resultComparator = resultComparator;
109
146
  }
110
147
  else if (resultChecker !== undefined) {
111
- this.resultComparator = (resultA, resultB) => this.resultChecker(resultA) && this.resultChecker(resultB);
148
+ this.#resultComparator = (resultA, resultB, context) => this.#resultChecker(resultA, context) && this.#resultChecker(resultB, context);
112
149
  }
113
150
  else {
114
- this.resultComparator = (resultA, resultB) => {
151
+ this.#resultComparator = (resultA, resultB) => {
115
152
  return (resultA.datasetItems.length === resultB.datasetItems.length &&
116
153
  resultA.datasetItems.every((itemA, i) => {
117
154
  const itemB = resultB.datasetItems[i];
@@ -119,330 +156,485 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
119
156
  }));
120
157
  };
121
158
  }
159
+ // `extendContext` is forwarded to the inner crawlers, which run it *before* navigation (see
160
+ // `BasicCrawler`), keeping the behavior consistent with the non-adaptive crawlers: the
161
+ // extension is visible to the pre/post-navigation hooks and the request handler, but cannot
162
+ // access navigation-dependent members (`page`, `response`, `$`, ...).
163
+ //
164
+ // The adaptive hooks target a subset context (`AdaptiveHookContext`); the casts to the inner
165
+ // crawlers' `PlaywrightHook` type relax that nominal difference. The `ContextPipeline` merges
166
+ // each hook's overrides at runtime regardless of the static type.
122
167
  const staticCrawler = new CheerioCrawler({
123
168
  ...rest,
124
- useSessionPool: false,
125
- statisticsOptions: {
126
- persistenceOptions: { enable: false },
127
- },
128
- preNavigationHooks: [
129
- async (context) => {
130
- for (const hook of preNavigationHooks ?? []) {
131
- await hook(context, undefined);
132
- }
133
- },
134
- ],
135
- postNavigationHooks: [
136
- async (context) => {
137
- for (const hook of postNavigationHooks ?? []) {
138
- await hook(context, undefined);
139
- }
140
- },
141
- ],
169
+ statistics: new Statistics({ persistenceOptions: { enable: false } }),
170
+ preNavigationHooks,
171
+ postNavigationHooks,
172
+ extendContext,
173
+ navigationTimeoutSecs,
142
174
  });
143
175
  const browserCrawler = new PlaywrightCrawler({
144
176
  ...rest,
145
- useSessionPool: false,
146
- statisticsOptions: {
147
- persistenceOptions: { enable: false },
148
- },
149
- preNavigationHooks: [
150
- async (context, gotoOptions) => {
151
- for (const hook of preNavigationHooks ?? []) {
152
- await hook(context, gotoOptions);
177
+ statistics: new Statistics({ persistenceOptions: { enable: false } }),
178
+ preNavigationHooks: preNavigationHooks,
179
+ postNavigationHooks: postNavigationHooks,
180
+ extendContext,
181
+ navigationTimeoutSecs,
182
+ launchContext,
183
+ headless,
184
+ browserPool,
185
+ remoteBrowser,
186
+ });
187
+ this.#staticCrawler = staticCrawler;
188
+ this.#browserCrawler = browserCrawler;
189
+ // Each attempt needs its own deferred cleanups, and they must share the attempt's cleanup stack: resources the
190
+ // pipeline defers releasing (the page) have to outlive the user's cleanups, which may still use them.
191
+ const deferredCleanup = ContextPipeline.create().compose((_context, onCleanup) => ({
192
+ registerDeferredCleanup: (cleanup) => {
193
+ onCleanup(async () => {
194
+ try {
195
+ await cleanup();
153
196
  }
154
- },
155
- ],
156
- postNavigationHooks: [
157
- async (context, gotoOptions) => {
158
- for (const hook of postNavigationHooks ?? []) {
159
- await hook(context, gotoOptions);
197
+ catch (error) {
198
+ this.log.debug('Error in deferred cleanup', { error });
160
199
  }
161
- },
162
- ],
163
- });
164
- this.teardownHooks.push(browserCrawler.teardown.bind(browserCrawler));
165
- this.staticContextPipeline = staticCrawler.contextPipeline
166
- .compose({
167
- action: this.adaptCheerioContext.bind(this),
168
- })
169
- .compose({
170
- action: async (context) => extendContext ? await extendContext(context) : context,
171
- });
172
- this.browserContextPipeline = browserCrawler.contextPipeline
173
- .compose({
174
- action: this.adaptPlaywrightContext.bind(this),
175
- })
176
- .compose({
177
- action: async (context) => extendContext ? await extendContext(context) : context,
178
- });
179
- this.stats = new AdaptivePlaywrightCrawlerStatistics({
180
- logMessage: `${this.log.getOptions().prefix} request statistics:`,
181
- ...statisticsOptions,
182
- });
183
- this.preventDirectStorageAccess = preventDirectStorageAccess;
200
+ });
201
+ },
202
+ }));
203
+ this.#staticContextPipeline = deferredCleanup
204
+ .chain(staticCrawler.contextPipeline)
205
+ .compose(this.#adaptCheerioContext.bind(this));
206
+ this.#browserContextPipeline = deferredCleanup
207
+ .chain(browserCrawler.contextPipeline)
208
+ .compose(this.#adaptPlaywrightContext.bind(this));
184
209
  }
185
- async _init() {
186
- await this.renderingTypePredictor.initialize();
187
- return await super._init();
210
+ async init() {
211
+ // A crawler can be run again after a teardown.
212
+ this.#shutDown = false;
213
+ // Only the predictor we built ourselves is ours to initialize - an injected one is borrowed, so its
214
+ // lifecycle (including restoring persisted state) stays with whoever created it.
215
+ await this.#renderingTypePredictor.ifOwned((predictor) => predictor.initialize());
216
+ return await super.init();
188
217
  }
189
- buildContextPipeline() {
218
+ #buildContextPipeline() {
190
219
  const errorMessage = (prop) => `The \`${prop}\` property is not available on the outer context pipeline of AdaptivePlaywrightCrawler - it is provided by the inner (static/browser) pipelines`;
191
- return super.buildContextPipeline().compose({
192
- action: async ({ request }) => ({
193
- get request() {
194
- return request;
195
- },
196
- get response() {
197
- throw new Error(errorMessage('response'));
198
- },
199
- get page() {
200
- throw new Error(errorMessage('page'));
201
- },
202
- get querySelector() {
203
- throw new Error(errorMessage('querySelector'));
204
- },
205
- get waitForSelector() {
206
- throw new Error(errorMessage('waitForSelector'));
207
- },
208
- get parseWithCheerio() {
209
- throw new Error(errorMessage('parseWithCheerio'));
210
- },
211
- }),
212
- });
220
+ return ContextPipeline.create().compose(async ({ request }) => ({
221
+ get request() {
222
+ return request;
223
+ },
224
+ get response() {
225
+ throw new Error(errorMessage('response'));
226
+ },
227
+ get page() {
228
+ throw new Error(errorMessage('page'));
229
+ },
230
+ get querySelectorAll() {
231
+ throw new Error(errorMessage('querySelectorAll'));
232
+ },
233
+ get querySelectorOne() {
234
+ throw new Error(errorMessage('querySelectorOne'));
235
+ },
236
+ get waitForSelector() {
237
+ throw new Error(errorMessage('waitForSelector'));
238
+ },
239
+ get parseWithCheerio() {
240
+ throw new Error(errorMessage('parseWithCheerio'));
241
+ },
242
+ get enqueueLinks() {
243
+ throw new Error(errorMessage('enqueueLinks'));
244
+ },
245
+ }));
213
246
  }
214
- async adaptCheerioContext(cheerioContext) {
215
- // Capture the original response to avoid infinite recursion when the getter is copied to the context
216
- const result = this.resultObjects.get(cheerioContext);
217
- if (result === undefined) {
218
- throw new Error('Logical error - `this.resultObjects` does not contain the result object');
219
- }
247
+ async #adaptCheerioContext(cheerioContext) {
220
248
  return {
221
249
  get page() {
222
250
  throw new Error('Page object was used in HTTP-only request handler');
223
251
  },
224
- async querySelector(selector) {
225
- return cheerioContext.$(selector);
226
- },
227
252
  enqueueLinks: async (options = {}) => {
228
- const urls = options.urls ??
229
- extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
230
- return (await this.enqueueLinks({ ...options, urls }, cheerioContext.request, result));
253
+ const urls = extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
254
+ return (await this.#enqueueLinks(urls, options, cheerioContext.request));
231
255
  },
232
- response: cheerioContext.response,
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),
233
259
  };
234
260
  }
235
- async adaptPlaywrightContext(playwrightContext) {
261
+ async #adaptPlaywrightContext(playwrightContext) {
262
+ // Capture the original response to avoid infinite recursion when the getter is copied to the context
236
263
  const originalResponse = playwrightContext.response;
237
- const result = this.resultObjects.get(playwrightContext);
238
- if (result === undefined) {
239
- throw new Error('Logical error - `this.resultObjects` does not contain the result object');
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);
240
268
  }
241
269
  return {
242
- response: new Response(Uint8Array.from(await originalResponse.body()), {
243
- headers: originalResponse.headers(),
270
+ response: new ResponseWithUrl(Uint8Array.from(await originalResponse.body()), {
271
+ headers,
244
272
  status: originalResponse.status(),
245
273
  statusText: originalResponse.statusText(),
274
+ url: originalResponse.url(),
246
275
  }),
247
- async querySelector(selector, timeoutMs = 5000) {
248
- const locator = playwrightContext.page.locator(selector).first();
249
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
250
- const $ = await playwrightContext.parseWithCheerio();
251
- return $(selector);
252
- },
253
276
  enqueueLinks: async (options = {}, timeoutMs = 5000) => {
254
277
  // TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
255
- let urls;
256
- if (options.urls === undefined) {
257
- const selector = options.selector ?? 'a';
258
- const locator = playwrightContext.page.locator(selector).first();
259
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
260
- urls =
261
- options.urls ??
262
- (await extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl));
263
- }
264
- else {
265
- urls = options.urls;
266
- }
267
- return (await this.enqueueLinks({ ...options, urls }, playwrightContext.request, result));
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));
268
287
  },
269
288
  };
270
289
  }
271
- async crawlOne(renderingType, context, useStateFunction) {
272
- const result = new RequestHandlerResult(serviceLocator.getConfiguration(), AdaptivePlaywrightCrawler.CRAWLEE_STATE_KEY);
290
+ /**
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}.
295
+ *
296
+ * `request` defaults to the context's; a detection rerun passes a copy so it sees the request as it
297
+ * was before the browser attempt.
298
+ */
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);
273
305
  const logs = [];
274
- const deferredCleanup = [];
275
- const resultBoundContextHelpers = {
276
- addRequests: result.addRequests,
277
- pushData: result.pushData,
278
- useState: this.allowStorageAccess(useStateFunction),
279
- getKeyValueStore: this.allowStorageAccess(result.getKeyValueStore),
280
- log: this.createLogProxy(context.log, logs),
281
- registerDeferredCleanup: (cleanup) => deferredCleanup.push(cleanup),
306
+ const contextModifications = {
307
+ request: new MutationJournal(),
308
+ state: new MutationJournal(),
282
309
  };
283
310
  const subCrawlerContext = Object.defineProperties({}, Object.getOwnPropertyDescriptors(context));
284
- // Mark result-bound helpers as non-configurable so they survive the sub-crawler context pipeline
285
- // (which would otherwise override them with the sub-crawler's own versions, losing the result binding).
286
- for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(resultBoundContextHelpers))) {
311
+ const attemptBoundContextHelpers = {
312
+ request: contextModifications.request.track(request),
313
+ useState: async (defaultValue) => contextModifications.state.track(await useStateFunction(defaultValue)),
314
+ log: this.#createLogProxy(context.log, logs),
315
+ // The sub-crawler pipeline keeps this attempt's navigation deadline on `subCrawlerContext`, but the
316
+ // outer `extendTimeout` only pushes the deadline it finds on `context`, so push this one as well.
317
+ extendTimeout: (secs) => {
318
+ context.extendTimeout(secs);
319
+ if (subCrawlerContext[navigationDeadlineKey] !== undefined) {
320
+ subCrawlerContext[navigationDeadlineKey] += secs * 1000;
321
+ }
322
+ },
323
+ };
324
+ // Mark attempt-bound helpers as non-configurable so they survive the sub-crawler context pipeline
325
+ // (which would otherwise override them with the sub-crawler's own versions, losing the binding).
326
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(attemptBoundContextHelpers))) {
287
327
  Object.defineProperty(subCrawlerContext, key, { ...descriptor, configurable: false });
288
328
  }
289
- this.resultObjects.set(subCrawlerContext, result);
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();
290
332
  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
+ };
291
349
  const callAdaptiveRequestHandler = async () => {
292
350
  if (renderingType === 'static') {
293
- await this.staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this));
351
+ await this.#staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this), rethrow);
294
352
  }
295
353
  else if (renderingType === 'clientOnly') {
296
- await this.browserContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this));
354
+ await this.#browserContextPipeline.call(subCrawlerContext, abandonableRequestHandler, rethrow);
297
355
  }
298
356
  };
299
- await addTimeoutToPromise(async () => withCheckedStorageAccess(() => {
300
- if (this.preventDirectStorageAccess) {
301
- throw new Error('Directly accessing storage in a request handler is not allowed in AdaptivePlaywrightCrawler');
302
- }
303
- }, callAdaptiveRequestHandler), this.individualRequestHandlerTimeoutMillis, 'Request handler timed out');
304
- return { result, ok: true, logs };
357
+ // this crawler overrides `runRequestHandler` and times each rendering-type run itself, so it has
358
+ // to resolve any per-route override too - otherwise routes would be silently ignored here
359
+ const routeTimeoutSecs = this.requestHandler.getTimeoutSecs?.(context.request.label);
360
+ const timeoutMillis = routeTimeoutSecs === undefined ? this.#individualRequestHandlerTimeoutMillis : routeTimeoutSecs * 1000;
361
+ await addTimeoutToPromise(async () => transaction.run(callAdaptiveRequestHandler), timeoutMillis, 'Request handler timed out');
362
+ return { ok: true, transaction, contextModifications, logs };
305
363
  }
306
364
  catch (error) {
307
- return { error, ok: false, logs };
308
- }
309
- finally {
310
- await Promise.all(deferredCleanup.map((cleanup) => cleanup()));
365
+ attemptFailed.abort(error);
366
+ return { ok: false, error, transaction, contextModifications, logs };
311
367
  }
312
368
  }
313
369
  async runRequestHandler(crawlingContext) {
314
- const renderingTypePrediction = this.renderingTypePredictor.predict(crawlingContext.request);
315
- const shouldDetectRenderingType = Math.random() < renderingTypePrediction.detectionProbabilityRecommendation;
370
+ const renderingTypePrediction = await this.#renderingTypePredictor.value.predict(crawlingContext.request);
371
+ const shouldDetectRenderingType = !this.#shutDown && Math.random() < renderingTypePrediction.detectionProbabilityRecommendation;
316
372
  if (!shouldDetectRenderingType) {
317
373
  crawlingContext.log.debug(`Predicted rendering type ${renderingTypePrediction.renderingType} for ${crawlingContext.request.url}`);
318
374
  }
319
- if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
320
- crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
321
- this.stats.trackHttpOnlyRequestHandlerRun();
322
- const plainHTTPRun = await this.crawlOne('static', crawlingContext, crawlingContext.useState);
323
- if (plainHTTPRun.ok && this.resultChecker(plainHTTPRun.result)) {
324
- crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
325
- plainHTTPRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
326
- await this.commitResult(crawlingContext, plainHTTPRun.result);
327
- return;
328
- }
329
- // Execution will "fall through" and try running the request handler in a browser
330
- if (!plainHTTPRun.ok) {
331
- const actualError = plainHTTPRun.error instanceof RequestHandlerError
332
- ? plainHTTPRun.error.cause
333
- : plainHTTPRun.error;
334
- crawlingContext.log.exception(actualError, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
335
- }
336
- else {
337
- crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
338
- this.stats.trackRenderingTypeMisprediction();
339
- }
340
- }
341
- crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
342
- this.stats.trackBrowserRequestHandlerRun();
343
- // Run the request handler in a browser. The copy of the crawler state is kept so that we can perform
344
- // a rendering type detection if necessary. Without this measure, the HTTP request handler would run
345
- // under different conditions, which could change its behavior. Changes done to the crawler state by
346
- // the HTTP request handler will not be committed to the actual storage.
347
- const stateTracker = {
348
- stateCopy: null,
349
- async getLiveState(defaultValue = {}) {
350
- const state = await crawlingContext.useState(defaultValue);
351
- if (this.stateCopy === null) {
352
- this.stateCopy = JSON.parse(JSON.stringify(state));
353
- }
354
- return state;
355
- },
356
- async getStateCopy(defaultValue = {}) {
357
- if (this.stateCopy === null) {
358
- return defaultValue;
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 = [];
379
+ try {
380
+ // A result the `resultChecker` rejected is as good as a detection saying the page needs a browser - but
381
+ // only once the browser run has succeeded. A thrown error says nothing about rendering.
382
+ let httpResultRejected = false;
383
+ if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
384
+ crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
385
+ this.statistics.state.httpOnlyRequestHandlerRuns++;
386
+ const plainHTTPRun = await this.#crawlOne('static', crawlingContext, crawlingContext.useState, transactions);
387
+ if (plainHTTPRun.ok &&
388
+ this.#resultChecker(plainHTTPRun.transaction, { request: crawlingContext.request })) {
389
+ crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
390
+ plainHTTPRun.logs.forEach(([log, method, ...args]) => log[method](...args));
391
+ this.#keepContextModifications(plainHTTPRun.contextModifications);
392
+ await plainHTTPRun.transaction.commit();
393
+ return;
359
394
  }
360
- return this.stateCopy;
361
- },
362
- };
363
- const browserRun = await this.crawlOne('clientOnly', crawlingContext, stateTracker.getLiveState.bind(stateTracker));
364
- if (!browserRun.ok) {
365
- throw browserRun.error;
366
- }
367
- await this.commitResult(crawlingContext, browserRun.result);
368
- if (shouldDetectRenderingType) {
369
- crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
370
- const plainHTTPRun = await this.crawlOne('static', crawlingContext, stateTracker.getStateCopy.bind(stateTracker));
371
- const detectionResult = (() => {
395
+ // Execution will "fall through" and try running the request handler in a browser
372
396
  if (!plainHTTPRun.ok) {
373
- return 'clientOnly';
374
- }
375
- const comparisonResult = this.resultComparator(plainHTTPRun.result, browserRun.result);
376
- if (comparisonResult === true || comparisonResult === 'equal') {
377
- return 'static';
397
+ const actualError = plainHTTPRun.error instanceof RequestHandlerError ||
398
+ plainHTTPRun.error instanceof ContextPipelineInitializationError
399
+ ? plainHTTPRun.error.cause
400
+ : plainHTTPRun.error;
401
+ if (actualError instanceof ContextPipelineInterruptedError ||
402
+ (await this.#shouldPropagateError(actualError, crawlingContext))) {
403
+ this.#keepContextModifications(plainHTTPRun.contextModifications);
404
+ throw actualError;
405
+ }
406
+ crawlingContext.log.exception(actualError, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
378
407
  }
379
- if (comparisonResult === false || comparisonResult === 'different') {
380
- return 'clientOnly';
408
+ else {
409
+ crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
410
+ this.statistics.state.renderingTypeMispredictions++;
411
+ httpResultRejected = true;
381
412
  }
382
- return undefined;
383
- })();
384
- crawlingContext.log.debug(`Detected rendering type ${detectionResult} for ${crawlingContext.request.url}`);
385
- if (detectionResult !== undefined) {
386
- this.renderingTypePredictor.storeResult(crawlingContext.request, detectionResult);
413
+ // The browser attempt starts from the request and state as they were before the rejected one.
414
+ this.#discardContextModifications(plainHTTPRun.contextModifications, crawlingContext);
415
+ }
416
+ crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
417
+ this.statistics.state.browserRequestHandlerRuns++;
418
+ const browserRun = await this.#crawlOne('clientOnly', crawlingContext, crawlingContext.useState, transactions);
419
+ if (!browserRun.ok) {
420
+ // A failed browser attempt is handed to the retry logic with its writes - `userData` stashed for the
421
+ // next attempt must survive.
422
+ this.#keepContextModifications(browserRun.contextModifications);
423
+ throw browserRun.error;
424
+ }
425
+ try {
426
+ browserRun.logs.forEach(([log, method, ...args]) => log[method](...args));
427
+ // The `afterStorageCommit` callbacks belong to this attempt, so the detection rerun undoes their
428
+ // writes too - the journals stay open until they have run.
429
+ await browserRun.transaction.commit();
430
+ }
431
+ finally {
432
+ this.#keepContextModifications(browserRun.contextModifications);
433
+ }
434
+ // Past the shutdown fence, `teardown()` has already drained - and possibly torn down the predictor.
435
+ if (httpResultRejected && !this.#shutDown) {
436
+ this.#storeRenderingType(crawlingContext.request, 'clientOnly');
437
+ }
438
+ if (shouldDetectRenderingType) {
439
+ const detectionPromise = (async () => {
440
+ crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
441
+ // The detection attempt's transaction is never committed - its writes exist only for the
442
+ // result comparison. It runs on copies of the request and the crawler state with the browser
443
+ // attempt's writes undone, so both attempts start from the same conditions, and the copies go
444
+ // away with it.
445
+ const { request: requestJournal, state: stateJournal } = browserRun.contextModifications;
446
+ 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)))));
448
+ const detectionResult = (() => {
449
+ if (!plainHTTPRun.ok) {
450
+ return 'clientOnly';
451
+ }
452
+ const comparisonResult = this.#resultComparator(plainHTTPRun.transaction, browserRun.transaction, {
453
+ request: crawlingContext.request,
454
+ });
455
+ if (comparisonResult === true || comparisonResult === 'equal') {
456
+ return 'static';
457
+ }
458
+ if (comparisonResult === false || comparisonResult === 'different') {
459
+ return 'clientOnly';
460
+ }
461
+ return undefined;
462
+ })();
463
+ crawlingContext.log.debug(`Detected rendering type ${detectionResult} for ${crawlingContext.request.url}`);
464
+ if (detectionResult !== undefined) {
465
+ this.#storeRenderingType(crawlingContext.request, detectionResult);
466
+ }
467
+ })();
468
+ await this.#trackDetection(detectionPromise);
469
+ }
470
+ }
471
+ 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();
387
476
  }
388
477
  }
389
478
  }
390
- async commitResult(crawlingContext, { calls, keyValueStoreChanges }) {
391
- await Promise.all([
392
- ...calls.pushData.map(async (params) => crawlingContext.pushData(...params)),
393
- ...calls.addRequests.map(async (params) => crawlingContext.addRequests(...params)),
394
- ...Object.entries(keyValueStoreChanges).map(async ([storeIdOrName, changes]) => {
395
- const store = await crawlingContext.getKeyValueStore(storeIdOrName);
396
- await Promise.all(Object.entries(changes).map(async ([key, { changedValue, options }]) => store.setValue(key, changedValue, options)));
397
- }),
398
- ]);
479
+ #keepContextModifications(modifications) {
480
+ modifications.request.close();
481
+ modifications.state.close();
399
482
  }
400
- allowStorageAccess(func) {
401
- return async (...args) => withCheckedStorageAccess(() => { }, async () => func(...args));
483
+ #discardContextModifications(modifications, { request, log }) {
484
+ // Nothing else writes to a request while its handler runs, so a conflict means a write that bypassed
485
+ // the context (e.g. through a stashed reference) - it stays, but it is not what the retry logic expects.
486
+ modifications.request.revert({
487
+ onConflict: (key) => log.warning(`Request ${request.url}: '${String(key)}' was modified outside the request handler`),
488
+ });
489
+ // The state is shared with concurrent handlers; a conflict is one of them having written the same
490
+ // property meanwhile. Their value wins, and this attempt's write stays with it.
491
+ modifications.state.revert({
492
+ onConflict: (key) => log.debug(`Crawler state '${String(key)}' was changed concurrently; keeping the newer value`),
493
+ });
402
494
  }
403
- async enqueueLinks(options, request, result) {
495
+ #storeRenderingType(request, renderingType) {
496
+ // Deliberately not awaited: a predictor that persists asynchronously gets to keep batching its writes,
497
+ // and `drainRenderingDetections()` catches whatever is still pending.
498
+ const stored = this.#renderingTypePredictor.value.storeResult(request, renderingType);
499
+ if (stored !== undefined) {
500
+ // Nothing downstream awaits this, so a failed write would otherwise be silent.
501
+ void this.#trackDetection(Promise.resolve(stored).catch((error) => this.log.exception(error, `Failed to store the rendering type detection result for ${request.url}`)));
502
+ }
503
+ }
504
+ async #enqueueLinks(urls, options, request) {
404
505
  const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
405
506
  enqueueStrategy: options?.strategy,
406
507
  finalRequestUrl: request.loadedUrl,
407
508
  originalRequestUrl: request.url,
408
509
  userProvidedBaseUrl: options?.baseUrl,
409
510
  });
410
- const addRequestsBatched = async (requests) => {
411
- await result.addRequests(requests);
412
- return {
413
- addedRequests: requests.map(({ uniqueKey, id }) => ({
414
- uniqueKey,
415
- requestId: id ?? '',
416
- wasAlreadyPresent: false,
417
- wasAlreadyHandled: false,
418
- })),
419
- waitForAllRequestsToBeAdded: Promise.resolve([]),
420
- };
421
- };
422
- // We need to use a mock request queue implementation, in order to add the requests into our result object
423
- const mockRequestQueue = { addRequestsBatched };
424
- return await this.enqueueLinksWithCrawlDepth({ ...options, baseUrl }, request, mockRequestQueue);
511
+ const requestsWithDepth = this.addCrawlDepthRequestGenerator(urls, request.crawlDepth + 1);
512
+ // The per-attempt transaction buffers these (the queue policy defaults to `deferred` here),
513
+ // so a discarded attempt's enqueues never reach the queue.
514
+ return await this.addRequests(requestsWithDepth, {
515
+ ...options,
516
+ baseUrl,
517
+ strategy: options.strategy ?? EnqueueStrategy.SameHostname,
518
+ });
425
519
  }
426
- createLogProxy(log, logs) {
520
+ #createLogProxy(log, logs) {
427
521
  return new Proxy(log, {
428
- get(target, propertyName, receiver) {
522
+ get(target, propertyName) {
429
523
  if (proxyLogMethods.includes(propertyName)) {
430
524
  return (...args) => {
431
525
  logs.push([target, propertyName, ...args]);
432
526
  };
433
527
  }
434
- return Reflect.get(target, propertyName, receiver);
528
+ const value = Reflect.get(target, propertyName, target);
529
+ // Bind non-intercepted methods to the target instance so private #-fields
530
+ // (e.g. BaseCrawleeLogger.#options, #warningsLogged) do not throw TypeError at runtime.
531
+ if (typeof value === 'function') {
532
+ return value.bind(target);
533
+ }
534
+ return value;
435
535
  },
436
536
  });
437
537
  }
538
+ #trackDetection(promise) {
539
+ this.#activeDetections.add(promise);
540
+ // Not `finally()`: the promise it derives would reject on its own and go unhandled. A rejection here
541
+ // belongs to whoever awaits the original, or to `allSettled` in the drain.
542
+ void promise.catch(() => { }).then(() => this.#activeDetections.delete(promise));
543
+ return promise;
544
+ }
545
+ /**
546
+ * Number of rendering type detections that have not settled yet, including results the predictor is
547
+ * still persisting.
548
+ */
549
+ get inFlightRenderingTypeDetectionCount() {
550
+ return this.#activeDetections.size;
551
+ }
552
+ /**
553
+ * Waits for in-flight rendering type detections to settle, bounded by `timeoutMillis` (defaults to the
554
+ * internal timeout).
555
+ */
556
+ async drainRenderingDetections({ timeoutMillis } = {}) {
557
+ if (this.#activeDetections.size === 0) {
558
+ return;
559
+ }
560
+ const drained = (async () => {
561
+ while (this.#activeDetections.size > 0) {
562
+ await Promise.allSettled(Array.from(this.#activeDetections));
563
+ }
564
+ })();
565
+ const millis = timeoutMillis ?? this.internalTimeoutMillis;
566
+ // A caller opting out of the bound would otherwise get an immediate spurious timeout - `setTimeout`
567
+ // clamps a non-finite delay to 1ms.
568
+ if (!Number.isFinite(millis)) {
569
+ await drained;
570
+ return;
571
+ }
572
+ const abortTimer = new AbortController();
573
+ try {
574
+ const outcome = await Promise.race([
575
+ drained.then(() => 'drained'),
576
+ delay(millis, 'timedOut', { signal: abortTimer.signal }).catch(() => 'aborted'),
577
+ ]);
578
+ if (outcome === 'timedOut') {
579
+ this.log.warning(`Timed out after ${millis / 1e3} seconds waiting for ${this.#activeDetections.size} rendering type detection(s) to settle - their results may be lost.`);
580
+ }
581
+ }
582
+ finally {
583
+ abortTimer.abort();
584
+ }
585
+ }
586
+ /**
587
+ * Stops the crawler immediately, but not before rendering type detections already under way (and results
588
+ * the predictor is still persisting) have settled - see
589
+ * {@link AdaptivePlaywrightCrawler.drainRenderingDetections|`drainRenderingDetections()`}. Requests
590
+ * that are still running are not waited for, unlike {@link BasicCrawler.stop|`stop()`}.
591
+ */
438
592
  async teardown() {
593
+ // Called from outside `run()` - under `keepAlive`, say - the pool keeps dispatching until
594
+ // `super.teardown()` aborts it, and a request starting during the drain would open a detection the
595
+ // drain has already passed. Closing that first makes the drain a fence.
596
+ this.#shutDown = true;
597
+ await this.drainRenderingDetections();
439
598
  await super.teardown();
440
- for (const hook of this.teardownHooks) {
441
- await hook();
442
- }
599
+ // Mirrors the owned-only `initialize()` in `init()` - without this, the predictor we built keeps its
600
+ // PERSIST_STATE listener registered after the crawl and never gets a final write.
601
+ await this.#renderingTypePredictor.ifOwned((predictor) => predictor.teardown());
602
+ await this.#browserCrawler.teardown();
443
603
  }
604
+ async destroy() {
605
+ await super.destroy();
606
+ await this.#staticCrawler.destroy();
607
+ await this.#browserCrawler.destroy();
608
+ }
609
+ }
610
+ export function createAdaptivePlaywrightRouter(routesOrSchemas) {
611
+ return Router.create(routesOrSchemas);
444
612
  }
445
- export function createAdaptivePlaywrightRouter(routes) {
446
- return Router.create(routes);
613
+ /**
614
+ * An opt-in {@link AdaptivePlaywrightCrawlerOptions.resultComparator|`resultComparator`} that considers two
615
+ * request handler results equal only if *all* of their observable effects match - the pushed dataset items, the
616
+ * enqueued requests, and the key-value store changes. This is stricter than the default comparator, which only
617
+ * compares dataset items.
618
+ *
619
+ * **Beware:** enqueued URLs are compared exactly. The same page rendered in a browser and via plain HTTP often
620
+ * yields links that differ only in tracking query parameters, for example:
621
+ * - `https://sdk.apify.com/docs/guides/getting-started`
622
+ * - `https://sdk.apify.com/docs/guides/getting-started?__hsfp=1136113150&__hssc=7591405.1.173549427712`
623
+ *
624
+ * Such links are treated as *different*, which will make the crawler favor browser rendering for those pages.
625
+ *
626
+ * **Example usage:**
627
+ * ```ts
628
+ * const crawler = new AdaptivePlaywrightCrawler({
629
+ * resultComparator: fullResultComparator,
630
+ * async requestHandler({ pushData, enqueueLinks }) {
631
+ * // ...
632
+ * },
633
+ * });
634
+ * ```
635
+ */
636
+ export function fullResultComparator(resultA, resultB) {
637
+ return (isDeepStrictEqual(resultA.datasetItems, resultB.datasetItems) &&
638
+ isDeepStrictEqual(resultA.enqueuedUrls, resultB.enqueuedUrls) &&
639
+ isDeepStrictEqual(resultA.keyValueStoreChanges, resultB.keyValueStoreChanges));
447
640
  }
448
- //# sourceMappingURL=adaptive-playwright-crawler.js.map