@crawlee/playwright 4.0.0-beta.9 → 4.0.0-beta.90

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 (31) hide show
  1. package/README.md +17 -13
  2. package/index.d.ts +1 -2
  3. package/index.js +0 -1
  4. package/internals/adaptive-playwright-crawler.d.ts +117 -63
  5. package/internals/adaptive-playwright-crawler.js +354 -214
  6. package/internals/enqueue-links/click-elements.d.ts +32 -14
  7. package/internals/enqueue-links/click-elements.js +57 -25
  8. package/internals/playwright-crawler.d.ts +104 -83
  9. package/internals/playwright-crawler.js +85 -41
  10. package/internals/playwright-launcher.d.ts +6 -5
  11. package/internals/playwright-launcher.js +10 -11
  12. package/internals/utils/playwright-utils.d.ts +56 -19
  13. package/internals/utils/playwright-utils.js +99 -86
  14. package/internals/utils/rendering-type-prediction.d.ts +27 -12
  15. package/internals/utils/rendering-type-prediction.js +67 -26
  16. package/package.json +16 -11
  17. package/index.d.ts.map +0 -1
  18. package/index.js.map +0 -1
  19. package/internals/adaptive-playwright-crawler.d.ts.map +0 -1
  20. package/internals/adaptive-playwright-crawler.js.map +0 -1
  21. package/internals/enqueue-links/click-elements.d.ts.map +0 -1
  22. package/internals/enqueue-links/click-elements.js.map +0 -1
  23. package/internals/playwright-crawler.d.ts.map +0 -1
  24. package/internals/playwright-crawler.js.map +0 -1
  25. package/internals/playwright-launcher.d.ts.map +0 -1
  26. package/internals/playwright-launcher.js.map +0 -1
  27. package/internals/utils/playwright-utils.d.ts.map +0 -1
  28. package/internals/utils/playwright-utils.js.map +0 -1
  29. package/internals/utils/rendering-type-prediction.d.ts.map +0 -1
  30. package/internals/utils/rendering-type-prediction.js.map +0 -1
  31. package/tsconfig.build.tsbuildinfo +0 -1
@@ -1,11 +1,12 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { BasicCrawler } from '@crawlee/basic';
1
3
  import { extractUrlsFromPage } from '@crawlee/browser';
2
- import { Configuration, RequestHandlerResult, Router, Statistics, withCheckedStorageAccess } from '@crawlee/core';
4
+ import { CheerioCrawler } from '@crawlee/cheerio';
5
+ import { OwnedOrInjected, RequestHandlerError, RequestHandlerResult, resolveBaseUrlForEnqueueLinksFiltering, Router, serviceLocator, Statistics, withCheckedStorageAccess, } from '@crawlee/core';
3
6
  import { extractUrlsFromCheerio } from '@crawlee/utils';
4
- import { load } from 'cheerio';
5
- import isEqual from 'lodash.isequal';
6
7
  import { addTimeoutToPromise } from '@apify/timeout';
7
8
  import { PlaywrightCrawler } from './playwright-crawler.js';
8
- import { RenderingTypePredictor } from './utils/rendering-type-prediction.js';
9
+ import { RenderingTypePredictor, } from './utils/rendering-type-prediction.js';
9
10
  class AdaptivePlaywrightCrawlerStatistics extends Statistics {
10
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
11
12
  constructor(options = {}) {
@@ -18,8 +19,8 @@ class AdaptivePlaywrightCrawlerStatistics extends Statistics {
18
19
  this.state.browserRequestHandlerRuns = 0;
19
20
  this.state.renderingTypeMispredictions = 0;
20
21
  }
21
- async _maybeLoadStatistics() {
22
- await super._maybeLoadStatistics();
22
+ async maybeLoadStatistics() {
23
+ await super.maybeLoadStatistics();
23
24
  const savedState = await this.keyValueStore?.getValue(this.persistStateKey);
24
25
  if (!savedState) {
25
26
  return;
@@ -80,27 +81,33 @@ const proxyLogMethods = [
80
81
  *
81
82
  * @experimental
82
83
  */
83
- export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
84
- config;
85
- adaptiveRequestHandler;
84
+ export class AdaptivePlaywrightCrawler extends BasicCrawler {
86
85
  renderingTypePredictor;
87
86
  resultChecker;
87
+ shouldPropagateError;
88
88
  resultComparator;
89
89
  preventDirectStorageAccess;
90
- /**
91
- * Default {@link Router} instance that will be used if we don't specify any {@link AdaptivePlaywrightCrawlerOptions.requestHandler|`requestHandler`}.
92
- * See {@link Router.addHandler|`router.addHandler()`} and {@link Router.addDefaultHandler|`router.addDefaultHandler()`}.
93
- */
94
- // @ts-ignore
95
- router = Router.create();
96
- constructor(options = {}, config = Configuration.getGlobalConfig()) {
97
- const { requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, resultComparator, statisticsOptions, preventDirectStorageAccess = true, ...rest } = options;
98
- super(rest, config);
99
- this.config = config;
100
- this.adaptiveRequestHandler = requestHandler ?? this.router;
101
- this.renderingTypePredictor =
102
- renderingTypePredictor ?? new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio });
90
+ staticContextPipeline;
91
+ browserContextPipeline;
92
+ individualRequestHandlerTimeoutMillis;
93
+ resultObjects = new WeakMap();
94
+ inFlightRenderingTypeDetections = 0;
95
+ teardownHooks = [];
96
+ constructor(options = {}) {
97
+ const { requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, shouldPropagateError, resultComparator, statisticsOptions, preventDirectStorageAccess = true, requestHandlerTimeoutSecs = 60, errorHandler, failedRequestHandler, preNavigationHooks = [], postNavigationHooks = [], extendContext, contextPipelineBuilder, ...rest } = options;
98
+ super({
99
+ ...rest,
100
+ errorHandler,
101
+ failedRequestHandler,
102
+ requestHandler,
103
+ contextPipelineBuilder: contextPipelineBuilder ?? (() => this.buildContextPipeline()),
104
+ });
105
+ this.individualRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
106
+ // `renderingTypeDetectionRatio` only configures the default predictor - an injected one brings its own
107
+ // detection ratio (and its own state), so the option is ignored in that case.
108
+ this.renderingTypePredictor = OwnedOrInjected.resolve(renderingTypePredictor, () => new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio }));
103
109
  this.resultChecker = resultChecker ?? (() => true);
110
+ this.shouldPropagateError = shouldPropagateError ?? (() => false);
104
111
  if (resultComparator !== undefined) {
105
112
  this.resultComparator = resultComparator;
106
113
  }
@@ -112,75 +119,288 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
112
119
  return (resultA.datasetItems.length === resultB.datasetItems.length &&
113
120
  resultA.datasetItems.every((itemA, i) => {
114
121
  const itemB = resultB.datasetItems[i];
115
- return isEqual(itemA, itemB);
122
+ return isDeepStrictEqual(itemA, itemB);
116
123
  }));
117
124
  };
118
125
  }
126
+ // `extendContext` is forwarded to the inner crawlers, which run it *before* navigation (see
127
+ // `BasicCrawler`), keeping the behavior consistent with the non-adaptive crawlers: the
128
+ // extension is visible to the pre/post-navigation hooks and the request handler, but cannot
129
+ // access navigation-dependent members (`page`, `response`, `$`, ...).
130
+ //
131
+ // The adaptive hooks target a subset context (`AdaptiveHookContext`); the casts to the inner
132
+ // crawlers' `PlaywrightHook` type relax that nominal difference. The `ContextPipeline` merges
133
+ // each hook's overrides at runtime regardless of the static type.
134
+ const staticCrawler = new CheerioCrawler({
135
+ ...rest,
136
+ statisticsOptions: {
137
+ persistenceOptions: { enable: false },
138
+ },
139
+ preNavigationHooks,
140
+ postNavigationHooks,
141
+ extendContext,
142
+ });
143
+ const browserCrawler = new PlaywrightCrawler({
144
+ ...rest,
145
+ statisticsOptions: {
146
+ persistenceOptions: { enable: false },
147
+ },
148
+ preNavigationHooks: preNavigationHooks,
149
+ postNavigationHooks: postNavigationHooks,
150
+ extendContext,
151
+ });
152
+ this.teardownHooks.push(browserCrawler.teardown.bind(browserCrawler));
153
+ this.staticContextPipeline = staticCrawler.contextPipeline.compose({
154
+ action: this.adaptCheerioContext.bind(this),
155
+ });
156
+ this.browserContextPipeline = browserCrawler.contextPipeline.compose({
157
+ action: this.adaptPlaywrightContext.bind(this),
158
+ });
119
159
  this.stats = new AdaptivePlaywrightCrawlerStatistics({
120
160
  logMessage: `${this.log.getOptions().prefix} request statistics:`,
121
- config,
122
161
  ...statisticsOptions,
123
162
  });
124
163
  this.preventDirectStorageAccess = preventDirectStorageAccess;
125
164
  }
126
- async _runRequestHandler(crawlingContext) {
127
- const renderingTypePrediction = this.renderingTypePredictor.predict(crawlingContext.request);
165
+ async _init() {
166
+ // Only the predictor we built ourselves is ours to initialize - an injected one is borrowed, so its
167
+ // lifecycle (including restoring persisted state) stays with whoever created it.
168
+ await this.renderingTypePredictor.ifOwned((predictor) => predictor.initialize());
169
+ return await super._init();
170
+ }
171
+ buildContextPipeline() {
172
+ 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`;
173
+ return super.buildContextPipeline().compose({
174
+ action: async ({ request }) => ({
175
+ get request() {
176
+ return request;
177
+ },
178
+ get response() {
179
+ throw new Error(errorMessage('response'));
180
+ },
181
+ get page() {
182
+ throw new Error(errorMessage('page'));
183
+ },
184
+ get querySelector() {
185
+ throw new Error(errorMessage('querySelector'));
186
+ },
187
+ get querySelectorAll() {
188
+ throw new Error(errorMessage('querySelectorAll'));
189
+ },
190
+ get waitForSelector() {
191
+ throw new Error(errorMessage('waitForSelector'));
192
+ },
193
+ get parseWithCheerio() {
194
+ throw new Error(errorMessage('parseWithCheerio'));
195
+ },
196
+ }),
197
+ });
198
+ }
199
+ async adaptCheerioContext(cheerioContext) {
200
+ // Capture the original response to avoid infinite recursion when the getter is copied to the context
201
+ const result = this.resultObjects.get(cheerioContext);
202
+ if (result === undefined) {
203
+ throw new Error('Logical error - `this.resultObjects` does not contain the result object');
204
+ }
205
+ return {
206
+ get page() {
207
+ throw new Error('Page object was used in HTTP-only request handler');
208
+ },
209
+ async querySelector(selector) {
210
+ return cheerioContext.$(selector).first();
211
+ },
212
+ async querySelectorAll(selector) {
213
+ return cheerioContext.$(selector);
214
+ },
215
+ enqueueLinks: async (options = {}) => {
216
+ const urls = options.urls ??
217
+ extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
218
+ return (await this.enqueueLinks({ ...options, urls }, cheerioContext.request, result));
219
+ },
220
+ response: cheerioContext.response,
221
+ };
222
+ }
223
+ async adaptPlaywrightContext(playwrightContext) {
224
+ const originalResponse = playwrightContext.response;
225
+ const result = this.resultObjects.get(playwrightContext);
226
+ if (result === undefined) {
227
+ throw new Error('Logical error - `this.resultObjects` does not contain the result object');
228
+ }
229
+ return {
230
+ response: new Response(Uint8Array.from(await originalResponse.body()), {
231
+ headers: originalResponse.headers(),
232
+ status: originalResponse.status(),
233
+ statusText: originalResponse.statusText(),
234
+ }),
235
+ async querySelector(selector, timeoutMs = 5000) {
236
+ const locator = playwrightContext.page.locator(selector).first();
237
+ await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
238
+ const $ = await playwrightContext.parseWithCheerio();
239
+ return $(selector).first();
240
+ },
241
+ async querySelectorAll(selector, timeoutMs = 5000) {
242
+ const locator = playwrightContext.page.locator(selector).first();
243
+ await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
244
+ const $ = await playwrightContext.parseWithCheerio();
245
+ return $(selector);
246
+ },
247
+ enqueueLinks: async (options = {}, timeoutMs = 5000) => {
248
+ // TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
249
+ let urls;
250
+ if (options.urls === undefined) {
251
+ const selector = options.selector ?? 'a';
252
+ const locator = playwrightContext.page.locator(selector).first();
253
+ await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
254
+ urls =
255
+ options.urls ??
256
+ (await extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl));
257
+ }
258
+ else {
259
+ urls = options.urls;
260
+ }
261
+ return (await this.enqueueLinks({ ...options, urls }, playwrightContext.request, result));
262
+ },
263
+ };
264
+ }
265
+ async crawlOne(renderingType, context, useStateFunction) {
266
+ const result = new RequestHandlerResult(serviceLocator.getConfiguration(), AdaptivePlaywrightCrawler.CRAWLEE_STATE_KEY);
267
+ const logs = [];
268
+ const deferredCleanup = [];
269
+ const resultBoundContextHelpers = {
270
+ addRequests: result.addRequests,
271
+ pushData: result.pushData,
272
+ useState: this.allowStorageAccess(useStateFunction),
273
+ getKeyValueStore: this.allowStorageAccess(result.getKeyValueStore),
274
+ log: this.createLogProxy(context.log, logs),
275
+ registerDeferredCleanup: (cleanup) => deferredCleanup.push(cleanup),
276
+ };
277
+ const subCrawlerContext = Object.defineProperties({}, Object.getOwnPropertyDescriptors(context));
278
+ // Mark result-bound helpers as non-configurable so they survive the sub-crawler context pipeline
279
+ // (which would otherwise override them with the sub-crawler's own versions, losing the result binding).
280
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(resultBoundContextHelpers))) {
281
+ Object.defineProperty(subCrawlerContext, key, { ...descriptor, configurable: false });
282
+ }
283
+ this.resultObjects.set(subCrawlerContext, result);
284
+ try {
285
+ const callAdaptiveRequestHandler = async () => {
286
+ if (renderingType === 'static') {
287
+ await this.staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this));
288
+ }
289
+ else if (renderingType === 'clientOnly') {
290
+ await this.browserContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this));
291
+ }
292
+ };
293
+ await addTimeoutToPromise(async () => withCheckedStorageAccess(() => {
294
+ if (this.preventDirectStorageAccess) {
295
+ throw new Error('Directly accessing storage in a request handler is not allowed in AdaptivePlaywrightCrawler');
296
+ }
297
+ }, callAdaptiveRequestHandler), this.individualRequestHandlerTimeoutMillis, 'Request handler timed out');
298
+ return { result, ok: true, logs };
299
+ }
300
+ catch (error) {
301
+ return { error, ok: false, logs };
302
+ }
303
+ finally {
304
+ await Promise.all(deferredCleanup.map((cleanup) => cleanup()));
305
+ }
306
+ }
307
+ async runRequestHandler(crawlingContext) {
308
+ const renderingTypePrediction = this.renderingTypePredictor.value.predict(crawlingContext.request);
128
309
  const shouldDetectRenderingType = Math.random() < renderingTypePrediction.detectionProbabilityRecommendation;
129
310
  if (!shouldDetectRenderingType) {
130
311
  crawlingContext.log.debug(`Predicted rendering type ${renderingTypePrediction.renderingType} for ${crawlingContext.request.url}`);
131
312
  }
132
- if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
133
- crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
134
- this.stats.trackHttpOnlyRequestHandlerRun();
135
- const plainHTTPRun = await this.runRequestHandlerWithPlainHTTP(crawlingContext);
136
- if (plainHTTPRun.ok && this.resultChecker(plainHTTPRun.result)) {
137
- crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
138
- plainHTTPRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
139
- await this.commitResult(crawlingContext, plainHTTPRun.result);
140
- return;
141
- }
142
- if (!plainHTTPRun.ok) {
143
- crawlingContext.log.exception(plainHTTPRun.error, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
144
- }
145
- else {
146
- crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
147
- this.stats.trackRenderingTypeMisprediction();
148
- }
149
- }
150
- crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
151
- this.stats.trackBrowserRequestHandlerRun();
152
- // Run the request handler in a browser. The copy of the crawler state is kept so that we can perform
153
- // a rendering type detection if necessary. Without this measure, the HTTP request handler would run
154
- // under different conditions, which could change its behavior. Changes done to the crawler state by
155
- // the HTTP request handler will not be committed to the actual storage.
156
- const { result: browserRun, initialStateCopy } = await this.runRequestHandlerInBrowser(crawlingContext);
157
- if (!browserRun.ok) {
158
- throw browserRun.error;
159
- }
160
- await this.commitResult(crawlingContext, browserRun.result);
161
313
  if (shouldDetectRenderingType) {
162
- crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
163
- const plainHTTPRun = await this.runRequestHandlerWithPlainHTTP(crawlingContext, initialStateCopy);
164
- const detectionResult = (() => {
314
+ this.inFlightRenderingTypeDetections += 1;
315
+ }
316
+ try {
317
+ if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
318
+ crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
319
+ this.stats.trackHttpOnlyRequestHandlerRun();
320
+ const plainHTTPRun = await this.crawlOne('static', crawlingContext, crawlingContext.useState);
321
+ if (plainHTTPRun.ok && this.resultChecker(plainHTTPRun.result)) {
322
+ crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
323
+ plainHTTPRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
324
+ await this.commitResult(crawlingContext, plainHTTPRun.result);
325
+ return;
326
+ }
327
+ // Execution will "fall through" and try running the request handler in a browser
165
328
  if (!plainHTTPRun.ok) {
166
- return 'clientOnly';
329
+ const actualError = plainHTTPRun.error instanceof RequestHandlerError
330
+ ? plainHTTPRun.error.cause
331
+ : plainHTTPRun.error;
332
+ if (await this.shouldPropagateError(actualError, crawlingContext)) {
333
+ throw actualError;
334
+ }
335
+ crawlingContext.log.exception(actualError, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
336
+ }
337
+ else {
338
+ crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
339
+ this.stats.trackRenderingTypeMisprediction();
167
340
  }
168
- if (this.resultComparator(plainHTTPRun.result, browserRun.result)) {
169
- return 'static';
341
+ }
342
+ crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
343
+ this.stats.trackBrowserRequestHandlerRun();
344
+ // Run the request handler in a browser. The copy of the crawler state is kept so that we can perform
345
+ // a rendering type detection if necessary. Without this measure, the HTTP request handler would run
346
+ // under different conditions, which could change its behavior. Changes done to the crawler state by
347
+ // the HTTP request handler will not be committed to the actual storage.
348
+ const stateTracker = {
349
+ stateCopy: null,
350
+ async getLiveState(defaultValue = {}) {
351
+ const state = await crawlingContext.useState(defaultValue);
352
+ if (this.stateCopy === null) {
353
+ this.stateCopy = JSON.parse(JSON.stringify(state));
354
+ }
355
+ return state;
356
+ },
357
+ async getStateCopy(defaultValue = {}) {
358
+ if (this.stateCopy === null) {
359
+ return defaultValue;
360
+ }
361
+ return this.stateCopy;
362
+ },
363
+ };
364
+ const browserRun = await this.crawlOne('clientOnly', crawlingContext, stateTracker.getLiveState.bind(stateTracker));
365
+ if (!browserRun.ok) {
366
+ throw browserRun.error;
367
+ }
368
+ browserRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
369
+ await this.commitResult(crawlingContext, browserRun.result);
370
+ if (shouldDetectRenderingType) {
371
+ crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
372
+ const plainHTTPRun = await this.crawlOne('static', crawlingContext, stateTracker.getStateCopy.bind(stateTracker));
373
+ const detectionResult = (() => {
374
+ if (!plainHTTPRun.ok) {
375
+ return 'clientOnly';
376
+ }
377
+ const comparisonResult = this.resultComparator(plainHTTPRun.result, browserRun.result);
378
+ if (comparisonResult === true || comparisonResult === 'equal') {
379
+ return 'static';
380
+ }
381
+ if (comparisonResult === false || comparisonResult === 'different') {
382
+ return 'clientOnly';
383
+ }
384
+ return undefined;
385
+ })();
386
+ crawlingContext.log.debug(`Detected rendering type ${detectionResult} for ${crawlingContext.request.url}`);
387
+ if (detectionResult !== undefined) {
388
+ this.renderingTypePredictor.value.storeResult(crawlingContext.request, detectionResult);
170
389
  }
171
- return 'clientOnly';
172
- })();
173
- crawlingContext.log.debug(`Detected rendering type ${detectionResult} for ${crawlingContext.request.url}`);
174
- this.renderingTypePredictor.storeResult(crawlingContext.request, detectionResult);
390
+ }
391
+ }
392
+ finally {
393
+ if (shouldDetectRenderingType) {
394
+ this.inFlightRenderingTypeDetections -= 1;
395
+ }
175
396
  }
176
397
  }
177
398
  async commitResult(crawlingContext, { calls, keyValueStoreChanges }) {
178
399
  await Promise.all([
179
400
  ...calls.pushData.map(async (params) => crawlingContext.pushData(...params)),
180
- ...calls.enqueueLinks.map(async (params) => await crawlingContext.enqueueLinks(...params)),
181
401
  ...calls.addRequests.map(async (params) => crawlingContext.addRequests(...params)),
182
402
  ...Object.entries(keyValueStoreChanges).map(async ([storeIdOrName, changes]) => {
183
- const store = await crawlingContext.getKeyValueStore(storeIdOrName);
403
+ const store = await crawlingContext.getKeyValueStore({ id: storeIdOrName });
184
404
  await Promise.all(Object.entries(changes).map(async ([key, { changedValue, options }]) => store.setValue(key, changedValue, options)));
185
405
  }),
186
406
  ]);
@@ -188,151 +408,37 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
188
408
  allowStorageAccess(func) {
189
409
  return async (...args) => withCheckedStorageAccess(() => { }, async () => func(...args));
190
410
  }
191
- async runRequestHandlerInBrowser(crawlingContext) {
192
- const result = new RequestHandlerResult(this.config, AdaptivePlaywrightCrawler.CRAWLEE_STATE_KEY);
193
- let initialStateCopy;
194
- try {
195
- await super._runRequestHandler.call(new Proxy(this, {
196
- get: (target, propertyName, receiver) => {
197
- if (propertyName === 'userProvidedRequestHandler') {
198
- return async (playwrightContext) => withCheckedStorageAccess(() => {
199
- if (this.preventDirectStorageAccess) {
200
- throw new Error('Directly accessing storage in a request handler is not allowed in AdaptivePlaywrightCrawler');
201
- }
202
- }, () => this.adaptiveRequestHandler({
203
- id: crawlingContext.id,
204
- session: crawlingContext.session,
205
- proxyInfo: crawlingContext.proxyInfo,
206
- request: crawlingContext.request,
207
- response: {
208
- url: crawlingContext.response.url(),
209
- statusCode: crawlingContext.response.status(),
210
- headers: crawlingContext.response.headers(),
211
- trailers: {},
212
- complete: true,
213
- redirectUrls: [],
214
- },
215
- log: crawlingContext.log,
216
- page: crawlingContext.page,
217
- querySelector: async (selector, timeoutMs = 5_000) => {
218
- const locator = playwrightContext.page.locator(selector).first();
219
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
220
- const $ = await playwrightContext.parseWithCheerio();
221
- return $(selector);
222
- },
223
- async waitForSelector(selector, timeoutMs = 5_000) {
224
- const locator = playwrightContext.page.locator(selector).first();
225
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
226
- },
227
- async parseWithCheerio(selector, timeoutMs = 5_000) {
228
- if (selector) {
229
- const locator = playwrightContext.page.locator(selector).first();
230
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
231
- }
232
- return playwrightContext.parseWithCheerio();
233
- },
234
- async enqueueLinks(options = {}, timeoutMs = 5_000) {
235
- const selector = options.selector ?? 'a';
236
- const locator = playwrightContext.page.locator(selector).first();
237
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
238
- const urls = await extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ??
239
- playwrightContext.request.loadedUrl ??
240
- playwrightContext.request.url);
241
- await result.enqueueLinks({ ...options, urls });
242
- },
243
- addRequests: result.addRequests,
244
- pushData: result.pushData,
245
- useState: this.allowStorageAccess(async (defaultValue) => {
246
- const state = await result.useState(defaultValue);
247
- if (initialStateCopy === undefined) {
248
- initialStateCopy = JSON.parse(JSON.stringify(state));
249
- }
250
- return state;
251
- }),
252
- getKeyValueStore: this.allowStorageAccess(result.getKeyValueStore),
253
- }));
254
- }
255
- return Reflect.get(target, propertyName, receiver);
256
- },
257
- }), crawlingContext);
258
- return { result: { result, ok: true }, initialStateCopy };
259
- }
260
- catch (error) {
261
- return { result: { error, ok: false }, initialStateCopy };
262
- }
411
+ /**
412
+ * Reading the pending request count queries the underlying request manager, which counts as storage access.
413
+ * Since this is internal crawler bookkeeping used to compute the `enqueueLinks` limit (not user-initiated storage
414
+ * access), it must be allowed even while a request handler runs inside the storage-access guard.
415
+ */
416
+ async getPendingRequestCountApproximation() {
417
+ return this.allowStorageAccess(() => super.getPendingRequestCountApproximation())();
263
418
  }
264
- async runRequestHandlerWithPlainHTTP(crawlingContext, oldStateCopy) {
265
- const result = new RequestHandlerResult(this.config, AdaptivePlaywrightCrawler.CRAWLEE_STATE_KEY);
266
- const logs = [];
267
- const pageGotoOptions = { timeout: this.navigationTimeoutMillis }; // Irrelevant, but required by BrowserCrawler
268
- try {
269
- await withCheckedStorageAccess(() => {
270
- if (this.preventDirectStorageAccess) {
271
- throw new Error('Directly accessing storage in a request handler is not allowed in AdaptivePlaywrightCrawler');
272
- }
273
- }, async () => addTimeoutToPromise(async () => {
274
- const hookContext = {
275
- id: crawlingContext.id,
276
- session: crawlingContext.session,
277
- proxyInfo: crawlingContext.proxyInfo,
278
- request: crawlingContext.request,
279
- log: this.createLogProxy(crawlingContext.log, logs),
280
- };
281
- await this._executeHooks(this.preNavigationHooks, {
282
- ...hookContext,
283
- get page() {
284
- throw new Error('Page object was used in HTTP-only pre-navigation hook');
285
- },
286
- }, // This is safe because `executeHooks` just passes the context to the hooks which accept the partial context
287
- pageGotoOptions);
288
- const response = await crawlingContext.sendRequest({});
289
- const loadedUrl = response.url;
290
- crawlingContext.request.loadedUrl = loadedUrl;
291
- const $ = load(response.body);
292
- await this.adaptiveRequestHandler({
293
- ...hookContext,
294
- request: crawlingContext.request,
295
- response,
296
- get page() {
297
- throw new Error('Page object was used in HTTP-only request handler');
298
- },
299
- async querySelector(selector, _timeoutMs) {
300
- return $(selector);
301
- },
302
- async waitForSelector(selector, _timeoutMs) {
303
- if ($(selector).get().length === 0) {
304
- throw new Error(`Selector '${selector}' not found.`);
305
- }
306
- },
307
- async parseWithCheerio(selector, _timeoutMs) {
308
- if (selector && $(selector).get().length === 0) {
309
- throw new Error(`Selector '${selector}' not found.`);
310
- }
311
- return $;
312
- },
313
- async enqueueLinks(options = {}) {
314
- const urls = extractUrlsFromCheerio($, options.selector, options.baseUrl ?? loadedUrl);
315
- await result.enqueueLinks({ ...options, urls });
316
- },
317
- addRequests: result.addRequests,
318
- pushData: result.pushData,
319
- useState: async (defaultValue) => {
320
- // return the old state before the browser handler was executed
321
- // when rerunning the handler via HTTP for detection
322
- if (oldStateCopy !== undefined) {
323
- return oldStateCopy ?? defaultValue; // fallback to the default for `null`
324
- }
325
- return this.allowStorageAccess(result.useState)(defaultValue);
326
- },
327
- getKeyValueStore: this.allowStorageAccess(result.getKeyValueStore),
328
- });
329
- await this._executeHooks(this.postNavigationHooks, crawlingContext, pageGotoOptions);
330
- }, this.requestHandlerTimeoutInnerMillis, 'Request handler timed out'));
331
- return { result, logs, ok: true };
332
- }
333
- catch (error) {
334
- return { error, logs, ok: false };
335
- }
419
+ async enqueueLinks(options, request, result) {
420
+ const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
421
+ enqueueStrategy: options?.strategy,
422
+ finalRequestUrl: request.loadedUrl,
423
+ originalRequestUrl: request.url,
424
+ userProvidedBaseUrl: options?.baseUrl,
425
+ });
426
+ const addRequestsBatched = async (requests) => {
427
+ await result.addRequests(requests);
428
+ return {
429
+ addedRequests: requests.map(({ uniqueKey, id }) => ({
430
+ uniqueKey,
431
+ requestId: id ?? '',
432
+ wasAlreadyPresent: false,
433
+ wasAlreadyHandled: false,
434
+ })),
435
+ waitForAllRequestsToBeAdded: Promise.resolve([]),
436
+ requestsOverLimit: [],
437
+ };
438
+ };
439
+ // We need to use a mock request queue implementation, in order to add the requests into our result object
440
+ const mockRequestQueue = { addRequestsBatched };
441
+ return await this.enqueueLinksWithCrawlDepth({ ...options, baseUrl }, request, mockRequestQueue);
336
442
  }
337
443
  createLogProxy(log, logs) {
338
444
  return new Proxy(log, {
@@ -346,8 +452,42 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
346
452
  },
347
453
  });
348
454
  }
455
+ async teardown() {
456
+ await super.teardown();
457
+ for (const hook of this.teardownHooks) {
458
+ await hook();
459
+ }
460
+ }
461
+ }
462
+ export function createAdaptivePlaywrightRouter(routesOrSchemas) {
463
+ return Router.create(routesOrSchemas);
349
464
  }
350
- export function createAdaptivePlaywrightRouter(routes) {
351
- return Router.create(routes);
465
+ /**
466
+ * An opt-in {@link AdaptivePlaywrightCrawlerOptions.resultComparator|`resultComparator`} that considers two
467
+ * request handler results equal only if *all* of their observable effects match - the pushed dataset items, the
468
+ * enqueued requests, and the key-value store changes. This is stricter than the default comparator, which only
469
+ * compares dataset items.
470
+ *
471
+ * **Beware:** enqueued URLs are compared exactly. The same page rendered in a browser and via plain HTTP often
472
+ * yields links that differ only in tracking query parameters, for example:
473
+ * - `https://sdk.apify.com/docs/guides/getting-started`
474
+ * - `https://sdk.apify.com/docs/guides/getting-started?__hsfp=1136113150&__hssc=7591405.1.173549427712`
475
+ *
476
+ * Such links are treated as *different*, which will make the crawler favor browser rendering for those pages.
477
+ *
478
+ * **Example usage:**
479
+ * ```ts
480
+ * const crawler = new AdaptivePlaywrightCrawler({
481
+ * resultComparator: fullResultComparator,
482
+ * async requestHandler({ pushData, enqueueLinks }) {
483
+ * // ...
484
+ * },
485
+ * });
486
+ * ```
487
+ */
488
+ export function fullResultComparator(resultA, resultB) {
489
+ return (isDeepStrictEqual(resultA.datasetItems, resultB.datasetItems) &&
490
+ isDeepStrictEqual(resultA.enqueuedUrls, resultB.enqueuedUrls) &&
491
+ isDeepStrictEqual(resultA.enqueuedUrlLists, resultB.enqueuedUrlLists) &&
492
+ isDeepStrictEqual(resultA.keyValueStoreChanges, resultB.keyValueStoreChanges));
352
493
  }
353
- //# sourceMappingURL=adaptive-playwright-crawler.js.map